blob: f1dde9c2266bbec227435bf703183c844fed4639 [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 Trafimovich50c4a4b2020-04-21 15:36:33 +010085 if !contains(android.GetJarsFromApexJarPairs(global.BootJars), 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.
106 for _, p := range global.UpdatableSystemServerJars {
Ulya Trafimovich4cdada22020-02-10 15:29:28 +0000107 if _, jar := android.SplitApexJarPair(p); jar == module.Name {
Ulyana Trafimovichf2cb7e92019-11-27 12:26:49 +0000108 return true
109 }
110 }
111
Colin Cross43f08db2018-11-12 10:13:39 -0800112 // If OnlyPreoptBootImageAndSystemServer=true and module is not in boot class path skip
113 // Also preopt system server jars since selinux prevents system server from loading anything from
114 // /data. If we don't do this they will need to be extracted which is not favorable for RAM usage
115 // or performance. If PreoptExtractedApk is true, we ignore the only preopt boot image options.
Ulya Trafimovich50c4a4b2020-04-21 15:36:33 +0100116 if global.OnlyPreoptBootImageAndSystemServer && !contains(android.GetJarsFromApexJarPairs(global.BootJars), module.Name) &&
Colin Cross43f08db2018-11-12 10:13:39 -0800117 !contains(global.SystemServerJars, module.Name) && !module.PreoptExtractedApk {
Colin Crosscbed6572019-01-08 17:38:37 -0800118 return true
Colin Cross43f08db2018-11-12 10:13:39 -0800119 }
120
Colin Crosscbed6572019-01-08 17:38:37 -0800121 return false
Colin Cross43f08db2018-11-12 10:13:39 -0800122}
123
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000124func profileCommand(ctx android.PathContext, globalSoong *GlobalSoongConfig, global *GlobalConfig,
125 module *ModuleConfig, rule *android.RuleBuilder) android.WritablePath {
Colin Cross69f59a32019-02-15 10:39:37 -0800126
127 profilePath := module.BuildPath.InSameDir(ctx, "profile.prof")
Colin Cross43f08db2018-11-12 10:13:39 -0800128 profileInstalledPath := module.DexLocation + ".prof"
129
130 if !module.ProfileIsTextListing {
131 rule.Command().FlagWithOutput("touch ", profilePath)
132 }
133
134 cmd := rule.Command().
135 Text(`ANDROID_LOG_TAGS="*:e"`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000136 Tool(globalSoong.Profman)
Colin Cross43f08db2018-11-12 10:13:39 -0800137
138 if module.ProfileIsTextListing {
139 // The profile is a test listing of classes (used for framework jars).
140 // We need to generate the actual binary profile before being able to compile.
Colin Cross69f59a32019-02-15 10:39:37 -0800141 cmd.FlagWithInput("--create-profile-from=", module.ProfileClassListing.Path())
Colin Cross43f08db2018-11-12 10:13:39 -0800142 } else {
143 // The profile is binary profile (used for apps). Run it through profman to
144 // ensure the profile keys match the apk.
145 cmd.
146 Flag("--copy-and-update-profile-key").
Colin Cross69f59a32019-02-15 10:39:37 -0800147 FlagWithInput("--profile-file=", module.ProfileClassListing.Path())
Colin Cross43f08db2018-11-12 10:13:39 -0800148 }
149
150 cmd.
151 FlagWithInput("--apk=", module.DexPath).
152 Flag("--dex-location="+module.DexLocation).
153 FlagWithOutput("--reference-profile-file=", profilePath)
154
155 if !module.ProfileIsTextListing {
156 cmd.Text(fmt.Sprintf(`|| echo "Profile out of date for %s"`, module.DexPath))
157 }
158 rule.Install(profilePath, profileInstalledPath)
159
160 return profilePath
161}
162
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000163func bootProfileCommand(ctx android.PathContext, globalSoong *GlobalSoongConfig, global *GlobalConfig,
164 module *ModuleConfig, rule *android.RuleBuilder) android.WritablePath {
Nicolas Geoffraye7102422019-07-24 13:19:29 +0100165
166 profilePath := module.BuildPath.InSameDir(ctx, "profile.bprof")
167 profileInstalledPath := module.DexLocation + ".bprof"
168
169 if !module.ProfileIsTextListing {
170 rule.Command().FlagWithOutput("touch ", profilePath)
171 }
172
173 cmd := rule.Command().
174 Text(`ANDROID_LOG_TAGS="*:e"`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000175 Tool(globalSoong.Profman)
Nicolas Geoffraye7102422019-07-24 13:19:29 +0100176
177 // The profile is a test listing of methods.
178 // We need to generate the actual binary profile.
179 cmd.FlagWithInput("--create-profile-from=", module.ProfileBootListing.Path())
180
181 cmd.
182 Flag("--generate-boot-profile").
183 FlagWithInput("--apk=", module.DexPath).
184 Flag("--dex-location="+module.DexLocation).
185 FlagWithOutput("--reference-profile-file=", profilePath)
186
187 if !module.ProfileIsTextListing {
188 cmd.Text(fmt.Sprintf(`|| echo "Profile out of date for %s"`, module.DexPath))
189 }
190 rule.Install(profilePath, profileInstalledPath)
191
192 return profilePath
193}
194
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000195func dexpreoptCommand(ctx android.PathContext, globalSoong *GlobalSoongConfig, global *GlobalConfig,
196 module *ModuleConfig, rule *android.RuleBuilder, archIdx int, profile android.WritablePath,
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000197 appImage bool, generateDM bool) {
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000198
199 arch := module.Archs[archIdx]
Colin Cross43f08db2018-11-12 10:13:39 -0800200
201 // HACK: make soname in Soong-generated .odex files match Make.
202 base := filepath.Base(module.DexLocation)
203 if filepath.Ext(base) == ".jar" {
204 base = "javalib.jar"
205 } else if filepath.Ext(base) == ".apk" {
206 base = "package.apk"
207 }
208
209 toOdexPath := func(path string) string {
210 return filepath.Join(
211 filepath.Dir(path),
212 "oat",
Colin Cross74ba9622019-02-11 15:11:14 -0800213 arch.String(),
Colin Cross43f08db2018-11-12 10:13:39 -0800214 pathtools.ReplaceExtension(filepath.Base(path), "odex"))
215 }
216
Colin Cross69f59a32019-02-15 10:39:37 -0800217 odexPath := module.BuildPath.InSameDir(ctx, "oat", arch.String(), pathtools.ReplaceExtension(base, "odex"))
Colin Cross43f08db2018-11-12 10:13:39 -0800218 odexInstallPath := toOdexPath(module.DexLocation)
219 if odexOnSystemOther(module, global) {
Anton Hansson43ab0bc2019-10-03 14:18:45 +0100220 odexInstallPath = filepath.Join(SystemOtherPartition, odexInstallPath)
Colin Cross43f08db2018-11-12 10:13:39 -0800221 }
222
Colin Cross69f59a32019-02-15 10:39:37 -0800223 vdexPath := odexPath.ReplaceExtension(ctx, "vdex")
Colin Cross43f08db2018-11-12 10:13:39 -0800224 vdexInstallPath := pathtools.ReplaceExtension(odexInstallPath, "vdex")
225
Colin Cross69f59a32019-02-15 10:39:37 -0800226 invocationPath := odexPath.ReplaceExtension(ctx, "invocation")
Alex Light5de41962018-12-18 15:16:26 -0800227
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000228 systemServerJars := NonUpdatableSystemServerJars(ctx, global)
229
Colin Cross43f08db2018-11-12 10:13:39 -0800230 // The class loader context using paths in the build
Colin Cross69f59a32019-02-15 10:39:37 -0800231 var classLoaderContextHost android.Paths
Colin Cross43f08db2018-11-12 10:13:39 -0800232
233 // The class loader context using paths as they will be on the device
234 var classLoaderContextTarget []string
235
236 // Extra paths that will be appended to the class loader if the APK manifest has targetSdkVersion < 28
Colin Cross69f59a32019-02-15 10:39:37 -0800237 var conditionalClassLoaderContextHost28 android.Paths
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000238 var conditionalClassLoaderContextTarget28 []string
239
240 // Extra paths that will be appended to the class loader if the APK manifest has targetSdkVersion < 29
Colin Cross69f59a32019-02-15 10:39:37 -0800241 var conditionalClassLoaderContextHost29 android.Paths
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000242 var conditionalClassLoaderContextTarget29 []string
Colin Cross43f08db2018-11-12 10:13:39 -0800243
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000244 // A flag indicating if the '&' class loader context is used.
245 unknownClassLoaderContext := false
Colin Cross69f59a32019-02-15 10:39:37 -0800246
Colin Cross43f08db2018-11-12 10:13:39 -0800247 if module.EnforceUsesLibraries {
Colin Cross50ddcc42019-05-16 12:28:22 -0700248 usesLibs := append(copyOf(module.UsesLibraries), module.PresentOptionalUsesLibraries...)
Colin Cross43f08db2018-11-12 10:13:39 -0800249
250 // Create class loader context for dex2oat from uses libraries and filtered optional libraries
Colin Cross50ddcc42019-05-16 12:28:22 -0700251 for _, l := range usesLibs {
Colin Cross43f08db2018-11-12 10:13:39 -0800252
253 classLoaderContextHost = append(classLoaderContextHost,
254 pathForLibrary(module, l))
255 classLoaderContextTarget = append(classLoaderContextTarget,
256 filepath.Join("/system/framework", l+".jar"))
257 }
258
259 const httpLegacy = "org.apache.http.legacy"
260 const httpLegacyImpl = "org.apache.http.legacy.impl"
261
Colin Cross38b96852019-05-22 10:21:09 -0700262 // org.apache.http.legacy contains classes that were in the default classpath until API 28. If the
263 // targetSdkVersion in the manifest or APK is < 28, and the module does not explicitly depend on
264 // org.apache.http.legacy, then implicitly add the classes to the classpath for dexpreopt. One the
265 // device the classes will be in a file called org.apache.http.legacy.impl.jar.
Colin Cross50ddcc42019-05-16 12:28:22 -0700266 module.LibraryPaths[httpLegacyImpl] = module.LibraryPaths[httpLegacy]
267
268 if !contains(module.UsesLibraries, httpLegacy) && !contains(module.PresentOptionalUsesLibraries, httpLegacy) {
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000269 conditionalClassLoaderContextHost28 = append(conditionalClassLoaderContextHost28,
Colin Cross43f08db2018-11-12 10:13:39 -0800270 pathForLibrary(module, httpLegacyImpl))
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000271 conditionalClassLoaderContextTarget28 = append(conditionalClassLoaderContextTarget28,
Colin Cross43f08db2018-11-12 10:13:39 -0800272 filepath.Join("/system/framework", httpLegacyImpl+".jar"))
273 }
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000274
275 const hidlBase = "android.hidl.base-V1.0-java"
276 const hidlManager = "android.hidl.manager-V1.0-java"
277
Colin Cross38b96852019-05-22 10:21:09 -0700278 // android.hidl.base-V1.0-java and android.hidl.manager-V1.0 contain classes that were in the default
279 // classpath until API 29. If the targetSdkVersion in the manifest or APK is < 29 then implicitly add
280 // the classes to the classpath for dexpreopt.
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000281 conditionalClassLoaderContextHost29 = append(conditionalClassLoaderContextHost29,
Alex Light5de41962018-12-18 15:16:26 -0800282 pathForLibrary(module, hidlManager))
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000283 conditionalClassLoaderContextTarget29 = append(conditionalClassLoaderContextTarget29,
284 filepath.Join("/system/framework", hidlManager+".jar"))
285 conditionalClassLoaderContextHost29 = append(conditionalClassLoaderContextHost29,
Alex Light5de41962018-12-18 15:16:26 -0800286 pathForLibrary(module, hidlBase))
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000287 conditionalClassLoaderContextTarget29 = append(conditionalClassLoaderContextTarget29,
288 filepath.Join("/system/framework", hidlBase+".jar"))
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000289 } else if jarIndex := android.IndexList(module.Name, systemServerJars); jarIndex >= 0 {
290 // System server jars should be dexpreopted together: class loader context of each jar
291 // should include all preceding jars on the system server classpath.
292 for _, otherJar := range systemServerJars[:jarIndex] {
293 classLoaderContextHost = append(classLoaderContextHost, SystemServerDexJarHostPath(ctx, otherJar))
294 classLoaderContextTarget = append(classLoaderContextTarget, "/system/framework/"+otherJar+".jar")
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +0000295 }
296
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000297 // Copy the system server jar to a predefined location where dex2oat will find it.
298 dexPathHost := SystemServerDexJarHostPath(ctx, module.Name)
299 rule.Command().Text("mkdir -p").Flag(filepath.Dir(dexPathHost.String()))
300 rule.Command().Text("cp -f").Input(module.DexPath).Output(dexPathHost)
Colin Cross43f08db2018-11-12 10:13:39 -0800301 } else {
302 // Pass special class loader context to skip the classpath and collision check.
303 // This will get removed once LOCAL_USES_LIBRARIES is enforced.
304 // Right now LOCAL_USES_LIBRARIES is opt in, for the case where it's not specified we still default
305 // to the &.
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000306 unknownClassLoaderContext = true
Colin Cross43f08db2018-11-12 10:13:39 -0800307 }
308
Colin Cross69f59a32019-02-15 10:39:37 -0800309 rule.Command().FlagWithArg("mkdir -p ", filepath.Dir(odexPath.String()))
Colin Cross43f08db2018-11-12 10:13:39 -0800310 rule.Command().FlagWithOutput("rm -f ", odexPath)
311 // Set values in the environment of the rule. These may be modified by construct_context.sh.
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000312 if unknownClassLoaderContext {
313 rule.Command().
314 Text(`class_loader_context_arg=--class-loader-context=\&`).
315 Text(`stored_class_loader_context_arg=""`)
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +0000316 } else {
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000317 rule.Command().
318 Text("class_loader_context_arg=--class-loader-context=PCL[" + strings.Join(classLoaderContextHost.Strings(), ":") + "]").
319 Implicits(classLoaderContextHost).
320 Text("stored_class_loader_context_arg=--stored-class-loader-context=PCL[" + strings.Join(classLoaderContextTarget, ":") + "]")
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +0000321 }
Colin Cross43f08db2018-11-12 10:13:39 -0800322
323 if module.EnforceUsesLibraries {
Colin Cross38b96852019-05-22 10:21:09 -0700324 if module.ManifestPath != nil {
325 rule.Command().Text(`target_sdk_version="$(`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000326 Tool(globalSoong.ManifestCheck).
Colin Cross38b96852019-05-22 10:21:09 -0700327 Flag("--extract-target-sdk-version").
328 Input(module.ManifestPath).
329 Text(`)"`)
330 } else {
331 // No manifest to extract targetSdkVersion from, hope that DexJar is an APK
332 rule.Command().Text(`target_sdk_version="$(`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000333 Tool(globalSoong.Aapt).
Colin Cross38b96852019-05-22 10:21:09 -0700334 Flag("dump badging").
335 Input(module.DexPath).
336 Text(`| grep "targetSdkVersion" | sed -n "s/targetSdkVersion:'\(.*\)'/\1/p"`).
337 Text(`)"`)
338 }
Colin Cross69f59a32019-02-15 10:39:37 -0800339 rule.Command().Textf(`dex_preopt_host_libraries="%s"`,
340 strings.Join(classLoaderContextHost.Strings(), " ")).
341 Implicits(classLoaderContextHost)
342 rule.Command().Textf(`dex_preopt_target_libraries="%s"`,
343 strings.Join(classLoaderContextTarget, " "))
344 rule.Command().Textf(`conditional_host_libs_28="%s"`,
345 strings.Join(conditionalClassLoaderContextHost28.Strings(), " ")).
346 Implicits(conditionalClassLoaderContextHost28)
347 rule.Command().Textf(`conditional_target_libs_28="%s"`,
348 strings.Join(conditionalClassLoaderContextTarget28, " "))
349 rule.Command().Textf(`conditional_host_libs_29="%s"`,
350 strings.Join(conditionalClassLoaderContextHost29.Strings(), " ")).
351 Implicits(conditionalClassLoaderContextHost29)
352 rule.Command().Textf(`conditional_target_libs_29="%s"`,
353 strings.Join(conditionalClassLoaderContextTarget29, " "))
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000354 rule.Command().Text("source").Tool(globalSoong.ConstructContext).Input(module.DexPath)
Colin Cross43f08db2018-11-12 10:13:39 -0800355 }
356
Nicolas Geoffray2464ef42019-03-05 14:07:07 +0000357 // Devices that do not have a product partition use a symlink from /product to /system/product.
358 // Because on-device dexopt will see dex locations starting with /product, we change the paths
359 // to mimic this behavior.
360 dexLocationArg := module.DexLocation
361 if strings.HasPrefix(dexLocationArg, "/system/product/") {
362 dexLocationArg = strings.TrimPrefix(dexLocationArg, "/system")
363 }
364
Colin Cross43f08db2018-11-12 10:13:39 -0800365 cmd := rule.Command().
366 Text(`ANDROID_LOG_TAGS="*:e"`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000367 Tool(globalSoong.Dex2oat).
Colin Cross43f08db2018-11-12 10:13:39 -0800368 Flag("--avoid-storing-invocation").
Alex Light5de41962018-12-18 15:16:26 -0800369 FlagWithOutput("--write-invocation-to=", invocationPath).ImplicitOutput(invocationPath).
Colin Cross43f08db2018-11-12 10:13:39 -0800370 Flag("--runtime-arg").FlagWithArg("-Xms", global.Dex2oatXms).
371 Flag("--runtime-arg").FlagWithArg("-Xmx", global.Dex2oatXmx).
Colin Cross800fe132019-02-11 14:21:24 -0800372 Flag("--runtime-arg").FlagWithInputList("-Xbootclasspath:", module.PreoptBootClassPathDexFiles, ":").
373 Flag("--runtime-arg").FlagWithList("-Xbootclasspath-locations:", module.PreoptBootClassPathDexLocations, ":").
Colin Cross43f08db2018-11-12 10:13:39 -0800374 Flag("${class_loader_context_arg}").
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000375 Flag("${stored_class_loader_context_arg}").
Ulya Trafimovich3391a1e2020-01-03 17:33:17 +0000376 FlagWithArg("--boot-image=", strings.Join(module.DexPreoptImageLocations, ":")).Implicits(module.DexPreoptImagesDeps[archIdx].Paths()).
Colin Cross43f08db2018-11-12 10:13:39 -0800377 FlagWithInput("--dex-file=", module.DexPath).
Nicolas Geoffray2464ef42019-03-05 14:07:07 +0000378 FlagWithArg("--dex-location=", dexLocationArg).
Colin Cross43f08db2018-11-12 10:13:39 -0800379 FlagWithOutput("--oat-file=", odexPath).ImplicitOutput(vdexPath).
380 // Pass an empty directory, dex2oat shouldn't be reading arbitrary files
381 FlagWithArg("--android-root=", global.EmptyDirectory).
Colin Cross74ba9622019-02-11 15:11:14 -0800382 FlagWithArg("--instruction-set=", arch.String()).
Colin Cross43f08db2018-11-12 10:13:39 -0800383 FlagWithArg("--instruction-set-variant=", global.CpuVariant[arch]).
384 FlagWithArg("--instruction-set-features=", global.InstructionSetFeatures[arch]).
385 Flag("--no-generate-debug-info").
386 Flag("--generate-build-id").
387 Flag("--abort-on-hard-verifier-error").
388 Flag("--force-determinism").
389 FlagWithArg("--no-inline-from=", "core-oj.jar")
390
391 var preoptFlags []string
392 if len(module.PreoptFlags) > 0 {
393 preoptFlags = module.PreoptFlags
394 } else if len(global.PreoptFlags) > 0 {
395 preoptFlags = global.PreoptFlags
396 }
397
398 if len(preoptFlags) > 0 {
399 cmd.Text(strings.Join(preoptFlags, " "))
400 }
401
402 if module.UncompressedDex {
403 cmd.FlagWithArg("--copy-dex-files=", "false")
404 }
405
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800406 if !android.PrefixInList(preoptFlags, "--compiler-filter=") {
Colin Cross43f08db2018-11-12 10:13:39 -0800407 var compilerFilter string
408 if contains(global.SystemServerJars, module.Name) {
409 // Jars of system server, use the product option if it is set, speed otherwise.
410 if global.SystemServerCompilerFilter != "" {
411 compilerFilter = global.SystemServerCompilerFilter
412 } else {
413 compilerFilter = "speed"
414 }
415 } else if contains(global.SpeedApps, module.Name) || contains(global.SystemServerApps, module.Name) {
416 // Apps loaded into system server, and apps the product default to being compiled with the
417 // 'speed' compiler filter.
418 compilerFilter = "speed"
Colin Cross69f59a32019-02-15 10:39:37 -0800419 } else if profile != nil {
Colin Cross43f08db2018-11-12 10:13:39 -0800420 // For non system server jars, use speed-profile when we have a profile.
421 compilerFilter = "speed-profile"
422 } else if global.DefaultCompilerFilter != "" {
423 compilerFilter = global.DefaultCompilerFilter
424 } else {
425 compilerFilter = "quicken"
426 }
427 cmd.FlagWithArg("--compiler-filter=", compilerFilter)
428 }
429
430 if generateDM {
431 cmd.FlagWithArg("--copy-dex-files=", "false")
Colin Cross69f59a32019-02-15 10:39:37 -0800432 dmPath := module.BuildPath.InSameDir(ctx, "generated.dm")
Colin Cross43f08db2018-11-12 10:13:39 -0800433 dmInstalledPath := pathtools.ReplaceExtension(module.DexLocation, "dm")
Colin Cross69f59a32019-02-15 10:39:37 -0800434 tmpPath := module.BuildPath.InSameDir(ctx, "primary.vdex")
Colin Cross43f08db2018-11-12 10:13:39 -0800435 rule.Command().Text("cp -f").Input(vdexPath).Output(tmpPath)
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000436 rule.Command().Tool(globalSoong.SoongZip).
Colin Cross43f08db2018-11-12 10:13:39 -0800437 FlagWithArg("-L", "9").
438 FlagWithOutput("-o", dmPath).
439 Flag("-j").
440 Input(tmpPath)
441 rule.Install(dmPath, dmInstalledPath)
442 }
443
444 // By default, emit debug info.
445 debugInfo := true
446 if global.NoDebugInfo {
447 // If the global setting suppresses mini-debug-info, disable it.
448 debugInfo = false
449 }
450
451 // PRODUCT_SYSTEM_SERVER_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO.
452 // PRODUCT_OTHER_JAVA_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO.
453 if contains(global.SystemServerJars, module.Name) {
454 if global.AlwaysSystemServerDebugInfo {
455 debugInfo = true
456 } else if global.NeverSystemServerDebugInfo {
457 debugInfo = false
458 }
459 } else {
460 if global.AlwaysOtherDebugInfo {
461 debugInfo = true
462 } else if global.NeverOtherDebugInfo {
463 debugInfo = false
464 }
465 }
466
467 // Never enable on eng.
468 if global.IsEng {
469 debugInfo = false
470 }
471
472 if debugInfo {
473 cmd.Flag("--generate-mini-debug-info")
474 } else {
475 cmd.Flag("--no-generate-mini-debug-info")
476 }
477
478 // Set the compiler reason to 'prebuilt' to identify the oat files produced
479 // during the build, as opposed to compiled on the device.
480 cmd.FlagWithArg("--compilation-reason=", "prebuilt")
481
482 if appImage {
Colin Cross69f59a32019-02-15 10:39:37 -0800483 appImagePath := odexPath.ReplaceExtension(ctx, "art")
Colin Cross43f08db2018-11-12 10:13:39 -0800484 appImageInstallPath := pathtools.ReplaceExtension(odexInstallPath, "art")
485 cmd.FlagWithOutput("--app-image-file=", appImagePath).
486 FlagWithArg("--image-format=", "lz4")
Mathieu Chartier3f7ddbb2019-04-29 09:33:50 -0700487 if !global.DontResolveStartupStrings {
488 cmd.FlagWithArg("--resolve-startup-const-strings=", "true")
489 }
Colin Cross43f08db2018-11-12 10:13:39 -0800490 rule.Install(appImagePath, appImageInstallPath)
491 }
492
Colin Cross69f59a32019-02-15 10:39:37 -0800493 if profile != nil {
494 cmd.FlagWithInput("--profile-file=", profile)
Colin Cross43f08db2018-11-12 10:13:39 -0800495 }
496
497 rule.Install(odexPath, odexInstallPath)
498 rule.Install(vdexPath, vdexInstallPath)
499}
500
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000501func shouldGenerateDM(module *ModuleConfig, global *GlobalConfig) bool {
Colin Cross43f08db2018-11-12 10:13:39 -0800502 // Generating DM files only makes sense for verify, avoid doing for non verify compiler filter APKs.
503 // No reason to use a dm file if the dex is already uncompressed.
504 return global.GenerateDMFiles && !module.UncompressedDex &&
505 contains(module.PreoptFlags, "--compiler-filter=verify")
506}
507
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000508func OdexOnSystemOtherByName(name string, dexLocation string, global *GlobalConfig) bool {
Colin Cross43f08db2018-11-12 10:13:39 -0800509 if !global.HasSystemOther {
510 return false
511 }
512
513 if global.SanitizeLite {
514 return false
515 }
516
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000517 if contains(global.SpeedApps, name) || contains(global.SystemServerApps, name) {
Colin Cross43f08db2018-11-12 10:13:39 -0800518 return false
519 }
520
521 for _, f := range global.PatternsOnSystemOther {
Anton Hanssond57bd3c2019-10-14 16:53:02 +0100522 if makefileMatch(filepath.Join(SystemPartition, f), dexLocation) {
Colin Cross43f08db2018-11-12 10:13:39 -0800523 return true
524 }
525 }
526
527 return false
528}
529
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000530func odexOnSystemOther(module *ModuleConfig, global *GlobalConfig) bool {
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000531 return OdexOnSystemOtherByName(module.Name, module.DexLocation, global)
532}
533
Colin Crossc7e40aa2019-02-08 21:37:00 -0800534// PathToLocation converts .../system/framework/arm64/boot.art to .../system/framework/boot.art
Colin Cross69f59a32019-02-15 10:39:37 -0800535func PathToLocation(path android.Path, arch android.ArchType) string {
536 pathArch := filepath.Base(filepath.Dir(path.String()))
Colin Cross74ba9622019-02-11 15:11:14 -0800537 if pathArch != arch.String() {
538 panic(fmt.Errorf("last directory in %q must be %q", path, arch.String()))
Colin Crossc7e40aa2019-02-08 21:37:00 -0800539 }
Colin Cross69f59a32019-02-15 10:39:37 -0800540 return filepath.Join(filepath.Dir(filepath.Dir(path.String())), filepath.Base(path.String()))
Colin Crossc7e40aa2019-02-08 21:37:00 -0800541}
542
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000543func pathForLibrary(module *ModuleConfig, lib string) android.Path {
Colin Cross69f59a32019-02-15 10:39:37 -0800544 path, ok := module.LibraryPaths[lib]
545 if !ok {
Colin Cross43f08db2018-11-12 10:13:39 -0800546 panic(fmt.Errorf("unknown library path for %q", lib))
547 }
548 return path
549}
550
551func makefileMatch(pattern, s string) bool {
552 percent := strings.IndexByte(pattern, '%')
553 switch percent {
554 case -1:
555 return pattern == s
556 case len(pattern) - 1:
557 return strings.HasPrefix(s, pattern[:len(pattern)-1])
558 default:
559 panic(fmt.Errorf("unsupported makefile pattern %q", pattern))
560 }
561}
562
Ulyana Trafimovichf2cb7e92019-11-27 12:26:49 +0000563// Expected format for apexJarValue = <apex name>:<jar name>
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000564func GetJarLocationFromApexJarPair(apexJarValue string) string {
Ulya Trafimovich4cdada22020-02-10 15:29:28 +0000565 apex, jar := android.SplitApexJarPair(apexJarValue)
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000566 return filepath.Join("/apex", apex, "javalib", jar+".jar")
Roshan Piusccc26ef2019-11-27 09:37:46 -0800567}
568
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +0000569var nonUpdatableSystemServerJarsKey = android.NewOnceKey("nonUpdatableSystemServerJars")
570
571// TODO: eliminate the superficial global config parameter by moving global config definition
572// from java subpackage to dexpreopt.
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000573func NonUpdatableSystemServerJars(ctx android.PathContext, global *GlobalConfig) []string {
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +0000574 return ctx.Config().Once(nonUpdatableSystemServerJarsKey, func() interface{} {
575 return android.RemoveListFromList(global.SystemServerJars,
Ulya Trafimovich50c4a4b2020-04-21 15:36:33 +0100576 android.GetJarsFromApexJarPairs(global.UpdatableSystemServerJars))
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +0000577 }).([]string)
578}
579
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000580// A predefined location for the system server dex jars. This is needed in order to generate
581// class loader context for dex2oat, as the path to the jar in the Soong module may be unknown
582// at that time (Soong processes the jars in dependency order, which may be different from the
583// the system server classpath order).
584func SystemServerDexJarHostPath(ctx android.PathContext, jar string) android.OutputPath {
Ulya Trafimovich6cf2c0c2020-04-24 12:15:20 +0100585 if DexpreoptRunningInSoong {
586 // Soong module, just use the default output directory $OUT/soong.
587 return android.PathForOutput(ctx, "system_server_dexjars", jar+".jar")
588 } else {
589 // Make module, default output directory is $OUT (passed via the "null config" created
590 // by dexpreopt_gen). Append Soong subdirectory to match Soong module paths.
591 return android.PathForOutput(ctx, "soong", "system_server_dexjars", jar+".jar")
592 }
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000593}
594
Colin Cross43f08db2018-11-12 10:13:39 -0800595func contains(l []string, s string) bool {
596 for _, e := range l {
597 if e == s {
598 return true
599 }
600 }
601 return false
602}
603
Colin Cross454c0872019-02-15 23:03:34 -0800604var copyOf = android.CopyOf