blob: 8deb0a3a60b50d7ebb633b0de880435a38c22c4b [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) {
Colin Crosscbed6572019-01-08 17:38:37 -080084 // Don't preopt individual boot jars, they will be preopted together.
Ulya Trafimovich249386a2020-07-01 14:31:13 +010085 if !global.BootJars.ContainsJar(module.Name) {
Colin Crosscbed6572019-01-08 17:38:37 -080086 appImage := (generateProfile || module.ForceCreateAppImage || global.DefaultAppImages) &&
87 !module.NoCreateAppImage
88
89 generateDM := shouldGenerateDM(module, global)
90
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +000091 for archIdx, _ := range module.Archs {
Martin Stjernholm75a48d82020-01-10 20:32:59 +000092 dexpreoptCommand(ctx, globalSoong, global, module, rule, archIdx, profile, appImage, generateDM)
Colin Crosscbed6572019-01-08 17:38:37 -080093 }
94 }
95 }
96
97 return rule, nil
98}
99
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000100func dexpreoptDisabled(ctx android.PathContext, global *GlobalConfig, module *ModuleConfig) bool {
Colin Crosscbed6572019-01-08 17:38:37 -0800101 if contains(global.DisablePreoptModules, module.Name) {
102 return true
Colin Cross43f08db2018-11-12 10:13:39 -0800103 }
104
Ulyana Trafimovichf2cb7e92019-11-27 12:26:49 +0000105 // Don't preopt system server jars that are updatable.
Ulya Trafimovich249386a2020-07-01 14:31:13 +0100106 if global.UpdatableSystemServerJars.ContainsJar(module.Name) {
107 return true
Ulyana Trafimovichf2cb7e92019-11-27 12:26:49 +0000108 }
109
Colin Cross43f08db2018-11-12 10:13:39 -0800110 // If OnlyPreoptBootImageAndSystemServer=true and module is not in boot class path skip
111 // Also preopt system server jars since selinux prevents system server from loading anything from
112 // /data. If we don't do this they will need to be extracted which is not favorable for RAM usage
113 // or performance. If PreoptExtractedApk is true, we ignore the only preopt boot image options.
Ulya Trafimovich249386a2020-07-01 14:31:13 +0100114 if global.OnlyPreoptBootImageAndSystemServer && !global.BootJars.ContainsJar(module.Name) &&
Colin Cross43f08db2018-11-12 10:13:39 -0800115 !contains(global.SystemServerJars, module.Name) && !module.PreoptExtractedApk {
Colin Crosscbed6572019-01-08 17:38:37 -0800116 return true
Colin Cross43f08db2018-11-12 10:13:39 -0800117 }
118
Colin Crosscbed6572019-01-08 17:38:37 -0800119 return false
Colin Cross43f08db2018-11-12 10:13:39 -0800120}
121
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000122func profileCommand(ctx android.PathContext, globalSoong *GlobalSoongConfig, global *GlobalConfig,
123 module *ModuleConfig, rule *android.RuleBuilder) android.WritablePath {
Colin Cross69f59a32019-02-15 10:39:37 -0800124
125 profilePath := module.BuildPath.InSameDir(ctx, "profile.prof")
Colin Cross43f08db2018-11-12 10:13:39 -0800126 profileInstalledPath := module.DexLocation + ".prof"
127
128 if !module.ProfileIsTextListing {
129 rule.Command().FlagWithOutput("touch ", profilePath)
130 }
131
132 cmd := rule.Command().
133 Text(`ANDROID_LOG_TAGS="*:e"`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000134 Tool(globalSoong.Profman)
Colin Cross43f08db2018-11-12 10:13:39 -0800135
136 if module.ProfileIsTextListing {
137 // The profile is a test listing of classes (used for framework jars).
138 // We need to generate the actual binary profile before being able to compile.
Colin Cross69f59a32019-02-15 10:39:37 -0800139 cmd.FlagWithInput("--create-profile-from=", module.ProfileClassListing.Path())
Colin Cross43f08db2018-11-12 10:13:39 -0800140 } else {
141 // The profile is binary profile (used for apps). Run it through profman to
142 // ensure the profile keys match the apk.
143 cmd.
144 Flag("--copy-and-update-profile-key").
Colin Cross69f59a32019-02-15 10:39:37 -0800145 FlagWithInput("--profile-file=", module.ProfileClassListing.Path())
Colin Cross43f08db2018-11-12 10:13:39 -0800146 }
147
148 cmd.
149 FlagWithInput("--apk=", module.DexPath).
150 Flag("--dex-location="+module.DexLocation).
151 FlagWithOutput("--reference-profile-file=", profilePath)
152
153 if !module.ProfileIsTextListing {
154 cmd.Text(fmt.Sprintf(`|| echo "Profile out of date for %s"`, module.DexPath))
155 }
156 rule.Install(profilePath, profileInstalledPath)
157
158 return profilePath
159}
160
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000161func bootProfileCommand(ctx android.PathContext, globalSoong *GlobalSoongConfig, global *GlobalConfig,
162 module *ModuleConfig, rule *android.RuleBuilder) android.WritablePath {
Nicolas Geoffraye7102422019-07-24 13:19:29 +0100163
164 profilePath := module.BuildPath.InSameDir(ctx, "profile.bprof")
165 profileInstalledPath := module.DexLocation + ".bprof"
166
167 if !module.ProfileIsTextListing {
168 rule.Command().FlagWithOutput("touch ", profilePath)
169 }
170
171 cmd := rule.Command().
172 Text(`ANDROID_LOG_TAGS="*:e"`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000173 Tool(globalSoong.Profman)
Nicolas Geoffraye7102422019-07-24 13:19:29 +0100174
175 // The profile is a test listing of methods.
176 // We need to generate the actual binary profile.
177 cmd.FlagWithInput("--create-profile-from=", module.ProfileBootListing.Path())
178
179 cmd.
180 Flag("--generate-boot-profile").
181 FlagWithInput("--apk=", module.DexPath).
182 Flag("--dex-location="+module.DexLocation).
183 FlagWithOutput("--reference-profile-file=", profilePath)
184
185 if !module.ProfileIsTextListing {
186 cmd.Text(fmt.Sprintf(`|| echo "Profile out of date for %s"`, module.DexPath))
187 }
188 rule.Install(profilePath, profileInstalledPath)
189
190 return profilePath
191}
192
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100193type classLoaderContext struct {
194 // The class loader context using paths in the build.
195 Host android.Paths
196
197 // The class loader context using paths as they will be on the device.
198 Target []string
199}
200
201// A map of class loader contexts for each SDK version.
202// A map entry for "any" version contains libraries that are unconditionally added to class loader
203// context. Map entries for existing versions contains libraries that were in the default classpath
204// until that API version, and should be added to class loader context if and only if the
205// targetSdkVersion in the manifest or APK is less than that API version.
206type classLoaderContextMap map[int]*classLoaderContext
207
Ulya Trafimovich5f364b62020-06-30 12:39:01 +0100208const anySdkVersion int = 9999 // should go last in class loader context
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100209
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100210func (m classLoaderContextMap) getValue(sdkVer int) *classLoaderContext {
211 if _, ok := m[sdkVer]; !ok {
212 m[sdkVer] = &classLoaderContext{}
213 }
214 return m[sdkVer]
215}
216
217func (m classLoaderContextMap) addLibs(sdkVer int, module *ModuleConfig, libs ...string) {
218 clc := m.getValue(sdkVer)
219 for _, lib := range libs {
Ulya Trafimovichd4bcea42020-06-03 14:57:22 +0100220 p := pathForLibrary(module, lib)
221 clc.Host = append(clc.Host, p.Host)
222 clc.Target = append(clc.Target, p.Device)
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100223 }
224}
225
226func (m classLoaderContextMap) addSystemServerLibs(sdkVer int, ctx android.PathContext, module *ModuleConfig, libs ...string) {
227 clc := m.getValue(sdkVer)
228 for _, lib := range libs {
229 clc.Host = append(clc.Host, SystemServerDexJarHostPath(ctx, lib))
230 clc.Target = append(clc.Target, filepath.Join("/system/framework", lib+".jar"))
231 }
232}
233
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000234func dexpreoptCommand(ctx android.PathContext, globalSoong *GlobalSoongConfig, global *GlobalConfig,
235 module *ModuleConfig, rule *android.RuleBuilder, archIdx int, profile android.WritablePath,
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000236 appImage bool, generateDM bool) {
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000237
238 arch := module.Archs[archIdx]
Colin Cross43f08db2018-11-12 10:13:39 -0800239
240 // HACK: make soname in Soong-generated .odex files match Make.
241 base := filepath.Base(module.DexLocation)
242 if filepath.Ext(base) == ".jar" {
243 base = "javalib.jar"
244 } else if filepath.Ext(base) == ".apk" {
245 base = "package.apk"
246 }
247
248 toOdexPath := func(path string) string {
249 return filepath.Join(
250 filepath.Dir(path),
251 "oat",
Colin Cross74ba9622019-02-11 15:11:14 -0800252 arch.String(),
Colin Cross43f08db2018-11-12 10:13:39 -0800253 pathtools.ReplaceExtension(filepath.Base(path), "odex"))
254 }
255
Colin Cross69f59a32019-02-15 10:39:37 -0800256 odexPath := module.BuildPath.InSameDir(ctx, "oat", arch.String(), pathtools.ReplaceExtension(base, "odex"))
Colin Cross43f08db2018-11-12 10:13:39 -0800257 odexInstallPath := toOdexPath(module.DexLocation)
258 if odexOnSystemOther(module, global) {
Anton Hansson43ab0bc2019-10-03 14:18:45 +0100259 odexInstallPath = filepath.Join(SystemOtherPartition, odexInstallPath)
Colin Cross43f08db2018-11-12 10:13:39 -0800260 }
261
Colin Cross69f59a32019-02-15 10:39:37 -0800262 vdexPath := odexPath.ReplaceExtension(ctx, "vdex")
Colin Cross43f08db2018-11-12 10:13:39 -0800263 vdexInstallPath := pathtools.ReplaceExtension(odexInstallPath, "vdex")
264
Colin Cross69f59a32019-02-15 10:39:37 -0800265 invocationPath := odexPath.ReplaceExtension(ctx, "invocation")
Alex Light5de41962018-12-18 15:16:26 -0800266
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100267 classLoaderContexts := make(classLoaderContextMap)
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000268 systemServerJars := NonUpdatableSystemServerJars(ctx, global)
269
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100270 rule.Command().FlagWithArg("mkdir -p ", filepath.Dir(odexPath.String()))
271 rule.Command().FlagWithOutput("rm -f ", odexPath)
Ulya Trafimovichc9af5382020-05-29 15:35:06 +0100272
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100273 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]...)
Colin Cross69f59a32019-02-15 10:39:37 -0800277
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100278 // Copy the system server jar to a predefined location where dex2oat will find it.
279 dexPathHost := SystemServerDexJarHostPath(ctx, module.Name)
280 rule.Command().Text("mkdir -p").Flag(filepath.Dir(dexPathHost.String()))
281 rule.Command().Text("cp -f").Input(module.DexPath).Output(dexPathHost)
282
283 checkSystemServerOrder(ctx, jarIndex)
284
285 clc := classLoaderContexts[anySdkVersion]
286 rule.Command().
287 Text("class_loader_context_arg=--class-loader-context=PCL[" + strings.Join(clc.Host.Strings(), ":") + "]").
288 Implicits(clc.Host).
289 Text("stored_class_loader_context_arg=--stored-class-loader-context=PCL[" + strings.Join(clc.Target, ":") + "]")
290 } else if module.EnforceUsesLibraries {
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100291 // Unconditional class loader context.
Ulya Trafimovich6e827482020-06-12 14:32:24 +0100292 usesLibs := append(copyOf(module.UsesLibraries), module.OptionalUsesLibraries...)
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100293 classLoaderContexts.addLibs(anySdkVersion, module, usesLibs...)
Colin Cross43f08db2018-11-12 10:13:39 -0800294
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100295 // Conditional class loader context for API version < 28.
Colin Cross43f08db2018-11-12 10:13:39 -0800296 const httpLegacy = "org.apache.http.legacy"
Ulya Trafimovichdf00dde2020-05-29 14:55:02 +0100297 if !contains(usesLibs, httpLegacy) {
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100298 classLoaderContexts.addLibs(28, module, httpLegacy)
Colin Cross43f08db2018-11-12 10:13:39 -0800299 }
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000300
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100301 // Conditional class loader context for API version < 29.
302 usesLibs29 := []string{
303 "android.hidl.base-V1.0-java",
304 "android.hidl.manager-V1.0-java",
305 }
306 classLoaderContexts.addLibs(29, module, usesLibs29...)
Ulya Trafimovichc9af5382020-05-29 15:35:06 +0100307
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100308 // Conditional class loader context for API version < 30.
Ulya Trafimovichc9af5382020-05-29 15:35:06 +0100309 const testBase = "android.test.base"
310 if !contains(usesLibs, testBase) {
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100311 classLoaderContexts.addLibs(30, module, testBase)
Ulya Trafimovichc9af5382020-05-29 15:35:06 +0100312 }
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +0000313
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100314 // Generate command that saves target SDK version in a shell variable.
Colin Cross38b96852019-05-22 10:21:09 -0700315 if module.ManifestPath != nil {
316 rule.Command().Text(`target_sdk_version="$(`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000317 Tool(globalSoong.ManifestCheck).
Colin Cross38b96852019-05-22 10:21:09 -0700318 Flag("--extract-target-sdk-version").
319 Input(module.ManifestPath).
320 Text(`)"`)
321 } else {
322 // No manifest to extract targetSdkVersion from, hope that DexJar is an APK
323 rule.Command().Text(`target_sdk_version="$(`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000324 Tool(globalSoong.Aapt).
Colin Cross38b96852019-05-22 10:21:09 -0700325 Flag("dump badging").
326 Input(module.DexPath).
327 Text(`| grep "targetSdkVersion" | sed -n "s/targetSdkVersion:'\(.*\)'/\1/p"`).
328 Text(`)"`)
329 }
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100330
Ulya Trafimovich5f364b62020-06-30 12:39:01 +0100331 // Generate command that saves host and target class loader context in shell variables.
332 cmd := rule.Command().
333 Text(`eval "$(`).Tool(globalSoong.ConstructContext).
334 Text(` --target-sdk-version ${target_sdk_version}`)
Ulya Trafimovichb8063c62020-08-20 11:33:12 +0100335 for _, ver := range android.SortedIntKeys(classLoaderContexts) {
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100336 clc := classLoaderContexts.getValue(ver)
Ulya Trafimovich5f364b62020-06-30 12:39:01 +0100337 verString := fmt.Sprintf("%d", ver)
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100338 if ver == anySdkVersion {
Ulya Trafimovich5f364b62020-06-30 12:39:01 +0100339 verString = "any" // a special keyword that means any SDK version
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100340 }
Ulya Trafimovich5f364b62020-06-30 12:39:01 +0100341 cmd.Textf(`--host-classpath-for-sdk %s %s`, verString, strings.Join(clc.Host.Strings(), ":")).
342 Implicits(clc.Host).
343 Textf(`--target-classpath-for-sdk %s %s`, verString, strings.Join(clc.Target, ":"))
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100344 }
Ulya Trafimovich5f364b62020-06-30 12:39:01 +0100345 cmd.Text(`)"`)
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100346 } else {
347 // Pass special class loader context to skip the classpath and collision check.
348 // This will get removed once LOCAL_USES_LIBRARIES is enforced.
349 // Right now LOCAL_USES_LIBRARIES is opt in, for the case where it's not specified we still default
350 // to the &.
351 rule.Command().
352 Text(`class_loader_context_arg=--class-loader-context=\&`).
353 Text(`stored_class_loader_context_arg=""`)
Colin Cross43f08db2018-11-12 10:13:39 -0800354 }
355
Nicolas Geoffray2464ef42019-03-05 14:07:07 +0000356 // Devices that do not have a product partition use a symlink from /product to /system/product.
357 // Because on-device dexopt will see dex locations starting with /product, we change the paths
358 // to mimic this behavior.
359 dexLocationArg := module.DexLocation
360 if strings.HasPrefix(dexLocationArg, "/system/product/") {
361 dexLocationArg = strings.TrimPrefix(dexLocationArg, "/system")
362 }
363
Colin Cross43f08db2018-11-12 10:13:39 -0800364 cmd := rule.Command().
365 Text(`ANDROID_LOG_TAGS="*:e"`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000366 Tool(globalSoong.Dex2oat).
Colin Cross43f08db2018-11-12 10:13:39 -0800367 Flag("--avoid-storing-invocation").
Alex Light5de41962018-12-18 15:16:26 -0800368 FlagWithOutput("--write-invocation-to=", invocationPath).ImplicitOutput(invocationPath).
Colin Cross43f08db2018-11-12 10:13:39 -0800369 Flag("--runtime-arg").FlagWithArg("-Xms", global.Dex2oatXms).
370 Flag("--runtime-arg").FlagWithArg("-Xmx", global.Dex2oatXmx).
Colin Cross800fe132019-02-11 14:21:24 -0800371 Flag("--runtime-arg").FlagWithInputList("-Xbootclasspath:", module.PreoptBootClassPathDexFiles, ":").
372 Flag("--runtime-arg").FlagWithList("-Xbootclasspath-locations:", module.PreoptBootClassPathDexLocations, ":").
Colin Cross43f08db2018-11-12 10:13:39 -0800373 Flag("${class_loader_context_arg}").
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000374 Flag("${stored_class_loader_context_arg}").
Ulya Trafimovich3391a1e2020-01-03 17:33:17 +0000375 FlagWithArg("--boot-image=", strings.Join(module.DexPreoptImageLocations, ":")).Implicits(module.DexPreoptImagesDeps[archIdx].Paths()).
Colin Cross43f08db2018-11-12 10:13:39 -0800376 FlagWithInput("--dex-file=", module.DexPath).
Nicolas Geoffray2464ef42019-03-05 14:07:07 +0000377 FlagWithArg("--dex-location=", dexLocationArg).
Colin Cross43f08db2018-11-12 10:13:39 -0800378 FlagWithOutput("--oat-file=", odexPath).ImplicitOutput(vdexPath).
379 // Pass an empty directory, dex2oat shouldn't be reading arbitrary files
380 FlagWithArg("--android-root=", global.EmptyDirectory).
Colin Cross74ba9622019-02-11 15:11:14 -0800381 FlagWithArg("--instruction-set=", arch.String()).
Colin Cross43f08db2018-11-12 10:13:39 -0800382 FlagWithArg("--instruction-set-variant=", global.CpuVariant[arch]).
383 FlagWithArg("--instruction-set-features=", global.InstructionSetFeatures[arch]).
384 Flag("--no-generate-debug-info").
385 Flag("--generate-build-id").
386 Flag("--abort-on-hard-verifier-error").
387 Flag("--force-determinism").
388 FlagWithArg("--no-inline-from=", "core-oj.jar")
389
390 var preoptFlags []string
391 if len(module.PreoptFlags) > 0 {
392 preoptFlags = module.PreoptFlags
393 } else if len(global.PreoptFlags) > 0 {
394 preoptFlags = global.PreoptFlags
395 }
396
397 if len(preoptFlags) > 0 {
398 cmd.Text(strings.Join(preoptFlags, " "))
399 }
400
401 if module.UncompressedDex {
402 cmd.FlagWithArg("--copy-dex-files=", "false")
403 }
404
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800405 if !android.PrefixInList(preoptFlags, "--compiler-filter=") {
Colin Cross43f08db2018-11-12 10:13:39 -0800406 var compilerFilter string
407 if contains(global.SystemServerJars, module.Name) {
408 // Jars of system server, use the product option if it is set, speed otherwise.
409 if global.SystemServerCompilerFilter != "" {
410 compilerFilter = global.SystemServerCompilerFilter
411 } else {
412 compilerFilter = "speed"
413 }
414 } else if contains(global.SpeedApps, module.Name) || contains(global.SystemServerApps, module.Name) {
415 // Apps loaded into system server, and apps the product default to being compiled with the
416 // 'speed' compiler filter.
417 compilerFilter = "speed"
Colin Cross69f59a32019-02-15 10:39:37 -0800418 } else if profile != nil {
Colin Cross43f08db2018-11-12 10:13:39 -0800419 // For non system server jars, use speed-profile when we have a profile.
420 compilerFilter = "speed-profile"
421 } else if global.DefaultCompilerFilter != "" {
422 compilerFilter = global.DefaultCompilerFilter
423 } else {
424 compilerFilter = "quicken"
425 }
426 cmd.FlagWithArg("--compiler-filter=", compilerFilter)
427 }
428
429 if generateDM {
430 cmd.FlagWithArg("--copy-dex-files=", "false")
Colin Cross69f59a32019-02-15 10:39:37 -0800431 dmPath := module.BuildPath.InSameDir(ctx, "generated.dm")
Colin Cross43f08db2018-11-12 10:13:39 -0800432 dmInstalledPath := pathtools.ReplaceExtension(module.DexLocation, "dm")
Colin Cross69f59a32019-02-15 10:39:37 -0800433 tmpPath := module.BuildPath.InSameDir(ctx, "primary.vdex")
Colin Cross43f08db2018-11-12 10:13:39 -0800434 rule.Command().Text("cp -f").Input(vdexPath).Output(tmpPath)
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000435 rule.Command().Tool(globalSoong.SoongZip).
Colin Cross43f08db2018-11-12 10:13:39 -0800436 FlagWithArg("-L", "9").
437 FlagWithOutput("-o", dmPath).
438 Flag("-j").
439 Input(tmpPath)
440 rule.Install(dmPath, dmInstalledPath)
441 }
442
443 // By default, emit debug info.
444 debugInfo := true
445 if global.NoDebugInfo {
446 // If the global setting suppresses mini-debug-info, disable it.
447 debugInfo = false
448 }
449
450 // PRODUCT_SYSTEM_SERVER_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO.
451 // PRODUCT_OTHER_JAVA_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO.
452 if contains(global.SystemServerJars, module.Name) {
453 if global.AlwaysSystemServerDebugInfo {
454 debugInfo = true
455 } else if global.NeverSystemServerDebugInfo {
456 debugInfo = false
457 }
458 } else {
459 if global.AlwaysOtherDebugInfo {
460 debugInfo = true
461 } else if global.NeverOtherDebugInfo {
462 debugInfo = false
463 }
464 }
465
466 // Never enable on eng.
467 if global.IsEng {
468 debugInfo = false
469 }
470
471 if debugInfo {
472 cmd.Flag("--generate-mini-debug-info")
473 } else {
474 cmd.Flag("--no-generate-mini-debug-info")
475 }
476
477 // Set the compiler reason to 'prebuilt' to identify the oat files produced
478 // during the build, as opposed to compiled on the device.
479 cmd.FlagWithArg("--compilation-reason=", "prebuilt")
480
481 if appImage {
Colin Cross69f59a32019-02-15 10:39:37 -0800482 appImagePath := odexPath.ReplaceExtension(ctx, "art")
Colin Cross43f08db2018-11-12 10:13:39 -0800483 appImageInstallPath := pathtools.ReplaceExtension(odexInstallPath, "art")
484 cmd.FlagWithOutput("--app-image-file=", appImagePath).
485 FlagWithArg("--image-format=", "lz4")
Mathieu Chartier3f7ddbb2019-04-29 09:33:50 -0700486 if !global.DontResolveStartupStrings {
487 cmd.FlagWithArg("--resolve-startup-const-strings=", "true")
488 }
Colin Cross43f08db2018-11-12 10:13:39 -0800489 rule.Install(appImagePath, appImageInstallPath)
490 }
491
Colin Cross69f59a32019-02-15 10:39:37 -0800492 if profile != nil {
493 cmd.FlagWithInput("--profile-file=", profile)
Colin Cross43f08db2018-11-12 10:13:39 -0800494 }
495
496 rule.Install(odexPath, odexInstallPath)
497 rule.Install(vdexPath, vdexInstallPath)
498}
499
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000500func shouldGenerateDM(module *ModuleConfig, global *GlobalConfig) bool {
Colin Cross43f08db2018-11-12 10:13:39 -0800501 // Generating DM files only makes sense for verify, avoid doing for non verify compiler filter APKs.
502 // No reason to use a dm file if the dex is already uncompressed.
503 return global.GenerateDMFiles && !module.UncompressedDex &&
504 contains(module.PreoptFlags, "--compiler-filter=verify")
505}
506
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000507func OdexOnSystemOtherByName(name string, dexLocation string, global *GlobalConfig) bool {
Colin Cross43f08db2018-11-12 10:13:39 -0800508 if !global.HasSystemOther {
509 return false
510 }
511
512 if global.SanitizeLite {
513 return false
514 }
515
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000516 if contains(global.SpeedApps, name) || contains(global.SystemServerApps, name) {
Colin Cross43f08db2018-11-12 10:13:39 -0800517 return false
518 }
519
520 for _, f := range global.PatternsOnSystemOther {
Anton Hanssond57bd3c2019-10-14 16:53:02 +0100521 if makefileMatch(filepath.Join(SystemPartition, f), dexLocation) {
Colin Cross43f08db2018-11-12 10:13:39 -0800522 return true
523 }
524 }
525
526 return false
527}
528
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000529func odexOnSystemOther(module *ModuleConfig, global *GlobalConfig) bool {
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000530 return OdexOnSystemOtherByName(module.Name, module.DexLocation, global)
531}
532
Colin Crossc7e40aa2019-02-08 21:37:00 -0800533// PathToLocation converts .../system/framework/arm64/boot.art to .../system/framework/boot.art
Colin Cross69f59a32019-02-15 10:39:37 -0800534func PathToLocation(path android.Path, arch android.ArchType) string {
535 pathArch := filepath.Base(filepath.Dir(path.String()))
Colin Cross74ba9622019-02-11 15:11:14 -0800536 if pathArch != arch.String() {
537 panic(fmt.Errorf("last directory in %q must be %q", path, arch.String()))
Colin Crossc7e40aa2019-02-08 21:37:00 -0800538 }
Colin Cross69f59a32019-02-15 10:39:37 -0800539 return filepath.Join(filepath.Dir(filepath.Dir(path.String())), filepath.Base(path.String()))
Colin Crossc7e40aa2019-02-08 21:37:00 -0800540}
541
Ulya Trafimovichd4bcea42020-06-03 14:57:22 +0100542func pathForLibrary(module *ModuleConfig, lib string) *LibraryPath {
Colin Cross69f59a32019-02-15 10:39:37 -0800543 path, ok := module.LibraryPaths[lib]
544 if !ok {
Colin Cross43f08db2018-11-12 10:13:39 -0800545 panic(fmt.Errorf("unknown library path for %q", lib))
546 }
547 return path
548}
549
550func makefileMatch(pattern, s string) bool {
551 percent := strings.IndexByte(pattern, '%')
552 switch percent {
553 case -1:
554 return pattern == s
555 case len(pattern) - 1:
556 return strings.HasPrefix(s, pattern[:len(pattern)-1])
557 default:
558 panic(fmt.Errorf("unsupported makefile pattern %q", pattern))
559 }
560}
561
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +0000562var nonUpdatableSystemServerJarsKey = android.NewOnceKey("nonUpdatableSystemServerJars")
563
564// TODO: eliminate the superficial global config parameter by moving global config definition
565// from java subpackage to dexpreopt.
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000566func NonUpdatableSystemServerJars(ctx android.PathContext, global *GlobalConfig) []string {
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +0000567 return ctx.Config().Once(nonUpdatableSystemServerJarsKey, func() interface{} {
Ulya Trafimovich249386a2020-07-01 14:31:13 +0100568 return android.RemoveListFromList(global.SystemServerJars, global.UpdatableSystemServerJars.CopyOfJars())
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +0000569 }).([]string)
570}
571
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000572// A predefined location for the system server dex jars. This is needed in order to generate
573// class loader context for dex2oat, as the path to the jar in the Soong module may be unknown
574// at that time (Soong processes the jars in dependency order, which may be different from the
575// the system server classpath order).
576func SystemServerDexJarHostPath(ctx android.PathContext, jar string) android.OutputPath {
Ulya Trafimovich6cf2c0c2020-04-24 12:15:20 +0100577 if DexpreoptRunningInSoong {
578 // Soong module, just use the default output directory $OUT/soong.
579 return android.PathForOutput(ctx, "system_server_dexjars", jar+".jar")
580 } else {
581 // Make module, default output directory is $OUT (passed via the "null config" created
582 // by dexpreopt_gen). Append Soong subdirectory to match Soong module paths.
583 return android.PathForOutput(ctx, "soong", "system_server_dexjars", jar+".jar")
584 }
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000585}
586
Ulya Trafimovichcd3203f2020-03-27 11:30:00 +0000587// Check the order of jars on the system server classpath and give a warning/error if a jar precedes
588// one of its dependencies. This is not an error, but a missed optimization, as dexpreopt won't
589// have the dependency jar in the class loader context, and it won't be able to resolve any
590// references to its classes and methods.
591func checkSystemServerOrder(ctx android.PathContext, jarIndex int) {
592 mctx, isModule := ctx.(android.ModuleContext)
593 if isModule {
594 config := GetGlobalConfig(ctx)
595 jars := NonUpdatableSystemServerJars(ctx, config)
596 mctx.WalkDeps(func(dep android.Module, parent android.Module) bool {
597 depIndex := android.IndexList(dep.Name(), jars)
598 if jarIndex < depIndex && !config.BrokenSuboptimalOrderOfSystemServerJars {
599 jar := jars[jarIndex]
600 dep := jars[depIndex]
601 mctx.ModuleErrorf("non-optimal order of jars on the system server classpath:"+
602 " '%s' precedes its dependency '%s', so dexpreopt is unable to resolve any"+
603 " references from '%s' to '%s'.\n", jar, dep, jar, dep)
604 }
605 return true
606 })
607 }
608}
609
Colin Cross43f08db2018-11-12 10:13:39 -0800610func contains(l []string, s string) bool {
611 for _, e := range l {
612 if e == s {
613 return true
614 }
615 }
616 return false
617}
618
Colin Cross454c0872019-02-15 23:03:34 -0800619var copyOf = android.CopyOf