blob: 660a6d04b2113052f4fc1945acc4c85b38a09ba8 [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
Colin Crossfeec25b2019-01-30 17:32:39 -080042 "android/soong/android"
43
Colin Cross43f08db2018-11-12 10:13:39 -080044 "github.com/google/blueprint/pathtools"
45)
46
47const SystemPartition = "/system/"
48const SystemOtherPartition = "/system_other/"
49
50// GenerateStripRule generates a set of commands that will take an APK or JAR as an input and strip the dex files if
51// they are no longer necessary after preopting.
Colin Crossfeec25b2019-01-30 17:32:39 -080052func GenerateStripRule(global GlobalConfig, module ModuleConfig) (rule *android.RuleBuilder, err error) {
Colin Cross43f08db2018-11-12 10:13:39 -080053 defer func() {
54 if r := recover(); r != nil {
55 if e, ok := r.(error); ok {
56 err = e
57 rule = nil
58 } else {
59 panic(r)
60 }
61 }
62 }()
63
64 tools := global.Tools
65
Colin Cross758290d2019-02-01 16:42:32 -080066 rule = android.NewRuleBuilder()
Colin Cross43f08db2018-11-12 10:13:39 -080067
68 strip := shouldStripDex(module, global)
69
70 if strip {
71 // Only strips if the dex files are not already uncompressed
72 rule.Command().
73 Textf(`if (zipinfo %s '*.dex' 2>/dev/null | grep -v ' stor ' >/dev/null) ; then`, module.StripInputPath).
74 Tool(tools.Zip2zip).FlagWithInput("-i ", module.StripInputPath).FlagWithOutput("-o ", module.StripOutputPath).
75 FlagWithArg("-x ", `"classes*.dex"`).
76 Textf(`; else cp -f %s %s; fi`, module.StripInputPath, module.StripOutputPath)
77 } else {
78 rule.Command().Text("cp -f").Input(module.StripInputPath).Output(module.StripOutputPath)
79 }
80
81 return rule, nil
82}
83
84// GenerateDexpreoptRule generates a set of commands that will preopt a module based on a GlobalConfig and a
85// ModuleConfig. The produced files and their install locations will be available through rule.Installs().
Colin Crossfeec25b2019-01-30 17:32:39 -080086func GenerateDexpreoptRule(global GlobalConfig, module ModuleConfig) (rule *android.RuleBuilder, err error) {
Colin Cross43f08db2018-11-12 10:13:39 -080087 defer func() {
88 if r := recover(); r != nil {
89 if e, ok := r.(error); ok {
90 err = e
91 rule = nil
92 } else {
93 panic(r)
94 }
95 }
96 }()
97
Colin Cross758290d2019-02-01 16:42:32 -080098 rule = android.NewRuleBuilder()
Colin Cross43f08db2018-11-12 10:13:39 -080099
Colin Crosscbed6572019-01-08 17:38:37 -0800100 generateProfile := module.ProfileClassListing != "" && !global.DisableGenerateProfile
Colin Cross43f08db2018-11-12 10:13:39 -0800101
Colin Crosscbed6572019-01-08 17:38:37 -0800102 var profile string
103 if generateProfile {
104 profile = profileCommand(global, module, rule)
105 }
106
107 if !dexpreoptDisabled(global, module) {
108 // Don't preopt individual boot jars, they will be preopted together.
109 // This check is outside dexpreoptDisabled because they still need to be stripped.
110 if !contains(global.BootJars, module.Name) {
111 appImage := (generateProfile || module.ForceCreateAppImage || global.DefaultAppImages) &&
112 !module.NoCreateAppImage
113
114 generateDM := shouldGenerateDM(module, global)
115
Colin Crossc7e40aa2019-02-08 21:37:00 -0800116 for i, arch := range module.Archs {
117 image := module.DexPreoptImages[i]
118 dexpreoptCommand(global, module, rule, profile, arch, image, appImage, generateDM)
Colin Crosscbed6572019-01-08 17:38:37 -0800119 }
120 }
121 }
122
123 return rule, nil
124}
125
126func dexpreoptDisabled(global GlobalConfig, module ModuleConfig) bool {
127 if contains(global.DisablePreoptModules, module.Name) {
128 return true
Colin Cross43f08db2018-11-12 10:13:39 -0800129 }
130
131 // If OnlyPreoptBootImageAndSystemServer=true and module is not in boot class path skip
132 // Also preopt system server jars since selinux prevents system server from loading anything from
133 // /data. If we don't do this they will need to be extracted which is not favorable for RAM usage
134 // or performance. If PreoptExtractedApk is true, we ignore the only preopt boot image options.
135 if global.OnlyPreoptBootImageAndSystemServer && !contains(global.BootJars, module.Name) &&
136 !contains(global.SystemServerJars, module.Name) && !module.PreoptExtractedApk {
Colin Crosscbed6572019-01-08 17:38:37 -0800137 return true
Colin Cross43f08db2018-11-12 10:13:39 -0800138 }
139
Colin Crosscbed6572019-01-08 17:38:37 -0800140 return false
Colin Cross43f08db2018-11-12 10:13:39 -0800141}
142
Colin Crossfeec25b2019-01-30 17:32:39 -0800143func profileCommand(global GlobalConfig, module ModuleConfig, rule *android.RuleBuilder) string {
Colin Cross43f08db2018-11-12 10:13:39 -0800144 profilePath := filepath.Join(filepath.Dir(module.BuildPath), "profile.prof")
145 profileInstalledPath := module.DexLocation + ".prof"
146
147 if !module.ProfileIsTextListing {
148 rule.Command().FlagWithOutput("touch ", profilePath)
149 }
150
151 cmd := rule.Command().
152 Text(`ANDROID_LOG_TAGS="*:e"`).
153 Tool(global.Tools.Profman)
154
155 if module.ProfileIsTextListing {
156 // The profile is a test listing of classes (used for framework jars).
157 // We need to generate the actual binary profile before being able to compile.
158 cmd.FlagWithInput("--create-profile-from=", module.ProfileClassListing)
159 } else {
160 // The profile is binary profile (used for apps). Run it through profman to
161 // ensure the profile keys match the apk.
162 cmd.
163 Flag("--copy-and-update-profile-key").
164 FlagWithInput("--profile-file=", module.ProfileClassListing)
165 }
166
167 cmd.
168 FlagWithInput("--apk=", module.DexPath).
169 Flag("--dex-location="+module.DexLocation).
170 FlagWithOutput("--reference-profile-file=", profilePath)
171
172 if !module.ProfileIsTextListing {
173 cmd.Text(fmt.Sprintf(`|| echo "Profile out of date for %s"`, module.DexPath))
174 }
175 rule.Install(profilePath, profileInstalledPath)
176
177 return profilePath
178}
179
Colin Crossfeec25b2019-01-30 17:32:39 -0800180func dexpreoptCommand(global GlobalConfig, module ModuleConfig, rule *android.RuleBuilder,
Colin Crossc7e40aa2019-02-08 21:37:00 -0800181 profile, arch, bootImage string, appImage, generateDM bool) {
Colin Cross43f08db2018-11-12 10:13:39 -0800182
183 // HACK: make soname in Soong-generated .odex files match Make.
184 base := filepath.Base(module.DexLocation)
185 if filepath.Ext(base) == ".jar" {
186 base = "javalib.jar"
187 } else if filepath.Ext(base) == ".apk" {
188 base = "package.apk"
189 }
190
191 toOdexPath := func(path string) string {
192 return filepath.Join(
193 filepath.Dir(path),
194 "oat",
195 arch,
196 pathtools.ReplaceExtension(filepath.Base(path), "odex"))
197 }
198
Vladimir Markod2ee5322018-12-19 17:57:57 +0000199 bcp := strings.Join(global.PreoptBootClassPathDexFiles, ":")
200 bcp_locations := strings.Join(global.PreoptBootClassPathDexLocations, ":")
201
Colin Cross43f08db2018-11-12 10:13:39 -0800202 odexPath := toOdexPath(filepath.Join(filepath.Dir(module.BuildPath), base))
203 odexInstallPath := toOdexPath(module.DexLocation)
204 if odexOnSystemOther(module, global) {
205 odexInstallPath = strings.Replace(odexInstallPath, SystemPartition, SystemOtherPartition, 1)
206 }
207
208 vdexPath := pathtools.ReplaceExtension(odexPath, "vdex")
209 vdexInstallPath := pathtools.ReplaceExtension(odexInstallPath, "vdex")
210
Alex Light5de41962018-12-18 15:16:26 -0800211 invocationPath := pathtools.ReplaceExtension(odexPath, "invocation")
212
Colin Crossc7e40aa2019-02-08 21:37:00 -0800213 // bootImage is .../dex_bootjars/system/framework/arm64/boot.art, but dex2oat wants
214 // .../dex_bootjars/system/framework/boot.art on the command line
215 var bootImageLocation string
216 if bootImage != "" {
217 bootImageLocation = PathToLocation(bootImage, arch)
Colin Cross43f08db2018-11-12 10:13:39 -0800218 }
219
220 // Lists of used and optional libraries from the build config to be verified against the manifest in the APK
221 var verifyUsesLibs []string
222 var verifyOptionalUsesLibs []string
223
224 // Lists of used and optional libraries from the build config, with optional libraries that are known to not
225 // be present in the current product removed.
226 var filteredUsesLibs []string
227 var filteredOptionalUsesLibs []string
228
229 // The class loader context using paths in the build
230 var classLoaderContextHost []string
231
232 // The class loader context using paths as they will be on the device
233 var classLoaderContextTarget []string
234
235 // Extra paths that will be appended to the class loader if the APK manifest has targetSdkVersion < 28
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000236 var conditionalClassLoaderContextHost28 []string
237 var conditionalClassLoaderContextTarget28 []string
238
239 // Extra paths that will be appended to the class loader if the APK manifest has targetSdkVersion < 29
240 var conditionalClassLoaderContextHost29 []string
241 var conditionalClassLoaderContextTarget29 []string
Colin Cross43f08db2018-11-12 10:13:39 -0800242
243 if module.EnforceUsesLibraries {
244 verifyUsesLibs = copyOf(module.UsesLibraries)
245 verifyOptionalUsesLibs = copyOf(module.OptionalUsesLibraries)
246
247 filteredOptionalUsesLibs = filterOut(global.MissingUsesLibraries, module.OptionalUsesLibraries)
248 filteredUsesLibs = append(copyOf(module.UsesLibraries), filteredOptionalUsesLibs...)
249
250 // Create class loader context for dex2oat from uses libraries and filtered optional libraries
251 for _, l := range filteredUsesLibs {
252
253 classLoaderContextHost = append(classLoaderContextHost,
254 pathForLibrary(module, l))
255 classLoaderContextTarget = append(classLoaderContextTarget,
256 filepath.Join("/system/framework", l+".jar"))
257 }
258
259 const httpLegacy = "org.apache.http.legacy"
260 const httpLegacyImpl = "org.apache.http.legacy.impl"
261
262 // Fix up org.apache.http.legacy.impl since it should be org.apache.http.legacy in the manifest.
263 replace(verifyUsesLibs, httpLegacyImpl, httpLegacy)
264 replace(verifyOptionalUsesLibs, httpLegacyImpl, httpLegacy)
265
266 if !contains(verifyUsesLibs, httpLegacy) && !contains(verifyOptionalUsesLibs, httpLegacy) {
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000267 conditionalClassLoaderContextHost28 = append(conditionalClassLoaderContextHost28,
Colin Cross43f08db2018-11-12 10:13:39 -0800268 pathForLibrary(module, httpLegacyImpl))
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000269 conditionalClassLoaderContextTarget28 = append(conditionalClassLoaderContextTarget28,
Colin Cross43f08db2018-11-12 10:13:39 -0800270 filepath.Join("/system/framework", httpLegacyImpl+".jar"))
271 }
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000272
273 const hidlBase = "android.hidl.base-V1.0-java"
274 const hidlManager = "android.hidl.manager-V1.0-java"
275
276 conditionalClassLoaderContextHost29 = append(conditionalClassLoaderContextHost29,
Alex Light5de41962018-12-18 15:16:26 -0800277 pathForLibrary(module, hidlManager))
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000278 conditionalClassLoaderContextTarget29 = append(conditionalClassLoaderContextTarget29,
279 filepath.Join("/system/framework", hidlManager+".jar"))
280 conditionalClassLoaderContextHost29 = append(conditionalClassLoaderContextHost29,
Alex Light5de41962018-12-18 15:16:26 -0800281 pathForLibrary(module, hidlBase))
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000282 conditionalClassLoaderContextTarget29 = append(conditionalClassLoaderContextTarget29,
283 filepath.Join("/system/framework", hidlBase+".jar"))
Colin Cross43f08db2018-11-12 10:13:39 -0800284 } else {
285 // Pass special class loader context to skip the classpath and collision check.
286 // This will get removed once LOCAL_USES_LIBRARIES is enforced.
287 // Right now LOCAL_USES_LIBRARIES is opt in, for the case where it's not specified we still default
288 // to the &.
289 classLoaderContextHost = []string{`\&`}
290 }
291
292 rule.Command().FlagWithArg("mkdir -p ", filepath.Dir(odexPath))
293 rule.Command().FlagWithOutput("rm -f ", odexPath)
294 // Set values in the environment of the rule. These may be modified by construct_context.sh.
295 rule.Command().FlagWithArg("class_loader_context_arg=--class-loader-context=",
296 strings.Join(classLoaderContextHost, ":"))
297 rule.Command().Text(`stored_class_loader_context_arg=""`)
298
299 if module.EnforceUsesLibraries {
Colin Cross43f08db2018-11-12 10:13:39 -0800300 rule.Command().Textf(`uses_library_names="%s"`, strings.Join(verifyUsesLibs, " "))
301 rule.Command().Textf(`optional_uses_library_names="%s"`, strings.Join(verifyOptionalUsesLibs, " "))
302 rule.Command().Textf(`aapt_binary="%s"`, global.Tools.Aapt)
Alex Light5de41962018-12-18 15:16:26 -0800303 rule.Command().Textf(`dex_preopt_host_libraries="%s"`, strings.Join(classLoaderContextHost, " "))
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000304 rule.Command().Textf(`dex_preopt_target_libraries="%s"`, strings.Join(classLoaderContextTarget, " "))
305 rule.Command().Textf(`conditional_host_libs_28="%s"`, strings.Join(conditionalClassLoaderContextHost28, " "))
306 rule.Command().Textf(`conditional_target_libs_28="%s"`, strings.Join(conditionalClassLoaderContextTarget28, " "))
307 rule.Command().Textf(`conditional_host_libs_29="%s"`, strings.Join(conditionalClassLoaderContextHost29, " "))
308 rule.Command().Textf(`conditional_target_libs_29="%s"`, strings.Join(conditionalClassLoaderContextTarget29, " "))
Colin Cross43f08db2018-11-12 10:13:39 -0800309 rule.Command().Text("source").Tool(global.Tools.VerifyUsesLibraries).Input(module.DexPath)
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000310 rule.Command().Text("source").Tool(global.Tools.ConstructContext)
Colin Cross43f08db2018-11-12 10:13:39 -0800311 }
312
313 cmd := rule.Command().
314 Text(`ANDROID_LOG_TAGS="*:e"`).
315 Tool(global.Tools.Dex2oat).
316 Flag("--avoid-storing-invocation").
Alex Light5de41962018-12-18 15:16:26 -0800317 FlagWithOutput("--write-invocation-to=", invocationPath).ImplicitOutput(invocationPath).
Colin Cross43f08db2018-11-12 10:13:39 -0800318 Flag("--runtime-arg").FlagWithArg("-Xms", global.Dex2oatXms).
319 Flag("--runtime-arg").FlagWithArg("-Xmx", global.Dex2oatXmx).
Vladimir Markod2ee5322018-12-19 17:57:57 +0000320 Flag("--runtime-arg").FlagWithArg("-Xbootclasspath:", bcp).
321 Implicits(global.PreoptBootClassPathDexFiles).
322 Flag("--runtime-arg").FlagWithArg("-Xbootclasspath-locations:", bcp_locations).
Colin Cross43f08db2018-11-12 10:13:39 -0800323 Flag("${class_loader_context_arg}").
324 Flag("${stored_class_loader_context_arg}").
Colin Crossc7e40aa2019-02-08 21:37:00 -0800325 FlagWithArg("--boot-image=", bootImageLocation).Implicit(bootImage).
Colin Cross43f08db2018-11-12 10:13:39 -0800326 FlagWithInput("--dex-file=", module.DexPath).
327 FlagWithArg("--dex-location=", module.DexLocation).
328 FlagWithOutput("--oat-file=", odexPath).ImplicitOutput(vdexPath).
329 // Pass an empty directory, dex2oat shouldn't be reading arbitrary files
330 FlagWithArg("--android-root=", global.EmptyDirectory).
331 FlagWithArg("--instruction-set=", arch).
332 FlagWithArg("--instruction-set-variant=", global.CpuVariant[arch]).
333 FlagWithArg("--instruction-set-features=", global.InstructionSetFeatures[arch]).
334 Flag("--no-generate-debug-info").
335 Flag("--generate-build-id").
336 Flag("--abort-on-hard-verifier-error").
337 Flag("--force-determinism").
338 FlagWithArg("--no-inline-from=", "core-oj.jar")
339
340 var preoptFlags []string
341 if len(module.PreoptFlags) > 0 {
342 preoptFlags = module.PreoptFlags
343 } else if len(global.PreoptFlags) > 0 {
344 preoptFlags = global.PreoptFlags
345 }
346
347 if len(preoptFlags) > 0 {
348 cmd.Text(strings.Join(preoptFlags, " "))
349 }
350
351 if module.UncompressedDex {
352 cmd.FlagWithArg("--copy-dex-files=", "false")
353 }
354
355 if !anyHavePrefix(preoptFlags, "--compiler-filter=") {
356 var compilerFilter string
357 if contains(global.SystemServerJars, module.Name) {
358 // Jars of system server, use the product option if it is set, speed otherwise.
359 if global.SystemServerCompilerFilter != "" {
360 compilerFilter = global.SystemServerCompilerFilter
361 } else {
362 compilerFilter = "speed"
363 }
364 } else if contains(global.SpeedApps, module.Name) || contains(global.SystemServerApps, module.Name) {
365 // Apps loaded into system server, and apps the product default to being compiled with the
366 // 'speed' compiler filter.
367 compilerFilter = "speed"
368 } else if profile != "" {
369 // For non system server jars, use speed-profile when we have a profile.
370 compilerFilter = "speed-profile"
371 } else if global.DefaultCompilerFilter != "" {
372 compilerFilter = global.DefaultCompilerFilter
373 } else {
374 compilerFilter = "quicken"
375 }
376 cmd.FlagWithArg("--compiler-filter=", compilerFilter)
377 }
378
379 if generateDM {
380 cmd.FlagWithArg("--copy-dex-files=", "false")
381 dmPath := filepath.Join(filepath.Dir(module.BuildPath), "generated.dm")
382 dmInstalledPath := pathtools.ReplaceExtension(module.DexLocation, "dm")
383 tmpPath := filepath.Join(filepath.Dir(module.BuildPath), "primary.vdex")
384 rule.Command().Text("cp -f").Input(vdexPath).Output(tmpPath)
385 rule.Command().Tool(global.Tools.SoongZip).
386 FlagWithArg("-L", "9").
387 FlagWithOutput("-o", dmPath).
388 Flag("-j").
389 Input(tmpPath)
390 rule.Install(dmPath, dmInstalledPath)
391 }
392
393 // By default, emit debug info.
394 debugInfo := true
395 if global.NoDebugInfo {
396 // If the global setting suppresses mini-debug-info, disable it.
397 debugInfo = false
398 }
399
400 // PRODUCT_SYSTEM_SERVER_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO.
401 // PRODUCT_OTHER_JAVA_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO.
402 if contains(global.SystemServerJars, module.Name) {
403 if global.AlwaysSystemServerDebugInfo {
404 debugInfo = true
405 } else if global.NeverSystemServerDebugInfo {
406 debugInfo = false
407 }
408 } else {
409 if global.AlwaysOtherDebugInfo {
410 debugInfo = true
411 } else if global.NeverOtherDebugInfo {
412 debugInfo = false
413 }
414 }
415
416 // Never enable on eng.
417 if global.IsEng {
418 debugInfo = false
419 }
420
421 if debugInfo {
422 cmd.Flag("--generate-mini-debug-info")
423 } else {
424 cmd.Flag("--no-generate-mini-debug-info")
425 }
426
427 // Set the compiler reason to 'prebuilt' to identify the oat files produced
428 // during the build, as opposed to compiled on the device.
429 cmd.FlagWithArg("--compilation-reason=", "prebuilt")
430
431 if appImage {
432 appImagePath := pathtools.ReplaceExtension(odexPath, "art")
433 appImageInstallPath := pathtools.ReplaceExtension(odexInstallPath, "art")
434 cmd.FlagWithOutput("--app-image-file=", appImagePath).
435 FlagWithArg("--image-format=", "lz4")
436 rule.Install(appImagePath, appImageInstallPath)
437 }
438
439 if profile != "" {
440 cmd.FlagWithArg("--profile-file=", profile)
441 }
442
443 rule.Install(odexPath, odexInstallPath)
444 rule.Install(vdexPath, vdexInstallPath)
445}
446
447// Return if the dex file in the APK should be stripped. If an APK is found to contain uncompressed dex files at
448// dex2oat time it will not be stripped even if strip=true.
449func shouldStripDex(module ModuleConfig, global GlobalConfig) bool {
450 strip := !global.DefaultNoStripping
451
Colin Crosscbed6572019-01-08 17:38:37 -0800452 if dexpreoptDisabled(global, module) {
453 strip = false
454 }
455
Colin Cross8c6d2502019-01-09 21:09:14 -0800456 if module.NoStripping {
457 strip = false
458 }
459
Colin Cross43f08db2018-11-12 10:13:39 -0800460 // Don't strip modules that are not on the system partition in case the oat/vdex version in system ROM
461 // doesn't match the one in other partitions. It needs to be able to fall back to the APK for that case.
462 if !strings.HasPrefix(module.DexLocation, SystemPartition) {
463 strip = false
464 }
465
466 // system_other isn't there for an OTA, so don't strip if module is on system, and odex is on system_other.
467 if odexOnSystemOther(module, global) {
468 strip = false
469 }
470
471 if module.HasApkLibraries {
472 strip = false
473 }
474
475 // Don't strip with dex files we explicitly uncompress (dexopt will not store the dex code).
476 if module.UncompressedDex {
477 strip = false
478 }
479
480 if shouldGenerateDM(module, global) {
481 strip = false
482 }
483
484 if module.PresignedPrebuilt {
485 // Only strip out files if we can re-sign the package.
486 strip = false
487 }
488
489 return strip
490}
491
492func shouldGenerateDM(module ModuleConfig, global GlobalConfig) bool {
493 // Generating DM files only makes sense for verify, avoid doing for non verify compiler filter APKs.
494 // No reason to use a dm file if the dex is already uncompressed.
495 return global.GenerateDMFiles && !module.UncompressedDex &&
496 contains(module.PreoptFlags, "--compiler-filter=verify")
497}
498
499func odexOnSystemOther(module ModuleConfig, global GlobalConfig) bool {
500 if !global.HasSystemOther {
501 return false
502 }
503
504 if global.SanitizeLite {
505 return false
506 }
507
508 if contains(global.SpeedApps, module.Name) || contains(global.SystemServerApps, module.Name) {
509 return false
510 }
511
512 for _, f := range global.PatternsOnSystemOther {
513 if makefileMatch(filepath.Join(SystemPartition, f), module.DexLocation) {
514 return true
515 }
516 }
517
518 return false
519}
520
Colin Crossc7e40aa2019-02-08 21:37:00 -0800521// PathToLocation converts .../system/framework/arm64/boot.art to .../system/framework/boot.art
522func PathToLocation(path, arch string) string {
523 pathArch := filepath.Base(filepath.Dir(path))
524 if pathArch != arch {
525 panic(fmt.Errorf("last directory in %q must be %q", path, arch))
526 }
527 return filepath.Join(filepath.Dir(filepath.Dir(path)), filepath.Base(path))
528}
529
Colin Cross43f08db2018-11-12 10:13:39 -0800530func pathForLibrary(module ModuleConfig, lib string) string {
531 path := module.LibraryPaths[lib]
532 if path == "" {
533 panic(fmt.Errorf("unknown library path for %q", lib))
534 }
535 return path
536}
537
538func makefileMatch(pattern, s string) bool {
539 percent := strings.IndexByte(pattern, '%')
540 switch percent {
541 case -1:
542 return pattern == s
543 case len(pattern) - 1:
544 return strings.HasPrefix(s, pattern[:len(pattern)-1])
545 default:
546 panic(fmt.Errorf("unsupported makefile pattern %q", pattern))
547 }
548}
549
550func contains(l []string, s string) bool {
551 for _, e := range l {
552 if e == s {
553 return true
554 }
555 }
556 return false
557}
558
559// remove all elements in a from b, returning a new slice
560func filterOut(a []string, b []string) []string {
561 var ret []string
562 for _, x := range b {
563 if !contains(a, x) {
564 ret = append(ret, x)
565 }
566 }
567 return ret
568}
569
570func replace(l []string, from, to string) {
571 for i := range l {
572 if l[i] == from {
573 l[i] = to
574 }
575 }
576}
577
578func copyOf(l []string) []string {
579 return append([]string(nil), l...)
580}
581
582func anyHavePrefix(l []string, prefix string) bool {
583 for _, x := range l {
584 if strings.HasPrefix(x, prefix) {
585 return true
586 }
587 }
588 return false
589}