1// Copyright 2019 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 java
16
17import (
18	"path/filepath"
19	"strings"
20
21	"android/soong/android"
22	"android/soong/dexpreopt"
23
24	"github.com/google/blueprint"
25	"github.com/google/blueprint/proptools"
26)
27
28// =================================================================================================
29// WIP - see http://b/177892522 for details
30//
31// The build support for boot images is currently being migrated away from singleton to modules so
32// the documentation may not be strictly accurate. Rather than update the documentation at every
33// step which will create a lot of churn the changes that have been made will be listed here and the
34// documentation will be updated once it is closer to the final result.
35//
36// Changes:
37// 1) dex_bootjars is now a singleton module and not a plain singleton.
38// 2) Boot images are now represented by the boot_image module type.
39// 3) The art boot image is called "art-boot-image", the framework boot image is called
40//    "framework-boot-image".
41// 4) They are defined in art/build/boot/Android.bp and frameworks/base/boot/Android.bp
42//    respectively.
43// 5) Each boot_image retrieves the appropriate boot image configuration from the map returned by
44//    genBootImageConfigs() using the image_name specified in the boot_image module.
45// =================================================================================================
46
47// This comment describes:
48//   1. ART boot images in general (their types, structure, file layout, etc.)
49//   2. build system support for boot images
50//
51// 1. ART boot images
52// ------------------
53//
54// A boot image in ART is a set of files that contain AOT-compiled native code and a heap snapshot
55// of AOT-initialized classes for the bootclasspath Java libraries. A boot image is compiled from a
56// set of DEX jars by the dex2oat compiler. A boot image is used for two purposes: 1) it is
57// installed on device and loaded at runtime, and 2) other Java libraries and apps are compiled
58// against it (compilation may take place either on host, known as "dexpreopt", or on device, known
59// as "dexopt").
60//
61// A boot image is not a single file, but a collection of interrelated files. Each boot image has a
62// number of components that correspond to the Java libraries that constitute it. For each component
63// there are multiple files:
64//   - *.oat or *.odex file with native code (architecture-specific, one per instruction set)
65//   - *.art file with pre-initialized Java classes (architecture-specific, one per instruction set)
66//   - *.vdex file with verification metadata for the DEX bytecode (architecture independent)
67//
68// *.vdex files for the boot images do not contain the DEX bytecode itself, because the
69// bootclasspath DEX files are stored on disk in uncompressed and aligned form. Consequently a boot
70// image is not self-contained and cannot be used without its DEX files. To simplify the management
71// of boot image files, ART uses a certain naming scheme and associates the following metadata with
72// each boot image:
73//   - A stem, which is a symbolic name that is prepended to boot image file names.
74//   - A location (on-device path to the boot image files).
75//   - A list of boot image locations (on-device paths to dependency boot images).
76//   - A set of DEX locations (on-device paths to the DEX files, one location for one DEX file used
77//     to compile the boot image).
78//
79// There are two kinds of boot images:
80//   - primary boot images
81//   - boot image extensions
82//
83// 1.1. Primary boot images
84// ------------------------
85//
86// A primary boot image is compiled for a core subset of bootclasspath Java libraries. It does not
87// depend on any other images, and other boot images may depend on it.
88//
89// For example, assuming that the stem is "boot", the location is /apex/com.android.art/javalib/,
90// the set of core bootclasspath libraries is A B C, and the boot image is compiled for ARM targets
91// (32 and 64 bits), it will have three components with the following files:
92//   - /apex/com.android.art/javalib/{arm,arm64}/boot.{art,oat,vdex}
93//   - /apex/com.android.art/javalib/{arm,arm64}/boot-B.{art,oat,vdex}
94//   - /apex/com.android.art/javalib/{arm,arm64}/boot-C.{art,oat,vdex}
95//
96// The files of the first component are special: they do not have the component name appended after
97// the stem. This naming convention dates back to the times when the boot image was not split into
98// components, and there were just boot.oat and boot.art. The decision to split was motivated by
99// licensing reasons for one of the bootclasspath libraries.
100//
101// As of November 2020 the only primary boot image in Android is the image in the ART APEX
102// com.android.art. The primary ART boot image contains the Core libraries that are part of the ART
103// module. When the ART module gets updated, the primary boot image will be updated with it, and all
104// dependent images will get invalidated (the checksum of the primary image stored in dependent
105// images will not match), unless they are updated in sync with the ART module.
106//
107// 1.2. Boot image extensions
108// --------------------------
109//
110// A boot image extension is compiled for a subset of bootclasspath Java libraries (in particular,
111// this subset does not include the Core bootclasspath libraries that go into the primary boot
112// image). A boot image extension depends on the primary boot image and optionally some other boot
113// image extensions. Other images may depend on it. In other words, boot image extensions can form
114// acyclic dependency graphs.
115//
116// The motivation for boot image extensions comes from the Mainline project. Consider a situation
117// when the list of bootclasspath libraries is A B C, and both A and B are parts of the Android
118// platform, but C is part of an updatable APEX com.android.C. When the APEX is updated, the Java
119// code for C might have changed compared to the code that was used to compile the boot image.
120// Consequently, the whole boot image is obsolete and invalidated (even though the code for A and B
121// that does not depend on C is up to date). To avoid this, the original monolithic boot image is
122// split in two parts: the primary boot image that contains A B, and the boot image extension that
123// contains C and depends on the primary boot image (extends it).
124//
125// For example, assuming that the stem is "boot", the location is /system/framework, the set of
126// bootclasspath libraries is D E (where D is part of the platform and is located in
127// /system/framework, and E is part of a non-updatable APEX com.android.E and is located in
128// /apex/com.android.E/javalib), and the boot image is compiled for ARM targets (32 and 64 bits),
129// it will have two components with the following files:
130//   - /system/framework/{arm,arm64}/boot-D.{art,oat,vdex}
131//   - /system/framework/{arm,arm64}/boot-E.{art,oat,vdex}
132//
133// As of November 2020 the only boot image extension in Android is the Framework boot image
134// extension. It extends the primary ART boot image and contains Framework libraries and other
135// bootclasspath libraries from the platform and non-updatable APEXes that are not included in the
136// ART image. The Framework boot image extension is updated together with the platform. In the
137// future other boot image extensions may be added for some updatable modules.
138//
139//
140// 2. Build system support for boot images
141// ---------------------------------------
142//
143// The primary ART boot image needs to be compiled with one dex2oat invocation that depends on DEX
144// jars for the core libraries. Framework boot image extension needs to be compiled with one dex2oat
145// invocation that depends on the primary ART boot image and all bootclasspath DEX jars except the
146// core libraries as they are already part of the primary ART boot image.
147//
148// 2.1. Libraries that go in the boot images
149// -----------------------------------------
150//
151// The contents of each boot image are determined by the PRODUCT variables. The primary ART APEX
152// boot image contains libraries listed in the ART_APEX_JARS variable in the AOSP makefiles. The
153// Framework boot image extension contains libraries specified in the PRODUCT_BOOT_JARS and
154// PRODUCT_BOOT_JARS_EXTRA variables. The AOSP makefiles specify some common Framework libraries,
155// but more product-specific libraries can be added in the product makefiles.
156//
157// Each component of the PRODUCT_BOOT_JARS and PRODUCT_BOOT_JARS_EXTRA variables is a
158// colon-separated pair <apex>:<library>, where <apex> is the variant name of a non-updatable APEX,
159// "platform" if the library is a part of the platform in the system partition, or "system_ext" if
160// it's in the system_ext partition.
161//
162// In these variables APEXes are identified by their "variant names", i.e. the names they get
163// mounted as in /apex on device. In Soong modules that is the name set in the "apex_name"
164// properties, which default to the "name" values. For example, many APEXes have both
165// com.android.xxx and com.google.android.xxx modules in Soong, but take the same place
166// /apex/com.android.xxx at runtime. In these cases the variant name is always com.android.xxx,
167// regardless which APEX goes into the product. See also android.ApexInfo.ApexVariationName and
168// apex.apexBundleProperties.Apex_name.
169//
170// A related variable PRODUCT_APEX_BOOT_JARS contains bootclasspath libraries that are in APEXes.
171// They are not included in the boot image. The only exception here are ART jars and core-icu4j.jar
172// that have been historically part of the boot image and are now in apexes; they are in boot images
173// and core-icu4j.jar is generally treated as being part of PRODUCT_BOOT_JARS.
174//
175// One exception to the above rules are "coverage" builds (a special build flavor which requires
176// setting environment variable EMMA_INSTRUMENT_FRAMEWORK=true). In coverage builds the Java code in
177// boot image libraries is instrumented, which means that the instrumentation library (jacocoagent)
178// needs to be added to the list of bootclasspath DEX jars.
179//
180// In general, there is a requirement that the source code for a boot image library must be
181// available at build time (e.g. it cannot be a stub that has a separate implementation library).
182//
183// 2.2. Static configs
184// -------------------
185//
186// Because boot images are used to dexpreopt other Java modules, the paths to boot image files must
187// be known by the time dexpreopt build rules for the dependent modules are generated. Boot image
188// configs are constructed very early during the build, before build rule generation. The configs
189// provide predefined paths to boot image files (these paths depend only on static build
190// configuration, such as PRODUCT variables, and use hard-coded directory names).
191//
192// 2.3. Singleton
193// --------------
194//
195// Build rules for the boot images are generated with a Soong singleton. Because a singleton has no
196// dependencies on other modules, it has to find the modules for the DEX jars using VisitAllModules.
197// Soong loops through all modules and compares each module against a list of bootclasspath library
198// names. Then it generates build rules that copy DEX jars from their intermediate module-specific
199// locations to the hard-coded locations predefined in the boot image configs.
200//
201// It would be possible to use a module with proper dependencies instead, but that would require
202// changes in the way Soong generates variables for Make: a singleton can use one MakeVars() method
203// that writes variables to out/soong/make_vars-*.mk, which is included early by the main makefile,
204// but module(s) would have to use out/soong/Android-*.mk which has a group of LOCAL_* variables
205// for each module, and is included later.
206//
207// 2.4. Install rules
208// ------------------
209//
210// The primary boot image and the Framework extension are installed in different ways. The primary
211// boot image is part of the ART APEX: it is copied into the APEX intermediate files, packaged
212// together with other APEX contents, extracted and mounted on device. The Framework boot image
213// extension is installed by the rules defined in makefiles (make/core/dex_preopt_libart.mk). Soong
214// writes out a few DEXPREOPT_IMAGE_* variables for Make; these variables contain boot image names,
215// paths and so on.
216//
217
218var artApexNames = []string{
219	"com.android.art",
220	"com.android.art.debug",
221	"com.android.art.testing",
222	"com.google.android.art",
223	"com.google.android.art.debug",
224	"com.google.android.art.testing",
225}
226
227var (
228	dexpreoptBootJarDepTag          = bootclasspathDependencyTag{name: "dexpreopt-boot-jar"}
229	dexBootJarsFragmentsKey         = android.NewOnceKey("dexBootJarsFragments")
230	apexContributionsMetadataDepTag = dependencyTag{name: "all_apex_contributions"}
231)
232
233func init() {
234	RegisterDexpreoptBootJarsComponents(android.InitRegistrationContext)
235}
236
237// Target-independent description of a boot image.
238//
239// WARNING: All fields in this struct should be initialized in the genBootImageConfigs function.
240// Failure to do so can lead to data races if there is no synchronization enforced ordering between
241// the writer and the reader.
242type bootImageConfig struct {
243	// If this image is an extension, the image that it extends.
244	extends *bootImageConfig
245
246	// Image name (used in directory names and ninja rule names).
247	name string
248
249	// If the module with the given name exists, this config is enabled.
250	enabledIfExists string
251
252	// Basename of the image: the resulting filenames are <stem>[-<jar>].{art,oat,vdex}.
253	stem string
254
255	// Output directory for the image files.
256	dir android.OutputPath
257
258	// Output directory for the image files with debug symbols.
259	symbolsDir android.OutputPath
260
261	// The relative location where the image files are installed. On host, the location is relative to
262	// $ANDROID_PRODUCT_OUT.
263	//
264	// Only the configs that are built by platform_bootclasspath are installable on device. On device,
265	// the location is relative to "/".
266	installDir string
267
268	// A list of (location, jar) pairs for the Java modules in this image.
269	modules android.ConfiguredJarList
270
271	// File paths to jars.
272	dexPaths     android.WritablePaths // for this image
273	dexPathsDeps android.WritablePaths // for the dependency images and in this image
274
275	// Map from module name (without prebuilt_ prefix) to the predefined build path.
276	dexPathsByModule map[string]android.WritablePath
277
278	// File path to a zip archive with all image files (or nil, if not needed).
279	zip android.WritablePath
280
281	// Target-dependent fields.
282	variants []*bootImageVariant
283
284	// Path of the preloaded classes file.
285	preloadedClassesFile string
286
287	// The "--compiler-filter" argument.
288	compilerFilter string
289
290	// The "--single-image" argument.
291	singleImage bool
292
293	// Profiles imported from APEXes, in addition to the profile at the default path. Each entry must
294	// be the name of an APEX module.
295	profileImports []string
296}
297
298// Target-dependent description of a boot image.
299//
300// WARNING: The warning comment on bootImageConfig applies here too.
301type bootImageVariant struct {
302	*bootImageConfig
303
304	// Target for which the image is generated.
305	target android.Target
306
307	// The "locations" of jars.
308	dexLocations     []string // for this image
309	dexLocationsDeps []string // for the dependency images and in this image
310
311	// Paths to image files.
312	imagePathOnHost   android.OutputPath // first image file path on host
313	imagePathOnDevice string             // first image file path on device
314
315	// All the files that constitute this image variant, i.e. .art, .oat and .vdex files.
316	imagesDeps android.OutputPaths
317
318	// The path to the base image variant's imagePathOnHost field, where base image variant
319	// means the image variant that this extends.
320	//
321	// This is only set for a variant of an image that extends another image.
322	baseImages android.OutputPaths
323
324	// The paths to the base image variant's imagesDeps field, where base image variant
325	// means the image variant that this extends.
326	//
327	// This is only set for a variant of an image that extends another image.
328	baseImagesDeps android.Paths
329
330	// Rules which should be used in make to install the outputs on host.
331	//
332	// Deprecated: Not initialized correctly, see struct comment.
333	installs android.RuleBuilderInstalls
334
335	// Rules which should be used in make to install the vdex outputs on host.
336	//
337	// Deprecated: Not initialized correctly, see struct comment.
338	vdexInstalls android.RuleBuilderInstalls
339
340	// Rules which should be used in make to install the unstripped outputs on host.
341	//
342	// Deprecated: Not initialized correctly, see struct comment.
343	unstrippedInstalls android.RuleBuilderInstalls
344
345	// Path to the license metadata file for the module that built the image.
346	//
347	// Deprecated: Not initialized correctly, see struct comment.
348	licenseMetadataFile android.OptionalPath
349}
350
351// Get target-specific boot image variant for the given boot image config and target.
352func (image bootImageConfig) getVariant(target android.Target) *bootImageVariant {
353	for _, variant := range image.variants {
354		if variant.target.Os == target.Os && variant.target.Arch.ArchType == target.Arch.ArchType {
355			return variant
356		}
357	}
358	return nil
359}
360
361// Return any (the first) variant which is for the device (as opposed to for the host).
362func (image bootImageConfig) getAnyAndroidVariant() *bootImageVariant {
363	for _, variant := range image.variants {
364		if variant.target.Os == android.Android {
365			return variant
366		}
367	}
368	return nil
369}
370
371// Return the name of a boot image module given a boot image config and a component (module) index.
372// A module name is a combination of the Java library name, and the boot image stem (that is stored
373// in the config).
374func (image bootImageConfig) moduleName(ctx android.PathContext, idx int) string {
375	// The first module of the primary boot image is special: its module name has only the stem, but
376	// not the library name. All other module names are of the form <stem>-<library name>
377	m := image.modules.Jar(idx)
378	name := image.stem
379	if idx != 0 || image.extends != nil {
380		name += "-" + android.ModuleStem(ctx.Config(), image.modules.Apex(idx), m)
381	}
382	return name
383}
384
385// Return the name of the first boot image module, or stem if the list of modules is empty.
386func (image bootImageConfig) firstModuleNameOrStem(ctx android.PathContext) string {
387	if image.modules.Len() > 0 {
388		return image.moduleName(ctx, 0)
389	} else {
390		return image.stem
391	}
392}
393
394// Return filenames for the given boot image component, given the output directory and a list of
395// extensions.
396func (image bootImageConfig) moduleFiles(ctx android.PathContext, dir android.OutputPath, exts ...string) android.OutputPaths {
397	ret := make(android.OutputPaths, 0, image.modules.Len()*len(exts))
398	for i := 0; i < image.modules.Len(); i++ {
399		name := image.moduleName(ctx, i)
400		for _, ext := range exts {
401			ret = append(ret, dir.Join(ctx, name+ext))
402		}
403		if image.singleImage {
404			break
405		}
406	}
407	return ret
408}
409
410// apexVariants returns a list of all *bootImageVariant that could be included in an apex.
411func (image *bootImageConfig) apexVariants() []*bootImageVariant {
412	variants := []*bootImageVariant{}
413	for _, variant := range image.variants {
414		// We also generate boot images for host (for testing), but we don't need those in the apex.
415		// TODO(b/177892522) - consider changing this to check Os.OsClass = android.Device
416		if variant.target.Os == android.Android {
417			variants = append(variants, variant)
418		}
419	}
420	return variants
421}
422
423// Return boot image locations (as a list of symbolic paths).
424//
425// The image "location" is a symbolic path that, with multiarchitecture support, doesn't really
426// exist on the device. Typically it is /apex/com.android.art/javalib/boot.art and should be the
427// same for all supported architectures on the device. The concrete architecture specific files
428// actually end up in architecture-specific sub-directory such as arm, arm64, x86, or x86_64.
429//
430// For example a physical file /apex/com.android.art/javalib/x86/boot.art has "image location"
431// /apex/com.android.art/javalib/boot.art (which is not an actual file).
432//
433// For a primary boot image the list of locations has a single element.
434//
435// For a boot image extension the list of locations contains a location for all dependency images
436// (including the primary image) and the location of the extension itself. For example, for the
437// Framework boot image extension that depends on the primary ART boot image the list contains two
438// elements.
439//
440// The location is passed as an argument to the ART tools like dex2oat instead of the real path.
441// ART tools will then reconstruct the architecture-specific real path.
442func (image *bootImageVariant) imageLocations() (imageLocationsOnHost []string, imageLocationsOnDevice []string) {
443	if image.extends != nil {
444		imageLocationsOnHost, imageLocationsOnDevice = image.extends.getVariant(image.target).imageLocations()
445	}
446	return append(imageLocationsOnHost, dexpreopt.PathToLocation(image.imagePathOnHost, image.target.Arch.ArchType)),
447		append(imageLocationsOnDevice, dexpreopt.PathStringToLocation(image.imagePathOnDevice, image.target.Arch.ArchType))
448}
449
450func (image *bootImageConfig) isProfileGuided() bool {
451	return image.compilerFilter == "speed-profile"
452}
453
454func (image *bootImageConfig) isEnabled(ctx android.BaseModuleContext) bool {
455	return ctx.OtherModuleExists(image.enabledIfExists)
456}
457
458func dexpreoptBootJarsFactory() android.SingletonModule {
459	m := &dexpreoptBootJars{}
460	android.InitAndroidArchModule(m, android.DeviceSupported, android.MultilibCommon)
461	return m
462}
463
464func RegisterDexpreoptBootJarsComponents(ctx android.RegistrationContext) {
465	ctx.RegisterParallelSingletonModuleType("dex_bootjars", dexpreoptBootJarsFactory)
466	ctx.FinalDepsMutators(func(ctx android.RegisterMutatorsContext) {
467		ctx.BottomUp("dex_bootjars_deps", DexpreoptBootJarsMutator).Parallel()
468	})
469}
470
471func SkipDexpreoptBootJars(ctx android.PathContext) bool {
472	global := dexpreopt.GetGlobalConfig(ctx)
473	return global.DisablePreoptBootImages || !shouldBuildBootImages(ctx.Config(), global)
474}
475
476// Singleton module for generating boot image build rules.
477type dexpreoptBootJars struct {
478	android.SingletonModuleBase
479
480	// Default boot image config (currently always the Framework boot image extension). It should be
481	// noted that JIT-Zygote builds use ART APEX image instead of the Framework boot image extension,
482	// but the switch is handled not here, but in the makefiles (triggered with
483	// DEXPREOPT_USE_ART_IMAGE=true).
484	defaultBootImage *bootImageConfig
485
486	// Other boot image configs (currently the list contains only the primary ART APEX image. It
487	// used to contain an experimental JIT-Zygote image (now replaced with the ART APEX image). In
488	// the future other boot image extensions may be added.
489	otherImages []*bootImageConfig
490
491	// Build path to a config file that Soong writes for Make (to be used in makefiles that install
492	// the default boot image).
493	dexpreoptConfigForMake android.WritablePath
494}
495
496func (dbj *dexpreoptBootJars) DepsMutator(ctx android.BottomUpMutatorContext) {
497	// Create a dependency on all_apex_contributions to determine the selected mainline module
498	ctx.AddDependency(ctx.Module(), apexContributionsMetadataDepTag, "all_apex_contributions")
499}
500
501func DexpreoptBootJarsMutator(ctx android.BottomUpMutatorContext) {
502	if _, ok := ctx.Module().(*dexpreoptBootJars); !ok {
503		return
504	}
505
506	if dexpreopt.IsDex2oatNeeded(ctx) {
507		// Add a dependency onto the dex2oat tool which is needed for creating the boot image. The
508		// path is retrieved from the dependency by GetGlobalSoongConfig(ctx).
509		dexpreopt.RegisterToolDeps(ctx)
510	}
511
512	imageConfigs := genBootImageConfigs(ctx)
513	for _, config := range imageConfigs {
514		if !config.isEnabled(ctx) {
515			continue
516		}
517		// For accessing the boot jars.
518		addDependenciesOntoBootImageModules(ctx, config.modules, dexpreoptBootJarDepTag)
519		// Create a dependency on the apex selected using RELEASE_APEX_CONTRIBUTIONS_*
520		// TODO: b/308174306 - Remove the direct depedendency edge to the java_library (source/prebuilt) once all mainline modules
521		// have been flagged using RELEASE_APEX_CONTRIBUTIONS_*
522		apexes := []string{}
523		for i := 0; i < config.modules.Len(); i++ {
524			apexes = append(apexes, config.modules.Apex(i))
525		}
526		addDependenciesOntoSelectedBootImageApexes(ctx, android.FirstUniqueStrings(apexes)...)
527	}
528
529	if ctx.OtherModuleExists("platform-bootclasspath") {
530		// For accessing all bootclasspath fragments.
531		addDependencyOntoApexModulePair(ctx, "platform", "platform-bootclasspath", platformBootclasspathDepTag)
532	} else if ctx.OtherModuleExists("art-bootclasspath-fragment") {
533		// For accessing the ART bootclasspath fragment on a thin manifest (e.g., master-art) where
534		// platform-bootclasspath doesn't exist.
535		addDependencyOntoApexModulePair(ctx, "com.android.art", "art-bootclasspath-fragment", bootclasspathFragmentDepTag)
536	}
537}
538
539// Create a dependency from dex_bootjars to the specific apexes selected using all_apex_contributions
540// This dependency will be used to get the path to the deapexed dex boot jars and profile (via a provider)
541func addDependenciesOntoSelectedBootImageApexes(ctx android.BottomUpMutatorContext, apexes ...string) {
542	psi := android.PrebuiltSelectionInfoMap{}
543	ctx.VisitDirectDepsWithTag(apexContributionsMetadataDepTag, func(am android.Module) {
544		if info, exists := android.OtherModuleProvider(ctx, am, android.PrebuiltSelectionInfoProvider); exists {
545			psi = info
546		}
547	})
548	for _, apex := range apexes {
549		for _, selected := range psi.GetSelectedModulesForApiDomain(apex) {
550			// We need to add a dep on only the apex listed in `contents` of the selected apex_contributions module
551			// This is not available in a structured format in `apex_contributions`, so this hack adds a dep on all `contents`
552			// (some modules like art.module.public.api do not have an apex variation since it is a pure stub module that does not get installed)
553			apexVariationOfSelected := append(ctx.Target().Variations(), blueprint.Variation{Mutator: "apex", Variation: apex})
554			if ctx.OtherModuleDependencyVariantExists(apexVariationOfSelected, selected) {
555				ctx.AddFarVariationDependencies(apexVariationOfSelected, dexpreoptBootJarDepTag, selected)
556			} else if ctx.OtherModuleDependencyVariantExists(apexVariationOfSelected, android.RemoveOptionalPrebuiltPrefix(selected)) {
557				// The prebuilt might have been renamed by prebuilt_rename mutator if the source module does not exist.
558				// Remove the prebuilt_ prefix.
559				ctx.AddFarVariationDependencies(apexVariationOfSelected, dexpreoptBootJarDepTag, android.RemoveOptionalPrebuiltPrefix(selected))
560			}
561		}
562	}
563}
564
565func gatherBootclasspathFragments(ctx android.ModuleContext) map[string]android.Module {
566	return ctx.Config().Once(dexBootJarsFragmentsKey, func() interface{} {
567		fragments := make(map[string]android.Module)
568		ctx.WalkDeps(func(child, parent android.Module) bool {
569			if !isActiveModule(ctx, child) {
570				return false
571			}
572			tag := ctx.OtherModuleDependencyTag(child)
573			if tag == platformBootclasspathDepTag {
574				return true
575			}
576			if tag == bootclasspathFragmentDepTag {
577				apexInfo, _ := android.OtherModuleProvider(ctx, child, android.ApexInfoProvider)
578				for _, apex := range apexInfo.InApexVariants {
579					fragments[apex] = child
580				}
581				return false
582			}
583			return false
584		})
585		return fragments
586	}).(map[string]android.Module)
587}
588
589func getBootclasspathFragmentByApex(ctx android.ModuleContext, apexName string) android.Module {
590	return gatherBootclasspathFragments(ctx)[apexName]
591}
592
593// GenerateAndroidBuildActions generates the build rules for boot images.
594func (d *dexpreoptBootJars) GenerateAndroidBuildActions(ctx android.ModuleContext) {
595	imageConfigs := genBootImageConfigs(ctx)
596	d.defaultBootImage = defaultBootImageConfig(ctx)
597	d.otherImages = make([]*bootImageConfig, 0, len(imageConfigs)-1)
598	var profileInstalls android.RuleBuilderInstalls
599	for _, name := range getImageNames() {
600		config := imageConfigs[name]
601		if config != d.defaultBootImage {
602			d.otherImages = append(d.otherImages, config)
603		}
604		if !config.isEnabled(ctx) {
605			continue
606		}
607		installs := generateBootImage(ctx, config)
608		profileInstalls = append(profileInstalls, installs...)
609		if config == d.defaultBootImage {
610			_, installs := bootFrameworkProfileRule(ctx, config)
611			profileInstalls = append(profileInstalls, installs...)
612		}
613	}
614	if len(profileInstalls) > 0 {
615		android.SetProvider(ctx, profileInstallInfoProvider, profileInstallInfo{
616			profileInstalls:            profileInstalls,
617			profileLicenseMetadataFile: android.OptionalPathForPath(ctx.LicenseMetadataFile()),
618		})
619		for _, install := range profileInstalls {
620			packageFile(ctx, install)
621		}
622	}
623}
624
625// GenerateSingletonBuildActions generates build rules for the dexpreopt config for Make.
626func (d *dexpreoptBootJars) GenerateSingletonBuildActions(ctx android.SingletonContext) {
627	d.dexpreoptConfigForMake =
628		android.PathForOutput(ctx, dexpreopt.GetDexpreoptDirName(ctx), "dexpreopt.config")
629	writeGlobalConfigForMake(ctx, d.dexpreoptConfigForMake)
630}
631
632// shouldBuildBootImages determines whether boot images should be built.
633func shouldBuildBootImages(config android.Config, global *dexpreopt.GlobalConfig) bool {
634	// Skip recompiling the boot image for the second sanitization phase. We'll get separate paths
635	// and invalidate first-stage artifacts which are crucial to SANITIZE_LITE builds.
636	// Note: this is technically incorrect. Compiled code contains stack checks which may depend
637	//       on ASAN settings.
638	if len(config.SanitizeDevice()) == 1 && config.SanitizeDevice()[0] == "address" && global.SanitizeLite {
639		return false
640	}
641	return true
642}
643
644func generateBootImage(ctx android.ModuleContext, imageConfig *bootImageConfig) android.RuleBuilderInstalls {
645	apexJarModulePairs := getModulesForImage(ctx, imageConfig)
646
647	// Copy module dex jars to their predefined locations.
648	bootDexJarsByModule := extractEncodedDexJarsFromModulesOrBootclasspathFragments(ctx, apexJarModulePairs)
649	copyBootJarsToPredefinedLocations(ctx, bootDexJarsByModule, imageConfig.dexPathsByModule)
650
651	// Build a profile for the image config from the profile at the default path. The profile will
652	// then be used along with profiles imported from APEXes to build the boot image.
653	profile, profileInstalls := bootImageProfileRule(ctx, imageConfig)
654
655	// If dexpreopt of boot image jars should be skipped, stop after generating a profile.
656	global := dexpreopt.GetGlobalConfig(ctx)
657	if SkipDexpreoptBootJars(ctx) || (global.OnlyPreoptArtBootImage && imageConfig.name != "art") {
658		return profileInstalls
659	}
660
661	// Build boot image files for the android variants.
662	androidBootImageFiles := buildBootImageVariantsForAndroidOs(ctx, imageConfig, profile)
663
664	// Zip the android variant boot image files up.
665	buildBootImageZipInPredefinedLocation(ctx, imageConfig, androidBootImageFiles.byArch)
666
667	// Build boot image files for the host variants. There are use directly by ART host side tests.
668	buildBootImageVariantsForBuildOs(ctx, imageConfig, profile)
669
670	// Create a `dump-oat-<image-name>` rule that runs `oatdump` for debugging purposes.
671	dumpOatRules(ctx, imageConfig)
672
673	return profileInstalls
674}
675
676type apexJarModulePair struct {
677	apex      string
678	jarModule android.Module
679}
680
681func getModulesForImage(ctx android.ModuleContext, imageConfig *bootImageConfig) []apexJarModulePair {
682	modules := make([]apexJarModulePair, 0, imageConfig.modules.Len())
683	for i := 0; i < imageConfig.modules.Len(); i++ {
684		found := false
685		for _, module := range gatherApexModulePairDepsWithTag(ctx, dexpreoptBootJarDepTag) {
686			name := android.RemoveOptionalPrebuiltPrefix(module.Name())
687			if name == imageConfig.modules.Jar(i) {
688				modules = append(modules, apexJarModulePair{
689					apex:      imageConfig.modules.Apex(i),
690					jarModule: module,
691				})
692				found = true
693				break
694			}
695		}
696		if !found && !ctx.Config().AllowMissingDependencies() {
697			ctx.ModuleErrorf(
698				"Boot image '%s' module '%s' not added as a dependency of dex_bootjars",
699				imageConfig.name,
700				imageConfig.modules.Jar(i))
701			return []apexJarModulePair{}
702		}
703	}
704	return modules
705}
706
707// extractEncodedDexJarsFromModulesOrBootclasspathFragments gets the hidden API encoded dex jars for
708// the given modules.
709func extractEncodedDexJarsFromModulesOrBootclasspathFragments(ctx android.ModuleContext, apexJarModulePairs []apexJarModulePair) bootDexJarByModule {
710	apexNameToApexExportInfoMap := getApexNameToApexExportsInfoMap(ctx)
711	encodedDexJarsByModuleName := bootDexJarByModule{}
712	for _, pair := range apexJarModulePairs {
713		dexJarPath := getDexJarForApex(ctx, pair, apexNameToApexExportInfoMap)
714		encodedDexJarsByModuleName.addPath(pair.jarModule, dexJarPath)
715	}
716	return encodedDexJarsByModuleName
717}
718
719type apexNameToApexExportsInfoMap map[string]android.ApexExportsInfo
720
721// javaLibraryPathOnHost returns the path to the java library which is exported by the apex for hiddenapi and dexpreopt and a boolean indicating whether the java library exists
722// For prebuilt apexes, this is created by deapexing the prebuilt apex
723func (m *apexNameToApexExportsInfoMap) javaLibraryDexPathOnHost(ctx android.ModuleContext, apex string, javalib string) (android.Path, bool) {
724	if info, exists := (*m)[apex]; exists {
725		if dex, exists := info.LibraryNameToDexJarPathOnHost[javalib]; exists {
726			return dex, true
727		} else {
728			ctx.ModuleErrorf("Apex %s does not provide a dex boot jar for library %s\n", apex, javalib)
729		}
730	}
731	// An apex entry could not be found. Return false.
732	// TODO: b/308174306 - When all the mainline modules have been flagged, make this a hard error
733	return nil, false
734}
735
736// Returns the stem of an artifact inside a prebuilt apex
737func ModuleStemForDeapexing(m android.Module) string {
738	bmn, _ := m.(interface{ BaseModuleName() string })
739	return bmn.BaseModuleName()
740}
741
742// Returns the java libraries exported by the apex for hiddenapi and dexpreopt
743// This information can come from two mechanisms
744// 1. New: Direct deps to _selected_ apexes. The apexes return a ApexExportsInfo
745// 2. Legacy: An edge to java_library or java_import (java_sdk_library) module. For prebuilt apexes, this serves as a hook and is populated by deapexers of prebuilt apxes
746// TODO: b/308174306 - Once all mainline modules have been flagged, drop (2)
747func getDexJarForApex(ctx android.ModuleContext, pair apexJarModulePair, apexNameToApexExportsInfoMap apexNameToApexExportsInfoMap) android.Path {
748	if dex, found := apexNameToApexExportsInfoMap.javaLibraryDexPathOnHost(ctx, pair.apex, ModuleStemForDeapexing(pair.jarModule)); found {
749		return dex
750	}
751	// TODO: b/308174306 - Remove the legacy mechanism
752	if android.IsConfiguredJarForPlatform(pair.apex) || android.IsModulePrebuilt(pair.jarModule) {
753		// This gives us the dex jar with the hidden API flags encoded from the monolithic hidden API
754		// files or the dex jar extracted from a prebuilt APEX. We can't use this for a boot jar for
755		// a source APEX because there is no guarantee that it is the same as the jar packed into the
756		// APEX. In practice, they are the same when we are building from a full source tree, but they
757		// are different when we are building from a thin manifest (e.g., master-art), where there is
758		// no monolithic hidden API files at all.
759		return retrieveEncodedBootDexJarFromModule(ctx, pair.jarModule)
760	} else {
761		// Use exactly the same jar that is packed into the APEX.
762		fragment := getBootclasspathFragmentByApex(ctx, pair.apex)
763		if fragment == nil {
764			ctx.ModuleErrorf("Boot jar '%[1]s' is from APEX '%[2]s', but a bootclasspath_fragment for "+
765				"APEX '%[2]s' doesn't exist or is not added as a dependency of dex_bootjars",
766				pair.jarModule.Name(),
767				pair.apex)
768		}
769		bootclasspathFragmentInfo, _ := android.OtherModuleProvider(ctx, fragment, BootclasspathFragmentApexContentInfoProvider)
770		jar, err := bootclasspathFragmentInfo.DexBootJarPathForContentModule(pair.jarModule)
771		if err != nil {
772			ctx.ModuleErrorf("%s", err)
773		}
774		return jar
775	}
776	return nil
777}
778
779// copyBootJarsToPredefinedLocations generates commands that will copy boot jars to predefined
780// paths in the global config.
781func copyBootJarsToPredefinedLocations(ctx android.ModuleContext, srcBootDexJarsByModule bootDexJarByModule, dstBootJarsByModule map[string]android.WritablePath) {
782	// Create the super set of module names.
783	names := []string{}
784	names = append(names, android.SortedKeys(srcBootDexJarsByModule)...)
785	names = append(names, android.SortedKeys(dstBootJarsByModule)...)
786	names = android.SortedUniqueStrings(names)
787	for _, name := range names {
788		src := srcBootDexJarsByModule[name]
789		dst := dstBootJarsByModule[name]
790
791		if src == nil {
792			// A dex boot jar should be provided by the source java module. It needs to be installable or
793			// have compile_dex=true - cf. assignments to java.Module.dexJarFile.
794			//
795			// However, the source java module may be either replaced or overridden (using prefer:true) by
796			// a prebuilt java module with the same name. In that case the dex boot jar needs to be
797			// provided by the corresponding prebuilt APEX module. That APEX is the one that refers
798			// through a exported_(boot|systemserver)classpath_fragments property to a
799			// prebuilt_(boot|systemserver)classpath_fragment module, which in turn lists the prebuilt
800			// java module in the contents property. If that chain is broken then this dependency will
801			// fail.
802			if !ctx.Config().AllowMissingDependencies() {
803				ctx.ModuleErrorf("module %s does not provide a dex boot jar (see comment next to this message in Soong for details)", name)
804			} else {
805				ctx.AddMissingDependencies([]string{name})
806			}
807		} else if dst == nil {
808			ctx.ModuleErrorf("module %s is not part of the boot configuration", name)
809		} else {
810			ctx.Build(pctx, android.BuildParams{
811				Rule:   android.Cp,
812				Input:  src,
813				Output: dst,
814			})
815		}
816	}
817}
818
819// buildBootImageVariantsForAndroidOs generates rules to build the boot image variants for the
820// android.Android OsType and returns a map from the architectures to the paths of the generated
821// boot image files.
822//
823// The paths are returned because they are needed elsewhere in Soong, e.g. for populating an APEX.
824func buildBootImageVariantsForAndroidOs(ctx android.ModuleContext, image *bootImageConfig, profile android.WritablePath) bootImageOutputs {
825	return buildBootImageForOsType(ctx, image, profile, android.Android)
826}
827
828// buildBootImageVariantsForBuildOs generates rules to build the boot image variants for the
829// config.BuildOS OsType, i.e. the type of OS on which the build is being running.
830//
831// The files need to be generated into their predefined location because they are used from there
832// both within Soong and outside, e.g. for ART based host side testing and also for use by some
833// cloud based tools. However, they are not needed by callers of this function and so the paths do
834// not need to be returned from this func, unlike the buildBootImageVariantsForAndroidOs func.
835func buildBootImageVariantsForBuildOs(ctx android.ModuleContext, image *bootImageConfig, profile android.WritablePath) {
836	buildBootImageForOsType(ctx, image, profile, ctx.Config().BuildOS)
837}
838
839// bootImageFilesByArch is a map from android.ArchType to the paths to the boot image files.
840//
841// The paths include the .art, .oat and .vdex files, one for each of the modules from which the boot
842// image is created.
843type bootImageFilesByArch map[android.ArchType]android.Paths
844
845// bootImageOutputs encapsulates information about boot images that were created/obtained by
846// commonBootclasspathFragment.produceBootImageFiles.
847type bootImageOutputs struct {
848	// Map from arch to the paths to the boot image files created/obtained for that arch.
849	byArch bootImageFilesByArch
850
851	variants []bootImageVariantOutputs
852
853	// The path to the profile file created/obtained for the boot image.
854	profile android.WritablePath
855}
856
857// buildBootImageForOsType takes a bootImageConfig, a profile file and an android.OsType
858// boot image files are required for and it creates rules to build the boot image
859// files for all the required architectures for them.
860//
861// It returns a map from android.ArchType to the predefined paths of the boot image files.
862func buildBootImageForOsType(ctx android.ModuleContext, image *bootImageConfig, profile android.WritablePath, requiredOsType android.OsType) bootImageOutputs {
863	filesByArch := bootImageFilesByArch{}
864	imageOutputs := bootImageOutputs{
865		byArch:  filesByArch,
866		profile: profile,
867	}
868	for _, variant := range image.variants {
869		if variant.target.Os == requiredOsType {
870			variantOutputs := buildBootImageVariant(ctx, variant, profile)
871			imageOutputs.variants = append(imageOutputs.variants, variantOutputs)
872			filesByArch[variant.target.Arch.ArchType] = variant.imagesDeps.Paths()
873		}
874	}
875
876	return imageOutputs
877}
878
879// buildBootImageZipInPredefinedLocation generates a zip file containing all the boot image files.
880//
881// The supplied filesByArch is nil when the boot image files have not been generated. Otherwise, it
882// is a map from android.ArchType to the predefined locations.
883func buildBootImageZipInPredefinedLocation(ctx android.ModuleContext, image *bootImageConfig, filesByArch bootImageFilesByArch) {
884	if filesByArch == nil {
885		return
886	}
887
888	// Compute the list of files from all the architectures.
889	zipFiles := android.Paths{}
890	for _, archType := range android.ArchTypeList() {
891		zipFiles = append(zipFiles, filesByArch[archType]...)
892	}
893
894	rule := android.NewRuleBuilder(pctx, ctx)
895	rule.Command().
896		BuiltTool("soong_zip").
897		FlagWithOutput("-o ", image.zip).
898		FlagWithArg("-C ", image.dir.Join(ctx, android.Android.String()).String()).
899		FlagWithInputList("-f ", zipFiles, " -f ")
900
901	rule.Build("zip_"+image.name, "zip "+image.name+" image")
902}
903
904type bootImageVariantOutputs struct {
905	config *bootImageVariant
906}
907
908// Returns the profile file for an apex
909// This information can come from two mechanisms
910// 1. New: Direct deps to _selected_ apexes. The apexes return a BootclasspathFragmentApexContentInfo
911// 2. Legacy: An edge to bootclasspath_fragment module. For prebuilt apexes, this serves as a hook and is populated by deapexers of prebuilt apxes
912// TODO: b/308174306 - Once all mainline modules have been flagged, drop (2)
913func getProfilePathForApex(ctx android.ModuleContext, apexName string, apexNameToBcpInfoMap map[string]android.ApexExportsInfo) android.Path {
914	if info, exists := apexNameToBcpInfoMap[apexName]; exists {
915		return info.ProfilePathOnHost
916	}
917	// TODO: b/308174306 - Remove the legacy mechanism
918	fragment := getBootclasspathFragmentByApex(ctx, apexName)
919	if fragment == nil {
920		ctx.ModuleErrorf("Boot image config imports profile from '%[2]s', but a "+
921			"bootclasspath_fragment for APEX '%[2]s' doesn't exist or is not added as a "+
922			"dependency of dex_bootjars",
923			apexName)
924		return nil
925	}
926	return fragment.(commonBootclasspathFragment).getProfilePath()
927}
928
929func getApexNameToApexExportsInfoMap(ctx android.ModuleContext) apexNameToApexExportsInfoMap {
930	apexNameToApexExportsInfoMap := apexNameToApexExportsInfoMap{}
931	ctx.VisitDirectDepsWithTag(dexpreoptBootJarDepTag, func(am android.Module) {
932		if info, exists := android.OtherModuleProvider(ctx, am, android.ApexExportsInfoProvider); exists {
933			apexNameToApexExportsInfoMap[info.ApexName] = info
934		}
935	})
936	return apexNameToApexExportsInfoMap
937}
938
939func packageFileForTargetImage(ctx android.ModuleContext, image *bootImageVariant) {
940	if image.target.Os != ctx.Os() {
941		// This is not for the target device.
942		return
943	}
944
945	for _, install := range image.installs {
946		packageFile(ctx, install)
947	}
948
949	for _, install := range image.vdexInstalls {
950		if image.target.Arch.ArchType.Name != ctx.DeviceConfig().DeviceArch() {
951			// Note that the vdex files are identical between architectures. If the target image is
952			// not for the primary architecture create symlinks to share the vdex of the primary
953			// architecture with the other architectures.
954			//
955			// Assuming that the install path has the architecture name with it, replace the
956			// architecture name with the primary architecture name to find the source vdex file.
957			installPath, relDir, name := getModuleInstallPathInfo(ctx, install.To)
958			if name != "" {
959				srcRelDir := strings.Replace(relDir, image.target.Arch.ArchType.Name, ctx.DeviceConfig().DeviceArch(), 1)
960				ctx.InstallSymlink(installPath.Join(ctx, relDir), name, installPath.Join(ctx, srcRelDir, name))
961			}
962		} else {
963			packageFile(ctx, install)
964		}
965	}
966}
967
968// Generate boot image build rules for a specific target.
969func buildBootImageVariant(ctx android.ModuleContext, image *bootImageVariant, profile android.Path) bootImageVariantOutputs {
970
971	globalSoong := dexpreopt.GetGlobalSoongConfig(ctx)
972	global := dexpreopt.GetGlobalConfig(ctx)
973
974	arch := image.target.Arch.ArchType
975	os := image.target.Os.String() // We need to distinguish host-x86 and device-x86.
976	symbolsDir := image.symbolsDir.Join(ctx, os, image.installDir, arch.String())
977	symbolsFile := symbolsDir.Join(ctx, image.stem+".oat")
978	outputDir := image.dir.Join(ctx, os, image.installDir, arch.String())
979	outputPath := outputDir.Join(ctx, image.stem+".oat")
980	oatLocation := dexpreopt.PathToLocation(outputPath, arch)
981	imagePath := outputPath.ReplaceExtension(ctx, "art")
982
983	rule := android.NewRuleBuilder(pctx, ctx)
984
985	rule.Command().Text("mkdir").Flag("-p").Flag(symbolsDir.String())
986	rule.Command().Text("rm").Flag("-f").
987		Flag(symbolsDir.Join(ctx, "*.art").String()).
988		Flag(symbolsDir.Join(ctx, "*.oat").String()).
989		Flag(symbolsDir.Join(ctx, "*.vdex").String()).
990		Flag(symbolsDir.Join(ctx, "*.invocation").String())
991	rule.Command().Text("rm").Flag("-f").
992		Flag(outputDir.Join(ctx, "*.art").String()).
993		Flag(outputDir.Join(ctx, "*.oat").String()).
994		Flag(outputDir.Join(ctx, "*.vdex").String()).
995		Flag(outputDir.Join(ctx, "*.invocation").String())
996
997	cmd := rule.Command()
998
999	extraFlags := ctx.Config().Getenv("ART_BOOT_IMAGE_EXTRA_ARGS")
1000	if extraFlags == "" {
1001		// Use ANDROID_LOG_TAGS to suppress most logging by default...
1002		cmd.Text(`ANDROID_LOG_TAGS="*:e"`)
1003	} else {
1004		// ...unless the boot image is generated specifically for testing, then allow all logging.
1005		cmd.Text(`ANDROID_LOG_TAGS="*:v"`)
1006	}
1007
1008	invocationPath := outputPath.ReplaceExtension(ctx, "invocation")
1009
1010	apexNameToApexExportsInfoMap := getApexNameToApexExportsInfoMap(ctx)
1011
1012	cmd.Tool(globalSoong.Dex2oat).
1013		Flag("--avoid-storing-invocation").
1014		FlagWithOutput("--write-invocation-to=", invocationPath).ImplicitOutput(invocationPath).
1015		Flag("--runtime-arg").FlagWithArg("-Xms", global.Dex2oatImageXms).
1016		Flag("--runtime-arg").FlagWithArg("-Xmx", global.Dex2oatImageXmx)
1017
1018	if image.isProfileGuided() && !global.DisableGenerateProfile {
1019		if profile != nil {
1020			cmd.FlagWithInput("--profile-file=", profile)
1021		}
1022
1023		for _, apex := range image.profileImports {
1024			importedProfile := getProfilePathForApex(ctx, apex, apexNameToApexExportsInfoMap)
1025			if importedProfile == nil {
1026				ctx.ModuleErrorf("Boot image config '%[1]s' imports profile from '%[2]s', but '%[2]s' "+
1027					"doesn't provide a profile",
1028					image.name,
1029					apex)
1030				return bootImageVariantOutputs{}
1031			}
1032			cmd.FlagWithInput("--profile-file=", importedProfile)
1033		}
1034	}
1035
1036	dirtyImageFile := "frameworks/base/config/dirty-image-objects"
1037	dirtyImagePath := android.ExistentPathForSource(ctx, dirtyImageFile)
1038	if dirtyImagePath.Valid() {
1039		cmd.FlagWithInput("--dirty-image-objects=", dirtyImagePath.Path())
1040	}
1041
1042	if image.extends != nil {
1043		// It is a boot image extension, so it needs the boot images that it depends on.
1044		baseImageLocations := make([]string, 0, len(image.baseImages))
1045		for _, image := range image.baseImages {
1046			baseImageLocations = append(baseImageLocations, dexpreopt.PathToLocation(image, arch))
1047		}
1048		cmd.
1049			Flag("--runtime-arg").FlagWithInputList("-Xbootclasspath:", image.dexPathsDeps.Paths(), ":").
1050			Flag("--runtime-arg").FlagWithList("-Xbootclasspath-locations:", image.dexLocationsDeps, ":").
1051			// Add the path to the first file in the boot image with the arch specific directory removed,
1052			// dex2oat will reconstruct the path to the actual file when it needs it. As the actual path
1053			// to the file cannot be passed to the command make sure to add the actual path as an Implicit
1054			// dependency to ensure that it is built before the command runs.
1055			FlagWithList("--boot-image=", baseImageLocations, ":").Implicits(image.baseImages.Paths()).
1056			// Similarly, the dex2oat tool will automatically find the paths to other files in the base
1057			// boot image so make sure to add them as implicit dependencies to ensure that they are built
1058			// before this command is run.
1059			Implicits(image.baseImagesDeps)
1060	} else {
1061		// It is a primary image, so it needs a base address.
1062		cmd.FlagWithArg("--base=", ctx.Config().LibartImgDeviceBaseAddress())
1063	}
1064
1065	if len(image.preloadedClassesFile) > 0 {
1066		// We always expect a preloaded classes file to be available. However, if we cannot find it, it's
1067		// OK to not pass the flag to dex2oat.
1068		preloadedClassesPath := android.ExistentPathForSource(ctx, image.preloadedClassesFile)
1069		if preloadedClassesPath.Valid() {
1070			cmd.FlagWithInput("--preloaded-classes=", preloadedClassesPath.Path())
1071		}
1072	}
1073
1074	cmd.
1075		FlagForEachInput("--dex-file=", image.dexPaths.Paths()).
1076		FlagForEachArg("--dex-location=", image.dexLocations).
1077		Flag("--generate-debug-info").
1078		Flag("--generate-build-id").
1079		Flag("--image-format=lz4hc").
1080		FlagWithArg("--oat-symbols=", symbolsFile.String()).
1081		FlagWithArg("--oat-file=", outputPath.String()).
1082		FlagWithArg("--oat-location=", oatLocation).
1083		FlagWithArg("--image=", imagePath.String()).
1084		FlagWithArg("--instruction-set=", arch.String()).
1085		FlagWithArg("--android-root=", global.EmptyDirectory).
1086		FlagWithArg("--no-inline-from=", "core-oj.jar").
1087		Flag("--force-determinism").
1088		Flag("--abort-on-hard-verifier-error")
1089
1090	// We don't strip on host to make perf tools work.
1091	if image.target.Os == android.Android {
1092		cmd.Flag("--strip")
1093	}
1094
1095	// If the image is profile-guided but the profile is disabled, we omit "--compiler-filter" to
1096	// leave the decision to dex2oat to pick the compiler filter.
1097	if !(image.isProfileGuided() && global.DisableGenerateProfile) {
1098		cmd.FlagWithArg("--compiler-filter=", image.compilerFilter)
1099	}
1100
1101	if image.singleImage {
1102		cmd.Flag("--single-image")
1103	}
1104
1105	// Use the default variant/features for host builds.
1106	// The map below contains only device CPU info (which might be x86 on some devices).
1107	if image.target.Os == android.Android {
1108		cmd.FlagWithArg("--instruction-set-variant=", global.CpuVariant[arch])
1109		cmd.FlagWithArg("--instruction-set-features=", global.InstructionSetFeatures[arch])
1110	}
1111
1112	if image.target.Os == android.Android {
1113		cmd.Text("$(cat").Input(globalSoong.UffdGcFlag).Text(")")
1114	}
1115
1116	if global.BootFlags != "" {
1117		cmd.Flag(global.BootFlags)
1118	}
1119
1120	if extraFlags != "" {
1121		cmd.Flag(extraFlags)
1122	}
1123
1124	cmd.Textf(`|| ( echo %s ; false )`, proptools.ShellEscape(failureMessage))
1125
1126	installDir := filepath.Dir(image.imagePathOnDevice)
1127
1128	var vdexInstalls android.RuleBuilderInstalls
1129	var unstrippedInstalls android.RuleBuilderInstalls
1130
1131	for _, artOrOat := range image.moduleFiles(ctx, outputDir, ".art", ".oat") {
1132		cmd.ImplicitOutput(artOrOat)
1133
1134		// Install the .oat and .art files
1135		rule.Install(artOrOat, filepath.Join(installDir, artOrOat.Base()))
1136	}
1137
1138	for _, vdex := range image.moduleFiles(ctx, outputDir, ".vdex") {
1139		cmd.ImplicitOutput(vdex)
1140
1141		// Note that the vdex files are identical between architectures.
1142		// Make rules will create symlinks to share them between architectures.
1143		vdexInstalls = append(vdexInstalls,
1144			android.RuleBuilderInstall{vdex, filepath.Join(installDir, vdex.Base())})
1145	}
1146
1147	for _, unstrippedOat := range image.moduleFiles(ctx, symbolsDir, ".oat") {
1148		cmd.ImplicitOutput(unstrippedOat)
1149
1150		// Install the unstripped oat files.  The Make rules will put these in $(TARGET_OUT_UNSTRIPPED)
1151		unstrippedInstalls = append(unstrippedInstalls,
1152			android.RuleBuilderInstall{unstrippedOat, filepath.Join(installDir, unstrippedOat.Base())})
1153	}
1154
1155	rule.Build(image.name+"JarsDexpreopt_"+image.target.String(), "dexpreopt "+image.name+" jars "+arch.String())
1156
1157	// save output and installed files for makevars
1158	// TODO - these are always the same and so should be initialized in genBootImageConfigs
1159	image.installs = rule.Installs()
1160	image.vdexInstalls = vdexInstalls
1161	image.unstrippedInstalls = unstrippedInstalls
1162	packageFileForTargetImage(ctx, image)
1163
1164	// Only set the licenseMetadataFile from the active module.
1165	if isActiveModule(ctx, ctx.Module()) {
1166		image.licenseMetadataFile = android.OptionalPathForPath(ctx.LicenseMetadataFile())
1167	}
1168
1169	return bootImageVariantOutputs{
1170		image,
1171	}
1172}
1173
1174const failureMessage = `ERROR: Dex2oat failed to compile a boot image.
1175It is likely that the boot classpath is inconsistent.
1176Rebuild with ART_BOOT_IMAGE_EXTRA_ARGS="--runtime-arg -verbose:verifier" to see verification errors.`
1177
1178func bootImageProfileRuleCommon(ctx android.ModuleContext, name string, dexFiles android.Paths, dexLocations []string) android.WritablePath {
1179	globalSoong := dexpreopt.GetGlobalSoongConfig(ctx)
1180	global := dexpreopt.GetGlobalConfig(ctx)
1181
1182	if global.DisableGenerateProfile {
1183		return nil
1184	}
1185
1186	defaultProfile := "frameworks/base/config/boot-image-profile.txt"
1187	extraProfile := "frameworks/base/config/boot-image-profile-extra.txt"
1188
1189	rule := android.NewRuleBuilder(pctx, ctx)
1190
1191	var profiles android.Paths
1192	if len(global.BootImageProfiles) > 0 {
1193		profiles = append(profiles, global.BootImageProfiles...)
1194	} else if path := android.ExistentPathForSource(ctx, defaultProfile); path.Valid() {
1195		profiles = append(profiles, path.Path())
1196	} else {
1197		// No profile (not even a default one, which is the case on some branches
1198		// like master-art-host that don't have frameworks/base).
1199		// Return nil and continue without profile.
1200		return nil
1201	}
1202	if path := android.ExistentPathForSource(ctx, extraProfile); path.Valid() {
1203		profiles = append(profiles, path.Path())
1204	}
1205	bootImageProfile := android.PathForModuleOut(ctx, name, "boot-image-profile.txt")
1206	rule.Command().Text("cat").Inputs(profiles).Text(">").Output(bootImageProfile)
1207
1208	profile := android.PathForModuleOut(ctx, name, "boot.prof")
1209
1210	rule.Command().
1211		Text(`ANDROID_LOG_TAGS="*:e"`).
1212		Tool(globalSoong.Profman).
1213		Flag("--output-profile-type=boot").
1214		FlagWithInput("--create-profile-from=", bootImageProfile).
1215		FlagForEachInput("--apk=", dexFiles).
1216		FlagForEachArg("--dex-location=", dexLocations).
1217		FlagWithOutput("--reference-profile-file=", profile)
1218
1219	rule.Build("bootJarsProfile_"+name, "profile boot jars "+name)
1220
1221	return profile
1222}
1223
1224type profileInstallInfo struct {
1225	// Rules which should be used in make to install the outputs.
1226	profileInstalls android.RuleBuilderInstalls
1227
1228	// Path to the license metadata file for the module that built the profile.
1229	profileLicenseMetadataFile android.OptionalPath
1230}
1231
1232var profileInstallInfoProvider = blueprint.NewProvider[profileInstallInfo]()
1233
1234func bootImageProfileRule(ctx android.ModuleContext, image *bootImageConfig) (android.WritablePath, android.RuleBuilderInstalls) {
1235	if !image.isProfileGuided() {
1236		return nil, nil
1237	}
1238
1239	profile := bootImageProfileRuleCommon(ctx, image.name, image.dexPathsDeps.Paths(), image.getAnyAndroidVariant().dexLocationsDeps)
1240
1241	if image == defaultBootImageConfig(ctx) {
1242		rule := android.NewRuleBuilder(pctx, ctx)
1243		rule.Install(profile, "/system/etc/boot-image.prof")
1244		return profile, rule.Installs()
1245	}
1246	return profile, nil
1247}
1248
1249// bootFrameworkProfileRule generates the rule to create the boot framework profile and
1250// returns a path to the generated file.
1251func bootFrameworkProfileRule(ctx android.ModuleContext, image *bootImageConfig) (android.WritablePath, android.RuleBuilderInstalls) {
1252	globalSoong := dexpreopt.GetGlobalSoongConfig(ctx)
1253	global := dexpreopt.GetGlobalConfig(ctx)
1254
1255	if global.DisableGenerateProfile || ctx.Config().UnbundledBuild() {
1256		return nil, nil
1257	}
1258
1259	defaultProfile := "frameworks/base/config/boot-profile.txt"
1260	bootFrameworkProfile := android.PathForSource(ctx, defaultProfile)
1261
1262	profile := image.dir.Join(ctx, "boot.bprof")
1263
1264	rule := android.NewRuleBuilder(pctx, ctx)
1265	rule.Command().
1266		Text(`ANDROID_LOG_TAGS="*:e"`).
1267		Tool(globalSoong.Profman).
1268		Flag("--output-profile-type=bprof").
1269		FlagWithInput("--create-profile-from=", bootFrameworkProfile).
1270		FlagForEachInput("--apk=", image.dexPathsDeps.Paths()).
1271		FlagForEachArg("--dex-location=", image.getAnyAndroidVariant().dexLocationsDeps).
1272		FlagWithOutput("--reference-profile-file=", profile)
1273
1274	rule.Install(profile, "/system/etc/boot-image.bprof")
1275	rule.Build("bootFrameworkProfile", "profile boot framework jars")
1276	return profile, rule.Installs()
1277}
1278
1279func dumpOatRules(ctx android.ModuleContext, image *bootImageConfig) {
1280	var allPhonies android.Paths
1281	name := image.name
1282	globalSoong := dexpreopt.GetGlobalSoongConfig(ctx)
1283	for _, image := range image.variants {
1284		arch := image.target.Arch.ArchType
1285		suffix := arch.String()
1286		// Host and target might both use x86 arch. We need to ensure the names are unique.
1287		if image.target.Os.Class == android.Host {
1288			suffix = "host-" + suffix
1289		}
1290		// Create a rule to call oatdump.
1291		output := android.PathForOutput(ctx, name+"."+suffix+".oatdump.txt")
1292		rule := android.NewRuleBuilder(pctx, ctx)
1293		imageLocationsOnHost, _ := image.imageLocations()
1294
1295		cmd := rule.Command().
1296			BuiltTool("oatdump").
1297			FlagWithInputList("--runtime-arg -Xbootclasspath:", image.dexPathsDeps.Paths(), ":").
1298			FlagWithList("--runtime-arg -Xbootclasspath-locations:", image.dexLocationsDeps, ":").
1299			FlagWithArg("--image=", strings.Join(imageLocationsOnHost, ":")).Implicits(image.imagesDeps.Paths()).
1300			FlagWithOutput("--output=", output).
1301			FlagWithArg("--instruction-set=", arch.String())
1302		if image.target.Os == android.Android {
1303			cmd.Text("$(cat").Input(globalSoong.UffdGcFlag).Text(")")
1304		}
1305		rule.Build("dump-oat-"+name+"-"+suffix, "dump oat "+name+" "+arch.String())
1306
1307		// Create a phony rule that depends on the output file and prints the path.
1308		phony := android.PathForPhony(ctx, "dump-oat-"+name+"-"+suffix)
1309		rule = android.NewRuleBuilder(pctx, ctx)
1310		rule.Command().
1311			Implicit(output).
1312			ImplicitOutput(phony).
1313			Text("echo").FlagWithArg("Output in ", output.String())
1314		rule.Build("phony-dump-oat-"+name+"-"+suffix, "dump oat "+name+" "+arch.String())
1315
1316		allPhonies = append(allPhonies, phony)
1317	}
1318
1319	phony := android.PathForPhony(ctx, "dump-oat-"+name)
1320	ctx.Build(pctx, android.BuildParams{
1321		Rule:        android.Phony,
1322		Output:      phony,
1323		Inputs:      allPhonies,
1324		Description: "dump-oat-" + name,
1325	})
1326}
1327
1328func writeGlobalConfigForMake(ctx android.SingletonContext, path android.WritablePath) {
1329	data := dexpreopt.GetGlobalConfigRawData(ctx)
1330
1331	android.WriteFileRule(ctx, path, string(data))
1332}
1333
1334// Define Make variables for boot image names, paths, etc. These variables are used in makefiles
1335// (make/core/dex_preopt_libart.mk) to generate install rules that copy boot image files to the
1336// correct output directories.
1337func (d *dexpreoptBootJars) MakeVars(ctx android.MakeVarsContext) {
1338	if d.dexpreoptConfigForMake != nil && !SkipDexpreoptBootJars(ctx) {
1339		ctx.Strict("DEX_PREOPT_CONFIG_FOR_MAKE", d.dexpreoptConfigForMake.String())
1340		ctx.Strict("DEX_PREOPT_SOONG_CONFIG_FOR_MAKE", android.PathForOutput(ctx, "dexpreopt_soong.config").String())
1341	}
1342
1343	image := d.defaultBootImage
1344	if image != nil {
1345		if profileInstallInfo, ok := android.SingletonModuleProvider(ctx, d, profileInstallInfoProvider); ok {
1346			ctx.Strict("DEXPREOPT_IMAGE_PROFILE_BUILT_INSTALLED", profileInstallInfo.profileInstalls.String())
1347			if profileInstallInfo.profileLicenseMetadataFile.Valid() {
1348				ctx.Strict("DEXPREOPT_IMAGE_PROFILE_LICENSE_METADATA", profileInstallInfo.profileLicenseMetadataFile.String())
1349			}
1350		}
1351
1352		if SkipDexpreoptBootJars(ctx) {
1353			return
1354		}
1355
1356		global := dexpreopt.GetGlobalConfig(ctx)
1357		dexPaths, dexLocations := bcpForDexpreopt(ctx, global.PreoptWithUpdatableBcp)
1358		ctx.Strict("DEXPREOPT_BOOTCLASSPATH_DEX_FILES", strings.Join(dexPaths.Strings(), " "))
1359		ctx.Strict("DEXPREOPT_BOOTCLASSPATH_DEX_LOCATIONS", strings.Join(dexLocations, " "))
1360
1361		// The primary ART boot image is exposed to Make for testing (gtests) and benchmarking
1362		// (golem) purposes.
1363		for _, current := range append(d.otherImages, image) {
1364			for _, variant := range current.variants {
1365				suffix := ""
1366				if variant.target.Os.Class == android.Host {
1367					suffix = "_host"
1368				}
1369				sfx := variant.name + suffix + "_" + variant.target.Arch.ArchType.String()
1370				ctx.Strict("DEXPREOPT_IMAGE_VDEX_BUILT_INSTALLED_"+sfx, variant.vdexInstalls.String())
1371				ctx.Strict("DEXPREOPT_IMAGE_"+sfx, variant.imagePathOnHost.String())
1372				ctx.Strict("DEXPREOPT_IMAGE_DEPS_"+sfx, strings.Join(variant.imagesDeps.Strings(), " "))
1373				ctx.Strict("DEXPREOPT_IMAGE_BUILT_INSTALLED_"+sfx, variant.installs.String())
1374				ctx.Strict("DEXPREOPT_IMAGE_UNSTRIPPED_BUILT_INSTALLED_"+sfx, variant.unstrippedInstalls.String())
1375				if variant.licenseMetadataFile.Valid() {
1376					ctx.Strict("DEXPREOPT_IMAGE_LICENSE_METADATA_"+sfx, variant.licenseMetadataFile.String())
1377				}
1378			}
1379			imageLocationsOnHost, imageLocationsOnDevice := current.getAnyAndroidVariant().imageLocations()
1380			ctx.Strict("DEXPREOPT_IMAGE_LOCATIONS_ON_HOST"+current.name, strings.Join(imageLocationsOnHost, ":"))
1381			ctx.Strict("DEXPREOPT_IMAGE_LOCATIONS_ON_DEVICE"+current.name, strings.Join(imageLocationsOnDevice, ":"))
1382			ctx.Strict("DEXPREOPT_IMAGE_ZIP_"+current.name, current.zip.String())
1383		}
1384		ctx.Strict("DEXPREOPT_IMAGE_NAMES", strings.Join(getImageNames(), " "))
1385	}
1386}
1387