blob: eefda197c4e4ef9c83593db6308b5c9a66c625a5 [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
Colin Cross43f08db2018-11-12 10:13:39 -080039 HasSystemOther bool // store odex files that match PatternsOnSystemOther on the system_other partition
40 PatternsOnSystemOther []string // patterns (using '%' to denote a prefix match) to put odex on the system_other partition
41
Colin Cross69f59a32019-02-15 10:39:37 -080042 DisableGenerateProfile bool // don't generate profiles
43 ProfileDir string // directory to find profiles in
Colin Cross43f08db2018-11-12 10:13:39 -080044
satayevd604b212021-07-21 14:23:52 +010045 BootJars android.ConfiguredJarList // modules for jars that form the boot class path
46 ApexBootJars android.ConfiguredJarList // jars within apex that form the boot class path
Vladimir Markod2ee5322018-12-19 17:57:57 +000047
Ulya Trafimovich249386a2020-07-01 14:31:13 +010048 ArtApexJars android.ConfiguredJarList // modules for jars that are in the ART APEX
Colin Cross800fe132019-02-11 14:21:24 -080049
Jiakai Zhangcee9e192021-10-29 19:46:45 +000050 SystemServerJars android.ConfiguredJarList // system_server classpath jars on the platform
51 SystemServerApps []string // apps that are loaded into system server
52 ApexSystemServerJars android.ConfiguredJarList // system_server classpath jars delivered via apex
53 StandaloneSystemServerJars android.ConfiguredJarList // jars on the platform that system_server loads dynamically using separate classloaders
54 ApexStandaloneSystemServerJars android.ConfiguredJarList // jars delivered via apex that system_server loads dynamically using separate classloaders
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
Jiakai Zhang389a6472021-12-14 18:54:06 +0000101var allPlatformSystemServerJarsKey = android.NewOnceKey("allPlatformSystemServerJars")
102
103// Returns all jars on the platform that system_server loads, including those on classpath and those
104// loaded dynamically.
105func (g *GlobalConfig) AllPlatformSystemServerJars(ctx android.PathContext) *android.ConfiguredJarList {
106 return ctx.Config().Once(allPlatformSystemServerJarsKey, func() interface{} {
107 res := g.SystemServerJars.AppendList(&g.StandaloneSystemServerJars)
108 return &res
109 }).(*android.ConfiguredJarList)
110}
111
112var allApexSystemServerJarsKey = android.NewOnceKey("allApexSystemServerJars")
113
114// Returns all jars delivered via apex that system_server loads, including those on classpath and
115// those loaded dynamically.
116func (g *GlobalConfig) AllApexSystemServerJars(ctx android.PathContext) *android.ConfiguredJarList {
117 return ctx.Config().Once(allApexSystemServerJarsKey, func() interface{} {
118 res := g.ApexSystemServerJars.AppendList(&g.ApexStandaloneSystemServerJars)
119 return &res
120 }).(*android.ConfiguredJarList)
121}
122
123var allSystemServerClasspathJarsKey = android.NewOnceKey("allSystemServerClasspathJars")
124
125// Returns all system_server classpath jars.
126func (g *GlobalConfig) AllSystemServerClasspathJars(ctx android.PathContext) *android.ConfiguredJarList {
127 return ctx.Config().Once(allSystemServerClasspathJarsKey, func() interface{} {
128 res := g.SystemServerJars.AppendList(&g.ApexSystemServerJars)
129 return &res
130 }).(*android.ConfiguredJarList)
131}
132
133var allSystemServerJarsKey = android.NewOnceKey("allSystemServerJars")
134
135// Returns all jars that system_server loads.
136func (g *GlobalConfig) AllSystemServerJars(ctx android.PathContext) *android.ConfiguredJarList {
137 return ctx.Config().Once(allSystemServerJarsKey, func() interface{} {
138 res := g.AllPlatformSystemServerJars(ctx).AppendList(g.AllApexSystemServerJars(ctx))
139 return &res
140 }).(*android.ConfiguredJarList)
141}
142
Martin Stjernholmc52aaf12020-01-06 23:11:37 +0000143// GlobalSoongConfig contains the global config that is generated from Soong,
144// stored in dexpreopt_soong.config.
145type GlobalSoongConfig struct {
146 // Paths to tools possibly used by the generated commands.
147 Profman android.Path
148 Dex2oat android.Path
149 Aapt android.Path
150 SoongZip android.Path
151 Zip2zip android.Path
152 ManifestCheck android.Path
Colin Cross38b96852019-05-22 10:21:09 -0700153 ConstructContext android.Path
Colin Cross43f08db2018-11-12 10:13:39 -0800154}
155
156type ModuleConfig struct {
Victor Hsiehd181c8b2019-01-29 13:00:33 -0800157 Name string
158 DexLocation string // dex location on device
Colin Cross69f59a32019-02-15 10:39:37 -0800159 BuildPath android.OutputPath
160 DexPath android.Path
Jeongik Cha33a3a812021-04-15 09:12:49 +0900161 ManifestPath android.OptionalPath
Victor Hsiehd181c8b2019-01-29 13:00:33 -0800162 UncompressedDex bool
163 HasApkLibraries bool
164 PreoptFlags []string
Colin Cross43f08db2018-11-12 10:13:39 -0800165
Colin Cross69f59a32019-02-15 10:39:37 -0800166 ProfileClassListing android.OptionalPath
Colin Cross43f08db2018-11-12 10:13:39 -0800167 ProfileIsTextListing bool
Nicolas Geoffraye7102422019-07-24 13:19:29 +0100168 ProfileBootListing android.OptionalPath
Colin Cross43f08db2018-11-12 10:13:39 -0800169
Ulya Trafimovich8c35fcf2021-02-17 16:23:28 +0000170 EnforceUsesLibraries bool // turn on build-time verify_uses_libraries check
171 EnforceUsesLibrariesStatusFile android.Path // a file with verify_uses_libraries errors (if any)
172 ProvidesUsesLibrary string // library name (usually the same as module name)
173 ClassLoaderContexts ClassLoaderContextMap
Colin Cross43f08db2018-11-12 10:13:39 -0800174
Jeongik Cha4dda75e2021-04-27 23:56:44 +0900175 Archs []android.ArchType
176 DexPreoptImagesDeps []android.OutputPaths
177
178 DexPreoptImageLocationsOnHost []string // boot image location on host (file path without the arch subdirectory)
179 DexPreoptImageLocationsOnDevice []string // boot image location on device (file path without the arch subdirectory)
Colin Cross43f08db2018-11-12 10:13:39 -0800180
Colin Cross69f59a32019-02-15 10:39:37 -0800181 PreoptBootClassPathDexFiles android.Paths // file paths of boot class path files
182 PreoptBootClassPathDexLocations []string // virtual locations of boot class path files
Colin Cross800fe132019-02-11 14:21:24 -0800183
Colin Cross43f08db2018-11-12 10:13:39 -0800184 PreoptExtractedApk bool // Overrides OnlyPreoptModules
185
186 NoCreateAppImage bool
187 ForceCreateAppImage bool
188
189 PresignedPrebuilt bool
Colin Cross43f08db2018-11-12 10:13:39 -0800190}
191
Martin Stjernholmc52aaf12020-01-06 23:11:37 +0000192type globalSoongConfigSingleton struct{}
193
194var pctx = android.NewPackageContext("android/soong/dexpreopt")
195
196func init() {
197 pctx.Import("android/soong/android")
198 android.RegisterSingletonType("dexpreopt-soong-config", func() android.Singleton {
199 return &globalSoongConfigSingleton{}
200 })
201}
202
Colin Cross69f59a32019-02-15 10:39:37 -0800203func constructPath(ctx android.PathContext, path string) android.Path {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200204 buildDirPrefix := ctx.Config().SoongOutDir() + "/"
Colin Cross69f59a32019-02-15 10:39:37 -0800205 if path == "" {
206 return nil
207 } else if strings.HasPrefix(path, buildDirPrefix) {
208 return android.PathForOutput(ctx, strings.TrimPrefix(path, buildDirPrefix))
209 } else {
210 return android.PathForSource(ctx, path)
211 }
Colin Cross43f08db2018-11-12 10:13:39 -0800212}
213
Colin Cross69f59a32019-02-15 10:39:37 -0800214func constructPaths(ctx android.PathContext, paths []string) android.Paths {
215 var ret android.Paths
216 for _, path := range paths {
217 ret = append(ret, constructPath(ctx, path))
218 }
219 return ret
Colin Cross43f08db2018-11-12 10:13:39 -0800220}
221
Colin Cross69f59a32019-02-15 10:39:37 -0800222func constructWritablePath(ctx android.PathContext, path string) android.WritablePath {
223 if path == "" {
224 return nil
225 }
226 return constructPath(ctx, path).(android.WritablePath)
227}
228
Martin Stjernholm40f9f3c2020-01-20 18:12:23 +0000229// ParseGlobalConfig parses the given data assumed to be read from the global
230// dexpreopt.config file into a GlobalConfig struct.
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000231func ParseGlobalConfig(ctx android.PathContext, data []byte) (*GlobalConfig, error) {
Colin Cross69f59a32019-02-15 10:39:37 -0800232 type GlobalJSONConfig struct {
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000233 *GlobalConfig
Colin Cross69f59a32019-02-15 10:39:37 -0800234
235 // Copies of entries in GlobalConfig that are not constructable without extra parameters. They will be
236 // used to construct the real value manually below.
Paul Duffin7ccacae2020-10-23 21:14:20 +0100237 BootImageProfiles []string
Colin Cross69f59a32019-02-15 10:39:37 -0800238 }
239
240 config := GlobalJSONConfig{}
Colin Cross988414c2020-01-11 01:11:46 +0000241 err := json.Unmarshal(data, &config)
Colin Cross69f59a32019-02-15 10:39:37 -0800242 if err != nil {
Colin Cross988414c2020-01-11 01:11:46 +0000243 return config.GlobalConfig, err
Colin Cross69f59a32019-02-15 10:39:37 -0800244 }
245
246 // Construct paths that require a PathContext.
Colin Cross69f59a32019-02-15 10:39:37 -0800247 config.GlobalConfig.BootImageProfiles = constructPaths(ctx, config.BootImageProfiles)
248
Colin Cross988414c2020-01-11 01:11:46 +0000249 return config.GlobalConfig, nil
Colin Cross69f59a32019-02-15 10:39:37 -0800250}
251
Martin Stjernholm40f9f3c2020-01-20 18:12:23 +0000252type globalConfigAndRaw struct {
Colin Cross7134e282021-12-01 12:16:55 -0800253 global *GlobalConfig
254 data []byte
255 pathErrors []error
Martin Stjernholm40f9f3c2020-01-20 18:12:23 +0000256}
257
258// GetGlobalConfig returns the global dexpreopt.config that's created in the
259// make config phase. It is loaded once the first time it is called for any
260// ctx.Config(), and returns the same data for all future calls with the same
261// ctx.Config(). A value can be inserted for tests using
262// setDexpreoptTestGlobalConfig.
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000263func GetGlobalConfig(ctx android.PathContext) *GlobalConfig {
Martin Stjernholm40f9f3c2020-01-20 18:12:23 +0000264 return getGlobalConfigRaw(ctx).global
265}
266
267// GetGlobalConfigRawData is the same as GetGlobalConfig, except that it returns
268// the literal content of dexpreopt.config.
269func GetGlobalConfigRawData(ctx android.PathContext) []byte {
270 return getGlobalConfigRaw(ctx).data
271}
272
273var globalConfigOnceKey = android.NewOnceKey("DexpreoptGlobalConfig")
274var testGlobalConfigOnceKey = android.NewOnceKey("TestDexpreoptGlobalConfig")
275
Colin Cross7134e282021-12-01 12:16:55 -0800276type pathContextErrorCollector struct {
277 android.PathContext
278 errors []error
279}
280
281func (p *pathContextErrorCollector) Errorf(format string, args ...interface{}) {
282 p.errors = append(p.errors, fmt.Errorf(format, args...))
283}
284
Martin Stjernholm40f9f3c2020-01-20 18:12:23 +0000285func getGlobalConfigRaw(ctx android.PathContext) globalConfigAndRaw {
Colin Cross7134e282021-12-01 12:16:55 -0800286 config := ctx.Config().Once(globalConfigOnceKey, func() interface{} {
Martin Stjernholm40f9f3c2020-01-20 18:12:23 +0000287 if data, err := ctx.Config().DexpreoptGlobalConfig(ctx); err != nil {
288 panic(err)
289 } else if data != nil {
Colin Cross7134e282021-12-01 12:16:55 -0800290 pathErrorCollectorCtx := &pathContextErrorCollector{PathContext: ctx}
291 globalConfig, err := ParseGlobalConfig(pathErrorCollectorCtx, data)
Martin Stjernholm40f9f3c2020-01-20 18:12:23 +0000292 if err != nil {
293 panic(err)
294 }
Colin Cross7134e282021-12-01 12:16:55 -0800295 return globalConfigAndRaw{globalConfig, data, pathErrorCollectorCtx.errors}
Martin Stjernholm40f9f3c2020-01-20 18:12:23 +0000296 }
297
298 // No global config filename set, see if there is a test config set
299 return ctx.Config().Once(testGlobalConfigOnceKey, func() interface{} {
300 // Nope, return a config with preopting disabled
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000301 return globalConfigAndRaw{&GlobalConfig{
Ulya Trafimovicha4a1c4e2021-01-15 18:40:04 +0000302 DisablePreopt: true,
303 DisablePreoptBootImages: true,
304 DisableGenerateProfile: true,
Colin Cross7134e282021-12-01 12:16:55 -0800305 }, nil, nil}
Martin Stjernholm40f9f3c2020-01-20 18:12:23 +0000306 })
307 }).(globalConfigAndRaw)
Colin Cross7134e282021-12-01 12:16:55 -0800308
309 // Avoid non-deterministic errors by reporting cached path errors on all callers.
310 for _, err := range config.pathErrors {
311 if ctx.Config().AllowMissingDependencies() {
312 // When AllowMissingDependencies it set, report errors through AddMissingDependencies.
313 // If AddMissingDependencies doesn't exist on the current context (for example when
314 // called with a SingletonContext), just swallow the errors since there is no way to
315 // report them.
316 if missingDepsCtx, ok := ctx.(interface {
317 AddMissingDependencies(missingDeps []string)
318 }); ok {
319 missingDepsCtx.AddMissingDependencies([]string{err.Error()})
320 }
321 } else {
322 android.ReportPathErrorf(ctx, "%w", err)
323 }
324 }
325
326 return config
Martin Stjernholm40f9f3c2020-01-20 18:12:23 +0000327}
328
329// SetTestGlobalConfig sets a GlobalConfig that future calls to GetGlobalConfig
330// will return. It must be called before the first call to GetGlobalConfig for
331// the config.
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000332func SetTestGlobalConfig(config android.Config, globalConfig *GlobalConfig) {
Colin Cross7134e282021-12-01 12:16:55 -0800333 config.Once(testGlobalConfigOnceKey, func() interface{} { return globalConfigAndRaw{globalConfig, nil, nil} })
Martin Stjernholm40f9f3c2020-01-20 18:12:23 +0000334}
335
Jeongik Chac6246672021-04-08 00:00:19 +0900336// This struct is required to convert ModuleConfig from/to JSON.
337// The types of fields in ModuleConfig are not convertible,
338// so moduleJSONConfig has those fields as a convertible type.
339type moduleJSONConfig struct {
340 *ModuleConfig
341
342 BuildPath string
343 DexPath string
344 ManifestPath string
345
346 ProfileClassListing string
347 ProfileBootListing string
348
349 EnforceUsesLibrariesStatusFile string
350 ClassLoaderContexts jsonClassLoaderContextMap
351
Jeongik Chac6246672021-04-08 00:00:19 +0900352 DexPreoptImagesDeps [][]string
353
354 PreoptBootClassPathDexFiles []string
355}
356
Martin Stjernholm40f9f3c2020-01-20 18:12:23 +0000357// ParseModuleConfig parses a per-module dexpreopt.config file into a
358// ModuleConfig struct. It is not used in Soong, which receives a ModuleConfig
359// struct directly from java/dexpreopt.go. It is used in dexpreopt_gen called
360// from Make to read the module dexpreopt.config written in the Make config
361// stage.
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000362func ParseModuleConfig(ctx android.PathContext, data []byte) (*ModuleConfig, error) {
Jeongik Chac6246672021-04-08 00:00:19 +0900363 config := moduleJSONConfig{}
Colin Cross69f59a32019-02-15 10:39:37 -0800364
Colin Cross988414c2020-01-11 01:11:46 +0000365 err := json.Unmarshal(data, &config)
Colin Cross69f59a32019-02-15 10:39:37 -0800366 if err != nil {
367 return config.ModuleConfig, err
368 }
369
370 // Construct paths that require a PathContext.
371 config.ModuleConfig.BuildPath = constructPath(ctx, config.BuildPath).(android.OutputPath)
372 config.ModuleConfig.DexPath = constructPath(ctx, config.DexPath)
Jeongik Cha33a3a812021-04-15 09:12:49 +0900373 config.ModuleConfig.ManifestPath = android.OptionalPathForPath(constructPath(ctx, config.ManifestPath))
Colin Cross69f59a32019-02-15 10:39:37 -0800374 config.ModuleConfig.ProfileClassListing = android.OptionalPathForPath(constructPath(ctx, config.ProfileClassListing))
Ulya Trafimovich8c35fcf2021-02-17 16:23:28 +0000375 config.ModuleConfig.EnforceUsesLibrariesStatusFile = constructPath(ctx, config.EnforceUsesLibrariesStatusFile)
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000376 config.ModuleConfig.ClassLoaderContexts = fromJsonClassLoaderContext(ctx, config.ClassLoaderContexts)
Colin Cross69f59a32019-02-15 10:39:37 -0800377 config.ModuleConfig.PreoptBootClassPathDexFiles = constructPaths(ctx, config.PreoptBootClassPathDexFiles)
Colin Cross69f59a32019-02-15 10:39:37 -0800378
Dan Willemsen0f416782019-06-13 21:44:53 +0000379 // 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 +0900380 config.ModuleConfig.DexPreoptImagesDeps = make([]android.OutputPaths, len(config.ModuleConfig.Archs))
Dan Willemsen0f416782019-06-13 21:44:53 +0000381
Colin Cross69f59a32019-02-15 10:39:37 -0800382 return config.ModuleConfig, nil
383}
384
Jeongik Chac6246672021-04-08 00:00:19 +0900385func pathsListToStringLists(pathsList []android.OutputPaths) [][]string {
386 ret := make([][]string, 0, len(pathsList))
387 for _, paths := range pathsList {
388 ret = append(ret, paths.Strings())
389 }
390 return ret
391}
392
393func moduleConfigToJSON(config *ModuleConfig) ([]byte, error) {
394 return json.MarshalIndent(&moduleJSONConfig{
395 BuildPath: config.BuildPath.String(),
396 DexPath: config.DexPath.String(),
397 ManifestPath: config.ManifestPath.String(),
398 ProfileClassListing: config.ProfileClassListing.String(),
399 ProfileBootListing: config.ProfileBootListing.String(),
400 EnforceUsesLibrariesStatusFile: config.EnforceUsesLibrariesStatusFile.String(),
401 ClassLoaderContexts: toJsonClassLoaderContext(config.ClassLoaderContexts),
Jeongik Chac6246672021-04-08 00:00:19 +0900402 DexPreoptImagesDeps: pathsListToStringLists(config.DexPreoptImagesDeps),
403 PreoptBootClassPathDexFiles: config.PreoptBootClassPathDexFiles.Strings(),
404 ModuleConfig: config,
405 }, "", " ")
406}
407
408// WriteModuleConfig serializes a ModuleConfig into a per-module dexpreopt.config JSON file.
409// These config files are used for post-processing.
410func WriteModuleConfig(ctx android.ModuleContext, config *ModuleConfig, path android.WritablePath) {
Ulya Trafimovich76b08522021-01-14 17:52:43 +0000411 if path == nil {
412 return
413 }
414
Jeongik Chac6246672021-04-08 00:00:19 +0900415 data, err := moduleConfigToJSON(config)
Ulya Trafimovich76b08522021-01-14 17:52:43 +0000416 if err != nil {
417 ctx.ModuleErrorf("failed to JSON marshal module dexpreopt.config: %v", err)
418 return
419 }
420
421 android.WriteFileRule(ctx, path, string(data))
422}
423
Martin Stjernholmd90676f2020-01-11 00:37:30 +0000424// dex2oatModuleName returns the name of the module to use for the dex2oat host
425// tool. It should be a binary module with public visibility that is compiled
426// and installed for host.
427func dex2oatModuleName(config android.Config) string {
428 // Default to the debug variant of dex2oat to help find bugs.
429 // Set USE_DEX2OAT_DEBUG to false for only building non-debug versions.
430 if config.Getenv("USE_DEX2OAT_DEBUG") == "false" {
431 return "dex2oat"
432 } else {
433 return "dex2oatd"
434 }
435}
436
Paul Duffinb506c9d2021-03-24 14:34:40 +0000437type dex2oatDependencyTag struct {
Martin Stjernholmd90676f2020-01-11 00:37:30 +0000438 blueprint.BaseDependencyTag
Colin Crossce564252022-01-12 11:13:32 -0800439 android.LicenseAnnotationToolchainDependencyTag
Paul Duffinb506c9d2021-03-24 14:34:40 +0000440}
441
442func (d dex2oatDependencyTag) ExcludeFromVisibilityEnforcement() {
443}
444
445func (d dex2oatDependencyTag) ExcludeFromApexContents() {
446}
447
Martin Stjernholm0e4cceb2021-05-13 02:38:35 +0100448func (d dex2oatDependencyTag) AllowDisabledModuleDependency(target android.Module) bool {
449 // RegisterToolDeps may run after the prebuilt mutators and hence register a
450 // dependency on the source module even when the prebuilt is to be used.
451 // dex2oatPathFromDep takes that into account when it retrieves the path to
452 // the binary, but we also need to disable the check for dependencies on
453 // disabled modules.
454 return target.IsReplacedByPrebuilt()
455}
456
Paul Duffinb506c9d2021-03-24 14:34:40 +0000457// Dex2oatDepTag represents the dependency onto the dex2oatd module. It is added to any module that
458// needs dexpreopting and so it makes no sense for it to be checked for visibility or included in
459// the apex.
460var Dex2oatDepTag = dex2oatDependencyTag{}
461
462var _ android.ExcludeFromVisibilityEnforcementTag = Dex2oatDepTag
463var _ android.ExcludeFromApexContentsTag = Dex2oatDepTag
Martin Stjernholm0e4cceb2021-05-13 02:38:35 +0100464var _ android.AllowDisabledModuleDependency = Dex2oatDepTag
Martin Stjernholmd90676f2020-01-11 00:37:30 +0000465
Martin Stjernholm6d415272020-01-31 17:10:36 +0000466// RegisterToolDeps adds the necessary dependencies to binary modules for tools
467// that are required later when Get(Cached)GlobalSoongConfig is called. It
468// should be called from a mutator that's registered with
469// android.RegistrationContext.FinalDepsMutators.
470func RegisterToolDeps(ctx android.BottomUpMutatorContext) {
Martin Stjernholmd90676f2020-01-11 00:37:30 +0000471 dex2oatBin := dex2oatModuleName(ctx.Config())
472 v := ctx.Config().BuildOSTarget.Variations()
Ulya Trafimovicha4a1c4e2021-01-15 18:40:04 +0000473 ctx.AddFarVariationDependencies(v, Dex2oatDepTag, dex2oatBin)
Martin Stjernholmd90676f2020-01-11 00:37:30 +0000474}
475
476func dex2oatPathFromDep(ctx android.ModuleContext) android.Path {
477 dex2oatBin := dex2oatModuleName(ctx.Config())
478
Martin Stjernholmc0048622020-08-18 17:37:41 +0100479 // Find the right dex2oat module, trying to follow PrebuiltDepTag from source
480 // to prebuilt if there is one. We wouldn't have to do this if the
481 // prebuilt_postdeps mutator that replaces source deps with prebuilt deps was
482 // run after RegisterToolDeps above, but changing that leads to ordering
483 // problems between mutators (RegisterToolDeps needs to run late to act on
484 // final variants, while prebuilt_postdeps needs to run before many of the
485 // PostDeps mutators, like the APEX mutators). Hence we need to dig out the
486 // prebuilt explicitly here instead.
487 var dex2oatModule android.Module
488 ctx.WalkDeps(func(child, parent android.Module) bool {
Ulya Trafimovicha4a1c4e2021-01-15 18:40:04 +0000489 if parent == ctx.Module() && ctx.OtherModuleDependencyTag(child) == Dex2oatDepTag {
Martin Stjernholmc0048622020-08-18 17:37:41 +0100490 // Found the source module, or prebuilt module that has replaced the source.
491 dex2oatModule = child
Paul Duffinf7c99f52021-04-28 10:41:21 +0100492 if android.IsModulePrebuilt(child) {
Martin Stjernholmc0048622020-08-18 17:37:41 +0100493 return false // If it's the prebuilt we're done.
494 } else {
495 return true // Recurse to check if the source has a prebuilt dependency.
496 }
497 }
498 if parent == dex2oatModule && ctx.OtherModuleDependencyTag(child) == android.PrebuiltDepTag {
Paul Duffinf7c99f52021-04-28 10:41:21 +0100499 if p := android.GetEmbeddedPrebuilt(child); p != nil && p.UsePrebuilt() {
Martin Stjernholmc0048622020-08-18 17:37:41 +0100500 dex2oatModule = child // Found a prebuilt that should be used.
501 }
502 }
503 return false
504 })
505
Martin Stjernholmd90676f2020-01-11 00:37:30 +0000506 if dex2oatModule == nil {
507 // If this happens there's probably a missing call to AddToolDeps in DepsMutator.
508 panic(fmt.Sprintf("Failed to lookup %s dependency", dex2oatBin))
509 }
510
511 dex2oatPath := dex2oatModule.(android.HostToolProvider).HostToolPath()
512 if !dex2oatPath.Valid() {
513 panic(fmt.Sprintf("Failed to find host tool path in %s", dex2oatModule))
514 }
515
516 return dex2oatPath.Path()
517}
518
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000519// createGlobalSoongConfig creates a GlobalSoongConfig from the current context.
Martin Stjernholmc52aaf12020-01-06 23:11:37 +0000520// Should not be used in dexpreopt_gen.
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000521func createGlobalSoongConfig(ctx android.ModuleContext) *GlobalSoongConfig {
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000522 return &GlobalSoongConfig{
Martin Stjernholmc52aaf12020-01-06 23:11:37 +0000523 Profman: ctx.Config().HostToolPath(ctx, "profman"),
Martin Stjernholmd90676f2020-01-11 00:37:30 +0000524 Dex2oat: dex2oatPathFromDep(ctx),
Saeid Farivar Asanjanfd27c7c2022-08-08 20:21:26 +0000525 Aapt: ctx.Config().HostToolPath(ctx, "aapt2"),
Martin Stjernholmc52aaf12020-01-06 23:11:37 +0000526 SoongZip: ctx.Config().HostToolPath(ctx, "soong_zip"),
527 Zip2zip: ctx.Config().HostToolPath(ctx, "zip2zip"),
528 ManifestCheck: ctx.Config().HostToolPath(ctx, "manifest_check"),
Ulya Trafimovich5f364b62020-06-30 12:39:01 +0100529 ConstructContext: ctx.Config().HostToolPath(ctx, "construct_context"),
Martin Stjernholmc52aaf12020-01-06 23:11:37 +0000530 }
531}
532
Martin Stjernholmd90676f2020-01-11 00:37:30 +0000533// The main reason for this Once cache for GlobalSoongConfig is to make the
534// dex2oat path available to singletons. In ordinary modules we get it through a
Ulya Trafimovicha4a1c4e2021-01-15 18:40:04 +0000535// Dex2oatDepTag dependency, but in singletons there's no simple way to do the
Martin Stjernholmd90676f2020-01-11 00:37:30 +0000536// same thing and ensure the right variant is selected, hence this cache to make
537// the resolved path available to singletons. This means we depend on there
Ulya Trafimovicha4a1c4e2021-01-15 18:40:04 +0000538// being at least one ordinary module with a Dex2oatDepTag dependency.
Martin Stjernholmd90676f2020-01-11 00:37:30 +0000539//
540// TODO(b/147613152): Implement a way to deal with dependencies from singletons,
Paul Duffin9f045242021-01-21 15:05:11 +0000541// and then possibly remove this cache altogether.
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000542var globalSoongConfigOnceKey = android.NewOnceKey("DexpreoptGlobalSoongConfig")
543
544// GetGlobalSoongConfig creates a GlobalSoongConfig the first time it's called,
545// and later returns the same cached instance.
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000546func GetGlobalSoongConfig(ctx android.ModuleContext) *GlobalSoongConfig {
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000547 globalSoong := ctx.Config().Once(globalSoongConfigOnceKey, func() interface{} {
548 return createGlobalSoongConfig(ctx)
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000549 }).(*GlobalSoongConfig)
Martin Stjernholmd90676f2020-01-11 00:37:30 +0000550
551 // Always resolve the tool path from the dependency, to ensure that every
552 // module has the dependency added properly.
553 myDex2oat := dex2oatPathFromDep(ctx)
554 if myDex2oat != globalSoong.Dex2oat {
555 panic(fmt.Sprintf("Inconsistent dex2oat path in cached config: expected %s, got %s", globalSoong.Dex2oat, myDex2oat))
556 }
557
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000558 return globalSoong
559}
560
561// GetCachedGlobalSoongConfig returns a cached GlobalSoongConfig created by an
562// earlier GetGlobalSoongConfig call. This function works with any context
563// compatible with a basic PathContext, since it doesn't try to create a
Martin Stjernholm6d415272020-01-31 17:10:36 +0000564// GlobalSoongConfig with the proper paths (which requires a full
565// ModuleContext). If there has been no prior call to GetGlobalSoongConfig, nil
566// is returned.
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000567func GetCachedGlobalSoongConfig(ctx android.PathContext) *GlobalSoongConfig {
Martin Stjernholm6d415272020-01-31 17:10:36 +0000568 return ctx.Config().Once(globalSoongConfigOnceKey, func() interface{} {
569 return (*GlobalSoongConfig)(nil)
570 }).(*GlobalSoongConfig)
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000571}
572
Martin Stjernholmc52aaf12020-01-06 23:11:37 +0000573type globalJsonSoongConfig struct {
574 Profman string
575 Dex2oat string
576 Aapt string
577 SoongZip string
578 Zip2zip string
579 ManifestCheck string
580 ConstructContext string
581}
582
Martin Stjernholm40f9f3c2020-01-20 18:12:23 +0000583// ParseGlobalSoongConfig parses the given data assumed to be read from the
584// global dexpreopt_soong.config file into a GlobalSoongConfig struct. It is
585// only used in dexpreopt_gen.
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000586func ParseGlobalSoongConfig(ctx android.PathContext, data []byte) (*GlobalSoongConfig, error) {
Martin Stjernholmc52aaf12020-01-06 23:11:37 +0000587 var jc globalJsonSoongConfig
588
Colin Cross988414c2020-01-11 01:11:46 +0000589 err := json.Unmarshal(data, &jc)
Martin Stjernholmc52aaf12020-01-06 23:11:37 +0000590 if err != nil {
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000591 return &GlobalSoongConfig{}, err
Martin Stjernholmc52aaf12020-01-06 23:11:37 +0000592 }
593
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000594 config := &GlobalSoongConfig{
Martin Stjernholmc52aaf12020-01-06 23:11:37 +0000595 Profman: constructPath(ctx, jc.Profman),
596 Dex2oat: constructPath(ctx, jc.Dex2oat),
597 Aapt: constructPath(ctx, jc.Aapt),
598 SoongZip: constructPath(ctx, jc.SoongZip),
599 Zip2zip: constructPath(ctx, jc.Zip2zip),
600 ManifestCheck: constructPath(ctx, jc.ManifestCheck),
601 ConstructContext: constructPath(ctx, jc.ConstructContext),
602 }
603
604 return config, nil
605}
606
satayevd604b212021-07-21 14:23:52 +0100607// checkBootJarsConfigConsistency checks the consistency of BootJars and ApexBootJars fields in
Paul Duffin7d1d0832021-04-23 11:39:41 +0100608// DexpreoptGlobalConfig and Config.productVariables.
609func checkBootJarsConfigConsistency(ctx android.SingletonContext, dexpreoptConfig *GlobalConfig, config android.Config) {
610 compareBootJars := func(property string, dexpreoptJars, variableJars android.ConfiguredJarList) {
611 dexpreoptPairs := dexpreoptJars.CopyOfApexJarPairs()
612 variablePairs := variableJars.CopyOfApexJarPairs()
613 if !reflect.DeepEqual(dexpreoptPairs, variablePairs) {
614 ctx.Errorf("Inconsistent configuration of %[1]s\n"+
615 " dexpreopt.GlobalConfig.%[1]s = %[2]s\n"+
616 " productVariables.%[1]s = %[3]s",
617 property, dexpreoptPairs, variablePairs)
618 }
619 }
620
satayevd604b212021-07-21 14:23:52 +0100621 compareBootJars("BootJars", dexpreoptConfig.BootJars, config.NonApexBootJars())
622 compareBootJars("ApexBootJars", dexpreoptConfig.ApexBootJars, config.ApexBootJars())
Paul Duffin7d1d0832021-04-23 11:39:41 +0100623}
624
Martin Stjernholmc52aaf12020-01-06 23:11:37 +0000625func (s *globalSoongConfigSingleton) GenerateBuildActions(ctx android.SingletonContext) {
Paul Duffin7d1d0832021-04-23 11:39:41 +0100626 checkBootJarsConfigConsistency(ctx, GetGlobalConfig(ctx), ctx.Config())
627
Martin Stjernholmd90676f2020-01-11 00:37:30 +0000628 if GetGlobalConfig(ctx).DisablePreopt {
629 return
630 }
631
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000632 config := GetCachedGlobalSoongConfig(ctx)
Martin Stjernholm6d415272020-01-31 17:10:36 +0000633 if config == nil {
634 // No module has enabled dexpreopting, so we assume there will be no calls
635 // to dexpreopt_gen.
636 return
637 }
638
Martin Stjernholmc52aaf12020-01-06 23:11:37 +0000639 jc := globalJsonSoongConfig{
640 Profman: config.Profman.String(),
641 Dex2oat: config.Dex2oat.String(),
642 Aapt: config.Aapt.String(),
643 SoongZip: config.SoongZip.String(),
644 Zip2zip: config.Zip2zip.String(),
645 ManifestCheck: config.ManifestCheck.String(),
646 ConstructContext: config.ConstructContext.String(),
647 }
648
649 data, err := json.Marshal(jc)
650 if err != nil {
651 ctx.Errorf("failed to JSON marshal GlobalSoongConfig: %v", err)
652 return
653 }
654
Colin Crosscf371cc2020-11-13 11:48:42 -0800655 android.WriteFileRule(ctx, android.PathForOutput(ctx, "dexpreopt_soong.config"), string(data))
Martin Stjernholmc52aaf12020-01-06 23:11:37 +0000656}
657
658func (s *globalSoongConfigSingleton) MakeVars(ctx android.MakeVarsContext) {
Martin Stjernholmd90676f2020-01-11 00:37:30 +0000659 if GetGlobalConfig(ctx).DisablePreopt {
660 return
661 }
662
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000663 config := GetCachedGlobalSoongConfig(ctx)
Martin Stjernholm6d415272020-01-31 17:10:36 +0000664 if config == nil {
665 return
666 }
Martin Stjernholmc52aaf12020-01-06 23:11:37 +0000667
668 ctx.Strict("DEX2OAT", config.Dex2oat.String())
669 ctx.Strict("DEXPREOPT_GEN_DEPS", strings.Join([]string{
670 config.Profman.String(),
671 config.Dex2oat.String(),
672 config.Aapt.String(),
673 config.SoongZip.String(),
674 config.Zip2zip.String(),
675 config.ManifestCheck.String(),
676 config.ConstructContext.String(),
677 }, " "))
678}
679
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000680func GlobalConfigForTests(ctx android.PathContext) *GlobalConfig {
681 return &GlobalConfig{
Colin Cross69f59a32019-02-15 10:39:37 -0800682 DisablePreopt: false,
683 DisablePreoptModules: nil,
684 OnlyPreoptBootImageAndSystemServer: false,
685 HasSystemOther: false,
686 PatternsOnSystemOther: nil,
687 DisableGenerateProfile: false,
688 ProfileDir: "",
Ulya Trafimovich249386a2020-07-01 14:31:13 +0100689 BootJars: android.EmptyConfiguredJarList(),
satayevd604b212021-07-21 14:23:52 +0100690 ApexBootJars: android.EmptyConfiguredJarList(),
Ulya Trafimovich249386a2020-07-01 14:31:13 +0100691 ArtApexJars: android.EmptyConfiguredJarList(),
satayev9a6f87e2021-05-04 16:14:48 +0100692 SystemServerJars: android.EmptyConfiguredJarList(),
Colin Cross69f59a32019-02-15 10:39:37 -0800693 SystemServerApps: nil,
satayev492b17d2021-07-28 14:04:49 +0100694 ApexSystemServerJars: android.EmptyConfiguredJarList(),
Jiakai Zhangcee9e192021-10-29 19:46:45 +0000695 StandaloneSystemServerJars: android.EmptyConfiguredJarList(),
696 ApexStandaloneSystemServerJars: android.EmptyConfiguredJarList(),
Colin Cross69f59a32019-02-15 10:39:37 -0800697 SpeedApps: nil,
698 PreoptFlags: nil,
699 DefaultCompilerFilter: "",
700 SystemServerCompilerFilter: "",
701 GenerateDMFiles: false,
Colin Cross69f59a32019-02-15 10:39:37 -0800702 NoDebugInfo: false,
Mathieu Chartier3f7ddbb2019-04-29 09:33:50 -0700703 DontResolveStartupStrings: false,
Colin Cross69f59a32019-02-15 10:39:37 -0800704 AlwaysSystemServerDebugInfo: false,
705 NeverSystemServerDebugInfo: false,
706 AlwaysOtherDebugInfo: false,
707 NeverOtherDebugInfo: false,
Colin Cross69f59a32019-02-15 10:39:37 -0800708 IsEng: false,
709 SanitizeLite: false,
710 DefaultAppImages: false,
711 Dex2oatXmx: "",
712 Dex2oatXms: "",
713 EmptyDirectory: "empty_dir",
714 CpuVariant: nil,
715 InstructionSetFeatures: nil,
Colin Cross69f59a32019-02-15 10:39:37 -0800716 BootImageProfiles: nil,
Colin Cross69f59a32019-02-15 10:39:37 -0800717 BootFlags: "",
718 Dex2oatImageXmx: "",
719 Dex2oatImageXms: "",
Martin Stjernholm75a48d82020-01-10 20:32:59 +0000720 }
721}
722
Paul Duffin9f045242021-01-21 15:05:11 +0000723func globalSoongConfigForTests() *GlobalSoongConfig {
724 return &GlobalSoongConfig{
725 Profman: android.PathForTesting("profman"),
726 Dex2oat: android.PathForTesting("dex2oat"),
Saeid Farivar Asanjanfd27c7c2022-08-08 20:21:26 +0000727 Aapt: android.PathForTesting("aapt2"),
Paul Duffin9f045242021-01-21 15:05:11 +0000728 SoongZip: android.PathForTesting("soong_zip"),
729 Zip2zip: android.PathForTesting("zip2zip"),
730 ManifestCheck: android.PathForTesting("manifest_check"),
731 ConstructContext: android.PathForTesting("construct_context"),
732 }
Colin Cross69f59a32019-02-15 10:39:37 -0800733}