blob: 1f99a96c1c6d61171da785f687956861216ca584 [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
satayevd604b212021-07-21 14:23:52 +010047 BootJars android.ConfiguredJarList // modules for jars that form the boot class path
48 ApexBootJars 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
Jiakai Zhangcee9e192021-10-29 19:46:45 +000052 SystemServerJars android.ConfiguredJarList // system_server classpath jars on the platform
53 SystemServerApps []string // apps that are loaded into system server
54 ApexSystemServerJars android.ConfiguredJarList // system_server classpath jars delivered via apex
55 StandaloneSystemServerJars android.ConfiguredJarList // jars on the platform that system_server loads dynamically using separate classloaders
56 ApexStandaloneSystemServerJars android.ConfiguredJarList // jars delivered via apex that system_server loads dynamically using separate classloaders
57 SpeedApps []string // apps that should be speed optimized
Colin Cross43f08db2018-11-12 10:13:39 -080058
Ulya Trafimovichcd3203f2020-03-27 11:30:00 +000059 BrokenSuboptimalOrderOfSystemServerJars bool // if true, sub-optimal order does not cause a build error
60
Colin Cross43f08db2018-11-12 10:13:39 -080061 PreoptFlags []string // global dex2oat flags that should be used if no module-specific dex2oat flags are specified
62
63 DefaultCompilerFilter string // default compiler filter to pass to dex2oat, overridden by --compiler-filter= in module-specific dex2oat flags
64 SystemServerCompilerFilter string // default compiler filter to pass to dex2oat for system server jars
65
Nicolas Geoffrayc1bf7242019-10-18 14:51:38 +010066 GenerateDMFiles bool // generate Dex Metadata files
Colin Cross43f08db2018-11-12 10:13:39 -080067
68 NoDebugInfo bool // don't generate debug info by default
Mathieu Chartier3f7ddbb2019-04-29 09:33:50 -070069 DontResolveStartupStrings bool // don't resolve string literals loaded during application startup.
Colin Cross43f08db2018-11-12 10:13:39 -080070 AlwaysSystemServerDebugInfo bool // always generate mini debug info for system server modules (overrides NoDebugInfo=true)
71 NeverSystemServerDebugInfo bool // never generate mini debug info for system server modules (overrides NoDebugInfo=false)
72 AlwaysOtherDebugInfo bool // always generate mini debug info for non-system server modules (overrides NoDebugInfo=true)
73 NeverOtherDebugInfo bool // never generate mini debug info for non-system server modules (overrides NoDebugInfo=true)
74
Colin Cross43f08db2018-11-12 10:13:39 -080075 IsEng bool // build is a eng variant
76 SanitizeLite bool // build is the second phase of a SANITIZE_LITE build
77
78 DefaultAppImages bool // build app images (TODO: .art files?) by default
79
Colin Cross800fe132019-02-11 14:21:24 -080080 Dex2oatXmx string // max heap size for dex2oat
81 Dex2oatXms string // initial heap size for dex2oat
Colin Cross43f08db2018-11-12 10:13:39 -080082
83 EmptyDirectory string // path to an empty directory
84
Colin Cross74ba9622019-02-11 15:11:14 -080085 CpuVariant map[android.ArchType]string // cpu variant for each architecture
86 InstructionSetFeatures map[android.ArchType]string // instruction set for each architecture
Colin Cross43f08db2018-11-12 10:13:39 -080087
Nicolas Geoffray1086e602021-01-20 14:30:40 +000088 BootImageProfiles android.Paths // path to a boot-image-profile.txt file
89 BootFlags string // extra flags to pass to dex2oat for the boot image
90 Dex2oatImageXmx string // max heap size for dex2oat for the boot image
91 Dex2oatImageXms string // initial heap size for dex2oat for the boot image
Ulya Trafimovich8c35fcf2021-02-17 16:23:28 +000092
Ulya Trafimovich4a13acb2021-03-02 12:25:02 +000093 // If true, downgrade the compiler filter of dexpreopt to "verify" when verify_uses_libraries
Ulya Trafimovich8c35fcf2021-02-17 16:23:28 +000094 // check fails, instead of failing the build. This will disable any AOT-compilation.
95 //
96 // The intended use case for this flag is to have a smoother migration path for the Java
97 // modules that need to add <uses-library> information in their build files. The flag allows to
98 // quickly silence build errors. This flag should be used with caution and only as a temporary
99 // measure, as it masks real errors and affects performance.
100 RelaxUsesLibraryCheck bool
Colin Cross43f08db2018-11-12 10:13:39 -0800101}
102
Jiakai Zhang389a6472021-12-14 18:54:06 +0000103var allPlatformSystemServerJarsKey = android.NewOnceKey("allPlatformSystemServerJars")
104
105// Returns all jars on the platform that system_server loads, including those on classpath and those
106// loaded dynamically.
107func (g *GlobalConfig) AllPlatformSystemServerJars(ctx android.PathContext) *android.ConfiguredJarList {
108 return ctx.Config().Once(allPlatformSystemServerJarsKey, func() interface{} {
109 res := g.SystemServerJars.AppendList(&g.StandaloneSystemServerJars)
110 return &res
111 }).(*android.ConfiguredJarList)
112}
113
114var allApexSystemServerJarsKey = android.NewOnceKey("allApexSystemServerJars")
115
116// Returns all jars delivered via apex that system_server loads, including those on classpath and
117// those loaded dynamically.
118func (g *GlobalConfig) AllApexSystemServerJars(ctx android.PathContext) *android.ConfiguredJarList {
119 return ctx.Config().Once(allApexSystemServerJarsKey, func() interface{} {
120 res := g.ApexSystemServerJars.AppendList(&g.ApexStandaloneSystemServerJars)
121 return &res
122 }).(*android.ConfiguredJarList)
123}
124
125var allSystemServerClasspathJarsKey = android.NewOnceKey("allSystemServerClasspathJars")
126
127// Returns all system_server classpath jars.
128func (g *GlobalConfig) AllSystemServerClasspathJars(ctx android.PathContext) *android.ConfiguredJarList {
129 return ctx.Config().Once(allSystemServerClasspathJarsKey, func() interface{} {
130 res := g.SystemServerJars.AppendList(&g.ApexSystemServerJars)
131 return &res
132 }).(*android.ConfiguredJarList)
133}
134
135var allSystemServerJarsKey = android.NewOnceKey("allSystemServerJars")
136
137// Returns all jars that system_server loads.
138func (g *GlobalConfig) AllSystemServerJars(ctx android.PathContext) *android.ConfiguredJarList {
139 return ctx.Config().Once(allSystemServerJarsKey, func() interface{} {
140 res := g.AllPlatformSystemServerJars(ctx).AppendList(g.AllApexSystemServerJars(ctx))
141 return &res
142 }).(*android.ConfiguredJarList)
143}
144
Martin Stjernholmc52aaf12020-01-06 23:11:37 +0000145// GlobalSoongConfig contains the global config that is generated from Soong,
146// stored in dexpreopt_soong.config.
147type GlobalSoongConfig struct {
148 // Paths to tools possibly used by the generated commands.
149 Profman android.Path
150 Dex2oat android.Path
151 Aapt android.Path
152 SoongZip android.Path
153 Zip2zip android.Path
154 ManifestCheck android.Path
Colin Cross38b96852019-05-22 10:21:09 -0700155 ConstructContext android.Path
Colin Cross43f08db2018-11-12 10:13:39 -0800156}
157
158type ModuleConfig struct {
Victor Hsiehd181c8b2019-01-29 13:00:33 -0800159 Name string
160 DexLocation string // dex location on device
Colin Cross69f59a32019-02-15 10:39:37 -0800161 BuildPath android.OutputPath
162 DexPath android.Path
Jeongik Cha33a3a812021-04-15 09:12:49 +0900163 ManifestPath android.OptionalPath
Victor Hsiehd181c8b2019-01-29 13:00:33 -0800164 UncompressedDex bool
165 HasApkLibraries bool
166 PreoptFlags []string
Colin Cross43f08db2018-11-12 10:13:39 -0800167
Colin Cross69f59a32019-02-15 10:39:37 -0800168 ProfileClassListing android.OptionalPath
Colin Cross43f08db2018-11-12 10:13:39 -0800169 ProfileIsTextListing bool
Nicolas Geoffraye7102422019-07-24 13:19:29 +0100170 ProfileBootListing android.OptionalPath
Colin Cross43f08db2018-11-12 10:13:39 -0800171
Ulya Trafimovich8c35fcf2021-02-17 16:23:28 +0000172 EnforceUsesLibraries bool // turn on build-time verify_uses_libraries check
173 EnforceUsesLibrariesStatusFile android.Path // a file with verify_uses_libraries errors (if any)
174 ProvidesUsesLibrary string // library name (usually the same as module name)
175 ClassLoaderContexts ClassLoaderContextMap
Colin Cross43f08db2018-11-12 10:13:39 -0800176
Jeongik Cha4dda75e2021-04-27 23:56:44 +0900177 Archs []android.ArchType
178 DexPreoptImagesDeps []android.OutputPaths
179
180 DexPreoptImageLocationsOnHost []string // boot image location on host (file path without the arch subdirectory)
181 DexPreoptImageLocationsOnDevice []string // boot image location on device (file path without the arch subdirectory)
Colin Cross43f08db2018-11-12 10:13:39 -0800182
Colin Cross69f59a32019-02-15 10:39:37 -0800183 PreoptBootClassPathDexFiles android.Paths // file paths of boot class path files
184 PreoptBootClassPathDexLocations []string // virtual locations of boot class path files
Colin Cross800fe132019-02-11 14:21:24 -0800185
Colin Cross43f08db2018-11-12 10:13:39 -0800186 PreoptExtractedApk bool // Overrides OnlyPreoptModules
187
188 NoCreateAppImage bool
189 ForceCreateAppImage bool
190
191 PresignedPrebuilt bool
Colin Cross43f08db2018-11-12 10:13:39 -0800192}
193
Martin Stjernholmc52aaf12020-01-06 23:11:37 +0000194type globalSoongConfigSingleton struct{}
195
196var pctx = android.NewPackageContext("android/soong/dexpreopt")
197
198func init() {
199 pctx.Import("android/soong/android")
200 android.RegisterSingletonType("dexpreopt-soong-config", func() android.Singleton {
201 return &globalSoongConfigSingleton{}
202 })
203}
204
Colin Cross69f59a32019-02-15 10:39:37 -0800205func constructPath(ctx android.PathContext, path string) android.Path {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200206 buildDirPrefix := ctx.Config().SoongOutDir() + "/"
Colin Cross69f59a32019-02-15 10:39:37 -0800207 if path == "" {
208 return nil
209 } else if strings.HasPrefix(path, buildDirPrefix) {
210 return android.PathForOutput(ctx, strings.TrimPrefix(path, buildDirPrefix))
211 } else {
212 return android.PathForSource(ctx, path)
213 }
Colin Cross43f08db2018-11-12 10:13:39 -0800214}
215
Colin Cross69f59a32019-02-15 10:39:37 -0800216func constructPaths(ctx android.PathContext, paths []string) android.Paths {
217 var ret android.Paths
218 for _, path := range paths {
219 ret = append(ret, constructPath(ctx, path))
220 }
221 return ret
Colin Cross43f08db2018-11-12 10:13:39 -0800222}
223
Colin Cross69f59a32019-02-15 10:39:37 -0800224func constructWritablePath(ctx android.PathContext, path string) android.WritablePath {
225 if path == "" {
226 return nil
227 }
228 return constructPath(ctx, path).(android.WritablePath)
229}
230
Martin Stjernholm40f9f3c2020-01-20 18:12:23 +0000231// ParseGlobalConfig parses the given data assumed to be read from the global
232// dexpreopt.config file into a GlobalConfig struct.
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000233func ParseGlobalConfig(ctx android.PathContext, data []byte) (*GlobalConfig, error) {
Colin Cross69f59a32019-02-15 10:39:37 -0800234 type GlobalJSONConfig struct {
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000235 *GlobalConfig
Colin Cross69f59a32019-02-15 10:39:37 -0800236
237 // Copies of entries in GlobalConfig that are not constructable without extra parameters. They will be
238 // used to construct the real value manually below.
Paul Duffin7ccacae2020-10-23 21:14:20 +0100239 BootImageProfiles []string
Colin Cross69f59a32019-02-15 10:39:37 -0800240 }
241
242 config := GlobalJSONConfig{}
Colin Cross988414c2020-01-11 01:11:46 +0000243 err := json.Unmarshal(data, &config)
Colin Cross69f59a32019-02-15 10:39:37 -0800244 if err != nil {
Colin Cross988414c2020-01-11 01:11:46 +0000245 return config.GlobalConfig, err
Colin Cross69f59a32019-02-15 10:39:37 -0800246 }
247
248 // Construct paths that require a PathContext.
Colin Cross69f59a32019-02-15 10:39:37 -0800249 config.GlobalConfig.BootImageProfiles = constructPaths(ctx, config.BootImageProfiles)
250
Colin Cross988414c2020-01-11 01:11:46 +0000251 return config.GlobalConfig, nil
Colin Cross69f59a32019-02-15 10:39:37 -0800252}
253
Martin Stjernholm40f9f3c2020-01-20 18:12:23 +0000254type globalConfigAndRaw struct {
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000255 global *GlobalConfig
Martin Stjernholm40f9f3c2020-01-20 18:12:23 +0000256 data []byte
257}
258
259// GetGlobalConfig returns the global dexpreopt.config that's created in the
260// make config phase. It is loaded once the first time it is called for any
261// ctx.Config(), and returns the same data for all future calls with the same
262// ctx.Config(). A value can be inserted for tests using
263// setDexpreoptTestGlobalConfig.
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000264func GetGlobalConfig(ctx android.PathContext) *GlobalConfig {
Martin Stjernholm40f9f3c2020-01-20 18:12:23 +0000265 return getGlobalConfigRaw(ctx).global
266}
267
268// GetGlobalConfigRawData is the same as GetGlobalConfig, except that it returns
269// the literal content of dexpreopt.config.
270func GetGlobalConfigRawData(ctx android.PathContext) []byte {
271 return getGlobalConfigRaw(ctx).data
272}
273
274var globalConfigOnceKey = android.NewOnceKey("DexpreoptGlobalConfig")
275var testGlobalConfigOnceKey = android.NewOnceKey("TestDexpreoptGlobalConfig")
276
277func getGlobalConfigRaw(ctx android.PathContext) globalConfigAndRaw {
278 return ctx.Config().Once(globalConfigOnceKey, func() interface{} {
279 if data, err := ctx.Config().DexpreoptGlobalConfig(ctx); err != nil {
280 panic(err)
281 } else if data != nil {
282 globalConfig, err := ParseGlobalConfig(ctx, data)
283 if err != nil {
284 panic(err)
285 }
286 return globalConfigAndRaw{globalConfig, data}
287 }
288
289 // No global config filename set, see if there is a test config set
290 return ctx.Config().Once(testGlobalConfigOnceKey, func() interface{} {
291 // Nope, return a config with preopting disabled
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000292 return globalConfigAndRaw{&GlobalConfig{
Ulya Trafimovicha4a1c4e2021-01-15 18:40:04 +0000293 DisablePreopt: true,
294 DisablePreoptBootImages: true,
295 DisableGenerateProfile: true,
Martin Stjernholm40f9f3c2020-01-20 18:12:23 +0000296 }, nil}
297 })
298 }).(globalConfigAndRaw)
299}
300
301// SetTestGlobalConfig sets a GlobalConfig that future calls to GetGlobalConfig
302// will return. It must be called before the first call to GetGlobalConfig for
303// the config.
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000304func SetTestGlobalConfig(config android.Config, globalConfig *GlobalConfig) {
Martin Stjernholm40f9f3c2020-01-20 18:12:23 +0000305 config.Once(testGlobalConfigOnceKey, func() interface{} { return globalConfigAndRaw{globalConfig, nil} })
306}
307
Jeongik Chac6246672021-04-08 00:00:19 +0900308// This struct is required to convert ModuleConfig from/to JSON.
309// The types of fields in ModuleConfig are not convertible,
310// so moduleJSONConfig has those fields as a convertible type.
311type moduleJSONConfig struct {
312 *ModuleConfig
313
314 BuildPath string
315 DexPath string
316 ManifestPath string
317
318 ProfileClassListing string
319 ProfileBootListing string
320
321 EnforceUsesLibrariesStatusFile string
322 ClassLoaderContexts jsonClassLoaderContextMap
323
Jeongik Chac6246672021-04-08 00:00:19 +0900324 DexPreoptImagesDeps [][]string
325
326 PreoptBootClassPathDexFiles []string
327}
328
Martin Stjernholm40f9f3c2020-01-20 18:12:23 +0000329// ParseModuleConfig parses a per-module dexpreopt.config file into a
330// ModuleConfig struct. It is not used in Soong, which receives a ModuleConfig
331// struct directly from java/dexpreopt.go. It is used in dexpreopt_gen called
332// from Make to read the module dexpreopt.config written in the Make config
333// stage.
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000334func ParseModuleConfig(ctx android.PathContext, data []byte) (*ModuleConfig, error) {
Jeongik Chac6246672021-04-08 00:00:19 +0900335 config := moduleJSONConfig{}
Colin Cross69f59a32019-02-15 10:39:37 -0800336
Colin Cross988414c2020-01-11 01:11:46 +0000337 err := json.Unmarshal(data, &config)
Colin Cross69f59a32019-02-15 10:39:37 -0800338 if err != nil {
339 return config.ModuleConfig, err
340 }
341
342 // Construct paths that require a PathContext.
343 config.ModuleConfig.BuildPath = constructPath(ctx, config.BuildPath).(android.OutputPath)
344 config.ModuleConfig.DexPath = constructPath(ctx, config.DexPath)
Jeongik Cha33a3a812021-04-15 09:12:49 +0900345 config.ModuleConfig.ManifestPath = android.OptionalPathForPath(constructPath(ctx, config.ManifestPath))
Colin Cross69f59a32019-02-15 10:39:37 -0800346 config.ModuleConfig.ProfileClassListing = android.OptionalPathForPath(constructPath(ctx, config.ProfileClassListing))
Ulya Trafimovich8c35fcf2021-02-17 16:23:28 +0000347 config.ModuleConfig.EnforceUsesLibrariesStatusFile = constructPath(ctx, config.EnforceUsesLibrariesStatusFile)
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000348 config.ModuleConfig.ClassLoaderContexts = fromJsonClassLoaderContext(ctx, config.ClassLoaderContexts)
Colin Cross69f59a32019-02-15 10:39:37 -0800349 config.ModuleConfig.PreoptBootClassPathDexFiles = constructPaths(ctx, config.PreoptBootClassPathDexFiles)
Colin Cross69f59a32019-02-15 10:39:37 -0800350
Dan Willemsen0f416782019-06-13 21:44:53 +0000351 // 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 +0900352 config.ModuleConfig.DexPreoptImagesDeps = make([]android.OutputPaths, len(config.ModuleConfig.Archs))
Dan Willemsen0f416782019-06-13 21:44:53 +0000353
Colin Cross69f59a32019-02-15 10:39:37 -0800354 return config.ModuleConfig, nil
355}
356
Jeongik Chac6246672021-04-08 00:00:19 +0900357func pathsListToStringLists(pathsList []android.OutputPaths) [][]string {
358 ret := make([][]string, 0, len(pathsList))
359 for _, paths := range pathsList {
360 ret = append(ret, paths.Strings())
361 }
362 return ret
363}
364
365func moduleConfigToJSON(config *ModuleConfig) ([]byte, error) {
366 return json.MarshalIndent(&moduleJSONConfig{
367 BuildPath: config.BuildPath.String(),
368 DexPath: config.DexPath.String(),
369 ManifestPath: config.ManifestPath.String(),
370 ProfileClassListing: config.ProfileClassListing.String(),
371 ProfileBootListing: config.ProfileBootListing.String(),
372 EnforceUsesLibrariesStatusFile: config.EnforceUsesLibrariesStatusFile.String(),
373 ClassLoaderContexts: toJsonClassLoaderContext(config.ClassLoaderContexts),
Jeongik Chac6246672021-04-08 00:00:19 +0900374 DexPreoptImagesDeps: pathsListToStringLists(config.DexPreoptImagesDeps),
375 PreoptBootClassPathDexFiles: config.PreoptBootClassPathDexFiles.Strings(),
376 ModuleConfig: config,
377 }, "", " ")
378}
379
380// WriteModuleConfig serializes a ModuleConfig into a per-module dexpreopt.config JSON file.
381// These config files are used for post-processing.
382func WriteModuleConfig(ctx android.ModuleContext, config *ModuleConfig, path android.WritablePath) {
Ulya Trafimovich76b08522021-01-14 17:52:43 +0000383 if path == nil {
384 return
385 }
386
Jeongik Chac6246672021-04-08 00:00:19 +0900387 data, err := moduleConfigToJSON(config)
Ulya Trafimovich76b08522021-01-14 17:52:43 +0000388 if err != nil {
389 ctx.ModuleErrorf("failed to JSON marshal module dexpreopt.config: %v", err)
390 return
391 }
392
393 android.WriteFileRule(ctx, path, string(data))
394}
395
Martin Stjernholmd90676f2020-01-11 00:37:30 +0000396// dex2oatModuleName returns the name of the module to use for the dex2oat host
397// tool. It should be a binary module with public visibility that is compiled
398// and installed for host.
399func dex2oatModuleName(config android.Config) string {
400 // Default to the debug variant of dex2oat to help find bugs.
401 // Set USE_DEX2OAT_DEBUG to false for only building non-debug versions.
402 if config.Getenv("USE_DEX2OAT_DEBUG") == "false" {
403 return "dex2oat"
404 } else {
405 return "dex2oatd"
406 }
407}
408
Paul Duffinb506c9d2021-03-24 14:34:40 +0000409type dex2oatDependencyTag struct {
Martin Stjernholmd90676f2020-01-11 00:37:30 +0000410 blueprint.BaseDependencyTag
Paul Duffinb506c9d2021-03-24 14:34:40 +0000411}
412
413func (d dex2oatDependencyTag) ExcludeFromVisibilityEnforcement() {
414}
415
416func (d dex2oatDependencyTag) ExcludeFromApexContents() {
417}
418
Martin Stjernholm0e4cceb2021-05-13 02:38:35 +0100419func (d dex2oatDependencyTag) AllowDisabledModuleDependency(target android.Module) bool {
420 // RegisterToolDeps may run after the prebuilt mutators and hence register a
421 // dependency on the source module even when the prebuilt is to be used.
422 // dex2oatPathFromDep takes that into account when it retrieves the path to
423 // the binary, but we also need to disable the check for dependencies on
424 // disabled modules.
425 return target.IsReplacedByPrebuilt()
426}
427
Paul Duffinb506c9d2021-03-24 14:34:40 +0000428// Dex2oatDepTag represents the dependency onto the dex2oatd module. It is added to any module that
429// needs dexpreopting and so it makes no sense for it to be checked for visibility or included in
430// the apex.
431var Dex2oatDepTag = dex2oatDependencyTag{}
432
433var _ android.ExcludeFromVisibilityEnforcementTag = Dex2oatDepTag
434var _ android.ExcludeFromApexContentsTag = Dex2oatDepTag
Martin Stjernholm0e4cceb2021-05-13 02:38:35 +0100435var _ android.AllowDisabledModuleDependency = Dex2oatDepTag
Martin Stjernholmd90676f2020-01-11 00:37:30 +0000436
Martin Stjernholm6d415272020-01-31 17:10:36 +0000437// RegisterToolDeps adds the necessary dependencies to binary modules for tools
438// that are required later when Get(Cached)GlobalSoongConfig is called. It
439// should be called from a mutator that's registered with
440// android.RegistrationContext.FinalDepsMutators.
441func RegisterToolDeps(ctx android.BottomUpMutatorContext) {
Martin Stjernholmd90676f2020-01-11 00:37:30 +0000442 dex2oatBin := dex2oatModuleName(ctx.Config())
443 v := ctx.Config().BuildOSTarget.Variations()
Ulya Trafimovicha4a1c4e2021-01-15 18:40:04 +0000444 ctx.AddFarVariationDependencies(v, Dex2oatDepTag, dex2oatBin)
Martin Stjernholmd90676f2020-01-11 00:37:30 +0000445}
446
447func dex2oatPathFromDep(ctx android.ModuleContext) android.Path {
448 dex2oatBin := dex2oatModuleName(ctx.Config())
449
Martin Stjernholmc0048622020-08-18 17:37:41 +0100450 // Find the right dex2oat module, trying to follow PrebuiltDepTag from source
451 // to prebuilt if there is one. We wouldn't have to do this if the
452 // prebuilt_postdeps mutator that replaces source deps with prebuilt deps was
453 // run after RegisterToolDeps above, but changing that leads to ordering
454 // problems between mutators (RegisterToolDeps needs to run late to act on
455 // final variants, while prebuilt_postdeps needs to run before many of the
456 // PostDeps mutators, like the APEX mutators). Hence we need to dig out the
457 // prebuilt explicitly here instead.
458 var dex2oatModule android.Module
459 ctx.WalkDeps(func(child, parent android.Module) bool {
Ulya Trafimovicha4a1c4e2021-01-15 18:40:04 +0000460 if parent == ctx.Module() && ctx.OtherModuleDependencyTag(child) == Dex2oatDepTag {
Martin Stjernholmc0048622020-08-18 17:37:41 +0100461 // Found the source module, or prebuilt module that has replaced the source.
462 dex2oatModule = child
Paul Duffinf7c99f52021-04-28 10:41:21 +0100463 if android.IsModulePrebuilt(child) {
Martin Stjernholmc0048622020-08-18 17:37:41 +0100464 return false // If it's the prebuilt we're done.
465 } else {
466 return true // Recurse to check if the source has a prebuilt dependency.
467 }
468 }
469 if parent == dex2oatModule && ctx.OtherModuleDependencyTag(child) == android.PrebuiltDepTag {
Paul Duffinf7c99f52021-04-28 10:41:21 +0100470 if p := android.GetEmbeddedPrebuilt(child); p != nil && p.UsePrebuilt() {
Martin Stjernholmc0048622020-08-18 17:37:41 +0100471 dex2oatModule = child // Found a prebuilt that should be used.
472 }
473 }
474 return false
475 })
476
Martin Stjernholmd90676f2020-01-11 00:37:30 +0000477 if dex2oatModule == nil {
478 // If this happens there's probably a missing call to AddToolDeps in DepsMutator.
479 panic(fmt.Sprintf("Failed to lookup %s dependency", dex2oatBin))
480 }
481
482 dex2oatPath := dex2oatModule.(android.HostToolProvider).HostToolPath()
483 if !dex2oatPath.Valid() {
484 panic(fmt.Sprintf("Failed to find host tool path in %s", dex2oatModule))
485 }
486
487 return dex2oatPath.Path()
488}
489
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000490// createGlobalSoongConfig creates a GlobalSoongConfig from the current context.
Martin Stjernholmc52aaf12020-01-06 23:11:37 +0000491// Should not be used in dexpreopt_gen.
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000492func createGlobalSoongConfig(ctx android.ModuleContext) *GlobalSoongConfig {
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000493 return &GlobalSoongConfig{
Martin Stjernholmc52aaf12020-01-06 23:11:37 +0000494 Profman: ctx.Config().HostToolPath(ctx, "profman"),
Martin Stjernholmd90676f2020-01-11 00:37:30 +0000495 Dex2oat: dex2oatPathFromDep(ctx),
Martin Stjernholmc52aaf12020-01-06 23:11:37 +0000496 Aapt: ctx.Config().HostToolPath(ctx, "aapt"),
497 SoongZip: ctx.Config().HostToolPath(ctx, "soong_zip"),
498 Zip2zip: ctx.Config().HostToolPath(ctx, "zip2zip"),
499 ManifestCheck: ctx.Config().HostToolPath(ctx, "manifest_check"),
Ulya Trafimovich5f364b62020-06-30 12:39:01 +0100500 ConstructContext: ctx.Config().HostToolPath(ctx, "construct_context"),
Martin Stjernholmc52aaf12020-01-06 23:11:37 +0000501 }
502}
503
Martin Stjernholmd90676f2020-01-11 00:37:30 +0000504// The main reason for this Once cache for GlobalSoongConfig is to make the
505// dex2oat path available to singletons. In ordinary modules we get it through a
Ulya Trafimovicha4a1c4e2021-01-15 18:40:04 +0000506// Dex2oatDepTag dependency, but in singletons there's no simple way to do the
Martin Stjernholmd90676f2020-01-11 00:37:30 +0000507// same thing and ensure the right variant is selected, hence this cache to make
508// the resolved path available to singletons. This means we depend on there
Ulya Trafimovicha4a1c4e2021-01-15 18:40:04 +0000509// being at least one ordinary module with a Dex2oatDepTag dependency.
Martin Stjernholmd90676f2020-01-11 00:37:30 +0000510//
511// TODO(b/147613152): Implement a way to deal with dependencies from singletons,
Paul Duffin9f045242021-01-21 15:05:11 +0000512// and then possibly remove this cache altogether.
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000513var globalSoongConfigOnceKey = android.NewOnceKey("DexpreoptGlobalSoongConfig")
514
515// GetGlobalSoongConfig creates a GlobalSoongConfig the first time it's called,
516// and later returns the same cached instance.
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000517func GetGlobalSoongConfig(ctx android.ModuleContext) *GlobalSoongConfig {
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000518 globalSoong := ctx.Config().Once(globalSoongConfigOnceKey, func() interface{} {
519 return createGlobalSoongConfig(ctx)
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000520 }).(*GlobalSoongConfig)
Martin Stjernholmd90676f2020-01-11 00:37:30 +0000521
522 // Always resolve the tool path from the dependency, to ensure that every
523 // module has the dependency added properly.
524 myDex2oat := dex2oatPathFromDep(ctx)
525 if myDex2oat != globalSoong.Dex2oat {
526 panic(fmt.Sprintf("Inconsistent dex2oat path in cached config: expected %s, got %s", globalSoong.Dex2oat, myDex2oat))
527 }
528
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000529 return globalSoong
530}
531
532// GetCachedGlobalSoongConfig returns a cached GlobalSoongConfig created by an
533// earlier GetGlobalSoongConfig call. This function works with any context
534// compatible with a basic PathContext, since it doesn't try to create a
Martin Stjernholm6d415272020-01-31 17:10:36 +0000535// GlobalSoongConfig with the proper paths (which requires a full
536// ModuleContext). If there has been no prior call to GetGlobalSoongConfig, nil
537// is returned.
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000538func GetCachedGlobalSoongConfig(ctx android.PathContext) *GlobalSoongConfig {
Martin Stjernholm6d415272020-01-31 17:10:36 +0000539 return ctx.Config().Once(globalSoongConfigOnceKey, func() interface{} {
540 return (*GlobalSoongConfig)(nil)
541 }).(*GlobalSoongConfig)
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000542}
543
Martin Stjernholmc52aaf12020-01-06 23:11:37 +0000544type globalJsonSoongConfig struct {
545 Profman string
546 Dex2oat string
547 Aapt string
548 SoongZip string
549 Zip2zip string
550 ManifestCheck string
551 ConstructContext string
552}
553
Martin Stjernholm40f9f3c2020-01-20 18:12:23 +0000554// ParseGlobalSoongConfig parses the given data assumed to be read from the
555// global dexpreopt_soong.config file into a GlobalSoongConfig struct. It is
556// only used in dexpreopt_gen.
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000557func ParseGlobalSoongConfig(ctx android.PathContext, data []byte) (*GlobalSoongConfig, error) {
Martin Stjernholmc52aaf12020-01-06 23:11:37 +0000558 var jc globalJsonSoongConfig
559
Colin Cross988414c2020-01-11 01:11:46 +0000560 err := json.Unmarshal(data, &jc)
Martin Stjernholmc52aaf12020-01-06 23:11:37 +0000561 if err != nil {
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000562 return &GlobalSoongConfig{}, err
Martin Stjernholmc52aaf12020-01-06 23:11:37 +0000563 }
564
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000565 config := &GlobalSoongConfig{
Martin Stjernholmc52aaf12020-01-06 23:11:37 +0000566 Profman: constructPath(ctx, jc.Profman),
567 Dex2oat: constructPath(ctx, jc.Dex2oat),
568 Aapt: constructPath(ctx, jc.Aapt),
569 SoongZip: constructPath(ctx, jc.SoongZip),
570 Zip2zip: constructPath(ctx, jc.Zip2zip),
571 ManifestCheck: constructPath(ctx, jc.ManifestCheck),
572 ConstructContext: constructPath(ctx, jc.ConstructContext),
573 }
574
575 return config, nil
576}
577
satayevd604b212021-07-21 14:23:52 +0100578// checkBootJarsConfigConsistency checks the consistency of BootJars and ApexBootJars fields in
Paul Duffin7d1d0832021-04-23 11:39:41 +0100579// DexpreoptGlobalConfig and Config.productVariables.
580func checkBootJarsConfigConsistency(ctx android.SingletonContext, dexpreoptConfig *GlobalConfig, config android.Config) {
581 compareBootJars := func(property string, dexpreoptJars, variableJars android.ConfiguredJarList) {
582 dexpreoptPairs := dexpreoptJars.CopyOfApexJarPairs()
583 variablePairs := variableJars.CopyOfApexJarPairs()
584 if !reflect.DeepEqual(dexpreoptPairs, variablePairs) {
585 ctx.Errorf("Inconsistent configuration of %[1]s\n"+
586 " dexpreopt.GlobalConfig.%[1]s = %[2]s\n"+
587 " productVariables.%[1]s = %[3]s",
588 property, dexpreoptPairs, variablePairs)
589 }
590 }
591
satayevd604b212021-07-21 14:23:52 +0100592 compareBootJars("BootJars", dexpreoptConfig.BootJars, config.NonApexBootJars())
593 compareBootJars("ApexBootJars", dexpreoptConfig.ApexBootJars, config.ApexBootJars())
Paul Duffin7d1d0832021-04-23 11:39:41 +0100594}
595
Martin Stjernholmc52aaf12020-01-06 23:11:37 +0000596func (s *globalSoongConfigSingleton) GenerateBuildActions(ctx android.SingletonContext) {
Paul Duffin7d1d0832021-04-23 11:39:41 +0100597 checkBootJarsConfigConsistency(ctx, GetGlobalConfig(ctx), ctx.Config())
598
Martin Stjernholmd90676f2020-01-11 00:37:30 +0000599 if GetGlobalConfig(ctx).DisablePreopt {
600 return
601 }
602
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000603 config := GetCachedGlobalSoongConfig(ctx)
Martin Stjernholm6d415272020-01-31 17:10:36 +0000604 if config == nil {
605 // No module has enabled dexpreopting, so we assume there will be no calls
606 // to dexpreopt_gen.
607 return
608 }
609
Martin Stjernholmc52aaf12020-01-06 23:11:37 +0000610 jc := globalJsonSoongConfig{
611 Profman: config.Profman.String(),
612 Dex2oat: config.Dex2oat.String(),
613 Aapt: config.Aapt.String(),
614 SoongZip: config.SoongZip.String(),
615 Zip2zip: config.Zip2zip.String(),
616 ManifestCheck: config.ManifestCheck.String(),
617 ConstructContext: config.ConstructContext.String(),
618 }
619
620 data, err := json.Marshal(jc)
621 if err != nil {
622 ctx.Errorf("failed to JSON marshal GlobalSoongConfig: %v", err)
623 return
624 }
625
Colin Crosscf371cc2020-11-13 11:48:42 -0800626 android.WriteFileRule(ctx, android.PathForOutput(ctx, "dexpreopt_soong.config"), string(data))
Martin Stjernholmc52aaf12020-01-06 23:11:37 +0000627}
628
629func (s *globalSoongConfigSingleton) MakeVars(ctx android.MakeVarsContext) {
Martin Stjernholmd90676f2020-01-11 00:37:30 +0000630 if GetGlobalConfig(ctx).DisablePreopt {
631 return
632 }
633
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000634 config := GetCachedGlobalSoongConfig(ctx)
Martin Stjernholm6d415272020-01-31 17:10:36 +0000635 if config == nil {
636 return
637 }
Martin Stjernholmc52aaf12020-01-06 23:11:37 +0000638
639 ctx.Strict("DEX2OAT", config.Dex2oat.String())
640 ctx.Strict("DEXPREOPT_GEN_DEPS", strings.Join([]string{
641 config.Profman.String(),
642 config.Dex2oat.String(),
643 config.Aapt.String(),
644 config.SoongZip.String(),
645 config.Zip2zip.String(),
646 config.ManifestCheck.String(),
647 config.ConstructContext.String(),
648 }, " "))
649}
650
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000651func GlobalConfigForTests(ctx android.PathContext) *GlobalConfig {
652 return &GlobalConfig{
Colin Cross69f59a32019-02-15 10:39:37 -0800653 DisablePreopt: false,
654 DisablePreoptModules: nil,
655 OnlyPreoptBootImageAndSystemServer: false,
656 HasSystemOther: false,
657 PatternsOnSystemOther: nil,
658 DisableGenerateProfile: false,
659 ProfileDir: "",
Ulya Trafimovich249386a2020-07-01 14:31:13 +0100660 BootJars: android.EmptyConfiguredJarList(),
satayevd604b212021-07-21 14:23:52 +0100661 ApexBootJars: android.EmptyConfiguredJarList(),
Ulya Trafimovich249386a2020-07-01 14:31:13 +0100662 ArtApexJars: android.EmptyConfiguredJarList(),
satayev9a6f87e2021-05-04 16:14:48 +0100663 SystemServerJars: android.EmptyConfiguredJarList(),
Colin Cross69f59a32019-02-15 10:39:37 -0800664 SystemServerApps: nil,
satayev492b17d2021-07-28 14:04:49 +0100665 ApexSystemServerJars: android.EmptyConfiguredJarList(),
Jiakai Zhangcee9e192021-10-29 19:46:45 +0000666 StandaloneSystemServerJars: android.EmptyConfiguredJarList(),
667 ApexStandaloneSystemServerJars: android.EmptyConfiguredJarList(),
Colin Cross69f59a32019-02-15 10:39:37 -0800668 SpeedApps: nil,
669 PreoptFlags: nil,
670 DefaultCompilerFilter: "",
671 SystemServerCompilerFilter: "",
672 GenerateDMFiles: false,
Colin Cross69f59a32019-02-15 10:39:37 -0800673 NoDebugInfo: false,
Mathieu Chartier3f7ddbb2019-04-29 09:33:50 -0700674 DontResolveStartupStrings: false,
Colin Cross69f59a32019-02-15 10:39:37 -0800675 AlwaysSystemServerDebugInfo: false,
676 NeverSystemServerDebugInfo: false,
677 AlwaysOtherDebugInfo: false,
678 NeverOtherDebugInfo: false,
Colin Cross69f59a32019-02-15 10:39:37 -0800679 IsEng: false,
680 SanitizeLite: false,
681 DefaultAppImages: false,
682 Dex2oatXmx: "",
683 Dex2oatXms: "",
684 EmptyDirectory: "empty_dir",
685 CpuVariant: nil,
686 InstructionSetFeatures: nil,
Colin Cross69f59a32019-02-15 10:39:37 -0800687 BootImageProfiles: nil,
Colin Cross69f59a32019-02-15 10:39:37 -0800688 BootFlags: "",
689 Dex2oatImageXmx: "",
690 Dex2oatImageXms: "",
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000691 }
692}
693
Paul Duffin9f045242021-01-21 15:05:11 +0000694func globalSoongConfigForTests() *GlobalSoongConfig {
695 return &GlobalSoongConfig{
696 Profman: android.PathForTesting("profman"),
697 Dex2oat: android.PathForTesting("dex2oat"),
698 Aapt: android.PathForTesting("aapt"),
699 SoongZip: android.PathForTesting("soong_zip"),
700 Zip2zip: android.PathForTesting("zip2zip"),
701 ManifestCheck: android.PathForTesting("manifest_check"),
702 ConstructContext: android.PathForTesting("construct_context"),
703 }
Colin Cross69f59a32019-02-15 10:39:37 -0800704}