blob: 51d11571ee20f701af648ea2bf41f648e71d6a89 [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
Ulya Trafimovich6cf2c0c2020-04-24 12:15:20 +010050var DexpreoptRunningInSoong = false
51
Colin Cross43f08db2018-11-12 10:13:39 -080052// GenerateDexpreoptRule generates a set of commands that will preopt a module based on a GlobalConfig and a
53// ModuleConfig. The produced files and their install locations will be available through rule.Installs().
Martin Stjernholm8d80cee2020-01-31 17:44:54 +000054func GenerateDexpreoptRule(ctx android.PathContext, globalSoong *GlobalSoongConfig,
55 global *GlobalConfig, module *ModuleConfig) (rule *android.RuleBuilder, err error) {
Colin Cross69f59a32019-02-15 10:39:37 -080056
Colin Cross43f08db2018-11-12 10:13:39 -080057 defer func() {
58 if r := recover(); r != nil {
Colin Cross69f59a32019-02-15 10:39:37 -080059 if _, ok := r.(runtime.Error); ok {
60 panic(r)
61 } else if e, ok := r.(error); ok {
Colin Cross43f08db2018-11-12 10:13:39 -080062 err = e
63 rule = nil
64 } else {
65 panic(r)
66 }
67 }
68 }()
69
Colin Cross758290d2019-02-01 16:42:32 -080070 rule = android.NewRuleBuilder()
Colin Cross43f08db2018-11-12 10:13:39 -080071
Colin Cross69f59a32019-02-15 10:39:37 -080072 generateProfile := module.ProfileClassListing.Valid() && !global.DisableGenerateProfile
Nicolas Geoffraye7102422019-07-24 13:19:29 +010073 generateBootProfile := module.ProfileBootListing.Valid() && !global.DisableGenerateProfile
Colin Cross43f08db2018-11-12 10:13:39 -080074
Colin Cross69f59a32019-02-15 10:39:37 -080075 var profile android.WritablePath
Colin Crosscbed6572019-01-08 17:38:37 -080076 if generateProfile {
Martin Stjernholm75a48d82020-01-10 20:32:59 +000077 profile = profileCommand(ctx, globalSoong, global, module, rule)
Colin Crosscbed6572019-01-08 17:38:37 -080078 }
Nicolas Geoffraye7102422019-07-24 13:19:29 +010079 if generateBootProfile {
Martin Stjernholm75a48d82020-01-10 20:32:59 +000080 bootProfileCommand(ctx, globalSoong, global, module, rule)
Nicolas Geoffraye7102422019-07-24 13:19:29 +010081 }
Colin Crosscbed6572019-01-08 17:38:37 -080082
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +000083 if !dexpreoptDisabled(ctx, global, module) {
Ulya Trafimovichfc24ad32020-08-19 16:32:54 +010084 if clc := genClassLoaderContext(ctx, global, module); clc != nil {
Colin Crosscbed6572019-01-08 17:38:37 -080085 appImage := (generateProfile || module.ForceCreateAppImage || global.DefaultAppImages) &&
86 !module.NoCreateAppImage
87
88 generateDM := shouldGenerateDM(module, global)
89
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +000090 for archIdx, _ := range module.Archs {
Ulya Trafimovichfc24ad32020-08-19 16:32:54 +010091 dexpreoptCommand(ctx, globalSoong, global, module, rule, archIdx, *clc, profile, appImage, generateDM)
Colin Crosscbed6572019-01-08 17:38:37 -080092 }
93 }
94 }
95
96 return rule, nil
97}
98
Martin Stjernholm8d80cee2020-01-31 17:44:54 +000099func dexpreoptDisabled(ctx android.PathContext, global *GlobalConfig, module *ModuleConfig) bool {
Colin Crosscbed6572019-01-08 17:38:37 -0800100 if contains(global.DisablePreoptModules, module.Name) {
101 return true
Colin Cross43f08db2018-11-12 10:13:39 -0800102 }
103
Ulya Trafimovichfc24ad32020-08-19 16:32:54 +0100104 // Don't preopt individual boot jars, they will be preopted together.
105 if global.BootJars.ContainsJar(module.Name) {
106 return true
107 }
108
Ulyana Trafimovichf2cb7e92019-11-27 12:26:49 +0000109 // Don't preopt system server jars that are updatable.
Ulya Trafimovich249386a2020-07-01 14:31:13 +0100110 if global.UpdatableSystemServerJars.ContainsJar(module.Name) {
111 return true
Ulyana Trafimovichf2cb7e92019-11-27 12:26:49 +0000112 }
113
Colin Cross43f08db2018-11-12 10:13:39 -0800114 // If OnlyPreoptBootImageAndSystemServer=true and module is not in boot class path skip
115 // Also preopt system server jars since selinux prevents system server from loading anything from
116 // /data. If we don't do this they will need to be extracted which is not favorable for RAM usage
117 // or performance. If PreoptExtractedApk is true, we ignore the only preopt boot image options.
Ulya Trafimovich249386a2020-07-01 14:31:13 +0100118 if global.OnlyPreoptBootImageAndSystemServer && !global.BootJars.ContainsJar(module.Name) &&
Colin Cross43f08db2018-11-12 10:13:39 -0800119 !contains(global.SystemServerJars, module.Name) && !module.PreoptExtractedApk {
Colin Crosscbed6572019-01-08 17:38:37 -0800120 return true
Colin Cross43f08db2018-11-12 10:13:39 -0800121 }
122
Colin Crosscbed6572019-01-08 17:38:37 -0800123 return false
Colin Cross43f08db2018-11-12 10:13:39 -0800124}
125
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000126func profileCommand(ctx android.PathContext, globalSoong *GlobalSoongConfig, global *GlobalConfig,
127 module *ModuleConfig, rule *android.RuleBuilder) android.WritablePath {
Colin Cross69f59a32019-02-15 10:39:37 -0800128
129 profilePath := module.BuildPath.InSameDir(ctx, "profile.prof")
Colin Cross43f08db2018-11-12 10:13:39 -0800130 profileInstalledPath := module.DexLocation + ".prof"
131
132 if !module.ProfileIsTextListing {
133 rule.Command().FlagWithOutput("touch ", profilePath)
134 }
135
136 cmd := rule.Command().
137 Text(`ANDROID_LOG_TAGS="*:e"`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000138 Tool(globalSoong.Profman)
Colin Cross43f08db2018-11-12 10:13:39 -0800139
140 if module.ProfileIsTextListing {
141 // The profile is a test listing of classes (used for framework jars).
142 // We need to generate the actual binary profile before being able to compile.
Colin Cross69f59a32019-02-15 10:39:37 -0800143 cmd.FlagWithInput("--create-profile-from=", module.ProfileClassListing.Path())
Colin Cross43f08db2018-11-12 10:13:39 -0800144 } else {
145 // The profile is binary profile (used for apps). Run it through profman to
146 // ensure the profile keys match the apk.
147 cmd.
148 Flag("--copy-and-update-profile-key").
Colin Cross69f59a32019-02-15 10:39:37 -0800149 FlagWithInput("--profile-file=", module.ProfileClassListing.Path())
Colin Cross43f08db2018-11-12 10:13:39 -0800150 }
151
152 cmd.
153 FlagWithInput("--apk=", module.DexPath).
154 Flag("--dex-location="+module.DexLocation).
155 FlagWithOutput("--reference-profile-file=", profilePath)
156
157 if !module.ProfileIsTextListing {
158 cmd.Text(fmt.Sprintf(`|| echo "Profile out of date for %s"`, module.DexPath))
159 }
160 rule.Install(profilePath, profileInstalledPath)
161
162 return profilePath
163}
164
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000165func bootProfileCommand(ctx android.PathContext, globalSoong *GlobalSoongConfig, global *GlobalConfig,
166 module *ModuleConfig, rule *android.RuleBuilder) android.WritablePath {
Nicolas Geoffraye7102422019-07-24 13:19:29 +0100167
168 profilePath := module.BuildPath.InSameDir(ctx, "profile.bprof")
169 profileInstalledPath := module.DexLocation + ".bprof"
170
171 if !module.ProfileIsTextListing {
172 rule.Command().FlagWithOutput("touch ", profilePath)
173 }
174
175 cmd := rule.Command().
176 Text(`ANDROID_LOG_TAGS="*:e"`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000177 Tool(globalSoong.Profman)
Nicolas Geoffraye7102422019-07-24 13:19:29 +0100178
179 // The profile is a test listing of methods.
180 // We need to generate the actual binary profile.
181 cmd.FlagWithInput("--create-profile-from=", module.ProfileBootListing.Path())
182
183 cmd.
184 Flag("--generate-boot-profile").
185 FlagWithInput("--apk=", module.DexPath).
186 Flag("--dex-location="+module.DexLocation).
187 FlagWithOutput("--reference-profile-file=", profilePath)
188
189 if !module.ProfileIsTextListing {
190 cmd.Text(fmt.Sprintf(`|| echo "Profile out of date for %s"`, module.DexPath))
191 }
192 rule.Install(profilePath, profileInstalledPath)
193
194 return profilePath
195}
196
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000197func dexpreoptCommand(ctx android.PathContext, globalSoong *GlobalSoongConfig, global *GlobalConfig,
Ulya Trafimovichfc24ad32020-08-19 16:32:54 +0100198 module *ModuleConfig, rule *android.RuleBuilder, archIdx int, classLoaderContexts classLoaderContextMap,
199 profile android.WritablePath, appImage bool, generateDM bool) {
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000200
201 arch := module.Archs[archIdx]
Colin Cross43f08db2018-11-12 10:13:39 -0800202
203 // HACK: make soname in Soong-generated .odex files match Make.
204 base := filepath.Base(module.DexLocation)
205 if filepath.Ext(base) == ".jar" {
206 base = "javalib.jar"
207 } else if filepath.Ext(base) == ".apk" {
208 base = "package.apk"
209 }
210
211 toOdexPath := func(path string) string {
212 return filepath.Join(
213 filepath.Dir(path),
214 "oat",
Colin Cross74ba9622019-02-11 15:11:14 -0800215 arch.String(),
Colin Cross43f08db2018-11-12 10:13:39 -0800216 pathtools.ReplaceExtension(filepath.Base(path), "odex"))
217 }
218
Colin Cross69f59a32019-02-15 10:39:37 -0800219 odexPath := module.BuildPath.InSameDir(ctx, "oat", arch.String(), pathtools.ReplaceExtension(base, "odex"))
Colin Cross43f08db2018-11-12 10:13:39 -0800220 odexInstallPath := toOdexPath(module.DexLocation)
221 if odexOnSystemOther(module, global) {
Anton Hansson43ab0bc2019-10-03 14:18:45 +0100222 odexInstallPath = filepath.Join(SystemOtherPartition, odexInstallPath)
Colin Cross43f08db2018-11-12 10:13:39 -0800223 }
224
Colin Cross69f59a32019-02-15 10:39:37 -0800225 vdexPath := odexPath.ReplaceExtension(ctx, "vdex")
Colin Cross43f08db2018-11-12 10:13:39 -0800226 vdexInstallPath := pathtools.ReplaceExtension(odexInstallPath, "vdex")
227
Colin Cross69f59a32019-02-15 10:39:37 -0800228 invocationPath := odexPath.ReplaceExtension(ctx, "invocation")
Alex Light5de41962018-12-18 15:16:26 -0800229
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000230 systemServerJars := NonUpdatableSystemServerJars(ctx, global)
231
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100232 rule.Command().FlagWithArg("mkdir -p ", filepath.Dir(odexPath.String()))
233 rule.Command().FlagWithOutput("rm -f ", odexPath)
Ulya Trafimovichc9af5382020-05-29 15:35:06 +0100234
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100235 if jarIndex := android.IndexList(module.Name, systemServerJars); jarIndex >= 0 {
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100236 // Copy the system server jar to a predefined location where dex2oat will find it.
237 dexPathHost := SystemServerDexJarHostPath(ctx, module.Name)
238 rule.Command().Text("mkdir -p").Flag(filepath.Dir(dexPathHost.String()))
239 rule.Command().Text("cp -f").Input(module.DexPath).Output(dexPathHost)
240
241 checkSystemServerOrder(ctx, jarIndex)
242
Ulya Trafimovich24813e12020-10-07 15:05:21 +0100243 clc := classLoaderContexts[AnySdkVersion]
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100244 rule.Command().
245 Text("class_loader_context_arg=--class-loader-context=PCL[" + strings.Join(clc.Host.Strings(), ":") + "]").
246 Implicits(clc.Host).
247 Text("stored_class_loader_context_arg=--stored-class-loader-context=PCL[" + strings.Join(clc.Target, ":") + "]")
248 } else if module.EnforceUsesLibraries {
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100249 // Generate command that saves target SDK version in a shell variable.
Colin Cross38b96852019-05-22 10:21:09 -0700250 if module.ManifestPath != nil {
251 rule.Command().Text(`target_sdk_version="$(`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000252 Tool(globalSoong.ManifestCheck).
Colin Cross38b96852019-05-22 10:21:09 -0700253 Flag("--extract-target-sdk-version").
254 Input(module.ManifestPath).
255 Text(`)"`)
256 } else {
257 // No manifest to extract targetSdkVersion from, hope that DexJar is an APK
258 rule.Command().Text(`target_sdk_version="$(`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000259 Tool(globalSoong.Aapt).
Colin Cross38b96852019-05-22 10:21:09 -0700260 Flag("dump badging").
261 Input(module.DexPath).
262 Text(`| grep "targetSdkVersion" | sed -n "s/targetSdkVersion:'\(.*\)'/\1/p"`).
263 Text(`)"`)
264 }
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100265
Ulya Trafimovich5f364b62020-06-30 12:39:01 +0100266 // Generate command that saves host and target class loader context in shell variables.
Ulya Trafimovich8130c482020-10-07 15:17:13 +0100267 clc, paths := computeClassLoaderContext(ctx, classLoaderContexts)
Ulya Trafimovich5f364b62020-06-30 12:39:01 +0100268 cmd := rule.Command().
269 Text(`eval "$(`).Tool(globalSoong.ConstructContext).
Ulya Trafimovich8130c482020-10-07 15:17:13 +0100270 Text(` --target-sdk-version ${target_sdk_version}`).
271 Text(clc).Implicits(paths)
Ulya Trafimovich5f364b62020-06-30 12:39:01 +0100272 cmd.Text(`)"`)
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100273 } else {
274 // Pass special class loader context to skip the classpath and collision check.
275 // This will get removed once LOCAL_USES_LIBRARIES is enforced.
276 // Right now LOCAL_USES_LIBRARIES is opt in, for the case where it's not specified we still default
277 // to the &.
278 rule.Command().
279 Text(`class_loader_context_arg=--class-loader-context=\&`).
280 Text(`stored_class_loader_context_arg=""`)
Colin Cross43f08db2018-11-12 10:13:39 -0800281 }
282
Nicolas Geoffray2464ef42019-03-05 14:07:07 +0000283 // Devices that do not have a product partition use a symlink from /product to /system/product.
284 // Because on-device dexopt will see dex locations starting with /product, we change the paths
285 // to mimic this behavior.
286 dexLocationArg := module.DexLocation
287 if strings.HasPrefix(dexLocationArg, "/system/product/") {
288 dexLocationArg = strings.TrimPrefix(dexLocationArg, "/system")
289 }
290
Colin Cross43f08db2018-11-12 10:13:39 -0800291 cmd := rule.Command().
292 Text(`ANDROID_LOG_TAGS="*:e"`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000293 Tool(globalSoong.Dex2oat).
Colin Cross43f08db2018-11-12 10:13:39 -0800294 Flag("--avoid-storing-invocation").
Alex Light5de41962018-12-18 15:16:26 -0800295 FlagWithOutput("--write-invocation-to=", invocationPath).ImplicitOutput(invocationPath).
Colin Cross43f08db2018-11-12 10:13:39 -0800296 Flag("--runtime-arg").FlagWithArg("-Xms", global.Dex2oatXms).
297 Flag("--runtime-arg").FlagWithArg("-Xmx", global.Dex2oatXmx).
Colin Cross800fe132019-02-11 14:21:24 -0800298 Flag("--runtime-arg").FlagWithInputList("-Xbootclasspath:", module.PreoptBootClassPathDexFiles, ":").
299 Flag("--runtime-arg").FlagWithList("-Xbootclasspath-locations:", module.PreoptBootClassPathDexLocations, ":").
Colin Cross43f08db2018-11-12 10:13:39 -0800300 Flag("${class_loader_context_arg}").
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000301 Flag("${stored_class_loader_context_arg}").
Ulya Trafimovich3391a1e2020-01-03 17:33:17 +0000302 FlagWithArg("--boot-image=", strings.Join(module.DexPreoptImageLocations, ":")).Implicits(module.DexPreoptImagesDeps[archIdx].Paths()).
Colin Cross43f08db2018-11-12 10:13:39 -0800303 FlagWithInput("--dex-file=", module.DexPath).
Nicolas Geoffray2464ef42019-03-05 14:07:07 +0000304 FlagWithArg("--dex-location=", dexLocationArg).
Colin Cross43f08db2018-11-12 10:13:39 -0800305 FlagWithOutput("--oat-file=", odexPath).ImplicitOutput(vdexPath).
306 // Pass an empty directory, dex2oat shouldn't be reading arbitrary files
307 FlagWithArg("--android-root=", global.EmptyDirectory).
Colin Cross74ba9622019-02-11 15:11:14 -0800308 FlagWithArg("--instruction-set=", arch.String()).
Colin Cross43f08db2018-11-12 10:13:39 -0800309 FlagWithArg("--instruction-set-variant=", global.CpuVariant[arch]).
310 FlagWithArg("--instruction-set-features=", global.InstructionSetFeatures[arch]).
311 Flag("--no-generate-debug-info").
312 Flag("--generate-build-id").
313 Flag("--abort-on-hard-verifier-error").
314 Flag("--force-determinism").
315 FlagWithArg("--no-inline-from=", "core-oj.jar")
316
317 var preoptFlags []string
318 if len(module.PreoptFlags) > 0 {
319 preoptFlags = module.PreoptFlags
320 } else if len(global.PreoptFlags) > 0 {
321 preoptFlags = global.PreoptFlags
322 }
323
324 if len(preoptFlags) > 0 {
325 cmd.Text(strings.Join(preoptFlags, " "))
326 }
327
328 if module.UncompressedDex {
329 cmd.FlagWithArg("--copy-dex-files=", "false")
330 }
331
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800332 if !android.PrefixInList(preoptFlags, "--compiler-filter=") {
Colin Cross43f08db2018-11-12 10:13:39 -0800333 var compilerFilter string
334 if contains(global.SystemServerJars, module.Name) {
335 // Jars of system server, use the product option if it is set, speed otherwise.
336 if global.SystemServerCompilerFilter != "" {
337 compilerFilter = global.SystemServerCompilerFilter
338 } else {
339 compilerFilter = "speed"
340 }
341 } else if contains(global.SpeedApps, module.Name) || contains(global.SystemServerApps, module.Name) {
342 // Apps loaded into system server, and apps the product default to being compiled with the
343 // 'speed' compiler filter.
344 compilerFilter = "speed"
Colin Cross69f59a32019-02-15 10:39:37 -0800345 } else if profile != nil {
Colin Cross43f08db2018-11-12 10:13:39 -0800346 // For non system server jars, use speed-profile when we have a profile.
347 compilerFilter = "speed-profile"
348 } else if global.DefaultCompilerFilter != "" {
349 compilerFilter = global.DefaultCompilerFilter
350 } else {
351 compilerFilter = "quicken"
352 }
353 cmd.FlagWithArg("--compiler-filter=", compilerFilter)
354 }
355
356 if generateDM {
357 cmd.FlagWithArg("--copy-dex-files=", "false")
Colin Cross69f59a32019-02-15 10:39:37 -0800358 dmPath := module.BuildPath.InSameDir(ctx, "generated.dm")
Colin Cross43f08db2018-11-12 10:13:39 -0800359 dmInstalledPath := pathtools.ReplaceExtension(module.DexLocation, "dm")
Colin Cross69f59a32019-02-15 10:39:37 -0800360 tmpPath := module.BuildPath.InSameDir(ctx, "primary.vdex")
Colin Cross43f08db2018-11-12 10:13:39 -0800361 rule.Command().Text("cp -f").Input(vdexPath).Output(tmpPath)
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000362 rule.Command().Tool(globalSoong.SoongZip).
Colin Cross43f08db2018-11-12 10:13:39 -0800363 FlagWithArg("-L", "9").
364 FlagWithOutput("-o", dmPath).
365 Flag("-j").
366 Input(tmpPath)
367 rule.Install(dmPath, dmInstalledPath)
368 }
369
370 // By default, emit debug info.
371 debugInfo := true
372 if global.NoDebugInfo {
373 // If the global setting suppresses mini-debug-info, disable it.
374 debugInfo = false
375 }
376
377 // PRODUCT_SYSTEM_SERVER_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO.
378 // PRODUCT_OTHER_JAVA_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO.
379 if contains(global.SystemServerJars, module.Name) {
380 if global.AlwaysSystemServerDebugInfo {
381 debugInfo = true
382 } else if global.NeverSystemServerDebugInfo {
383 debugInfo = false
384 }
385 } else {
386 if global.AlwaysOtherDebugInfo {
387 debugInfo = true
388 } else if global.NeverOtherDebugInfo {
389 debugInfo = false
390 }
391 }
392
393 // Never enable on eng.
394 if global.IsEng {
395 debugInfo = false
396 }
397
398 if debugInfo {
399 cmd.Flag("--generate-mini-debug-info")
400 } else {
401 cmd.Flag("--no-generate-mini-debug-info")
402 }
403
404 // Set the compiler reason to 'prebuilt' to identify the oat files produced
405 // during the build, as opposed to compiled on the device.
406 cmd.FlagWithArg("--compilation-reason=", "prebuilt")
407
408 if appImage {
Colin Cross69f59a32019-02-15 10:39:37 -0800409 appImagePath := odexPath.ReplaceExtension(ctx, "art")
Colin Cross43f08db2018-11-12 10:13:39 -0800410 appImageInstallPath := pathtools.ReplaceExtension(odexInstallPath, "art")
411 cmd.FlagWithOutput("--app-image-file=", appImagePath).
412 FlagWithArg("--image-format=", "lz4")
Mathieu Chartier3f7ddbb2019-04-29 09:33:50 -0700413 if !global.DontResolveStartupStrings {
414 cmd.FlagWithArg("--resolve-startup-const-strings=", "true")
415 }
Colin Cross43f08db2018-11-12 10:13:39 -0800416 rule.Install(appImagePath, appImageInstallPath)
417 }
418
Colin Cross69f59a32019-02-15 10:39:37 -0800419 if profile != nil {
420 cmd.FlagWithInput("--profile-file=", profile)
Colin Cross43f08db2018-11-12 10:13:39 -0800421 }
422
423 rule.Install(odexPath, odexInstallPath)
424 rule.Install(vdexPath, vdexInstallPath)
425}
426
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000427func shouldGenerateDM(module *ModuleConfig, global *GlobalConfig) bool {
Colin Cross43f08db2018-11-12 10:13:39 -0800428 // Generating DM files only makes sense for verify, avoid doing for non verify compiler filter APKs.
429 // No reason to use a dm file if the dex is already uncompressed.
430 return global.GenerateDMFiles && !module.UncompressedDex &&
431 contains(module.PreoptFlags, "--compiler-filter=verify")
432}
433
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000434func OdexOnSystemOtherByName(name string, dexLocation string, global *GlobalConfig) bool {
Colin Cross43f08db2018-11-12 10:13:39 -0800435 if !global.HasSystemOther {
436 return false
437 }
438
439 if global.SanitizeLite {
440 return false
441 }
442
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000443 if contains(global.SpeedApps, name) || contains(global.SystemServerApps, name) {
Colin Cross43f08db2018-11-12 10:13:39 -0800444 return false
445 }
446
447 for _, f := range global.PatternsOnSystemOther {
Anton Hanssonda4d9d92020-09-15 09:28:55 +0000448 if makefileMatch(filepath.Join(SystemPartition, f), dexLocation) {
Colin Cross43f08db2018-11-12 10:13:39 -0800449 return true
450 }
451 }
452
453 return false
454}
455
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000456func odexOnSystemOther(module *ModuleConfig, global *GlobalConfig) bool {
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000457 return OdexOnSystemOtherByName(module.Name, module.DexLocation, global)
458}
459
Colin Crossc7e40aa2019-02-08 21:37:00 -0800460// PathToLocation converts .../system/framework/arm64/boot.art to .../system/framework/boot.art
Colin Cross69f59a32019-02-15 10:39:37 -0800461func PathToLocation(path android.Path, arch android.ArchType) string {
462 pathArch := filepath.Base(filepath.Dir(path.String()))
Colin Cross74ba9622019-02-11 15:11:14 -0800463 if pathArch != arch.String() {
464 panic(fmt.Errorf("last directory in %q must be %q", path, arch.String()))
Colin Crossc7e40aa2019-02-08 21:37:00 -0800465 }
Colin Cross69f59a32019-02-15 10:39:37 -0800466 return filepath.Join(filepath.Dir(filepath.Dir(path.String())), filepath.Base(path.String()))
Colin Crossc7e40aa2019-02-08 21:37:00 -0800467}
468
Colin Cross43f08db2018-11-12 10:13:39 -0800469func makefileMatch(pattern, s string) bool {
470 percent := strings.IndexByte(pattern, '%')
471 switch percent {
472 case -1:
473 return pattern == s
474 case len(pattern) - 1:
475 return strings.HasPrefix(s, pattern[:len(pattern)-1])
476 default:
477 panic(fmt.Errorf("unsupported makefile pattern %q", pattern))
478 }
479}
480
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +0000481var nonUpdatableSystemServerJarsKey = android.NewOnceKey("nonUpdatableSystemServerJars")
482
483// TODO: eliminate the superficial global config parameter by moving global config definition
484// from java subpackage to dexpreopt.
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000485func NonUpdatableSystemServerJars(ctx android.PathContext, global *GlobalConfig) []string {
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +0000486 return ctx.Config().Once(nonUpdatableSystemServerJarsKey, func() interface{} {
Ulya Trafimovich249386a2020-07-01 14:31:13 +0100487 return android.RemoveListFromList(global.SystemServerJars, global.UpdatableSystemServerJars.CopyOfJars())
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +0000488 }).([]string)
489}
490
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000491// A predefined location for the system server dex jars. This is needed in order to generate
492// class loader context for dex2oat, as the path to the jar in the Soong module may be unknown
493// at that time (Soong processes the jars in dependency order, which may be different from the
494// the system server classpath order).
495func SystemServerDexJarHostPath(ctx android.PathContext, jar string) android.OutputPath {
Ulya Trafimovich6cf2c0c2020-04-24 12:15:20 +0100496 if DexpreoptRunningInSoong {
497 // Soong module, just use the default output directory $OUT/soong.
498 return android.PathForOutput(ctx, "system_server_dexjars", jar+".jar")
499 } else {
500 // Make module, default output directory is $OUT (passed via the "null config" created
501 // by dexpreopt_gen). Append Soong subdirectory to match Soong module paths.
502 return android.PathForOutput(ctx, "soong", "system_server_dexjars", jar+".jar")
503 }
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000504}
505
Ulya Trafimovichcd3203f2020-03-27 11:30:00 +0000506// Check the order of jars on the system server classpath and give a warning/error if a jar precedes
507// one of its dependencies. This is not an error, but a missed optimization, as dexpreopt won't
508// have the dependency jar in the class loader context, and it won't be able to resolve any
509// references to its classes and methods.
510func checkSystemServerOrder(ctx android.PathContext, jarIndex int) {
511 mctx, isModule := ctx.(android.ModuleContext)
512 if isModule {
513 config := GetGlobalConfig(ctx)
514 jars := NonUpdatableSystemServerJars(ctx, config)
515 mctx.WalkDeps(func(dep android.Module, parent android.Module) bool {
516 depIndex := android.IndexList(dep.Name(), jars)
517 if jarIndex < depIndex && !config.BrokenSuboptimalOrderOfSystemServerJars {
518 jar := jars[jarIndex]
519 dep := jars[depIndex]
520 mctx.ModuleErrorf("non-optimal order of jars on the system server classpath:"+
521 " '%s' precedes its dependency '%s', so dexpreopt is unable to resolve any"+
522 " references from '%s' to '%s'.\n", jar, dep, jar, dep)
523 }
524 return true
525 })
526 }
527}
528
Colin Cross43f08db2018-11-12 10:13:39 -0800529func contains(l []string, s string) bool {
530 for _, e := range l {
531 if e == s {
532 return true
533 }
534 }
535 return false
536}
537
Colin Cross454c0872019-02-15 23:03:34 -0800538var copyOf = android.CopyOf