blob: 39315c900bae48e0564bef1dca6c53a717a68ff2 [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):
Søren Gjessea5dc7ed2023-03-20 13:25:38 +0100418 if line.lstrip().startswith('#'):
419 return False
Christoffer Quist Adamsenf86fc0b2021-12-10 12:39:36 +0100420 if ('-injars' in line or '-libraryjars' in line or
Christoffer Quist Adamsen3f21c2b2023-02-28 09:37:22 +0100421 '-print' in line or '-applymapping' in line):
Christoffer Quist Adamsenf86fc0b2021-12-10 12:39:36 +0100422 return True
423 if minify == 'force-enable' and '-dontobfuscate' in line:
424 return True
425 if optimize == 'force-enable' and '-dontoptimize' in line:
426 return True
427 if shrink == 'force-enable' and '-dontshrink' in line:
428 return True
429 return False
Rico Windc9e52f72021-08-19 08:30:26 +0200430
Morten Krogh-Jespersen327e76d2022-06-23 09:31:13 +0200431def prepare_r8_wrapper(dist, temp, jdkhome):
Christoffer Quist Adamsen819273a2023-03-02 15:20:45 +0100432 compile_wrapper_with_javac(
Morten Krogh-Jespersen327e76d2022-06-23 09:31:13 +0200433 dist,
434 temp,
435 jdkhome,
436 os.path.join(
Ian Zerny5ffa58f2020-02-26 08:37:14 +0100437 utils.REPO_ROOT,
Morten Krogh-Jespersen327e76d2022-06-23 09:31:13 +0200438 'src/main/java/com/android/tools/r8/utils/CompileDumpCompatR8.java'))
439
440def prepare_d8_wrapper(dist, temp, jdkhome):
Christoffer Quist Adamsen819273a2023-03-02 15:20:45 +0100441 compile_wrapper_with_javac(
Morten Krogh-Jespersen327e76d2022-06-23 09:31:13 +0200442 dist,
443 temp,
444 jdkhome,
445 os.path.join(
446 utils.REPO_ROOT,
447 'src/main/java/com/android/tools/r8/utils/CompileDumpD8.java'))
448
Christoffer Quist Adamsen819273a2023-03-02 15:20:45 +0100449def compile_wrapper_with_javac(dist, temp, jdkhome, path):
450 base_path = os.path.join(
451 utils.REPO_ROOT,
452 'src/main/java/com/android/tools/r8/utils/CompileDumpBase.java')
Ian Zerny268c9632020-11-13 11:36:35 +0100453 cmd = [
Rico Wind33936d12021-04-07 08:04:14 +0200454 jdk.GetJavacExecutable(jdkhome),
Morten Krogh-Jespersen327e76d2022-06-23 09:31:13 +0200455 path,
Christoffer Quist Adamsen819273a2023-03-02 15:20:45 +0100456 base_path,
Ian Zerny5ffa58f2020-02-26 08:37:14 +0100457 '-d', temp,
458 '-cp', dist,
Ian Zerny268c9632020-11-13 11:36:35 +0100459 ]
460 utils.PrintCmd(cmd)
461 subprocess.check_output(cmd)
Ian Zerny5ffa58f2020-02-26 08:37:14 +0100462
463def is_hash(version):
464 return len(version) == 40
465
Rico Wind33936d12021-04-07 08:04:14 +0200466def run1(out, args, otherargs, jdkhome=None):
Ian Zerny09d42832022-11-17 07:45:02 +0100467 jvmargs = []
468 compilerargs = []
469 for arg in otherargs:
470 if arg.startswith('-D'):
471 jvmargs.append(arg)
472 else:
473 compilerargs.append(arg)
Ian Zerny5ffa58f2020-02-26 08:37:14 +0100474 with utils.TempDir() as temp:
Søren Gjesse7360f2b2020-08-10 09:13:35 +0200475 if out:
476 temp = out
Rico Wind9ed87b92020-03-06 12:37:18 +0100477 if not os.path.exists(temp):
478 os.makedirs(temp)
Ian Zerny0e53ff12021-06-15 13:40:14 +0200479 dump = read_dump_from_args(args, temp)
Ian Zerny46bc4cf2020-08-03 15:58:27 +0200480 if not dump.program_jar():
481 error("Cannot compile dump with no program classes")
482 if not dump.library_jar():
Rico Wind3d369b42021-01-12 10:26:24 +0100483 print("WARNING: Unexpected lack of library classes in dump")
Christoffer Quist Adamsenfcfc63a2020-05-15 19:04:24 +0200484 build_properties = determine_build_properties(args, dump)
Ian Zerny5ffa58f2020-02-26 08:37:14 +0100485 version = determine_version(args, dump)
Søren Gjesse0f8d88b2021-09-28 15:15:54 +0200486 compiler = determine_compiler(args, build_properties)
Christoffer Quist Adamsen3f21c2b2023-02-28 09:37:22 +0100487 config_files = determine_config_files(args, dump, temp)
Ian Zerny5ffa58f2020-02-26 08:37:14 +0100488 out = determine_output(args, temp)
Ian Zerny77bdf5f2020-07-08 11:46:24 +0200489 min_api = determine_min_api(args, build_properties)
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +0100490 classfile = determine_class_file(args, build_properties)
Morten Krogh-Jespersen9e201ea2022-06-14 12:41:50 +0200491 android_platform_build = determine_android_platform_build(args, build_properties)
492 enable_missing_library_api_modeling = determine_enable_missing_library_api_modeling(args, build_properties)
Morten Krogh-Jespersenaa2f9ec2022-07-04 13:10:17 +0200493 mode = determine_compilation_mode(args, build_properties)
Ian Zerny171c6a62022-04-04 14:25:30 +0200494 jar = args.r8_jar if args.r8_jar else download_distribution(version, args.nolib, temp)
Ian Zerny268c9632020-11-13 11:36:35 +0100495 if ':' not in jar and not os.path.exists(jar):
496 error("Distribution does not exist: " + jar)
Rico Wind33936d12021-04-07 08:04:14 +0200497 cmd = [jdk.GetJavaExecutable(jdkhome)]
Ian Zerny09d42832022-11-17 07:45:02 +0100498 cmd.extend(jvmargs)
Ian Zerny5ffa58f2020-02-26 08:37:14 +0100499 if args.debug_agent:
500 if not args.nolib:
Rico Wind3d369b42021-01-12 10:26:24 +0100501 print("WARNING: Running debugging agent on r8lib is questionable...")
Ian Zerny5ffa58f2020-02-26 08:37:14 +0100502 cmd.append(
503 '-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=*:5005')
Ian Zerny77bdf5f2020-07-08 11:46:24 +0200504 if args.xmx:
505 cmd.append('-Xmx' + args.xmx)
Ian Zerny5ffa58f2020-02-26 08:37:14 +0100506 if args.ea:
507 cmd.append('-ea')
Morten Krogh-Jespersen23f0b032021-07-06 18:10:15 +0200508 cmd.append('-Dcom.android.tools.r8.enableTestAssertions=1')
Morten Krogh-Jespersen6c702402021-06-21 12:29:48 +0200509 if args.print_times:
Rico Wind28653642020-03-31 13:59:07 +0200510 cmd.append('-Dcom.android.tools.r8.printtimes=1')
Christoffer Quist Adamsen2f48f3f2021-10-14 17:25:03 +0200511 if args.r8_flags:
512 cmd.extend(args.r8_flags.split(' '))
Morten Krogh-Jespersen43f3cea2020-11-12 17:09:51 +0100513 if hasattr(args, 'properties'):
Morten Krogh-Jespersendd12e782023-03-01 16:34:51 +0100514 cmd.extend(args.properties)
Søren Gjesse1768e252021-10-06 12:50:36 +0200515 cmd.extend(determine_properties(build_properties))
Morten Krogh-Jespersen327e76d2022-06-23 09:31:13 +0200516 cmd.extend(['-cp', '%s:%s' % (temp, jar)])
Ian Zerny5ffa58f2020-02-26 08:37:14 +0100517 if compiler == 'd8':
Ian Zerny1ad7cac2023-01-09 14:03:04 +0100518 prepare_d8_wrapper(jar, temp, jdkhome)
Morten Krogh-Jespersen327e76d2022-06-23 09:31:13 +0200519 cmd.append('com.android.tools.r8.utils.CompileDumpD8')
Christoffer Quist Adamsen7953d0a2023-02-27 12:08:33 +0100520 if is_l8_compiler(compiler):
Morten Krogh-Jespersenbb624e42021-04-19 14:33:48 +0200521 cmd.append('com.android.tools.r8.L8')
Morten Krogh-Jespersendd12e782023-03-01 16:34:51 +0100522 if compiler == 'tracereferences':
523 cmd.append('com.android.tools.r8.tracereferences.TraceReferences')
524 cmd.extend(determine_trace_references_commands(build_properties, out))
Ian Zerny5ffa58f2020-02-26 08:37:14 +0100525 if compiler.startswith('r8'):
Ian Zerny1ad7cac2023-01-09 14:03:04 +0100526 prepare_r8_wrapper(jar, temp, jdkhome)
Ian Zerny5ffa58f2020-02-26 08:37:14 +0100527 cmd.append('com.android.tools.r8.utils.CompileDumpCompatR8')
528 if compiler == 'r8':
529 cmd.append('--compat')
Morten Krogh-Jespersendd12e782023-03-01 16:34:51 +0100530 if compiler != 'tracereferences':
531 assert mode == 'debug' or mode == 'release'
532 cmd.append('--' + mode)
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +0100533 # For recompilation of dumps run_on_app_dumps pass in a program jar.
Morten Krogh-Jespersendd12e782023-03-01 16:34:51 +0100534 program_jar = determine_program_jar(args, dump)
535 if compiler != 'tracereferences':
536 cmd.append(program_jar)
537 cmd.extend(['--output', out])
538 else:
539 cmd.extend(['--source', program_jar])
Christoffer Quist Adamsenfcfc63a2020-05-15 19:04:24 +0200540 for feature_jar in dump.feature_jars():
541 cmd.extend(['--feature-jar', feature_jar,
542 determine_feature_output(feature_jar, temp)])
Ian Zerny5ffa58f2020-02-26 08:37:14 +0100543 if dump.library_jar():
544 cmd.extend(['--lib', dump.library_jar()])
Christoffer Quist Adamsen7953d0a2023-02-27 12:08:33 +0100545 if dump.classpath_jar() and not is_l8_compiler(compiler):
Morten Krogh-Jespersendd12e782023-03-01 16:34:51 +0100546 cmd.extend(
547 ['--target' if compiler == 'tracereferences' else '--classpath',
548 dump.classpath_jar()])
Morten Krogh-Jespersend86a81b2020-11-13 12:33:26 +0100549 if dump.desugared_library_json() and not args.disable_desugared_lib:
Clément Béradaae4ca2020-10-27 14:26:41 +0000550 cmd.extend(['--desugared-lib', dump.desugared_library_json()])
Christoffer Quist Adamsen3f21c2b2023-02-28 09:37:22 +0100551 if not is_l8_compiler(compiler):
552 cmd.extend([
553 '--desugared-lib-pg-conf-output',
554 determine_desugared_lib_pg_conf_output(temp)])
555 if (is_r8_compiler(compiler) or compiler == 'l8') and config_files:
556 if hasattr(args, 'config_files_consumer') and args.config_files_consumer:
557 args.config_files_consumer(config_files)
Rico Windc9e52f72021-08-19 08:30:26 +0200558 else:
559 # If we get a dump from the wild we can't use -injars, -libraryjars or
560 # -print{mapping,usage}
Christoffer Quist Adamsen3f21c2b2023-02-28 09:37:22 +0100561 clean_configs(config_files, args)
562 for config_file in config_files:
563 cmd.extend(['--pg-conf', config_file])
564 cmd.extend(['--pg-map-output', '%s.map' % out])
Christoffer Quist Adamsencd7f7ec2022-08-26 13:39:11 +0200565 if dump.main_dex_list_resource():
566 cmd.extend(['--main-dex-list', dump.main_dex_list_resource()])
Morten Krogh-Jespersen1e774252021-03-01 16:56:07 +0100567 if dump.main_dex_rules_resource():
568 cmd.extend(['--main-dex-rules', dump.main_dex_rules_resource()])
Christoffer Quist Adamsen819273a2023-03-02 15:20:45 +0100569 for art_profile_resource in dump.art_profile_resources():
570 residual_art_profile_output = \
571 determine_residual_art_profile_output(art_profile_resource, temp)
572 cmd.extend([
573 '--art-profile', art_profile_resource, residual_art_profile_output])
Christoffer Quist Adamsencd7f7ec2022-08-26 13:39:11 +0200574 for startup_profile_resource in dump.startup_profile_resources():
575 cmd.extend(['--startup-profile', startup_profile_resource])
Ian Zerny77bdf5f2020-07-08 11:46:24 +0200576 if min_api:
577 cmd.extend(['--min-api', min_api])
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +0100578 if classfile:
579 cmd.extend(['--classfile'])
Morten Krogh-Jespersen9e201ea2022-06-14 12:41:50 +0200580 if android_platform_build:
581 cmd.extend(['--android-platform-build'])
582 if enable_missing_library_api_modeling:
583 cmd.extend(['--enable-missing-library-api-modeling'])
Ian Zerny77bdf5f2020-07-08 11:46:24 +0200584 if args.threads:
585 cmd.extend(['--threads', args.threads])
Ian Zerny09d42832022-11-17 07:45:02 +0100586 cmd.extend(compilerargs)
Ian Zerny5ffa58f2020-02-26 08:37:14 +0100587 utils.PrintCmd(cmd)
588 try:
Morten Krogh-Jespersen6c702402021-06-21 12:29:48 +0200589 print(subprocess.check_output(cmd, stderr=subprocess.STDOUT).decode('utf-8'))
Ian Zerny5ffa58f2020-02-26 08:37:14 +0100590 return 0
Rico Wind3d369b42021-01-12 10:26:24 +0100591 except subprocess.CalledProcessError as e:
Ian Zerny9ff31b72021-04-22 11:36:26 +0200592 if args.nolib \
593 or version == 'source' \
594 or not try_retrace_output(e, version, temp):
Morten Krogh-Jespersen86222742021-03-02 11:13:33 +0100595 print(e.output.decode('UTF-8'))
Ian Zerny5ffa58f2020-02-26 08:37:14 +0100596 return 1
597
Ian Zerny9ff31b72021-04-22 11:36:26 +0200598def try_retrace_output(e, version, temp):
599 try:
600 stacktrace = os.path.join(temp, 'stacktrace')
601 open(stacktrace, 'w+').write(e.output.decode('UTF-8'))
602 print("=" * 80)
603 print(" RETRACED OUTPUT")
604 print("=" * 80)
605 retrace.run(get_map_file(version, temp), stacktrace, no_r8lib=False)
606 return True
607 except Exception as e2:
608 print("Failed to retrace for version: %s" % version)
609 print(e2)
610 return False
611
612def get_map_file(version, temp):
613 if version == 'main':
614 return utils.R8LIB_MAP
615 download_path = archive.GetUploadDestination(
616 version,
617 'r8lib.jar.map',
618 is_hash(version))
619 if utils.file_exists_on_cloud_storage(download_path):
620 map_path = os.path.join(temp, 'mapping.map')
621 utils.download_file_from_cloud_storage(download_path, map_path)
622 return map_path
623 else:
624 print('Could not find map file from argument: %s.' % version)
625 return None
626
Ian Zerny0e53ff12021-06-15 13:40:14 +0200627def summarize_dump_files(dumpfiles):
628 if len(dumpfiles) == 0:
629 error('Summary command expects a list of dumps to summarize')
630 for f in dumpfiles:
631 print(f + ':')
632 try:
633 with utils.TempDir() as temp:
634 dump = read_dump(f, temp)
635 summarize_dump(dump)
636 except IOError as e:
637 print("Error: " + str(e))
638 except zipfile.BadZipfile as e:
639 print("Error: " + str(e))
640
641def summarize_dump(dump):
642 version = dump.version()
643 if not version:
644 print('No dump version info')
645 return
646 print('version=' + version)
647 props = dump.build_properties_file()
648 if props:
649 with open(props) as props_file:
650 print(props_file.read())
651 if dump.library_jar():
652 print('library.jar present')
653 if dump.classpath_jar():
654 print('classpath.jar present')
655 prog = dump.program_jar()
656 if prog:
657 print('program.jar content:')
658 summarize_jar(prog)
659
660def summarize_jar(jar):
661 with zipfile.ZipFile(jar) as zip:
662 pkgs = {}
663 for info in zip.infolist():
664 if info.filename.endswith('.class'):
665 pkg, clazz = os.path.split(info.filename)
666 count = pkgs.get(pkg, 0)
667 pkgs[pkg] = count + 1
668 sorted = list(pkgs.keys())
669 sorted.sort()
670 for p in sorted:
671 print(' ' + p + ': ' + str(pkgs[p]))
672
Søren Gjesse7360f2b2020-08-10 09:13:35 +0200673def run(args, otherargs):
Ian Zerny0e53ff12021-06-15 13:40:14 +0200674 if args.summary:
675 summarize_dump_files(otherargs)
676 elif args.loop:
Søren Gjesse7360f2b2020-08-10 09:13:35 +0200677 count = 1
678 while True:
679 print('Iteration {:03d}'.format(count))
680 out = args.temp
681 if out:
682 out = os.path.join(out, '{:03d}'.format(count))
683 run1(out, args, otherargs)
684 count += 1
685 else:
686 run1(args.temp, args, otherargs)
687
Ian Zerny5ffa58f2020-02-26 08:37:14 +0100688if __name__ == '__main__':
689 (args, otherargs) = make_parser().parse_known_args(sys.argv[1:])
690 sys.exit(run(args, otherargs))