[go: nahoru, domu]

blob: b9f0200f52a32026e44457048b1447a63bdbcbcf [file] [log] [blame]
Ari Chivukulaa52f8ba2021-08-10 22:30:391#!/usr/bin/env vpython3
Benoit Lizea3fe2932017-10-20 10:24:522# 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
8The orderfile is used by the linker to order text sections such that the
9sections are placed consecutively in the order specified. This allows us
10to page in less code during start-up.
11
12Example usage:
Egor Paskoa7ac67a42020-09-09 12:06:5813 tools/cygprofile/orderfile_generator_backend.py --use-goma --target-arch=arm
Benoit Lizea3fe2932017-10-20 10:24:5214"""
15
Raul Tambre48f176622019-09-23 10:05:2416
Benoit Lizea1b64f82017-12-07 10:12:5017import argparse
Egor Paskoa7ac67a42020-09-09 12:06:5818import csv
Benoit Lizea3fe2932017-10-20 10:24:5219import hashlib
20import json
Matthew Cary69e9e422018-08-10 18:30:0621import glob
Benoit Lizea3fe2932017-10-20 10:24:5222import logging
Benoit Lizea3fe2932017-10-20 10:24:5223import os
Benoit Lizea3fe2932017-10-20 10:24:5224import shutil
25import subprocess
26import sys
Benoit Lizea87e5bc2017-11-07 15:12:5727import tempfile
Benoit Lizea3fe2932017-10-20 10:24:5228import time
29
Matthew Cary91df9792018-11-30 14:35:1530import cluster
Matthew Carye8400642018-06-14 15:43:0231import cyglog_to_orderfile
Benoit Lizefefbb27c2018-01-17 13:54:1832import patch_orderfile
Benoit Lizea87e5bc2017-11-07 15:12:5733import process_profiles
Egor Pasko3bc0b932018-04-03 10:08:2734import profile_android_startup
Benoit Lizefefbb27c2018-01-17 13:54:1835import symbol_extractor
Benoit Lizea3fe2932017-10-20 10:24:5236
Monica Salamaeea2d942019-03-11 12:36:1837_SRC_PATH = os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)
38sys.path.append(os.path.join(_SRC_PATH, 'third_party', 'catapult', 'devil'))
39from devil.android import device_utils
40from devil.android.sdk import version_codes
41
Benoit Lizea3fe2932017-10-20 10:24:5242
43_SRC_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)),
44 os.pardir, os.pardir)
45sys.path.append(os.path.join(_SRC_PATH, 'build', 'android'))
46import devil_chromium
47from pylib import constants
48
49
50# Needs to happen early for GetBuildType()/GetOutDirectory() to work correctly
51constants.SetBuildType('Release')
52
53
Matthew Cary53f74ba2019-01-24 10:07:1854# Architecture specific GN args. Trying to build an orderfile for an
55# architecture not listed here will eventually throw.
56_ARCH_GN_ARGS = {
57 'arm': [ 'target_cpu = "arm"' ],
58 'arm64': [ 'target_cpu = "arm64"',
59 'android_64bit_browser = true'],
60}
61
Benoit Lizea3fe2932017-10-20 10:24:5262class CommandError(Exception):
63 """Indicates that a dispatched shell command exited with a non-zero status."""
64
65 def __init__(self, value):
66 super(CommandError, self).__init__()
67 self.value = value
68
69 def __str__(self):
70 return repr(self.value)
71
72
73def _GenerateHash(file_path):
74 """Calculates and returns the hash of the file at file_path."""
75 sha1 = hashlib.sha1()
76 with open(file_path, 'rb') as f:
77 while True:
78 # Read in 1mb chunks, so it doesn't all have to be loaded into memory.
79 chunk = f.read(1024 * 1024)
80 if not chunk:
81 break
82 sha1.update(chunk)
83 return sha1.hexdigest()
84
85
86def _GetFileExtension(file_name):
87 """Calculates the file extension from a file name.
88
89 Args:
90 file_name: The source file name.
91 Returns:
92 The part of file_name after the dot (.) or None if the file has no
93 extension.
94 Examples: /home/user/foo.bar -> bar
95 /home/user.name/foo -> None
96 /home/user/.foo -> None
97 /home/user/foo.bar.baz -> baz
98 """
99 file_name_parts = os.path.basename(file_name).split('.')
100 if len(file_name_parts) > 1:
101 return file_name_parts[-1]
102 else:
103 return None
104
105
106def _StashOutputDirectory(buildpath):
107 """Takes the output directory and stashes it in the default output directory.
108
109 This allows it to be used for incremental builds next time (after unstashing)
110 by keeping it in a place that isn't deleted normally, while also ensuring
111 that it is properly clobbered when appropriate.
112
113 This is a dirty hack to deal with the needs of clobbering while also handling
114 incremental builds and the hardcoded relative paths used in some of the
115 project files.
116
117 Args:
118 buildpath: The path where the building happens. If this corresponds to the
119 default output directory, no action is taken.
120 """
121 if os.path.abspath(buildpath) == os.path.abspath(os.path.dirname(
122 constants.GetOutDirectory())):
123 return
124 name = os.path.basename(buildpath)
125 stashpath = os.path.join(constants.GetOutDirectory(), name)
126 if not os.path.exists(buildpath):
127 return
128 if os.path.exists(stashpath):
129 shutil.rmtree(stashpath, ignore_errors=True)
130 shutil.move(buildpath, stashpath)
131
132
133def _UnstashOutputDirectory(buildpath):
134 """Inverse of _StashOutputDirectory.
135
136 Moves the output directory stashed within the default output directory
137 (out/Release) to the position where the builds can actually happen.
138
139 This is a dirty hack to deal with the needs of clobbering while also handling
140 incremental builds and the hardcoded relative paths used in some of the
141 project files.
142
143 Args:
144 buildpath: The path where the building happens. If this corresponds to the
145 default output directory, no action is taken.
146 """
147 if os.path.abspath(buildpath) == os.path.abspath(os.path.dirname(
148 constants.GetOutDirectory())):
149 return
150 name = os.path.basename(buildpath)
151 stashpath = os.path.join(constants.GetOutDirectory(), name)
152 if not os.path.exists(stashpath):
153 return
154 if os.path.exists(buildpath):
155 shutil.rmtree(buildpath, ignore_errors=True)
156 shutil.move(stashpath, buildpath)
157
158
159class StepRecorder(object):
160 """Records steps and timings."""
161
162 def __init__(self, buildbot):
163 self.timings = []
164 self._previous_step = ('', 0.0)
165 self._buildbot = buildbot
166 self._error_recorded = False
167
168 def BeginStep(self, name):
169 """Marks a beginning of the next step in the script.
170
171 On buildbot, this prints a specially formatted name that will show up
172 in the waterfall. Otherwise, just prints the step name.
173
174 Args:
175 name: The name of the step.
176 """
177 self.EndStep()
178 self._previous_step = (name, time.time())
Raul Tambre48f176622019-09-23 10:05:24179 print('Running step: ', name)
Benoit Lizea3fe2932017-10-20 10:24:52180
181 def EndStep(self):
182 """Records successful completion of the current step.
183
184 This is optional if the step is immediately followed by another BeginStep.
185 """
186 if self._previous_step[0]:
187 elapsed = time.time() - self._previous_step[1]
Raul Tambre48f176622019-09-23 10:05:24188 print('Step %s took %f seconds' % (self._previous_step[0], elapsed))
Benoit Lizea3fe2932017-10-20 10:24:52189 self.timings.append((self._previous_step[0], elapsed))
190
191 self._previous_step = ('', 0.0)
192
193 def FailStep(self, message=None):
194 """Marks that a particular step has failed.
195
196 On buildbot, this will mark the current step as failed on the waterfall.
197 Otherwise we will just print an optional failure message.
198
199 Args:
200 message: An optional explanation as to why the step failed.
201 """
Raul Tambre48f176622019-09-23 10:05:24202 print('STEP FAILED!!')
Benoit Lizea3fe2932017-10-20 10:24:52203 if message:
Raul Tambre48f176622019-09-23 10:05:24204 print(message)
Benoit Lizea3fe2932017-10-20 10:24:52205 self._error_recorded = True
206 self.EndStep()
207
208 def ErrorRecorded(self):
209 """True if FailStep has been called."""
210 return self._error_recorded
211
212 def RunCommand(self, cmd, cwd=constants.DIR_SOURCE_ROOT, raise_on_error=True,
213 stdout=None):
214 """Execute a shell command.
215
216 Args:
217 cmd: A list of command strings.
Matthew Cary78aae162018-08-10 17:16:30218 cwd: Directory in which the command should be executed, defaults to build
219 root of script's location if not specified.
Benoit Lizea3fe2932017-10-20 10:24:52220 raise_on_error: If true will raise a CommandError if the call doesn't
221 succeed and mark the step as failed.
222 stdout: A file to redirect stdout for the command to.
223
224 Returns:
225 The process's return code.
226
227 Raises:
228 CommandError: An error executing the specified command.
229 """
Raul Tambre48f176622019-09-23 10:05:24230 print('Executing %s in %s' % (' '.join(cmd), cwd))
Benoit Lizea3fe2932017-10-20 10:24:52231 process = subprocess.Popen(cmd, stdout=stdout, cwd=cwd, env=os.environ)
232 process.wait()
233 if raise_on_error and process.returncode != 0:
234 self.FailStep()
235 raise CommandError('Exception executing command %s' % ' '.join(cmd))
236 return process.returncode
237
238
239class ClankCompiler(object):
240 """Handles compilation of clank."""
241
Christopher Grant073637472019-07-05 13:34:57242 def __init__(self, out_dir, step_recorder, arch, use_goma, goma_dir,
243 system_health_profiling, monochrome, public, orderfile_location):
Benoit Lizea3fe2932017-10-20 10:24:52244 self._out_dir = out_dir
245 self._step_recorder = step_recorder
Benoit Lizea87e5bc2017-11-07 15:12:57246 self._arch = arch
Benoit Lizea3fe2932017-10-20 10:24:52247 self._use_goma = use_goma
Benoit Lizea87e5bc2017-11-07 15:12:57248 self._goma_dir = goma_dir
Matthew Cary78aae162018-08-10 17:16:30249 self._system_health_profiling = system_health_profiling
Stephen Kylef11339f2019-03-25 09:00:47250 self._public = public
251 self._orderfile_location = orderfile_location
Matthew Caryd6bfcb72018-09-14 11:27:46252 if monochrome:
253 self._apk = 'Monochrome.apk'
Matthew Carye1b00062018-09-19 14:27:44254 self._apk_target = 'monochrome_apk'
Matthew Caryd6bfcb72018-09-14 11:27:46255 self._libname = 'libmonochrome'
Matthew Cary2216fef2019-06-17 13:35:59256 self._libchrome_target = 'libmonochrome'
Matthew Caryd6bfcb72018-09-14 11:27:46257 else:
258 self._apk = 'Chrome.apk'
Matthew Carye1b00062018-09-19 14:27:44259 self._apk_target = 'chrome_apk'
Matthew Caryd6bfcb72018-09-14 11:27:46260 self._libname = 'libchrome'
261 self._libchrome_target = 'libchrome'
Stephen Kylef11339f2019-03-25 09:00:47262 if public:
263 self._apk = self._apk.replace('.apk', 'Public.apk')
264 self._apk_target = self._apk_target.replace('_apk', '_public_apk')
Matthew Cary78aae162018-08-10 17:16:30265
266 self.obj_dir = os.path.join(self._out_dir, 'Release', 'obj')
Benoit Lizea3fe2932017-10-20 10:24:52267 self.lib_chrome_so = os.path.join(
Matthew Caryd6bfcb72018-09-14 11:27:46268 self._out_dir, 'Release', 'lib.unstripped',
269 '{}.so'.format(self._libname))
270 self.chrome_apk = os.path.join(self._out_dir, 'Release', 'apks', self._apk)
Benoit Lizea3fe2932017-10-20 10:24:52271
Monica Basta99c101f2019-05-21 13:50:05272 def Build(self, instrumented, use_call_graph, target):
Benoit Lizea3fe2932017-10-20 10:24:52273 """Builds the provided ninja target with or without order_profiling on.
274
275 Args:
Benoit Lizea87e5bc2017-11-07 15:12:57276 instrumented: (bool) Whether we want to build an instrumented binary.
Monica Basta99c101f2019-05-21 13:50:05277 use_call_graph: (bool) Whether to use the call graph instrumentation.
Benoit Lizea87e5bc2017-11-07 15:12:57278 target: (str) The name of the ninja target to build.
Benoit Lizea3fe2932017-10-20 10:24:52279 """
280 self._step_recorder.BeginStep('Compile %s' % target)
Monica Basta99c101f2019-05-21 13:50:05281 assert not use_call_graph or instrumented, ('You can not enable call graph '
282 'without instrumentation!')
Benoit Lizea3fe2932017-10-20 10:24:52283
284 # Set the "Release Official" flavor, the parts affecting performance.
285 args = [
Andrew Grieve0e8790c2020-09-03 17:27:32286 'enable_resource_allowlist_generation=false',
Stephen Kylef11339f2019-03-25 09:00:47287 'is_chrome_branded=' + str(not self._public).lower(),
Benoit Lizea3fe2932017-10-20 10:24:52288 'is_debug=false',
289 'is_official_build=true',
Egor Pasko1d13d532020-01-14 21:25:19290 'symbol_level=1', # to fit 30 GiB RAM on the bot when LLD is running
Benoit Lizea3fe2932017-10-20 10:24:52291 'target_os="android"',
292 'use_goma=' + str(self._use_goma).lower(),
293 'use_order_profiling=' + str(instrumented).lower(),
Monica Basta99c101f2019-05-21 13:50:05294 'use_call_graph=' + str(use_call_graph).lower(),
Benoit Lizea3fe2932017-10-20 10:24:52295 ]
Matthew Cary53f74ba2019-01-24 10:07:18296 args += _ARCH_GN_ARGS[self._arch]
Benoit Lizea3fe2932017-10-20 10:24:52297 if self._goma_dir:
298 args += ['goma_dir="%s"' % self._goma_dir]
Matthew Cary78aae162018-08-10 17:16:30299 if self._system_health_profiling:
300 args += ['devtools_instrumentation_dumping = ' +
301 str(instrumented).lower()]
Benoit Lizea87e5bc2017-11-07 15:12:57302
Stephen Kylef11339f2019-03-25 09:00:47303 if self._public and os.path.exists(self._orderfile_location):
304 # GN needs the orderfile path to be source-absolute.
305 src_abs_orderfile = os.path.relpath(self._orderfile_location,
306 constants.DIR_SOURCE_ROOT)
307 args += ['chrome_orderfile="//{}"'.format(src_abs_orderfile)]
308
Benoit Lizea3fe2932017-10-20 10:24:52309 self._step_recorder.RunCommand(
310 ['gn', 'gen', os.path.join(self._out_dir, 'Release'),
311 '--args=' + ' '.join(args)])
312
313 self._step_recorder.RunCommand(
Christopher Grant073637472019-07-05 13:34:57314 ['autoninja', '-C',
315 os.path.join(self._out_dir, 'Release'), target])
Benoit Lizea3fe2932017-10-20 10:24:52316
Christopher Grant10221762019-07-05 12:10:04317 def ForceRelink(self):
318 """Forces libchrome.so or libmonochrome.so to be re-linked.
319
320 With partitioned libraries enabled, deleting these library files does not
321 guarantee they'll be recreated by the linker (they may simply be
322 re-extracted from a combined library). To be safe, touch a source file
323 instead. See http://crbug.com/972701 for more explanation.
324 """
325 file_to_touch = os.path.join(constants.DIR_SOURCE_ROOT, 'chrome', 'browser',
326 'chrome_browser_main_android.cc')
327 assert os.path.exists(file_to_touch)
328 self._step_recorder.RunCommand(['touch', file_to_touch])
329
Monica Basta99c101f2019-05-21 13:50:05330 def CompileChromeApk(self, instrumented, use_call_graph, force_relink=False):
Benoit Lizea3fe2932017-10-20 10:24:52331 """Builds a Chrome.apk either with or without order_profiling on.
332
333 Args:
Benoit Lizea87e5bc2017-11-07 15:12:57334 instrumented: (bool) Whether to build an instrumented apk.
Monica Basta99c101f2019-05-21 13:50:05335 use_call_graph: (bool) Whether to use the call graph instrumentation.
Benoit Lizea3fe2932017-10-20 10:24:52336 force_relink: Whether libchromeview.so should be re-created.
337 """
338 if force_relink:
Christopher Grant10221762019-07-05 12:10:04339 self.ForceRelink()
Monica Basta99c101f2019-05-21 13:50:05340 self.Build(instrumented, use_call_graph, self._apk_target)
Benoit Lizea3fe2932017-10-20 10:24:52341
Monica Basta99c101f2019-05-21 13:50:05342 def CompileLibchrome(self, instrumented, use_call_graph, force_relink=False):
Benoit Lizea3fe2932017-10-20 10:24:52343 """Builds a libchrome.so either with or without order_profiling on.
344
345 Args:
Benoit Lizea87e5bc2017-11-07 15:12:57346 instrumented: (bool) Whether to build an instrumented apk.
Monica Basta99c101f2019-05-21 13:50:05347 use_call_graph: (bool) Whether to use the call graph instrumentation.
Benoit Lizea87e5bc2017-11-07 15:12:57348 force_relink: (bool) Whether libchrome.so should be re-created.
Benoit Lizea3fe2932017-10-20 10:24:52349 """
350 if force_relink:
Christopher Grant10221762019-07-05 12:10:04351 self.ForceRelink()
Monica Basta99c101f2019-05-21 13:50:05352 self.Build(instrumented, use_call_graph, self._libchrome_target)
Benoit Lizea3fe2932017-10-20 10:24:52353
354
355class OrderfileUpdater(object):
356 """Handles uploading and committing a new orderfile in the repository.
357
358 Only used for testing or on a bot.
359 """
360
361 _CLOUD_STORAGE_BUCKET_FOR_DEBUG = None
362 _CLOUD_STORAGE_BUCKET = None
363 _UPLOAD_TO_CLOUD_COMMAND = 'upload_to_google_storage.py'
364
Egor Pasko0c533c6682019-11-26 21:16:32365 def __init__(self, repository_root, step_recorder):
Benoit Lizea3fe2932017-10-20 10:24:52366 """Constructor.
367
368 Args:
369 repository_root: (str) Root of the target repository.
370 step_recorder: (StepRecorder) Step recorder, for logging.
Benoit Lizea3fe2932017-10-20 10:24:52371 """
372 self._repository_root = repository_root
373 self._step_recorder = step_recorder
Benoit Lizea3fe2932017-10-20 10:24:52374
Matthew Cary86a226e2019-03-19 12:17:44375 def CommitStashedFileHashes(self, files):
376 """Commits unpatched and patched orderfiles hashes if changed.
377
378 The files are committed only if their associated sha1 hash files match, and
379 are modified in git. In normal operations the hash files are changed only
380 when a file is uploaded to cloud storage. If the hash file is not modified
381 in git, the file is skipped.
382
383 Args:
384 files: [str or None] specifies file paths. None items are ignored.
385
386 Raises:
387 Exception if the hash file does not match the file.
388 NotImplementedError when the commit logic hasn't been overridden.
389 """
Ari Chivukulaa52f8ba2021-08-10 22:30:39390 files_to_commit = [_f for _f in files if _f]
Matthew Cary86a226e2019-03-19 12:17:44391 if files_to_commit:
392 self._CommitStashedFiles(files_to_commit)
393
Benoit Lizea3fe2932017-10-20 10:24:52394 def UploadToCloudStorage(self, filename, use_debug_location):
395 """Uploads a file to cloud storage.
396
397 Args:
398 filename: (str) File to upload.
399 use_debug_location: (bool) Whether to use the debug location.
400 """
401 bucket = (self._CLOUD_STORAGE_BUCKET_FOR_DEBUG if use_debug_location
402 else self._CLOUD_STORAGE_BUCKET)
403 extension = _GetFileExtension(filename)
404 cmd = [self._UPLOAD_TO_CLOUD_COMMAND, '--bucket', bucket]
405 if extension:
406 cmd.extend(['-z', extension])
407 cmd.append(filename)
408 self._step_recorder.RunCommand(cmd)
Raul Tambre48f176622019-09-23 10:05:24409 print('Download: https://sandbox.google.com/storage/%s/%s' %
410 (bucket, _GenerateHash(filename)))
Benoit Lizea3fe2932017-10-20 10:24:52411
412 def _GetHashFilePathAndContents(self, filename):
413 """Gets the name and content of the hash file created from uploading the
414 given file.
415
416 Args:
417 filename: (str) The file that was uploaded to cloud storage.
418
419 Returns:
420 A tuple of the hash file name, relative to the reository root, and the
421 content, which should be the sha1 hash of the file
422 ('base_file.sha1', hash)
423 """
424 abs_hash_filename = filename + '.sha1'
425 rel_hash_filename = os.path.relpath(
426 abs_hash_filename, self._repository_root)
427 with open(abs_hash_filename, 'r') as f:
428 return (rel_hash_filename, f.read())
429
Matthew Cary86a226e2019-03-19 12:17:44430 def _GitStash(self):
431 """Git stash the current clank tree.
432
433 Raises:
434 NotImplementedError when the stash logic hasn't been overridden.
435 """
436 raise NotImplementedError
437
438 def _CommitStashedFiles(self, expected_files_in_stash):
439 """Commits stashed files.
440
441 The local repository is updated and then the files to commit are taken from
442 modified files from the git stash. The modified files should be a subset of
443 |expected_files_in_stash|. If there are unexpected modified files, this
444 function may raise. This is meant to be paired with _GitStash().
445
446 Args:
447 expected_files_in_stash: [str] paths to a possible superset of files
448 expected to be stashed & committed.
449
450 Raises:
451 NotImplementedError when the commit logic hasn't been overridden.
452 """
453 raise NotImplementedError
454
Benoit Lizea3fe2932017-10-20 10:24:52455
456class OrderfileGenerator(object):
457 """A utility for generating a new orderfile for Clank.
458
459 Builds an instrumented binary, profiles a run of the application, and
460 generates an updated orderfile.
461 """
Benoit Lizea3fe2932017-10-20 10:24:52462 _CHECK_ORDERFILE_SCRIPT = os.path.join(
463 constants.DIR_SOURCE_ROOT, 'tools', 'cygprofile', 'check_orderfile.py')
464 _BUILD_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(
465 constants.GetOutDirectory()))) # Normally /path/to/src
466
Benoit Lizea3fe2932017-10-20 10:24:52467 # Previous orderfile_generator debug files would be overwritten.
468 _DIRECTORY_FOR_DEBUG_FILES = '/tmp/orderfile_generator_debug_files'
469
Stephen Kylef11339f2019-03-25 09:00:47470 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 Lizea3fe2932017-10-20 10:24:52485 def _GetPathToOrderfile(self):
486 """Gets the path to the architecture-specific orderfile."""
Stephen Kylef11339f2019-03-25 09:00:47487 return self._path_to_orderfile % self._options.arch
Benoit Lizea3fe2932017-10-20 10:24:52488
489 def _GetUnpatchedOrderfileFilename(self):
490 """Gets the path to the architecture-specific unpatched orderfile."""
Stephen Kylef11339f2019-03-25 09:00:47491 return self._unpatched_orderfile_filename % self._options.arch
Benoit Lizea3fe2932017-10-20 10:24:52492
Monica Salamaeea2d942019-03-11 12:36:18493 def _SetDevice(self):
494 """ Selects the device to be used by the script.
495
496 Returns:
497 (Device with given serial ID) : if the --device flag is set.
498 (Device running Android[K,L]) : if --use-legacy-chrome-apk flag is set or
499 no device running Android N+ was found.
500 (Device running Android N+) : Otherwise.
501
502 Raises Error:
503 If no device meeting the requirements has been found.
504 """
505 devices = None
506 if self._options.device:
507 devices = [device_utils.DeviceUtils(self._options.device)]
508 else:
509 devices = device_utils.DeviceUtils.HealthyDevices()
510
511 assert devices, 'Expected at least one connected device'
512
513 if self._options.use_legacy_chrome_apk:
514 self._monochrome = False
515 for device in devices:
516 device_version = device.build_version_sdk
517 if (device_version >= version_codes.KITKAT
518 and device_version <= version_codes.LOLLIPOP_MR1):
519 return device
520
521 assert not self._options.use_legacy_chrome_apk, \
522 'No device found running suitable android version for Chrome.apk.'
523
524 preferred_device = None
525 for device in devices:
526 if device.build_version_sdk >= version_codes.NOUGAT:
Monica Salama90b8f5b2019-04-25 11:10:38527 preferred_device = device
528 break
Monica Salamaeea2d942019-03-11 12:36:18529
530 self._monochrome = preferred_device is not None
531
532 return preferred_device if preferred_device else devices[0]
533
534
Benoit Lizea3fe2932017-10-20 10:24:52535 def __init__(self, options, orderfile_updater_class):
536 self._options = options
Benoit Lizea3fe2932017-10-20 10:24:52537 self._instrumented_out_dir = os.path.join(
538 self._BUILD_ROOT, self._options.arch + '_instrumented_out')
Monica Basta99c101f2019-05-21 13:50:05539 if self._options.use_call_graph:
Christopher Grantdfe1bac2019-07-05 13:34:10540 self._instrumented_out_dir += '_call_graph'
Monica Basta99c101f2019-05-21 13:50:05541
Benoit Lizea3fe2932017-10-20 10:24:52542 self._uninstrumented_out_dir = os.path.join(
543 self._BUILD_ROOT, self._options.arch + '_uninstrumented_out')
Monica Salama90b8f5b2019-04-25 11:10:38544 self._no_orderfile_out_dir = os.path.join(
545 self._BUILD_ROOT, self._options.arch + '_no_orderfile_out')
Benoit Lizea3fe2932017-10-20 10:24:52546
Stephen Kylef11339f2019-03-25 09:00:47547 self._PrepareOrderfilePaths()
548
Benoit Lizea3fe2932017-10-20 10:24:52549 if options.profile:
Benoit Lizea1b64f82017-12-07 10:12:50550 output_directory = os.path.join(self._instrumented_out_dir, 'Release')
Matthew Caryb8daed942018-06-11 10:58:08551 host_profile_dir = os.path.join(output_directory, 'profile_data')
Benoit Lizea1b64f82017-12-07 10:12:50552 urls = [profile_android_startup.AndroidProfileTool.TEST_URL]
553 use_wpr = True
554 simulate_user = False
Benoit L96466812018-03-06 15:58:37555 urls = options.urls
556 use_wpr = not options.no_wpr
557 simulate_user = options.simulate_user
Monica Salamaeea2d942019-03-11 12:36:18558 device = self._SetDevice()
Benoit Lizea3fe2932017-10-20 10:24:52559 self._profiler = profile_android_startup.AndroidProfileTool(
Matthew Cary453ff1452018-07-18 12:19:35560 output_directory, host_profile_dir, use_wpr, urls, simulate_user,
Matthew Cary1ea82212019-03-20 12:10:27561 device, debug=self._options.streamline_for_debugging)
Matthew Cary69e9e422018-08-10 18:30:06562 if options.pregenerated_profiles:
563 self._profiler.SetPregeneratedProfiles(
564 glob.glob(options.pregenerated_profiles))
565 else:
566 assert not options.pregenerated_profiles, (
567 '--pregenerated-profiles cannot be used with --skip-profile')
568 assert not options.profile_save_dir, (
569 '--profile-save-dir cannot be used with --skip-profile')
Monica Salamaeea2d942019-03-11 12:36:18570 self._monochrome = not self._options.use_legacy_chrome_apk
Benoit Lizea3fe2932017-10-20 10:24:52571
Matthew Caryf949bba2019-02-04 13:39:23572 # Outlined function handling enabled by default for all architectures.
573 self._order_outlined_functions = not options.noorder_outlined_functions
574
Benoit Lizea3fe2932017-10-20 10:24:52575 self._output_data = {}
576 self._step_recorder = StepRecorder(options.buildbot)
577 self._compiler = None
Stephen Kylef11339f2019-03-25 09:00:47578 if orderfile_updater_class is None:
Egor Paskod80bfad2020-09-10 21:53:06579 orderfile_updater_class = OrderfileUpdater
Benoit Lizea3fe2932017-10-20 10:24:52580 assert issubclass(orderfile_updater_class, OrderfileUpdater)
Stephen Kylef11339f2019-03-25 09:00:47581 self._orderfile_updater = orderfile_updater_class(self._clank_dir,
Egor Pasko0c533c6682019-11-26 21:16:32582 self._step_recorder)
Benoit Lizea3fe2932017-10-20 10:24:52583 assert os.path.isdir(constants.DIR_SOURCE_ROOT), 'No src directory found'
Benoit Lizefefbb27c2018-01-17 13:54:18584 symbol_extractor.SetArchitecture(options.arch)
Benoit Lizea3fe2932017-10-20 10:24:52585
Benoit Lizea3fe2932017-10-20 10:24:52586 @staticmethod
587 def _RemoveBlanks(src_file, dest_file):
588 """A utility to remove blank lines from a file.
589
590 Args:
591 src_file: The name of the file to remove the blanks from.
592 dest_file: The name of the file to write the output without blanks.
593 """
594 assert src_file != dest_file, 'Source and destination need to be distinct'
595
596 try:
597 src = open(src_file, 'r')
598 dest = open(dest_file, 'w')
599 for line in src:
600 if line and not line.isspace():
601 dest.write(line)
602 finally:
603 src.close()
604 dest.close()
605
606 def _GenerateAndProcessProfile(self):
Matthew Cary78aae162018-08-10 17:16:30607 """Invokes a script to merge the per-thread traces into one file.
608
609 The produced list of offsets is saved in
610 self._GetUnpatchedOrderfileFilename().
611 """
Benoit Lizea3fe2932017-10-20 10:24:52612 self._step_recorder.BeginStep('Generate Profile Data')
613 files = []
Matthew Cary78aae162018-08-10 17:16:30614 logging.getLogger().setLevel(logging.DEBUG)
Christopher Grantdfe1bac2019-07-05 13:34:10615
616 if self._options.profile_save_dir:
617 # The directory must not preexist, to ensure purity of data. Check
618 # before profiling to save time.
619 if os.path.exists(self._options.profile_save_dir):
620 raise Exception('Profile save directory must not pre-exist')
621 os.makedirs(self._options.profile_save_dir)
622
Matthew Cary78aae162018-08-10 17:16:30623 if self._options.system_health_orderfile:
624 files = self._profiler.CollectSystemHealthProfile(
625 self._compiler.chrome_apk)
Matthew Cary69e9e422018-08-10 18:30:06626 self._MaybeSaveProfile(files)
Matthew Cary78aae162018-08-10 17:16:30627 try:
628 self._ProcessPhasedOrderfile(files)
629 except Exception:
630 for f in files:
631 self._SaveForDebugging(f)
Matthew Cary8b1416232018-08-10 19:12:22632 self._SaveForDebugging(self._compiler.lib_chrome_so)
Matthew Cary78aae162018-08-10 17:16:30633 raise
634 finally:
635 self._profiler.Cleanup()
636 else:
637 self._CollectLegacyProfile()
638 logging.getLogger().setLevel(logging.INFO)
639
640 def _ProcessPhasedOrderfile(self, files):
641 """Process the phased orderfiles produced by system health benchmarks.
642
643 The offsets will be placed in _GetUnpatchedOrderfileFilename().
644
645 Args:
646 file: Profile files pulled locally.
647 """
648 self._step_recorder.BeginStep('Process Phased Orderfile')
649 profiles = process_profiles.ProfileManager(files)
650 processor = process_profiles.SymbolOffsetProcessor(
651 self._compiler.lib_chrome_so)
Monica Basta99c101f2019-05-21 13:50:05652 ordered_symbols = cluster.ClusterOffsets(profiles, processor,
653 call_graph=self._options.use_call_graph)
Matthew Cary8b1416232018-08-10 19:12:22654 if not ordered_symbols:
655 raise Exception('Failed to get ordered symbols')
Matthew Caryda9db932019-03-11 15:28:17656 for sym in ordered_symbols:
657 assert not sym.startswith('OUTLINED_FUNCTION_'), (
658 'Outlined function found in instrumented function, very likely '
659 'something has gone very wrong!')
Matthew Cary91df9792018-11-30 14:35:15660 self._output_data['offsets_kib'] = processor.SymbolsSize(
661 ordered_symbols) / 1024
Matthew Cary78aae162018-08-10 17:16:30662 with open(self._GetUnpatchedOrderfileFilename(), 'w') as orderfile:
Matthew Cary8b1416232018-08-10 19:12:22663 orderfile.write('\n'.join(ordered_symbols))
Matthew Cary78aae162018-08-10 17:16:30664
665 def _CollectLegacyProfile(self):
Matthew Cary2df8d452018-09-19 07:50:20666 files = []
Benoit Lizea3fe2932017-10-20 10:24:52667 try:
Benoit Lizea3fe2932017-10-20 10:24:52668 files = self._profiler.CollectProfile(
669 self._compiler.chrome_apk,
670 constants.PACKAGE_INFO['chrome'])
Matthew Cary69e9e422018-08-10 18:30:06671 self._MaybeSaveProfile(files)
Matthew Caryb8daed942018-06-11 10:58:08672 self._step_recorder.BeginStep('Process profile')
Benoit L96466812018-03-06 15:58:37673 assert os.path.exists(self._compiler.lib_chrome_so)
674 offsets = process_profiles.GetReachedOffsetsFromDumpFiles(
675 files, self._compiler.lib_chrome_so)
676 if not offsets:
677 raise Exception('No profiler offsets found in {}'.format(
678 '\n'.join(files)))
Matthew Cary8b1416232018-08-10 19:12:22679 processor = process_profiles.SymbolOffsetProcessor(
680 self._compiler.lib_chrome_so)
681 ordered_symbols = processor.GetOrderedSymbols(offsets)
682 if not ordered_symbols:
683 raise Exception('No symbol names from offsets found in {}'.format(
684 '\n'.join(files)))
685 with open(self._GetUnpatchedOrderfileFilename(), 'w') as orderfile:
686 orderfile.write('\n'.join(ordered_symbols))
Matthew Cary0f1f681a2018-01-22 10:40:51687 except Exception:
Benoit Lizea3fe2932017-10-20 10:24:52688 for f in files:
689 self._SaveForDebugging(f)
690 raise
691 finally:
692 self._profiler.Cleanup()
Benoit Lizea3fe2932017-10-20 10:24:52693
Matthew Cary69e9e422018-08-10 18:30:06694 def _MaybeSaveProfile(self, files):
695 if self._options.profile_save_dir:
696 logging.info('Saving profiles to %s', self._options.profile_save_dir)
697 for f in files:
698 shutil.copy(f, self._options.profile_save_dir)
699 logging.info('Saved profile %s', f)
700
Benoit Lizea3fe2932017-10-20 10:24:52701 def _PatchOrderfile(self):
702 """Patches the orderfile using clean version of libchrome.so."""
703 self._step_recorder.BeginStep('Patch Orderfile')
Benoit Lizefefbb27c2018-01-17 13:54:18704 patch_orderfile.GeneratePatchedOrderfile(
705 self._GetUnpatchedOrderfileFilename(), self._compiler.lib_chrome_so,
Matthew Caryf949bba2019-02-04 13:39:23706 self._GetPathToOrderfile(), self._order_outlined_functions)
Benoit Lizea3fe2932017-10-20 10:24:52707
708 def _VerifySymbolOrder(self):
709 self._step_recorder.BeginStep('Verify Symbol Order')
710 return_code = self._step_recorder.RunCommand(
711 [self._CHECK_ORDERFILE_SCRIPT, self._compiler.lib_chrome_so,
712 self._GetPathToOrderfile(),
713 '--target-arch=' + self._options.arch],
714 constants.DIR_SOURCE_ROOT,
715 raise_on_error=False)
716 if return_code:
717 self._step_recorder.FailStep('Orderfile check returned %d.' % return_code)
718
719 def _RecordHash(self, file_name):
720 """Records the hash of the file into the output_data dictionary."""
721 self._output_data[os.path.basename(file_name) + '.sha1'] = _GenerateHash(
722 file_name)
723
724 def _SaveFileLocally(self, file_name, file_sha1):
725 """Saves the file to a temporary location and prints the sha1sum."""
726 if not os.path.exists(self._DIRECTORY_FOR_DEBUG_FILES):
727 os.makedirs(self._DIRECTORY_FOR_DEBUG_FILES)
728 shutil.copy(file_name, self._DIRECTORY_FOR_DEBUG_FILES)
Raul Tambre48f176622019-09-23 10:05:24729 print('File: %s, saved in: %s, sha1sum: %s' %
730 (file_name, self._DIRECTORY_FOR_DEBUG_FILES, file_sha1))
Benoit Lizea3fe2932017-10-20 10:24:52731
732 def _SaveForDebugging(self, filename):
733 """Uploads the file to cloud storage or saves to a temporary location."""
734 file_sha1 = _GenerateHash(filename)
735 if not self._options.buildbot:
736 self._SaveFileLocally(filename, file_sha1)
737 else:
Raul Tambre48f176622019-09-23 10:05:24738 print('Uploading file for debugging: ' + filename)
Benoit Lizea3fe2932017-10-20 10:24:52739 self._orderfile_updater.UploadToCloudStorage(
740 filename, use_debug_location=True)
741
742 def _SaveForDebuggingWithOverwrite(self, file_name):
743 """Uploads and overwrites the file in cloud storage or copies locally.
744
745 Should be used for large binaries like lib_chrome_so.
746
747 Args:
748 file_name: (str) File to upload.
749 """
750 file_sha1 = _GenerateHash(file_name)
751 if not self._options.buildbot:
752 self._SaveFileLocally(file_name, file_sha1)
753 else:
Raul Tambre48f176622019-09-23 10:05:24754 print('Uploading file for debugging: %s, sha1sum: %s' % (file_name,
755 file_sha1))
Benoit Lizea3fe2932017-10-20 10:24:52756 upload_location = '%s/%s' % (
757 self._CLOUD_STORAGE_BUCKET_FOR_DEBUG, os.path.basename(file_name))
758 self._step_recorder.RunCommand([
759 'gsutil.py', 'cp', file_name, 'gs://' + upload_location])
Raul Tambre48f176622019-09-23 10:05:24760 print('Uploaded to: https://sandbox.google.com/storage/' +
761 upload_location)
Benoit Lizea3fe2932017-10-20 10:24:52762
763 def _MaybeArchiveOrderfile(self, filename):
764 """In buildbot configuration, uploads the generated orderfile to
765 Google Cloud Storage.
766
767 Args:
768 filename: (str) Orderfile to upload.
769 """
Matthew Cary91df9792018-11-30 14:35:15770 # First compute hashes so that we can download them later if we need to.
Benoit Lizea3fe2932017-10-20 10:24:52771 self._step_recorder.BeginStep('Compute hash for ' + filename)
772 self._RecordHash(filename)
773 if self._options.buildbot:
774 self._step_recorder.BeginStep('Archive ' + filename)
775 self._orderfile_updater.UploadToCloudStorage(
776 filename, use_debug_location=False)
777
Egor Paskobce64d012018-11-20 12:02:37778 def UploadReadyOrderfiles(self):
779 self._step_recorder.BeginStep('Upload Ready Orderfiles')
780 for file_name in [self._GetUnpatchedOrderfileFilename(),
781 self._GetPathToOrderfile()]:
782 self._orderfile_updater.UploadToCloudStorage(
783 file_name, use_debug_location=False)
784
Monica Salama90b8f5b2019-04-25 11:10:38785 def _NativeCodeMemoryBenchmark(self, apk):
786 """Runs system_health.memory_mobile to assess native code memory footprint.
787
788 Args:
789 apk: (str) Path to the apk.
790
791 Returns:
792 results: ([int]) Values of native code memory footprint in bytes from the
793 benchmark results.
794 """
795 self._step_recorder.BeginStep("Running orderfile.memory_mobile")
796 try:
797 out_dir = tempfile.mkdtemp()
798 self._profiler._RunCommand(['tools/perf/run_benchmark',
799 '--device={}'.format(
800 self._profiler._device.serial),
801 '--browser=exact',
Juan Antonio Navarro Perez5b0867f72019-10-21 15:21:54802 '--output-format=csv',
Monica Salama90b8f5b2019-04-25 11:10:38803 '--output-dir={}'.format(out_dir),
804 '--reset-results',
805 '--browser-executable={}'.format(apk),
806 'orderfile.memory_mobile'])
807
Juan Antonio Navarro Perez5b0867f72019-10-21 15:21:54808 out_file_path = os.path.join(out_dir, 'results.csv')
Monica Salama90b8f5b2019-04-25 11:10:38809 if not os.path.exists(out_file_path):
Monica Basta8ec87fd2019-05-13 12:12:35810 raise Exception('Results file not found!')
Monica Salama90b8f5b2019-04-25 11:10:38811
Juan Antonio Navarro Perez5b0867f72019-10-21 15:21:54812 results = {}
Monica Salama90b8f5b2019-04-25 11:10:38813 with open(out_file_path, 'r') as f:
Juan Antonio Navarro Perez5b0867f72019-10-21 15:21:54814 reader = csv.DictReader(f)
815 for row in reader:
816 if not row['name'].endswith('NativeCodeResidentMemory'):
Monica Basta8ec87fd2019-05-13 12:12:35817 continue
Juan Antonio Navarro Perez5b0867f72019-10-21 15:21:54818 # Note: NativeCodeResidentMemory records a single sample from each
819 # story run, so this average (reported as 'avg') is exactly the value
820 # of that one sample. Each story is run multiple times, so this loop
821 # will accumulate into a list all values for all runs of each story.
822 results.setdefault(row['name'], {}).setdefault(
823 row['stories'], []).append(row['avg'])
Monica Basta8ec87fd2019-05-13 12:12:35824
Juan Antonio Navarro Perez5b0867f72019-10-21 15:21:54825 if not results:
826 raise Exception('Could not find relevant results')
827
Monica Basta8ec87fd2019-05-13 12:12:35828 return results
829
830 except Exception as e:
831 return 'Error: ' + str(e)
Monica Salama90b8f5b2019-04-25 11:10:38832
833 finally:
834 shutil.rmtree(out_dir)
835
Monica Salama90b8f5b2019-04-25 11:10:38836
837 def _PerformanceBenchmark(self, apk):
838 """Runs Speedometer2.0 to assess performance.
839
840 Args:
841 apk: (str) Path to the apk.
842
843 Returns:
844 results: ([float]) Speedometer2.0 results samples in milliseconds.
845 """
846 self._step_recorder.BeginStep("Running Speedometer2.0.")
847 try:
848 out_dir = tempfile.mkdtemp()
849 self._profiler._RunCommand(['tools/perf/run_benchmark',
850 '--device={}'.format(
851 self._profiler._device.serial),
852 '--browser=exact',
Monica Basta8ec87fd2019-05-13 12:12:35853 '--output-format=histograms',
Monica Salama90b8f5b2019-04-25 11:10:38854 '--output-dir={}'.format(out_dir),
855 '--reset-results',
856 '--browser-executable={}'.format(apk),
857 'speedometer2'])
858
Monica Basta8ec87fd2019-05-13 12:12:35859 out_file_path = os.path.join(out_dir, 'histograms.json')
Monica Salama90b8f5b2019-04-25 11:10:38860 if not os.path.exists(out_file_path):
Monica Basta8ec87fd2019-05-13 12:12:35861 raise Exception('Results file not found!')
Monica Salama90b8f5b2019-04-25 11:10:38862
863 with open(out_file_path, 'r') as f:
864 results = json.load(f)
865
866 if not results:
Monica Basta8ec87fd2019-05-13 12:12:35867 raise Exception('Results file is empty.')
868
869 for el in results:
870 if 'name' in el and el['name'] == 'Total' and 'sampleValues' in el:
871 return el['sampleValues']
872
873 raise Exception('Unexpected results format.')
874
875 except Exception as e:
876 return 'Error: ' + str(e)
Monica Salama90b8f5b2019-04-25 11:10:38877
878 finally:
879 shutil.rmtree(out_dir)
880
Monica Salama90b8f5b2019-04-25 11:10:38881
882 def RunBenchmark(self, out_directory, no_orderfile=False):
883 """Builds chrome apk and runs performance and memory benchmarks.
884
885 Builds a non-instrumented version of chrome.
886 Installs chrome apk on the device.
887 Runs Speedometer2.0 benchmark to assess performance.
888 Runs system_health.memory_mobile to evaluate memory footprint.
889
890 Args:
891 out_directory: (str) Path to out directory for this build.
892 no_orderfile: (bool) True if chrome to be built without orderfile.
893
894 Returns:
895 benchmark_results: (dict) Results extracted from benchmarks.
896 """
897 try:
898 _UnstashOutputDirectory(out_directory)
Christopher Grant073637472019-07-05 13:34:57899 self._compiler = ClankCompiler(out_directory, self._step_recorder,
900 self._options.arch, self._options.use_goma,
901 self._options.goma_dir,
902 self._options.system_health_orderfile,
903 self._monochrome, self._options.public,
904 self._GetPathToOrderfile())
Monica Salama90b8f5b2019-04-25 11:10:38905
906 if no_orderfile:
907 orderfile_path = self._GetPathToOrderfile()
908 backup_orderfile = orderfile_path + '.backup'
909 shutil.move(orderfile_path, backup_orderfile)
910 open(orderfile_path, 'w').close()
911
912 # Build APK to be installed on the device.
Monica Basta99c101f2019-05-21 13:50:05913 self._compiler.CompileChromeApk(instrumented=False,
914 use_call_graph=False,
915 force_relink=True)
Monica Salama90b8f5b2019-04-25 11:10:38916 benchmark_results = dict()
917 benchmark_results['Speedometer2.0'] = self._PerformanceBenchmark(
918 self._compiler.chrome_apk)
919 benchmark_results['orderfile.memory_mobile'] = (
920 self._NativeCodeMemoryBenchmark(self._compiler.chrome_apk))
Monica Basta8ec87fd2019-05-13 12:12:35921
922 except Exception as e:
923 benchmark_results['Error'] = str(e)
924
Monica Salama90b8f5b2019-04-25 11:10:38925 finally:
926 if no_orderfile and os.path.exists(backup_orderfile):
927 shutil.move(backup_orderfile, orderfile_path)
928 _StashOutputDirectory(out_directory)
929
930 return benchmark_results
931
Benoit Lizea3fe2932017-10-20 10:24:52932 def Generate(self):
933 """Generates and maybe upload an order."""
Matthew Carye8400642018-06-14 15:43:02934 assert (bool(self._options.profile) ^
935 bool(self._options.manual_symbol_offsets))
Matthew Cary78aae162018-08-10 17:16:30936 if self._options.system_health_orderfile and not self._options.profile:
937 raise AssertionError('--system_health_orderfile must be not be used '
938 'with --skip-profile')
939 if (self._options.manual_symbol_offsets and
940 not self._options.system_health_orderfile):
941 raise AssertionError('--manual-symbol-offsets must be used with '
942 '--system_health_orderfile.')
Matthew Carye8400642018-06-14 15:43:02943
Benoit Lizea3fe2932017-10-20 10:24:52944 if self._options.profile:
945 try:
946 _UnstashOutputDirectory(self._instrumented_out_dir)
947 self._compiler = ClankCompiler(
Christopher Grant073637472019-07-05 13:34:57948 self._instrumented_out_dir, self._step_recorder, self._options.arch,
949 self._options.use_goma, self._options.goma_dir,
950 self._options.system_health_orderfile, self._monochrome,
951 self._options.public, self._GetPathToOrderfile())
Matthew Carya2bea452018-11-13 10:21:07952 if not self._options.pregenerated_profiles:
953 # If there are pregenerated profiles, the instrumented build should
954 # not be changed to avoid invalidating the pregenerated profile
955 # offsets.
Monica Basta99c101f2019-05-21 13:50:05956 self._compiler.CompileChromeApk(instrumented=True,
957 use_call_graph=
958 self._options.use_call_graph)
Benoit Lizea3fe2932017-10-20 10:24:52959 self._GenerateAndProcessProfile()
960 self._MaybeArchiveOrderfile(self._GetUnpatchedOrderfileFilename())
Benoit Lizea3fe2932017-10-20 10:24:52961 finally:
Benoit Lizea3fe2932017-10-20 10:24:52962 _StashOutputDirectory(self._instrumented_out_dir)
Matthew Carye8400642018-06-14 15:43:02963 elif self._options.manual_symbol_offsets:
964 assert self._options.manual_libname
965 assert self._options.manual_objdir
Ari Chivukulaa52f8ba2021-08-10 22:30:39966 with open(self._options.manual_symbol_offsets) as f:
967 symbol_offsets = [int(x) for x in f]
Matthew Carye8400642018-06-14 15:43:02968 processor = process_profiles.SymbolOffsetProcessor(
Matthew Caryb46ad282018-11-23 14:43:57969 self._compiler.manual_libname)
Matthew Carye8400642018-06-14 15:43:02970 generator = cyglog_to_orderfile.OffsetOrderfileGenerator(
971 processor, cyglog_to_orderfile.ObjectFileProcessor(
972 self._options.manual_objdir))
973 ordered_sections = generator.GetOrderedSections(symbol_offsets)
974 if not ordered_sections: # Either None or empty is a problem.
975 raise Exception('Failed to get ordered sections')
976 with open(self._GetUnpatchedOrderfileFilename(), 'w') as orderfile:
977 orderfile.write('\n'.join(ordered_sections))
978
Benoit Lizea3fe2932017-10-20 10:24:52979 if self._options.patch:
980 if self._options.profile:
981 self._RemoveBlanks(self._GetUnpatchedOrderfileFilename(),
982 self._GetPathToOrderfile())
983 try:
984 _UnstashOutputDirectory(self._uninstrumented_out_dir)
985 self._compiler = ClankCompiler(
986 self._uninstrumented_out_dir, self._step_recorder,
Christopher Grant073637472019-07-05 13:34:57987 self._options.arch, self._options.use_goma, self._options.goma_dir,
Stephen Kylef11339f2019-03-25 09:00:47988 self._options.system_health_orderfile, self._monochrome,
989 self._options.public, self._GetPathToOrderfile())
990
Monica Basta99c101f2019-05-21 13:50:05991 self._compiler.CompileLibchrome(instrumented=False,
992 use_call_graph=False)
Benoit Lizea3fe2932017-10-20 10:24:52993 self._PatchOrderfile()
994 # Because identical code folding is a bit different with and without
995 # the orderfile build, we need to re-patch the orderfile with code
996 # folding as close to the final version as possible.
Monica Basta99c101f2019-05-21 13:50:05997 self._compiler.CompileLibchrome(instrumented=False,
998 use_call_graph=False, force_relink=True)
Benoit Lizea3fe2932017-10-20 10:24:52999 self._PatchOrderfile()
Monica Basta99c101f2019-05-21 13:50:051000 self._compiler.CompileLibchrome(instrumented=False,
1001 use_call_graph=False, force_relink=True)
Benoit Lizea3fe2932017-10-20 10:24:521002 self._VerifySymbolOrder()
1003 self._MaybeArchiveOrderfile(self._GetPathToOrderfile())
1004 finally:
1005 _StashOutputDirectory(self._uninstrumented_out_dir)
Benoit Lizea3fe2932017-10-20 10:24:521006
Monica Salama90b8f5b2019-04-25 11:10:381007 if self._options.benchmark:
1008 self._output_data['orderfile_benchmark_results'] = self.RunBenchmark(
1009 self._uninstrumented_out_dir)
1010 self._output_data['no_orderfile_benchmark_results'] = self.RunBenchmark(
1011 self._no_orderfile_out_dir, no_orderfile=True)
1012
Egor Paskod80bfad2020-09-10 21:53:061013 if self._options.buildbot:
1014 self._orderfile_updater._GitStash()
Benoit Lizea3fe2932017-10-20 10:24:521015 self._step_recorder.EndStep()
1016 return not self._step_recorder.ErrorRecorded()
1017
1018 def GetReportingData(self):
1019 """Get a dictionary of reporting data (timings, output hashes)"""
1020 self._output_data['timings'] = self._step_recorder.timings
1021 return self._output_data
1022
Matthew Cary86a226e2019-03-19 12:17:441023 def CommitStashedOrderfileHashes(self):
1024 """Commit any orderfile hash files in the current checkout.
1025
1026 Only possible if running on the buildbot.
1027
1028 Returns: true on success.
1029 """
Egor Pasko7ff04122019-11-25 15:47:181030 if not self._options.buildbot:
Matthew Cary86a226e2019-03-19 12:17:441031 logging.error('Trying to commit when not running on the buildbot')
1032 return False
1033 self._orderfile_updater._CommitStashedFiles([
1034 filename + '.sha1'
1035 for filename in (self._GetUnpatchedOrderfileFilename(),
1036 self._GetPathToOrderfile())])
1037 return True
1038
Benoit Lizea3fe2932017-10-20 10:24:521039
Benoit Lizea1b64f82017-12-07 10:12:501040def CreateArgumentParser():
1041 """Creates and returns the argument parser."""
1042 parser = argparse.ArgumentParser()
Monica Salama90b8f5b2019-04-25 11:10:381043 parser.add_argument('--no-benchmark', action='store_false', dest='benchmark',
1044 default=True, help='Disables running benchmarks.')
Benoit Lizea1b64f82017-12-07 10:12:501045 parser.add_argument(
Benoit Lizea3fe2932017-10-20 10:24:521046 '--buildbot', action='store_true',
1047 help='If true, the script expects to be run on a buildbot')
Benoit Lizea1b64f82017-12-07 10:12:501048 parser.add_argument(
Matthew Cary453ff1452018-07-18 12:19:351049 '--device', default=None, type=str,
1050 help='Device serial number on which to run profiling.')
1051 parser.add_argument(
Benoit Lizea3fe2932017-10-20 10:24:521052 '--verify', action='store_true',
1053 help='If true, the script only verifies the current orderfile')
Benoit Lizea1b64f82017-12-07 10:12:501054 parser.add_argument('--target-arch', action='store', dest='arch',
Stephen Martinis71b391b52018-12-04 15:08:041055 default='arm',
Matthew Cary53f74ba2019-01-24 10:07:181056 choices=['arm', 'arm64'],
1057 help='The target architecture for which to build.')
Benoit Lizea1b64f82017-12-07 10:12:501058 parser.add_argument('--output-json', action='store', dest='json_file',
1059 help='Location to save stats in json format')
1060 parser.add_argument(
Benoit Lizea3fe2932017-10-20 10:24:521061 '--skip-profile', action='store_false', dest='profile', default=True,
1062 help='Don\'t generate a profile on the device. Only patch from the '
1063 'existing profile.')
Benoit Lizea1b64f82017-12-07 10:12:501064 parser.add_argument(
Benoit Lizea3fe2932017-10-20 10:24:521065 '--skip-patch', action='store_false', dest='patch', default=True,
1066 help='Only generate the raw (unpatched) orderfile, don\'t patch it.')
Benoit Lizea1b64f82017-12-07 10:12:501067 parser.add_argument('--goma-dir', help='GOMA directory.')
1068 parser.add_argument(
Benoit Lizea3fe2932017-10-20 10:24:521069 '--use-goma', action='store_true', help='Enable GOMA.', default=False)
Benoit Lizea1b64f82017-12-07 10:12:501070 parser.add_argument('--adb-path', help='Path to the adb binary.')
Matthew Carye8400642018-06-14 15:43:021071
Egor Paskod80bfad2020-09-10 21:53:061072 parser.add_argument('--public',
1073 action='store_true',
1074 help='Build non-internal APK and change the orderfile '
1075 'location. Required if your checkout is non-internal.',
Stephen Kylef11339f2019-03-25 09:00:471076 default=False)
Matthew Cary04f41032018-12-10 15:55:271077 parser.add_argument('--nosystem-health-orderfile', action='store_false',
Benoit Lcba421e2019-04-26 15:28:261078 dest='system_health_orderfile', default=True,
Matthew Caryc262f5d2018-09-19 14:36:281079 help=('Create an orderfile based on an about:blank '
1080 'startup benchmark instead of system health '
1081 'benchmarks.'))
Monica Salamaeea2d942019-03-11 12:36:181082 parser.add_argument(
1083 '--use-legacy-chrome-apk', action='store_true', default=False,
1084 help=('Compile and instrument chrome for [L, K] devices.'))
Matthew Carye8400642018-06-14 15:43:021085 parser.add_argument('--manual-symbol-offsets', default=None, type=str,
1086 help=('File of list of ordered symbol offsets generated '
1087 'by manual profiling. Must set other --manual* '
1088 'flags if this is used, and must --skip-profile.'))
1089 parser.add_argument('--manual-libname', default=None, type=str,
1090 help=('Library filename corresponding to '
1091 '--manual-symbol-offsets.'))
1092 parser.add_argument('--manual-objdir', default=None, type=str,
1093 help=('Root of object file directory corresponding to '
1094 '--manual-symbol-offsets.'))
Matthew Caryf949bba2019-02-04 13:39:231095 parser.add_argument('--noorder-outlined-functions', action='store_true',
1096 help='Disable outlined functions in the orderfile.')
Matthew Cary69e9e422018-08-10 18:30:061097 parser.add_argument('--pregenerated-profiles', default=None, type=str,
1098 help=('Pregenerated profiles to use instead of running '
1099 'profile step. Cannot be used with '
1100 '--skip-profiles.'))
1101 parser.add_argument('--profile-save-dir', default=None, type=str,
1102 help=('Directory to save any profiles created. These can '
1103 'be used with --pregenerated-profiles. Cannot be '
1104 'used with --skip-profiles.'))
Egor Paskobce64d012018-11-20 12:02:371105 parser.add_argument('--upload-ready-orderfiles', action='store_true',
1106 help=('Skip orderfile generation and manually upload '
1107 'orderfiles (both patched and unpatched) from '
1108 'their normal location in the tree to the cloud '
1109 'storage. DANGEROUS! USE WITH CARE!'))
Matthew Cary1ea82212019-03-20 12:10:271110 parser.add_argument('--streamline-for-debugging', action='store_true',
1111 help=('Streamline where possible the run for faster '
1112 'iteration while debugging. The orderfile '
1113 'generated will be valid and nontrivial, but '
1114 'may not be based on a representative profile '
1115 'or other such considerations. Use with caution.'))
Matthew Cary86a226e2019-03-19 12:17:441116 parser.add_argument('--commit-hashes', action='store_true',
1117 help=('Commit any orderfile hash files in the current '
1118 'checkout; performs no other action'))
Monica Basta99c101f2019-05-21 13:50:051119 parser.add_argument('--use-call-graph', action='store_true', default=False,
1120 help='Use call graph instrumentation.')
Benoit Lizea1b64f82017-12-07 10:12:501121 profile_android_startup.AddProfileCollectionArguments(parser)
Benoit Lizea3fe2932017-10-20 10:24:521122 return parser
1123
1124
Stephen Kylef11339f2019-03-25 09:00:471125def CreateOrderfile(options, orderfile_updater_class=None):
Christopher Grantdfe1bac2019-07-05 13:34:101126 """Creates an orderfile.
Benoit Lizea3fe2932017-10-20 10:24:521127
1128 Args:
1129 options: As returned from optparse.OptionParser.parse_args()
1130 orderfile_updater_class: (OrderfileUpdater) subclass of OrderfileUpdater.
1131
1132 Returns:
1133 True iff success.
1134 """
1135 logging.basicConfig(level=logging.INFO)
1136 devil_chromium.Initialize(adb_path=options.adb_path)
1137
Egor Pasko93e514e2017-10-31 13:32:361138 generator = OrderfileGenerator(options, orderfile_updater_class)
Benoit Lizea3fe2932017-10-20 10:24:521139 try:
1140 if options.verify:
Egor Pasko93e514e2017-10-31 13:32:361141 generator._VerifySymbolOrder()
Matthew Cary86a226e2019-03-19 12:17:441142 elif options.commit_hashes:
Matthew Cary86a226e2019-03-19 12:17:441143 return generator.CommitStashedOrderfileHashes()
Egor Paskobce64d012018-11-20 12:02:371144 elif options.upload_ready_orderfiles:
1145 return generator.UploadReadyOrderfiles()
Benoit Lizea3fe2932017-10-20 10:24:521146 else:
Egor Pasko93e514e2017-10-31 13:32:361147 return generator.Generate()
Benoit Lizea3fe2932017-10-20 10:24:521148 finally:
Egor Pasko93e514e2017-10-31 13:32:361149 json_output = json.dumps(generator.GetReportingData(),
Benoit Lizea3fe2932017-10-20 10:24:521150 indent=2) + '\n'
1151 if options.json_file:
1152 with open(options.json_file, 'w') as f:
1153 f.write(json_output)
Raul Tambre48f176622019-09-23 10:05:241154 print(json_output)
Benoit Lizea3fe2932017-10-20 10:24:521155 return False
1156
1157
Benoit Lizea1b64f82017-12-07 10:12:501158def main():
1159 parser = CreateArgumentParser()
1160 options = parser.parse_args()
Stephen Kylef11339f2019-03-25 09:00:471161 return 0 if CreateOrderfile(options) else 1
Benoit Lizea3fe2932017-10-20 10:24:521162
1163
1164if __name__ == '__main__':
Benoit Lizea1b64f82017-12-07 10:12:501165 sys.exit(main())