blob: c313cb971a380787d16107178f514c52b27b74c1 [file] [log] [blame]
Ian Zernydcb172e2022-02-22 15:36:45 +01001#!/usr/bin/env python3
Ian Zerny5ffa58f2020-02-26 08:37:14 +01002# Copyright (c) 2020, the R8 project authors. Please see the AUTHORS file
3# for details. All rights reserved. Use of this source code is governed by a
4# BSD-style license that can be found in the LICENSE file.
5
6import argparse
7import os
Christoffer Quist Adamsen3f21c2b2023-02-28 09:37:22 +01008import shutil
Ian Zerny5ffa58f2020-02-26 08:37:14 +01009import subprocess
10import sys
11import zipfile
12
Ian Zerny0e53ff12021-06-15 13:40:14 +020013import archive
14import jdk
15import retrace
Ian Zerny5ffa58f2020-02-26 08:37:14 +010016import utils
17
18
19def make_parser():
20 parser = argparse.ArgumentParser(description = 'Compile a dump artifact.')
21 parser.add_argument(
Ian Zerny0e53ff12021-06-15 13:40:14 +020022 '--summary',
23 help='List a summary of the contents of the dumps.',
24 default=False,
25 action='store_true')
26 parser.add_argument(
Ian Zerny5ffa58f2020-02-26 08:37:14 +010027 '-d',
28 '--dump',
Christoffer Quist Adamsend84a6f02020-05-16 12:29:35 +020029 help='Dump file or directory to compile',
Ian Zerny5ffa58f2020-02-26 08:37:14 +010030 default=None)
31 parser.add_argument(
Rico Wind9ed87b92020-03-06 12:37:18 +010032 '--temp',
33 help='Temp directory to extract the dump to, allows you to rerun the command'
34 ' more easily in the terminal with changes',
35 default=None)
36 parser.add_argument(
Ian Zerny5ffa58f2020-02-26 08:37:14 +010037 '-c',
38 '--compiler',
Rico Windf73f18d2020-03-03 09:28:54 +010039 help='Compiler to use',
Ian Zerny5ffa58f2020-02-26 08:37:14 +010040 default=None)
41 parser.add_argument(
Christoffer Quist Adamsenf86fc0b2021-12-10 12:39:36 +010042 '--minify',
43 help='Force enable/disable minification'
44 ' (defaults to app proguard config)',
45 choices=['default', 'force-enable', 'force-disable'],
46 default='default')
47 parser.add_argument(
48 '--optimize',
49 help='Force enable/disable optimizations'
50 ' (defaults to app proguard config)',
51 choices=['default', 'force-enable', 'force-disable'],
52 default='default')
53 parser.add_argument(
54 '--shrink',
55 help='Force enable/disable shrinking'
56 ' (defaults to app proguard config)',
57 choices=['default', 'force-enable', 'force-disable'],
58 default='default')
59 parser.add_argument(
Ian Zerny5ffa58f2020-02-26 08:37:14 +010060 '-v',
61 '--version',
62 help='Compiler version to use (default read from dump version file).'
63 'Valid arguments are:'
Rico Wind1b52acf2021-03-21 12:36:55 +010064 ' "main" to run from your own tree,'
Morten Krogh-Jespersen51db2b02020-11-11 12:49:26 +010065 ' "source" to run from build classes directly,'
Ian Zerny5ffa58f2020-02-26 08:37:14 +010066 ' "X.Y.Z" to run a specific version, or'
Rico Wind1b52acf2021-03-21 12:36:55 +010067 ' <hash> to run that hash from main.',
Ian Zerny5ffa58f2020-02-26 08:37:14 +010068 default=None)
69 parser.add_argument(
Morten Krogh-Jespersend8bceb52020-03-06 12:56:48 +010070 '--r8-jar',
71 help='Path to an R8 jar.',
72 default=None)
73 parser.add_argument(
Christoffer Quist Adamsen2f48f3f2021-10-14 17:25:03 +020074 '--r8-flags', '--r8_flags',
75 help='Additional option(s) for the compiler.')
76 parser.add_argument(
Christoffer Quist Adamsen3f21c2b2023-02-28 09:37:22 +010077 '--pg-conf', '--pg_conf',
78 help='Keep rule file(s).',
79 action='append')
80 parser.add_argument(
Morten Krogh-Jespersen1fbfd592021-11-26 13:41:32 +010081 '--override',
Morten Krogh-Jespersen9206a662020-11-23 08:47:06 +010082 help='Do not override any extracted dump in temp-dir',
83 default=False,
84 action='store_true')
85 parser.add_argument(
Ian Zerny5ffa58f2020-02-26 08:37:14 +010086 '--nolib',
87 help='Use the non-lib distribution (default uses the lib distribution)',
88 default=False,
89 action='store_true')
90 parser.add_argument(
Morten Krogh-Jespersen6c702402021-06-21 12:29:48 +020091 '--print-times',
Rico Wind28653642020-03-31 13:59:07 +020092 help='Print timing information from r8',
93 default=False,
94 action='store_true')
95 parser.add_argument(
Ian Zerny5ffa58f2020-02-26 08:37:14 +010096 '--ea',
97 help='Enable Java assertions when running the compiler (default disabled)',
98 default=False,
99 action='store_true')
100 parser.add_argument(
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +0100101 '--classfile',
102 help='Run with classfile output',
103 default=False,
104 action='store_true')
105 parser.add_argument(
Ian Zerny5ffa58f2020-02-26 08:37:14 +0100106 '--debug-agent',
107 help='Enable Java debug agent and suspend compilation (default disabled)',
108 default=False,
109 action='store_true')
Ian Zerny77bdf5f2020-07-08 11:46:24 +0200110 parser.add_argument(
111 '--xmx',
112 help='Set JVM max heap size (-Xmx)',
113 default=None)
114 parser.add_argument(
115 '--threads',
116 help='Set the number of threads to use',
117 default=None)
118 parser.add_argument(
119 '--min-api',
120 help='Set min-api (default read from dump properties file)',
121 default=None)
Søren Gjesse7360f2b2020-08-10 09:13:35 +0200122 parser.add_argument(
Clément Béradaae4ca2020-10-27 14:26:41 +0000123 '--desugared-lib',
124 help='Set desugared-library (default set from dump)',
125 default=None)
126 parser.add_argument(
Morten Krogh-Jespersend86a81b2020-11-13 12:33:26 +0100127 '--disable-desugared-lib',
128 help='Disable desugared-libary if it will be set from dump',
129 default=False,
130 action='store_true'
131 )
132 parser.add_argument(
Søren Gjesse7360f2b2020-08-10 09:13:35 +0200133 '--loop',
134 help='Run the compilation in a loop',
135 default=False,
136 action='store_true')
Morten Krogh-Jespersen9e201ea2022-06-14 12:41:50 +0200137 parser.add_argument(
138 '--enable-missing-library-api-modeling',
139 help='Run with api modeling',
140 default=False,
141 action='store_true')
142 parser.add_argument(
143 '--android-platform-build',
144 help='Run as a platform build',
145 default=False,
146 action='store_true')
Morten Krogh-Jespersenaa2f9ec2022-07-04 13:10:17 +0200147 parser.add_argument(
148 '--compilation-mode', '--compilation_mode',
149 help='Run compilation in specified mode',
150 choices=['debug', 'release'],
151 default=None)
Ian Zerny5ffa58f2020-02-26 08:37:14 +0100152 return parser
153
154def error(msg):
Rico Wind3d369b42021-01-12 10:26:24 +0100155 print(msg)
Ian Zerny5ffa58f2020-02-26 08:37:14 +0100156 sys.exit(1)
157
158class Dump(object):
159
160 def __init__(self, directory):
161 self.directory = directory
162
163 def if_exists(self, name):
164 f = os.path.join(self.directory, name)
165 if os.path.exists(f):
166 return f
167 return None
168
169 def program_jar(self):
170 return self.if_exists('program.jar')
171
Christoffer Quist Adamsenfcfc63a2020-05-15 19:04:24 +0200172 def feature_jars(self):
173 feature_jars = []
174 i = 1
175 while True:
176 feature_jar = self.if_exists('feature-%s.jar' % i)
177 if feature_jar:
178 feature_jars.append(feature_jar)
179 i = i + 1
180 else:
181 return feature_jars
182
Ian Zerny5ffa58f2020-02-26 08:37:14 +0100183 def library_jar(self):
184 return self.if_exists('library.jar')
185
186 def classpath_jar(self):
187 return self.if_exists('classpath.jar')
188
Clément Béradaae4ca2020-10-27 14:26:41 +0000189 def desugared_library_json(self):
190 return self.if_exists('desugared-library.json')
191
Clément Béra64a3c4c2020-11-10 08:16:17 +0000192 def proguard_input_map(self):
193 if self.if_exists('proguard_input.config'):
Rico Wind3d369b42021-01-12 10:26:24 +0100194 print("Unimplemented: proguard_input configuration.")
Clément Béra64a3c4c2020-11-10 08:16:17 +0000195
Morten Krogh-Jespersen1e774252021-03-01 16:56:07 +0100196 def main_dex_list_resource(self):
Christoffer Quist Adamsencd7f7ec2022-08-26 13:39:11 +0200197 return self.if_exists('main-dex-list.txt')
Clément Béra64a3c4c2020-11-10 08:16:17 +0000198
Morten Krogh-Jespersen1e774252021-03-01 16:56:07 +0100199 def main_dex_rules_resource(self):
200 return self.if_exists('main-dex-rules.txt')
201
Christoffer Quist Adamsen819273a2023-03-02 15:20:45 +0100202 def art_profile_resources(self):
203 art_profile_resources = []
204 while True:
205 current_art_profile_index = len(art_profile_resources) + 1
206 art_profile_resource = self.if_exists(
207 'art-profile-%s.txt' % current_art_profile_index)
208 if art_profile_resource is None:
209 return art_profile_resources
210 art_profile_resources.append(art_profile_resource)
211
Christoffer Quist Adamsencd7f7ec2022-08-26 13:39:11 +0200212 def startup_profile_resources(self):
213 startup_profile_resources = []
214 while True:
215 current_startup_profile_index = len(startup_profile_resources) + 1
216 startup_profile_resource = self.if_exists(
217 'startup-profile-%s.txt' % current_startup_profile_index)
218 if startup_profile_resource is None:
219 return startup_profile_resources
220 startup_profile_resources.append(startup_profile_resource)
221
Christoffer Quist Adamsenfcfc63a2020-05-15 19:04:24 +0200222 def build_properties_file(self):
223 return self.if_exists('build.properties')
224
Ian Zerny5ffa58f2020-02-26 08:37:14 +0100225 def config_file(self):
226 return self.if_exists('proguard.config')
227
228 def version_file(self):
229 return self.if_exists('r8-version')
230
231 def version(self):
232 f = self.version_file()
233 if f:
234 return open(f).read().split(' ')[0]
235 return None
236
Ian Zerny0e53ff12021-06-15 13:40:14 +0200237def read_dump_from_args(args, temp):
Ian Zerny5ffa58f2020-02-26 08:37:14 +0100238 if args.dump is None:
Christoffer Quist Adamsend84a6f02020-05-16 12:29:35 +0200239 error("A dump file or directory must be specified")
Ian Zerny674099e2021-06-15 13:44:37 +0200240 return read_dump(args.dump, temp, args.override)
Ian Zerny0e53ff12021-06-15 13:40:14 +0200241
242def read_dump(dump, temp, override=False):
243 if os.path.isdir(dump):
244 return Dump(dump)
245 dump_file = zipfile.ZipFile(os.path.abspath(dump), 'r')
246 with utils.ChangedWorkingDirectory(temp, quiet=True):
247 if override or not os.path.isfile('r8-version'):
Morten Krogh-Jespersen9206a662020-11-23 08:47:06 +0100248 dump_file.extractall()
Ian Zerny202330b2021-05-03 13:23:04 +0200249 if not os.path.isfile('r8-version'):
Morten Krogh-Jespersen9206a662020-11-23 08:47:06 +0100250 error("Did not extract into %s. Either the zip file is invalid or the "
251 "dump is missing files" % temp)
Ian Zerny5ffa58f2020-02-26 08:37:14 +0100252 return Dump(temp)
253
Christoffer Quist Adamsenfcfc63a2020-05-15 19:04:24 +0200254def determine_build_properties(args, dump):
255 build_properties = {}
256 build_properties_file = dump.build_properties_file()
257 if build_properties_file:
258 with open(build_properties_file) as f:
259 build_properties_contents = f.readlines()
260 for line in build_properties_contents:
261 stripped = line.strip()
262 if stripped:
263 pair = stripped.split('=')
264 build_properties[pair[0]] = pair[1]
Rico Windcfe1b2a2023-03-03 08:11:39 +0100265 if 'mode' not in build_properties:
266 build_properties['mode'] = 'release'
Christoffer Quist Adamsenfcfc63a2020-05-15 19:04:24 +0200267 return build_properties
268
Ian Zerny5ffa58f2020-02-26 08:37:14 +0100269def determine_version(args, dump):
270 if args.version is None:
271 return dump.version()
272 return args.version
273
Søren Gjesse0f8d88b2021-09-28 15:15:54 +0200274def determine_compiler(args, build_properties):
Morten Krogh-Jespersendd12e782023-03-01 16:34:51 +0100275 compilers = ['d8', 'r8', 'r8full', 'l8', 'l8d8', 'tracereferences']
Søren Gjesse0f8d88b2021-09-28 15:15:54 +0200276 compiler = args.compiler
277 if not compiler and 'tool' in build_properties:
278 compiler = build_properties.get('tool').lower()
Morten Krogh-Jespersendd12e782023-03-01 16:34:51 +0100279 if compiler == 'r8':
Søren Gjesse0f8d88b2021-09-28 15:15:54 +0200280 if not 'force-proguard-compatibility' in build_properties:
281 error("Unable to determine R8 compiler variant from build.properties."
282 " No value for 'force-proguard-compatibility'.")
283 if build_properties.get('force-proguard-compatibility').lower() == 'false':
284 compiler = compiler + 'full'
Morten Krogh-Jespersendd12e782023-03-01 16:34:51 +0100285 if compiler == 'TraceReferences':
286 compiler = build_properties.get('tool').lower()
Søren Gjesse0f8d88b2021-09-28 15:15:54 +0200287 if compiler not in compilers:
Rico Windf73f18d2020-03-03 09:28:54 +0100288 error("Unable to determine a compiler to use. Specified %s,"
289 " Valid options: %s" % (args.compiler, ', '.join(compilers)))
Søren Gjesse0f8d88b2021-09-28 15:15:54 +0200290 return compiler
Ian Zerny5ffa58f2020-02-26 08:37:14 +0100291
Morten Krogh-Jespersendd12e782023-03-01 16:34:51 +0100292def determine_trace_references_commands(build_properties, output):
293 trace_ref_consumer = build_properties.get('trace_references_consumer')
294 if trace_ref_consumer == 'com.android.tools.r8.tracereferences.TraceReferencesCheckConsumer':
295 return ["--check"]
296 else:
297 assert trace_ref_consumer == 'com.android.tools.r8.tracereferences.TraceReferencesKeepRules'
298 args = ['--allowobfuscation'] if build_properties.get('minification') == 'true' else []
299 args.extend(['--keep-rules', '--output', output])
300 return args
301
Christoffer Quist Adamsen7953d0a2023-02-27 12:08:33 +0100302def is_l8_compiler(compiler):
303 return compiler.startswith('l8')
304
Christoffer Quist Adamsen3f21c2b2023-02-28 09:37:22 +0100305def is_r8_compiler(compiler):
306 return compiler.startswith('r8')
307
308def determine_config_files(args, dump, temp):
309 if args.pg_conf:
310 config_files = []
311 for config_file in args.pg_conf:
312 dst = os.path.join(temp, 'proguard-%s.config' % len(config_files))
313 shutil.copyfile(config_file, dst)
314 config_files.append(dst)
315 return config_files
316 dump_config_file = dump.config_file()
317 if dump_config_file:
318 return [dump_config_file]
319 return []
320
Ian Zerny5ffa58f2020-02-26 08:37:14 +0100321def determine_output(args, temp):
322 return os.path.join(temp, 'out.jar')
323
Ian Zerny77bdf5f2020-07-08 11:46:24 +0200324def determine_min_api(args, build_properties):
325 if args.min_api:
326 return args.min_api
327 if 'min-api' in build_properties:
328 return build_properties.get('min-api')
329 return None
330
Christoffer Quist Adamsen819273a2023-03-02 15:20:45 +0100331def determine_residual_art_profile_output(art_profile, temp):
332 return os.path.join(temp, os.path.basename(art_profile)[:-4] + ".out.txt")
333
Christoffer Quist Adamsen3f21c2b2023-02-28 09:37:22 +0100334def determine_desugared_lib_pg_conf_output(temp):
335 return os.path.join(temp, 'desugared-library-keep-rules.config')
336
Christoffer Quist Adamsenfcfc63a2020-05-15 19:04:24 +0200337def determine_feature_output(feature_jar, temp):
338 return os.path.join(temp, os.path.basename(feature_jar)[:-4] + ".out.jar")
339
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +0100340def determine_program_jar(args, dump):
341 if hasattr(args, 'program_jar') and args.program_jar:
342 return args.program_jar
343 return dump.program_jar()
344
345def determine_class_file(args, build_properties):
Christoffer Quist Adamsen0a3c16e2023-02-15 14:34:44 +0100346 return args.classfile \
347 or build_properties.get('backend', 'dex').lower() == 'cf'
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +0100348
Morten Krogh-Jespersen9e201ea2022-06-14 12:41:50 +0200349def determine_android_platform_build(args, build_properties):
350 if args.android_platform_build:
Morten Krogh-Jespersen9e201ea2022-06-14 12:41:50 +0200351 return True
Morten Krogh-Jespersenaa2f9ec2022-07-04 13:10:17 +0200352 return build_properties.get('android-platform-build') == 'true'
Morten Krogh-Jespersen9e201ea2022-06-14 12:41:50 +0200353
354def determine_enable_missing_library_api_modeling(args, build_properties):
355 if args.enable_missing_library_api_modeling:
Morten Krogh-Jespersen9e201ea2022-06-14 12:41:50 +0200356 return True
Morten Krogh-Jespersenaa2f9ec2022-07-04 13:10:17 +0200357 return build_properties.get('enable-missing-library-api-modeling') == 'true'
358
359def determine_compilation_mode(args, build_properties):
360 if args.compilation_mode:
361 return args.compilation_mode
362 return build_properties.get('mode')
Morten Krogh-Jespersen9e201ea2022-06-14 12:41:50 +0200363
Søren Gjesse1768e252021-10-06 12:50:36 +0200364def determine_properties(build_properties):
365 args = []
366 for key, value in build_properties.items():
367 # When writing dumps all system properties starting with com.android.tools.r8
368 # are written to the build.properties file in the format
369 # system-property-com.android.tools.r8.XXX=<value>
370 if key.startswith('system-property-'):
371 name = key[len('system-property-'):]
372 if name.endswith('dumpinputtofile') or name.endswith('dumpinputtodirectory'):
373 continue
374 if len(value) == 0:
375 args.append('-D' + name)
376 else:
377 args.append('-D' + name + '=' + value)
378 return args
379
Ian Zerny171c6a62022-04-04 14:25:30 +0200380def download_distribution(version, nolib, temp):
Rico Wind1b52acf2021-03-21 12:36:55 +0100381 if version == 'main':
Ian Zerny171c6a62022-04-04 14:25:30 +0200382 return utils.R8_JAR if nolib else utils.R8LIB_JAR
Morten Krogh-Jespersen51db2b02020-11-11 12:49:26 +0100383 if version == 'source':
384 return '%s:%s' % (utils.BUILD_JAVA_MAIN_DIR, utils.ALL_DEPS_JAR)
Ian Zerny171c6a62022-04-04 14:25:30 +0200385 name = 'r8.jar' if nolib else 'r8lib.jar'
Ian Zerny5ffa58f2020-02-26 08:37:14 +0100386 source = archive.GetUploadDestination(version, name, is_hash(version))
387 dest = os.path.join(temp, 'r8.jar')
388 utils.download_file_from_cloud_storage(source, dest)
389 return dest
390
Christoffer Quist Adamsen3f21c2b2023-02-28 09:37:22 +0100391def clean_configs(files, args):
392 for file in files:
393 clean_config(file, args)
Rico Windc9e52f72021-08-19 08:30:26 +0200394
Christoffer Quist Adamsenf86fc0b2021-12-10 12:39:36 +0100395def clean_config(file, args):
Rico Windc9e52f72021-08-19 08:30:26 +0200396 with open(file) as f:
397 lines = f.readlines()
Christoffer Quist Adamsenf86fc0b2021-12-10 12:39:36 +0100398 minify = args.minify
399 optimize = args.optimize
400 shrink = args.shrink
Rico Windc9e52f72021-08-19 08:30:26 +0200401 with open(file, 'w') as f:
Christoffer Quist Adamsenf86fc0b2021-12-10 12:39:36 +0100402 if minify == 'force-disable':
403 print('Adding config line: -dontobfuscate')
404 f.write('-dontobfuscate\n')
405 if optimize == 'force-disable':
406 print('Adding config line: -dontoptimize')
407 f.write('-dontoptimize\n')
408 if shrink == 'force-disable':
409 print('Adding config line: -dontshrink')
410 f.write('-dontshrink\n')
Rico Windc9e52f72021-08-19 08:30:26 +0200411 for line in lines:
Christoffer Quist Adamsenf86fc0b2021-12-10 12:39:36 +0100412 if clean_config_line(line, minify, optimize, shrink):
Rico Windc9e52f72021-08-19 08:30:26 +0200413 print('Removing from config line: \n%s' % line)
Christoffer Quist Adamsenf86fc0b2021-12-10 12:39:36 +0100414 else:
415 f.write(line)
Rico Windc9e52f72021-08-19 08:30:26 +0200416
Christoffer Quist Adamsenf86fc0b2021-12-10 12:39:36 +0100417def clean_config_line(line, minify, optimize, shrink):
418 if ('-injars' in line or '-libraryjars' in line or
Christoffer Quist Adamsen3f21c2b2023-02-28 09:37:22 +0100419 '-print' in line or '-applymapping' in line):
Christoffer Quist Adamsenf86fc0b2021-12-10 12:39:36 +0100420 return True
421 if minify == 'force-enable' and '-dontobfuscate' in line:
422 return True
423 if optimize == 'force-enable' and '-dontoptimize' in line:
424 return True
425 if shrink == 'force-enable' and '-dontshrink' in line:
426 return True
427 return False
Rico Windc9e52f72021-08-19 08:30:26 +0200428
Morten Krogh-Jespersen327e76d2022-06-23 09:31:13 +0200429def prepare_r8_wrapper(dist, temp, jdkhome):
Christoffer Quist Adamsen819273a2023-03-02 15:20:45 +0100430 compile_wrapper_with_javac(
Morten Krogh-Jespersen327e76d2022-06-23 09:31:13 +0200431 dist,
432 temp,
433 jdkhome,
434 os.path.join(
Ian Zerny5ffa58f2020-02-26 08:37:14 +0100435 utils.REPO_ROOT,
Morten Krogh-Jespersen327e76d2022-06-23 09:31:13 +0200436 'src/main/java/com/android/tools/r8/utils/CompileDumpCompatR8.java'))
437
438def prepare_d8_wrapper(dist, temp, jdkhome):
Christoffer Quist Adamsen819273a2023-03-02 15:20:45 +0100439 compile_wrapper_with_javac(
Morten Krogh-Jespersen327e76d2022-06-23 09:31:13 +0200440 dist,
441 temp,
442 jdkhome,
443 os.path.join(
444 utils.REPO_ROOT,
445 'src/main/java/com/android/tools/r8/utils/CompileDumpD8.java'))
446
Christoffer Quist Adamsen819273a2023-03-02 15:20:45 +0100447def compile_wrapper_with_javac(dist, temp, jdkhome, path):
448 base_path = os.path.join(
449 utils.REPO_ROOT,
450 'src/main/java/com/android/tools/r8/utils/CompileDumpBase.java')
Ian Zerny268c9632020-11-13 11:36:35 +0100451 cmd = [
Rico Wind33936d12021-04-07 08:04:14 +0200452 jdk.GetJavacExecutable(jdkhome),
Morten Krogh-Jespersen327e76d2022-06-23 09:31:13 +0200453 path,
Christoffer Quist Adamsen819273a2023-03-02 15:20:45 +0100454 base_path,
Ian Zerny5ffa58f2020-02-26 08:37:14 +0100455 '-d', temp,
456 '-cp', dist,
Ian Zerny268c9632020-11-13 11:36:35 +0100457 ]
458 utils.PrintCmd(cmd)
459 subprocess.check_output(cmd)
Ian Zerny5ffa58f2020-02-26 08:37:14 +0100460
461def is_hash(version):
462 return len(version) == 40
463
Rico Wind33936d12021-04-07 08:04:14 +0200464def run1(out, args, otherargs, jdkhome=None):
Ian Zerny09d42832022-11-17 07:45:02 +0100465 jvmargs = []
466 compilerargs = []
467 for arg in otherargs:
468 if arg.startswith('-D'):
469 jvmargs.append(arg)
470 else:
471 compilerargs.append(arg)
Ian Zerny5ffa58f2020-02-26 08:37:14 +0100472 with utils.TempDir() as temp:
Søren Gjesse7360f2b2020-08-10 09:13:35 +0200473 if out:
474 temp = out
Rico Wind9ed87b92020-03-06 12:37:18 +0100475 if not os.path.exists(temp):
476 os.makedirs(temp)
Ian Zerny0e53ff12021-06-15 13:40:14 +0200477 dump = read_dump_from_args(args, temp)
Ian Zerny46bc4cf2020-08-03 15:58:27 +0200478 if not dump.program_jar():
479 error("Cannot compile dump with no program classes")
480 if not dump.library_jar():
Rico Wind3d369b42021-01-12 10:26:24 +0100481 print("WARNING: Unexpected lack of library classes in dump")
Christoffer Quist Adamsenfcfc63a2020-05-15 19:04:24 +0200482 build_properties = determine_build_properties(args, dump)
Ian Zerny5ffa58f2020-02-26 08:37:14 +0100483 version = determine_version(args, dump)
Søren Gjesse0f8d88b2021-09-28 15:15:54 +0200484 compiler = determine_compiler(args, build_properties)
Christoffer Quist Adamsen3f21c2b2023-02-28 09:37:22 +0100485 config_files = determine_config_files(args, dump, temp)
Ian Zerny5ffa58f2020-02-26 08:37:14 +0100486 out = determine_output(args, temp)
Ian Zerny77bdf5f2020-07-08 11:46:24 +0200487 min_api = determine_min_api(args, build_properties)
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +0100488 classfile = determine_class_file(args, build_properties)
Morten Krogh-Jespersen9e201ea2022-06-14 12:41:50 +0200489 android_platform_build = determine_android_platform_build(args, build_properties)
490 enable_missing_library_api_modeling = determine_enable_missing_library_api_modeling(args, build_properties)
Morten Krogh-Jespersenaa2f9ec2022-07-04 13:10:17 +0200491 mode = determine_compilation_mode(args, build_properties)
Ian Zerny171c6a62022-04-04 14:25:30 +0200492 jar = args.r8_jar if args.r8_jar else download_distribution(version, args.nolib, temp)
Ian Zerny268c9632020-11-13 11:36:35 +0100493 if ':' not in jar and not os.path.exists(jar):
494 error("Distribution does not exist: " + jar)
Rico Wind33936d12021-04-07 08:04:14 +0200495 cmd = [jdk.GetJavaExecutable(jdkhome)]
Ian Zerny09d42832022-11-17 07:45:02 +0100496 cmd.extend(jvmargs)
Ian Zerny5ffa58f2020-02-26 08:37:14 +0100497 if args.debug_agent:
498 if not args.nolib:
Rico Wind3d369b42021-01-12 10:26:24 +0100499 print("WARNING: Running debugging agent on r8lib is questionable...")
Ian Zerny5ffa58f2020-02-26 08:37:14 +0100500 cmd.append(
501 '-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=*:5005')
Ian Zerny77bdf5f2020-07-08 11:46:24 +0200502 if args.xmx:
503 cmd.append('-Xmx' + args.xmx)
Ian Zerny5ffa58f2020-02-26 08:37:14 +0100504 if args.ea:
505 cmd.append('-ea')
Morten Krogh-Jespersen23f0b032021-07-06 18:10:15 +0200506 cmd.append('-Dcom.android.tools.r8.enableTestAssertions=1')
Morten Krogh-Jespersen6c702402021-06-21 12:29:48 +0200507 if args.print_times:
Rico Wind28653642020-03-31 13:59:07 +0200508 cmd.append('-Dcom.android.tools.r8.printtimes=1')
Christoffer Quist Adamsen2f48f3f2021-10-14 17:25:03 +0200509 if args.r8_flags:
510 cmd.extend(args.r8_flags.split(' '))
Morten Krogh-Jespersen43f3cea2020-11-12 17:09:51 +0100511 if hasattr(args, 'properties'):
Morten Krogh-Jespersendd12e782023-03-01 16:34:51 +0100512 cmd.extend(args.properties)
Søren Gjesse1768e252021-10-06 12:50:36 +0200513 cmd.extend(determine_properties(build_properties))
Morten Krogh-Jespersen327e76d2022-06-23 09:31:13 +0200514 cmd.extend(['-cp', '%s:%s' % (temp, jar)])
Ian Zerny5ffa58f2020-02-26 08:37:14 +0100515 if compiler == 'd8':
Ian Zerny1ad7cac2023-01-09 14:03:04 +0100516 prepare_d8_wrapper(jar, temp, jdkhome)
Morten Krogh-Jespersen327e76d2022-06-23 09:31:13 +0200517 cmd.append('com.android.tools.r8.utils.CompileDumpD8')
Christoffer Quist Adamsen7953d0a2023-02-27 12:08:33 +0100518 if is_l8_compiler(compiler):
Morten Krogh-Jespersenbb624e42021-04-19 14:33:48 +0200519 cmd.append('com.android.tools.r8.L8')
Morten Krogh-Jespersendd12e782023-03-01 16:34:51 +0100520 if compiler == 'tracereferences':
521 cmd.append('com.android.tools.r8.tracereferences.TraceReferences')
522 cmd.extend(determine_trace_references_commands(build_properties, out))
Ian Zerny5ffa58f2020-02-26 08:37:14 +0100523 if compiler.startswith('r8'):
Ian Zerny1ad7cac2023-01-09 14:03:04 +0100524 prepare_r8_wrapper(jar, temp, jdkhome)
Ian Zerny5ffa58f2020-02-26 08:37:14 +0100525 cmd.append('com.android.tools.r8.utils.CompileDumpCompatR8')
526 if compiler == 'r8':
527 cmd.append('--compat')
Morten Krogh-Jespersendd12e782023-03-01 16:34:51 +0100528 if compiler != 'tracereferences':
529 assert mode == 'debug' or mode == 'release'
530 cmd.append('--' + mode)
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +0100531 # For recompilation of dumps run_on_app_dumps pass in a program jar.
Morten Krogh-Jespersendd12e782023-03-01 16:34:51 +0100532 program_jar = determine_program_jar(args, dump)
533 if compiler != 'tracereferences':
534 cmd.append(program_jar)
535 cmd.extend(['--output', out])
536 else:
537 cmd.extend(['--source', program_jar])
Christoffer Quist Adamsenfcfc63a2020-05-15 19:04:24 +0200538 for feature_jar in dump.feature_jars():
539 cmd.extend(['--feature-jar', feature_jar,
540 determine_feature_output(feature_jar, temp)])
Ian Zerny5ffa58f2020-02-26 08:37:14 +0100541 if dump.library_jar():
542 cmd.extend(['--lib', dump.library_jar()])
Christoffer Quist Adamsen7953d0a2023-02-27 12:08:33 +0100543 if dump.classpath_jar() and not is_l8_compiler(compiler):
Morten Krogh-Jespersendd12e782023-03-01 16:34:51 +0100544 cmd.extend(
545 ['--target' if compiler == 'tracereferences' else '--classpath',
546 dump.classpath_jar()])
Morten Krogh-Jespersend86a81b2020-11-13 12:33:26 +0100547 if dump.desugared_library_json() and not args.disable_desugared_lib:
Clément Béradaae4ca2020-10-27 14:26:41 +0000548 cmd.extend(['--desugared-lib', dump.desugared_library_json()])
Christoffer Quist Adamsen3f21c2b2023-02-28 09:37:22 +0100549 if not is_l8_compiler(compiler):
550 cmd.extend([
551 '--desugared-lib-pg-conf-output',
552 determine_desugared_lib_pg_conf_output(temp)])
553 if (is_r8_compiler(compiler) or compiler == 'l8') and config_files:
554 if hasattr(args, 'config_files_consumer') and args.config_files_consumer:
555 args.config_files_consumer(config_files)
Rico Windc9e52f72021-08-19 08:30:26 +0200556 else:
557 # If we get a dump from the wild we can't use -injars, -libraryjars or
558 # -print{mapping,usage}
Christoffer Quist Adamsen3f21c2b2023-02-28 09:37:22 +0100559 clean_configs(config_files, args)
560 for config_file in config_files:
561 cmd.extend(['--pg-conf', config_file])
562 cmd.extend(['--pg-map-output', '%s.map' % out])
Christoffer Quist Adamsencd7f7ec2022-08-26 13:39:11 +0200563 if dump.main_dex_list_resource():
564 cmd.extend(['--main-dex-list', dump.main_dex_list_resource()])
Morten Krogh-Jespersen1e774252021-03-01 16:56:07 +0100565 if dump.main_dex_rules_resource():
566 cmd.extend(['--main-dex-rules', dump.main_dex_rules_resource()])
Christoffer Quist Adamsen819273a2023-03-02 15:20:45 +0100567 for art_profile_resource in dump.art_profile_resources():
568 residual_art_profile_output = \
569 determine_residual_art_profile_output(art_profile_resource, temp)
570 cmd.extend([
571 '--art-profile', art_profile_resource, residual_art_profile_output])
Christoffer Quist Adamsencd7f7ec2022-08-26 13:39:11 +0200572 for startup_profile_resource in dump.startup_profile_resources():
573 cmd.extend(['--startup-profile', startup_profile_resource])
Ian Zerny77bdf5f2020-07-08 11:46:24 +0200574 if min_api:
575 cmd.extend(['--min-api', min_api])
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +0100576 if classfile:
577 cmd.extend(['--classfile'])
Morten Krogh-Jespersen9e201ea2022-06-14 12:41:50 +0200578 if android_platform_build:
579 cmd.extend(['--android-platform-build'])
580 if enable_missing_library_api_modeling:
581 cmd.extend(['--enable-missing-library-api-modeling'])
Ian Zerny77bdf5f2020-07-08 11:46:24 +0200582 if args.threads:
583 cmd.extend(['--threads', args.threads])
Ian Zerny09d42832022-11-17 07:45:02 +0100584 cmd.extend(compilerargs)
Ian Zerny5ffa58f2020-02-26 08:37:14 +0100585 utils.PrintCmd(cmd)
586 try:
Morten Krogh-Jespersen6c702402021-06-21 12:29:48 +0200587 print(subprocess.check_output(cmd, stderr=subprocess.STDOUT).decode('utf-8'))
Ian Zerny5ffa58f2020-02-26 08:37:14 +0100588 return 0
Rico Wind3d369b42021-01-12 10:26:24 +0100589 except subprocess.CalledProcessError as e:
Ian Zerny9ff31b72021-04-22 11:36:26 +0200590 if args.nolib \
591 or version == 'source' \
592 or not try_retrace_output(e, version, temp):
Morten Krogh-Jespersen86222742021-03-02 11:13:33 +0100593 print(e.output.decode('UTF-8'))
Ian Zerny5ffa58f2020-02-26 08:37:14 +0100594 return 1
595
Ian Zerny9ff31b72021-04-22 11:36:26 +0200596def try_retrace_output(e, version, temp):
597 try:
598 stacktrace = os.path.join(temp, 'stacktrace')
599 open(stacktrace, 'w+').write(e.output.decode('UTF-8'))
600 print("=" * 80)
601 print(" RETRACED OUTPUT")
602 print("=" * 80)
603 retrace.run(get_map_file(version, temp), stacktrace, no_r8lib=False)
604 return True
605 except Exception as e2:
606 print("Failed to retrace for version: %s" % version)
607 print(e2)
608 return False
609
610def get_map_file(version, temp):
611 if version == 'main':
612 return utils.R8LIB_MAP
613 download_path = archive.GetUploadDestination(
614 version,
615 'r8lib.jar.map',
616 is_hash(version))
617 if utils.file_exists_on_cloud_storage(download_path):
618 map_path = os.path.join(temp, 'mapping.map')
619 utils.download_file_from_cloud_storage(download_path, map_path)
620 return map_path
621 else:
622 print('Could not find map file from argument: %s.' % version)
623 return None
624
Ian Zerny0e53ff12021-06-15 13:40:14 +0200625def summarize_dump_files(dumpfiles):
626 if len(dumpfiles) == 0:
627 error('Summary command expects a list of dumps to summarize')
628 for f in dumpfiles:
629 print(f + ':')
630 try:
631 with utils.TempDir() as temp:
632 dump = read_dump(f, temp)
633 summarize_dump(dump)
634 except IOError as e:
635 print("Error: " + str(e))
636 except zipfile.BadZipfile as e:
637 print("Error: " + str(e))
638
639def summarize_dump(dump):
640 version = dump.version()
641 if not version:
642 print('No dump version info')
643 return
644 print('version=' + version)
645 props = dump.build_properties_file()
646 if props:
647 with open(props) as props_file:
648 print(props_file.read())
649 if dump.library_jar():
650 print('library.jar present')
651 if dump.classpath_jar():
652 print('classpath.jar present')
653 prog = dump.program_jar()
654 if prog:
655 print('program.jar content:')
656 summarize_jar(prog)
657
658def summarize_jar(jar):
659 with zipfile.ZipFile(jar) as zip:
660 pkgs = {}
661 for info in zip.infolist():
662 if info.filename.endswith('.class'):
663 pkg, clazz = os.path.split(info.filename)
664 count = pkgs.get(pkg, 0)
665 pkgs[pkg] = count + 1
666 sorted = list(pkgs.keys())
667 sorted.sort()
668 for p in sorted:
669 print(' ' + p + ': ' + str(pkgs[p]))
670
Søren Gjesse7360f2b2020-08-10 09:13:35 +0200671def run(args, otherargs):
Ian Zerny0e53ff12021-06-15 13:40:14 +0200672 if args.summary:
673 summarize_dump_files(otherargs)
674 elif args.loop:
Søren Gjesse7360f2b2020-08-10 09:13:35 +0200675 count = 1
676 while True:
677 print('Iteration {:03d}'.format(count))
678 out = args.temp
679 if out:
680 out = os.path.join(out, '{:03d}'.format(count))
681 run1(out, args, otherargs)
682 count += 1
683 else:
684 run1(args.temp, args, otherargs)
685
Ian Zerny5ffa58f2020-02-26 08:37:14 +0100686if __name__ == '__main__':
687 (args, otherargs) = make_parser().parse_known_args(sys.argv[1:])
688 sys.exit(run(args, otherargs))