blob: a07f1fa2ba9d8686da02e20401836a801148285e [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 Trafimovich69612672020-10-20 17:41:54 +010084 if clc, err := genClassLoaderContext(ctx, global, module); err != nil {
85 android.ReportPathErrorf(ctx, err.Error())
86 } else if clc != nil {
Colin Crosscbed6572019-01-08 17:38:37 -080087 appImage := (generateProfile || module.ForceCreateAppImage || global.DefaultAppImages) &&
88 !module.NoCreateAppImage
89
90 generateDM := shouldGenerateDM(module, global)
91
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +000092 for archIdx, _ := range module.Archs {
Ulya Trafimovichfc24ad32020-08-19 16:32:54 +010093 dexpreoptCommand(ctx, globalSoong, global, module, rule, archIdx, *clc, profile, appImage, generateDM)
Colin Crosscbed6572019-01-08 17:38:37 -080094 }
95 }
96 }
97
98 return rule, nil
99}
100
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000101func dexpreoptDisabled(ctx android.PathContext, global *GlobalConfig, module *ModuleConfig) bool {
Colin Crosscbed6572019-01-08 17:38:37 -0800102 if contains(global.DisablePreoptModules, module.Name) {
103 return true
Colin Cross43f08db2018-11-12 10:13:39 -0800104 }
105
Ulya Trafimovichfc24ad32020-08-19 16:32:54 +0100106 // Don't preopt individual boot jars, they will be preopted together.
107 if global.BootJars.ContainsJar(module.Name) {
108 return true
109 }
110
Ulyana Trafimovichf2cb7e92019-11-27 12:26:49 +0000111 // Don't preopt system server jars that are updatable.
Ulya Trafimovich249386a2020-07-01 14:31:13 +0100112 if global.UpdatableSystemServerJars.ContainsJar(module.Name) {
113 return true
Ulyana Trafimovichf2cb7e92019-11-27 12:26:49 +0000114 }
115
Colin Cross43f08db2018-11-12 10:13:39 -0800116 // If OnlyPreoptBootImageAndSystemServer=true and module is not in boot class path skip
117 // Also preopt system server jars since selinux prevents system server from loading anything from
118 // /data. If we don't do this they will need to be extracted which is not favorable for RAM usage
119 // or performance. If PreoptExtractedApk is true, we ignore the only preopt boot image options.
Ulya Trafimovich249386a2020-07-01 14:31:13 +0100120 if global.OnlyPreoptBootImageAndSystemServer && !global.BootJars.ContainsJar(module.Name) &&
Colin Cross43f08db2018-11-12 10:13:39 -0800121 !contains(global.SystemServerJars, module.Name) && !module.PreoptExtractedApk {
Colin Crosscbed6572019-01-08 17:38:37 -0800122 return true
Colin Cross43f08db2018-11-12 10:13:39 -0800123 }
124
Colin Crosscbed6572019-01-08 17:38:37 -0800125 return false
Colin Cross43f08db2018-11-12 10:13:39 -0800126}
127
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000128func profileCommand(ctx android.PathContext, globalSoong *GlobalSoongConfig, global *GlobalConfig,
129 module *ModuleConfig, rule *android.RuleBuilder) android.WritablePath {
Colin Cross69f59a32019-02-15 10:39:37 -0800130
131 profilePath := module.BuildPath.InSameDir(ctx, "profile.prof")
Colin Cross43f08db2018-11-12 10:13:39 -0800132 profileInstalledPath := module.DexLocation + ".prof"
133
134 if !module.ProfileIsTextListing {
135 rule.Command().FlagWithOutput("touch ", profilePath)
136 }
137
138 cmd := rule.Command().
139 Text(`ANDROID_LOG_TAGS="*:e"`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000140 Tool(globalSoong.Profman)
Colin Cross43f08db2018-11-12 10:13:39 -0800141
142 if module.ProfileIsTextListing {
143 // The profile is a test listing of classes (used for framework jars).
144 // We need to generate the actual binary profile before being able to compile.
Colin Cross69f59a32019-02-15 10:39:37 -0800145 cmd.FlagWithInput("--create-profile-from=", module.ProfileClassListing.Path())
Colin Cross43f08db2018-11-12 10:13:39 -0800146 } else {
147 // The profile is binary profile (used for apps). Run it through profman to
148 // ensure the profile keys match the apk.
149 cmd.
150 Flag("--copy-and-update-profile-key").
Colin Cross69f59a32019-02-15 10:39:37 -0800151 FlagWithInput("--profile-file=", module.ProfileClassListing.Path())
Colin Cross43f08db2018-11-12 10:13:39 -0800152 }
153
154 cmd.
155 FlagWithInput("--apk=", module.DexPath).
156 Flag("--dex-location="+module.DexLocation).
157 FlagWithOutput("--reference-profile-file=", profilePath)
158
159 if !module.ProfileIsTextListing {
160 cmd.Text(fmt.Sprintf(`|| echo "Profile out of date for %s"`, module.DexPath))
161 }
162 rule.Install(profilePath, profileInstalledPath)
163
164 return profilePath
165}
166
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000167func bootProfileCommand(ctx android.PathContext, globalSoong *GlobalSoongConfig, global *GlobalConfig,
168 module *ModuleConfig, rule *android.RuleBuilder) android.WritablePath {
Nicolas Geoffraye7102422019-07-24 13:19:29 +0100169
170 profilePath := module.BuildPath.InSameDir(ctx, "profile.bprof")
171 profileInstalledPath := module.DexLocation + ".bprof"
172
173 if !module.ProfileIsTextListing {
174 rule.Command().FlagWithOutput("touch ", profilePath)
175 }
176
177 cmd := rule.Command().
178 Text(`ANDROID_LOG_TAGS="*:e"`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000179 Tool(globalSoong.Profman)
Nicolas Geoffraye7102422019-07-24 13:19:29 +0100180
181 // The profile is a test listing of methods.
182 // We need to generate the actual binary profile.
183 cmd.FlagWithInput("--create-profile-from=", module.ProfileBootListing.Path())
184
185 cmd.
186 Flag("--generate-boot-profile").
187 FlagWithInput("--apk=", module.DexPath).
188 Flag("--dex-location="+module.DexLocation).
189 FlagWithOutput("--reference-profile-file=", profilePath)
190
191 if !module.ProfileIsTextListing {
192 cmd.Text(fmt.Sprintf(`|| echo "Profile out of date for %s"`, module.DexPath))
193 }
194 rule.Install(profilePath, profileInstalledPath)
195
196 return profilePath
197}
198
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000199func dexpreoptCommand(ctx android.PathContext, globalSoong *GlobalSoongConfig, global *GlobalConfig,
Ulya Trafimovichfc24ad32020-08-19 16:32:54 +0100200 module *ModuleConfig, rule *android.RuleBuilder, archIdx int, classLoaderContexts classLoaderContextMap,
201 profile android.WritablePath, appImage bool, generateDM bool) {
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000202
203 arch := module.Archs[archIdx]
Colin Cross43f08db2018-11-12 10:13:39 -0800204
205 // HACK: make soname in Soong-generated .odex files match Make.
206 base := filepath.Base(module.DexLocation)
207 if filepath.Ext(base) == ".jar" {
208 base = "javalib.jar"
209 } else if filepath.Ext(base) == ".apk" {
210 base = "package.apk"
211 }
212
213 toOdexPath := func(path string) string {
214 return filepath.Join(
215 filepath.Dir(path),
216 "oat",
Colin Cross74ba9622019-02-11 15:11:14 -0800217 arch.String(),
Colin Cross43f08db2018-11-12 10:13:39 -0800218 pathtools.ReplaceExtension(filepath.Base(path), "odex"))
219 }
220
Colin Cross69f59a32019-02-15 10:39:37 -0800221 odexPath := module.BuildPath.InSameDir(ctx, "oat", arch.String(), pathtools.ReplaceExtension(base, "odex"))
Colin Cross43f08db2018-11-12 10:13:39 -0800222 odexInstallPath := toOdexPath(module.DexLocation)
223 if odexOnSystemOther(module, global) {
Anton Hansson43ab0bc2019-10-03 14:18:45 +0100224 odexInstallPath = filepath.Join(SystemOtherPartition, odexInstallPath)
Colin Cross43f08db2018-11-12 10:13:39 -0800225 }
226
Colin Cross69f59a32019-02-15 10:39:37 -0800227 vdexPath := odexPath.ReplaceExtension(ctx, "vdex")
Colin Cross43f08db2018-11-12 10:13:39 -0800228 vdexInstallPath := pathtools.ReplaceExtension(odexInstallPath, "vdex")
229
Colin Cross69f59a32019-02-15 10:39:37 -0800230 invocationPath := odexPath.ReplaceExtension(ctx, "invocation")
Alex Light5de41962018-12-18 15:16:26 -0800231
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000232 systemServerJars := NonUpdatableSystemServerJars(ctx, global)
233
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100234 rule.Command().FlagWithArg("mkdir -p ", filepath.Dir(odexPath.String()))
235 rule.Command().FlagWithOutput("rm -f ", odexPath)
Ulya Trafimovichc9af5382020-05-29 15:35:06 +0100236
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100237 if jarIndex := android.IndexList(module.Name, systemServerJars); jarIndex >= 0 {
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100238 // Copy the system server jar to a predefined location where dex2oat will find it.
239 dexPathHost := SystemServerDexJarHostPath(ctx, module.Name)
240 rule.Command().Text("mkdir -p").Flag(filepath.Dir(dexPathHost.String()))
241 rule.Command().Text("cp -f").Input(module.DexPath).Output(dexPathHost)
242
243 checkSystemServerOrder(ctx, jarIndex)
244
Ulya Trafimovich24813e12020-10-07 15:05:21 +0100245 clc := classLoaderContexts[AnySdkVersion]
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100246 rule.Command().
247 Text("class_loader_context_arg=--class-loader-context=PCL[" + strings.Join(clc.Host.Strings(), ":") + "]").
248 Implicits(clc.Host).
249 Text("stored_class_loader_context_arg=--stored-class-loader-context=PCL[" + strings.Join(clc.Target, ":") + "]")
250 } else if module.EnforceUsesLibraries {
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100251 // Generate command that saves target SDK version in a shell variable.
Colin Cross38b96852019-05-22 10:21:09 -0700252 if module.ManifestPath != nil {
253 rule.Command().Text(`target_sdk_version="$(`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000254 Tool(globalSoong.ManifestCheck).
Colin Cross38b96852019-05-22 10:21:09 -0700255 Flag("--extract-target-sdk-version").
256 Input(module.ManifestPath).
257 Text(`)"`)
258 } else {
259 // No manifest to extract targetSdkVersion from, hope that DexJar is an APK
260 rule.Command().Text(`target_sdk_version="$(`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000261 Tool(globalSoong.Aapt).
Colin Cross38b96852019-05-22 10:21:09 -0700262 Flag("dump badging").
263 Input(module.DexPath).
264 Text(`| grep "targetSdkVersion" | sed -n "s/targetSdkVersion:'\(.*\)'/\1/p"`).
265 Text(`)"`)
266 }
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100267
Ulya Trafimovich5f364b62020-06-30 12:39:01 +0100268 // Generate command that saves host and target class loader context in shell variables.
Ulya Trafimovich8130c482020-10-07 15:17:13 +0100269 clc, paths := computeClassLoaderContext(ctx, classLoaderContexts)
Ulya Trafimovich5f364b62020-06-30 12:39:01 +0100270 cmd := rule.Command().
271 Text(`eval "$(`).Tool(globalSoong.ConstructContext).
Ulya Trafimovich8130c482020-10-07 15:17:13 +0100272 Text(` --target-sdk-version ${target_sdk_version}`).
273 Text(clc).Implicits(paths)
Ulya Trafimovich5f364b62020-06-30 12:39:01 +0100274 cmd.Text(`)"`)
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100275 } else {
276 // Pass special class loader context to skip the classpath and collision check.
277 // This will get removed once LOCAL_USES_LIBRARIES is enforced.
278 // Right now LOCAL_USES_LIBRARIES is opt in, for the case where it's not specified we still default
279 // to the &.
280 rule.Command().
281 Text(`class_loader_context_arg=--class-loader-context=\&`).
282 Text(`stored_class_loader_context_arg=""`)
Colin Cross43f08db2018-11-12 10:13:39 -0800283 }
284
Nicolas Geoffray2464ef42019-03-05 14:07:07 +0000285 // Devices that do not have a product partition use a symlink from /product to /system/product.
286 // Because on-device dexopt will see dex locations starting with /product, we change the paths
287 // to mimic this behavior.
288 dexLocationArg := module.DexLocation
289 if strings.HasPrefix(dexLocationArg, "/system/product/") {
290 dexLocationArg = strings.TrimPrefix(dexLocationArg, "/system")
291 }
292
Colin Cross43f08db2018-11-12 10:13:39 -0800293 cmd := rule.Command().
294 Text(`ANDROID_LOG_TAGS="*:e"`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000295 Tool(globalSoong.Dex2oat).
Colin Cross43f08db2018-11-12 10:13:39 -0800296 Flag("--avoid-storing-invocation").
Alex Light5de41962018-12-18 15:16:26 -0800297 FlagWithOutput("--write-invocation-to=", invocationPath).ImplicitOutput(invocationPath).
Colin Cross43f08db2018-11-12 10:13:39 -0800298 Flag("--runtime-arg").FlagWithArg("-Xms", global.Dex2oatXms).
299 Flag("--runtime-arg").FlagWithArg("-Xmx", global.Dex2oatXmx).
Colin Cross800fe132019-02-11 14:21:24 -0800300 Flag("--runtime-arg").FlagWithInputList("-Xbootclasspath:", module.PreoptBootClassPathDexFiles, ":").
301 Flag("--runtime-arg").FlagWithList("-Xbootclasspath-locations:", module.PreoptBootClassPathDexLocations, ":").
Colin Cross43f08db2018-11-12 10:13:39 -0800302 Flag("${class_loader_context_arg}").
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000303 Flag("${stored_class_loader_context_arg}").
Ulya Trafimovich3391a1e2020-01-03 17:33:17 +0000304 FlagWithArg("--boot-image=", strings.Join(module.DexPreoptImageLocations, ":")).Implicits(module.DexPreoptImagesDeps[archIdx].Paths()).
Colin Cross43f08db2018-11-12 10:13:39 -0800305 FlagWithInput("--dex-file=", module.DexPath).
Nicolas Geoffray2464ef42019-03-05 14:07:07 +0000306 FlagWithArg("--dex-location=", dexLocationArg).
Colin Cross43f08db2018-11-12 10:13:39 -0800307 FlagWithOutput("--oat-file=", odexPath).ImplicitOutput(vdexPath).
308 // Pass an empty directory, dex2oat shouldn't be reading arbitrary files
309 FlagWithArg("--android-root=", global.EmptyDirectory).
Colin Cross74ba9622019-02-11 15:11:14 -0800310 FlagWithArg("--instruction-set=", arch.String()).
Colin Cross43f08db2018-11-12 10:13:39 -0800311 FlagWithArg("--instruction-set-variant=", global.CpuVariant[arch]).
312 FlagWithArg("--instruction-set-features=", global.InstructionSetFeatures[arch]).
313 Flag("--no-generate-debug-info").
314 Flag("--generate-build-id").
315 Flag("--abort-on-hard-verifier-error").
316 Flag("--force-determinism").
317 FlagWithArg("--no-inline-from=", "core-oj.jar")
318
319 var preoptFlags []string
320 if len(module.PreoptFlags) > 0 {
321 preoptFlags = module.PreoptFlags
322 } else if len(global.PreoptFlags) > 0 {
323 preoptFlags = global.PreoptFlags
324 }
325
326 if len(preoptFlags) > 0 {
327 cmd.Text(strings.Join(preoptFlags, " "))
328 }
329
330 if module.UncompressedDex {
331 cmd.FlagWithArg("--copy-dex-files=", "false")
332 }
333
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800334 if !android.PrefixInList(preoptFlags, "--compiler-filter=") {
Colin Cross43f08db2018-11-12 10:13:39 -0800335 var compilerFilter string
336 if contains(global.SystemServerJars, module.Name) {
337 // Jars of system server, use the product option if it is set, speed otherwise.
338 if global.SystemServerCompilerFilter != "" {
339 compilerFilter = global.SystemServerCompilerFilter
340 } else {
341 compilerFilter = "speed"
342 }
343 } else if contains(global.SpeedApps, module.Name) || contains(global.SystemServerApps, module.Name) {
344 // Apps loaded into system server, and apps the product default to being compiled with the
345 // 'speed' compiler filter.
346 compilerFilter = "speed"
Colin Cross69f59a32019-02-15 10:39:37 -0800347 } else if profile != nil {
Colin Cross43f08db2018-11-12 10:13:39 -0800348 // For non system server jars, use speed-profile when we have a profile.
349 compilerFilter = "speed-profile"
350 } else if global.DefaultCompilerFilter != "" {
351 compilerFilter = global.DefaultCompilerFilter
352 } else {
353 compilerFilter = "quicken"
354 }
355 cmd.FlagWithArg("--compiler-filter=", compilerFilter)
356 }
357
358 if generateDM {
359 cmd.FlagWithArg("--copy-dex-files=", "false")
Colin Cross69f59a32019-02-15 10:39:37 -0800360 dmPath := module.BuildPath.InSameDir(ctx, "generated.dm")
Colin Cross43f08db2018-11-12 10:13:39 -0800361 dmInstalledPath := pathtools.ReplaceExtension(module.DexLocation, "dm")
Colin Cross69f59a32019-02-15 10:39:37 -0800362 tmpPath := module.BuildPath.InSameDir(ctx, "primary.vdex")
Colin Cross43f08db2018-11-12 10:13:39 -0800363 rule.Command().Text("cp -f").Input(vdexPath).Output(tmpPath)
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000364 rule.Command().Tool(globalSoong.SoongZip).
Colin Cross43f08db2018-11-12 10:13:39 -0800365 FlagWithArg("-L", "9").
366 FlagWithOutput("-o", dmPath).
367 Flag("-j").
368 Input(tmpPath)
369 rule.Install(dmPath, dmInstalledPath)
370 }
371
372 // By default, emit debug info.
373 debugInfo := true
374 if global.NoDebugInfo {
375 // If the global setting suppresses mini-debug-info, disable it.
376 debugInfo = false
377 }
378
379 // PRODUCT_SYSTEM_SERVER_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO.
380 // PRODUCT_OTHER_JAVA_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO.
381 if contains(global.SystemServerJars, module.Name) {
382 if global.AlwaysSystemServerDebugInfo {
383 debugInfo = true
384 } else if global.NeverSystemServerDebugInfo {
385 debugInfo = false
386 }
387 } else {
388 if global.AlwaysOtherDebugInfo {
389 debugInfo = true
390 } else if global.NeverOtherDebugInfo {
391 debugInfo = false
392 }
393 }
394
395 // Never enable on eng.
396 if global.IsEng {
397 debugInfo = false
398 }
399
400 if debugInfo {
401 cmd.Flag("--generate-mini-debug-info")
402 } else {
403 cmd.Flag("--no-generate-mini-debug-info")
404 }
405
406 // Set the compiler reason to 'prebuilt' to identify the oat files produced
407 // during the build, as opposed to compiled on the device.
408 cmd.FlagWithArg("--compilation-reason=", "prebuilt")
409
410 if appImage {
Colin Cross69f59a32019-02-15 10:39:37 -0800411 appImagePath := odexPath.ReplaceExtension(ctx, "art")
Colin Cross43f08db2018-11-12 10:13:39 -0800412 appImageInstallPath := pathtools.ReplaceExtension(odexInstallPath, "art")
413 cmd.FlagWithOutput("--app-image-file=", appImagePath).
414 FlagWithArg("--image-format=", "lz4")
Mathieu Chartier3f7ddbb2019-04-29 09:33:50 -0700415 if !global.DontResolveStartupStrings {
416 cmd.FlagWithArg("--resolve-startup-const-strings=", "true")
417 }
Colin Cross43f08db2018-11-12 10:13:39 -0800418 rule.Install(appImagePath, appImageInstallPath)
419 }
420
Colin Cross69f59a32019-02-15 10:39:37 -0800421 if profile != nil {
422 cmd.FlagWithInput("--profile-file=", profile)
Colin Cross43f08db2018-11-12 10:13:39 -0800423 }
424
425 rule.Install(odexPath, odexInstallPath)
426 rule.Install(vdexPath, vdexInstallPath)
427}
428
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000429func shouldGenerateDM(module *ModuleConfig, global *GlobalConfig) bool {
Colin Cross43f08db2018-11-12 10:13:39 -0800430 // Generating DM files only makes sense for verify, avoid doing for non verify compiler filter APKs.
431 // No reason to use a dm file if the dex is already uncompressed.
432 return global.GenerateDMFiles && !module.UncompressedDex &&
433 contains(module.PreoptFlags, "--compiler-filter=verify")
434}
435
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000436func OdexOnSystemOtherByName(name string, dexLocation string, global *GlobalConfig) bool {
Colin Cross43f08db2018-11-12 10:13:39 -0800437 if !global.HasSystemOther {
438 return false
439 }
440
441 if global.SanitizeLite {
442 return false
443 }
444
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000445 if contains(global.SpeedApps, name) || contains(global.SystemServerApps, name) {
Colin Cross43f08db2018-11-12 10:13:39 -0800446 return false
447 }
448
449 for _, f := range global.PatternsOnSystemOther {
Anton Hanssonda4d9d92020-09-15 09:28:55 +0000450 if makefileMatch(filepath.Join(SystemPartition, f), dexLocation) {
Colin Cross43f08db2018-11-12 10:13:39 -0800451 return true
452 }
453 }
454
455 return false
456}
457
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000458func odexOnSystemOther(module *ModuleConfig, global *GlobalConfig) bool {
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000459 return OdexOnSystemOtherByName(module.Name, module.DexLocation, global)
460}
461
Colin Crossc7e40aa2019-02-08 21:37:00 -0800462// PathToLocation converts .../system/framework/arm64/boot.art to .../system/framework/boot.art
Colin Cross69f59a32019-02-15 10:39:37 -0800463func PathToLocation(path android.Path, arch android.ArchType) string {
464 pathArch := filepath.Base(filepath.Dir(path.String()))
Colin Cross74ba9622019-02-11 15:11:14 -0800465 if pathArch != arch.String() {
466 panic(fmt.Errorf("last directory in %q must be %q", path, arch.String()))
Colin Crossc7e40aa2019-02-08 21:37:00 -0800467 }
Colin Cross69f59a32019-02-15 10:39:37 -0800468 return filepath.Join(filepath.Dir(filepath.Dir(path.String())), filepath.Base(path.String()))
Colin Crossc7e40aa2019-02-08 21:37:00 -0800469}
470
Colin Cross43f08db2018-11-12 10:13:39 -0800471func makefileMatch(pattern, s string) bool {
472 percent := strings.IndexByte(pattern, '%')
473 switch percent {
474 case -1:
475 return pattern == s
476 case len(pattern) - 1:
477 return strings.HasPrefix(s, pattern[:len(pattern)-1])
478 default:
479 panic(fmt.Errorf("unsupported makefile pattern %q", pattern))
480 }
481}
482
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +0000483var nonUpdatableSystemServerJarsKey = android.NewOnceKey("nonUpdatableSystemServerJars")
484
485// TODO: eliminate the superficial global config parameter by moving global config definition
486// from java subpackage to dexpreopt.
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000487func NonUpdatableSystemServerJars(ctx android.PathContext, global *GlobalConfig) []string {
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +0000488 return ctx.Config().Once(nonUpdatableSystemServerJarsKey, func() interface{} {
Ulya Trafimovich249386a2020-07-01 14:31:13 +0100489 return android.RemoveListFromList(global.SystemServerJars, global.UpdatableSystemServerJars.CopyOfJars())
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +0000490 }).([]string)
491}
492
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000493// A predefined location for the system server dex jars. This is needed in order to generate
494// class loader context for dex2oat, as the path to the jar in the Soong module may be unknown
495// at that time (Soong processes the jars in dependency order, which may be different from the
496// the system server classpath order).
497func SystemServerDexJarHostPath(ctx android.PathContext, jar string) android.OutputPath {
Ulya Trafimovich6cf2c0c2020-04-24 12:15:20 +0100498 if DexpreoptRunningInSoong {
499 // Soong module, just use the default output directory $OUT/soong.
500 return android.PathForOutput(ctx, "system_server_dexjars", jar+".jar")
501 } else {
502 // Make module, default output directory is $OUT (passed via the "null config" created
503 // by dexpreopt_gen). Append Soong subdirectory to match Soong module paths.
504 return android.PathForOutput(ctx, "soong", "system_server_dexjars", jar+".jar")
505 }
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000506}
507
Ulya Trafimovichcd3203f2020-03-27 11:30:00 +0000508// Check the order of jars on the system server classpath and give a warning/error if a jar precedes
509// one of its dependencies. This is not an error, but a missed optimization, as dexpreopt won't
510// have the dependency jar in the class loader context, and it won't be able to resolve any
511// references to its classes and methods.
512func checkSystemServerOrder(ctx android.PathContext, jarIndex int) {
513 mctx, isModule := ctx.(android.ModuleContext)
514 if isModule {
515 config := GetGlobalConfig(ctx)
516 jars := NonUpdatableSystemServerJars(ctx, config)
517 mctx.WalkDeps(func(dep android.Module, parent android.Module) bool {
518 depIndex := android.IndexList(dep.Name(), jars)
519 if jarIndex < depIndex && !config.BrokenSuboptimalOrderOfSystemServerJars {
520 jar := jars[jarIndex]
521 dep := jars[depIndex]
522 mctx.ModuleErrorf("non-optimal order of jars on the system server classpath:"+
523 " '%s' precedes its dependency '%s', so dexpreopt is unable to resolve any"+
524 " references from '%s' to '%s'.\n", jar, dep, jar, dep)
525 }
526 return true
527 })
528 }
529}
530
Colin Cross43f08db2018-11-12 10:13:39 -0800531func contains(l []string, s string) bool {
532 for _, e := range l {
533 if e == s {
534 return true
535 }
536 }
537 return false
538}
539
Colin Cross454c0872019-02-15 23:03:34 -0800540var copyOf = android.CopyOf