blob: a4e825090676f6841bca982c214385c2a2e47236 [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 Adamsen5b5c6482024-12-18 10:37:46 +010020import historic_run
Christoffer Quist Adamsen65ef2982023-08-24 08:45:39 +020021from thread_utils import print_thread
Ian Zerny37097652019-04-11 13:13:27 +020022
Christoffer Quist Adamsen17879c12019-01-22 16:13:54 +010023ANDROID_JAR_DIR = 'third_party/android_jar/lib-v{api}'
24ANDROID_JAR = os.path.join(ANDROID_JAR_DIR, 'android.jar')
Ian Zerny3f54e222019-02-12 10:51:17 +010025TOOLS_DIR = defines.TOOLS_DIR
26REPO_ROOT = defines.REPO_ROOT
27THIRD_PARTY = defines.THIRD_PARTY
Christoffer Quist Adamsen4d9fc512022-08-11 19:59:44 +020028BUNDLETOOL_JAR_DIR = os.path.join(THIRD_PARTY, 'bundletool/bundletool-1.11.0')
29BUNDLETOOL_JAR = os.path.join(BUNDLETOOL_JAR_DIR, 'bundletool-all-1.11.0.jar')
Tamas Kenezfc34cd82017-07-13 12:43:57 +020030MEMORY_USE_TMP_FILE = 'memory_use.tmp'
Tamas Kenez02bff032017-07-18 12:13:58 +020031DEX_SEGMENTS_RESULT_PATTERN = re.compile('- ([^:]+): ([0-9]+)')
Rico Windaf9e8fb2023-10-10 09:25:26 +020032
Rico Windb65d75c2023-10-10 11:14:52 +020033DEPENDENCIES_DIR = os.path.join(THIRD_PARTY, 'dependencies')
34
Mads Ager12a56bc2017-11-27 11:51:25 +010035BUILD = os.path.join(REPO_ROOT, 'build')
Rico Wind9115b892024-11-06 08:18:52 +010036BUILD_JAVA_MAIN_DIR = os.path.join(REPO_ROOT, 'd8_r8', 'main', 'build',
37 'classes', 'java', 'main')
Mads Ager12a56bc2017-11-27 11:51:25 +010038LIBS = os.path.join(BUILD, 'libs')
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +020039CUSTOM_CONVERSION_DIR = os.path.join(THIRD_PARTY, 'openjdk',
40 'custom_conversion')
Mads Ager12a56bc2017-11-27 11:51:25 +010041GENERATED_LICENSE_DIR = os.path.join(BUILD, 'generatedLicense')
Mads Agera4911eb2017-11-22 13:19:36 +010042SRC_ROOT = os.path.join(REPO_ROOT, 'src', 'main', 'java')
Ian Zerny59dfa4c2019-10-25 10:34:36 +020043REPO_SOURCE = 'https://r8.googlesource.com/r8'
Søren Gjessedc9d8a22017-10-12 12:40:59 +020044
Rico Wind93755fb2023-10-09 13:29:29 +020045GRADLE_TASK_CLEAN_TEST = ':test:cleanTest'
46GRADLE_TASK_CONSOLIDATED_LICENSE = ':main:consolidatedLicense'
Christoffer Adamsen92e8c262025-03-13 13:31:23 +010047GRADLE_TASK_DOWNLOAD_DEPS = ':shared:downloadDeps'
Rico Wind93755fb2023-10-09 13:29:29 +020048GRADLE_TASK_KEEP_ANNO_JAR = ':keepanno:keepAnnoAnnotationsJar'
Søren Gjesse591455a2025-02-06 16:46:39 +010049GRADLE_TASK_KEEP_ANNO_LEGACY_JAR = ':keepanno:keepAnnoLegacyAnnotationsJar'
50GRADLE_TASK_KEEP_ANNO_ANDROIDX_JAR = ':keepanno:keepAnnoAndroidXAnnotationsJar'
Ian Zernya6af7772023-11-21 14:05:57 +010051GRADLE_TASK_KEEP_ANNO_DOC = ':keepanno:keepAnnoAnnotationsDoc'
Rico Wind9115b892024-11-06 08:18:52 +010052GRADLE_TASK_MAIN_COMPILE = ':main:compileJava'
Rico Wind93755fb2023-10-09 13:29:29 +020053GRADLE_TASK_R8 = ':main:r8WithRelocatedDeps'
Christoffer Quist Adamsen31237c32023-10-13 10:59:53 +020054GRADLE_TASK_R8LIB = ':test:assembleR8LibWithRelocatedDeps'
55GRADLE_TASK_R8LIB_NO_DEPS = ':test:assembleR8LibNoDeps'
Ian Zerny077a73f2023-10-31 09:05:47 +010056GRADLE_TASK_THREADING_MODULE_BLOCKING = ':main:threadingModuleBlockingJar'
57GRADLE_TASK_THREADING_MODULE_SINGLE_THREADED = ':main:threadingModuleSingleThreadedJar'
Christoffer Quist Adamsen31237c32023-10-13 10:59:53 +020058GRADLE_TASK_SOURCE_JAR = ':test:packageSources'
Rico Wind93755fb2023-10-09 13:29:29 +020059GRADLE_TASK_SWISS_ARMY_KNIFE = ':main:swissArmyKnife'
60GRADLE_TASK_TEST = ':test:test'
Søren Gjesse397f1a12023-10-13 13:22:31 +020061GRADLE_TASK_ALL_TESTS_WITH_APPLY_MAPPING_JAR = ':test:rewriteTestsForR8LibWithRelocatedDeps'
Rico Wind9365e942024-03-27 12:58:05 +010062GRADLE_TASK_TESTBASE_WITH_APPLY_MAPPING_JAR = ':test:rewriteTestBaseForR8LibWithRelocatedDeps'
Søren Gjesse397f1a12023-10-13 13:22:31 +020063GRADLE_TASK_TEST_DEPS_JAR = ':test:packageTestDeps'
Søren Gjesse1da57172024-07-31 11:10:37 +020064GRADLE_TASK_TEST_BASE_JAR = ':test:relocateTestBaseForR8LibWithRelocatedDeps'
Søren Gjessea28c4612023-11-01 14:55:27 +010065GRADLE_TASK_TEST_JAR = ':test:relocateTestsForR8LibWithRelocatedDeps'
Christoffer Adamsend58f0472024-06-04 14:28:12 +020066GRADLE_TASK_TEST_UNZIP_TESTBASE = ':test:unzipTestBase'
Rico Wind93755fb2023-10-09 13:29:29 +020067
Søren Gjessedc9d8a22017-10-12 12:40:59 +020068R8 = 'r8'
Tamas Kenez03ab76f2018-12-07 14:33:25 +010069R8LIB = 'r8lib'
Søren Gjessedc9d8a22017-10-12 12:40:59 +020070
Morten Krogh-Jespersen51db2b02020-11-11 12:49:26 +010071ALL_DEPS_JAR = os.path.join(LIBS, 'deps_all.jar')
Rico Wind74fab302017-10-02 07:25:33 +020072R8_JAR = os.path.join(LIBS, 'r8.jar')
Tamas Kenez03ab76f2018-12-07 14:33:25 +010073R8LIB_JAR = os.path.join(LIBS, 'r8lib.jar')
Rico Wind158ef9f2022-05-19 11:08:30 +020074R8LIB_MAP = '%s.map' % R8LIB_JAR
Mads Agerb10c07f2017-11-27 13:25:52 +010075R8_SRC_JAR = os.path.join(LIBS, 'r8-src.jar')
Tamas Kenez03ab76f2018-12-07 14:33:25 +010076R8LIB_EXCLUDE_DEPS_JAR = os.path.join(LIBS, 'r8lib-exclude-deps.jar')
Tamas Kenez180be092018-12-05 15:23:06 +010077R8_FULL_EXCLUDE_DEPS_JAR = os.path.join(LIBS, 'r8-full-exclude-deps.jar')
Christoffer Adamsene3b8b6d2024-06-12 13:07:49 +020078THREADING_MODULE_BLOCKING_JAR = os.path.join(LIBS,
79 'threading-module-blocking.jar')
80THREADING_MODULE_SINGLE_THREADED_JAR = os.path.join(
81 LIBS, 'threading-module-single-threaded.jar')
Ian Zerny161ff742022-01-20 12:39:40 +010082R8_TESTS_JAR = os.path.join(LIBS, 'r8tests.jar')
Rico Wind9365e942024-03-27 12:58:05 +010083R8_TESTBASE_JAR = os.path.join(LIBS, 'r8test_base.jar')
84R8LIB_TESTBASE_JAR = os.path.join(LIBS, 'r8libtestbase-cf.jar')
Ian Zerny161ff742022-01-20 12:39:40 +010085R8LIB_TESTS_JAR = os.path.join(LIBS, 'r8libtestdeps-cf.jar')
86R8_TESTS_DEPS_JAR = os.path.join(LIBS, 'test_deps_all.jar')
87R8LIB_TESTS_DEPS_JAR = R8_TESTS_DEPS_JAR
Rico Wind8fc8bfa2019-03-22 09:57:36 +010088MAVEN_ZIP_LIB = os.path.join(LIBS, 'r8lib.zip')
Clément Béra3718ad02023-09-05 14:12:48 +020089LIBRARY_DESUGAR_CONVERSIONS_LEGACY_ZIP = os.path.join(
90 CUSTOM_CONVERSION_DIR, 'library_desugar_conversions_legacy.jar')
91LIBRARY_DESUGAR_CONVERSIONS_ZIP = os.path.join(
92 CUSTOM_CONVERSION_DIR, 'library_desugar_conversions.jar')
Ian Zernyf13d18f2023-05-24 12:50:37 +020093KEEPANNO_ANNOTATIONS_JAR = os.path.join(LIBS, 'keepanno-annotations.jar')
Christoffer Adamsene3b8b6d2024-06-12 13:07:49 +020094KEEPANNO_ANNOTATIONS_DOC = os.path.join('d8_r8', 'keepanno', 'build', 'docs',
95 'javadoc')
Søren Gjesse591455a2025-02-06 16:46:39 +010096KEEPANNO_LEGACY_ANNOTATIONS_JAR = os.path.join(LIBS, 'keepanno-annotations-legacy.jar')
97KEEPANNO_ANDROIDX_ANNOTATIONS_JAR = os.path.join(LIBS, 'keepanno-annotations-androidx.jar')
Søren Gjesse17fc67d2019-12-04 14:50:17 +010098
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +020099DESUGAR_CONFIGURATION = os.path.join('src', 'library_desugar',
100 'desugar_jdk_libs.json')
101DESUGAR_IMPLEMENTATION = os.path.join('third_party', 'openjdk',
102 'desugar_jdk_libs',
103 'desugar_jdk_libs.jar')
Søren Gjesse705a3b12022-03-17 11:37:30 +0100104DESUGAR_CONFIGURATION_JDK11_LEGACY = os.path.join(
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200105 'src', 'library_desugar', 'jdk11', 'desugar_jdk_libs_legacy.json')
Søren Gjesse2b047692022-08-19 16:34:38 +0200106DESUGAR_CONFIGURATION_JDK11_MINIMAL = os.path.join(
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200107 'src', 'library_desugar', 'jdk11', 'desugar_jdk_libs_minimal.json')
108DESUGAR_CONFIGURATION_JDK11 = os.path.join('src', 'library_desugar', 'jdk11',
109 'desugar_jdk_libs.json')
110DESUGAR_CONFIGURATION_JDK11_NIO = os.path.join('src', 'library_desugar',
111 'jdk11',
112 'desugar_jdk_libs_nio.json')
113DESUGAR_IMPLEMENTATION_JDK11 = os.path.join('third_party', 'openjdk',
114 'desugar_jdk_libs_11',
115 'desugar_jdk_libs.jar')
Søren Gjesse6e5e5842019-09-03 08:48:30 +0200116DESUGAR_CONFIGURATION_MAVEN_ZIP = os.path.join(
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200117 LIBS, 'desugar_jdk_libs_configuration.zip')
Søren Gjessee18fa6e2022-06-24 15:14:53 +0200118DESUGAR_CONFIGURATION_JDK11_LEGACY_MAVEN_ZIP = os.path.join(
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200119 LIBS, 'desugar_jdk_libs_configuration_jdk11_legacy.zip')
Søren Gjesse2b047692022-08-19 16:34:38 +0200120DESUGAR_CONFIGURATION_JDK11_MINIMAL_MAVEN_ZIP = os.path.join(
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200121 LIBS, 'desugar_jdk_libs_configuration_jdk11_minimal.zip')
Søren Gjesse2b047692022-08-19 16:34:38 +0200122DESUGAR_CONFIGURATION_JDK11_MAVEN_ZIP = os.path.join(
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200123 LIBS, 'desugar_jdk_libs_configuration_jdk11.zip')
Søren Gjesse2b047692022-08-19 16:34:38 +0200124DESUGAR_CONFIGURATION_JDK11_NIO_MAVEN_ZIP = os.path.join(
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200125 LIBS, 'desugar_jdk_libs_configuration_jdk11_nio.zip')
Mads Ager12a56bc2017-11-27 11:51:25 +0100126GENERATED_LICENSE = os.path.join(GENERATED_LICENSE_DIR, 'LICENSE')
Mathias Rav3fb4a3a2018-05-29 15:41:36 +0200127RT_JAR = os.path.join(REPO_ROOT, 'third_party/openjdk/openjdk-rt-1.8/rt.jar')
Mathias Ravb46dc002018-06-06 09:37:11 +0200128R8LIB_KEEP_RULES = os.path.join(REPO_ROOT, 'src/main/keep.txt')
Morten Krogh-Jespersen480784d2019-02-05 08:10:46 +0100129CF_SEGMENTS_TOOL = os.path.join(THIRD_PARTY, 'cf_segments')
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100130PINNED_R8_JAR = os.path.join(REPO_ROOT, 'third_party/r8/r8.jar')
131PINNED_PGR8_JAR = os.path.join(REPO_ROOT, 'third_party/r8/r8-pg6.0.1.jar')
Rico Wind8bd693f2023-10-13 11:29:32 +0200132
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +0100133OPENSOURCE_DUMPS_DIR = os.path.join(THIRD_PARTY, 'opensource-apps')
Morten Krogh-Jespersen86222742021-03-02 11:13:33 +0100134INTERNAL_DUMPS_DIR = os.path.join(THIRD_PARTY, 'internal-apps')
Søren Gjesse1c115b52019-08-14 12:43:57 +0200135BAZEL_SHA_FILE = os.path.join(THIRD_PARTY, 'bazel.tar.gz.sha1')
136BAZEL_TOOL = os.path.join(THIRD_PARTY, 'bazel')
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200137JAVA8_SHA_FILE = os.path.join(THIRD_PARTY, 'openjdk', 'jdk8',
138 'linux-x86.tar.gz.sha1')
139JAVA11_SHA_FILE = os.path.join(THIRD_PARTY, 'openjdk', 'jdk-11',
140 'linux.tar.gz.sha1')
141DESUGAR_JDK_LIBS_11_SHA_FILE = os.path.join(THIRD_PARTY, 'openjdk',
142 'desugar_jdk_libs_11.tar.gz.sha1')
143IGNORE_WARNINGS_RULES = os.path.join(REPO_ROOT, 'src', 'test',
144 'ignorewarnings.rules')
Morten Krogh-Jespersen220e5702019-02-27 12:57:01 +0100145ANDROID_HOME_ENVIROMENT_NAME = "ANDROID_HOME"
146ANDROID_TOOLS_VERSION_ENVIRONMENT_NAME = "ANDROID_TOOLS_VERSION"
Morten Krogh-Jespersenc8efedd2019-01-28 11:36:17 +0100147USER_HOME = os.path.expanduser('~')
Morten Krogh-Jespersen220e5702019-02-27 12:57:01 +0100148
Morten Krogh-Jespersen0981b722019-10-09 10:00:33 +0200149R8_TEST_RESULTS_BUCKET = 'r8-test-results'
Rico Wind635b2de2022-04-25 10:35:14 +0200150R8_INTERNAL_TEST_RESULTS_BUCKET = 'r8-internal-test-results'
Morten Krogh-Jespersen0981b722019-10-09 10:00:33 +0200151
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200152
Morten Krogh-Jespersen0981b722019-10-09 10:00:33 +0200153def archive_file(name, gs_dir, src_file):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200154 gs_file = '%s/%s' % (gs_dir, name)
155 upload_file_to_cloud_storage(src_file, gs_file)
156
Morten Krogh-Jespersen0981b722019-10-09 10:00:33 +0200157
158def archive_value(name, gs_dir, value):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200159 with TempDir() as temp:
160 temparchive = os.path.join(temp, name)
161 with open(temparchive, 'w') as f:
162 f.write(str(value))
163 archive_file(name, gs_dir, temparchive)
164
Morten Krogh-Jespersen0981b722019-10-09 10:00:33 +0200165
Christoffer Quist Adamsen4d38d032021-04-20 12:31:31 +0200166def find_cloud_storage_file_from_options(name, options, orElse=None):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200167 # Import archive on-demand since archive depends on utils.
168 from archive import GetUploadDestination
169 hash_or_version = find_hash_or_version_from_options(options)
170 if not hash_or_version:
171 return orElse
172 is_hash = options.commit_hash is not None
173 download_path = GetUploadDestination(hash_or_version, name, is_hash)
174 if file_exists_on_cloud_storage(download_path):
175 out = tempfile.NamedTemporaryFile().name
176 download_file_from_cloud_storage(download_path, out)
177 return out
178 else:
179 raise Exception('Could not find file {} from hash/version: {}.'.format(
180 name, hash_or_version))
181
Christoffer Quist Adamsen4d38d032021-04-20 12:31:31 +0200182
183def find_r8_jar_from_options(options):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200184 return find_cloud_storage_file_from_options('r8.jar', options)
Christoffer Quist Adamsen4d38d032021-04-20 12:31:31 +0200185
Christoffer Quist Adamsen4d38d032021-04-20 12:31:31 +0200186
187def find_hash_or_version_from_options(options):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200188 if options.tag:
189 return find_hash_or_version_from_tag(options.tag)
190 else:
191 return options.commit_hash or options.version
192
Christoffer Quist Adamsen4d38d032021-04-20 12:31:31 +0200193
194def find_hash_or_version_from_tag(tag_or_hash):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200195 info = subprocess.check_output(
196 ['git', 'show', tag_or_hash, '-s',
197 '--format=oneline']).decode('utf-8').splitlines()[-1].split()
198 # The info should be on the following form [hash,"Version",version]
199 if len(info) == 3 and len(info[0]) == 40 and info[1] == "Version":
200 return info[2]
201 return None
202
Christoffer Quist Adamsen4d38d032021-04-20 12:31:31 +0200203
Morten Krogh-Jespersen220e5702019-02-27 12:57:01 +0100204def getAndroidHome():
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200205 return os.environ.get(ANDROID_HOME_ENVIROMENT_NAME,
206 os.path.join(USER_HOME, 'Android', 'Sdk'))
207
Morten Krogh-Jespersen220e5702019-02-27 12:57:01 +0100208
209def getAndroidBuildTools():
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200210 if ANDROID_TOOLS_VERSION_ENVIRONMENT_NAME in os.environ:
211 version = os.environ.get(ANDROID_TOOLS_VERSION_ENVIRONMENT_NAME)
212 build_tools_dir = os.path.join(getAndroidHome(), 'build-tools', version)
213 assert os.path.exists(build_tools_dir)
Christoffer Quist Adamsen8c803b42022-05-31 10:36:17 +0200214 return build_tools_dir
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200215 else:
Christoffer Adamsen500a6522024-02-27 12:27:29 +0000216 versions = ['34.0.0', '33.0.1', '32.0.0']
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200217 for version in versions:
218 build_tools_dir = os.path.join(getAndroidHome(), 'build-tools',
219 version)
220 if os.path.exists(build_tools_dir):
221 return build_tools_dir
222 raise Exception('Unable to find Android build-tools')
223
Morten Krogh-Jespersenc8efedd2019-01-28 11:36:17 +0100224
Christoffer Quist Adamsen5c9ded12021-01-14 14:29:37 +0100225def is_python3():
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200226 return sys.version_info.major == 3
227
Christoffer Quist Adamsen5c9ded12021-01-14 14:29:37 +0100228
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100229def Print(s, quiet=False):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200230 if quiet:
231 return
232 print(s)
233
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100234
235def Warn(message):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200236 CRED = '\033[91m'
237 CEND = '\033[0m'
238 print(CRED + message + CEND)
239
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100240
Christoffer Quist Adamsen65ef2982023-08-24 08:45:39 +0200241def PrintCmd(cmd, env=None, quiet=False, worker_id=None):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200242 if quiet:
243 return
244 if type(cmd) is list:
245 cmd = ' '.join(cmd)
246 if env:
247 env = ' '.join(['{}=\"{}\"'.format(x, y) for x, y in env.iteritems()])
248 print_thread('Running: {} {}'.format(env, cmd), worker_id)
249 else:
250 print_thread('Running: {}'.format(cmd), worker_id)
251 # I know this will hit os on windows eventually if we don't do this.
252 sys.stdout.flush()
253
Mads Ager418d1ca2017-05-22 09:35:49 +0200254
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100255class ProgressLogger(object):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200256 CLEAR_LINE = '\033[K'
257 UP = '\033[F'
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100258
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200259 def __init__(self, quiet=False):
260 self._count = 0
261 self._has_printed = False
262 self._quiet = quiet
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100263
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200264 def log(self, text):
265 if len(text.strip()) == 0:
266 return
267 if self._quiet:
268 if self._has_printed:
269 sys.stdout.write(ProgressLogger.UP + ProgressLogger.CLEAR_LINE)
270 if len(text) > 140:
271 text = text[0:140] + '...'
272 print(text)
273 self._has_printed = True
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100274
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200275 def done(self):
276 if self._quiet and self._has_printed:
277 sys.stdout.write(ProgressLogger.UP + ProgressLogger.CLEAR_LINE)
278 print('')
279 sys.stdout.write(ProgressLogger.UP)
280
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100281
Morten Krogh-Jespersen7cdd3a72019-03-13 14:58:25 +0100282def RunCmd(cmd, env_vars=None, quiet=False, fail=True, logging=True):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200283 PrintCmd(cmd, env=env_vars, quiet=quiet)
284 env = os.environ.copy()
285 if env_vars:
286 env.update(env_vars)
287 process = subprocess.Popen(cmd,
288 env=env,
289 stdout=subprocess.PIPE,
290 stderr=subprocess.STDOUT)
291 stdout = []
292 logger = ProgressLogger(quiet=quiet) if logging else None
293 failed = False
294 while True:
295 line = process.stdout.readline().decode('utf-8')
296 if line != '':
297 stripped = line.rstrip()
298 stdout.append(stripped)
299 if logger:
300 logger.log(stripped)
301 # TODO(christofferqa): r8 should fail with non-zero exit code.
302 if ('AssertionError:' in stripped or
303 'CompilationError:' in stripped or
304 'CompilationFailedException:' in stripped or
305 'Compilation failed' in stripped or
306 'FAILURE:' in stripped or
307 'org.gradle.api.ProjectConfigurationException' in stripped
308 or 'BUILD FAILED' in stripped):
309 failed = True
310 else:
311 if logger:
312 logger.done()
313 exit_code = process.poll()
314 if exit_code or failed:
315 for line in stdout:
316 Warn(line)
317 if fail:
318 raise subprocess.CalledProcessError(
319 exit_code or -1, cmd, output='\n'.join(stdout))
320 return stdout
321
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100322
Rico Windf80f5a22017-06-16 09:15:57 +0200323def IsWindows():
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200324 return defines.IsWindows()
325
Ian Zerny5fffb0a2019-02-11 13:54:22 +0100326
Ian Zerny5fffb0a2019-02-11 13:54:22 +0100327def EnsureDepFromGoogleCloudStorage(dep, tgz, sha1, msg):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200328 if (not os.path.exists(dep) or not os.path.exists(tgz) or
329 os.path.getmtime(tgz) < os.path.getmtime(sha1)):
330 DownloadFromGoogleCloudStorage(sha1)
331 # Update the mtime of the tar file to make sure we do not run again unless
332 # there is an update.
333 os.utime(tgz, None)
334 else:
335 print('Ensure cloud dependency:', msg, 'present')
336
Rico Windf80f5a22017-06-16 09:15:57 +0200337
Jean-Marie Henaffe4e36d12018-04-05 10:33:50 +0200338def DownloadFromX20(sha1_file):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200339 download_script = os.path.join(REPO_ROOT, 'tools', 'download_from_x20.py')
340 cmd = [download_script, sha1_file]
Rico Wind59593922021-03-03 09:12:36 +0100341 PrintCmd(cmd)
342 subprocess.check_call(cmd)
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200343
344
345def DownloadFromGoogleCloudStorage(sha1_file,
Rico Wind5e1580a2024-07-01 08:32:39 +0000346 bucket='r8-deps',
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200347 auth=False,
348 quiet=False):
349 suffix = '.bat' if IsWindows() else ''
350 download_script = 'download_from_google_storage%s' % suffix
351 cmd = [download_script]
352 if not auth:
353 cmd.append('-n')
354 cmd.extend(['-b', bucket, '-u', '-s', sha1_file])
355 if not quiet:
356 PrintCmd(cmd)
357 subprocess.check_call(cmd)
358 else:
359 subprocess.check_output(cmd)
360
Mads Ager418d1ca2017-05-22 09:35:49 +0200361
Christoffer Adamsenc09ba6f2024-06-12 18:48:36 +0200362def get_nth_sha1_from_revision(n, revision):
363 result = subprocess.check_output([
364 'git', 'log', revision, f'--skip={n}', '--max-count=1',
365 '--pretty=format:%H'
366 ]).decode('utf-8')
Christoffer Adamsen30283712024-06-12 13:08:14 +0200367 return result.strip()
368
369
Mads Ager418d1ca2017-05-22 09:35:49 +0200370def get_sha1(filename):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200371 sha1 = hashlib.sha1()
372 with open(filename, 'rb') as f:
373 while True:
374 chunk = f.read(1024 * 1024)
375 if not chunk:
376 break
377 sha1.update(chunk)
378 return sha1.hexdigest()
379
Mads Ager418d1ca2017-05-22 09:35:49 +0200380
Christoffer Adamsenc09ba6f2024-06-12 18:48:36 +0200381def get_sha1_from_revision(revision):
382 cmd = ['git', 'rev-parse', revision]
383 PrintCmd(cmd)
384 with ChangedWorkingDirectory(REPO_ROOT):
385 return subprocess.check_output(cmd).decode('utf-8').strip()
386
387
Ian Zernyc2de7b72023-09-06 20:52:16 +0200388def get_HEAD_branch():
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200389 result = subprocess.check_output(
390 ['git', 'rev-parse', '--abbrev-ref', 'HEAD']).decode('utf-8')
391 return result.strip()
392
Ian Zernyc2de7b72023-09-06 20:52:16 +0200393
Christoffer Adamsen5b5c6482024-12-18 10:37:46 +0100394def get_HEAD_commit():
395 return historic_run.git_commit_from_hash(get_HEAD_sha1())
396
397
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +0200398def get_HEAD_sha1():
Christoffer Adamsenc09ba6f2024-06-12 18:48:36 +0200399 return get_sha1_from_revision('HEAD')
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200400
Morten Krogh-Jespersene0ce6a32019-02-07 11:44:45 +0100401
Ian Zerny9f0345d2023-09-07 11:15:00 +0200402def get_HEAD_diff_stat():
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200403 return subprocess.check_output(['git', 'diff', '--stat']).decode('utf-8')
404
Ian Zerny9f0345d2023-09-07 11:15:00 +0200405
Tamas Kenez971eec62017-05-24 11:08:40 +0200406def makedirs_if_needed(path):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200407 try:
408 os.makedirs(path)
409 except OSError:
410 if not os.path.isdir(path):
411 raise
412
Tamas Kenez971eec62017-05-24 11:08:40 +0200413
Rico Windef7420c2021-10-14 13:16:01 +0200414def get_gsutil():
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200415 return 'gsutil.py' if os.name != 'nt' else 'gsutil.py.bat'
416
Rico Windef7420c2021-10-14 13:16:01 +0200417
Christoffer Adamsenb43ff592024-06-12 18:49:01 +0200418def upload_file_to_cloud_storage(source, destination, header=None):
419 cmd = [get_gsutil()]
420 if header:
421 cmd.extend(['-h', header])
422 cmd.extend(['cp', source, destination])
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200423 PrintCmd(cmd)
424 subprocess.check_call(cmd)
425
Christoffer Adamsene3b8b6d2024-06-12 13:07:49 +0200426
Ian Zerny566046e2024-01-04 14:24:56 +0100427def check_dir_args(source, destination):
428 # We require that the dirname of the paths coincide, e.g., src/dirname and dst/dirname
429 # The target is then stripped so the upload command will be: cp -R src/dirname dst/
430 (destination_parent, destination_file) = os.path.split(destination)
431 if os.path.basename(source) != destination_file:
432 raise Exception(
433 'Attempt to upload directory with non-matching directory name: ' +
434 f'{source} and {destination}')
435 if len(destination_parent.strip()) == 0:
436 raise Exception(
Christoffer Adamsene3b8b6d2024-06-12 13:07:49 +0200437 'Attempt to upload directory to empty destination directory: ' +
438 destination)
Ian Zerny566046e2024-01-04 14:24:56 +0100439 return destination_parent
440
Christoffer Adamsene3b8b6d2024-06-12 13:07:49 +0200441
Ian Zernya6af7772023-11-21 14:05:57 +0100442def upload_directory_to_cloud_storage(source, destination, parallel=True):
Ian Zerny566046e2024-01-04 14:24:56 +0100443 destination_parent = check_dir_args(source, destination)
Ian Zernya6af7772023-11-21 14:05:57 +0100444 cmd = [get_gsutil()]
445 if parallel:
446 cmd += ['-m']
447 cmd += ['cp', '-R']
Ian Zerny566046e2024-01-04 14:24:56 +0100448 cmd += [source, destination_parent + '/']
449 PrintCmd(cmd)
450 subprocess.check_call(cmd)
451
Christoffer Adamsene3b8b6d2024-06-12 13:07:49 +0200452
Ian Zerny566046e2024-01-04 14:24:56 +0100453def rsync_directory_to_cloud_storage(source, destination, parallel=True):
454 check_dir_args(source, destination)
455 cmd = [get_gsutil()]
456 if parallel:
457 cmd += ['-m']
458 cmd += ['rsync', '-R']
Ian Zernya6af7772023-11-21 14:05:57 +0100459 cmd += [source, destination]
460 PrintCmd(cmd)
461 subprocess.check_call(cmd)
Rico Windb4621c12017-08-28 12:48:53 +0200462
Christoffer Adamsene3b8b6d2024-06-12 13:07:49 +0200463
Rico Wind139eece2018-09-25 09:42:09 +0200464def delete_file_from_cloud_storage(destination):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200465 cmd = [get_gsutil(), 'rm', destination]
466 PrintCmd(cmd)
467 subprocess.check_call(cmd)
468
Rico Wind139eece2018-09-25 09:42:09 +0200469
Rico Wind4fd2dda2018-09-26 17:41:45 +0200470def ls_files_on_cloud_storage(destination):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200471 cmd = [get_gsutil(), 'ls', destination]
472 PrintCmd(cmd)
473 return subprocess.check_output(cmd).decode('utf-8')
474
Rico Wind4fd2dda2018-09-26 17:41:45 +0200475
Rico Wind139eece2018-09-25 09:42:09 +0200476def cat_file_on_cloud_storage(destination, ignore_errors=False):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200477 cmd = [get_gsutil(), 'cat', destination]
478 PrintCmd(cmd)
479 try:
480 return subprocess.check_output(cmd).decode('utf-8').strip()
481 except subprocess.CalledProcessError as e:
482 if ignore_errors:
483 return ''
484 else:
485 raise e
486
Rico Wind139eece2018-09-25 09:42:09 +0200487
488def file_exists_on_cloud_storage(destination):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200489 cmd = [get_gsutil(), 'ls', destination]
490 PrintCmd(cmd)
491 return subprocess.call(cmd) == 0
492
Rico Wind139eece2018-09-25 09:42:09 +0200493
Christoffer Adamsenc09ba6f2024-06-12 18:48:36 +0200494def download_file_from_cloud_storage(source,
495 destination,
496 concurrent=False,
497 flags=None,
498 quiet=False):
499 cmd = [get_gsutil()]
500 if concurrent:
501 cmd.append('-m')
502 cmd.append('cp')
503 if flags:
504 cmd.extend(flags)
505 cmd.extend([source, destination])
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200506 PrintCmd(cmd, quiet=quiet)
507 subprocess.check_call(cmd)
508
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +0200509
Morten Krogh-Jespersen220e5702019-02-27 12:57:01 +0100510def create_archive(name, sources=None):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200511 if not sources:
512 sources = [name]
513 tarname = '%s.tar.gz' % name
514 with tarfile.open(tarname, 'w:gz') as tar:
515 for source in sources:
516 tar.add(source)
517 return tarname
518
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +0200519
520def extract_dir(filename):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200521 return filename[0:len(filename) - len('.tar.gz')]
522
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +0200523
524def unpack_archive(filename):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200525 dest_dir = extract_dir(filename)
526 if os.path.exists(dest_dir):
527 print('Deleting existing dir %s' % dest_dir)
528 shutil.rmtree(dest_dir)
529 dirname = os.path.dirname(os.path.abspath(filename))
530 with tarfile.open(filename, 'r:gz') as tar:
531 tar.extractall(path=dirname)
532
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +0200533
Morten Krogh-Jespersenec3047b2020-08-18 13:09:06 +0200534def check_gcert():
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200535 status = subprocess.call(['gcertstatus'])
536 if status != 0:
537 subprocess.check_call(['gcert'])
538
Morten Krogh-Jespersen54090862019-02-19 11:31:10 +0100539
Rico Wind1a29c4f2018-01-25 08:43:08 +0100540# Note that gcs is eventually consistent with regards to list operations.
541# This is not a problem in our case, but don't ever use this method
542# for synchronization.
543def cloud_storage_exists(destination):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200544 cmd = [get_gsutil(), 'ls', destination]
545 PrintCmd(cmd)
546 exit_code = subprocess.call(cmd)
547 return exit_code == 0
548
Rico Wind1a29c4f2018-01-25 08:43:08 +0100549
Mads Ager418d1ca2017-05-22 09:35:49 +0200550class TempDir(object):
Mads Ager418d1ca2017-05-22 09:35:49 +0200551
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200552 def __init__(self, prefix='', delete=True):
553 self._temp_dir = None
554 self._prefix = prefix
555 self._delete = delete
Mads Ager418d1ca2017-05-22 09:35:49 +0200556
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200557 def __enter__(self):
558 self._temp_dir = tempfile.mkdtemp(self._prefix)
559 return self._temp_dir
560
561 def __exit__(self, *_):
562 if self._delete:
563 shutil.rmtree(self._temp_dir, ignore_errors=True)
564
Mads Ager418d1ca2017-05-22 09:35:49 +0200565
566class ChangedWorkingDirectory(object):
Mads Ager418d1ca2017-05-22 09:35:49 +0200567
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200568 def __init__(self, working_directory, quiet=False):
569 self._quiet = quiet
570 self._working_directory = working_directory
Mads Ager418d1ca2017-05-22 09:35:49 +0200571
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200572 def __enter__(self):
573 self._old_cwd = os.getcwd()
574 if not self._quiet:
575 print('Enter directory:', self._working_directory)
576 os.chdir(self._working_directory)
577
578 def __exit__(self, *_):
579 if not self._quiet:
580 print('Enter directory:', self._old_cwd)
581 os.chdir(self._old_cwd)
582
Tamas Kenez82efeb52017-06-12 13:56:22 +0200583
584# Reading Android CTS test_result.xml
585
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200586
Tamas Kenez82efeb52017-06-12 13:56:22 +0200587class CtsModule(object):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200588
589 def __init__(self, module_name):
590 self.name = module_name
591
Tamas Kenez82efeb52017-06-12 13:56:22 +0200592
593class CtsTestCase(object):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200594
595 def __init__(self, test_case_name):
596 self.name = test_case_name
597
Tamas Kenez82efeb52017-06-12 13:56:22 +0200598
599class CtsTest(object):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200600
601 def __init__(self, test_name, outcome):
602 self.name = test_name
603 self.outcome = outcome
604
Tamas Kenez82efeb52017-06-12 13:56:22 +0200605
606# Generator yielding CtsModule, CtsTestCase or CtsTest from
607# reading through a CTS test_result.xml file.
608def read_cts_test_result(file_xml):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200609 re_module = re.compile('<Module name="([^"]*)"')
610 re_test_case = re.compile('<TestCase name="([^"]*)"')
611 re_test = re.compile('<Test result="(pass|fail)" name="([^"]*)"')
612 with open(file_xml) as f:
613 for line in f:
614 m = re_module.search(line)
615 if m:
616 yield CtsModule(m.groups()[0])
617 continue
618 m = re_test_case.search(line)
619 if m:
620 yield CtsTestCase(m.groups()[0])
621 continue
622 m = re_test.search(line)
623 if m:
624 outcome = m.groups()[0]
625 assert outcome in ['fail', 'pass']
626 yield CtsTest(m.groups()[1], outcome == 'pass')
627
Tamas Kenezfc34cd82017-07-13 12:43:57 +0200628
629def grep_memoryuse(logfile):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200630 re_vmhwm = re.compile('^VmHWM:[ \t]*([0-9]+)[ \t]*([a-zA-Z]*)')
631 result = None
632 with open(logfile) as f:
633 for line in f:
634 m = re_vmhwm.search(line)
635 if m:
636 groups = m.groups()
637 s = len(groups)
638 if s >= 1:
639 result = int(groups[0])
640 if s >= 2:
641 unit = groups[1]
642 if unit == 'kB':
643 result *= 1024
644 elif unit != '':
645 raise Exception(
646 'Unrecognized unit in memory usage log: {}'.
647 format(unit))
648 if result is None:
649 raise Exception('No memory usage found in log: {}'.format(logfile))
650 return result
651
Tamas Kenez02bff032017-07-18 12:13:58 +0200652
653# Return a dictionary: {segment_name -> segments_size}
654def getDexSegmentSizes(dex_files):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200655 assert len(dex_files) > 0
656 cmd = [jdk.GetJavaExecutable(), '-jar', R8_JAR, 'dexsegments']
657 cmd.extend(dex_files)
658 PrintCmd(cmd)
659 output = subprocess.check_output(cmd).decode('utf-8')
Tamas Kenez02bff032017-07-18 12:13:58 +0200660
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200661 matches = DEX_SEGMENTS_RESULT_PATTERN.findall(output)
Tamas Kenez02bff032017-07-18 12:13:58 +0200662
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200663 if matches is None or len(matches) == 0:
664 raise Exception('DexSegments failed to return any output for' \
665 ' these files: {}'.format(dex_files))
Tamas Kenez02bff032017-07-18 12:13:58 +0200666
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200667 result = {}
Tamas Kenez02bff032017-07-18 12:13:58 +0200668
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200669 for match in matches:
670 result[match[0]] = int(match[1])
Tamas Kenez02bff032017-07-18 12:13:58 +0200671
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200672 return result
673
Tamas Kenez02bff032017-07-18 12:13:58 +0200674
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100675# Return a dictionary: {segment_name -> segments_size}
676def getCfSegmentSizes(cfFile):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200677 cmd = [
678 jdk.GetJavaExecutable(), '-cp', CF_SEGMENTS_TOOL,
679 'com.android.tools.r8.cf_segments.MeasureLib', cfFile
680 ]
681 PrintCmd(cmd)
682 output = subprocess.check_output(cmd).decode('utf-8')
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100683
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200684 matches = DEX_SEGMENTS_RESULT_PATTERN.findall(output)
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100685
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200686 if matches is None or len(matches) == 0:
687 raise Exception('CfSegments failed to return any output for' \
688 ' the file: ' + cfFile)
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100689
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200690 result = {}
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100691
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200692 for match in matches:
693 result[match[0]] = int(match[1])
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100694
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200695 return result
696
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100697
Søren Gjesse1c115b52019-08-14 12:43:57 +0200698def get_maven_path(artifact, version):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200699 return os.path.join('com', 'android', 'tools', artifact, version)
700
Rico Windc0b16382018-05-17 13:23:43 +0200701
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100702def print_cfsegments(prefix, cf_files):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200703 for cf_file in cf_files:
704 for segment_name, size in getCfSegmentSizes(cf_file).items():
705 print('{}-{}(CodeSize): {}'.format(prefix, segment_name, size))
706
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100707
Christoffer Quist Adamsenbe6661d2023-08-24 11:01:12 +0200708def print_dexsegments(prefix, dex_files, worker_id=None):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200709 for segment_name, size in getDexSegmentSizes(dex_files).items():
710 print_thread('{}-{}(CodeSize): {}'.format(prefix, segment_name, size),
711 worker_id)
712
Tamas Kenez2cf47cf2017-07-25 10:22:52 +0200713
Mads Agerbc7b2ce2018-02-05 11:28:47 +0100714# Ensure that we are not benchmarking with a google jvm.
Tamas Kenez2cf47cf2017-07-25 10:22:52 +0200715def check_java_version():
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200716 cmd = [jdk.GetJavaExecutable(), '-version']
717 output = subprocess.check_output(cmd,
718 stderr=subprocess.STDOUT).decode('utf-8')
719 m = re.search('openjdk version "([^"]*)"', output)
720 if m is None:
721 raise Exception("Can't check java version: no version string in output"
722 " of 'java -version': '{}'".format(output))
723 version = m.groups(0)[0]
724 m = re.search('google', version)
725 if m is not None:
726 raise Exception("Do not use google JVM for benchmarking: " + version)
727
Søren Gjesse03fa1162025-03-10 12:03:05 +0100728def api_str(api_level_major, api_level_minor):
729 api = str(api_level_major)
730 if api_level_minor > 0:
731 api = api + '.' + str(api_level_minor)
732 return api
Tamas Kenez0cad51c2017-08-21 14:42:01 +0200733
Søren Gjesse03fa1162025-03-10 12:03:05 +0100734def get_android_jar_dir(api_level_major, api_level_minor):
735 return os.path.join(
736 REPO_ROOT,
737 ANDROID_JAR_DIR.format(api=api_str(api_level_major, api_level_minor)))
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200738
Christoffer Quist Adamsen17879c12019-01-22 16:13:54 +0100739
Søren Gjesse03fa1162025-03-10 12:03:05 +0100740def get_android_jar(api_level_major, api_level_minor):
741 return os.path.join(
742 REPO_ROOT,
743 ANDROID_JAR.format(api=api_str(api_level_major, api_level_minor)))
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200744
Rico Windda6836e2018-12-07 12:32:03 +0100745
Rico Windfaaac012019-02-25 11:24:05 +0100746def is_bot():
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200747 return 'SWARMING_BOT_ID' in os.environ
748
Morten Krogh-Jespersen16e925d2019-01-25 14:40:38 +0100749
750def uncompressed_size(path):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200751 return sum(z.file_size for z in zipfile.ZipFile(path).infolist())
752
Morten Krogh-Jespersen0de13732019-03-01 08:56:39 +0100753
Søren Gjesse2b047692022-08-19 16:34:38 +0200754def desugar_configuration_name_and_version(configuration, is_for_maven):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200755 name = 'desugar_jdk_libs_configuration'
756 with open(configuration, 'r') as f:
757 configuration_json = json.loads(f.read())
758 configuration_format_version = \
759 configuration_json.get('configuration_format_version')
760 if (not configuration_format_version):
761 raise Exception('No "configuration_format_version" found in ' +
762 configuration)
763 if (configuration_format_version != 3 and
764 configuration_format_version != 5 and
Clément Béra43b5cf02023-11-06 14:14:52 +0100765 configuration_format_version != (200 if is_for_maven else 101)):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200766 raise Exception(
767 'Unsupported "configuration_format_version" "%s" found in %s' %
768 (configuration_format_version, configuration))
769 version = configuration_json.get('version')
770 if not version:
Clément Béra43b5cf02023-11-06 14:14:52 +0100771 if configuration_format_version == (200 if is_for_maven else 101):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200772 identifier = configuration_json.get('identifier')
773 if not identifier:
774 raise Exception('No "identifier" found in ' + configuration)
775 identifier_split = identifier.split(':')
776 if (len(identifier_split) != 3):
777 raise Exception('Invalid "identifier" found in ' +
778 configuration)
779 if (identifier_split[0] != 'com.tools.android'):
780 raise Exception('Invalid "identifier" found in ' +
781 configuration)
782 if not identifier_split[1].startswith(
783 'desugar_jdk_libs_configuration'):
784 raise Exception('Invalid "identifier" found in ' +
785 configuration)
786 name = identifier_split[1]
787 version = identifier_split[2]
788 else:
789 raise Exception('No "version" found in ' + configuration)
790 else:
Clément Béra43b5cf02023-11-06 14:14:52 +0100791 if configuration_format_version == (200 if is_for_maven else 101):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200792 raise Exception('No "version" expected in ' + configuration)
793 # Disallow prerelease, as older R8 versions cannot parse it causing hard to
794 # understand errors.
795 check_basic_semver_version(version,
796 'in ' + configuration,
797 allowPrerelease=False)
798 return (name, version)
799
Søren Gjesse1e171532019-09-03 09:44:22 +0200800
Søren Gjesse4e5c6fe2019-11-05 17:17:43 +0100801class SemanticVersion:
Søren Gjesse4e5c6fe2019-11-05 17:17:43 +0100802
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200803 def __init__(self, major, minor, patch, prerelease):
804 self.major = major
805 self.minor = minor
806 self.patch = patch
807 self.prerelease = prerelease
808 # Build metadata currently not suppported
809
810 def larger_than(self, other):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200811 if self.major > other.major:
812 return True
813 if self.major == other.major and self.minor > other.minor:
814 return True
815 if self.patch:
816 return (self.major == other.major and self.minor == other.minor and
817 self.patch > other.patch)
Søren Gjesse749a0be2023-10-26 14:07:18 +0200818 if self.prerelease:
819 if other.prerelease:
820 return self.prerelease > other.prerelease
821 else:
822 return False
823
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200824 else:
825 return False
Søren Gjesse4e5c6fe2019-11-05 17:17:43 +0100826
827
Søren Gjesse705a3b12022-03-17 11:37:30 +0100828# Check that the passed string is formatted as a basic semver version (x.y.z or x.y.z-prerelease
829# depending on the value of allowPrerelease).
830# See https://semver.org/. The regexp parts used are not all complient with what is suggested
831# on https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string.
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200832def check_basic_semver_version(version,
833 error_context='',
834 components=3,
835 allowPrerelease=False):
Søren Gjesse4e5c6fe2019-11-05 17:17:43 +0100836 regexp = '^'
837 for x in range(components):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200838 regexp += '([0-9]+)'
839 if x < components - 1:
840 regexp += '\\.'
Søren Gjesse705a3b12022-03-17 11:37:30 +0100841 if allowPrerelease:
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200842 # This part is from
843 # https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string
844 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 +0100845 regexp += '$'
846 reg = re.compile(regexp)
847 match = reg.match(version)
848 if not match:
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200849 raise Exception("Invalid version '" + version + "'" +
850 (' ' + error_context) if len(error_context) > 0 else '')
Søren Gjesse4e5c6fe2019-11-05 17:17:43 +0100851 if components == 2:
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200852 return SemanticVersion(int(match.group(1)), int(match.group(2)), None,
853 None)
Søren Gjesse705a3b12022-03-17 11:37:30 +0100854 elif components == 3 and not allowPrerelease:
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200855 return SemanticVersion(int(match.group(1)), int(match.group(2)),
856 int(match.group(3)), None)
Søren Gjesse705a3b12022-03-17 11:37:30 +0100857 elif components == 3 and allowPrerelease:
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200858 return SemanticVersion(int(match.group(1)), int(match.group(2)),
859 int(match.group(3)), match.group('prerelease'))
Søren Gjesse4e5c6fe2019-11-05 17:17:43 +0100860 else:
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200861 raise Exception('Argument "components" must be 2 or 3')