blob: 2d521dab571ba48cae9ee54e1c33629603e2d52f [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 Crossc0324982019-05-29 20:28:47 +0000229 // Lists of used and optional libraries from the build config, with optional libraries that are known to not
230 // be present in the current product removed.
231 var filteredUsesLibs []string
232 var filteredOptionalUsesLibs []string
233
Colin Cross43f08db2018-11-12 10:13:39 -0800234 // The class loader context using paths in the build
Colin Cross69f59a32019-02-15 10:39:37 -0800235 var classLoaderContextHost android.Paths
Colin Cross43f08db2018-11-12 10:13:39 -0800236
237 // The class loader context using paths as they will be on the device
238 var classLoaderContextTarget []string
239
240 // Extra paths that will be appended to the class loader if the APK manifest has targetSdkVersion < 28
Colin Cross69f59a32019-02-15 10:39:37 -0800241 var conditionalClassLoaderContextHost28 android.Paths
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000242 var conditionalClassLoaderContextTarget28 []string
243
244 // Extra paths that will be appended to the class loader if the APK manifest has targetSdkVersion < 29
Colin Cross69f59a32019-02-15 10:39:37 -0800245 var conditionalClassLoaderContextHost29 android.Paths
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000246 var conditionalClassLoaderContextTarget29 []string
Colin Cross43f08db2018-11-12 10:13:39 -0800247
Colin Cross69f59a32019-02-15 10:39:37 -0800248 var classLoaderContextHostString string
249
Colin Cross43f08db2018-11-12 10:13:39 -0800250 if module.EnforceUsesLibraries {
Colin Crossc0324982019-05-29 20:28:47 +0000251 filteredOptionalUsesLibs = filterOut(global.MissingUsesLibraries, module.OptionalUsesLibraries)
252 filteredUsesLibs = append(copyOf(module.UsesLibraries), filteredOptionalUsesLibs...)
Colin Cross43f08db2018-11-12 10:13:39 -0800253
254 // Create class loader context for dex2oat from uses libraries and filtered optional libraries
Colin Crossc0324982019-05-29 20:28:47 +0000255 for _, l := range filteredUsesLibs {
Colin Cross43f08db2018-11-12 10:13:39 -0800256
257 classLoaderContextHost = append(classLoaderContextHost,
258 pathForLibrary(module, l))
259 classLoaderContextTarget = append(classLoaderContextTarget,
260 filepath.Join("/system/framework", l+".jar"))
261 }
262
263 const httpLegacy = "org.apache.http.legacy"
264 const httpLegacyImpl = "org.apache.http.legacy.impl"
265
Colin Cross38b96852019-05-22 10:21:09 -0700266 // org.apache.http.legacy contains classes that were in the default classpath until API 28. If the
267 // targetSdkVersion in the manifest or APK is < 28, and the module does not explicitly depend on
268 // org.apache.http.legacy, then implicitly add the classes to the classpath for dexpreopt. One the
269 // device the classes will be in a file called org.apache.http.legacy.impl.jar.
Colin Crossc0324982019-05-29 20:28:47 +0000270 if !contains(module.UsesLibraries, httpLegacy) && !contains(module.OptionalUsesLibraries, httpLegacy) {
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000271 conditionalClassLoaderContextHost28 = append(conditionalClassLoaderContextHost28,
Colin Cross43f08db2018-11-12 10:13:39 -0800272 pathForLibrary(module, httpLegacyImpl))
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000273 conditionalClassLoaderContextTarget28 = append(conditionalClassLoaderContextTarget28,
Colin Cross43f08db2018-11-12 10:13:39 -0800274 filepath.Join("/system/framework", httpLegacyImpl+".jar"))
275 }
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000276
277 const hidlBase = "android.hidl.base-V1.0-java"
278 const hidlManager = "android.hidl.manager-V1.0-java"
279
Colin Cross38b96852019-05-22 10:21:09 -0700280 // android.hidl.base-V1.0-java and android.hidl.manager-V1.0 contain classes that were in the default
281 // classpath until API 29. If the targetSdkVersion in the manifest or APK is < 29 then implicitly add
282 // the classes to the classpath for dexpreopt.
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000283 conditionalClassLoaderContextHost29 = append(conditionalClassLoaderContextHost29,
Alex Light5de41962018-12-18 15:16:26 -0800284 pathForLibrary(module, hidlManager))
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000285 conditionalClassLoaderContextTarget29 = append(conditionalClassLoaderContextTarget29,
286 filepath.Join("/system/framework", hidlManager+".jar"))
287 conditionalClassLoaderContextHost29 = append(conditionalClassLoaderContextHost29,
Alex Light5de41962018-12-18 15:16:26 -0800288 pathForLibrary(module, hidlBase))
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000289 conditionalClassLoaderContextTarget29 = append(conditionalClassLoaderContextTarget29,
290 filepath.Join("/system/framework", hidlBase+".jar"))
Colin Cross69f59a32019-02-15 10:39:37 -0800291
292 classLoaderContextHostString = strings.Join(classLoaderContextHost.Strings(), ":")
Colin Cross43f08db2018-11-12 10:13:39 -0800293 } else {
294 // Pass special class loader context to skip the classpath and collision check.
295 // This will get removed once LOCAL_USES_LIBRARIES is enforced.
296 // Right now LOCAL_USES_LIBRARIES is opt in, for the case where it's not specified we still default
297 // to the &.
Colin Cross69f59a32019-02-15 10:39:37 -0800298 classLoaderContextHostString = `\&`
Colin Cross43f08db2018-11-12 10:13:39 -0800299 }
300
Colin Cross69f59a32019-02-15 10:39:37 -0800301 rule.Command().FlagWithArg("mkdir -p ", filepath.Dir(odexPath.String()))
Colin Cross43f08db2018-11-12 10:13:39 -0800302 rule.Command().FlagWithOutput("rm -f ", odexPath)
303 // Set values in the environment of the rule. These may be modified by construct_context.sh.
Colin Cross69f59a32019-02-15 10:39:37 -0800304 rule.Command().FlagWithArg("class_loader_context_arg=--class-loader-context=", classLoaderContextHostString)
Colin Cross43f08db2018-11-12 10:13:39 -0800305 rule.Command().Text(`stored_class_loader_context_arg=""`)
306
307 if module.EnforceUsesLibraries {
Colin Cross38b96852019-05-22 10:21:09 -0700308 if module.ManifestPath != nil {
309 rule.Command().Text(`target_sdk_version="$(`).
310 Tool(global.Tools.ManifestCheck).
311 Flag("--extract-target-sdk-version").
312 Input(module.ManifestPath).
313 Text(`)"`)
314 } else {
315 // No manifest to extract targetSdkVersion from, hope that DexJar is an APK
316 rule.Command().Text(`target_sdk_version="$(`).
317 Tool(global.Tools.Aapt).
318 Flag("dump badging").
319 Input(module.DexPath).
320 Text(`| grep "targetSdkVersion" | sed -n "s/targetSdkVersion:'\(.*\)'/\1/p"`).
321 Text(`)"`)
322 }
Colin Cross69f59a32019-02-15 10:39:37 -0800323 rule.Command().Textf(`dex_preopt_host_libraries="%s"`,
324 strings.Join(classLoaderContextHost.Strings(), " ")).
325 Implicits(classLoaderContextHost)
326 rule.Command().Textf(`dex_preopt_target_libraries="%s"`,
327 strings.Join(classLoaderContextTarget, " "))
328 rule.Command().Textf(`conditional_host_libs_28="%s"`,
329 strings.Join(conditionalClassLoaderContextHost28.Strings(), " ")).
330 Implicits(conditionalClassLoaderContextHost28)
331 rule.Command().Textf(`conditional_target_libs_28="%s"`,
332 strings.Join(conditionalClassLoaderContextTarget28, " "))
333 rule.Command().Textf(`conditional_host_libs_29="%s"`,
334 strings.Join(conditionalClassLoaderContextHost29.Strings(), " ")).
335 Implicits(conditionalClassLoaderContextHost29)
336 rule.Command().Textf(`conditional_target_libs_29="%s"`,
337 strings.Join(conditionalClassLoaderContextTarget29, " "))
Colin Cross38b96852019-05-22 10:21:09 -0700338 rule.Command().Text("source").Tool(global.Tools.ConstructContext).Input(module.DexPath)
Colin Cross43f08db2018-11-12 10:13:39 -0800339 }
340
Nicolas Geoffray2464ef42019-03-05 14:07:07 +0000341 // Devices that do not have a product partition use a symlink from /product to /system/product.
342 // Because on-device dexopt will see dex locations starting with /product, we change the paths
343 // to mimic this behavior.
344 dexLocationArg := module.DexLocation
345 if strings.HasPrefix(dexLocationArg, "/system/product/") {
346 dexLocationArg = strings.TrimPrefix(dexLocationArg, "/system")
347 }
348
Colin Cross43f08db2018-11-12 10:13:39 -0800349 cmd := rule.Command().
350 Text(`ANDROID_LOG_TAGS="*:e"`).
351 Tool(global.Tools.Dex2oat).
352 Flag("--avoid-storing-invocation").
Alex Light5de41962018-12-18 15:16:26 -0800353 FlagWithOutput("--write-invocation-to=", invocationPath).ImplicitOutput(invocationPath).
Colin Cross43f08db2018-11-12 10:13:39 -0800354 Flag("--runtime-arg").FlagWithArg("-Xms", global.Dex2oatXms).
355 Flag("--runtime-arg").FlagWithArg("-Xmx", global.Dex2oatXmx).
Colin Cross800fe132019-02-11 14:21:24 -0800356 Flag("--runtime-arg").FlagWithInputList("-Xbootclasspath:", module.PreoptBootClassPathDexFiles, ":").
357 Flag("--runtime-arg").FlagWithList("-Xbootclasspath-locations:", module.PreoptBootClassPathDexLocations, ":").
Colin Cross43f08db2018-11-12 10:13:39 -0800358 Flag("${class_loader_context_arg}").
359 Flag("${stored_class_loader_context_arg}").
Colin Crossc7e40aa2019-02-08 21:37:00 -0800360 FlagWithArg("--boot-image=", bootImageLocation).Implicit(bootImage).
Colin Cross43f08db2018-11-12 10:13:39 -0800361 FlagWithInput("--dex-file=", module.DexPath).
Nicolas Geoffray2464ef42019-03-05 14:07:07 +0000362 FlagWithArg("--dex-location=", dexLocationArg).
Colin Cross43f08db2018-11-12 10:13:39 -0800363 FlagWithOutput("--oat-file=", odexPath).ImplicitOutput(vdexPath).
364 // Pass an empty directory, dex2oat shouldn't be reading arbitrary files
365 FlagWithArg("--android-root=", global.EmptyDirectory).
Colin Cross74ba9622019-02-11 15:11:14 -0800366 FlagWithArg("--instruction-set=", arch.String()).
Colin Cross43f08db2018-11-12 10:13:39 -0800367 FlagWithArg("--instruction-set-variant=", global.CpuVariant[arch]).
368 FlagWithArg("--instruction-set-features=", global.InstructionSetFeatures[arch]).
369 Flag("--no-generate-debug-info").
370 Flag("--generate-build-id").
371 Flag("--abort-on-hard-verifier-error").
372 Flag("--force-determinism").
373 FlagWithArg("--no-inline-from=", "core-oj.jar")
374
375 var preoptFlags []string
376 if len(module.PreoptFlags) > 0 {
377 preoptFlags = module.PreoptFlags
378 } else if len(global.PreoptFlags) > 0 {
379 preoptFlags = global.PreoptFlags
380 }
381
382 if len(preoptFlags) > 0 {
383 cmd.Text(strings.Join(preoptFlags, " "))
384 }
385
386 if module.UncompressedDex {
387 cmd.FlagWithArg("--copy-dex-files=", "false")
388 }
389
390 if !anyHavePrefix(preoptFlags, "--compiler-filter=") {
391 var compilerFilter string
392 if contains(global.SystemServerJars, module.Name) {
393 // Jars of system server, use the product option if it is set, speed otherwise.
394 if global.SystemServerCompilerFilter != "" {
395 compilerFilter = global.SystemServerCompilerFilter
396 } else {
397 compilerFilter = "speed"
398 }
399 } else if contains(global.SpeedApps, module.Name) || contains(global.SystemServerApps, module.Name) {
400 // Apps loaded into system server, and apps the product default to being compiled with the
401 // 'speed' compiler filter.
402 compilerFilter = "speed"
Colin Cross69f59a32019-02-15 10:39:37 -0800403 } else if profile != nil {
Colin Cross43f08db2018-11-12 10:13:39 -0800404 // For non system server jars, use speed-profile when we have a profile.
405 compilerFilter = "speed-profile"
406 } else if global.DefaultCompilerFilter != "" {
407 compilerFilter = global.DefaultCompilerFilter
408 } else {
409 compilerFilter = "quicken"
410 }
411 cmd.FlagWithArg("--compiler-filter=", compilerFilter)
412 }
413
414 if generateDM {
415 cmd.FlagWithArg("--copy-dex-files=", "false")
Colin Cross69f59a32019-02-15 10:39:37 -0800416 dmPath := module.BuildPath.InSameDir(ctx, "generated.dm")
Colin Cross43f08db2018-11-12 10:13:39 -0800417 dmInstalledPath := pathtools.ReplaceExtension(module.DexLocation, "dm")
Colin Cross69f59a32019-02-15 10:39:37 -0800418 tmpPath := module.BuildPath.InSameDir(ctx, "primary.vdex")
Colin Cross43f08db2018-11-12 10:13:39 -0800419 rule.Command().Text("cp -f").Input(vdexPath).Output(tmpPath)
420 rule.Command().Tool(global.Tools.SoongZip).
421 FlagWithArg("-L", "9").
422 FlagWithOutput("-o", dmPath).
423 Flag("-j").
424 Input(tmpPath)
425 rule.Install(dmPath, dmInstalledPath)
426 }
427
428 // By default, emit debug info.
429 debugInfo := true
430 if global.NoDebugInfo {
431 // If the global setting suppresses mini-debug-info, disable it.
432 debugInfo = false
433 }
434
435 // PRODUCT_SYSTEM_SERVER_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO.
436 // PRODUCT_OTHER_JAVA_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO.
437 if contains(global.SystemServerJars, module.Name) {
438 if global.AlwaysSystemServerDebugInfo {
439 debugInfo = true
440 } else if global.NeverSystemServerDebugInfo {
441 debugInfo = false
442 }
443 } else {
444 if global.AlwaysOtherDebugInfo {
445 debugInfo = true
446 } else if global.NeverOtherDebugInfo {
447 debugInfo = false
448 }
449 }
450
451 // Never enable on eng.
452 if global.IsEng {
453 debugInfo = false
454 }
455
456 if debugInfo {
457 cmd.Flag("--generate-mini-debug-info")
458 } else {
459 cmd.Flag("--no-generate-mini-debug-info")
460 }
461
462 // Set the compiler reason to 'prebuilt' to identify the oat files produced
463 // during the build, as opposed to compiled on the device.
464 cmd.FlagWithArg("--compilation-reason=", "prebuilt")
465
466 if appImage {
Colin Cross69f59a32019-02-15 10:39:37 -0800467 appImagePath := odexPath.ReplaceExtension(ctx, "art")
Colin Cross43f08db2018-11-12 10:13:39 -0800468 appImageInstallPath := pathtools.ReplaceExtension(odexInstallPath, "art")
469 cmd.FlagWithOutput("--app-image-file=", appImagePath).
470 FlagWithArg("--image-format=", "lz4")
Mathieu Chartier3f7ddbb2019-04-29 09:33:50 -0700471 if !global.DontResolveStartupStrings {
472 cmd.FlagWithArg("--resolve-startup-const-strings=", "true")
473 }
Colin Cross43f08db2018-11-12 10:13:39 -0800474 rule.Install(appImagePath, appImageInstallPath)
475 }
476
Colin Cross69f59a32019-02-15 10:39:37 -0800477 if profile != nil {
478 cmd.FlagWithInput("--profile-file=", profile)
Colin Cross43f08db2018-11-12 10:13:39 -0800479 }
480
481 rule.Install(odexPath, odexInstallPath)
482 rule.Install(vdexPath, vdexInstallPath)
483}
484
485// Return if the dex file in the APK should be stripped. If an APK is found to contain uncompressed dex files at
486// dex2oat time it will not be stripped even if strip=true.
487func shouldStripDex(module ModuleConfig, global GlobalConfig) bool {
488 strip := !global.DefaultNoStripping
489
Colin Crosscbed6572019-01-08 17:38:37 -0800490 if dexpreoptDisabled(global, module) {
491 strip = false
492 }
493
Colin Cross8c6d2502019-01-09 21:09:14 -0800494 if module.NoStripping {
495 strip = false
496 }
497
Colin Cross43f08db2018-11-12 10:13:39 -0800498 // Don't strip modules that are not on the system partition in case the oat/vdex version in system ROM
499 // doesn't match the one in other partitions. It needs to be able to fall back to the APK for that case.
500 if !strings.HasPrefix(module.DexLocation, SystemPartition) {
501 strip = false
502 }
503
504 // system_other isn't there for an OTA, so don't strip if module is on system, and odex is on system_other.
505 if odexOnSystemOther(module, global) {
506 strip = false
507 }
508
509 if module.HasApkLibraries {
510 strip = false
511 }
512
513 // Don't strip with dex files we explicitly uncompress (dexopt will not store the dex code).
514 if module.UncompressedDex {
515 strip = false
516 }
517
518 if shouldGenerateDM(module, global) {
519 strip = false
520 }
521
522 if module.PresignedPrebuilt {
523 // Only strip out files if we can re-sign the package.
524 strip = false
525 }
526
527 return strip
528}
529
530func shouldGenerateDM(module ModuleConfig, global GlobalConfig) bool {
531 // Generating DM files only makes sense for verify, avoid doing for non verify compiler filter APKs.
532 // No reason to use a dm file if the dex is already uncompressed.
533 return global.GenerateDMFiles && !module.UncompressedDex &&
534 contains(module.PreoptFlags, "--compiler-filter=verify")
535}
536
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000537func OdexOnSystemOtherByName(name string, dexLocation string, global GlobalConfig) bool {
Colin Cross43f08db2018-11-12 10:13:39 -0800538 if !global.HasSystemOther {
539 return false
540 }
541
542 if global.SanitizeLite {
543 return false
544 }
545
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000546 if contains(global.SpeedApps, name) || contains(global.SystemServerApps, name) {
Colin Cross43f08db2018-11-12 10:13:39 -0800547 return false
548 }
549
550 for _, f := range global.PatternsOnSystemOther {
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000551 if makefileMatch(filepath.Join(SystemPartition, f), dexLocation) {
Colin Cross43f08db2018-11-12 10:13:39 -0800552 return true
553 }
554 }
555
556 return false
557}
558
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000559func odexOnSystemOther(module ModuleConfig, global GlobalConfig) bool {
560 return OdexOnSystemOtherByName(module.Name, module.DexLocation, global)
561}
562
Colin Crossc7e40aa2019-02-08 21:37:00 -0800563// PathToLocation converts .../system/framework/arm64/boot.art to .../system/framework/boot.art
Colin Cross69f59a32019-02-15 10:39:37 -0800564func PathToLocation(path android.Path, arch android.ArchType) string {
565 pathArch := filepath.Base(filepath.Dir(path.String()))
Colin Cross74ba9622019-02-11 15:11:14 -0800566 if pathArch != arch.String() {
567 panic(fmt.Errorf("last directory in %q must be %q", path, arch.String()))
Colin Crossc7e40aa2019-02-08 21:37:00 -0800568 }
Colin Cross69f59a32019-02-15 10:39:37 -0800569 return filepath.Join(filepath.Dir(filepath.Dir(path.String())), filepath.Base(path.String()))
Colin Crossc7e40aa2019-02-08 21:37:00 -0800570}
571
Colin Cross69f59a32019-02-15 10:39:37 -0800572func pathForLibrary(module ModuleConfig, lib string) android.Path {
573 path, ok := module.LibraryPaths[lib]
574 if !ok {
Colin Cross43f08db2018-11-12 10:13:39 -0800575 panic(fmt.Errorf("unknown library path for %q", lib))
576 }
577 return path
578}
579
580func makefileMatch(pattern, s string) bool {
581 percent := strings.IndexByte(pattern, '%')
582 switch percent {
583 case -1:
584 return pattern == s
585 case len(pattern) - 1:
586 return strings.HasPrefix(s, pattern[:len(pattern)-1])
587 default:
588 panic(fmt.Errorf("unsupported makefile pattern %q", pattern))
589 }
590}
591
592func contains(l []string, s string) bool {
593 for _, e := range l {
594 if e == s {
595 return true
596 }
597 }
598 return false
599}
600
601// remove all elements in a from b, returning a new slice
602func filterOut(a []string, b []string) []string {
603 var ret []string
604 for _, x := range b {
605 if !contains(a, x) {
606 ret = append(ret, x)
607 }
608 }
609 return ret
610}
611
612func replace(l []string, from, to string) {
613 for i := range l {
614 if l[i] == from {
615 l[i] = to
616 }
617 }
618}
619
Colin Cross454c0872019-02-15 23:03:34 -0800620var copyOf = android.CopyOf
Colin Cross43f08db2018-11-12 10:13:39 -0800621
622func anyHavePrefix(l []string, prefix string) bool {
623 for _, x := range l {
624 if strings.HasPrefix(x, prefix) {
625 return true
626 }
627 }
628 return false
629}