blob: 8c9f0a2b59643a69dd5c80158c015ffeac94e84d [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 Trafimovich249386a2020-07-01 14:31:13 +010086 if !global.BootJars.ContainsJar(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.
Ulya Trafimovich249386a2020-07-01 14:31:13 +0100107 if global.UpdatableSystemServerJars.ContainsJar(module.Name) {
108 return true
Ulyana Trafimovichf2cb7e92019-11-27 12:26:49 +0000109 }
110
Colin Cross43f08db2018-11-12 10:13:39 -0800111 // If OnlyPreoptBootImageAndSystemServer=true and module is not in boot class path skip
112 // Also preopt system server jars since selinux prevents system server from loading anything from
113 // /data. If we don't do this they will need to be extracted which is not favorable for RAM usage
114 // or performance. If PreoptExtractedApk is true, we ignore the only preopt boot image options.
Ulya Trafimovich249386a2020-07-01 14:31:13 +0100115 if global.OnlyPreoptBootImageAndSystemServer && !global.BootJars.ContainsJar(module.Name) &&
Colin Cross43f08db2018-11-12 10:13:39 -0800116 !contains(global.SystemServerJars, module.Name) && !module.PreoptExtractedApk {
Colin Crosscbed6572019-01-08 17:38:37 -0800117 return true
Colin Cross43f08db2018-11-12 10:13:39 -0800118 }
119
Colin Crosscbed6572019-01-08 17:38:37 -0800120 return false
Colin Cross43f08db2018-11-12 10:13:39 -0800121}
122
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000123func profileCommand(ctx android.PathContext, globalSoong *GlobalSoongConfig, global *GlobalConfig,
124 module *ModuleConfig, rule *android.RuleBuilder) android.WritablePath {
Colin Cross69f59a32019-02-15 10:39:37 -0800125
126 profilePath := module.BuildPath.InSameDir(ctx, "profile.prof")
Colin Cross43f08db2018-11-12 10:13:39 -0800127 profileInstalledPath := module.DexLocation + ".prof"
128
129 if !module.ProfileIsTextListing {
130 rule.Command().FlagWithOutput("touch ", profilePath)
131 }
132
133 cmd := rule.Command().
134 Text(`ANDROID_LOG_TAGS="*:e"`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000135 Tool(globalSoong.Profman)
Colin Cross43f08db2018-11-12 10:13:39 -0800136
137 if module.ProfileIsTextListing {
138 // The profile is a test listing of classes (used for framework jars).
139 // We need to generate the actual binary profile before being able to compile.
Colin Cross69f59a32019-02-15 10:39:37 -0800140 cmd.FlagWithInput("--create-profile-from=", module.ProfileClassListing.Path())
Colin Cross43f08db2018-11-12 10:13:39 -0800141 } else {
142 // The profile is binary profile (used for apps). Run it through profman to
143 // ensure the profile keys match the apk.
144 cmd.
145 Flag("--copy-and-update-profile-key").
Colin Cross69f59a32019-02-15 10:39:37 -0800146 FlagWithInput("--profile-file=", module.ProfileClassListing.Path())
Colin Cross43f08db2018-11-12 10:13:39 -0800147 }
148
149 cmd.
150 FlagWithInput("--apk=", module.DexPath).
151 Flag("--dex-location="+module.DexLocation).
152 FlagWithOutput("--reference-profile-file=", profilePath)
153
154 if !module.ProfileIsTextListing {
155 cmd.Text(fmt.Sprintf(`|| echo "Profile out of date for %s"`, module.DexPath))
156 }
157 rule.Install(profilePath, profileInstalledPath)
158
159 return profilePath
160}
161
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000162func bootProfileCommand(ctx android.PathContext, globalSoong *GlobalSoongConfig, global *GlobalConfig,
163 module *ModuleConfig, rule *android.RuleBuilder) android.WritablePath {
Nicolas Geoffraye7102422019-07-24 13:19:29 +0100164
165 profilePath := module.BuildPath.InSameDir(ctx, "profile.bprof")
166 profileInstalledPath := module.DexLocation + ".bprof"
167
168 if !module.ProfileIsTextListing {
169 rule.Command().FlagWithOutput("touch ", profilePath)
170 }
171
172 cmd := rule.Command().
173 Text(`ANDROID_LOG_TAGS="*:e"`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000174 Tool(globalSoong.Profman)
Nicolas Geoffraye7102422019-07-24 13:19:29 +0100175
176 // The profile is a test listing of methods.
177 // We need to generate the actual binary profile.
178 cmd.FlagWithInput("--create-profile-from=", module.ProfileBootListing.Path())
179
180 cmd.
181 Flag("--generate-boot-profile").
182 FlagWithInput("--apk=", module.DexPath).
183 Flag("--dex-location="+module.DexLocation).
184 FlagWithOutput("--reference-profile-file=", profilePath)
185
186 if !module.ProfileIsTextListing {
187 cmd.Text(fmt.Sprintf(`|| echo "Profile out of date for %s"`, module.DexPath))
188 }
189 rule.Install(profilePath, profileInstalledPath)
190
191 return profilePath
192}
193
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100194type classLoaderContext struct {
195 // The class loader context using paths in the build.
196 Host android.Paths
197
198 // The class loader context using paths as they will be on the device.
199 Target []string
200}
201
202// A map of class loader contexts for each SDK version.
203// A map entry for "any" version contains libraries that are unconditionally added to class loader
204// context. Map entries for existing versions contains libraries that were in the default classpath
205// until that API version, and should be added to class loader context if and only if the
206// targetSdkVersion in the manifest or APK is less than that API version.
207type classLoaderContextMap map[int]*classLoaderContext
208
Ulya Trafimovich5f364b62020-06-30 12:39:01 +0100209const anySdkVersion int = 9999 // should go last in class loader context
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100210
211func (m classLoaderContextMap) getSortedKeys() []int {
212 keys := make([]int, 0, len(m))
213 for k := range m {
214 keys = append(keys, k)
215 }
216 sort.Ints(keys)
217 return keys
218}
219
220func (m classLoaderContextMap) getValue(sdkVer int) *classLoaderContext {
221 if _, ok := m[sdkVer]; !ok {
222 m[sdkVer] = &classLoaderContext{}
223 }
224 return m[sdkVer]
225}
226
227func (m classLoaderContextMap) addLibs(sdkVer int, module *ModuleConfig, libs ...string) {
228 clc := m.getValue(sdkVer)
229 for _, lib := range libs {
Ulya Trafimovichd4bcea42020-06-03 14:57:22 +0100230 p := pathForLibrary(module, lib)
231 clc.Host = append(clc.Host, p.Host)
232 clc.Target = append(clc.Target, p.Device)
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100233 }
234}
235
236func (m classLoaderContextMap) addSystemServerLibs(sdkVer int, ctx android.PathContext, module *ModuleConfig, libs ...string) {
237 clc := m.getValue(sdkVer)
238 for _, lib := range libs {
239 clc.Host = append(clc.Host, SystemServerDexJarHostPath(ctx, lib))
240 clc.Target = append(clc.Target, filepath.Join("/system/framework", lib+".jar"))
241 }
242}
243
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000244func dexpreoptCommand(ctx android.PathContext, globalSoong *GlobalSoongConfig, global *GlobalConfig,
245 module *ModuleConfig, rule *android.RuleBuilder, archIdx int, profile android.WritablePath,
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000246 appImage bool, generateDM bool) {
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000247
248 arch := module.Archs[archIdx]
Colin Cross43f08db2018-11-12 10:13:39 -0800249
250 // HACK: make soname in Soong-generated .odex files match Make.
251 base := filepath.Base(module.DexLocation)
252 if filepath.Ext(base) == ".jar" {
253 base = "javalib.jar"
254 } else if filepath.Ext(base) == ".apk" {
255 base = "package.apk"
256 }
257
258 toOdexPath := func(path string) string {
259 return filepath.Join(
260 filepath.Dir(path),
261 "oat",
Colin Cross74ba9622019-02-11 15:11:14 -0800262 arch.String(),
Colin Cross43f08db2018-11-12 10:13:39 -0800263 pathtools.ReplaceExtension(filepath.Base(path), "odex"))
264 }
265
Colin Cross69f59a32019-02-15 10:39:37 -0800266 odexPath := module.BuildPath.InSameDir(ctx, "oat", arch.String(), pathtools.ReplaceExtension(base, "odex"))
Colin Cross43f08db2018-11-12 10:13:39 -0800267 odexInstallPath := toOdexPath(module.DexLocation)
268 if odexOnSystemOther(module, global) {
Anton Hansson43ab0bc2019-10-03 14:18:45 +0100269 odexInstallPath = filepath.Join(SystemOtherPartition, odexInstallPath)
Colin Cross43f08db2018-11-12 10:13:39 -0800270 }
271
Colin Cross69f59a32019-02-15 10:39:37 -0800272 vdexPath := odexPath.ReplaceExtension(ctx, "vdex")
Colin Cross43f08db2018-11-12 10:13:39 -0800273 vdexInstallPath := pathtools.ReplaceExtension(odexInstallPath, "vdex")
274
Colin Cross69f59a32019-02-15 10:39:37 -0800275 invocationPath := odexPath.ReplaceExtension(ctx, "invocation")
Alex Light5de41962018-12-18 15:16:26 -0800276
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100277 classLoaderContexts := make(classLoaderContextMap)
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000278 systemServerJars := NonUpdatableSystemServerJars(ctx, global)
279
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100280 rule.Command().FlagWithArg("mkdir -p ", filepath.Dir(odexPath.String()))
281 rule.Command().FlagWithOutput("rm -f ", odexPath)
Ulya Trafimovichc9af5382020-05-29 15:35:06 +0100282
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100283 if jarIndex := android.IndexList(module.Name, systemServerJars); jarIndex >= 0 {
284 // System server jars should be dexpreopted together: class loader context of each jar
285 // should include all preceding jars on the system server classpath.
286 classLoaderContexts.addSystemServerLibs(anySdkVersion, ctx, module, systemServerJars[:jarIndex]...)
Colin Cross69f59a32019-02-15 10:39:37 -0800287
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100288 // Copy the system server jar to a predefined location where dex2oat will find it.
289 dexPathHost := SystemServerDexJarHostPath(ctx, module.Name)
290 rule.Command().Text("mkdir -p").Flag(filepath.Dir(dexPathHost.String()))
291 rule.Command().Text("cp -f").Input(module.DexPath).Output(dexPathHost)
292
293 checkSystemServerOrder(ctx, jarIndex)
294
295 clc := classLoaderContexts[anySdkVersion]
296 rule.Command().
297 Text("class_loader_context_arg=--class-loader-context=PCL[" + strings.Join(clc.Host.Strings(), ":") + "]").
298 Implicits(clc.Host).
299 Text("stored_class_loader_context_arg=--stored-class-loader-context=PCL[" + strings.Join(clc.Target, ":") + "]")
300 } else if module.EnforceUsesLibraries {
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100301 // Unconditional class loader context.
Ulya Trafimovich6e827482020-06-12 14:32:24 +0100302 usesLibs := append(copyOf(module.UsesLibraries), module.OptionalUsesLibraries...)
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100303 classLoaderContexts.addLibs(anySdkVersion, module, usesLibs...)
Colin Cross43f08db2018-11-12 10:13:39 -0800304
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100305 // Conditional class loader context for API version < 28.
Colin Cross43f08db2018-11-12 10:13:39 -0800306 const httpLegacy = "org.apache.http.legacy"
Ulya Trafimovichdf00dde2020-05-29 14:55:02 +0100307 if !contains(usesLibs, httpLegacy) {
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100308 classLoaderContexts.addLibs(28, module, httpLegacy)
Colin Cross43f08db2018-11-12 10:13:39 -0800309 }
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000310
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100311 // Conditional class loader context for API version < 29.
312 usesLibs29 := []string{
313 "android.hidl.base-V1.0-java",
314 "android.hidl.manager-V1.0-java",
315 }
316 classLoaderContexts.addLibs(29, module, usesLibs29...)
Ulya Trafimovichc9af5382020-05-29 15:35:06 +0100317
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100318 // Conditional class loader context for API version < 30.
Ulya Trafimovichc9af5382020-05-29 15:35:06 +0100319 const testBase = "android.test.base"
320 if !contains(usesLibs, testBase) {
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100321 classLoaderContexts.addLibs(30, module, testBase)
Ulya Trafimovichc9af5382020-05-29 15:35:06 +0100322 }
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +0000323
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100324 // Generate command that saves target SDK version in a shell variable.
Colin Cross38b96852019-05-22 10:21:09 -0700325 if module.ManifestPath != nil {
326 rule.Command().Text(`target_sdk_version="$(`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000327 Tool(globalSoong.ManifestCheck).
Colin Cross38b96852019-05-22 10:21:09 -0700328 Flag("--extract-target-sdk-version").
329 Input(module.ManifestPath).
330 Text(`)"`)
331 } else {
332 // No manifest to extract targetSdkVersion from, hope that DexJar is an APK
333 rule.Command().Text(`target_sdk_version="$(`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000334 Tool(globalSoong.Aapt).
Colin Cross38b96852019-05-22 10:21:09 -0700335 Flag("dump badging").
336 Input(module.DexPath).
337 Text(`| grep "targetSdkVersion" | sed -n "s/targetSdkVersion:'\(.*\)'/\1/p"`).
338 Text(`)"`)
339 }
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100340
Ulya Trafimovich5f364b62020-06-30 12:39:01 +0100341 // Generate command that saves host and target class loader context in shell variables.
342 cmd := rule.Command().
343 Text(`eval "$(`).Tool(globalSoong.ConstructContext).
344 Text(` --target-sdk-version ${target_sdk_version}`)
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100345 for _, ver := range classLoaderContexts.getSortedKeys() {
346 clc := classLoaderContexts.getValue(ver)
Ulya Trafimovich5f364b62020-06-30 12:39:01 +0100347 verString := fmt.Sprintf("%d", ver)
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100348 if ver == anySdkVersion {
Ulya Trafimovich5f364b62020-06-30 12:39:01 +0100349 verString = "any" // a special keyword that means any SDK version
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100350 }
Ulya Trafimovich5f364b62020-06-30 12:39:01 +0100351 cmd.Textf(`--host-classpath-for-sdk %s %s`, verString, strings.Join(clc.Host.Strings(), ":")).
352 Implicits(clc.Host).
353 Textf(`--target-classpath-for-sdk %s %s`, verString, strings.Join(clc.Target, ":"))
Ulya Trafimovich696c59d2020-06-01 16:10:56 +0100354 }
Ulya Trafimovich5f364b62020-06-30 12:39:01 +0100355 cmd.Text(`)"`)
Ulya Trafimovichc4dac262020-06-30 11:25:49 +0100356 } else {
357 // Pass special class loader context to skip the classpath and collision check.
358 // This will get removed once LOCAL_USES_LIBRARIES is enforced.
359 // Right now LOCAL_USES_LIBRARIES is opt in, for the case where it's not specified we still default
360 // to the &.
361 rule.Command().
362 Text(`class_loader_context_arg=--class-loader-context=\&`).
363 Text(`stored_class_loader_context_arg=""`)
Colin Cross43f08db2018-11-12 10:13:39 -0800364 }
365
Nicolas Geoffray2464ef42019-03-05 14:07:07 +0000366 // Devices that do not have a product partition use a symlink from /product to /system/product.
367 // Because on-device dexopt will see dex locations starting with /product, we change the paths
368 // to mimic this behavior.
369 dexLocationArg := module.DexLocation
370 if strings.HasPrefix(dexLocationArg, "/system/product/") {
371 dexLocationArg = strings.TrimPrefix(dexLocationArg, "/system")
372 }
373
Colin Cross43f08db2018-11-12 10:13:39 -0800374 cmd := rule.Command().
375 Text(`ANDROID_LOG_TAGS="*:e"`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000376 Tool(globalSoong.Dex2oat).
Colin Cross43f08db2018-11-12 10:13:39 -0800377 Flag("--avoid-storing-invocation").
Alex Light5de41962018-12-18 15:16:26 -0800378 FlagWithOutput("--write-invocation-to=", invocationPath).ImplicitOutput(invocationPath).
Colin Cross43f08db2018-11-12 10:13:39 -0800379 Flag("--runtime-arg").FlagWithArg("-Xms", global.Dex2oatXms).
380 Flag("--runtime-arg").FlagWithArg("-Xmx", global.Dex2oatXmx).
Colin Cross800fe132019-02-11 14:21:24 -0800381 Flag("--runtime-arg").FlagWithInputList("-Xbootclasspath:", module.PreoptBootClassPathDexFiles, ":").
382 Flag("--runtime-arg").FlagWithList("-Xbootclasspath-locations:", module.PreoptBootClassPathDexLocations, ":").
Colin Cross43f08db2018-11-12 10:13:39 -0800383 Flag("${class_loader_context_arg}").
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000384 Flag("${stored_class_loader_context_arg}").
Ulya Trafimovich3391a1e2020-01-03 17:33:17 +0000385 FlagWithArg("--boot-image=", strings.Join(module.DexPreoptImageLocations, ":")).Implicits(module.DexPreoptImagesDeps[archIdx].Paths()).
Colin Cross43f08db2018-11-12 10:13:39 -0800386 FlagWithInput("--dex-file=", module.DexPath).
Nicolas Geoffray2464ef42019-03-05 14:07:07 +0000387 FlagWithArg("--dex-location=", dexLocationArg).
Colin Cross43f08db2018-11-12 10:13:39 -0800388 FlagWithOutput("--oat-file=", odexPath).ImplicitOutput(vdexPath).
389 // Pass an empty directory, dex2oat shouldn't be reading arbitrary files
390 FlagWithArg("--android-root=", global.EmptyDirectory).
Colin Cross74ba9622019-02-11 15:11:14 -0800391 FlagWithArg("--instruction-set=", arch.String()).
Colin Cross43f08db2018-11-12 10:13:39 -0800392 FlagWithArg("--instruction-set-variant=", global.CpuVariant[arch]).
393 FlagWithArg("--instruction-set-features=", global.InstructionSetFeatures[arch]).
394 Flag("--no-generate-debug-info").
395 Flag("--generate-build-id").
396 Flag("--abort-on-hard-verifier-error").
397 Flag("--force-determinism").
398 FlagWithArg("--no-inline-from=", "core-oj.jar")
399
400 var preoptFlags []string
401 if len(module.PreoptFlags) > 0 {
402 preoptFlags = module.PreoptFlags
403 } else if len(global.PreoptFlags) > 0 {
404 preoptFlags = global.PreoptFlags
405 }
406
407 if len(preoptFlags) > 0 {
408 cmd.Text(strings.Join(preoptFlags, " "))
409 }
410
411 if module.UncompressedDex {
412 cmd.FlagWithArg("--copy-dex-files=", "false")
413 }
414
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800415 if !android.PrefixInList(preoptFlags, "--compiler-filter=") {
Colin Cross43f08db2018-11-12 10:13:39 -0800416 var compilerFilter string
417 if contains(global.SystemServerJars, module.Name) {
418 // Jars of system server, use the product option if it is set, speed otherwise.
419 if global.SystemServerCompilerFilter != "" {
420 compilerFilter = global.SystemServerCompilerFilter
421 } else {
422 compilerFilter = "speed"
423 }
424 } else if contains(global.SpeedApps, module.Name) || contains(global.SystemServerApps, module.Name) {
425 // Apps loaded into system server, and apps the product default to being compiled with the
426 // 'speed' compiler filter.
427 compilerFilter = "speed"
Colin Cross69f59a32019-02-15 10:39:37 -0800428 } else if profile != nil {
Colin Cross43f08db2018-11-12 10:13:39 -0800429 // For non system server jars, use speed-profile when we have a profile.
430 compilerFilter = "speed-profile"
431 } else if global.DefaultCompilerFilter != "" {
432 compilerFilter = global.DefaultCompilerFilter
433 } else {
434 compilerFilter = "quicken"
435 }
436 cmd.FlagWithArg("--compiler-filter=", compilerFilter)
437 }
438
439 if generateDM {
440 cmd.FlagWithArg("--copy-dex-files=", "false")
Colin Cross69f59a32019-02-15 10:39:37 -0800441 dmPath := module.BuildPath.InSameDir(ctx, "generated.dm")
Colin Cross43f08db2018-11-12 10:13:39 -0800442 dmInstalledPath := pathtools.ReplaceExtension(module.DexLocation, "dm")
Colin Cross69f59a32019-02-15 10:39:37 -0800443 tmpPath := module.BuildPath.InSameDir(ctx, "primary.vdex")
Colin Cross43f08db2018-11-12 10:13:39 -0800444 rule.Command().Text("cp -f").Input(vdexPath).Output(tmpPath)
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000445 rule.Command().Tool(globalSoong.SoongZip).
Colin Cross43f08db2018-11-12 10:13:39 -0800446 FlagWithArg("-L", "9").
447 FlagWithOutput("-o", dmPath).
448 Flag("-j").
449 Input(tmpPath)
450 rule.Install(dmPath, dmInstalledPath)
451 }
452
453 // By default, emit debug info.
454 debugInfo := true
455 if global.NoDebugInfo {
456 // If the global setting suppresses mini-debug-info, disable it.
457 debugInfo = false
458 }
459
460 // PRODUCT_SYSTEM_SERVER_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO.
461 // PRODUCT_OTHER_JAVA_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO.
462 if contains(global.SystemServerJars, module.Name) {
463 if global.AlwaysSystemServerDebugInfo {
464 debugInfo = true
465 } else if global.NeverSystemServerDebugInfo {
466 debugInfo = false
467 }
468 } else {
469 if global.AlwaysOtherDebugInfo {
470 debugInfo = true
471 } else if global.NeverOtherDebugInfo {
472 debugInfo = false
473 }
474 }
475
476 // Never enable on eng.
477 if global.IsEng {
478 debugInfo = false
479 }
480
481 if debugInfo {
482 cmd.Flag("--generate-mini-debug-info")
483 } else {
484 cmd.Flag("--no-generate-mini-debug-info")
485 }
486
487 // Set the compiler reason to 'prebuilt' to identify the oat files produced
488 // during the build, as opposed to compiled on the device.
489 cmd.FlagWithArg("--compilation-reason=", "prebuilt")
490
491 if appImage {
Colin Cross69f59a32019-02-15 10:39:37 -0800492 appImagePath := odexPath.ReplaceExtension(ctx, "art")
Colin Cross43f08db2018-11-12 10:13:39 -0800493 appImageInstallPath := pathtools.ReplaceExtension(odexInstallPath, "art")
494 cmd.FlagWithOutput("--app-image-file=", appImagePath).
495 FlagWithArg("--image-format=", "lz4")
Mathieu Chartier3f7ddbb2019-04-29 09:33:50 -0700496 if !global.DontResolveStartupStrings {
497 cmd.FlagWithArg("--resolve-startup-const-strings=", "true")
498 }
Colin Cross43f08db2018-11-12 10:13:39 -0800499 rule.Install(appImagePath, appImageInstallPath)
500 }
501
Colin Cross69f59a32019-02-15 10:39:37 -0800502 if profile != nil {
503 cmd.FlagWithInput("--profile-file=", profile)
Colin Cross43f08db2018-11-12 10:13:39 -0800504 }
505
506 rule.Install(odexPath, odexInstallPath)
507 rule.Install(vdexPath, vdexInstallPath)
508}
509
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000510func shouldGenerateDM(module *ModuleConfig, global *GlobalConfig) bool {
Colin Cross43f08db2018-11-12 10:13:39 -0800511 // Generating DM files only makes sense for verify, avoid doing for non verify compiler filter APKs.
512 // No reason to use a dm file if the dex is already uncompressed.
513 return global.GenerateDMFiles && !module.UncompressedDex &&
514 contains(module.PreoptFlags, "--compiler-filter=verify")
515}
516
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000517func OdexOnSystemOtherByName(name string, dexLocation string, global *GlobalConfig) bool {
Colin Cross43f08db2018-11-12 10:13:39 -0800518 if !global.HasSystemOther {
519 return false
520 }
521
522 if global.SanitizeLite {
523 return false
524 }
525
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000526 if contains(global.SpeedApps, name) || contains(global.SystemServerApps, name) {
Colin Cross43f08db2018-11-12 10:13:39 -0800527 return false
528 }
529
530 for _, f := range global.PatternsOnSystemOther {
Anton Hanssond57bd3c2019-10-14 16:53:02 +0100531 if makefileMatch(filepath.Join(SystemPartition, f), dexLocation) {
Colin Cross43f08db2018-11-12 10:13:39 -0800532 return true
533 }
534 }
535
536 return false
537}
538
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000539func odexOnSystemOther(module *ModuleConfig, global *GlobalConfig) bool {
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000540 return OdexOnSystemOtherByName(module.Name, module.DexLocation, global)
541}
542
Colin Crossc7e40aa2019-02-08 21:37:00 -0800543// PathToLocation converts .../system/framework/arm64/boot.art to .../system/framework/boot.art
Colin Cross69f59a32019-02-15 10:39:37 -0800544func PathToLocation(path android.Path, arch android.ArchType) string {
545 pathArch := filepath.Base(filepath.Dir(path.String()))
Colin Cross74ba9622019-02-11 15:11:14 -0800546 if pathArch != arch.String() {
547 panic(fmt.Errorf("last directory in %q must be %q", path, arch.String()))
Colin Crossc7e40aa2019-02-08 21:37:00 -0800548 }
Colin Cross69f59a32019-02-15 10:39:37 -0800549 return filepath.Join(filepath.Dir(filepath.Dir(path.String())), filepath.Base(path.String()))
Colin Crossc7e40aa2019-02-08 21:37:00 -0800550}
551
Ulya Trafimovichd4bcea42020-06-03 14:57:22 +0100552func pathForLibrary(module *ModuleConfig, lib string) *LibraryPath {
Colin Cross69f59a32019-02-15 10:39:37 -0800553 path, ok := module.LibraryPaths[lib]
554 if !ok {
Colin Cross43f08db2018-11-12 10:13:39 -0800555 panic(fmt.Errorf("unknown library path for %q", lib))
556 }
557 return path
558}
559
560func makefileMatch(pattern, s string) bool {
561 percent := strings.IndexByte(pattern, '%')
562 switch percent {
563 case -1:
564 return pattern == s
565 case len(pattern) - 1:
566 return strings.HasPrefix(s, pattern[:len(pattern)-1])
567 default:
568 panic(fmt.Errorf("unsupported makefile pattern %q", pattern))
569 }
570}
571
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +0000572var nonUpdatableSystemServerJarsKey = android.NewOnceKey("nonUpdatableSystemServerJars")
573
574// TODO: eliminate the superficial global config parameter by moving global config definition
575// from java subpackage to dexpreopt.
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000576func NonUpdatableSystemServerJars(ctx android.PathContext, global *GlobalConfig) []string {
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +0000577 return ctx.Config().Once(nonUpdatableSystemServerJarsKey, func() interface{} {
Ulya Trafimovich249386a2020-07-01 14:31:13 +0100578 return android.RemoveListFromList(global.SystemServerJars, global.UpdatableSystemServerJars.CopyOfJars())
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +0000579 }).([]string)
580}
581
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000582// A predefined location for the system server dex jars. This is needed in order to generate
583// class loader context for dex2oat, as the path to the jar in the Soong module may be unknown
584// at that time (Soong processes the jars in dependency order, which may be different from the
585// the system server classpath order).
586func SystemServerDexJarHostPath(ctx android.PathContext, jar string) android.OutputPath {
Ulya Trafimovich6cf2c0c2020-04-24 12:15:20 +0100587 if DexpreoptRunningInSoong {
588 // Soong module, just use the default output directory $OUT/soong.
589 return android.PathForOutput(ctx, "system_server_dexjars", jar+".jar")
590 } else {
591 // Make module, default output directory is $OUT (passed via the "null config" created
592 // by dexpreopt_gen). Append Soong subdirectory to match Soong module paths.
593 return android.PathForOutput(ctx, "soong", "system_server_dexjars", jar+".jar")
594 }
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000595}
596
Ulya Trafimovichcd3203f2020-03-27 11:30:00 +0000597// Check the order of jars on the system server classpath and give a warning/error if a jar precedes
598// one of its dependencies. This is not an error, but a missed optimization, as dexpreopt won't
599// have the dependency jar in the class loader context, and it won't be able to resolve any
600// references to its classes and methods.
601func checkSystemServerOrder(ctx android.PathContext, jarIndex int) {
602 mctx, isModule := ctx.(android.ModuleContext)
603 if isModule {
604 config := GetGlobalConfig(ctx)
605 jars := NonUpdatableSystemServerJars(ctx, config)
606 mctx.WalkDeps(func(dep android.Module, parent android.Module) bool {
607 depIndex := android.IndexList(dep.Name(), jars)
608 if jarIndex < depIndex && !config.BrokenSuboptimalOrderOfSystemServerJars {
609 jar := jars[jarIndex]
610 dep := jars[depIndex]
611 mctx.ModuleErrorf("non-optimal order of jars on the system server classpath:"+
612 " '%s' precedes its dependency '%s', so dexpreopt is unable to resolve any"+
613 " references from '%s' to '%s'.\n", jar, dep, jar, dep)
614 }
615 return true
616 })
617 }
618}
619
Colin Cross43f08db2018-11-12 10:13:39 -0800620func contains(l []string, s string) bool {
621 for _, e := range l {
622 if e == s {
623 return true
624 }
625 }
626 return false
627}
628
Colin Cross454c0872019-02-15 23:03:34 -0800629var copyOf = android.CopyOf