blob: fc1bae1affbd6ba081a76af01a3e085bf67a61b6 [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
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +000089 for archIdx, _ := range module.Archs {
90 dexpreoptCommand(ctx, global, module, rule, archIdx, profile, appImage, generateDM)
Colin Crosscbed6572019-01-08 17:38:37 -080091 }
92 }
93 }
94
95 return rule, nil
96}
97
98func dexpreoptDisabled(global GlobalConfig, module ModuleConfig) bool {
99 if contains(global.DisablePreoptModules, module.Name) {
100 return true
Colin Cross43f08db2018-11-12 10:13:39 -0800101 }
102
Ulyana Trafimovichf2cb7e92019-11-27 12:26:49 +0000103 // Don't preopt system server jars that are updatable.
104 for _, p := range global.UpdatableSystemServerJars {
105 if _, jar := SplitApexJarPair(p); jar == module.Name {
106 return true
107 }
108 }
109
Colin Cross43f08db2018-11-12 10:13:39 -0800110 // If OnlyPreoptBootImageAndSystemServer=true and module is not in boot class path skip
111 // Also preopt system server jars since selinux prevents system server from loading anything from
112 // /data. If we don't do this they will need to be extracted which is not favorable for RAM usage
113 // or performance. If PreoptExtractedApk is true, we ignore the only preopt boot image options.
114 if global.OnlyPreoptBootImageAndSystemServer && !contains(global.BootJars, module.Name) &&
115 !contains(global.SystemServerJars, module.Name) && !module.PreoptExtractedApk {
Colin Crosscbed6572019-01-08 17:38:37 -0800116 return true
Colin Cross43f08db2018-11-12 10:13:39 -0800117 }
118
Colin Crosscbed6572019-01-08 17:38:37 -0800119 return false
Colin Cross43f08db2018-11-12 10:13:39 -0800120}
121
Colin Cross69f59a32019-02-15 10:39:37 -0800122func profileCommand(ctx android.PathContext, global GlobalConfig, module ModuleConfig,
123 rule *android.RuleBuilder) android.WritablePath {
124
125 profilePath := module.BuildPath.InSameDir(ctx, "profile.prof")
Colin Cross43f08db2018-11-12 10:13:39 -0800126 profileInstalledPath := module.DexLocation + ".prof"
127
128 if !module.ProfileIsTextListing {
129 rule.Command().FlagWithOutput("touch ", profilePath)
130 }
131
132 cmd := rule.Command().
133 Text(`ANDROID_LOG_TAGS="*:e"`).
134 Tool(global.Tools.Profman)
135
136 if module.ProfileIsTextListing {
137 // The profile is a test listing of classes (used for framework jars).
138 // We need to generate the actual binary profile before being able to compile.
Colin Cross69f59a32019-02-15 10:39:37 -0800139 cmd.FlagWithInput("--create-profile-from=", module.ProfileClassListing.Path())
Colin Cross43f08db2018-11-12 10:13:39 -0800140 } else {
141 // The profile is binary profile (used for apps). Run it through profman to
142 // ensure the profile keys match the apk.
143 cmd.
144 Flag("--copy-and-update-profile-key").
Colin Cross69f59a32019-02-15 10:39:37 -0800145 FlagWithInput("--profile-file=", module.ProfileClassListing.Path())
Colin Cross43f08db2018-11-12 10:13:39 -0800146 }
147
148 cmd.
149 FlagWithInput("--apk=", module.DexPath).
150 Flag("--dex-location="+module.DexLocation).
151 FlagWithOutput("--reference-profile-file=", profilePath)
152
153 if !module.ProfileIsTextListing {
154 cmd.Text(fmt.Sprintf(`|| echo "Profile out of date for %s"`, module.DexPath))
155 }
156 rule.Install(profilePath, profileInstalledPath)
157
158 return profilePath
159}
160
Nicolas Geoffraye7102422019-07-24 13:19:29 +0100161func bootProfileCommand(ctx android.PathContext, global GlobalConfig, module ModuleConfig,
162 rule *android.RuleBuilder) android.WritablePath {
163
164 profilePath := module.BuildPath.InSameDir(ctx, "profile.bprof")
165 profileInstalledPath := module.DexLocation + ".bprof"
166
167 if !module.ProfileIsTextListing {
168 rule.Command().FlagWithOutput("touch ", profilePath)
169 }
170
171 cmd := rule.Command().
172 Text(`ANDROID_LOG_TAGS="*:e"`).
173 Tool(global.Tools.Profman)
174
175 // The profile is a test listing of methods.
176 // We need to generate the actual binary profile.
177 cmd.FlagWithInput("--create-profile-from=", module.ProfileBootListing.Path())
178
179 cmd.
180 Flag("--generate-boot-profile").
181 FlagWithInput("--apk=", module.DexPath).
182 Flag("--dex-location="+module.DexLocation).
183 FlagWithOutput("--reference-profile-file=", profilePath)
184
185 if !module.ProfileIsTextListing {
186 cmd.Text(fmt.Sprintf(`|| echo "Profile out of date for %s"`, module.DexPath))
187 }
188 rule.Install(profilePath, profileInstalledPath)
189
190 return profilePath
191}
192
Colin Cross69f59a32019-02-15 10:39:37 -0800193func dexpreoptCommand(ctx android.PathContext, global GlobalConfig, module ModuleConfig, rule *android.RuleBuilder,
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000194 archIdx int, profile android.WritablePath, appImage bool, generateDM bool) {
195
196 arch := module.Archs[archIdx]
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
Ulya Trafimovich33805312019-12-19 22:17:08 +0000225 // TODO(skvadrik): fix this to use boot image location in the module config (currently it is broken
226 // in JIT-zygote builds, because "default" boot image is hard-coded in parts of the module config).
227 bootImage := module.DexPreoptImages[archIdx]
228 var bootImageLocation string
229 if bootImage != nil {
230 bootImageLocation = PathToLocation(bootImage, arch)
231 }
232
Colin Cross43f08db2018-11-12 10:13:39 -0800233 // The class loader context using paths in the build
Colin Cross69f59a32019-02-15 10:39:37 -0800234 var classLoaderContextHost android.Paths
Colin Cross43f08db2018-11-12 10:13:39 -0800235
236 // The class loader context using paths as they will be on the device
237 var classLoaderContextTarget []string
238
239 // Extra paths that will be appended to the class loader if the APK manifest has targetSdkVersion < 28
Colin Cross69f59a32019-02-15 10:39:37 -0800240 var conditionalClassLoaderContextHost28 android.Paths
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000241 var conditionalClassLoaderContextTarget28 []string
242
243 // Extra paths that will be appended to the class loader if the APK manifest has targetSdkVersion < 29
Colin Cross69f59a32019-02-15 10:39:37 -0800244 var conditionalClassLoaderContextHost29 android.Paths
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000245 var conditionalClassLoaderContextTarget29 []string
Colin Cross43f08db2018-11-12 10:13:39 -0800246
Colin Cross69f59a32019-02-15 10:39:37 -0800247 var classLoaderContextHostString string
248
Colin Cross43f08db2018-11-12 10:13:39 -0800249 if module.EnforceUsesLibraries {
Colin Cross50ddcc42019-05-16 12:28:22 -0700250 usesLibs := append(copyOf(module.UsesLibraries), module.PresentOptionalUsesLibraries...)
Colin Cross43f08db2018-11-12 10:13:39 -0800251
252 // Create class loader context for dex2oat from uses libraries and filtered optional libraries
Colin Cross50ddcc42019-05-16 12:28:22 -0700253 for _, l := range usesLibs {
Colin Cross43f08db2018-11-12 10:13:39 -0800254
255 classLoaderContextHost = append(classLoaderContextHost,
256 pathForLibrary(module, l))
257 classLoaderContextTarget = append(classLoaderContextTarget,
258 filepath.Join("/system/framework", l+".jar"))
259 }
260
261 const httpLegacy = "org.apache.http.legacy"
262 const httpLegacyImpl = "org.apache.http.legacy.impl"
263
Colin Cross38b96852019-05-22 10:21:09 -0700264 // org.apache.http.legacy contains classes that were in the default classpath until API 28. If the
265 // targetSdkVersion in the manifest or APK is < 28, and the module does not explicitly depend on
266 // org.apache.http.legacy, then implicitly add the classes to the classpath for dexpreopt. One the
267 // device the classes will be in a file called org.apache.http.legacy.impl.jar.
Colin Cross50ddcc42019-05-16 12:28:22 -0700268 module.LibraryPaths[httpLegacyImpl] = module.LibraryPaths[httpLegacy]
269
270 if !contains(module.UsesLibraries, httpLegacy) && !contains(module.PresentOptionalUsesLibraries, 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}").
Ulya Trafimovich33805312019-12-19 22:17:08 +0000360 FlagWithArg("--boot-image=", bootImageLocation).Implicits(module.DexPreoptImagesDeps[archIdx].Paths()).
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
Colin Cross43f08db2018-11-12 10:13:39 -0800485func shouldGenerateDM(module ModuleConfig, global GlobalConfig) bool {
486 // Generating DM files only makes sense for verify, avoid doing for non verify compiler filter APKs.
487 // No reason to use a dm file if the dex is already uncompressed.
488 return global.GenerateDMFiles && !module.UncompressedDex &&
489 contains(module.PreoptFlags, "--compiler-filter=verify")
490}
491
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000492func OdexOnSystemOtherByName(name string, dexLocation string, global GlobalConfig) bool {
Colin Cross43f08db2018-11-12 10:13:39 -0800493 if !global.HasSystemOther {
494 return false
495 }
496
497 if global.SanitizeLite {
498 return false
499 }
500
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000501 if contains(global.SpeedApps, name) || contains(global.SystemServerApps, name) {
Colin Cross43f08db2018-11-12 10:13:39 -0800502 return false
503 }
504
505 for _, f := range global.PatternsOnSystemOther {
Anton Hanssond57bd3c2019-10-14 16:53:02 +0100506 if 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>
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000558func GetJarLocationFromApexJarPair(apexJarValue string) string {
Roshan Piusccc26ef2019-11-27 09:37:46 -0800559 apex, jar := SplitApexJarPair(apexJarValue)
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000560 return filepath.Join("/apex", apex, "javalib", jar+".jar")
Roshan Piusccc26ef2019-11-27 09:37:46 -0800561}
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}