blob: bed28d8765dc258bbf15b2f3271d185d8ea62541 [file] [log] [blame]
Mads Ager418d1ca2017-05-22 09:35:49 +02001# Copyright (c) 2016, the R8 project authors. Please see the AUTHORS file
2# for details. All rights reserved. Use of this source code is governed by a
3# BSD-style license that can be found in the LICENSE file.
4
5# Different utility functions used accross scripts
6
7import hashlib
Søren Gjesse6e5e5842019-09-03 08:48:30 +02008import json
Mads Ager418d1ca2017-05-22 09:35:49 +02009import os
Tamas Kenez82efeb52017-06-12 13:56:22 +020010import re
Mads Ager418d1ca2017-05-22 09:35:49 +020011import shutil
12import subprocess
13import sys
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +020014import tarfile
Mads Ager418d1ca2017-05-22 09:35:49 +020015import tempfile
Morten Krogh-Jespersen16e925d2019-01-25 14:40:38 +010016import zipfile
Mads Ager418d1ca2017-05-22 09:35:49 +020017
Ian Zerny37097652019-04-11 13:13:27 +020018import defines
19import jdk
20
Christoffer Quist Adamsen17879c12019-01-22 16:13:54 +010021ANDROID_JAR_DIR = 'third_party/android_jar/lib-v{api}'
22ANDROID_JAR = os.path.join(ANDROID_JAR_DIR, 'android.jar')
Ian Zerny3f54e222019-02-12 10:51:17 +010023TOOLS_DIR = defines.TOOLS_DIR
24REPO_ROOT = defines.REPO_ROOT
25THIRD_PARTY = defines.THIRD_PARTY
Morten Krogh-Jespersen220e5702019-02-27 12:57:01 +010026ANDROID_SDK = os.path.join(THIRD_PARTY, 'android_sdk')
Tamas Kenezfc34cd82017-07-13 12:43:57 +020027MEMORY_USE_TMP_FILE = 'memory_use.tmp'
Tamas Kenez02bff032017-07-18 12:13:58 +020028DEX_SEGMENTS_RESULT_PATTERN = re.compile('- ([^:]+): ([0-9]+)')
Mads Ager12a56bc2017-11-27 11:51:25 +010029BUILD = os.path.join(REPO_ROOT, 'build')
Ian Zerny0f5fc732018-11-15 14:34:41 +010030BUILD_DEPS_DIR = os.path.join(BUILD, 'deps')
31BUILD_MAIN_DIR = os.path.join(BUILD, 'classes', 'main')
Morten Krogh-Jespersen51db2b02020-11-11 12:49:26 +010032BUILD_JAVA_MAIN_DIR = os.path.join(BUILD, 'classes', 'java', 'main')
Ian Zerny0f5fc732018-11-15 14:34:41 +010033BUILD_TEST_DIR = os.path.join(BUILD, 'classes', 'test')
Mads Ager12a56bc2017-11-27 11:51:25 +010034LIBS = os.path.join(BUILD, 'libs')
35GENERATED_LICENSE_DIR = os.path.join(BUILD, 'generatedLicense')
Mads Agera4911eb2017-11-22 13:19:36 +010036SRC_ROOT = os.path.join(REPO_ROOT, 'src', 'main', 'java')
Søren Gjesse6e5e5842019-09-03 08:48:30 +020037TEST_ROOT = os.path.join(REPO_ROOT, 'src', 'test', 'java')
Ian Zerny59dfa4c2019-10-25 10:34:36 +020038REPO_SOURCE = 'https://r8.googlesource.com/r8'
Søren Gjessedc9d8a22017-10-12 12:40:59 +020039
40D8 = 'd8'
41R8 = 'r8'
Tamas Kenez03ab76f2018-12-07 14:33:25 +010042R8LIB = 'r8lib'
Morten Krogh-Jespersene28db462019-01-09 13:32:15 +010043R8LIB_NO_DEPS = 'r8LibNoDeps'
Mads Agerb10c07f2017-11-27 13:25:52 +010044R8_SRC = 'sourceJar'
Søren Gjesse17fc67d2019-12-04 14:50:17 +010045LIBRARY_DESUGAR_CONVERSIONS = 'buildLibraryDesugarConversions'
Søren Gjessedc9d8a22017-10-12 12:40:59 +020046
Morten Krogh-Jespersen51db2b02020-11-11 12:49:26 +010047ALL_DEPS_JAR = os.path.join(LIBS, 'deps_all.jar')
Rico Wind74fab302017-10-02 07:25:33 +020048D8_JAR = os.path.join(LIBS, 'd8.jar')
49R8_JAR = os.path.join(LIBS, 'r8.jar')
Tamas Kenez03ab76f2018-12-07 14:33:25 +010050R8LIB_JAR = os.path.join(LIBS, 'r8lib.jar')
Ian Zerny5ffa58f2020-02-26 08:37:14 +010051R8LIB_MAP = os.path.join(LIBS, 'r8lib.jar.map')
Mads Agerb10c07f2017-11-27 13:25:52 +010052R8_SRC_JAR = os.path.join(LIBS, 'r8-src.jar')
Tamas Kenez03ab76f2018-12-07 14:33:25 +010053R8LIB_EXCLUDE_DEPS_JAR = os.path.join(LIBS, 'r8lib-exclude-deps.jar')
Tamas Kenez180be092018-12-05 15:23:06 +010054R8_FULL_EXCLUDE_DEPS_JAR = os.path.join(LIBS, 'r8-full-exclude-deps.jar')
Mads Ager12a56bc2017-11-27 11:51:25 +010055MAVEN_ZIP = os.path.join(LIBS, 'r8.zip')
Rico Wind8fc8bfa2019-03-22 09:57:36 +010056MAVEN_ZIP_LIB = os.path.join(LIBS, 'r8lib.zip')
Søren Gjesse17fc67d2019-12-04 14:50:17 +010057LIBRARY_DESUGAR_CONVERSIONS_ZIP = os.path.join(LIBS, 'library_desugar_conversions.zip')
58
Søren Gjesse6e5e5842019-09-03 08:48:30 +020059DESUGAR_CONFIGURATION = os.path.join(
Søren Gjesse927a92e2019-12-04 15:18:06 +010060 'src', 'library_desugar', 'desugar_jdk_libs.json')
Søren Gjesseee086b22020-10-30 11:46:39 +010061DESUGAR_IMPLEMENTATION = os.path.join(
62 'third_party', 'openjdk', 'desugar_jdk_libs', 'libjava.jar')
Søren Gjesse6e5e5842019-09-03 08:48:30 +020063DESUGAR_CONFIGURATION_MAVEN_ZIP = os.path.join(
64 LIBS, 'desugar_jdk_libs_configuration.zip')
Mads Ager12a56bc2017-11-27 11:51:25 +010065GENERATED_LICENSE = os.path.join(GENERATED_LICENSE_DIR, 'LICENSE')
Mathias Rav3fb4a3a2018-05-29 15:41:36 +020066RT_JAR = os.path.join(REPO_ROOT, 'third_party/openjdk/openjdk-rt-1.8/rt.jar')
Mathias Ravb46dc002018-06-06 09:37:11 +020067R8LIB_KEEP_RULES = os.path.join(REPO_ROOT, 'src/main/keep.txt')
Morten Krogh-Jespersen480784d2019-02-05 08:10:46 +010068CF_SEGMENTS_TOOL = os.path.join(THIRD_PARTY, 'cf_segments')
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +010069PINNED_R8_JAR = os.path.join(REPO_ROOT, 'third_party/r8/r8.jar')
70PINNED_PGR8_JAR = os.path.join(REPO_ROOT, 'third_party/r8/r8-pg6.0.1.jar')
Ian Zernyfbb1f7a2019-05-02 14:34:13 +020071SAMPLE_LIBRARIES_SHA_FILE = os.path.join(
72 THIRD_PARTY, 'sample_libraries.tar.gz.sha1')
Morten Krogh-Jespersen64740202019-02-07 13:06:04 +010073OPENSOURCE_APPS_SHA_FILE = os.path.join(
Rico Windec283b52019-04-03 15:16:55 +020074 THIRD_PARTY, 'opensource_apps.tar.gz.sha1')
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +010075# TODO(b/152155164): Remove this when all apps has been migrated.
Rico Windec283b52019-04-03 15:16:55 +020076OPENSOURCE_APPS_FOLDER = os.path.join(THIRD_PARTY, 'opensource_apps')
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +010077OPENSOURCE_DUMPS_DIR = os.path.join(THIRD_PARTY, 'opensource-apps')
Søren Gjesse1c115b52019-08-14 12:43:57 +020078BAZEL_SHA_FILE = os.path.join(THIRD_PARTY, 'bazel.tar.gz.sha1')
79BAZEL_TOOL = os.path.join(THIRD_PARTY, 'bazel')
Søren Gjesse699f6362019-10-09 14:56:33 +020080JAVA8_SHA_FILE = os.path.join(THIRD_PARTY, 'openjdk', 'jdk8', 'linux-x86.tar.gz.sha1')
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +010081
Morten Krogh-Jespersen220e5702019-02-27 12:57:01 +010082ANDROID_HOME_ENVIROMENT_NAME = "ANDROID_HOME"
83ANDROID_TOOLS_VERSION_ENVIRONMENT_NAME = "ANDROID_TOOLS_VERSION"
Morten Krogh-Jespersenc8efedd2019-01-28 11:36:17 +010084USER_HOME = os.path.expanduser('~')
Morten Krogh-Jespersen220e5702019-02-27 12:57:01 +010085
Morten Krogh-Jespersen0981b722019-10-09 10:00:33 +020086R8_TEST_RESULTS_BUCKET = 'r8-test-results'
87
88def archive_file(name, gs_dir, src_file):
89 gs_file = '%s/%s' % (gs_dir, name)
90 upload_file_to_cloud_storage(src_file, gs_file, public_read=False)
91
92def archive_value(name, gs_dir, value):
93 with TempDir() as temp:
94 tempfile = os.path.join(temp, name);
95 with open(tempfile, 'w') as f:
96 f.write(str(value))
97 archive_file(name, gs_dir, tempfile)
98
Morten Krogh-Jespersen220e5702019-02-27 12:57:01 +010099def getAndroidHome():
100 return os.environ.get(
101 ANDROID_HOME_ENVIROMENT_NAME, os.path.join(USER_HOME, 'Android', 'Sdk'))
102
103def getAndroidBuildTools():
104 version = os.environ.get(ANDROID_TOOLS_VERSION_ENVIRONMENT_NAME, '28.0.3')
105 return os.path.join(getAndroidHome(), 'build-tools', version)
Morten Krogh-Jespersenc8efedd2019-01-28 11:36:17 +0100106
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100107def Print(s, quiet=False):
108 if quiet:
109 return
110 print(s)
111
112def Warn(message):
113 CRED = '\033[91m'
114 CEND = '\033[0m'
115 print(CRED + message + CEND)
116
117def PrintCmd(cmd, env=None, quiet=False):
118 if quiet:
119 return
120 if type(cmd) is list:
121 cmd = ' '.join(cmd)
122 if env:
123 env = ' '.join(['{}=\"{}\"'.format(x, y) for x, y in env.iteritems()])
124 print('Running: {} {}'.format(env, cmd))
125 else:
126 print('Running: {}'.format(cmd))
Mads Ager418d1ca2017-05-22 09:35:49 +0200127 # I know this will hit os on windows eventually if we don't do this.
128 sys.stdout.flush()
129
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100130class ProgressLogger(object):
131 CLEAR_LINE = '\033[K'
132 UP = '\033[F'
133
134 def __init__(self, quiet=False):
135 self._count = 0
136 self._has_printed = False
137 self._quiet = quiet
138
139 def log(self, text):
140 if self._quiet:
141 if self._has_printed:
142 sys.stdout.write(ProgressLogger.UP + ProgressLogger.CLEAR_LINE)
143 if len(text) > 140:
144 text = text[0:140] + '...'
145 print(text)
146 self._has_printed = True
147
148 def done(self):
149 if self._quiet and self._has_printed:
150 sys.stdout.write(ProgressLogger.UP + ProgressLogger.CLEAR_LINE)
151 print('')
152 sys.stdout.write(ProgressLogger.UP)
153
Morten Krogh-Jespersen7cdd3a72019-03-13 14:58:25 +0100154def RunCmd(cmd, env_vars=None, quiet=False, fail=True, logging=True):
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100155 PrintCmd(cmd, env=env_vars, quiet=quiet)
156 env = os.environ.copy()
157 if env_vars:
158 env.update(env_vars)
159 process = subprocess.Popen(
160 cmd, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
161 stdout = []
Morten Krogh-Jespersen7cdd3a72019-03-13 14:58:25 +0100162 logger = ProgressLogger(quiet=quiet) if logging else None
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100163 failed = False
164 while True:
165 line = process.stdout.readline()
166 if line != b'':
167 stripped = line.rstrip()
168 stdout.append(stripped)
Morten Krogh-Jespersen7cdd3a72019-03-13 14:58:25 +0100169 if logger:
170 logger.log(stripped)
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100171
172 # TODO(christofferqa): r8 should fail with non-zero exit code.
Morten Krogh-Jespersen121c47b2019-01-25 09:57:21 +0100173 if ('AssertionError:' in stripped
174 or 'CompilationError:' in stripped
175 or 'CompilationFailedException:' in stripped
Morten Krogh-Jespersen5d02a6b2019-10-29 14:48:56 +0100176 or 'Compilation failed' in stripped
177 or 'FAILURE:' in stripped
178 or 'org.gradle.api.ProjectConfigurationException' in stripped
179 or 'BUILD FAILED' in stripped):
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100180 failed = True
181 else:
Morten Krogh-Jespersen7cdd3a72019-03-13 14:58:25 +0100182 if logger:
183 logger.done()
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100184 exit_code = process.poll()
185 if exit_code or failed:
186 for line in stdout:
187 Warn(line)
Christoffer Quist Adamsen7cf4c562019-03-07 10:57:33 +0100188 if fail:
189 raise subprocess.CalledProcessError(
190 exit_code or -1, cmd, output='\n'.join(stdout))
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100191 return stdout
192
Christoffer Quist Adamsen7cf4c562019-03-07 10:57:33 +0100193def RunGradlew(
194 args, clean=True, stacktrace=True, use_daemon=False, env_vars=None,
Morten Krogh-Jespersen7cdd3a72019-03-13 14:58:25 +0100195 quiet=False, fail=True, logging=True):
Christoffer Quist Adamsen7cf4c562019-03-07 10:57:33 +0100196 cmd = ['./gradlew']
197 if clean:
198 assert 'clean' not in args
199 cmd.append('clean')
200 if stacktrace:
201 assert '--stacktrace' not in args
202 cmd.append('--stacktrace')
203 if not use_daemon:
204 assert '--no-daemon' not in args
205 cmd.append('--no-daemon')
206 cmd.extend(args)
Morten Krogh-Jespersen7cdd3a72019-03-13 14:58:25 +0100207 return RunCmd(cmd, env_vars=env_vars, quiet=quiet, fail=fail, logging=logging)
Christoffer Quist Adamsen7cf4c562019-03-07 10:57:33 +0100208
Rico Windf80f5a22017-06-16 09:15:57 +0200209def IsWindows():
Ian Zerny3f54e222019-02-12 10:51:17 +0100210 return defines.IsWindows()
Ian Zerny5fffb0a2019-02-11 13:54:22 +0100211
212def IsLinux():
Ian Zerny3f54e222019-02-12 10:51:17 +0100213 return defines.IsLinux()
Ian Zerny5fffb0a2019-02-11 13:54:22 +0100214
215def IsOsX():
Ian Zerny3f54e222019-02-12 10:51:17 +0100216 return defines.IsOsX()
Ian Zerny5fffb0a2019-02-11 13:54:22 +0100217
218def EnsureDepFromGoogleCloudStorage(dep, tgz, sha1, msg):
219 if not os.path.exists(dep) or os.path.getmtime(tgz) < os.path.getmtime(sha1):
220 DownloadFromGoogleCloudStorage(sha1)
221 # Update the mtime of the tar file to make sure we do not run again unless
222 # there is an update.
223 os.utime(tgz, None)
224 else:
225 print 'Ensure cloud dependency:', msg, 'present'
Rico Windf80f5a22017-06-16 09:15:57 +0200226
Jean-Marie Henaffe4e36d12018-04-05 10:33:50 +0200227def DownloadFromX20(sha1_file):
228 download_script = os.path.join(REPO_ROOT, 'tools', 'download_from_x20.py')
229 cmd = [download_script, sha1_file]
230 PrintCmd(cmd)
231 subprocess.check_call(cmd)
232
Rico Wind533e3ce2019-04-04 10:26:12 +0200233def DownloadFromGoogleCloudStorage(sha1_file, bucket='r8-deps', auth=False):
Rico Windf80f5a22017-06-16 09:15:57 +0200234 suffix = '.bat' if IsWindows() else ''
235 download_script = 'download_from_google_storage%s' % suffix
Rico Wind533e3ce2019-04-04 10:26:12 +0200236 cmd = [download_script]
237 if not auth:
238 cmd.append('-n')
239 cmd.extend(['-b', bucket, '-u', '-s', sha1_file])
Mads Ager418d1ca2017-05-22 09:35:49 +0200240 PrintCmd(cmd)
241 subprocess.check_call(cmd)
242
243def get_sha1(filename):
244 sha1 = hashlib.sha1()
245 with open(filename, 'rb') as f:
246 while True:
247 chunk = f.read(1024*1024)
248 if not chunk:
249 break
250 sha1.update(chunk)
251 return sha1.hexdigest()
252
Rico Wind1b09c562019-01-17 08:53:09 +0100253def is_master():
254 remotes = subprocess.check_output(['git', 'branch', '-r', '--contains',
255 'HEAD'])
256 return 'origin/master' in remotes
257
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +0200258def get_HEAD_sha1():
Morten Krogh-Jespersene0ce6a32019-02-07 11:44:45 +0100259 return get_HEAD_sha1_for_checkout(REPO_ROOT)
260
261def get_HEAD_sha1_for_checkout(checkout):
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +0200262 cmd = ['git', 'rev-parse', 'HEAD']
263 PrintCmd(cmd)
Morten Krogh-Jespersene0ce6a32019-02-07 11:44:45 +0100264 with ChangedWorkingDirectory(checkout):
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +0200265 return subprocess.check_output(cmd).strip()
266
Tamas Kenez971eec62017-05-24 11:08:40 +0200267def makedirs_if_needed(path):
268 try:
269 os.makedirs(path)
270 except OSError:
271 if not os.path.isdir(path):
272 raise
273
Rico Wind800fd712018-09-24 11:29:33 +0200274def upload_dir_to_cloud_storage(directory, destination, is_html=False, public_read=True):
Rico Winda94f01c2017-06-27 10:32:34 +0200275 # Upload and make the content encoding right for viewing directly
Rico Windd55ce272019-03-26 08:02:09 +0100276 cmd = ['gsutil.py', '-m', 'cp']
Rico Windd0d88cf2018-02-09 09:46:11 +0100277 if is_html:
278 cmd += ['-z', 'html']
Rico Wind800fd712018-09-24 11:29:33 +0200279 if public_read:
280 cmd += ['-a', 'public-read']
281 cmd += ['-R', directory, destination]
Rico Winda94f01c2017-06-27 10:32:34 +0200282 PrintCmd(cmd)
283 subprocess.check_call(cmd)
284
Rico Wind800fd712018-09-24 11:29:33 +0200285def upload_file_to_cloud_storage(source, destination, public_read=True):
286 cmd = ['gsutil.py', 'cp']
287 if public_read:
288 cmd += ['-a', 'public-read']
289 cmd += [source, destination]
Rico Windb4621c12017-08-28 12:48:53 +0200290 PrintCmd(cmd)
291 subprocess.check_call(cmd)
292
Rico Wind139eece2018-09-25 09:42:09 +0200293def delete_file_from_cloud_storage(destination):
294 cmd = ['gsutil.py', 'rm', destination]
295 PrintCmd(cmd)
296 subprocess.check_call(cmd)
297
Rico Wind4fd2dda2018-09-26 17:41:45 +0200298def ls_files_on_cloud_storage(destination):
299 cmd = ['gsutil.py', 'ls', destination]
300 PrintCmd(cmd)
301 return subprocess.check_output(cmd)
302
Rico Wind139eece2018-09-25 09:42:09 +0200303def cat_file_on_cloud_storage(destination, ignore_errors=False):
304 cmd = ['gsutil.py', 'cat', destination]
305 PrintCmd(cmd)
306 try:
307 return subprocess.check_output(cmd)
308 except subprocess.CalledProcessError as e:
309 if ignore_errors:
310 return ''
311 else:
312 raise e
313
314def file_exists_on_cloud_storage(destination):
315 cmd = ['gsutil.py', 'ls', destination]
316 PrintCmd(cmd)
317 return subprocess.call(cmd) == 0
318
Christoffer Quist Adamsen870fa462020-12-15 10:50:54 +0100319def download_file_from_cloud_storage(source, destination, quiet=False):
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +0200320 cmd = ['gsutil.py', 'cp', source, destination]
Christoffer Quist Adamsen870fa462020-12-15 10:50:54 +0100321 PrintCmd(cmd, quiet=quiet)
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +0200322 subprocess.check_call(cmd)
323
Morten Krogh-Jespersen220e5702019-02-27 12:57:01 +0100324def create_archive(name, sources=None):
325 if not sources:
326 sources = [name]
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +0200327 tarname = '%s.tar.gz' % name
328 with tarfile.open(tarname, 'w:gz') as tar:
Morten Krogh-Jespersen54090862019-02-19 11:31:10 +0100329 for source in sources:
330 tar.add(source)
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +0200331 return tarname
332
333def extract_dir(filename):
334 return filename[0:len(filename) - len('.tar.gz')]
335
336def unpack_archive(filename):
337 dest_dir = extract_dir(filename)
338 if os.path.exists(dest_dir):
339 print 'Deleting existing dir %s' % dest_dir
340 shutil.rmtree(dest_dir)
341 dirname = os.path.dirname(os.path.abspath(filename))
342 with tarfile.open(filename, 'r:gz') as tar:
343 tar.extractall(path=dirname)
344
Morten Krogh-Jespersenec3047b2020-08-18 13:09:06 +0200345def check_gcert():
346 subprocess.check_call(['gcert'])
Morten Krogh-Jespersen54090862019-02-19 11:31:10 +0100347
Rico Wind1a29c4f2018-01-25 08:43:08 +0100348# Note that gcs is eventually consistent with regards to list operations.
349# This is not a problem in our case, but don't ever use this method
350# for synchronization.
351def cloud_storage_exists(destination):
352 cmd = ['gsutil.py', 'ls', destination]
353 PrintCmd(cmd)
354 exit_code = subprocess.call(cmd)
355 return exit_code == 0
356
Mads Ager418d1ca2017-05-22 09:35:49 +0200357class TempDir(object):
Søren Gjessecbeae782019-05-21 14:14:25 +0200358 def __init__(self, prefix='', delete=True):
Mads Ager418d1ca2017-05-22 09:35:49 +0200359 self._temp_dir = None
360 self._prefix = prefix
Søren Gjessecbeae782019-05-21 14:14:25 +0200361 self._delete = delete
Mads Ager418d1ca2017-05-22 09:35:49 +0200362
363 def __enter__(self):
364 self._temp_dir = tempfile.mkdtemp(self._prefix)
365 return self._temp_dir
366
367 def __exit__(self, *_):
Søren Gjessecbeae782019-05-21 14:14:25 +0200368 if self._delete:
369 shutil.rmtree(self._temp_dir, ignore_errors=True)
Mads Ager418d1ca2017-05-22 09:35:49 +0200370
371class ChangedWorkingDirectory(object):
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100372 def __init__(self, working_directory, quiet=False):
373 self._quiet = quiet
Mads Ager418d1ca2017-05-22 09:35:49 +0200374 self._working_directory = working_directory
375
376 def __enter__(self):
377 self._old_cwd = os.getcwd()
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100378 if not self._quiet:
379 print 'Enter directory:', self._working_directory
Mads Ager418d1ca2017-05-22 09:35:49 +0200380 os.chdir(self._working_directory)
381
382 def __exit__(self, *_):
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100383 if not self._quiet:
384 print 'Enter directory:', self._old_cwd
Mads Ager418d1ca2017-05-22 09:35:49 +0200385 os.chdir(self._old_cwd)
Tamas Kenez82efeb52017-06-12 13:56:22 +0200386
387# Reading Android CTS test_result.xml
388
389class CtsModule(object):
390 def __init__(self, module_name):
391 self.name = module_name
392
393class CtsTestCase(object):
394 def __init__(self, test_case_name):
395 self.name = test_case_name
396
397class CtsTest(object):
398 def __init__(self, test_name, outcome):
399 self.name = test_name
400 self.outcome = outcome
401
402# Generator yielding CtsModule, CtsTestCase or CtsTest from
403# reading through a CTS test_result.xml file.
404def read_cts_test_result(file_xml):
405 re_module = re.compile('<Module name="([^"]*)"')
406 re_test_case = re.compile('<TestCase name="([^"]*)"')
407 re_test = re.compile('<Test result="(pass|fail)" name="([^"]*)"')
408 with open(file_xml) as f:
409 for line in f:
410 m = re_module.search(line)
411 if m:
412 yield CtsModule(m.groups()[0])
413 continue
414 m = re_test_case.search(line)
415 if m:
416 yield CtsTestCase(m.groups()[0])
417 continue
418 m = re_test.search(line)
419 if m:
420 outcome = m.groups()[0]
Rico Windf80f5a22017-06-16 09:15:57 +0200421 assert outcome in ['fail', 'pass']
Tamas Kenez82efeb52017-06-12 13:56:22 +0200422 yield CtsTest(m.groups()[1], outcome == 'pass')
Tamas Kenezfc34cd82017-07-13 12:43:57 +0200423
424def grep_memoryuse(logfile):
425 re_vmhwm = re.compile('^VmHWM:[ \t]*([0-9]+)[ \t]*([a-zA-Z]*)')
426 result = None
427 with open(logfile) as f:
428 for line in f:
429 m = re_vmhwm.search(line)
430 if m:
431 groups = m.groups()
432 s = len(groups)
433 if s >= 1:
434 result = int(groups[0])
435 if s >= 2:
436 unit = groups[1]
437 if unit == 'kB':
438 result *= 1024
439 elif unit != '':
440 raise Exception('Unrecognized unit in memory usage log: {}'
441 .format(unit))
442 if result is None:
443 raise Exception('No memory usage found in log: {}'.format(logfile))
Tamas Kenez02bff032017-07-18 12:13:58 +0200444 return result
445
446# Return a dictionary: {segment_name -> segments_size}
447def getDexSegmentSizes(dex_files):
448 assert len(dex_files) > 0
Ian Zerny3f54e222019-02-12 10:51:17 +0100449 cmd = [jdk.GetJavaExecutable(), '-jar', R8_JAR, 'dexsegments']
Tamas Kenez02bff032017-07-18 12:13:58 +0200450 cmd.extend(dex_files)
451 PrintCmd(cmd)
452 output = subprocess.check_output(cmd)
453
454 matches = DEX_SEGMENTS_RESULT_PATTERN.findall(output)
455
456 if matches is None or len(matches) == 0:
457 raise Exception('DexSegments failed to return any output for' \
458 ' these files: {}'.format(dex_files))
459
460 result = {}
461
462 for match in matches:
463 result[match[0]] = int(match[1])
464
465 return result
466
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100467# Return a dictionary: {segment_name -> segments_size}
468def getCfSegmentSizes(cfFile):
Ian Zerny3f54e222019-02-12 10:51:17 +0100469 cmd = [jdk.GetJavaExecutable(),
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100470 '-cp',
Morten Krogh-Jespersen480784d2019-02-05 08:10:46 +0100471 CF_SEGMENTS_TOOL,
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100472 'com.android.tools.r8.cf_segments.MeasureLib',
473 cfFile]
474 PrintCmd(cmd)
475 output = subprocess.check_output(cmd)
476
477 matches = DEX_SEGMENTS_RESULT_PATTERN.findall(output)
478
479 if matches is None or len(matches) == 0:
480 raise Exception('CfSegments failed to return any output for' \
481 ' the file: ' + cfFile)
482
483 result = {}
484
485 for match in matches:
486 result[match[0]] = int(match[1])
487
488 return result
489
Søren Gjesse1c115b52019-08-14 12:43:57 +0200490def get_maven_path(artifact, version):
491 return os.path.join('com', 'android', 'tools', artifact, version)
Rico Windc0b16382018-05-17 13:23:43 +0200492
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100493def print_cfsegments(prefix, cf_files):
494 for cf_file in cf_files:
495 for segment_name, size in getCfSegmentSizes(cf_file).items():
496 print('{}-{}(CodeSize): {}'
497 .format(prefix, segment_name, size))
498
Tamas Kenez02bff032017-07-18 12:13:58 +0200499def print_dexsegments(prefix, dex_files):
500 for segment_name, size in getDexSegmentSizes(dex_files).items():
501 print('{}-{}(CodeSize): {}'
502 .format(prefix, segment_name, size))
Tamas Kenez2cf47cf2017-07-25 10:22:52 +0200503
Mads Agerbc7b2ce2018-02-05 11:28:47 +0100504# Ensure that we are not benchmarking with a google jvm.
Tamas Kenez2cf47cf2017-07-25 10:22:52 +0200505def check_java_version():
Ian Zerny3f54e222019-02-12 10:51:17 +0100506 cmd= [jdk.GetJavaExecutable(), '-version']
Tamas Kenez2cf47cf2017-07-25 10:22:52 +0200507 output = subprocess.check_output(cmd, stderr = subprocess.STDOUT)
508 m = re.search('openjdk version "([^"]*)"', output)
509 if m is None:
510 raise Exception("Can't check java version: no version string in output"
511 " of 'java -version': '{}'".format(output))
512 version = m.groups(0)[0]
Mads Agerbc7b2ce2018-02-05 11:28:47 +0100513 m = re.search('google', version)
514 if m is not None:
515 raise Exception("Do not use google JVM for benchmarking: " + version)
Tamas Kenez0cad51c2017-08-21 14:42:01 +0200516
Christoffer Quist Adamsen17879c12019-01-22 16:13:54 +0100517def get_android_jar_dir(api):
518 return os.path.join(REPO_ROOT, ANDROID_JAR_DIR.format(api=api))
519
Rico Wind9d70f612018-08-31 09:17:43 +0200520def get_android_jar(api):
521 return os.path.join(REPO_ROOT, ANDROID_JAR.format(api=api))
Rico Windda6836e2018-12-07 12:32:03 +0100522
Christoffer Quist Adamsen17879c12019-01-22 16:13:54 +0100523def get_android_optional_jars(api):
524 android_optional_jars_dir = os.path.join(get_android_jar_dir(api), 'optional')
525 android_optional_jars = [
526 os.path.join(android_optional_jars_dir, 'android.test.base.jar'),
527 os.path.join(android_optional_jars_dir, 'android.test.mock.jar'),
528 os.path.join(android_optional_jars_dir, 'android.test.runner.jar'),
529 os.path.join(android_optional_jars_dir, 'org.apache.http.legacy.jar')
530 ]
531 return [
532 android_optional_jar for android_optional_jar in android_optional_jars
533 if os.path.isfile(android_optional_jar)]
534
Rico Windfaaac012019-02-25 11:24:05 +0100535def is_bot():
Rico Winde11f4392019-03-18 07:59:37 +0100536 return 'SWARMING_BOT_ID' in os.environ
Morten Krogh-Jespersen16e925d2019-01-25 14:40:38 +0100537
538def uncompressed_size(path):
539 return sum(z.file_size for z in zipfile.ZipFile(path).infolist())
Morten Krogh-Jespersen0de13732019-03-01 08:56:39 +0100540
541def getR8Version(path):
542 cmd = [jdk.GetJavaExecutable(), '-cp', path, 'com.android.tools.r8.R8',
543 '--version']
544 output = subprocess.check_output(cmd, stderr = subprocess.STDOUT)
Jinseong Jeona2394232019-11-26 22:17:55 -0800545 # output is of the form 'R8 <version> (with additional info)'
546 # so we split on '('; clean up tailing spaces; and strip off 'R8 '.
547 return output.split('(')[0].strip()[3:]
Søren Gjesse6e5e5842019-09-03 08:48:30 +0200548
549def desugar_configuration_version():
550 with open(DESUGAR_CONFIGURATION, 'r') as f:
551 configuration_json = json.loads(f.read())
552 configuration_format_version = \
553 configuration_json.get('configuration_format_version')
Søren Gjesse6e5e5842019-09-03 08:48:30 +0200554 version = configuration_json.get('version')
555 if not version:
556 raise Exception(
557 'No "version" found in ' + utils.DESUGAR_CONFIGURATION)
Søren Gjesse1e171532019-09-03 09:44:22 +0200558 check_basic_semver_version(version, 'in ' + DESUGAR_CONFIGURATION)
Søren Gjesse6e5e5842019-09-03 08:48:30 +0200559 return version
Søren Gjesse1e171532019-09-03 09:44:22 +0200560
Søren Gjesse4e5c6fe2019-11-05 17:17:43 +0100561class SemanticVersion:
562 def __init__(self, major, minor, patch):
563 self.major = major
564 self.minor = minor
565 self.patch = patch
566 # Build metadata currently not suppported
567
568 def larger_than(self, other):
569 if self.major > other.major:
570 return True
571 if self.major == other.major and self.minor > other.minor:
572 return True
573 if self.patch:
574 return (self.major == other.major
575 and self.minor == other.minor
576 and self.patch > other.patch)
577 else:
578 return False
579
580
Søren Gjesse1e171532019-09-03 09:44:22 +0200581# Check that the passed string is formatted as a basic semver version (x.y.z)
582# See https://semver.org/.
Søren Gjesse4e5c6fe2019-11-05 17:17:43 +0100583def check_basic_semver_version(version, error_context = '', components = 3):
584 regexp = '^'
585 for x in range(components):
586 regexp += '([0-9]+)'
587 if x < components - 1:
588 regexp += '\\.'
589 regexp += '$'
590 reg = re.compile(regexp)
591 match = reg.match(version)
592 if not match:
Søren Gjesse1e171532019-09-03 09:44:22 +0200593 raise Exception("Invalid version '"
594 + version
595 + "'"
596 + (' ' + error_context) if len(error_context) > 0 else '')
Søren Gjesse4e5c6fe2019-11-05 17:17:43 +0100597 if components == 2:
598 return SemanticVersion(int(match.group(1)), int(match.group(2)), None)
599 elif components == 3:
600 return SemanticVersion(
601 int(match.group(1)), int(match.group(2)), int(match.group(3)))
602 else:
603 raise Exception('Argument "components" must be 2 or 3')