blob: 0be37d0ff2cadac881a74b1b3767fa7095e6c629 [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"
Colin Cross69f59a32019-02-15 10:39:37 -080040 "runtime"
Colin Cross43f08db2018-11-12 10:13:39 -080041 "strings"
42
Colin Crossfeec25b2019-01-30 17:32:39 -080043 "android/soong/android"
44
Colin Cross43f08db2018-11-12 10:13:39 -080045 "github.com/google/blueprint/pathtools"
46)
47
48const SystemPartition = "/system/"
49const SystemOtherPartition = "/system_other/"
50
51// GenerateStripRule generates a set of commands that will take an APK or JAR as an input and strip the dex files if
52// they are no longer necessary after preopting.
Colin Crossfeec25b2019-01-30 17:32:39 -080053func GenerateStripRule(global GlobalConfig, module ModuleConfig) (rule *android.RuleBuilder, err error) {
Colin Cross43f08db2018-11-12 10:13:39 -080054 defer func() {
55 if r := recover(); r != nil {
Colin Cross69f59a32019-02-15 10:39:37 -080056 if _, ok := r.(runtime.Error); ok {
57 panic(r)
58 } else if e, ok := r.(error); ok {
Colin Cross43f08db2018-11-12 10:13:39 -080059 err = e
60 rule = nil
61 } else {
62 panic(r)
63 }
64 }
65 }()
66
67 tools := global.Tools
68
Colin Cross758290d2019-02-01 16:42:32 -080069 rule = android.NewRuleBuilder()
Colin Cross43f08db2018-11-12 10:13:39 -080070
71 strip := shouldStripDex(module, global)
72
73 if strip {
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +000074 if global.NeverAllowStripping {
75 panic(fmt.Errorf("Stripping requested on %q, though the product does not allow it", module.DexLocation))
76 }
Colin Cross43f08db2018-11-12 10:13:39 -080077 // Only strips if the dex files are not already uncompressed
78 rule.Command().
79 Textf(`if (zipinfo %s '*.dex' 2>/dev/null | grep -v ' stor ' >/dev/null) ; then`, module.StripInputPath).
80 Tool(tools.Zip2zip).FlagWithInput("-i ", module.StripInputPath).FlagWithOutput("-o ", module.StripOutputPath).
81 FlagWithArg("-x ", `"classes*.dex"`).
82 Textf(`; else cp -f %s %s; fi`, module.StripInputPath, module.StripOutputPath)
83 } else {
84 rule.Command().Text("cp -f").Input(module.StripInputPath).Output(module.StripOutputPath)
85 }
86
87 return rule, nil
88}
89
90// GenerateDexpreoptRule generates a set of commands that will preopt a module based on a GlobalConfig and a
91// ModuleConfig. The produced files and their install locations will be available through rule.Installs().
Colin Cross69f59a32019-02-15 10:39:37 -080092func GenerateDexpreoptRule(ctx android.PathContext,
93 global GlobalConfig, module ModuleConfig) (rule *android.RuleBuilder, err error) {
94
Colin Cross43f08db2018-11-12 10:13:39 -080095 defer func() {
96 if r := recover(); r != nil {
Colin Cross69f59a32019-02-15 10:39:37 -080097 if _, ok := r.(runtime.Error); ok {
98 panic(r)
99 } else if e, ok := r.(error); ok {
Colin Cross43f08db2018-11-12 10:13:39 -0800100 err = e
101 rule = nil
102 } else {
103 panic(r)
104 }
105 }
106 }()
107
Colin Cross758290d2019-02-01 16:42:32 -0800108 rule = android.NewRuleBuilder()
Colin Cross43f08db2018-11-12 10:13:39 -0800109
Colin Cross69f59a32019-02-15 10:39:37 -0800110 generateProfile := module.ProfileClassListing.Valid() && !global.DisableGenerateProfile
Colin Cross43f08db2018-11-12 10:13:39 -0800111
Colin Cross69f59a32019-02-15 10:39:37 -0800112 var profile android.WritablePath
Colin Crosscbed6572019-01-08 17:38:37 -0800113 if generateProfile {
Colin Cross69f59a32019-02-15 10:39:37 -0800114 profile = profileCommand(ctx, global, module, rule)
Colin Crosscbed6572019-01-08 17:38:37 -0800115 }
116
117 if !dexpreoptDisabled(global, module) {
118 // Don't preopt individual boot jars, they will be preopted together.
119 // This check is outside dexpreoptDisabled because they still need to be stripped.
120 if !contains(global.BootJars, module.Name) {
121 appImage := (generateProfile || module.ForceCreateAppImage || global.DefaultAppImages) &&
122 !module.NoCreateAppImage
123
124 generateDM := shouldGenerateDM(module, global)
125
Colin Crossc7e40aa2019-02-08 21:37:00 -0800126 for i, arch := range module.Archs {
127 image := module.DexPreoptImages[i]
Colin Cross69f59a32019-02-15 10:39:37 -0800128 dexpreoptCommand(ctx, global, module, rule, arch, profile, image, appImage, generateDM)
Colin Crosscbed6572019-01-08 17:38:37 -0800129 }
130 }
131 }
132
133 return rule, nil
134}
135
136func dexpreoptDisabled(global GlobalConfig, module ModuleConfig) bool {
137 if contains(global.DisablePreoptModules, module.Name) {
138 return true
Colin Cross43f08db2018-11-12 10:13:39 -0800139 }
140
141 // If OnlyPreoptBootImageAndSystemServer=true and module is not in boot class path skip
142 // Also preopt system server jars since selinux prevents system server from loading anything from
143 // /data. If we don't do this they will need to be extracted which is not favorable for RAM usage
144 // or performance. If PreoptExtractedApk is true, we ignore the only preopt boot image options.
145 if global.OnlyPreoptBootImageAndSystemServer && !contains(global.BootJars, module.Name) &&
146 !contains(global.SystemServerJars, module.Name) && !module.PreoptExtractedApk {
Colin Crosscbed6572019-01-08 17:38:37 -0800147 return true
Colin Cross43f08db2018-11-12 10:13:39 -0800148 }
149
Colin Crosscbed6572019-01-08 17:38:37 -0800150 return false
Colin Cross43f08db2018-11-12 10:13:39 -0800151}
152
Colin Cross69f59a32019-02-15 10:39:37 -0800153func profileCommand(ctx android.PathContext, global GlobalConfig, module ModuleConfig,
154 rule *android.RuleBuilder) android.WritablePath {
155
156 profilePath := module.BuildPath.InSameDir(ctx, "profile.prof")
Colin Cross43f08db2018-11-12 10:13:39 -0800157 profileInstalledPath := module.DexLocation + ".prof"
158
159 if !module.ProfileIsTextListing {
160 rule.Command().FlagWithOutput("touch ", profilePath)
161 }
162
163 cmd := rule.Command().
164 Text(`ANDROID_LOG_TAGS="*:e"`).
165 Tool(global.Tools.Profman)
166
167 if module.ProfileIsTextListing {
168 // The profile is a test listing of classes (used for framework jars).
169 // We need to generate the actual binary profile before being able to compile.
Colin Cross69f59a32019-02-15 10:39:37 -0800170 cmd.FlagWithInput("--create-profile-from=", module.ProfileClassListing.Path())
Colin Cross43f08db2018-11-12 10:13:39 -0800171 } else {
172 // The profile is binary profile (used for apps). Run it through profman to
173 // ensure the profile keys match the apk.
174 cmd.
175 Flag("--copy-and-update-profile-key").
Colin Cross69f59a32019-02-15 10:39:37 -0800176 FlagWithInput("--profile-file=", module.ProfileClassListing.Path())
Colin Cross43f08db2018-11-12 10:13:39 -0800177 }
178
179 cmd.
180 FlagWithInput("--apk=", module.DexPath).
181 Flag("--dex-location="+module.DexLocation).
182 FlagWithOutput("--reference-profile-file=", profilePath)
183
184 if !module.ProfileIsTextListing {
185 cmd.Text(fmt.Sprintf(`|| echo "Profile out of date for %s"`, module.DexPath))
186 }
187 rule.Install(profilePath, profileInstalledPath)
188
189 return profilePath
190}
191
Colin Cross69f59a32019-02-15 10:39:37 -0800192func dexpreoptCommand(ctx android.PathContext, global GlobalConfig, module ModuleConfig, rule *android.RuleBuilder,
193 arch android.ArchType, profile, bootImage android.Path, appImage, generateDM bool) {
Colin Cross43f08db2018-11-12 10:13:39 -0800194
195 // HACK: make soname in Soong-generated .odex files match Make.
196 base := filepath.Base(module.DexLocation)
197 if filepath.Ext(base) == ".jar" {
198 base = "javalib.jar"
199 } else if filepath.Ext(base) == ".apk" {
200 base = "package.apk"
201 }
202
203 toOdexPath := func(path string) string {
204 return filepath.Join(
205 filepath.Dir(path),
206 "oat",
Colin Cross74ba9622019-02-11 15:11:14 -0800207 arch.String(),
Colin Cross43f08db2018-11-12 10:13:39 -0800208 pathtools.ReplaceExtension(filepath.Base(path), "odex"))
209 }
210
Colin Cross69f59a32019-02-15 10:39:37 -0800211 odexPath := module.BuildPath.InSameDir(ctx, "oat", arch.String(), pathtools.ReplaceExtension(base, "odex"))
Colin Cross43f08db2018-11-12 10:13:39 -0800212 odexInstallPath := toOdexPath(module.DexLocation)
213 if odexOnSystemOther(module, global) {
214 odexInstallPath = strings.Replace(odexInstallPath, SystemPartition, SystemOtherPartition, 1)
215 }
216
Colin Cross69f59a32019-02-15 10:39:37 -0800217 vdexPath := odexPath.ReplaceExtension(ctx, "vdex")
Colin Cross43f08db2018-11-12 10:13:39 -0800218 vdexInstallPath := pathtools.ReplaceExtension(odexInstallPath, "vdex")
219
Colin Cross69f59a32019-02-15 10:39:37 -0800220 invocationPath := odexPath.ReplaceExtension(ctx, "invocation")
Alex Light5de41962018-12-18 15:16:26 -0800221
Colin Crossc7e40aa2019-02-08 21:37:00 -0800222 // bootImage is .../dex_bootjars/system/framework/arm64/boot.art, but dex2oat wants
223 // .../dex_bootjars/system/framework/boot.art on the command line
224 var bootImageLocation string
Colin Cross69f59a32019-02-15 10:39:37 -0800225 if bootImage != nil {
Colin Crossc7e40aa2019-02-08 21:37:00 -0800226 bootImageLocation = PathToLocation(bootImage, arch)
Colin Cross43f08db2018-11-12 10:13:39 -0800227 }
228
Colin Cross43f08db2018-11-12 10:13:39 -0800229 // The class loader context using paths in the build
Colin Cross69f59a32019-02-15 10:39:37 -0800230 var classLoaderContextHost android.Paths
Colin Cross43f08db2018-11-12 10:13:39 -0800231
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
Colin Cross69f59a32019-02-15 10:39:37 -0800236 var conditionalClassLoaderContextHost28 android.Paths
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000237 var conditionalClassLoaderContextTarget28 []string
238
239 // Extra paths that will be appended to the class loader if the APK manifest has targetSdkVersion < 29
Colin Cross69f59a32019-02-15 10:39:37 -0800240 var conditionalClassLoaderContextHost29 android.Paths
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000241 var conditionalClassLoaderContextTarget29 []string
Colin Cross43f08db2018-11-12 10:13:39 -0800242
Colin Cross69f59a32019-02-15 10:39:37 -0800243 var classLoaderContextHostString string
244
Colin Cross43f08db2018-11-12 10:13:39 -0800245 if module.EnforceUsesLibraries {
Colin Cross50ddcc42019-05-16 12:28:22 -0700246 usesLibs := append(copyOf(module.UsesLibraries), module.PresentOptionalUsesLibraries...)
Colin Cross43f08db2018-11-12 10:13:39 -0800247
248 // Create class loader context for dex2oat from uses libraries and filtered optional libraries
Colin Cross50ddcc42019-05-16 12:28:22 -0700249 for _, l := range usesLibs {
Colin Cross43f08db2018-11-12 10:13:39 -0800250
251 classLoaderContextHost = append(classLoaderContextHost,
252 pathForLibrary(module, l))
253 classLoaderContextTarget = append(classLoaderContextTarget,
254 filepath.Join("/system/framework", l+".jar"))
255 }
256
257 const httpLegacy = "org.apache.http.legacy"
258 const httpLegacyImpl = "org.apache.http.legacy.impl"
259
Colin Cross38b96852019-05-22 10:21:09 -0700260 // org.apache.http.legacy contains classes that were in the default classpath until API 28. If the
261 // targetSdkVersion in the manifest or APK is < 28, and the module does not explicitly depend on
262 // org.apache.http.legacy, then implicitly add the classes to the classpath for dexpreopt. One the
263 // device the classes will be in a file called org.apache.http.legacy.impl.jar.
Colin Cross50ddcc42019-05-16 12:28:22 -0700264 module.LibraryPaths[httpLegacyImpl] = module.LibraryPaths[httpLegacy]
265
266 if !contains(module.UsesLibraries, httpLegacy) && !contains(module.PresentOptionalUsesLibraries, 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
Colin Cross38b96852019-05-22 10:21:09 -0700276 // android.hidl.base-V1.0-java and android.hidl.manager-V1.0 contain classes that were in the default
277 // classpath until API 29. If the targetSdkVersion in the manifest or APK is < 29 then implicitly add
278 // the classes to the classpath for dexpreopt.
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000279 conditionalClassLoaderContextHost29 = append(conditionalClassLoaderContextHost29,
Alex Light5de41962018-12-18 15:16:26 -0800280 pathForLibrary(module, hidlManager))
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000281 conditionalClassLoaderContextTarget29 = append(conditionalClassLoaderContextTarget29,
282 filepath.Join("/system/framework", hidlManager+".jar"))
283 conditionalClassLoaderContextHost29 = append(conditionalClassLoaderContextHost29,
Alex Light5de41962018-12-18 15:16:26 -0800284 pathForLibrary(module, hidlBase))
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000285 conditionalClassLoaderContextTarget29 = append(conditionalClassLoaderContextTarget29,
286 filepath.Join("/system/framework", hidlBase+".jar"))
Colin Cross69f59a32019-02-15 10:39:37 -0800287
288 classLoaderContextHostString = strings.Join(classLoaderContextHost.Strings(), ":")
Colin Cross43f08db2018-11-12 10:13:39 -0800289 } else {
290 // Pass special class loader context to skip the classpath and collision check.
291 // This will get removed once LOCAL_USES_LIBRARIES is enforced.
292 // Right now LOCAL_USES_LIBRARIES is opt in, for the case where it's not specified we still default
293 // to the &.
Colin Cross69f59a32019-02-15 10:39:37 -0800294 classLoaderContextHostString = `\&`
Colin Cross43f08db2018-11-12 10:13:39 -0800295 }
296
Colin Cross69f59a32019-02-15 10:39:37 -0800297 rule.Command().FlagWithArg("mkdir -p ", filepath.Dir(odexPath.String()))
Colin Cross43f08db2018-11-12 10:13:39 -0800298 rule.Command().FlagWithOutput("rm -f ", odexPath)
299 // Set values in the environment of the rule. These may be modified by construct_context.sh.
Colin Cross69f59a32019-02-15 10:39:37 -0800300 rule.Command().FlagWithArg("class_loader_context_arg=--class-loader-context=", classLoaderContextHostString)
Colin Cross43f08db2018-11-12 10:13:39 -0800301 rule.Command().Text(`stored_class_loader_context_arg=""`)
302
303 if module.EnforceUsesLibraries {
Colin Cross38b96852019-05-22 10:21:09 -0700304 if module.ManifestPath != nil {
305 rule.Command().Text(`target_sdk_version="$(`).
306 Tool(global.Tools.ManifestCheck).
307 Flag("--extract-target-sdk-version").
308 Input(module.ManifestPath).
309 Text(`)"`)
310 } else {
311 // No manifest to extract targetSdkVersion from, hope that DexJar is an APK
312 rule.Command().Text(`target_sdk_version="$(`).
313 Tool(global.Tools.Aapt).
314 Flag("dump badging").
315 Input(module.DexPath).
316 Text(`| grep "targetSdkVersion" | sed -n "s/targetSdkVersion:'\(.*\)'/\1/p"`).
317 Text(`)"`)
318 }
Colin Cross69f59a32019-02-15 10:39:37 -0800319 rule.Command().Textf(`dex_preopt_host_libraries="%s"`,
320 strings.Join(classLoaderContextHost.Strings(), " ")).
321 Implicits(classLoaderContextHost)
322 rule.Command().Textf(`dex_preopt_target_libraries="%s"`,
323 strings.Join(classLoaderContextTarget, " "))
324 rule.Command().Textf(`conditional_host_libs_28="%s"`,
325 strings.Join(conditionalClassLoaderContextHost28.Strings(), " ")).
326 Implicits(conditionalClassLoaderContextHost28)
327 rule.Command().Textf(`conditional_target_libs_28="%s"`,
328 strings.Join(conditionalClassLoaderContextTarget28, " "))
329 rule.Command().Textf(`conditional_host_libs_29="%s"`,
330 strings.Join(conditionalClassLoaderContextHost29.Strings(), " ")).
331 Implicits(conditionalClassLoaderContextHost29)
332 rule.Command().Textf(`conditional_target_libs_29="%s"`,
333 strings.Join(conditionalClassLoaderContextTarget29, " "))
Colin Cross38b96852019-05-22 10:21:09 -0700334 rule.Command().Text("source").Tool(global.Tools.ConstructContext).Input(module.DexPath)
Colin Cross43f08db2018-11-12 10:13:39 -0800335 }
336
Nicolas Geoffray2464ef42019-03-05 14:07:07 +0000337 // Devices that do not have a product partition use a symlink from /product to /system/product.
338 // Because on-device dexopt will see dex locations starting with /product, we change the paths
339 // to mimic this behavior.
340 dexLocationArg := module.DexLocation
341 if strings.HasPrefix(dexLocationArg, "/system/product/") {
342 dexLocationArg = strings.TrimPrefix(dexLocationArg, "/system")
343 }
344
Colin Cross43f08db2018-11-12 10:13:39 -0800345 cmd := rule.Command().
346 Text(`ANDROID_LOG_TAGS="*:e"`).
347 Tool(global.Tools.Dex2oat).
348 Flag("--avoid-storing-invocation").
Alex Light5de41962018-12-18 15:16:26 -0800349 FlagWithOutput("--write-invocation-to=", invocationPath).ImplicitOutput(invocationPath).
Colin Cross43f08db2018-11-12 10:13:39 -0800350 Flag("--runtime-arg").FlagWithArg("-Xms", global.Dex2oatXms).
351 Flag("--runtime-arg").FlagWithArg("-Xmx", global.Dex2oatXmx).
Colin Cross800fe132019-02-11 14:21:24 -0800352 Flag("--runtime-arg").FlagWithInputList("-Xbootclasspath:", module.PreoptBootClassPathDexFiles, ":").
353 Flag("--runtime-arg").FlagWithList("-Xbootclasspath-locations:", module.PreoptBootClassPathDexLocations, ":").
Colin Cross43f08db2018-11-12 10:13:39 -0800354 Flag("${class_loader_context_arg}").
355 Flag("${stored_class_loader_context_arg}").
Colin Crossc7e40aa2019-02-08 21:37:00 -0800356 FlagWithArg("--boot-image=", bootImageLocation).Implicit(bootImage).
Colin Cross43f08db2018-11-12 10:13:39 -0800357 FlagWithInput("--dex-file=", module.DexPath).
Nicolas Geoffray2464ef42019-03-05 14:07:07 +0000358 FlagWithArg("--dex-location=", dexLocationArg).
Colin Cross43f08db2018-11-12 10:13:39 -0800359 FlagWithOutput("--oat-file=", odexPath).ImplicitOutput(vdexPath).
360 // Pass an empty directory, dex2oat shouldn't be reading arbitrary files
361 FlagWithArg("--android-root=", global.EmptyDirectory).
Colin Cross74ba9622019-02-11 15:11:14 -0800362 FlagWithArg("--instruction-set=", arch.String()).
Colin Cross43f08db2018-11-12 10:13:39 -0800363 FlagWithArg("--instruction-set-variant=", global.CpuVariant[arch]).
364 FlagWithArg("--instruction-set-features=", global.InstructionSetFeatures[arch]).
365 Flag("--no-generate-debug-info").
366 Flag("--generate-build-id").
367 Flag("--abort-on-hard-verifier-error").
368 Flag("--force-determinism").
369 FlagWithArg("--no-inline-from=", "core-oj.jar")
370
371 var preoptFlags []string
372 if len(module.PreoptFlags) > 0 {
373 preoptFlags = module.PreoptFlags
374 } else if len(global.PreoptFlags) > 0 {
375 preoptFlags = global.PreoptFlags
376 }
377
378 if len(preoptFlags) > 0 {
379 cmd.Text(strings.Join(preoptFlags, " "))
380 }
381
382 if module.UncompressedDex {
383 cmd.FlagWithArg("--copy-dex-files=", "false")
384 }
385
386 if !anyHavePrefix(preoptFlags, "--compiler-filter=") {
387 var compilerFilter string
388 if contains(global.SystemServerJars, module.Name) {
389 // Jars of system server, use the product option if it is set, speed otherwise.
390 if global.SystemServerCompilerFilter != "" {
391 compilerFilter = global.SystemServerCompilerFilter
392 } else {
393 compilerFilter = "speed"
394 }
395 } else if contains(global.SpeedApps, module.Name) || contains(global.SystemServerApps, module.Name) {
396 // Apps loaded into system server, and apps the product default to being compiled with the
397 // 'speed' compiler filter.
398 compilerFilter = "speed"
Colin Cross69f59a32019-02-15 10:39:37 -0800399 } else if profile != nil {
Colin Cross43f08db2018-11-12 10:13:39 -0800400 // For non system server jars, use speed-profile when we have a profile.
401 compilerFilter = "speed-profile"
402 } else if global.DefaultCompilerFilter != "" {
403 compilerFilter = global.DefaultCompilerFilter
404 } else {
405 compilerFilter = "quicken"
406 }
407 cmd.FlagWithArg("--compiler-filter=", compilerFilter)
408 }
409
410 if generateDM {
411 cmd.FlagWithArg("--copy-dex-files=", "false")
Colin Cross69f59a32019-02-15 10:39:37 -0800412 dmPath := module.BuildPath.InSameDir(ctx, "generated.dm")
Colin Cross43f08db2018-11-12 10:13:39 -0800413 dmInstalledPath := pathtools.ReplaceExtension(module.DexLocation, "dm")
Colin Cross69f59a32019-02-15 10:39:37 -0800414 tmpPath := module.BuildPath.InSameDir(ctx, "primary.vdex")
Colin Cross43f08db2018-11-12 10:13:39 -0800415 rule.Command().Text("cp -f").Input(vdexPath).Output(tmpPath)
416 rule.Command().Tool(global.Tools.SoongZip).
417 FlagWithArg("-L", "9").
418 FlagWithOutput("-o", dmPath).
419 Flag("-j").
420 Input(tmpPath)
421 rule.Install(dmPath, dmInstalledPath)
422 }
423
424 // By default, emit debug info.
425 debugInfo := true
426 if global.NoDebugInfo {
427 // If the global setting suppresses mini-debug-info, disable it.
428 debugInfo = false
429 }
430
431 // PRODUCT_SYSTEM_SERVER_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO.
432 // PRODUCT_OTHER_JAVA_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO.
433 if contains(global.SystemServerJars, module.Name) {
434 if global.AlwaysSystemServerDebugInfo {
435 debugInfo = true
436 } else if global.NeverSystemServerDebugInfo {
437 debugInfo = false
438 }
439 } else {
440 if global.AlwaysOtherDebugInfo {
441 debugInfo = true
442 } else if global.NeverOtherDebugInfo {
443 debugInfo = false
444 }
445 }
446
447 // Never enable on eng.
448 if global.IsEng {
449 debugInfo = false
450 }
451
452 if debugInfo {
453 cmd.Flag("--generate-mini-debug-info")
454 } else {
455 cmd.Flag("--no-generate-mini-debug-info")
456 }
457
458 // Set the compiler reason to 'prebuilt' to identify the oat files produced
459 // during the build, as opposed to compiled on the device.
460 cmd.FlagWithArg("--compilation-reason=", "prebuilt")
461
462 if appImage {
Colin Cross69f59a32019-02-15 10:39:37 -0800463 appImagePath := odexPath.ReplaceExtension(ctx, "art")
Colin Cross43f08db2018-11-12 10:13:39 -0800464 appImageInstallPath := pathtools.ReplaceExtension(odexInstallPath, "art")
465 cmd.FlagWithOutput("--app-image-file=", appImagePath).
466 FlagWithArg("--image-format=", "lz4")
Mathieu Chartier3f7ddbb2019-04-29 09:33:50 -0700467 if !global.DontResolveStartupStrings {
468 cmd.FlagWithArg("--resolve-startup-const-strings=", "true")
469 }
Colin Cross43f08db2018-11-12 10:13:39 -0800470 rule.Install(appImagePath, appImageInstallPath)
471 }
472
Colin Cross69f59a32019-02-15 10:39:37 -0800473 if profile != nil {
474 cmd.FlagWithInput("--profile-file=", profile)
Colin Cross43f08db2018-11-12 10:13:39 -0800475 }
476
477 rule.Install(odexPath, odexInstallPath)
478 rule.Install(vdexPath, vdexInstallPath)
479}
480
481// Return if the dex file in the APK should be stripped. If an APK is found to contain uncompressed dex files at
482// dex2oat time it will not be stripped even if strip=true.
483func shouldStripDex(module ModuleConfig, global GlobalConfig) bool {
484 strip := !global.DefaultNoStripping
485
Colin Crosscbed6572019-01-08 17:38:37 -0800486 if dexpreoptDisabled(global, module) {
487 strip = false
488 }
489
Colin Cross8c6d2502019-01-09 21:09:14 -0800490 if module.NoStripping {
491 strip = false
492 }
493
Colin Cross43f08db2018-11-12 10:13:39 -0800494 // Don't strip modules that are not on the system partition in case the oat/vdex version in system ROM
495 // doesn't match the one in other partitions. It needs to be able to fall back to the APK for that case.
496 if !strings.HasPrefix(module.DexLocation, SystemPartition) {
497 strip = false
498 }
499
500 // system_other isn't there for an OTA, so don't strip if module is on system, and odex is on system_other.
501 if odexOnSystemOther(module, global) {
502 strip = false
503 }
504
505 if module.HasApkLibraries {
506 strip = false
507 }
508
509 // Don't strip with dex files we explicitly uncompress (dexopt will not store the dex code).
510 if module.UncompressedDex {
511 strip = false
512 }
513
514 if shouldGenerateDM(module, global) {
515 strip = false
516 }
517
518 if module.PresignedPrebuilt {
519 // Only strip out files if we can re-sign the package.
520 strip = false
521 }
522
523 return strip
524}
525
526func shouldGenerateDM(module ModuleConfig, global GlobalConfig) bool {
527 // Generating DM files only makes sense for verify, avoid doing for non verify compiler filter APKs.
528 // No reason to use a dm file if the dex is already uncompressed.
529 return global.GenerateDMFiles && !module.UncompressedDex &&
530 contains(module.PreoptFlags, "--compiler-filter=verify")
531}
532
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000533func OdexOnSystemOtherByName(name string, dexLocation string, global GlobalConfig) bool {
Colin Cross43f08db2018-11-12 10:13:39 -0800534 if !global.HasSystemOther {
535 return false
536 }
537
538 if global.SanitizeLite {
539 return false
540 }
541
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000542 if contains(global.SpeedApps, name) || contains(global.SystemServerApps, name) {
Colin Cross43f08db2018-11-12 10:13:39 -0800543 return false
544 }
545
546 for _, f := range global.PatternsOnSystemOther {
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000547 if makefileMatch(filepath.Join(SystemPartition, f), dexLocation) {
Colin Cross43f08db2018-11-12 10:13:39 -0800548 return true
549 }
550 }
551
552 return false
553}
554
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000555func odexOnSystemOther(module ModuleConfig, global GlobalConfig) bool {
556 return OdexOnSystemOtherByName(module.Name, module.DexLocation, global)
557}
558
Colin Crossc7e40aa2019-02-08 21:37:00 -0800559// PathToLocation converts .../system/framework/arm64/boot.art to .../system/framework/boot.art
Colin Cross69f59a32019-02-15 10:39:37 -0800560func PathToLocation(path android.Path, arch android.ArchType) string {
561 pathArch := filepath.Base(filepath.Dir(path.String()))
Colin Cross74ba9622019-02-11 15:11:14 -0800562 if pathArch != arch.String() {
563 panic(fmt.Errorf("last directory in %q must be %q", path, arch.String()))
Colin Crossc7e40aa2019-02-08 21:37:00 -0800564 }
Colin Cross69f59a32019-02-15 10:39:37 -0800565 return filepath.Join(filepath.Dir(filepath.Dir(path.String())), filepath.Base(path.String()))
Colin Crossc7e40aa2019-02-08 21:37:00 -0800566}
567
Colin Cross69f59a32019-02-15 10:39:37 -0800568func pathForLibrary(module ModuleConfig, lib string) android.Path {
569 path, ok := module.LibraryPaths[lib]
570 if !ok {
Colin Cross43f08db2018-11-12 10:13:39 -0800571 panic(fmt.Errorf("unknown library path for %q", lib))
572 }
573 return path
574}
575
576func makefileMatch(pattern, s string) bool {
577 percent := strings.IndexByte(pattern, '%')
578 switch percent {
579 case -1:
580 return pattern == s
581 case len(pattern) - 1:
582 return strings.HasPrefix(s, pattern[:len(pattern)-1])
583 default:
584 panic(fmt.Errorf("unsupported makefile pattern %q", pattern))
585 }
586}
587
588func contains(l []string, s string) bool {
589 for _, e := range l {
590 if e == s {
591 return true
592 }
593 }
594 return false
595}
596
597// remove all elements in a from b, returning a new slice
598func filterOut(a []string, b []string) []string {
599 var ret []string
600 for _, x := range b {
601 if !contains(a, x) {
602 ret = append(ret, x)
603 }
604 }
605 return ret
606}
607
608func replace(l []string, from, to string) {
609 for i := range l {
610 if l[i] == from {
611 l[i] = to
612 }
613 }
614}
615
Colin Cross454c0872019-02-15 23:03:34 -0800616var copyOf = android.CopyOf
Colin Cross43f08db2018-11-12 10:13:39 -0800617
618func anyHavePrefix(l []string, prefix string) bool {
619 for _, x := range l {
620 if strings.HasPrefix(x, prefix) {
621 return true
622 }
623 }
624 return false
625}