blob: 40986c344c02eee96a55e9d40f34ff09b25042e6 [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().
Colin Cross69f59a32019-02-15 10:39:37 -080052func GenerateDexpreoptRule(ctx android.PathContext,
53 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 {
Colin Cross69f59a32019-02-15 10:39:37 -080075 profile = profileCommand(ctx, global, module, rule)
Colin Crosscbed6572019-01-08 17:38:37 -080076 }
Nicolas Geoffraye7102422019-07-24 13:19:29 +010077 if generateBootProfile {
78 bootProfileCommand(ctx, global, module, rule)
79 }
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 {
90 dexpreoptCommand(ctx, 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
Colin Cross69f59a32019-02-15 10:39:37 -0800122func profileCommand(ctx android.PathContext, global GlobalConfig, module ModuleConfig,
123 rule *android.RuleBuilder) android.WritablePath {
124
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"`).
134 Tool(global.Tools.Profman)
135
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
Nicolas Geoffraye7102422019-07-24 13:19:29 +0100161func bootProfileCommand(ctx android.PathContext, global GlobalConfig, module ModuleConfig,
162 rule *android.RuleBuilder) android.WritablePath {
163
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"`).
173 Tool(global.Tools.Profman)
174
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
Colin Cross69f59a32019-02-15 10:39:37 -0800193func dexpreoptCommand(ctx android.PathContext, global GlobalConfig, module ModuleConfig, rule *android.RuleBuilder,
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000194 archIdx int, profile android.WritablePath, appImage bool, generateDM bool) {
195
196 arch := module.Archs[archIdx]
Colin Cross43f08db2018-11-12 10:13:39 -0800197
198 // HACK: make soname in Soong-generated .odex files match Make.
199 base := filepath.Base(module.DexLocation)
200 if filepath.Ext(base) == ".jar" {
201 base = "javalib.jar"
202 } else if filepath.Ext(base) == ".apk" {
203 base = "package.apk"
204 }
205
206 toOdexPath := func(path string) string {
207 return filepath.Join(
208 filepath.Dir(path),
209 "oat",
Colin Cross74ba9622019-02-11 15:11:14 -0800210 arch.String(),
Colin Cross43f08db2018-11-12 10:13:39 -0800211 pathtools.ReplaceExtension(filepath.Base(path), "odex"))
212 }
213
Colin Cross69f59a32019-02-15 10:39:37 -0800214 odexPath := module.BuildPath.InSameDir(ctx, "oat", arch.String(), pathtools.ReplaceExtension(base, "odex"))
Colin Cross43f08db2018-11-12 10:13:39 -0800215 odexInstallPath := toOdexPath(module.DexLocation)
216 if odexOnSystemOther(module, global) {
Anton Hansson43ab0bc2019-10-03 14:18:45 +0100217 odexInstallPath = filepath.Join(SystemOtherPartition, odexInstallPath)
Colin Cross43f08db2018-11-12 10:13:39 -0800218 }
219
Colin Cross69f59a32019-02-15 10:39:37 -0800220 vdexPath := odexPath.ReplaceExtension(ctx, "vdex")
Colin Cross43f08db2018-11-12 10:13:39 -0800221 vdexInstallPath := pathtools.ReplaceExtension(odexInstallPath, "vdex")
222
Colin Cross69f59a32019-02-15 10:39:37 -0800223 invocationPath := odexPath.ReplaceExtension(ctx, "invocation")
Alex Light5de41962018-12-18 15:16:26 -0800224
Colin Cross43f08db2018-11-12 10:13:39 -0800225 // The class loader context using paths in the build
Colin Cross69f59a32019-02-15 10:39:37 -0800226 var classLoaderContextHost android.Paths
Colin Cross43f08db2018-11-12 10:13:39 -0800227
228 // The class loader context using paths as they will be on the device
229 var classLoaderContextTarget []string
230
231 // Extra paths that will be appended to the class loader if the APK manifest has targetSdkVersion < 28
Colin Cross69f59a32019-02-15 10:39:37 -0800232 var conditionalClassLoaderContextHost28 android.Paths
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000233 var conditionalClassLoaderContextTarget28 []string
234
235 // Extra paths that will be appended to the class loader if the APK manifest has targetSdkVersion < 29
Colin Cross69f59a32019-02-15 10:39:37 -0800236 var conditionalClassLoaderContextHost29 android.Paths
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000237 var conditionalClassLoaderContextTarget29 []string
Colin Cross43f08db2018-11-12 10:13:39 -0800238
Colin Cross69f59a32019-02-15 10:39:37 -0800239 var classLoaderContextHostString string
240
Colin Cross43f08db2018-11-12 10:13:39 -0800241 if module.EnforceUsesLibraries {
Colin Cross50ddcc42019-05-16 12:28:22 -0700242 usesLibs := append(copyOf(module.UsesLibraries), module.PresentOptionalUsesLibraries...)
Colin Cross43f08db2018-11-12 10:13:39 -0800243
244 // Create class loader context for dex2oat from uses libraries and filtered optional libraries
Colin Cross50ddcc42019-05-16 12:28:22 -0700245 for _, l := range usesLibs {
Colin Cross43f08db2018-11-12 10:13:39 -0800246
247 classLoaderContextHost = append(classLoaderContextHost,
248 pathForLibrary(module, l))
249 classLoaderContextTarget = append(classLoaderContextTarget,
250 filepath.Join("/system/framework", l+".jar"))
251 }
252
253 const httpLegacy = "org.apache.http.legacy"
254 const httpLegacyImpl = "org.apache.http.legacy.impl"
255
Colin Cross38b96852019-05-22 10:21:09 -0700256 // org.apache.http.legacy contains classes that were in the default classpath until API 28. If the
257 // targetSdkVersion in the manifest or APK is < 28, and the module does not explicitly depend on
258 // org.apache.http.legacy, then implicitly add the classes to the classpath for dexpreopt. One the
259 // device the classes will be in a file called org.apache.http.legacy.impl.jar.
Colin Cross50ddcc42019-05-16 12:28:22 -0700260 module.LibraryPaths[httpLegacyImpl] = module.LibraryPaths[httpLegacy]
261
262 if !contains(module.UsesLibraries, httpLegacy) && !contains(module.PresentOptionalUsesLibraries, httpLegacy) {
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000263 conditionalClassLoaderContextHost28 = append(conditionalClassLoaderContextHost28,
Colin Cross43f08db2018-11-12 10:13:39 -0800264 pathForLibrary(module, httpLegacyImpl))
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000265 conditionalClassLoaderContextTarget28 = append(conditionalClassLoaderContextTarget28,
Colin Cross43f08db2018-11-12 10:13:39 -0800266 filepath.Join("/system/framework", httpLegacyImpl+".jar"))
267 }
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000268
269 const hidlBase = "android.hidl.base-V1.0-java"
270 const hidlManager = "android.hidl.manager-V1.0-java"
271
Colin Cross38b96852019-05-22 10:21:09 -0700272 // android.hidl.base-V1.0-java and android.hidl.manager-V1.0 contain classes that were in the default
273 // classpath until API 29. If the targetSdkVersion in the manifest or APK is < 29 then implicitly add
274 // the classes to the classpath for dexpreopt.
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000275 conditionalClassLoaderContextHost29 = append(conditionalClassLoaderContextHost29,
Alex Light5de41962018-12-18 15:16:26 -0800276 pathForLibrary(module, hidlManager))
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000277 conditionalClassLoaderContextTarget29 = append(conditionalClassLoaderContextTarget29,
278 filepath.Join("/system/framework", hidlManager+".jar"))
279 conditionalClassLoaderContextHost29 = append(conditionalClassLoaderContextHost29,
Alex Light5de41962018-12-18 15:16:26 -0800280 pathForLibrary(module, hidlBase))
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000281 conditionalClassLoaderContextTarget29 = append(conditionalClassLoaderContextTarget29,
282 filepath.Join("/system/framework", hidlBase+".jar"))
Colin Cross69f59a32019-02-15 10:39:37 -0800283
284 classLoaderContextHostString = strings.Join(classLoaderContextHost.Strings(), ":")
Colin Cross43f08db2018-11-12 10:13:39 -0800285 } else {
286 // Pass special class loader context to skip the classpath and collision check.
287 // This will get removed once LOCAL_USES_LIBRARIES is enforced.
288 // Right now LOCAL_USES_LIBRARIES is opt in, for the case where it's not specified we still default
289 // to the &.
Colin Cross69f59a32019-02-15 10:39:37 -0800290 classLoaderContextHostString = `\&`
Colin Cross43f08db2018-11-12 10:13:39 -0800291 }
292
Colin Cross69f59a32019-02-15 10:39:37 -0800293 rule.Command().FlagWithArg("mkdir -p ", filepath.Dir(odexPath.String()))
Colin Cross43f08db2018-11-12 10:13:39 -0800294 rule.Command().FlagWithOutput("rm -f ", odexPath)
295 // Set values in the environment of the rule. These may be modified by construct_context.sh.
Colin Cross69f59a32019-02-15 10:39:37 -0800296 rule.Command().FlagWithArg("class_loader_context_arg=--class-loader-context=", classLoaderContextHostString)
Colin Cross43f08db2018-11-12 10:13:39 -0800297 rule.Command().Text(`stored_class_loader_context_arg=""`)
298
299 if module.EnforceUsesLibraries {
Colin Cross38b96852019-05-22 10:21:09 -0700300 if module.ManifestPath != nil {
301 rule.Command().Text(`target_sdk_version="$(`).
302 Tool(global.Tools.ManifestCheck).
303 Flag("--extract-target-sdk-version").
304 Input(module.ManifestPath).
305 Text(`)"`)
306 } else {
307 // No manifest to extract targetSdkVersion from, hope that DexJar is an APK
308 rule.Command().Text(`target_sdk_version="$(`).
309 Tool(global.Tools.Aapt).
310 Flag("dump badging").
311 Input(module.DexPath).
312 Text(`| grep "targetSdkVersion" | sed -n "s/targetSdkVersion:'\(.*\)'/\1/p"`).
313 Text(`)"`)
314 }
Colin Cross69f59a32019-02-15 10:39:37 -0800315 rule.Command().Textf(`dex_preopt_host_libraries="%s"`,
316 strings.Join(classLoaderContextHost.Strings(), " ")).
317 Implicits(classLoaderContextHost)
318 rule.Command().Textf(`dex_preopt_target_libraries="%s"`,
319 strings.Join(classLoaderContextTarget, " "))
320 rule.Command().Textf(`conditional_host_libs_28="%s"`,
321 strings.Join(conditionalClassLoaderContextHost28.Strings(), " ")).
322 Implicits(conditionalClassLoaderContextHost28)
323 rule.Command().Textf(`conditional_target_libs_28="%s"`,
324 strings.Join(conditionalClassLoaderContextTarget28, " "))
325 rule.Command().Textf(`conditional_host_libs_29="%s"`,
326 strings.Join(conditionalClassLoaderContextHost29.Strings(), " ")).
327 Implicits(conditionalClassLoaderContextHost29)
328 rule.Command().Textf(`conditional_target_libs_29="%s"`,
329 strings.Join(conditionalClassLoaderContextTarget29, " "))
Colin Cross38b96852019-05-22 10:21:09 -0700330 rule.Command().Text("source").Tool(global.Tools.ConstructContext).Input(module.DexPath)
Colin Cross43f08db2018-11-12 10:13:39 -0800331 }
332
Nicolas Geoffray2464ef42019-03-05 14:07:07 +0000333 // Devices that do not have a product partition use a symlink from /product to /system/product.
334 // Because on-device dexopt will see dex locations starting with /product, we change the paths
335 // to mimic this behavior.
336 dexLocationArg := module.DexLocation
337 if strings.HasPrefix(dexLocationArg, "/system/product/") {
338 dexLocationArg = strings.TrimPrefix(dexLocationArg, "/system")
339 }
340
Colin Cross43f08db2018-11-12 10:13:39 -0800341 cmd := rule.Command().
342 Text(`ANDROID_LOG_TAGS="*:e"`).
343 Tool(global.Tools.Dex2oat).
344 Flag("--avoid-storing-invocation").
Alex Light5de41962018-12-18 15:16:26 -0800345 FlagWithOutput("--write-invocation-to=", invocationPath).ImplicitOutput(invocationPath).
Colin Cross43f08db2018-11-12 10:13:39 -0800346 Flag("--runtime-arg").FlagWithArg("-Xms", global.Dex2oatXms).
347 Flag("--runtime-arg").FlagWithArg("-Xmx", global.Dex2oatXmx).
Colin Cross800fe132019-02-11 14:21:24 -0800348 Flag("--runtime-arg").FlagWithInputList("-Xbootclasspath:", module.PreoptBootClassPathDexFiles, ":").
349 Flag("--runtime-arg").FlagWithList("-Xbootclasspath-locations:", module.PreoptBootClassPathDexLocations, ":").
Colin Cross43f08db2018-11-12 10:13:39 -0800350 Flag("${class_loader_context_arg}").
351 Flag("${stored_class_loader_context_arg}").
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000352 FlagWithArg("--boot-image=", strings.Join(module.DexPreoptImageLocations, ":")).Implicits(module.DexPreoptImagesDeps[archIdx].Paths()).
Colin Cross43f08db2018-11-12 10:13:39 -0800353 FlagWithInput("--dex-file=", module.DexPath).
Nicolas Geoffray2464ef42019-03-05 14:07:07 +0000354 FlagWithArg("--dex-location=", dexLocationArg).
Colin Cross43f08db2018-11-12 10:13:39 -0800355 FlagWithOutput("--oat-file=", odexPath).ImplicitOutput(vdexPath).
356 // Pass an empty directory, dex2oat shouldn't be reading arbitrary files
357 FlagWithArg("--android-root=", global.EmptyDirectory).
Colin Cross74ba9622019-02-11 15:11:14 -0800358 FlagWithArg("--instruction-set=", arch.String()).
Colin Cross43f08db2018-11-12 10:13:39 -0800359 FlagWithArg("--instruction-set-variant=", global.CpuVariant[arch]).
360 FlagWithArg("--instruction-set-features=", global.InstructionSetFeatures[arch]).
361 Flag("--no-generate-debug-info").
362 Flag("--generate-build-id").
363 Flag("--abort-on-hard-verifier-error").
364 Flag("--force-determinism").
365 FlagWithArg("--no-inline-from=", "core-oj.jar")
366
367 var preoptFlags []string
368 if len(module.PreoptFlags) > 0 {
369 preoptFlags = module.PreoptFlags
370 } else if len(global.PreoptFlags) > 0 {
371 preoptFlags = global.PreoptFlags
372 }
373
374 if len(preoptFlags) > 0 {
375 cmd.Text(strings.Join(preoptFlags, " "))
376 }
377
378 if module.UncompressedDex {
379 cmd.FlagWithArg("--copy-dex-files=", "false")
380 }
381
382 if !anyHavePrefix(preoptFlags, "--compiler-filter=") {
383 var compilerFilter string
384 if contains(global.SystemServerJars, module.Name) {
385 // Jars of system server, use the product option if it is set, speed otherwise.
386 if global.SystemServerCompilerFilter != "" {
387 compilerFilter = global.SystemServerCompilerFilter
388 } else {
389 compilerFilter = "speed"
390 }
391 } else if contains(global.SpeedApps, module.Name) || contains(global.SystemServerApps, module.Name) {
392 // Apps loaded into system server, and apps the product default to being compiled with the
393 // 'speed' compiler filter.
394 compilerFilter = "speed"
Colin Cross69f59a32019-02-15 10:39:37 -0800395 } else if profile != nil {
Colin Cross43f08db2018-11-12 10:13:39 -0800396 // For non system server jars, use speed-profile when we have a profile.
397 compilerFilter = "speed-profile"
398 } else if global.DefaultCompilerFilter != "" {
399 compilerFilter = global.DefaultCompilerFilter
400 } else {
401 compilerFilter = "quicken"
402 }
403 cmd.FlagWithArg("--compiler-filter=", compilerFilter)
404 }
405
406 if generateDM {
407 cmd.FlagWithArg("--copy-dex-files=", "false")
Colin Cross69f59a32019-02-15 10:39:37 -0800408 dmPath := module.BuildPath.InSameDir(ctx, "generated.dm")
Colin Cross43f08db2018-11-12 10:13:39 -0800409 dmInstalledPath := pathtools.ReplaceExtension(module.DexLocation, "dm")
Colin Cross69f59a32019-02-15 10:39:37 -0800410 tmpPath := module.BuildPath.InSameDir(ctx, "primary.vdex")
Colin Cross43f08db2018-11-12 10:13:39 -0800411 rule.Command().Text("cp -f").Input(vdexPath).Output(tmpPath)
412 rule.Command().Tool(global.Tools.SoongZip).
413 FlagWithArg("-L", "9").
414 FlagWithOutput("-o", dmPath).
415 Flag("-j").
416 Input(tmpPath)
417 rule.Install(dmPath, dmInstalledPath)
418 }
419
420 // By default, emit debug info.
421 debugInfo := true
422 if global.NoDebugInfo {
423 // If the global setting suppresses mini-debug-info, disable it.
424 debugInfo = false
425 }
426
427 // PRODUCT_SYSTEM_SERVER_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO.
428 // PRODUCT_OTHER_JAVA_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO.
429 if contains(global.SystemServerJars, module.Name) {
430 if global.AlwaysSystemServerDebugInfo {
431 debugInfo = true
432 } else if global.NeverSystemServerDebugInfo {
433 debugInfo = false
434 }
435 } else {
436 if global.AlwaysOtherDebugInfo {
437 debugInfo = true
438 } else if global.NeverOtherDebugInfo {
439 debugInfo = false
440 }
441 }
442
443 // Never enable on eng.
444 if global.IsEng {
445 debugInfo = false
446 }
447
448 if debugInfo {
449 cmd.Flag("--generate-mini-debug-info")
450 } else {
451 cmd.Flag("--no-generate-mini-debug-info")
452 }
453
454 // Set the compiler reason to 'prebuilt' to identify the oat files produced
455 // during the build, as opposed to compiled on the device.
456 cmd.FlagWithArg("--compilation-reason=", "prebuilt")
457
458 if appImage {
Colin Cross69f59a32019-02-15 10:39:37 -0800459 appImagePath := odexPath.ReplaceExtension(ctx, "art")
Colin Cross43f08db2018-11-12 10:13:39 -0800460 appImageInstallPath := pathtools.ReplaceExtension(odexInstallPath, "art")
461 cmd.FlagWithOutput("--app-image-file=", appImagePath).
462 FlagWithArg("--image-format=", "lz4")
Mathieu Chartier3f7ddbb2019-04-29 09:33:50 -0700463 if !global.DontResolveStartupStrings {
464 cmd.FlagWithArg("--resolve-startup-const-strings=", "true")
465 }
Colin Cross43f08db2018-11-12 10:13:39 -0800466 rule.Install(appImagePath, appImageInstallPath)
467 }
468
Colin Cross69f59a32019-02-15 10:39:37 -0800469 if profile != nil {
470 cmd.FlagWithInput("--profile-file=", profile)
Colin Cross43f08db2018-11-12 10:13:39 -0800471 }
472
473 rule.Install(odexPath, odexInstallPath)
474 rule.Install(vdexPath, vdexInstallPath)
475}
476
Colin Cross43f08db2018-11-12 10:13:39 -0800477func shouldGenerateDM(module ModuleConfig, global GlobalConfig) bool {
478 // Generating DM files only makes sense for verify, avoid doing for non verify compiler filter APKs.
479 // No reason to use a dm file if the dex is already uncompressed.
480 return global.GenerateDMFiles && !module.UncompressedDex &&
481 contains(module.PreoptFlags, "--compiler-filter=verify")
482}
483
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000484func OdexOnSystemOtherByName(name string, dexLocation string, global GlobalConfig) bool {
Colin Cross43f08db2018-11-12 10:13:39 -0800485 if !global.HasSystemOther {
486 return false
487 }
488
489 if global.SanitizeLite {
490 return false
491 }
492
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000493 if contains(global.SpeedApps, name) || contains(global.SystemServerApps, name) {
Colin Cross43f08db2018-11-12 10:13:39 -0800494 return false
495 }
496
497 for _, f := range global.PatternsOnSystemOther {
Anton Hansson12b8d422019-10-02 18:14:02 +0100498 // See comment of SYSTEM_OTHER_ODEX_FILTER for details on the matching.
499 if makefileMatch("/"+f, dexLocation) || 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}