blob: a69498a29d7cfaa215572b73d67075b538ea9cef [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 Stjernholmbe9d0d22020-01-10 20:32:59 +000052func GenerateDexpreoptRule(ctx android.PathContext, globalSoong GlobalSoongConfig,
Colin Cross69f59a32019-02-15 10:39:37 -080053 global GlobalConfig, module ModuleConfig) (rule *android.RuleBuilder, err error) {
54
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 Stjernholmbe9d0d22020-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 Stjernholmbe9d0d22020-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
81 if !dexpreoptDisabled(global, module) {
82 // 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 Stjernholmbe9d0d22020-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
98func dexpreoptDisabled(global GlobalConfig, module ModuleConfig) bool {
99 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 {
105 if _, jar := SplitApexJarPair(p); jar == module.Name {
106 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 Stjernholmbe9d0d22020-01-10 20:32:59 +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 Stjernholmbe9d0d22020-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 Stjernholmbe9d0d22020-01-10 20:32:59 +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 Stjernholmbe9d0d22020-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 Stjernholmbe9d0d22020-01-10 20:32:59 +0000193func dexpreoptCommand(ctx android.PathContext, globalSoong GlobalSoongConfig, global GlobalConfig,
194 module ModuleConfig, rule *android.RuleBuilder, archIdx int, profile android.WritablePath,
195 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
Colin Cross43f08db2018-11-12 10:13:39 -0800226 // The class loader context using paths in the build
Colin Cross69f59a32019-02-15 10:39:37 -0800227 var classLoaderContextHost android.Paths
Colin Cross43f08db2018-11-12 10:13:39 -0800228
229 // The class loader context using paths as they will be on the device
230 var classLoaderContextTarget []string
231
232 // Extra paths that will be appended to the class loader if the APK manifest has targetSdkVersion < 28
Colin Cross69f59a32019-02-15 10:39:37 -0800233 var conditionalClassLoaderContextHost28 android.Paths
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000234 var conditionalClassLoaderContextTarget28 []string
235
236 // Extra paths that will be appended to the class loader if the APK manifest has targetSdkVersion < 29
Colin Cross69f59a32019-02-15 10:39:37 -0800237 var conditionalClassLoaderContextHost29 android.Paths
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000238 var conditionalClassLoaderContextTarget29 []string
Colin Cross43f08db2018-11-12 10:13:39 -0800239
Colin Cross69f59a32019-02-15 10:39:37 -0800240 var classLoaderContextHostString string
241
Colin Cross43f08db2018-11-12 10:13:39 -0800242 if module.EnforceUsesLibraries {
Colin Cross50ddcc42019-05-16 12:28:22 -0700243 usesLibs := append(copyOf(module.UsesLibraries), module.PresentOptionalUsesLibraries...)
Colin Cross43f08db2018-11-12 10:13:39 -0800244
245 // Create class loader context for dex2oat from uses libraries and filtered optional libraries
Colin Cross50ddcc42019-05-16 12:28:22 -0700246 for _, l := range usesLibs {
Colin Cross43f08db2018-11-12 10:13:39 -0800247
248 classLoaderContextHost = append(classLoaderContextHost,
249 pathForLibrary(module, l))
250 classLoaderContextTarget = append(classLoaderContextTarget,
251 filepath.Join("/system/framework", l+".jar"))
252 }
253
254 const httpLegacy = "org.apache.http.legacy"
255 const httpLegacyImpl = "org.apache.http.legacy.impl"
256
Colin Cross38b96852019-05-22 10:21:09 -0700257 // org.apache.http.legacy contains classes that were in the default classpath until API 28. If the
258 // targetSdkVersion in the manifest or APK is < 28, and the module does not explicitly depend on
259 // org.apache.http.legacy, then implicitly add the classes to the classpath for dexpreopt. One the
260 // device the classes will be in a file called org.apache.http.legacy.impl.jar.
Colin Cross50ddcc42019-05-16 12:28:22 -0700261 module.LibraryPaths[httpLegacyImpl] = module.LibraryPaths[httpLegacy]
262
263 if !contains(module.UsesLibraries, httpLegacy) && !contains(module.PresentOptionalUsesLibraries, httpLegacy) {
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000264 conditionalClassLoaderContextHost28 = append(conditionalClassLoaderContextHost28,
Colin Cross43f08db2018-11-12 10:13:39 -0800265 pathForLibrary(module, httpLegacyImpl))
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000266 conditionalClassLoaderContextTarget28 = append(conditionalClassLoaderContextTarget28,
Colin Cross43f08db2018-11-12 10:13:39 -0800267 filepath.Join("/system/framework", httpLegacyImpl+".jar"))
268 }
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000269
270 const hidlBase = "android.hidl.base-V1.0-java"
271 const hidlManager = "android.hidl.manager-V1.0-java"
272
Colin Cross38b96852019-05-22 10:21:09 -0700273 // android.hidl.base-V1.0-java and android.hidl.manager-V1.0 contain classes that were in the default
274 // classpath until API 29. If the targetSdkVersion in the manifest or APK is < 29 then implicitly add
275 // the classes to the classpath for dexpreopt.
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000276 conditionalClassLoaderContextHost29 = append(conditionalClassLoaderContextHost29,
Alex Light5de41962018-12-18 15:16:26 -0800277 pathForLibrary(module, hidlManager))
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000278 conditionalClassLoaderContextTarget29 = append(conditionalClassLoaderContextTarget29,
279 filepath.Join("/system/framework", hidlManager+".jar"))
280 conditionalClassLoaderContextHost29 = append(conditionalClassLoaderContextHost29,
Alex Light5de41962018-12-18 15:16:26 -0800281 pathForLibrary(module, hidlBase))
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000282 conditionalClassLoaderContextTarget29 = append(conditionalClassLoaderContextTarget29,
283 filepath.Join("/system/framework", hidlBase+".jar"))
Colin Cross69f59a32019-02-15 10:39:37 -0800284
285 classLoaderContextHostString = strings.Join(classLoaderContextHost.Strings(), ":")
Colin Cross43f08db2018-11-12 10:13:39 -0800286 } else {
287 // Pass special class loader context to skip the classpath and collision check.
288 // This will get removed once LOCAL_USES_LIBRARIES is enforced.
289 // Right now LOCAL_USES_LIBRARIES is opt in, for the case where it's not specified we still default
290 // to the &.
Colin Cross69f59a32019-02-15 10:39:37 -0800291 classLoaderContextHostString = `\&`
Colin Cross43f08db2018-11-12 10:13:39 -0800292 }
293
Colin Cross69f59a32019-02-15 10:39:37 -0800294 rule.Command().FlagWithArg("mkdir -p ", filepath.Dir(odexPath.String()))
Colin Cross43f08db2018-11-12 10:13:39 -0800295 rule.Command().FlagWithOutput("rm -f ", odexPath)
296 // Set values in the environment of the rule. These may be modified by construct_context.sh.
Colin Cross69f59a32019-02-15 10:39:37 -0800297 rule.Command().FlagWithArg("class_loader_context_arg=--class-loader-context=", classLoaderContextHostString)
Colin Cross43f08db2018-11-12 10:13:39 -0800298 rule.Command().Text(`stored_class_loader_context_arg=""`)
299
300 if module.EnforceUsesLibraries {
Colin Cross38b96852019-05-22 10:21:09 -0700301 if module.ManifestPath != nil {
302 rule.Command().Text(`target_sdk_version="$(`).
Martin Stjernholmbe9d0d22020-01-10 20:32:59 +0000303 Tool(globalSoong.ManifestCheck).
Colin Cross38b96852019-05-22 10:21:09 -0700304 Flag("--extract-target-sdk-version").
305 Input(module.ManifestPath).
306 Text(`)"`)
307 } else {
308 // No manifest to extract targetSdkVersion from, hope that DexJar is an APK
309 rule.Command().Text(`target_sdk_version="$(`).
Martin Stjernholmbe9d0d22020-01-10 20:32:59 +0000310 Tool(globalSoong.Aapt).
Colin Cross38b96852019-05-22 10:21:09 -0700311 Flag("dump badging").
312 Input(module.DexPath).
313 Text(`| grep "targetSdkVersion" | sed -n "s/targetSdkVersion:'\(.*\)'/\1/p"`).
314 Text(`)"`)
315 }
Colin Cross69f59a32019-02-15 10:39:37 -0800316 rule.Command().Textf(`dex_preopt_host_libraries="%s"`,
317 strings.Join(classLoaderContextHost.Strings(), " ")).
318 Implicits(classLoaderContextHost)
319 rule.Command().Textf(`dex_preopt_target_libraries="%s"`,
320 strings.Join(classLoaderContextTarget, " "))
321 rule.Command().Textf(`conditional_host_libs_28="%s"`,
322 strings.Join(conditionalClassLoaderContextHost28.Strings(), " ")).
323 Implicits(conditionalClassLoaderContextHost28)
324 rule.Command().Textf(`conditional_target_libs_28="%s"`,
325 strings.Join(conditionalClassLoaderContextTarget28, " "))
326 rule.Command().Textf(`conditional_host_libs_29="%s"`,
327 strings.Join(conditionalClassLoaderContextHost29.Strings(), " ")).
328 Implicits(conditionalClassLoaderContextHost29)
329 rule.Command().Textf(`conditional_target_libs_29="%s"`,
330 strings.Join(conditionalClassLoaderContextTarget29, " "))
Martin Stjernholmbe9d0d22020-01-10 20:32:59 +0000331 rule.Command().Text("source").Tool(globalSoong.ConstructContext).Input(module.DexPath)
Colin Cross43f08db2018-11-12 10:13:39 -0800332 }
333
Nicolas Geoffray2464ef42019-03-05 14:07:07 +0000334 // Devices that do not have a product partition use a symlink from /product to /system/product.
335 // Because on-device dexopt will see dex locations starting with /product, we change the paths
336 // to mimic this behavior.
337 dexLocationArg := module.DexLocation
338 if strings.HasPrefix(dexLocationArg, "/system/product/") {
339 dexLocationArg = strings.TrimPrefix(dexLocationArg, "/system")
340 }
341
Colin Cross43f08db2018-11-12 10:13:39 -0800342 cmd := rule.Command().
343 Text(`ANDROID_LOG_TAGS="*:e"`).
Martin Stjernholmbe9d0d22020-01-10 20:32:59 +0000344 Tool(globalSoong.Dex2oat).
Colin Cross43f08db2018-11-12 10:13:39 -0800345 Flag("--avoid-storing-invocation").
Alex Light5de41962018-12-18 15:16:26 -0800346 FlagWithOutput("--write-invocation-to=", invocationPath).ImplicitOutput(invocationPath).
Colin Cross43f08db2018-11-12 10:13:39 -0800347 Flag("--runtime-arg").FlagWithArg("-Xms", global.Dex2oatXms).
348 Flag("--runtime-arg").FlagWithArg("-Xmx", global.Dex2oatXmx).
Colin Cross800fe132019-02-11 14:21:24 -0800349 Flag("--runtime-arg").FlagWithInputList("-Xbootclasspath:", module.PreoptBootClassPathDexFiles, ":").
350 Flag("--runtime-arg").FlagWithList("-Xbootclasspath-locations:", module.PreoptBootClassPathDexLocations, ":").
Colin Cross43f08db2018-11-12 10:13:39 -0800351 Flag("${class_loader_context_arg}").
352 Flag("${stored_class_loader_context_arg}").
Ulya Trafimovich3391a1e2020-01-03 17:33:17 +0000353 FlagWithArg("--boot-image=", strings.Join(module.DexPreoptImageLocations, ":")).Implicits(module.DexPreoptImagesDeps[archIdx].Paths()).
Colin Cross43f08db2018-11-12 10:13:39 -0800354 FlagWithInput("--dex-file=", module.DexPath).
Nicolas Geoffray2464ef42019-03-05 14:07:07 +0000355 FlagWithArg("--dex-location=", dexLocationArg).
Colin Cross43f08db2018-11-12 10:13:39 -0800356 FlagWithOutput("--oat-file=", odexPath).ImplicitOutput(vdexPath).
357 // Pass an empty directory, dex2oat shouldn't be reading arbitrary files
358 FlagWithArg("--android-root=", global.EmptyDirectory).
Colin Cross74ba9622019-02-11 15:11:14 -0800359 FlagWithArg("--instruction-set=", arch.String()).
Colin Cross43f08db2018-11-12 10:13:39 -0800360 FlagWithArg("--instruction-set-variant=", global.CpuVariant[arch]).
361 FlagWithArg("--instruction-set-features=", global.InstructionSetFeatures[arch]).
362 Flag("--no-generate-debug-info").
363 Flag("--generate-build-id").
364 Flag("--abort-on-hard-verifier-error").
365 Flag("--force-determinism").
366 FlagWithArg("--no-inline-from=", "core-oj.jar")
367
368 var preoptFlags []string
369 if len(module.PreoptFlags) > 0 {
370 preoptFlags = module.PreoptFlags
371 } else if len(global.PreoptFlags) > 0 {
372 preoptFlags = global.PreoptFlags
373 }
374
375 if len(preoptFlags) > 0 {
376 cmd.Text(strings.Join(preoptFlags, " "))
377 }
378
379 if module.UncompressedDex {
380 cmd.FlagWithArg("--copy-dex-files=", "false")
381 }
382
383 if !anyHavePrefix(preoptFlags, "--compiler-filter=") {
384 var compilerFilter string
385 if contains(global.SystemServerJars, module.Name) {
386 // Jars of system server, use the product option if it is set, speed otherwise.
387 if global.SystemServerCompilerFilter != "" {
388 compilerFilter = global.SystemServerCompilerFilter
389 } else {
390 compilerFilter = "speed"
391 }
392 } else if contains(global.SpeedApps, module.Name) || contains(global.SystemServerApps, module.Name) {
393 // Apps loaded into system server, and apps the product default to being compiled with the
394 // 'speed' compiler filter.
395 compilerFilter = "speed"
Colin Cross69f59a32019-02-15 10:39:37 -0800396 } else if profile != nil {
Colin Cross43f08db2018-11-12 10:13:39 -0800397 // For non system server jars, use speed-profile when we have a profile.
398 compilerFilter = "speed-profile"
399 } else if global.DefaultCompilerFilter != "" {
400 compilerFilter = global.DefaultCompilerFilter
401 } else {
402 compilerFilter = "quicken"
403 }
404 cmd.FlagWithArg("--compiler-filter=", compilerFilter)
405 }
406
407 if generateDM {
408 cmd.FlagWithArg("--copy-dex-files=", "false")
Colin Cross69f59a32019-02-15 10:39:37 -0800409 dmPath := module.BuildPath.InSameDir(ctx, "generated.dm")
Colin Cross43f08db2018-11-12 10:13:39 -0800410 dmInstalledPath := pathtools.ReplaceExtension(module.DexLocation, "dm")
Colin Cross69f59a32019-02-15 10:39:37 -0800411 tmpPath := module.BuildPath.InSameDir(ctx, "primary.vdex")
Colin Cross43f08db2018-11-12 10:13:39 -0800412 rule.Command().Text("cp -f").Input(vdexPath).Output(tmpPath)
Martin Stjernholmbe9d0d22020-01-10 20:32:59 +0000413 rule.Command().Tool(globalSoong.SoongZip).
Colin Cross43f08db2018-11-12 10:13:39 -0800414 FlagWithArg("-L", "9").
415 FlagWithOutput("-o", dmPath).
416 Flag("-j").
417 Input(tmpPath)
418 rule.Install(dmPath, dmInstalledPath)
419 }
420
421 // By default, emit debug info.
422 debugInfo := true
423 if global.NoDebugInfo {
424 // If the global setting suppresses mini-debug-info, disable it.
425 debugInfo = false
426 }
427
428 // PRODUCT_SYSTEM_SERVER_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO.
429 // PRODUCT_OTHER_JAVA_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO.
430 if contains(global.SystemServerJars, module.Name) {
431 if global.AlwaysSystemServerDebugInfo {
432 debugInfo = true
433 } else if global.NeverSystemServerDebugInfo {
434 debugInfo = false
435 }
436 } else {
437 if global.AlwaysOtherDebugInfo {
438 debugInfo = true
439 } else if global.NeverOtherDebugInfo {
440 debugInfo = false
441 }
442 }
443
444 // Never enable on eng.
445 if global.IsEng {
446 debugInfo = false
447 }
448
449 if debugInfo {
450 cmd.Flag("--generate-mini-debug-info")
451 } else {
452 cmd.Flag("--no-generate-mini-debug-info")
453 }
454
455 // Set the compiler reason to 'prebuilt' to identify the oat files produced
456 // during the build, as opposed to compiled on the device.
457 cmd.FlagWithArg("--compilation-reason=", "prebuilt")
458
459 if appImage {
Colin Cross69f59a32019-02-15 10:39:37 -0800460 appImagePath := odexPath.ReplaceExtension(ctx, "art")
Colin Cross43f08db2018-11-12 10:13:39 -0800461 appImageInstallPath := pathtools.ReplaceExtension(odexInstallPath, "art")
462 cmd.FlagWithOutput("--app-image-file=", appImagePath).
463 FlagWithArg("--image-format=", "lz4")
Mathieu Chartier3f7ddbb2019-04-29 09:33:50 -0700464 if !global.DontResolveStartupStrings {
465 cmd.FlagWithArg("--resolve-startup-const-strings=", "true")
466 }
Colin Cross43f08db2018-11-12 10:13:39 -0800467 rule.Install(appImagePath, appImageInstallPath)
468 }
469
Colin Cross69f59a32019-02-15 10:39:37 -0800470 if profile != nil {
471 cmd.FlagWithInput("--profile-file=", profile)
Colin Cross43f08db2018-11-12 10:13:39 -0800472 }
473
474 rule.Install(odexPath, odexInstallPath)
475 rule.Install(vdexPath, vdexInstallPath)
476}
477
Colin Cross43f08db2018-11-12 10:13:39 -0800478func shouldGenerateDM(module ModuleConfig, global GlobalConfig) bool {
479 // Generating DM files only makes sense for verify, avoid doing for non verify compiler filter APKs.
480 // No reason to use a dm file if the dex is already uncompressed.
481 return global.GenerateDMFiles && !module.UncompressedDex &&
482 contains(module.PreoptFlags, "--compiler-filter=verify")
483}
484
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000485func OdexOnSystemOtherByName(name string, dexLocation string, global GlobalConfig) bool {
Colin Cross43f08db2018-11-12 10:13:39 -0800486 if !global.HasSystemOther {
487 return false
488 }
489
490 if global.SanitizeLite {
491 return false
492 }
493
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000494 if contains(global.SpeedApps, name) || contains(global.SystemServerApps, name) {
Colin Cross43f08db2018-11-12 10:13:39 -0800495 return false
496 }
497
498 for _, f := range global.PatternsOnSystemOther {
Anton Hanssond57bd3c2019-10-14 16:53:02 +0100499 if makefileMatch(filepath.Join(SystemPartition, f), dexLocation) {
Colin Cross43f08db2018-11-12 10:13:39 -0800500 return true
501 }
502 }
503
504 return false
505}
506
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000507func odexOnSystemOther(module ModuleConfig, global GlobalConfig) bool {
508 return OdexOnSystemOtherByName(module.Name, module.DexLocation, global)
509}
510
Colin Crossc7e40aa2019-02-08 21:37:00 -0800511// PathToLocation converts .../system/framework/arm64/boot.art to .../system/framework/boot.art
Colin Cross69f59a32019-02-15 10:39:37 -0800512func PathToLocation(path android.Path, arch android.ArchType) string {
513 pathArch := filepath.Base(filepath.Dir(path.String()))
Colin Cross74ba9622019-02-11 15:11:14 -0800514 if pathArch != arch.String() {
515 panic(fmt.Errorf("last directory in %q must be %q", path, arch.String()))
Colin Crossc7e40aa2019-02-08 21:37:00 -0800516 }
Colin Cross69f59a32019-02-15 10:39:37 -0800517 return filepath.Join(filepath.Dir(filepath.Dir(path.String())), filepath.Base(path.String()))
Colin Crossc7e40aa2019-02-08 21:37:00 -0800518}
519
Colin Cross69f59a32019-02-15 10:39:37 -0800520func pathForLibrary(module ModuleConfig, lib string) android.Path {
521 path, ok := module.LibraryPaths[lib]
522 if !ok {
Colin Cross43f08db2018-11-12 10:13:39 -0800523 panic(fmt.Errorf("unknown library path for %q", lib))
524 }
525 return path
526}
527
528func makefileMatch(pattern, s string) bool {
529 percent := strings.IndexByte(pattern, '%')
530 switch percent {
531 case -1:
532 return pattern == s
533 case len(pattern) - 1:
534 return strings.HasPrefix(s, pattern[:len(pattern)-1])
535 default:
536 panic(fmt.Errorf("unsupported makefile pattern %q", pattern))
537 }
538}
539
Ulyana Trafimovichf2cb7e92019-11-27 12:26:49 +0000540// Expected format for apexJarValue = <apex name>:<jar name>
541func SplitApexJarPair(apexJarValue string) (string, string) {
542 var apexJarPair []string = strings.SplitN(apexJarValue, ":", 2)
543 if apexJarPair == nil || len(apexJarPair) != 2 {
544 panic(fmt.Errorf("malformed apexJarValue: %q, expected format: <apex>:<jar>",
545 apexJarValue))
546 }
547 return apexJarPair[0], apexJarPair[1]
548}
549
Roshan Piusccc26ef2019-11-27 09:37:46 -0800550// Expected format for apexJarValue = <apex name>:<jar name>
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000551func GetJarLocationFromApexJarPair(apexJarValue string) string {
Roshan Piusccc26ef2019-11-27 09:37:46 -0800552 apex, jar := SplitApexJarPair(apexJarValue)
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000553 return filepath.Join("/apex", apex, "javalib", jar+".jar")
Roshan Piusccc26ef2019-11-27 09:37:46 -0800554}
555
Colin Cross43f08db2018-11-12 10:13:39 -0800556func contains(l []string, s string) bool {
557 for _, e := range l {
558 if e == s {
559 return true
560 }
561 }
562 return false
563}
564
565// remove all elements in a from b, returning a new slice
566func filterOut(a []string, b []string) []string {
567 var ret []string
568 for _, x := range b {
569 if !contains(a, x) {
570 ret = append(ret, x)
571 }
572 }
573 return ret
574}
575
576func replace(l []string, from, to string) {
577 for i := range l {
578 if l[i] == from {
579 l[i] = to
580 }
581 }
582}
583
Colin Cross454c0872019-02-15 23:03:34 -0800584var copyOf = android.CopyOf
Colin Cross43f08db2018-11-12 10:13:39 -0800585
586func anyHavePrefix(l []string, prefix string) bool {
587 for _, x := range l {
588 if strings.HasPrefix(x, prefix) {
589 return true
590 }
591 }
592 return false
593}