blob: cad17b79ec6c5428bca0dc1c2a2ec0f843998a07 [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
Clément Béra3718ad02023-09-05 14:12:48 +02008import jdk
Søren Gjesse6e5e5842019-09-03 08:48:30 +02009import json
Mads Ager418d1ca2017-05-22 09:35:49 +020010import os
Tamas Kenez82efeb52017-06-12 13:56:22 +020011import re
Mads Ager418d1ca2017-05-22 09:35:49 +020012import shutil
13import subprocess
14import sys
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +020015import tarfile
Mads Ager418d1ca2017-05-22 09:35:49 +020016import tempfile
Morten Krogh-Jespersen16e925d2019-01-25 14:40:38 +010017import zipfile
Mads Ager418d1ca2017-05-22 09:35:49 +020018
Ian Zerny37097652019-04-11 13:13:27 +020019import defines
Christoffer Quist Adamsen65ef2982023-08-24 08:45:39 +020020from thread_utils import print_thread
Ian Zerny37097652019-04-11 13:13:27 +020021
Christoffer Quist Adamsen17879c12019-01-22 16:13:54 +010022ANDROID_JAR_DIR = 'third_party/android_jar/lib-v{api}'
23ANDROID_JAR = os.path.join(ANDROID_JAR_DIR, 'android.jar')
Ian Zerny3f54e222019-02-12 10:51:17 +010024TOOLS_DIR = defines.TOOLS_DIR
25REPO_ROOT = defines.REPO_ROOT
26THIRD_PARTY = defines.THIRD_PARTY
Christoffer Quist Adamsen4d9fc512022-08-11 19:59:44 +020027BUNDLETOOL_JAR_DIR = os.path.join(THIRD_PARTY, 'bundletool/bundletool-1.11.0')
28BUNDLETOOL_JAR = os.path.join(BUNDLETOOL_JAR_DIR, 'bundletool-all-1.11.0.jar')
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]+)')
Rico Windaf9e8fb2023-10-10 09:25:26 +020031
Rico Windb65d75c2023-10-10 11:14:52 +020032DEPENDENCIES_DIR = os.path.join(THIRD_PARTY, 'dependencies')
33
Mads Ager12a56bc2017-11-27 11:51:25 +010034BUILD = os.path.join(REPO_ROOT, 'build')
Morten Krogh-Jespersen51db2b02020-11-11 12:49:26 +010035BUILD_JAVA_MAIN_DIR = os.path.join(BUILD, 'classes', 'java', 'main')
Mads Ager12a56bc2017-11-27 11:51:25 +010036LIBS = os.path.join(BUILD, 'libs')
Clément Béra3718ad02023-09-05 14:12:48 +020037CUSTOM_CONVERSION_DIR = os.path.join(
Clément Béradb79e5d2023-09-06 14:48:35 +020038 THIRD_PARTY, 'openjdk', 'custom_conversion')
Mads Ager12a56bc2017-11-27 11:51:25 +010039GENERATED_LICENSE_DIR = os.path.join(BUILD, 'generatedLicense')
Mads Agera4911eb2017-11-22 13:19:36 +010040SRC_ROOT = os.path.join(REPO_ROOT, 'src', 'main', 'java')
Ian Zerny59dfa4c2019-10-25 10:34:36 +020041REPO_SOURCE = 'https://r8.googlesource.com/r8'
Søren Gjessedc9d8a22017-10-12 12:40:59 +020042
Rico Wind93755fb2023-10-09 13:29:29 +020043GRADLE_TASK_CLEAN_TEST = ':test:cleanTest'
44GRADLE_TASK_CONSOLIDATED_LICENSE = ':main:consolidatedLicense'
45GRADLE_TASK_KEEP_ANNO_JAR = ':keepanno:keepAnnoAnnotationsJar'
46GRADLE_TASK_R8 = ':main:r8WithRelocatedDeps'
Christoffer Quist Adamsen31237c32023-10-13 10:59:53 +020047GRADLE_TASK_R8LIB = ':test:assembleR8LibWithRelocatedDeps'
48GRADLE_TASK_R8LIB_NO_DEPS = ':test:assembleR8LibNoDeps'
49GRADLE_TASK_RETRACE = ':test:assembleRetraceLibWithRelocatedDeps'
50GRADLE_TASK_RETRACE_NO_DEPS = ':test:assembleRetraceLibNoDeps'
51GRADLE_TASK_SOURCE_JAR = ':test:packageSources'
Rico Wind93755fb2023-10-09 13:29:29 +020052GRADLE_TASK_SWISS_ARMY_KNIFE = ':main:swissArmyKnife'
53GRADLE_TASK_TEST = ':test:test'
Søren Gjessed54faae2023-10-12 09:07:54 +020054GRADLE_TASK_ALL_TESTS_WITH_APPLY_MAPPING_JAR = ':test:allTestsWithApplyMapping'
Rico Wind833710c2023-10-11 15:02:34 +020055GRADLE_TASK_TEST_DEPS_JAR = ':test:allDepsJar'
56GRADLE_TASK_TEST_JAR = ':test:allTestsJar'
Rico Wind93755fb2023-10-09 13:29:29 +020057
Søren Gjessedc9d8a22017-10-12 12:40:59 +020058R8 = 'r8'
Tamas Kenez03ab76f2018-12-07 14:33:25 +010059R8LIB = 'r8lib'
Søren Gjessedc9d8a22017-10-12 12:40:59 +020060
Morten Krogh-Jespersen51db2b02020-11-11 12:49:26 +010061ALL_DEPS_JAR = os.path.join(LIBS, 'deps_all.jar')
Rico Wind74fab302017-10-02 07:25:33 +020062R8_JAR = os.path.join(LIBS, 'r8.jar')
Tamas Kenez03ab76f2018-12-07 14:33:25 +010063R8LIB_JAR = os.path.join(LIBS, 'r8lib.jar')
Rico Wind158ef9f2022-05-19 11:08:30 +020064R8LIB_MAP = '%s.map' % R8LIB_JAR
Mads Agerb10c07f2017-11-27 13:25:52 +010065R8_SRC_JAR = os.path.join(LIBS, 'r8-src.jar')
Tamas Kenez03ab76f2018-12-07 14:33:25 +010066R8LIB_EXCLUDE_DEPS_JAR = os.path.join(LIBS, 'r8lib-exclude-deps.jar')
Tamas Kenez180be092018-12-05 15:23:06 +010067R8_FULL_EXCLUDE_DEPS_JAR = os.path.join(LIBS, 'r8-full-exclude-deps.jar')
Morten Krogh-Jespersen98ee89a2021-10-25 20:59:02 +020068R8RETRACE_JAR = os.path.join(LIBS, 'r8retrace.jar')
69R8RETRACE_EXCLUDE_DEPS_JAR = os.path.join(LIBS, 'r8retrace-exclude-deps.jar')
Ian Zerny161ff742022-01-20 12:39:40 +010070R8_TESTS_JAR = os.path.join(LIBS, 'r8tests.jar')
71R8LIB_TESTS_JAR = os.path.join(LIBS, 'r8libtestdeps-cf.jar')
72R8_TESTS_DEPS_JAR = os.path.join(LIBS, 'test_deps_all.jar')
73R8LIB_TESTS_DEPS_JAR = R8_TESTS_DEPS_JAR
Rico Wind8fc8bfa2019-03-22 09:57:36 +010074MAVEN_ZIP_LIB = os.path.join(LIBS, 'r8lib.zip')
Clément Béra3718ad02023-09-05 14:12:48 +020075LIBRARY_DESUGAR_CONVERSIONS_LEGACY_ZIP = os.path.join(
76 CUSTOM_CONVERSION_DIR, 'library_desugar_conversions_legacy.jar')
77LIBRARY_DESUGAR_CONVERSIONS_ZIP = os.path.join(
78 CUSTOM_CONVERSION_DIR, 'library_desugar_conversions.jar')
Ian Zernyf13d18f2023-05-24 12:50:37 +020079KEEPANNO_ANNOTATIONS_JAR = os.path.join(LIBS, 'keepanno-annotations.jar')
Søren Gjesse17fc67d2019-12-04 14:50:17 +010080
Søren Gjesse6e5e5842019-09-03 08:48:30 +020081DESUGAR_CONFIGURATION = os.path.join(
Søren Gjesse927a92e2019-12-04 15:18:06 +010082 'src', 'library_desugar', 'desugar_jdk_libs.json')
Søren Gjesseee086b22020-10-30 11:46:39 +010083DESUGAR_IMPLEMENTATION = os.path.join(
Søren Gjesse3dc207b2021-02-15 09:45:30 +010084 'third_party', 'openjdk', 'desugar_jdk_libs', 'desugar_jdk_libs.jar')
Søren Gjesse705a3b12022-03-17 11:37:30 +010085DESUGAR_CONFIGURATION_JDK11_LEGACY = os.path.join(
86 'src', 'library_desugar', 'jdk11', 'desugar_jdk_libs_legacy.json')
Søren Gjesse2b047692022-08-19 16:34:38 +020087DESUGAR_CONFIGURATION_JDK11_MINIMAL = os.path.join(
88 'src', 'library_desugar', 'jdk11', 'desugar_jdk_libs_minimal.json')
89DESUGAR_CONFIGURATION_JDK11 = os.path.join(
90 'src', 'library_desugar', 'jdk11', 'desugar_jdk_libs.json')
91DESUGAR_CONFIGURATION_JDK11_NIO = os.path.join(
92 'src', 'library_desugar', 'jdk11', 'desugar_jdk_libs_nio.json')
Søren Gjesse705a3b12022-03-17 11:37:30 +010093DESUGAR_IMPLEMENTATION_JDK11 = os.path.join(
94 'third_party', 'openjdk', 'desugar_jdk_libs_11', 'desugar_jdk_libs.jar')
Søren Gjesse6e5e5842019-09-03 08:48:30 +020095DESUGAR_CONFIGURATION_MAVEN_ZIP = os.path.join(
96 LIBS, 'desugar_jdk_libs_configuration.zip')
Søren Gjessee18fa6e2022-06-24 15:14:53 +020097DESUGAR_CONFIGURATION_JDK11_LEGACY_MAVEN_ZIP = os.path.join(
98 LIBS, 'desugar_jdk_libs_configuration_jdk11_legacy.zip')
Søren Gjesse2b047692022-08-19 16:34:38 +020099DESUGAR_CONFIGURATION_JDK11_MINIMAL_MAVEN_ZIP = os.path.join(
100 LIBS, 'desugar_jdk_libs_configuration_jdk11_minimal.zip')
101DESUGAR_CONFIGURATION_JDK11_MAVEN_ZIP = os.path.join(
102 LIBS, 'desugar_jdk_libs_configuration_jdk11.zip')
103DESUGAR_CONFIGURATION_JDK11_NIO_MAVEN_ZIP = os.path.join(
104 LIBS, 'desugar_jdk_libs_configuration_jdk11_nio.zip')
Mads Ager12a56bc2017-11-27 11:51:25 +0100105GENERATED_LICENSE = os.path.join(GENERATED_LICENSE_DIR, 'LICENSE')
Mathias Rav3fb4a3a2018-05-29 15:41:36 +0200106RT_JAR = os.path.join(REPO_ROOT, 'third_party/openjdk/openjdk-rt-1.8/rt.jar')
Mathias Ravb46dc002018-06-06 09:37:11 +0200107R8LIB_KEEP_RULES = os.path.join(REPO_ROOT, 'src/main/keep.txt')
Morten Krogh-Jespersen480784d2019-02-05 08:10:46 +0100108CF_SEGMENTS_TOOL = os.path.join(THIRD_PARTY, 'cf_segments')
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100109PINNED_R8_JAR = os.path.join(REPO_ROOT, 'third_party/r8/r8.jar')
110PINNED_PGR8_JAR = os.path.join(REPO_ROOT, 'third_party/r8/r8-pg6.0.1.jar')
Rico Wind8bd693f2023-10-13 11:29:32 +0200111
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +0100112OPENSOURCE_DUMPS_DIR = os.path.join(THIRD_PARTY, 'opensource-apps')
Morten Krogh-Jespersen86222742021-03-02 11:13:33 +0100113INTERNAL_DUMPS_DIR = os.path.join(THIRD_PARTY, 'internal-apps')
Søren Gjesse1c115b52019-08-14 12:43:57 +0200114BAZEL_SHA_FILE = os.path.join(THIRD_PARTY, 'bazel.tar.gz.sha1')
115BAZEL_TOOL = os.path.join(THIRD_PARTY, 'bazel')
Søren Gjesse699f6362019-10-09 14:56:33 +0200116JAVA8_SHA_FILE = os.path.join(THIRD_PARTY, 'openjdk', 'jdk8', 'linux-x86.tar.gz.sha1')
Søren Gjesseef195772021-03-11 16:04:42 +0100117JAVA11_SHA_FILE = os.path.join(THIRD_PARTY, 'openjdk', 'jdk-11', 'linux.tar.gz.sha1')
Søren Gjesseeddc6612022-09-02 15:38:39 +0200118DESUGAR_JDK_LIBS_11_SHA_FILE = os.path.join(THIRD_PARTY, 'openjdk', 'desugar_jdk_libs_11.tar.gz.sha1')
Christoffer Quist Adamsen1ca046c2021-02-21 11:25:16 +0100119IGNORE_WARNINGS_RULES = os.path.join(REPO_ROOT, 'src', 'test', 'ignorewarnings.rules')
Morten Krogh-Jespersen220e5702019-02-27 12:57:01 +0100120ANDROID_HOME_ENVIROMENT_NAME = "ANDROID_HOME"
121ANDROID_TOOLS_VERSION_ENVIRONMENT_NAME = "ANDROID_TOOLS_VERSION"
Morten Krogh-Jespersenc8efedd2019-01-28 11:36:17 +0100122USER_HOME = os.path.expanduser('~')
Morten Krogh-Jespersen220e5702019-02-27 12:57:01 +0100123
Morten Krogh-Jespersen0981b722019-10-09 10:00:33 +0200124R8_TEST_RESULTS_BUCKET = 'r8-test-results'
Rico Wind635b2de2022-04-25 10:35:14 +0200125R8_INTERNAL_TEST_RESULTS_BUCKET = 'r8-internal-test-results'
Morten Krogh-Jespersen0981b722019-10-09 10:00:33 +0200126
127def archive_file(name, gs_dir, src_file):
128 gs_file = '%s/%s' % (gs_dir, name)
Rico Wind03424282022-04-26 15:09:51 +0200129 upload_file_to_cloud_storage(src_file, gs_file)
Morten Krogh-Jespersen0981b722019-10-09 10:00:33 +0200130
131def archive_value(name, gs_dir, value):
132 with TempDir() as temp:
Rico Wind8bd693f2023-10-13 11:29:32 +0200133 temparchive = os.path.join(temp, name)
134 with open(temparchive, 'w') as f:
Morten Krogh-Jespersen0981b722019-10-09 10:00:33 +0200135 f.write(str(value))
Rico Wind8bd693f2023-10-13 11:29:32 +0200136 archive_file(name, gs_dir, temparchive)
Morten Krogh-Jespersen0981b722019-10-09 10:00:33 +0200137
Christoffer Quist Adamsen4d38d032021-04-20 12:31:31 +0200138def find_cloud_storage_file_from_options(name, options, orElse=None):
139 # Import archive on-demand since archive depends on utils.
140 from archive import GetUploadDestination
141 hash_or_version = find_hash_or_version_from_options(options)
142 if not hash_or_version:
143 return orElse
144 is_hash = options.commit_hash is not None
145 download_path = GetUploadDestination(hash_or_version, name, is_hash)
146 if file_exists_on_cloud_storage(download_path):
147 out = tempfile.NamedTemporaryFile().name
148 download_file_from_cloud_storage(download_path, out)
149 return out
150 else:
151 raise Exception('Could not find file {} from hash/version: {}.'
152 .format(name, hash_or_version))
153
154def find_r8_jar_from_options(options):
155 return find_cloud_storage_file_from_options('r8.jar', options)
156
Christoffer Quist Adamsen4d38d032021-04-20 12:31:31 +0200157
158def find_hash_or_version_from_options(options):
159 if options.tag:
160 return find_hash_or_version_from_tag(options.tag)
161 else:
162 return options.commit_hash or options.version
163
164def find_hash_or_version_from_tag(tag_or_hash):
Rico Windfd186372022-02-28 08:55:48 +0100165 info = subprocess.check_output([
Christoffer Quist Adamsen4d38d032021-04-20 12:31:31 +0200166 'git',
167 'show',
168 tag_or_hash,
169 '-s',
Rico Windfd186372022-02-28 08:55:48 +0100170 '--format=oneline']).decode('utf-8').splitlines()[-1].split()
Christoffer Quist Adamsen4d38d032021-04-20 12:31:31 +0200171 # The info should be on the following form [hash,"Version",version]
172 if len(info) == 3 and len(info[0]) == 40 and info[1] == "Version":
173 return info[2]
174 return None
175
Morten Krogh-Jespersen220e5702019-02-27 12:57:01 +0100176def getAndroidHome():
177 return os.environ.get(
178 ANDROID_HOME_ENVIROMENT_NAME, os.path.join(USER_HOME, 'Android', 'Sdk'))
179
180def getAndroidBuildTools():
Christoffer Quist Adamsen8c803b42022-05-31 10:36:17 +0200181 if ANDROID_TOOLS_VERSION_ENVIRONMENT_NAME in os.environ:
182 version = os.environ.get(ANDROID_TOOLS_VERSION_ENVIRONMENT_NAME)
183 build_tools_dir = os.path.join(getAndroidHome(), 'build-tools', version)
184 assert os.path.exists(build_tools_dir)
185 return build_tools_dir
186 else:
Morten Krogh-Jespersen9c1e7022023-02-07 13:56:35 +0100187 versions = ['33.0.1', '32.0.0']
Christoffer Quist Adamsen8c803b42022-05-31 10:36:17 +0200188 for version in versions:
189 build_tools_dir = os.path.join(getAndroidHome(), 'build-tools', version)
190 if os.path.exists(build_tools_dir):
191 return build_tools_dir
192 raise Exception('Unable to find Android build-tools')
Morten Krogh-Jespersenc8efedd2019-01-28 11:36:17 +0100193
Christoffer Quist Adamsen5c9ded12021-01-14 14:29:37 +0100194def is_python3():
195 return sys.version_info.major == 3
196
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100197def Print(s, quiet=False):
198 if quiet:
199 return
200 print(s)
201
202def Warn(message):
203 CRED = '\033[91m'
204 CEND = '\033[0m'
205 print(CRED + message + CEND)
206
Christoffer Quist Adamsen65ef2982023-08-24 08:45:39 +0200207def PrintCmd(cmd, env=None, quiet=False, worker_id=None):
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100208 if quiet:
209 return
210 if type(cmd) is list:
211 cmd = ' '.join(cmd)
212 if env:
213 env = ' '.join(['{}=\"{}\"'.format(x, y) for x, y in env.iteritems()])
Christoffer Quist Adamsen65ef2982023-08-24 08:45:39 +0200214 print_thread('Running: {} {}'.format(env, cmd), worker_id)
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100215 else:
Christoffer Quist Adamsen65ef2982023-08-24 08:45:39 +0200216 print_thread('Running: {}'.format(cmd), worker_id)
Mads Ager418d1ca2017-05-22 09:35:49 +0200217 # I know this will hit os on windows eventually if we don't do this.
218 sys.stdout.flush()
219
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100220class ProgressLogger(object):
221 CLEAR_LINE = '\033[K'
222 UP = '\033[F'
223
224 def __init__(self, quiet=False):
225 self._count = 0
226 self._has_printed = False
227 self._quiet = quiet
228
229 def log(self, text):
Christoffer Quist Adamsen7607ebe2022-06-28 11:52:46 +0200230 if len(text.strip()) == 0:
231 return
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100232 if self._quiet:
233 if self._has_printed:
234 sys.stdout.write(ProgressLogger.UP + ProgressLogger.CLEAR_LINE)
235 if len(text) > 140:
236 text = text[0:140] + '...'
237 print(text)
238 self._has_printed = True
239
240 def done(self):
241 if self._quiet and self._has_printed:
242 sys.stdout.write(ProgressLogger.UP + ProgressLogger.CLEAR_LINE)
243 print('')
244 sys.stdout.write(ProgressLogger.UP)
245
Morten Krogh-Jespersen7cdd3a72019-03-13 14:58:25 +0100246def RunCmd(cmd, env_vars=None, quiet=False, fail=True, logging=True):
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100247 PrintCmd(cmd, env=env_vars, quiet=quiet)
248 env = os.environ.copy()
249 if env_vars:
250 env.update(env_vars)
251 process = subprocess.Popen(
252 cmd, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
253 stdout = []
Morten Krogh-Jespersen7cdd3a72019-03-13 14:58:25 +0100254 logger = ProgressLogger(quiet=quiet) if logging else None
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100255 failed = False
256 while True:
Rico Wind744ba752021-01-22 06:24:49 +0100257 line = process.stdout.readline().decode('utf-8')
258 if line != '':
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100259 stripped = line.rstrip()
260 stdout.append(stripped)
Morten Krogh-Jespersen7cdd3a72019-03-13 14:58:25 +0100261 if logger:
262 logger.log(stripped)
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100263 # TODO(christofferqa): r8 should fail with non-zero exit code.
Morten Krogh-Jespersen121c47b2019-01-25 09:57:21 +0100264 if ('AssertionError:' in stripped
265 or 'CompilationError:' in stripped
266 or 'CompilationFailedException:' in stripped
Morten Krogh-Jespersen5d02a6b2019-10-29 14:48:56 +0100267 or 'Compilation failed' in stripped
268 or 'FAILURE:' in stripped
269 or 'org.gradle.api.ProjectConfigurationException' in stripped
270 or 'BUILD FAILED' in stripped):
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100271 failed = True
272 else:
Morten Krogh-Jespersen7cdd3a72019-03-13 14:58:25 +0100273 if logger:
274 logger.done()
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100275 exit_code = process.poll()
276 if exit_code or failed:
277 for line in stdout:
278 Warn(line)
Christoffer Quist Adamsen7cf4c562019-03-07 10:57:33 +0100279 if fail:
280 raise subprocess.CalledProcessError(
281 exit_code or -1, cmd, output='\n'.join(stdout))
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100282 return stdout
283
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
Ian Zerny5fffb0a2019-02-11 13:54:22 +0100287def EnsureDepFromGoogleCloudStorage(dep, tgz, sha1, msg):
Morten Krogh-Jespersen3295c842023-09-18 13:48:22 +0200288 if (not os.path.exists(dep)
289 or not os.path.exists(tgz)
290 or os.path.getmtime(tgz) < os.path.getmtime(sha1)):
Ian Zerny5fffb0a2019-02-11 13:54:22 +0100291 DownloadFromGoogleCloudStorage(sha1)
292 # Update the mtime of the tar file to make sure we do not run again unless
293 # there is an update.
294 os.utime(tgz, None)
295 else:
Rico Wind3d369b42021-01-12 10:26:24 +0100296 print('Ensure cloud dependency:', msg, 'present')
Rico Windf80f5a22017-06-16 09:15:57 +0200297
Jean-Marie Henaffe4e36d12018-04-05 10:33:50 +0200298def DownloadFromX20(sha1_file):
299 download_script = os.path.join(REPO_ROOT, 'tools', 'download_from_x20.py')
300 cmd = [download_script, sha1_file]
301 PrintCmd(cmd)
302 subprocess.check_call(cmd)
303
Rico Wind59593922021-03-03 09:12:36 +0100304def DownloadFromGoogleCloudStorage(sha1_file, bucket='r8-deps', auth=False,
305 quiet=False):
Rico Windf80f5a22017-06-16 09:15:57 +0200306 suffix = '.bat' if IsWindows() else ''
307 download_script = 'download_from_google_storage%s' % suffix
Rico Wind533e3ce2019-04-04 10:26:12 +0200308 cmd = [download_script]
309 if not auth:
310 cmd.append('-n')
311 cmd.extend(['-b', bucket, '-u', '-s', sha1_file])
Rico Wind59593922021-03-03 09:12:36 +0100312 if not quiet:
313 PrintCmd(cmd)
314 subprocess.check_call(cmd)
315 else:
316 subprocess.check_output(cmd)
Mads Ager418d1ca2017-05-22 09:35:49 +0200317
318def get_sha1(filename):
319 sha1 = hashlib.sha1()
320 with open(filename, 'rb') as f:
321 while True:
322 chunk = f.read(1024*1024)
323 if not chunk:
324 break
325 sha1.update(chunk)
326 return sha1.hexdigest()
327
Ian Zernyc2de7b72023-09-06 20:52:16 +0200328def get_HEAD_branch():
329 result = subprocess.check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD']).decode('utf-8')
330 return result.strip()
331
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +0200332def get_HEAD_sha1():
Morten Krogh-Jespersene0ce6a32019-02-07 11:44:45 +0100333 return get_HEAD_sha1_for_checkout(REPO_ROOT)
334
Ian Zerny9f0345d2023-09-07 11:15:00 +0200335def get_HEAD_diff_stat():
336 return subprocess.check_output(['git', 'diff', '--stat']).decode('utf-8')
337
Morten Krogh-Jespersene0ce6a32019-02-07 11:44:45 +0100338def get_HEAD_sha1_for_checkout(checkout):
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +0200339 cmd = ['git', 'rev-parse', 'HEAD']
340 PrintCmd(cmd)
Morten Krogh-Jespersene0ce6a32019-02-07 11:44:45 +0100341 with ChangedWorkingDirectory(checkout):
Christoffer Quist Adamsen50930e42021-01-20 11:55:12 +0100342 return subprocess.check_output(cmd).decode('utf-8').strip()
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +0200343
Tamas Kenez971eec62017-05-24 11:08:40 +0200344def makedirs_if_needed(path):
345 try:
346 os.makedirs(path)
347 except OSError:
348 if not os.path.isdir(path):
349 raise
350
Rico Windef7420c2021-10-14 13:16:01 +0200351def get_gsutil():
352 return 'gsutil.py' if os.name != 'nt' else 'gsutil.py.bat'
353
Rico Wind03424282022-04-26 15:09:51 +0200354def upload_file_to_cloud_storage(source, destination):
Rico Windef7420c2021-10-14 13:16:01 +0200355 cmd = [get_gsutil(), 'cp']
Rico Wind800fd712018-09-24 11:29:33 +0200356 cmd += [source, destination]
Rico Windb4621c12017-08-28 12:48:53 +0200357 PrintCmd(cmd)
358 subprocess.check_call(cmd)
359
Rico Wind139eece2018-09-25 09:42:09 +0200360def delete_file_from_cloud_storage(destination):
Rico Windef7420c2021-10-14 13:16:01 +0200361 cmd = [get_gsutil(), 'rm', destination]
Rico Wind139eece2018-09-25 09:42:09 +0200362 PrintCmd(cmd)
363 subprocess.check_call(cmd)
364
Rico Wind4fd2dda2018-09-26 17:41:45 +0200365def ls_files_on_cloud_storage(destination):
Rico Windef7420c2021-10-14 13:16:01 +0200366 cmd = [get_gsutil(), 'ls', destination]
Rico Wind4fd2dda2018-09-26 17:41:45 +0200367 PrintCmd(cmd)
Rico Windfd186372022-02-28 08:55:48 +0100368 return subprocess.check_output(cmd).decode('utf-8')
Rico Wind4fd2dda2018-09-26 17:41:45 +0200369
Rico Wind139eece2018-09-25 09:42:09 +0200370def cat_file_on_cloud_storage(destination, ignore_errors=False):
Rico Windef7420c2021-10-14 13:16:01 +0200371 cmd = [get_gsutil(), 'cat', destination]
Rico Wind139eece2018-09-25 09:42:09 +0200372 PrintCmd(cmd)
373 try:
Rico Wind8dadb312022-02-28 08:40:20 +0100374 return subprocess.check_output(cmd).decode('utf-8').strip()
Rico Wind139eece2018-09-25 09:42:09 +0200375 except subprocess.CalledProcessError as e:
376 if ignore_errors:
377 return ''
378 else:
379 raise e
380
381def file_exists_on_cloud_storage(destination):
Rico Windef7420c2021-10-14 13:16:01 +0200382 cmd = [get_gsutil(), 'ls', destination]
Rico Wind139eece2018-09-25 09:42:09 +0200383 PrintCmd(cmd)
384 return subprocess.call(cmd) == 0
385
Christoffer Quist Adamsen870fa462020-12-15 10:50:54 +0100386def download_file_from_cloud_storage(source, destination, quiet=False):
Rico Windef7420c2021-10-14 13:16:01 +0200387 cmd = [get_gsutil(), 'cp', source, destination]
Christoffer Quist Adamsen870fa462020-12-15 10:50:54 +0100388 PrintCmd(cmd, quiet=quiet)
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +0200389 subprocess.check_call(cmd)
390
Morten Krogh-Jespersen220e5702019-02-27 12:57:01 +0100391def create_archive(name, sources=None):
392 if not sources:
393 sources = [name]
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +0200394 tarname = '%s.tar.gz' % name
395 with tarfile.open(tarname, 'w:gz') as tar:
Morten Krogh-Jespersen54090862019-02-19 11:31:10 +0100396 for source in sources:
397 tar.add(source)
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +0200398 return tarname
399
400def extract_dir(filename):
401 return filename[0:len(filename) - len('.tar.gz')]
402
403def unpack_archive(filename):
404 dest_dir = extract_dir(filename)
405 if os.path.exists(dest_dir):
Rico Wind3d369b42021-01-12 10:26:24 +0100406 print('Deleting existing dir %s' % dest_dir)
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +0200407 shutil.rmtree(dest_dir)
408 dirname = os.path.dirname(os.path.abspath(filename))
409 with tarfile.open(filename, 'r:gz') as tar:
410 tar.extractall(path=dirname)
411
Morten Krogh-Jespersenec3047b2020-08-18 13:09:06 +0200412def check_gcert():
Ian Zerny86c4cfd2022-01-17 13:43:37 +0100413 status = subprocess.call(['gcertstatus'])
414 if status != 0:
415 subprocess.check_call(['gcert'])
Morten Krogh-Jespersen54090862019-02-19 11:31:10 +0100416
Rico Wind1a29c4f2018-01-25 08:43:08 +0100417# Note that gcs is eventually consistent with regards to list operations.
418# This is not a problem in our case, but don't ever use this method
419# for synchronization.
420def cloud_storage_exists(destination):
Rico Windef7420c2021-10-14 13:16:01 +0200421 cmd = [get_gsutil(), 'ls', destination]
Rico Wind1a29c4f2018-01-25 08:43:08 +0100422 PrintCmd(cmd)
423 exit_code = subprocess.call(cmd)
424 return exit_code == 0
425
Mads Ager418d1ca2017-05-22 09:35:49 +0200426class TempDir(object):
Søren Gjessecbeae782019-05-21 14:14:25 +0200427 def __init__(self, prefix='', delete=True):
Mads Ager418d1ca2017-05-22 09:35:49 +0200428 self._temp_dir = None
429 self._prefix = prefix
Søren Gjessecbeae782019-05-21 14:14:25 +0200430 self._delete = delete
Mads Ager418d1ca2017-05-22 09:35:49 +0200431
432 def __enter__(self):
433 self._temp_dir = tempfile.mkdtemp(self._prefix)
434 return self._temp_dir
435
436 def __exit__(self, *_):
Søren Gjessecbeae782019-05-21 14:14:25 +0200437 if self._delete:
438 shutil.rmtree(self._temp_dir, ignore_errors=True)
Mads Ager418d1ca2017-05-22 09:35:49 +0200439
440class ChangedWorkingDirectory(object):
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100441 def __init__(self, working_directory, quiet=False):
442 self._quiet = quiet
Mads Ager418d1ca2017-05-22 09:35:49 +0200443 self._working_directory = working_directory
444
445 def __enter__(self):
446 self._old_cwd = os.getcwd()
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100447 if not self._quiet:
Rico Wind3d369b42021-01-12 10:26:24 +0100448 print('Enter directory:', self._working_directory)
Mads Ager418d1ca2017-05-22 09:35:49 +0200449 os.chdir(self._working_directory)
450
451 def __exit__(self, *_):
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100452 if not self._quiet:
Rico Wind3d369b42021-01-12 10:26:24 +0100453 print('Enter directory:', self._old_cwd)
Mads Ager418d1ca2017-05-22 09:35:49 +0200454 os.chdir(self._old_cwd)
Tamas Kenez82efeb52017-06-12 13:56:22 +0200455
456# Reading Android CTS test_result.xml
457
458class CtsModule(object):
459 def __init__(self, module_name):
460 self.name = module_name
461
462class CtsTestCase(object):
463 def __init__(self, test_case_name):
464 self.name = test_case_name
465
466class CtsTest(object):
467 def __init__(self, test_name, outcome):
468 self.name = test_name
469 self.outcome = outcome
470
471# Generator yielding CtsModule, CtsTestCase or CtsTest from
472# reading through a CTS test_result.xml file.
473def read_cts_test_result(file_xml):
474 re_module = re.compile('<Module name="([^"]*)"')
475 re_test_case = re.compile('<TestCase name="([^"]*)"')
476 re_test = re.compile('<Test result="(pass|fail)" name="([^"]*)"')
477 with open(file_xml) as f:
478 for line in f:
479 m = re_module.search(line)
480 if m:
481 yield CtsModule(m.groups()[0])
482 continue
483 m = re_test_case.search(line)
484 if m:
485 yield CtsTestCase(m.groups()[0])
486 continue
487 m = re_test.search(line)
488 if m:
489 outcome = m.groups()[0]
Rico Windf80f5a22017-06-16 09:15:57 +0200490 assert outcome in ['fail', 'pass']
Tamas Kenez82efeb52017-06-12 13:56:22 +0200491 yield CtsTest(m.groups()[1], outcome == 'pass')
Tamas Kenezfc34cd82017-07-13 12:43:57 +0200492
493def grep_memoryuse(logfile):
494 re_vmhwm = re.compile('^VmHWM:[ \t]*([0-9]+)[ \t]*([a-zA-Z]*)')
495 result = None
496 with open(logfile) as f:
497 for line in f:
498 m = re_vmhwm.search(line)
499 if m:
500 groups = m.groups()
501 s = len(groups)
502 if s >= 1:
503 result = int(groups[0])
504 if s >= 2:
505 unit = groups[1]
506 if unit == 'kB':
507 result *= 1024
508 elif unit != '':
509 raise Exception('Unrecognized unit in memory usage log: {}'
510 .format(unit))
511 if result is None:
512 raise Exception('No memory usage found in log: {}'.format(logfile))
Tamas Kenez02bff032017-07-18 12:13:58 +0200513 return result
514
515# Return a dictionary: {segment_name -> segments_size}
516def getDexSegmentSizes(dex_files):
517 assert len(dex_files) > 0
Ian Zerny3f54e222019-02-12 10:51:17 +0100518 cmd = [jdk.GetJavaExecutable(), '-jar', R8_JAR, 'dexsegments']
Tamas Kenez02bff032017-07-18 12:13:58 +0200519 cmd.extend(dex_files)
520 PrintCmd(cmd)
Morten Krogh-Jespersenf54dd782021-02-09 09:06:08 +0100521 output = subprocess.check_output(cmd).decode('utf-8')
Tamas Kenez02bff032017-07-18 12:13:58 +0200522
523 matches = DEX_SEGMENTS_RESULT_PATTERN.findall(output)
524
525 if matches is None or len(matches) == 0:
526 raise Exception('DexSegments failed to return any output for' \
527 ' these files: {}'.format(dex_files))
528
529 result = {}
530
531 for match in matches:
532 result[match[0]] = int(match[1])
533
534 return result
535
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100536# Return a dictionary: {segment_name -> segments_size}
537def getCfSegmentSizes(cfFile):
Ian Zerny3f54e222019-02-12 10:51:17 +0100538 cmd = [jdk.GetJavaExecutable(),
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100539 '-cp',
Morten Krogh-Jespersen480784d2019-02-05 08:10:46 +0100540 CF_SEGMENTS_TOOL,
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100541 'com.android.tools.r8.cf_segments.MeasureLib',
542 cfFile]
543 PrintCmd(cmd)
Rico Windfd186372022-02-28 08:55:48 +0100544 output = subprocess.check_output(cmd).decode('utf-8')
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100545
546 matches = DEX_SEGMENTS_RESULT_PATTERN.findall(output)
547
548 if matches is None or len(matches) == 0:
549 raise Exception('CfSegments failed to return any output for' \
550 ' the file: ' + cfFile)
551
552 result = {}
553
554 for match in matches:
555 result[match[0]] = int(match[1])
556
557 return result
558
Søren Gjesse1c115b52019-08-14 12:43:57 +0200559def get_maven_path(artifact, version):
560 return os.path.join('com', 'android', 'tools', artifact, version)
Rico Windc0b16382018-05-17 13:23:43 +0200561
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100562def print_cfsegments(prefix, cf_files):
563 for cf_file in cf_files:
564 for segment_name, size in getCfSegmentSizes(cf_file).items():
565 print('{}-{}(CodeSize): {}'
566 .format(prefix, segment_name, size))
567
Christoffer Quist Adamsenbe6661d2023-08-24 11:01:12 +0200568def print_dexsegments(prefix, dex_files, worker_id=None):
Tamas Kenez02bff032017-07-18 12:13:58 +0200569 for segment_name, size in getDexSegmentSizes(dex_files).items():
Christoffer Quist Adamsenbe6661d2023-08-24 11:01:12 +0200570 print_thread(
571 '{}-{}(CodeSize): {}'.format(prefix, segment_name, size),
572 worker_id)
Tamas Kenez2cf47cf2017-07-25 10:22:52 +0200573
Mads Agerbc7b2ce2018-02-05 11:28:47 +0100574# Ensure that we are not benchmarking with a google jvm.
Tamas Kenez2cf47cf2017-07-25 10:22:52 +0200575def check_java_version():
Ian Zerny3f54e222019-02-12 10:51:17 +0100576 cmd= [jdk.GetJavaExecutable(), '-version']
Rico Windfd186372022-02-28 08:55:48 +0100577 output = subprocess.check_output(cmd, stderr = subprocess.STDOUT).decode('utf-8')
578 m = re.search('openjdk version "([^"]*)"', output)
Tamas Kenez2cf47cf2017-07-25 10:22:52 +0200579 if m is None:
580 raise Exception("Can't check java version: no version string in output"
581 " of 'java -version': '{}'".format(output))
582 version = m.groups(0)[0]
Mads Agerbc7b2ce2018-02-05 11:28:47 +0100583 m = re.search('google', version)
584 if m is not None:
585 raise Exception("Do not use google JVM for benchmarking: " + version)
Tamas Kenez0cad51c2017-08-21 14:42:01 +0200586
Christoffer Quist Adamsen17879c12019-01-22 16:13:54 +0100587def get_android_jar_dir(api):
588 return os.path.join(REPO_ROOT, ANDROID_JAR_DIR.format(api=api))
589
Rico Wind9d70f612018-08-31 09:17:43 +0200590def get_android_jar(api):
591 return os.path.join(REPO_ROOT, ANDROID_JAR.format(api=api))
Rico Windda6836e2018-12-07 12:32:03 +0100592
Rico Windfaaac012019-02-25 11:24:05 +0100593def is_bot():
Rico Winde11f4392019-03-18 07:59:37 +0100594 return 'SWARMING_BOT_ID' in os.environ
Morten Krogh-Jespersen16e925d2019-01-25 14:40:38 +0100595
596def uncompressed_size(path):
597 return sum(z.file_size for z in zipfile.ZipFile(path).infolist())
Morten Krogh-Jespersen0de13732019-03-01 08:56:39 +0100598
Søren Gjesse2b047692022-08-19 16:34:38 +0200599def desugar_configuration_name_and_version(configuration, is_for_maven):
600 name = 'desugar_jdk_libs_configuration'
Søren Gjesse705a3b12022-03-17 11:37:30 +0100601 with open(configuration, 'r') as f:
Søren Gjesse6e5e5842019-09-03 08:48:30 +0200602 configuration_json = json.loads(f.read())
603 configuration_format_version = \
604 configuration_json.get('configuration_format_version')
Søren Gjesse2b047692022-08-19 16:34:38 +0200605 if (not configuration_format_version):
606 raise Exception(
607 'No "configuration_format_version" found in ' + configuration)
608 if (configuration_format_version != 3
609 and configuration_format_version != 5
610 and configuration_format_version != (200 if is_for_maven else 100)):
611 raise Exception(
612 'Unsupported "configuration_format_version" "%s" found in %s'
613 % (configuration_format_version, configuration))
Søren Gjesse6e5e5842019-09-03 08:48:30 +0200614 version = configuration_json.get('version')
615 if not version:
Søren Gjesse2b047692022-08-19 16:34:38 +0200616 if configuration_format_version == (200 if is_for_maven else 100):
617 identifier = configuration_json.get('identifier')
618 if not identifier:
619 raise Exception(
620 'No "identifier" found in ' + configuration)
621 identifier_split = identifier.split(':')
622 if (len(identifier_split) != 3):
623 raise Exception('Invalid "identifier" found in ' + configuration)
624 if (identifier_split[0] != 'com.tools.android'):
625 raise Exception('Invalid "identifier" found in ' + configuration)
626 if not identifier_split[1].startswith('desugar_jdk_libs_configuration'):
627 raise Exception('Invalid "identifier" found in ' + configuration)
628 name = identifier_split[1]
629 version = identifier_split[2]
630 else:
631 raise Exception(
632 'No "version" found in ' + configuration)
633 else:
634 if configuration_format_version == (200 if is_for_maven else 100):
635 raise Exception(
636 'No "version" expected in ' + configuration)
637 # Disallow prerelease, as older R8 versions cannot parse it causing hard to
638 # understand errors.
639 check_basic_semver_version(version, 'in ' + configuration, allowPrerelease = False)
640 return (name, version)
Søren Gjesse1e171532019-09-03 09:44:22 +0200641
Søren Gjesse4e5c6fe2019-11-05 17:17:43 +0100642class SemanticVersion:
Søren Gjesse705a3b12022-03-17 11:37:30 +0100643 def __init__(self, major, minor, patch, prerelease):
Søren Gjesse4e5c6fe2019-11-05 17:17:43 +0100644 self.major = major
645 self.minor = minor
646 self.patch = patch
Søren Gjesse705a3b12022-03-17 11:37:30 +0100647 self.prerelease = prerelease
Søren Gjesse4e5c6fe2019-11-05 17:17:43 +0100648 # Build metadata currently not suppported
649
650 def larger_than(self, other):
Søren Gjesse29d108a2022-04-07 10:49:49 +0200651 if self.prerelease or other.prerelease:
Søren Gjesse705a3b12022-03-17 11:37:30 +0100652 raise Exception("Comparison with prerelease not implemented")
Søren Gjesse4e5c6fe2019-11-05 17:17:43 +0100653 if self.major > other.major:
654 return True
655 if self.major == other.major and self.minor > other.minor:
656 return True
657 if self.patch:
658 return (self.major == other.major
659 and self.minor == other.minor
660 and self.patch > other.patch)
661 else:
662 return False
663
664
Søren Gjesse705a3b12022-03-17 11:37:30 +0100665# Check that the passed string is formatted as a basic semver version (x.y.z or x.y.z-prerelease
666# depending on the value of allowPrerelease).
667# See https://semver.org/. The regexp parts used are not all complient with what is suggested
668# on https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string.
669def check_basic_semver_version(version, error_context = '', components = 3, allowPrerelease = False):
Søren Gjesse4e5c6fe2019-11-05 17:17:43 +0100670 regexp = '^'
671 for x in range(components):
672 regexp += '([0-9]+)'
673 if x < components - 1:
674 regexp += '\\.'
Søren Gjesse705a3b12022-03-17 11:37:30 +0100675 if allowPrerelease:
676 # This part is from
677 # https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string
678 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 +0100679 regexp += '$'
680 reg = re.compile(regexp)
681 match = reg.match(version)
682 if not match:
Søren Gjesse1e171532019-09-03 09:44:22 +0200683 raise Exception("Invalid version '"
684 + version
685 + "'"
686 + (' ' + error_context) if len(error_context) > 0 else '')
Søren Gjesse4e5c6fe2019-11-05 17:17:43 +0100687 if components == 2:
Søren Gjesse705a3b12022-03-17 11:37:30 +0100688 return SemanticVersion(int(match.group(1)), int(match.group(2)), None, None)
689 elif components == 3 and not allowPrerelease:
Søren Gjesse4e5c6fe2019-11-05 17:17:43 +0100690 return SemanticVersion(
Søren Gjesse705a3b12022-03-17 11:37:30 +0100691 int(match.group(1)), int(match.group(2)), int(match.group(3)), None)
692 elif components == 3 and allowPrerelease:
693 return SemanticVersion(
694 int(match.group(1)), int(match.group(2)), int(match.group(3)), match.group('prerelease'))
Søren Gjesse4e5c6fe2019-11-05 17:17:43 +0100695 else:
696 raise Exception('Argument "components" must be 2 or 3')