blob: 814b75dc79b826afb3b1b6b5e32c6d6674eeeaff [file] [log] [blame]
Colin Cross43f08db2018-11-12 10:13:39 -08001// Copyright 2018 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15// The dexpreopt package converts a global dexpreopt config and a module dexpreopt config into rules to perform
Nicolas Geoffrayc1bf7242019-10-18 14:51:38 +010016// dexpreopting.
Colin Cross43f08db2018-11-12 10:13:39 -080017//
18// It is used in two places; in the dexpeopt_gen binary for modules defined in Make, and directly linked into Soong.
19//
20// For Make modules it is built into the dexpreopt_gen binary, which is executed as a Make rule using global config and
21// module config specified in JSON files. The binary writes out two shell scripts, only updating them if they have
22// changed. One script takes an APK or JAR as an input and produces a zip file containing any outputs of preopting,
23// in the location they should be on the device. The Make build rules will unzip the zip file into $(PRODUCT_OUT) when
24// installing the APK, which will install the preopt outputs into $(PRODUCT_OUT)/system or $(PRODUCT_OUT)/system_other
Nicolas Geoffrayc1bf7242019-10-18 14:51:38 +010025// as necessary. The zip file may be empty if preopting was disabled for any reason.
Colin Cross43f08db2018-11-12 10:13:39 -080026//
27// The intermediate shell scripts allow changes to this package or to the global config to regenerate the shell scripts
28// but only require re-executing preopting if the script has changed.
29//
30// For Soong modules this package is linked directly into Soong and run from the java package. It generates the same
31// commands as for make, using athe same global config JSON file used by make, but using a module config structure
32// provided by Soong. The generated commands are then converted into Soong rule and written directly to the ninja file,
33// with no extra shell scripts involved.
34package dexpreopt
35
36import (
37 "fmt"
38 "path/filepath"
Colin Cross69f59a32019-02-15 10:39:37 -080039 "runtime"
Colin Cross43f08db2018-11-12 10:13:39 -080040 "strings"
41
Colin Crossfeec25b2019-01-30 17:32:39 -080042 "android/soong/android"
43
Colin Cross43f08db2018-11-12 10:13:39 -080044 "github.com/google/blueprint/pathtools"
45)
46
47const SystemPartition = "/system/"
48const SystemOtherPartition = "/system_other/"
49
Ulya Trafimovich6cf2c0c2020-04-24 12:15:20 +010050var DexpreoptRunningInSoong = false
51
Colin Cross43f08db2018-11-12 10:13:39 -080052// GenerateDexpreoptRule generates a set of commands that will preopt a module based on a GlobalConfig and a
53// ModuleConfig. The produced files and their install locations will be available through rule.Installs().
Martin Stjernholm8d80cee2020-01-31 17:44:54 +000054func GenerateDexpreoptRule(ctx android.PathContext, globalSoong *GlobalSoongConfig,
55 global *GlobalConfig, module *ModuleConfig) (rule *android.RuleBuilder, err error) {
Colin Cross69f59a32019-02-15 10:39:37 -080056
Colin Cross43f08db2018-11-12 10:13:39 -080057 defer func() {
58 if r := recover(); r != nil {
Colin Cross69f59a32019-02-15 10:39:37 -080059 if _, ok := r.(runtime.Error); ok {
60 panic(r)
61 } else if e, ok := r.(error); ok {
Colin Cross43f08db2018-11-12 10:13:39 -080062 err = e
63 rule = nil
64 } else {
65 panic(r)
66 }
67 }
68 }()
69
Colin Cross758290d2019-02-01 16:42:32 -080070 rule = android.NewRuleBuilder()
Colin Cross43f08db2018-11-12 10:13:39 -080071
Colin Cross69f59a32019-02-15 10:39:37 -080072 generateProfile := module.ProfileClassListing.Valid() && !global.DisableGenerateProfile
Nicolas Geoffraye7102422019-07-24 13:19:29 +010073 generateBootProfile := module.ProfileBootListing.Valid() && !global.DisableGenerateProfile
Colin Cross43f08db2018-11-12 10:13:39 -080074
Colin Cross69f59a32019-02-15 10:39:37 -080075 var profile android.WritablePath
Colin Crosscbed6572019-01-08 17:38:37 -080076 if generateProfile {
Martin Stjernholm75a48d82020-01-10 20:32:59 +000077 profile = profileCommand(ctx, globalSoong, global, module, rule)
Colin Crosscbed6572019-01-08 17:38:37 -080078 }
Nicolas Geoffraye7102422019-07-24 13:19:29 +010079 if generateBootProfile {
Martin Stjernholm75a48d82020-01-10 20:32:59 +000080 bootProfileCommand(ctx, globalSoong, global, module, rule)
Nicolas Geoffraye7102422019-07-24 13:19:29 +010081 }
Colin Crosscbed6572019-01-08 17:38:37 -080082
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +000083 if !dexpreoptDisabled(ctx, global, module) {
Ulya Trafimovichfc24ad32020-08-19 16:32:54 +010084 if clc := genClassLoaderContext(ctx, global, module); clc != nil {
Colin Crosscbed6572019-01-08 17:38:37 -080085 appImage := (generateProfile || module.ForceCreateAppImage || global.DefaultAppImages) &&
86 !module.NoCreateAppImage
87
88 generateDM := shouldGenerateDM(module, global)
89
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +000090 for archIdx, _ := range module.Archs {
Ulya Trafimovichfc24ad32020-08-19 16:32:54 +010091 dexpreoptCommand(ctx, globalSoong, global, module, rule, archIdx, *clc, profile, appImage, generateDM)
Colin Crosscbed6572019-01-08 17:38:37 -080092 }
93 }
94 }
95
96 return rule, nil
97}
98
Martin Stjernholm8d80cee2020-01-31 17:44:54 +000099func dexpreoptDisabled(ctx android.PathContext, global *GlobalConfig, module *ModuleConfig) bool {
Colin Crosscbed6572019-01-08 17:38:37 -0800100 if contains(global.DisablePreoptModules, module.Name) {
101 return true
Colin Cross43f08db2018-11-12 10:13:39 -0800102 }
103
Ulya Trafimovichfc24ad32020-08-19 16:32:54 +0100104 // Don't preopt individual boot jars, they will be preopted together.
105 if global.BootJars.ContainsJar(module.Name) {
106 return true
107 }
108
Ulyana Trafimovichf2cb7e92019-11-27 12:26:49 +0000109 // Don't preopt system server jars that are updatable.
Ulya Trafimovich249386a2020-07-01 14:31:13 +0100110 if global.UpdatableSystemServerJars.ContainsJar(module.Name) {
111 return true
Ulyana Trafimovichf2cb7e92019-11-27 12:26:49 +0000112 }
113
Colin Cross43f08db2018-11-12 10:13:39 -0800114 // If OnlyPreoptBootImageAndSystemServer=true and module is not in boot class path skip
115 // Also preopt system server jars since selinux prevents system server from loading anything from
116 // /data. If we don't do this they will need to be extracted which is not favorable for RAM usage
117 // or performance. If PreoptExtractedApk is true, we ignore the only preopt boot image options.
Ulya Trafimovich249386a2020-07-01 14:31:13 +0100118 if global.OnlyPreoptBootImageAndSystemServer && !global.BootJars.ContainsJar(module.Name) &&
Colin Cross43f08db2018-11-12 10:13:39 -0800119 !contains(global.SystemServerJars, module.Name) && !module.PreoptExtractedApk {
Colin Crosscbed6572019-01-08 17:38:37 -0800120 return true
Colin Cross43f08db2018-11-12 10:13:39 -0800121 }
122
Colin Crosscbed6572019-01-08 17:38:37 -0800123 return false
Colin Cross43f08db2018-11-12 10:13:39 -0800124}
125
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000126func profileCommand(ctx android.PathContext, globalSoong *GlobalSoongConfig, global *GlobalConfig,
127 module *ModuleConfig, rule *android.RuleBuilder) android.WritablePath {
Colin Cross69f59a32019-02-15 10:39:37 -0800128
129 profilePath := module.BuildPath.InSameDir(ctx, "profile.prof")
Colin Cross43f08db2018-11-12 10:13:39 -0800130 profileInstalledPath := module.DexLocation + ".prof"
131
132 if !module.ProfileIsTextListing {
133 rule.Command().FlagWithOutput("touch ", profilePath)
134 }
135
136 cmd := rule.Command().
137 Text(`ANDROID_LOG_TAGS="*:e"`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000138 Tool(globalSoong.Profman)
Colin Cross43f08db2018-11-12 10:13:39 -0800139
140 if module.ProfileIsTextListing {
141 // The profile is a test listing of classes (used for framework jars).
142 // We need to generate the actual binary profile before being able to compile.
Colin Cross69f59a32019-02-15 10:39:37 -0800143 cmd.FlagWithInput("--create-profile-from=", module.ProfileClassListing.Path())
Colin Cross43f08db2018-11-12 10:13:39 -0800144 } else {
145 // The profile is binary profile (used for apps). Run it through profman to
146 // ensure the profile keys match the apk.
147 cmd.
148 Flag("--copy-and-update-profile-key").
Colin Cross69f59a32019-02-15 10:39:37 -0800149 FlagWithInput("--profile-file=", module.ProfileClassListing.Path())
Colin Cross43f08db2018-11-12 10:13:39 -0800150 }
151
152 cmd.
153 FlagWithInput("--apk=", module.DexPath).
154 Flag("--dex-location="+module.DexLocation).
155 FlagWithOutput("--reference-profile-file=", profilePath)
156
157 if !module.ProfileIsTextListing {
158 cmd.Text(fmt.Sprintf(`|| echo "Profile out of date for %s"`, module.DexPath))
159 }
160 rule.Install(profilePath, profileInstalledPath)
161
162 return profilePath
163}
164
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000165func bootProfileCommand(ctx android.PathContext, globalSoong *GlobalSoongConfig, global *GlobalConfig,
166 module *ModuleConfig, rule *android.RuleBuilder) android.WritablePath {
Nicolas Geoffraye7102422019-07-24 13:19:29 +0100167
168 profilePath := module.BuildPath.InSameDir(ctx, "profile.bprof")
169 profileInstalledPath := module.DexLocation + ".bprof"
170
171 if !module.ProfileIsTextListing {
172 rule.Command().FlagWithOutput("touch ", profilePath)
173 }
174
175 cmd := rule.Command().
176 Text(`ANDROID_LOG_TAGS="*:e"`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000177 Tool(globalSoong.Profman)
Nicolas Geoffraye7102422019-07-24 13:19:29 +0100178
179 // The profile is a test listing of methods.
180 // We need to generate the actual binary profile.
181 cmd.FlagWithInput("--create-profile-from=", module.ProfileBootListing.Path())
182
183 cmd.
184 Flag("--generate-boot-profile").
185 FlagWithInput("--apk=", module.DexPath).
186 Flag("--dex-location="+module.DexLocation).
187 FlagWithOutput("--reference-profile-file=", profilePath)
188
189 if !module.ProfileIsTextListing {
190 cmd.Text(fmt.Sprintf(`|| echo "Profile out of date for %s"`, module.DexPath))
191 }
192 rule.Install(profilePath, profileInstalledPath)
193
194 return profilePath
195}
196
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100197type classLoaderContext struct {
198 // The class loader context using paths in the build.
199 Host android.Paths
200
201 // The class loader context using paths as they will be on the device.
202 Target []string
203}
204
205// A map of class loader contexts for each SDK version.
206// A map entry for "any" version contains libraries that are unconditionally added to class loader
207// context. Map entries for existing versions contains libraries that were in the default classpath
208// until that API version, and should be added to class loader context if and only if the
209// targetSdkVersion in the manifest or APK is less than that API version.
210type classLoaderContextMap map[int]*classLoaderContext
211
Ulya Trafimovich5f364b62020-06-30 12:39:01 +0100212const anySdkVersion int = 9999 // should go last in class loader context
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100213
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100214func (m classLoaderContextMap) getValue(sdkVer int) *classLoaderContext {
215 if _, ok := m[sdkVer]; !ok {
216 m[sdkVer] = &classLoaderContext{}
217 }
218 return m[sdkVer]
219}
220
Ulya Trafimovicha54d33b2020-09-23 16:55:42 +0100221func (m classLoaderContextMap) addLibs(ctx android.PathContext, sdkVer int, module *ModuleConfig, libs ...string) bool {
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100222 clc := m.getValue(sdkVer)
223 for _, lib := range libs {
Ulya Trafimovicha54d33b2020-09-23 16:55:42 +0100224 if p, ok := module.LibraryPaths[lib]; ok && p.Host != nil && p.Device != UnknownInstallLibraryPath {
Ulya Trafimovichfc24ad32020-08-19 16:32:54 +0100225 clc.Host = append(clc.Host, p.Host)
226 clc.Target = append(clc.Target, p.Device)
227 } else {
Ulya Trafimovicha54d33b2020-09-23 16:55:42 +0100228 if sdkVer == anySdkVersion {
229 // Fail the build if dexpreopt doesn't know paths to one of the <uses-library>
230 // dependencies. In the future we may need to relax this and just disable dexpreopt.
231 android.ReportPathErrorf(ctx, "dexpreopt cannot find path for <uses-library> '%s'", lib)
232 } else {
233 // No error for compatibility libraries, as Soong doesn't know if they are needed
234 // (this depends on the targetSdkVersion in the manifest).
235 }
Ulya Trafimovichfc24ad32020-08-19 16:32:54 +0100236 return false
237 }
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100238 }
Ulya Trafimovichfc24ad32020-08-19 16:32:54 +0100239 return true
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100240}
241
242func (m classLoaderContextMap) addSystemServerLibs(sdkVer int, ctx android.PathContext, module *ModuleConfig, libs ...string) {
243 clc := m.getValue(sdkVer)
244 for _, lib := range libs {
245 clc.Host = append(clc.Host, SystemServerDexJarHostPath(ctx, lib))
246 clc.Target = append(clc.Target, filepath.Join("/system/framework", lib+".jar"))
247 }
248}
249
Ulya Trafimovichfc24ad32020-08-19 16:32:54 +0100250// genClassLoaderContext generates host and target class loader context to be passed to the dex2oat
251// command for the dexpreopted module. There are three possible cases:
252//
253// 1. System server jars. They have a special class loader context that includes other system
254// server jars.
255//
256// 2. Library jars or APKs which have precise list of their <uses-library> libs. Their class loader
257// context includes build and on-device paths to these libs. In some cases it may happen that
258// the path to a <uses-library> is unknown (e.g. the dexpreopted module may depend on stubs
259// library, whose implementation library is missing from the build altogether). In such case
260// dexpreopting with the <uses-library> is impossible, and dexpreopting without it is pointless,
261// as the runtime classpath won't match and the dexpreopted code will be discarded. Therefore in
262// such cases the function returns nil, which disables dexpreopt.
263//
264// 2. All other library jars or APKs for which the exact <uses-library> list is unknown. They use
265// the unsafe &-classpath workaround that means empty class loader context and absence of runtime
266// check that the class loader context provided by the PackageManager agrees with the stored
267// class loader context recorded in the .odex file.
268//
269func genClassLoaderContext(ctx android.PathContext, global *GlobalConfig, module *ModuleConfig) *classLoaderContextMap {
270 classLoaderContexts := make(classLoaderContextMap)
271 systemServerJars := NonUpdatableSystemServerJars(ctx, global)
272
273 if jarIndex := android.IndexList(module.Name, systemServerJars); jarIndex >= 0 {
274 // System server jars should be dexpreopted together: class loader context of each jar
275 // should include all preceding jars on the system server classpath.
276 classLoaderContexts.addSystemServerLibs(anySdkVersion, ctx, module, systemServerJars[:jarIndex]...)
277
278 } else if module.EnforceUsesLibraries {
279 // Unconditional class loader context.
280 usesLibs := append(copyOf(module.UsesLibraries), module.OptionalUsesLibraries...)
Ulya Trafimovicha54d33b2020-09-23 16:55:42 +0100281 if !classLoaderContexts.addLibs(ctx, anySdkVersion, module, usesLibs...) {
Ulya Trafimovichfc24ad32020-08-19 16:32:54 +0100282 return nil
283 }
284
285 // Conditional class loader context for API version < 28.
286 const httpLegacy = "org.apache.http.legacy"
287 if !contains(usesLibs, httpLegacy) {
Ulya Trafimovicha54d33b2020-09-23 16:55:42 +0100288 if !classLoaderContexts.addLibs(ctx, 28, module, httpLegacy) {
Ulya Trafimovichfc24ad32020-08-19 16:32:54 +0100289 return nil
290 }
291 }
292
293 // Conditional class loader context for API version < 29.
294 usesLibs29 := []string{
295 "android.hidl.base-V1.0-java",
296 "android.hidl.manager-V1.0-java",
297 }
Ulya Trafimovicha54d33b2020-09-23 16:55:42 +0100298 if !classLoaderContexts.addLibs(ctx, 29, module, usesLibs29...) {
Ulya Trafimovichfc24ad32020-08-19 16:32:54 +0100299 return nil
300 }
301
302 // Conditional class loader context for API version < 30.
303 const testBase = "android.test.base"
304 if !contains(usesLibs, testBase) {
Ulya Trafimovicha54d33b2020-09-23 16:55:42 +0100305 if !classLoaderContexts.addLibs(ctx, 30, module, testBase) {
Ulya Trafimovichfc24ad32020-08-19 16:32:54 +0100306 return nil
307 }
308 }
309
310 } else {
311 // Pass special class loader context to skip the classpath and collision check.
312 // This will get removed once LOCAL_USES_LIBRARIES is enforced.
313 // Right now LOCAL_USES_LIBRARIES is opt in, for the case where it's not specified we still default
314 // to the &.
315 }
316
317 return &classLoaderContexts
318}
319
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000320func dexpreoptCommand(ctx android.PathContext, globalSoong *GlobalSoongConfig, global *GlobalConfig,
Ulya Trafimovichfc24ad32020-08-19 16:32:54 +0100321 module *ModuleConfig, rule *android.RuleBuilder, archIdx int, classLoaderContexts classLoaderContextMap,
322 profile android.WritablePath, appImage bool, generateDM bool) {
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000323
324 arch := module.Archs[archIdx]
Colin Cross43f08db2018-11-12 10:13:39 -0800325
326 // HACK: make soname in Soong-generated .odex files match Make.
327 base := filepath.Base(module.DexLocation)
328 if filepath.Ext(base) == ".jar" {
329 base = "javalib.jar"
330 } else if filepath.Ext(base) == ".apk" {
331 base = "package.apk"
332 }
333
334 toOdexPath := func(path string) string {
335 return filepath.Join(
336 filepath.Dir(path),
337 "oat",
Colin Cross74ba9622019-02-11 15:11:14 -0800338 arch.String(),
Colin Cross43f08db2018-11-12 10:13:39 -0800339 pathtools.ReplaceExtension(filepath.Base(path), "odex"))
340 }
341
Colin Cross69f59a32019-02-15 10:39:37 -0800342 odexPath := module.BuildPath.InSameDir(ctx, "oat", arch.String(), pathtools.ReplaceExtension(base, "odex"))
Colin Cross43f08db2018-11-12 10:13:39 -0800343 odexInstallPath := toOdexPath(module.DexLocation)
344 if odexOnSystemOther(module, global) {
Anton Hansson43ab0bc2019-10-03 14:18:45 +0100345 odexInstallPath = filepath.Join(SystemOtherPartition, odexInstallPath)
Colin Cross43f08db2018-11-12 10:13:39 -0800346 }
347
Colin Cross69f59a32019-02-15 10:39:37 -0800348 vdexPath := odexPath.ReplaceExtension(ctx, "vdex")
Colin Cross43f08db2018-11-12 10:13:39 -0800349 vdexInstallPath := pathtools.ReplaceExtension(odexInstallPath, "vdex")
350
Colin Cross69f59a32019-02-15 10:39:37 -0800351 invocationPath := odexPath.ReplaceExtension(ctx, "invocation")
Alex Light5de41962018-12-18 15:16:26 -0800352
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000353 systemServerJars := NonUpdatableSystemServerJars(ctx, global)
354
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100355 rule.Command().FlagWithArg("mkdir -p ", filepath.Dir(odexPath.String()))
356 rule.Command().FlagWithOutput("rm -f ", odexPath)
Ulya Trafimovichc9af5382020-05-29 15:35:06 +0100357
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100358 if jarIndex := android.IndexList(module.Name, systemServerJars); jarIndex >= 0 {
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100359 // Copy the system server jar to a predefined location where dex2oat will find it.
360 dexPathHost := SystemServerDexJarHostPath(ctx, module.Name)
361 rule.Command().Text("mkdir -p").Flag(filepath.Dir(dexPathHost.String()))
362 rule.Command().Text("cp -f").Input(module.DexPath).Output(dexPathHost)
363
364 checkSystemServerOrder(ctx, jarIndex)
365
366 clc := classLoaderContexts[anySdkVersion]
367 rule.Command().
368 Text("class_loader_context_arg=--class-loader-context=PCL[" + strings.Join(clc.Host.Strings(), ":") + "]").
369 Implicits(clc.Host).
370 Text("stored_class_loader_context_arg=--stored-class-loader-context=PCL[" + strings.Join(clc.Target, ":") + "]")
371 } else if module.EnforceUsesLibraries {
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100372 // Generate command that saves target SDK version in a shell variable.
Colin Cross38b96852019-05-22 10:21:09 -0700373 if module.ManifestPath != nil {
374 rule.Command().Text(`target_sdk_version="$(`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000375 Tool(globalSoong.ManifestCheck).
Colin Cross38b96852019-05-22 10:21:09 -0700376 Flag("--extract-target-sdk-version").
377 Input(module.ManifestPath).
378 Text(`)"`)
379 } else {
380 // No manifest to extract targetSdkVersion from, hope that DexJar is an APK
381 rule.Command().Text(`target_sdk_version="$(`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000382 Tool(globalSoong.Aapt).
Colin Cross38b96852019-05-22 10:21:09 -0700383 Flag("dump badging").
384 Input(module.DexPath).
385 Text(`| grep "targetSdkVersion" | sed -n "s/targetSdkVersion:'\(.*\)'/\1/p"`).
386 Text(`)"`)
387 }
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100388
Ulya Trafimovich5f364b62020-06-30 12:39:01 +0100389 // Generate command that saves host and target class loader context in shell variables.
390 cmd := rule.Command().
391 Text(`eval "$(`).Tool(globalSoong.ConstructContext).
392 Text(` --target-sdk-version ${target_sdk_version}`)
Ulya Trafimovichb8063c62020-08-20 11:33:12 +0100393 for _, ver := range android.SortedIntKeys(classLoaderContexts) {
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100394 clc := classLoaderContexts.getValue(ver)
Ulya Trafimovich5f364b62020-06-30 12:39:01 +0100395 verString := fmt.Sprintf("%d", ver)
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100396 if ver == anySdkVersion {
Ulya Trafimovich5f364b62020-06-30 12:39:01 +0100397 verString = "any" // a special keyword that means any SDK version
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100398 }
Ulya Trafimovich5f364b62020-06-30 12:39:01 +0100399 cmd.Textf(`--host-classpath-for-sdk %s %s`, verString, strings.Join(clc.Host.Strings(), ":")).
400 Implicits(clc.Host).
401 Textf(`--target-classpath-for-sdk %s %s`, verString, strings.Join(clc.Target, ":"))
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100402 }
Ulya Trafimovich5f364b62020-06-30 12:39:01 +0100403 cmd.Text(`)"`)
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100404 } else {
405 // Pass special class loader context to skip the classpath and collision check.
406 // This will get removed once LOCAL_USES_LIBRARIES is enforced.
407 // Right now LOCAL_USES_LIBRARIES is opt in, for the case where it's not specified we still default
408 // to the &.
409 rule.Command().
410 Text(`class_loader_context_arg=--class-loader-context=\&`).
411 Text(`stored_class_loader_context_arg=""`)
Colin Cross43f08db2018-11-12 10:13:39 -0800412 }
413
Nicolas Geoffray2464ef42019-03-05 14:07:07 +0000414 // Devices that do not have a product partition use a symlink from /product to /system/product.
415 // Because on-device dexopt will see dex locations starting with /product, we change the paths
416 // to mimic this behavior.
417 dexLocationArg := module.DexLocation
418 if strings.HasPrefix(dexLocationArg, "/system/product/") {
419 dexLocationArg = strings.TrimPrefix(dexLocationArg, "/system")
420 }
421
Colin Cross43f08db2018-11-12 10:13:39 -0800422 cmd := rule.Command().
423 Text(`ANDROID_LOG_TAGS="*:e"`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000424 Tool(globalSoong.Dex2oat).
Colin Cross43f08db2018-11-12 10:13:39 -0800425 Flag("--avoid-storing-invocation").
Alex Light5de41962018-12-18 15:16:26 -0800426 FlagWithOutput("--write-invocation-to=", invocationPath).ImplicitOutput(invocationPath).
Colin Cross43f08db2018-11-12 10:13:39 -0800427 Flag("--runtime-arg").FlagWithArg("-Xms", global.Dex2oatXms).
428 Flag("--runtime-arg").FlagWithArg("-Xmx", global.Dex2oatXmx).
Colin Cross800fe132019-02-11 14:21:24 -0800429 Flag("--runtime-arg").FlagWithInputList("-Xbootclasspath:", module.PreoptBootClassPathDexFiles, ":").
430 Flag("--runtime-arg").FlagWithList("-Xbootclasspath-locations:", module.PreoptBootClassPathDexLocations, ":").
Colin Cross43f08db2018-11-12 10:13:39 -0800431 Flag("${class_loader_context_arg}").
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000432 Flag("${stored_class_loader_context_arg}").
Ulya Trafimovich3391a1e2020-01-03 17:33:17 +0000433 FlagWithArg("--boot-image=", strings.Join(module.DexPreoptImageLocations, ":")).Implicits(module.DexPreoptImagesDeps[archIdx].Paths()).
Colin Cross43f08db2018-11-12 10:13:39 -0800434 FlagWithInput("--dex-file=", module.DexPath).
Nicolas Geoffray2464ef42019-03-05 14:07:07 +0000435 FlagWithArg("--dex-location=", dexLocationArg).
Colin Cross43f08db2018-11-12 10:13:39 -0800436 FlagWithOutput("--oat-file=", odexPath).ImplicitOutput(vdexPath).
437 // Pass an empty directory, dex2oat shouldn't be reading arbitrary files
438 FlagWithArg("--android-root=", global.EmptyDirectory).
Colin Cross74ba9622019-02-11 15:11:14 -0800439 FlagWithArg("--instruction-set=", arch.String()).
Colin Cross43f08db2018-11-12 10:13:39 -0800440 FlagWithArg("--instruction-set-variant=", global.CpuVariant[arch]).
441 FlagWithArg("--instruction-set-features=", global.InstructionSetFeatures[arch]).
442 Flag("--no-generate-debug-info").
443 Flag("--generate-build-id").
444 Flag("--abort-on-hard-verifier-error").
445 Flag("--force-determinism").
446 FlagWithArg("--no-inline-from=", "core-oj.jar")
447
448 var preoptFlags []string
449 if len(module.PreoptFlags) > 0 {
450 preoptFlags = module.PreoptFlags
451 } else if len(global.PreoptFlags) > 0 {
452 preoptFlags = global.PreoptFlags
453 }
454
455 if len(preoptFlags) > 0 {
456 cmd.Text(strings.Join(preoptFlags, " "))
457 }
458
459 if module.UncompressedDex {
460 cmd.FlagWithArg("--copy-dex-files=", "false")
461 }
462
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800463 if !android.PrefixInList(preoptFlags, "--compiler-filter=") {
Colin Cross43f08db2018-11-12 10:13:39 -0800464 var compilerFilter string
465 if contains(global.SystemServerJars, module.Name) {
466 // Jars of system server, use the product option if it is set, speed otherwise.
467 if global.SystemServerCompilerFilter != "" {
468 compilerFilter = global.SystemServerCompilerFilter
469 } else {
470 compilerFilter = "speed"
471 }
472 } else if contains(global.SpeedApps, module.Name) || contains(global.SystemServerApps, module.Name) {
473 // Apps loaded into system server, and apps the product default to being compiled with the
474 // 'speed' compiler filter.
475 compilerFilter = "speed"
Colin Cross69f59a32019-02-15 10:39:37 -0800476 } else if profile != nil {
Colin Cross43f08db2018-11-12 10:13:39 -0800477 // For non system server jars, use speed-profile when we have a profile.
478 compilerFilter = "speed-profile"
479 } else if global.DefaultCompilerFilter != "" {
480 compilerFilter = global.DefaultCompilerFilter
481 } else {
482 compilerFilter = "quicken"
483 }
484 cmd.FlagWithArg("--compiler-filter=", compilerFilter)
485 }
486
487 if generateDM {
488 cmd.FlagWithArg("--copy-dex-files=", "false")
Colin Cross69f59a32019-02-15 10:39:37 -0800489 dmPath := module.BuildPath.InSameDir(ctx, "generated.dm")
Colin Cross43f08db2018-11-12 10:13:39 -0800490 dmInstalledPath := pathtools.ReplaceExtension(module.DexLocation, "dm")
Colin Cross69f59a32019-02-15 10:39:37 -0800491 tmpPath := module.BuildPath.InSameDir(ctx, "primary.vdex")
Colin Cross43f08db2018-11-12 10:13:39 -0800492 rule.Command().Text("cp -f").Input(vdexPath).Output(tmpPath)
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000493 rule.Command().Tool(globalSoong.SoongZip).
Colin Cross43f08db2018-11-12 10:13:39 -0800494 FlagWithArg("-L", "9").
495 FlagWithOutput("-o", dmPath).
496 Flag("-j").
497 Input(tmpPath)
498 rule.Install(dmPath, dmInstalledPath)
499 }
500
501 // By default, emit debug info.
502 debugInfo := true
503 if global.NoDebugInfo {
504 // If the global setting suppresses mini-debug-info, disable it.
505 debugInfo = false
506 }
507
508 // PRODUCT_SYSTEM_SERVER_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO.
509 // PRODUCT_OTHER_JAVA_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO.
510 if contains(global.SystemServerJars, module.Name) {
511 if global.AlwaysSystemServerDebugInfo {
512 debugInfo = true
513 } else if global.NeverSystemServerDebugInfo {
514 debugInfo = false
515 }
516 } else {
517 if global.AlwaysOtherDebugInfo {
518 debugInfo = true
519 } else if global.NeverOtherDebugInfo {
520 debugInfo = false
521 }
522 }
523
524 // Never enable on eng.
525 if global.IsEng {
526 debugInfo = false
527 }
528
529 if debugInfo {
530 cmd.Flag("--generate-mini-debug-info")
531 } else {
532 cmd.Flag("--no-generate-mini-debug-info")
533 }
534
535 // Set the compiler reason to 'prebuilt' to identify the oat files produced
536 // during the build, as opposed to compiled on the device.
537 cmd.FlagWithArg("--compilation-reason=", "prebuilt")
538
539 if appImage {
Colin Cross69f59a32019-02-15 10:39:37 -0800540 appImagePath := odexPath.ReplaceExtension(ctx, "art")
Colin Cross43f08db2018-11-12 10:13:39 -0800541 appImageInstallPath := pathtools.ReplaceExtension(odexInstallPath, "art")
542 cmd.FlagWithOutput("--app-image-file=", appImagePath).
543 FlagWithArg("--image-format=", "lz4")
Mathieu Chartier3f7ddbb2019-04-29 09:33:50 -0700544 if !global.DontResolveStartupStrings {
545 cmd.FlagWithArg("--resolve-startup-const-strings=", "true")
546 }
Colin Cross43f08db2018-11-12 10:13:39 -0800547 rule.Install(appImagePath, appImageInstallPath)
548 }
549
Colin Cross69f59a32019-02-15 10:39:37 -0800550 if profile != nil {
551 cmd.FlagWithInput("--profile-file=", profile)
Colin Cross43f08db2018-11-12 10:13:39 -0800552 }
553
554 rule.Install(odexPath, odexInstallPath)
555 rule.Install(vdexPath, vdexInstallPath)
556}
557
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000558func shouldGenerateDM(module *ModuleConfig, global *GlobalConfig) bool {
Colin Cross43f08db2018-11-12 10:13:39 -0800559 // Generating DM files only makes sense for verify, avoid doing for non verify compiler filter APKs.
560 // No reason to use a dm file if the dex is already uncompressed.
561 return global.GenerateDMFiles && !module.UncompressedDex &&
562 contains(module.PreoptFlags, "--compiler-filter=verify")
563}
564
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000565func OdexOnSystemOtherByName(name string, dexLocation string, global *GlobalConfig) bool {
Colin Cross43f08db2018-11-12 10:13:39 -0800566 if !global.HasSystemOther {
567 return false
568 }
569
570 if global.SanitizeLite {
571 return false
572 }
573
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000574 if contains(global.SpeedApps, name) || contains(global.SystemServerApps, name) {
Colin Cross43f08db2018-11-12 10:13:39 -0800575 return false
576 }
577
578 for _, f := range global.PatternsOnSystemOther {
Anton Hanssonda4d9d92020-09-15 09:28:55 +0000579 if makefileMatch(filepath.Join(SystemPartition, f), dexLocation) {
Colin Cross43f08db2018-11-12 10:13:39 -0800580 return true
581 }
582 }
583
584 return false
585}
586
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000587func odexOnSystemOther(module *ModuleConfig, global *GlobalConfig) bool {
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000588 return OdexOnSystemOtherByName(module.Name, module.DexLocation, global)
589}
590
Colin Crossc7e40aa2019-02-08 21:37:00 -0800591// PathToLocation converts .../system/framework/arm64/boot.art to .../system/framework/boot.art
Colin Cross69f59a32019-02-15 10:39:37 -0800592func PathToLocation(path android.Path, arch android.ArchType) string {
593 pathArch := filepath.Base(filepath.Dir(path.String()))
Colin Cross74ba9622019-02-11 15:11:14 -0800594 if pathArch != arch.String() {
595 panic(fmt.Errorf("last directory in %q must be %q", path, arch.String()))
Colin Crossc7e40aa2019-02-08 21:37:00 -0800596 }
Colin Cross69f59a32019-02-15 10:39:37 -0800597 return filepath.Join(filepath.Dir(filepath.Dir(path.String())), filepath.Base(path.String()))
Colin Crossc7e40aa2019-02-08 21:37:00 -0800598}
599
Colin Cross43f08db2018-11-12 10:13:39 -0800600func makefileMatch(pattern, s string) bool {
601 percent := strings.IndexByte(pattern, '%')
602 switch percent {
603 case -1:
604 return pattern == s
605 case len(pattern) - 1:
606 return strings.HasPrefix(s, pattern[:len(pattern)-1])
607 default:
608 panic(fmt.Errorf("unsupported makefile pattern %q", pattern))
609 }
610}
611
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +0000612var nonUpdatableSystemServerJarsKey = android.NewOnceKey("nonUpdatableSystemServerJars")
613
614// TODO: eliminate the superficial global config parameter by moving global config definition
615// from java subpackage to dexpreopt.
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000616func NonUpdatableSystemServerJars(ctx android.PathContext, global *GlobalConfig) []string {
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +0000617 return ctx.Config().Once(nonUpdatableSystemServerJarsKey, func() interface{} {
Ulya Trafimovich249386a2020-07-01 14:31:13 +0100618 return android.RemoveListFromList(global.SystemServerJars, global.UpdatableSystemServerJars.CopyOfJars())
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +0000619 }).([]string)
620}
621
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000622// A predefined location for the system server dex jars. This is needed in order to generate
623// class loader context for dex2oat, as the path to the jar in the Soong module may be unknown
624// at that time (Soong processes the jars in dependency order, which may be different from the
625// the system server classpath order).
626func SystemServerDexJarHostPath(ctx android.PathContext, jar string) android.OutputPath {
Ulya Trafimovich6cf2c0c2020-04-24 12:15:20 +0100627 if DexpreoptRunningInSoong {
628 // Soong module, just use the default output directory $OUT/soong.
629 return android.PathForOutput(ctx, "system_server_dexjars", jar+".jar")
630 } else {
631 // Make module, default output directory is $OUT (passed via the "null config" created
632 // by dexpreopt_gen). Append Soong subdirectory to match Soong module paths.
633 return android.PathForOutput(ctx, "soong", "system_server_dexjars", jar+".jar")
634 }
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000635}
636
Ulya Trafimovichcd3203f2020-03-27 11:30:00 +0000637// Check the order of jars on the system server classpath and give a warning/error if a jar precedes
638// one of its dependencies. This is not an error, but a missed optimization, as dexpreopt won't
639// have the dependency jar in the class loader context, and it won't be able to resolve any
640// references to its classes and methods.
641func checkSystemServerOrder(ctx android.PathContext, jarIndex int) {
642 mctx, isModule := ctx.(android.ModuleContext)
643 if isModule {
644 config := GetGlobalConfig(ctx)
645 jars := NonUpdatableSystemServerJars(ctx, config)
646 mctx.WalkDeps(func(dep android.Module, parent android.Module) bool {
647 depIndex := android.IndexList(dep.Name(), jars)
648 if jarIndex < depIndex && !config.BrokenSuboptimalOrderOfSystemServerJars {
649 jar := jars[jarIndex]
650 dep := jars[depIndex]
651 mctx.ModuleErrorf("non-optimal order of jars on the system server classpath:"+
652 " '%s' precedes its dependency '%s', so dexpreopt is unable to resolve any"+
653 " references from '%s' to '%s'.\n", jar, dep, jar, dep)
654 }
655 return true
656 })
657 }
658}
659
Colin Cross43f08db2018-11-12 10:13:39 -0800660func contains(l []string, s string) bool {
661 for _, e := range l {
662 if e == s {
663 return true
664 }
665 }
666 return false
667}
668
Colin Cross454c0872019-02-15 23:03:34 -0800669var copyOf = android.CopyOf