blob: a590c72a518f9dd7bb8becc8738e59c75dc104df [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 {
Jiakai Zhang3317ce72023-02-08 01:19:19 +0800104 if ctx.Config().UnbundledBuild() {
105 return true
106 }
107
Colin Crosscbed6572019-01-08 17:38:37 -0800108 if contains(global.DisablePreoptModules, module.Name) {
109 return true
Colin Cross43f08db2018-11-12 10:13:39 -0800110 }
111
Ulya Trafimovichfc24ad32020-08-19 16:32:54 +0100112 // Don't preopt individual boot jars, they will be preopted together.
113 if global.BootJars.ContainsJar(module.Name) {
114 return true
115 }
116
Colin Cross43f08db2018-11-12 10:13:39 -0800117 // If OnlyPreoptBootImageAndSystemServer=true and module is not in boot class path skip
118 // Also preopt system server jars since selinux prevents system server from loading anything from
119 // /data. If we don't do this they will need to be extracted which is not favorable for RAM usage
120 // or performance. If PreoptExtractedApk is true, we ignore the only preopt boot image options.
Ulya Trafimovich249386a2020-07-01 14:31:13 +0100121 if global.OnlyPreoptBootImageAndSystemServer && !global.BootJars.ContainsJar(module.Name) &&
Jiakai Zhang389a6472021-12-14 18:54:06 +0000122 !global.AllSystemServerJars(ctx).ContainsJar(module.Name) && !module.PreoptExtractedApk {
Colin Crosscbed6572019-01-08 17:38:37 -0800123 return true
Colin Cross43f08db2018-11-12 10:13:39 -0800124 }
125
Colin Crosscbed6572019-01-08 17:38:37 -0800126 return false
Colin Cross43f08db2018-11-12 10:13:39 -0800127}
128
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000129func profileCommand(ctx android.PathContext, globalSoong *GlobalSoongConfig, global *GlobalConfig,
130 module *ModuleConfig, rule *android.RuleBuilder) android.WritablePath {
Colin Cross69f59a32019-02-15 10:39:37 -0800131
132 profilePath := module.BuildPath.InSameDir(ctx, "profile.prof")
Colin Cross43f08db2018-11-12 10:13:39 -0800133 profileInstalledPath := module.DexLocation + ".prof"
134
135 if !module.ProfileIsTextListing {
Vladimir Marko982e3842021-04-29 09:05:18 +0100136 rule.Command().Text("rm -f").Output(profilePath)
137 rule.Command().Text("touch").Output(profilePath)
Colin Cross43f08db2018-11-12 10:13:39 -0800138 }
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.
Vladimir Marko230bd422021-04-23 15:18:33 +0100157 Flag("--output-profile-type=app").
Colin Cross43f08db2018-11-12 10:13:39 -0800158 FlagWithInput("--apk=", module.DexPath).
159 Flag("--dex-location="+module.DexLocation).
160 FlagWithOutput("--reference-profile-file=", profilePath)
161
162 if !module.ProfileIsTextListing {
163 cmd.Text(fmt.Sprintf(`|| echo "Profile out of date for %s"`, module.DexPath))
164 }
165 rule.Install(profilePath, profileInstalledPath)
166
167 return profilePath
168}
169
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000170func bootProfileCommand(ctx android.PathContext, globalSoong *GlobalSoongConfig, global *GlobalConfig,
171 module *ModuleConfig, rule *android.RuleBuilder) android.WritablePath {
Nicolas Geoffraye7102422019-07-24 13:19:29 +0100172
173 profilePath := module.BuildPath.InSameDir(ctx, "profile.bprof")
174 profileInstalledPath := module.DexLocation + ".bprof"
175
176 if !module.ProfileIsTextListing {
Vladimir Marko982e3842021-04-29 09:05:18 +0100177 rule.Command().Text("rm -f").Output(profilePath)
178 rule.Command().Text("touch").Output(profilePath)
Nicolas Geoffraye7102422019-07-24 13:19:29 +0100179 }
180
181 cmd := rule.Command().
182 Text(`ANDROID_LOG_TAGS="*:e"`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000183 Tool(globalSoong.Profman)
Nicolas Geoffraye7102422019-07-24 13:19:29 +0100184
185 // The profile is a test listing of methods.
186 // We need to generate the actual binary profile.
187 cmd.FlagWithInput("--create-profile-from=", module.ProfileBootListing.Path())
188
189 cmd.
Vladimir Marko230bd422021-04-23 15:18:33 +0100190 Flag("--output-profile-type=bprof").
Nicolas Geoffraye7102422019-07-24 13:19:29 +0100191 FlagWithInput("--apk=", module.DexPath).
192 Flag("--dex-location="+module.DexLocation).
193 FlagWithOutput("--reference-profile-file=", profilePath)
194
195 if !module.ProfileIsTextListing {
196 cmd.Text(fmt.Sprintf(`|| echo "Profile out of date for %s"`, module.DexPath))
197 }
198 rule.Install(profilePath, profileInstalledPath)
199
200 return profilePath
201}
202
Jiakai Zhang519c5c82021-09-16 06:15:39 +0000203// Returns the dex location of a system server java library.
Jiakai Zhang389a6472021-12-14 18:54:06 +0000204func GetSystemServerDexLocation(ctx android.PathContext, global *GlobalConfig, lib string) string {
205 if apex := global.AllApexSystemServerJars(ctx).ApexOfJar(lib); apex != "" {
Jiakai Zhang519c5c82021-09-16 06:15:39 +0000206 return fmt.Sprintf("/apex/%s/javalib/%s.jar", apex, lib)
207 }
liulvping76d56ee2022-05-07 14:40:13 +0800208
209 if apex := global.AllPlatformSystemServerJars(ctx).ApexOfJar(lib); apex == "system_ext" {
210 return fmt.Sprintf("/system_ext/framework/%s.jar", lib)
211 }
212
Jiakai Zhang519c5c82021-09-16 06:15:39 +0000213 return fmt.Sprintf("/system/framework/%s.jar", lib)
214}
215
Jiakai Zhang0a0a2fb2021-09-30 09:38:19 +0000216// Returns the location to the odex file for the dex file at `path`.
217func ToOdexPath(path string, arch android.ArchType) string {
218 if strings.HasPrefix(path, "/apex/") {
219 return filepath.Join("/system/framework/oat", arch.String(),
220 strings.ReplaceAll(path[1:], "/", "@")+"@classes.odex")
221 }
222
223 return filepath.Join(filepath.Dir(path), "oat", arch.String(),
224 pathtools.ReplaceExtension(filepath.Base(path), "odex"))
225}
226
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000227func dexpreoptCommand(ctx android.PathContext, globalSoong *GlobalSoongConfig, global *GlobalConfig,
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000228 module *ModuleConfig, rule *android.RuleBuilder, archIdx int, profile android.WritablePath,
229 appImage bool, generateDM bool) {
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000230
231 arch := module.Archs[archIdx]
Colin Cross43f08db2018-11-12 10:13:39 -0800232
233 // HACK: make soname in Soong-generated .odex files match Make.
234 base := filepath.Base(module.DexLocation)
235 if filepath.Ext(base) == ".jar" {
236 base = "javalib.jar"
237 } else if filepath.Ext(base) == ".apk" {
238 base = "package.apk"
239 }
240
Colin Cross69f59a32019-02-15 10:39:37 -0800241 odexPath := module.BuildPath.InSameDir(ctx, "oat", arch.String(), pathtools.ReplaceExtension(base, "odex"))
Jiakai Zhang0a0a2fb2021-09-30 09:38:19 +0000242 odexInstallPath := ToOdexPath(module.DexLocation, arch)
Colin Cross43f08db2018-11-12 10:13:39 -0800243 if odexOnSystemOther(module, global) {
Anton Hansson43ab0bc2019-10-03 14:18:45 +0100244 odexInstallPath = filepath.Join(SystemOtherPartition, odexInstallPath)
Colin Cross43f08db2018-11-12 10:13:39 -0800245 }
246
Colin Cross69f59a32019-02-15 10:39:37 -0800247 vdexPath := odexPath.ReplaceExtension(ctx, "vdex")
Colin Cross43f08db2018-11-12 10:13:39 -0800248 vdexInstallPath := pathtools.ReplaceExtension(odexInstallPath, "vdex")
249
Colin Cross69f59a32019-02-15 10:39:37 -0800250 invocationPath := odexPath.ReplaceExtension(ctx, "invocation")
Alex Light5de41962018-12-18 15:16:26 -0800251
Jiakai Zhang389a6472021-12-14 18:54:06 +0000252 systemServerJars := global.AllSystemServerJars(ctx)
253 systemServerClasspathJars := global.AllSystemServerClasspathJars(ctx)
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000254
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100255 rule.Command().FlagWithArg("mkdir -p ", filepath.Dir(odexPath.String()))
256 rule.Command().FlagWithOutput("rm -f ", odexPath)
Ulya Trafimovichc9af5382020-05-29 15:35:06 +0100257
Jiakai Zhang519c5c82021-09-16 06:15:39 +0000258 if jarIndex := systemServerJars.IndexOfJar(module.Name); jarIndex >= 0 {
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000259 // System server jars should be dexpreopted together: class loader context of each jar
260 // should include all preceding jars on the system server classpath.
261
262 var clcHost android.Paths
263 var clcTarget []string
Jiakai Zhang389a6472021-12-14 18:54:06 +0000264 endIndex := systemServerClasspathJars.IndexOfJar(module.Name)
265 if endIndex < 0 {
266 // The jar is a standalone one. Use the full classpath as the class loader context.
267 endIndex = systemServerClasspathJars.Len()
268 }
269 for i := 0; i < endIndex; i++ {
270 lib := systemServerClasspathJars.Jar(i)
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000271 clcHost = append(clcHost, SystemServerDexJarHostPath(ctx, lib))
Jiakai Zhang389a6472021-12-14 18:54:06 +0000272 clcTarget = append(clcTarget, GetSystemServerDexLocation(ctx, global, lib))
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000273 }
274
Ulya Trafimovich29e95d92021-09-21 12:59:39 +0100275 if DexpreoptRunningInSoong {
276 // Copy the system server jar to a predefined location where dex2oat will find it.
277 dexPathHost := SystemServerDexJarHostPath(ctx, module.Name)
278 rule.Command().Text("mkdir -p").Flag(filepath.Dir(dexPathHost.String()))
279 rule.Command().Text("cp -f").Input(module.DexPath).Output(dexPathHost)
280 } else {
281 // For Make modules the copy rule is generated in the makefiles, not in dexpreopt.sh.
282 // This is necessary to expose the rule to Ninja, otherwise it has rules that depend on
283 // the jar (namely, dexpreopt commands for all subsequent system server jars that have
284 // this one in their class loader context), but no rule that creates it (because Ninja
285 // cannot see the rule in the generated dexpreopt.sh script).
286 }
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100287
Jiakai Zhang389a6472021-12-14 18:54:06 +0000288 clcHostString := "PCL[" + strings.Join(clcHost.Strings(), ":") + "]"
289 clcTargetString := "PCL[" + strings.Join(clcTarget, ":") + "]"
290
291 if systemServerClasspathJars.ContainsJar(module.Name) {
292 checkSystemServerOrder(ctx, jarIndex)
293 } else {
294 // Standalone jars are loaded by separate class loaders with SYSTEMSERVERCLASSPATH as the
295 // parent.
296 clcHostString = "PCL[];" + clcHostString
297 clcTargetString = "PCL[];" + clcTargetString
298 }
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100299
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100300 rule.Command().
Jiakai Zhang389a6472021-12-14 18:54:06 +0000301 Text(`class_loader_context_arg=--class-loader-context="` + clcHostString + `"`).
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000302 Implicits(clcHost).
Jiakai Zhang389a6472021-12-14 18:54:06 +0000303 Text(`stored_class_loader_context_arg=--stored-class-loader-context="` + clcTargetString + `"`)
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000304
Ulya Trafimovichbd6b0762021-03-12 12:12:12 +0000305 } else {
306 // There are three categories of Java modules handled here:
307 //
308 // - Modules that have passed verify_uses_libraries check. They are AOT-compiled and
309 // expected to be loaded on device without CLC mismatch errors.
310 //
311 // - Modules that have failed the check in relaxed mode, so it didn't cause a build error.
312 // They are dexpreopted with "verify" filter and not AOT-compiled.
313 // TODO(b/132357300): ensure that CLC mismatch errors are ignored with "verify" filter.
314 //
315 // - Modules that didn't run the check. They are AOT-compiled, but it's unknown if they
316 // will have CLC mismatch errors on device (the check is disabled by default).
317 //
318 // TODO(b/132357300): enable the check by default and eliminate the last category, so that
319 // no time/space is wasted on AOT-compiling modules that will fail CLC check on device.
320
321 var manifestOrApk android.Path
Jeongik Cha33a3a812021-04-15 09:12:49 +0900322 if module.ManifestPath.Valid() {
Ulya Trafimovichbd6b0762021-03-12 12:12:12 +0000323 // Ok, there is an XML manifest.
Jeongik Cha33a3a812021-04-15 09:12:49 +0900324 manifestOrApk = module.ManifestPath.Path()
Ulya Trafimovichbd6b0762021-03-12 12:12:12 +0000325 } else if filepath.Ext(base) == ".apk" {
326 // Ok, there is is an APK with the manifest inside.
Ulya Trafimovich0aba2522021-03-03 16:38:37 +0000327 manifestOrApk = module.DexPath
Colin Cross38b96852019-05-22 10:21:09 -0700328 }
Ulya Trafimovichbd6b0762021-03-12 12:12:12 +0000329
330 // Generate command that saves target SDK version in a shell variable.
331 if manifestOrApk == nil {
332 // There is neither an XML manifest nor APK => nowhere to extract targetSdkVersion from.
333 // Set the latest ("any") version: then construct_context will not add any compatibility
334 // libraries (if this is incorrect, there will be a CLC mismatch and dexopt on device).
335 rule.Command().Textf(`target_sdk_version=%d`, AnySdkVersion)
336 } else {
337 rule.Command().Text(`target_sdk_version="$(`).
338 Tool(globalSoong.ManifestCheck).
339 Flag("--extract-target-sdk-version").
340 Input(manifestOrApk).
Ulya Trafimovichdd622952021-03-25 12:52:49 +0000341 FlagWithInput("--aapt ", globalSoong.Aapt).
Ulya Trafimovichbd6b0762021-03-12 12:12:12 +0000342 Text(`)"`)
343 }
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100344
Ulya Trafimovich5f364b62020-06-30 12:39:01 +0100345 // Generate command that saves host and target class loader context in shell variables.
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000346 clc, paths := ComputeClassLoaderContext(module.ClassLoaderContexts)
Ulya Trafimovich8c35fcf2021-02-17 16:23:28 +0000347 rule.Command().
Ulya Trafimovichbd6b0762021-03-12 12:12:12 +0000348 Text(`eval "$(`).Tool(globalSoong.ConstructContext).
Ulya Trafimovich8130c482020-10-07 15:17:13 +0100349 Text(` --target-sdk-version ${target_sdk_version}`).
Ulya Trafimovich8c35fcf2021-02-17 16:23:28 +0000350 Text(clc).Implicits(paths).
Ulya Trafimovichbd6b0762021-03-12 12:12:12 +0000351 Text(`)"`)
Colin Cross43f08db2018-11-12 10:13:39 -0800352 }
353
Nicolas Geoffray2464ef42019-03-05 14:07:07 +0000354 // Devices that do not have a product partition use a symlink from /product to /system/product.
355 // Because on-device dexopt will see dex locations starting with /product, we change the paths
356 // to mimic this behavior.
357 dexLocationArg := module.DexLocation
358 if strings.HasPrefix(dexLocationArg, "/system/product/") {
359 dexLocationArg = strings.TrimPrefix(dexLocationArg, "/system")
360 }
361
Colin Cross43f08db2018-11-12 10:13:39 -0800362 cmd := rule.Command().
363 Text(`ANDROID_LOG_TAGS="*:e"`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000364 Tool(globalSoong.Dex2oat).
Colin Cross43f08db2018-11-12 10:13:39 -0800365 Flag("--avoid-storing-invocation").
Alex Light5de41962018-12-18 15:16:26 -0800366 FlagWithOutput("--write-invocation-to=", invocationPath).ImplicitOutput(invocationPath).
Colin Cross43f08db2018-11-12 10:13:39 -0800367 Flag("--runtime-arg").FlagWithArg("-Xms", global.Dex2oatXms).
368 Flag("--runtime-arg").FlagWithArg("-Xmx", global.Dex2oatXmx).
Colin Cross800fe132019-02-11 14:21:24 -0800369 Flag("--runtime-arg").FlagWithInputList("-Xbootclasspath:", module.PreoptBootClassPathDexFiles, ":").
370 Flag("--runtime-arg").FlagWithList("-Xbootclasspath-locations:", module.PreoptBootClassPathDexLocations, ":").
Colin Cross43f08db2018-11-12 10:13:39 -0800371 Flag("${class_loader_context_arg}").
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000372 Flag("${stored_class_loader_context_arg}").
Jeongik Chaa5969092021-05-07 18:53:21 +0900373 FlagWithArg("--boot-image=", strings.Join(module.DexPreoptImageLocationsOnHost, ":")).Implicits(module.DexPreoptImagesDeps[archIdx].Paths()).
Colin Cross43f08db2018-11-12 10:13:39 -0800374 FlagWithInput("--dex-file=", module.DexPath).
Nicolas Geoffray2464ef42019-03-05 14:07:07 +0000375 FlagWithArg("--dex-location=", dexLocationArg).
Colin Cross43f08db2018-11-12 10:13:39 -0800376 FlagWithOutput("--oat-file=", odexPath).ImplicitOutput(vdexPath).
377 // Pass an empty directory, dex2oat shouldn't be reading arbitrary files
378 FlagWithArg("--android-root=", global.EmptyDirectory).
Colin Cross74ba9622019-02-11 15:11:14 -0800379 FlagWithArg("--instruction-set=", arch.String()).
Colin Cross43f08db2018-11-12 10:13:39 -0800380 FlagWithArg("--instruction-set-variant=", global.CpuVariant[arch]).
381 FlagWithArg("--instruction-set-features=", global.InstructionSetFeatures[arch]).
382 Flag("--no-generate-debug-info").
383 Flag("--generate-build-id").
384 Flag("--abort-on-hard-verifier-error").
385 Flag("--force-determinism").
386 FlagWithArg("--no-inline-from=", "core-oj.jar")
387
388 var preoptFlags []string
389 if len(module.PreoptFlags) > 0 {
390 preoptFlags = module.PreoptFlags
391 } else if len(global.PreoptFlags) > 0 {
392 preoptFlags = global.PreoptFlags
393 }
394
395 if len(preoptFlags) > 0 {
396 cmd.Text(strings.Join(preoptFlags, " "))
397 }
398
399 if module.UncompressedDex {
400 cmd.FlagWithArg("--copy-dex-files=", "false")
401 }
402
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800403 if !android.PrefixInList(preoptFlags, "--compiler-filter=") {
Colin Cross43f08db2018-11-12 10:13:39 -0800404 var compilerFilter string
Jiakai Zhang519c5c82021-09-16 06:15:39 +0000405 if systemServerJars.ContainsJar(module.Name) {
Colin Cross43f08db2018-11-12 10:13:39 -0800406 if global.SystemServerCompilerFilter != "" {
Ulya Trafimovich6fad1d02022-06-30 13:21:35 +0100407 // Use the product option if it is set.
Colin Cross43f08db2018-11-12 10:13:39 -0800408 compilerFilter = global.SystemServerCompilerFilter
Ulya Trafimovich6fad1d02022-06-30 13:21:35 +0100409 } else if profile != nil {
410 // Use "speed-profile" for system server jars that have a profile.
411 compilerFilter = "speed-profile"
Colin Cross43f08db2018-11-12 10:13:39 -0800412 } else {
Ulya Trafimovich6fad1d02022-06-30 13:21:35 +0100413 // Use "speed" for system server jars that do not have a profile.
Colin Cross43f08db2018-11-12 10:13:39 -0800414 compilerFilter = "speed"
415 }
416 } else if contains(global.SpeedApps, module.Name) || contains(global.SystemServerApps, module.Name) {
417 // Apps loaded into system server, and apps the product default to being compiled with the
418 // 'speed' compiler filter.
419 compilerFilter = "speed"
Colin Cross69f59a32019-02-15 10:39:37 -0800420 } else if profile != nil {
Colin Cross43f08db2018-11-12 10:13:39 -0800421 // For non system server jars, use speed-profile when we have a profile.
422 compilerFilter = "speed-profile"
423 } else if global.DefaultCompilerFilter != "" {
424 compilerFilter = global.DefaultCompilerFilter
425 } else {
426 compilerFilter = "quicken"
427 }
Ulya Trafimovich8c35fcf2021-02-17 16:23:28 +0000428 if module.EnforceUsesLibraries {
429 // If the verify_uses_libraries check failed (in this case status file contains a
Ulya Trafimovich4a13acb2021-03-02 12:25:02 +0000430 // non-empty error message), then use "verify" compiler filter to avoid compiling any
Ulya Trafimovich8c35fcf2021-02-17 16:23:28 +0000431 // code (it would be rejected on device because of a class loader context mismatch).
432 cmd.Text("--compiler-filter=$(if test -s ").
433 Input(module.EnforceUsesLibrariesStatusFile).
Ulya Trafimovich4a13acb2021-03-02 12:25:02 +0000434 Text(" ; then echo verify ; else echo " + compilerFilter + " ; fi)")
Ulya Trafimovich8c35fcf2021-02-17 16:23:28 +0000435 } else {
436 cmd.FlagWithArg("--compiler-filter=", compilerFilter)
437 }
Colin Cross43f08db2018-11-12 10:13:39 -0800438 }
439
440 if generateDM {
441 cmd.FlagWithArg("--copy-dex-files=", "false")
Colin Cross69f59a32019-02-15 10:39:37 -0800442 dmPath := module.BuildPath.InSameDir(ctx, "generated.dm")
Colin Cross43f08db2018-11-12 10:13:39 -0800443 dmInstalledPath := pathtools.ReplaceExtension(module.DexLocation, "dm")
Colin Cross69f59a32019-02-15 10:39:37 -0800444 tmpPath := module.BuildPath.InSameDir(ctx, "primary.vdex")
Colin Cross43f08db2018-11-12 10:13:39 -0800445 rule.Command().Text("cp -f").Input(vdexPath).Output(tmpPath)
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000446 rule.Command().Tool(globalSoong.SoongZip).
Colin Cross43f08db2018-11-12 10:13:39 -0800447 FlagWithArg("-L", "9").
448 FlagWithOutput("-o", dmPath).
449 Flag("-j").
450 Input(tmpPath)
451 rule.Install(dmPath, dmInstalledPath)
452 }
453
454 // By default, emit debug info.
455 debugInfo := true
456 if global.NoDebugInfo {
457 // If the global setting suppresses mini-debug-info, disable it.
458 debugInfo = false
459 }
460
461 // PRODUCT_SYSTEM_SERVER_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO.
462 // PRODUCT_OTHER_JAVA_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO.
Jiakai Zhang519c5c82021-09-16 06:15:39 +0000463 if systemServerJars.ContainsJar(module.Name) {
Colin Cross43f08db2018-11-12 10:13:39 -0800464 if global.AlwaysSystemServerDebugInfo {
465 debugInfo = true
466 } else if global.NeverSystemServerDebugInfo {
467 debugInfo = false
468 }
469 } else {
470 if global.AlwaysOtherDebugInfo {
471 debugInfo = true
472 } else if global.NeverOtherDebugInfo {
473 debugInfo = false
474 }
475 }
476
Colin Cross43f08db2018-11-12 10:13:39 -0800477 if debugInfo {
478 cmd.Flag("--generate-mini-debug-info")
479 } else {
480 cmd.Flag("--no-generate-mini-debug-info")
481 }
482
483 // Set the compiler reason to 'prebuilt' to identify the oat files produced
484 // during the build, as opposed to compiled on the device.
485 cmd.FlagWithArg("--compilation-reason=", "prebuilt")
486
487 if appImage {
Colin Cross69f59a32019-02-15 10:39:37 -0800488 appImagePath := odexPath.ReplaceExtension(ctx, "art")
Colin Cross43f08db2018-11-12 10:13:39 -0800489 appImageInstallPath := pathtools.ReplaceExtension(odexInstallPath, "art")
490 cmd.FlagWithOutput("--app-image-file=", appImagePath).
491 FlagWithArg("--image-format=", "lz4")
Mathieu Chartier3f7ddbb2019-04-29 09:33:50 -0700492 if !global.DontResolveStartupStrings {
493 cmd.FlagWithArg("--resolve-startup-const-strings=", "true")
494 }
Colin Cross43f08db2018-11-12 10:13:39 -0800495 rule.Install(appImagePath, appImageInstallPath)
496 }
497
Colin Cross69f59a32019-02-15 10:39:37 -0800498 if profile != nil {
499 cmd.FlagWithInput("--profile-file=", profile)
Colin Cross43f08db2018-11-12 10:13:39 -0800500 }
501
Jiakai Zhang616be062022-11-16 11:50:59 +0000502 if global.EnableUffdGc {
503 cmd.Flag("--runtime-arg").Flag("-Xgc:CMC")
504 }
505
Colin Cross43f08db2018-11-12 10:13:39 -0800506 rule.Install(odexPath, odexInstallPath)
507 rule.Install(vdexPath, vdexInstallPath)
508}
509
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000510func shouldGenerateDM(module *ModuleConfig, global *GlobalConfig) bool {
Colin Cross43f08db2018-11-12 10:13:39 -0800511 // Generating DM files only makes sense for verify, avoid doing for non verify compiler filter APKs.
512 // No reason to use a dm file if the dex is already uncompressed.
513 return global.GenerateDMFiles && !module.UncompressedDex &&
514 contains(module.PreoptFlags, "--compiler-filter=verify")
515}
516
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000517func OdexOnSystemOtherByName(name string, dexLocation string, global *GlobalConfig) bool {
Colin Cross43f08db2018-11-12 10:13:39 -0800518 if !global.HasSystemOther {
519 return false
520 }
521
522 if global.SanitizeLite {
523 return false
524 }
525
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000526 if contains(global.SpeedApps, name) || contains(global.SystemServerApps, name) {
Colin Cross43f08db2018-11-12 10:13:39 -0800527 return false
528 }
529
530 for _, f := range global.PatternsOnSystemOther {
Anton Hanssonda4d9d92020-09-15 09:28:55 +0000531 if makefileMatch(filepath.Join(SystemPartition, f), dexLocation) {
Colin Cross43f08db2018-11-12 10:13:39 -0800532 return true
533 }
534 }
535
536 return false
537}
538
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000539func odexOnSystemOther(module *ModuleConfig, global *GlobalConfig) bool {
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000540 return OdexOnSystemOtherByName(module.Name, module.DexLocation, global)
541}
542
Colin Crossc7e40aa2019-02-08 21:37:00 -0800543// PathToLocation converts .../system/framework/arm64/boot.art to .../system/framework/boot.art
Colin Cross69f59a32019-02-15 10:39:37 -0800544func PathToLocation(path android.Path, arch android.ArchType) string {
Jeongik Cha4dda75e2021-04-27 23:56:44 +0900545 return PathStringToLocation(path.String(), arch)
546}
547
548// PathStringToLocation converts .../system/framework/arm64/boot.art to .../system/framework/boot.art
549func PathStringToLocation(path string, arch android.ArchType) string {
550 pathArch := filepath.Base(filepath.Dir(path))
Colin Cross74ba9622019-02-11 15:11:14 -0800551 if pathArch != arch.String() {
552 panic(fmt.Errorf("last directory in %q must be %q", path, arch.String()))
Colin Crossc7e40aa2019-02-08 21:37:00 -0800553 }
Jeongik Cha4dda75e2021-04-27 23:56:44 +0900554 return filepath.Join(filepath.Dir(filepath.Dir(path)), filepath.Base(path))
Colin Crossc7e40aa2019-02-08 21:37:00 -0800555}
556
Colin Cross43f08db2018-11-12 10:13:39 -0800557func makefileMatch(pattern, s string) bool {
558 percent := strings.IndexByte(pattern, '%')
559 switch percent {
560 case -1:
561 return pattern == s
562 case len(pattern) - 1:
563 return strings.HasPrefix(s, pattern[:len(pattern)-1])
564 default:
565 panic(fmt.Errorf("unsupported makefile pattern %q", pattern))
566 }
567}
568
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000569// A predefined location for the system server dex jars. This is needed in order to generate
570// class loader context for dex2oat, as the path to the jar in the Soong module may be unknown
571// at that time (Soong processes the jars in dependency order, which may be different from the
572// the system server classpath order).
573func SystemServerDexJarHostPath(ctx android.PathContext, jar string) android.OutputPath {
Ulya Trafimovich6cf2c0c2020-04-24 12:15:20 +0100574 if DexpreoptRunningInSoong {
575 // Soong module, just use the default output directory $OUT/soong.
576 return android.PathForOutput(ctx, "system_server_dexjars", jar+".jar")
577 } else {
578 // Make module, default output directory is $OUT (passed via the "null config" created
579 // by dexpreopt_gen). Append Soong subdirectory to match Soong module paths.
580 return android.PathForOutput(ctx, "soong", "system_server_dexjars", jar+".jar")
581 }
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000582}
583
Ulya Trafimovichcd3203f2020-03-27 11:30:00 +0000584// Check the order of jars on the system server classpath and give a warning/error if a jar precedes
585// one of its dependencies. This is not an error, but a missed optimization, as dexpreopt won't
586// have the dependency jar in the class loader context, and it won't be able to resolve any
587// references to its classes and methods.
588func checkSystemServerOrder(ctx android.PathContext, jarIndex int) {
589 mctx, isModule := ctx.(android.ModuleContext)
590 if isModule {
591 config := GetGlobalConfig(ctx)
Jiakai Zhang389a6472021-12-14 18:54:06 +0000592 jars := config.AllSystemServerClasspathJars(ctx)
Ulya Trafimovichcd3203f2020-03-27 11:30:00 +0000593 mctx.WalkDeps(func(dep android.Module, parent android.Module) bool {
Jiakai Zhang519c5c82021-09-16 06:15:39 +0000594 depIndex := jars.IndexOfJar(dep.Name())
Ulya Trafimovichcd3203f2020-03-27 11:30:00 +0000595 if jarIndex < depIndex && !config.BrokenSuboptimalOrderOfSystemServerJars {
Jiakai Zhang519c5c82021-09-16 06:15:39 +0000596 jar := jars.Jar(jarIndex)
597 dep := jars.Jar(depIndex)
Ulya Trafimovichcd3203f2020-03-27 11:30:00 +0000598 mctx.ModuleErrorf("non-optimal order of jars on the system server classpath:"+
599 " '%s' precedes its dependency '%s', so dexpreopt is unable to resolve any"+
600 " references from '%s' to '%s'.\n", jar, dep, jar, dep)
601 }
602 return true
603 })
604 }
605}
606
Ulya Trafimovich8c35fcf2021-02-17 16:23:28 +0000607// Returns path to a file containing the reult of verify_uses_libraries check (empty if the check
608// has succeeded, or an error message if it failed).
609func UsesLibrariesStatusFile(ctx android.ModuleContext) android.WritablePath {
610 return android.PathForModuleOut(ctx, "enforce_uses_libraries.status")
611}
612
Colin Cross43f08db2018-11-12 10:13:39 -0800613func contains(l []string, s string) bool {
614 for _, e := range l {
615 if e == s {
616 return true
617 }
618 }
619 return false
620}
621
Colin Cross454c0872019-02-15 23:03:34 -0800622var copyOf = android.CopyOf