blob: 0c2df6e5a28f032f86833219982738f4deada7d7 [file] [log] [blame]
Colin Cross43f08db2018-11-12 10:13:39 -08001// Copyright 2018 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15// The dexpreopt package converts a global dexpreopt config and a module dexpreopt config into rules to perform
16// dexpreopting and to strip the dex files from the APK or JAR.
17//
18// It is used in two places; in the dexpeopt_gen binary for modules defined in Make, and directly linked into Soong.
19//
20// For Make modules it is built into the dexpreopt_gen binary, which is executed as a Make rule using global config and
21// module config specified in JSON files. The binary writes out two shell scripts, only updating them if they have
22// changed. One script takes an APK or JAR as an input and produces a zip file containing any outputs of preopting,
23// in the location they should be on the device. The Make build rules will unzip the zip file into $(PRODUCT_OUT) when
24// installing the APK, which will install the preopt outputs into $(PRODUCT_OUT)/system or $(PRODUCT_OUT)/system_other
25// as necessary. The zip file may be empty if preopting was disabled for any reason. The second script takes an APK or
26// JAR as an input and strips the dex files in it as necessary.
27//
28// The intermediate shell scripts allow changes to this package or to the global config to regenerate the shell scripts
29// but only require re-executing preopting if the script has changed.
30//
31// For Soong modules this package is linked directly into Soong and run from the java package. It generates the same
32// commands as for make, using athe same global config JSON file used by make, but using a module config structure
33// provided by Soong. The generated commands are then converted into Soong rule and written directly to the ninja file,
34// with no extra shell scripts involved.
35package dexpreopt
36
37import (
38 "fmt"
39 "path/filepath"
40 "strings"
41
42 "github.com/google/blueprint/pathtools"
43)
44
45const SystemPartition = "/system/"
46const SystemOtherPartition = "/system_other/"
47
48// GenerateStripRule generates a set of commands that will take an APK or JAR as an input and strip the dex files if
49// they are no longer necessary after preopting.
50func GenerateStripRule(global GlobalConfig, module ModuleConfig) (rule *Rule, err error) {
51 defer func() {
52 if r := recover(); r != nil {
53 if e, ok := r.(error); ok {
54 err = e
55 rule = nil
56 } else {
57 panic(r)
58 }
59 }
60 }()
61
62 tools := global.Tools
63
64 rule = &Rule{}
65
66 strip := shouldStripDex(module, global)
67
68 if strip {
69 // Only strips if the dex files are not already uncompressed
70 rule.Command().
71 Textf(`if (zipinfo %s '*.dex' 2>/dev/null | grep -v ' stor ' >/dev/null) ; then`, module.StripInputPath).
72 Tool(tools.Zip2zip).FlagWithInput("-i ", module.StripInputPath).FlagWithOutput("-o ", module.StripOutputPath).
73 FlagWithArg("-x ", `"classes*.dex"`).
74 Textf(`; else cp -f %s %s; fi`, module.StripInputPath, module.StripOutputPath)
75 } else {
76 rule.Command().Text("cp -f").Input(module.StripInputPath).Output(module.StripOutputPath)
77 }
78
79 return rule, nil
80}
81
82// GenerateDexpreoptRule generates a set of commands that will preopt a module based on a GlobalConfig and a
83// ModuleConfig. The produced files and their install locations will be available through rule.Installs().
84func GenerateDexpreoptRule(global GlobalConfig, module ModuleConfig) (rule *Rule, err error) {
85 defer func() {
86 if r := recover(); r != nil {
87 if e, ok := r.(error); ok {
88 err = e
89 rule = nil
90 } else {
91 panic(r)
92 }
93 }
94 }()
95
96 rule = &Rule{}
97
98 dexpreoptDisabled := contains(global.DisablePreoptModules, module.Name)
99
100 if contains(global.BootJars, module.Name) {
101 // Don't preopt individual boot jars, they will be preopted together
102 dexpreoptDisabled = true
103 }
104
105 // If OnlyPreoptBootImageAndSystemServer=true and module is not in boot class path skip
106 // Also preopt system server jars since selinux prevents system server from loading anything from
107 // /data. If we don't do this they will need to be extracted which is not favorable for RAM usage
108 // or performance. If PreoptExtractedApk is true, we ignore the only preopt boot image options.
109 if global.OnlyPreoptBootImageAndSystemServer && !contains(global.BootJars, module.Name) &&
110 !contains(global.SystemServerJars, module.Name) && !module.PreoptExtractedApk {
111 dexpreoptDisabled = true
112 }
113
114 generateProfile := module.ProfileClassListing != "" && !global.DisableGenerateProfile
115
116 var profile string
117 if generateProfile {
118 profile = profileCommand(global, module, rule)
119 }
120
121 if !dexpreoptDisabled {
122 appImage := (generateProfile || module.ForceCreateAppImage || global.DefaultAppImages) &&
123 !module.NoCreateAppImage
124
125 generateDM := shouldGenerateDM(module, global)
126
127 for _, arch := range module.Archs {
128 imageLocation := module.DexPreoptImageLocation
129 if imageLocation == "" {
130 imageLocation = global.DefaultDexPreoptImageLocation[arch]
131 }
132 dexpreoptCommand(global, module, rule, profile, arch, imageLocation, appImage, generateDM)
133 }
134 }
135
136 return rule, nil
137}
138
139func profileCommand(global GlobalConfig, module ModuleConfig, rule *Rule) string {
140 profilePath := filepath.Join(filepath.Dir(module.BuildPath), "profile.prof")
141 profileInstalledPath := module.DexLocation + ".prof"
142
143 if !module.ProfileIsTextListing {
144 rule.Command().FlagWithOutput("touch ", profilePath)
145 }
146
147 cmd := rule.Command().
148 Text(`ANDROID_LOG_TAGS="*:e"`).
149 Tool(global.Tools.Profman)
150
151 if module.ProfileIsTextListing {
152 // The profile is a test listing of classes (used for framework jars).
153 // We need to generate the actual binary profile before being able to compile.
154 cmd.FlagWithInput("--create-profile-from=", module.ProfileClassListing)
155 } else {
156 // The profile is binary profile (used for apps). Run it through profman to
157 // ensure the profile keys match the apk.
158 cmd.
159 Flag("--copy-and-update-profile-key").
160 FlagWithInput("--profile-file=", module.ProfileClassListing)
161 }
162
163 cmd.
164 FlagWithInput("--apk=", module.DexPath).
165 Flag("--dex-location="+module.DexLocation).
166 FlagWithOutput("--reference-profile-file=", profilePath)
167
168 if !module.ProfileIsTextListing {
169 cmd.Text(fmt.Sprintf(`|| echo "Profile out of date for %s"`, module.DexPath))
170 }
171 rule.Install(profilePath, profileInstalledPath)
172
173 return profilePath
174}
175
176func dexpreoptCommand(global GlobalConfig, module ModuleConfig, rule *Rule, profile, arch, bootImageLocation string,
177 appImage, generateDM bool) {
178
179 // HACK: make soname in Soong-generated .odex files match Make.
180 base := filepath.Base(module.DexLocation)
181 if filepath.Ext(base) == ".jar" {
182 base = "javalib.jar"
183 } else if filepath.Ext(base) == ".apk" {
184 base = "package.apk"
185 }
186
187 toOdexPath := func(path string) string {
188 return filepath.Join(
189 filepath.Dir(path),
190 "oat",
191 arch,
192 pathtools.ReplaceExtension(filepath.Base(path), "odex"))
193 }
194
195 odexPath := toOdexPath(filepath.Join(filepath.Dir(module.BuildPath), base))
196 odexInstallPath := toOdexPath(module.DexLocation)
197 if odexOnSystemOther(module, global) {
198 odexInstallPath = strings.Replace(odexInstallPath, SystemPartition, SystemOtherPartition, 1)
199 }
200
201 vdexPath := pathtools.ReplaceExtension(odexPath, "vdex")
202 vdexInstallPath := pathtools.ReplaceExtension(odexInstallPath, "vdex")
203
204 // bootImageLocation is $OUT/dex_bootjars/system/framework/boot.art, but dex2oat actually reads
205 // $OUT/dex_bootjars/system/framework/arm64/boot.art
206 var bootImagePath string
207 if bootImageLocation != "" {
208 bootImagePath = filepath.Join(filepath.Dir(bootImageLocation), arch, filepath.Base(bootImageLocation))
209 }
210
211 // Lists of used and optional libraries from the build config to be verified against the manifest in the APK
212 var verifyUsesLibs []string
213 var verifyOptionalUsesLibs []string
214
215 // Lists of used and optional libraries from the build config, with optional libraries that are known to not
216 // be present in the current product removed.
217 var filteredUsesLibs []string
218 var filteredOptionalUsesLibs []string
219
220 // The class loader context using paths in the build
221 var classLoaderContextHost []string
222
223 // The class loader context using paths as they will be on the device
224 var classLoaderContextTarget []string
225
226 // Extra paths that will be appended to the class loader if the APK manifest has targetSdkVersion < 28
227 var conditionalClassLoaderContextHost []string
228 var conditionalClassLoaderContextTarget []string
229
230 if module.EnforceUsesLibraries {
231 verifyUsesLibs = copyOf(module.UsesLibraries)
232 verifyOptionalUsesLibs = copyOf(module.OptionalUsesLibraries)
233
234 filteredOptionalUsesLibs = filterOut(global.MissingUsesLibraries, module.OptionalUsesLibraries)
235 filteredUsesLibs = append(copyOf(module.UsesLibraries), filteredOptionalUsesLibs...)
236
237 // Create class loader context for dex2oat from uses libraries and filtered optional libraries
238 for _, l := range filteredUsesLibs {
239
240 classLoaderContextHost = append(classLoaderContextHost,
241 pathForLibrary(module, l))
242 classLoaderContextTarget = append(classLoaderContextTarget,
243 filepath.Join("/system/framework", l+".jar"))
244 }
245
246 const httpLegacy = "org.apache.http.legacy"
247 const httpLegacyImpl = "org.apache.http.legacy.impl"
248
249 // Fix up org.apache.http.legacy.impl since it should be org.apache.http.legacy in the manifest.
250 replace(verifyUsesLibs, httpLegacyImpl, httpLegacy)
251 replace(verifyOptionalUsesLibs, httpLegacyImpl, httpLegacy)
252
253 if !contains(verifyUsesLibs, httpLegacy) && !contains(verifyOptionalUsesLibs, httpLegacy) {
254 conditionalClassLoaderContextHost = append(conditionalClassLoaderContextHost,
255 pathForLibrary(module, httpLegacyImpl))
256 conditionalClassLoaderContextTarget = append(conditionalClassLoaderContextTarget,
257 filepath.Join("/system/framework", httpLegacyImpl+".jar"))
258 }
259 } else {
260 // Pass special class loader context to skip the classpath and collision check.
261 // This will get removed once LOCAL_USES_LIBRARIES is enforced.
262 // Right now LOCAL_USES_LIBRARIES is opt in, for the case where it's not specified we still default
263 // to the &.
264 classLoaderContextHost = []string{`\&`}
265 }
266
267 rule.Command().FlagWithArg("mkdir -p ", filepath.Dir(odexPath))
268 rule.Command().FlagWithOutput("rm -f ", odexPath)
269 // Set values in the environment of the rule. These may be modified by construct_context.sh.
270 rule.Command().FlagWithArg("class_loader_context_arg=--class-loader-context=",
271 strings.Join(classLoaderContextHost, ":"))
272 rule.Command().Text(`stored_class_loader_context_arg=""`)
273
274 if module.EnforceUsesLibraries {
275 rule.Command().FlagWithList("stored_class_loader_context_libs=", classLoaderContextTarget, ":")
276 rule.Command().FlagWithInputList("class_loader_context=", classLoaderContextHost, ":")
277 rule.Command().Textf(`uses_library_names="%s"`, strings.Join(verifyUsesLibs, " "))
278 rule.Command().Textf(`optional_uses_library_names="%s"`, strings.Join(verifyOptionalUsesLibs, " "))
279 rule.Command().Textf(`aapt_binary="%s"`, global.Tools.Aapt)
280 rule.Command().Text("source").Tool(global.Tools.VerifyUsesLibraries).Input(module.DexPath)
281 rule.Command().Text("source").Tool(global.Tools.ConstructContext).
282 Textf(`"%s"`, strings.Join(conditionalClassLoaderContextHost, ":")).
283 Textf(`"%s"`, strings.Join(conditionalClassLoaderContextTarget, ":"))
284 }
285
286 cmd := rule.Command().
287 Text(`ANDROID_LOG_TAGS="*:e"`).
288 Tool(global.Tools.Dex2oat).
289 Flag("--avoid-storing-invocation").
290 Flag("--runtime-arg").FlagWithArg("-Xms", global.Dex2oatXms).
291 Flag("--runtime-arg").FlagWithArg("-Xmx", global.Dex2oatXmx).
292 Flag("${class_loader_context_arg}").
293 Flag("${stored_class_loader_context_arg}").
294 FlagWithArg("--boot-image=", bootImageLocation).Implicit(bootImagePath).
295 FlagWithInput("--dex-file=", module.DexPath).
296 FlagWithArg("--dex-location=", module.DexLocation).
297 FlagWithOutput("--oat-file=", odexPath).ImplicitOutput(vdexPath).
298 // Pass an empty directory, dex2oat shouldn't be reading arbitrary files
299 FlagWithArg("--android-root=", global.EmptyDirectory).
300 FlagWithArg("--instruction-set=", arch).
301 FlagWithArg("--instruction-set-variant=", global.CpuVariant[arch]).
302 FlagWithArg("--instruction-set-features=", global.InstructionSetFeatures[arch]).
303 Flag("--no-generate-debug-info").
304 Flag("--generate-build-id").
305 Flag("--abort-on-hard-verifier-error").
306 Flag("--force-determinism").
307 FlagWithArg("--no-inline-from=", "core-oj.jar")
308
309 var preoptFlags []string
310 if len(module.PreoptFlags) > 0 {
311 preoptFlags = module.PreoptFlags
312 } else if len(global.PreoptFlags) > 0 {
313 preoptFlags = global.PreoptFlags
314 }
315
316 if len(preoptFlags) > 0 {
317 cmd.Text(strings.Join(preoptFlags, " "))
318 }
319
320 if module.UncompressedDex {
321 cmd.FlagWithArg("--copy-dex-files=", "false")
322 }
323
324 if !anyHavePrefix(preoptFlags, "--compiler-filter=") {
325 var compilerFilter string
326 if contains(global.SystemServerJars, module.Name) {
327 // Jars of system server, use the product option if it is set, speed otherwise.
328 if global.SystemServerCompilerFilter != "" {
329 compilerFilter = global.SystemServerCompilerFilter
330 } else {
331 compilerFilter = "speed"
332 }
333 } else if contains(global.SpeedApps, module.Name) || contains(global.SystemServerApps, module.Name) {
334 // Apps loaded into system server, and apps the product default to being compiled with the
335 // 'speed' compiler filter.
336 compilerFilter = "speed"
337 } else if profile != "" {
338 // For non system server jars, use speed-profile when we have a profile.
339 compilerFilter = "speed-profile"
340 } else if global.DefaultCompilerFilter != "" {
341 compilerFilter = global.DefaultCompilerFilter
342 } else {
343 compilerFilter = "quicken"
344 }
345 cmd.FlagWithArg("--compiler-filter=", compilerFilter)
346 }
347
348 if generateDM {
349 cmd.FlagWithArg("--copy-dex-files=", "false")
350 dmPath := filepath.Join(filepath.Dir(module.BuildPath), "generated.dm")
351 dmInstalledPath := pathtools.ReplaceExtension(module.DexLocation, "dm")
352 tmpPath := filepath.Join(filepath.Dir(module.BuildPath), "primary.vdex")
353 rule.Command().Text("cp -f").Input(vdexPath).Output(tmpPath)
354 rule.Command().Tool(global.Tools.SoongZip).
355 FlagWithArg("-L", "9").
356 FlagWithOutput("-o", dmPath).
357 Flag("-j").
358 Input(tmpPath)
359 rule.Install(dmPath, dmInstalledPath)
360 }
361
362 // By default, emit debug info.
363 debugInfo := true
364 if global.NoDebugInfo {
365 // If the global setting suppresses mini-debug-info, disable it.
366 debugInfo = false
367 }
368
369 // PRODUCT_SYSTEM_SERVER_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO.
370 // PRODUCT_OTHER_JAVA_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO.
371 if contains(global.SystemServerJars, module.Name) {
372 if global.AlwaysSystemServerDebugInfo {
373 debugInfo = true
374 } else if global.NeverSystemServerDebugInfo {
375 debugInfo = false
376 }
377 } else {
378 if global.AlwaysOtherDebugInfo {
379 debugInfo = true
380 } else if global.NeverOtherDebugInfo {
381 debugInfo = false
382 }
383 }
384
385 // Never enable on eng.
386 if global.IsEng {
387 debugInfo = false
388 }
389
390 if debugInfo {
391 cmd.Flag("--generate-mini-debug-info")
392 } else {
393 cmd.Flag("--no-generate-mini-debug-info")
394 }
395
396 // Set the compiler reason to 'prebuilt' to identify the oat files produced
397 // during the build, as opposed to compiled on the device.
398 cmd.FlagWithArg("--compilation-reason=", "prebuilt")
399
400 if appImage {
401 appImagePath := pathtools.ReplaceExtension(odexPath, "art")
402 appImageInstallPath := pathtools.ReplaceExtension(odexInstallPath, "art")
403 cmd.FlagWithOutput("--app-image-file=", appImagePath).
404 FlagWithArg("--image-format=", "lz4")
405 rule.Install(appImagePath, appImageInstallPath)
406 }
407
408 if profile != "" {
409 cmd.FlagWithArg("--profile-file=", profile)
410 }
411
412 rule.Install(odexPath, odexInstallPath)
413 rule.Install(vdexPath, vdexInstallPath)
414}
415
416// Return if the dex file in the APK should be stripped. If an APK is found to contain uncompressed dex files at
417// dex2oat time it will not be stripped even if strip=true.
418func shouldStripDex(module ModuleConfig, global GlobalConfig) bool {
419 strip := !global.DefaultNoStripping
420
421 // Don't strip modules that are not on the system partition in case the oat/vdex version in system ROM
422 // doesn't match the one in other partitions. It needs to be able to fall back to the APK for that case.
423 if !strings.HasPrefix(module.DexLocation, SystemPartition) {
424 strip = false
425 }
426
427 // system_other isn't there for an OTA, so don't strip if module is on system, and odex is on system_other.
428 if odexOnSystemOther(module, global) {
429 strip = false
430 }
431
432 if module.HasApkLibraries {
433 strip = false
434 }
435
436 // Don't strip with dex files we explicitly uncompress (dexopt will not store the dex code).
437 if module.UncompressedDex {
438 strip = false
439 }
440
441 if shouldGenerateDM(module, global) {
442 strip = false
443 }
444
445 if module.PresignedPrebuilt {
446 // Only strip out files if we can re-sign the package.
447 strip = false
448 }
449
450 return strip
451}
452
453func shouldGenerateDM(module ModuleConfig, global GlobalConfig) bool {
454 // Generating DM files only makes sense for verify, avoid doing for non verify compiler filter APKs.
455 // No reason to use a dm file if the dex is already uncompressed.
456 return global.GenerateDMFiles && !module.UncompressedDex &&
457 contains(module.PreoptFlags, "--compiler-filter=verify")
458}
459
460func odexOnSystemOther(module ModuleConfig, global GlobalConfig) bool {
461 if !global.HasSystemOther {
462 return false
463 }
464
465 if global.SanitizeLite {
466 return false
467 }
468
469 if contains(global.SpeedApps, module.Name) || contains(global.SystemServerApps, module.Name) {
470 return false
471 }
472
473 for _, f := range global.PatternsOnSystemOther {
474 if makefileMatch(filepath.Join(SystemPartition, f), module.DexLocation) {
475 return true
476 }
477 }
478
479 return false
480}
481
482func pathForLibrary(module ModuleConfig, lib string) string {
483 path := module.LibraryPaths[lib]
484 if path == "" {
485 panic(fmt.Errorf("unknown library path for %q", lib))
486 }
487 return path
488}
489
490func makefileMatch(pattern, s string) bool {
491 percent := strings.IndexByte(pattern, '%')
492 switch percent {
493 case -1:
494 return pattern == s
495 case len(pattern) - 1:
496 return strings.HasPrefix(s, pattern[:len(pattern)-1])
497 default:
498 panic(fmt.Errorf("unsupported makefile pattern %q", pattern))
499 }
500}
501
502func contains(l []string, s string) bool {
503 for _, e := range l {
504 if e == s {
505 return true
506 }
507 }
508 return false
509}
510
511// remove all elements in a from b, returning a new slice
512func filterOut(a []string, b []string) []string {
513 var ret []string
514 for _, x := range b {
515 if !contains(a, x) {
516 ret = append(ret, x)
517 }
518 }
519 return ret
520}
521
522func replace(l []string, from, to string) {
523 for i := range l {
524 if l[i] == from {
525 l[i] = to
526 }
527 }
528}
529
530func copyOf(l []string) []string {
531 return append([]string(nil), l...)
532}
533
534func anyHavePrefix(l []string, prefix string) bool {
535 for _, x := range l {
536 if strings.HasPrefix(x, prefix) {
537 return true
538 }
539 }
540 return false
541}