blob: 1844bce6e8a888e80b1c613b96767b399b540f39 [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
15package dexpreopt
16
17import (
18 "encoding/json"
Martin Stjernholmd90676f2020-01-11 00:37:30 +000019 "fmt"
Paul Duffin7d1d0832021-04-23 11:39:41 +010020 "reflect"
Colin Cross69f59a32019-02-15 10:39:37 -080021 "strings"
Colin Cross74ba9622019-02-11 15:11:14 -080022
Martin Stjernholmd90676f2020-01-11 00:37:30 +000023 "github.com/google/blueprint"
24
Colin Cross74ba9622019-02-11 15:11:14 -080025 "android/soong/android"
Colin Cross43f08db2018-11-12 10:13:39 -080026)
27
Martin Stjernholmc52aaf12020-01-06 23:11:37 +000028// GlobalConfig stores the configuration for dex preopting. The fields are set
Martin Stjernholm75a48d82020-01-10 20:32:59 +000029// from product variables via dex_preopt_config.mk.
Colin Cross43f08db2018-11-12 10:13:39 -080030type GlobalConfig struct {
Ulya Trafimovicha4a1c4e2021-01-15 18:40:04 +000031 DisablePreopt bool // disable preopt for all modules (excluding boot images)
32 DisablePreoptBootImages bool // disable prepot for boot images
33 DisablePreoptModules []string // modules with preopt disabled by product-specific config
Colin Cross43f08db2018-11-12 10:13:39 -080034
35 OnlyPreoptBootImageAndSystemServer bool // only preopt jars in the boot image or system server
36
Ulya Trafimovich9023b022021-03-22 16:02:28 +000037 PreoptWithUpdatableBcp bool // If updatable boot jars are included in dexpreopt or not.
38
Vladimir Marko40139d62020-02-06 15:14:29 +000039 UseArtImage bool // use the art image (use other boot class path dex files without image)
40
Colin Cross43f08db2018-11-12 10:13:39 -080041 HasSystemOther bool // store odex files that match PatternsOnSystemOther on the system_other partition
42 PatternsOnSystemOther []string // patterns (using '%' to denote a prefix match) to put odex on the system_other partition
43
Colin Cross69f59a32019-02-15 10:39:37 -080044 DisableGenerateProfile bool // don't generate profiles
45 ProfileDir string // directory to find profiles in
Colin Cross43f08db2018-11-12 10:13:39 -080046
Ulya Trafimovich249386a2020-07-01 14:31:13 +010047 BootJars android.ConfiguredJarList // modules for jars that form the boot class path
48 UpdatableBootJars android.ConfiguredJarList // jars within apex that form the boot class path
Vladimir Markod2ee5322018-12-19 17:57:57 +000049
Ulya Trafimovich249386a2020-07-01 14:31:13 +010050 ArtApexJars android.ConfiguredJarList // modules for jars that are in the ART APEX
Colin Cross800fe132019-02-11 14:21:24 -080051
satayev9a6f87e2021-05-04 16:14:48 +010052 SystemServerJars android.ConfiguredJarList // jars that form the system server
Ulya Trafimovich249386a2020-07-01 14:31:13 +010053 SystemServerApps []string // apps that are loaded into system server
54 UpdatableSystemServerJars android.ConfiguredJarList // jars within apex that are loaded into system server
55 SpeedApps []string // apps that should be speed optimized
Colin Cross43f08db2018-11-12 10:13:39 -080056
Ulya Trafimovichcd3203f2020-03-27 11:30:00 +000057 BrokenSuboptimalOrderOfSystemServerJars bool // if true, sub-optimal order does not cause a build error
58
Colin Cross43f08db2018-11-12 10:13:39 -080059 PreoptFlags []string // global dex2oat flags that should be used if no module-specific dex2oat flags are specified
60
61 DefaultCompilerFilter string // default compiler filter to pass to dex2oat, overridden by --compiler-filter= in module-specific dex2oat flags
62 SystemServerCompilerFilter string // default compiler filter to pass to dex2oat for system server jars
63
Nicolas Geoffrayc1bf7242019-10-18 14:51:38 +010064 GenerateDMFiles bool // generate Dex Metadata files
Colin Cross43f08db2018-11-12 10:13:39 -080065
66 NoDebugInfo bool // don't generate debug info by default
Mathieu Chartier3f7ddbb2019-04-29 09:33:50 -070067 DontResolveStartupStrings bool // don't resolve string literals loaded during application startup.
Colin Cross43f08db2018-11-12 10:13:39 -080068 AlwaysSystemServerDebugInfo bool // always generate mini debug info for system server modules (overrides NoDebugInfo=true)
69 NeverSystemServerDebugInfo bool // never generate mini debug info for system server modules (overrides NoDebugInfo=false)
70 AlwaysOtherDebugInfo bool // always generate mini debug info for non-system server modules (overrides NoDebugInfo=true)
71 NeverOtherDebugInfo bool // never generate mini debug info for non-system server modules (overrides NoDebugInfo=true)
72
Colin Cross43f08db2018-11-12 10:13:39 -080073 IsEng bool // build is a eng variant
74 SanitizeLite bool // build is the second phase of a SANITIZE_LITE build
75
76 DefaultAppImages bool // build app images (TODO: .art files?) by default
77
Colin Cross800fe132019-02-11 14:21:24 -080078 Dex2oatXmx string // max heap size for dex2oat
79 Dex2oatXms string // initial heap size for dex2oat
Colin Cross43f08db2018-11-12 10:13:39 -080080
81 EmptyDirectory string // path to an empty directory
82
Colin Cross74ba9622019-02-11 15:11:14 -080083 CpuVariant map[android.ArchType]string // cpu variant for each architecture
84 InstructionSetFeatures map[android.ArchType]string // instruction set for each architecture
Colin Cross43f08db2018-11-12 10:13:39 -080085
Nicolas Geoffray1086e602021-01-20 14:30:40 +000086 BootImageProfiles android.Paths // path to a boot-image-profile.txt file
87 BootFlags string // extra flags to pass to dex2oat for the boot image
88 Dex2oatImageXmx string // max heap size for dex2oat for the boot image
89 Dex2oatImageXms string // initial heap size for dex2oat for the boot image
Ulya Trafimovich8c35fcf2021-02-17 16:23:28 +000090
Ulya Trafimovich4a13acb2021-03-02 12:25:02 +000091 // If true, downgrade the compiler filter of dexpreopt to "verify" when verify_uses_libraries
Ulya Trafimovich8c35fcf2021-02-17 16:23:28 +000092 // check fails, instead of failing the build. This will disable any AOT-compilation.
93 //
94 // The intended use case for this flag is to have a smoother migration path for the Java
95 // modules that need to add <uses-library> information in their build files. The flag allows to
96 // quickly silence build errors. This flag should be used with caution and only as a temporary
97 // measure, as it masks real errors and affects performance.
98 RelaxUsesLibraryCheck bool
Colin Cross43f08db2018-11-12 10:13:39 -080099}
100
Martin Stjernholmc52aaf12020-01-06 23:11:37 +0000101// GlobalSoongConfig contains the global config that is generated from Soong,
102// stored in dexpreopt_soong.config.
103type GlobalSoongConfig struct {
104 // Paths to tools possibly used by the generated commands.
105 Profman android.Path
106 Dex2oat android.Path
107 Aapt android.Path
108 SoongZip android.Path
109 Zip2zip android.Path
110 ManifestCheck android.Path
Colin Cross38b96852019-05-22 10:21:09 -0700111 ConstructContext android.Path
Colin Cross43f08db2018-11-12 10:13:39 -0800112}
113
114type ModuleConfig struct {
Victor Hsiehd181c8b2019-01-29 13:00:33 -0800115 Name string
116 DexLocation string // dex location on device
Colin Cross69f59a32019-02-15 10:39:37 -0800117 BuildPath android.OutputPath
118 DexPath android.Path
Jeongik Cha33a3a812021-04-15 09:12:49 +0900119 ManifestPath android.OptionalPath
Victor Hsiehd181c8b2019-01-29 13:00:33 -0800120 UncompressedDex bool
121 HasApkLibraries bool
122 PreoptFlags []string
Colin Cross43f08db2018-11-12 10:13:39 -0800123
Colin Cross69f59a32019-02-15 10:39:37 -0800124 ProfileClassListing android.OptionalPath
Colin Cross43f08db2018-11-12 10:13:39 -0800125 ProfileIsTextListing bool
Nicolas Geoffraye7102422019-07-24 13:19:29 +0100126 ProfileBootListing android.OptionalPath
Colin Cross43f08db2018-11-12 10:13:39 -0800127
Ulya Trafimovich8c35fcf2021-02-17 16:23:28 +0000128 EnforceUsesLibraries bool // turn on build-time verify_uses_libraries check
129 EnforceUsesLibrariesStatusFile android.Path // a file with verify_uses_libraries errors (if any)
130 ProvidesUsesLibrary string // library name (usually the same as module name)
131 ClassLoaderContexts ClassLoaderContextMap
Colin Cross43f08db2018-11-12 10:13:39 -0800132
Jeongik Chaa5969092021-05-07 18:53:21 +0900133 Archs []android.ArchType
134 DexPreoptImagesDeps []android.OutputPaths
135 DexPreoptImageLocationsOnHost []string // boot image location on host (file path without the arch subdirectory)
Colin Cross43f08db2018-11-12 10:13:39 -0800136
Colin Cross69f59a32019-02-15 10:39:37 -0800137 PreoptBootClassPathDexFiles android.Paths // file paths of boot class path files
138 PreoptBootClassPathDexLocations []string // virtual locations of boot class path files
Colin Cross800fe132019-02-11 14:21:24 -0800139
Colin Cross43f08db2018-11-12 10:13:39 -0800140 PreoptExtractedApk bool // Overrides OnlyPreoptModules
141
142 NoCreateAppImage bool
143 ForceCreateAppImage bool
144
145 PresignedPrebuilt bool
Colin Cross43f08db2018-11-12 10:13:39 -0800146}
147
Martin Stjernholmc52aaf12020-01-06 23:11:37 +0000148type globalSoongConfigSingleton struct{}
149
150var pctx = android.NewPackageContext("android/soong/dexpreopt")
151
152func init() {
153 pctx.Import("android/soong/android")
154 android.RegisterSingletonType("dexpreopt-soong-config", func() android.Singleton {
155 return &globalSoongConfigSingleton{}
156 })
157}
158
Colin Cross69f59a32019-02-15 10:39:37 -0800159func constructPath(ctx android.PathContext, path string) android.Path {
160 buildDirPrefix := ctx.Config().BuildDir() + "/"
161 if path == "" {
162 return nil
163 } else if strings.HasPrefix(path, buildDirPrefix) {
164 return android.PathForOutput(ctx, strings.TrimPrefix(path, buildDirPrefix))
165 } else {
166 return android.PathForSource(ctx, path)
167 }
Colin Cross43f08db2018-11-12 10:13:39 -0800168}
169
Colin Cross69f59a32019-02-15 10:39:37 -0800170func constructPaths(ctx android.PathContext, paths []string) android.Paths {
171 var ret android.Paths
172 for _, path := range paths {
173 ret = append(ret, constructPath(ctx, path))
174 }
175 return ret
Colin Cross43f08db2018-11-12 10:13:39 -0800176}
177
Colin Cross69f59a32019-02-15 10:39:37 -0800178func constructWritablePath(ctx android.PathContext, path string) android.WritablePath {
179 if path == "" {
180 return nil
181 }
182 return constructPath(ctx, path).(android.WritablePath)
183}
184
Martin Stjernholm40f9f3c2020-01-20 18:12:23 +0000185// ParseGlobalConfig parses the given data assumed to be read from the global
186// dexpreopt.config file into a GlobalConfig struct.
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000187func ParseGlobalConfig(ctx android.PathContext, data []byte) (*GlobalConfig, error) {
Colin Cross69f59a32019-02-15 10:39:37 -0800188 type GlobalJSONConfig struct {
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000189 *GlobalConfig
Colin Cross69f59a32019-02-15 10:39:37 -0800190
191 // Copies of entries in GlobalConfig that are not constructable without extra parameters. They will be
192 // used to construct the real value manually below.
Paul Duffin7ccacae2020-10-23 21:14:20 +0100193 BootImageProfiles []string
Colin Cross69f59a32019-02-15 10:39:37 -0800194 }
195
196 config := GlobalJSONConfig{}
Colin Cross988414c2020-01-11 01:11:46 +0000197 err := json.Unmarshal(data, &config)
Colin Cross69f59a32019-02-15 10:39:37 -0800198 if err != nil {
Colin Cross988414c2020-01-11 01:11:46 +0000199 return config.GlobalConfig, err
Colin Cross69f59a32019-02-15 10:39:37 -0800200 }
201
202 // Construct paths that require a PathContext.
Colin Cross69f59a32019-02-15 10:39:37 -0800203 config.GlobalConfig.BootImageProfiles = constructPaths(ctx, config.BootImageProfiles)
204
Colin Cross988414c2020-01-11 01:11:46 +0000205 return config.GlobalConfig, nil
Colin Cross69f59a32019-02-15 10:39:37 -0800206}
207
Martin Stjernholm40f9f3c2020-01-20 18:12:23 +0000208type globalConfigAndRaw struct {
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000209 global *GlobalConfig
Martin Stjernholm40f9f3c2020-01-20 18:12:23 +0000210 data []byte
211}
212
213// GetGlobalConfig returns the global dexpreopt.config that's created in the
214// make config phase. It is loaded once the first time it is called for any
215// ctx.Config(), and returns the same data for all future calls with the same
216// ctx.Config(). A value can be inserted for tests using
217// setDexpreoptTestGlobalConfig.
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000218func GetGlobalConfig(ctx android.PathContext) *GlobalConfig {
Martin Stjernholm40f9f3c2020-01-20 18:12:23 +0000219 return getGlobalConfigRaw(ctx).global
220}
221
222// GetGlobalConfigRawData is the same as GetGlobalConfig, except that it returns
223// the literal content of dexpreopt.config.
224func GetGlobalConfigRawData(ctx android.PathContext) []byte {
225 return getGlobalConfigRaw(ctx).data
226}
227
228var globalConfigOnceKey = android.NewOnceKey("DexpreoptGlobalConfig")
229var testGlobalConfigOnceKey = android.NewOnceKey("TestDexpreoptGlobalConfig")
230
231func getGlobalConfigRaw(ctx android.PathContext) globalConfigAndRaw {
232 return ctx.Config().Once(globalConfigOnceKey, func() interface{} {
233 if data, err := ctx.Config().DexpreoptGlobalConfig(ctx); err != nil {
234 panic(err)
235 } else if data != nil {
236 globalConfig, err := ParseGlobalConfig(ctx, data)
237 if err != nil {
238 panic(err)
239 }
240 return globalConfigAndRaw{globalConfig, data}
241 }
242
243 // No global config filename set, see if there is a test config set
244 return ctx.Config().Once(testGlobalConfigOnceKey, func() interface{} {
245 // Nope, return a config with preopting disabled
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000246 return globalConfigAndRaw{&GlobalConfig{
Ulya Trafimovicha4a1c4e2021-01-15 18:40:04 +0000247 DisablePreopt: true,
248 DisablePreoptBootImages: true,
249 DisableGenerateProfile: true,
Martin Stjernholm40f9f3c2020-01-20 18:12:23 +0000250 }, nil}
251 })
252 }).(globalConfigAndRaw)
253}
254
255// SetTestGlobalConfig sets a GlobalConfig that future calls to GetGlobalConfig
256// will return. It must be called before the first call to GetGlobalConfig for
257// the config.
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000258func SetTestGlobalConfig(config android.Config, globalConfig *GlobalConfig) {
Martin Stjernholm40f9f3c2020-01-20 18:12:23 +0000259 config.Once(testGlobalConfigOnceKey, func() interface{} { return globalConfigAndRaw{globalConfig, nil} })
260}
261
Jeongik Chac6246672021-04-08 00:00:19 +0900262// This struct is required to convert ModuleConfig from/to JSON.
263// The types of fields in ModuleConfig are not convertible,
264// so moduleJSONConfig has those fields as a convertible type.
265type moduleJSONConfig struct {
266 *ModuleConfig
267
268 BuildPath string
269 DexPath string
270 ManifestPath string
271
272 ProfileClassListing string
273 ProfileBootListing string
274
275 EnforceUsesLibrariesStatusFile string
276 ClassLoaderContexts jsonClassLoaderContextMap
277
Jeongik Chac6246672021-04-08 00:00:19 +0900278 DexPreoptImagesDeps [][]string
279
280 PreoptBootClassPathDexFiles []string
281}
282
Martin Stjernholm40f9f3c2020-01-20 18:12:23 +0000283// ParseModuleConfig parses a per-module dexpreopt.config file into a
284// ModuleConfig struct. It is not used in Soong, which receives a ModuleConfig
285// struct directly from java/dexpreopt.go. It is used in dexpreopt_gen called
286// from Make to read the module dexpreopt.config written in the Make config
287// stage.
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000288func ParseModuleConfig(ctx android.PathContext, data []byte) (*ModuleConfig, error) {
Jeongik Chac6246672021-04-08 00:00:19 +0900289 config := moduleJSONConfig{}
Colin Cross69f59a32019-02-15 10:39:37 -0800290
Colin Cross988414c2020-01-11 01:11:46 +0000291 err := json.Unmarshal(data, &config)
Colin Cross69f59a32019-02-15 10:39:37 -0800292 if err != nil {
293 return config.ModuleConfig, err
294 }
295
296 // Construct paths that require a PathContext.
297 config.ModuleConfig.BuildPath = constructPath(ctx, config.BuildPath).(android.OutputPath)
298 config.ModuleConfig.DexPath = constructPath(ctx, config.DexPath)
Jeongik Cha33a3a812021-04-15 09:12:49 +0900299 config.ModuleConfig.ManifestPath = android.OptionalPathForPath(constructPath(ctx, config.ManifestPath))
Colin Cross69f59a32019-02-15 10:39:37 -0800300 config.ModuleConfig.ProfileClassListing = android.OptionalPathForPath(constructPath(ctx, config.ProfileClassListing))
Ulya Trafimovich8c35fcf2021-02-17 16:23:28 +0000301 config.ModuleConfig.EnforceUsesLibrariesStatusFile = constructPath(ctx, config.EnforceUsesLibrariesStatusFile)
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000302 config.ModuleConfig.ClassLoaderContexts = fromJsonClassLoaderContext(ctx, config.ClassLoaderContexts)
Colin Cross69f59a32019-02-15 10:39:37 -0800303 config.ModuleConfig.PreoptBootClassPathDexFiles = constructPaths(ctx, config.PreoptBootClassPathDexFiles)
Colin Cross69f59a32019-02-15 10:39:37 -0800304
Dan Willemsen0f416782019-06-13 21:44:53 +0000305 // This needs to exist, but dependencies are already handled in Make, so we don't need to pass them through JSON.
Jeongik Chab19b58a2021-04-26 22:57:27 +0900306 config.ModuleConfig.DexPreoptImagesDeps = make([]android.OutputPaths, len(config.ModuleConfig.Archs))
Dan Willemsen0f416782019-06-13 21:44:53 +0000307
Colin Cross69f59a32019-02-15 10:39:37 -0800308 return config.ModuleConfig, nil
309}
310
Jeongik Chac6246672021-04-08 00:00:19 +0900311func pathsListToStringLists(pathsList []android.OutputPaths) [][]string {
312 ret := make([][]string, 0, len(pathsList))
313 for _, paths := range pathsList {
314 ret = append(ret, paths.Strings())
315 }
316 return ret
317}
318
319func moduleConfigToJSON(config *ModuleConfig) ([]byte, error) {
320 return json.MarshalIndent(&moduleJSONConfig{
321 BuildPath: config.BuildPath.String(),
322 DexPath: config.DexPath.String(),
323 ManifestPath: config.ManifestPath.String(),
324 ProfileClassListing: config.ProfileClassListing.String(),
325 ProfileBootListing: config.ProfileBootListing.String(),
326 EnforceUsesLibrariesStatusFile: config.EnforceUsesLibrariesStatusFile.String(),
327 ClassLoaderContexts: toJsonClassLoaderContext(config.ClassLoaderContexts),
Jeongik Chac6246672021-04-08 00:00:19 +0900328 DexPreoptImagesDeps: pathsListToStringLists(config.DexPreoptImagesDeps),
329 PreoptBootClassPathDexFiles: config.PreoptBootClassPathDexFiles.Strings(),
330 ModuleConfig: config,
331 }, "", " ")
332}
333
334// WriteModuleConfig serializes a ModuleConfig into a per-module dexpreopt.config JSON file.
335// These config files are used for post-processing.
336func WriteModuleConfig(ctx android.ModuleContext, config *ModuleConfig, path android.WritablePath) {
Ulya Trafimovich76b08522021-01-14 17:52:43 +0000337 if path == nil {
338 return
339 }
340
Jeongik Chac6246672021-04-08 00:00:19 +0900341 data, err := moduleConfigToJSON(config)
Ulya Trafimovich76b08522021-01-14 17:52:43 +0000342 if err != nil {
343 ctx.ModuleErrorf("failed to JSON marshal module dexpreopt.config: %v", err)
344 return
345 }
346
347 android.WriteFileRule(ctx, path, string(data))
348}
349
Martin Stjernholmd90676f2020-01-11 00:37:30 +0000350// dex2oatModuleName returns the name of the module to use for the dex2oat host
351// tool. It should be a binary module with public visibility that is compiled
352// and installed for host.
353func dex2oatModuleName(config android.Config) string {
354 // Default to the debug variant of dex2oat to help find bugs.
355 // Set USE_DEX2OAT_DEBUG to false for only building non-debug versions.
356 if config.Getenv("USE_DEX2OAT_DEBUG") == "false" {
357 return "dex2oat"
358 } else {
359 return "dex2oatd"
360 }
361}
362
Paul Duffinb506c9d2021-03-24 14:34:40 +0000363type dex2oatDependencyTag struct {
Martin Stjernholmd90676f2020-01-11 00:37:30 +0000364 blueprint.BaseDependencyTag
Paul Duffinb506c9d2021-03-24 14:34:40 +0000365}
366
367func (d dex2oatDependencyTag) ExcludeFromVisibilityEnforcement() {
368}
369
370func (d dex2oatDependencyTag) ExcludeFromApexContents() {
371}
372
373// Dex2oatDepTag represents the dependency onto the dex2oatd module. It is added to any module that
374// needs dexpreopting and so it makes no sense for it to be checked for visibility or included in
375// the apex.
376var Dex2oatDepTag = dex2oatDependencyTag{}
377
378var _ android.ExcludeFromVisibilityEnforcementTag = Dex2oatDepTag
379var _ android.ExcludeFromApexContentsTag = Dex2oatDepTag
Martin Stjernholmd90676f2020-01-11 00:37:30 +0000380
Martin Stjernholm6d415272020-01-31 17:10:36 +0000381// RegisterToolDeps adds the necessary dependencies to binary modules for tools
382// that are required later when Get(Cached)GlobalSoongConfig is called. It
383// should be called from a mutator that's registered with
384// android.RegistrationContext.FinalDepsMutators.
385func RegisterToolDeps(ctx android.BottomUpMutatorContext) {
Martin Stjernholmd90676f2020-01-11 00:37:30 +0000386 dex2oatBin := dex2oatModuleName(ctx.Config())
387 v := ctx.Config().BuildOSTarget.Variations()
Ulya Trafimovicha4a1c4e2021-01-15 18:40:04 +0000388 ctx.AddFarVariationDependencies(v, Dex2oatDepTag, dex2oatBin)
Martin Stjernholmd90676f2020-01-11 00:37:30 +0000389}
390
391func dex2oatPathFromDep(ctx android.ModuleContext) android.Path {
392 dex2oatBin := dex2oatModuleName(ctx.Config())
393
Martin Stjernholmc0048622020-08-18 17:37:41 +0100394 // Find the right dex2oat module, trying to follow PrebuiltDepTag from source
395 // to prebuilt if there is one. We wouldn't have to do this if the
396 // prebuilt_postdeps mutator that replaces source deps with prebuilt deps was
397 // run after RegisterToolDeps above, but changing that leads to ordering
398 // problems between mutators (RegisterToolDeps needs to run late to act on
399 // final variants, while prebuilt_postdeps needs to run before many of the
400 // PostDeps mutators, like the APEX mutators). Hence we need to dig out the
401 // prebuilt explicitly here instead.
402 var dex2oatModule android.Module
403 ctx.WalkDeps(func(child, parent android.Module) bool {
Ulya Trafimovicha4a1c4e2021-01-15 18:40:04 +0000404 if parent == ctx.Module() && ctx.OtherModuleDependencyTag(child) == Dex2oatDepTag {
Martin Stjernholmc0048622020-08-18 17:37:41 +0100405 // Found the source module, or prebuilt module that has replaced the source.
406 dex2oatModule = child
Paul Duffinf7c99f52021-04-28 10:41:21 +0100407 if android.IsModulePrebuilt(child) {
Martin Stjernholmc0048622020-08-18 17:37:41 +0100408 return false // If it's the prebuilt we're done.
409 } else {
410 return true // Recurse to check if the source has a prebuilt dependency.
411 }
412 }
413 if parent == dex2oatModule && ctx.OtherModuleDependencyTag(child) == android.PrebuiltDepTag {
Paul Duffinf7c99f52021-04-28 10:41:21 +0100414 if p := android.GetEmbeddedPrebuilt(child); p != nil && p.UsePrebuilt() {
Martin Stjernholmc0048622020-08-18 17:37:41 +0100415 dex2oatModule = child // Found a prebuilt that should be used.
416 }
417 }
418 return false
419 })
420
Martin Stjernholmd90676f2020-01-11 00:37:30 +0000421 if dex2oatModule == nil {
422 // If this happens there's probably a missing call to AddToolDeps in DepsMutator.
423 panic(fmt.Sprintf("Failed to lookup %s dependency", dex2oatBin))
424 }
425
426 dex2oatPath := dex2oatModule.(android.HostToolProvider).HostToolPath()
427 if !dex2oatPath.Valid() {
428 panic(fmt.Sprintf("Failed to find host tool path in %s", dex2oatModule))
429 }
430
431 return dex2oatPath.Path()
432}
433
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000434// createGlobalSoongConfig creates a GlobalSoongConfig from the current context.
Martin Stjernholmc52aaf12020-01-06 23:11:37 +0000435// Should not be used in dexpreopt_gen.
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000436func createGlobalSoongConfig(ctx android.ModuleContext) *GlobalSoongConfig {
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000437 return &GlobalSoongConfig{
Martin Stjernholmc52aaf12020-01-06 23:11:37 +0000438 Profman: ctx.Config().HostToolPath(ctx, "profman"),
Martin Stjernholmd90676f2020-01-11 00:37:30 +0000439 Dex2oat: dex2oatPathFromDep(ctx),
Martin Stjernholmc52aaf12020-01-06 23:11:37 +0000440 Aapt: ctx.Config().HostToolPath(ctx, "aapt"),
441 SoongZip: ctx.Config().HostToolPath(ctx, "soong_zip"),
442 Zip2zip: ctx.Config().HostToolPath(ctx, "zip2zip"),
443 ManifestCheck: ctx.Config().HostToolPath(ctx, "manifest_check"),
Ulya Trafimovich5f364b62020-06-30 12:39:01 +0100444 ConstructContext: ctx.Config().HostToolPath(ctx, "construct_context"),
Martin Stjernholmc52aaf12020-01-06 23:11:37 +0000445 }
446}
447
Martin Stjernholmd90676f2020-01-11 00:37:30 +0000448// The main reason for this Once cache for GlobalSoongConfig is to make the
449// dex2oat path available to singletons. In ordinary modules we get it through a
Ulya Trafimovicha4a1c4e2021-01-15 18:40:04 +0000450// Dex2oatDepTag dependency, but in singletons there's no simple way to do the
Martin Stjernholmd90676f2020-01-11 00:37:30 +0000451// same thing and ensure the right variant is selected, hence this cache to make
452// the resolved path available to singletons. This means we depend on there
Ulya Trafimovicha4a1c4e2021-01-15 18:40:04 +0000453// being at least one ordinary module with a Dex2oatDepTag dependency.
Martin Stjernholmd90676f2020-01-11 00:37:30 +0000454//
455// TODO(b/147613152): Implement a way to deal with dependencies from singletons,
Paul Duffin9f045242021-01-21 15:05:11 +0000456// and then possibly remove this cache altogether.
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000457var globalSoongConfigOnceKey = android.NewOnceKey("DexpreoptGlobalSoongConfig")
458
459// GetGlobalSoongConfig creates a GlobalSoongConfig the first time it's called,
460// and later returns the same cached instance.
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000461func GetGlobalSoongConfig(ctx android.ModuleContext) *GlobalSoongConfig {
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000462 globalSoong := ctx.Config().Once(globalSoongConfigOnceKey, func() interface{} {
463 return createGlobalSoongConfig(ctx)
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000464 }).(*GlobalSoongConfig)
Martin Stjernholmd90676f2020-01-11 00:37:30 +0000465
466 // Always resolve the tool path from the dependency, to ensure that every
467 // module has the dependency added properly.
468 myDex2oat := dex2oatPathFromDep(ctx)
469 if myDex2oat != globalSoong.Dex2oat {
470 panic(fmt.Sprintf("Inconsistent dex2oat path in cached config: expected %s, got %s", globalSoong.Dex2oat, myDex2oat))
471 }
472
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000473 return globalSoong
474}
475
476// GetCachedGlobalSoongConfig returns a cached GlobalSoongConfig created by an
477// earlier GetGlobalSoongConfig call. This function works with any context
478// compatible with a basic PathContext, since it doesn't try to create a
Martin Stjernholm6d415272020-01-31 17:10:36 +0000479// GlobalSoongConfig with the proper paths (which requires a full
480// ModuleContext). If there has been no prior call to GetGlobalSoongConfig, nil
481// is returned.
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000482func GetCachedGlobalSoongConfig(ctx android.PathContext) *GlobalSoongConfig {
Martin Stjernholm6d415272020-01-31 17:10:36 +0000483 return ctx.Config().Once(globalSoongConfigOnceKey, func() interface{} {
484 return (*GlobalSoongConfig)(nil)
485 }).(*GlobalSoongConfig)
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000486}
487
Martin Stjernholmc52aaf12020-01-06 23:11:37 +0000488type globalJsonSoongConfig struct {
489 Profman string
490 Dex2oat string
491 Aapt string
492 SoongZip string
493 Zip2zip string
494 ManifestCheck string
495 ConstructContext string
496}
497
Martin Stjernholm40f9f3c2020-01-20 18:12:23 +0000498// ParseGlobalSoongConfig parses the given data assumed to be read from the
499// global dexpreopt_soong.config file into a GlobalSoongConfig struct. It is
500// only used in dexpreopt_gen.
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000501func ParseGlobalSoongConfig(ctx android.PathContext, data []byte) (*GlobalSoongConfig, error) {
Martin Stjernholmc52aaf12020-01-06 23:11:37 +0000502 var jc globalJsonSoongConfig
503
Colin Cross988414c2020-01-11 01:11:46 +0000504 err := json.Unmarshal(data, &jc)
Martin Stjernholmc52aaf12020-01-06 23:11:37 +0000505 if err != nil {
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000506 return &GlobalSoongConfig{}, err
Martin Stjernholmc52aaf12020-01-06 23:11:37 +0000507 }
508
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000509 config := &GlobalSoongConfig{
Martin Stjernholmc52aaf12020-01-06 23:11:37 +0000510 Profman: constructPath(ctx, jc.Profman),
511 Dex2oat: constructPath(ctx, jc.Dex2oat),
512 Aapt: constructPath(ctx, jc.Aapt),
513 SoongZip: constructPath(ctx, jc.SoongZip),
514 Zip2zip: constructPath(ctx, jc.Zip2zip),
515 ManifestCheck: constructPath(ctx, jc.ManifestCheck),
516 ConstructContext: constructPath(ctx, jc.ConstructContext),
517 }
518
519 return config, nil
520}
521
Paul Duffin7d1d0832021-04-23 11:39:41 +0100522// checkBootJarsConfigConsistency checks the consistency of BootJars and UpdatableBootJars fields in
523// DexpreoptGlobalConfig and Config.productVariables.
524func checkBootJarsConfigConsistency(ctx android.SingletonContext, dexpreoptConfig *GlobalConfig, config android.Config) {
525 compareBootJars := func(property string, dexpreoptJars, variableJars android.ConfiguredJarList) {
526 dexpreoptPairs := dexpreoptJars.CopyOfApexJarPairs()
527 variablePairs := variableJars.CopyOfApexJarPairs()
528 if !reflect.DeepEqual(dexpreoptPairs, variablePairs) {
529 ctx.Errorf("Inconsistent configuration of %[1]s\n"+
530 " dexpreopt.GlobalConfig.%[1]s = %[2]s\n"+
531 " productVariables.%[1]s = %[3]s",
532 property, dexpreoptPairs, variablePairs)
533 }
534 }
535
536 compareBootJars("BootJars", dexpreoptConfig.BootJars, config.NonUpdatableBootJars())
537 compareBootJars("UpdatableBootJars", dexpreoptConfig.UpdatableBootJars, config.UpdatableBootJars())
538}
539
Martin Stjernholmc52aaf12020-01-06 23:11:37 +0000540func (s *globalSoongConfigSingleton) GenerateBuildActions(ctx android.SingletonContext) {
Paul Duffin7d1d0832021-04-23 11:39:41 +0100541 checkBootJarsConfigConsistency(ctx, GetGlobalConfig(ctx), ctx.Config())
542
Martin Stjernholmd90676f2020-01-11 00:37:30 +0000543 if GetGlobalConfig(ctx).DisablePreopt {
544 return
545 }
546
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000547 config := GetCachedGlobalSoongConfig(ctx)
Martin Stjernholm6d415272020-01-31 17:10:36 +0000548 if config == nil {
549 // No module has enabled dexpreopting, so we assume there will be no calls
550 // to dexpreopt_gen.
551 return
552 }
553
Martin Stjernholmc52aaf12020-01-06 23:11:37 +0000554 jc := globalJsonSoongConfig{
555 Profman: config.Profman.String(),
556 Dex2oat: config.Dex2oat.String(),
557 Aapt: config.Aapt.String(),
558 SoongZip: config.SoongZip.String(),
559 Zip2zip: config.Zip2zip.String(),
560 ManifestCheck: config.ManifestCheck.String(),
561 ConstructContext: config.ConstructContext.String(),
562 }
563
564 data, err := json.Marshal(jc)
565 if err != nil {
566 ctx.Errorf("failed to JSON marshal GlobalSoongConfig: %v", err)
567 return
568 }
569
Colin Crosscf371cc2020-11-13 11:48:42 -0800570 android.WriteFileRule(ctx, android.PathForOutput(ctx, "dexpreopt_soong.config"), string(data))
Martin Stjernholmc52aaf12020-01-06 23:11:37 +0000571}
572
573func (s *globalSoongConfigSingleton) MakeVars(ctx android.MakeVarsContext) {
Martin Stjernholmd90676f2020-01-11 00:37:30 +0000574 if GetGlobalConfig(ctx).DisablePreopt {
575 return
576 }
577
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000578 config := GetCachedGlobalSoongConfig(ctx)
Martin Stjernholm6d415272020-01-31 17:10:36 +0000579 if config == nil {
580 return
581 }
Martin Stjernholmc52aaf12020-01-06 23:11:37 +0000582
583 ctx.Strict("DEX2OAT", config.Dex2oat.String())
584 ctx.Strict("DEXPREOPT_GEN_DEPS", strings.Join([]string{
585 config.Profman.String(),
586 config.Dex2oat.String(),
587 config.Aapt.String(),
588 config.SoongZip.String(),
589 config.Zip2zip.String(),
590 config.ManifestCheck.String(),
591 config.ConstructContext.String(),
592 }, " "))
593}
594
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000595func GlobalConfigForTests(ctx android.PathContext) *GlobalConfig {
596 return &GlobalConfig{
Colin Cross69f59a32019-02-15 10:39:37 -0800597 DisablePreopt: false,
598 DisablePreoptModules: nil,
599 OnlyPreoptBootImageAndSystemServer: false,
600 HasSystemOther: false,
601 PatternsOnSystemOther: nil,
602 DisableGenerateProfile: false,
603 ProfileDir: "",
Ulya Trafimovich249386a2020-07-01 14:31:13 +0100604 BootJars: android.EmptyConfiguredJarList(),
605 UpdatableBootJars: android.EmptyConfiguredJarList(),
606 ArtApexJars: android.EmptyConfiguredJarList(),
satayev9a6f87e2021-05-04 16:14:48 +0100607 SystemServerJars: android.EmptyConfiguredJarList(),
Colin Cross69f59a32019-02-15 10:39:37 -0800608 SystemServerApps: nil,
Ulya Trafimovich249386a2020-07-01 14:31:13 +0100609 UpdatableSystemServerJars: android.EmptyConfiguredJarList(),
Colin Cross69f59a32019-02-15 10:39:37 -0800610 SpeedApps: nil,
611 PreoptFlags: nil,
612 DefaultCompilerFilter: "",
613 SystemServerCompilerFilter: "",
614 GenerateDMFiles: false,
Colin Cross69f59a32019-02-15 10:39:37 -0800615 NoDebugInfo: false,
Mathieu Chartier3f7ddbb2019-04-29 09:33:50 -0700616 DontResolveStartupStrings: false,
Colin Cross69f59a32019-02-15 10:39:37 -0800617 AlwaysSystemServerDebugInfo: false,
618 NeverSystemServerDebugInfo: false,
619 AlwaysOtherDebugInfo: false,
620 NeverOtherDebugInfo: false,
Colin Cross69f59a32019-02-15 10:39:37 -0800621 IsEng: false,
622 SanitizeLite: false,
623 DefaultAppImages: false,
624 Dex2oatXmx: "",
625 Dex2oatXms: "",
626 EmptyDirectory: "empty_dir",
627 CpuVariant: nil,
628 InstructionSetFeatures: nil,
Colin Cross69f59a32019-02-15 10:39:37 -0800629 BootImageProfiles: nil,
Colin Cross69f59a32019-02-15 10:39:37 -0800630 BootFlags: "",
631 Dex2oatImageXmx: "",
632 Dex2oatImageXms: "",
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000633 }
634}
635
Paul Duffin9f045242021-01-21 15:05:11 +0000636func globalSoongConfigForTests() *GlobalSoongConfig {
637 return &GlobalSoongConfig{
638 Profman: android.PathForTesting("profman"),
639 Dex2oat: android.PathForTesting("dex2oat"),
640 Aapt: android.PathForTesting("aapt"),
641 SoongZip: android.PathForTesting("soong_zip"),
642 Zip2zip: android.PathForTesting("zip2zip"),
643 ManifestCheck: android.PathForTesting("manifest_check"),
644 ConstructContext: android.PathForTesting("construct_context"),
645 }
Colin Cross69f59a32019-02-15 10:39:37 -0800646}