blob: 0e1bfc615c9fe211368fd4ce1b13e027973d503f [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
Colin Cross43f08db2018-11-12 10:13:39 -080050// GenerateDexpreoptRule generates a set of commands that will preopt a module based on a GlobalConfig and a
51// ModuleConfig. The produced files and their install locations will be available through rule.Installs().
Martin Stjernholm8d80cee2020-01-31 17:44:54 +000052func GenerateDexpreoptRule(ctx android.PathContext, globalSoong *GlobalSoongConfig,
53 global *GlobalConfig, module *ModuleConfig) (rule *android.RuleBuilder, err error) {
Colin Cross69f59a32019-02-15 10:39:37 -080054
Colin Cross43f08db2018-11-12 10:13:39 -080055 defer func() {
56 if r := recover(); r != nil {
Colin Cross69f59a32019-02-15 10:39:37 -080057 if _, ok := r.(runtime.Error); ok {
58 panic(r)
59 } else if e, ok := r.(error); ok {
Colin Cross43f08db2018-11-12 10:13:39 -080060 err = e
61 rule = nil
62 } else {
63 panic(r)
64 }
65 }
66 }()
67
Colin Cross758290d2019-02-01 16:42:32 -080068 rule = android.NewRuleBuilder()
Colin Cross43f08db2018-11-12 10:13:39 -080069
Colin Cross69f59a32019-02-15 10:39:37 -080070 generateProfile := module.ProfileClassListing.Valid() && !global.DisableGenerateProfile
Nicolas Geoffraye7102422019-07-24 13:19:29 +010071 generateBootProfile := module.ProfileBootListing.Valid() && !global.DisableGenerateProfile
Colin Cross43f08db2018-11-12 10:13:39 -080072
Colin Cross69f59a32019-02-15 10:39:37 -080073 var profile android.WritablePath
Colin Crosscbed6572019-01-08 17:38:37 -080074 if generateProfile {
Martin Stjernholm75a48d82020-01-10 20:32:59 +000075 profile = profileCommand(ctx, globalSoong, global, module, rule)
Colin Crosscbed6572019-01-08 17:38:37 -080076 }
Nicolas Geoffraye7102422019-07-24 13:19:29 +010077 if generateBootProfile {
Martin Stjernholm75a48d82020-01-10 20:32:59 +000078 bootProfileCommand(ctx, globalSoong, global, module, rule)
Nicolas Geoffraye7102422019-07-24 13:19:29 +010079 }
Colin Crosscbed6572019-01-08 17:38:37 -080080
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +000081 if !dexpreoptDisabled(ctx, global, module) {
Colin Crosscbed6572019-01-08 17:38:37 -080082 // Don't preopt individual boot jars, they will be preopted together.
Colin Crosscbed6572019-01-08 17:38:37 -080083 if !contains(global.BootJars, module.Name) {
84 appImage := (generateProfile || module.ForceCreateAppImage || global.DefaultAppImages) &&
85 !module.NoCreateAppImage
86
87 generateDM := shouldGenerateDM(module, global)
88
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +000089 for archIdx, _ := range module.Archs {
Martin Stjernholm75a48d82020-01-10 20:32:59 +000090 dexpreoptCommand(ctx, globalSoong, global, module, rule, archIdx, profile, appImage, generateDM)
Colin Crosscbed6572019-01-08 17:38:37 -080091 }
92 }
93 }
94
95 return rule, nil
96}
97
Martin Stjernholm8d80cee2020-01-31 17:44:54 +000098func dexpreoptDisabled(ctx android.PathContext, global *GlobalConfig, module *ModuleConfig) bool {
Colin Crosscbed6572019-01-08 17:38:37 -080099 if contains(global.DisablePreoptModules, module.Name) {
100 return true
Colin Cross43f08db2018-11-12 10:13:39 -0800101 }
102
Ulyana Trafimovichf2cb7e92019-11-27 12:26:49 +0000103 // Don't preopt system server jars that are updatable.
104 for _, p := range global.UpdatableSystemServerJars {
Ulya Trafimovich4cdada22020-02-10 15:29:28 +0000105 if _, jar := android.SplitApexJarPair(p); jar == module.Name {
Ulyana Trafimovichf2cb7e92019-11-27 12:26:49 +0000106 return true
107 }
108 }
109
Colin Cross43f08db2018-11-12 10:13:39 -0800110 // If OnlyPreoptBootImageAndSystemServer=true and module is not in boot class path skip
111 // Also preopt system server jars since selinux prevents system server from loading anything from
112 // /data. If we don't do this they will need to be extracted which is not favorable for RAM usage
113 // or performance. If PreoptExtractedApk is true, we ignore the only preopt boot image options.
114 if global.OnlyPreoptBootImageAndSystemServer && !contains(global.BootJars, module.Name) &&
115 !contains(global.SystemServerJars, module.Name) && !module.PreoptExtractedApk {
Colin Crosscbed6572019-01-08 17:38:37 -0800116 return true
Colin Cross43f08db2018-11-12 10:13:39 -0800117 }
118
Colin Crosscbed6572019-01-08 17:38:37 -0800119 return false
Colin Cross43f08db2018-11-12 10:13:39 -0800120}
121
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000122func profileCommand(ctx android.PathContext, globalSoong *GlobalSoongConfig, global *GlobalConfig,
123 module *ModuleConfig, rule *android.RuleBuilder) android.WritablePath {
Colin Cross69f59a32019-02-15 10:39:37 -0800124
125 profilePath := module.BuildPath.InSameDir(ctx, "profile.prof")
Colin Cross43f08db2018-11-12 10:13:39 -0800126 profileInstalledPath := module.DexLocation + ".prof"
127
128 if !module.ProfileIsTextListing {
129 rule.Command().FlagWithOutput("touch ", profilePath)
130 }
131
132 cmd := rule.Command().
133 Text(`ANDROID_LOG_TAGS="*:e"`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000134 Tool(globalSoong.Profman)
Colin Cross43f08db2018-11-12 10:13:39 -0800135
136 if module.ProfileIsTextListing {
137 // The profile is a test listing of classes (used for framework jars).
138 // We need to generate the actual binary profile before being able to compile.
Colin Cross69f59a32019-02-15 10:39:37 -0800139 cmd.FlagWithInput("--create-profile-from=", module.ProfileClassListing.Path())
Colin Cross43f08db2018-11-12 10:13:39 -0800140 } else {
141 // The profile is binary profile (used for apps). Run it through profman to
142 // ensure the profile keys match the apk.
143 cmd.
144 Flag("--copy-and-update-profile-key").
Colin Cross69f59a32019-02-15 10:39:37 -0800145 FlagWithInput("--profile-file=", module.ProfileClassListing.Path())
Colin Cross43f08db2018-11-12 10:13:39 -0800146 }
147
148 cmd.
149 FlagWithInput("--apk=", module.DexPath).
150 Flag("--dex-location="+module.DexLocation).
151 FlagWithOutput("--reference-profile-file=", profilePath)
152
153 if !module.ProfileIsTextListing {
154 cmd.Text(fmt.Sprintf(`|| echo "Profile out of date for %s"`, module.DexPath))
155 }
156 rule.Install(profilePath, profileInstalledPath)
157
158 return profilePath
159}
160
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000161func bootProfileCommand(ctx android.PathContext, globalSoong *GlobalSoongConfig, global *GlobalConfig,
162 module *ModuleConfig, rule *android.RuleBuilder) android.WritablePath {
Nicolas Geoffraye7102422019-07-24 13:19:29 +0100163
164 profilePath := module.BuildPath.InSameDir(ctx, "profile.bprof")
165 profileInstalledPath := module.DexLocation + ".bprof"
166
167 if !module.ProfileIsTextListing {
168 rule.Command().FlagWithOutput("touch ", profilePath)
169 }
170
171 cmd := rule.Command().
172 Text(`ANDROID_LOG_TAGS="*:e"`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000173 Tool(globalSoong.Profman)
Nicolas Geoffraye7102422019-07-24 13:19:29 +0100174
175 // The profile is a test listing of methods.
176 // We need to generate the actual binary profile.
177 cmd.FlagWithInput("--create-profile-from=", module.ProfileBootListing.Path())
178
179 cmd.
180 Flag("--generate-boot-profile").
181 FlagWithInput("--apk=", module.DexPath).
182 Flag("--dex-location="+module.DexLocation).
183 FlagWithOutput("--reference-profile-file=", profilePath)
184
185 if !module.ProfileIsTextListing {
186 cmd.Text(fmt.Sprintf(`|| echo "Profile out of date for %s"`, module.DexPath))
187 }
188 rule.Install(profilePath, profileInstalledPath)
189
190 return profilePath
191}
192
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000193func dexpreoptCommand(ctx android.PathContext, globalSoong *GlobalSoongConfig, global *GlobalConfig,
194 module *ModuleConfig, rule *android.RuleBuilder, archIdx int, profile android.WritablePath,
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000195 appImage bool, generateDM bool) {
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000196
197 arch := module.Archs[archIdx]
Colin Cross43f08db2018-11-12 10:13:39 -0800198
199 // HACK: make soname in Soong-generated .odex files match Make.
200 base := filepath.Base(module.DexLocation)
201 if filepath.Ext(base) == ".jar" {
202 base = "javalib.jar"
203 } else if filepath.Ext(base) == ".apk" {
204 base = "package.apk"
205 }
206
207 toOdexPath := func(path string) string {
208 return filepath.Join(
209 filepath.Dir(path),
210 "oat",
Colin Cross74ba9622019-02-11 15:11:14 -0800211 arch.String(),
Colin Cross43f08db2018-11-12 10:13:39 -0800212 pathtools.ReplaceExtension(filepath.Base(path), "odex"))
213 }
214
Colin Cross69f59a32019-02-15 10:39:37 -0800215 odexPath := module.BuildPath.InSameDir(ctx, "oat", arch.String(), pathtools.ReplaceExtension(base, "odex"))
Colin Cross43f08db2018-11-12 10:13:39 -0800216 odexInstallPath := toOdexPath(module.DexLocation)
217 if odexOnSystemOther(module, global) {
Anton Hansson43ab0bc2019-10-03 14:18:45 +0100218 odexInstallPath = filepath.Join(SystemOtherPartition, odexInstallPath)
Colin Cross43f08db2018-11-12 10:13:39 -0800219 }
220
Colin Cross69f59a32019-02-15 10:39:37 -0800221 vdexPath := odexPath.ReplaceExtension(ctx, "vdex")
Colin Cross43f08db2018-11-12 10:13:39 -0800222 vdexInstallPath := pathtools.ReplaceExtension(odexInstallPath, "vdex")
223
Colin Cross69f59a32019-02-15 10:39:37 -0800224 invocationPath := odexPath.ReplaceExtension(ctx, "invocation")
Alex Light5de41962018-12-18 15:16:26 -0800225
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000226 systemServerJars := NonUpdatableSystemServerJars(ctx, global)
227
Colin Cross43f08db2018-11-12 10:13:39 -0800228 // The class loader context using paths in the build
Colin Cross69f59a32019-02-15 10:39:37 -0800229 var classLoaderContextHost android.Paths
Colin Cross43f08db2018-11-12 10:13:39 -0800230
231 // The class loader context using paths as they will be on the device
232 var classLoaderContextTarget []string
233
234 // Extra paths that will be appended to the class loader if the APK manifest has targetSdkVersion < 28
Colin Cross69f59a32019-02-15 10:39:37 -0800235 var conditionalClassLoaderContextHost28 android.Paths
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000236 var conditionalClassLoaderContextTarget28 []string
237
238 // Extra paths that will be appended to the class loader if the APK manifest has targetSdkVersion < 29
Colin Cross69f59a32019-02-15 10:39:37 -0800239 var conditionalClassLoaderContextHost29 android.Paths
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000240 var conditionalClassLoaderContextTarget29 []string
Colin Cross43f08db2018-11-12 10:13:39 -0800241
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000242 // A flag indicating if the '&' class loader context is used.
243 unknownClassLoaderContext := false
Colin Cross69f59a32019-02-15 10:39:37 -0800244
Colin Cross43f08db2018-11-12 10:13:39 -0800245 if module.EnforceUsesLibraries {
Colin Cross50ddcc42019-05-16 12:28:22 -0700246 usesLibs := append(copyOf(module.UsesLibraries), module.PresentOptionalUsesLibraries...)
Colin Cross43f08db2018-11-12 10:13:39 -0800247
248 // Create class loader context for dex2oat from uses libraries and filtered optional libraries
Colin Cross50ddcc42019-05-16 12:28:22 -0700249 for _, l := range usesLibs {
Colin Cross43f08db2018-11-12 10:13:39 -0800250
251 classLoaderContextHost = append(classLoaderContextHost,
252 pathForLibrary(module, l))
253 classLoaderContextTarget = append(classLoaderContextTarget,
254 filepath.Join("/system/framework", l+".jar"))
255 }
256
257 const httpLegacy = "org.apache.http.legacy"
258 const httpLegacyImpl = "org.apache.http.legacy.impl"
259
Colin Cross38b96852019-05-22 10:21:09 -0700260 // org.apache.http.legacy contains classes that were in the default classpath until API 28. If the
261 // targetSdkVersion in the manifest or APK is < 28, and the module does not explicitly depend on
262 // org.apache.http.legacy, then implicitly add the classes to the classpath for dexpreopt. One the
263 // device the classes will be in a file called org.apache.http.legacy.impl.jar.
Colin Cross50ddcc42019-05-16 12:28:22 -0700264 module.LibraryPaths[httpLegacyImpl] = module.LibraryPaths[httpLegacy]
265
266 if !contains(module.UsesLibraries, httpLegacy) && !contains(module.PresentOptionalUsesLibraries, httpLegacy) {
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000267 conditionalClassLoaderContextHost28 = append(conditionalClassLoaderContextHost28,
Colin Cross43f08db2018-11-12 10:13:39 -0800268 pathForLibrary(module, httpLegacyImpl))
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000269 conditionalClassLoaderContextTarget28 = append(conditionalClassLoaderContextTarget28,
Colin Cross43f08db2018-11-12 10:13:39 -0800270 filepath.Join("/system/framework", httpLegacyImpl+".jar"))
271 }
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000272
273 const hidlBase = "android.hidl.base-V1.0-java"
274 const hidlManager = "android.hidl.manager-V1.0-java"
275
Colin Cross38b96852019-05-22 10:21:09 -0700276 // android.hidl.base-V1.0-java and android.hidl.manager-V1.0 contain classes that were in the default
277 // classpath until API 29. If the targetSdkVersion in the manifest or APK is < 29 then implicitly add
278 // the classes to the classpath for dexpreopt.
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000279 conditionalClassLoaderContextHost29 = append(conditionalClassLoaderContextHost29,
Alex Light5de41962018-12-18 15:16:26 -0800280 pathForLibrary(module, hidlManager))
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000281 conditionalClassLoaderContextTarget29 = append(conditionalClassLoaderContextTarget29,
282 filepath.Join("/system/framework", hidlManager+".jar"))
283 conditionalClassLoaderContextHost29 = append(conditionalClassLoaderContextHost29,
Alex Light5de41962018-12-18 15:16:26 -0800284 pathForLibrary(module, hidlBase))
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000285 conditionalClassLoaderContextTarget29 = append(conditionalClassLoaderContextTarget29,
286 filepath.Join("/system/framework", hidlBase+".jar"))
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000287 } else if jarIndex := android.IndexList(module.Name, systemServerJars); jarIndex >= 0 {
288 // System server jars should be dexpreopted together: class loader context of each jar
289 // should include all preceding jars on the system server classpath.
290 for _, otherJar := range systemServerJars[:jarIndex] {
291 classLoaderContextHost = append(classLoaderContextHost, SystemServerDexJarHostPath(ctx, otherJar))
292 classLoaderContextTarget = append(classLoaderContextTarget, "/system/framework/"+otherJar+".jar")
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +0000293 }
294
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000295 // Copy the system server jar to a predefined location where dex2oat will find it.
296 dexPathHost := SystemServerDexJarHostPath(ctx, module.Name)
297 rule.Command().Text("mkdir -p").Flag(filepath.Dir(dexPathHost.String()))
298 rule.Command().Text("cp -f").Input(module.DexPath).Output(dexPathHost)
Colin Cross43f08db2018-11-12 10:13:39 -0800299 } else {
300 // Pass special class loader context to skip the classpath and collision check.
301 // This will get removed once LOCAL_USES_LIBRARIES is enforced.
302 // Right now LOCAL_USES_LIBRARIES is opt in, for the case where it's not specified we still default
303 // to the &.
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000304 unknownClassLoaderContext = true
Colin Cross43f08db2018-11-12 10:13:39 -0800305 }
306
Colin Cross69f59a32019-02-15 10:39:37 -0800307 rule.Command().FlagWithArg("mkdir -p ", filepath.Dir(odexPath.String()))
Colin Cross43f08db2018-11-12 10:13:39 -0800308 rule.Command().FlagWithOutput("rm -f ", odexPath)
309 // Set values in the environment of the rule. These may be modified by construct_context.sh.
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000310 if unknownClassLoaderContext {
311 rule.Command().
312 Text(`class_loader_context_arg=--class-loader-context=\&`).
313 Text(`stored_class_loader_context_arg=""`)
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +0000314 } else {
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000315 rule.Command().
316 Text("class_loader_context_arg=--class-loader-context=PCL[" + strings.Join(classLoaderContextHost.Strings(), ":") + "]").
317 Implicits(classLoaderContextHost).
318 Text("stored_class_loader_context_arg=--stored-class-loader-context=PCL[" + strings.Join(classLoaderContextTarget, ":") + "]")
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +0000319 }
Colin Cross43f08db2018-11-12 10:13:39 -0800320
321 if module.EnforceUsesLibraries {
Colin Cross38b96852019-05-22 10:21:09 -0700322 if module.ManifestPath != nil {
323 rule.Command().Text(`target_sdk_version="$(`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000324 Tool(globalSoong.ManifestCheck).
Colin Cross38b96852019-05-22 10:21:09 -0700325 Flag("--extract-target-sdk-version").
326 Input(module.ManifestPath).
327 Text(`)"`)
328 } else {
329 // No manifest to extract targetSdkVersion from, hope that DexJar is an APK
330 rule.Command().Text(`target_sdk_version="$(`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000331 Tool(globalSoong.Aapt).
Colin Cross38b96852019-05-22 10:21:09 -0700332 Flag("dump badging").
333 Input(module.DexPath).
334 Text(`| grep "targetSdkVersion" | sed -n "s/targetSdkVersion:'\(.*\)'/\1/p"`).
335 Text(`)"`)
336 }
Colin Cross69f59a32019-02-15 10:39:37 -0800337 rule.Command().Textf(`dex_preopt_host_libraries="%s"`,
338 strings.Join(classLoaderContextHost.Strings(), " ")).
339 Implicits(classLoaderContextHost)
340 rule.Command().Textf(`dex_preopt_target_libraries="%s"`,
341 strings.Join(classLoaderContextTarget, " "))
342 rule.Command().Textf(`conditional_host_libs_28="%s"`,
343 strings.Join(conditionalClassLoaderContextHost28.Strings(), " ")).
344 Implicits(conditionalClassLoaderContextHost28)
345 rule.Command().Textf(`conditional_target_libs_28="%s"`,
346 strings.Join(conditionalClassLoaderContextTarget28, " "))
347 rule.Command().Textf(`conditional_host_libs_29="%s"`,
348 strings.Join(conditionalClassLoaderContextHost29.Strings(), " ")).
349 Implicits(conditionalClassLoaderContextHost29)
350 rule.Command().Textf(`conditional_target_libs_29="%s"`,
351 strings.Join(conditionalClassLoaderContextTarget29, " "))
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000352 rule.Command().Text("source").Tool(globalSoong.ConstructContext).Input(module.DexPath)
Colin Cross43f08db2018-11-12 10:13:39 -0800353 }
354
Nicolas Geoffray2464ef42019-03-05 14:07:07 +0000355 // Devices that do not have a product partition use a symlink from /product to /system/product.
356 // Because on-device dexopt will see dex locations starting with /product, we change the paths
357 // to mimic this behavior.
358 dexLocationArg := module.DexLocation
359 if strings.HasPrefix(dexLocationArg, "/system/product/") {
360 dexLocationArg = strings.TrimPrefix(dexLocationArg, "/system")
361 }
362
Colin Cross43f08db2018-11-12 10:13:39 -0800363 cmd := rule.Command().
364 Text(`ANDROID_LOG_TAGS="*:e"`).
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000365 Tool(globalSoong.Dex2oat).
Colin Cross43f08db2018-11-12 10:13:39 -0800366 Flag("--avoid-storing-invocation").
Alex Light5de41962018-12-18 15:16:26 -0800367 FlagWithOutput("--write-invocation-to=", invocationPath).ImplicitOutput(invocationPath).
Colin Cross43f08db2018-11-12 10:13:39 -0800368 Flag("--runtime-arg").FlagWithArg("-Xms", global.Dex2oatXms).
369 Flag("--runtime-arg").FlagWithArg("-Xmx", global.Dex2oatXmx).
Colin Cross800fe132019-02-11 14:21:24 -0800370 Flag("--runtime-arg").FlagWithInputList("-Xbootclasspath:", module.PreoptBootClassPathDexFiles, ":").
371 Flag("--runtime-arg").FlagWithList("-Xbootclasspath-locations:", module.PreoptBootClassPathDexLocations, ":").
Colin Cross43f08db2018-11-12 10:13:39 -0800372 Flag("${class_loader_context_arg}").
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000373 Flag("${stored_class_loader_context_arg}").
Ulya Trafimovich3391a1e2020-01-03 17:33:17 +0000374 FlagWithArg("--boot-image=", strings.Join(module.DexPreoptImageLocations, ":")).Implicits(module.DexPreoptImagesDeps[archIdx].Paths()).
Colin Cross43f08db2018-11-12 10:13:39 -0800375 FlagWithInput("--dex-file=", module.DexPath).
Nicolas Geoffray2464ef42019-03-05 14:07:07 +0000376 FlagWithArg("--dex-location=", dexLocationArg).
Colin Cross43f08db2018-11-12 10:13:39 -0800377 FlagWithOutput("--oat-file=", odexPath).ImplicitOutput(vdexPath).
378 // Pass an empty directory, dex2oat shouldn't be reading arbitrary files
379 FlagWithArg("--android-root=", global.EmptyDirectory).
Colin Cross74ba9622019-02-11 15:11:14 -0800380 FlagWithArg("--instruction-set=", arch.String()).
Colin Cross43f08db2018-11-12 10:13:39 -0800381 FlagWithArg("--instruction-set-variant=", global.CpuVariant[arch]).
382 FlagWithArg("--instruction-set-features=", global.InstructionSetFeatures[arch]).
383 Flag("--no-generate-debug-info").
384 Flag("--generate-build-id").
385 Flag("--abort-on-hard-verifier-error").
386 Flag("--force-determinism").
387 FlagWithArg("--no-inline-from=", "core-oj.jar")
388
389 var preoptFlags []string
390 if len(module.PreoptFlags) > 0 {
391 preoptFlags = module.PreoptFlags
392 } else if len(global.PreoptFlags) > 0 {
393 preoptFlags = global.PreoptFlags
394 }
395
396 if len(preoptFlags) > 0 {
397 cmd.Text(strings.Join(preoptFlags, " "))
398 }
399
400 if module.UncompressedDex {
401 cmd.FlagWithArg("--copy-dex-files=", "false")
402 }
403
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800404 if !android.PrefixInList(preoptFlags, "--compiler-filter=") {
Colin Cross43f08db2018-11-12 10:13:39 -0800405 var compilerFilter string
406 if contains(global.SystemServerJars, module.Name) {
407 // Jars of system server, use the product option if it is set, speed otherwise.
408 if global.SystemServerCompilerFilter != "" {
409 compilerFilter = global.SystemServerCompilerFilter
410 } else {
411 compilerFilter = "speed"
412 }
413 } else if contains(global.SpeedApps, module.Name) || contains(global.SystemServerApps, module.Name) {
414 // Apps loaded into system server, and apps the product default to being compiled with the
415 // 'speed' compiler filter.
416 compilerFilter = "speed"
Colin Cross69f59a32019-02-15 10:39:37 -0800417 } else if profile != nil {
Colin Cross43f08db2018-11-12 10:13:39 -0800418 // For non system server jars, use speed-profile when we have a profile.
419 compilerFilter = "speed-profile"
420 } else if global.DefaultCompilerFilter != "" {
421 compilerFilter = global.DefaultCompilerFilter
422 } else {
423 compilerFilter = "quicken"
424 }
425 cmd.FlagWithArg("--compiler-filter=", compilerFilter)
426 }
427
428 if generateDM {
429 cmd.FlagWithArg("--copy-dex-files=", "false")
Colin Cross69f59a32019-02-15 10:39:37 -0800430 dmPath := module.BuildPath.InSameDir(ctx, "generated.dm")
Colin Cross43f08db2018-11-12 10:13:39 -0800431 dmInstalledPath := pathtools.ReplaceExtension(module.DexLocation, "dm")
Colin Cross69f59a32019-02-15 10:39:37 -0800432 tmpPath := module.BuildPath.InSameDir(ctx, "primary.vdex")
Colin Cross43f08db2018-11-12 10:13:39 -0800433 rule.Command().Text("cp -f").Input(vdexPath).Output(tmpPath)
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000434 rule.Command().Tool(globalSoong.SoongZip).
Colin Cross43f08db2018-11-12 10:13:39 -0800435 FlagWithArg("-L", "9").
436 FlagWithOutput("-o", dmPath).
437 Flag("-j").
438 Input(tmpPath)
439 rule.Install(dmPath, dmInstalledPath)
440 }
441
442 // By default, emit debug info.
443 debugInfo := true
444 if global.NoDebugInfo {
445 // If the global setting suppresses mini-debug-info, disable it.
446 debugInfo = false
447 }
448
449 // PRODUCT_SYSTEM_SERVER_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO.
450 // PRODUCT_OTHER_JAVA_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO.
451 if contains(global.SystemServerJars, module.Name) {
452 if global.AlwaysSystemServerDebugInfo {
453 debugInfo = true
454 } else if global.NeverSystemServerDebugInfo {
455 debugInfo = false
456 }
457 } else {
458 if global.AlwaysOtherDebugInfo {
459 debugInfo = true
460 } else if global.NeverOtherDebugInfo {
461 debugInfo = false
462 }
463 }
464
465 // Never enable on eng.
466 if global.IsEng {
467 debugInfo = false
468 }
469
470 if debugInfo {
471 cmd.Flag("--generate-mini-debug-info")
472 } else {
473 cmd.Flag("--no-generate-mini-debug-info")
474 }
475
476 // Set the compiler reason to 'prebuilt' to identify the oat files produced
477 // during the build, as opposed to compiled on the device.
478 cmd.FlagWithArg("--compilation-reason=", "prebuilt")
479
480 if appImage {
Colin Cross69f59a32019-02-15 10:39:37 -0800481 appImagePath := odexPath.ReplaceExtension(ctx, "art")
Colin Cross43f08db2018-11-12 10:13:39 -0800482 appImageInstallPath := pathtools.ReplaceExtension(odexInstallPath, "art")
483 cmd.FlagWithOutput("--app-image-file=", appImagePath).
484 FlagWithArg("--image-format=", "lz4")
Mathieu Chartier3f7ddbb2019-04-29 09:33:50 -0700485 if !global.DontResolveStartupStrings {
486 cmd.FlagWithArg("--resolve-startup-const-strings=", "true")
487 }
Colin Cross43f08db2018-11-12 10:13:39 -0800488 rule.Install(appImagePath, appImageInstallPath)
489 }
490
Colin Cross69f59a32019-02-15 10:39:37 -0800491 if profile != nil {
492 cmd.FlagWithInput("--profile-file=", profile)
Colin Cross43f08db2018-11-12 10:13:39 -0800493 }
494
495 rule.Install(odexPath, odexInstallPath)
496 rule.Install(vdexPath, vdexInstallPath)
497}
498
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000499func shouldGenerateDM(module *ModuleConfig, global *GlobalConfig) bool {
Colin Cross43f08db2018-11-12 10:13:39 -0800500 // Generating DM files only makes sense for verify, avoid doing for non verify compiler filter APKs.
501 // No reason to use a dm file if the dex is already uncompressed.
502 return global.GenerateDMFiles && !module.UncompressedDex &&
503 contains(module.PreoptFlags, "--compiler-filter=verify")
504}
505
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000506func OdexOnSystemOtherByName(name string, dexLocation string, global *GlobalConfig) bool {
Colin Cross43f08db2018-11-12 10:13:39 -0800507 if !global.HasSystemOther {
508 return false
509 }
510
511 if global.SanitizeLite {
512 return false
513 }
514
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000515 if contains(global.SpeedApps, name) || contains(global.SystemServerApps, name) {
Colin Cross43f08db2018-11-12 10:13:39 -0800516 return false
517 }
518
519 for _, f := range global.PatternsOnSystemOther {
Anton Hanssond57bd3c2019-10-14 16:53:02 +0100520 if makefileMatch(filepath.Join(SystemPartition, f), dexLocation) {
Colin Cross43f08db2018-11-12 10:13:39 -0800521 return true
522 }
523 }
524
525 return false
526}
527
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000528func odexOnSystemOther(module *ModuleConfig, global *GlobalConfig) bool {
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000529 return OdexOnSystemOtherByName(module.Name, module.DexLocation, global)
530}
531
Colin Crossc7e40aa2019-02-08 21:37:00 -0800532// PathToLocation converts .../system/framework/arm64/boot.art to .../system/framework/boot.art
Colin Cross69f59a32019-02-15 10:39:37 -0800533func PathToLocation(path android.Path, arch android.ArchType) string {
534 pathArch := filepath.Base(filepath.Dir(path.String()))
Colin Cross74ba9622019-02-11 15:11:14 -0800535 if pathArch != arch.String() {
536 panic(fmt.Errorf("last directory in %q must be %q", path, arch.String()))
Colin Crossc7e40aa2019-02-08 21:37:00 -0800537 }
Colin Cross69f59a32019-02-15 10:39:37 -0800538 return filepath.Join(filepath.Dir(filepath.Dir(path.String())), filepath.Base(path.String()))
Colin Crossc7e40aa2019-02-08 21:37:00 -0800539}
540
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000541func pathForLibrary(module *ModuleConfig, lib string) android.Path {
Colin Cross69f59a32019-02-15 10:39:37 -0800542 path, ok := module.LibraryPaths[lib]
543 if !ok {
Colin Cross43f08db2018-11-12 10:13:39 -0800544 panic(fmt.Errorf("unknown library path for %q", lib))
545 }
546 return path
547}
548
549func makefileMatch(pattern, s string) bool {
550 percent := strings.IndexByte(pattern, '%')
551 switch percent {
552 case -1:
553 return pattern == s
554 case len(pattern) - 1:
555 return strings.HasPrefix(s, pattern[:len(pattern)-1])
556 default:
557 panic(fmt.Errorf("unsupported makefile pattern %q", pattern))
558 }
559}
560
Ulyana Trafimovichf2cb7e92019-11-27 12:26:49 +0000561// Expected format for apexJarValue = <apex name>:<jar name>
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000562func GetJarLocationFromApexJarPair(apexJarValue string) string {
Ulya Trafimovich4cdada22020-02-10 15:29:28 +0000563 apex, jar := android.SplitApexJarPair(apexJarValue)
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000564 return filepath.Join("/apex", apex, "javalib", jar+".jar")
Roshan Piusccc26ef2019-11-27 09:37:46 -0800565}
566
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +0000567func GetJarsFromApexJarPairs(apexJarPairs []string) []string {
568 modules := make([]string, len(apexJarPairs))
569 for i, p := range apexJarPairs {
570 _, jar := android.SplitApexJarPair(p)
571 modules[i] = jar
572 }
573 return modules
574}
575
576var nonUpdatableSystemServerJarsKey = android.NewOnceKey("nonUpdatableSystemServerJars")
577
578// TODO: eliminate the superficial global config parameter by moving global config definition
579// from java subpackage to dexpreopt.
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000580func NonUpdatableSystemServerJars(ctx android.PathContext, global *GlobalConfig) []string {
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +0000581 return ctx.Config().Once(nonUpdatableSystemServerJarsKey, func() interface{} {
582 return android.RemoveListFromList(global.SystemServerJars,
583 GetJarsFromApexJarPairs(global.UpdatableSystemServerJars))
584 }).([]string)
585}
586
Ulya Trafimovichdacc6c52020-03-11 11:59:34 +0000587// A predefined location for the system server dex jars. This is needed in order to generate
588// class loader context for dex2oat, as the path to the jar in the Soong module may be unknown
589// at that time (Soong processes the jars in dependency order, which may be different from the
590// the system server classpath order).
591func SystemServerDexJarHostPath(ctx android.PathContext, jar string) android.OutputPath {
Ulya Trafimovich55285ba2020-03-24 13:59:24 +0000592 return android.PathForOutput(ctx, "system_server_dexjars", jar+".jar")
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