blob: 9bd518ffefb3ed6dbe549a6fd358136632556882 [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
Christoffer Quist Adamsen4d9fc512022-08-11 19:59:44 +020026BUNDLETOOL_JAR_DIR = os.path.join(THIRD_PARTY, 'bundletool/bundletool-1.11.0')
27BUNDLETOOL_JAR = os.path.join(BUNDLETOOL_JAR_DIR, 'bundletool-all-1.11.0.jar')
Morten Krogh-Jespersen220e5702019-02-27 12:57:01 +010028ANDROID_SDK = os.path.join(THIRD_PARTY, 'android_sdk')
Tamas Kenezfc34cd82017-07-13 12:43:57 +020029MEMORY_USE_TMP_FILE = 'memory_use.tmp'
Tamas Kenez02bff032017-07-18 12:13:58 +020030DEX_SEGMENTS_RESULT_PATTERN = re.compile('- ([^:]+): ([0-9]+)')
Mads Ager12a56bc2017-11-27 11:51:25 +010031BUILD = os.path.join(REPO_ROOT, 'build')
Ian Zerny0f5fc732018-11-15 14:34:41 +010032BUILD_DEPS_DIR = os.path.join(BUILD, 'deps')
33BUILD_MAIN_DIR = os.path.join(BUILD, 'classes', 'main')
Morten Krogh-Jespersen51db2b02020-11-11 12:49:26 +010034BUILD_JAVA_MAIN_DIR = os.path.join(BUILD, 'classes', 'java', 'main')
Ian Zerny0f5fc732018-11-15 14:34:41 +010035BUILD_TEST_DIR = os.path.join(BUILD, 'classes', 'test')
Mads Ager12a56bc2017-11-27 11:51:25 +010036LIBS = os.path.join(BUILD, 'libs')
37GENERATED_LICENSE_DIR = os.path.join(BUILD, 'generatedLicense')
Mads Agera4911eb2017-11-22 13:19:36 +010038SRC_ROOT = os.path.join(REPO_ROOT, 'src', 'main', 'java')
Søren Gjesse6e5e5842019-09-03 08:48:30 +020039TEST_ROOT = os.path.join(REPO_ROOT, 'src', 'test', 'java')
Ian Zerny59dfa4c2019-10-25 10:34:36 +020040REPO_SOURCE = 'https://r8.googlesource.com/r8'
Søren Gjessedc9d8a22017-10-12 12:40:59 +020041
42D8 = 'd8'
43R8 = 'r8'
Tamas Kenez03ab76f2018-12-07 14:33:25 +010044R8LIB = 'r8lib'
Morten Krogh-Jespersene28db462019-01-09 13:32:15 +010045R8LIB_NO_DEPS = 'r8LibNoDeps'
Morten Krogh-Jespersen98ee89a2021-10-25 20:59:02 +020046R8RETRACE = 'R8Retrace'
47R8RETRACE_NO_DEPS = 'R8RetraceNoDeps'
Mads Agerb10c07f2017-11-27 13:25:52 +010048R8_SRC = 'sourceJar'
Søren Gjesse17fc67d2019-12-04 14:50:17 +010049LIBRARY_DESUGAR_CONVERSIONS = 'buildLibraryDesugarConversions'
Ian Zerny161ff742022-01-20 12:39:40 +010050R8_TESTS_TARGET = 'TestJar'
51R8_TESTS_DEPS_TARGET = 'RepackageTestDeps'
52R8LIB_TESTS_TARGET = 'configureTestForR8Lib'
53R8LIB_TESTS_DEPS_TARGET = R8_TESTS_DEPS_TARGET
Søren Gjessedc9d8a22017-10-12 12:40:59 +020054
Morten Krogh-Jespersen51db2b02020-11-11 12:49:26 +010055ALL_DEPS_JAR = os.path.join(LIBS, 'deps_all.jar')
Rico Wind74fab302017-10-02 07:25:33 +020056R8_JAR = os.path.join(LIBS, 'r8.jar')
Ian Zerny161ff742022-01-20 12:39:40 +010057R8_WITH_RELOCATED_DEPS_JAR = os.path.join(LIBS, 'r8_with_relocated_deps.jar')
Tamas Kenez03ab76f2018-12-07 14:33:25 +010058R8LIB_JAR = os.path.join(LIBS, 'r8lib.jar')
Rico Wind158ef9f2022-05-19 11:08:30 +020059R8LIB_MAP = '%s.map' % R8LIB_JAR
Mads Agerb10c07f2017-11-27 13:25:52 +010060R8_SRC_JAR = os.path.join(LIBS, 'r8-src.jar')
Tamas Kenez03ab76f2018-12-07 14:33:25 +010061R8LIB_EXCLUDE_DEPS_JAR = os.path.join(LIBS, 'r8lib-exclude-deps.jar')
Tamas Kenez180be092018-12-05 15:23:06 +010062R8_FULL_EXCLUDE_DEPS_JAR = os.path.join(LIBS, 'r8-full-exclude-deps.jar')
Morten Krogh-Jespersen98ee89a2021-10-25 20:59:02 +020063R8RETRACE_JAR = os.path.join(LIBS, 'r8retrace.jar')
64R8RETRACE_EXCLUDE_DEPS_JAR = os.path.join(LIBS, 'r8retrace-exclude-deps.jar')
Ian Zerny161ff742022-01-20 12:39:40 +010065R8_TESTS_JAR = os.path.join(LIBS, 'r8tests.jar')
66R8LIB_TESTS_JAR = os.path.join(LIBS, 'r8libtestdeps-cf.jar')
67R8_TESTS_DEPS_JAR = os.path.join(LIBS, 'test_deps_all.jar')
68R8LIB_TESTS_DEPS_JAR = R8_TESTS_DEPS_JAR
Mads Ager12a56bc2017-11-27 11:51:25 +010069MAVEN_ZIP = os.path.join(LIBS, 'r8.zip')
Rico Wind8fc8bfa2019-03-22 09:57:36 +010070MAVEN_ZIP_LIB = os.path.join(LIBS, 'r8lib.zip')
Søren Gjessee18fa6e2022-06-24 15:14:53 +020071LIBRARY_DESUGAR_CONVERSIONS_LEGACY_ZIP = os.path.join(LIBS, 'library_desugar_conversions_legacy.jar')
Clément Béra00aedde2022-06-22 12:48:35 +020072LIBRARY_DESUGAR_CONVERSIONS_ZIP = os.path.join(LIBS, 'library_desugar_conversions.jar')
Søren Gjesse17fc67d2019-12-04 14:50:17 +010073
Søren Gjesse6e5e5842019-09-03 08:48:30 +020074DESUGAR_CONFIGURATION = os.path.join(
Søren Gjesse927a92e2019-12-04 15:18:06 +010075 'src', 'library_desugar', 'desugar_jdk_libs.json')
Søren Gjesseee086b22020-10-30 11:46:39 +010076DESUGAR_IMPLEMENTATION = os.path.join(
Søren Gjesse3dc207b2021-02-15 09:45:30 +010077 'third_party', 'openjdk', 'desugar_jdk_libs', 'desugar_jdk_libs.jar')
Søren Gjesse705a3b12022-03-17 11:37:30 +010078DESUGAR_CONFIGURATION_JDK11_LEGACY = os.path.join(
79 'src', 'library_desugar', 'jdk11', 'desugar_jdk_libs_legacy.json')
80DESUGAR_IMPLEMENTATION_JDK11 = os.path.join(
81 'third_party', 'openjdk', 'desugar_jdk_libs_11', 'desugar_jdk_libs.jar')
Søren Gjesse6e5e5842019-09-03 08:48:30 +020082DESUGAR_CONFIGURATION_MAVEN_ZIP = os.path.join(
83 LIBS, 'desugar_jdk_libs_configuration.zip')
Søren Gjessee18fa6e2022-06-24 15:14:53 +020084DESUGAR_CONFIGURATION_JDK11_LEGACY_MAVEN_ZIP = os.path.join(
85 LIBS, 'desugar_jdk_libs_configuration_jdk11_legacy.zip')
Mads Ager12a56bc2017-11-27 11:51:25 +010086GENERATED_LICENSE = os.path.join(GENERATED_LICENSE_DIR, 'LICENSE')
Mathias Rav3fb4a3a2018-05-29 15:41:36 +020087RT_JAR = os.path.join(REPO_ROOT, 'third_party/openjdk/openjdk-rt-1.8/rt.jar')
Mathias Ravb46dc002018-06-06 09:37:11 +020088R8LIB_KEEP_RULES = os.path.join(REPO_ROOT, 'src/main/keep.txt')
Morten Krogh-Jespersen480784d2019-02-05 08:10:46 +010089CF_SEGMENTS_TOOL = os.path.join(THIRD_PARTY, 'cf_segments')
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +010090PINNED_R8_JAR = os.path.join(REPO_ROOT, 'third_party/r8/r8.jar')
91PINNED_PGR8_JAR = os.path.join(REPO_ROOT, 'third_party/r8/r8-pg6.0.1.jar')
Ian Zernyfbb1f7a2019-05-02 14:34:13 +020092SAMPLE_LIBRARIES_SHA_FILE = os.path.join(
93 THIRD_PARTY, 'sample_libraries.tar.gz.sha1')
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +010094OPENSOURCE_DUMPS_DIR = os.path.join(THIRD_PARTY, 'opensource-apps')
Morten Krogh-Jespersen86222742021-03-02 11:13:33 +010095INTERNAL_DUMPS_DIR = os.path.join(THIRD_PARTY, 'internal-apps')
Søren Gjesse1c115b52019-08-14 12:43:57 +020096BAZEL_SHA_FILE = os.path.join(THIRD_PARTY, 'bazel.tar.gz.sha1')
97BAZEL_TOOL = os.path.join(THIRD_PARTY, 'bazel')
Søren Gjesse699f6362019-10-09 14:56:33 +020098JAVA8_SHA_FILE = os.path.join(THIRD_PARTY, 'openjdk', 'jdk8', 'linux-x86.tar.gz.sha1')
Søren Gjesseef195772021-03-11 16:04:42 +010099JAVA11_SHA_FILE = os.path.join(THIRD_PARTY, 'openjdk', 'jdk-11', 'linux.tar.gz.sha1')
Christoffer Quist Adamsen1ca046c2021-02-21 11:25:16 +0100100IGNORE_WARNINGS_RULES = os.path.join(REPO_ROOT, 'src', 'test', 'ignorewarnings.rules')
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100101
Morten Krogh-Jespersen220e5702019-02-27 12:57:01 +0100102ANDROID_HOME_ENVIROMENT_NAME = "ANDROID_HOME"
103ANDROID_TOOLS_VERSION_ENVIRONMENT_NAME = "ANDROID_TOOLS_VERSION"
Morten Krogh-Jespersenc8efedd2019-01-28 11:36:17 +0100104USER_HOME = os.path.expanduser('~')
Morten Krogh-Jespersen220e5702019-02-27 12:57:01 +0100105
Morten Krogh-Jespersen0981b722019-10-09 10:00:33 +0200106R8_TEST_RESULTS_BUCKET = 'r8-test-results'
Rico Wind635b2de2022-04-25 10:35:14 +0200107R8_INTERNAL_TEST_RESULTS_BUCKET = 'r8-internal-test-results'
Morten Krogh-Jespersen0981b722019-10-09 10:00:33 +0200108
109def archive_file(name, gs_dir, src_file):
110 gs_file = '%s/%s' % (gs_dir, name)
Rico Wind03424282022-04-26 15:09:51 +0200111 upload_file_to_cloud_storage(src_file, gs_file)
Morten Krogh-Jespersen0981b722019-10-09 10:00:33 +0200112
113def archive_value(name, gs_dir, value):
114 with TempDir() as temp:
115 tempfile = os.path.join(temp, name);
116 with open(tempfile, 'w') as f:
117 f.write(str(value))
118 archive_file(name, gs_dir, tempfile)
119
Christoffer Quist Adamsen4d38d032021-04-20 12:31:31 +0200120def find_cloud_storage_file_from_options(name, options, orElse=None):
121 # Import archive on-demand since archive depends on utils.
122 from archive import GetUploadDestination
123 hash_or_version = find_hash_or_version_from_options(options)
124 if not hash_or_version:
125 return orElse
126 is_hash = options.commit_hash is not None
127 download_path = GetUploadDestination(hash_or_version, name, is_hash)
128 if file_exists_on_cloud_storage(download_path):
129 out = tempfile.NamedTemporaryFile().name
130 download_file_from_cloud_storage(download_path, out)
131 return out
132 else:
133 raise Exception('Could not find file {} from hash/version: {}.'
134 .format(name, hash_or_version))
135
136def find_r8_jar_from_options(options):
137 return find_cloud_storage_file_from_options('r8.jar', options)
138
139def find_r8_lib_jar_from_options(options):
140 return find_cloud_storage_file_from_options('r8lib.jar', options)
141
142def find_hash_or_version_from_options(options):
143 if options.tag:
144 return find_hash_or_version_from_tag(options.tag)
145 else:
146 return options.commit_hash or options.version
147
148def find_hash_or_version_from_tag(tag_or_hash):
Rico Windfd186372022-02-28 08:55:48 +0100149 info = subprocess.check_output([
Christoffer Quist Adamsen4d38d032021-04-20 12:31:31 +0200150 'git',
151 'show',
152 tag_or_hash,
153 '-s',
Rico Windfd186372022-02-28 08:55:48 +0100154 '--format=oneline']).decode('utf-8').splitlines()[-1].split()
Christoffer Quist Adamsen4d38d032021-04-20 12:31:31 +0200155 # The info should be on the following form [hash,"Version",version]
156 if len(info) == 3 and len(info[0]) == 40 and info[1] == "Version":
157 return info[2]
158 return None
159
Morten Krogh-Jespersen220e5702019-02-27 12:57:01 +0100160def getAndroidHome():
161 return os.environ.get(
162 ANDROID_HOME_ENVIROMENT_NAME, os.path.join(USER_HOME, 'Android', 'Sdk'))
163
164def getAndroidBuildTools():
Christoffer Quist Adamsen8c803b42022-05-31 10:36:17 +0200165 if ANDROID_TOOLS_VERSION_ENVIRONMENT_NAME in os.environ:
166 version = os.environ.get(ANDROID_TOOLS_VERSION_ENVIRONMENT_NAME)
167 build_tools_dir = os.path.join(getAndroidHome(), 'build-tools', version)
168 assert os.path.exists(build_tools_dir)
169 return build_tools_dir
170 else:
171 versions = ['30.0.3', '30.0.2', '30.0.1', '30.0.0']
172 for version in versions:
173 build_tools_dir = os.path.join(getAndroidHome(), 'build-tools', version)
174 if os.path.exists(build_tools_dir):
175 return build_tools_dir
176 raise Exception('Unable to find Android build-tools')
Morten Krogh-Jespersenc8efedd2019-01-28 11:36:17 +0100177
Christoffer Quist Adamsen5c9ded12021-01-14 14:29:37 +0100178def is_python3():
179 return sys.version_info.major == 3
180
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100181def Print(s, quiet=False):
182 if quiet:
183 return
184 print(s)
185
186def Warn(message):
187 CRED = '\033[91m'
188 CEND = '\033[0m'
189 print(CRED + message + CEND)
190
191def PrintCmd(cmd, env=None, quiet=False):
192 if quiet:
193 return
194 if type(cmd) is list:
195 cmd = ' '.join(cmd)
196 if env:
197 env = ' '.join(['{}=\"{}\"'.format(x, y) for x, y in env.iteritems()])
198 print('Running: {} {}'.format(env, cmd))
199 else:
200 print('Running: {}'.format(cmd))
Mads Ager418d1ca2017-05-22 09:35:49 +0200201 # I know this will hit os on windows eventually if we don't do this.
202 sys.stdout.flush()
203
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100204class ProgressLogger(object):
205 CLEAR_LINE = '\033[K'
206 UP = '\033[F'
207
208 def __init__(self, quiet=False):
209 self._count = 0
210 self._has_printed = False
211 self._quiet = quiet
212
213 def log(self, text):
Christoffer Quist Adamsen7607ebe2022-06-28 11:52:46 +0200214 if len(text.strip()) == 0:
215 return
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100216 if self._quiet:
217 if self._has_printed:
218 sys.stdout.write(ProgressLogger.UP + ProgressLogger.CLEAR_LINE)
219 if len(text) > 140:
220 text = text[0:140] + '...'
221 print(text)
222 self._has_printed = True
223
224 def done(self):
225 if self._quiet and self._has_printed:
226 sys.stdout.write(ProgressLogger.UP + ProgressLogger.CLEAR_LINE)
227 print('')
228 sys.stdout.write(ProgressLogger.UP)
229
Morten Krogh-Jespersen7cdd3a72019-03-13 14:58:25 +0100230def RunCmd(cmd, env_vars=None, quiet=False, fail=True, logging=True):
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100231 PrintCmd(cmd, env=env_vars, quiet=quiet)
232 env = os.environ.copy()
233 if env_vars:
234 env.update(env_vars)
235 process = subprocess.Popen(
236 cmd, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
237 stdout = []
Morten Krogh-Jespersen7cdd3a72019-03-13 14:58:25 +0100238 logger = ProgressLogger(quiet=quiet) if logging else None
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100239 failed = False
240 while True:
Rico Wind744ba752021-01-22 06:24:49 +0100241 line = process.stdout.readline().decode('utf-8')
242 if line != '':
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100243 stripped = line.rstrip()
244 stdout.append(stripped)
Morten Krogh-Jespersen7cdd3a72019-03-13 14:58:25 +0100245 if logger:
246 logger.log(stripped)
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100247 # TODO(christofferqa): r8 should fail with non-zero exit code.
Morten Krogh-Jespersen121c47b2019-01-25 09:57:21 +0100248 if ('AssertionError:' in stripped
249 or 'CompilationError:' in stripped
250 or 'CompilationFailedException:' in stripped
Morten Krogh-Jespersen5d02a6b2019-10-29 14:48:56 +0100251 or 'Compilation failed' in stripped
252 or 'FAILURE:' in stripped
253 or 'org.gradle.api.ProjectConfigurationException' in stripped
254 or 'BUILD FAILED' in stripped):
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100255 failed = True
256 else:
Morten Krogh-Jespersen7cdd3a72019-03-13 14:58:25 +0100257 if logger:
258 logger.done()
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100259 exit_code = process.poll()
260 if exit_code or failed:
261 for line in stdout:
262 Warn(line)
Christoffer Quist Adamsen7cf4c562019-03-07 10:57:33 +0100263 if fail:
264 raise subprocess.CalledProcessError(
265 exit_code or -1, cmd, output='\n'.join(stdout))
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100266 return stdout
267
Christoffer Quist Adamsen7cf4c562019-03-07 10:57:33 +0100268def RunGradlew(
269 args, clean=True, stacktrace=True, use_daemon=False, env_vars=None,
Morten Krogh-Jespersen7cdd3a72019-03-13 14:58:25 +0100270 quiet=False, fail=True, logging=True):
Christoffer Quist Adamsen7cf4c562019-03-07 10:57:33 +0100271 cmd = ['./gradlew']
272 if clean:
273 assert 'clean' not in args
274 cmd.append('clean')
275 if stacktrace:
276 assert '--stacktrace' not in args
277 cmd.append('--stacktrace')
278 if not use_daemon:
279 assert '--no-daemon' not in args
280 cmd.append('--no-daemon')
281 cmd.extend(args)
Morten Krogh-Jespersen7cdd3a72019-03-13 14:58:25 +0100282 return RunCmd(cmd, env_vars=env_vars, quiet=quiet, fail=fail, logging=logging)
Christoffer Quist Adamsen7cf4c562019-03-07 10:57:33 +0100283
Rico Windf80f5a22017-06-16 09:15:57 +0200284def IsWindows():
Ian Zerny3f54e222019-02-12 10:51:17 +0100285 return defines.IsWindows()
Ian Zerny5fffb0a2019-02-11 13:54:22 +0100286
287def IsLinux():
Ian Zerny3f54e222019-02-12 10:51:17 +0100288 return defines.IsLinux()
Ian Zerny5fffb0a2019-02-11 13:54:22 +0100289
290def IsOsX():
Ian Zerny3f54e222019-02-12 10:51:17 +0100291 return defines.IsOsX()
Ian Zerny5fffb0a2019-02-11 13:54:22 +0100292
293def EnsureDepFromGoogleCloudStorage(dep, tgz, sha1, msg):
294 if not os.path.exists(dep) or os.path.getmtime(tgz) < os.path.getmtime(sha1):
295 DownloadFromGoogleCloudStorage(sha1)
296 # Update the mtime of the tar file to make sure we do not run again unless
297 # there is an update.
298 os.utime(tgz, None)
299 else:
Rico Wind3d369b42021-01-12 10:26:24 +0100300 print('Ensure cloud dependency:', msg, 'present')
Rico Windf80f5a22017-06-16 09:15:57 +0200301
Jean-Marie Henaffe4e36d12018-04-05 10:33:50 +0200302def DownloadFromX20(sha1_file):
303 download_script = os.path.join(REPO_ROOT, 'tools', 'download_from_x20.py')
304 cmd = [download_script, sha1_file]
305 PrintCmd(cmd)
306 subprocess.check_call(cmd)
307
Rico Wind59593922021-03-03 09:12:36 +0100308def DownloadFromGoogleCloudStorage(sha1_file, bucket='r8-deps', auth=False,
309 quiet=False):
Rico Windf80f5a22017-06-16 09:15:57 +0200310 suffix = '.bat' if IsWindows() else ''
311 download_script = 'download_from_google_storage%s' % suffix
Rico Wind533e3ce2019-04-04 10:26:12 +0200312 cmd = [download_script]
313 if not auth:
314 cmd.append('-n')
315 cmd.extend(['-b', bucket, '-u', '-s', sha1_file])
Rico Wind59593922021-03-03 09:12:36 +0100316 if not quiet:
317 PrintCmd(cmd)
318 subprocess.check_call(cmd)
319 else:
320 subprocess.check_output(cmd)
Mads Ager418d1ca2017-05-22 09:35:49 +0200321
322def get_sha1(filename):
323 sha1 = hashlib.sha1()
324 with open(filename, 'rb') as f:
325 while True:
326 chunk = f.read(1024*1024)
327 if not chunk:
328 break
329 sha1.update(chunk)
330 return sha1.hexdigest()
331
Rico Wind1b52acf2021-03-21 12:36:55 +0100332def is_main():
Rico Windfd186372022-02-28 08:55:48 +0100333 remotes = subprocess.check_output(['git', 'branch', '-r', '--contains',
334 'HEAD']).decode('utf-8')
Rico Wind1b52acf2021-03-21 12:36:55 +0100335 return 'origin/main' in remotes
Rico Wind1b09c562019-01-17 08:53:09 +0100336
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +0200337def get_HEAD_sha1():
Morten Krogh-Jespersene0ce6a32019-02-07 11:44:45 +0100338 return get_HEAD_sha1_for_checkout(REPO_ROOT)
339
340def get_HEAD_sha1_for_checkout(checkout):
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +0200341 cmd = ['git', 'rev-parse', 'HEAD']
342 PrintCmd(cmd)
Morten Krogh-Jespersene0ce6a32019-02-07 11:44:45 +0100343 with ChangedWorkingDirectory(checkout):
Christoffer Quist Adamsen50930e42021-01-20 11:55:12 +0100344 return subprocess.check_output(cmd).decode('utf-8').strip()
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +0200345
Tamas Kenez971eec62017-05-24 11:08:40 +0200346def makedirs_if_needed(path):
347 try:
348 os.makedirs(path)
349 except OSError:
350 if not os.path.isdir(path):
351 raise
352
Rico Windef7420c2021-10-14 13:16:01 +0200353def get_gsutil():
354 return 'gsutil.py' if os.name != 'nt' else 'gsutil.py.bat'
355
Rico Wind03424282022-04-26 15:09:51 +0200356def upload_dir_to_cloud_storage(directory, destination, is_html=False):
Rico Winda94f01c2017-06-27 10:32:34 +0200357 # Upload and make the content encoding right for viewing directly
Rico Windef7420c2021-10-14 13:16:01 +0200358 cmd = [get_gsutil(), '-m', 'cp']
Rico Windd0d88cf2018-02-09 09:46:11 +0100359 if is_html:
360 cmd += ['-z', 'html']
Rico Wind800fd712018-09-24 11:29:33 +0200361 cmd += ['-R', directory, destination]
Rico Winda94f01c2017-06-27 10:32:34 +0200362 PrintCmd(cmd)
363 subprocess.check_call(cmd)
364
Rico Wind03424282022-04-26 15:09:51 +0200365def upload_file_to_cloud_storage(source, destination):
Rico Windef7420c2021-10-14 13:16:01 +0200366 cmd = [get_gsutil(), 'cp']
Rico Wind800fd712018-09-24 11:29:33 +0200367 cmd += [source, destination]
Rico Windb4621c12017-08-28 12:48:53 +0200368 PrintCmd(cmd)
369 subprocess.check_call(cmd)
370
Rico Wind139eece2018-09-25 09:42:09 +0200371def delete_file_from_cloud_storage(destination):
Rico Windef7420c2021-10-14 13:16:01 +0200372 cmd = [get_gsutil(), 'rm', destination]
Rico Wind139eece2018-09-25 09:42:09 +0200373 PrintCmd(cmd)
374 subprocess.check_call(cmd)
375
Rico Wind4fd2dda2018-09-26 17:41:45 +0200376def ls_files_on_cloud_storage(destination):
Rico Windef7420c2021-10-14 13:16:01 +0200377 cmd = [get_gsutil(), 'ls', destination]
Rico Wind4fd2dda2018-09-26 17:41:45 +0200378 PrintCmd(cmd)
Rico Windfd186372022-02-28 08:55:48 +0100379 return subprocess.check_output(cmd).decode('utf-8')
Rico Wind4fd2dda2018-09-26 17:41:45 +0200380
Rico Wind139eece2018-09-25 09:42:09 +0200381def cat_file_on_cloud_storage(destination, ignore_errors=False):
Rico Windef7420c2021-10-14 13:16:01 +0200382 cmd = [get_gsutil(), 'cat', destination]
Rico Wind139eece2018-09-25 09:42:09 +0200383 PrintCmd(cmd)
384 try:
Rico Wind8dadb312022-02-28 08:40:20 +0100385 return subprocess.check_output(cmd).decode('utf-8').strip()
Rico Wind139eece2018-09-25 09:42:09 +0200386 except subprocess.CalledProcessError as e:
387 if ignore_errors:
388 return ''
389 else:
390 raise e
391
392def file_exists_on_cloud_storage(destination):
Rico Windef7420c2021-10-14 13:16:01 +0200393 cmd = [get_gsutil(), 'ls', destination]
Rico Wind139eece2018-09-25 09:42:09 +0200394 PrintCmd(cmd)
395 return subprocess.call(cmd) == 0
396
Christoffer Quist Adamsen870fa462020-12-15 10:50:54 +0100397def download_file_from_cloud_storage(source, destination, quiet=False):
Rico Windef7420c2021-10-14 13:16:01 +0200398 cmd = [get_gsutil(), 'cp', source, destination]
Christoffer Quist Adamsen870fa462020-12-15 10:50:54 +0100399 PrintCmd(cmd, quiet=quiet)
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +0200400 subprocess.check_call(cmd)
401
Morten Krogh-Jespersen220e5702019-02-27 12:57:01 +0100402def create_archive(name, sources=None):
403 if not sources:
404 sources = [name]
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +0200405 tarname = '%s.tar.gz' % name
406 with tarfile.open(tarname, 'w:gz') as tar:
Morten Krogh-Jespersen54090862019-02-19 11:31:10 +0100407 for source in sources:
408 tar.add(source)
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +0200409 return tarname
410
411def extract_dir(filename):
412 return filename[0:len(filename) - len('.tar.gz')]
413
414def unpack_archive(filename):
415 dest_dir = extract_dir(filename)
416 if os.path.exists(dest_dir):
Rico Wind3d369b42021-01-12 10:26:24 +0100417 print('Deleting existing dir %s' % dest_dir)
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +0200418 shutil.rmtree(dest_dir)
419 dirname = os.path.dirname(os.path.abspath(filename))
420 with tarfile.open(filename, 'r:gz') as tar:
421 tar.extractall(path=dirname)
422
Morten Krogh-Jespersenec3047b2020-08-18 13:09:06 +0200423def check_gcert():
Ian Zerny86c4cfd2022-01-17 13:43:37 +0100424 status = subprocess.call(['gcertstatus'])
425 if status != 0:
426 subprocess.check_call(['gcert'])
Morten Krogh-Jespersen54090862019-02-19 11:31:10 +0100427
Rico Wind1a29c4f2018-01-25 08:43:08 +0100428# Note that gcs is eventually consistent with regards to list operations.
429# This is not a problem in our case, but don't ever use this method
430# for synchronization.
431def cloud_storage_exists(destination):
Rico Windef7420c2021-10-14 13:16:01 +0200432 cmd = [get_gsutil(), 'ls', destination]
Rico Wind1a29c4f2018-01-25 08:43:08 +0100433 PrintCmd(cmd)
434 exit_code = subprocess.call(cmd)
435 return exit_code == 0
436
Mads Ager418d1ca2017-05-22 09:35:49 +0200437class TempDir(object):
Søren Gjessecbeae782019-05-21 14:14:25 +0200438 def __init__(self, prefix='', delete=True):
Mads Ager418d1ca2017-05-22 09:35:49 +0200439 self._temp_dir = None
440 self._prefix = prefix
Søren Gjessecbeae782019-05-21 14:14:25 +0200441 self._delete = delete
Mads Ager418d1ca2017-05-22 09:35:49 +0200442
443 def __enter__(self):
444 self._temp_dir = tempfile.mkdtemp(self._prefix)
445 return self._temp_dir
446
447 def __exit__(self, *_):
Søren Gjessecbeae782019-05-21 14:14:25 +0200448 if self._delete:
449 shutil.rmtree(self._temp_dir, ignore_errors=True)
Mads Ager418d1ca2017-05-22 09:35:49 +0200450
451class ChangedWorkingDirectory(object):
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100452 def __init__(self, working_directory, quiet=False):
453 self._quiet = quiet
Mads Ager418d1ca2017-05-22 09:35:49 +0200454 self._working_directory = working_directory
455
456 def __enter__(self):
457 self._old_cwd = os.getcwd()
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100458 if not self._quiet:
Rico Wind3d369b42021-01-12 10:26:24 +0100459 print('Enter directory:', self._working_directory)
Mads Ager418d1ca2017-05-22 09:35:49 +0200460 os.chdir(self._working_directory)
461
462 def __exit__(self, *_):
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100463 if not self._quiet:
Rico Wind3d369b42021-01-12 10:26:24 +0100464 print('Enter directory:', self._old_cwd)
Mads Ager418d1ca2017-05-22 09:35:49 +0200465 os.chdir(self._old_cwd)
Tamas Kenez82efeb52017-06-12 13:56:22 +0200466
467# Reading Android CTS test_result.xml
468
469class CtsModule(object):
470 def __init__(self, module_name):
471 self.name = module_name
472
473class CtsTestCase(object):
474 def __init__(self, test_case_name):
475 self.name = test_case_name
476
477class CtsTest(object):
478 def __init__(self, test_name, outcome):
479 self.name = test_name
480 self.outcome = outcome
481
482# Generator yielding CtsModule, CtsTestCase or CtsTest from
483# reading through a CTS test_result.xml file.
484def read_cts_test_result(file_xml):
485 re_module = re.compile('<Module name="([^"]*)"')
486 re_test_case = re.compile('<TestCase name="([^"]*)"')
487 re_test = re.compile('<Test result="(pass|fail)" name="([^"]*)"')
488 with open(file_xml) as f:
489 for line in f:
490 m = re_module.search(line)
491 if m:
492 yield CtsModule(m.groups()[0])
493 continue
494 m = re_test_case.search(line)
495 if m:
496 yield CtsTestCase(m.groups()[0])
497 continue
498 m = re_test.search(line)
499 if m:
500 outcome = m.groups()[0]
Rico Windf80f5a22017-06-16 09:15:57 +0200501 assert outcome in ['fail', 'pass']
Tamas Kenez82efeb52017-06-12 13:56:22 +0200502 yield CtsTest(m.groups()[1], outcome == 'pass')
Tamas Kenezfc34cd82017-07-13 12:43:57 +0200503
504def grep_memoryuse(logfile):
505 re_vmhwm = re.compile('^VmHWM:[ \t]*([0-9]+)[ \t]*([a-zA-Z]*)')
506 result = None
507 with open(logfile) as f:
508 for line in f:
509 m = re_vmhwm.search(line)
510 if m:
511 groups = m.groups()
512 s = len(groups)
513 if s >= 1:
514 result = int(groups[0])
515 if s >= 2:
516 unit = groups[1]
517 if unit == 'kB':
518 result *= 1024
519 elif unit != '':
520 raise Exception('Unrecognized unit in memory usage log: {}'
521 .format(unit))
522 if result is None:
523 raise Exception('No memory usage found in log: {}'.format(logfile))
Tamas Kenez02bff032017-07-18 12:13:58 +0200524 return result
525
526# Return a dictionary: {segment_name -> segments_size}
527def getDexSegmentSizes(dex_files):
528 assert len(dex_files) > 0
Ian Zerny3f54e222019-02-12 10:51:17 +0100529 cmd = [jdk.GetJavaExecutable(), '-jar', R8_JAR, 'dexsegments']
Tamas Kenez02bff032017-07-18 12:13:58 +0200530 cmd.extend(dex_files)
531 PrintCmd(cmd)
Morten Krogh-Jespersenf54dd782021-02-09 09:06:08 +0100532 output = subprocess.check_output(cmd).decode('utf-8')
Tamas Kenez02bff032017-07-18 12:13:58 +0200533
534 matches = DEX_SEGMENTS_RESULT_PATTERN.findall(output)
535
536 if matches is None or len(matches) == 0:
537 raise Exception('DexSegments failed to return any output for' \
538 ' these files: {}'.format(dex_files))
539
540 result = {}
541
542 for match in matches:
543 result[match[0]] = int(match[1])
544
545 return result
546
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100547# Return a dictionary: {segment_name -> segments_size}
548def getCfSegmentSizes(cfFile):
Ian Zerny3f54e222019-02-12 10:51:17 +0100549 cmd = [jdk.GetJavaExecutable(),
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100550 '-cp',
Morten Krogh-Jespersen480784d2019-02-05 08:10:46 +0100551 CF_SEGMENTS_TOOL,
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100552 'com.android.tools.r8.cf_segments.MeasureLib',
553 cfFile]
554 PrintCmd(cmd)
Rico Windfd186372022-02-28 08:55:48 +0100555 output = subprocess.check_output(cmd).decode('utf-8')
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100556
557 matches = DEX_SEGMENTS_RESULT_PATTERN.findall(output)
558
559 if matches is None or len(matches) == 0:
560 raise Exception('CfSegments failed to return any output for' \
561 ' the file: ' + cfFile)
562
563 result = {}
564
565 for match in matches:
566 result[match[0]] = int(match[1])
567
568 return result
569
Søren Gjesse1c115b52019-08-14 12:43:57 +0200570def get_maven_path(artifact, version):
571 return os.path.join('com', 'android', 'tools', artifact, version)
Rico Windc0b16382018-05-17 13:23:43 +0200572
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100573def print_cfsegments(prefix, cf_files):
574 for cf_file in cf_files:
575 for segment_name, size in getCfSegmentSizes(cf_file).items():
576 print('{}-{}(CodeSize): {}'
577 .format(prefix, segment_name, size))
578
Tamas Kenez02bff032017-07-18 12:13:58 +0200579def print_dexsegments(prefix, dex_files):
580 for segment_name, size in getDexSegmentSizes(dex_files).items():
581 print('{}-{}(CodeSize): {}'
582 .format(prefix, segment_name, size))
Tamas Kenez2cf47cf2017-07-25 10:22:52 +0200583
Mads Agerbc7b2ce2018-02-05 11:28:47 +0100584# Ensure that we are not benchmarking with a google jvm.
Tamas Kenez2cf47cf2017-07-25 10:22:52 +0200585def check_java_version():
Ian Zerny3f54e222019-02-12 10:51:17 +0100586 cmd= [jdk.GetJavaExecutable(), '-version']
Rico Windfd186372022-02-28 08:55:48 +0100587 output = subprocess.check_output(cmd, stderr = subprocess.STDOUT).decode('utf-8')
588 m = re.search('openjdk version "([^"]*)"', output)
Tamas Kenez2cf47cf2017-07-25 10:22:52 +0200589 if m is None:
590 raise Exception("Can't check java version: no version string in output"
591 " of 'java -version': '{}'".format(output))
592 version = m.groups(0)[0]
Mads Agerbc7b2ce2018-02-05 11:28:47 +0100593 m = re.search('google', version)
594 if m is not None:
595 raise Exception("Do not use google JVM for benchmarking: " + version)
Tamas Kenez0cad51c2017-08-21 14:42:01 +0200596
Christoffer Quist Adamsen17879c12019-01-22 16:13:54 +0100597def get_android_jar_dir(api):
598 return os.path.join(REPO_ROOT, ANDROID_JAR_DIR.format(api=api))
599
Rico Wind9d70f612018-08-31 09:17:43 +0200600def get_android_jar(api):
601 return os.path.join(REPO_ROOT, ANDROID_JAR.format(api=api))
Rico Windda6836e2018-12-07 12:32:03 +0100602
Christoffer Quist Adamsen17879c12019-01-22 16:13:54 +0100603def get_android_optional_jars(api):
604 android_optional_jars_dir = os.path.join(get_android_jar_dir(api), 'optional')
605 android_optional_jars = [
606 os.path.join(android_optional_jars_dir, 'android.test.base.jar'),
607 os.path.join(android_optional_jars_dir, 'android.test.mock.jar'),
608 os.path.join(android_optional_jars_dir, 'android.test.runner.jar'),
609 os.path.join(android_optional_jars_dir, 'org.apache.http.legacy.jar')
610 ]
611 return [
612 android_optional_jar for android_optional_jar in android_optional_jars
613 if os.path.isfile(android_optional_jar)]
614
Rico Windfaaac012019-02-25 11:24:05 +0100615def is_bot():
Rico Winde11f4392019-03-18 07:59:37 +0100616 return 'SWARMING_BOT_ID' in os.environ
Morten Krogh-Jespersen16e925d2019-01-25 14:40:38 +0100617
618def uncompressed_size(path):
619 return sum(z.file_size for z in zipfile.ZipFile(path).infolist())
Morten Krogh-Jespersen0de13732019-03-01 08:56:39 +0100620
621def getR8Version(path):
622 cmd = [jdk.GetJavaExecutable(), '-cp', path, 'com.android.tools.r8.R8',
623 '--version']
Rico Windfd186372022-02-28 08:55:48 +0100624 output = subprocess.check_output(cmd, stderr = subprocess.STDOUT).decode('utf-8')
Jinseong Jeona2394232019-11-26 22:17:55 -0800625 # output is of the form 'R8 <version> (with additional info)'
626 # so we split on '('; clean up tailing spaces; and strip off 'R8 '.
627 return output.split('(')[0].strip()[3:]
Søren Gjesse6e5e5842019-09-03 08:48:30 +0200628
Søren Gjesse705a3b12022-03-17 11:37:30 +0100629def desugar_configuration_version(configuration):
630 with open(configuration, 'r') as f:
Søren Gjesse6e5e5842019-09-03 08:48:30 +0200631 configuration_json = json.loads(f.read())
632 configuration_format_version = \
633 configuration_json.get('configuration_format_version')
Søren Gjesse6e5e5842019-09-03 08:48:30 +0200634 version = configuration_json.get('version')
635 if not version:
636 raise Exception(
Søren Gjesse705a3b12022-03-17 11:37:30 +0100637 'No "version" found in ' + configuration)
638 check_basic_semver_version(version, 'in ' + configuration, allowPrerelease = True)
Søren Gjesse6e5e5842019-09-03 08:48:30 +0200639 return version
Søren Gjesse1e171532019-09-03 09:44:22 +0200640
Søren Gjesse4e5c6fe2019-11-05 17:17:43 +0100641class SemanticVersion:
Søren Gjesse705a3b12022-03-17 11:37:30 +0100642 def __init__(self, major, minor, patch, prerelease):
Søren Gjesse4e5c6fe2019-11-05 17:17:43 +0100643 self.major = major
644 self.minor = minor
645 self.patch = patch
Søren Gjesse705a3b12022-03-17 11:37:30 +0100646 self.prerelease = prerelease
Søren Gjesse4e5c6fe2019-11-05 17:17:43 +0100647 # Build metadata currently not suppported
648
649 def larger_than(self, other):
Søren Gjesse29d108a2022-04-07 10:49:49 +0200650 if self.prerelease or other.prerelease:
Søren Gjesse705a3b12022-03-17 11:37:30 +0100651 raise Exception("Comparison with prerelease not implemented")
Søren Gjesse4e5c6fe2019-11-05 17:17:43 +0100652 if self.major > other.major:
653 return True
654 if self.major == other.major and self.minor > other.minor:
655 return True
656 if self.patch:
657 return (self.major == other.major
658 and self.minor == other.minor
659 and self.patch > other.patch)
660 else:
661 return False
662
663
Søren Gjesse705a3b12022-03-17 11:37:30 +0100664# Check that the passed string is formatted as a basic semver version (x.y.z or x.y.z-prerelease
665# depending on the value of allowPrerelease).
666# See https://semver.org/. The regexp parts used are not all complient with what is suggested
667# on https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string.
668def check_basic_semver_version(version, error_context = '', components = 3, allowPrerelease = False):
Søren Gjesse4e5c6fe2019-11-05 17:17:43 +0100669 regexp = '^'
670 for x in range(components):
671 regexp += '([0-9]+)'
672 if x < components - 1:
673 regexp += '\\.'
Søren Gjesse705a3b12022-03-17 11:37:30 +0100674 if allowPrerelease:
675 # This part is from
676 # https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string
677 regexp += r'(?:-(?P<prerelease>(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?'
Søren Gjesse4e5c6fe2019-11-05 17:17:43 +0100678 regexp += '$'
679 reg = re.compile(regexp)
680 match = reg.match(version)
681 if not match:
Søren Gjesse1e171532019-09-03 09:44:22 +0200682 raise Exception("Invalid version '"
683 + version
684 + "'"
685 + (' ' + error_context) if len(error_context) > 0 else '')
Søren Gjesse4e5c6fe2019-11-05 17:17:43 +0100686 if components == 2:
Søren Gjesse705a3b12022-03-17 11:37:30 +0100687 return SemanticVersion(int(match.group(1)), int(match.group(2)), None, None)
688 elif components == 3 and not allowPrerelease:
Søren Gjesse4e5c6fe2019-11-05 17:17:43 +0100689 return SemanticVersion(
Søren Gjesse705a3b12022-03-17 11:37:30 +0100690 int(match.group(1)), int(match.group(2)), int(match.group(3)), None)
691 elif components == 3 and allowPrerelease:
692 return SemanticVersion(
693 int(match.group(1)), int(match.group(2)), int(match.group(3)), match.group('prerelease'))
Søren Gjesse4e5c6fe2019-11-05 17:17:43 +0100694 else:
695 raise Exception('Argument "components" must be 2 or 3')