blob: 9e333c108da286d5d6596182b52998d17c6b7c82 [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
229 // Lists of used and optional libraries from the build config to be verified against the manifest in the APK
230 var verifyUsesLibs []string
231 var verifyOptionalUsesLibs []string
232
233 // Lists of used and optional libraries from the build config, with optional libraries that are known to not
234 // be present in the current product removed.
235 var filteredUsesLibs []string
236 var filteredOptionalUsesLibs []string
237
238 // The class loader context using paths in the build
Colin Cross69f59a32019-02-15 10:39:37 -0800239 var classLoaderContextHost android.Paths
Colin Cross43f08db2018-11-12 10:13:39 -0800240
241 // The class loader context using paths as they will be on the device
242 var classLoaderContextTarget []string
243
244 // Extra paths that will be appended to the class loader if the APK manifest has targetSdkVersion < 28
Colin Cross69f59a32019-02-15 10:39:37 -0800245 var conditionalClassLoaderContextHost28 android.Paths
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000246 var conditionalClassLoaderContextTarget28 []string
247
248 // Extra paths that will be appended to the class loader if the APK manifest has targetSdkVersion < 29
Colin Cross69f59a32019-02-15 10:39:37 -0800249 var conditionalClassLoaderContextHost29 android.Paths
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000250 var conditionalClassLoaderContextTarget29 []string
Colin Cross43f08db2018-11-12 10:13:39 -0800251
Colin Cross69f59a32019-02-15 10:39:37 -0800252 var classLoaderContextHostString string
253
Colin Cross43f08db2018-11-12 10:13:39 -0800254 if module.EnforceUsesLibraries {
255 verifyUsesLibs = copyOf(module.UsesLibraries)
256 verifyOptionalUsesLibs = copyOf(module.OptionalUsesLibraries)
257
258 filteredOptionalUsesLibs = filterOut(global.MissingUsesLibraries, module.OptionalUsesLibraries)
259 filteredUsesLibs = append(copyOf(module.UsesLibraries), filteredOptionalUsesLibs...)
260
261 // Create class loader context for dex2oat from uses libraries and filtered optional libraries
262 for _, l := range filteredUsesLibs {
263
264 classLoaderContextHost = append(classLoaderContextHost,
265 pathForLibrary(module, l))
266 classLoaderContextTarget = append(classLoaderContextTarget,
267 filepath.Join("/system/framework", l+".jar"))
268 }
269
270 const httpLegacy = "org.apache.http.legacy"
271 const httpLegacyImpl = "org.apache.http.legacy.impl"
272
273 // Fix up org.apache.http.legacy.impl since it should be org.apache.http.legacy in the manifest.
274 replace(verifyUsesLibs, httpLegacyImpl, httpLegacy)
275 replace(verifyOptionalUsesLibs, httpLegacyImpl, httpLegacy)
276
277 if !contains(verifyUsesLibs, httpLegacy) && !contains(verifyOptionalUsesLibs, httpLegacy) {
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000278 conditionalClassLoaderContextHost28 = append(conditionalClassLoaderContextHost28,
Colin Cross43f08db2018-11-12 10:13:39 -0800279 pathForLibrary(module, httpLegacyImpl))
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000280 conditionalClassLoaderContextTarget28 = append(conditionalClassLoaderContextTarget28,
Colin Cross43f08db2018-11-12 10:13:39 -0800281 filepath.Join("/system/framework", httpLegacyImpl+".jar"))
282 }
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000283
284 const hidlBase = "android.hidl.base-V1.0-java"
285 const hidlManager = "android.hidl.manager-V1.0-java"
286
287 conditionalClassLoaderContextHost29 = append(conditionalClassLoaderContextHost29,
Alex Light5de41962018-12-18 15:16:26 -0800288 pathForLibrary(module, hidlManager))
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000289 conditionalClassLoaderContextTarget29 = append(conditionalClassLoaderContextTarget29,
290 filepath.Join("/system/framework", hidlManager+".jar"))
291 conditionalClassLoaderContextHost29 = append(conditionalClassLoaderContextHost29,
Alex Light5de41962018-12-18 15:16:26 -0800292 pathForLibrary(module, hidlBase))
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000293 conditionalClassLoaderContextTarget29 = append(conditionalClassLoaderContextTarget29,
294 filepath.Join("/system/framework", hidlBase+".jar"))
Colin Cross69f59a32019-02-15 10:39:37 -0800295
296 classLoaderContextHostString = strings.Join(classLoaderContextHost.Strings(), ":")
Colin Cross43f08db2018-11-12 10:13:39 -0800297 } else {
298 // Pass special class loader context to skip the classpath and collision check.
299 // This will get removed once LOCAL_USES_LIBRARIES is enforced.
300 // Right now LOCAL_USES_LIBRARIES is opt in, for the case where it's not specified we still default
301 // to the &.
Colin Cross69f59a32019-02-15 10:39:37 -0800302 classLoaderContextHostString = `\&`
Colin Cross43f08db2018-11-12 10:13:39 -0800303 }
304
Colin Cross69f59a32019-02-15 10:39:37 -0800305 rule.Command().FlagWithArg("mkdir -p ", filepath.Dir(odexPath.String()))
Colin Cross43f08db2018-11-12 10:13:39 -0800306 rule.Command().FlagWithOutput("rm -f ", odexPath)
307 // Set values in the environment of the rule. These may be modified by construct_context.sh.
Colin Cross69f59a32019-02-15 10:39:37 -0800308 rule.Command().FlagWithArg("class_loader_context_arg=--class-loader-context=", classLoaderContextHostString)
Colin Cross43f08db2018-11-12 10:13:39 -0800309 rule.Command().Text(`stored_class_loader_context_arg=""`)
310
311 if module.EnforceUsesLibraries {
Colin Cross43f08db2018-11-12 10:13:39 -0800312 rule.Command().Textf(`uses_library_names="%s"`, strings.Join(verifyUsesLibs, " "))
313 rule.Command().Textf(`optional_uses_library_names="%s"`, strings.Join(verifyOptionalUsesLibs, " "))
314 rule.Command().Textf(`aapt_binary="%s"`, global.Tools.Aapt)
Colin Cross69f59a32019-02-15 10:39:37 -0800315 rule.Command().Textf(`dex_preopt_host_libraries="%s"`,
316 strings.Join(classLoaderContextHost.Strings(), " ")).
317 Implicits(classLoaderContextHost)
318 rule.Command().Textf(`dex_preopt_target_libraries="%s"`,
319 strings.Join(classLoaderContextTarget, " "))
320 rule.Command().Textf(`conditional_host_libs_28="%s"`,
321 strings.Join(conditionalClassLoaderContextHost28.Strings(), " ")).
322 Implicits(conditionalClassLoaderContextHost28)
323 rule.Command().Textf(`conditional_target_libs_28="%s"`,
324 strings.Join(conditionalClassLoaderContextTarget28, " "))
325 rule.Command().Textf(`conditional_host_libs_29="%s"`,
326 strings.Join(conditionalClassLoaderContextHost29.Strings(), " ")).
327 Implicits(conditionalClassLoaderContextHost29)
328 rule.Command().Textf(`conditional_target_libs_29="%s"`,
329 strings.Join(conditionalClassLoaderContextTarget29, " "))
Colin Cross43f08db2018-11-12 10:13:39 -0800330 rule.Command().Text("source").Tool(global.Tools.VerifyUsesLibraries).Input(module.DexPath)
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000331 rule.Command().Text("source").Tool(global.Tools.ConstructContext)
Colin Cross43f08db2018-11-12 10:13:39 -0800332 }
333
334 cmd := rule.Command().
335 Text(`ANDROID_LOG_TAGS="*:e"`).
336 Tool(global.Tools.Dex2oat).
337 Flag("--avoid-storing-invocation").
Alex Light5de41962018-12-18 15:16:26 -0800338 FlagWithOutput("--write-invocation-to=", invocationPath).ImplicitOutput(invocationPath).
Colin Cross43f08db2018-11-12 10:13:39 -0800339 Flag("--runtime-arg").FlagWithArg("-Xms", global.Dex2oatXms).
340 Flag("--runtime-arg").FlagWithArg("-Xmx", global.Dex2oatXmx).
Colin Cross800fe132019-02-11 14:21:24 -0800341 Flag("--runtime-arg").FlagWithInputList("-Xbootclasspath:", module.PreoptBootClassPathDexFiles, ":").
342 Flag("--runtime-arg").FlagWithList("-Xbootclasspath-locations:", module.PreoptBootClassPathDexLocations, ":").
Colin Cross43f08db2018-11-12 10:13:39 -0800343 Flag("${class_loader_context_arg}").
344 Flag("${stored_class_loader_context_arg}").
Colin Crossc7e40aa2019-02-08 21:37:00 -0800345 FlagWithArg("--boot-image=", bootImageLocation).Implicit(bootImage).
Colin Cross43f08db2018-11-12 10:13:39 -0800346 FlagWithInput("--dex-file=", module.DexPath).
347 FlagWithArg("--dex-location=", module.DexLocation).
348 FlagWithOutput("--oat-file=", odexPath).ImplicitOutput(vdexPath).
349 // Pass an empty directory, dex2oat shouldn't be reading arbitrary files
350 FlagWithArg("--android-root=", global.EmptyDirectory).
Colin Cross74ba9622019-02-11 15:11:14 -0800351 FlagWithArg("--instruction-set=", arch.String()).
Colin Cross43f08db2018-11-12 10:13:39 -0800352 FlagWithArg("--instruction-set-variant=", global.CpuVariant[arch]).
353 FlagWithArg("--instruction-set-features=", global.InstructionSetFeatures[arch]).
354 Flag("--no-generate-debug-info").
355 Flag("--generate-build-id").
356 Flag("--abort-on-hard-verifier-error").
357 Flag("--force-determinism").
358 FlagWithArg("--no-inline-from=", "core-oj.jar")
359
360 var preoptFlags []string
361 if len(module.PreoptFlags) > 0 {
362 preoptFlags = module.PreoptFlags
363 } else if len(global.PreoptFlags) > 0 {
364 preoptFlags = global.PreoptFlags
365 }
366
367 if len(preoptFlags) > 0 {
368 cmd.Text(strings.Join(preoptFlags, " "))
369 }
370
371 if module.UncompressedDex {
372 cmd.FlagWithArg("--copy-dex-files=", "false")
373 }
374
375 if !anyHavePrefix(preoptFlags, "--compiler-filter=") {
376 var compilerFilter string
377 if contains(global.SystemServerJars, module.Name) {
378 // Jars of system server, use the product option if it is set, speed otherwise.
379 if global.SystemServerCompilerFilter != "" {
380 compilerFilter = global.SystemServerCompilerFilter
381 } else {
382 compilerFilter = "speed"
383 }
384 } else if contains(global.SpeedApps, module.Name) || contains(global.SystemServerApps, module.Name) {
385 // Apps loaded into system server, and apps the product default to being compiled with the
386 // 'speed' compiler filter.
387 compilerFilter = "speed"
Colin Cross69f59a32019-02-15 10:39:37 -0800388 } else if profile != nil {
Colin Cross43f08db2018-11-12 10:13:39 -0800389 // For non system server jars, use speed-profile when we have a profile.
390 compilerFilter = "speed-profile"
391 } else if global.DefaultCompilerFilter != "" {
392 compilerFilter = global.DefaultCompilerFilter
393 } else {
394 compilerFilter = "quicken"
395 }
396 cmd.FlagWithArg("--compiler-filter=", compilerFilter)
397 }
398
399 if generateDM {
400 cmd.FlagWithArg("--copy-dex-files=", "false")
Colin Cross69f59a32019-02-15 10:39:37 -0800401 dmPath := module.BuildPath.InSameDir(ctx, "generated.dm")
Colin Cross43f08db2018-11-12 10:13:39 -0800402 dmInstalledPath := pathtools.ReplaceExtension(module.DexLocation, "dm")
Colin Cross69f59a32019-02-15 10:39:37 -0800403 tmpPath := module.BuildPath.InSameDir(ctx, "primary.vdex")
Colin Cross43f08db2018-11-12 10:13:39 -0800404 rule.Command().Text("cp -f").Input(vdexPath).Output(tmpPath)
405 rule.Command().Tool(global.Tools.SoongZip).
406 FlagWithArg("-L", "9").
407 FlagWithOutput("-o", dmPath).
408 Flag("-j").
409 Input(tmpPath)
410 rule.Install(dmPath, dmInstalledPath)
411 }
412
413 // By default, emit debug info.
414 debugInfo := true
415 if global.NoDebugInfo {
416 // If the global setting suppresses mini-debug-info, disable it.
417 debugInfo = false
418 }
419
420 // PRODUCT_SYSTEM_SERVER_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO.
421 // PRODUCT_OTHER_JAVA_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO.
422 if contains(global.SystemServerJars, module.Name) {
423 if global.AlwaysSystemServerDebugInfo {
424 debugInfo = true
425 } else if global.NeverSystemServerDebugInfo {
426 debugInfo = false
427 }
428 } else {
429 if global.AlwaysOtherDebugInfo {
430 debugInfo = true
431 } else if global.NeverOtherDebugInfo {
432 debugInfo = false
433 }
434 }
435
436 // Never enable on eng.
437 if global.IsEng {
438 debugInfo = false
439 }
440
441 if debugInfo {
442 cmd.Flag("--generate-mini-debug-info")
443 } else {
444 cmd.Flag("--no-generate-mini-debug-info")
445 }
446
447 // Set the compiler reason to 'prebuilt' to identify the oat files produced
448 // during the build, as opposed to compiled on the device.
449 cmd.FlagWithArg("--compilation-reason=", "prebuilt")
450
451 if appImage {
Colin Cross69f59a32019-02-15 10:39:37 -0800452 appImagePath := odexPath.ReplaceExtension(ctx, "art")
Colin Cross43f08db2018-11-12 10:13:39 -0800453 appImageInstallPath := pathtools.ReplaceExtension(odexInstallPath, "art")
454 cmd.FlagWithOutput("--app-image-file=", appImagePath).
455 FlagWithArg("--image-format=", "lz4")
456 rule.Install(appImagePath, appImageInstallPath)
457 }
458
Colin Cross69f59a32019-02-15 10:39:37 -0800459 if profile != nil {
460 cmd.FlagWithInput("--profile-file=", profile)
Colin Cross43f08db2018-11-12 10:13:39 -0800461 }
462
463 rule.Install(odexPath, odexInstallPath)
464 rule.Install(vdexPath, vdexInstallPath)
465}
466
467// Return if the dex file in the APK should be stripped. If an APK is found to contain uncompressed dex files at
468// dex2oat time it will not be stripped even if strip=true.
469func shouldStripDex(module ModuleConfig, global GlobalConfig) bool {
470 strip := !global.DefaultNoStripping
471
Colin Crosscbed6572019-01-08 17:38:37 -0800472 if dexpreoptDisabled(global, module) {
473 strip = false
474 }
475
Colin Cross8c6d2502019-01-09 21:09:14 -0800476 if module.NoStripping {
477 strip = false
478 }
479
Colin Cross43f08db2018-11-12 10:13:39 -0800480 // Don't strip modules that are not on the system partition in case the oat/vdex version in system ROM
481 // doesn't match the one in other partitions. It needs to be able to fall back to the APK for that case.
482 if !strings.HasPrefix(module.DexLocation, SystemPartition) {
483 strip = false
484 }
485
486 // system_other isn't there for an OTA, so don't strip if module is on system, and odex is on system_other.
487 if odexOnSystemOther(module, global) {
488 strip = false
489 }
490
491 if module.HasApkLibraries {
492 strip = false
493 }
494
495 // Don't strip with dex files we explicitly uncompress (dexopt will not store the dex code).
496 if module.UncompressedDex {
497 strip = false
498 }
499
500 if shouldGenerateDM(module, global) {
501 strip = false
502 }
503
504 if module.PresignedPrebuilt {
505 // Only strip out files if we can re-sign the package.
506 strip = false
507 }
508
509 return strip
510}
511
512func shouldGenerateDM(module ModuleConfig, global GlobalConfig) bool {
513 // Generating DM files only makes sense for verify, avoid doing for non verify compiler filter APKs.
514 // No reason to use a dm file if the dex is already uncompressed.
515 return global.GenerateDMFiles && !module.UncompressedDex &&
516 contains(module.PreoptFlags, "--compiler-filter=verify")
517}
518
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000519func OdexOnSystemOtherByName(name string, dexLocation string, global GlobalConfig) bool {
Colin Cross43f08db2018-11-12 10:13:39 -0800520 if !global.HasSystemOther {
521 return false
522 }
523
524 if global.SanitizeLite {
525 return false
526 }
527
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000528 if contains(global.SpeedApps, name) || contains(global.SystemServerApps, name) {
Colin Cross43f08db2018-11-12 10:13:39 -0800529 return false
530 }
531
532 for _, f := range global.PatternsOnSystemOther {
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000533 if makefileMatch(filepath.Join(SystemPartition, f), dexLocation) {
Colin Cross43f08db2018-11-12 10:13:39 -0800534 return true
535 }
536 }
537
538 return false
539}
540
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000541func odexOnSystemOther(module ModuleConfig, global GlobalConfig) bool {
542 return OdexOnSystemOtherByName(module.Name, module.DexLocation, global)
543}
544
Colin Crossc7e40aa2019-02-08 21:37:00 -0800545// PathToLocation converts .../system/framework/arm64/boot.art to .../system/framework/boot.art
Colin Cross69f59a32019-02-15 10:39:37 -0800546func PathToLocation(path android.Path, arch android.ArchType) string {
547 pathArch := filepath.Base(filepath.Dir(path.String()))
Colin Cross74ba9622019-02-11 15:11:14 -0800548 if pathArch != arch.String() {
549 panic(fmt.Errorf("last directory in %q must be %q", path, arch.String()))
Colin Crossc7e40aa2019-02-08 21:37:00 -0800550 }
Colin Cross69f59a32019-02-15 10:39:37 -0800551 return filepath.Join(filepath.Dir(filepath.Dir(path.String())), filepath.Base(path.String()))
Colin Crossc7e40aa2019-02-08 21:37:00 -0800552}
553
Colin Cross69f59a32019-02-15 10:39:37 -0800554func pathForLibrary(module ModuleConfig, lib string) android.Path {
555 path, ok := module.LibraryPaths[lib]
556 if !ok {
Colin Cross43f08db2018-11-12 10:13:39 -0800557 panic(fmt.Errorf("unknown library path for %q", lib))
558 }
559 return path
560}
561
562func makefileMatch(pattern, s string) bool {
563 percent := strings.IndexByte(pattern, '%')
564 switch percent {
565 case -1:
566 return pattern == s
567 case len(pattern) - 1:
568 return strings.HasPrefix(s, pattern[:len(pattern)-1])
569 default:
570 panic(fmt.Errorf("unsupported makefile pattern %q", pattern))
571 }
572}
573
574func contains(l []string, s string) bool {
575 for _, e := range l {
576 if e == s {
577 return true
578 }
579 }
580 return false
581}
582
583// remove all elements in a from b, returning a new slice
584func filterOut(a []string, b []string) []string {
585 var ret []string
586 for _, x := range b {
587 if !contains(a, x) {
588 ret = append(ret, x)
589 }
590 }
591 return ret
592}
593
594func replace(l []string, from, to string) {
595 for i := range l {
596 if l[i] == from {
597 l[i] = to
598 }
599 }
600}
601
Colin Cross454c0872019-02-15 23:03:34 -0800602var copyOf = android.CopyOf
Colin Cross43f08db2018-11-12 10:13:39 -0800603
604func anyHavePrefix(l []string, prefix string) bool {
605 for _, x := range l {
606 if strings.HasPrefix(x, prefix) {
607 return true
608 }
609 }
610 return false
611}