Egor Pasko | 0462e852d | 2018-03-29 15:52:09 | [diff] [blame] | 1 | #!/usr/bin/env vpython |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 2 | # Copyright (c) 2013 The Chromium Authors. All rights reserved. |
| 3 | # Use of this source code is governed by a BSD-style license that can be |
| 4 | # found in the LICENSE file. |
| 5 | |
| 6 | """ A utility to generate an up-to-date orderfile. |
| 7 | |
| 8 | The orderfile is used by the linker to order text sections such that the |
| 9 | sections are placed consecutively in the order specified. This allows us |
| 10 | to page in less code during start-up. |
| 11 | |
| 12 | Example usage: |
Egor Pasko | 93e514e | 2017-10-31 13:32:36 | [diff] [blame] | 13 | tools/cygprofile/orderfile_generator_backend.py -l 20 -j 1000 --use-goma \ |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 14 | --target-arch=arm |
| 15 | """ |
| 16 | |
Benoit Lize | a1b64f8 | 2017-12-07 10:12:50 | [diff] [blame] | 17 | import argparse |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 18 | import hashlib |
| 19 | import json |
Matthew Cary | 69e9e42 | 2018-08-10 18:30:06 | [diff] [blame] | 20 | import glob |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 21 | import logging |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 22 | import os |
| 23 | import re |
| 24 | import shutil |
| 25 | import subprocess |
| 26 | import sys |
Benoit Lize | a87e5bc | 2017-11-07 15:12:57 | [diff] [blame] | 27 | import tempfile |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 28 | import time |
| 29 | |
Matthew Cary | 91df979 | 2018-11-30 14:35:15 | [diff] [blame] | 30 | import cluster |
Matthew Cary | e840064 | 2018-06-14 15:43:02 | [diff] [blame] | 31 | import cyglog_to_orderfile |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 32 | import cygprofile_utils |
Benoit Lize | fefbb27c | 2018-01-17 13:54:18 | [diff] [blame] | 33 | import patch_orderfile |
Benoit Lize | a87e5bc | 2017-11-07 15:12:57 | [diff] [blame] | 34 | import process_profiles |
Egor Pasko | 3bc0b93 | 2018-04-03 10:08:27 | [diff] [blame] | 35 | import profile_android_startup |
Benoit Lize | fefbb27c | 2018-01-17 13:54:18 | [diff] [blame] | 36 | import symbol_extractor |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 37 | |
Monica Salama | eea2d94 | 2019-03-11 12:36:18 | [diff] [blame] | 38 | _SRC_PATH = os.path.join(os.path.dirname(__file__), os.pardir, os.pardir) |
| 39 | sys.path.append(os.path.join(_SRC_PATH, 'third_party', 'catapult', 'devil')) |
| 40 | from devil.android import device_utils |
| 41 | from devil.android.sdk import version_codes |
| 42 | |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 43 | |
| 44 | _SRC_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), |
| 45 | os.pardir, os.pardir) |
| 46 | sys.path.append(os.path.join(_SRC_PATH, 'build', 'android')) |
| 47 | import devil_chromium |
| 48 | from pylib import constants |
| 49 | |
| 50 | |
| 51 | # Needs to happen early for GetBuildType()/GetOutDirectory() to work correctly |
| 52 | constants.SetBuildType('Release') |
| 53 | |
| 54 | |
Matthew Cary | 53f74ba | 2019-01-24 10:07:18 | [diff] [blame] | 55 | # Architecture specific GN args. Trying to build an orderfile for an |
| 56 | # architecture not listed here will eventually throw. |
| 57 | _ARCH_GN_ARGS = { |
| 58 | 'arm': [ 'target_cpu = "arm"' ], |
| 59 | 'arm64': [ 'target_cpu = "arm64"', |
| 60 | 'android_64bit_browser = true'], |
| 61 | } |
| 62 | |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 63 | class CommandError(Exception): |
| 64 | """Indicates that a dispatched shell command exited with a non-zero status.""" |
| 65 | |
| 66 | def __init__(self, value): |
| 67 | super(CommandError, self).__init__() |
| 68 | self.value = value |
| 69 | |
| 70 | def __str__(self): |
| 71 | return repr(self.value) |
| 72 | |
| 73 | |
| 74 | def _GenerateHash(file_path): |
| 75 | """Calculates and returns the hash of the file at file_path.""" |
| 76 | sha1 = hashlib.sha1() |
| 77 | with open(file_path, 'rb') as f: |
| 78 | while True: |
| 79 | # Read in 1mb chunks, so it doesn't all have to be loaded into memory. |
| 80 | chunk = f.read(1024 * 1024) |
| 81 | if not chunk: |
| 82 | break |
| 83 | sha1.update(chunk) |
| 84 | return sha1.hexdigest() |
| 85 | |
| 86 | |
| 87 | def _GetFileExtension(file_name): |
| 88 | """Calculates the file extension from a file name. |
| 89 | |
| 90 | Args: |
| 91 | file_name: The source file name. |
| 92 | Returns: |
| 93 | The part of file_name after the dot (.) or None if the file has no |
| 94 | extension. |
| 95 | Examples: /home/user/foo.bar -> bar |
| 96 | /home/user.name/foo -> None |
| 97 | /home/user/.foo -> None |
| 98 | /home/user/foo.bar.baz -> baz |
| 99 | """ |
| 100 | file_name_parts = os.path.basename(file_name).split('.') |
| 101 | if len(file_name_parts) > 1: |
| 102 | return file_name_parts[-1] |
| 103 | else: |
| 104 | return None |
| 105 | |
| 106 | |
| 107 | def _StashOutputDirectory(buildpath): |
| 108 | """Takes the output directory and stashes it in the default output directory. |
| 109 | |
| 110 | This allows it to be used for incremental builds next time (after unstashing) |
| 111 | by keeping it in a place that isn't deleted normally, while also ensuring |
| 112 | that it is properly clobbered when appropriate. |
| 113 | |
| 114 | This is a dirty hack to deal with the needs of clobbering while also handling |
| 115 | incremental builds and the hardcoded relative paths used in some of the |
| 116 | project files. |
| 117 | |
| 118 | Args: |
| 119 | buildpath: The path where the building happens. If this corresponds to the |
| 120 | default output directory, no action is taken. |
| 121 | """ |
| 122 | if os.path.abspath(buildpath) == os.path.abspath(os.path.dirname( |
| 123 | constants.GetOutDirectory())): |
| 124 | return |
| 125 | name = os.path.basename(buildpath) |
| 126 | stashpath = os.path.join(constants.GetOutDirectory(), name) |
| 127 | if not os.path.exists(buildpath): |
| 128 | return |
| 129 | if os.path.exists(stashpath): |
| 130 | shutil.rmtree(stashpath, ignore_errors=True) |
| 131 | shutil.move(buildpath, stashpath) |
| 132 | |
| 133 | |
| 134 | def _UnstashOutputDirectory(buildpath): |
| 135 | """Inverse of _StashOutputDirectory. |
| 136 | |
| 137 | Moves the output directory stashed within the default output directory |
| 138 | (out/Release) to the position where the builds can actually happen. |
| 139 | |
| 140 | This is a dirty hack to deal with the needs of clobbering while also handling |
| 141 | incremental builds and the hardcoded relative paths used in some of the |
| 142 | project files. |
| 143 | |
| 144 | Args: |
| 145 | buildpath: The path where the building happens. If this corresponds to the |
| 146 | default output directory, no action is taken. |
| 147 | """ |
| 148 | if os.path.abspath(buildpath) == os.path.abspath(os.path.dirname( |
| 149 | constants.GetOutDirectory())): |
| 150 | return |
| 151 | name = os.path.basename(buildpath) |
| 152 | stashpath = os.path.join(constants.GetOutDirectory(), name) |
| 153 | if not os.path.exists(stashpath): |
| 154 | return |
| 155 | if os.path.exists(buildpath): |
| 156 | shutil.rmtree(buildpath, ignore_errors=True) |
| 157 | shutil.move(stashpath, buildpath) |
| 158 | |
| 159 | |
| 160 | class StepRecorder(object): |
| 161 | """Records steps and timings.""" |
| 162 | |
| 163 | def __init__(self, buildbot): |
| 164 | self.timings = [] |
| 165 | self._previous_step = ('', 0.0) |
| 166 | self._buildbot = buildbot |
| 167 | self._error_recorded = False |
| 168 | |
| 169 | def BeginStep(self, name): |
| 170 | """Marks a beginning of the next step in the script. |
| 171 | |
| 172 | On buildbot, this prints a specially formatted name that will show up |
| 173 | in the waterfall. Otherwise, just prints the step name. |
| 174 | |
| 175 | Args: |
| 176 | name: The name of the step. |
| 177 | """ |
| 178 | self.EndStep() |
| 179 | self._previous_step = (name, time.time()) |
| 180 | print 'Running step: ', name |
| 181 | |
| 182 | def EndStep(self): |
| 183 | """Records successful completion of the current step. |
| 184 | |
| 185 | This is optional if the step is immediately followed by another BeginStep. |
| 186 | """ |
| 187 | if self._previous_step[0]: |
| 188 | elapsed = time.time() - self._previous_step[1] |
| 189 | print 'Step %s took %f seconds' % (self._previous_step[0], elapsed) |
| 190 | self.timings.append((self._previous_step[0], elapsed)) |
| 191 | |
| 192 | self._previous_step = ('', 0.0) |
| 193 | |
| 194 | def FailStep(self, message=None): |
| 195 | """Marks that a particular step has failed. |
| 196 | |
| 197 | On buildbot, this will mark the current step as failed on the waterfall. |
| 198 | Otherwise we will just print an optional failure message. |
| 199 | |
| 200 | Args: |
| 201 | message: An optional explanation as to why the step failed. |
| 202 | """ |
| 203 | print 'STEP FAILED!!' |
| 204 | if message: |
| 205 | print message |
| 206 | self._error_recorded = True |
| 207 | self.EndStep() |
| 208 | |
| 209 | def ErrorRecorded(self): |
| 210 | """True if FailStep has been called.""" |
| 211 | return self._error_recorded |
| 212 | |
| 213 | def RunCommand(self, cmd, cwd=constants.DIR_SOURCE_ROOT, raise_on_error=True, |
| 214 | stdout=None): |
| 215 | """Execute a shell command. |
| 216 | |
| 217 | Args: |
| 218 | cmd: A list of command strings. |
Matthew Cary | 78aae16 | 2018-08-10 17:16:30 | [diff] [blame] | 219 | cwd: Directory in which the command should be executed, defaults to build |
| 220 | root of script's location if not specified. |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 221 | raise_on_error: If true will raise a CommandError if the call doesn't |
| 222 | succeed and mark the step as failed. |
| 223 | stdout: A file to redirect stdout for the command to. |
| 224 | |
| 225 | Returns: |
| 226 | The process's return code. |
| 227 | |
| 228 | Raises: |
| 229 | CommandError: An error executing the specified command. |
| 230 | """ |
| 231 | print 'Executing %s in %s' % (' '.join(cmd), cwd) |
| 232 | process = subprocess.Popen(cmd, stdout=stdout, cwd=cwd, env=os.environ) |
| 233 | process.wait() |
| 234 | if raise_on_error and process.returncode != 0: |
| 235 | self.FailStep() |
| 236 | raise CommandError('Exception executing command %s' % ' '.join(cmd)) |
| 237 | return process.returncode |
| 238 | |
| 239 | |
| 240 | class ClankCompiler(object): |
| 241 | """Handles compilation of clank.""" |
| 242 | |
| 243 | def __init__(self, out_dir, step_recorder, arch, jobs, max_load, use_goma, |
Stephen Kyle | f11339f | 2019-03-25 09:00:47 | [diff] [blame^] | 244 | goma_dir, system_health_profiling, monochrome, public, |
| 245 | orderfile_location): |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 246 | self._out_dir = out_dir |
| 247 | self._step_recorder = step_recorder |
Benoit Lize | a87e5bc | 2017-11-07 15:12:57 | [diff] [blame] | 248 | self._arch = arch |
| 249 | self._jobs = jobs |
| 250 | self._max_load = max_load |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 251 | self._use_goma = use_goma |
Benoit Lize | a87e5bc | 2017-11-07 15:12:57 | [diff] [blame] | 252 | self._goma_dir = goma_dir |
Matthew Cary | 78aae16 | 2018-08-10 17:16:30 | [diff] [blame] | 253 | self._system_health_profiling = system_health_profiling |
Stephen Kyle | f11339f | 2019-03-25 09:00:47 | [diff] [blame^] | 254 | self._public = public |
| 255 | self._orderfile_location = orderfile_location |
Matthew Cary | d6bfcb7 | 2018-09-14 11:27:46 | [diff] [blame] | 256 | if monochrome: |
| 257 | self._apk = 'Monochrome.apk' |
Matthew Cary | e1b0006 | 2018-09-19 14:27:44 | [diff] [blame] | 258 | self._apk_target = 'monochrome_apk' |
Matthew Cary | d6bfcb7 | 2018-09-14 11:27:46 | [diff] [blame] | 259 | self._libname = 'libmonochrome' |
| 260 | self._libchrome_target = 'monochrome' |
| 261 | else: |
| 262 | self._apk = 'Chrome.apk' |
Matthew Cary | e1b0006 | 2018-09-19 14:27:44 | [diff] [blame] | 263 | self._apk_target = 'chrome_apk' |
Matthew Cary | d6bfcb7 | 2018-09-14 11:27:46 | [diff] [blame] | 264 | self._libname = 'libchrome' |
| 265 | self._libchrome_target = 'libchrome' |
Stephen Kyle | f11339f | 2019-03-25 09:00:47 | [diff] [blame^] | 266 | if public: |
| 267 | self._apk = self._apk.replace('.apk', 'Public.apk') |
| 268 | self._apk_target = self._apk_target.replace('_apk', '_public_apk') |
Matthew Cary | 78aae16 | 2018-08-10 17:16:30 | [diff] [blame] | 269 | |
| 270 | self.obj_dir = os.path.join(self._out_dir, 'Release', 'obj') |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 271 | self.lib_chrome_so = os.path.join( |
Matthew Cary | d6bfcb7 | 2018-09-14 11:27:46 | [diff] [blame] | 272 | self._out_dir, 'Release', 'lib.unstripped', |
| 273 | '{}.so'.format(self._libname)) |
| 274 | self.chrome_apk = os.path.join(self._out_dir, 'Release', 'apks', self._apk) |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 275 | |
| 276 | def Build(self, instrumented, target): |
| 277 | """Builds the provided ninja target with or without order_profiling on. |
| 278 | |
| 279 | Args: |
Benoit Lize | a87e5bc | 2017-11-07 15:12:57 | [diff] [blame] | 280 | instrumented: (bool) Whether we want to build an instrumented binary. |
| 281 | target: (str) The name of the ninja target to build. |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 282 | """ |
| 283 | self._step_recorder.BeginStep('Compile %s' % target) |
| 284 | |
| 285 | # Set the "Release Official" flavor, the parts affecting performance. |
| 286 | args = [ |
Peter Collingbourne | 1c85d5d2 | 2018-08-22 18:06:35 | [diff] [blame] | 287 | 'enable_resource_whitelist_generation=false', |
Stephen Kyle | f11339f | 2019-03-25 09:00:47 | [diff] [blame^] | 288 | 'is_chrome_branded=' + str(not self._public).lower(), |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 289 | 'is_debug=false', |
| 290 | 'is_official_build=true', |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 291 | 'target_os="android"', |
| 292 | 'use_goma=' + str(self._use_goma).lower(), |
| 293 | 'use_order_profiling=' + str(instrumented).lower(), |
| 294 | ] |
Matthew Cary | 53f74ba | 2019-01-24 10:07:18 | [diff] [blame] | 295 | args += _ARCH_GN_ARGS[self._arch] |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 296 | if self._goma_dir: |
| 297 | args += ['goma_dir="%s"' % self._goma_dir] |
Matthew Cary | 78aae16 | 2018-08-10 17:16:30 | [diff] [blame] | 298 | if self._system_health_profiling: |
| 299 | args += ['devtools_instrumentation_dumping = ' + |
| 300 | str(instrumented).lower()] |
Benoit Lize | a87e5bc | 2017-11-07 15:12:57 | [diff] [blame] | 301 | |
Stephen Kyle | f11339f | 2019-03-25 09:00:47 | [diff] [blame^] | 302 | if self._public and os.path.exists(self._orderfile_location): |
| 303 | # GN needs the orderfile path to be source-absolute. |
| 304 | src_abs_orderfile = os.path.relpath(self._orderfile_location, |
| 305 | constants.DIR_SOURCE_ROOT) |
| 306 | args += ['chrome_orderfile="//{}"'.format(src_abs_orderfile)] |
| 307 | |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 308 | self._step_recorder.RunCommand( |
| 309 | ['gn', 'gen', os.path.join(self._out_dir, 'Release'), |
| 310 | '--args=' + ' '.join(args)]) |
| 311 | |
| 312 | self._step_recorder.RunCommand( |
| 313 | ['ninja', '-C', os.path.join(self._out_dir, 'Release'), |
| 314 | '-j' + str(self._jobs), '-l' + str(self._max_load), target]) |
| 315 | |
| 316 | def CompileChromeApk(self, instrumented, force_relink=False): |
| 317 | """Builds a Chrome.apk either with or without order_profiling on. |
| 318 | |
| 319 | Args: |
Benoit Lize | a87e5bc | 2017-11-07 15:12:57 | [diff] [blame] | 320 | instrumented: (bool) Whether to build an instrumented apk. |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 321 | force_relink: Whether libchromeview.so should be re-created. |
| 322 | """ |
| 323 | if force_relink: |
| 324 | self._step_recorder.RunCommand(['rm', '-rf', self.lib_chrome_so]) |
Matthew Cary | e1b0006 | 2018-09-19 14:27:44 | [diff] [blame] | 325 | self.Build(instrumented, self._apk_target) |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 326 | |
| 327 | def CompileLibchrome(self, instrumented, force_relink=False): |
| 328 | """Builds a libchrome.so either with or without order_profiling on. |
| 329 | |
| 330 | Args: |
Benoit Lize | a87e5bc | 2017-11-07 15:12:57 | [diff] [blame] | 331 | instrumented: (bool) Whether to build an instrumented apk. |
| 332 | force_relink: (bool) Whether libchrome.so should be re-created. |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 333 | """ |
| 334 | if force_relink: |
| 335 | self._step_recorder.RunCommand(['rm', '-rf', self.lib_chrome_so]) |
Matthew Cary | d6bfcb7 | 2018-09-14 11:27:46 | [diff] [blame] | 336 | self.Build(instrumented, self._libchrome_target) |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 337 | |
| 338 | |
| 339 | class OrderfileUpdater(object): |
| 340 | """Handles uploading and committing a new orderfile in the repository. |
| 341 | |
| 342 | Only used for testing or on a bot. |
| 343 | """ |
| 344 | |
| 345 | _CLOUD_STORAGE_BUCKET_FOR_DEBUG = None |
| 346 | _CLOUD_STORAGE_BUCKET = None |
| 347 | _UPLOAD_TO_CLOUD_COMMAND = 'upload_to_google_storage.py' |
| 348 | |
| 349 | def __init__(self, repository_root, step_recorder, branch, netrc): |
| 350 | """Constructor. |
| 351 | |
| 352 | Args: |
| 353 | repository_root: (str) Root of the target repository. |
| 354 | step_recorder: (StepRecorder) Step recorder, for logging. |
| 355 | branch: (str) Branch to commit to. |
| 356 | netrc: (str) Path to the .netrc file to use. |
| 357 | """ |
| 358 | self._repository_root = repository_root |
| 359 | self._step_recorder = step_recorder |
| 360 | self._branch = branch |
| 361 | self._netrc = netrc |
| 362 | |
Matthew Cary | 86a226e | 2019-03-19 12:17:44 | [diff] [blame] | 363 | def CommitStashedFileHashes(self, files): |
| 364 | """Commits unpatched and patched orderfiles hashes if changed. |
| 365 | |
| 366 | The files are committed only if their associated sha1 hash files match, and |
| 367 | are modified in git. In normal operations the hash files are changed only |
| 368 | when a file is uploaded to cloud storage. If the hash file is not modified |
| 369 | in git, the file is skipped. |
| 370 | |
| 371 | Args: |
| 372 | files: [str or None] specifies file paths. None items are ignored. |
| 373 | |
| 374 | Raises: |
| 375 | Exception if the hash file does not match the file. |
| 376 | NotImplementedError when the commit logic hasn't been overridden. |
| 377 | """ |
| 378 | files_to_commit = list(filter(None, files)) |
| 379 | if files_to_commit: |
| 380 | self._CommitStashedFiles(files_to_commit) |
| 381 | |
| 382 | def LegacyCommitFileHashes(self, |
| 383 | unpatched_orderfile_filename, |
| 384 | orderfile_filename): |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 385 | """Commits unpatched and patched orderfiles hashes, if provided. |
| 386 | |
Matthew Cary | 86a226e | 2019-03-19 12:17:44 | [diff] [blame] | 387 | DEPRECATED. Left in place during transition. |
| 388 | |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 389 | Files must have been successfilly uploaded to cloud storage first. |
| 390 | |
| 391 | Args: |
| 392 | unpatched_orderfile_filename: (str or None) Unpatched orderfile path. |
| 393 | orderfile_filename: (str or None) Orderfile path. |
| 394 | |
| 395 | Raises: |
Matthew Cary | 86a226e | 2019-03-19 12:17:44 | [diff] [blame] | 396 | NotImplementedError when the commit logic hasn't been overridden. |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 397 | """ |
| 398 | files_to_commit = [] |
| 399 | commit_message_lines = ['Update Orderfile.'] |
| 400 | for filename in [unpatched_orderfile_filename, orderfile_filename]: |
| 401 | if not filename: |
| 402 | continue |
| 403 | (relative_path, sha1) = self._GetHashFilePathAndContents(filename) |
| 404 | commit_message_lines.append('Profile: %s: %s' % ( |
| 405 | os.path.basename(relative_path), sha1)) |
| 406 | files_to_commit.append(relative_path) |
| 407 | if files_to_commit: |
| 408 | self._CommitFiles(files_to_commit, commit_message_lines) |
| 409 | |
| 410 | def UploadToCloudStorage(self, filename, use_debug_location): |
| 411 | """Uploads a file to cloud storage. |
| 412 | |
| 413 | Args: |
| 414 | filename: (str) File to upload. |
| 415 | use_debug_location: (bool) Whether to use the debug location. |
| 416 | """ |
| 417 | bucket = (self._CLOUD_STORAGE_BUCKET_FOR_DEBUG if use_debug_location |
| 418 | else self._CLOUD_STORAGE_BUCKET) |
| 419 | extension = _GetFileExtension(filename) |
| 420 | cmd = [self._UPLOAD_TO_CLOUD_COMMAND, '--bucket', bucket] |
| 421 | if extension: |
| 422 | cmd.extend(['-z', extension]) |
| 423 | cmd.append(filename) |
| 424 | self._step_recorder.RunCommand(cmd) |
| 425 | print 'Download: https://sandbox.google.com/storage/%s/%s' % ( |
| 426 | bucket, _GenerateHash(filename)) |
| 427 | |
| 428 | def _GetHashFilePathAndContents(self, filename): |
| 429 | """Gets the name and content of the hash file created from uploading the |
| 430 | given file. |
| 431 | |
| 432 | Args: |
| 433 | filename: (str) The file that was uploaded to cloud storage. |
| 434 | |
| 435 | Returns: |
| 436 | A tuple of the hash file name, relative to the reository root, and the |
| 437 | content, which should be the sha1 hash of the file |
| 438 | ('base_file.sha1', hash) |
| 439 | """ |
| 440 | abs_hash_filename = filename + '.sha1' |
| 441 | rel_hash_filename = os.path.relpath( |
| 442 | abs_hash_filename, self._repository_root) |
| 443 | with open(abs_hash_filename, 'r') as f: |
| 444 | return (rel_hash_filename, f.read()) |
| 445 | |
| 446 | def _CommitFiles(self, files_to_commit, commit_message_lines): |
| 447 | """Commits a list of files, with a given message.""" |
| 448 | raise NotImplementedError |
| 449 | |
Matthew Cary | 86a226e | 2019-03-19 12:17:44 | [diff] [blame] | 450 | def _GitStash(self): |
| 451 | """Git stash the current clank tree. |
| 452 | |
| 453 | Raises: |
| 454 | NotImplementedError when the stash logic hasn't been overridden. |
| 455 | """ |
| 456 | raise NotImplementedError |
| 457 | |
| 458 | def _CommitStashedFiles(self, expected_files_in_stash): |
| 459 | """Commits stashed files. |
| 460 | |
| 461 | The local repository is updated and then the files to commit are taken from |
| 462 | modified files from the git stash. The modified files should be a subset of |
| 463 | |expected_files_in_stash|. If there are unexpected modified files, this |
| 464 | function may raise. This is meant to be paired with _GitStash(). |
| 465 | |
| 466 | Args: |
| 467 | expected_files_in_stash: [str] paths to a possible superset of files |
| 468 | expected to be stashed & committed. |
| 469 | |
| 470 | Raises: |
| 471 | NotImplementedError when the commit logic hasn't been overridden. |
| 472 | """ |
| 473 | raise NotImplementedError |
| 474 | |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 475 | |
Stephen Kyle | f11339f | 2019-03-25 09:00:47 | [diff] [blame^] | 476 | class OrderfileNoopUpdater(OrderfileUpdater): |
| 477 | def CommitFileHashes(self, unpatched_orderfile_filename, orderfile_filename): |
| 478 | # pylint: disable=unused-argument |
| 479 | return |
| 480 | |
| 481 | def UploadToCloudStorage(self, filename, use_debug_location): |
| 482 | # pylint: disable=unused-argument |
| 483 | return |
| 484 | |
| 485 | def _CommitFiles(self, files_to_commit, commit_message_lines): |
| 486 | raise NotImplementedError |
| 487 | |
| 488 | |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 489 | class OrderfileGenerator(object): |
| 490 | """A utility for generating a new orderfile for Clank. |
| 491 | |
| 492 | Builds an instrumented binary, profiles a run of the application, and |
| 493 | generates an updated orderfile. |
| 494 | """ |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 495 | _CHECK_ORDERFILE_SCRIPT = os.path.join( |
| 496 | constants.DIR_SOURCE_ROOT, 'tools', 'cygprofile', 'check_orderfile.py') |
| 497 | _BUILD_ROOT = os.path.abspath(os.path.dirname(os.path.dirname( |
| 498 | constants.GetOutDirectory()))) # Normally /path/to/src |
| 499 | |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 500 | # Previous orderfile_generator debug files would be overwritten. |
| 501 | _DIRECTORY_FOR_DEBUG_FILES = '/tmp/orderfile_generator_debug_files' |
| 502 | |
Stephen Kyle | f11339f | 2019-03-25 09:00:47 | [diff] [blame^] | 503 | def _PrepareOrderfilePaths(self): |
| 504 | if self._options.public: |
| 505 | self._clank_dir = os.path.join(constants.DIR_SOURCE_ROOT, |
| 506 | '') |
| 507 | if not os.path.exists(os.path.join(self._clank_dir, 'orderfiles')): |
| 508 | os.makedirs(os.path.join(self._clank_dir, 'orderfiles')) |
| 509 | else: |
| 510 | self._clank_dir = os.path.join(constants.DIR_SOURCE_ROOT, |
| 511 | 'clank') |
| 512 | |
| 513 | self._unpatched_orderfile_filename = os.path.join( |
| 514 | self._clank_dir, 'orderfiles', 'unpatched_orderfile.%s') |
| 515 | self._path_to_orderfile = os.path.join( |
| 516 | self._clank_dir, 'orderfiles', 'orderfile.%s.out') |
| 517 | |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 518 | def _GetPathToOrderfile(self): |
| 519 | """Gets the path to the architecture-specific orderfile.""" |
Stephen Kyle | f11339f | 2019-03-25 09:00:47 | [diff] [blame^] | 520 | return self._path_to_orderfile % self._options.arch |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 521 | |
| 522 | def _GetUnpatchedOrderfileFilename(self): |
| 523 | """Gets the path to the architecture-specific unpatched orderfile.""" |
Stephen Kyle | f11339f | 2019-03-25 09:00:47 | [diff] [blame^] | 524 | return self._unpatched_orderfile_filename % self._options.arch |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 525 | |
Monica Salama | eea2d94 | 2019-03-11 12:36:18 | [diff] [blame] | 526 | def _SetDevice(self): |
| 527 | """ Selects the device to be used by the script. |
| 528 | |
| 529 | Returns: |
| 530 | (Device with given serial ID) : if the --device flag is set. |
| 531 | (Device running Android[K,L]) : if --use-legacy-chrome-apk flag is set or |
| 532 | no device running Android N+ was found. |
| 533 | (Device running Android N+) : Otherwise. |
| 534 | |
| 535 | Raises Error: |
| 536 | If no device meeting the requirements has been found. |
| 537 | """ |
| 538 | devices = None |
| 539 | if self._options.device: |
| 540 | devices = [device_utils.DeviceUtils(self._options.device)] |
| 541 | else: |
| 542 | devices = device_utils.DeviceUtils.HealthyDevices() |
| 543 | |
| 544 | assert devices, 'Expected at least one connected device' |
| 545 | |
| 546 | if self._options.use_legacy_chrome_apk: |
| 547 | self._monochrome = False |
| 548 | for device in devices: |
| 549 | device_version = device.build_version_sdk |
| 550 | if (device_version >= version_codes.KITKAT |
| 551 | and device_version <= version_codes.LOLLIPOP_MR1): |
| 552 | return device |
| 553 | |
| 554 | assert not self._options.use_legacy_chrome_apk, \ |
| 555 | 'No device found running suitable android version for Chrome.apk.' |
| 556 | |
| 557 | preferred_device = None |
| 558 | for device in devices: |
| 559 | if device.build_version_sdk >= version_codes.NOUGAT: |
| 560 | preferred_device = device |
| 561 | break |
| 562 | |
| 563 | self._monochrome = preferred_device is not None |
| 564 | |
| 565 | return preferred_device if preferred_device else devices[0] |
| 566 | |
| 567 | |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 568 | def __init__(self, options, orderfile_updater_class): |
| 569 | self._options = options |
| 570 | |
| 571 | self._instrumented_out_dir = os.path.join( |
| 572 | self._BUILD_ROOT, self._options.arch + '_instrumented_out') |
| 573 | self._uninstrumented_out_dir = os.path.join( |
| 574 | self._BUILD_ROOT, self._options.arch + '_uninstrumented_out') |
| 575 | |
Stephen Kyle | f11339f | 2019-03-25 09:00:47 | [diff] [blame^] | 576 | self._PrepareOrderfilePaths() |
| 577 | |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 578 | if options.profile: |
Benoit Lize | a1b64f8 | 2017-12-07 10:12:50 | [diff] [blame] | 579 | output_directory = os.path.join(self._instrumented_out_dir, 'Release') |
Matthew Cary | b8daed94 | 2018-06-11 10:58:08 | [diff] [blame] | 580 | host_profile_dir = os.path.join(output_directory, 'profile_data') |
Benoit Lize | a1b64f8 | 2017-12-07 10:12:50 | [diff] [blame] | 581 | urls = [profile_android_startup.AndroidProfileTool.TEST_URL] |
| 582 | use_wpr = True |
| 583 | simulate_user = False |
Benoit L | 9646681 | 2018-03-06 15:58:37 | [diff] [blame] | 584 | urls = options.urls |
| 585 | use_wpr = not options.no_wpr |
| 586 | simulate_user = options.simulate_user |
Monica Salama | eea2d94 | 2019-03-11 12:36:18 | [diff] [blame] | 587 | device = self._SetDevice() |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 588 | self._profiler = profile_android_startup.AndroidProfileTool( |
Matthew Cary | 453ff145 | 2018-07-18 12:19:35 | [diff] [blame] | 589 | output_directory, host_profile_dir, use_wpr, urls, simulate_user, |
Matthew Cary | 1ea8221 | 2019-03-20 12:10:27 | [diff] [blame] | 590 | device, debug=self._options.streamline_for_debugging) |
Matthew Cary | 69e9e42 | 2018-08-10 18:30:06 | [diff] [blame] | 591 | if options.pregenerated_profiles: |
| 592 | self._profiler.SetPregeneratedProfiles( |
| 593 | glob.glob(options.pregenerated_profiles)) |
| 594 | else: |
| 595 | assert not options.pregenerated_profiles, ( |
| 596 | '--pregenerated-profiles cannot be used with --skip-profile') |
| 597 | assert not options.profile_save_dir, ( |
| 598 | '--profile-save-dir cannot be used with --skip-profile') |
Monica Salama | eea2d94 | 2019-03-11 12:36:18 | [diff] [blame] | 599 | self._monochrome = not self._options.use_legacy_chrome_apk |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 600 | |
Matthew Cary | f949bba | 2019-02-04 13:39:23 | [diff] [blame] | 601 | # Outlined function handling enabled by default for all architectures. |
| 602 | self._order_outlined_functions = not options.noorder_outlined_functions |
| 603 | |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 604 | self._output_data = {} |
| 605 | self._step_recorder = StepRecorder(options.buildbot) |
| 606 | self._compiler = None |
Stephen Kyle | f11339f | 2019-03-25 09:00:47 | [diff] [blame^] | 607 | if orderfile_updater_class is None: |
| 608 | if options.public: |
| 609 | orderfile_updater_class = OrderfileNoopUpdater |
| 610 | else: |
| 611 | orderfile_updater_class = OrderfileUpdater |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 612 | assert issubclass(orderfile_updater_class, OrderfileUpdater) |
Stephen Kyle | f11339f | 2019-03-25 09:00:47 | [diff] [blame^] | 613 | self._orderfile_updater = orderfile_updater_class(self._clank_dir, |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 614 | self._step_recorder, |
| 615 | options.branch, |
| 616 | options.netrc) |
| 617 | assert os.path.isdir(constants.DIR_SOURCE_ROOT), 'No src directory found' |
Benoit Lize | fefbb27c | 2018-01-17 13:54:18 | [diff] [blame] | 618 | symbol_extractor.SetArchitecture(options.arch) |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 619 | |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 620 | @staticmethod |
| 621 | def _RemoveBlanks(src_file, dest_file): |
| 622 | """A utility to remove blank lines from a file. |
| 623 | |
| 624 | Args: |
| 625 | src_file: The name of the file to remove the blanks from. |
| 626 | dest_file: The name of the file to write the output without blanks. |
| 627 | """ |
| 628 | assert src_file != dest_file, 'Source and destination need to be distinct' |
| 629 | |
| 630 | try: |
| 631 | src = open(src_file, 'r') |
| 632 | dest = open(dest_file, 'w') |
| 633 | for line in src: |
| 634 | if line and not line.isspace(): |
| 635 | dest.write(line) |
| 636 | finally: |
| 637 | src.close() |
| 638 | dest.close() |
| 639 | |
| 640 | def _GenerateAndProcessProfile(self): |
Matthew Cary | 78aae16 | 2018-08-10 17:16:30 | [diff] [blame] | 641 | """Invokes a script to merge the per-thread traces into one file. |
| 642 | |
| 643 | The produced list of offsets is saved in |
| 644 | self._GetUnpatchedOrderfileFilename(). |
| 645 | """ |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 646 | self._step_recorder.BeginStep('Generate Profile Data') |
| 647 | files = [] |
Matthew Cary | 78aae16 | 2018-08-10 17:16:30 | [diff] [blame] | 648 | logging.getLogger().setLevel(logging.DEBUG) |
| 649 | if self._options.system_health_orderfile: |
| 650 | files = self._profiler.CollectSystemHealthProfile( |
| 651 | self._compiler.chrome_apk) |
Matthew Cary | 69e9e42 | 2018-08-10 18:30:06 | [diff] [blame] | 652 | self._MaybeSaveProfile(files) |
Matthew Cary | 78aae16 | 2018-08-10 17:16:30 | [diff] [blame] | 653 | try: |
| 654 | self._ProcessPhasedOrderfile(files) |
| 655 | except Exception: |
| 656 | for f in files: |
| 657 | self._SaveForDebugging(f) |
Matthew Cary | 8b141623 | 2018-08-10 19:12:22 | [diff] [blame] | 658 | self._SaveForDebugging(self._compiler.lib_chrome_so) |
Matthew Cary | 78aae16 | 2018-08-10 17:16:30 | [diff] [blame] | 659 | raise |
| 660 | finally: |
| 661 | self._profiler.Cleanup() |
| 662 | else: |
| 663 | self._CollectLegacyProfile() |
| 664 | logging.getLogger().setLevel(logging.INFO) |
| 665 | |
| 666 | def _ProcessPhasedOrderfile(self, files): |
| 667 | """Process the phased orderfiles produced by system health benchmarks. |
| 668 | |
| 669 | The offsets will be placed in _GetUnpatchedOrderfileFilename(). |
| 670 | |
| 671 | Args: |
| 672 | file: Profile files pulled locally. |
| 673 | """ |
| 674 | self._step_recorder.BeginStep('Process Phased Orderfile') |
| 675 | profiles = process_profiles.ProfileManager(files) |
| 676 | processor = process_profiles.SymbolOffsetProcessor( |
| 677 | self._compiler.lib_chrome_so) |
Matthew Cary | da9db93 | 2019-03-11 15:28:17 | [diff] [blame] | 678 | ordered_symbols = cluster.ClusterOffsets(profiles, processor) |
Matthew Cary | 8b141623 | 2018-08-10 19:12:22 | [diff] [blame] | 679 | if not ordered_symbols: |
| 680 | raise Exception('Failed to get ordered symbols') |
Matthew Cary | da9db93 | 2019-03-11 15:28:17 | [diff] [blame] | 681 | for sym in ordered_symbols: |
| 682 | assert not sym.startswith('OUTLINED_FUNCTION_'), ( |
| 683 | 'Outlined function found in instrumented function, very likely ' |
| 684 | 'something has gone very wrong!') |
Matthew Cary | 91df979 | 2018-11-30 14:35:15 | [diff] [blame] | 685 | self._output_data['offsets_kib'] = processor.SymbolsSize( |
| 686 | ordered_symbols) / 1024 |
Matthew Cary | 78aae16 | 2018-08-10 17:16:30 | [diff] [blame] | 687 | with open(self._GetUnpatchedOrderfileFilename(), 'w') as orderfile: |
Matthew Cary | 8b141623 | 2018-08-10 19:12:22 | [diff] [blame] | 688 | orderfile.write('\n'.join(ordered_symbols)) |
Matthew Cary | 78aae16 | 2018-08-10 17:16:30 | [diff] [blame] | 689 | |
| 690 | def _CollectLegacyProfile(self): |
Matthew Cary | 2df8d45 | 2018-09-19 07:50:20 | [diff] [blame] | 691 | files = [] |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 692 | try: |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 693 | files = self._profiler.CollectProfile( |
| 694 | self._compiler.chrome_apk, |
| 695 | constants.PACKAGE_INFO['chrome']) |
Matthew Cary | 69e9e42 | 2018-08-10 18:30:06 | [diff] [blame] | 696 | self._MaybeSaveProfile(files) |
Matthew Cary | b8daed94 | 2018-06-11 10:58:08 | [diff] [blame] | 697 | self._step_recorder.BeginStep('Process profile') |
Benoit L | 9646681 | 2018-03-06 15:58:37 | [diff] [blame] | 698 | assert os.path.exists(self._compiler.lib_chrome_so) |
| 699 | offsets = process_profiles.GetReachedOffsetsFromDumpFiles( |
| 700 | files, self._compiler.lib_chrome_so) |
| 701 | if not offsets: |
| 702 | raise Exception('No profiler offsets found in {}'.format( |
| 703 | '\n'.join(files))) |
Matthew Cary | 8b141623 | 2018-08-10 19:12:22 | [diff] [blame] | 704 | processor = process_profiles.SymbolOffsetProcessor( |
| 705 | self._compiler.lib_chrome_so) |
| 706 | ordered_symbols = processor.GetOrderedSymbols(offsets) |
| 707 | if not ordered_symbols: |
| 708 | raise Exception('No symbol names from offsets found in {}'.format( |
| 709 | '\n'.join(files))) |
| 710 | with open(self._GetUnpatchedOrderfileFilename(), 'w') as orderfile: |
| 711 | orderfile.write('\n'.join(ordered_symbols)) |
Matthew Cary | 0f1f681a | 2018-01-22 10:40:51 | [diff] [blame] | 712 | except Exception: |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 713 | for f in files: |
| 714 | self._SaveForDebugging(f) |
| 715 | raise |
| 716 | finally: |
| 717 | self._profiler.Cleanup() |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 718 | |
Matthew Cary | 69e9e42 | 2018-08-10 18:30:06 | [diff] [blame] | 719 | def _MaybeSaveProfile(self, files): |
| 720 | if self._options.profile_save_dir: |
| 721 | logging.info('Saving profiles to %s', self._options.profile_save_dir) |
| 722 | for f in files: |
| 723 | shutil.copy(f, self._options.profile_save_dir) |
| 724 | logging.info('Saved profile %s', f) |
| 725 | |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 726 | def _PatchOrderfile(self): |
| 727 | """Patches the orderfile using clean version of libchrome.so.""" |
| 728 | self._step_recorder.BeginStep('Patch Orderfile') |
Benoit Lize | fefbb27c | 2018-01-17 13:54:18 | [diff] [blame] | 729 | patch_orderfile.GeneratePatchedOrderfile( |
| 730 | self._GetUnpatchedOrderfileFilename(), self._compiler.lib_chrome_so, |
Matthew Cary | f949bba | 2019-02-04 13:39:23 | [diff] [blame] | 731 | self._GetPathToOrderfile(), self._order_outlined_functions) |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 732 | |
| 733 | def _VerifySymbolOrder(self): |
| 734 | self._step_recorder.BeginStep('Verify Symbol Order') |
| 735 | return_code = self._step_recorder.RunCommand( |
| 736 | [self._CHECK_ORDERFILE_SCRIPT, self._compiler.lib_chrome_so, |
| 737 | self._GetPathToOrderfile(), |
| 738 | '--target-arch=' + self._options.arch], |
| 739 | constants.DIR_SOURCE_ROOT, |
| 740 | raise_on_error=False) |
| 741 | if return_code: |
| 742 | self._step_recorder.FailStep('Orderfile check returned %d.' % return_code) |
| 743 | |
| 744 | def _RecordHash(self, file_name): |
| 745 | """Records the hash of the file into the output_data dictionary.""" |
| 746 | self._output_data[os.path.basename(file_name) + '.sha1'] = _GenerateHash( |
| 747 | file_name) |
| 748 | |
| 749 | def _SaveFileLocally(self, file_name, file_sha1): |
| 750 | """Saves the file to a temporary location and prints the sha1sum.""" |
| 751 | if not os.path.exists(self._DIRECTORY_FOR_DEBUG_FILES): |
| 752 | os.makedirs(self._DIRECTORY_FOR_DEBUG_FILES) |
| 753 | shutil.copy(file_name, self._DIRECTORY_FOR_DEBUG_FILES) |
| 754 | print 'File: %s, saved in: %s, sha1sum: %s' % ( |
| 755 | file_name, self._DIRECTORY_FOR_DEBUG_FILES, file_sha1) |
| 756 | |
| 757 | def _SaveForDebugging(self, filename): |
| 758 | """Uploads the file to cloud storage or saves to a temporary location.""" |
| 759 | file_sha1 = _GenerateHash(filename) |
| 760 | if not self._options.buildbot: |
| 761 | self._SaveFileLocally(filename, file_sha1) |
| 762 | else: |
| 763 | print 'Uploading file for debugging: ' + filename |
| 764 | self._orderfile_updater.UploadToCloudStorage( |
| 765 | filename, use_debug_location=True) |
| 766 | |
| 767 | def _SaveForDebuggingWithOverwrite(self, file_name): |
| 768 | """Uploads and overwrites the file in cloud storage or copies locally. |
| 769 | |
| 770 | Should be used for large binaries like lib_chrome_so. |
| 771 | |
| 772 | Args: |
| 773 | file_name: (str) File to upload. |
| 774 | """ |
| 775 | file_sha1 = _GenerateHash(file_name) |
| 776 | if not self._options.buildbot: |
| 777 | self._SaveFileLocally(file_name, file_sha1) |
| 778 | else: |
| 779 | print 'Uploading file for debugging: %s, sha1sum: %s' % ( |
| 780 | file_name, file_sha1) |
| 781 | upload_location = '%s/%s' % ( |
| 782 | self._CLOUD_STORAGE_BUCKET_FOR_DEBUG, os.path.basename(file_name)) |
| 783 | self._step_recorder.RunCommand([ |
| 784 | 'gsutil.py', 'cp', file_name, 'gs://' + upload_location]) |
| 785 | print ('Uploaded to: https://sandbox.google.com/storage/' + |
| 786 | upload_location) |
| 787 | |
| 788 | def _MaybeArchiveOrderfile(self, filename): |
| 789 | """In buildbot configuration, uploads the generated orderfile to |
| 790 | Google Cloud Storage. |
| 791 | |
| 792 | Args: |
| 793 | filename: (str) Orderfile to upload. |
| 794 | """ |
Matthew Cary | 91df979 | 2018-11-30 14:35:15 | [diff] [blame] | 795 | # First compute hashes so that we can download them later if we need to. |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 796 | self._step_recorder.BeginStep('Compute hash for ' + filename) |
| 797 | self._RecordHash(filename) |
| 798 | if self._options.buildbot: |
| 799 | self._step_recorder.BeginStep('Archive ' + filename) |
| 800 | self._orderfile_updater.UploadToCloudStorage( |
| 801 | filename, use_debug_location=False) |
| 802 | |
Egor Pasko | bce64d01 | 2018-11-20 12:02:37 | [diff] [blame] | 803 | def UploadReadyOrderfiles(self): |
| 804 | self._step_recorder.BeginStep('Upload Ready Orderfiles') |
| 805 | for file_name in [self._GetUnpatchedOrderfileFilename(), |
| 806 | self._GetPathToOrderfile()]: |
| 807 | self._orderfile_updater.UploadToCloudStorage( |
| 808 | file_name, use_debug_location=False) |
| 809 | |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 810 | def Generate(self): |
| 811 | """Generates and maybe upload an order.""" |
| 812 | profile_uploaded = False |
| 813 | orderfile_uploaded = False |
| 814 | |
Matthew Cary | e840064 | 2018-06-14 15:43:02 | [diff] [blame] | 815 | assert (bool(self._options.profile) ^ |
| 816 | bool(self._options.manual_symbol_offsets)) |
Matthew Cary | 78aae16 | 2018-08-10 17:16:30 | [diff] [blame] | 817 | if self._options.system_health_orderfile and not self._options.profile: |
| 818 | raise AssertionError('--system_health_orderfile must be not be used ' |
| 819 | 'with --skip-profile') |
| 820 | if (self._options.manual_symbol_offsets and |
| 821 | not self._options.system_health_orderfile): |
| 822 | raise AssertionError('--manual-symbol-offsets must be used with ' |
| 823 | '--system_health_orderfile.') |
Matthew Cary | e840064 | 2018-06-14 15:43:02 | [diff] [blame] | 824 | |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 825 | if self._options.profile: |
| 826 | try: |
| 827 | _UnstashOutputDirectory(self._instrumented_out_dir) |
| 828 | self._compiler = ClankCompiler( |
| 829 | self._instrumented_out_dir, |
| 830 | self._step_recorder, self._options.arch, self._options.jobs, |
| 831 | self._options.max_load, self._options.use_goma, |
Matthew Cary | d6bfcb7 | 2018-09-14 11:27:46 | [diff] [blame] | 832 | self._options.goma_dir, self._options.system_health_orderfile, |
Stephen Kyle | f11339f | 2019-03-25 09:00:47 | [diff] [blame^] | 833 | self._monochrome, self._options.public, |
| 834 | self._GetPathToOrderfile()) |
Matthew Cary | a2bea45 | 2018-11-13 10:21:07 | [diff] [blame] | 835 | if not self._options.pregenerated_profiles: |
| 836 | # If there are pregenerated profiles, the instrumented build should |
| 837 | # not be changed to avoid invalidating the pregenerated profile |
| 838 | # offsets. |
| 839 | self._compiler.CompileChromeApk(True) |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 840 | self._GenerateAndProcessProfile() |
| 841 | self._MaybeArchiveOrderfile(self._GetUnpatchedOrderfileFilename()) |
| 842 | profile_uploaded = True |
| 843 | finally: |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 844 | _StashOutputDirectory(self._instrumented_out_dir) |
Matthew Cary | e840064 | 2018-06-14 15:43:02 | [diff] [blame] | 845 | elif self._options.manual_symbol_offsets: |
| 846 | assert self._options.manual_libname |
| 847 | assert self._options.manual_objdir |
| 848 | with file(self._options.manual_symbol_offsets) as f: |
| 849 | symbol_offsets = [int(x) for x in f.xreadlines()] |
| 850 | processor = process_profiles.SymbolOffsetProcessor( |
Matthew Cary | b46ad28 | 2018-11-23 14:43:57 | [diff] [blame] | 851 | self._compiler.manual_libname) |
Matthew Cary | e840064 | 2018-06-14 15:43:02 | [diff] [blame] | 852 | generator = cyglog_to_orderfile.OffsetOrderfileGenerator( |
| 853 | processor, cyglog_to_orderfile.ObjectFileProcessor( |
| 854 | self._options.manual_objdir)) |
| 855 | ordered_sections = generator.GetOrderedSections(symbol_offsets) |
| 856 | if not ordered_sections: # Either None or empty is a problem. |
| 857 | raise Exception('Failed to get ordered sections') |
| 858 | with open(self._GetUnpatchedOrderfileFilename(), 'w') as orderfile: |
| 859 | orderfile.write('\n'.join(ordered_sections)) |
| 860 | |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 861 | if self._options.patch: |
| 862 | if self._options.profile: |
| 863 | self._RemoveBlanks(self._GetUnpatchedOrderfileFilename(), |
| 864 | self._GetPathToOrderfile()) |
| 865 | try: |
| 866 | _UnstashOutputDirectory(self._uninstrumented_out_dir) |
| 867 | self._compiler = ClankCompiler( |
| 868 | self._uninstrumented_out_dir, self._step_recorder, |
| 869 | self._options.arch, self._options.jobs, self._options.max_load, |
Matthew Cary | 78aae16 | 2018-08-10 17:16:30 | [diff] [blame] | 870 | self._options.use_goma, self._options.goma_dir, |
Stephen Kyle | f11339f | 2019-03-25 09:00:47 | [diff] [blame^] | 871 | self._options.system_health_orderfile, self._monochrome, |
| 872 | self._options.public, self._GetPathToOrderfile()) |
| 873 | |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 874 | self._compiler.CompileLibchrome(False) |
| 875 | self._PatchOrderfile() |
| 876 | # Because identical code folding is a bit different with and without |
| 877 | # the orderfile build, we need to re-patch the orderfile with code |
| 878 | # folding as close to the final version as possible. |
| 879 | self._compiler.CompileLibchrome(False, force_relink=True) |
| 880 | self._PatchOrderfile() |
| 881 | self._compiler.CompileLibchrome(False, force_relink=True) |
| 882 | self._VerifySymbolOrder() |
| 883 | self._MaybeArchiveOrderfile(self._GetPathToOrderfile()) |
| 884 | finally: |
| 885 | _StashOutputDirectory(self._uninstrumented_out_dir) |
| 886 | orderfile_uploaded = True |
| 887 | |
Matthew Cary | c5ab92a | 2019-03-19 15:49:24 | [diff] [blame] | 888 | if self._options.new_commit_flow: |
Matthew Cary | 86a226e | 2019-03-19 12:17:44 | [diff] [blame] | 889 | self._orderfile_updater._GitStash() |
| 890 | else: |
| 891 | if (self._options.buildbot and self._options.netrc |
| 892 | and not self._step_recorder.ErrorRecorded()): |
| 893 | unpatched_orderfile_filename = ( |
| 894 | self._GetUnpatchedOrderfileFilename() if profile_uploaded else None) |
| 895 | orderfile_filename = ( |
| 896 | self._GetPathToOrderfile() if orderfile_uploaded else None) |
| 897 | self._orderfile_updater.LegacyCommitFileHashes( |
| 898 | unpatched_orderfile_filename, orderfile_filename) |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 899 | self._step_recorder.EndStep() |
| 900 | return not self._step_recorder.ErrorRecorded() |
| 901 | |
| 902 | def GetReportingData(self): |
| 903 | """Get a dictionary of reporting data (timings, output hashes)""" |
| 904 | self._output_data['timings'] = self._step_recorder.timings |
| 905 | return self._output_data |
| 906 | |
Matthew Cary | 86a226e | 2019-03-19 12:17:44 | [diff] [blame] | 907 | def CommitStashedOrderfileHashes(self): |
| 908 | """Commit any orderfile hash files in the current checkout. |
| 909 | |
| 910 | Only possible if running on the buildbot. |
| 911 | |
| 912 | Returns: true on success. |
| 913 | """ |
| 914 | if not (self._options.buildbot and self._options.netrc): |
| 915 | logging.error('Trying to commit when not running on the buildbot') |
| 916 | return False |
| 917 | self._orderfile_updater._CommitStashedFiles([ |
| 918 | filename + '.sha1' |
| 919 | for filename in (self._GetUnpatchedOrderfileFilename(), |
| 920 | self._GetPathToOrderfile())]) |
| 921 | return True |
| 922 | |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 923 | |
Benoit Lize | a1b64f8 | 2017-12-07 10:12:50 | [diff] [blame] | 924 | def CreateArgumentParser(): |
| 925 | """Creates and returns the argument parser.""" |
| 926 | parser = argparse.ArgumentParser() |
| 927 | parser.add_argument( |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 928 | '--buildbot', action='store_true', |
| 929 | help='If true, the script expects to be run on a buildbot') |
Benoit Lize | a1b64f8 | 2017-12-07 10:12:50 | [diff] [blame] | 930 | parser.add_argument( |
Matthew Cary | 453ff145 | 2018-07-18 12:19:35 | [diff] [blame] | 931 | '--device', default=None, type=str, |
| 932 | help='Device serial number on which to run profiling.') |
| 933 | parser.add_argument( |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 934 | '--verify', action='store_true', |
| 935 | help='If true, the script only verifies the current orderfile') |
Benoit Lize | a1b64f8 | 2017-12-07 10:12:50 | [diff] [blame] | 936 | parser.add_argument('--target-arch', action='store', dest='arch', |
Stephen Martinis | 71b391b5 | 2018-12-04 15:08:04 | [diff] [blame] | 937 | default='arm', |
Matthew Cary | 53f74ba | 2019-01-24 10:07:18 | [diff] [blame] | 938 | choices=['arm', 'arm64'], |
| 939 | help='The target architecture for which to build.') |
Benoit Lize | a1b64f8 | 2017-12-07 10:12:50 | [diff] [blame] | 940 | parser.add_argument('--output-json', action='store', dest='json_file', |
| 941 | help='Location to save stats in json format') |
| 942 | parser.add_argument( |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 943 | '--skip-profile', action='store_false', dest='profile', default=True, |
| 944 | help='Don\'t generate a profile on the device. Only patch from the ' |
| 945 | 'existing profile.') |
Benoit Lize | a1b64f8 | 2017-12-07 10:12:50 | [diff] [blame] | 946 | parser.add_argument( |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 947 | '--skip-patch', action='store_false', dest='patch', default=True, |
| 948 | help='Only generate the raw (unpatched) orderfile, don\'t patch it.') |
Benoit Lize | a1b64f8 | 2017-12-07 10:12:50 | [diff] [blame] | 949 | parser.add_argument( |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 950 | '--netrc', action='store', |
| 951 | help='A custom .netrc file to use for git checkin. Only used on bots.') |
Benoit Lize | a1b64f8 | 2017-12-07 10:12:50 | [diff] [blame] | 952 | parser.add_argument( |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 953 | '--branch', action='store', default='master', |
| 954 | help='When running on buildbot with a netrc, the branch orderfile ' |
| 955 | 'hashes get checked into.') |
| 956 | # Note: -j50 was causing issues on the bot. |
Benoit Lize | a1b64f8 | 2017-12-07 10:12:50 | [diff] [blame] | 957 | parser.add_argument( |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 958 | '-j', '--jobs', action='store', default=20, |
| 959 | help='Number of jobs to use for compilation.') |
Benoit Lize | a1b64f8 | 2017-12-07 10:12:50 | [diff] [blame] | 960 | parser.add_argument( |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 961 | '-l', '--max-load', action='store', default=4, help='Max cpu load.') |
Benoit Lize | a1b64f8 | 2017-12-07 10:12:50 | [diff] [blame] | 962 | parser.add_argument('--goma-dir', help='GOMA directory.') |
| 963 | parser.add_argument( |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 964 | '--use-goma', action='store_true', help='Enable GOMA.', default=False) |
Benoit Lize | a1b64f8 | 2017-12-07 10:12:50 | [diff] [blame] | 965 | parser.add_argument('--adb-path', help='Path to the adb binary.') |
Matthew Cary | e840064 | 2018-06-14 15:43:02 | [diff] [blame] | 966 | |
Stephen Kyle | f11339f | 2019-03-25 09:00:47 | [diff] [blame^] | 967 | parser.add_argument('--public', action='store_true', |
| 968 | help='Required if your checkout is non-internal.', |
| 969 | default=False) |
Matthew Cary | 04f4103 | 2018-12-10 15:55:27 | [diff] [blame] | 970 | parser.add_argument('--nosystem-health-orderfile', action='store_false', |
| 971 | dest='system_health_orderfile', default=True, |
Matthew Cary | c262f5d | 2018-09-19 14:36:28 | [diff] [blame] | 972 | help=('Create an orderfile based on an about:blank ' |
| 973 | 'startup benchmark instead of system health ' |
| 974 | 'benchmarks.')) |
Monica Salama | eea2d94 | 2019-03-11 12:36:18 | [diff] [blame] | 975 | parser.add_argument( |
| 976 | '--use-legacy-chrome-apk', action='store_true', default=False, |
| 977 | help=('Compile and instrument chrome for [L, K] devices.')) |
Matthew Cary | 78aae16 | 2018-08-10 17:16:30 | [diff] [blame] | 978 | |
Matthew Cary | e840064 | 2018-06-14 15:43:02 | [diff] [blame] | 979 | parser.add_argument('--manual-symbol-offsets', default=None, type=str, |
| 980 | help=('File of list of ordered symbol offsets generated ' |
| 981 | 'by manual profiling. Must set other --manual* ' |
| 982 | 'flags if this is used, and must --skip-profile.')) |
| 983 | parser.add_argument('--manual-libname', default=None, type=str, |
| 984 | help=('Library filename corresponding to ' |
| 985 | '--manual-symbol-offsets.')) |
| 986 | parser.add_argument('--manual-objdir', default=None, type=str, |
| 987 | help=('Root of object file directory corresponding to ' |
| 988 | '--manual-symbol-offsets.')) |
Matthew Cary | f949bba | 2019-02-04 13:39:23 | [diff] [blame] | 989 | parser.add_argument('--noorder-outlined-functions', action='store_true', |
| 990 | help='Disable outlined functions in the orderfile.') |
Matthew Cary | 69e9e42 | 2018-08-10 18:30:06 | [diff] [blame] | 991 | parser.add_argument('--pregenerated-profiles', default=None, type=str, |
| 992 | help=('Pregenerated profiles to use instead of running ' |
| 993 | 'profile step. Cannot be used with ' |
| 994 | '--skip-profiles.')) |
| 995 | parser.add_argument('--profile-save-dir', default=None, type=str, |
| 996 | help=('Directory to save any profiles created. These can ' |
| 997 | 'be used with --pregenerated-profiles. Cannot be ' |
| 998 | 'used with --skip-profiles.')) |
Egor Pasko | bce64d01 | 2018-11-20 12:02:37 | [diff] [blame] | 999 | parser.add_argument('--upload-ready-orderfiles', action='store_true', |
| 1000 | help=('Skip orderfile generation and manually upload ' |
| 1001 | 'orderfiles (both patched and unpatched) from ' |
| 1002 | 'their normal location in the tree to the cloud ' |
| 1003 | 'storage. DANGEROUS! USE WITH CARE!')) |
Matthew Cary | 1ea8221 | 2019-03-20 12:10:27 | [diff] [blame] | 1004 | parser.add_argument('--streamline-for-debugging', action='store_true', |
| 1005 | help=('Streamline where possible the run for faster ' |
| 1006 | 'iteration while debugging. The orderfile ' |
| 1007 | 'generated will be valid and nontrivial, but ' |
| 1008 | 'may not be based on a representative profile ' |
| 1009 | 'or other such considerations. Use with caution.')) |
Matthew Cary | 86a226e | 2019-03-19 12:17:44 | [diff] [blame] | 1010 | parser.add_argument('--commit-hashes', action='store_true', |
| 1011 | help=('Commit any orderfile hash files in the current ' |
| 1012 | 'checkout; performs no other action')) |
| 1013 | parser.add_argument('--new-commit-flow', action='store_true', |
| 1014 | help='Use the new two-step commit flow.') |
Matthew Cary | e840064 | 2018-06-14 15:43:02 | [diff] [blame] | 1015 | |
Benoit Lize | a1b64f8 | 2017-12-07 10:12:50 | [diff] [blame] | 1016 | profile_android_startup.AddProfileCollectionArguments(parser) |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 1017 | return parser |
| 1018 | |
| 1019 | |
Stephen Kyle | f11339f | 2019-03-25 09:00:47 | [diff] [blame^] | 1020 | def CreateOrderfile(options, orderfile_updater_class=None): |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 1021 | """Creates an oderfile. |
| 1022 | |
| 1023 | Args: |
| 1024 | options: As returned from optparse.OptionParser.parse_args() |
| 1025 | orderfile_updater_class: (OrderfileUpdater) subclass of OrderfileUpdater. |
Stephen Kyle | f11339f | 2019-03-25 09:00:47 | [diff] [blame^] | 1026 | Use to explicitly set an OrderfileUpdater class, |
| 1027 | the defaults are OrderfileUpdater, or |
| 1028 | OrderfileNoopUpdater if --public is set. |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 1029 | |
| 1030 | Returns: |
| 1031 | True iff success. |
| 1032 | """ |
| 1033 | logging.basicConfig(level=logging.INFO) |
| 1034 | devil_chromium.Initialize(adb_path=options.adb_path) |
| 1035 | |
Egor Pasko | 93e514e | 2017-10-31 13:32:36 | [diff] [blame] | 1036 | generator = OrderfileGenerator(options, orderfile_updater_class) |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 1037 | try: |
| 1038 | if options.verify: |
Egor Pasko | 93e514e | 2017-10-31 13:32:36 | [diff] [blame] | 1039 | generator._VerifySymbolOrder() |
Matthew Cary | 86a226e | 2019-03-19 12:17:44 | [diff] [blame] | 1040 | elif options.commit_hashes: |
Matthew Cary | c5ab92a | 2019-03-19 15:49:24 | [diff] [blame] | 1041 | if not options.new_commit_flow: |
Matthew Cary | 86a226e | 2019-03-19 12:17:44 | [diff] [blame] | 1042 | raise Exception('--commit-hashes requries --new-commit-flow') |
| 1043 | return generator.CommitStashedOrderfileHashes() |
Egor Pasko | bce64d01 | 2018-11-20 12:02:37 | [diff] [blame] | 1044 | elif options.upload_ready_orderfiles: |
| 1045 | return generator.UploadReadyOrderfiles() |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 1046 | else: |
Egor Pasko | 93e514e | 2017-10-31 13:32:36 | [diff] [blame] | 1047 | return generator.Generate() |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 1048 | finally: |
Egor Pasko | 93e514e | 2017-10-31 13:32:36 | [diff] [blame] | 1049 | json_output = json.dumps(generator.GetReportingData(), |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 1050 | indent=2) + '\n' |
| 1051 | if options.json_file: |
| 1052 | with open(options.json_file, 'w') as f: |
| 1053 | f.write(json_output) |
| 1054 | print json_output |
| 1055 | return False |
| 1056 | |
| 1057 | |
Benoit Lize | a1b64f8 | 2017-12-07 10:12:50 | [diff] [blame] | 1058 | def main(): |
| 1059 | parser = CreateArgumentParser() |
| 1060 | options = parser.parse_args() |
Stephen Kyle | f11339f | 2019-03-25 09:00:47 | [diff] [blame^] | 1061 | return 0 if CreateOrderfile(options) else 1 |
Benoit Lize | a3fe293 | 2017-10-20 10:24:52 | [diff] [blame] | 1062 | |
| 1063 | |
| 1064 | if __name__ == '__main__': |
Benoit Lize | a1b64f8 | 2017-12-07 10:12:50 | [diff] [blame] | 1065 | sys.exit(main()) |