blob: d6226be4a5dd2d1cc82176203280da0073ffe931 [file] [log] [blame]
Rico Wind3d369b42021-01-12 10:26:24 +01001#!/usr/bin/env python3
Christoffer Quist Adamsenf2e8db72020-11-07 14:09:49 +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.
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +01005
Ian Zerny161ff742022-01-20 12:39:40 +01006import argparse
7import hashlib
8import os
9import shutil
10import sys
11import time
12import zipfile
13from datetime import datetime
14
Morten Krogh-Jespersencd55f812020-11-04 09:13:31 +010015import adb
16import apk_masseur
Christoffer Quist Adamsenf79f1a22021-01-12 16:24:34 +010017import as_utils
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +010018import compiledump
19import gradle
Rico Wind61a034f2021-03-16 09:37:11 +010020import jdk
Christoffer Quist Adamsenbe6661d2023-08-24 11:01:12 +020021import thread_utils
22from thread_utils import print_thread
Morten Krogh-Jespersen47764032020-11-11 15:09:39 +010023import update_prebuilds_in_android
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +010024import utils
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +010025
Ian Zernyed1f8512023-11-07 11:07:57 +010026GOLEM_BUILD_TARGETS = [utils.GRADLE_TASK_R8LIB]
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +010027SHRINKERS = ['r8', 'r8-full', 'r8-nolib', 'r8-nolib-full']
28
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +020029
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +010030class AttrDict(dict):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +020031
32 def __getattr__(self, name):
33 return self.get(name, None)
34
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +010035
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +010036# To generate the files for a new app, navigate to the app source folder and
37# run:
38# ./gradlew clean :app:assembleRelease -Dcom.android.tools.r8.dumpinputtodirectory=<path>
39# and store the dump and the apk.
40# If the app has instrumented tests, adding `testBuildType "release"` and
41# running:
42# ./gradlew assembleAndroidTest -Dcom.android.tools.r8.dumpinputtodirectory=<path>
43# will also generate dumps and apk for tests.
44
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +020045
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +010046class App(object):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +020047
48 def __init__(self, fields):
49 defaults = {
50 'id': None,
51 'name': None,
52 'collections': [],
53 'dump_app': None,
54 'apk_app': None,
55 'dump_test': None,
56 'apk_test': None,
57 'skip': False,
58 'url': None, # url is not used but nice to have for updating apps
59 'revision': None,
60 'folder': None,
61 'skip_recompilation': False,
62 'compiler_properties': [],
63 'internal': False,
64 'golem_duration': None,
65 }
66 # This below does not work in python3
67 defaults.update(fields.items())
68 self.__dict__ = defaults
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +010069
70
Christoffer Quist Adamsen53e29472020-11-13 10:53:06 +010071class AppCollection(object):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +020072
73 def __init__(self, fields):
74 defaults = {'name': None}
75 # This below does not work in python3
76 defaults.update(fields.items())
77 self.__dict__ = defaults
Christoffer Quist Adamsen53e29472020-11-13 10:53:06 +010078
79
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +010080APPS = [
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +020081 App({
82 'id':
83 'com.numix.calculator',
84 'name':
85 'Calculator',
86 'dump_app':
87 'dump_app.zip',
88 'apk_app':
89 'app-release.apk',
90 # Compiling tests fail: Library class android.content.res.XmlResourceParser
91 # implements program class org.xmlpull.v1.XmlPullParser. Nothing to really
92 # do about that.
93 'id_test':
94 'com.numix.calculator.test',
95 'dump_test':
96 'dump_test.zip',
97 'apk_test':
98 'app-release-androidTest.apk',
99 'url':
100 'https://github.com/numixproject/android-suite/tree/master/Calculator',
101 'revision':
102 'f58e1b53f7278c9b675d5855842c6d8a44cccb1f',
103 'folder':
104 'android-suite-calculator',
105 }),
106 App({
107 'id': 'dev.dworks.apps.anexplorer.pro',
108 'name': 'AnExplorer',
109 'dump_app': 'dump_app.zip',
110 'apk_app': 'AnExplorer-googleMobileProRelease-4.0.3.apk',
111 'url': 'https://github.com/christofferqa/AnExplorer',
112 'revision': '365927477b8eab4052a1882d5e358057ae3dee4d',
113 'folder': 'anexplorer',
114 }),
115 App({
116 'id': 'de.danoeh.antennapod',
117 'name': 'AntennaPod',
118 'dump_app': 'dump_app.zip',
119 'apk_app': 'app-free-release.apk',
120 # TODO(b/172452102): Tests and monkey do not work
121 'id_test': 'de.danoeh.antennapod.test',
122 'dump_test': 'dump_test.zip',
123 'apk_test': 'app-free-release-androidTest.apk',
124 'url': 'https://github.com/christofferqa/AntennaPod.git',
125 'revision': '77e94f4783a16abe9cc5b78dc2d2b2b1867d8c06',
126 'folder': 'antennapod',
127 }),
128 App({
129 'id': 'com.example.applymapping',
130 'name': 'applymapping',
131 'dump_app': 'dump_app.zip',
132 'apk_app': 'app-release.apk',
133 'id_test': 'com.example.applymapping.test',
134 'dump_test': 'dump_test.zip',
135 'apk_test': 'app-release-androidTest.apk',
136 'url': 'https://github.com/mkj-gram/applymapping',
137 'revision': 'e3ae14b8c16fa4718e5dea8f7ad00937701b3c48',
138 'folder': 'applymapping',
139 }),
140 App({
141 'id':
142 'com.chanapps.four.activity',
143 'name':
144 'chanu',
145 'dump_app':
146 'dump_app.zip',
147 'apk_app':
148 'app-release.apk',
149 'url':
150 'https://github.com/mkj-gram/chanu.git',
151 'revision':
152 '6e53458f167b6d78398da60c20fd0da01a232617',
153 'folder':
154 'chanu',
155 # The app depends on a class file that has access flags interface but
156 # not abstract
157 'compiler_properties': [
158 '-Dcom.android.tools.r8.allowInvalidCfAccessFlags=true'
159 ]
160 }),
161 App({
162 'id': 'com.example.myapplication',
163 'name': 'empty-activity',
164 'dump_app': 'dump_app.zip',
165 'apk_app': 'app-release.apk',
166 'url': 'https://github.com/christofferqa/empty_android_activity.git',
167 'revision': '2d297ec3373dadb03cbae916b9feba4792563156',
168 'folder': 'empty-activity',
169 }),
170 App({
171 'id':
172 'com.example.emptycomposeactivity',
173 'name':
174 'empty-compose-activity',
175 'dump_app':
176 'dump_app.zip',
177 'apk_app':
178 'app-release.apk',
179 'url':
180 'https://github.com/christofferqa/empty_android_compose_activity.git',
181 'revision':
182 '3c8111b8b7d6e9184049a07e2b96702d7b33d03e',
183 'folder':
184 'empty-compose-activity',
185 }),
186 # TODO(b/172539375): Monkey runner fails on recompilation.
187 App({
188 'id': 'com.google.firebase.example.fireeats',
189 'name': 'FriendlyEats',
190 'dump_app': 'dump_app.zip',
191 'apk_app': 'app-release-unsigned.apk',
192 'url': 'https://github.com/firebase/friendlyeats-android',
193 'revision': '7c6dd016fc31ea5ecb948d5166b8479efc3775cc',
194 'folder': 'friendlyeats',
195 }),
196 App({
197 'id': 'com.google.samples.apps.sunflower',
198 'name': 'Sunflower',
199 'dump_app': 'dump_app.zip',
200 'apk_app': 'app-debug.apk',
201 # TODO(b/172549283): Compiling tests fails
202 'id_test': 'com.google.samples.apps.sunflower.test',
203 'dump_test': 'dump_test.zip',
204 'apk_test': 'app-debug-androidTest.apk',
205 'url': 'https://github.com/android/sunflower',
206 'revision': '0c4c88fdad2a74791199dffd1a6559559b1dbd4a',
207 'folder': 'sunflower',
208 }),
209 # TODO(b/172565385): Monkey runner fails on recompilation
210 App({
211 'id': 'com.google.samples.apps.iosched',
212 'name': 'iosched',
213 'dump_app': 'dump_app.zip',
214 'apk_app': 'mobile-release.apk',
215 'url': 'https://github.com/christofferqa/iosched.git',
216 'revision': '581cbbe2253711775dbccb753cdb53e7e506cb02',
217 'folder': 'iosched',
218 }),
219 App({
220 'id': 'fr.neamar.kiss',
221 'name': 'KISS',
222 'dump_app': 'dump_app.zip',
223 'apk_app': 'app-release.apk',
224 # TODO(b/172569220): Running tests fails due to missing keep rules
225 'id_test': 'fr.neamar.kiss.test',
226 'dump_test': 'dump_test.zip',
227 'apk_test': 'app-release-androidTest.apk',
228 'url': 'https://github.com/Neamar/KISS',
229 'revision': '8ccffaadaf0d0b8fc4418ed2b4281a0935d3d971',
230 'folder': 'kiss',
231 }),
232 # TODO(b/172577344): Monkey runner not working.
233 App({
234 'id': 'io.github.hidroh.materialistic',
235 'name': 'materialistic',
236 'dump_app': 'dump_app.zip',
237 'apk_app': 'app-release.apk',
238 'url': 'https://github.com/christofferqa/materialistic.git',
239 'revision': '2b2b2ee25ce9e672d5aab1dc90a354af1522b1d9',
240 'folder': 'materialistic',
241 }),
242 App({
243 'id': 'com.avjindersinghsekhon.minimaltodo',
244 'name': 'MinimalTodo',
245 'dump_app': 'dump_app.zip',
246 'apk_app': 'app-release.apk',
247 'url': 'https://github.com/christofferqa/Minimal-Todo',
248 'revision': '9d8c73746762cd376b718858ec1e8783ca07ba7c',
249 'folder': 'minimal-todo',
250 }),
251 App({
252 'id': 'net.nurik.roman.muzei',
253 'name': 'muzei',
254 'dump_app': 'dump_app.zip',
255 'apk_app': 'muzei-release.apk',
256 'url': 'https://github.com/romannurik/muzei',
257 'revision': '9eac6e98aebeaf0ae40bdcd85f16dd2886551138',
258 'folder': 'muzei',
259 }),
260 # TODO(b/172806281): Monkey runner does not work.
261 App({
262 'id': 'org.schabi.newpipe',
263 'name': 'NewPipe',
264 'dump_app': 'dump_app.zip',
265 'apk_app': 'app-release-unsigned.apk',
266 'url': 'https://github.com/TeamNewPipe/NewPipe',
267 'revision': 'f4435f90313281beece70c544032f784418d85fa',
268 'folder': 'newpipe',
269 }),
270 # TODO(b/172806808): Monkey runner does not work.
271 App({
272 'id': 'io.rover.app.debug',
273 'name': 'Rover',
274 'dump_app': 'dump_app.zip',
275 'apk_app': 'example-app-release-unsigned.apk',
276 'url': 'https://github.com/RoverPlatform/rover-android',
277 'revision': '94342117097770ea3ca2c6df6ab496a1a55c3ce7',
278 'folder': 'rover-android',
279 }),
280 # TODO(b/172808159): Monkey runner does not work
281 App({
282 'id': 'com.google.android.apps.santatracker',
283 'name': 'SantaTracker',
284 'dump_app': 'dump_app.zip',
285 'apk_app': 'santa-tracker-release.apk',
286 'url': 'https://github.com/christofferqa/santa-tracker-android',
287 'revision': '8dee74be7d9ee33c69465a07088c53087d24a6dd',
288 'folder': 'santa-tracker',
289 }),
290 App({
291 'id': 'org.thoughtcrime.securesms',
292 'name': 'Signal',
293 'dump_app': 'dump_app.zip',
294 'apk_app': 'Signal-Android-play-prod-universal-release-4.76.2.apk',
295 # TODO(b/172812839): Instrumentation test fails.
296 'id_test': 'org.thoughtcrime.securesms.test',
297 'dump_test': 'dump_test.zip',
298 'apk_test': 'Signal-Android-play-prod-release-androidTest.apk',
299 'url': 'https://github.com/signalapp/Signal-Android',
300 'revision': '91ca19f294362ccee2c2b43c247eba228e2b30a1',
301 'folder': 'signal-android',
Rico Wind685d48e2024-01-18 08:39:48 +0100302 'golem_duration': 300
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200303 }),
304 # TODO(b/172815827): Monkey runner does not work
305 App({
306 'id': 'com.simplemobiletools.calendar.pro',
307 'name': 'Simple-Calendar',
308 'dump_app': 'dump_app.zip',
309 'apk_app': 'calendar-release.apk',
310 'url': 'https://github.com/SimpleMobileTools/Simple-Calendar',
311 'revision': '906209874d0a091c7fce5a57972472f272d6b068',
312 'folder': 'simple-calendar',
313 }),
314 # TODO(b/172815534): Monkey runner does not work
315 App({
316 'id': 'com.simplemobiletools.camera.pro',
317 'name': 'Simple-Camera',
318 'dump_app': 'dump_app.zip',
319 'apk_app': 'camera-release.apk',
320 'url': 'https://github.com/SimpleMobileTools/Simple-Camera',
321 'revision': 'ebf9820c51e960912b3238287e30a131244fdee6',
322 'folder': 'simple-camera',
323 }),
324 App({
325 'id': 'com.simplemobiletools.filemanager.pro',
326 'name': 'Simple-File-Manager',
327 'dump_app': 'dump_app.zip',
328 'apk_app': 'file-manager-release.apk',
329 'url': 'https://github.com/SimpleMobileTools/Simple-File-Manager',
330 'revision': '2b7fa68ea251222cc40cf6d62ad1de260a6f54d9',
331 'folder': 'simple-file-manager',
332 }),
333 App({
334 'id': 'com.simplemobiletools.gallery.pro',
335 'name': 'Simple-Gallery',
336 'dump_app': 'dump_app.zip',
337 'apk_app': 'gallery-326-foss-release.apk',
338 'url': 'https://github.com/SimpleMobileTools/Simple-Gallery',
339 'revision': '564e56b20d33b28d0018c8087ec705beeb60785e',
340 'folder': 'simple-gallery',
341 }),
342 App({
343 'id': 'com.example.sqldelight.hockey',
344 'name': 'SQLDelight',
345 'dump_app': 'dump_app.zip',
346 'apk_app': 'android-release.apk',
347 'url': 'https://github.com/christofferqa/sqldelight',
348 'revision': '2e67a1126b6df05e4119d1e3a432fde51d76cdc8',
349 'folder': 'sqldelight',
350 }),
351 # TODO(b/172824096): Monkey runner does not work.
352 App({
353 'id': 'eu.kanade.tachiyomi',
354 'name': 'Tachiyomi',
355 'dump_app': 'dump_app.zip',
356 'apk_app': 'app-dev-release.apk',
357 'url': 'https://github.com/inorichi/tachiyomi',
358 'revision': '8aa6486bf76ab9a61a5494bee284b1a5e9180bf3',
359 'folder': 'tachiyomi',
360 }),
361 # TODO(b/172862042): Monkey runner does not work.
362 App({
363 'id': 'app.tivi',
364 'name': 'Tivi',
365 'dump_app': 'dump_app.zip',
366 'apk_app': 'app-release.apk',
367 'url': 'https://github.com/chrisbanes/tivi',
368 'revision': '5c6d9ed338885c59b1fc64050d92d056417bb4de',
369 'folder': 'tivi',
370 'golem_duration': 300
371 }),
372 App({
373 'id': 'com.keylesspalace.tusky',
374 'name': 'Tusky',
375 'dump_app': 'dump_app.zip',
376 'apk_app': 'app-blue-release.apk',
377 'url': 'https://github.com/tuskyapp/Tusky',
378 'revision': '814a9b8f9bacf8d26f712b06a0313a3534a2be95',
379 'folder': 'tusky',
380 }),
381 App({
382 'id': 'org.wikipedia',
383 'name': 'Wikipedia',
384 'dump_app': 'dump_app.zip',
385 'apk_app': 'app-prod-release.apk',
386 'url': 'https://github.com/wikimedia/apps-android-wikipedia',
387 'revision': '0fa7cad843c66313be8e25790ef084cf1a1fa67e',
388 'folder': 'wikipedia',
Christoffer Adamsend240df92024-06-14 13:52:42 +0200389 })
Christoffer Quist Adamsen53e29472020-11-13 10:53:06 +0100390]
391
Christoffer Adamsend240df92024-06-14 13:52:42 +0200392APP_COLLECTIONS = []
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +0100393
Morten Krogh-Jespersenf8e77032020-11-09 23:44:58 +0100394
Morten Krogh-Jespersendfeb0e32020-11-04 14:55:55 +0100395def remove_print_lines(file):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200396 with open(file) as f:
397 lines = f.readlines()
398 with open(file, 'w') as f:
399 for line in lines:
400 if '-printconfiguration' not in line:
401 f.write(line)
Morten Krogh-Jespersendfeb0e32020-11-04 14:55:55 +0100402
403
Rico Wind61a034f2021-03-16 09:37:11 +0100404def download_sha(app_sha, internal, quiet=False):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200405 if internal:
406 utils.DownloadFromX20(app_sha)
407 else:
408 utils.DownloadFromGoogleCloudStorage(app_sha, quiet=quiet)
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +0100409
410
Morten Krogh-Jespersencd55f812020-11-04 09:13:31 +0100411def is_logging_enabled_for(app, options):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200412 if options.no_logging:
413 return False
414 if options.app_logging_filter and app.name not in options.app_logging_filter:
415 return False
416 return True
Morten Krogh-Jespersencd55f812020-11-04 09:13:31 +0100417
418
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +0100419def is_minified_r8(shrinker):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200420 return '-nolib' not in shrinker
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +0100421
422
423def is_full_r8(shrinker):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200424 return '-full' in shrinker
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +0100425
426
Morten Krogh-Jespersen51db2b02020-11-11 12:49:26 +0100427def version_is_built_jar(version):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200428 return version != 'main' and version != 'source'
Morten Krogh-Jespersen51db2b02020-11-11 12:49:26 +0100429
430
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +0100431def compute_size_of_dex_files_in_package(path):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200432 dex_size = 0
433 z = zipfile.ZipFile(path, 'r')
434 for filename in z.namelist():
435 if filename.endswith('.dex'):
436 dex_size += z.getinfo(filename).file_size
437 return dex_size
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +0100438
439
440def dump_for_app(app_dir, app):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200441 return os.path.join(app_dir, app.dump_app)
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +0100442
443
Morten Krogh-Jespersen51a16352020-11-04 09:31:15 +0100444def dump_test_for_app(app_dir, app):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200445 return os.path.join(app_dir, app.dump_test)
Morten Krogh-Jespersen51a16352020-11-04 09:31:15 +0100446
447
Morten Krogh-Jespersen51db2b02020-11-11 12:49:26 +0100448def get_r8_jar(options, temp_dir, shrinker):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200449 if (options.version == 'source'):
450 return None
451 jar = os.path.abspath(
452 os.path.join(temp_dir, '..',
453 'r8lib.jar' if is_minified_r8(shrinker) else 'r8.jar'))
454 return jar
Morten Krogh-Jespersen51db2b02020-11-11 12:49:26 +0100455
456
Christoffer Quist Adamsenbe6661d2023-08-24 11:01:12 +0200457def get_results_for_app(app, options, temp_dir, worker_id):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200458 app_folder = app.folder if app.folder else app.name + "_" + app.revision
459 # Golem extraction will extract to the basename under the benchmarks dir.
460 app_location = os.path.basename(app_folder) if options.golem else app_folder
461 opensource_basedir = (os.path.join('benchmarks', app.name)
462 if options.golem else utils.OPENSOURCE_DUMPS_DIR)
463 app_dir = (os.path.join(utils.INTERNAL_DUMPS_DIR, app_location) if
464 app.internal else os.path.join(opensource_basedir, app_location))
465 if not os.path.exists(app_dir) and not options.golem:
466 # Download the app from google storage.
467 download_sha(app_dir + ".tar.gz.sha1", app.internal)
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +0100468
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200469 # Ensure that the dumps are in place
470 assert os.path.isfile(dump_for_app(app_dir, app)), "Could not find dump " \
471 "for app " + app.name
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +0100472
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200473 result = {}
474 result['status'] = 'success'
475 result_per_shrinker = build_app_with_shrinkers(app,
476 options,
477 temp_dir,
478 app_dir,
479 worker_id=worker_id)
480 for shrinker, shrinker_result in result_per_shrinker.items():
481 result[shrinker] = shrinker_result
482 return result
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +0100483
484
Christoffer Quist Adamsenbe6661d2023-08-24 11:01:12 +0200485def build_app_with_shrinkers(app, options, temp_dir, app_dir, worker_id):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200486 result_per_shrinker = {}
487 for shrinker in options.shrinker:
488 results = []
489 build_app_and_run_with_shrinker(app,
490 options,
491 temp_dir,
492 app_dir,
493 shrinker,
494 results,
495 worker_id=worker_id)
496 result_per_shrinker[shrinker] = results
497 if len(options.apps) > 1:
498 print_thread('', worker_id)
499 log_results_for_app(app,
500 result_per_shrinker,
501 options,
502 worker_id=worker_id)
503 print_thread('', worker_id)
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +0100504
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200505 return result_per_shrinker
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +0100506
507
508def is_last_build(index, compilation_steps):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200509 return index == compilation_steps - 1
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +0100510
511
512def build_app_and_run_with_shrinker(app, options, temp_dir, app_dir, shrinker,
Christoffer Quist Adamsenbe6661d2023-08-24 11:01:12 +0200513 results, worker_id):
Christoffer Quist Adamsenbe6661d2023-08-24 11:01:12 +0200514 print_thread(
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200515 '[{}] Building {} with {}'.format(datetime.now().strftime("%H:%M:%S"),
516 app.name, shrinker), worker_id)
517 print_thread(
518 'To compile locally: '
519 'tools/run_on_app_dump.py --shrinker {} --r8-compilation-steps {} '
520 '--app {} --minify {} --optimize {} --shrink {}'.format(
521 shrinker, options.r8_compilation_steps, app.name, options.minify,
522 options.optimize, options.shrink), worker_id)
523 print_thread(
524 'HINT: use --shrinker r8-nolib --no-build if you have a local R8.jar',
Christoffer Quist Adamsenbe6661d2023-08-24 11:01:12 +0200525 worker_id)
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200526 recomp_jar = None
527 status = 'success'
528 if options.r8_compilation_steps < 1:
529 return
530 compilation_steps = 1 if app.skip_recompilation else options.r8_compilation_steps
531 for compilation_step in range(0, compilation_steps):
532 if status != 'success':
533 break
534 print_thread(
535 'Compiling {} of {}'.format(compilation_step + 1,
536 compilation_steps), worker_id)
537 result = {}
538 try:
539 start = time.time()
540 (app_jar, mapping, new_recomp_jar) = \
541 build_app_with_shrinker(
542 app, options, temp_dir, app_dir, shrinker, compilation_step,
543 compilation_steps, recomp_jar, worker_id=worker_id)
544 end = time.time()
545 dex_size = compute_size_of_dex_files_in_package(app_jar)
546 result['build_status'] = 'success'
547 result['recompilation_status'] = 'success'
548 result['output_jar'] = app_jar
549 result['output_mapping'] = mapping
550 result['dex_size'] = dex_size
551 result['duration'] = int((end - start) * 1000) # Wall time
552 if (new_recomp_jar is None and
553 not is_last_build(compilation_step, compilation_steps)):
554 result['recompilation_status'] = 'failed'
555 warn('Failed to build {} with {}'.format(app.name, shrinker))
556 recomp_jar = new_recomp_jar
557 except Exception as e:
558 warn('Failed to build {} with {}'.format(app.name, shrinker))
559 if e:
560 print_thread('Error: ' + str(e), worker_id)
561 result['build_status'] = 'failed'
562 status = 'failed'
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +0100563
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200564 original_app_apk = os.path.join(app_dir, app.apk_app)
565 app_apk_destination = os.path.join(
566 temp_dir, "{}_{}.apk".format(app.id, compilation_step))
Morten Krogh-Jespersen51a16352020-11-04 09:31:15 +0100567
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200568 if result.get('build_status') == 'success' and options.monkey:
569 # Make a copy of the given APK, move the newly generated dex files into the
570 # copied APK, and then sign the APK.
571 apk_masseur.masseur(original_app_apk,
572 dex=app_jar,
573 resources='META-INF/services/*',
574 out=app_apk_destination,
575 quiet=options.quiet,
576 logging=is_logging_enabled_for(app, options),
577 keystore=options.keystore)
Morten Krogh-Jespersencd55f812020-11-04 09:13:31 +0100578
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200579 result['monkey_status'] = 'success' if adb.run_monkey(
580 app.id, options.emulator_id, app_apk_destination,
581 options.monkey_events, options.quiet,
582 is_logging_enabled_for(app, options)) else 'failed'
Morten Krogh-Jespersencd55f812020-11-04 09:13:31 +0100583
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200584 if (result.get('build_status') == 'success' and options.run_tests and
585 app.dump_test):
586 if not os.path.isfile(app_apk_destination):
587 apk_masseur.masseur(original_app_apk,
588 dex=app_jar,
589 resources='META-INF/services/*',
590 out=app_apk_destination,
591 quiet=options.quiet,
592 logging=is_logging_enabled_for(
593 app, options),
594 keystore=options.keystore)
Morten Krogh-Jespersen51a16352020-11-04 09:31:15 +0100595
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200596 # Compile the tests with the mapping file.
597 test_jar = build_test_with_shrinker(app, options, temp_dir, app_dir,
598 shrinker, compilation_step,
599 result['output_mapping'])
600 if not test_jar:
601 result['instrumentation_test_status'] = 'compilation_failed'
602 else:
603 original_test_apk = os.path.join(app_dir, app.apk_test)
604 test_apk_destination = os.path.join(
605 temp_dir, "{}_{}.test.apk".format(app.id_test,
606 compilation_step))
607 apk_masseur.masseur(original_test_apk,
608 dex=test_jar,
609 resources='META-INF/services/*',
610 out=test_apk_destination,
611 quiet=options.quiet,
612 logging=is_logging_enabled_for(
613 app, options),
614 keystore=options.keystore)
615 result[
616 'instrumentation_test_status'] = 'success' if adb.run_instrumented(
617 app.id, app.id_test, options.emulator_id,
618 app_apk_destination,
619 test_apk_destination, options.quiet,
620 is_logging_enabled_for(app, options)) else 'failed'
Morten Krogh-Jespersen51a16352020-11-04 09:31:15 +0100621
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200622 results.append(result)
623 if result.get('recompilation_status') != 'success':
624 break
625
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +0100626
Rico Wind33936d12021-04-07 08:04:14 +0200627def get_jdk_home(options, app):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200628 if options.golem:
629 return os.path.join('benchmarks', app.name, 'linux')
630 return None
631
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +0100632
633def build_app_with_shrinker(app, options, temp_dir, app_dir, shrinker,
634 compilation_step_index, compilation_steps,
Christoffer Quist Adamsenbe6661d2023-08-24 11:01:12 +0200635 prev_recomp_jar, worker_id):
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +0100636
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200637 def config_files_consumer(files):
638 for file in files:
639 compiledump.clean_config(file, options)
640 remove_print_lines(file)
Morten Krogh-Jespersenc9d23462020-11-12 15:36:57 +0100641
Christoffer Quist Adamsena2f22a42024-01-23 16:35:45 +0100642 properties = app.compiler_properties
643 if options.dump_input_to_directory:
644 properties.append(
645 '-Dcom.android.tools.r8.dumpinputtodirectory=%s'
646 % options.dump_input_to_directory)
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200647 args = AttrDict({
648 'dump': dump_for_app(app_dir, app),
649 'r8_jar': get_r8_jar(options, temp_dir, shrinker),
650 'r8_flags': options.r8_flags,
651 'disable_assertions': options.disable_assertions,
652 'version': options.version,
653 'compiler': 'r8full' if is_full_r8(shrinker) else 'r8',
654 'debug_agent': options.debug_agent,
655 'program_jar': prev_recomp_jar,
656 'nolib': not is_minified_r8(shrinker),
657 'config_files_consumer': config_files_consumer,
Christoffer Quist Adamsena2f22a42024-01-23 16:35:45 +0100658 'properties': properties,
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200659 'disable_desugared_lib': False,
660 'print_times': options.print_times,
Søren Gjesse7a4225c2023-11-24 13:40:22 +0100661 'java_opts': [],
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200662 })
Morten Krogh-Jespersenc9d23462020-11-12 15:36:57 +0100663
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200664 app_jar = os.path.join(
665 temp_dir, '{}_{}_{}_dex_out.jar'.format(app.name, shrinker,
666 compilation_step_index))
667 app_mapping = os.path.join(
668 temp_dir, '{}_{}_{}_dex_out.jar.map'.format(app.name, shrinker,
669 compilation_step_index))
670 recomp_jar = None
671 jdkhome = get_jdk_home(options, app)
672 with utils.TempDir() as compile_temp_dir:
673 compile_result = compiledump.run1(compile_temp_dir,
674 args, [],
675 jdkhome,
676 worker_id=worker_id)
677 out_jar = os.path.join(compile_temp_dir, "out.jar")
678 out_mapping = os.path.join(compile_temp_dir, "out.jar.map")
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +0100679
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200680 if compile_result != 0 or not os.path.isfile(out_jar):
681 assert False, 'Compilation of {} failed'.format(
682 dump_for_app(app_dir, app))
683 shutil.move(out_jar, app_jar)
684 shutil.move(out_mapping, app_mapping)
685
686 if compilation_step_index < compilation_steps - 1:
687 args['classfile'] = True
688 args['min_api'] = "10000"
689 args['disable_desugared_lib'] = True
690 compile_result = compiledump.run1(compile_temp_dir, args, [],
691 jdkhome)
692 if compile_result == 0:
693 recomp_jar = os.path.join(
694 temp_dir,
695 '{}_{}_{}_cf_out.jar'.format(app.name, shrinker,
696 compilation_step_index))
697 shutil.move(out_jar, recomp_jar)
698
699 return (app_jar, app_mapping, recomp_jar)
Morten Krogh-Jespersen51a16352020-11-04 09:31:15 +0100700
Morten Krogh-Jespersen162b3452020-11-05 13:07:10 +0100701
Morten Krogh-Jespersen51a16352020-11-04 09:31:15 +0100702def build_test_with_shrinker(app, options, temp_dir, app_dir, shrinker,
703 compilation_step_index, mapping):
Morten Krogh-Jespersen51a16352020-11-04 09:31:15 +0100704
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200705 def rewrite_files(files):
706 add_applymapping = True
707 for file in files:
708 compiledump.clean_config(file, options)
709 remove_print_lines(file)
710 with open(file) as f:
711 lines = f.readlines()
712 with open(file, 'w') as f:
713 for line in lines:
714 if '-applymapping' not in line:
715 f.write(line + '\n')
716 if add_applymapping:
717 f.write("-applymapping " + mapping + '\n')
718 add_applymapping = False
Morten Krogh-Jespersen51a16352020-11-04 09:31:15 +0100719
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200720 args = AttrDict({
721 'dump': dump_test_for_app(app_dir, app),
722 'r8_jar': get_r8_jar(options, temp_dir, shrinker),
723 'disable_assertions': options.disable_assertions,
724 'version': options.version,
725 'compiler': 'r8full' if is_full_r8(shrinker) else 'r8',
726 'debug_agent': options.debug_agent,
727 'nolib': not is_minified_r8(shrinker),
728 # The config file will have an -applymapping reference to an old map.
729 # Update it to point to mapping file build in the compilation of the app.
730 'config_files_consumer': rewrite_files,
731 })
Morten Krogh-Jespersen51a16352020-11-04 09:31:15 +0100732
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200733 test_jar = os.path.join(
734 temp_dir, '{}_{}_{}_test_out.jar'.format(app.name, shrinker,
735 compilation_step_index))
Morten Krogh-Jespersen51a16352020-11-04 09:31:15 +0100736
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200737 with utils.TempDir() as compile_temp_dir:
738 jdkhome = get_jdk_home(options, app)
739 compile_result = compiledump.run1(compile_temp_dir, args, [], jdkhome)
740 out_jar = os.path.join(compile_temp_dir, "out.jar")
741 if compile_result != 0 or not os.path.isfile(out_jar):
742 return None
743 shutil.move(out_jar, test_jar)
Morten Krogh-Jespersen51a16352020-11-04 09:31:15 +0100744
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200745 return test_jar
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +0100746
747
748def log_results_for_apps(result_per_shrinker_per_app, options):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200749 print('')
750 app_errors = 0
751 for (app, result_per_shrinker) in result_per_shrinker_per_app:
752 app_errors += (1 if log_results_for_app(app, result_per_shrinker,
753 options) else 0)
754 return app_errors
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +0100755
756
Christoffer Quist Adamsenbe6661d2023-08-24 11:01:12 +0200757def log_results_for_app(app, result_per_shrinker, options, worker_id=None):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200758 if options.print_dexsegments:
759 log_segments_for_app(app,
760 result_per_shrinker,
761 options,
762 worker_id=worker_id)
763 return False
764 else:
765 return log_comparison_results_for_app(app,
766 result_per_shrinker,
767 options,
768 worker_id=worker_id)
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +0100769
770
Christoffer Quist Adamsenbe6661d2023-08-24 11:01:12 +0200771def log_segments_for_app(app, result_per_shrinker, options, worker_id):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200772 for shrinker in SHRINKERS:
773 if shrinker not in result_per_shrinker:
774 continue
775 for result in result_per_shrinker.get(shrinker):
776 benchmark_name = '{}-{}'.format(options.print_dexsegments, app.name)
777 utils.print_dexsegments(benchmark_name, [result.get('output_jar')],
778 worker_id=worker_id)
779 duration = result.get('duration')
780 print_thread(
781 '%s-Total(RunTimeRaw): %s ms' % (benchmark_name, duration),
782 worker_id)
783 print_thread(
784 '%s-Total(CodeSize): %s' %
785 (benchmark_name, result.get('dex_size')), worker_id)
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +0100786
787
788def percentage_diff_as_string(before, after):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200789 if after < before:
790 return '-' + str(round((1.0 - after / before) * 100)) + '%'
791 else:
792 return '+' + str(round((after - before) / before * 100)) + '%'
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +0100793
794
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200795def log_comparison_results_for_app(app, result_per_shrinker, options,
796 worker_id):
797 print_thread(app.name + ':', worker_id)
798 app_error = False
799 if result_per_shrinker.get('status', 'success') != 'success':
800 error_message = result_per_shrinker.get('error_message')
801 print_thread(' skipped ({})'.format(error_message), worker_id)
802 return
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +0100803
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200804 proguard_result = result_per_shrinker.get('pg', {})
805 proguard_dex_size = float(proguard_result.get('dex_size', -1))
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +0100806
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200807 for shrinker in SHRINKERS:
808 if shrinker not in result_per_shrinker:
809 continue
810 compilation_index = 1
811 for result in result_per_shrinker.get(shrinker):
812 build_status = result.get('build_status')
813 if build_status != 'success' and build_status is not None:
814 app_error = True
815 warn(' {}-#{}: {}'.format(shrinker, compilation_index,
816 build_status))
817 continue
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +0100818
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200819 if options.golem:
820 print_thread(
821 '%s(RunTimeRaw): %s ms' %
822 (app.name, result.get('duration')), worker_id)
823 print_thread(
824 '%s(CodeSize): %s' % (app.name, result.get('dex_size')),
825 worker_id)
826 continue
Rico Wind59593922021-03-03 09:12:36 +0100827
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200828 print_thread(' {}-#{}:'.format(shrinker, compilation_index),
829 worker_id)
830 dex_size = result.get('dex_size')
831 msg = ' dex size: {}'.format(dex_size)
832 if options.print_runtimeraw:
833 print_thread(
834 ' run time raw: {} ms'.format(result.get('duration')),
835 worker_id)
836 if dex_size != proguard_dex_size and proguard_dex_size >= 0:
837 msg = '{} ({}, {})'.format(
838 msg, dex_size - proguard_dex_size,
839 percentage_diff_as_string(proguard_dex_size, dex_size))
840 success(msg) if dex_size < proguard_dex_size else warn(msg)
841 else:
842 print_thread(msg, worker_id)
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +0100843
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200844 if options.monkey:
845 monkey_status = result.get('monkey_status')
846 if monkey_status != 'success':
847 app_error = True
848 warn(' monkey: {}'.format(monkey_status))
849 else:
850 success(' monkey: {}'.format(monkey_status))
Morten Krogh-Jespersencd55f812020-11-04 09:13:31 +0100851
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200852 if options.run_tests and 'instrumentation_test_status' in result:
853 test_status = result.get('instrumentation_test_status')
854 if test_status != 'success':
855 warn(' instrumentation_tests: {}'.format(test_status))
856 else:
857 success(' instrumentation_tests: {}'.format(test_status))
Morten Krogh-Jespersen51a16352020-11-04 09:31:15 +0100858
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200859 recompilation_status = result.get('recompilation_status', '')
860 if recompilation_status == 'failed':
861 app_error = True
862 warn(' recompilation {}-#{}: failed'.format(
863 shrinker, compilation_index))
864 continue
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +0100865
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200866 compilation_index += 1
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +0100867
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200868 return app_error
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +0100869
870
871def parse_options(argv):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200872 result = argparse.ArgumentParser(description='Run/compile dump artifacts.')
873 result.add_argument('--app',
874 help='What app to run on',
875 choices=[app.name for app in APPS],
876 action='append')
877 result.add_argument(
878 '--app-collection',
879 '--app_collection',
880 help='What app collection to run',
881 choices=[collection.name for collection in APP_COLLECTIONS],
882 action='append')
883 result.add_argument('--app-logging-filter',
884 '--app_logging_filter',
885 help='The apps for which to turn on logging',
886 action='append')
887 result.add_argument('--bot',
888 help='Running on bot, use third_party dependency.',
889 default=False,
890 action='store_true')
891 result.add_argument('--generate-golem-config',
892 '--generate_golem_config',
893 help='Generate a new config for golem.',
894 default=False,
895 action='store_true')
896 result.add_argument('--debug-agent',
897 help='Enable Java debug agent and suspend compilation '
898 '(default disabled)',
899 default=False,
900 action='store_true')
901 result.add_argument(
902 '--disable-assertions',
903 '--disable_assertions',
904 '-da',
905 help='Disable Java assertions when running the compiler '
906 '(default enabled)',
907 default=False,
908 action='store_true')
Christoffer Quist Adamsena2f22a42024-01-23 16:35:45 +0100909 result.add_argument(
910 '--dump-input-to-directory',
911 '--dump_input_to_directory',
912 help='Dump all compilations to directory',
913 default=None)
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +0200914 result.add_argument('--emulator-id',
915 '--emulator_id',
916 help='Id of the emulator to use',
917 default='emulator-5554')
918 result.add_argument('--golem',
919 help='Running on golem, do not download',
920 default=False,
921 action='store_true')
922 result.add_argument('--hash', help='The commit of R8 to use')
923 result.add_argument(
924 '--internal',
925 help='Run internal apps if set, otherwise run opensource',
926 default=False,
927 action='store_true')
928 result.add_argument('--keystore',
929 help='Path to app.keystore',
930 default=os.path.join(utils.TOOLS_DIR, 'debug.keystore'))
931 result.add_argument('--keystore-password',
932 '--keystore_password',
933 help='Password for app.keystore',
934 default='android')
935 result.add_argument('--minify',
936 help='Force enable/disable minification' +
937 ' (defaults to app proguard config)',
938 choices=['default', 'force-enable', 'force-disable'],
939 default='default')
940 result.add_argument('--monkey',
941 help='Whether to install and run app(s) with monkey',
942 default=False,
943 action='store_true')
944 result.add_argument('--monkey-events',
945 '--monkey_events',
946 help='Number of events that the monkey should trigger',
947 default=250,
948 type=int)
949 result.add_argument('--no-build',
950 '--no_build',
951 help='Run without building first (only when using ToT)',
952 default=False,
953 action='store_true')
954 result.add_argument('--no-logging',
955 '--no_logging',
956 help='Disable logging except for errors',
957 default=False,
958 action='store_true')
959 result.add_argument('--optimize',
960 help='Force enable/disable optimizations' +
961 ' (defaults to app proguard config)',
962 choices=['default', 'force-enable', 'force-disable'],
963 default='default')
964 result.add_argument('--print-times',
965 help='Print timing information from r8',
966 default=False,
967 action='store_true')
968 result.add_argument('--print-dexsegments',
969 metavar='BENCHMARKNAME',
970 help='Print the sizes of individual dex segments as ' +
971 '\'<BENCHMARKNAME>-<APP>-<segment>(CodeSize): '
972 '<bytes>\'')
973 result.add_argument('--print-runtimeraw',
974 metavar='BENCHMARKNAME',
975 help='Print the line \'<BENCHMARKNAME>(RunTimeRaw):' +
976 ' <elapsed> ms\' at the end where <elapsed> is' +
977 ' the elapsed time in milliseconds.')
978 result.add_argument('--quiet',
979 help='Disable verbose logging',
980 default=False,
981 action='store_true')
982 result.add_argument('--r8-compilation-steps',
983 '--r8_compilation_steps',
984 help='Number of times R8 should be run on each app',
985 default=2,
986 type=int)
987 result.add_argument('--r8-flags',
988 '--r8_flags',
989 help='Additional option(s) for the compiler.')
990 result.add_argument('--run-tests',
991 '--run_tests',
992 help='Whether to run instrumentation tests',
993 default=False,
994 action='store_true')
995 result.add_argument('--shrink',
996 help='Force enable/disable shrinking' +
997 ' (defaults to app proguard config)',
998 choices=['default', 'force-enable', 'force-disable'],
999 default='default')
1000 result.add_argument('--sign-apks',
1001 '--sign_apks',
1002 help='Whether the APKs should be signed',
1003 default=False,
1004 action='store_true')
1005 result.add_argument('--shrinker',
1006 help='The shrinkers to use (by default, all are run)',
1007 action='append')
1008 result.add_argument('--temp',
1009 help='A directory to use for temporaries and outputs.',
1010 default=None)
1011 result.add_argument('--version',
1012 default='main',
1013 help='The version of R8 to use (e.g., 1.4.51)')
1014 result.add_argument('--workers',
1015 help='Number of workers to use',
1016 default=1,
1017 type=int)
1018 (options, args) = result.parse_known_args(argv)
Christoffer Quist Adamsen53e29472020-11-13 10:53:06 +01001019
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +02001020 if options.app or options.app_collection:
1021 if not options.app:
1022 options.app = []
1023 if not options.app_collection:
1024 options.app_collection = []
1025 options.apps = [
1026 app for app in APPS if app.name in options.app or any(
1027 collection in options.app_collection
1028 for collection in app.collections)
1029 ]
1030 del options.app
1031 del options.app_collection
1032 else:
1033 options.apps = [app for app in APPS if app.internal == options.internal]
Christoffer Quist Adamsen53e29472020-11-13 10:53:06 +01001034
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +02001035 if options.app_logging_filter:
1036 for app_name in options.app_logging_filter:
1037 assert any(app.name == app_name for app in options.apps)
1038 if options.shrinker:
1039 for shrinker in options.shrinker:
1040 assert shrinker in SHRINKERS, ('Shrinker must be one of %s' %
1041 ', '.join(SHRINKERS))
1042 else:
1043 options.shrinker = [shrinker for shrinker in SHRINKERS]
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +01001044
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +02001045 if options.hash or version_is_built_jar(options.version):
1046 # No need to build R8 if a specific version should be used.
1047 options.no_build = True
1048 if 'r8-nolib' in options.shrinker:
1049 warn('Skipping shrinker r8-nolib because a specific version ' +
1050 'of r8 was specified')
1051 options.shrinker.remove('r8-nolib')
1052 if 'r8-nolib-full' in options.shrinker:
1053 warn('Skipping shrinker r8-nolib-full because a specific version ' +
1054 'of r8 was specified')
1055 options.shrinker.remove('r8-nolib-full')
1056 return (options, args)
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +01001057
1058
Rico Wind59593922021-03-03 09:12:36 +01001059def print_indented(s, indent):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +02001060 print(' ' * indent + s)
Rico Wind59593922021-03-03 09:12:36 +01001061
1062
1063def get_sha256(gz_file):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +02001064 with open(gz_file, 'rb') as f:
1065 bytes = f.read() # read entire file as bytes
1066 return hashlib.sha256(bytes).hexdigest()
Rico Wind59593922021-03-03 09:12:36 +01001067
1068
1069def get_sha_from_file(sha_file):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +02001070 with open(sha_file, 'r') as f:
1071 return f.readlines()[0]
Rico Wind59593922021-03-03 09:12:36 +01001072
1073
1074def print_golem_config(options):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +02001075 print('// AUTOGENERATED FILE from tools/run_on_app_dump.py in R8 repo')
1076 print('part of r8_config;')
1077 print('')
1078 print('final Suite dumpsSuite = Suite("OpenSourceAppDumps");')
1079 print('')
1080 print('createOpenSourceAppBenchmarks() {')
1081 print_indented('final cpus = ["Lenovo M90"];', 2)
1082 print_indented('final targetsCompat = ["R8"];', 2)
1083 print_indented('final targetsFull = ["R8-full-minify-optimize-shrink"];', 2)
1084 # Avoid calculating this for every app
1085 jdk_gz = jdk.GetJdkHome() + '.tar.gz'
1086 add_golem_resource(2, jdk_gz, 'openjdk')
1087 for app in options.apps:
1088 if app.folder and not app.internal:
1089 indentation = 2
1090 print_indented('{', indentation)
1091 indentation = 4
1092 print_indented('final name = "%s";' % app.name, indentation)
1093 print_indented('final benchmark =', indentation)
1094 print_indented(
1095 'StandardBenchmark(name, [Metric.RunTimeRaw, Metric.CodeSize]);',
1096 indentation + 4)
1097 if app.golem_duration != None:
1098 print_indented(
1099 'final timeout = const Duration(seconds: %s);' %
1100 app.golem_duration, indentation)
1101 print_indented(
1102 'ExecutionManagement.addTimeoutConstraint'
1103 '(timeout, benchmark: benchmark);', indentation)
1104 app_gz = os.path.join(utils.OPENSOURCE_DUMPS_DIR,
1105 app.folder + '.tar.gz')
1106 name = 'appResource'
1107 add_golem_resource(indentation, app_gz, name)
1108 print_golem_config_target('Compat', 'r8', app, indentation)
1109 print_golem_config_target('Full',
1110 'r8-full',
1111 app,
1112 indentation,
1113 minify='force-enable',
1114 optimize='force-enable',
1115 shrink='force-enable')
1116 print_indented('dumpsSuite.addBenchmark(name);', indentation)
1117 indentation = 2
1118 print_indented('}', indentation)
1119 print('}')
Rico Wind59593922021-03-03 09:12:36 +01001120
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +02001121
1122def print_golem_config_target(target,
1123 shrinker,
1124 app,
1125 indentation,
1126 minify='default',
1127 optimize='default',
1128 shrink='default'):
1129 options = "options" + target
1130 print_indented(
1131 'final %s = benchmark.addTargets(noImplementation, targets%s);' %
1132 (options, target), indentation)
1133 print_indented('%s.cpus = cpus;' % options, indentation)
1134 print_indented('%s.isScript = true;' % options, indentation)
1135 print_indented('%s.fromRevision = 9700;' % options, indentation)
1136 print_indented('%s.mainFile = "tools/run_on_app_dump.py "' % options,
1137 indentation)
1138 print_indented(
1139 '"--golem --disable-assertions --quiet --shrinker %s --app %s "' %
1140 (shrinker, app.name), indentation + 4)
1141 print_indented(
1142 '"--minify %s --optimize %s --shrink %s";' % (minify, optimize, shrink),
1143 indentation + 4)
1144 print_indented('%s.resources.add(appResource);' % options, indentation)
1145 print_indented('%s.resources.add(openjdk);' % options, indentation)
1146
Christoffer Quist Adamsen8e9f7982021-12-10 13:10:05 +01001147
Rico Wind61a034f2021-03-16 09:37:11 +01001148def add_golem_resource(indentation, gz, name, sha256=None):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +02001149 sha = gz + '.sha1'
1150 if not sha256:
1151 # Golem uses a sha256 of the file in the cache, and you need to specify that.
1152 download_sha(sha, False, quiet=True)
1153 sha256 = get_sha256(gz)
1154 sha = get_sha_from_file(sha)
1155 print_indented('final %s = BenchmarkResource("",' % name, indentation)
1156 print_indented('type: BenchmarkResourceType.storage,', indentation + 4)
1157 print_indented('uri: "gs://r8-deps/%s",' % sha, indentation + 4)
1158 # Make dart formatter happy.
1159 if indentation > 2:
1160 print_indented('hash:', indentation + 4)
1161 print_indented('"%s",' % sha256, indentation + 8)
1162 else:
1163 print_indented('hash: "%s",' % sha256, indentation + 4)
1164 print_indented('extract: "gz");', indentation + 4)
1165
Rico Wind61a034f2021-03-16 09:37:11 +01001166
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +01001167def main(argv):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +02001168 (options, args) = parse_options(argv)
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +01001169
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +02001170 if options.bot:
1171 options.no_logging = True
1172 options.shrinker = ['r8', 'r8-full']
1173 print(options.shrinker)
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +01001174
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +02001175 if options.golem:
1176 options.disable_assertions = True
1177 options.no_build = True
1178 options.r8_compilation_steps = 1
1179 options.quiet = True
1180 options.no_logging = True
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +01001181
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +02001182 if options.generate_golem_config:
1183 print_golem_config(options)
1184 return 0
Rico Wind59593922021-03-03 09:12:36 +01001185
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +02001186 with utils.TempDir() as temp_dir:
1187 if options.temp:
1188 temp_dir = options.temp
1189 os.makedirs(temp_dir, exist_ok=True)
1190 if options.hash:
1191 # Download r8-<hash>.jar from
1192 # https://storage.googleapis.com/r8-releases/raw/.
1193 target = 'r8-{}.jar'.format(options.hash)
1194 update_prebuilds_in_android.download_hash(
1195 temp_dir, 'com/android/tools/r8/' + options.hash, target)
1196 as_utils.MoveFile(os.path.join(temp_dir, target),
1197 os.path.join(temp_dir, 'r8lib.jar'),
1198 quiet=options.quiet)
1199 elif version_is_built_jar(options.version):
1200 # Download r8-<version>.jar from
1201 # https://storage.googleapis.com/r8-releases/raw/.
1202 target = 'r8-{}.jar'.format(options.version)
1203 update_prebuilds_in_android.download_version(
1204 temp_dir, 'com/android/tools/r8/' + options.version, target)
1205 as_utils.MoveFile(os.path.join(temp_dir, target),
1206 os.path.join(temp_dir, 'r8lib.jar'),
1207 quiet=options.quiet)
1208 elif options.version == 'main':
1209 if not options.no_build:
1210 gradle.RunGradle([
Ian Zernyed1f8512023-11-07 11:07:57 +01001211 utils.GRADLE_TASK_R8,
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +02001212 '-Pno_internal'
1213 ])
1214 build_r8lib = False
1215 for shrinker in options.shrinker:
1216 if is_minified_r8(shrinker):
1217 build_r8lib = True
1218 if build_r8lib:
1219 gradle.RunGradle([utils.GRADLE_TASK_R8LIB, '-Pno_internal'])
1220 # Make a copy of r8.jar and r8lib.jar such that they stay the same for
1221 # the entire execution of this script.
1222 if 'r8-nolib' in options.shrinker or 'r8-nolib-full' in options.shrinker:
1223 assert os.path.isfile(
1224 utils.R8_JAR), 'Cannot build without r8.jar'
1225 shutil.copyfile(utils.R8_JAR, os.path.join(temp_dir, 'r8.jar'))
1226 if 'r8' in options.shrinker or 'r8-full' in options.shrinker:
1227 assert os.path.isfile(
1228 utils.R8LIB_JAR), 'Cannot build without r8lib.jar'
1229 shutil.copyfile(utils.R8LIB_JAR,
1230 os.path.join(temp_dir, 'r8lib.jar'))
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +01001231
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +02001232 jobs = []
1233 result_per_shrinker_per_app = []
1234 for app in options.apps:
1235 if app.skip:
1236 continue
1237 result = {}
1238 result_per_shrinker_per_app.append((app, result))
1239 jobs.append(create_job(app, options, result, temp_dir))
1240 thread_utils.run_in_parallel(jobs,
1241 number_of_workers=options.workers,
1242 stop_on_first_failure=False)
1243 errors = log_results_for_apps(result_per_shrinker_per_app, options)
1244 if errors > 0:
1245 dest = 'gs://r8-test-results/r8-libs/' + str(int(time.time()))
1246 utils.upload_file_to_cloud_storage(
1247 os.path.join(temp_dir, 'r8lib.jar'), dest)
1248 print('R8lib saved to %s' % dest)
1249 return errors
1250
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +01001251
Christoffer Quist Adamsenbe6661d2023-08-24 11:01:12 +02001252def create_job(app, options, result, temp_dir):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +02001253 return lambda worker_id: run_job(app, options, result, temp_dir, worker_id)
1254
Christoffer Quist Adamsenbe6661d2023-08-24 11:01:12 +02001255
1256def run_job(app, options, result, temp_dir, worker_id):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +02001257 job_temp_dir = os.path.join(temp_dir, str(worker_id or 0))
1258 os.makedirs(job_temp_dir, exist_ok=True)
1259 result.update(get_results_for_app(app, options, job_temp_dir, worker_id))
1260 return 0
1261
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +01001262
1263def success(message):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +02001264 CGREEN = '\033[32m'
1265 CEND = '\033[0m'
1266 print(CGREEN + message + CEND)
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +01001267
1268
1269def warn(message):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +02001270 CRED = '\033[91m'
1271 CEND = '\033[0m'
1272 print(CRED + message + CEND)
Morten Krogh-Jespersen45d7a7b2020-11-02 08:31:09 +01001273
1274
1275if __name__ == '__main__':
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +02001276 sys.exit(main(sys.argv[1:]))