• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright (C) 2019 The Android Open Source Project
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 apex
16
17import (
18	"fmt"
19	"slices"
20	"sort"
21	"strconv"
22	"strings"
23
24	"android/soong/android"
25	"android/soong/dexpreopt"
26	"android/soong/filesystem"
27	"android/soong/java"
28	"android/soong/provenance"
29
30	"github.com/google/blueprint"
31	"github.com/google/blueprint/proptools"
32)
33
34var (
35	extractMatchingApex = pctx.StaticRule(
36		"extractMatchingApex",
37		blueprint.RuleParams{
38			Command: `rm -rf "$out" && ` +
39				`${extract_apks} -o "${out}" -allow-prereleased=${allow-prereleased} ` +
40				`-sdk-version=${sdk-version} -skip-sdk-check=${skip-sdk-check} -abis=${abis} ` +
41				`-screen-densities=all -extract-single ` +
42				`${in}`,
43			CommandDeps: []string{"${extract_apks}"},
44		},
45		"abis", "allow-prereleased", "sdk-version", "skip-sdk-check")
46	decompressApex = pctx.StaticRule("decompressApex", blueprint.RuleParams{
47		Command:     `rm -rf $out && ${deapexer} decompress --copy-if-uncompressed --input ${in} --output ${out}`,
48		CommandDeps: []string{"${deapexer}"},
49		Description: "decompress $out",
50	})
51)
52
53type prebuilt interface {
54	isForceDisabled() bool
55	InstallFilename() string
56}
57
58type prebuiltCommon struct {
59	android.ModuleBase
60	java.Dexpreopter
61	prebuilt android.Prebuilt
62
63	// Properties common to both prebuilt_apex and apex_set.
64	prebuiltCommonProperties *PrebuiltCommonProperties
65
66	installDir          android.InstallPath
67	installFilename     string
68	installedFile       android.InstallPath
69	extraInstalledFiles android.InstallPaths
70	extraInstalledPairs installPairs
71	outputApex          android.WritablePath
72
73	// fragment for this apex for apexkeys.txt
74	apexKeysPath android.WritablePath
75
76	// Installed locations of symlinks for backward compatibility.
77	compatSymlinks android.InstallPaths
78
79	// systemServerDexpreoptInstalls stores the list of dexpreopt artifacts for a system server jar.
80	systemServerDexpreoptInstalls []java.DexpreopterInstall
81
82	// systemServerDexJars stores the list of dexjars for system server jars in the prebuilt for use when
83	// dexpreopting system server jars that are later in the system server classpath.
84	systemServerDexJars android.Paths
85
86	// Certificate information of any apk packaged inside the prebuilt apex.
87	// This will be nil if the prebuilt apex does not contain any apk.
88	apkCertsFile android.WritablePath
89}
90
91type sanitizedPrebuilt interface {
92	hasSanitizedSource(sanitizer string) bool
93}
94
95type PrebuiltCommonProperties struct {
96	SelectedApexProperties
97
98	// Canonical name of this APEX. Used to determine the path to the activated APEX on
99	// device (/apex/<apex_name>). If unspecified, follows the name property.
100	Apex_name *string
101
102	// Name of the source APEX that gets shadowed by this prebuilt
103	// e.g. com.mycompany.android.myapex
104	// If unspecified, follows the naming convention that the source apex of
105	// the prebuilt is Name() without "prebuilt_" prefix
106	Source_apex_name *string
107
108	ForceDisable bool `blueprint:"mutated"`
109
110	// whether the extracted apex file is installable.
111	Installable *bool
112
113	// optional name for the installed apex. If unspecified, name of the
114	// module is used as the file name
115	Filename *string
116
117	// names of modules to be overridden. Listed modules can only be other binaries
118	// (in Make or Soong).
119	// This does not completely prevent installation of the overridden binaries, but if both
120	// binaries would be installed by default (in PRODUCT_PACKAGES) the other binary will be removed
121	// from PRODUCT_PACKAGES.
122	Overrides []string
123
124	// List of bootclasspath fragments inside this prebuilt APEX bundle and for which this APEX
125	// bundle will create an APEX variant.
126	Exported_bootclasspath_fragments []string
127
128	// List of systemserverclasspath fragments inside this prebuilt APEX bundle and for which this
129	// APEX bundle will create an APEX variant.
130	Exported_systemserverclasspath_fragments []string
131
132	// Path to the .prebuilt_info file of the prebuilt apex.
133	// In case of mainline modules, the .prebuilt_info file contains the build_id that was used to
134	// generate the prebuilt.
135	Prebuilt_info *string `android:"path"`
136}
137
138// initPrebuiltCommon initializes the prebuiltCommon structure and performs initialization of the
139// module that is common to Prebuilt and ApexSet.
140func (p *prebuiltCommon) initPrebuiltCommon(module android.Module, properties *PrebuiltCommonProperties) {
141	p.prebuiltCommonProperties = properties
142	android.InitSingleSourcePrebuiltModule(module.(android.PrebuiltInterface), properties, "Selected_apex")
143	android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
144}
145
146func (p *prebuiltCommon) ApexVariationName() string {
147	return proptools.StringDefault(p.prebuiltCommonProperties.Apex_name, p.BaseModuleName())
148}
149
150func (p *prebuiltCommon) BaseModuleName() string {
151	return proptools.StringDefault(p.prebuiltCommonProperties.Source_apex_name, p.ModuleBase.BaseModuleName())
152}
153
154func (p *prebuiltCommon) Prebuilt() *android.Prebuilt {
155	return &p.prebuilt
156}
157
158func (p *prebuiltCommon) isForceDisabled() bool {
159	return p.prebuiltCommonProperties.ForceDisable
160}
161
162func (p *prebuiltCommon) checkForceDisable(ctx android.ModuleContext) bool {
163	forceDisable := false
164
165	// Force disable the prebuilts when we are doing unbundled build. We do unbundled build
166	// to build the prebuilts themselves.
167	forceDisable = forceDisable || ctx.Config().UnbundledBuild()
168
169	// b/137216042 don't use prebuilts when address sanitizer is on, unless the prebuilt has a sanitized source
170	sanitized := ctx.Module().(sanitizedPrebuilt)
171	forceDisable = forceDisable || (android.InList("address", ctx.Config().SanitizeDevice()) && !sanitized.hasSanitizedSource("address"))
172	forceDisable = forceDisable || (android.InList("hwaddress", ctx.Config().SanitizeDevice()) && !sanitized.hasSanitizedSource("hwaddress"))
173
174	if forceDisable && p.prebuilt.SourceExists() {
175		p.prebuiltCommonProperties.ForceDisable = true
176		return true
177	}
178	return false
179}
180
181func (p *prebuiltCommon) InstallFilename() string {
182	return proptools.StringDefault(p.prebuiltCommonProperties.Filename, p.BaseModuleName()+imageApexSuffix)
183}
184
185func (p *prebuiltCommon) Name() string {
186	return p.prebuilt.Name(p.ModuleBase.Name())
187}
188
189func (p *prebuiltCommon) Overrides() []string {
190	return p.prebuiltCommonProperties.Overrides
191}
192
193func (p *prebuiltCommon) installable() bool {
194	return proptools.BoolDefault(p.prebuiltCommonProperties.Installable, true)
195}
196
197// To satisfy java.DexpreopterInterface
198func (p *prebuiltCommon) IsInstallable() bool {
199	return p.installable()
200}
201
202// initApexFilesForAndroidMk initializes the prebuiltCommon.requiredModuleNames field with the install only deps of the prebuilt apex
203func (p *prebuiltCommon) initApexFilesForAndroidMk(ctx android.ModuleContext) {
204	// If this apex contains a system server jar, then the dexpreopt artifacts should be added as required
205	p.systemServerDexpreoptInstalls = append(p.systemServerDexpreoptInstalls, p.Dexpreopter.ApexSystemServerDexpreoptInstalls()...)
206	p.systemServerDexJars = append(p.systemServerDexJars, p.Dexpreopter.ApexSystemServerDexJars()...)
207}
208
209// If this prebuilt has system server jar, create the rules to dexpreopt it and install it alongside the prebuilt apex
210func (p *prebuiltCommon) dexpreoptSystemServerJars(ctx android.ModuleContext, di *android.DeapexerInfo) {
211	if di == nil {
212		return
213	}
214	// If this prebuilt apex has not been selected, return
215	if p.IsHideFromMake() {
216		return
217	}
218	// Use apex_name to determine the api domain of this prebuilt apex
219	apexName := p.ApexVariationName()
220	// TODO: do not compute twice
221	dc := dexpreopt.GetGlobalConfig(ctx)
222	systemServerJarList := dc.AllApexSystemServerJars(ctx)
223
224	for i := 0; i < systemServerJarList.Len(); i++ {
225		sscpApex := systemServerJarList.Apex(i)
226		sscpJar := systemServerJarList.Jar(i)
227		if apexName != sscpApex {
228			continue
229		}
230		p.Dexpreopter.DexpreoptPrebuiltApexSystemServerJars(ctx, sscpJar, di)
231	}
232}
233
234// installApexSystemServerFiles installs dexpreopt files for system server classpath entries
235// provided by the apex.  They are installed here instead of in library module because there may be multiple
236// variants of the library, generally one for the "main" apex and another with a different min_sdk_version
237// for the Android Go version of the apex.  Both variants would attempt to install to the same locations,
238// and the library variants cannot determine which one should.  The apex module is better equipped to determine
239// if it is "selected".
240// This assumes that the jars produced by different min_sdk_version values are identical, which is currently
241// true but may not be true if the min_sdk_version difference between the variants spans version that changed
242// the dex format.
243func (p *prebuiltCommon) installApexSystemServerFiles(ctx android.ModuleContext) {
244	performInstalls := android.IsModulePreferred(ctx.Module())
245
246	for _, install := range p.systemServerDexpreoptInstalls {
247		var installedFile android.InstallPath
248		if performInstalls {
249			installedFile = ctx.InstallFile(install.InstallDirOnDevice, install.InstallFileOnDevice, install.OutputPathOnHost)
250		} else {
251			installedFile = install.InstallDirOnDevice.Join(ctx, install.InstallFileOnDevice)
252		}
253		p.extraInstalledFiles = append(p.extraInstalledFiles, installedFile)
254		p.extraInstalledPairs = append(p.extraInstalledPairs, installPair{install.OutputPathOnHost, installedFile})
255		ctx.PackageFile(install.InstallDirOnDevice, install.InstallFileOnDevice, install.OutputPathOnHost)
256	}
257
258	for _, dexJar := range p.systemServerDexJars {
259		// Copy the system server dex jar to a predefined location where dex2oat will find it.
260		android.CopyFileRule(ctx, dexJar,
261			android.PathForOutput(ctx, dexpreopt.SystemServerDexjarsDir, dexJar.Base()))
262	}
263}
264
265func (p *prebuiltCommon) AndroidMkEntries() []android.AndroidMkEntries {
266	entriesList := []android.AndroidMkEntries{
267		{
268			Class:      "ETC",
269			OutputFile: android.OptionalPathForPath(p.outputApex),
270			Include:    "$(BUILD_PREBUILT)",
271			ExtraEntries: []android.AndroidMkExtraEntriesFunc{
272				func(ctx android.AndroidMkExtraEntriesContext, entries *android.AndroidMkEntries) {
273					entries.SetString("LOCAL_MODULE_PATH", p.installDir.String())
274					entries.SetString("LOCAL_MODULE_STEM", p.installFilename)
275					entries.SetPath("LOCAL_SOONG_INSTALLED_MODULE", p.installedFile)
276					installPairs := append(installPairs{{p.outputApex, p.installedFile}}, p.extraInstalledPairs...)
277					entries.SetString("LOCAL_SOONG_INSTALL_PAIRS", installPairs.String())
278					entries.AddStrings("LOCAL_SOONG_INSTALL_SYMLINKS", p.compatSymlinks.Strings()...)
279					entries.SetBoolIfTrue("LOCAL_UNINSTALLABLE_MODULE", !p.installable())
280					entries.AddStrings("LOCAL_OVERRIDES_MODULES", p.prebuiltCommonProperties.Overrides...)
281					entries.SetString("LOCAL_APEX_KEY_PATH", p.apexKeysPath.String())
282					if p.apkCertsFile != nil {
283						entries.SetString("LOCAL_APKCERTS_FILE", p.apkCertsFile.String())
284					}
285
286				},
287			},
288		},
289	}
290
291	return entriesList
292}
293
294func (p *prebuiltCommon) hasExportedDeps() bool {
295	return len(p.prebuiltCommonProperties.Exported_bootclasspath_fragments) > 0 ||
296		len(p.prebuiltCommonProperties.Exported_systemserverclasspath_fragments) > 0
297}
298
299type appInPrebuiltApexDepTag struct {
300	blueprint.BaseDependencyTag
301}
302
303func (appInPrebuiltApexDepTag) ExcludeFromVisibilityEnforcement() {}
304
305var appInPrebuiltApexTag = appInPrebuiltApexDepTag{}
306
307// prebuiltApexContentsDeps adds dependencies onto the prebuilt apex module's contents.
308func (p *prebuiltCommon) prebuiltApexContentsDeps(ctx android.BottomUpMutatorContext) {
309	module := ctx.Module()
310
311	for _, dep := range p.prebuiltCommonProperties.Exported_bootclasspath_fragments {
312		prebuiltDep := android.PrebuiltNameFromSource(dep)
313		ctx.AddDependency(module, exportedBootclasspathFragmentTag, prebuiltDep)
314		ctx.AddDependency(module, fragmentInApexTag, prebuiltDep)
315	}
316
317	for _, dep := range p.prebuiltCommonProperties.Exported_systemserverclasspath_fragments {
318		prebuiltDep := android.PrebuiltNameFromSource(dep)
319		ctx.AddDependency(module, exportedSystemserverclasspathFragmentTag, prebuiltDep)
320	}
321}
322
323// Implements android.DepInInSameApex
324func (m *prebuiltCommon) GetDepInSameApexChecker() android.DepInSameApexChecker {
325	return ApexPrebuiltDepInSameApexChecker{}
326}
327
328type ApexPrebuiltDepInSameApexChecker struct {
329	android.BaseDepInSameApexChecker
330}
331
332func (m ApexPrebuiltDepInSameApexChecker) OutgoingDepIsInSameApex(tag blueprint.DependencyTag) bool {
333	_, ok := tag.(exportedDependencyTag)
334	return ok
335}
336
337func (p *prebuiltCommon) checkExportedDependenciesArePrebuilts(ctx android.ModuleContext) {
338	ctx.VisitDirectDeps(func(dep android.Module) {
339		tag := ctx.OtherModuleDependencyTag(dep)
340		depName := ctx.OtherModuleName(dep)
341		if exportedTag, ok := tag.(exportedDependencyTag); ok {
342			propertyName := exportedTag.name
343
344			// It is an error if the other module is not a prebuilt.
345			if !android.IsModulePrebuilt(dep) {
346				ctx.PropertyErrorf(propertyName, "%q is not a prebuilt module", depName)
347			}
348
349			// It is an error if the other module is not an ApexModule.
350			if _, ok := dep.(android.ApexModule); !ok {
351				ctx.PropertyErrorf(propertyName, "%q is not usable within an apex", depName)
352			}
353		}
354
355	})
356}
357
358// generateApexInfo returns an android.ApexInfo configuration suitable for dependencies of this apex.
359func (p *prebuiltCommon) generateApexInfo(ctx generateApexInfoContext) android.ApexInfo {
360	return android.ApexInfo{
361		ApexVariationName: "prebuilt_" + p.ApexVariationName(),
362		BaseApexName:      p.ApexVariationName(),
363		ForPrebuiltApex:   true,
364	}
365}
366
367type Prebuilt struct {
368	prebuiltCommon
369
370	properties PrebuiltProperties
371
372	inputApex android.Path
373
374	provenanceMetaDataFile android.Path
375}
376
377type ApexFileProperties struct {
378	// the path to the prebuilt .apex file to import.
379	//
380	// This cannot be marked as `android:"arch_variant"` because the `prebuilt_apex` is only mutated
381	// for android_common. That is so that it will have the same arch variant as, and so be compatible
382	// with, the source `apex` module type that it replaces.
383	Src  proptools.Configurable[string] `android:"path,replace_instead_of_append"`
384	Arch struct {
385		Arm struct {
386			Src *string `android:"path"`
387		}
388		Arm64 struct {
389			Src *string `android:"path"`
390		}
391		Riscv64 struct {
392			Src *string `android:"path"`
393		}
394		X86 struct {
395			Src *string `android:"path"`
396		}
397		X86_64 struct {
398			Src *string `android:"path"`
399		}
400	}
401}
402
403// prebuiltApexSelector selects the correct prebuilt APEX file for the build target.
404//
405// The ctx parameter can be for any module not just the prebuilt module so care must be taken not
406// to use methods on it that are specific to the current module.
407//
408// See the ApexFileProperties.Src property.
409func (p *ApexFileProperties) prebuiltApexSelector(ctx android.BaseModuleContext, prebuilt android.Module) string {
410	multiTargets := prebuilt.MultiTargets()
411	if len(multiTargets) != 1 {
412		ctx.OtherModuleErrorf(prebuilt, "compile_multilib shouldn't be \"both\" for prebuilt_apex")
413		return ""
414	}
415	var src string
416	switch multiTargets[0].Arch.ArchType {
417	case android.Arm:
418		src = String(p.Arch.Arm.Src)
419	case android.Arm64:
420		src = String(p.Arch.Arm64.Src)
421	case android.Riscv64:
422		src = String(p.Arch.Riscv64.Src)
423		// HACK: fall back to arm64 prebuilts, the riscv64 ones don't exist yet.
424		if src == "" {
425			src = String(p.Arch.Arm64.Src)
426		}
427	case android.X86:
428		src = String(p.Arch.X86.Src)
429	case android.X86_64:
430		src = String(p.Arch.X86_64.Src)
431	}
432	if src == "" {
433		src = p.Src.GetOrDefault(ctx, "")
434	}
435
436	if src == "" {
437		if ctx.Config().AllowMissingDependencies() {
438			ctx.AddMissingDependencies([]string{ctx.OtherModuleName(prebuilt)})
439		} else {
440			ctx.OtherModuleErrorf(prebuilt, "prebuilt_apex does not support %q", multiTargets[0].Arch.String())
441		}
442		// Drop through to return an empty string as the src (instead of nil) to avoid the prebuilt
443		// logic from reporting a more general, less useful message.
444	}
445
446	return src
447}
448
449type PrebuiltProperties struct {
450	ApexFileProperties
451
452	PrebuiltCommonProperties
453
454	// List of apps that are bundled inside this prebuilt apex.
455	// This will be used to create the certificate info of those apps for apkcerts.txt
456	// This dependency will only be used for apkcerts.txt processing.
457	// Notably, building the prebuilt apex will not build the source app.
458	Apps []string
459}
460
461func (a *Prebuilt) hasSanitizedSource(sanitizer string) bool {
462	return false
463}
464
465// prebuilt_apex imports an `.apex` file into the build graph as if it was built with apex.
466func PrebuiltFactory() android.Module {
467	module := &Prebuilt{}
468	module.AddProperties(&module.properties)
469	module.prebuiltCommon.prebuiltCommonProperties = &module.properties.PrebuiltCommonProperties
470
471	// init the module as a prebuilt
472	// even though this module type has srcs, use `InitPrebuiltModuleWithoutSrcs`, since the existing
473	// InitPrebuiltModule* are not friendly with Sources of Configurable type.
474	// The actual src will be evaluated in GenerateAndroidBuildActions.
475	android.InitPrebuiltModuleWithoutSrcs(module)
476	android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
477
478	return module
479}
480
481func (p *prebuiltCommon) getDeapexerPropertiesIfNeeded(ctx android.ModuleContext) DeapexerProperties {
482	// Compute the deapexer properties from the transitive dependencies of this module.
483	commonModules := []string{}
484	dexpreoptProfileGuidedModules := []string{}
485	exportedFiles := []string{}
486	ctx.WalkDeps(func(child, parent android.Module) bool {
487		tag := ctx.OtherModuleDependencyTag(child)
488
489		// If the child is not in the same apex as the parent then ignore it and all its children.
490		if !android.IsDepInSameApex(ctx, parent, child) {
491			return false
492		}
493
494		name := java.ModuleStemForDeapexing(child)
495		if _, ok := tag.(android.RequiresFilesFromPrebuiltApexTag); ok {
496			commonModules = append(commonModules, name)
497
498			extract := child.(android.RequiredFilesFromPrebuiltApex)
499			requiredFiles := extract.RequiredFilesFromPrebuiltApex(ctx)
500			exportedFiles = append(exportedFiles, requiredFiles...)
501
502			if extract.UseProfileGuidedDexpreopt() {
503				dexpreoptProfileGuidedModules = append(dexpreoptProfileGuidedModules, name)
504			}
505
506			// Visit the dependencies of this module just in case they also require files from the
507			// prebuilt apex.
508			return true
509		}
510
511		return false
512	})
513
514	// Create properties for deapexer module.
515	deapexerProperties := DeapexerProperties{
516		// Remove any duplicates from the common modules lists as a module may be included via a direct
517		// dependency as well as transitive ones.
518		CommonModules:                 android.SortedUniqueStrings(commonModules),
519		DexpreoptProfileGuidedModules: android.SortedUniqueStrings(dexpreoptProfileGuidedModules),
520	}
521
522	// Populate the exported files property in a fixed order.
523	deapexerProperties.ExportedFiles = android.SortedUniqueStrings(exportedFiles)
524	return deapexerProperties
525}
526
527func prebuiltApexExportedModuleName(ctx android.BottomUpMutatorContext, name string) string {
528	// The prebuilt_apex should be depending on prebuilt modules but as this runs after
529	// prebuilt_rename the prebuilt module may or may not be using the prebuilt_ prefixed named. So,
530	// check to see if the prefixed name is in use first, if it is then use that, otherwise assume
531	// the unprefixed name is the one to use. If the unprefixed one turns out to be a source module
532	// and not a renamed prebuilt module then that will be detected and reported as an error when
533	// processing the dependency in ApexInfoMutator().
534	prebuiltName := android.PrebuiltNameFromSource(name)
535	if ctx.OtherModuleExists(prebuiltName) {
536		name = prebuiltName
537	}
538	return name
539}
540
541type exportedDependencyTag struct {
542	blueprint.BaseDependencyTag
543	name string
544}
545
546// Mark this tag so dependencies that use it are excluded from visibility enforcement.
547//
548// This does allow any prebuilt_apex to reference any module which does open up a small window for
549// restricted visibility modules to be referenced from the wrong prebuilt_apex. However, doing so
550// avoids opening up a much bigger window by widening the visibility of modules that need files
551// provided by the prebuilt_apex to include all the possible locations they may be defined, which
552// could include everything below vendor/.
553//
554// A prebuilt_apex that references a module via this tag will have to contain the appropriate files
555// corresponding to that module, otherwise it will fail when attempting to retrieve the files from
556// the .apex file. It will also have to be included in the module's apex_available property too.
557// That makes it highly unlikely that a prebuilt_apex would reference a restricted module
558// incorrectly.
559func (t exportedDependencyTag) ExcludeFromVisibilityEnforcement() {}
560
561func (t exportedDependencyTag) RequiresFilesFromPrebuiltApex() {}
562
563var _ android.RequiresFilesFromPrebuiltApexTag = exportedDependencyTag{}
564
565var (
566	exportedBootclasspathFragmentTag         = exportedDependencyTag{name: "exported_bootclasspath_fragments"}
567	exportedSystemserverclasspathFragmentTag = exportedDependencyTag{name: "exported_systemserverclasspath_fragments"}
568)
569
570func (p *Prebuilt) ComponentDepsMutator(ctx android.BottomUpMutatorContext) {
571	p.prebuiltApexContentsDeps(ctx)
572	for _, app := range p.properties.Apps {
573		ctx.AddDependency(p, appInPrebuiltApexTag, app)
574	}
575}
576
577var _ ApexTransitionMutator = (*Prebuilt)(nil)
578
579func (p *Prebuilt) ApexTransitionMutatorSplit(ctx android.BaseModuleContext) []android.ApexInfo {
580	return []android.ApexInfo{p.generateApexInfo(ctx)}
581}
582
583func (p *Prebuilt) ApexTransitionMutatorOutgoing(ctx android.OutgoingTransitionContext, sourceInfo android.ApexInfo) android.ApexInfo {
584	return sourceInfo
585}
586
587func (p *Prebuilt) ApexTransitionMutatorIncoming(ctx android.IncomingTransitionContext, outgoingInfo android.ApexInfo) android.ApexInfo {
588	return p.generateApexInfo(ctx)
589}
590
591func (p *Prebuilt) ApexTransitionMutatorMutate(ctx android.BottomUpMutatorContext, info android.ApexInfo) {
592	android.SetProvider(ctx, android.ApexBundleInfoProvider, android.ApexBundleInfo{})
593}
594
595// creates the build rules to deapex the prebuilt, and returns a deapexerInfo
596func (p *prebuiltCommon) getDeapexerInfo(ctx android.ModuleContext, apexFile android.Path) *android.DeapexerInfo {
597	if !p.hasExportedDeps() {
598		// nothing to do
599		return nil
600	}
601	deapexerProps := p.getDeapexerPropertiesIfNeeded(ctx)
602	return deapex(ctx, apexFile, deapexerProps)
603}
604
605// Set a provider containing information about the jars and .prof provided by the apex
606// Apexes built from prebuilts retrieve this information by visiting its internal deapexer module
607// Used by dex_bootjars to generate the boot image
608func (p *prebuiltCommon) provideApexExportsInfo(ctx android.ModuleContext, di *android.DeapexerInfo) {
609	if di == nil {
610		return
611	}
612	javaModuleToDexPath := map[string]android.Path{}
613	for _, commonModule := range di.GetExportedModuleNames() {
614		if dex := di.PrebuiltExportPath(java.ApexRootRelativePathToJavaLib(commonModule)); dex != nil {
615			javaModuleToDexPath[commonModule] = dex
616		}
617	}
618
619	exports := android.ApexExportsInfo{
620		ApexName:                      p.ApexVariationName(),
621		ProfilePathOnHost:             di.PrebuiltExportPath(java.ProfileInstallPathInApex),
622		LibraryNameToDexJarPathOnHost: javaModuleToDexPath,
623	}
624	android.SetProvider(ctx, android.ApexExportsInfoProvider, exports)
625}
626
627// Set prebuiltInfoProvider. This will be used by `apex_prebuiltinfo_singleton` to print out a metadata file
628// with information about whether source or prebuilt of an apex was used during the build.
629func (p *prebuiltCommon) providePrebuiltInfo(ctx android.ModuleContext) {
630	info := android.PrebuiltInfo{
631		Name:        p.BaseModuleName(),
632		Is_prebuilt: true,
633	}
634	// If Prebuilt_info information is available in the soong module definition, add it to prebuilt_info.json.
635	if p.prebuiltCommonProperties.Prebuilt_info != nil {
636		info.Prebuilt_info_file_path = android.PathForModuleSrc(ctx, *p.prebuiltCommonProperties.Prebuilt_info).String()
637	}
638	android.SetProvider(ctx, android.PrebuiltInfoProvider, info)
639}
640
641// Uses an object provided by its deps to validate that the contents of bcpf have been added to the global
642// PRODUCT_APEX_BOOT_JARS
643// This validation will only run on the apex which is active for this product/release_config
644func validateApexClasspathFragments(ctx android.ModuleContext) {
645	ctx.VisitDirectDeps(func(m android.Module) {
646		if info, exists := android.OtherModuleProvider(ctx, m, java.ClasspathFragmentValidationInfoProvider); exists {
647			ctx.ModuleErrorf("%s in contents of %s must also be declared in PRODUCT_APEX_BOOT_JARS", info.UnknownJars, info.ClasspathFragmentModuleName)
648		}
649	})
650}
651
652func (p *Prebuilt) GenerateAndroidBuildActions(ctx android.ModuleContext) {
653	// Validate contents of classpath fragments
654	if !p.IsHideFromMake() {
655		validateApexClasspathFragments(ctx)
656	}
657
658	p.checkExportedDependenciesArePrebuilts(ctx)
659
660	p.apexKeysPath = writeApexKeys(ctx, p)
661	// TODO(jungjw): Check the key validity.
662	p.inputApex = android.PathForModuleSrc(ctx, p.properties.prebuiltApexSelector(ctx, ctx.Module()))
663	p.installDir = android.PathForModuleInstall(ctx, "apex")
664	p.installFilename = p.InstallFilename()
665	if !strings.HasSuffix(p.installFilename, imageApexSuffix) {
666		ctx.ModuleErrorf("filename should end in %s for prebuilt_apex", imageApexSuffix)
667	}
668	p.outputApex = android.PathForModuleOut(ctx, p.installFilename)
669	ctx.Build(pctx, android.BuildParams{
670		Rule:   android.Cp,
671		Input:  p.inputApex,
672		Output: p.outputApex,
673	})
674
675	if p.prebuiltCommon.checkForceDisable(ctx) {
676		p.HideFromMake()
677		return
678	}
679
680	deapexerInfo := p.getDeapexerInfo(ctx, p.inputApex)
681
682	// dexpreopt any system server jars if present
683	p.dexpreoptSystemServerJars(ctx, deapexerInfo)
684
685	// provide info used for generating the boot image
686	p.provideApexExportsInfo(ctx, deapexerInfo)
687
688	p.providePrebuiltInfo(ctx)
689
690	// Save the files that need to be made available to Make.
691	p.initApexFilesForAndroidMk(ctx)
692
693	// in case that prebuilt_apex replaces source apex (using prefer: prop)
694	p.compatSymlinks = makeCompatSymlinks(p.BaseModuleName(), ctx)
695	// or that prebuilt_apex overrides other apexes (using overrides: prop)
696	for _, overridden := range p.prebuiltCommonProperties.Overrides {
697		p.compatSymlinks = append(p.compatSymlinks, makeCompatSymlinks(overridden, ctx)...)
698	}
699
700	if p.installable() {
701		p.installApexSystemServerFiles(ctx)
702		installDeps := slices.Concat(p.compatSymlinks, p.extraInstalledFiles)
703		p.installedFile = ctx.InstallFile(p.installDir, p.installFilename, p.inputApex, installDeps...)
704		p.provenanceMetaDataFile = provenance.GenerateArtifactProvenanceMetaData(ctx, p.inputApex, p.installedFile)
705	}
706
707	p.addApkCertsInfo(ctx)
708
709	ctx.SetOutputFiles(android.Paths{p.outputApex}, "")
710
711	android.SetProvider(ctx, filesystem.ApexKeyPathInfoProvider, filesystem.ApexKeyPathInfo{p.apexKeysPath})
712}
713
714// `addApkCertsInfo` sets a provider that will be used to create apkcerts.txt
715func (p *Prebuilt) addApkCertsInfo(ctx android.ModuleContext) {
716	formatLine := func(cert java.Certificate, name, partition string) string {
717		pem := cert.AndroidMkString()
718		var key string
719		if cert.Key == nil {
720			key = ""
721		} else {
722			key = cert.Key.String()
723		}
724		return fmt.Sprintf(`name="%s" certificate="%s" private_key="%s" partition="%s"`, name, pem, key, partition)
725	}
726
727	// Determine if this prebuilt_apex contains any .apks
728	var appInfos java.AppInfos
729	ctx.VisitDirectDepsProxyWithTag(appInPrebuiltApexTag, func(app android.ModuleProxy) {
730		if appInfo, ok := android.OtherModuleProvider(ctx, app, java.AppInfoProvider); ok {
731			appInfos = append(appInfos, *appInfo)
732		} else {
733			ctx.ModuleErrorf("App %s does not set AppInfoProvider\n", app.Name())
734		}
735	})
736	sort.Slice(appInfos, func(i, j int) bool {
737		return appInfos[i].InstallApkName < appInfos[j].InstallApkName
738	})
739
740	if len(appInfos) == 0 {
741		return
742	}
743
744	// Set a provider for use by `android_device`.
745	// `android_device` will create an apkcerts.txt with the list of installed apps for that device.
746	android.SetProvider(ctx, java.AppInfosProvider, appInfos)
747
748	// Set a Make variable for legacy apkcerts.txt creation
749	// p.apkCertsFile will become `LOCAL_APKCERTS_FILE`
750	var lines []string
751	for _, appInfo := range appInfos {
752		lines = append(lines, formatLine(appInfo.Certificate, appInfo.InstallApkName+".apk", p.PartitionTag(ctx.DeviceConfig())))
753	}
754	if len(lines) > 0 {
755		p.apkCertsFile = android.PathForModuleOut(ctx, "apkcerts.txt")
756		android.WriteFileRule(ctx, p.apkCertsFile, strings.Join(lines, "\n"))
757	}
758}
759
760func (p *Prebuilt) ProvenanceMetaDataFile() android.Path {
761	return p.provenanceMetaDataFile
762}
763
764// extract registers the build actions to extract an apex from .apks file
765// returns the path of the extracted apex
766func extract(ctx android.ModuleContext, apexSet android.Path, prerelease *bool) android.Path {
767	defaultAllowPrerelease := ctx.Config().IsEnvTrue("SOONG_ALLOW_PRERELEASE_APEXES")
768	extractedApex := android.PathForModuleOut(ctx, "extracted", apexSet.Base())
769	// Filter out NativeBridge archs (b/260115309)
770	abis := java.SupportedAbis(ctx, true)
771	ctx.Build(pctx,
772		android.BuildParams{
773			Rule:        extractMatchingApex,
774			Description: "Extract an apex from an apex set",
775			Inputs:      android.Paths{apexSet},
776			Output:      extractedApex,
777			Args: map[string]string{
778				"abis":              strings.Join(abis, ","),
779				"allow-prereleased": strconv.FormatBool(proptools.BoolDefault(prerelease, defaultAllowPrerelease)),
780				"sdk-version":       ctx.Config().PlatformSdkVersion().String(),
781				"skip-sdk-check":    strconv.FormatBool(ctx.Config().IsEnvTrue("SOONG_SKIP_APPSET_SDK_CHECK")),
782			},
783		},
784	)
785	return extractedApex
786}
787
788type ApexSet struct {
789	prebuiltCommon
790
791	properties ApexSetProperties
792}
793
794type ApexExtractorProperties struct {
795	// the .apks file path that contains prebuilt apex files to be extracted.
796	Set *string `android:"path"`
797
798	Sanitized struct {
799		None struct {
800			Set *string `android:"path"`
801		}
802		Address struct {
803			Set *string `android:"path"`
804		}
805		Hwaddress struct {
806			Set *string `android:"path"`
807		}
808	}
809
810	// apexes in this set use prerelease SDK version
811	Prerelease *bool
812}
813
814func (e *ApexExtractorProperties) prebuiltSrcs(ctx android.BaseModuleContext) []string {
815	var srcs []string
816	if e.Set != nil {
817		srcs = append(srcs, *e.Set)
818	}
819
820	sanitizers := ctx.Config().SanitizeDevice()
821
822	if android.InList("address", sanitizers) && e.Sanitized.Address.Set != nil {
823		srcs = append(srcs, *e.Sanitized.Address.Set)
824	} else if android.InList("hwaddress", sanitizers) && e.Sanitized.Hwaddress.Set != nil {
825		srcs = append(srcs, *e.Sanitized.Hwaddress.Set)
826	} else if e.Sanitized.None.Set != nil {
827		srcs = append(srcs, *e.Sanitized.None.Set)
828	}
829
830	return srcs
831}
832
833type ApexSetProperties struct {
834	ApexExtractorProperties
835
836	PrebuiltCommonProperties
837}
838
839func (a *ApexSet) hasSanitizedSource(sanitizer string) bool {
840	if sanitizer == "address" {
841		return a.properties.Sanitized.Address.Set != nil
842	}
843	if sanitizer == "hwaddress" {
844		return a.properties.Sanitized.Hwaddress.Set != nil
845	}
846
847	return false
848}
849
850// prebuilt_apex imports an `.apex` file into the build graph as if it was built with apex.
851func apexSetFactory() android.Module {
852	module := &ApexSet{}
853	module.AddProperties(&module.properties)
854	module.prebuiltCommon.prebuiltCommonProperties = &module.properties.PrebuiltCommonProperties
855
856	// init the module as a prebuilt
857	// even though this module type has srcs, use `InitPrebuiltModuleWithoutSrcs`, since the existing
858	// InitPrebuiltModule* are not friendly with Sources of Configurable type.
859	// The actual src will be evaluated in GenerateAndroidBuildActions.
860	android.InitPrebuiltModuleWithoutSrcs(module)
861	android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
862
863	return module
864}
865
866func (a *ApexSet) ComponentDepsMutator(ctx android.BottomUpMutatorContext) {
867	a.prebuiltApexContentsDeps(ctx)
868}
869
870var _ ApexTransitionMutator = (*ApexSet)(nil)
871
872func (a *ApexSet) ApexTransitionMutatorSplit(ctx android.BaseModuleContext) []android.ApexInfo {
873	return []android.ApexInfo{a.generateApexInfo(ctx)}
874}
875
876func (a *ApexSet) ApexTransitionMutatorOutgoing(ctx android.OutgoingTransitionContext, sourceInfo android.ApexInfo) android.ApexInfo {
877	return sourceInfo
878}
879
880func (a *ApexSet) ApexTransitionMutatorIncoming(ctx android.IncomingTransitionContext, outgoingInfo android.ApexInfo) android.ApexInfo {
881	return a.generateApexInfo(ctx)
882}
883
884func (a *ApexSet) ApexTransitionMutatorMutate(ctx android.BottomUpMutatorContext, info android.ApexInfo) {
885	android.SetProvider(ctx, android.ApexBundleInfoProvider, android.ApexBundleInfo{})
886}
887
888func (a *ApexSet) GenerateAndroidBuildActions(ctx android.ModuleContext) {
889	// Validate contents of classpath fragments
890	if !a.IsHideFromMake() {
891		validateApexClasspathFragments(ctx)
892	}
893
894	a.apexKeysPath = writeApexKeys(ctx, a)
895	a.installFilename = a.InstallFilename()
896	if !strings.HasSuffix(a.installFilename, imageApexSuffix) && !strings.HasSuffix(a.installFilename, imageCapexSuffix) {
897		ctx.ModuleErrorf("filename should end in %s or %s for apex_set", imageApexSuffix, imageCapexSuffix)
898	}
899
900	var apexSet android.Path
901	if srcs := a.properties.prebuiltSrcs(ctx); len(srcs) == 1 {
902		apexSet = android.PathForModuleSrc(ctx, srcs[0])
903	} else {
904		ctx.ModuleErrorf("Expected exactly one source apex_set file, found %v\n", srcs)
905	}
906
907	extractedApex := extract(ctx, apexSet, a.properties.Prerelease)
908
909	a.outputApex = android.PathForModuleOut(ctx, a.installFilename)
910
911	// Build the output APEX. If compression is not enabled, make sure the output is not compressed even if the input is compressed
912	buildRule := android.Cp
913	if !ctx.Config().ApexCompressionEnabled() {
914		buildRule = decompressApex
915	}
916	ctx.Build(pctx, android.BuildParams{
917		Rule:   buildRule,
918		Input:  extractedApex,
919		Output: a.outputApex,
920	})
921
922	if a.prebuiltCommon.checkForceDisable(ctx) {
923		a.HideFromMake()
924		return
925	}
926
927	deapexerInfo := a.getDeapexerInfo(ctx, extractedApex)
928
929	// dexpreopt any system server jars if present
930	a.dexpreoptSystemServerJars(ctx, deapexerInfo)
931
932	// provide info used for generating the boot image
933	a.provideApexExportsInfo(ctx, deapexerInfo)
934
935	a.providePrebuiltInfo(ctx)
936
937	// Save the files that need to be made available to Make.
938	a.initApexFilesForAndroidMk(ctx)
939
940	a.installDir = android.PathForModuleInstall(ctx, "apex")
941	if a.installable() {
942		a.installApexSystemServerFiles(ctx)
943		a.installedFile = ctx.InstallFile(a.installDir, a.installFilename, a.outputApex, a.extraInstalledFiles...)
944	}
945
946	// in case that apex_set replaces source apex (using prefer: prop)
947	a.compatSymlinks = makeCompatSymlinks(a.BaseModuleName(), ctx)
948	// or that apex_set overrides other apexes (using overrides: prop)
949	for _, overridden := range a.prebuiltCommonProperties.Overrides {
950		a.compatSymlinks = append(a.compatSymlinks, makeCompatSymlinks(overridden, ctx)...)
951	}
952
953	ctx.SetOutputFiles(android.Paths{a.outputApex}, "")
954
955	android.SetProvider(ctx, filesystem.ApexKeyPathInfoProvider, filesystem.ApexKeyPathInfo{a.apexKeysPath})
956}
957