blob: 3aad6c46d5eadbb86d792886e3e9056053054125 [file] [log] [blame]
Mads Ager418d1ca2017-05-22 09:35:49 +02001# Copyright (c) 2016, the R8 project authors. Please see the AUTHORS file
2# for details. All rights reserved. Use of this source code is governed by a
3# BSD-style license that can be found in the LICENSE file.
4
5# Different utility functions used accross scripts
6
7import hashlib
Søren Gjesse6e5e5842019-09-03 08:48:30 +02008import json
Mads Ager418d1ca2017-05-22 09:35:49 +02009import os
Tamas Kenez82efeb52017-06-12 13:56:22 +020010import re
Mads Ager418d1ca2017-05-22 09:35:49 +020011import shutil
12import subprocess
13import sys
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +020014import tarfile
Mads Ager418d1ca2017-05-22 09:35:49 +020015import tempfile
Morten Krogh-Jespersen16e925d2019-01-25 14:40:38 +010016import zipfile
Mads Ager418d1ca2017-05-22 09:35:49 +020017
Ian Zerny37097652019-04-11 13:13:27 +020018import defines
19import jdk
20
Christoffer Quist Adamsen17879c12019-01-22 16:13:54 +010021ANDROID_JAR_DIR = 'third_party/android_jar/lib-v{api}'
22ANDROID_JAR = os.path.join(ANDROID_JAR_DIR, 'android.jar')
Ian Zerny3f54e222019-02-12 10:51:17 +010023TOOLS_DIR = defines.TOOLS_DIR
24REPO_ROOT = defines.REPO_ROOT
25THIRD_PARTY = defines.THIRD_PARTY
Morten Krogh-Jespersen220e5702019-02-27 12:57:01 +010026ANDROID_SDK = os.path.join(THIRD_PARTY, 'android_sdk')
Tamas Kenezfc34cd82017-07-13 12:43:57 +020027MEMORY_USE_TMP_FILE = 'memory_use.tmp'
Tamas Kenez02bff032017-07-18 12:13:58 +020028DEX_SEGMENTS_RESULT_PATTERN = re.compile('- ([^:]+): ([0-9]+)')
Mads Ager12a56bc2017-11-27 11:51:25 +010029BUILD = os.path.join(REPO_ROOT, 'build')
Ian Zerny0f5fc732018-11-15 14:34:41 +010030BUILD_DEPS_DIR = os.path.join(BUILD, 'deps')
31BUILD_MAIN_DIR = os.path.join(BUILD, 'classes', 'main')
32BUILD_TEST_DIR = os.path.join(BUILD, 'classes', 'test')
Mads Ager12a56bc2017-11-27 11:51:25 +010033LIBS = os.path.join(BUILD, 'libs')
34GENERATED_LICENSE_DIR = os.path.join(BUILD, 'generatedLicense')
Mads Agera4911eb2017-11-22 13:19:36 +010035SRC_ROOT = os.path.join(REPO_ROOT, 'src', 'main', 'java')
Søren Gjesse6e5e5842019-09-03 08:48:30 +020036TEST_ROOT = os.path.join(REPO_ROOT, 'src', 'test', 'java')
Ian Zerny59dfa4c2019-10-25 10:34:36 +020037REPO_SOURCE = 'https://r8.googlesource.com/r8'
Søren Gjessedc9d8a22017-10-12 12:40:59 +020038
39D8 = 'd8'
40R8 = 'r8'
Tamas Kenez03ab76f2018-12-07 14:33:25 +010041R8LIB = 'r8lib'
Morten Krogh-Jespersene28db462019-01-09 13:32:15 +010042R8LIB_NO_DEPS = 'r8LibNoDeps'
Mads Agerb10c07f2017-11-27 13:25:52 +010043R8_SRC = 'sourceJar'
Søren Gjesse17fc67d2019-12-04 14:50:17 +010044LIBRARY_DESUGAR_CONVERSIONS = 'buildLibraryDesugarConversions'
Søren Gjessedc9d8a22017-10-12 12:40:59 +020045
Rico Wind74fab302017-10-02 07:25:33 +020046D8_JAR = os.path.join(LIBS, 'd8.jar')
47R8_JAR = os.path.join(LIBS, 'r8.jar')
Tamas Kenez03ab76f2018-12-07 14:33:25 +010048R8LIB_JAR = os.path.join(LIBS, 'r8lib.jar')
Ian Zerny5ffa58f2020-02-26 08:37:14 +010049R8LIB_MAP = os.path.join(LIBS, 'r8lib.jar.map')
Mads Agerb10c07f2017-11-27 13:25:52 +010050R8_SRC_JAR = os.path.join(LIBS, 'r8-src.jar')
Tamas Kenez03ab76f2018-12-07 14:33:25 +010051R8LIB_EXCLUDE_DEPS_JAR = os.path.join(LIBS, 'r8lib-exclude-deps.jar')
Tamas Kenez180be092018-12-05 15:23:06 +010052R8_FULL_EXCLUDE_DEPS_JAR = os.path.join(LIBS, 'r8-full-exclude-deps.jar')
Mads Ager12a56bc2017-11-27 11:51:25 +010053MAVEN_ZIP = os.path.join(LIBS, 'r8.zip')
Rico Wind8fc8bfa2019-03-22 09:57:36 +010054MAVEN_ZIP_LIB = os.path.join(LIBS, 'r8lib.zip')
Søren Gjesse17fc67d2019-12-04 14:50:17 +010055LIBRARY_DESUGAR_CONVERSIONS_ZIP = os.path.join(LIBS, 'library_desugar_conversions.zip')
56
Søren Gjesse6e5e5842019-09-03 08:48:30 +020057DESUGAR_CONFIGURATION = os.path.join(
Søren Gjesse927a92e2019-12-04 15:18:06 +010058 'src', 'library_desugar', 'desugar_jdk_libs.json')
Søren Gjesse6e5e5842019-09-03 08:48:30 +020059DESUGAR_CONFIGURATION_MAVEN_ZIP = os.path.join(
60 LIBS, 'desugar_jdk_libs_configuration.zip')
Mads Ager12a56bc2017-11-27 11:51:25 +010061GENERATED_LICENSE = os.path.join(GENERATED_LICENSE_DIR, 'LICENSE')
Mathias Rav3fb4a3a2018-05-29 15:41:36 +020062RT_JAR = os.path.join(REPO_ROOT, 'third_party/openjdk/openjdk-rt-1.8/rt.jar')
Mathias Ravb46dc002018-06-06 09:37:11 +020063R8LIB_KEEP_RULES = os.path.join(REPO_ROOT, 'src/main/keep.txt')
Morten Krogh-Jespersen480784d2019-02-05 08:10:46 +010064CF_SEGMENTS_TOOL = os.path.join(THIRD_PARTY, 'cf_segments')
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +010065PINNED_R8_JAR = os.path.join(REPO_ROOT, 'third_party/r8/r8.jar')
66PINNED_PGR8_JAR = os.path.join(REPO_ROOT, 'third_party/r8/r8-pg6.0.1.jar')
Ian Zernyfbb1f7a2019-05-02 14:34:13 +020067SAMPLE_LIBRARIES_SHA_FILE = os.path.join(
68 THIRD_PARTY, 'sample_libraries.tar.gz.sha1')
Morten Krogh-Jespersen64740202019-02-07 13:06:04 +010069OPENSOURCE_APPS_SHA_FILE = os.path.join(
Rico Windec283b52019-04-03 15:16:55 +020070 THIRD_PARTY, 'opensource_apps.tar.gz.sha1')
71OPENSOURCE_APPS_FOLDER = os.path.join(THIRD_PARTY, 'opensource_apps')
Søren Gjesse1c115b52019-08-14 12:43:57 +020072BAZEL_SHA_FILE = os.path.join(THIRD_PARTY, 'bazel.tar.gz.sha1')
73BAZEL_TOOL = os.path.join(THIRD_PARTY, 'bazel')
Søren Gjesse699f6362019-10-09 14:56:33 +020074JAVA8_SHA_FILE = os.path.join(THIRD_PARTY, 'openjdk', 'jdk8', 'linux-x86.tar.gz.sha1')
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +010075
Morten Krogh-Jespersen220e5702019-02-27 12:57:01 +010076ANDROID_HOME_ENVIROMENT_NAME = "ANDROID_HOME"
77ANDROID_TOOLS_VERSION_ENVIRONMENT_NAME = "ANDROID_TOOLS_VERSION"
Morten Krogh-Jespersenc8efedd2019-01-28 11:36:17 +010078USER_HOME = os.path.expanduser('~')
Morten Krogh-Jespersen220e5702019-02-27 12:57:01 +010079
Morten Krogh-Jespersen0981b722019-10-09 10:00:33 +020080R8_TEST_RESULTS_BUCKET = 'r8-test-results'
81
82def archive_file(name, gs_dir, src_file):
83 gs_file = '%s/%s' % (gs_dir, name)
84 upload_file_to_cloud_storage(src_file, gs_file, public_read=False)
85
86def archive_value(name, gs_dir, value):
87 with TempDir() as temp:
88 tempfile = os.path.join(temp, name);
89 with open(tempfile, 'w') as f:
90 f.write(str(value))
91 archive_file(name, gs_dir, tempfile)
92
Morten Krogh-Jespersen220e5702019-02-27 12:57:01 +010093def getAndroidHome():
94 return os.environ.get(
95 ANDROID_HOME_ENVIROMENT_NAME, os.path.join(USER_HOME, 'Android', 'Sdk'))
96
97def getAndroidBuildTools():
98 version = os.environ.get(ANDROID_TOOLS_VERSION_ENVIRONMENT_NAME, '28.0.3')
99 return os.path.join(getAndroidHome(), 'build-tools', version)
Morten Krogh-Jespersenc8efedd2019-01-28 11:36:17 +0100100
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100101def Print(s, quiet=False):
102 if quiet:
103 return
104 print(s)
105
106def Warn(message):
107 CRED = '\033[91m'
108 CEND = '\033[0m'
109 print(CRED + message + CEND)
110
111def PrintCmd(cmd, env=None, quiet=False):
112 if quiet:
113 return
114 if type(cmd) is list:
115 cmd = ' '.join(cmd)
116 if env:
117 env = ' '.join(['{}=\"{}\"'.format(x, y) for x, y in env.iteritems()])
118 print('Running: {} {}'.format(env, cmd))
119 else:
120 print('Running: {}'.format(cmd))
Mads Ager418d1ca2017-05-22 09:35:49 +0200121 # I know this will hit os on windows eventually if we don't do this.
122 sys.stdout.flush()
123
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100124class ProgressLogger(object):
125 CLEAR_LINE = '\033[K'
126 UP = '\033[F'
127
128 def __init__(self, quiet=False):
129 self._count = 0
130 self._has_printed = False
131 self._quiet = quiet
132
133 def log(self, text):
134 if self._quiet:
135 if self._has_printed:
136 sys.stdout.write(ProgressLogger.UP + ProgressLogger.CLEAR_LINE)
137 if len(text) > 140:
138 text = text[0:140] + '...'
139 print(text)
140 self._has_printed = True
141
142 def done(self):
143 if self._quiet and self._has_printed:
144 sys.stdout.write(ProgressLogger.UP + ProgressLogger.CLEAR_LINE)
145 print('')
146 sys.stdout.write(ProgressLogger.UP)
147
Morten Krogh-Jespersen7cdd3a72019-03-13 14:58:25 +0100148def RunCmd(cmd, env_vars=None, quiet=False, fail=True, logging=True):
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100149 PrintCmd(cmd, env=env_vars, quiet=quiet)
150 env = os.environ.copy()
151 if env_vars:
152 env.update(env_vars)
153 process = subprocess.Popen(
154 cmd, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
155 stdout = []
Morten Krogh-Jespersen7cdd3a72019-03-13 14:58:25 +0100156 logger = ProgressLogger(quiet=quiet) if logging else None
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100157 failed = False
158 while True:
159 line = process.stdout.readline()
160 if line != b'':
161 stripped = line.rstrip()
162 stdout.append(stripped)
Morten Krogh-Jespersen7cdd3a72019-03-13 14:58:25 +0100163 if logger:
164 logger.log(stripped)
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100165
166 # TODO(christofferqa): r8 should fail with non-zero exit code.
Morten Krogh-Jespersen121c47b2019-01-25 09:57:21 +0100167 if ('AssertionError:' in stripped
168 or 'CompilationError:' in stripped
169 or 'CompilationFailedException:' in stripped
Morten Krogh-Jespersen5d02a6b2019-10-29 14:48:56 +0100170 or 'Compilation failed' in stripped
171 or 'FAILURE:' in stripped
172 or 'org.gradle.api.ProjectConfigurationException' in stripped
173 or 'BUILD FAILED' in stripped):
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100174 failed = True
175 else:
Morten Krogh-Jespersen7cdd3a72019-03-13 14:58:25 +0100176 if logger:
177 logger.done()
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100178 exit_code = process.poll()
179 if exit_code or failed:
180 for line in stdout:
181 Warn(line)
Christoffer Quist Adamsen7cf4c562019-03-07 10:57:33 +0100182 if fail:
183 raise subprocess.CalledProcessError(
184 exit_code or -1, cmd, output='\n'.join(stdout))
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100185 return stdout
186
Christoffer Quist Adamsen7cf4c562019-03-07 10:57:33 +0100187def RunGradlew(
188 args, clean=True, stacktrace=True, use_daemon=False, env_vars=None,
Morten Krogh-Jespersen7cdd3a72019-03-13 14:58:25 +0100189 quiet=False, fail=True, logging=True):
Christoffer Quist Adamsen7cf4c562019-03-07 10:57:33 +0100190 cmd = ['./gradlew']
191 if clean:
192 assert 'clean' not in args
193 cmd.append('clean')
194 if stacktrace:
195 assert '--stacktrace' not in args
196 cmd.append('--stacktrace')
197 if not use_daemon:
198 assert '--no-daemon' not in args
199 cmd.append('--no-daemon')
200 cmd.extend(args)
Morten Krogh-Jespersen7cdd3a72019-03-13 14:58:25 +0100201 return RunCmd(cmd, env_vars=env_vars, quiet=quiet, fail=fail, logging=logging)
Christoffer Quist Adamsen7cf4c562019-03-07 10:57:33 +0100202
Rico Windf80f5a22017-06-16 09:15:57 +0200203def IsWindows():
Ian Zerny3f54e222019-02-12 10:51:17 +0100204 return defines.IsWindows()
Ian Zerny5fffb0a2019-02-11 13:54:22 +0100205
206def IsLinux():
Ian Zerny3f54e222019-02-12 10:51:17 +0100207 return defines.IsLinux()
Ian Zerny5fffb0a2019-02-11 13:54:22 +0100208
209def IsOsX():
Ian Zerny3f54e222019-02-12 10:51:17 +0100210 return defines.IsOsX()
Ian Zerny5fffb0a2019-02-11 13:54:22 +0100211
212def EnsureDepFromGoogleCloudStorage(dep, tgz, sha1, msg):
213 if not os.path.exists(dep) or os.path.getmtime(tgz) < os.path.getmtime(sha1):
214 DownloadFromGoogleCloudStorage(sha1)
215 # Update the mtime of the tar file to make sure we do not run again unless
216 # there is an update.
217 os.utime(tgz, None)
218 else:
219 print 'Ensure cloud dependency:', msg, 'present'
Rico Windf80f5a22017-06-16 09:15:57 +0200220
Jean-Marie Henaffe4e36d12018-04-05 10:33:50 +0200221def DownloadFromX20(sha1_file):
222 download_script = os.path.join(REPO_ROOT, 'tools', 'download_from_x20.py')
223 cmd = [download_script, sha1_file]
224 PrintCmd(cmd)
225 subprocess.check_call(cmd)
226
Rico Wind533e3ce2019-04-04 10:26:12 +0200227def DownloadFromGoogleCloudStorage(sha1_file, bucket='r8-deps', auth=False):
Rico Windf80f5a22017-06-16 09:15:57 +0200228 suffix = '.bat' if IsWindows() else ''
229 download_script = 'download_from_google_storage%s' % suffix
Rico Wind533e3ce2019-04-04 10:26:12 +0200230 cmd = [download_script]
231 if not auth:
232 cmd.append('-n')
233 cmd.extend(['-b', bucket, '-u', '-s', sha1_file])
Mads Ager418d1ca2017-05-22 09:35:49 +0200234 PrintCmd(cmd)
235 subprocess.check_call(cmd)
236
237def get_sha1(filename):
238 sha1 = hashlib.sha1()
239 with open(filename, 'rb') as f:
240 while True:
241 chunk = f.read(1024*1024)
242 if not chunk:
243 break
244 sha1.update(chunk)
245 return sha1.hexdigest()
246
Rico Wind1b09c562019-01-17 08:53:09 +0100247def is_master():
248 remotes = subprocess.check_output(['git', 'branch', '-r', '--contains',
249 'HEAD'])
250 return 'origin/master' in remotes
251
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +0200252def get_HEAD_sha1():
Morten Krogh-Jespersene0ce6a32019-02-07 11:44:45 +0100253 return get_HEAD_sha1_for_checkout(REPO_ROOT)
254
255def get_HEAD_sha1_for_checkout(checkout):
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +0200256 cmd = ['git', 'rev-parse', 'HEAD']
257 PrintCmd(cmd)
Morten Krogh-Jespersene0ce6a32019-02-07 11:44:45 +0100258 with ChangedWorkingDirectory(checkout):
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +0200259 return subprocess.check_output(cmd).strip()
260
Tamas Kenez971eec62017-05-24 11:08:40 +0200261def makedirs_if_needed(path):
262 try:
263 os.makedirs(path)
264 except OSError:
265 if not os.path.isdir(path):
266 raise
267
Rico Wind800fd712018-09-24 11:29:33 +0200268def upload_dir_to_cloud_storage(directory, destination, is_html=False, public_read=True):
Rico Winda94f01c2017-06-27 10:32:34 +0200269 # Upload and make the content encoding right for viewing directly
Rico Windd55ce272019-03-26 08:02:09 +0100270 cmd = ['gsutil.py', '-m', 'cp']
Rico Windd0d88cf2018-02-09 09:46:11 +0100271 if is_html:
272 cmd += ['-z', 'html']
Rico Wind800fd712018-09-24 11:29:33 +0200273 if public_read:
274 cmd += ['-a', 'public-read']
275 cmd += ['-R', directory, destination]
Rico Winda94f01c2017-06-27 10:32:34 +0200276 PrintCmd(cmd)
277 subprocess.check_call(cmd)
278
Rico Wind800fd712018-09-24 11:29:33 +0200279def upload_file_to_cloud_storage(source, destination, public_read=True):
280 cmd = ['gsutil.py', 'cp']
281 if public_read:
282 cmd += ['-a', 'public-read']
283 cmd += [source, destination]
Rico Windb4621c12017-08-28 12:48:53 +0200284 PrintCmd(cmd)
285 subprocess.check_call(cmd)
286
Rico Wind139eece2018-09-25 09:42:09 +0200287def delete_file_from_cloud_storage(destination):
288 cmd = ['gsutil.py', 'rm', destination]
289 PrintCmd(cmd)
290 subprocess.check_call(cmd)
291
Rico Wind4fd2dda2018-09-26 17:41:45 +0200292def ls_files_on_cloud_storage(destination):
293 cmd = ['gsutil.py', 'ls', destination]
294 PrintCmd(cmd)
295 return subprocess.check_output(cmd)
296
Rico Wind139eece2018-09-25 09:42:09 +0200297def cat_file_on_cloud_storage(destination, ignore_errors=False):
298 cmd = ['gsutil.py', 'cat', destination]
299 PrintCmd(cmd)
300 try:
301 return subprocess.check_output(cmd)
302 except subprocess.CalledProcessError as e:
303 if ignore_errors:
304 return ''
305 else:
306 raise e
307
308def file_exists_on_cloud_storage(destination):
309 cmd = ['gsutil.py', 'ls', destination]
310 PrintCmd(cmd)
311 return subprocess.call(cmd) == 0
312
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +0200313def download_file_from_cloud_storage(source, destination):
314 cmd = ['gsutil.py', 'cp', source, destination]
315 PrintCmd(cmd)
316 subprocess.check_call(cmd)
317
Morten Krogh-Jespersen220e5702019-02-27 12:57:01 +0100318def create_archive(name, sources=None):
319 if not sources:
320 sources = [name]
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +0200321 tarname = '%s.tar.gz' % name
322 with tarfile.open(tarname, 'w:gz') as tar:
Morten Krogh-Jespersen54090862019-02-19 11:31:10 +0100323 for source in sources:
324 tar.add(source)
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +0200325 return tarname
326
327def extract_dir(filename):
328 return filename[0:len(filename) - len('.tar.gz')]
329
330def unpack_archive(filename):
331 dest_dir = extract_dir(filename)
332 if os.path.exists(dest_dir):
333 print 'Deleting existing dir %s' % dest_dir
334 shutil.rmtree(dest_dir)
335 dirname = os.path.dirname(os.path.abspath(filename))
336 with tarfile.open(filename, 'r:gz') as tar:
337 tar.extractall(path=dirname)
338
Morten Krogh-Jespersenec3047b2020-08-18 13:09:06 +0200339def check_gcert():
340 subprocess.check_call(['gcert'])
Morten Krogh-Jespersen54090862019-02-19 11:31:10 +0100341
Rico Wind1a29c4f2018-01-25 08:43:08 +0100342# Note that gcs is eventually consistent with regards to list operations.
343# This is not a problem in our case, but don't ever use this method
344# for synchronization.
345def cloud_storage_exists(destination):
346 cmd = ['gsutil.py', 'ls', destination]
347 PrintCmd(cmd)
348 exit_code = subprocess.call(cmd)
349 return exit_code == 0
350
Mads Ager418d1ca2017-05-22 09:35:49 +0200351class TempDir(object):
Søren Gjessecbeae782019-05-21 14:14:25 +0200352 def __init__(self, prefix='', delete=True):
Mads Ager418d1ca2017-05-22 09:35:49 +0200353 self._temp_dir = None
354 self._prefix = prefix
Søren Gjessecbeae782019-05-21 14:14:25 +0200355 self._delete = delete
Mads Ager418d1ca2017-05-22 09:35:49 +0200356
357 def __enter__(self):
358 self._temp_dir = tempfile.mkdtemp(self._prefix)
359 return self._temp_dir
360
361 def __exit__(self, *_):
Søren Gjessecbeae782019-05-21 14:14:25 +0200362 if self._delete:
363 shutil.rmtree(self._temp_dir, ignore_errors=True)
Mads Ager418d1ca2017-05-22 09:35:49 +0200364
365class ChangedWorkingDirectory(object):
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100366 def __init__(self, working_directory, quiet=False):
367 self._quiet = quiet
Mads Ager418d1ca2017-05-22 09:35:49 +0200368 self._working_directory = working_directory
369
370 def __enter__(self):
371 self._old_cwd = os.getcwd()
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100372 if not self._quiet:
373 print 'Enter directory:', self._working_directory
Mads Ager418d1ca2017-05-22 09:35:49 +0200374 os.chdir(self._working_directory)
375
376 def __exit__(self, *_):
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100377 if not self._quiet:
378 print 'Enter directory:', self._old_cwd
Mads Ager418d1ca2017-05-22 09:35:49 +0200379 os.chdir(self._old_cwd)
Tamas Kenez82efeb52017-06-12 13:56:22 +0200380
381# Reading Android CTS test_result.xml
382
383class CtsModule(object):
384 def __init__(self, module_name):
385 self.name = module_name
386
387class CtsTestCase(object):
388 def __init__(self, test_case_name):
389 self.name = test_case_name
390
391class CtsTest(object):
392 def __init__(self, test_name, outcome):
393 self.name = test_name
394 self.outcome = outcome
395
396# Generator yielding CtsModule, CtsTestCase or CtsTest from
397# reading through a CTS test_result.xml file.
398def read_cts_test_result(file_xml):
399 re_module = re.compile('<Module name="([^"]*)"')
400 re_test_case = re.compile('<TestCase name="([^"]*)"')
401 re_test = re.compile('<Test result="(pass|fail)" name="([^"]*)"')
402 with open(file_xml) as f:
403 for line in f:
404 m = re_module.search(line)
405 if m:
406 yield CtsModule(m.groups()[0])
407 continue
408 m = re_test_case.search(line)
409 if m:
410 yield CtsTestCase(m.groups()[0])
411 continue
412 m = re_test.search(line)
413 if m:
414 outcome = m.groups()[0]
Rico Windf80f5a22017-06-16 09:15:57 +0200415 assert outcome in ['fail', 'pass']
Tamas Kenez82efeb52017-06-12 13:56:22 +0200416 yield CtsTest(m.groups()[1], outcome == 'pass')
Tamas Kenezfc34cd82017-07-13 12:43:57 +0200417
418def grep_memoryuse(logfile):
419 re_vmhwm = re.compile('^VmHWM:[ \t]*([0-9]+)[ \t]*([a-zA-Z]*)')
420 result = None
421 with open(logfile) as f:
422 for line in f:
423 m = re_vmhwm.search(line)
424 if m:
425 groups = m.groups()
426 s = len(groups)
427 if s >= 1:
428 result = int(groups[0])
429 if s >= 2:
430 unit = groups[1]
431 if unit == 'kB':
432 result *= 1024
433 elif unit != '':
434 raise Exception('Unrecognized unit in memory usage log: {}'
435 .format(unit))
436 if result is None:
437 raise Exception('No memory usage found in log: {}'.format(logfile))
Tamas Kenez02bff032017-07-18 12:13:58 +0200438 return result
439
440# Return a dictionary: {segment_name -> segments_size}
441def getDexSegmentSizes(dex_files):
442 assert len(dex_files) > 0
Ian Zerny3f54e222019-02-12 10:51:17 +0100443 cmd = [jdk.GetJavaExecutable(), '-jar', R8_JAR, 'dexsegments']
Tamas Kenez02bff032017-07-18 12:13:58 +0200444 cmd.extend(dex_files)
445 PrintCmd(cmd)
446 output = subprocess.check_output(cmd)
447
448 matches = DEX_SEGMENTS_RESULT_PATTERN.findall(output)
449
450 if matches is None or len(matches) == 0:
451 raise Exception('DexSegments failed to return any output for' \
452 ' these files: {}'.format(dex_files))
453
454 result = {}
455
456 for match in matches:
457 result[match[0]] = int(match[1])
458
459 return result
460
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100461# Return a dictionary: {segment_name -> segments_size}
462def getCfSegmentSizes(cfFile):
Ian Zerny3f54e222019-02-12 10:51:17 +0100463 cmd = [jdk.GetJavaExecutable(),
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100464 '-cp',
Morten Krogh-Jespersen480784d2019-02-05 08:10:46 +0100465 CF_SEGMENTS_TOOL,
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100466 'com.android.tools.r8.cf_segments.MeasureLib',
467 cfFile]
468 PrintCmd(cmd)
469 output = subprocess.check_output(cmd)
470
471 matches = DEX_SEGMENTS_RESULT_PATTERN.findall(output)
472
473 if matches is None or len(matches) == 0:
474 raise Exception('CfSegments failed to return any output for' \
475 ' the file: ' + cfFile)
476
477 result = {}
478
479 for match in matches:
480 result[match[0]] = int(match[1])
481
482 return result
483
Søren Gjesse1c115b52019-08-14 12:43:57 +0200484def get_maven_path(artifact, version):
485 return os.path.join('com', 'android', 'tools', artifact, version)
Rico Windc0b16382018-05-17 13:23:43 +0200486
Morten Krogh-Jespersen38c7ca02019-02-04 10:39:57 +0100487def print_cfsegments(prefix, cf_files):
488 for cf_file in cf_files:
489 for segment_name, size in getCfSegmentSizes(cf_file).items():
490 print('{}-{}(CodeSize): {}'
491 .format(prefix, segment_name, size))
492
Tamas Kenez02bff032017-07-18 12:13:58 +0200493def print_dexsegments(prefix, dex_files):
494 for segment_name, size in getDexSegmentSizes(dex_files).items():
495 print('{}-{}(CodeSize): {}'
496 .format(prefix, segment_name, size))
Tamas Kenez2cf47cf2017-07-25 10:22:52 +0200497
Mads Agerbc7b2ce2018-02-05 11:28:47 +0100498# Ensure that we are not benchmarking with a google jvm.
Tamas Kenez2cf47cf2017-07-25 10:22:52 +0200499def check_java_version():
Ian Zerny3f54e222019-02-12 10:51:17 +0100500 cmd= [jdk.GetJavaExecutable(), '-version']
Tamas Kenez2cf47cf2017-07-25 10:22:52 +0200501 output = subprocess.check_output(cmd, stderr = subprocess.STDOUT)
502 m = re.search('openjdk version "([^"]*)"', output)
503 if m is None:
504 raise Exception("Can't check java version: no version string in output"
505 " of 'java -version': '{}'".format(output))
506 version = m.groups(0)[0]
Mads Agerbc7b2ce2018-02-05 11:28:47 +0100507 m = re.search('google', version)
508 if m is not None:
509 raise Exception("Do not use google JVM for benchmarking: " + version)
Tamas Kenez0cad51c2017-08-21 14:42:01 +0200510
Christoffer Quist Adamsen17879c12019-01-22 16:13:54 +0100511def get_android_jar_dir(api):
512 return os.path.join(REPO_ROOT, ANDROID_JAR_DIR.format(api=api))
513
Rico Wind9d70f612018-08-31 09:17:43 +0200514def get_android_jar(api):
515 return os.path.join(REPO_ROOT, ANDROID_JAR.format(api=api))
Rico Windda6836e2018-12-07 12:32:03 +0100516
Christoffer Quist Adamsen17879c12019-01-22 16:13:54 +0100517def get_android_optional_jars(api):
518 android_optional_jars_dir = os.path.join(get_android_jar_dir(api), 'optional')
519 android_optional_jars = [
520 os.path.join(android_optional_jars_dir, 'android.test.base.jar'),
521 os.path.join(android_optional_jars_dir, 'android.test.mock.jar'),
522 os.path.join(android_optional_jars_dir, 'android.test.runner.jar'),
523 os.path.join(android_optional_jars_dir, 'org.apache.http.legacy.jar')
524 ]
525 return [
526 android_optional_jar for android_optional_jar in android_optional_jars
527 if os.path.isfile(android_optional_jar)]
528
Rico Windfaaac012019-02-25 11:24:05 +0100529def is_bot():
Rico Winde11f4392019-03-18 07:59:37 +0100530 return 'SWARMING_BOT_ID' in os.environ
Morten Krogh-Jespersen16e925d2019-01-25 14:40:38 +0100531
532def uncompressed_size(path):
533 return sum(z.file_size for z in zipfile.ZipFile(path).infolist())
Morten Krogh-Jespersen0de13732019-03-01 08:56:39 +0100534
535def getR8Version(path):
536 cmd = [jdk.GetJavaExecutable(), '-cp', path, 'com.android.tools.r8.R8',
537 '--version']
538 output = subprocess.check_output(cmd, stderr = subprocess.STDOUT)
Jinseong Jeona2394232019-11-26 22:17:55 -0800539 # output is of the form 'R8 <version> (with additional info)'
540 # so we split on '('; clean up tailing spaces; and strip off 'R8 '.
541 return output.split('(')[0].strip()[3:]
Søren Gjesse6e5e5842019-09-03 08:48:30 +0200542
543def desugar_configuration_version():
544 with open(DESUGAR_CONFIGURATION, 'r') as f:
545 configuration_json = json.loads(f.read())
546 configuration_format_version = \
547 configuration_json.get('configuration_format_version')
Søren Gjesse6e5e5842019-09-03 08:48:30 +0200548 version = configuration_json.get('version')
549 if not version:
550 raise Exception(
551 'No "version" found in ' + utils.DESUGAR_CONFIGURATION)
Søren Gjesse1e171532019-09-03 09:44:22 +0200552 check_basic_semver_version(version, 'in ' + DESUGAR_CONFIGURATION)
Søren Gjesse6e5e5842019-09-03 08:48:30 +0200553 return version
Søren Gjesse1e171532019-09-03 09:44:22 +0200554
Søren Gjesse4e5c6fe2019-11-05 17:17:43 +0100555class SemanticVersion:
556 def __init__(self, major, minor, patch):
557 self.major = major
558 self.minor = minor
559 self.patch = patch
560 # Build metadata currently not suppported
561
562 def larger_than(self, other):
563 if self.major > other.major:
564 return True
565 if self.major == other.major and self.minor > other.minor:
566 return True
567 if self.patch:
568 return (self.major == other.major
569 and self.minor == other.minor
570 and self.patch > other.patch)
571 else:
572 return False
573
574
Søren Gjesse1e171532019-09-03 09:44:22 +0200575# Check that the passed string is formatted as a basic semver version (x.y.z)
576# See https://semver.org/.
Søren Gjesse4e5c6fe2019-11-05 17:17:43 +0100577def check_basic_semver_version(version, error_context = '', components = 3):
578 regexp = '^'
579 for x in range(components):
580 regexp += '([0-9]+)'
581 if x < components - 1:
582 regexp += '\\.'
583 regexp += '$'
584 reg = re.compile(regexp)
585 match = reg.match(version)
586 if not match:
Søren Gjesse1e171532019-09-03 09:44:22 +0200587 raise Exception("Invalid version '"
588 + version
589 + "'"
590 + (' ' + error_context) if len(error_context) > 0 else '')
Søren Gjesse4e5c6fe2019-11-05 17:17:43 +0100591 if components == 2:
592 return SemanticVersion(int(match.group(1)), int(match.group(2)), None)
593 elif components == 3:
594 return SemanticVersion(
595 int(match.group(1)), int(match.group(2)), int(match.group(3)))
596 else:
597 raise Exception('Argument "components" must be 2 or 3')