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