blob: 9cbe6e5915a813a181c622f987139ef441e04ce6 [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"
Ulya Trafimovich696c59d2020-06-01 16:10:56 +010040 "sort"
Colin Cross43f08db2018-11-12 10:13:39 -080041 "strings"
42
Colin Crossfeec25b2019-01-30 17:32:39 -080043 "android/soong/android"
44
Colin Cross43f08db2018-11-12 10:13:39 -080045 "github.com/google/blueprint/pathtools"
46)
47
48const SystemPartition = "/system/"
49const SystemOtherPartition = "/system_other/"
50
Ulya Trafimovich6cf2c0c2020-04-24 12:15:20 +010051var DexpreoptRunningInSoong = false
52
Colin Cross43f08db2018-11-12 10:13:39 -080053// GenerateDexpreoptRule generates a set of commands that will preopt a module based on a GlobalConfig and a
54// ModuleConfig. The produced files and their install locations will be available through rule.Installs().
Martin Stjernholm8d80cee2020-01-31 17:44:54 +000055func GenerateDexpreoptRule(ctx android.PathContext, globalSoong *GlobalSoongConfig,
56 global *GlobalConfig, module *ModuleConfig) (rule *android.RuleBuilder, err error) {
Colin Cross69f59a32019-02-15 10:39:37 -080057
Colin Cross43f08db2018-11-12 10:13:39 -080058 defer func() {
59 if r := recover(); r != nil {
Colin Cross69f59a32019-02-15 10:39:37 -080060 if _, ok := r.(runtime.Error); ok {
61 panic(r)
62 } else if e, ok := r.(error); ok {
Colin Cross43f08db2018-11-12 10:13:39 -080063 err = e
64 rule = nil
65 } else {
66 panic(r)
67 }
68 }
69 }()
70
Colin Cross758290d2019-02-01 16:42:32 -080071 rule = android.NewRuleBuilder()
Colin Cross43f08db2018-11-12 10:13:39 -080072
Colin Cross69f59a32019-02-15 10:39:37 -080073 generateProfile := module.ProfileClassListing.Valid() && !global.DisableGenerateProfile
Nicolas Geoffraye7102422019-07-24 13:19:29 +010074 generateBootProfile := module.ProfileBootListing.Valid() && !global.DisableGenerateProfile
Colin Cross43f08db2018-11-12 10:13:39 -080075
Colin Cross69f59a32019-02-15 10:39:37 -080076 var profile android.WritablePath
Colin Crosscbed6572019-01-08 17:38:37 -080077 if generateProfile {
Martin Stjernholm75a48d82020-01-10 20:32:59 +000078 profile = profileCommand(ctx, globalSoong, global, module, rule)
Colin Crosscbed6572019-01-08 17:38:37 -080079 }
Nicolas Geoffraye7102422019-07-24 13:19:29 +010080 if generateBootProfile {
Martin Stjernholm75a48d82020-01-10 20:32:59 +000081 bootProfileCommand(ctx, globalSoong, global, module, rule)
Nicolas Geoffraye7102422019-07-24 13:19:29 +010082 }
Colin Crosscbed6572019-01-08 17:38:37 -080083
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +000084 if !dexpreoptDisabled(ctx, global, module) {
Colin Crosscbed6572019-01-08 17:38:37 -080085 // Don't preopt individual boot jars, they will be preopted together.
Ulya Trafimovich8640ab92020-05-11 18:06:15 +010086 if !contains(android.GetJarsFromApexJarPairs(ctx, global.BootJars), module.Name) {
Colin Crosscbed6572019-01-08 17:38:37 -080087 appImage := (generateProfile || module.ForceCreateAppImage || global.DefaultAppImages) &&
88 !module.NoCreateAppImage
89
90 generateDM := shouldGenerateDM(module, global)
91
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +000092 for archIdx, _ := range module.Archs {
Martin Stjernholm75a48d82020-01-10 20:32:59 +000093 dexpreoptCommand(ctx, globalSoong, global, module, rule, archIdx, profile, appImage, generateDM)
Colin Crosscbed6572019-01-08 17:38:37 -080094 }
95 }
96 }
97
98 return rule, nil
99}
100
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000101func dexpreoptDisabled(ctx android.PathContext, global *GlobalConfig, module *ModuleConfig) bool {
Colin Crosscbed6572019-01-08 17:38:37 -0800102 if contains(global.DisablePreoptModules, module.Name) {
103 return true
Colin Cross43f08db2018-11-12 10:13:39 -0800104 }
105
Ulyana Trafimovichf2cb7e92019-11-27 12:26:49 +0000106 // Don't preopt system server jars that are updatable.
107 for _, p := range global.UpdatableSystemServerJars {
Ulya Trafimovich8640ab92020-05-11 18:06:15 +0100108 if _, jar := android.SplitApexJarPair(ctx, p); jar == module.Name {
Ulyana Trafimovichf2cb7e92019-11-27 12:26:49 +0000109 return true
110 }
111 }
112
Colin Cross43f08db2018-11-12 10:13:39 -0800113 // If OnlyPreoptBootImageAndSystemServer=true and module is not in boot class path skip
114 // Also preopt system server jars since selinux prevents system server from loading anything from
115 // /data. If we don't do this they will need to be extracted which is not favorable for RAM usage
116 // or performance. If PreoptExtractedApk is true, we ignore the only preopt boot image options.
Ulya Trafimovich8640ab92020-05-11 18:06:15 +0100117 if global.OnlyPreoptBootImageAndSystemServer && !contains(android.GetJarsFromApexJarPairs(ctx, global.BootJars), module.Name) &&
Colin Cross43f08db2018-11-12 10:13:39 -0800118 !contains(global.SystemServerJars, module.Name) && !module.PreoptExtractedApk {
Colin Crosscbed6572019-01-08 17:38:37 -0800119 return true
Colin Cross43f08db2018-11-12 10:13:39 -0800120 }
121
Colin Crosscbed6572019-01-08 17:38:37 -0800122 return false
Colin Cross43f08db2018-11-12 10:13:39 -0800123}
124
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000125func profileCommand(ctx android.PathContext, globalSoong *GlobalSoongConfig, global *GlobalConfig,
126 module *ModuleConfig, rule *android.RuleBuilder) android.WritablePath {
Colin Cross69f59a32019-02-15 10:39:37 -0800127
128 profilePath := module.BuildPath.InSameDir(ctx, "profile.prof")
Colin Cross43f08db2018-11-12 10:13:39 -0800129 profileInstalledPath := module.DexLocation + ".prof"
130
131 if !module.ProfileIsTextListing {
132 rule.Command().FlagWithOutput("touch ", profilePath)
133 }
134
135 cmd := rule.Command().
136 Text(`ANDROID_LOG_TAGS="*:e"`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000137 Tool(globalSoong.Profman)
Colin Cross43f08db2018-11-12 10:13:39 -0800138
139 if module.ProfileIsTextListing {
140 // The profile is a test listing of classes (used for framework jars).
141 // We need to generate the actual binary profile before being able to compile.
Colin Cross69f59a32019-02-15 10:39:37 -0800142 cmd.FlagWithInput("--create-profile-from=", module.ProfileClassListing.Path())
Colin Cross43f08db2018-11-12 10:13:39 -0800143 } else {
144 // The profile is binary profile (used for apps). Run it through profman to
145 // ensure the profile keys match the apk.
146 cmd.
147 Flag("--copy-and-update-profile-key").
Colin Cross69f59a32019-02-15 10:39:37 -0800148 FlagWithInput("--profile-file=", module.ProfileClassListing.Path())
Colin Cross43f08db2018-11-12 10:13:39 -0800149 }
150
151 cmd.
152 FlagWithInput("--apk=", module.DexPath).
153 Flag("--dex-location="+module.DexLocation).
154 FlagWithOutput("--reference-profile-file=", profilePath)
155
156 if !module.ProfileIsTextListing {
157 cmd.Text(fmt.Sprintf(`|| echo "Profile out of date for %s"`, module.DexPath))
158 }
159 rule.Install(profilePath, profileInstalledPath)
160
161 return profilePath
162}
163
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000164func bootProfileCommand(ctx android.PathContext, globalSoong *GlobalSoongConfig, global *GlobalConfig,
165 module *ModuleConfig, rule *android.RuleBuilder) android.WritablePath {
Nicolas Geoffraye7102422019-07-24 13:19:29 +0100166
167 profilePath := module.BuildPath.InSameDir(ctx, "profile.bprof")
168 profileInstalledPath := module.DexLocation + ".bprof"
169
170 if !module.ProfileIsTextListing {
171 rule.Command().FlagWithOutput("touch ", profilePath)
172 }
173
174 cmd := rule.Command().
175 Text(`ANDROID_LOG_TAGS="*:e"`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000176 Tool(globalSoong.Profman)
Nicolas Geoffraye7102422019-07-24 13:19:29 +0100177
178 // The profile is a test listing of methods.
179 // We need to generate the actual binary profile.
180 cmd.FlagWithInput("--create-profile-from=", module.ProfileBootListing.Path())
181
182 cmd.
183 Flag("--generate-boot-profile").
184 FlagWithInput("--apk=", module.DexPath).
185 Flag("--dex-location="+module.DexLocation).
186 FlagWithOutput("--reference-profile-file=", profilePath)
187
188 if !module.ProfileIsTextListing {
189 cmd.Text(fmt.Sprintf(`|| echo "Profile out of date for %s"`, module.DexPath))
190 }
191 rule.Install(profilePath, profileInstalledPath)
192
193 return profilePath
194}
195
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100196type classLoaderContext struct {
197 // The class loader context using paths in the build.
198 Host android.Paths
199
200 // The class loader context using paths as they will be on the device.
201 Target []string
202}
203
204// A map of class loader contexts for each SDK version.
205// A map entry for "any" version contains libraries that are unconditionally added to class loader
206// context. Map entries for existing versions contains libraries that were in the default classpath
207// until that API version, and should be added to class loader context if and only if the
208// targetSdkVersion in the manifest or APK is less than that API version.
209type classLoaderContextMap map[int]*classLoaderContext
210
211const anySdkVersion int = -1
212
213func (m classLoaderContextMap) getSortedKeys() []int {
214 keys := make([]int, 0, len(m))
215 for k := range m {
216 keys = append(keys, k)
217 }
218 sort.Ints(keys)
219 return keys
220}
221
222func (m classLoaderContextMap) getValue(sdkVer int) *classLoaderContext {
223 if _, ok := m[sdkVer]; !ok {
224 m[sdkVer] = &classLoaderContext{}
225 }
226 return m[sdkVer]
227}
228
229func (m classLoaderContextMap) addLibs(sdkVer int, module *ModuleConfig, libs ...string) {
230 clc := m.getValue(sdkVer)
231 for _, lib := range libs {
Ulya Trafimovichd4bcea42020-06-03 14:57:22 +0100232 p := pathForLibrary(module, lib)
233 clc.Host = append(clc.Host, p.Host)
234 clc.Target = append(clc.Target, p.Device)
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100235 }
236}
237
238func (m classLoaderContextMap) addSystemServerLibs(sdkVer int, ctx android.PathContext, module *ModuleConfig, libs ...string) {
239 clc := m.getValue(sdkVer)
240 for _, lib := range libs {
241 clc.Host = append(clc.Host, SystemServerDexJarHostPath(ctx, lib))
242 clc.Target = append(clc.Target, filepath.Join("/system/framework", lib+".jar"))
243 }
244}
245
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000246func dexpreoptCommand(ctx android.PathContext, globalSoong *GlobalSoongConfig, global *GlobalConfig,
247 module *ModuleConfig, rule *android.RuleBuilder, archIdx int, profile android.WritablePath,
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000248 appImage bool, generateDM bool) {
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000249
250 arch := module.Archs[archIdx]
Colin Cross43f08db2018-11-12 10:13:39 -0800251
252 // HACK: make soname in Soong-generated .odex files match Make.
253 base := filepath.Base(module.DexLocation)
254 if filepath.Ext(base) == ".jar" {
255 base = "javalib.jar"
256 } else if filepath.Ext(base) == ".apk" {
257 base = "package.apk"
258 }
259
260 toOdexPath := func(path string) string {
261 return filepath.Join(
262 filepath.Dir(path),
263 "oat",
Colin Cross74ba9622019-02-11 15:11:14 -0800264 arch.String(),
Colin Cross43f08db2018-11-12 10:13:39 -0800265 pathtools.ReplaceExtension(filepath.Base(path), "odex"))
266 }
267
Colin Cross69f59a32019-02-15 10:39:37 -0800268 odexPath := module.BuildPath.InSameDir(ctx, "oat", arch.String(), pathtools.ReplaceExtension(base, "odex"))
Colin Cross43f08db2018-11-12 10:13:39 -0800269 odexInstallPath := toOdexPath(module.DexLocation)
270 if odexOnSystemOther(module, global) {
Anton Hansson43ab0bc2019-10-03 14:18:45 +0100271 odexInstallPath = filepath.Join(SystemOtherPartition, odexInstallPath)
Colin Cross43f08db2018-11-12 10:13:39 -0800272 }
273
Colin Cross69f59a32019-02-15 10:39:37 -0800274 vdexPath := odexPath.ReplaceExtension(ctx, "vdex")
Colin Cross43f08db2018-11-12 10:13:39 -0800275 vdexInstallPath := pathtools.ReplaceExtension(odexInstallPath, "vdex")
276
Colin Cross69f59a32019-02-15 10:39:37 -0800277 invocationPath := odexPath.ReplaceExtension(ctx, "invocation")
Alex Light5de41962018-12-18 15:16:26 -0800278
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000279 systemServerJars := NonUpdatableSystemServerJars(ctx, global)
280
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100281 classLoaderContexts := make(classLoaderContextMap)
Ulya Trafimovichc9af5382020-05-29 15:35:06 +0100282
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000283 // A flag indicating if the '&' class loader context is used.
284 unknownClassLoaderContext := false
Colin Cross69f59a32019-02-15 10:39:37 -0800285
Colin Cross43f08db2018-11-12 10:13:39 -0800286 if module.EnforceUsesLibraries {
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100287 // Unconditional class loader context.
Ulya Trafimovich6e827482020-06-12 14:32:24 +0100288 usesLibs := append(copyOf(module.UsesLibraries), module.OptionalUsesLibraries...)
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100289 classLoaderContexts.addLibs(anySdkVersion, module, usesLibs...)
Colin Cross43f08db2018-11-12 10:13:39 -0800290
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100291 // Conditional class loader context for API version < 28.
Colin Cross43f08db2018-11-12 10:13:39 -0800292 const httpLegacy = "org.apache.http.legacy"
Ulya Trafimovichdf00dde2020-05-29 14:55:02 +0100293 if !contains(usesLibs, httpLegacy) {
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100294 classLoaderContexts.addLibs(28, module, httpLegacy)
Colin Cross43f08db2018-11-12 10:13:39 -0800295 }
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000296
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100297 // Conditional class loader context for API version < 29.
298 usesLibs29 := []string{
299 "android.hidl.base-V1.0-java",
300 "android.hidl.manager-V1.0-java",
301 }
302 classLoaderContexts.addLibs(29, module, usesLibs29...)
Ulya Trafimovichc9af5382020-05-29 15:35:06 +0100303
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100304 // Conditional class loader context for API version < 30.
Ulya Trafimovichc9af5382020-05-29 15:35:06 +0100305 const testBase = "android.test.base"
306 if !contains(usesLibs, testBase) {
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100307 classLoaderContexts.addLibs(30, module, testBase)
Ulya Trafimovichc9af5382020-05-29 15:35:06 +0100308 }
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000309 } else if jarIndex := android.IndexList(module.Name, systemServerJars); jarIndex >= 0 {
310 // System server jars should be dexpreopted together: class loader context of each jar
311 // should include all preceding jars on the system server classpath.
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100312 classLoaderContexts.addSystemServerLibs(anySdkVersion, ctx, module, systemServerJars[:jarIndex]...)
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +0000313
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000314 // Copy the system server jar to a predefined location where dex2oat will find it.
315 dexPathHost := SystemServerDexJarHostPath(ctx, module.Name)
316 rule.Command().Text("mkdir -p").Flag(filepath.Dir(dexPathHost.String()))
317 rule.Command().Text("cp -f").Input(module.DexPath).Output(dexPathHost)
Ulya Trafimovichcd3203f2020-03-27 11:30:00 +0000318
319 checkSystemServerOrder(ctx, jarIndex)
Colin Cross43f08db2018-11-12 10:13:39 -0800320 } else {
321 // Pass special class loader context to skip the classpath and collision check.
322 // This will get removed once LOCAL_USES_LIBRARIES is enforced.
323 // Right now LOCAL_USES_LIBRARIES is opt in, for the case where it's not specified we still default
324 // to the &.
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000325 unknownClassLoaderContext = true
Colin Cross43f08db2018-11-12 10:13:39 -0800326 }
327
Colin Cross69f59a32019-02-15 10:39:37 -0800328 rule.Command().FlagWithArg("mkdir -p ", filepath.Dir(odexPath.String()))
Colin Cross43f08db2018-11-12 10:13:39 -0800329 rule.Command().FlagWithOutput("rm -f ", odexPath)
330 // Set values in the environment of the rule. These may be modified by construct_context.sh.
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000331 if unknownClassLoaderContext {
332 rule.Command().
333 Text(`class_loader_context_arg=--class-loader-context=\&`).
334 Text(`stored_class_loader_context_arg=""`)
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +0000335 } else {
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100336 clc := classLoaderContexts[anySdkVersion]
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000337 rule.Command().
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100338 Text("class_loader_context_arg=--class-loader-context=PCL[" + strings.Join(clc.Host.Strings(), ":") + "]").
339 Implicits(clc.Host).
340 Text("stored_class_loader_context_arg=--stored-class-loader-context=PCL[" + strings.Join(clc.Target, ":") + "]")
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +0000341 }
Colin Cross43f08db2018-11-12 10:13:39 -0800342
343 if module.EnforceUsesLibraries {
Colin Cross38b96852019-05-22 10:21:09 -0700344 if module.ManifestPath != nil {
345 rule.Command().Text(`target_sdk_version="$(`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000346 Tool(globalSoong.ManifestCheck).
Colin Cross38b96852019-05-22 10:21:09 -0700347 Flag("--extract-target-sdk-version").
348 Input(module.ManifestPath).
349 Text(`)"`)
350 } else {
351 // No manifest to extract targetSdkVersion from, hope that DexJar is an APK
352 rule.Command().Text(`target_sdk_version="$(`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000353 Tool(globalSoong.Aapt).
Colin Cross38b96852019-05-22 10:21:09 -0700354 Flag("dump badging").
355 Input(module.DexPath).
356 Text(`| grep "targetSdkVersion" | sed -n "s/targetSdkVersion:'\(.*\)'/\1/p"`).
357 Text(`)"`)
358 }
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100359 for _, ver := range classLoaderContexts.getSortedKeys() {
360 clc := classLoaderContexts.getValue(ver)
361 var varHost, varTarget string
362 if ver == anySdkVersion {
363 varHost = "dex_preopt_host_libraries"
364 varTarget = "dex_preopt_target_libraries"
365 } else {
366 varHost = fmt.Sprintf("conditional_host_libs_%d", ver)
367 varTarget = fmt.Sprintf("conditional_target_libs_%d", ver)
368 }
369 rule.Command().Textf(varHost+`="%s"`, strings.Join(clc.Host.Strings(), " ")).Implicits(clc.Host)
370 rule.Command().Textf(varTarget+`="%s"`, strings.Join(clc.Target, " "))
371 }
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000372 rule.Command().Text("source").Tool(globalSoong.ConstructContext).Input(module.DexPath)
Colin Cross43f08db2018-11-12 10:13:39 -0800373 }
374
Nicolas Geoffray2464ef42019-03-05 14:07:07 +0000375 // Devices that do not have a product partition use a symlink from /product to /system/product.
376 // Because on-device dexopt will see dex locations starting with /product, we change the paths
377 // to mimic this behavior.
378 dexLocationArg := module.DexLocation
379 if strings.HasPrefix(dexLocationArg, "/system/product/") {
380 dexLocationArg = strings.TrimPrefix(dexLocationArg, "/system")
381 }
382
Colin Cross43f08db2018-11-12 10:13:39 -0800383 cmd := rule.Command().
384 Text(`ANDROID_LOG_TAGS="*:e"`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000385 Tool(globalSoong.Dex2oat).
Colin Cross43f08db2018-11-12 10:13:39 -0800386 Flag("--avoid-storing-invocation").
Alex Light5de41962018-12-18 15:16:26 -0800387 FlagWithOutput("--write-invocation-to=", invocationPath).ImplicitOutput(invocationPath).
Colin Cross43f08db2018-11-12 10:13:39 -0800388 Flag("--runtime-arg").FlagWithArg("-Xms", global.Dex2oatXms).
389 Flag("--runtime-arg").FlagWithArg("-Xmx", global.Dex2oatXmx).
Colin Cross800fe132019-02-11 14:21:24 -0800390 Flag("--runtime-arg").FlagWithInputList("-Xbootclasspath:", module.PreoptBootClassPathDexFiles, ":").
391 Flag("--runtime-arg").FlagWithList("-Xbootclasspath-locations:", module.PreoptBootClassPathDexLocations, ":").
Colin Cross43f08db2018-11-12 10:13:39 -0800392 Flag("${class_loader_context_arg}").
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000393 Flag("${stored_class_loader_context_arg}").
Ulya Trafimovich3391a1e2020-01-03 17:33:17 +0000394 FlagWithArg("--boot-image=", strings.Join(module.DexPreoptImageLocations, ":")).Implicits(module.DexPreoptImagesDeps[archIdx].Paths()).
Colin Cross43f08db2018-11-12 10:13:39 -0800395 FlagWithInput("--dex-file=", module.DexPath).
Nicolas Geoffray2464ef42019-03-05 14:07:07 +0000396 FlagWithArg("--dex-location=", dexLocationArg).
Colin Cross43f08db2018-11-12 10:13:39 -0800397 FlagWithOutput("--oat-file=", odexPath).ImplicitOutput(vdexPath).
398 // Pass an empty directory, dex2oat shouldn't be reading arbitrary files
399 FlagWithArg("--android-root=", global.EmptyDirectory).
Colin Cross74ba9622019-02-11 15:11:14 -0800400 FlagWithArg("--instruction-set=", arch.String()).
Colin Cross43f08db2018-11-12 10:13:39 -0800401 FlagWithArg("--instruction-set-variant=", global.CpuVariant[arch]).
402 FlagWithArg("--instruction-set-features=", global.InstructionSetFeatures[arch]).
403 Flag("--no-generate-debug-info").
404 Flag("--generate-build-id").
405 Flag("--abort-on-hard-verifier-error").
406 Flag("--force-determinism").
407 FlagWithArg("--no-inline-from=", "core-oj.jar")
408
409 var preoptFlags []string
410 if len(module.PreoptFlags) > 0 {
411 preoptFlags = module.PreoptFlags
412 } else if len(global.PreoptFlags) > 0 {
413 preoptFlags = global.PreoptFlags
414 }
415
416 if len(preoptFlags) > 0 {
417 cmd.Text(strings.Join(preoptFlags, " "))
418 }
419
420 if module.UncompressedDex {
421 cmd.FlagWithArg("--copy-dex-files=", "false")
422 }
423
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800424 if !android.PrefixInList(preoptFlags, "--compiler-filter=") {
Colin Cross43f08db2018-11-12 10:13:39 -0800425 var compilerFilter string
426 if contains(global.SystemServerJars, module.Name) {
427 // Jars of system server, use the product option if it is set, speed otherwise.
428 if global.SystemServerCompilerFilter != "" {
429 compilerFilter = global.SystemServerCompilerFilter
430 } else {
431 compilerFilter = "speed"
432 }
433 } else if contains(global.SpeedApps, module.Name) || contains(global.SystemServerApps, module.Name) {
434 // Apps loaded into system server, and apps the product default to being compiled with the
435 // 'speed' compiler filter.
436 compilerFilter = "speed"
Colin Cross69f59a32019-02-15 10:39:37 -0800437 } else if profile != nil {
Colin Cross43f08db2018-11-12 10:13:39 -0800438 // For non system server jars, use speed-profile when we have a profile.
439 compilerFilter = "speed-profile"
440 } else if global.DefaultCompilerFilter != "" {
441 compilerFilter = global.DefaultCompilerFilter
442 } else {
443 compilerFilter = "quicken"
444 }
445 cmd.FlagWithArg("--compiler-filter=", compilerFilter)
446 }
447
448 if generateDM {
449 cmd.FlagWithArg("--copy-dex-files=", "false")
Colin Cross69f59a32019-02-15 10:39:37 -0800450 dmPath := module.BuildPath.InSameDir(ctx, "generated.dm")
Colin Cross43f08db2018-11-12 10:13:39 -0800451 dmInstalledPath := pathtools.ReplaceExtension(module.DexLocation, "dm")
Colin Cross69f59a32019-02-15 10:39:37 -0800452 tmpPath := module.BuildPath.InSameDir(ctx, "primary.vdex")
Colin Cross43f08db2018-11-12 10:13:39 -0800453 rule.Command().Text("cp -f").Input(vdexPath).Output(tmpPath)
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000454 rule.Command().Tool(globalSoong.SoongZip).
Colin Cross43f08db2018-11-12 10:13:39 -0800455 FlagWithArg("-L", "9").
456 FlagWithOutput("-o", dmPath).
457 Flag("-j").
458 Input(tmpPath)
459 rule.Install(dmPath, dmInstalledPath)
460 }
461
462 // By default, emit debug info.
463 debugInfo := true
464 if global.NoDebugInfo {
465 // If the global setting suppresses mini-debug-info, disable it.
466 debugInfo = false
467 }
468
469 // PRODUCT_SYSTEM_SERVER_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO.
470 // PRODUCT_OTHER_JAVA_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO.
471 if contains(global.SystemServerJars, module.Name) {
472 if global.AlwaysSystemServerDebugInfo {
473 debugInfo = true
474 } else if global.NeverSystemServerDebugInfo {
475 debugInfo = false
476 }
477 } else {
478 if global.AlwaysOtherDebugInfo {
479 debugInfo = true
480 } else if global.NeverOtherDebugInfo {
481 debugInfo = false
482 }
483 }
484
485 // Never enable on eng.
486 if global.IsEng {
487 debugInfo = false
488 }
489
490 if debugInfo {
491 cmd.Flag("--generate-mini-debug-info")
492 } else {
493 cmd.Flag("--no-generate-mini-debug-info")
494 }
495
496 // Set the compiler reason to 'prebuilt' to identify the oat files produced
497 // during the build, as opposed to compiled on the device.
498 cmd.FlagWithArg("--compilation-reason=", "prebuilt")
499
500 if appImage {
Colin Cross69f59a32019-02-15 10:39:37 -0800501 appImagePath := odexPath.ReplaceExtension(ctx, "art")
Colin Cross43f08db2018-11-12 10:13:39 -0800502 appImageInstallPath := pathtools.ReplaceExtension(odexInstallPath, "art")
503 cmd.FlagWithOutput("--app-image-file=", appImagePath).
504 FlagWithArg("--image-format=", "lz4")
Mathieu Chartier3f7ddbb2019-04-29 09:33:50 -0700505 if !global.DontResolveStartupStrings {
506 cmd.FlagWithArg("--resolve-startup-const-strings=", "true")
507 }
Colin Cross43f08db2018-11-12 10:13:39 -0800508 rule.Install(appImagePath, appImageInstallPath)
509 }
510
Colin Cross69f59a32019-02-15 10:39:37 -0800511 if profile != nil {
512 cmd.FlagWithInput("--profile-file=", profile)
Colin Cross43f08db2018-11-12 10:13:39 -0800513 }
514
515 rule.Install(odexPath, odexInstallPath)
516 rule.Install(vdexPath, vdexInstallPath)
517}
518
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000519func shouldGenerateDM(module *ModuleConfig, global *GlobalConfig) bool {
Colin Cross43f08db2018-11-12 10:13:39 -0800520 // Generating DM files only makes sense for verify, avoid doing for non verify compiler filter APKs.
521 // No reason to use a dm file if the dex is already uncompressed.
522 return global.GenerateDMFiles && !module.UncompressedDex &&
523 contains(module.PreoptFlags, "--compiler-filter=verify")
524}
525
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000526func OdexOnSystemOtherByName(name string, dexLocation string, global *GlobalConfig) bool {
Colin Cross43f08db2018-11-12 10:13:39 -0800527 if !global.HasSystemOther {
528 return false
529 }
530
531 if global.SanitizeLite {
532 return false
533 }
534
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000535 if contains(global.SpeedApps, name) || contains(global.SystemServerApps, name) {
Colin Cross43f08db2018-11-12 10:13:39 -0800536 return false
537 }
538
539 for _, f := range global.PatternsOnSystemOther {
Anton Hanssond57bd3c2019-10-14 16:53:02 +0100540 if makefileMatch(filepath.Join(SystemPartition, f), dexLocation) {
Colin Cross43f08db2018-11-12 10:13:39 -0800541 return true
542 }
543 }
544
545 return false
546}
547
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000548func odexOnSystemOther(module *ModuleConfig, global *GlobalConfig) bool {
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000549 return OdexOnSystemOtherByName(module.Name, module.DexLocation, global)
550}
551
Colin Crossc7e40aa2019-02-08 21:37:00 -0800552// PathToLocation converts .../system/framework/arm64/boot.art to .../system/framework/boot.art
Colin Cross69f59a32019-02-15 10:39:37 -0800553func PathToLocation(path android.Path, arch android.ArchType) string {
554 pathArch := filepath.Base(filepath.Dir(path.String()))
Colin Cross74ba9622019-02-11 15:11:14 -0800555 if pathArch != arch.String() {
556 panic(fmt.Errorf("last directory in %q must be %q", path, arch.String()))
Colin Crossc7e40aa2019-02-08 21:37:00 -0800557 }
Colin Cross69f59a32019-02-15 10:39:37 -0800558 return filepath.Join(filepath.Dir(filepath.Dir(path.String())), filepath.Base(path.String()))
Colin Crossc7e40aa2019-02-08 21:37:00 -0800559}
560
Ulya Trafimovichd4bcea42020-06-03 14:57:22 +0100561func pathForLibrary(module *ModuleConfig, lib string) *LibraryPath {
Colin Cross69f59a32019-02-15 10:39:37 -0800562 path, ok := module.LibraryPaths[lib]
563 if !ok {
Colin Cross43f08db2018-11-12 10:13:39 -0800564 panic(fmt.Errorf("unknown library path for %q", lib))
565 }
566 return path
567}
568
569func makefileMatch(pattern, s string) bool {
570 percent := strings.IndexByte(pattern, '%')
571 switch percent {
572 case -1:
573 return pattern == s
574 case len(pattern) - 1:
575 return strings.HasPrefix(s, pattern[:len(pattern)-1])
576 default:
577 panic(fmt.Errorf("unsupported makefile pattern %q", pattern))
578 }
579}
580
Ulyana Trafimovichf2cb7e92019-11-27 12:26:49 +0000581// Expected format for apexJarValue = <apex name>:<jar name>
Ulya Trafimovich8640ab92020-05-11 18:06:15 +0100582func GetJarLocationFromApexJarPair(ctx android.PathContext, apexJarValue string) string {
583 apex, jar := android.SplitApexJarPair(ctx, apexJarValue)
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000584 return filepath.Join("/apex", apex, "javalib", jar+".jar")
Roshan Piusccc26ef2019-11-27 09:37:46 -0800585}
586
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +0000587var nonUpdatableSystemServerJarsKey = android.NewOnceKey("nonUpdatableSystemServerJars")
588
589// TODO: eliminate the superficial global config parameter by moving global config definition
590// from java subpackage to dexpreopt.
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000591func NonUpdatableSystemServerJars(ctx android.PathContext, global *GlobalConfig) []string {
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +0000592 return ctx.Config().Once(nonUpdatableSystemServerJarsKey, func() interface{} {
593 return android.RemoveListFromList(global.SystemServerJars,
Ulya Trafimovich8640ab92020-05-11 18:06:15 +0100594 android.GetJarsFromApexJarPairs(ctx, global.UpdatableSystemServerJars))
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +0000595 }).([]string)
596}
597
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000598// A predefined location for the system server dex jars. This is needed in order to generate
599// class loader context for dex2oat, as the path to the jar in the Soong module may be unknown
600// at that time (Soong processes the jars in dependency order, which may be different from the
601// the system server classpath order).
602func SystemServerDexJarHostPath(ctx android.PathContext, jar string) android.OutputPath {
Ulya Trafimovich6cf2c0c2020-04-24 12:15:20 +0100603 if DexpreoptRunningInSoong {
604 // Soong module, just use the default output directory $OUT/soong.
605 return android.PathForOutput(ctx, "system_server_dexjars", jar+".jar")
606 } else {
607 // Make module, default output directory is $OUT (passed via the "null config" created
608 // by dexpreopt_gen). Append Soong subdirectory to match Soong module paths.
609 return android.PathForOutput(ctx, "soong", "system_server_dexjars", jar+".jar")
610 }
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000611}
612
Ulya Trafimovichcd3203f2020-03-27 11:30:00 +0000613// Check the order of jars on the system server classpath and give a warning/error if a jar precedes
614// one of its dependencies. This is not an error, but a missed optimization, as dexpreopt won't
615// have the dependency jar in the class loader context, and it won't be able to resolve any
616// references to its classes and methods.
617func checkSystemServerOrder(ctx android.PathContext, jarIndex int) {
618 mctx, isModule := ctx.(android.ModuleContext)
619 if isModule {
620 config := GetGlobalConfig(ctx)
621 jars := NonUpdatableSystemServerJars(ctx, config)
622 mctx.WalkDeps(func(dep android.Module, parent android.Module) bool {
623 depIndex := android.IndexList(dep.Name(), jars)
624 if jarIndex < depIndex && !config.BrokenSuboptimalOrderOfSystemServerJars {
625 jar := jars[jarIndex]
626 dep := jars[depIndex]
627 mctx.ModuleErrorf("non-optimal order of jars on the system server classpath:"+
628 " '%s' precedes its dependency '%s', so dexpreopt is unable to resolve any"+
629 " references from '%s' to '%s'.\n", jar, dep, jar, dep)
630 }
631 return true
632 })
633 }
634}
635
Colin Cross43f08db2018-11-12 10:13:39 -0800636func contains(l []string, s string) bool {
637 for _, e := range l {
638 if e == s {
639 return true
640 }
641 }
642 return false
643}
644
Colin Cross454c0872019-02-15 23:03:34 -0800645var copyOf = android.CopyOf