blob: 4d8ccb5fb61e7bda212227df41d048638412b23f [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
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +000044 "github.com/google/blueprint"
Colin Cross43f08db2018-11-12 10:13:39 -080045 "github.com/google/blueprint/pathtools"
46)
47
48const SystemPartition = "/system/"
49const SystemOtherPartition = "/system_other/"
50
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +000051type dependencyTag struct {
52 blueprint.BaseDependencyTag
53 name string
54}
55
56var SystemServerDepTag = dependencyTag{name: "system-server-dep"}
57var SystemServerForcedDepTag = dependencyTag{name: "system-server-forced-dep"}
58
Colin Cross43f08db2018-11-12 10:13:39 -080059// GenerateDexpreoptRule generates a set of commands that will preopt a module based on a GlobalConfig and a
60// ModuleConfig. The produced files and their install locations will be available through rule.Installs().
Hans Boehme4b53422020-01-25 01:44:30 +000061func GenerateDexpreoptRule(ctx android.PathContext,
Colin Cross69f59a32019-02-15 10:39:37 -080062 global GlobalConfig, module ModuleConfig) (rule *android.RuleBuilder, err error) {
63
Colin Cross43f08db2018-11-12 10:13:39 -080064 defer func() {
65 if r := recover(); r != nil {
Colin Cross69f59a32019-02-15 10:39:37 -080066 if _, ok := r.(runtime.Error); ok {
67 panic(r)
68 } else if e, ok := r.(error); ok {
Colin Cross43f08db2018-11-12 10:13:39 -080069 err = e
70 rule = nil
71 } else {
72 panic(r)
73 }
74 }
75 }()
76
Colin Cross758290d2019-02-01 16:42:32 -080077 rule = android.NewRuleBuilder()
Colin Cross43f08db2018-11-12 10:13:39 -080078
Colin Cross69f59a32019-02-15 10:39:37 -080079 generateProfile := module.ProfileClassListing.Valid() && !global.DisableGenerateProfile
Nicolas Geoffraye7102422019-07-24 13:19:29 +010080 generateBootProfile := module.ProfileBootListing.Valid() && !global.DisableGenerateProfile
Colin Cross43f08db2018-11-12 10:13:39 -080081
Colin Cross69f59a32019-02-15 10:39:37 -080082 var profile android.WritablePath
Colin Crosscbed6572019-01-08 17:38:37 -080083 if generateProfile {
Hans Boehme4b53422020-01-25 01:44:30 +000084 profile = profileCommand(ctx, global, module, rule)
Colin Crosscbed6572019-01-08 17:38:37 -080085 }
Nicolas Geoffraye7102422019-07-24 13:19:29 +010086 if generateBootProfile {
Hans Boehme4b53422020-01-25 01:44:30 +000087 bootProfileCommand(ctx, global, module, rule)
Nicolas Geoffraye7102422019-07-24 13:19:29 +010088 }
Colin Crosscbed6572019-01-08 17:38:37 -080089
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +000090 if !dexpreoptDisabled(ctx, global, module) {
Colin Crosscbed6572019-01-08 17:38:37 -080091 // Don't preopt individual boot jars, they will be preopted together.
Colin Crosscbed6572019-01-08 17:38:37 -080092 if !contains(global.BootJars, module.Name) {
93 appImage := (generateProfile || module.ForceCreateAppImage || global.DefaultAppImages) &&
94 !module.NoCreateAppImage
95
96 generateDM := shouldGenerateDM(module, global)
97
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +000098 for archIdx, _ := range module.Archs {
Hans Boehme4b53422020-01-25 01:44:30 +000099 dexpreoptCommand(ctx, global, module, rule, archIdx, profile, appImage, generateDM)
Colin Crosscbed6572019-01-08 17:38:37 -0800100 }
101 }
102 }
103
104 return rule, nil
105}
106
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +0000107func dexpreoptDisabled(ctx android.PathContext, global GlobalConfig, module ModuleConfig) bool {
Colin Crosscbed6572019-01-08 17:38:37 -0800108 if contains(global.DisablePreoptModules, module.Name) {
109 return true
Colin Cross43f08db2018-11-12 10:13:39 -0800110 }
111
Ulyana Trafimovichf2cb7e92019-11-27 12:26:49 +0000112 // Don't preopt system server jars that are updatable.
113 for _, p := range global.UpdatableSystemServerJars {
Ulya Trafimovich4cdada22020-02-10 15:29:28 +0000114 if _, jar := android.SplitApexJarPair(p); jar == module.Name {
Ulyana Trafimovichf2cb7e92019-11-27 12:26:49 +0000115 return true
116 }
117 }
118
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +0000119 // Don't preopt system server jars that are not Soong modules.
120 if android.InList(module.Name, NonUpdatableSystemServerJars(ctx, global)) {
121 if _, ok := ctx.(android.ModuleContext); !ok {
122 return true
123 }
124 }
125
Colin Cross43f08db2018-11-12 10:13:39 -0800126 // If OnlyPreoptBootImageAndSystemServer=true and module is not in boot class path skip
127 // Also preopt system server jars since selinux prevents system server from loading anything from
128 // /data. If we don't do this they will need to be extracted which is not favorable for RAM usage
129 // or performance. If PreoptExtractedApk is true, we ignore the only preopt boot image options.
130 if global.OnlyPreoptBootImageAndSystemServer && !contains(global.BootJars, module.Name) &&
131 !contains(global.SystemServerJars, module.Name) && !module.PreoptExtractedApk {
Colin Crosscbed6572019-01-08 17:38:37 -0800132 return true
Colin Cross43f08db2018-11-12 10:13:39 -0800133 }
134
Colin Crosscbed6572019-01-08 17:38:37 -0800135 return false
Colin Cross43f08db2018-11-12 10:13:39 -0800136}
137
Hans Boehme4b53422020-01-25 01:44:30 +0000138func profileCommand(ctx android.PathContext, global GlobalConfig, module ModuleConfig,
139 rule *android.RuleBuilder) android.WritablePath {
Colin Cross69f59a32019-02-15 10:39:37 -0800140
141 profilePath := module.BuildPath.InSameDir(ctx, "profile.prof")
Colin Cross43f08db2018-11-12 10:13:39 -0800142 profileInstalledPath := module.DexLocation + ".prof"
143
144 if !module.ProfileIsTextListing {
145 rule.Command().FlagWithOutput("touch ", profilePath)
146 }
147
148 cmd := rule.Command().
149 Text(`ANDROID_LOG_TAGS="*:e"`).
Hans Boehme4b53422020-01-25 01:44:30 +0000150 Tool(global.SoongConfig.Profman)
Colin Cross43f08db2018-11-12 10:13:39 -0800151
152 if module.ProfileIsTextListing {
153 // The profile is a test listing of classes (used for framework jars).
154 // We need to generate the actual binary profile before being able to compile.
Colin Cross69f59a32019-02-15 10:39:37 -0800155 cmd.FlagWithInput("--create-profile-from=", module.ProfileClassListing.Path())
Colin Cross43f08db2018-11-12 10:13:39 -0800156 } else {
157 // The profile is binary profile (used for apps). Run it through profman to
158 // ensure the profile keys match the apk.
159 cmd.
160 Flag("--copy-and-update-profile-key").
Colin Cross69f59a32019-02-15 10:39:37 -0800161 FlagWithInput("--profile-file=", module.ProfileClassListing.Path())
Colin Cross43f08db2018-11-12 10:13:39 -0800162 }
163
164 cmd.
165 FlagWithInput("--apk=", module.DexPath).
166 Flag("--dex-location="+module.DexLocation).
167 FlagWithOutput("--reference-profile-file=", profilePath)
168
169 if !module.ProfileIsTextListing {
170 cmd.Text(fmt.Sprintf(`|| echo "Profile out of date for %s"`, module.DexPath))
171 }
172 rule.Install(profilePath, profileInstalledPath)
173
174 return profilePath
175}
176
Hans Boehme4b53422020-01-25 01:44:30 +0000177func bootProfileCommand(ctx android.PathContext, global GlobalConfig, module ModuleConfig,
178 rule *android.RuleBuilder) android.WritablePath {
Nicolas Geoffraye7102422019-07-24 13:19:29 +0100179
180 profilePath := module.BuildPath.InSameDir(ctx, "profile.bprof")
181 profileInstalledPath := module.DexLocation + ".bprof"
182
183 if !module.ProfileIsTextListing {
184 rule.Command().FlagWithOutput("touch ", profilePath)
185 }
186
187 cmd := rule.Command().
188 Text(`ANDROID_LOG_TAGS="*:e"`).
Hans Boehme4b53422020-01-25 01:44:30 +0000189 Tool(global.SoongConfig.Profman)
Nicolas Geoffraye7102422019-07-24 13:19:29 +0100190
191 // The profile is a test listing of methods.
192 // We need to generate the actual binary profile.
193 cmd.FlagWithInput("--create-profile-from=", module.ProfileBootListing.Path())
194
195 cmd.
196 Flag("--generate-boot-profile").
197 FlagWithInput("--apk=", module.DexPath).
198 Flag("--dex-location="+module.DexLocation).
199 FlagWithOutput("--reference-profile-file=", profilePath)
200
201 if !module.ProfileIsTextListing {
202 cmd.Text(fmt.Sprintf(`|| echo "Profile out of date for %s"`, module.DexPath))
203 }
204 rule.Install(profilePath, profileInstalledPath)
205
206 return profilePath
207}
208
Hans Boehme4b53422020-01-25 01:44:30 +0000209func dexpreoptCommand(ctx android.PathContext, global GlobalConfig, module ModuleConfig, rule *android.RuleBuilder,
210 archIdx int, profile android.WritablePath, appImage bool, generateDM bool) {
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000211
212 arch := module.Archs[archIdx]
Colin Cross43f08db2018-11-12 10:13:39 -0800213
214 // HACK: make soname in Soong-generated .odex files match Make.
215 base := filepath.Base(module.DexLocation)
216 if filepath.Ext(base) == ".jar" {
217 base = "javalib.jar"
218 } else if filepath.Ext(base) == ".apk" {
219 base = "package.apk"
220 }
221
222 toOdexPath := func(path string) string {
223 return filepath.Join(
224 filepath.Dir(path),
225 "oat",
Colin Cross74ba9622019-02-11 15:11:14 -0800226 arch.String(),
Colin Cross43f08db2018-11-12 10:13:39 -0800227 pathtools.ReplaceExtension(filepath.Base(path), "odex"))
228 }
229
Colin Cross69f59a32019-02-15 10:39:37 -0800230 odexPath := module.BuildPath.InSameDir(ctx, "oat", arch.String(), pathtools.ReplaceExtension(base, "odex"))
Colin Cross43f08db2018-11-12 10:13:39 -0800231 odexInstallPath := toOdexPath(module.DexLocation)
232 if odexOnSystemOther(module, global) {
Anton Hansson43ab0bc2019-10-03 14:18:45 +0100233 odexInstallPath = filepath.Join(SystemOtherPartition, odexInstallPath)
Colin Cross43f08db2018-11-12 10:13:39 -0800234 }
235
Colin Cross69f59a32019-02-15 10:39:37 -0800236 vdexPath := odexPath.ReplaceExtension(ctx, "vdex")
Colin Cross43f08db2018-11-12 10:13:39 -0800237 vdexInstallPath := pathtools.ReplaceExtension(odexInstallPath, "vdex")
238
Colin Cross69f59a32019-02-15 10:39:37 -0800239 invocationPath := odexPath.ReplaceExtension(ctx, "invocation")
Alex Light5de41962018-12-18 15:16:26 -0800240
Colin Cross43f08db2018-11-12 10:13:39 -0800241 // The class loader context using paths in the build
Colin Cross69f59a32019-02-15 10:39:37 -0800242 var classLoaderContextHost android.Paths
Colin Cross43f08db2018-11-12 10:13:39 -0800243
244 // The class loader context using paths as they will be on the device
245 var classLoaderContextTarget []string
246
247 // Extra paths that will be appended to the class loader if the APK manifest has targetSdkVersion < 28
Colin Cross69f59a32019-02-15 10:39:37 -0800248 var conditionalClassLoaderContextHost28 android.Paths
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000249 var conditionalClassLoaderContextTarget28 []string
250
251 // Extra paths that will be appended to the class loader if the APK manifest has targetSdkVersion < 29
Colin Cross69f59a32019-02-15 10:39:37 -0800252 var conditionalClassLoaderContextHost29 android.Paths
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000253 var conditionalClassLoaderContextTarget29 []string
Colin Cross43f08db2018-11-12 10:13:39 -0800254
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +0000255 var classLoaderContextHostString, classLoaderContextDeviceString string
256 var classLoaderDeps android.Paths
Colin Cross69f59a32019-02-15 10:39:37 -0800257
Colin Cross43f08db2018-11-12 10:13:39 -0800258 if module.EnforceUsesLibraries {
Colin Cross50ddcc42019-05-16 12:28:22 -0700259 usesLibs := append(copyOf(module.UsesLibraries), module.PresentOptionalUsesLibraries...)
Colin Cross43f08db2018-11-12 10:13:39 -0800260
261 // Create class loader context for dex2oat from uses libraries and filtered optional libraries
Colin Cross50ddcc42019-05-16 12:28:22 -0700262 for _, l := range usesLibs {
Colin Cross43f08db2018-11-12 10:13:39 -0800263
264 classLoaderContextHost = append(classLoaderContextHost,
265 pathForLibrary(module, l))
266 classLoaderContextTarget = append(classLoaderContextTarget,
267 filepath.Join("/system/framework", l+".jar"))
268 }
269
270 const httpLegacy = "org.apache.http.legacy"
271 const httpLegacyImpl = "org.apache.http.legacy.impl"
272
Colin Cross38b96852019-05-22 10:21:09 -0700273 // org.apache.http.legacy contains classes that were in the default classpath until API 28. If the
274 // targetSdkVersion in the manifest or APK is < 28, and the module does not explicitly depend on
275 // org.apache.http.legacy, then implicitly add the classes to the classpath for dexpreopt. One the
276 // device the classes will be in a file called org.apache.http.legacy.impl.jar.
Colin Cross50ddcc42019-05-16 12:28:22 -0700277 module.LibraryPaths[httpLegacyImpl] = module.LibraryPaths[httpLegacy]
278
279 if !contains(module.UsesLibraries, httpLegacy) && !contains(module.PresentOptionalUsesLibraries, httpLegacy) {
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000280 conditionalClassLoaderContextHost28 = append(conditionalClassLoaderContextHost28,
Colin Cross43f08db2018-11-12 10:13:39 -0800281 pathForLibrary(module, httpLegacyImpl))
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000282 conditionalClassLoaderContextTarget28 = append(conditionalClassLoaderContextTarget28,
Colin Cross43f08db2018-11-12 10:13:39 -0800283 filepath.Join("/system/framework", httpLegacyImpl+".jar"))
284 }
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000285
286 const hidlBase = "android.hidl.base-V1.0-java"
287 const hidlManager = "android.hidl.manager-V1.0-java"
288
Colin Cross38b96852019-05-22 10:21:09 -0700289 // android.hidl.base-V1.0-java and android.hidl.manager-V1.0 contain classes that were in the default
290 // classpath until API 29. If the targetSdkVersion in the manifest or APK is < 29 then implicitly add
291 // the classes to the classpath for dexpreopt.
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000292 conditionalClassLoaderContextHost29 = append(conditionalClassLoaderContextHost29,
Alex Light5de41962018-12-18 15:16:26 -0800293 pathForLibrary(module, hidlManager))
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000294 conditionalClassLoaderContextTarget29 = append(conditionalClassLoaderContextTarget29,
295 filepath.Join("/system/framework", hidlManager+".jar"))
296 conditionalClassLoaderContextHost29 = append(conditionalClassLoaderContextHost29,
Alex Light5de41962018-12-18 15:16:26 -0800297 pathForLibrary(module, hidlBase))
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000298 conditionalClassLoaderContextTarget29 = append(conditionalClassLoaderContextTarget29,
299 filepath.Join("/system/framework", hidlBase+".jar"))
Colin Cross69f59a32019-02-15 10:39:37 -0800300
301 classLoaderContextHostString = strings.Join(classLoaderContextHost.Strings(), ":")
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +0000302 } else if android.InList(module.Name, NonUpdatableSystemServerJars(ctx, global)) {
303 // We expect that all dexpreopted system server jars are Soong modules.
304 mctx, isModule := ctx.(android.ModuleContext)
305 if !isModule {
306 panic("Cannot dexpreopt system server jar that is not a soong module.")
307 }
308
309 // System server jars should be dexpreopted together: class loader context of each jar
310 // should include preceding jars (which can be found as dependencies of the current jar
311 // with a special tag).
312 var jarsOnHost android.Paths
313 var jarsOnDevice []string
314 mctx.VisitDirectDepsWithTag(SystemServerDepTag, func(dep android.Module) {
315 depName := mctx.OtherModuleName(dep)
316 if jar, ok := dep.(interface{ DexJar() android.Path }); ok {
317 jarsOnHost = append(jarsOnHost, jar.DexJar())
318 jarsOnDevice = append(jarsOnDevice, "/system/framework/"+depName+".jar")
319 } else {
320 mctx.ModuleErrorf("module \"%s\" is not a jar", depName)
321 }
322 })
323 classLoaderContextHostString = strings.Join(jarsOnHost.Strings(), ":")
324 classLoaderContextDeviceString = strings.Join(jarsOnDevice, ":")
325 classLoaderDeps = jarsOnHost
Colin Cross43f08db2018-11-12 10:13:39 -0800326 } else {
327 // Pass special class loader context to skip the classpath and collision check.
328 // This will get removed once LOCAL_USES_LIBRARIES is enforced.
329 // Right now LOCAL_USES_LIBRARIES is opt in, for the case where it's not specified we still default
330 // to the &.
Colin Cross69f59a32019-02-15 10:39:37 -0800331 classLoaderContextHostString = `\&`
Colin Cross43f08db2018-11-12 10:13:39 -0800332 }
333
Colin Cross69f59a32019-02-15 10:39:37 -0800334 rule.Command().FlagWithArg("mkdir -p ", filepath.Dir(odexPath.String()))
Colin Cross43f08db2018-11-12 10:13:39 -0800335 rule.Command().FlagWithOutput("rm -f ", odexPath)
336 // Set values in the environment of the rule. These may be modified by construct_context.sh.
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +0000337 if classLoaderContextHostString == `\&` {
338 rule.Command().Text(`class_loader_context_arg=--class-loader-context=\&`)
339 rule.Command().Text(`stored_class_loader_context_arg=""`)
340 } else {
341 rule.Command().Text("class_loader_context_arg=--class-loader-context=PCL[" + classLoaderContextHostString + "]")
342 rule.Command().Text("stored_class_loader_context_arg=--stored-class-loader-context=PCL[" + classLoaderContextDeviceString + "]")
343 }
Colin Cross43f08db2018-11-12 10:13:39 -0800344
345 if module.EnforceUsesLibraries {
Colin Cross38b96852019-05-22 10:21:09 -0700346 if module.ManifestPath != nil {
347 rule.Command().Text(`target_sdk_version="$(`).
Hans Boehme4b53422020-01-25 01:44:30 +0000348 Tool(global.SoongConfig.ManifestCheck).
Colin Cross38b96852019-05-22 10:21:09 -0700349 Flag("--extract-target-sdk-version").
350 Input(module.ManifestPath).
351 Text(`)"`)
352 } else {
353 // No manifest to extract targetSdkVersion from, hope that DexJar is an APK
354 rule.Command().Text(`target_sdk_version="$(`).
Hans Boehme4b53422020-01-25 01:44:30 +0000355 Tool(global.SoongConfig.Aapt).
Colin Cross38b96852019-05-22 10:21:09 -0700356 Flag("dump badging").
357 Input(module.DexPath).
358 Text(`| grep "targetSdkVersion" | sed -n "s/targetSdkVersion:'\(.*\)'/\1/p"`).
359 Text(`)"`)
360 }
Colin Cross69f59a32019-02-15 10:39:37 -0800361 rule.Command().Textf(`dex_preopt_host_libraries="%s"`,
362 strings.Join(classLoaderContextHost.Strings(), " ")).
363 Implicits(classLoaderContextHost)
364 rule.Command().Textf(`dex_preopt_target_libraries="%s"`,
365 strings.Join(classLoaderContextTarget, " "))
366 rule.Command().Textf(`conditional_host_libs_28="%s"`,
367 strings.Join(conditionalClassLoaderContextHost28.Strings(), " ")).
368 Implicits(conditionalClassLoaderContextHost28)
369 rule.Command().Textf(`conditional_target_libs_28="%s"`,
370 strings.Join(conditionalClassLoaderContextTarget28, " "))
371 rule.Command().Textf(`conditional_host_libs_29="%s"`,
372 strings.Join(conditionalClassLoaderContextHost29.Strings(), " ")).
373 Implicits(conditionalClassLoaderContextHost29)
374 rule.Command().Textf(`conditional_target_libs_29="%s"`,
375 strings.Join(conditionalClassLoaderContextTarget29, " "))
Hans Boehme4b53422020-01-25 01:44:30 +0000376 rule.Command().Text("source").Tool(global.SoongConfig.ConstructContext).Input(module.DexPath)
Colin Cross43f08db2018-11-12 10:13:39 -0800377 }
378
Nicolas Geoffray2464ef42019-03-05 14:07:07 +0000379 // Devices that do not have a product partition use a symlink from /product to /system/product.
380 // Because on-device dexopt will see dex locations starting with /product, we change the paths
381 // to mimic this behavior.
382 dexLocationArg := module.DexLocation
383 if strings.HasPrefix(dexLocationArg, "/system/product/") {
384 dexLocationArg = strings.TrimPrefix(dexLocationArg, "/system")
385 }
386
Colin Cross43f08db2018-11-12 10:13:39 -0800387 cmd := rule.Command().
388 Text(`ANDROID_LOG_TAGS="*:e"`).
Hans Boehme4b53422020-01-25 01:44:30 +0000389 Tool(global.SoongConfig.Dex2oat).
Colin Cross43f08db2018-11-12 10:13:39 -0800390 Flag("--avoid-storing-invocation").
Alex Light5de41962018-12-18 15:16:26 -0800391 FlagWithOutput("--write-invocation-to=", invocationPath).ImplicitOutput(invocationPath).
Colin Cross43f08db2018-11-12 10:13:39 -0800392 Flag("--runtime-arg").FlagWithArg("-Xms", global.Dex2oatXms).
393 Flag("--runtime-arg").FlagWithArg("-Xmx", global.Dex2oatXmx).
Colin Cross800fe132019-02-11 14:21:24 -0800394 Flag("--runtime-arg").FlagWithInputList("-Xbootclasspath:", module.PreoptBootClassPathDexFiles, ":").
395 Flag("--runtime-arg").FlagWithList("-Xbootclasspath-locations:", module.PreoptBootClassPathDexLocations, ":").
Colin Cross43f08db2018-11-12 10:13:39 -0800396 Flag("${class_loader_context_arg}").
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +0000397 Flag("${stored_class_loader_context_arg}").Implicits(classLoaderDeps).
Ulya Trafimovich3391a1e2020-01-03 17:33:17 +0000398 FlagWithArg("--boot-image=", strings.Join(module.DexPreoptImageLocations, ":")).Implicits(module.DexPreoptImagesDeps[archIdx].Paths()).
Colin Cross43f08db2018-11-12 10:13:39 -0800399 FlagWithInput("--dex-file=", module.DexPath).
Nicolas Geoffray2464ef42019-03-05 14:07:07 +0000400 FlagWithArg("--dex-location=", dexLocationArg).
Colin Cross43f08db2018-11-12 10:13:39 -0800401 FlagWithOutput("--oat-file=", odexPath).ImplicitOutput(vdexPath).
402 // Pass an empty directory, dex2oat shouldn't be reading arbitrary files
403 FlagWithArg("--android-root=", global.EmptyDirectory).
Colin Cross74ba9622019-02-11 15:11:14 -0800404 FlagWithArg("--instruction-set=", arch.String()).
Colin Cross43f08db2018-11-12 10:13:39 -0800405 FlagWithArg("--instruction-set-variant=", global.CpuVariant[arch]).
406 FlagWithArg("--instruction-set-features=", global.InstructionSetFeatures[arch]).
407 Flag("--no-generate-debug-info").
408 Flag("--generate-build-id").
409 Flag("--abort-on-hard-verifier-error").
410 Flag("--force-determinism").
411 FlagWithArg("--no-inline-from=", "core-oj.jar")
412
413 var preoptFlags []string
414 if len(module.PreoptFlags) > 0 {
415 preoptFlags = module.PreoptFlags
416 } else if len(global.PreoptFlags) > 0 {
417 preoptFlags = global.PreoptFlags
418 }
419
420 if len(preoptFlags) > 0 {
421 cmd.Text(strings.Join(preoptFlags, " "))
422 }
423
424 if module.UncompressedDex {
425 cmd.FlagWithArg("--copy-dex-files=", "false")
426 }
427
428 if !anyHavePrefix(preoptFlags, "--compiler-filter=") {
429 var compilerFilter string
430 if contains(global.SystemServerJars, module.Name) {
431 // Jars of system server, use the product option if it is set, speed otherwise.
432 if global.SystemServerCompilerFilter != "" {
433 compilerFilter = global.SystemServerCompilerFilter
434 } else {
435 compilerFilter = "speed"
436 }
437 } else if contains(global.SpeedApps, module.Name) || contains(global.SystemServerApps, module.Name) {
438 // Apps loaded into system server, and apps the product default to being compiled with the
439 // 'speed' compiler filter.
440 compilerFilter = "speed"
Colin Cross69f59a32019-02-15 10:39:37 -0800441 } else if profile != nil {
Colin Cross43f08db2018-11-12 10:13:39 -0800442 // For non system server jars, use speed-profile when we have a profile.
443 compilerFilter = "speed-profile"
444 } else if global.DefaultCompilerFilter != "" {
445 compilerFilter = global.DefaultCompilerFilter
446 } else {
447 compilerFilter = "quicken"
448 }
449 cmd.FlagWithArg("--compiler-filter=", compilerFilter)
450 }
451
452 if generateDM {
453 cmd.FlagWithArg("--copy-dex-files=", "false")
Colin Cross69f59a32019-02-15 10:39:37 -0800454 dmPath := module.BuildPath.InSameDir(ctx, "generated.dm")
Colin Cross43f08db2018-11-12 10:13:39 -0800455 dmInstalledPath := pathtools.ReplaceExtension(module.DexLocation, "dm")
Colin Cross69f59a32019-02-15 10:39:37 -0800456 tmpPath := module.BuildPath.InSameDir(ctx, "primary.vdex")
Colin Cross43f08db2018-11-12 10:13:39 -0800457 rule.Command().Text("cp -f").Input(vdexPath).Output(tmpPath)
Hans Boehme4b53422020-01-25 01:44:30 +0000458 rule.Command().Tool(global.SoongConfig.SoongZip).
Colin Cross43f08db2018-11-12 10:13:39 -0800459 FlagWithArg("-L", "9").
460 FlagWithOutput("-o", dmPath).
461 Flag("-j").
462 Input(tmpPath)
463 rule.Install(dmPath, dmInstalledPath)
464 }
465
466 // By default, emit debug info.
467 debugInfo := true
468 if global.NoDebugInfo {
469 // If the global setting suppresses mini-debug-info, disable it.
470 debugInfo = false
471 }
472
473 // PRODUCT_SYSTEM_SERVER_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO.
474 // PRODUCT_OTHER_JAVA_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO.
475 if contains(global.SystemServerJars, module.Name) {
476 if global.AlwaysSystemServerDebugInfo {
477 debugInfo = true
478 } else if global.NeverSystemServerDebugInfo {
479 debugInfo = false
480 }
481 } else {
482 if global.AlwaysOtherDebugInfo {
483 debugInfo = true
484 } else if global.NeverOtherDebugInfo {
485 debugInfo = false
486 }
487 }
488
489 // Never enable on eng.
490 if global.IsEng {
491 debugInfo = false
492 }
493
494 if debugInfo {
495 cmd.Flag("--generate-mini-debug-info")
496 } else {
497 cmd.Flag("--no-generate-mini-debug-info")
498 }
499
500 // Set the compiler reason to 'prebuilt' to identify the oat files produced
501 // during the build, as opposed to compiled on the device.
502 cmd.FlagWithArg("--compilation-reason=", "prebuilt")
503
504 if appImage {
Colin Cross69f59a32019-02-15 10:39:37 -0800505 appImagePath := odexPath.ReplaceExtension(ctx, "art")
Colin Cross43f08db2018-11-12 10:13:39 -0800506 appImageInstallPath := pathtools.ReplaceExtension(odexInstallPath, "art")
507 cmd.FlagWithOutput("--app-image-file=", appImagePath).
508 FlagWithArg("--image-format=", "lz4")
Mathieu Chartier3f7ddbb2019-04-29 09:33:50 -0700509 if !global.DontResolveStartupStrings {
510 cmd.FlagWithArg("--resolve-startup-const-strings=", "true")
511 }
Colin Cross43f08db2018-11-12 10:13:39 -0800512 rule.Install(appImagePath, appImageInstallPath)
513 }
514
Colin Cross69f59a32019-02-15 10:39:37 -0800515 if profile != nil {
516 cmd.FlagWithInput("--profile-file=", profile)
Colin Cross43f08db2018-11-12 10:13:39 -0800517 }
518
519 rule.Install(odexPath, odexInstallPath)
520 rule.Install(vdexPath, vdexInstallPath)
521}
522
Colin Cross43f08db2018-11-12 10:13:39 -0800523func shouldGenerateDM(module ModuleConfig, global GlobalConfig) bool {
524 // Generating DM files only makes sense for verify, avoid doing for non verify compiler filter APKs.
525 // No reason to use a dm file if the dex is already uncompressed.
526 return global.GenerateDMFiles && !module.UncompressedDex &&
527 contains(module.PreoptFlags, "--compiler-filter=verify")
528}
529
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000530func OdexOnSystemOtherByName(name string, dexLocation string, global GlobalConfig) bool {
Colin Cross43f08db2018-11-12 10:13:39 -0800531 if !global.HasSystemOther {
532 return false
533 }
534
535 if global.SanitizeLite {
536 return false
537 }
538
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000539 if contains(global.SpeedApps, name) || contains(global.SystemServerApps, name) {
Colin Cross43f08db2018-11-12 10:13:39 -0800540 return false
541 }
542
543 for _, f := range global.PatternsOnSystemOther {
Anton Hanssond57bd3c2019-10-14 16:53:02 +0100544 if makefileMatch(filepath.Join(SystemPartition, f), dexLocation) {
Colin Cross43f08db2018-11-12 10:13:39 -0800545 return true
546 }
547 }
548
549 return false
550}
551
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000552func odexOnSystemOther(module ModuleConfig, global GlobalConfig) bool {
553 return OdexOnSystemOtherByName(module.Name, module.DexLocation, global)
554}
555
Colin Crossc7e40aa2019-02-08 21:37:00 -0800556// PathToLocation converts .../system/framework/arm64/boot.art to .../system/framework/boot.art
Colin Cross69f59a32019-02-15 10:39:37 -0800557func PathToLocation(path android.Path, arch android.ArchType) string {
558 pathArch := filepath.Base(filepath.Dir(path.String()))
Colin Cross74ba9622019-02-11 15:11:14 -0800559 if pathArch != arch.String() {
560 panic(fmt.Errorf("last directory in %q must be %q", path, arch.String()))
Colin Crossc7e40aa2019-02-08 21:37:00 -0800561 }
Colin Cross69f59a32019-02-15 10:39:37 -0800562 return filepath.Join(filepath.Dir(filepath.Dir(path.String())), filepath.Base(path.String()))
Colin Crossc7e40aa2019-02-08 21:37:00 -0800563}
564
Colin Cross69f59a32019-02-15 10:39:37 -0800565func pathForLibrary(module ModuleConfig, lib string) android.Path {
566 path, ok := module.LibraryPaths[lib]
567 if !ok {
Colin Cross43f08db2018-11-12 10:13:39 -0800568 panic(fmt.Errorf("unknown library path for %q", lib))
569 }
570 return path
571}
572
573func makefileMatch(pattern, s string) bool {
574 percent := strings.IndexByte(pattern, '%')
575 switch percent {
576 case -1:
577 return pattern == s
578 case len(pattern) - 1:
579 return strings.HasPrefix(s, pattern[:len(pattern)-1])
580 default:
581 panic(fmt.Errorf("unsupported makefile pattern %q", pattern))
582 }
583}
584
Ulyana Trafimovichf2cb7e92019-11-27 12:26:49 +0000585// Expected format for apexJarValue = <apex name>:<jar name>
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000586func GetJarLocationFromApexJarPair(apexJarValue string) string {
Ulya Trafimovich4cdada22020-02-10 15:29:28 +0000587 apex, jar := android.SplitApexJarPair(apexJarValue)
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000588 return filepath.Join("/apex", apex, "javalib", jar+".jar")
Roshan Piusccc26ef2019-11-27 09:37:46 -0800589}
590
Ulya Trafimovichf3ff0102019-12-03 15:39:23 +0000591func GetJarsFromApexJarPairs(apexJarPairs []string) []string {
592 modules := make([]string, len(apexJarPairs))
593 for i, p := range apexJarPairs {
594 _, jar := android.SplitApexJarPair(p)
595 modules[i] = jar
596 }
597 return modules
598}
599
600var nonUpdatableSystemServerJarsKey = android.NewOnceKey("nonUpdatableSystemServerJars")
601
602// TODO: eliminate the superficial global config parameter by moving global config definition
603// from java subpackage to dexpreopt.
604func NonUpdatableSystemServerJars(ctx android.PathContext, global GlobalConfig) []string {
605 return ctx.Config().Once(nonUpdatableSystemServerJarsKey, func() interface{} {
606 return android.RemoveListFromList(global.SystemServerJars,
607 GetJarsFromApexJarPairs(global.UpdatableSystemServerJars))
608 }).([]string)
609}
610
Colin Cross43f08db2018-11-12 10:13:39 -0800611func contains(l []string, s string) bool {
612 for _, e := range l {
613 if e == s {
614 return true
615 }
616 }
617 return false
618}
619
620// remove all elements in a from b, returning a new slice
621func filterOut(a []string, b []string) []string {
622 var ret []string
623 for _, x := range b {
624 if !contains(a, x) {
625 ret = append(ret, x)
626 }
627 }
628 return ret
629}
630
631func replace(l []string, from, to string) {
632 for i := range l {
633 if l[i] == from {
634 l[i] = to
635 }
636 }
637}
638
Colin Cross454c0872019-02-15 23:03:34 -0800639var copyOf = android.CopyOf
Colin Cross43f08db2018-11-12 10:13:39 -0800640
641func anyHavePrefix(l []string, prefix string) bool {
642 for _, x := range l {
643 if strings.HasPrefix(x, prefix) {
644 return true
645 }
646 }
647 return false
648}