blob: f8b446917eb0c0edb5d8bc803508a97a112e9fac [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
8import os
Tamas Kenez82efeb52017-06-12 13:56:22 +02009import re
Mads Ager418d1ca2017-05-22 09:35:49 +020010import shutil
11import subprocess
12import sys
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +020013import tarfile
Mads Ager418d1ca2017-05-22 09:35:49 +020014import tempfile
15
Rico Wind9d70f612018-08-31 09:17:43 +020016ANDROID_JAR = 'third_party/android_jar/lib-v{api}/android.jar'
Mads Ager418d1ca2017-05-22 09:35:49 +020017TOOLS_DIR = os.path.abspath(os.path.normpath(os.path.join(__file__, '..')))
18REPO_ROOT = os.path.realpath(os.path.join(TOOLS_DIR, '..'))
Rico Wind6238f222018-10-03 10:36:10 +020019THIRD_PARTY = os.path.join(REPO_ROOT, 'third_party')
Tamas Kenezfc34cd82017-07-13 12:43:57 +020020MEMORY_USE_TMP_FILE = 'memory_use.tmp'
Tamas Kenez02bff032017-07-18 12:13:58 +020021DEX_SEGMENTS_RESULT_PATTERN = re.compile('- ([^:]+): ([0-9]+)')
Mads Ager12a56bc2017-11-27 11:51:25 +010022BUILD = os.path.join(REPO_ROOT, 'build')
Ian Zerny0f5fc732018-11-15 14:34:41 +010023BUILD_DEPS_DIR = os.path.join(BUILD, 'deps')
24BUILD_MAIN_DIR = os.path.join(BUILD, 'classes', 'main')
25BUILD_TEST_DIR = os.path.join(BUILD, 'classes', 'test')
Mads Ager12a56bc2017-11-27 11:51:25 +010026LIBS = os.path.join(BUILD, 'libs')
27GENERATED_LICENSE_DIR = os.path.join(BUILD, 'generatedLicense')
Mads Agera4911eb2017-11-22 13:19:36 +010028SRC_ROOT = os.path.join(REPO_ROOT, 'src', 'main', 'java')
Søren Gjessedc9d8a22017-10-12 12:40:59 +020029
30D8 = 'd8'
31R8 = 'r8'
Tamas Kenez03ab76f2018-12-07 14:33:25 +010032R8LIB = 'r8lib'
Morten Krogh-Jespersene28db462019-01-09 13:32:15 +010033R8LIB_NO_DEPS = 'r8LibNoDeps'
Mads Agerb10c07f2017-11-27 13:25:52 +010034R8_SRC = 'sourceJar'
Søren Gjessedc9d8a22017-10-12 12:40:59 +020035COMPATDX = 'compatdx'
Tamas Kenez03ab76f2018-12-07 14:33:25 +010036COMPATDXLIB = 'compatdxlib'
Søren Gjessedc9d8a22017-10-12 12:40:59 +020037COMPATPROGUARD = 'compatproguard'
Tamas Kenez03ab76f2018-12-07 14:33:25 +010038COMPATPROGUARDLIB = 'compatproguardlib'
Søren Gjessedc9d8a22017-10-12 12:40:59 +020039
Rico Wind74fab302017-10-02 07:25:33 +020040D8_JAR = os.path.join(LIBS, 'd8.jar')
41R8_JAR = os.path.join(LIBS, 'r8.jar')
Tamas Kenez03ab76f2018-12-07 14:33:25 +010042R8LIB_JAR = os.path.join(LIBS, 'r8lib.jar')
Mads Agerb10c07f2017-11-27 13:25:52 +010043R8_SRC_JAR = os.path.join(LIBS, 'r8-src.jar')
Tamas Kenez03ab76f2018-12-07 14:33:25 +010044R8LIB_EXCLUDE_DEPS_JAR = os.path.join(LIBS, 'r8lib-exclude-deps.jar')
Tamas Kenez180be092018-12-05 15:23:06 +010045R8_FULL_EXCLUDE_DEPS_JAR = os.path.join(LIBS, 'r8-full-exclude-deps.jar')
Rico Wind74fab302017-10-02 07:25:33 +020046COMPATDX_JAR = os.path.join(LIBS, 'compatdx.jar')
Tamas Kenez03ab76f2018-12-07 14:33:25 +010047COMPATDXLIB_JAR = os.path.join(LIBS, 'compatdxlib.jar')
Søren Gjessedc9d8a22017-10-12 12:40:59 +020048COMPATPROGUARD_JAR = os.path.join(LIBS, 'compatproguard.jar')
Tamas Kenez03ab76f2018-12-07 14:33:25 +010049COMPATPROGUARDLIB_JAR = os.path.join(LIBS, 'compatproguardlib.jar')
Mads Ager12a56bc2017-11-27 11:51:25 +010050MAVEN_ZIP = os.path.join(LIBS, 'r8.zip')
51GENERATED_LICENSE = os.path.join(GENERATED_LICENSE_DIR, 'LICENSE')
Mathias Rav3fb4a3a2018-05-29 15:41:36 +020052RT_JAR = os.path.join(REPO_ROOT, 'third_party/openjdk/openjdk-rt-1.8/rt.jar')
Mathias Ravb46dc002018-06-06 09:37:11 +020053R8LIB_KEEP_RULES = os.path.join(REPO_ROOT, 'src/main/keep.txt')
Morten Krogh-Jespersen017a7002019-01-10 14:14:17 +010054RETRACE_JAR = os.path.join(THIRD_PARTY, 'proguard', 'proguard6.0.1', 'lib', 'retrace.jar')
Mads Ager418d1ca2017-05-22 09:35:49 +020055
56def PrintCmd(s):
57 if type(s) is list:
58 s = ' '.join(s)
59 print 'Running: %s' % s
60 # I know this will hit os on windows eventually if we don't do this.
61 sys.stdout.flush()
62
Rico Windf80f5a22017-06-16 09:15:57 +020063def IsWindows():
64 return os.name == 'nt'
65
Jean-Marie Henaffe4e36d12018-04-05 10:33:50 +020066def DownloadFromX20(sha1_file):
67 download_script = os.path.join(REPO_ROOT, 'tools', 'download_from_x20.py')
68 cmd = [download_script, sha1_file]
69 PrintCmd(cmd)
70 subprocess.check_call(cmd)
71
Mads Ager418d1ca2017-05-22 09:35:49 +020072def DownloadFromGoogleCloudStorage(sha1_file, bucket='r8-deps'):
Rico Windf80f5a22017-06-16 09:15:57 +020073 suffix = '.bat' if IsWindows() else ''
74 download_script = 'download_from_google_storage%s' % suffix
75 cmd = [download_script, '-n', '-b', bucket, '-u', '-s',
Mads Ager418d1ca2017-05-22 09:35:49 +020076 sha1_file]
77 PrintCmd(cmd)
78 subprocess.check_call(cmd)
79
80def get_sha1(filename):
81 sha1 = hashlib.sha1()
82 with open(filename, 'rb') as f:
83 while True:
84 chunk = f.read(1024*1024)
85 if not chunk:
86 break
87 sha1.update(chunk)
88 return sha1.hexdigest()
89
Rico Wind1b09c562019-01-17 08:53:09 +010090def is_master():
91 remotes = subprocess.check_output(['git', 'branch', '-r', '--contains',
92 'HEAD'])
93 return 'origin/master' in remotes
94
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +020095def get_HEAD_sha1():
96 cmd = ['git', 'rev-parse', 'HEAD']
97 PrintCmd(cmd)
98 with ChangedWorkingDirectory(REPO_ROOT):
99 return subprocess.check_output(cmd).strip()
100
Tamas Kenez971eec62017-05-24 11:08:40 +0200101def makedirs_if_needed(path):
102 try:
103 os.makedirs(path)
104 except OSError:
105 if not os.path.isdir(path):
106 raise
107
Rico Wind800fd712018-09-24 11:29:33 +0200108def upload_dir_to_cloud_storage(directory, destination, is_html=False, public_read=True):
Rico Winda94f01c2017-06-27 10:32:34 +0200109 # Upload and make the content encoding right for viewing directly
Rico Windd0d88cf2018-02-09 09:46:11 +0100110 cmd = ['gsutil.py', 'cp']
111 if is_html:
112 cmd += ['-z', 'html']
Rico Wind800fd712018-09-24 11:29:33 +0200113 if public_read:
114 cmd += ['-a', 'public-read']
115 cmd += ['-R', directory, destination]
Rico Winda94f01c2017-06-27 10:32:34 +0200116 PrintCmd(cmd)
117 subprocess.check_call(cmd)
118
Rico Wind800fd712018-09-24 11:29:33 +0200119def upload_file_to_cloud_storage(source, destination, public_read=True):
120 cmd = ['gsutil.py', 'cp']
121 if public_read:
122 cmd += ['-a', 'public-read']
123 cmd += [source, destination]
Rico Windb4621c12017-08-28 12:48:53 +0200124 PrintCmd(cmd)
125 subprocess.check_call(cmd)
126
Rico Wind139eece2018-09-25 09:42:09 +0200127def delete_file_from_cloud_storage(destination):
128 cmd = ['gsutil.py', 'rm', destination]
129 PrintCmd(cmd)
130 subprocess.check_call(cmd)
131
Rico Wind4fd2dda2018-09-26 17:41:45 +0200132def ls_files_on_cloud_storage(destination):
133 cmd = ['gsutil.py', 'ls', destination]
134 PrintCmd(cmd)
135 return subprocess.check_output(cmd)
136
Rico Wind139eece2018-09-25 09:42:09 +0200137def cat_file_on_cloud_storage(destination, ignore_errors=False):
138 cmd = ['gsutil.py', 'cat', destination]
139 PrintCmd(cmd)
140 try:
141 return subprocess.check_output(cmd)
142 except subprocess.CalledProcessError as e:
143 if ignore_errors:
144 return ''
145 else:
146 raise e
147
148def file_exists_on_cloud_storage(destination):
149 cmd = ['gsutil.py', 'ls', destination]
150 PrintCmd(cmd)
151 return subprocess.call(cmd) == 0
152
Jean-Marie Henaff7a64eec2018-05-31 15:30:35 +0200153def download_file_from_cloud_storage(source, destination):
154 cmd = ['gsutil.py', 'cp', source, destination]
155 PrintCmd(cmd)
156 subprocess.check_call(cmd)
157
158def create_archive(name):
159 tarname = '%s.tar.gz' % name
160 with tarfile.open(tarname, 'w:gz') as tar:
161 tar.add(name)
162 return tarname
163
164def extract_dir(filename):
165 return filename[0:len(filename) - len('.tar.gz')]
166
167def unpack_archive(filename):
168 dest_dir = extract_dir(filename)
169 if os.path.exists(dest_dir):
170 print 'Deleting existing dir %s' % dest_dir
171 shutil.rmtree(dest_dir)
172 dirname = os.path.dirname(os.path.abspath(filename))
173 with tarfile.open(filename, 'r:gz') as tar:
174 tar.extractall(path=dirname)
175
Rico Wind1a29c4f2018-01-25 08:43:08 +0100176# Note that gcs is eventually consistent with regards to list operations.
177# This is not a problem in our case, but don't ever use this method
178# for synchronization.
179def cloud_storage_exists(destination):
180 cmd = ['gsutil.py', 'ls', destination]
181 PrintCmd(cmd)
182 exit_code = subprocess.call(cmd)
183 return exit_code == 0
184
Mads Ager418d1ca2017-05-22 09:35:49 +0200185class TempDir(object):
186 def __init__(self, prefix=''):
187 self._temp_dir = None
188 self._prefix = prefix
189
190 def __enter__(self):
191 self._temp_dir = tempfile.mkdtemp(self._prefix)
192 return self._temp_dir
193
194 def __exit__(self, *_):
195 shutil.rmtree(self._temp_dir, ignore_errors=True)
196
197class ChangedWorkingDirectory(object):
198 def __init__(self, working_directory):
199 self._working_directory = working_directory
200
201 def __enter__(self):
202 self._old_cwd = os.getcwd()
Rico Windf80f5a22017-06-16 09:15:57 +0200203 print 'Enter directory = ', self._working_directory
Mads Ager418d1ca2017-05-22 09:35:49 +0200204 os.chdir(self._working_directory)
205
206 def __exit__(self, *_):
Rico Windf80f5a22017-06-16 09:15:57 +0200207 print 'Enter directory = ', self._old_cwd
Mads Ager418d1ca2017-05-22 09:35:49 +0200208 os.chdir(self._old_cwd)
Tamas Kenez82efeb52017-06-12 13:56:22 +0200209
210# Reading Android CTS test_result.xml
211
212class CtsModule(object):
213 def __init__(self, module_name):
214 self.name = module_name
215
216class CtsTestCase(object):
217 def __init__(self, test_case_name):
218 self.name = test_case_name
219
220class CtsTest(object):
221 def __init__(self, test_name, outcome):
222 self.name = test_name
223 self.outcome = outcome
224
225# Generator yielding CtsModule, CtsTestCase or CtsTest from
226# reading through a CTS test_result.xml file.
227def read_cts_test_result(file_xml):
228 re_module = re.compile('<Module name="([^"]*)"')
229 re_test_case = re.compile('<TestCase name="([^"]*)"')
230 re_test = re.compile('<Test result="(pass|fail)" name="([^"]*)"')
231 with open(file_xml) as f:
232 for line in f:
233 m = re_module.search(line)
234 if m:
235 yield CtsModule(m.groups()[0])
236 continue
237 m = re_test_case.search(line)
238 if m:
239 yield CtsTestCase(m.groups()[0])
240 continue
241 m = re_test.search(line)
242 if m:
243 outcome = m.groups()[0]
Rico Windf80f5a22017-06-16 09:15:57 +0200244 assert outcome in ['fail', 'pass']
Tamas Kenez82efeb52017-06-12 13:56:22 +0200245 yield CtsTest(m.groups()[1], outcome == 'pass')
Tamas Kenezfc34cd82017-07-13 12:43:57 +0200246
247def grep_memoryuse(logfile):
248 re_vmhwm = re.compile('^VmHWM:[ \t]*([0-9]+)[ \t]*([a-zA-Z]*)')
249 result = None
250 with open(logfile) as f:
251 for line in f:
252 m = re_vmhwm.search(line)
253 if m:
254 groups = m.groups()
255 s = len(groups)
256 if s >= 1:
257 result = int(groups[0])
258 if s >= 2:
259 unit = groups[1]
260 if unit == 'kB':
261 result *= 1024
262 elif unit != '':
263 raise Exception('Unrecognized unit in memory usage log: {}'
264 .format(unit))
265 if result is None:
266 raise Exception('No memory usage found in log: {}'.format(logfile))
Tamas Kenez02bff032017-07-18 12:13:58 +0200267 return result
268
269# Return a dictionary: {segment_name -> segments_size}
270def getDexSegmentSizes(dex_files):
271 assert len(dex_files) > 0
Mathias Rav9cf6a742018-05-22 09:34:45 +0200272 cmd = ['java', '-jar', R8_JAR, 'dexsegments']
Tamas Kenez02bff032017-07-18 12:13:58 +0200273 cmd.extend(dex_files)
274 PrintCmd(cmd)
275 output = subprocess.check_output(cmd)
276
277 matches = DEX_SEGMENTS_RESULT_PATTERN.findall(output)
278
279 if matches is None or len(matches) == 0:
280 raise Exception('DexSegments failed to return any output for' \
281 ' these files: {}'.format(dex_files))
282
283 result = {}
284
285 for match in matches:
286 result[match[0]] = int(match[1])
287
288 return result
289
Rico Windc0b16382018-05-17 13:23:43 +0200290def get_maven_path(version):
291 return os.path.join('com', 'android', 'tools', 'r8', version)
292
Tamas Kenez02bff032017-07-18 12:13:58 +0200293def print_dexsegments(prefix, dex_files):
294 for segment_name, size in getDexSegmentSizes(dex_files).items():
295 print('{}-{}(CodeSize): {}'
296 .format(prefix, segment_name, size))
Tamas Kenez2cf47cf2017-07-25 10:22:52 +0200297
Mads Agerbc7b2ce2018-02-05 11:28:47 +0100298# Ensure that we are not benchmarking with a google jvm.
Tamas Kenez2cf47cf2017-07-25 10:22:52 +0200299def check_java_version():
300 cmd= ['java', '-version']
301 output = subprocess.check_output(cmd, stderr = subprocess.STDOUT)
302 m = re.search('openjdk version "([^"]*)"', output)
303 if m is None:
304 raise Exception("Can't check java version: no version string in output"
305 " of 'java -version': '{}'".format(output))
306 version = m.groups(0)[0]
Mads Agerbc7b2ce2018-02-05 11:28:47 +0100307 m = re.search('google', version)
308 if m is not None:
309 raise Exception("Do not use google JVM for benchmarking: " + version)
Tamas Kenez0cad51c2017-08-21 14:42:01 +0200310
Rico Wind9d70f612018-08-31 09:17:43 +0200311def get_android_jar(api):
312 return os.path.join(REPO_ROOT, ANDROID_JAR.format(api=api))
Rico Windda6836e2018-12-07 12:32:03 +0100313
314def is_bot():
315 return 'BUILDBOT_BUILDERNAME' in os.environ