blob: f865e2d56ef127d9d089444f0ec834d758b662ef [file] [log] [blame]
Søren Gjessecdae8792018-12-12 09:02:43 +01001#!/usr/bin/env python
2# Copyright (c) 2018, 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
Christoffer Quist Adamsen4038bbe2019-01-15 14:31:46 +01006import apk_masseur
Søren Gjessecdae8792018-12-12 09:02:43 +01007import apk_utils
Morten Krogh-Jespersenc2fbde22019-02-07 13:59:55 +01008import golem
Søren Gjesseeed839d2019-01-11 15:19:16 +01009import gradle
Ian Zerny3f54e222019-02-12 10:51:17 +010010import jdk
Christoffer Quist Adamsen2a902752019-02-19 12:33:48 +010011import json
Søren Gjessecdae8792018-12-12 09:02:43 +010012import os
13import optparse
Christoffer Quist Adamsenbbe5d7d2019-01-23 13:15:21 +010014import shutil
Søren Gjessecdae8792018-12-12 09:02:43 +010015import subprocess
16import sys
Christoffer Quist Adamsen1d0a0fe2018-12-21 14:28:56 +010017import time
Søren Gjessecdae8792018-12-12 09:02:43 +010018import utils
Christoffer Quist Adamsen404aade2018-12-20 13:00:09 +010019import zipfile
Christoffer Quist Adamsen7cf4c562019-03-07 10:57:33 +010020from xml.dom import minidom
Søren Gjessecdae8792018-12-12 09:02:43 +010021
Christoffer Quist Adamsen10b7db82018-12-13 14:50:38 +010022import as_utils
Christoffer Quist Adamsen2a902752019-02-19 12:33:48 +010023import create_maven_release
24import update_prebuilds_in_android
Christoffer Quist Adamsen10b7db82018-12-13 14:50:38 +010025
Morten Krogh-Jespersend45d95e2019-02-07 13:27:17 +010026SHRINKERS = ['r8', 'r8-full', 'r8-nolib', 'r8-nolib-full', 'pg']
Morten Krogh-Jespersen64740202019-02-07 13:06:04 +010027WORKING_DIR = os.path.join(utils.BUILD, 'opensource_apps')
Christoffer Quist Adamsen10b7db82018-12-13 14:50:38 +010028
Morten Krogh-Jespersenaeb665e2019-02-07 12:29:03 +010029if ('R8_BENCHMARK_DIR' in os.environ
30 and os.path.isdir(os.environ['R8_BENCHMARK_DIR'])):
Christoffer Quist Adamsen10b7db82018-12-13 14:50:38 +010031 WORKING_DIR = os.environ['R8_BENCHMARK_DIR']
Søren Gjessecdae8792018-12-12 09:02:43 +010032
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +010033class Repo(object):
34 def __init__(self, fields):
35 self.__dict__ = fields
36
37 # If there is only one app in this repository, then give the app the same
38 # name as the repository, if it does not already have one.
39 if len(self.apps) == 1:
40 app = self.apps[0]
41 if not app.name:
42 app.name = self.name
43
44class App(object):
45 def __init__(self, fields):
46 module = fields.get('module', 'app')
47 defaults = {
48 'archives_base_name': module,
49 'build_dir': 'build',
50 'compile_sdk': None,
51 'dir': '.',
52 'flavor': None,
Christoffer Quist Adamsen7cf4c562019-03-07 10:57:33 +010053 'has_instrumentation_tests': False,
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +010054 'main_dex_rules': None,
55 'module': module,
56 'min_sdk': None,
57 'name': None,
58 'releaseTarget': None,
59 'signed_apk_name': None,
60 'skip': False
61 }
62 self.__dict__ = dict(defaults.items() + fields.items())
63
64# For running on Golem all third-party repositories are bundled as an x20-
65# dependency and then copied to WORKING_DIR. To update the app-bundle use
66# 'run_on_as_app_x20_packager.py'.
67APP_REPOSITORIES = [
68 # ...
69 # Repo({
70 # 'name': ...,
71 # 'url': ...,
Morten Krogh-Jespersene0ce6a32019-02-07 11:44:45 +010072 # 'revision': ...,
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +010073 # 'apps': [
74 # {
75 # 'id': ...,
76 # 'dir': ...,
77 # 'module': ... (default app)
78 # 'name': ...,
79 # 'archives_base_name': ... (default same as module)
80 # 'flavor': ... (default no flavor)
81 # 'releaseTarget': ... (default <module>:assemble<flavor>Release
82 # },
83 # ...
84 # ]
85 # }),
86 # ...
87 Repo({
88 'name': 'android-suite',
89 'url': 'https://github.com/christofferqa/android-suite',
90 'revision': '46c96f214711cf6cdcb72cc0c94520ef418e3739',
91 'apps': [
92 App({
93 'id': 'com.numix.calculator',
94 'dir': 'Calculator',
Christoffer Quist Adamsen7cf4c562019-03-07 10:57:33 +010095 'name': 'numix-calculator',
96 'has_instrumentation_tests': True
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +010097 })
98 ]
99 }),
100 Repo({
101 'name': 'AnExplorer',
102 'url': 'https://github.com/christofferqa/AnExplorer',
Morten Krogh-Jespersene0ce6a32019-02-07 11:44:45 +0100103 'revision': '365927477b8eab4052a1882d5e358057ae3dee4d',
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100104 'apps': [
105 App({
106 'id': 'dev.dworks.apps.anexplorer.pro',
107 'flavor': 'googleMobilePro',
108 'signed_apk_name': 'AnExplorer-googleMobileProRelease-4.0.3.apk',
109 'min_sdk': 17
110 })
111 ]
112 }),
113 Repo({
114 'name': 'AntennaPod',
115 'url': 'https://github.com/christofferqa/AntennaPod.git',
Morten Krogh-Jespersene0ce6a32019-02-07 11:44:45 +0100116 'revision': '77e94f4783a16abe9cc5b78dc2d2b2b1867d8c06',
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100117 'apps': [
118 App({
119 'id': 'de.danoeh.antennapod',
120 'flavor': 'play',
121 'min_sdk': 14,
122 'compile_sdk': 26
123 })
124 ]
125 }),
126 Repo({
Morten Krogh-Jespersen2af7daa2019-03-11 13:50:42 +0100127 'name': 'applymapping',
128 'url': 'https://github.com/mkj-gram/applymapping',
129 'revision': 'f94a6726859b2a832752bb349a56ce405441e31f',
130 'apps': [
131 App({
132 'id': 'com.example.applymapping',
133 'has_instrumentation_tests': True
134 })
135 ]
136 }),
137 Repo({
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100138 'name': 'apps-android-wikipedia',
139 'url': 'https://github.com/christofferqa/apps-android-wikipedia',
Morten Krogh-Jespersene0ce6a32019-02-07 11:44:45 +0100140 'revision': '686e8aa5682af8e6a905054b935dd2daa57e63ee',
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100141 'apps': [
142 App({
143 'id': 'org.wikipedia',
144 'flavor': 'prod',
145 'signed_apk_name': 'app-prod-universal-release.apk'
146 })
147 ]
148 }),
149 Repo({
150 'name': 'chanu',
151 'url': 'https://github.com/mkj-gram/chanu.git',
Morten Krogh-Jespersen81bf5ab2019-03-11 13:33:16 +0100152 'revision': 'f5dae10b965974f7bf7cf75b8fa80ba9c844f102',
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100153 'apps': [
154 App({
155 'id': 'com.chanapps.four.activity'
156 })
157 ]
158 }),
159 Repo({
160 'name': 'friendlyeats-android',
161 'url': 'https://github.com/christofferqa/friendlyeats-android.git',
Morten Krogh-Jespersene0ce6a32019-02-07 11:44:45 +0100162 'revision': '10091fa0ec37da12e66286559ad1b6098976b07b',
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100163 'apps': [
164 App({
165 'id': 'com.google.firebase.example.fireeats'
166 })
167 ]
168 }),
169 Repo({
170 'name': 'Instabug-Android',
171 'url': 'https://github.com/christofferqa/Instabug-Android.git',
172 'revision': 'b8df78c96630a6537fbc07787b4990afc030cc0f',
173 'apps': [
174 App({
175 'id': 'com.example.instabug'
176 })
177 ]
178 }),
179 Repo({
180 'name': 'KISS',
181 'url': 'https://github.com/christofferqa/KISS',
Morten Krogh-Jespersene0ce6a32019-02-07 11:44:45 +0100182 'revision': '093da9ee0512e67192f62951c45a07a616fc3224',
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100183 'apps': [
184 App({
185 'id': 'fr.neamar.kiss'
186 })
187 ]
188 }),
189 Repo({
190 'name': 'materialistic',
191 'url': 'https://github.com/christofferqa/materialistic',
Morten Krogh-Jespersene0ce6a32019-02-07 11:44:45 +0100192 'revision': '2b2b2ee25ce9e672d5aab1dc90a354af1522b1d9',
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100193 'apps': [
194 App({
195 'id': 'io.github.hidroh.materialistic'
196 })
197 ]
198 }),
199 Repo({
200 'name': 'Minimal-Todo',
201 'url': 'https://github.com/christofferqa/Minimal-Todo',
Morten Krogh-Jespersene0ce6a32019-02-07 11:44:45 +0100202 'revision': '9d8c73746762cd376b718858ec1e8783ca07ba7c',
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100203 'apps': [
204 App({
205 'id': 'com.avjindersinghsekhon.minimaltodo'
206 })
207 ]
208 }),
209 Repo({
Christoffer Quist Adamsen493acd82019-03-14 12:20:02 +0100210 'name': 'muzei',
211 'url': 'https://github.com/sgjesse/muzei.git',
212 'revision': 'e7e4ab1039bb18009254b94831b17676bc3b8bc1',
213 'apps': [
214 App({
215 'id': 'net.nurik.roman.muzei',
216 'module': 'main',
217 'archives_base_name': 'muzei',
218 'compile_sdk': 28
219 })
220 ]
221 }),
222 Repo({
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100223 'name': 'NewPipe',
224 'url': 'https://github.com/christofferqa/NewPipe',
Morten Krogh-Jespersene0ce6a32019-02-07 11:44:45 +0100225 'revision': 'ed543099c7823be00f15d9340f94bdb7cb37d1e6',
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100226 'apps': [
227 App({
228 'id': 'org.schabi.newpipe'
229 })
230 ]
231 }),
232 Repo({
233 'name': 'rover-android',
234 'url': 'https://github.com/mkj-gram/rover-android.git',
Morten Krogh-Jespersen81bf5ab2019-03-11 13:33:16 +0100235 'revision': 'a5e155a1ed7d19b1cecd9a7b075e2852623a06bf',
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100236 'apps': [
237 App({
238 'id': 'io.rover.app.debug',
239 'module': 'debug-app'
240 })
241 ]
242 }),
243 Repo({
244 'name': 'Signal-Android',
245 'url': 'https://github.com/mkj-gram/Signal-Android.git',
Morten Krogh-Jespersen81bf5ab2019-03-11 13:33:16 +0100246 'revision': 'cd542cab9bf860e71504ecb1caaf0a8476ba3989',
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100247 'apps': [
248 App({
249 'id': 'org.thoughtcrime.securesms',
250 'module': '',
251 'flavor': 'play',
252 'main_dex_rules': 'multidex-config.pro',
253 'releaseTarget': 'assemblePlayRelease',
254 'signed_apk_name': 'Signal-play-release-4.32.7.apk'
255 })
256 ]
257 }),
258 Repo({
259 'name': 'Simple-Calendar',
260 'url': 'https://github.com/christofferqa/Simple-Calendar',
Morten Krogh-Jespersene0ce6a32019-02-07 11:44:45 +0100261 'revision': '82dad8c203eea5a0f0ddb513506d8f1de986ef2b',
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100262 'apps': [
263 App({
264 'id': 'com.simplemobiletools.calendar.pro',
265 'signed_apk_name': 'calendar-release.apk'
266 })
267 ]
268 }),
269 Repo({
270 'name': 'sqldelight',
271 'url': 'https://github.com/christofferqa/sqldelight.git',
Morten Krogh-Jespersene0ce6a32019-02-07 11:44:45 +0100272 'revision': '2e67a1126b6df05e4119d1e3a432fde51d76cdc8',
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100273 'apps': [
274 App({
275 'id': 'com.example.sqldelight.hockey',
276 'module': 'sample/android',
277 'archives_base_name': 'android',
278 'min_sdk': 14,
279 'compile_sdk': 28
280 })
281 ]
282 }),
283 Repo({
284 'name': 'tachiyomi',
285 'url': 'https://github.com/sgjesse/tachiyomi.git',
Morten Krogh-Jespersene0ce6a32019-02-07 11:44:45 +0100286 'revision': 'b15d2fe16864645055af6a745a62cc5566629798',
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100287 'apps': [
288 App({
289 'id': 'eu.kanade.tachiyomi',
290 'flavor': 'standard',
291 'releaseTarget': 'app:assembleRelease',
292 'min_sdk': 16
293 })
294 ]
295 }),
296 Repo({
297 'name': 'tivi',
298 'url': 'https://github.com/sgjesse/tivi.git',
Søren Gjessedbe6ebc2019-02-14 09:38:47 +0100299 'revision': '25c52e3593e7c98da4e537b49b29f6f67f88754d',
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100300 'apps': [
301 App({
302 'id': 'app.tivi',
303 'min_sdk': 23,
304 'compile_sdk': 28
305 })
306 ]
307 }),
308 Repo({
309 'name': 'Tusky',
310 'url': 'https://github.com/mkj-gram/Tusky.git',
Morten Krogh-Jespersen81bf5ab2019-03-11 13:33:16 +0100311 'revision': 'e7fbd190fb53bf9fde72253b816920cb6fe34518',
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100312 'apps': [
313 App({
314 'id': 'com.keylesspalace.tusky',
315 'flavor': 'blue'
316 })
317 ]
318 }),
319 Repo({
320 'name': 'Vungle-Android-SDK',
321 'url': 'https://github.com/mkj-gram/Vungle-Android-SDK.git',
Morten Krogh-Jespersen81bf5ab2019-03-11 13:33:16 +0100322 'revision': '138d3f18c027b61b195c98911f1c5ab7d87ad18b',
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100323 'apps': [
324 App({
325 'id': 'com.publisher.vungle.sample'
326 })
327 ]
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100328 })
329]
330
331def GetAllApps():
332 apps = []
333 for repo in APP_REPOSITORIES:
334 for app in repo.apps:
335 apps.append((app, repo))
336 return apps
337
338def GetAllAppNames():
339 return [app.name for (app, repo) in GetAllApps()]
340
341def GetAppWithName(query):
342 for (app, repo) in GetAllApps():
343 if app.name == query:
344 return (app, repo)
345 assert False
Søren Gjessecdae8792018-12-12 09:02:43 +0100346
Christoffer Quist Adamsen404aade2018-12-20 13:00:09 +0100347def ComputeSizeOfDexFilesInApk(apk):
348 dex_size = 0
349 z = zipfile.ZipFile(apk, 'r')
350 for filename in z.namelist():
351 if filename.endswith('.dex'):
352 dex_size += z.getinfo(filename).file_size
353 return dex_size
354
Christoffer Quist Adamsen2a902752019-02-19 12:33:48 +0100355def ExtractMarker(apk, temp_dir, options):
Christoffer Quist Adamsenbbe5d7d2019-01-23 13:15:21 +0100356 r8_jar = os.path.join(temp_dir, 'r8.jar')
Christoffer Quist Adamsenbe2593f2019-02-19 13:01:56 +0100357 r8lib_jar = os.path.join(temp_dir, 'r8lib.jar')
Christoffer Quist Adamsenbbe5d7d2019-01-23 13:15:21 +0100358
Christoffer Quist Adamsenbe2593f2019-02-19 13:01:56 +0100359 # Use the copy of r8.jar or r8lib.jar if one is there.
Christoffer Quist Adamsenbbe5d7d2019-01-23 13:15:21 +0100360 if os.path.isfile(r8_jar):
Ian Zerny3f54e222019-02-12 10:51:17 +0100361 cmd = [jdk.GetJavaExecutable(), '-ea', '-jar', r8_jar, 'extractmarker', apk]
Christoffer Quist Adamsenbe2593f2019-02-19 13:01:56 +0100362 elif os.path.isfile(r8lib_jar):
363 cmd = [jdk.GetJavaExecutable(), '-ea', '-cp', r8lib_jar,
Morten Krogh-Jespersen220e5702019-02-27 12:57:01 +0100364 'com.android.tools.r8.ExtractMarker', apk]
Christoffer Quist Adamsenbbe5d7d2019-01-23 13:15:21 +0100365 else:
366 script = os.path.join(utils.TOOLS_DIR, 'extractmarker.py')
367 cmd = ['python', script, apk]
368
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100369 utils.PrintCmd(cmd, quiet=options.quiet)
Christoffer Quist Adamsen2a902752019-02-19 12:33:48 +0100370 stdout = subprocess.check_output(cmd)
371
372 # Return the last line.
373 lines = stdout.strip().splitlines()
374 assert len(lines) >= 1
375 return lines[-1]
376
Morten Krogh-Jespersen0de13732019-03-01 08:56:39 +0100377def CheckIsBuiltWithExpectedR8(apk, temp_dir, shrinker, options):
Christoffer Quist Adamsen2a902752019-02-19 12:33:48 +0100378 marker = ExtractMarker(apk, temp_dir, options)
379 expected_version = (
380 options.version
381 if options.version
Morten Krogh-Jespersen0de13732019-03-01 08:56:39 +0100382 else utils.getR8Version(
383 os.path.join(
384 temp_dir,
385 'r8lib.jar' if IsMinifiedR8(shrinker) else 'r8.jar')))
Christoffer Quist Adamsen2a902752019-02-19 12:33:48 +0100386 if marker.startswith('~~R8'):
387 actual_version = json.loads(marker[4:]).get('version')
388 if actual_version == expected_version:
389 return True
390 raise Exception(
391 'Expected APK to be built with R8 version {} (was: {})'.format(
392 expected_version, marker))
Christoffer Quist Adamsen10b7db82018-12-13 14:50:38 +0100393
Christoffer Quist Adamsen7cf4c562019-03-07 10:57:33 +0100394def isR8(shrinker):
395 return 'r8' in shrinker
396
397def isR8FullMode(shrinker):
398 return shrinker == 'r8-full' or shrinker == 'r8-nolib-full'
399
Morten Krogh-Jespersend45d95e2019-02-07 13:27:17 +0100400def IsMinifiedR8(shrinker):
401 return 'nolib' not in shrinker
402
Christoffer Quist Adamsen10b7db82018-12-13 14:50:38 +0100403def IsTrackedByGit(file):
404 return subprocess.check_output(['git', 'ls-files', file]).strip() != ''
405
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100406def GitClone(repo, checkout_dir, quiet):
Morten Krogh-Jespersene0ce6a32019-02-07 11:44:45 +0100407 result = subprocess.check_output(
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100408 ['git', 'clone', repo.url, checkout_dir]).strip()
Morten Krogh-Jespersene0ce6a32019-02-07 11:44:45 +0100409 head_rev = utils.get_HEAD_sha1_for_checkout(checkout_dir)
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100410 if repo.revision == head_rev:
Morten Krogh-Jespersene0ce6a32019-02-07 11:44:45 +0100411 return result
412 warn('Target revision is not head in {}.'.format(checkout_dir))
Morten Krogh-Jespersen54090862019-02-19 11:31:10 +0100413 with utils.ChangedWorkingDirectory(checkout_dir, quiet=quiet):
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100414 subprocess.check_output(['git', 'reset', '--hard', repo.revision])
Morten Krogh-Jespersene0ce6a32019-02-07 11:44:45 +0100415 return result
Søren Gjessecdae8792018-12-12 09:02:43 +0100416
417def GitCheckout(file):
418 return subprocess.check_output(['git', 'checkout', file]).strip()
419
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100420def InstallApkOnEmulator(apk_dest, options):
Christoffer Quist Adamsen7cf4c562019-03-07 10:57:33 +0100421 cmd = ['adb', '-s', options.emulator_id, 'install', '-r', '-d', apk_dest]
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100422 if options.quiet:
423 with open(os.devnull, 'w') as devnull:
424 subprocess.check_call(cmd, stdout=devnull)
425 else:
426 subprocess.check_call(cmd)
Christoffer Quist Adamsen1d0a0fe2018-12-21 14:28:56 +0100427
Christoffer Quist Adamsen81321b62019-01-15 14:39:53 +0100428def PercentageDiffAsString(before, after):
429 if after < before:
430 return '-' + str(round((1.0 - after / before) * 100)) + '%'
431 else:
432 return '+' + str(round((after - before) / before * 100)) + '%'
433
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100434def UninstallApkOnEmulator(app, options):
Christoffer Quist Adamsen4038bbe2019-01-15 14:31:46 +0100435 process = subprocess.Popen(
Christoffer Quist Adamsen7cf4c562019-03-07 10:57:33 +0100436 ['adb', '-s', options.emulator_id, 'uninstall', app.id],
Christoffer Quist Adamsen4038bbe2019-01-15 14:31:46 +0100437 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
438 stdout, stderr = process.communicate()
439
440 if stdout.strip() == 'Success':
441 # Successfully uninstalled
442 return
443
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100444 if 'Unknown package: {}'.format(app.id) in stderr:
Christoffer Quist Adamsen4038bbe2019-01-15 14:31:46 +0100445 # Application not installed
446 return
447
448 raise Exception(
449 'Unexpected result from `adb uninstall {}\nStdout: {}\nStderr: {}'.format(
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100450 app.id, stdout, stderr))
Christoffer Quist Adamsen4038bbe2019-01-15 14:31:46 +0100451
Christoffer Quist Adamsen7cf4c562019-03-07 10:57:33 +0100452def WaitForEmulator(options):
Christoffer Quist Adamsen1d0a0fe2018-12-21 14:28:56 +0100453 stdout = subprocess.check_output(['adb', 'devices'])
Christoffer Quist Adamsen7cf4c562019-03-07 10:57:33 +0100454 if '{}\tdevice'.format(options.emulator_id) in stdout:
Christoffer Quist Adamsenbae36612019-01-15 12:23:51 +0100455 return True
Christoffer Quist Adamsen1d0a0fe2018-12-21 14:28:56 +0100456
457 print('Emulator \'{}\' not connected; waiting for connection'.format(
Christoffer Quist Adamsen7cf4c562019-03-07 10:57:33 +0100458 options.emulator_id))
Christoffer Quist Adamsen1d0a0fe2018-12-21 14:28:56 +0100459
460 time_waited = 0
461 while True:
462 time.sleep(10)
463 time_waited += 10
464 stdout = subprocess.check_output(['adb', 'devices'])
Christoffer Quist Adamsen7cf4c562019-03-07 10:57:33 +0100465 if '{}\tdevice'.format(options.emulator_id) not in stdout:
Christoffer Quist Adamsen1d0a0fe2018-12-21 14:28:56 +0100466 print('... still waiting for connection')
467 if time_waited >= 5 * 60:
Christoffer Quist Adamsenbae36612019-01-15 12:23:51 +0100468 return False
Christoffer Quist Adamsen1d0a0fe2018-12-21 14:28:56 +0100469 else:
Christoffer Quist Adamsenbae36612019-01-15 12:23:51 +0100470 return True
Christoffer Quist Adamsen1d0a0fe2018-12-21 14:28:56 +0100471
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100472def GetResultsForApp(app, repo, options, temp_dir):
Christoffer Quist Adamsen3aa8d252018-12-13 14:56:40 +0100473 # Checkout and build in the build directory.
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100474 repo_name = repo.name
475 repo_checkout_dir = os.path.join(WORKING_DIR, repo_name)
Christoffer Quist Adamsen3aa8d252018-12-13 14:56:40 +0100476
Christoffer Quist Adamsen724bfb02019-01-10 09:54:38 +0100477 result = {}
478
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100479 if not os.path.exists(repo_checkout_dir) and not options.golem:
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100480 with utils.ChangedWorkingDirectory(WORKING_DIR, quiet=options.quiet):
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100481 GitClone(repo, repo_checkout_dir, options.quiet)
Christoffer Quist Adamsen860fa932019-01-10 14:27:39 +0100482
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100483 checkout_rev = utils.get_HEAD_sha1_for_checkout(repo_checkout_dir)
484 if repo.revision != checkout_rev:
Morten Krogh-Jespersene0ce6a32019-02-07 11:44:45 +0100485 msg = 'Checkout is not target revision for {} in {}.'.format(
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100486 app.name, repo_checkout_dir)
Morten Krogh-Jespersene0ce6a32019-02-07 11:44:45 +0100487 if options.ignore_versions:
488 warn(msg)
489 else:
490 raise Exception(msg)
Christoffer Quist Adamsen3aa8d252018-12-13 14:56:40 +0100491
Christoffer Quist Adamsen724bfb02019-01-10 09:54:38 +0100492 result['status'] = 'success'
493
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100494 app_checkout_dir = os.path.join(repo_checkout_dir, app.dir)
Christoffer Quist Adamsen724bfb02019-01-10 09:54:38 +0100495 result_per_shrinker = BuildAppWithSelectedShrinkers(
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100496 app, repo, options, app_checkout_dir, temp_dir)
Christoffer Quist Adamsen724bfb02019-01-10 09:54:38 +0100497 for shrinker, shrinker_result in result_per_shrinker.iteritems():
498 result[shrinker] = shrinker_result
499
500 return result
501
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100502def BuildAppWithSelectedShrinkers(
503 app, repo, options, checkout_dir, temp_dir):
Christoffer Quist Adamsen1d0a0fe2018-12-21 14:28:56 +0100504 result_per_shrinker = {}
Christoffer Quist Adamsen404aade2018-12-20 13:00:09 +0100505
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100506 with utils.ChangedWorkingDirectory(checkout_dir, quiet=options.quiet):
Christoffer Quist Adamsen2a902752019-02-19 12:33:48 +0100507 for shrinker in options.shrinker:
Christoffer Quist Adamsen1d0a0fe2018-12-21 14:28:56 +0100508 apk_dest = None
Christoffer Quist Adamsend0e0a7c2019-01-22 10:00:30 +0100509
Christoffer Quist Adamsen1d0a0fe2018-12-21 14:28:56 +0100510 result = {}
511 try:
Christoffer Quist Adamsend0e0a7c2019-01-22 10:00:30 +0100512 out_dir = os.path.join(checkout_dir, 'out', shrinker)
Christoffer Quist Adamsen4038bbe2019-01-15 14:31:46 +0100513 (apk_dest, profile_dest_dir, proguard_config_file) = \
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100514 BuildAppWithShrinker(
515 app, repo, shrinker, checkout_dir, out_dir, temp_dir,
516 options)
Christoffer Quist Adamsen1d0a0fe2018-12-21 14:28:56 +0100517 dex_size = ComputeSizeOfDexFilesInApk(apk_dest)
Morten Krogh-Jespersend35065e2019-02-07 10:28:52 +0100518 result['apk_dest'] = apk_dest
Christoffer Quist Adamsen1d0a0fe2018-12-21 14:28:56 +0100519 result['build_status'] = 'success'
520 result['dex_size'] = dex_size
Christoffer Quist Adamsen1d87ca62019-01-11 12:22:26 +0100521 result['profile_dest_dir'] = profile_dest_dir
Christoffer Quist Adamsen81321b62019-01-15 14:39:53 +0100522
523 profile = as_utils.ParseProfileReport(profile_dest_dir)
524 result['profile'] = {
525 task_name:duration for task_name, duration in profile.iteritems()
526 if as_utils.IsGradleCompilerTask(task_name, shrinker)}
Christoffer Quist Adamsen1d87ca62019-01-11 12:22:26 +0100527 except Exception as e:
Christoffer Quist Adamsen493acd82019-03-14 12:20:02 +0100528 warn('Failed to build {} with {}'.format(app.name, shrinker))
Christoffer Quist Adamsen1d87ca62019-01-11 12:22:26 +0100529 if e:
530 print('Error: ' + str(e))
Christoffer Quist Adamsen1d0a0fe2018-12-21 14:28:56 +0100531 result['build_status'] = 'failed'
Christoffer Quist Adamsen404aade2018-12-20 13:00:09 +0100532
Christoffer Quist Adamsen4038bbe2019-01-15 14:31:46 +0100533 if result.get('build_status') == 'success':
534 if options.monkey:
Christoffer Quist Adamsen1d0a0fe2018-12-21 14:28:56 +0100535 result['monkey_status'] = 'success' if RunMonkey(
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100536 app, options, apk_dest) else 'failed'
Christoffer Quist Adamsen1d0a0fe2018-12-21 14:28:56 +0100537
Christoffer Quist Adamsen4038bbe2019-01-15 14:31:46 +0100538 if 'r8' in shrinker and options.r8_compilation_steps > 1:
Christoffer Quist Adamsen7cf4c562019-03-07 10:57:33 +0100539 result['recompilation_results'] = \
540 ComputeRecompilationResults(
541 app, repo, options, checkout_dir, temp_dir, shrinker,
542 proguard_config_file)
Christoffer Quist Adamsend0e0a7c2019-01-22 10:00:30 +0100543
Christoffer Quist Adamsen7cf4c562019-03-07 10:57:33 +0100544 if options.run_tests and app.has_instrumentation_tests:
545 result['instrumentation_test_results'] = \
546 ComputeInstrumentationTestResults(
547 app, options, checkout_dir, out_dir, shrinker)
Christoffer Quist Adamsen4038bbe2019-01-15 14:31:46 +0100548
Christoffer Quist Adamsen1d0a0fe2018-12-21 14:28:56 +0100549 result_per_shrinker[shrinker] = result
Christoffer Quist Adamsen3aa8d252018-12-13 14:56:40 +0100550
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100551 if len(options.apps) > 1:
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100552 print('')
553 LogResultsForApp(app, result_per_shrinker, options)
554 print('')
555
Christoffer Quist Adamsen1d0a0fe2018-12-21 14:28:56 +0100556 return result_per_shrinker
Christoffer Quist Adamsen404aade2018-12-20 13:00:09 +0100557
Christoffer Quist Adamsend0e0a7c2019-01-22 10:00:30 +0100558def BuildAppWithShrinker(
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100559 app, repo, shrinker, checkout_dir, out_dir, temp_dir, options,
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100560 keepRuleSynthesisForRecompilation=False):
561 print('Building {} with {}{}'.format(
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100562 app.name,
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100563 shrinker,
564 ' for recompilation' if keepRuleSynthesisForRecompilation else ''))
Christoffer Quist Adamsen3aa8d252018-12-13 14:56:40 +0100565
Morten Krogh-Jespersende566ea2019-02-18 11:59:48 +0100566 # Add settings.gradle file if it is not present to prevent gradle from finding
567 # the settings.gradle file in the r8 root when apps are placed under
568 # $R8/build.
Christoffer Quist Adamsen082351d2019-03-08 13:07:50 +0100569 as_utils.add_settings_gradle(checkout_dir, app.name)
Morten Krogh-Jespersende566ea2019-02-18 11:59:48 +0100570
Christoffer Quist Adamsen2a902752019-02-19 12:33:48 +0100571 # Add 'r8.jar' to top-level build.gradle.
Morten Krogh-Jespersend45d95e2019-02-07 13:27:17 +0100572 as_utils.add_r8_dependency(checkout_dir, temp_dir, IsMinifiedR8(shrinker))
Christoffer Quist Adamsenf8ad4792019-01-09 13:19:19 +0100573
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100574 archives_base_name = app.archives_base_name
Christoffer Quist Adamsen3aa8d252018-12-13 14:56:40 +0100575
Christoffer Quist Adamsend0e0a7c2019-01-22 10:00:30 +0100576 if not os.path.exists(out_dir):
577 os.makedirs(out_dir)
Christoffer Quist Adamsen3aa8d252018-12-13 14:56:40 +0100578
Christoffer Quist Adamsen4038bbe2019-01-15 14:31:46 +0100579 # Set -printconfiguration in Proguard rules.
580 proguard_config_dest = os.path.abspath(
Christoffer Quist Adamsend0e0a7c2019-01-22 10:00:30 +0100581 os.path.join(out_dir, 'proguard-rules.pro'))
Christoffer Quist Adamsen4038bbe2019-01-15 14:31:46 +0100582 as_utils.SetPrintConfigurationDirective(
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100583 app, checkout_dir, proguard_config_dest)
Christoffer Quist Adamsen4038bbe2019-01-15 14:31:46 +0100584
Christoffer Quist Adamsen7cf4c562019-03-07 10:57:33 +0100585 env_vars = {}
586 env_vars['ANDROID_HOME'] = utils.getAndroidHome()
587 env_vars['JAVA_OPTS'] = '-ea:com.android.tools.r8...'
Christoffer Quist Adamsend0e0a7c2019-01-22 10:00:30 +0100588
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100589 releaseTarget = app.releaseTarget
Søren Gjesse8c111482018-12-21 14:47:57 +0100590 if not releaseTarget:
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100591 releaseTarget = app.module.replace('/', ':') + ':' + 'assemble' + (
592 app.flavor.capitalize() if app.flavor else '') + 'Release'
Christoffer Quist Adamsen3aa8d252018-12-13 14:56:40 +0100593
Christoffer Quist Adamsen7cf4c562019-03-07 10:57:33 +0100594 # Build using gradle.
595 args = [releaseTarget,
596 '--profile',
597 '-Pandroid.enableR8=' + str(isR8(shrinker)).lower(),
598 '-Pandroid.enableR8.fullMode=' + str(isR8FullMode(shrinker)).lower()]
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100599 if keepRuleSynthesisForRecompilation:
Christoffer Quist Adamsen7cf4c562019-03-07 10:57:33 +0100600 args.append('-Dcom.android.tools.r8.keepRuleSynthesisForRecompilation=true')
Søren Gjesse9fb48802019-01-18 11:00:00 +0100601 if options.gradle_flags:
Christoffer Quist Adamsen7cf4c562019-03-07 10:57:33 +0100602 args.extend(options.gradle_flags.split(' '))
Christoffer Quist Adamsen1d87ca62019-01-11 12:22:26 +0100603
Morten Krogh-Jespersen7cdd3a72019-03-13 14:58:25 +0100604 stdout = utils.RunGradlew(args, env_vars=env_vars, quiet=options.quiet,
605 logging=not options.golem)
Christoffer Quist Adamsen3aa8d252018-12-13 14:56:40 +0100606
607 apk_base_name = (archives_base_name
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100608 + (('-' + app.flavor) if app.flavor else '') + '-release')
609 signed_apk_name = (
610 app.signed_apk_name
611 if app.signed_apk_name
612 else apk_base_name + '.apk')
Christoffer Quist Adamsen3aa8d252018-12-13 14:56:40 +0100613 unsigned_apk_name = apk_base_name + '-unsigned.apk'
614
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100615 build_dir = app.build_dir
616 build_output_apks = os.path.join(app.module, build_dir, 'outputs', 'apk')
617 if app.flavor:
618 build_output_apks = os.path.join(build_output_apks, app.flavor, 'release')
Christoffer Quist Adamsen3aa8d252018-12-13 14:56:40 +0100619 else:
620 build_output_apks = os.path.join(build_output_apks, 'release')
621
622 signed_apk = os.path.join(build_output_apks, signed_apk_name)
623 unsigned_apk = os.path.join(build_output_apks, unsigned_apk_name)
624
625 if options.sign_apks and not os.path.isfile(signed_apk):
626 assert os.path.isfile(unsigned_apk)
627 if options.sign_apks:
Christoffer Quist Adamsen3aa8d252018-12-13 14:56:40 +0100628 apk_utils.sign_with_apksigner(
Christoffer Quist Adamsen3aa8d252018-12-13 14:56:40 +0100629 unsigned_apk,
630 signed_apk,
Christoffer Quist Adamsen3b6f1062019-02-07 09:49:43 +0100631 options.keystore,
632 options.keystore_password,
633 quiet=options.quiet)
Christoffer Quist Adamsen3aa8d252018-12-13 14:56:40 +0100634
635 if os.path.isfile(signed_apk):
Christoffer Quist Adamsend0e0a7c2019-01-22 10:00:30 +0100636 apk_dest = os.path.join(out_dir, signed_apk_name)
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100637 as_utils.MoveFile(signed_apk, apk_dest, quiet=options.quiet)
Christoffer Quist Adamsen3aa8d252018-12-13 14:56:40 +0100638 else:
Christoffer Quist Adamsend0e0a7c2019-01-22 10:00:30 +0100639 apk_dest = os.path.join(out_dir, unsigned_apk_name)
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100640 as_utils.MoveFile(unsigned_apk, apk_dest, quiet=options.quiet)
Christoffer Quist Adamsen3aa8d252018-12-13 14:56:40 +0100641
Morten Krogh-Jespersen8a3450d2019-03-07 07:29:14 +0000642 assert ('r8' not in shrinker
643 or CheckIsBuiltWithExpectedR8(apk_dest, temp_dir, shrinker, options))
Christoffer Quist Adamsen3aa8d252018-12-13 14:56:40 +0100644
Christoffer Quist Adamsend0e0a7c2019-01-22 10:00:30 +0100645 profile_dest_dir = os.path.join(out_dir, 'profile')
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100646 as_utils.MoveProfileReportTo(profile_dest_dir, stdout, quiet=options.quiet)
Christoffer Quist Adamsen1d87ca62019-01-11 12:22:26 +0100647
Christoffer Quist Adamsen4038bbe2019-01-15 14:31:46 +0100648 return (apk_dest, profile_dest_dir, proguard_config_dest)
649
Christoffer Quist Adamsen7cf4c562019-03-07 10:57:33 +0100650def ComputeInstrumentationTestResults(
651 app, options, checkout_dir, out_dir, shrinker):
652 args = ['connectedAndroidTest',
653 '-Pandroid.enableR8=' + str(isR8(shrinker)).lower(),
654 '-Pandroid.enableR8.fullMode=' + str(isR8FullMode(shrinker)).lower()]
655 env_vars = { 'ANDROID_SERIAL': options.emulator_id }
656 stdout = \
Morten Krogh-Jespersen7cdd3a72019-03-13 14:58:25 +0100657 utils.RunGradlew(args, env_vars=env_vars, quiet=options.quiet,
658 fail=False, logging=not options.golem)
Christoffer Quist Adamsen7cf4c562019-03-07 10:57:33 +0100659
660 xml_test_result_dest = os.path.join(out_dir, 'test_result')
661 as_utils.MoveXMLTestResultFileTo(
662 xml_test_result_dest, stdout, quiet=options.quiet)
663
664 with open(xml_test_result_dest, 'r') as f:
665 xml_test_result_contents = f.read()
666
667 xml_document = minidom.parseString(xml_test_result_contents)
668 testsuite_element = xml_document.documentElement
669
670 return {
671 'xml_test_result_dest': xml_test_result_dest,
672 'tests': int(testsuite_element.getAttribute('tests')),
673 'failures': int(testsuite_element.getAttribute('failures')),
674 'errors': int(testsuite_element.getAttribute('errors')),
675 'skipped': int(testsuite_element.getAttribute('skipped'))
676 }
677
678def ComputeRecompilationResults(
679 app, repo, options, checkout_dir, temp_dir, shrinker, proguard_config_file):
680 recompilation_results = []
681
682 # Build app with gradle using -D...keepRuleSynthesisForRecompilation=
683 # true.
684 out_dir = os.path.join(checkout_dir, 'out', shrinker + '-1')
685 (apk_dest, profile_dest_dir, ext_proguard_config_file) = \
686 BuildAppWithShrinker(
687 app, repo, shrinker, checkout_dir, out_dir,
688 temp_dir, options, keepRuleSynthesisForRecompilation=True)
689 dex_size = ComputeSizeOfDexFilesInApk(apk_dest)
690 recompilation_result = {
691 'apk_dest': apk_dest,
692 'build_status': 'success',
693 'dex_size': ComputeSizeOfDexFilesInApk(apk_dest),
694 'monkey_status': 'skipped'
695 }
696 recompilation_results.append(recompilation_result)
697
698 # Sanity check that keep rules have changed.
699 with open(ext_proguard_config_file) as new:
700 with open(proguard_config_file) as old:
701 assert(
702 sum(1 for line in new
703 if line.strip() and '-printconfiguration' not in line)
704 >
705 sum(1 for line in old
706 if line.strip() and '-printconfiguration' not in line))
707
708 # Extract min-sdk and target-sdk
709 (min_sdk, compile_sdk) = \
710 as_utils.GetMinAndCompileSdk(app, checkout_dir, apk_dest)
711
712 # Now rebuild generated apk.
713 previous_apk = apk_dest
714
715 # We may need main dex rules when re-compiling with R8 as standalone.
716 main_dex_rules = None
717 if app.main_dex_rules:
718 main_dex_rules = os.path.join(checkout_dir, app.main_dex_rules)
719
720 for i in range(1, options.r8_compilation_steps):
721 try:
722 recompiled_apk_dest = os.path.join(
723 checkout_dir, 'out', shrinker, 'app-release-{}.apk'.format(i))
724 RebuildAppWithShrinker(
725 app, previous_apk, recompiled_apk_dest,
726 ext_proguard_config_file, shrinker, min_sdk, compile_sdk,
727 options, temp_dir, main_dex_rules)
728 recompilation_result = {
729 'apk_dest': recompiled_apk_dest,
730 'build_status': 'success',
731 'dex_size': ComputeSizeOfDexFilesInApk(recompiled_apk_dest)
732 }
733 if options.monkey:
734 recompilation_result['monkey_status'] = 'success' if RunMonkey(
735 app, options, recompiled_apk_dest) else 'failed'
736 recompilation_results.append(recompilation_result)
737 previous_apk = recompiled_apk_dest
738 except Exception as e:
739 warn('Failed to recompile {} with {}'.format(
740 app.name, shrinker))
741 recompilation_results.append({ 'build_status': 'failed' })
742 break
743 return recompilation_results
744
Christoffer Quist Adamsene59840b2019-01-22 15:25:15 +0100745def RebuildAppWithShrinker(
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100746 app, apk, apk_dest, proguard_config_file, shrinker, min_sdk, compile_sdk,
Morten Krogh-Jespersen03627262019-02-18 14:30:22 +0100747 options, temp_dir, main_dex_rules):
Christoffer Quist Adamsen4038bbe2019-01-15 14:31:46 +0100748 assert 'r8' in shrinker
749 assert apk_dest.endswith('.apk')
Søren Gjesse9fb48802019-01-18 11:00:00 +0100750
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100751 print('Rebuilding {} with {}'.format(app.name, shrinker))
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100752
Christoffer Quist Adamsen4038bbe2019-01-15 14:31:46 +0100753 # Compile given APK with shrinker to temporary zip file.
Christoffer Quist Adamsen17879c12019-01-22 16:13:54 +0100754 android_jar = utils.get_android_jar(compile_sdk)
Morten Krogh-Jespersend45d95e2019-02-07 13:27:17 +0100755 r8_jar = os.path.join(
756 temp_dir, 'r8lib.jar' if IsMinifiedR8(shrinker) else 'r8.jar')
Christoffer Quist Adamsend0e0a7c2019-01-22 10:00:30 +0100757 zip_dest = apk_dest[:-4] + '.zip'
Christoffer Quist Adamsen4038bbe2019-01-15 14:31:46 +0100758
Christoffer Quist Adamsene59840b2019-01-22 15:25:15 +0100759 # TODO(christofferqa): Entry point should be CompatProguard if the shrinker
760 # is 'r8'.
761 entry_point = 'com.android.tools.r8.R8'
762
Christoffer Quist Adamsenbe2593f2019-02-19 13:01:56 +0100763 cmd = [jdk.GetJavaExecutable(), '-ea:com.android.tools.r8...', '-cp', r8_jar,
764 entry_point, '--release', '--min-api', str(min_sdk), '--pg-conf',
765 proguard_config_file, '--lib', android_jar, '--output', zip_dest, apk]
Christoffer Quist Adamsen17879c12019-01-22 16:13:54 +0100766
767 for android_optional_jar in utils.get_android_optional_jars(compile_sdk):
768 cmd.append('--lib')
769 cmd.append(android_optional_jar)
770
Morten Krogh-Jespersen03627262019-02-18 14:30:22 +0100771 if main_dex_rules:
772 cmd.append('--main-dex-rules')
773 cmd.append(main_dex_rules)
774
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100775 utils.RunCmd(cmd, quiet=options.quiet)
Christoffer Quist Adamsen4038bbe2019-01-15 14:31:46 +0100776
777 # Make a copy of the given APK, move the newly generated dex files into the
778 # copied APK, and then sign the APK.
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100779 apk_masseur.masseur(
Christoffer Quist Adamsen2dcea102019-02-20 11:31:38 +0100780 apk, dex=zip_dest, resources='META-INF/services/*', out=apk_dest,
781 quiet=options.quiet)
Christoffer Quist Adamsen404aade2018-12-20 13:00:09 +0100782
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100783def RunMonkey(app, options, apk_dest):
Christoffer Quist Adamsen7cf4c562019-03-07 10:57:33 +0100784 if not WaitForEmulator(options):
Christoffer Quist Adamsenbae36612019-01-15 12:23:51 +0100785 return False
786
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100787 UninstallApkOnEmulator(app, options)
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100788 InstallApkOnEmulator(apk_dest, options)
Christoffer Quist Adamsen1d0a0fe2018-12-21 14:28:56 +0100789
Christoffer Quist Adamsenbae36612019-01-15 12:23:51 +0100790 number_of_events_to_generate = options.monkey_events
Christoffer Quist Adamsen1d0a0fe2018-12-21 14:28:56 +0100791
Christoffer Quist Adamsenbae36612019-01-15 12:23:51 +0100792 # Intentionally using a constant seed such that the monkey generates the same
793 # event sequence for each shrinker.
794 random_seed = 42
795
Christoffer Quist Adamsen7cf4c562019-03-07 10:57:33 +0100796 cmd = ['adb', '-s', options.emulator_id, 'shell', 'monkey', '-p', app.id,
797 '-s', str(random_seed), str(number_of_events_to_generate)]
Christoffer Quist Adamsen88b7ebe2019-01-14 11:22:17 +0100798
799 try:
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100800 stdout = utils.RunCmd(cmd, quiet=options.quiet)
Christoffer Quist Adamsend0e0a7c2019-01-22 10:00:30 +0100801 succeeded = (
802 'Events injected: {}'.format(number_of_events_to_generate) in stdout)
Christoffer Quist Adamsen88b7ebe2019-01-14 11:22:17 +0100803 except subprocess.CalledProcessError as e:
Christoffer Quist Adamsend0e0a7c2019-01-22 10:00:30 +0100804 succeeded = False
Christoffer Quist Adamsen88b7ebe2019-01-14 11:22:17 +0100805
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100806 UninstallApkOnEmulator(app, options)
Christoffer Quist Adamsen1d0a0fe2018-12-21 14:28:56 +0100807
Christoffer Quist Adamsend0e0a7c2019-01-22 10:00:30 +0100808 return succeeded
809
810def LogResultsForApps(result_per_shrinker_per_app, options):
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100811 print('')
Christoffer Quist Adamsen7cf4c562019-03-07 10:57:33 +0100812 for (app, result_per_shrinker) in result_per_shrinker_per_app:
Christoffer Quist Adamsend0e0a7c2019-01-22 10:00:30 +0100813 LogResultsForApp(app, result_per_shrinker, options)
Christoffer Quist Adamsen724bfb02019-01-10 09:54:38 +0100814
Christoffer Quist Adamsend0e0a7c2019-01-22 10:00:30 +0100815def LogResultsForApp(app, result_per_shrinker, options):
Morten Krogh-Jespersenaeb665e2019-02-07 12:29:03 +0100816 if options.print_dexsegments:
817 LogSegmentsForApp(app, result_per_shrinker, options)
818 else:
819 LogComparisonResultsForApp(app, result_per_shrinker, options)
820
821def LogSegmentsForApp(app, result_per_shrinker, options):
822 for shrinker in SHRINKERS:
823 if shrinker not in result_per_shrinker:
824 continue
825 result = result_per_shrinker[shrinker];
Christoffer Quist Adamsen7cf4c562019-03-07 10:57:33 +0100826 benchmark_name = '{}-{}'.format(options.print_dexsegments, app.name)
Morten Krogh-Jespersenaeb665e2019-02-07 12:29:03 +0100827 utils.print_dexsegments(benchmark_name, [result.get('apk_dest')])
828 duration = sum(result.get('profile').values())
829 print('%s-Total(RunTimeRaw): %s ms' % (benchmark_name, duration * 1000))
830 print('%s-Total(CodeSize): %s' % (benchmark_name, result.get('dex_size')))
831
832
833def LogComparisonResultsForApp(app, result_per_shrinker, options):
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100834 print(app.name + ':')
Christoffer Quist Adamsend0e0a7c2019-01-22 10:00:30 +0100835
Christoffer Quist Adamsen1de3dde2019-01-24 13:17:46 +0100836 if result_per_shrinker.get('status', 'success') != 'success':
Christoffer Quist Adamsend0e0a7c2019-01-22 10:00:30 +0100837 error_message = result_per_shrinker.get('error_message')
838 print(' skipped ({})'.format(error_message))
839 return
840
Morten Krogh-Jespersenaeb665e2019-02-07 12:29:03 +0100841 proguard_result = result_per_shrinker.get('pg', {})
Christoffer Quist Adamsend0e0a7c2019-01-22 10:00:30 +0100842 proguard_dex_size = float(proguard_result.get('dex_size', -1))
843 proguard_duration = sum(proguard_result.get('profile', {}).values())
844
845 for shrinker in SHRINKERS:
846 if shrinker not in result_per_shrinker:
Christoffer Quist Adamsen724bfb02019-01-10 09:54:38 +0100847 continue
Christoffer Quist Adamsend0e0a7c2019-01-22 10:00:30 +0100848 result = result_per_shrinker.get(shrinker)
849 build_status = result.get('build_status')
850 if build_status != 'success':
851 warn(' {}: {}'.format(shrinker, build_status))
852 else:
853 print(' {}:'.format(shrinker))
854 dex_size = result.get('dex_size')
855 msg = ' dex size: {}'.format(dex_size)
856 if dex_size != proguard_dex_size and proguard_dex_size >= 0:
857 msg = '{} ({}, {})'.format(
858 msg, dex_size - proguard_dex_size,
859 PercentageDiffAsString(proguard_dex_size, dex_size))
860 success(msg) if dex_size < proguard_dex_size else warn(msg)
Christoffer Quist Adamsen404aade2018-12-20 13:00:09 +0100861 else:
Christoffer Quist Adamsend0e0a7c2019-01-22 10:00:30 +0100862 print(msg)
Christoffer Quist Adamsen81321b62019-01-15 14:39:53 +0100863
Christoffer Quist Adamsend0e0a7c2019-01-22 10:00:30 +0100864 profile = result.get('profile')
865 duration = sum(profile.values())
866 msg = ' performance: {}s'.format(duration)
867 if duration != proguard_duration and proguard_duration > 0:
868 msg = '{} ({}s, {})'.format(
869 msg, duration - proguard_duration,
870 PercentageDiffAsString(proguard_duration, duration))
871 success(msg) if duration < proguard_duration else warn(msg)
872 else:
873 print(msg)
874 if len(profile) >= 2:
875 for task_name, task_duration in profile.iteritems():
876 print(' {}: {}s'.format(task_name, task_duration))
Christoffer Quist Adamsen81321b62019-01-15 14:39:53 +0100877
Christoffer Quist Adamsend0e0a7c2019-01-22 10:00:30 +0100878 if options.monkey:
879 monkey_status = result.get('monkey_status')
880 if monkey_status != 'success':
881 warn(' monkey: {}'.format(monkey_status))
882 else:
883 success(' monkey: {}'.format(monkey_status))
Christoffer Quist Adamsen7cf4c562019-03-07 10:57:33 +0100884
Christoffer Quist Adamsend0e0a7c2019-01-22 10:00:30 +0100885 recompilation_results = result.get('recompilation_results', [])
886 i = 0
887 for recompilation_result in recompilation_results:
888 build_status = recompilation_result.get('build_status')
889 if build_status != 'success':
890 print(' recompilation #{}: {}'.format(i, build_status))
891 else:
892 dex_size = recompilation_result.get('dex_size')
893 print(' recompilation #{}'.format(i))
894 print(' dex size: {}'.format(dex_size))
895 if options.monkey:
896 monkey_status = recompilation_result.get('monkey_status')
897 msg = ' monkey: {}'.format(monkey_status)
898 if monkey_status == 'success':
899 success(msg)
900 elif monkey_status == 'skipped':
901 print(msg)
902 else:
903 warn(msg)
904 i += 1
Christoffer Quist Adamsen404aade2018-12-20 13:00:09 +0100905
Christoffer Quist Adamsen7cf4c562019-03-07 10:57:33 +0100906 if options.run_tests and 'instrumentation_test_results' in result:
907 instrumentation_test_results = \
908 result.get('instrumentation_test_results')
909 succeeded = (
910 instrumentation_test_results.get('failures')
911 + instrumentation_test_results.get('errors')
912 + instrumentation_test_results.get('skipped')) == 0
913 if succeeded:
914 success(' tests: succeeded')
915 else:
916 warn(
917 ' tests: failed (failures: {}, errors: {}, skipped: {})'
918 .format(
919 instrumentation_test_results.get('failures'),
920 instrumentation_test_results.get('errors'),
921 instrumentation_test_results.get('skipped')))
922
Søren Gjessecdae8792018-12-12 09:02:43 +0100923def ParseOptions(argv):
924 result = optparse.OptionParser()
925 result.add_option('--app',
926 help='What app to run on',
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100927 choices=GetAllAppNames())
Morten Krogh-Jespersen64740202019-02-07 13:06:04 +0100928 result.add_option('--download-only', '--download_only',
929 help='Whether to download apps without any compilation',
930 default=False,
931 action='store_true')
Christoffer Quist Adamsen7cf4c562019-03-07 10:57:33 +0100932 result.add_option('--emulator-id', '--emulator_id',
933 help='Id of the emulator to use',
934 default='emulator-5554')
Morten Krogh-Jespersen64740202019-02-07 13:06:04 +0100935 result.add_option('--golem',
936 help='Running on golem, do not download',
937 default=False,
938 action='store_true')
Morten Krogh-Jespersend35065e2019-02-07 10:28:52 +0100939 result.add_option('--gradle-flags', '--gradle_flags',
940 help='Flags to pass in to gradle')
Morten Krogh-Jespersene0ce6a32019-02-07 11:44:45 +0100941 result.add_option('--ignore-versions', '--ignore_versions',
942 help='Allow checked-out app to differ in revision from '
943 'pinned',
944 default=False,
945 action='store_true')
Christoffer Quist Adamsen3b6f1062019-02-07 09:49:43 +0100946 result.add_option('--keystore',
947 help='Path to app.keystore',
948 default='app.keystore')
949 result.add_option('--keystore-password', '--keystore_password',
950 help='Password for app.keystore',
951 default='android')
Christoffer Quist Adamsen1d0a0fe2018-12-21 14:28:56 +0100952 result.add_option('--monkey',
953 help='Whether to install and run app(s) with monkey',
954 default=False,
955 action='store_true')
Christoffer Quist Adamsenbae36612019-01-15 12:23:51 +0100956 result.add_option('--monkey_events',
957 help='Number of events that the monkey should trigger',
958 default=250,
959 type=int)
Morten Krogh-Jespersend35065e2019-02-07 10:28:52 +0100960 result.add_option('--no-build', '--no_build',
961 help='Run without building ToT first (only when using ToT)',
962 default=False,
963 action='store_true')
Morten Krogh-Jespersend35065e2019-02-07 10:28:52 +0100964 result.add_option('--quiet',
965 help='Disable verbose logging',
966 default=False,
967 action='store_true')
Morten Krogh-Jespersenaeb665e2019-02-07 12:29:03 +0100968 result.add_option('--print-dexsegments',
969 metavar='BENCHMARKNAME',
970 help='Print the sizes of individual dex segments as ' +
971 '\'<BENCHMARKNAME>-<APP>-<segment>(CodeSize): '
972 '<bytes>\'')
Morten Krogh-Jespersend35065e2019-02-07 10:28:52 +0100973 result.add_option('--r8-compilation-steps', '--r8_compilation_steps',
974 help='Number of times R8 should be run on each app',
975 default=2,
976 type=int)
Christoffer Quist Adamsen7cf4c562019-03-07 10:57:33 +0100977 result.add_option('--run-tests', '--run_tests',
978 help='Whether to run instrumentation tests',
979 default=False,
980 action='store_true')
Søren Gjesseeed839d2019-01-11 15:19:16 +0100981 result.add_option('--sign-apks', '--sign_apks',
Christoffer Quist Adamsen10b7db82018-12-13 14:50:38 +0100982 help='Whether the APKs should be signed',
983 default=False,
984 action='store_true')
985 result.add_option('--shrinker',
Christoffer Quist Adamsen860fa932019-01-10 14:27:39 +0100986 help='The shrinkers to use (by default, all are run)',
987 action='append')
Christoffer Quist Adamsen2a902752019-02-19 12:33:48 +0100988 result.add_option('--version',
989 help='The version of R8 to use (e.g., 1.4.51)')
Christoffer Quist Adamsen860fa932019-01-10 14:27:39 +0100990 (options, args) = result.parse_args(argv)
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +0100991 if options.app:
992 options.apps = [GetAppWithName(options.app)]
993 del options.app
994 else:
995 options.apps = GetAllApps()
Christoffer Quist Adamsen860fa932019-01-10 14:27:39 +0100996 if options.shrinker:
997 for shrinker in options.shrinker:
998 assert shrinker in SHRINKERS
Christoffer Quist Adamsen2a902752019-02-19 12:33:48 +0100999 else:
1000 options.shrinker = [shrinker for shrinker in SHRINKERS]
1001 if options.version:
1002 # No need to build R8 if a specific release version should be used.
1003 options.no_build = True
1004 if 'r8-nolib' in options.shrinker:
1005 warn('Skipping shrinker r8-nolib because a specific release version '
1006 + 'of r8 was specified')
1007 options.shrinker.remove('r8-nolib')
1008 if 'r8-nolib-full' in options.shrinker:
1009 warn('Skipping shrinker r8-nolib-full because a specific release version '
1010 + 'of r8 was specified')
1011 options.shrinker.remove('r8-nolib-full')
Christoffer Quist Adamsen860fa932019-01-10 14:27:39 +01001012 return (options, args)
Søren Gjessecdae8792018-12-12 09:02:43 +01001013
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +01001014def clone_repositories(quiet):
1015 # Clone repositories into WORKING_DIR.
Morten Krogh-Jespersen64740202019-02-07 13:06:04 +01001016 with utils.ChangedWorkingDirectory(WORKING_DIR):
Christoffer Quist Adamsene57b73c2019-03-07 15:13:03 +01001017 for repo in APP_REPOSITORIES:
1018 repo_dir = os.path.join(WORKING_DIR, repo.name)
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +01001019 if not os.path.exists(repo_dir):
1020 GitClone(repo, repo_dir, quiet)
Morten Krogh-Jespersen64740202019-02-07 13:06:04 +01001021
1022
Søren Gjessecdae8792018-12-12 09:02:43 +01001023def main(argv):
1024 (options, args) = ParseOptions(argv)
Christoffer Quist Adamsenf8ad4792019-01-09 13:19:19 +01001025
Morten Krogh-Jespersen64740202019-02-07 13:06:04 +01001026 if options.golem:
Morten Krogh-Jespersenc2fbde22019-02-07 13:59:55 +01001027 golem.link_third_party()
Morten Krogh-Jespersen64740202019-02-07 13:06:04 +01001028 if os.path.exists(WORKING_DIR):
1029 shutil.rmtree(WORKING_DIR)
1030 shutil.copytree(utils.OPENSOURCE_APPS_FOLDER, WORKING_DIR)
Morten Krogh-Jespersen220e5702019-02-27 12:57:01 +01001031 os.environ[utils.ANDROID_HOME_ENVIROMENT_NAME] = os.path.join(
1032 utils.ANDROID_SDK)
1033 os.environ[utils.ANDROID_TOOLS_VERSION_ENVIRONMENT_NAME] = '28.0.3'
Morten Krogh-Jespersen64740202019-02-07 13:06:04 +01001034
1035 if not os.path.exists(WORKING_DIR):
1036 os.makedirs(WORKING_DIR)
1037
1038 if options.download_only:
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +01001039 clone_repositories(options.quiet)
Morten Krogh-Jespersen64740202019-02-07 13:06:04 +01001040 return
1041
Christoffer Quist Adamsenbbe5d7d2019-01-23 13:15:21 +01001042 with utils.TempDir() as temp_dir:
Morten Krogh-Jespersen2bd5ec82019-02-25 16:01:23 +01001043 if not (options.no_build or options.golem):
Morten Krogh-Jespersend45d95e2019-02-07 13:27:17 +01001044 gradle.RunGradle(['r8', 'r8lib'])
Søren Gjessecdae8792018-12-12 09:02:43 +01001045
Christoffer Quist Adamsen2a902752019-02-19 12:33:48 +01001046 if options.version:
1047 # Download r8-<version>.jar from
1048 # http://storage.googleapis.com/r8-releases/raw/.
1049 target = 'r8-{}.jar'.format(options.version)
1050 update_prebuilds_in_android.download_version(
1051 temp_dir, 'com/android/tools/r8/' + options.version, target)
1052 as_utils.MoveFile(
1053 os.path.join(temp_dir, target), os.path.join(temp_dir, 'r8lib.jar'),
1054 quiet=options.quiet)
1055 else:
1056 # Make a copy of r8.jar and r8lib.jar such that they stay the same for
1057 # the entire execution of this script.
1058 if 'r8-nolib' in options.shrinker:
1059 assert os.path.isfile(utils.R8_JAR), 'Cannot build without r8.jar'
1060 shutil.copyfile(utils.R8_JAR, os.path.join(temp_dir, 'r8.jar'))
1061 if 'r8' in options.shrinker:
1062 assert os.path.isfile(utils.R8LIB_JAR), 'Cannot build without r8lib.jar'
1063 shutil.copyfile(utils.R8LIB_JAR, os.path.join(temp_dir, 'r8lib.jar'))
Christoffer Quist Adamsen404aade2018-12-20 13:00:09 +01001064
Christoffer Quist Adamsen7cf4c562019-03-07 10:57:33 +01001065 result_per_shrinker_per_app = []
Christoffer Quist Adamsen404aade2018-12-20 13:00:09 +01001066
Christoffer Quist Adamsenb899c112019-03-06 15:25:00 +01001067 for (app, repo) in options.apps:
1068 if app.skip:
1069 continue
Christoffer Quist Adamsen7cf4c562019-03-07 10:57:33 +01001070 result_per_shrinker_per_app.append(
1071 (app, GetResultsForApp(app, repo, options, temp_dir)))
Christoffer Quist Adamsenbbe5d7d2019-01-23 13:15:21 +01001072
1073 LogResultsForApps(result_per_shrinker_per_app, options)
Christoffer Quist Adamsen404aade2018-12-20 13:00:09 +01001074
1075def success(message):
1076 CGREEN = '\033[32m'
1077 CEND = '\033[0m'
1078 print(CGREEN + message + CEND)
1079
1080def warn(message):
1081 CRED = '\033[91m'
1082 CEND = '\033[0m'
1083 print(CRED + message + CEND)
Søren Gjessecdae8792018-12-12 09:02:43 +01001084
1085if __name__ == '__main__':
1086 sys.exit(main(sys.argv[1:]))