blob: b0a684eed69175bc761bb81a7c86977e4e7423f4 [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().
Colin Crossf1a035e2020-11-16 17:32:30 -080054func GenerateDexpreoptRule(ctx android.BuilderContext, globalSoong *GlobalSoongConfig,
Martin Stjernholm8d80cee2020-01-31 17:44:54 +000055 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 Crossf1a035e2020-11-16 17:32:30 -080070 rule = android.NewRuleBuilder(pctx, ctx)
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 Trafimovich8cbc5d22020-11-03 15:15:46 +000084 if valid, err := validateClassLoaderContext(module.ClassLoaderContexts); err != nil {
Ulya Trafimovich69612672020-10-20 17:41:54 +010085 android.ReportPathErrorf(ctx, err.Error())
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +000086 } else if valid {
87 fixClassLoaderContext(module.ClassLoaderContexts)
88
Colin Crosscbed6572019-01-08 17:38:37 -080089 appImage := (generateProfile || module.ForceCreateAppImage || global.DefaultAppImages) &&
90 !module.NoCreateAppImage
91
92 generateDM := shouldGenerateDM(module, global)
93
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +000094 for archIdx, _ := range module.Archs {
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +000095 dexpreoptCommand(ctx, globalSoong, global, module, rule, archIdx, profile, appImage, generateDM)
Colin Crosscbed6572019-01-08 17:38:37 -080096 }
97 }
98 }
99
100 return rule, nil
101}
102
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000103func dexpreoptDisabled(ctx android.PathContext, global *GlobalConfig, module *ModuleConfig) bool {
Colin Crosscbed6572019-01-08 17:38:37 -0800104 if contains(global.DisablePreoptModules, module.Name) {
105 return true
Colin Cross43f08db2018-11-12 10:13:39 -0800106 }
107
Ulya Trafimovichfc24ad32020-08-19 16:32:54 +0100108 // Don't preopt individual boot jars, they will be preopted together.
109 if global.BootJars.ContainsJar(module.Name) {
110 return true
111 }
112
Ulyana Trafimovichf2cb7e92019-11-27 12:26:49 +0000113 // Don't preopt system server jars that are updatable.
Ulya Trafimovich249386a2020-07-01 14:31:13 +0100114 if global.UpdatableSystemServerJars.ContainsJar(module.Name) {
115 return true
Ulyana Trafimovichf2cb7e92019-11-27 12:26:49 +0000116 }
117
Colin Cross43f08db2018-11-12 10:13:39 -0800118 // If OnlyPreoptBootImageAndSystemServer=true and module is not in boot class path skip
119 // Also preopt system server jars since selinux prevents system server from loading anything from
120 // /data. If we don't do this they will need to be extracted which is not favorable for RAM usage
121 // or performance. If PreoptExtractedApk is true, we ignore the only preopt boot image options.
Ulya Trafimovich249386a2020-07-01 14:31:13 +0100122 if global.OnlyPreoptBootImageAndSystemServer && !global.BootJars.ContainsJar(module.Name) &&
Colin Cross43f08db2018-11-12 10:13:39 -0800123 !contains(global.SystemServerJars, module.Name) && !module.PreoptExtractedApk {
Colin Crosscbed6572019-01-08 17:38:37 -0800124 return true
Colin Cross43f08db2018-11-12 10:13:39 -0800125 }
126
Colin Crosscbed6572019-01-08 17:38:37 -0800127 return false
Colin Cross43f08db2018-11-12 10:13:39 -0800128}
129
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000130func profileCommand(ctx android.PathContext, globalSoong *GlobalSoongConfig, global *GlobalConfig,
131 module *ModuleConfig, rule *android.RuleBuilder) android.WritablePath {
Colin Cross69f59a32019-02-15 10:39:37 -0800132
133 profilePath := module.BuildPath.InSameDir(ctx, "profile.prof")
Colin Cross43f08db2018-11-12 10:13:39 -0800134 profileInstalledPath := module.DexLocation + ".prof"
135
136 if !module.ProfileIsTextListing {
137 rule.Command().FlagWithOutput("touch ", profilePath)
138 }
139
140 cmd := rule.Command().
141 Text(`ANDROID_LOG_TAGS="*:e"`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000142 Tool(globalSoong.Profman)
Colin Cross43f08db2018-11-12 10:13:39 -0800143
144 if module.ProfileIsTextListing {
145 // The profile is a test listing of classes (used for framework jars).
146 // We need to generate the actual binary profile before being able to compile.
Colin Cross69f59a32019-02-15 10:39:37 -0800147 cmd.FlagWithInput("--create-profile-from=", module.ProfileClassListing.Path())
Colin Cross43f08db2018-11-12 10:13:39 -0800148 } else {
149 // The profile is binary profile (used for apps). Run it through profman to
150 // ensure the profile keys match the apk.
151 cmd.
152 Flag("--copy-and-update-profile-key").
Colin Cross69f59a32019-02-15 10:39:37 -0800153 FlagWithInput("--profile-file=", module.ProfileClassListing.Path())
Colin Cross43f08db2018-11-12 10:13:39 -0800154 }
155
156 cmd.
157 FlagWithInput("--apk=", module.DexPath).
158 Flag("--dex-location="+module.DexLocation).
159 FlagWithOutput("--reference-profile-file=", profilePath)
160
161 if !module.ProfileIsTextListing {
162 cmd.Text(fmt.Sprintf(`|| echo "Profile out of date for %s"`, module.DexPath))
163 }
164 rule.Install(profilePath, profileInstalledPath)
165
166 return profilePath
167}
168
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000169func bootProfileCommand(ctx android.PathContext, globalSoong *GlobalSoongConfig, global *GlobalConfig,
170 module *ModuleConfig, rule *android.RuleBuilder) android.WritablePath {
Nicolas Geoffraye7102422019-07-24 13:19:29 +0100171
172 profilePath := module.BuildPath.InSameDir(ctx, "profile.bprof")
173 profileInstalledPath := module.DexLocation + ".bprof"
174
175 if !module.ProfileIsTextListing {
176 rule.Command().FlagWithOutput("touch ", profilePath)
177 }
178
179 cmd := rule.Command().
180 Text(`ANDROID_LOG_TAGS="*:e"`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000181 Tool(globalSoong.Profman)
Nicolas Geoffraye7102422019-07-24 13:19:29 +0100182
183 // The profile is a test listing of methods.
184 // We need to generate the actual binary profile.
185 cmd.FlagWithInput("--create-profile-from=", module.ProfileBootListing.Path())
186
187 cmd.
188 Flag("--generate-boot-profile").
189 FlagWithInput("--apk=", module.DexPath).
190 Flag("--dex-location="+module.DexLocation).
191 FlagWithOutput("--reference-profile-file=", profilePath)
192
193 if !module.ProfileIsTextListing {
194 cmd.Text(fmt.Sprintf(`|| echo "Profile out of date for %s"`, module.DexPath))
195 }
196 rule.Install(profilePath, profileInstalledPath)
197
198 return profilePath
199}
200
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000201func dexpreoptCommand(ctx android.PathContext, globalSoong *GlobalSoongConfig, global *GlobalConfig,
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000202 module *ModuleConfig, rule *android.RuleBuilder, archIdx int, profile android.WritablePath,
203 appImage bool, generateDM bool) {
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000204
205 arch := module.Archs[archIdx]
Colin Cross43f08db2018-11-12 10:13:39 -0800206
207 // HACK: make soname in Soong-generated .odex files match Make.
208 base := filepath.Base(module.DexLocation)
209 if filepath.Ext(base) == ".jar" {
210 base = "javalib.jar"
211 } else if filepath.Ext(base) == ".apk" {
212 base = "package.apk"
213 }
214
215 toOdexPath := func(path string) string {
216 return filepath.Join(
217 filepath.Dir(path),
218 "oat",
Colin Cross74ba9622019-02-11 15:11:14 -0800219 arch.String(),
Colin Cross43f08db2018-11-12 10:13:39 -0800220 pathtools.ReplaceExtension(filepath.Base(path), "odex"))
221 }
222
Colin Cross69f59a32019-02-15 10:39:37 -0800223 odexPath := module.BuildPath.InSameDir(ctx, "oat", arch.String(), pathtools.ReplaceExtension(base, "odex"))
Colin Cross43f08db2018-11-12 10:13:39 -0800224 odexInstallPath := toOdexPath(module.DexLocation)
225 if odexOnSystemOther(module, global) {
Anton Hansson43ab0bc2019-10-03 14:18:45 +0100226 odexInstallPath = filepath.Join(SystemOtherPartition, odexInstallPath)
Colin Cross43f08db2018-11-12 10:13:39 -0800227 }
228
Colin Cross69f59a32019-02-15 10:39:37 -0800229 vdexPath := odexPath.ReplaceExtension(ctx, "vdex")
Colin Cross43f08db2018-11-12 10:13:39 -0800230 vdexInstallPath := pathtools.ReplaceExtension(odexInstallPath, "vdex")
231
Colin Cross69f59a32019-02-15 10:39:37 -0800232 invocationPath := odexPath.ReplaceExtension(ctx, "invocation")
Alex Light5de41962018-12-18 15:16:26 -0800233
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000234 systemServerJars := NonUpdatableSystemServerJars(ctx, global)
235
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100236 rule.Command().FlagWithArg("mkdir -p ", filepath.Dir(odexPath.String()))
237 rule.Command().FlagWithOutput("rm -f ", odexPath)
Ulya Trafimovichc9af5382020-05-29 15:35:06 +0100238
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100239 if jarIndex := android.IndexList(module.Name, systemServerJars); jarIndex >= 0 {
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000240 // System server jars should be dexpreopted together: class loader context of each jar
241 // should include all preceding jars on the system server classpath.
242
243 var clcHost android.Paths
244 var clcTarget []string
245 for _, lib := range systemServerJars[:jarIndex] {
246 clcHost = append(clcHost, SystemServerDexJarHostPath(ctx, lib))
247 clcTarget = append(clcTarget, filepath.Join("/system/framework", lib+".jar"))
248 }
249
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100250 // Copy the system server jar to a predefined location where dex2oat will find it.
251 dexPathHost := SystemServerDexJarHostPath(ctx, module.Name)
252 rule.Command().Text("mkdir -p").Flag(filepath.Dir(dexPathHost.String()))
253 rule.Command().Text("cp -f").Input(module.DexPath).Output(dexPathHost)
254
255 checkSystemServerOrder(ctx, jarIndex)
256
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100257 rule.Command().
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000258 Text("class_loader_context_arg=--class-loader-context=PCL[" + strings.Join(clcHost.Strings(), ":") + "]").
259 Implicits(clcHost).
260 Text("stored_class_loader_context_arg=--stored-class-loader-context=PCL[" + strings.Join(clcTarget, ":") + "]")
261
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100262 } else if module.EnforceUsesLibraries {
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100263 // Generate command that saves target SDK version in a shell variable.
Colin Cross38b96852019-05-22 10:21:09 -0700264 if module.ManifestPath != nil {
265 rule.Command().Text(`target_sdk_version="$(`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000266 Tool(globalSoong.ManifestCheck).
Colin Cross38b96852019-05-22 10:21:09 -0700267 Flag("--extract-target-sdk-version").
268 Input(module.ManifestPath).
269 Text(`)"`)
270 } else {
271 // No manifest to extract targetSdkVersion from, hope that DexJar is an APK
272 rule.Command().Text(`target_sdk_version="$(`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000273 Tool(globalSoong.Aapt).
Colin Cross38b96852019-05-22 10:21:09 -0700274 Flag("dump badging").
275 Input(module.DexPath).
276 Text(`| grep "targetSdkVersion" | sed -n "s/targetSdkVersion:'\(.*\)'/\1/p"`).
277 Text(`)"`)
278 }
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100279
Ulya Trafimovich5f364b62020-06-30 12:39:01 +0100280 // Generate command that saves host and target class loader context in shell variables.
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000281 clc, paths := ComputeClassLoaderContext(module.ClassLoaderContexts)
Ulya Trafimovich5f364b62020-06-30 12:39:01 +0100282 cmd := rule.Command().
283 Text(`eval "$(`).Tool(globalSoong.ConstructContext).
Ulya Trafimovich8130c482020-10-07 15:17:13 +0100284 Text(` --target-sdk-version ${target_sdk_version}`).
285 Text(clc).Implicits(paths)
Ulya Trafimovich5f364b62020-06-30 12:39:01 +0100286 cmd.Text(`)"`)
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000287
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100288 } else {
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000289 // Other libraries or APKs for which the exact <uses-library> list is unknown.
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100290 // Pass special class loader context to skip the classpath and collision check.
291 // This will get removed once LOCAL_USES_LIBRARIES is enforced.
292 // Right now LOCAL_USES_LIBRARIES is opt in, for the case where it's not specified we still default
293 // to the &.
294 rule.Command().
295 Text(`class_loader_context_arg=--class-loader-context=\&`).
296 Text(`stored_class_loader_context_arg=""`)
Colin Cross43f08db2018-11-12 10:13:39 -0800297 }
298
Nicolas Geoffray2464ef42019-03-05 14:07:07 +0000299 // Devices that do not have a product partition use a symlink from /product to /system/product.
300 // Because on-device dexopt will see dex locations starting with /product, we change the paths
301 // to mimic this behavior.
302 dexLocationArg := module.DexLocation
303 if strings.HasPrefix(dexLocationArg, "/system/product/") {
304 dexLocationArg = strings.TrimPrefix(dexLocationArg, "/system")
305 }
306
Colin Cross43f08db2018-11-12 10:13:39 -0800307 cmd := rule.Command().
308 Text(`ANDROID_LOG_TAGS="*:e"`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000309 Tool(globalSoong.Dex2oat).
Colin Cross43f08db2018-11-12 10:13:39 -0800310 Flag("--avoid-storing-invocation").
Alex Light5de41962018-12-18 15:16:26 -0800311 FlagWithOutput("--write-invocation-to=", invocationPath).ImplicitOutput(invocationPath).
Colin Cross43f08db2018-11-12 10:13:39 -0800312 Flag("--runtime-arg").FlagWithArg("-Xms", global.Dex2oatXms).
313 Flag("--runtime-arg").FlagWithArg("-Xmx", global.Dex2oatXmx).
Colin Cross800fe132019-02-11 14:21:24 -0800314 Flag("--runtime-arg").FlagWithInputList("-Xbootclasspath:", module.PreoptBootClassPathDexFiles, ":").
315 Flag("--runtime-arg").FlagWithList("-Xbootclasspath-locations:", module.PreoptBootClassPathDexLocations, ":").
Colin Cross43f08db2018-11-12 10:13:39 -0800316 Flag("${class_loader_context_arg}").
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000317 Flag("${stored_class_loader_context_arg}").
Ulya Trafimovich3391a1e2020-01-03 17:33:17 +0000318 FlagWithArg("--boot-image=", strings.Join(module.DexPreoptImageLocations, ":")).Implicits(module.DexPreoptImagesDeps[archIdx].Paths()).
Colin Cross43f08db2018-11-12 10:13:39 -0800319 FlagWithInput("--dex-file=", module.DexPath).
Nicolas Geoffray2464ef42019-03-05 14:07:07 +0000320 FlagWithArg("--dex-location=", dexLocationArg).
Colin Cross43f08db2018-11-12 10:13:39 -0800321 FlagWithOutput("--oat-file=", odexPath).ImplicitOutput(vdexPath).
322 // Pass an empty directory, dex2oat shouldn't be reading arbitrary files
323 FlagWithArg("--android-root=", global.EmptyDirectory).
Colin Cross74ba9622019-02-11 15:11:14 -0800324 FlagWithArg("--instruction-set=", arch.String()).
Colin Cross43f08db2018-11-12 10:13:39 -0800325 FlagWithArg("--instruction-set-variant=", global.CpuVariant[arch]).
326 FlagWithArg("--instruction-set-features=", global.InstructionSetFeatures[arch]).
327 Flag("--no-generate-debug-info").
328 Flag("--generate-build-id").
329 Flag("--abort-on-hard-verifier-error").
330 Flag("--force-determinism").
331 FlagWithArg("--no-inline-from=", "core-oj.jar")
332
333 var preoptFlags []string
334 if len(module.PreoptFlags) > 0 {
335 preoptFlags = module.PreoptFlags
336 } else if len(global.PreoptFlags) > 0 {
337 preoptFlags = global.PreoptFlags
338 }
339
340 if len(preoptFlags) > 0 {
341 cmd.Text(strings.Join(preoptFlags, " "))
342 }
343
344 if module.UncompressedDex {
345 cmd.FlagWithArg("--copy-dex-files=", "false")
346 }
347
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800348 if !android.PrefixInList(preoptFlags, "--compiler-filter=") {
Colin Cross43f08db2018-11-12 10:13:39 -0800349 var compilerFilter string
350 if contains(global.SystemServerJars, module.Name) {
351 // Jars of system server, use the product option if it is set, speed otherwise.
352 if global.SystemServerCompilerFilter != "" {
353 compilerFilter = global.SystemServerCompilerFilter
354 } else {
355 compilerFilter = "speed"
356 }
357 } else if contains(global.SpeedApps, module.Name) || contains(global.SystemServerApps, module.Name) {
358 // Apps loaded into system server, and apps the product default to being compiled with the
359 // 'speed' compiler filter.
360 compilerFilter = "speed"
Colin Cross69f59a32019-02-15 10:39:37 -0800361 } else if profile != nil {
Colin Cross43f08db2018-11-12 10:13:39 -0800362 // For non system server jars, use speed-profile when we have a profile.
363 compilerFilter = "speed-profile"
364 } else if global.DefaultCompilerFilter != "" {
365 compilerFilter = global.DefaultCompilerFilter
366 } else {
367 compilerFilter = "quicken"
368 }
369 cmd.FlagWithArg("--compiler-filter=", compilerFilter)
370 }
371
372 if generateDM {
373 cmd.FlagWithArg("--copy-dex-files=", "false")
Colin Cross69f59a32019-02-15 10:39:37 -0800374 dmPath := module.BuildPath.InSameDir(ctx, "generated.dm")
Colin Cross43f08db2018-11-12 10:13:39 -0800375 dmInstalledPath := pathtools.ReplaceExtension(module.DexLocation, "dm")
Colin Cross69f59a32019-02-15 10:39:37 -0800376 tmpPath := module.BuildPath.InSameDir(ctx, "primary.vdex")
Colin Cross43f08db2018-11-12 10:13:39 -0800377 rule.Command().Text("cp -f").Input(vdexPath).Output(tmpPath)
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000378 rule.Command().Tool(globalSoong.SoongZip).
Colin Cross43f08db2018-11-12 10:13:39 -0800379 FlagWithArg("-L", "9").
380 FlagWithOutput("-o", dmPath).
381 Flag("-j").
382 Input(tmpPath)
383 rule.Install(dmPath, dmInstalledPath)
384 }
385
386 // By default, emit debug info.
387 debugInfo := true
388 if global.NoDebugInfo {
389 // If the global setting suppresses mini-debug-info, disable it.
390 debugInfo = false
391 }
392
393 // PRODUCT_SYSTEM_SERVER_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO.
394 // PRODUCT_OTHER_JAVA_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO.
395 if contains(global.SystemServerJars, module.Name) {
396 if global.AlwaysSystemServerDebugInfo {
397 debugInfo = true
398 } else if global.NeverSystemServerDebugInfo {
399 debugInfo = false
400 }
401 } else {
402 if global.AlwaysOtherDebugInfo {
403 debugInfo = true
404 } else if global.NeverOtherDebugInfo {
405 debugInfo = false
406 }
407 }
408
409 // Never enable on eng.
410 if global.IsEng {
411 debugInfo = false
412 }
413
414 if debugInfo {
415 cmd.Flag("--generate-mini-debug-info")
416 } else {
417 cmd.Flag("--no-generate-mini-debug-info")
418 }
419
420 // Set the compiler reason to 'prebuilt' to identify the oat files produced
421 // during the build, as opposed to compiled on the device.
422 cmd.FlagWithArg("--compilation-reason=", "prebuilt")
423
424 if appImage {
Colin Cross69f59a32019-02-15 10:39:37 -0800425 appImagePath := odexPath.ReplaceExtension(ctx, "art")
Colin Cross43f08db2018-11-12 10:13:39 -0800426 appImageInstallPath := pathtools.ReplaceExtension(odexInstallPath, "art")
427 cmd.FlagWithOutput("--app-image-file=", appImagePath).
428 FlagWithArg("--image-format=", "lz4")
Mathieu Chartier3f7ddbb2019-04-29 09:33:50 -0700429 if !global.DontResolveStartupStrings {
430 cmd.FlagWithArg("--resolve-startup-const-strings=", "true")
431 }
Colin Cross43f08db2018-11-12 10:13:39 -0800432 rule.Install(appImagePath, appImageInstallPath)
433 }
434
Colin Cross69f59a32019-02-15 10:39:37 -0800435 if profile != nil {
436 cmd.FlagWithInput("--profile-file=", profile)
Colin Cross43f08db2018-11-12 10:13:39 -0800437 }
438
439 rule.Install(odexPath, odexInstallPath)
440 rule.Install(vdexPath, vdexInstallPath)
441}
442
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000443func shouldGenerateDM(module *ModuleConfig, global *GlobalConfig) bool {
Colin Cross43f08db2018-11-12 10:13:39 -0800444 // Generating DM files only makes sense for verify, avoid doing for non verify compiler filter APKs.
445 // No reason to use a dm file if the dex is already uncompressed.
446 return global.GenerateDMFiles && !module.UncompressedDex &&
447 contains(module.PreoptFlags, "--compiler-filter=verify")
448}
449
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000450func OdexOnSystemOtherByName(name string, dexLocation string, global *GlobalConfig) bool {
Colin Cross43f08db2018-11-12 10:13:39 -0800451 if !global.HasSystemOther {
452 return false
453 }
454
455 if global.SanitizeLite {
456 return false
457 }
458
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000459 if contains(global.SpeedApps, name) || contains(global.SystemServerApps, name) {
Colin Cross43f08db2018-11-12 10:13:39 -0800460 return false
461 }
462
463 for _, f := range global.PatternsOnSystemOther {
Anton Hanssonda4d9d92020-09-15 09:28:55 +0000464 if makefileMatch(filepath.Join(SystemPartition, f), dexLocation) {
Colin Cross43f08db2018-11-12 10:13:39 -0800465 return true
466 }
467 }
468
469 return false
470}
471
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000472func odexOnSystemOther(module *ModuleConfig, global *GlobalConfig) bool {
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000473 return OdexOnSystemOtherByName(module.Name, module.DexLocation, global)
474}
475
Colin Crossc7e40aa2019-02-08 21:37:00 -0800476// PathToLocation converts .../system/framework/arm64/boot.art to .../system/framework/boot.art
Colin Cross69f59a32019-02-15 10:39:37 -0800477func PathToLocation(path android.Path, arch android.ArchType) string {
478 pathArch := filepath.Base(filepath.Dir(path.String()))
Colin Cross74ba9622019-02-11 15:11:14 -0800479 if pathArch != arch.String() {
480 panic(fmt.Errorf("last directory in %q must be %q", path, arch.String()))
Colin Crossc7e40aa2019-02-08 21:37:00 -0800481 }
Colin Cross69f59a32019-02-15 10:39:37 -0800482 return filepath.Join(filepath.Dir(filepath.Dir(path.String())), filepath.Base(path.String()))
Colin Crossc7e40aa2019-02-08 21:37:00 -0800483}
484
Colin Cross43f08db2018-11-12 10:13:39 -0800485func makefileMatch(pattern, s string) bool {
486 percent := strings.IndexByte(pattern, '%')
487 switch percent {
488 case -1:
489 return pattern == s
490 case len(pattern) - 1:
491 return strings.HasPrefix(s, pattern[:len(pattern)-1])
492 default:
493 panic(fmt.Errorf("unsupported makefile pattern %q", pattern))
494 }
495}
496
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +0000497var nonUpdatableSystemServerJarsKey = android.NewOnceKey("nonUpdatableSystemServerJars")
498
499// TODO: eliminate the superficial global config parameter by moving global config definition
500// from java subpackage to dexpreopt.
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000501func NonUpdatableSystemServerJars(ctx android.PathContext, global *GlobalConfig) []string {
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +0000502 return ctx.Config().Once(nonUpdatableSystemServerJarsKey, func() interface{} {
Ulya Trafimovich249386a2020-07-01 14:31:13 +0100503 return android.RemoveListFromList(global.SystemServerJars, global.UpdatableSystemServerJars.CopyOfJars())
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +0000504 }).([]string)
505}
506
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000507// A predefined location for the system server dex jars. This is needed in order to generate
508// class loader context for dex2oat, as the path to the jar in the Soong module may be unknown
509// at that time (Soong processes the jars in dependency order, which may be different from the
510// the system server classpath order).
511func SystemServerDexJarHostPath(ctx android.PathContext, jar string) android.OutputPath {
Ulya Trafimovich6cf2c0c2020-04-24 12:15:20 +0100512 if DexpreoptRunningInSoong {
513 // Soong module, just use the default output directory $OUT/soong.
514 return android.PathForOutput(ctx, "system_server_dexjars", jar+".jar")
515 } else {
516 // Make module, default output directory is $OUT (passed via the "null config" created
517 // by dexpreopt_gen). Append Soong subdirectory to match Soong module paths.
518 return android.PathForOutput(ctx, "soong", "system_server_dexjars", jar+".jar")
519 }
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000520}
521
Ulya Trafimovichcd3203f2020-03-27 11:30:00 +0000522// Check the order of jars on the system server classpath and give a warning/error if a jar precedes
523// one of its dependencies. This is not an error, but a missed optimization, as dexpreopt won't
524// have the dependency jar in the class loader context, and it won't be able to resolve any
525// references to its classes and methods.
526func checkSystemServerOrder(ctx android.PathContext, jarIndex int) {
527 mctx, isModule := ctx.(android.ModuleContext)
528 if isModule {
529 config := GetGlobalConfig(ctx)
530 jars := NonUpdatableSystemServerJars(ctx, config)
531 mctx.WalkDeps(func(dep android.Module, parent android.Module) bool {
532 depIndex := android.IndexList(dep.Name(), jars)
533 if jarIndex < depIndex && !config.BrokenSuboptimalOrderOfSystemServerJars {
534 jar := jars[jarIndex]
535 dep := jars[depIndex]
536 mctx.ModuleErrorf("non-optimal order of jars on the system server classpath:"+
537 " '%s' precedes its dependency '%s', so dexpreopt is unable to resolve any"+
538 " references from '%s' to '%s'.\n", jar, dep, jar, dep)
539 }
540 return true
541 })
542 }
543}
544
Colin Cross43f08db2018-11-12 10:13:39 -0800545func contains(l []string, s string) bool {
546 for _, e := range l {
547 if e == s {
548 return true
549 }
550 }
551 return false
552}
553
Colin Cross454c0872019-02-15 23:03:34 -0800554var copyOf = android.CopyOf