blob: 3145315e3e2830875b9d3cd930a8bbdc93db6026 [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
Colin Cross43f08db2018-11-12 10:13:39 -0800113 // If OnlyPreoptBootImageAndSystemServer=true and module is not in boot class path skip
114 // Also preopt system server jars since selinux prevents system server from loading anything from
115 // /data. If we don't do this they will need to be extracted which is not favorable for RAM usage
116 // or performance. If PreoptExtractedApk is true, we ignore the only preopt boot image options.
Ulya Trafimovich249386a2020-07-01 14:31:13 +0100117 if global.OnlyPreoptBootImageAndSystemServer && !global.BootJars.ContainsJar(module.Name) &&
Jiakai Zhang519c5c82021-09-16 06:15:39 +0000118 !AllSystemServerJars(ctx, global).ContainsJar(module.Name) && !module.PreoptExtractedApk {
Colin Crosscbed6572019-01-08 17:38:37 -0800119 return true
Colin Cross43f08db2018-11-12 10:13:39 -0800120 }
121
Colin Crosscbed6572019-01-08 17:38:37 -0800122 return false
Colin Cross43f08db2018-11-12 10:13:39 -0800123}
124
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000125func profileCommand(ctx android.PathContext, globalSoong *GlobalSoongConfig, global *GlobalConfig,
126 module *ModuleConfig, rule *android.RuleBuilder) android.WritablePath {
Colin Cross69f59a32019-02-15 10:39:37 -0800127
128 profilePath := module.BuildPath.InSameDir(ctx, "profile.prof")
Colin Cross43f08db2018-11-12 10:13:39 -0800129 profileInstalledPath := module.DexLocation + ".prof"
130
131 if !module.ProfileIsTextListing {
Vladimir Marko982e3842021-04-29 09:05:18 +0100132 rule.Command().Text("rm -f").Output(profilePath)
133 rule.Command().Text("touch").Output(profilePath)
Colin Cross43f08db2018-11-12 10:13:39 -0800134 }
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.
Vladimir Marko230bd422021-04-23 15:18:33 +0100153 Flag("--output-profile-type=app").
Colin Cross43f08db2018-11-12 10:13:39 -0800154 FlagWithInput("--apk=", module.DexPath).
155 Flag("--dex-location="+module.DexLocation).
156 FlagWithOutput("--reference-profile-file=", profilePath)
157
158 if !module.ProfileIsTextListing {
159 cmd.Text(fmt.Sprintf(`|| echo "Profile out of date for %s"`, module.DexPath))
160 }
161 rule.Install(profilePath, profileInstalledPath)
162
163 return profilePath
164}
165
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000166func bootProfileCommand(ctx android.PathContext, globalSoong *GlobalSoongConfig, global *GlobalConfig,
167 module *ModuleConfig, rule *android.RuleBuilder) android.WritablePath {
Nicolas Geoffraye7102422019-07-24 13:19:29 +0100168
169 profilePath := module.BuildPath.InSameDir(ctx, "profile.bprof")
170 profileInstalledPath := module.DexLocation + ".bprof"
171
172 if !module.ProfileIsTextListing {
Vladimir Marko982e3842021-04-29 09:05:18 +0100173 rule.Command().Text("rm -f").Output(profilePath)
174 rule.Command().Text("touch").Output(profilePath)
Nicolas Geoffraye7102422019-07-24 13:19:29 +0100175 }
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.
Vladimir Marko230bd422021-04-23 15:18:33 +0100186 Flag("--output-profile-type=bprof").
Nicolas Geoffraye7102422019-07-24 13:19:29 +0100187 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
Jiakai Zhang519c5c82021-09-16 06:15:39 +0000199// Returns the dex location of a system server java library.
200func GetSystemServerDexLocation(global *GlobalConfig, lib string) string {
201 if apex := global.ApexSystemServerJars.ApexOfJar(lib); apex != "" {
202 return fmt.Sprintf("/apex/%s/javalib/%s.jar", apex, lib)
203 }
204 return fmt.Sprintf("/system/framework/%s.jar", lib)
205}
206
Jiakai Zhang0a0a2fb2021-09-30 09:38:19 +0000207// Returns the location to the odex file for the dex file at `path`.
208func ToOdexPath(path string, arch android.ArchType) string {
209 if strings.HasPrefix(path, "/apex/") {
210 return filepath.Join("/system/framework/oat", arch.String(),
211 strings.ReplaceAll(path[1:], "/", "@")+"@classes.odex")
212 }
213
214 return filepath.Join(filepath.Dir(path), "oat", arch.String(),
215 pathtools.ReplaceExtension(filepath.Base(path), "odex"))
216}
217
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000218func dexpreoptCommand(ctx android.PathContext, globalSoong *GlobalSoongConfig, global *GlobalConfig,
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000219 module *ModuleConfig, rule *android.RuleBuilder, archIdx int, profile android.WritablePath,
220 appImage bool, generateDM bool) {
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000221
222 arch := module.Archs[archIdx]
Colin Cross43f08db2018-11-12 10:13:39 -0800223
224 // HACK: make soname in Soong-generated .odex files match Make.
225 base := filepath.Base(module.DexLocation)
226 if filepath.Ext(base) == ".jar" {
227 base = "javalib.jar"
228 } else if filepath.Ext(base) == ".apk" {
229 base = "package.apk"
230 }
231
Colin Cross69f59a32019-02-15 10:39:37 -0800232 odexPath := module.BuildPath.InSameDir(ctx, "oat", arch.String(), pathtools.ReplaceExtension(base, "odex"))
Jiakai Zhang0a0a2fb2021-09-30 09:38:19 +0000233 odexInstallPath := ToOdexPath(module.DexLocation, arch)
Colin Cross43f08db2018-11-12 10:13:39 -0800234 if odexOnSystemOther(module, global) {
Anton Hansson43ab0bc2019-10-03 14:18:45 +0100235 odexInstallPath = filepath.Join(SystemOtherPartition, odexInstallPath)
Colin Cross43f08db2018-11-12 10:13:39 -0800236 }
237
Colin Cross69f59a32019-02-15 10:39:37 -0800238 vdexPath := odexPath.ReplaceExtension(ctx, "vdex")
Colin Cross43f08db2018-11-12 10:13:39 -0800239 vdexInstallPath := pathtools.ReplaceExtension(odexInstallPath, "vdex")
240
Colin Cross69f59a32019-02-15 10:39:37 -0800241 invocationPath := odexPath.ReplaceExtension(ctx, "invocation")
Alex Light5de41962018-12-18 15:16:26 -0800242
Jiakai Zhang519c5c82021-09-16 06:15:39 +0000243 systemServerJars := AllSystemServerJars(ctx, global)
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000244
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100245 rule.Command().FlagWithArg("mkdir -p ", filepath.Dir(odexPath.String()))
246 rule.Command().FlagWithOutput("rm -f ", odexPath)
Ulya Trafimovichc9af5382020-05-29 15:35:06 +0100247
Jiakai Zhang519c5c82021-09-16 06:15:39 +0000248 if jarIndex := systemServerJars.IndexOfJar(module.Name); jarIndex >= 0 {
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000249 // System server jars should be dexpreopted together: class loader context of each jar
250 // should include all preceding jars on the system server classpath.
251
252 var clcHost android.Paths
253 var clcTarget []string
Jiakai Zhang519c5c82021-09-16 06:15:39 +0000254 for i := 0; i < jarIndex; i++ {
255 lib := systemServerJars.Jar(i)
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000256 clcHost = append(clcHost, SystemServerDexJarHostPath(ctx, lib))
Jiakai Zhang519c5c82021-09-16 06:15:39 +0000257 clcTarget = append(clcTarget, GetSystemServerDexLocation(global, lib))
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000258 }
259
Ulya Trafimovich29e95d92021-09-21 12:59:39 +0100260 if DexpreoptRunningInSoong {
261 // Copy the system server jar to a predefined location where dex2oat will find it.
262 dexPathHost := SystemServerDexJarHostPath(ctx, module.Name)
263 rule.Command().Text("mkdir -p").Flag(filepath.Dir(dexPathHost.String()))
264 rule.Command().Text("cp -f").Input(module.DexPath).Output(dexPathHost)
265 } else {
266 // For Make modules the copy rule is generated in the makefiles, not in dexpreopt.sh.
267 // This is necessary to expose the rule to Ninja, otherwise it has rules that depend on
268 // the jar (namely, dexpreopt commands for all subsequent system server jars that have
269 // this one in their class loader context), but no rule that creates it (because Ninja
270 // cannot see the rule in the generated dexpreopt.sh script).
271 }
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100272
273 checkSystemServerOrder(ctx, jarIndex)
274
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100275 rule.Command().
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000276 Text("class_loader_context_arg=--class-loader-context=PCL[" + strings.Join(clcHost.Strings(), ":") + "]").
277 Implicits(clcHost).
278 Text("stored_class_loader_context_arg=--stored-class-loader-context=PCL[" + strings.Join(clcTarget, ":") + "]")
279
Ulya Trafimovichbd6b0762021-03-12 12:12:12 +0000280 } else {
281 // There are three categories of Java modules handled here:
282 //
283 // - Modules that have passed verify_uses_libraries check. They are AOT-compiled and
284 // expected to be loaded on device without CLC mismatch errors.
285 //
286 // - Modules that have failed the check in relaxed mode, so it didn't cause a build error.
287 // They are dexpreopted with "verify" filter and not AOT-compiled.
288 // TODO(b/132357300): ensure that CLC mismatch errors are ignored with "verify" filter.
289 //
290 // - Modules that didn't run the check. They are AOT-compiled, but it's unknown if they
291 // will have CLC mismatch errors on device (the check is disabled by default).
292 //
293 // TODO(b/132357300): enable the check by default and eliminate the last category, so that
294 // no time/space is wasted on AOT-compiling modules that will fail CLC check on device.
295
296 var manifestOrApk android.Path
Jeongik Cha33a3a812021-04-15 09:12:49 +0900297 if module.ManifestPath.Valid() {
Ulya Trafimovichbd6b0762021-03-12 12:12:12 +0000298 // Ok, there is an XML manifest.
Jeongik Cha33a3a812021-04-15 09:12:49 +0900299 manifestOrApk = module.ManifestPath.Path()
Ulya Trafimovichbd6b0762021-03-12 12:12:12 +0000300 } else if filepath.Ext(base) == ".apk" {
301 // Ok, there is is an APK with the manifest inside.
Ulya Trafimovich0aba2522021-03-03 16:38:37 +0000302 manifestOrApk = module.DexPath
Colin Cross38b96852019-05-22 10:21:09 -0700303 }
Ulya Trafimovichbd6b0762021-03-12 12:12:12 +0000304
305 // Generate command that saves target SDK version in a shell variable.
306 if manifestOrApk == nil {
307 // There is neither an XML manifest nor APK => nowhere to extract targetSdkVersion from.
308 // Set the latest ("any") version: then construct_context will not add any compatibility
309 // libraries (if this is incorrect, there will be a CLC mismatch and dexopt on device).
310 rule.Command().Textf(`target_sdk_version=%d`, AnySdkVersion)
311 } else {
312 rule.Command().Text(`target_sdk_version="$(`).
313 Tool(globalSoong.ManifestCheck).
314 Flag("--extract-target-sdk-version").
315 Input(manifestOrApk).
Ulya Trafimovichdd622952021-03-25 12:52:49 +0000316 FlagWithInput("--aapt ", globalSoong.Aapt).
Ulya Trafimovichbd6b0762021-03-12 12:12:12 +0000317 Text(`)"`)
318 }
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100319
Ulya Trafimovich5f364b62020-06-30 12:39:01 +0100320 // Generate command that saves host and target class loader context in shell variables.
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000321 clc, paths := ComputeClassLoaderContext(module.ClassLoaderContexts)
Ulya Trafimovich8c35fcf2021-02-17 16:23:28 +0000322 rule.Command().
Ulya Trafimovichbd6b0762021-03-12 12:12:12 +0000323 Text(`eval "$(`).Tool(globalSoong.ConstructContext).
Ulya Trafimovich8130c482020-10-07 15:17:13 +0100324 Text(` --target-sdk-version ${target_sdk_version}`).
Ulya Trafimovich8c35fcf2021-02-17 16:23:28 +0000325 Text(clc).Implicits(paths).
Ulya Trafimovichbd6b0762021-03-12 12:12:12 +0000326 Text(`)"`)
Colin Cross43f08db2018-11-12 10:13:39 -0800327 }
328
Nicolas Geoffray2464ef42019-03-05 14:07:07 +0000329 // Devices that do not have a product partition use a symlink from /product to /system/product.
330 // Because on-device dexopt will see dex locations starting with /product, we change the paths
331 // to mimic this behavior.
332 dexLocationArg := module.DexLocation
333 if strings.HasPrefix(dexLocationArg, "/system/product/") {
334 dexLocationArg = strings.TrimPrefix(dexLocationArg, "/system")
335 }
336
Colin Cross43f08db2018-11-12 10:13:39 -0800337 cmd := rule.Command().
338 Text(`ANDROID_LOG_TAGS="*:e"`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000339 Tool(globalSoong.Dex2oat).
Colin Cross43f08db2018-11-12 10:13:39 -0800340 Flag("--avoid-storing-invocation").
Alex Light5de41962018-12-18 15:16:26 -0800341 FlagWithOutput("--write-invocation-to=", invocationPath).ImplicitOutput(invocationPath).
Colin Cross43f08db2018-11-12 10:13:39 -0800342 Flag("--runtime-arg").FlagWithArg("-Xms", global.Dex2oatXms).
343 Flag("--runtime-arg").FlagWithArg("-Xmx", global.Dex2oatXmx).
Colin Cross800fe132019-02-11 14:21:24 -0800344 Flag("--runtime-arg").FlagWithInputList("-Xbootclasspath:", module.PreoptBootClassPathDexFiles, ":").
345 Flag("--runtime-arg").FlagWithList("-Xbootclasspath-locations:", module.PreoptBootClassPathDexLocations, ":").
Colin Cross43f08db2018-11-12 10:13:39 -0800346 Flag("${class_loader_context_arg}").
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000347 Flag("${stored_class_loader_context_arg}").
Jeongik Chaa5969092021-05-07 18:53:21 +0900348 FlagWithArg("--boot-image=", strings.Join(module.DexPreoptImageLocationsOnHost, ":")).Implicits(module.DexPreoptImagesDeps[archIdx].Paths()).
Colin Cross43f08db2018-11-12 10:13:39 -0800349 FlagWithInput("--dex-file=", module.DexPath).
Nicolas Geoffray2464ef42019-03-05 14:07:07 +0000350 FlagWithArg("--dex-location=", dexLocationArg).
Colin Cross43f08db2018-11-12 10:13:39 -0800351 FlagWithOutput("--oat-file=", odexPath).ImplicitOutput(vdexPath).
352 // Pass an empty directory, dex2oat shouldn't be reading arbitrary files
353 FlagWithArg("--android-root=", global.EmptyDirectory).
Colin Cross74ba9622019-02-11 15:11:14 -0800354 FlagWithArg("--instruction-set=", arch.String()).
Colin Cross43f08db2018-11-12 10:13:39 -0800355 FlagWithArg("--instruction-set-variant=", global.CpuVariant[arch]).
356 FlagWithArg("--instruction-set-features=", global.InstructionSetFeatures[arch]).
357 Flag("--no-generate-debug-info").
358 Flag("--generate-build-id").
359 Flag("--abort-on-hard-verifier-error").
360 Flag("--force-determinism").
361 FlagWithArg("--no-inline-from=", "core-oj.jar")
362
363 var preoptFlags []string
364 if len(module.PreoptFlags) > 0 {
365 preoptFlags = module.PreoptFlags
366 } else if len(global.PreoptFlags) > 0 {
367 preoptFlags = global.PreoptFlags
368 }
369
370 if len(preoptFlags) > 0 {
371 cmd.Text(strings.Join(preoptFlags, " "))
372 }
373
374 if module.UncompressedDex {
375 cmd.FlagWithArg("--copy-dex-files=", "false")
376 }
377
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800378 if !android.PrefixInList(preoptFlags, "--compiler-filter=") {
Colin Cross43f08db2018-11-12 10:13:39 -0800379 var compilerFilter string
Jiakai Zhang519c5c82021-09-16 06:15:39 +0000380 if systemServerJars.ContainsJar(module.Name) {
Colin Cross43f08db2018-11-12 10:13:39 -0800381 // Jars of system server, use the product option if it is set, speed otherwise.
382 if global.SystemServerCompilerFilter != "" {
383 compilerFilter = global.SystemServerCompilerFilter
384 } else {
385 compilerFilter = "speed"
386 }
387 } else if contains(global.SpeedApps, module.Name) || contains(global.SystemServerApps, module.Name) {
388 // Apps loaded into system server, and apps the product default to being compiled with the
389 // 'speed' compiler filter.
390 compilerFilter = "speed"
Colin Cross69f59a32019-02-15 10:39:37 -0800391 } else if profile != nil {
Colin Cross43f08db2018-11-12 10:13:39 -0800392 // For non system server jars, use speed-profile when we have a profile.
393 compilerFilter = "speed-profile"
394 } else if global.DefaultCompilerFilter != "" {
395 compilerFilter = global.DefaultCompilerFilter
396 } else {
397 compilerFilter = "quicken"
398 }
Ulya Trafimovich8c35fcf2021-02-17 16:23:28 +0000399 if module.EnforceUsesLibraries {
400 // If the verify_uses_libraries check failed (in this case status file contains a
Ulya Trafimovich4a13acb2021-03-02 12:25:02 +0000401 // non-empty error message), then use "verify" compiler filter to avoid compiling any
Ulya Trafimovich8c35fcf2021-02-17 16:23:28 +0000402 // code (it would be rejected on device because of a class loader context mismatch).
403 cmd.Text("--compiler-filter=$(if test -s ").
404 Input(module.EnforceUsesLibrariesStatusFile).
Ulya Trafimovich4a13acb2021-03-02 12:25:02 +0000405 Text(" ; then echo verify ; else echo " + compilerFilter + " ; fi)")
Ulya Trafimovich8c35fcf2021-02-17 16:23:28 +0000406 } else {
407 cmd.FlagWithArg("--compiler-filter=", compilerFilter)
408 }
Colin Cross43f08db2018-11-12 10:13:39 -0800409 }
410
411 if generateDM {
412 cmd.FlagWithArg("--copy-dex-files=", "false")
Colin Cross69f59a32019-02-15 10:39:37 -0800413 dmPath := module.BuildPath.InSameDir(ctx, "generated.dm")
Colin Cross43f08db2018-11-12 10:13:39 -0800414 dmInstalledPath := pathtools.ReplaceExtension(module.DexLocation, "dm")
Colin Cross69f59a32019-02-15 10:39:37 -0800415 tmpPath := module.BuildPath.InSameDir(ctx, "primary.vdex")
Colin Cross43f08db2018-11-12 10:13:39 -0800416 rule.Command().Text("cp -f").Input(vdexPath).Output(tmpPath)
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000417 rule.Command().Tool(globalSoong.SoongZip).
Colin Cross43f08db2018-11-12 10:13:39 -0800418 FlagWithArg("-L", "9").
419 FlagWithOutput("-o", dmPath).
420 Flag("-j").
421 Input(tmpPath)
422 rule.Install(dmPath, dmInstalledPath)
423 }
424
425 // By default, emit debug info.
426 debugInfo := true
427 if global.NoDebugInfo {
428 // If the global setting suppresses mini-debug-info, disable it.
429 debugInfo = false
430 }
431
432 // PRODUCT_SYSTEM_SERVER_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO.
433 // PRODUCT_OTHER_JAVA_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO.
Jiakai Zhang519c5c82021-09-16 06:15:39 +0000434 if systemServerJars.ContainsJar(module.Name) {
Colin Cross43f08db2018-11-12 10:13:39 -0800435 if global.AlwaysSystemServerDebugInfo {
436 debugInfo = true
437 } else if global.NeverSystemServerDebugInfo {
438 debugInfo = false
439 }
440 } else {
441 if global.AlwaysOtherDebugInfo {
442 debugInfo = true
443 } else if global.NeverOtherDebugInfo {
444 debugInfo = false
445 }
446 }
447
Colin Cross43f08db2018-11-12 10:13:39 -0800448 if debugInfo {
449 cmd.Flag("--generate-mini-debug-info")
450 } else {
451 cmd.Flag("--no-generate-mini-debug-info")
452 }
453
454 // Set the compiler reason to 'prebuilt' to identify the oat files produced
455 // during the build, as opposed to compiled on the device.
456 cmd.FlagWithArg("--compilation-reason=", "prebuilt")
457
458 if appImage {
Colin Cross69f59a32019-02-15 10:39:37 -0800459 appImagePath := odexPath.ReplaceExtension(ctx, "art")
Colin Cross43f08db2018-11-12 10:13:39 -0800460 appImageInstallPath := pathtools.ReplaceExtension(odexInstallPath, "art")
461 cmd.FlagWithOutput("--app-image-file=", appImagePath).
462 FlagWithArg("--image-format=", "lz4")
Mathieu Chartier3f7ddbb2019-04-29 09:33:50 -0700463 if !global.DontResolveStartupStrings {
464 cmd.FlagWithArg("--resolve-startup-const-strings=", "true")
465 }
Colin Cross43f08db2018-11-12 10:13:39 -0800466 rule.Install(appImagePath, appImageInstallPath)
467 }
468
Colin Cross69f59a32019-02-15 10:39:37 -0800469 if profile != nil {
470 cmd.FlagWithInput("--profile-file=", profile)
Colin Cross43f08db2018-11-12 10:13:39 -0800471 }
472
473 rule.Install(odexPath, odexInstallPath)
474 rule.Install(vdexPath, vdexInstallPath)
475}
476
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000477func shouldGenerateDM(module *ModuleConfig, global *GlobalConfig) bool {
Colin Cross43f08db2018-11-12 10:13:39 -0800478 // Generating DM files only makes sense for verify, avoid doing for non verify compiler filter APKs.
479 // No reason to use a dm file if the dex is already uncompressed.
480 return global.GenerateDMFiles && !module.UncompressedDex &&
481 contains(module.PreoptFlags, "--compiler-filter=verify")
482}
483
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000484func OdexOnSystemOtherByName(name string, dexLocation string, global *GlobalConfig) bool {
Colin Cross43f08db2018-11-12 10:13:39 -0800485 if !global.HasSystemOther {
486 return false
487 }
488
489 if global.SanitizeLite {
490 return false
491 }
492
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000493 if contains(global.SpeedApps, name) || contains(global.SystemServerApps, name) {
Colin Cross43f08db2018-11-12 10:13:39 -0800494 return false
495 }
496
497 for _, f := range global.PatternsOnSystemOther {
Anton Hanssonda4d9d92020-09-15 09:28:55 +0000498 if makefileMatch(filepath.Join(SystemPartition, f), dexLocation) {
Colin Cross43f08db2018-11-12 10:13:39 -0800499 return true
500 }
501 }
502
503 return false
504}
505
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000506func odexOnSystemOther(module *ModuleConfig, global *GlobalConfig) bool {
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000507 return OdexOnSystemOtherByName(module.Name, module.DexLocation, global)
508}
509
Colin Crossc7e40aa2019-02-08 21:37:00 -0800510// PathToLocation converts .../system/framework/arm64/boot.art to .../system/framework/boot.art
Colin Cross69f59a32019-02-15 10:39:37 -0800511func PathToLocation(path android.Path, arch android.ArchType) string {
Jeongik Cha4dda75e2021-04-27 23:56:44 +0900512 return PathStringToLocation(path.String(), arch)
513}
514
515// PathStringToLocation converts .../system/framework/arm64/boot.art to .../system/framework/boot.art
516func PathStringToLocation(path string, arch android.ArchType) string {
517 pathArch := filepath.Base(filepath.Dir(path))
Colin Cross74ba9622019-02-11 15:11:14 -0800518 if pathArch != arch.String() {
519 panic(fmt.Errorf("last directory in %q must be %q", path, arch.String()))
Colin Crossc7e40aa2019-02-08 21:37:00 -0800520 }
Jeongik Cha4dda75e2021-04-27 23:56:44 +0900521 return filepath.Join(filepath.Dir(filepath.Dir(path)), filepath.Base(path))
Colin Crossc7e40aa2019-02-08 21:37:00 -0800522}
523
Colin Cross43f08db2018-11-12 10:13:39 -0800524func makefileMatch(pattern, s string) bool {
525 percent := strings.IndexByte(pattern, '%')
526 switch percent {
527 case -1:
528 return pattern == s
529 case len(pattern) - 1:
530 return strings.HasPrefix(s, pattern[:len(pattern)-1])
531 default:
532 panic(fmt.Errorf("unsupported makefile pattern %q", pattern))
533 }
534}
535
Jiakai Zhang519c5c82021-09-16 06:15:39 +0000536var allSystemServerJarsKey = android.NewOnceKey("allSystemServerJars")
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +0000537
538// TODO: eliminate the superficial global config parameter by moving global config definition
539// from java subpackage to dexpreopt.
Jiakai Zhang519c5c82021-09-16 06:15:39 +0000540func AllSystemServerJars(ctx android.PathContext, global *GlobalConfig) *android.ConfiguredJarList {
541 return ctx.Config().Once(allSystemServerJarsKey, func() interface{} {
542 allSystemServerJars := global.SystemServerJars.AppendList(global.ApexSystemServerJars)
543 return &allSystemServerJars
544 }).(*android.ConfiguredJarList)
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +0000545}
546
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000547// A predefined location for the system server dex jars. This is needed in order to generate
548// class loader context for dex2oat, as the path to the jar in the Soong module may be unknown
549// at that time (Soong processes the jars in dependency order, which may be different from the
550// the system server classpath order).
551func SystemServerDexJarHostPath(ctx android.PathContext, jar string) android.OutputPath {
Ulya Trafimovich6cf2c0c2020-04-24 12:15:20 +0100552 if DexpreoptRunningInSoong {
553 // Soong module, just use the default output directory $OUT/soong.
554 return android.PathForOutput(ctx, "system_server_dexjars", jar+".jar")
555 } else {
556 // Make module, default output directory is $OUT (passed via the "null config" created
557 // by dexpreopt_gen). Append Soong subdirectory to match Soong module paths.
558 return android.PathForOutput(ctx, "soong", "system_server_dexjars", jar+".jar")
559 }
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000560}
561
Ulya Trafimovichcd3203f2020-03-27 11:30:00 +0000562// Check the order of jars on the system server classpath and give a warning/error if a jar precedes
563// one of its dependencies. This is not an error, but a missed optimization, as dexpreopt won't
564// have the dependency jar in the class loader context, and it won't be able to resolve any
565// references to its classes and methods.
566func checkSystemServerOrder(ctx android.PathContext, jarIndex int) {
567 mctx, isModule := ctx.(android.ModuleContext)
568 if isModule {
569 config := GetGlobalConfig(ctx)
Jiakai Zhang519c5c82021-09-16 06:15:39 +0000570 jars := AllSystemServerJars(ctx, config)
Ulya Trafimovichcd3203f2020-03-27 11:30:00 +0000571 mctx.WalkDeps(func(dep android.Module, parent android.Module) bool {
Jiakai Zhang519c5c82021-09-16 06:15:39 +0000572 depIndex := jars.IndexOfJar(dep.Name())
Ulya Trafimovichcd3203f2020-03-27 11:30:00 +0000573 if jarIndex < depIndex && !config.BrokenSuboptimalOrderOfSystemServerJars {
Jiakai Zhang519c5c82021-09-16 06:15:39 +0000574 jar := jars.Jar(jarIndex)
575 dep := jars.Jar(depIndex)
Ulya Trafimovichcd3203f2020-03-27 11:30:00 +0000576 mctx.ModuleErrorf("non-optimal order of jars on the system server classpath:"+
577 " '%s' precedes its dependency '%s', so dexpreopt is unable to resolve any"+
578 " references from '%s' to '%s'.\n", jar, dep, jar, dep)
579 }
580 return true
581 })
582 }
583}
584
Ulya Trafimovich8c35fcf2021-02-17 16:23:28 +0000585// Returns path to a file containing the reult of verify_uses_libraries check (empty if the check
586// has succeeded, or an error message if it failed).
587func UsesLibrariesStatusFile(ctx android.ModuleContext) android.WritablePath {
588 return android.PathForModuleOut(ctx, "enforce_uses_libraries.status")
589}
590
Colin Cross43f08db2018-11-12 10:13:39 -0800591func contains(l []string, s string) bool {
592 for _, e := range l {
593 if e == s {
594 return true
595 }
596 }
597 return false
598}
599
Colin Cross454c0872019-02-15 23:03:34 -0800600var copyOf = android.CopyOf