blob: f3bf2ff804ea2cefbf73ab6db7d5591dc24852fb [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
Nicolas Geoffrayc1bf7242019-10-18 14:51:38 +010016// dexpreopting.
Colin Cross43f08db2018-11-12 10:13:39 -080017//
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
Nicolas Geoffrayc1bf7242019-10-18 14:51:38 +010025// as necessary. The zip file may be empty if preopting was disabled for any reason.
Colin Cross43f08db2018-11-12 10:13:39 -080026//
27// The intermediate shell scripts allow changes to this package or to the global config to regenerate the shell scripts
28// but only require re-executing preopting if the script has changed.
29//
30// For Soong modules this package is linked directly into Soong and run from the java package. It generates the same
31// commands as for make, using athe same global config JSON file used by make, but using a module config structure
32// provided by Soong. The generated commands are then converted into Soong rule and written directly to the ninja file,
33// with no extra shell scripts involved.
34package dexpreopt
35
36import (
37 "fmt"
38 "path/filepath"
Colin Cross69f59a32019-02-15 10:39:37 -080039 "runtime"
Colin Cross43f08db2018-11-12 10:13:39 -080040 "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
Colin Cross43f08db2018-11-12 10:13:39 -080050// GenerateDexpreoptRule generates a set of commands that will preopt a module based on a GlobalConfig and a
51// ModuleConfig. The produced files and their install locations will be available through rule.Installs().
Colin Cross69f59a32019-02-15 10:39:37 -080052func GenerateDexpreoptRule(ctx android.PathContext,
53 global GlobalConfig, module ModuleConfig) (rule *android.RuleBuilder, err error) {
54
Colin Cross43f08db2018-11-12 10:13:39 -080055 defer func() {
56 if r := recover(); r != nil {
Colin Cross69f59a32019-02-15 10:39:37 -080057 if _, ok := r.(runtime.Error); ok {
58 panic(r)
59 } else if e, ok := r.(error); ok {
Colin Cross43f08db2018-11-12 10:13:39 -080060 err = e
61 rule = nil
62 } else {
63 panic(r)
64 }
65 }
66 }()
67
Colin Cross758290d2019-02-01 16:42:32 -080068 rule = android.NewRuleBuilder()
Colin Cross43f08db2018-11-12 10:13:39 -080069
Colin Cross69f59a32019-02-15 10:39:37 -080070 generateProfile := module.ProfileClassListing.Valid() && !global.DisableGenerateProfile
Nicolas Geoffraye7102422019-07-24 13:19:29 +010071 generateBootProfile := module.ProfileBootListing.Valid() && !global.DisableGenerateProfile
Colin Cross43f08db2018-11-12 10:13:39 -080072
Colin Cross69f59a32019-02-15 10:39:37 -080073 var profile android.WritablePath
Colin Crosscbed6572019-01-08 17:38:37 -080074 if generateProfile {
Colin Cross69f59a32019-02-15 10:39:37 -080075 profile = profileCommand(ctx, global, module, rule)
Colin Crosscbed6572019-01-08 17:38:37 -080076 }
Nicolas Geoffraye7102422019-07-24 13:19:29 +010077 if generateBootProfile {
78 bootProfileCommand(ctx, global, module, rule)
79 }
Colin Crosscbed6572019-01-08 17:38:37 -080080
81 if !dexpreoptDisabled(global, module) {
82 // Don't preopt individual boot jars, they will be preopted together.
Colin Crosscbed6572019-01-08 17:38:37 -080083 if !contains(global.BootJars, module.Name) {
84 appImage := (generateProfile || module.ForceCreateAppImage || global.DefaultAppImages) &&
85 !module.NoCreateAppImage
86
87 generateDM := shouldGenerateDM(module, global)
88
Colin Crossc7e40aa2019-02-08 21:37:00 -080089 for i, arch := range module.Archs {
90 image := module.DexPreoptImages[i]
Dan Willemsen0f416782019-06-13 21:44:53 +000091 imageDeps := module.DexPreoptImagesDeps[i]
92 dexpreoptCommand(ctx, global, module, rule, arch, profile, image, imageDeps, appImage, generateDM)
Colin Crosscbed6572019-01-08 17:38:37 -080093 }
94 }
95 }
96
97 return rule, nil
98}
99
100func dexpreoptDisabled(global GlobalConfig, module ModuleConfig) bool {
101 if contains(global.DisablePreoptModules, module.Name) {
102 return true
Colin Cross43f08db2018-11-12 10:13:39 -0800103 }
104
Ulyana Trafimovichf2cb7e92019-11-27 12:26:49 +0000105 // Don't preopt system server jars that are updatable.
106 for _, p := range global.UpdatableSystemServerJars {
107 if _, jar := SplitApexJarPair(p); jar == module.Name {
108 return true
109 }
110 }
111
Colin Cross43f08db2018-11-12 10:13:39 -0800112 // If OnlyPreoptBootImageAndSystemServer=true and module is not in boot class path skip
113 // Also preopt system server jars since selinux prevents system server from loading anything from
114 // /data. If we don't do this they will need to be extracted which is not favorable for RAM usage
115 // or performance. If PreoptExtractedApk is true, we ignore the only preopt boot image options.
116 if global.OnlyPreoptBootImageAndSystemServer && !contains(global.BootJars, module.Name) &&
117 !contains(global.SystemServerJars, module.Name) && !module.PreoptExtractedApk {
Colin Crosscbed6572019-01-08 17:38:37 -0800118 return true
Colin Cross43f08db2018-11-12 10:13:39 -0800119 }
120
Colin Crosscbed6572019-01-08 17:38:37 -0800121 return false
Colin Cross43f08db2018-11-12 10:13:39 -0800122}
123
Colin Cross69f59a32019-02-15 10:39:37 -0800124func profileCommand(ctx android.PathContext, global GlobalConfig, module ModuleConfig,
125 rule *android.RuleBuilder) android.WritablePath {
126
127 profilePath := module.BuildPath.InSameDir(ctx, "profile.prof")
Colin Cross43f08db2018-11-12 10:13:39 -0800128 profileInstalledPath := module.DexLocation + ".prof"
129
130 if !module.ProfileIsTextListing {
131 rule.Command().FlagWithOutput("touch ", profilePath)
132 }
133
134 cmd := rule.Command().
135 Text(`ANDROID_LOG_TAGS="*:e"`).
136 Tool(global.Tools.Profman)
137
138 if module.ProfileIsTextListing {
139 // The profile is a test listing of classes (used for framework jars).
140 // We need to generate the actual binary profile before being able to compile.
Colin Cross69f59a32019-02-15 10:39:37 -0800141 cmd.FlagWithInput("--create-profile-from=", module.ProfileClassListing.Path())
Colin Cross43f08db2018-11-12 10:13:39 -0800142 } else {
143 // The profile is binary profile (used for apps). Run it through profman to
144 // ensure the profile keys match the apk.
145 cmd.
146 Flag("--copy-and-update-profile-key").
Colin Cross69f59a32019-02-15 10:39:37 -0800147 FlagWithInput("--profile-file=", module.ProfileClassListing.Path())
Colin Cross43f08db2018-11-12 10:13:39 -0800148 }
149
150 cmd.
151 FlagWithInput("--apk=", module.DexPath).
152 Flag("--dex-location="+module.DexLocation).
153 FlagWithOutput("--reference-profile-file=", profilePath)
154
155 if !module.ProfileIsTextListing {
156 cmd.Text(fmt.Sprintf(`|| echo "Profile out of date for %s"`, module.DexPath))
157 }
158 rule.Install(profilePath, profileInstalledPath)
159
160 return profilePath
161}
162
Nicolas Geoffraye7102422019-07-24 13:19:29 +0100163func bootProfileCommand(ctx android.PathContext, global GlobalConfig, module ModuleConfig,
164 rule *android.RuleBuilder) android.WritablePath {
165
166 profilePath := module.BuildPath.InSameDir(ctx, "profile.bprof")
167 profileInstalledPath := module.DexLocation + ".bprof"
168
169 if !module.ProfileIsTextListing {
170 rule.Command().FlagWithOutput("touch ", profilePath)
171 }
172
173 cmd := rule.Command().
174 Text(`ANDROID_LOG_TAGS="*:e"`).
175 Tool(global.Tools.Profman)
176
177 // The profile is a test listing of methods.
178 // We need to generate the actual binary profile.
179 cmd.FlagWithInput("--create-profile-from=", module.ProfileBootListing.Path())
180
181 cmd.
182 Flag("--generate-boot-profile").
183 FlagWithInput("--apk=", module.DexPath).
184 Flag("--dex-location="+module.DexLocation).
185 FlagWithOutput("--reference-profile-file=", profilePath)
186
187 if !module.ProfileIsTextListing {
188 cmd.Text(fmt.Sprintf(`|| echo "Profile out of date for %s"`, module.DexPath))
189 }
190 rule.Install(profilePath, profileInstalledPath)
191
192 return profilePath
193}
194
Colin Cross69f59a32019-02-15 10:39:37 -0800195func dexpreoptCommand(ctx android.PathContext, global GlobalConfig, module ModuleConfig, rule *android.RuleBuilder,
Dan Willemsen0f416782019-06-13 21:44:53 +0000196 arch android.ArchType, profile, bootImage android.Path, bootImageDeps android.Paths, appImage, generateDM bool) {
Colin Cross43f08db2018-11-12 10:13:39 -0800197
198 // HACK: make soname in Soong-generated .odex files match Make.
199 base := filepath.Base(module.DexLocation)
200 if filepath.Ext(base) == ".jar" {
201 base = "javalib.jar"
202 } else if filepath.Ext(base) == ".apk" {
203 base = "package.apk"
204 }
205
206 toOdexPath := func(path string) string {
207 return filepath.Join(
208 filepath.Dir(path),
209 "oat",
Colin Cross74ba9622019-02-11 15:11:14 -0800210 arch.String(),
Colin Cross43f08db2018-11-12 10:13:39 -0800211 pathtools.ReplaceExtension(filepath.Base(path), "odex"))
212 }
213
Colin Cross69f59a32019-02-15 10:39:37 -0800214 odexPath := module.BuildPath.InSameDir(ctx, "oat", arch.String(), pathtools.ReplaceExtension(base, "odex"))
Colin Cross43f08db2018-11-12 10:13:39 -0800215 odexInstallPath := toOdexPath(module.DexLocation)
216 if odexOnSystemOther(module, global) {
Anton Hansson43ab0bc2019-10-03 14:18:45 +0100217 odexInstallPath = filepath.Join(SystemOtherPartition, odexInstallPath)
Colin Cross43f08db2018-11-12 10:13:39 -0800218 }
219
Colin Cross69f59a32019-02-15 10:39:37 -0800220 vdexPath := odexPath.ReplaceExtension(ctx, "vdex")
Colin Cross43f08db2018-11-12 10:13:39 -0800221 vdexInstallPath := pathtools.ReplaceExtension(odexInstallPath, "vdex")
222
Colin Cross69f59a32019-02-15 10:39:37 -0800223 invocationPath := odexPath.ReplaceExtension(ctx, "invocation")
Alex Light5de41962018-12-18 15:16:26 -0800224
Colin Crossc7e40aa2019-02-08 21:37:00 -0800225 // bootImage is .../dex_bootjars/system/framework/arm64/boot.art, but dex2oat wants
226 // .../dex_bootjars/system/framework/boot.art on the command line
227 var bootImageLocation string
Colin Cross69f59a32019-02-15 10:39:37 -0800228 if bootImage != nil {
Colin Crossc7e40aa2019-02-08 21:37:00 -0800229 bootImageLocation = PathToLocation(bootImage, arch)
Colin Cross43f08db2018-11-12 10:13:39 -0800230 }
231
Colin Cross43f08db2018-11-12 10:13:39 -0800232 // The class loader context using paths in the build
Colin Cross69f59a32019-02-15 10:39:37 -0800233 var classLoaderContextHost android.Paths
Colin Cross43f08db2018-11-12 10:13:39 -0800234
235 // The class loader context using paths as they will be on the device
236 var classLoaderContextTarget []string
237
238 // Extra paths that will be appended to the class loader if the APK manifest has targetSdkVersion < 28
Colin Cross69f59a32019-02-15 10:39:37 -0800239 var conditionalClassLoaderContextHost28 android.Paths
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000240 var conditionalClassLoaderContextTarget28 []string
241
242 // Extra paths that will be appended to the class loader if the APK manifest has targetSdkVersion < 29
Colin Cross69f59a32019-02-15 10:39:37 -0800243 var conditionalClassLoaderContextHost29 android.Paths
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000244 var conditionalClassLoaderContextTarget29 []string
Colin Cross43f08db2018-11-12 10:13:39 -0800245
Colin Cross69f59a32019-02-15 10:39:37 -0800246 var classLoaderContextHostString string
247
Colin Cross43f08db2018-11-12 10:13:39 -0800248 if module.EnforceUsesLibraries {
Colin Cross50ddcc42019-05-16 12:28:22 -0700249 usesLibs := append(copyOf(module.UsesLibraries), module.PresentOptionalUsesLibraries...)
Colin Cross43f08db2018-11-12 10:13:39 -0800250
251 // Create class loader context for dex2oat from uses libraries and filtered optional libraries
Colin Cross50ddcc42019-05-16 12:28:22 -0700252 for _, l := range usesLibs {
Colin Cross43f08db2018-11-12 10:13:39 -0800253
254 classLoaderContextHost = append(classLoaderContextHost,
255 pathForLibrary(module, l))
256 classLoaderContextTarget = append(classLoaderContextTarget,
257 filepath.Join("/system/framework", l+".jar"))
258 }
259
260 const httpLegacy = "org.apache.http.legacy"
261 const httpLegacyImpl = "org.apache.http.legacy.impl"
262
Colin Cross38b96852019-05-22 10:21:09 -0700263 // org.apache.http.legacy contains classes that were in the default classpath until API 28. If the
264 // targetSdkVersion in the manifest or APK is < 28, and the module does not explicitly depend on
265 // org.apache.http.legacy, then implicitly add the classes to the classpath for dexpreopt. One the
266 // device the classes will be in a file called org.apache.http.legacy.impl.jar.
Colin Cross50ddcc42019-05-16 12:28:22 -0700267 module.LibraryPaths[httpLegacyImpl] = module.LibraryPaths[httpLegacy]
268
269 if !contains(module.UsesLibraries, httpLegacy) && !contains(module.PresentOptionalUsesLibraries, httpLegacy) {
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000270 conditionalClassLoaderContextHost28 = append(conditionalClassLoaderContextHost28,
Colin Cross43f08db2018-11-12 10:13:39 -0800271 pathForLibrary(module, httpLegacyImpl))
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000272 conditionalClassLoaderContextTarget28 = append(conditionalClassLoaderContextTarget28,
Colin Cross43f08db2018-11-12 10:13:39 -0800273 filepath.Join("/system/framework", httpLegacyImpl+".jar"))
274 }
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000275
276 const hidlBase = "android.hidl.base-V1.0-java"
277 const hidlManager = "android.hidl.manager-V1.0-java"
278
Colin Cross38b96852019-05-22 10:21:09 -0700279 // android.hidl.base-V1.0-java and android.hidl.manager-V1.0 contain classes that were in the default
280 // classpath until API 29. If the targetSdkVersion in the manifest or APK is < 29 then implicitly add
281 // the classes to the classpath for dexpreopt.
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000282 conditionalClassLoaderContextHost29 = append(conditionalClassLoaderContextHost29,
Alex Light5de41962018-12-18 15:16:26 -0800283 pathForLibrary(module, hidlManager))
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000284 conditionalClassLoaderContextTarget29 = append(conditionalClassLoaderContextTarget29,
285 filepath.Join("/system/framework", hidlManager+".jar"))
286 conditionalClassLoaderContextHost29 = append(conditionalClassLoaderContextHost29,
Alex Light5de41962018-12-18 15:16:26 -0800287 pathForLibrary(module, hidlBase))
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000288 conditionalClassLoaderContextTarget29 = append(conditionalClassLoaderContextTarget29,
289 filepath.Join("/system/framework", hidlBase+".jar"))
Colin Cross69f59a32019-02-15 10:39:37 -0800290
291 classLoaderContextHostString = strings.Join(classLoaderContextHost.Strings(), ":")
Colin Cross43f08db2018-11-12 10:13:39 -0800292 } else {
293 // Pass special class loader context to skip the classpath and collision check.
294 // This will get removed once LOCAL_USES_LIBRARIES is enforced.
295 // Right now LOCAL_USES_LIBRARIES is opt in, for the case where it's not specified we still default
296 // to the &.
Colin Cross69f59a32019-02-15 10:39:37 -0800297 classLoaderContextHostString = `\&`
Colin Cross43f08db2018-11-12 10:13:39 -0800298 }
299
Colin Cross69f59a32019-02-15 10:39:37 -0800300 rule.Command().FlagWithArg("mkdir -p ", filepath.Dir(odexPath.String()))
Colin Cross43f08db2018-11-12 10:13:39 -0800301 rule.Command().FlagWithOutput("rm -f ", odexPath)
302 // Set values in the environment of the rule. These may be modified by construct_context.sh.
Colin Cross69f59a32019-02-15 10:39:37 -0800303 rule.Command().FlagWithArg("class_loader_context_arg=--class-loader-context=", classLoaderContextHostString)
Colin Cross43f08db2018-11-12 10:13:39 -0800304 rule.Command().Text(`stored_class_loader_context_arg=""`)
305
306 if module.EnforceUsesLibraries {
Colin Cross38b96852019-05-22 10:21:09 -0700307 if module.ManifestPath != nil {
308 rule.Command().Text(`target_sdk_version="$(`).
309 Tool(global.Tools.ManifestCheck).
310 Flag("--extract-target-sdk-version").
311 Input(module.ManifestPath).
312 Text(`)"`)
313 } else {
314 // No manifest to extract targetSdkVersion from, hope that DexJar is an APK
315 rule.Command().Text(`target_sdk_version="$(`).
316 Tool(global.Tools.Aapt).
317 Flag("dump badging").
318 Input(module.DexPath).
319 Text(`| grep "targetSdkVersion" | sed -n "s/targetSdkVersion:'\(.*\)'/\1/p"`).
320 Text(`)"`)
321 }
Colin Cross69f59a32019-02-15 10:39:37 -0800322 rule.Command().Textf(`dex_preopt_host_libraries="%s"`,
323 strings.Join(classLoaderContextHost.Strings(), " ")).
324 Implicits(classLoaderContextHost)
325 rule.Command().Textf(`dex_preopt_target_libraries="%s"`,
326 strings.Join(classLoaderContextTarget, " "))
327 rule.Command().Textf(`conditional_host_libs_28="%s"`,
328 strings.Join(conditionalClassLoaderContextHost28.Strings(), " ")).
329 Implicits(conditionalClassLoaderContextHost28)
330 rule.Command().Textf(`conditional_target_libs_28="%s"`,
331 strings.Join(conditionalClassLoaderContextTarget28, " "))
332 rule.Command().Textf(`conditional_host_libs_29="%s"`,
333 strings.Join(conditionalClassLoaderContextHost29.Strings(), " ")).
334 Implicits(conditionalClassLoaderContextHost29)
335 rule.Command().Textf(`conditional_target_libs_29="%s"`,
336 strings.Join(conditionalClassLoaderContextTarget29, " "))
Colin Cross38b96852019-05-22 10:21:09 -0700337 rule.Command().Text("source").Tool(global.Tools.ConstructContext).Input(module.DexPath)
Colin Cross43f08db2018-11-12 10:13:39 -0800338 }
339
Nicolas Geoffray2464ef42019-03-05 14:07:07 +0000340 // Devices that do not have a product partition use a symlink from /product to /system/product.
341 // Because on-device dexopt will see dex locations starting with /product, we change the paths
342 // to mimic this behavior.
343 dexLocationArg := module.DexLocation
344 if strings.HasPrefix(dexLocationArg, "/system/product/") {
345 dexLocationArg = strings.TrimPrefix(dexLocationArg, "/system")
346 }
347
Colin Cross43f08db2018-11-12 10:13:39 -0800348 cmd := rule.Command().
349 Text(`ANDROID_LOG_TAGS="*:e"`).
350 Tool(global.Tools.Dex2oat).
351 Flag("--avoid-storing-invocation").
Alex Light5de41962018-12-18 15:16:26 -0800352 FlagWithOutput("--write-invocation-to=", invocationPath).ImplicitOutput(invocationPath).
Colin Cross43f08db2018-11-12 10:13:39 -0800353 Flag("--runtime-arg").FlagWithArg("-Xms", global.Dex2oatXms).
354 Flag("--runtime-arg").FlagWithArg("-Xmx", global.Dex2oatXmx).
Colin Cross800fe132019-02-11 14:21:24 -0800355 Flag("--runtime-arg").FlagWithInputList("-Xbootclasspath:", module.PreoptBootClassPathDexFiles, ":").
356 Flag("--runtime-arg").FlagWithList("-Xbootclasspath-locations:", module.PreoptBootClassPathDexLocations, ":").
Colin Cross43f08db2018-11-12 10:13:39 -0800357 Flag("${class_loader_context_arg}").
358 Flag("${stored_class_loader_context_arg}").
Dan Willemsen0f416782019-06-13 21:44:53 +0000359 FlagWithArg("--boot-image=", bootImageLocation).Implicits(bootImageDeps).
Colin Cross43f08db2018-11-12 10:13:39 -0800360 FlagWithInput("--dex-file=", module.DexPath).
Nicolas Geoffray2464ef42019-03-05 14:07:07 +0000361 FlagWithArg("--dex-location=", dexLocationArg).
Colin Cross43f08db2018-11-12 10:13:39 -0800362 FlagWithOutput("--oat-file=", odexPath).ImplicitOutput(vdexPath).
363 // Pass an empty directory, dex2oat shouldn't be reading arbitrary files
364 FlagWithArg("--android-root=", global.EmptyDirectory).
Colin Cross74ba9622019-02-11 15:11:14 -0800365 FlagWithArg("--instruction-set=", arch.String()).
Colin Cross43f08db2018-11-12 10:13:39 -0800366 FlagWithArg("--instruction-set-variant=", global.CpuVariant[arch]).
367 FlagWithArg("--instruction-set-features=", global.InstructionSetFeatures[arch]).
368 Flag("--no-generate-debug-info").
369 Flag("--generate-build-id").
370 Flag("--abort-on-hard-verifier-error").
371 Flag("--force-determinism").
372 FlagWithArg("--no-inline-from=", "core-oj.jar")
373
374 var preoptFlags []string
375 if len(module.PreoptFlags) > 0 {
376 preoptFlags = module.PreoptFlags
377 } else if len(global.PreoptFlags) > 0 {
378 preoptFlags = global.PreoptFlags
379 }
380
381 if len(preoptFlags) > 0 {
382 cmd.Text(strings.Join(preoptFlags, " "))
383 }
384
385 if module.UncompressedDex {
386 cmd.FlagWithArg("--copy-dex-files=", "false")
387 }
388
389 if !anyHavePrefix(preoptFlags, "--compiler-filter=") {
390 var compilerFilter string
391 if contains(global.SystemServerJars, module.Name) {
392 // Jars of system server, use the product option if it is set, speed otherwise.
393 if global.SystemServerCompilerFilter != "" {
394 compilerFilter = global.SystemServerCompilerFilter
395 } else {
396 compilerFilter = "speed"
397 }
398 } else if contains(global.SpeedApps, module.Name) || contains(global.SystemServerApps, module.Name) {
399 // Apps loaded into system server, and apps the product default to being compiled with the
400 // 'speed' compiler filter.
401 compilerFilter = "speed"
Colin Cross69f59a32019-02-15 10:39:37 -0800402 } else if profile != nil {
Colin Cross43f08db2018-11-12 10:13:39 -0800403 // For non system server jars, use speed-profile when we have a profile.
404 compilerFilter = "speed-profile"
405 } else if global.DefaultCompilerFilter != "" {
406 compilerFilter = global.DefaultCompilerFilter
407 } else {
408 compilerFilter = "quicken"
409 }
410 cmd.FlagWithArg("--compiler-filter=", compilerFilter)
411 }
412
413 if generateDM {
414 cmd.FlagWithArg("--copy-dex-files=", "false")
Colin Cross69f59a32019-02-15 10:39:37 -0800415 dmPath := module.BuildPath.InSameDir(ctx, "generated.dm")
Colin Cross43f08db2018-11-12 10:13:39 -0800416 dmInstalledPath := pathtools.ReplaceExtension(module.DexLocation, "dm")
Colin Cross69f59a32019-02-15 10:39:37 -0800417 tmpPath := module.BuildPath.InSameDir(ctx, "primary.vdex")
Colin Cross43f08db2018-11-12 10:13:39 -0800418 rule.Command().Text("cp -f").Input(vdexPath).Output(tmpPath)
419 rule.Command().Tool(global.Tools.SoongZip).
420 FlagWithArg("-L", "9").
421 FlagWithOutput("-o", dmPath).
422 Flag("-j").
423 Input(tmpPath)
424 rule.Install(dmPath, dmInstalledPath)
425 }
426
427 // By default, emit debug info.
428 debugInfo := true
429 if global.NoDebugInfo {
430 // If the global setting suppresses mini-debug-info, disable it.
431 debugInfo = false
432 }
433
434 // PRODUCT_SYSTEM_SERVER_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO.
435 // PRODUCT_OTHER_JAVA_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO.
436 if contains(global.SystemServerJars, module.Name) {
437 if global.AlwaysSystemServerDebugInfo {
438 debugInfo = true
439 } else if global.NeverSystemServerDebugInfo {
440 debugInfo = false
441 }
442 } else {
443 if global.AlwaysOtherDebugInfo {
444 debugInfo = true
445 } else if global.NeverOtherDebugInfo {
446 debugInfo = false
447 }
448 }
449
450 // Never enable on eng.
451 if global.IsEng {
452 debugInfo = false
453 }
454
455 if debugInfo {
456 cmd.Flag("--generate-mini-debug-info")
457 } else {
458 cmd.Flag("--no-generate-mini-debug-info")
459 }
460
461 // Set the compiler reason to 'prebuilt' to identify the oat files produced
462 // during the build, as opposed to compiled on the device.
463 cmd.FlagWithArg("--compilation-reason=", "prebuilt")
464
465 if appImage {
Colin Cross69f59a32019-02-15 10:39:37 -0800466 appImagePath := odexPath.ReplaceExtension(ctx, "art")
Colin Cross43f08db2018-11-12 10:13:39 -0800467 appImageInstallPath := pathtools.ReplaceExtension(odexInstallPath, "art")
468 cmd.FlagWithOutput("--app-image-file=", appImagePath).
469 FlagWithArg("--image-format=", "lz4")
Mathieu Chartier3f7ddbb2019-04-29 09:33:50 -0700470 if !global.DontResolveStartupStrings {
471 cmd.FlagWithArg("--resolve-startup-const-strings=", "true")
472 }
Colin Cross43f08db2018-11-12 10:13:39 -0800473 rule.Install(appImagePath, appImageInstallPath)
474 }
475
Colin Cross69f59a32019-02-15 10:39:37 -0800476 if profile != nil {
477 cmd.FlagWithInput("--profile-file=", profile)
Colin Cross43f08db2018-11-12 10:13:39 -0800478 }
479
480 rule.Install(odexPath, odexInstallPath)
481 rule.Install(vdexPath, vdexInstallPath)
482}
483
Colin Cross43f08db2018-11-12 10:13:39 -0800484func shouldGenerateDM(module ModuleConfig, global GlobalConfig) bool {
485 // Generating DM files only makes sense for verify, avoid doing for non verify compiler filter APKs.
486 // No reason to use a dm file if the dex is already uncompressed.
487 return global.GenerateDMFiles && !module.UncompressedDex &&
488 contains(module.PreoptFlags, "--compiler-filter=verify")
489}
490
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000491func OdexOnSystemOtherByName(name string, dexLocation string, global GlobalConfig) bool {
Colin Cross43f08db2018-11-12 10:13:39 -0800492 if !global.HasSystemOther {
493 return false
494 }
495
496 if global.SanitizeLite {
497 return false
498 }
499
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000500 if contains(global.SpeedApps, name) || contains(global.SystemServerApps, name) {
Colin Cross43f08db2018-11-12 10:13:39 -0800501 return false
502 }
503
504 for _, f := range global.PatternsOnSystemOther {
Anton Hansson12b8d422019-10-02 18:14:02 +0100505 // See comment of SYSTEM_OTHER_ODEX_FILTER for details on the matching.
506 if makefileMatch("/"+f, dexLocation) || makefileMatch(filepath.Join(SystemPartition, f), dexLocation) {
Colin Cross43f08db2018-11-12 10:13:39 -0800507 return true
508 }
509 }
510
511 return false
512}
513
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000514func odexOnSystemOther(module ModuleConfig, global GlobalConfig) bool {
515 return OdexOnSystemOtherByName(module.Name, module.DexLocation, global)
516}
517
Colin Crossc7e40aa2019-02-08 21:37:00 -0800518// PathToLocation converts .../system/framework/arm64/boot.art to .../system/framework/boot.art
Colin Cross69f59a32019-02-15 10:39:37 -0800519func PathToLocation(path android.Path, arch android.ArchType) string {
520 pathArch := filepath.Base(filepath.Dir(path.String()))
Colin Cross74ba9622019-02-11 15:11:14 -0800521 if pathArch != arch.String() {
522 panic(fmt.Errorf("last directory in %q must be %q", path, arch.String()))
Colin Crossc7e40aa2019-02-08 21:37:00 -0800523 }
Colin Cross69f59a32019-02-15 10:39:37 -0800524 return filepath.Join(filepath.Dir(filepath.Dir(path.String())), filepath.Base(path.String()))
Colin Crossc7e40aa2019-02-08 21:37:00 -0800525}
526
Colin Cross69f59a32019-02-15 10:39:37 -0800527func pathForLibrary(module ModuleConfig, lib string) android.Path {
528 path, ok := module.LibraryPaths[lib]
529 if !ok {
Colin Cross43f08db2018-11-12 10:13:39 -0800530 panic(fmt.Errorf("unknown library path for %q", lib))
531 }
532 return path
533}
534
535func makefileMatch(pattern, s string) bool {
536 percent := strings.IndexByte(pattern, '%')
537 switch percent {
538 case -1:
539 return pattern == s
540 case len(pattern) - 1:
541 return strings.HasPrefix(s, pattern[:len(pattern)-1])
542 default:
543 panic(fmt.Errorf("unsupported makefile pattern %q", pattern))
544 }
545}
546
Ulyana Trafimovichf2cb7e92019-11-27 12:26:49 +0000547// Expected format for apexJarValue = <apex name>:<jar name>
548func SplitApexJarPair(apexJarValue string) (string, string) {
549 var apexJarPair []string = strings.SplitN(apexJarValue, ":", 2)
550 if apexJarPair == nil || len(apexJarPair) != 2 {
551 panic(fmt.Errorf("malformed apexJarValue: %q, expected format: <apex>:<jar>",
552 apexJarValue))
553 }
554 return apexJarPair[0], apexJarPair[1]
555}
556
Roshan Piusccc26ef2019-11-27 09:37:46 -0800557// Expected format for apexJarValue = <apex name>:<jar name>
558func GetJarLocationFromApexJarPair(apexJarValue string) (string) {
559 apex, jar := SplitApexJarPair(apexJarValue)
560 return filepath.Join("/apex", apex, "javalib", jar + ".jar")
561}
562
Colin Cross43f08db2018-11-12 10:13:39 -0800563func contains(l []string, s string) bool {
564 for _, e := range l {
565 if e == s {
566 return true
567 }
568 }
569 return false
570}
571
572// remove all elements in a from b, returning a new slice
573func filterOut(a []string, b []string) []string {
574 var ret []string
575 for _, x := range b {
576 if !contains(a, x) {
577 ret = append(ret, x)
578 }
579 }
580 return ret
581}
582
583func replace(l []string, from, to string) {
584 for i := range l {
585 if l[i] == from {
586 l[i] = to
587 }
588 }
589}
590
Colin Cross454c0872019-02-15 23:03:34 -0800591var copyOf = android.CopyOf
Colin Cross43f08db2018-11-12 10:13:39 -0800592
593func anyHavePrefix(l []string, prefix string) bool {
594 for _, x := range l {
595 if strings.HasPrefix(x, prefix) {
596 return true
597 }
598 }
599 return false
600}