• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright 2015 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 cc
16
17// This file contains the module types for compiling C/C++ for Android, and converts the properties
18// into the flags and filenames necessary to pass to the compiler.  The final creation of the rules
19// is handled in builder.go
20
21import (
22	"errors"
23	"fmt"
24	"io"
25	"slices"
26	"strconv"
27	"strings"
28
29	"github.com/google/blueprint"
30	"github.com/google/blueprint/depset"
31	"github.com/google/blueprint/proptools"
32
33	"android/soong/aidl_library"
34	"android/soong/android"
35	"android/soong/cc/config"
36	"android/soong/fuzz"
37)
38
39type CcMakeVarsInfo struct {
40	WarningsAllowed string
41	UsingWnoError   string
42	MissingProfile  string
43}
44
45var CcMakeVarsInfoProvider = blueprint.NewProvider[*CcMakeVarsInfo]()
46
47type CcObjectInfo struct {
48	ObjFiles   android.Paths
49	TidyFiles  android.Paths
50	KytheFiles android.Paths
51}
52
53var CcObjectInfoProvider = blueprint.NewProvider[CcObjectInfo]()
54
55type AidlInterfaceInfo struct {
56	// list of aidl_interface sources
57	Sources []string
58	// root directory of AIDL sources
59	AidlRoot string
60	// AIDL backend language (e.g. "cpp", "ndk")
61	Lang string
62	// list of flags passed to AIDL generator
63	Flags []string
64}
65
66type CompilerInfo struct {
67	Srcs android.Paths
68	// list of module-specific flags that will be used for C and C++ compiles.
69	Cflags               []string
70	AidlInterfaceInfo    AidlInterfaceInfo
71	LibraryDecoratorInfo *LibraryDecoratorInfo
72}
73
74type LinkerInfo struct {
75	WholeStaticLibs []string
76	// list of modules that should be statically linked into this module.
77	StaticLibs []string
78	// list of modules that should be dynamically linked into this module.
79	SharedLibs []string
80	// list of modules that should only provide headers for this module.
81	HeaderLibs               []string
82	ImplementationModuleName *string
83
84	BinaryDecoratorInfo       *BinaryDecoratorInfo
85	LibraryDecoratorInfo      *LibraryDecoratorInfo
86	TestBinaryInfo            *TestBinaryInfo
87	BenchmarkDecoratorInfo    *BenchmarkDecoratorInfo
88	ObjectLinkerInfo          *ObjectLinkerInfo
89	StubDecoratorInfo         *StubDecoratorInfo
90	PrebuiltLibraryLinkerInfo *PrebuiltLibraryLinkerInfo
91}
92
93type BinaryDecoratorInfo struct{}
94type LibraryDecoratorInfo struct {
95	ExportIncludeDirs []string
96	InjectBsslHash    bool
97	// Location of the static library in the sysroot. Empty if the library is
98	// not included in the NDK.
99	NdkSysrootPath android.Path
100	VndkFileName   string
101}
102
103type SnapshotInfo struct {
104	SnapshotAndroidMkSuffix string
105}
106
107type TestBinaryInfo struct {
108	Gtest bool
109}
110type BenchmarkDecoratorInfo struct{}
111
112type StubDecoratorInfo struct {
113	AbiDumpPath  android.OutputPath
114	HasAbiDump   bool
115	AbiDiffPaths android.Paths
116	InstallPath  android.Path
117}
118
119type ObjectLinkerInfo struct {
120	// Location of the object in the sysroot. Empty if the object is not
121	// included in the NDK.
122	NdkSysrootPath android.Path
123}
124
125type PrebuiltLibraryLinkerInfo struct {
126	VndkFileName string
127}
128
129type LibraryInfo struct {
130	BuildStubs bool
131}
132
133type InstallerInfo struct {
134	StubDecoratorInfo *StubDecoratorInfo
135}
136
137type LocalOrGlobalFlagsInfo struct {
138	CommonFlags []string // Flags that apply to C, C++, and assembly source files
139	CFlags      []string // Flags that apply to C and C++ source files
140	ConlyFlags  []string // Flags that apply to C source files
141	CppFlags    []string // Flags that apply to C++ source files
142}
143
144// Common info about the cc module.
145type CcInfo struct {
146	IsPrebuilt             bool
147	CmakeSnapshotSupported bool
148	HasLlndkStubs          bool
149	DataPaths              []android.DataPath
150	CompilerInfo           *CompilerInfo
151	LinkerInfo             *LinkerInfo
152	SnapshotInfo           *SnapshotInfo
153	LibraryInfo            *LibraryInfo
154	InstallerInfo          *InstallerInfo
155}
156
157var CcInfoProvider = blueprint.NewProvider[*CcInfo]()
158
159type LinkableInfo struct {
160	// StaticExecutable returns true if this is a binary module with "static_executable: true".
161	StaticExecutable     bool
162	Static               bool
163	Shared               bool
164	Header               bool
165	HasStubsVariants     bool
166	StubsVersion         string
167	IsStubs              bool
168	UnstrippedOutputFile android.Path
169	OutputFile           android.OptionalPath
170	CoverageFiles        android.Paths
171	// CoverageOutputFile returns the output archive of gcno coverage information files.
172	CoverageOutputFile android.OptionalPath
173	SAbiDumpFiles      android.Paths
174	// Partition returns the partition string for this module.
175	Partition            string
176	CcLibrary            bool
177	CcLibraryInterface   bool
178	RustLibraryInterface bool
179	// CrateName returns the crateName for a Rust library
180	CrateName string
181	// DepFlags returns a slice of Rustc string flags
182	ExportedCrateLinkDirs []string
183	HasNonSystemVariants  bool
184	IsLlndk               bool
185	// True if the library is in the configs known NDK list.
186	IsNdk             bool
187	InVendorOrProduct bool
188	// SubName returns the modules SubName, used for image and NDK/SDK variations.
189	SubName             string
190	InRamdisk           bool
191	OnlyInRamdisk       bool
192	InVendorRamdisk     bool
193	OnlyInVendorRamdisk bool
194	InRecovery          bool
195	OnlyInRecovery      bool
196	InVendor            bool
197	Installable         *bool
198	// RelativeInstallPath returns the relative install path for this module.
199	RelativeInstallPath string
200	// TODO(b/362509506): remove this once all apex_exclude uses are switched to stubs.
201	RustApexExclude bool
202	// Bootstrap tests if this module is allowed to use non-APEX version of libraries.
203	Bootstrap                       bool
204	Multilib                        string
205	ImplementationModuleNameForMake string
206	IsStubsImplementationRequired   bool
207	// Symlinks returns a list of symlinks that should be created for this module.
208	Symlinks               []string
209	APIListCoverageXMLPath android.ModuleOutPath
210	// FuzzSharedLibraries returns the shared library dependencies for this module.
211	// Expects that IsFuzzModule returns true.
212	FuzzSharedLibraries      android.RuleBuilderInstalls
213	IsVndkPrebuiltLibrary    bool
214	HasLLNDKStubs            bool
215	IsLLNDKMovedToApex       bool
216	ImplementationModuleName string
217}
218
219var LinkableInfoProvider = blueprint.NewProvider[*LinkableInfo]()
220
221func init() {
222	RegisterCCBuildComponents(android.InitRegistrationContext)
223
224	pctx.Import("android/soong/android")
225	pctx.Import("android/soong/cc/config")
226}
227
228func RegisterCCBuildComponents(ctx android.RegistrationContext) {
229	ctx.RegisterModuleType("cc_defaults", defaultsFactory)
230
231	ctx.PreDepsMutators(func(ctx android.RegisterMutatorsContext) {
232		ctx.Transition("sdk", &sdkTransitionMutator{})
233		ctx.BottomUp("llndk", llndkMutator)
234		ctx.Transition("link", &linkageTransitionMutator{})
235		ctx.Transition("version", &versionTransitionMutator{})
236		ctx.BottomUp("begin", BeginMutator)
237	})
238
239	ctx.PostDepsMutators(func(ctx android.RegisterMutatorsContext) {
240		for _, san := range Sanitizers {
241			san.registerMutators(ctx)
242		}
243
244		ctx.BottomUp("sanitize_runtime_deps", sanitizerRuntimeDepsMutator)
245		ctx.BottomUp("sanitize_runtime", sanitizerRuntimeMutator)
246
247		ctx.Transition("fuzz", &fuzzTransitionMutator{})
248
249		ctx.Transition("coverage", &coverageTransitionMutator{})
250
251		ctx.Transition("afdo", &afdoTransitionMutator{})
252
253		ctx.Transition("orderfile", &orderfileTransitionMutator{})
254
255		ctx.Transition("lto", &ltoTransitionMutator{})
256
257		ctx.BottomUp("check_linktype", checkLinkTypeMutator)
258		ctx.BottomUp("double_loadable", checkDoubleLoadableLibraries)
259	})
260
261	ctx.PostApexMutators(func(ctx android.RegisterMutatorsContext) {
262		// sabi mutator needs to be run after apex mutator finishes.
263		ctx.Transition("sabi", &sabiTransitionMutator{})
264	})
265
266	ctx.RegisterParallelSingletonType("kythe_extract_all", kytheExtractAllFactory)
267}
268
269// Deps is a struct containing module names of dependencies, separated by the kind of dependency.
270// Mutators should use `AddVariationDependencies` or its sibling methods to add actual dependency
271// edges to these modules.
272// This object is constructed in DepsMutator, by calling to various module delegates to set
273// relevant fields. For example, `module.compiler.compilerDeps()` may append type-specific
274// dependencies.
275// This is then consumed by the same DepsMutator, which will call `ctx.AddVariationDependencies()`
276// (or its sibling methods) to set real dependencies on the given modules.
277type Deps struct {
278	SharedLibs, LateSharedLibs                  []string
279	StaticLibs, LateStaticLibs, WholeStaticLibs []string
280	HeaderLibs                                  []string
281	RuntimeLibs                                 []string
282
283	// UnexportedStaticLibs are static libraries that are also passed to -Wl,--exclude-libs= to
284	// prevent automatically exporting symbols.
285	UnexportedStaticLibs []string
286
287	// Used for data dependencies adjacent to tests
288	DataLibs []string
289	DataBins []string
290
291	// Used by DepsMutator to pass system_shared_libs information to check_elf_file.py.
292	SystemSharedLibs []string
293
294	// Used by DepMutator to pass aidl_library modules to aidl compiler
295	AidlLibs []string
296
297	// If true, statically link the unwinder into native libraries/binaries.
298	StaticUnwinderIfLegacy bool
299
300	ReexportSharedLibHeaders, ReexportStaticLibHeaders, ReexportHeaderLibHeaders []string
301
302	ObjFiles []string
303
304	GeneratedSources            []string
305	GeneratedHeaders            []string
306	DeviceFirstGeneratedHeaders []string
307	GeneratedDeps               []string
308
309	ReexportGeneratedHeaders []string
310
311	CrtBegin, CrtEnd []string
312
313	// Used for host bionic
314	DynamicLinker string
315
316	// List of libs that need to be excluded for APEX variant
317	ExcludeLibsForApex []string
318	// List of libs that need to be excluded for non-APEX variant
319	ExcludeLibsForNonApex []string
320
321	// LLNDK headers for the ABI checker to check LLNDK implementation library.
322	// An LLNDK implementation is the core variant. LLNDK header libs are reexported by the vendor variant.
323	// The core variant cannot depend on the vendor variant because of the order of imageTransitionMutator.Split().
324	// Instead, the LLNDK implementation depends on the LLNDK header libs.
325	LlndkHeaderLibs []string
326}
327
328// A struct which to collect flags for rlib dependencies
329type RustRlibDep struct {
330	LibPath   android.Path // path to the rlib
331	LinkDirs  []string     // flags required for dependency (e.g. -L flags)
332	CrateName string       // crateNames associated with rlibDeps
333}
334
335func EqRustRlibDeps(a RustRlibDep, b RustRlibDep) bool {
336	return a.LibPath == b.LibPath
337}
338
339// PathDeps is a struct containing file paths to dependencies of a module.
340// It's constructed in depsToPath() by traversing the direct dependencies of the current module.
341// It's used to construct flags for various build statements (such as for compiling and linking).
342// It is then passed to module decorator functions responsible for registering build statements
343// (such as `module.compiler.compile()`).`
344type PathDeps struct {
345	// Paths to .so files
346	SharedLibs, EarlySharedLibs, LateSharedLibs android.Paths
347	// Paths to the dependencies to use for .so files (.so.toc files)
348	SharedLibsDeps, EarlySharedLibsDeps, LateSharedLibsDeps android.Paths
349	// Paths to .a files
350	StaticLibs, LateStaticLibs, WholeStaticLibs android.Paths
351	// Paths and crateNames for RustStaticLib dependencies
352	RustRlibDeps []RustRlibDep
353
354	// Transitive static library dependencies of static libraries for use in ordering.
355	TranstiveStaticLibrariesForOrdering depset.DepSet[android.Path]
356
357	// Paths to .o files
358	Objs Objects
359	// Paths to .o files in dependencies that provide them. Note that these lists
360	// aren't complete since prebuilt modules don't provide the .o files.
361	StaticLibObjs      Objects
362	WholeStaticLibObjs Objects
363
364	// Paths to .a files in prebuilts. Complements WholeStaticLibObjs to contain
365	// the libs from all whole_static_lib dependencies.
366	WholeStaticLibsFromPrebuilts android.Paths
367
368	// Paths to generated source files
369	GeneratedSources android.Paths
370	GeneratedDeps    android.Paths
371
372	Flags                      []string
373	LdFlags                    []string
374	IncludeDirs                android.Paths
375	SystemIncludeDirs          android.Paths
376	ReexportedDirs             android.Paths
377	ReexportedSystemDirs       android.Paths
378	ReexportedFlags            []string
379	ReexportedGeneratedHeaders android.Paths
380	ReexportedDeps             android.Paths
381	ReexportedRustRlibDeps     []RustRlibDep
382
383	// Paths to crt*.o files
384	CrtBegin, CrtEnd android.Paths
385
386	// Path to the dynamic linker binary
387	DynamicLinker android.OptionalPath
388
389	// For Darwin builds, the path to the second architecture's output that should
390	// be combined with this architectures's output into a FAT MachO file.
391	DarwinSecondArchOutput android.OptionalPath
392
393	// Paths to direct srcs and transitive include dirs from direct aidl_library deps
394	AidlLibraryInfos []aidl_library.AidlLibraryInfo
395
396	// LLNDK headers for the ABI checker to check LLNDK implementation library.
397	LlndkIncludeDirs       android.Paths
398	LlndkSystemIncludeDirs android.Paths
399
400	directImplementationDeps     android.Paths
401	transitiveImplementationDeps []depset.DepSet[android.Path]
402}
403
404// LocalOrGlobalFlags contains flags that need to have values set globally by the build system or locally by the module
405// tracked separately, in order to maintain the required ordering (most of the global flags need to go first on the
406// command line so they can be overridden by the local module flags).
407type LocalOrGlobalFlags struct {
408	CommonFlags     []string // Flags that apply to C, C++, and assembly source files
409	AsFlags         []string // Flags that apply to assembly source files
410	YasmFlags       []string // Flags that apply to yasm assembly source files
411	CFlags          []string // Flags that apply to C and C++ source files
412	ToolingCFlags   []string // Flags that apply to C and C++ source files parsed by clang LibTooling tools
413	ConlyFlags      []string // Flags that apply to C source files
414	CppFlags        []string // Flags that apply to C++ source files
415	ToolingCppFlags []string // Flags that apply to C++ source files parsed by clang LibTooling tools
416	LdFlags         []string // Flags that apply to linker command lines
417}
418
419// Flags contains various types of command line flags (and settings) for use in building build
420// statements related to C++.
421type Flags struct {
422	// Local flags (which individual modules are responsible for). These may override global flags.
423	Local LocalOrGlobalFlags
424	// Global flags (which build system or toolchain is responsible for).
425	Global          LocalOrGlobalFlags
426	NoOverrideFlags []string // Flags applied to the end of list of flags so they are not overridden
427
428	aidlFlags     []string // Flags that apply to aidl source files
429	rsFlags       []string // Flags that apply to renderscript source files
430	libFlags      []string // Flags to add libraries early to the link order
431	extraLibFlags []string // Flags to add libraries late in the link order after LdFlags
432	TidyFlags     []string // Flags that apply to clang-tidy
433	SAbiFlags     []string // Flags that apply to header-abi-dumper
434
435	// Global include flags that apply to C, C++, and assembly source files
436	// These must be after any module include flags, which will be in CommonFlags.
437	SystemIncludeFlags []string
438
439	Toolchain     config.Toolchain
440	Tidy          bool // True if ninja .tidy rules should be generated.
441	NeedTidyFiles bool // True if module link should depend on .tidy files
442	GcovCoverage  bool // True if coverage files should be generated.
443	SAbiDump      bool // True if header abi dumps should be generated.
444	EmitXrefs     bool // If true, generate Ninja rules to generate emitXrefs input files for Kythe
445	ClangVerify   bool // If true, append cflags "-Xclang -verify" and append "&& touch $out" to the clang command line.
446
447	// The instruction set required for clang ("arm" or "thumb").
448	RequiredInstructionSet string
449	// The target-device system path to the dynamic linker.
450	DynamicLinker string
451
452	CFlagsDeps  android.Paths // Files depended on by compiler flags
453	LdFlagsDeps android.Paths // Files depended on by linker flags
454
455	// True if .s files should be processed with the c preprocessor.
456	AssemblerWithCpp bool
457
458	proto            android.ProtoFlags
459	protoC           bool // Whether to use C instead of C++
460	protoOptionsFile bool // Whether to look for a .options file next to the .proto
461
462	Yacc *YaccProperties
463	Lex  *LexProperties
464}
465
466// Properties used to compile all C or C++ modules
467type BaseProperties struct {
468	// Deprecated. true is the default, false is invalid.
469	Clang *bool `android:"arch_variant"`
470
471	// Aggresively trade performance for smaller binary size.
472	// This should only be used for on-device binaries that are rarely executed and not
473	// performance critical.
474	Optimize_for_size *bool `android:"arch_variant"`
475
476	// The API level that this module is built against. The APIs of this API level will be
477	// visible at build time, but use of any APIs newer than min_sdk_version will render the
478	// module unloadable on older devices.  In the future it will be possible to weakly-link new
479	// APIs, making the behavior match Java: such modules will load on older devices, but
480	// calling new APIs on devices that do not support them will result in a crash.
481	//
482	// This property has the same behavior as sdk_version does for Java modules. For those
483	// familiar with Android Gradle, the property behaves similarly to how compileSdkVersion
484	// does for Java code.
485	//
486	// In addition, setting this property causes two variants to be built, one for the platform
487	// and one for apps.
488	Sdk_version *string
489
490	// Minimum OS API level supported by this C or C++ module. This property becomes the value
491	// of the __ANDROID_API__ macro. When the C or C++ module is included in an APEX or an APK,
492	// this property is also used to ensure that the min_sdk_version of the containing module is
493	// not older (i.e. less) than this module's min_sdk_version. When not set, this property
494	// defaults to the value of sdk_version.  When this is set to "apex_inherit", this tracks
495	// min_sdk_version of the containing APEX. When the module
496	// is not built for an APEX, "apex_inherit" defaults to sdk_version.
497	Min_sdk_version *string
498
499	// If true, always create an sdk variant and don't create a platform variant.
500	Sdk_variant_only *bool
501
502	AndroidMkSharedLibs      []string `blueprint:"mutated"`
503	AndroidMkStaticLibs      []string `blueprint:"mutated"`
504	AndroidMkRlibs           []string `blueprint:"mutated"`
505	AndroidMkRuntimeLibs     []string `blueprint:"mutated"`
506	AndroidMkWholeStaticLibs []string `blueprint:"mutated"`
507	AndroidMkHeaderLibs      []string `blueprint:"mutated"`
508	HideFromMake             bool     `blueprint:"mutated"`
509	PreventInstall           bool     `blueprint:"mutated"`
510
511	// Set by DepsMutator.
512	AndroidMkSystemSharedLibs []string `blueprint:"mutated"`
513
514	// The name of the image this module is built for
515	ImageVariation string `blueprint:"mutated"`
516
517	// The VNDK version this module is built against. If empty, the module is not
518	// build against the VNDK.
519	VndkVersion string `blueprint:"mutated"`
520
521	// Suffix for the name of Android.mk entries generated by this module
522	SubName string `blueprint:"mutated"`
523
524	// *.logtags files, to combine together in order to generate the /system/etc/event-log-tags
525	// file
526	Logtags []string `android:"path"`
527
528	// Make this module available when building for ramdisk.
529	// On device without a dedicated recovery partition, the module is only
530	// available after switching root into
531	// /first_stage_ramdisk. To expose the module before switching root, install
532	// the recovery variant instead.
533	Ramdisk_available *bool
534
535	// Make this module available when building for vendor ramdisk.
536	// On device without a dedicated recovery partition, the module is only
537	// available after switching root into
538	// /first_stage_ramdisk. To expose the module before switching root, install
539	// the recovery variant instead.
540	Vendor_ramdisk_available *bool
541
542	// Make this module available when building for recovery
543	Recovery_available *bool
544
545	// Used by imageMutator, set by ImageMutatorBegin()
546	VendorVariantNeeded        bool `blueprint:"mutated"`
547	ProductVariantNeeded       bool `blueprint:"mutated"`
548	CoreVariantNeeded          bool `blueprint:"mutated"`
549	RamdiskVariantNeeded       bool `blueprint:"mutated"`
550	VendorRamdiskVariantNeeded bool `blueprint:"mutated"`
551	RecoveryVariantNeeded      bool `blueprint:"mutated"`
552
553	// A list of variations for the "image" mutator of the form
554	//<image name> '.' <version char>, for example, 'vendor.S'
555	ExtraVersionedImageVariations []string `blueprint:"mutated"`
556
557	// Allows this module to use non-APEX version of libraries. Useful
558	// for building binaries that are started before APEXes are activated.
559	Bootstrap *bool
560
561	// Allows this module to be included in CMake release snapshots to be built outside of Android
562	// build system and source tree.
563	Cmake_snapshot_supported *bool
564
565	Installable *bool `android:"arch_variant"`
566
567	// Set by factories of module types that can only be referenced from variants compiled against
568	// the SDK.
569	AlwaysSdk bool `blueprint:"mutated"`
570
571	// Variant is an SDK variant created by sdkMutator
572	IsSdkVariant bool `blueprint:"mutated"`
573	// Set when both SDK and platform variants are exported to Make to trigger renaming the SDK
574	// variant to have a ".sdk" suffix.
575	SdkAndPlatformVariantVisibleToMake bool `blueprint:"mutated"`
576
577	Target struct {
578		Platform struct {
579			// List of modules required by the core variant.
580			Required []string `android:"arch_variant"`
581
582			// List of modules not required by the core variant.
583			Exclude_required []string `android:"arch_variant"`
584		} `android:"arch_variant"`
585
586		Recovery struct {
587			// List of modules required by the recovery variant.
588			Required []string `android:"arch_variant"`
589
590			// List of modules not required by the recovery variant.
591			Exclude_required []string `android:"arch_variant"`
592		} `android:"arch_variant"`
593	} `android:"arch_variant"`
594}
595
596type VendorProperties struct {
597	// whether this module should be allowed to be directly depended by other
598	// modules with `vendor: true`, `proprietary: true`, or `vendor_available:true`.
599	// If set to true, two variants will be built separately, one like
600	// normal, and the other limited to the set of libraries and headers
601	// that are exposed to /vendor modules.
602	//
603	// The vendor variant may be used with a different (newer) /system,
604	// so it shouldn't have any unversioned runtime dependencies, or
605	// make assumptions about the system that may not be true in the
606	// future.
607	//
608	// If set to false, this module becomes inaccessible from /vendor modules.
609	//
610	// The modules with vndk: {enabled: true} must define 'vendor_available'
611	// to 'true'.
612	//
613	// Nothing happens if BOARD_VNDK_VERSION isn't set in the BoardConfig.mk
614	Vendor_available *bool
615
616	// This is the same as the "vendor_available" except that the install path
617	// of the vendor variant is /odm or /vendor/odm.
618	// By replacing "vendor_available: true" with "odm_available: true", the
619	// module will install its vendor variant to the /odm partition or /vendor/odm.
620	// As the modules with "odm_available: true" still create the vendor variants,
621	// they can link to the other vendor modules as the vendor_available modules do.
622	// Also, the vendor modules can link to odm_available modules.
623	//
624	// It may not be used for VNDK modules.
625	Odm_available *bool
626
627	// whether this module should be allowed to be directly depended by other
628	// modules with `product_specific: true` or `product_available: true`.
629	// If set to true, an additional product variant will be built separately
630	// that is limited to the set of libraries and headers that are exposed to
631	// /product modules.
632	//
633	// The product variant may be used with a different (newer) /system,
634	// so it shouldn't have any unversioned runtime dependencies, or
635	// make assumptions about the system that may not be true in the
636	// future.
637	//
638	// If set to false, this module becomes inaccessible from /product modules.
639	//
640	// Different from the 'vendor_available' property, the modules with
641	// vndk: {enabled: true} don't have to define 'product_available'. The VNDK
642	// library without 'product_available' may not be depended on by any other
643	// modules that has product variants including the product available VNDKs.
644	//
645	// Nothing happens if BOARD_VNDK_VERSION isn't set in the BoardConfig.mk
646	// and PRODUCT_PRODUCT_VNDK_VERSION isn't set.
647	Product_available *bool
648
649	// whether this module is capable of being loaded with other instance
650	// (possibly an older version) of the same module in the same process.
651	// Currently, a shared library that is a member of VNDK (vndk: {enabled: true})
652	// can be double loaded in a vendor process if the library is also a
653	// (direct and indirect) dependency of an LLNDK library. Such libraries must be
654	// explicitly marked as `double_loadable: true` by the owner, or the dependency
655	// from the LLNDK lib should be cut if the lib is not designed to be double loaded.
656	Double_loadable *bool
657
658	// IsLLNDK is set to true for the vendor variant of a cc_library module that has LLNDK stubs.
659	IsLLNDK bool `blueprint:"mutated"`
660
661	// IsVendorPublicLibrary is set for the core and product variants of a library that has
662	// vendor_public_library stubs.
663	IsVendorPublicLibrary bool `blueprint:"mutated"`
664}
665
666// ModuleContextIntf is an interface (on a module context helper) consisting of functions related
667// to understanding  details about the type of the current module.
668// For example, one might call these functions to determine whether the current module is a static
669// library and/or is installed in vendor directories.
670type ModuleContextIntf interface {
671	static() bool
672	staticBinary() bool
673	staticLibrary() bool
674	testBinary() bool
675	testLibrary() bool
676	header() bool
677	binary() bool
678	object() bool
679	toolchain() config.Toolchain
680	useSdk() bool
681	sdkVersion() string
682	minSdkVersion() string
683	isSdkVariant() bool
684	useVndk() bool
685	isNdk(config android.Config) bool
686	IsLlndk() bool
687	isImplementationForLLNDKPublic() bool
688	IsVendorPublicLibrary() bool
689	inProduct() bool
690	inVendor() bool
691	inRamdisk() bool
692	inVendorRamdisk() bool
693	inRecovery() bool
694	InVendorOrProduct() bool
695	selectedStl() string
696	baseModuleName() string
697	isAfdoCompile(ctx ModuleContext) bool
698	isOrderfileCompile() bool
699	isCfi() bool
700	isFuzzer() bool
701	isNDKStubLibrary() bool
702	useClangLld(actx ModuleContext) bool
703	apexVariationName() string
704	bootstrap() bool
705	nativeCoverage() bool
706	isPreventInstall() bool
707	isCfiAssemblySupportEnabled() bool
708	getSharedFlags() *SharedFlags
709	notInPlatform() bool
710	optimizeForSize() bool
711	getOrCreateMakeVarsInfo() *CcMakeVarsInfo
712}
713
714type SharedFlags struct {
715	NumSharedFlags int
716	FlagsMap       map[string]string
717}
718
719type ModuleContext interface {
720	android.ModuleContext
721	ModuleContextIntf
722}
723
724type BaseModuleContext interface {
725	android.BaseModuleContext
726	ModuleContextIntf
727}
728
729type DepsContext interface {
730	android.BottomUpMutatorContext
731	ModuleContextIntf
732}
733
734// feature represents additional (optional) steps to building cc-related modules, such as invocation
735// of clang-tidy.
736type feature interface {
737	flags(ctx ModuleContext, flags Flags) Flags
738	props() []interface{}
739}
740
741// Information returned from Generator about the source code it's generating
742type GeneratedSource struct {
743	IncludeDirs    android.Paths
744	Sources        android.Paths
745	Headers        android.Paths
746	ReexportedDirs android.Paths
747}
748
749// generator allows injection of generated code
750type Generator interface {
751	GeneratorProps() []interface{}
752	GeneratorInit(ctx BaseModuleContext)
753	GeneratorDeps(ctx DepsContext, deps Deps) Deps
754	GeneratorFlags(ctx ModuleContext, flags Flags, deps PathDeps) Flags
755	GeneratorSources(ctx ModuleContext) GeneratedSource
756	GeneratorBuildActions(ctx ModuleContext, flags Flags, deps PathDeps)
757}
758
759// compiler is the interface for a compiler helper object. Different module decorators may implement
760// this helper differently.
761type compiler interface {
762	compilerInit(ctx BaseModuleContext)
763	compilerDeps(ctx DepsContext, deps Deps) Deps
764	compilerFlags(ctx ModuleContext, flags Flags, deps PathDeps) Flags
765	compilerProps() []interface{}
766	baseCompilerProps() BaseCompilerProperties
767
768	appendCflags([]string)
769	appendAsflags([]string)
770	compile(ctx ModuleContext, flags Flags, deps PathDeps) Objects
771}
772
773// linker is the interface for a linker decorator object. Individual module types can provide
774// their own implementation for this decorator, and thus specify custom logic regarding build
775// statements pertaining to linking.
776type linker interface {
777	linkerInit(ctx BaseModuleContext)
778	linkerDeps(ctx DepsContext, deps Deps) Deps
779	linkerFlags(ctx ModuleContext, flags Flags) Flags
780	linkerProps() []interface{}
781	baseLinkerProps() BaseLinkerProperties
782	useClangLld(actx ModuleContext) bool
783
784	link(ctx ModuleContext, flags Flags, deps PathDeps, objs Objects) android.Path
785	appendLdflags([]string)
786	unstrippedOutputFilePath() android.Path
787	strippedAllOutputFilePath() android.Path
788
789	nativeCoverage() bool
790	coverageOutputFilePath() android.OptionalPath
791
792	// Get the deps that have been explicitly specified in the properties.
793	linkerSpecifiedDeps(ctx android.ConfigurableEvaluatorContext, module *Module, specifiedDeps specifiedDeps) specifiedDeps
794
795	// Gets a list of files that will be disted when using the dist property without specifying
796	// an output file tag.
797	defaultDistFiles() []android.Path
798
799	moduleInfoJSON(ctx ModuleContext, moduleInfoJSON *android.ModuleInfoJSON)
800
801	testSuiteInfo(ctx ModuleContext)
802}
803
804// specifiedDeps is a tuple struct representing dependencies of a linked binary owned by the linker.
805type specifiedDeps struct {
806	sharedLibs []string
807	// Note nil and [] are semantically distinct. [] prevents linking against the defaults (usually
808	// libc, libm, etc.)
809	systemSharedLibs []string
810}
811
812// installer is the interface for an installer helper object. This helper is responsible for
813// copying build outputs to the appropriate locations so that they may be installed on device.
814type installer interface {
815	installerProps() []interface{}
816	install(ctx ModuleContext, path android.Path)
817	everInstallable() bool
818	inData() bool
819	inSanitizerDir() bool
820	hostToolPath() android.OptionalPath
821	relativeInstallPath() string
822	makeUninstallable(mod *Module)
823	installInRoot() bool
824}
825
826type overridable interface {
827	overriddenModules() []string
828}
829
830type libraryDependencyKind int
831
832const (
833	headerLibraryDependency = iota
834	sharedLibraryDependency
835	staticLibraryDependency
836	rlibLibraryDependency
837)
838
839func (k libraryDependencyKind) String() string {
840	switch k {
841	case headerLibraryDependency:
842		return "headerLibraryDependency"
843	case sharedLibraryDependency:
844		return "sharedLibraryDependency"
845	case staticLibraryDependency:
846		return "staticLibraryDependency"
847	case rlibLibraryDependency:
848		return "rlibLibraryDependency"
849	default:
850		panic(fmt.Errorf("unknown libraryDependencyKind %d", k))
851	}
852}
853
854type libraryDependencyOrder int
855
856const (
857	earlyLibraryDependency  = -1
858	normalLibraryDependency = 0
859	lateLibraryDependency   = 1
860)
861
862func (o libraryDependencyOrder) String() string {
863	switch o {
864	case earlyLibraryDependency:
865		return "earlyLibraryDependency"
866	case normalLibraryDependency:
867		return "normalLibraryDependency"
868	case lateLibraryDependency:
869		return "lateLibraryDependency"
870	default:
871		panic(fmt.Errorf("unknown libraryDependencyOrder %d", o))
872	}
873}
874
875// libraryDependencyTag is used to tag dependencies on libraries.  Unlike many dependency
876// tags that have a set of predefined tag objects that are reused for each dependency, a
877// libraryDependencyTag is designed to contain extra metadata and is constructed as needed.
878// That means that comparing a libraryDependencyTag for equality will only be equal if all
879// of the metadata is equal.  Most usages will want to type assert to libraryDependencyTag and
880// then check individual metadata fields instead.
881type libraryDependencyTag struct {
882	blueprint.BaseDependencyTag
883
884	// These are exported so that fmt.Printf("%#v") can call their String methods.
885	Kind  libraryDependencyKind
886	Order libraryDependencyOrder
887
888	wholeStatic bool
889
890	reexportFlags       bool
891	explicitlyVersioned bool
892	explicitlyImpl      bool
893	dataLib             bool
894	ndk                 bool
895
896	staticUnwinder bool
897
898	makeSuffix string
899
900	// Whether or not this dependency should skip the apex dependency check
901	skipApexAllowedDependenciesCheck bool
902
903	// Whether or not this dependency has to be followed for the apex variants
904	excludeInApex bool
905	// Whether or not this dependency has to be followed for the non-apex variants
906	excludeInNonApex bool
907
908	// If true, don't automatically export symbols from the static library into a shared library.
909	unexportedSymbols bool
910}
911
912// header returns true if the libraryDependencyTag is tagging a header lib dependency.
913func (d libraryDependencyTag) header() bool {
914	return d.Kind == headerLibraryDependency
915}
916
917// shared returns true if the libraryDependencyTag is tagging a shared lib dependency.
918func (d libraryDependencyTag) shared() bool {
919	return d.Kind == sharedLibraryDependency
920}
921
922// shared returns true if the libraryDependencyTag is tagging a static lib dependency.
923func (d libraryDependencyTag) static() bool {
924	return d.Kind == staticLibraryDependency
925}
926
927func (d libraryDependencyTag) LicenseAnnotations() []android.LicenseAnnotation {
928	if d.shared() {
929		return []android.LicenseAnnotation{android.LicenseAnnotationSharedDependency}
930	}
931	return nil
932}
933
934var _ android.LicenseAnnotationsDependencyTag = libraryDependencyTag{}
935
936// InstallDepNeeded returns true for shared libraries so that shared library dependencies of
937// binaries or other shared libraries are installed as dependencies.
938func (d libraryDependencyTag) InstallDepNeeded() bool {
939	return d.shared()
940}
941
942var _ android.InstallNeededDependencyTag = libraryDependencyTag{}
943
944func (d libraryDependencyTag) PropagateAconfigValidation() bool {
945	return d.static()
946}
947
948var _ android.PropagateAconfigValidationDependencyTag = libraryDependencyTag{}
949
950// dependencyTag is used for tagging miscellaneous dependency types that don't fit into
951// libraryDependencyTag.  Each tag object is created globally and reused for multiple
952// dependencies (although since the object contains no references, assigning a tag to a
953// variable and modifying it will not modify the original).  Users can compare the tag
954// returned by ctx.OtherModuleDependencyTag against the global original
955type dependencyTag struct {
956	blueprint.BaseDependencyTag
957	name string
958}
959
960// installDependencyTag is used for tagging miscellaneous dependency types that don't fit into
961// libraryDependencyTag, but where the dependency needs to be installed when the parent is
962// installed.
963type installDependencyTag struct {
964	blueprint.BaseDependencyTag
965	android.InstallAlwaysNeededDependencyTag
966	name string
967}
968
969var (
970	genSourceDepTag       = dependencyTag{name: "gen source"}
971	genHeaderDepTag       = dependencyTag{name: "gen header"}
972	genHeaderExportDepTag = dependencyTag{name: "gen header export"}
973	objDepTag             = dependencyTag{name: "obj"}
974	dynamicLinkerDepTag   = installDependencyTag{name: "dynamic linker"}
975	reuseObjTag           = dependencyTag{name: "reuse objects"}
976	staticVariantTag      = dependencyTag{name: "static variant"}
977	vndkExtDepTag         = dependencyTag{name: "vndk extends"}
978	dataLibDepTag         = dependencyTag{name: "data lib"}
979	dataBinDepTag         = dependencyTag{name: "data bin"}
980	runtimeDepTag         = installDependencyTag{name: "runtime lib"}
981	StubImplDepTag        = dependencyTag{name: "stub_impl"}
982	JniFuzzLibTag         = dependencyTag{name: "jni_fuzz_lib_tag"}
983	FdoProfileTag         = dependencyTag{name: "fdo_profile"}
984	aidlLibraryTag        = dependencyTag{name: "aidl_library"}
985	llndkHeaderLibTag     = dependencyTag{name: "llndk_header_lib"}
986)
987
988func IsExplicitImplSharedDepTag(depTag blueprint.DependencyTag) bool {
989	ccLibDepTag, ok := depTag.(libraryDependencyTag)
990	return ok && ccLibDepTag.shared() && ccLibDepTag.explicitlyImpl
991}
992
993func IsSharedDepTag(depTag blueprint.DependencyTag) bool {
994	ccLibDepTag, ok := depTag.(libraryDependencyTag)
995	return ok && ccLibDepTag.shared()
996}
997
998func IsStaticDepTag(depTag blueprint.DependencyTag) bool {
999	ccLibDepTag, ok := depTag.(libraryDependencyTag)
1000	return ok && ccLibDepTag.static()
1001}
1002
1003func IsHeaderDepTag(depTag blueprint.DependencyTag) bool {
1004	ccLibDepTag, ok := depTag.(libraryDependencyTag)
1005	return ok && ccLibDepTag.header()
1006}
1007
1008func IsRuntimeDepTag(depTag blueprint.DependencyTag) bool {
1009	return depTag == runtimeDepTag
1010}
1011
1012func ExcludeInApexDepTag(depTag blueprint.DependencyTag) bool {
1013	ccLibDepTag, ok := depTag.(libraryDependencyTag)
1014	return ok && ccLibDepTag.excludeInApex
1015}
1016
1017// Module contains the properties and members used by all C/C++ module types, and implements
1018// the blueprint.Module interface.  It delegates to compiler, linker, and installer interfaces
1019// to construct the output file.  Behavior can be customized with a Customizer, or "decorator",
1020// interface.
1021//
1022// To define a C/C++ related module, construct a new Module object and point its delegates to
1023// type-specific structs. These delegates will be invoked to register module-specific build
1024// statements which may be unique to the module type. For example, module.compiler.compile() should
1025// be defined so as to register build statements which are responsible for compiling the module.
1026//
1027// Another example: to construct a cc_binary module, one can create a `cc.binaryDecorator` struct
1028// which implements the `linker` and `installer` interfaces, and points the `linker` and `installer`
1029// members of the cc.Module to this decorator. Thus, a cc_binary module has custom linker and
1030// installer logic.
1031type Module struct {
1032	fuzz.FuzzModule
1033
1034	VendorProperties VendorProperties
1035	Properties       BaseProperties
1036	sourceProperties android.SourceProperties
1037
1038	// initialize before calling Init
1039	hod         android.HostOrDeviceSupported
1040	multilib    android.Multilib
1041	testModule  bool
1042	incremental bool
1043
1044	// Allowable SdkMemberTypes of this module type.
1045	sdkMemberTypes []android.SdkMemberType
1046
1047	// decorator delegates, initialize before calling Init
1048	// these may contain module-specific implementations, and effectively allow for custom
1049	// type-specific logic. These members may reference different objects or the same object.
1050	// Functions of these decorators will be invoked to initialize and register type-specific
1051	// build statements.
1052	generators []Generator
1053	compiler   compiler
1054	linker     linker
1055	installer  installer
1056
1057	features  []feature
1058	stl       *stl
1059	sanitize  *sanitize
1060	coverage  *coverage
1061	fuzzer    *fuzzer
1062	sabi      *sabi
1063	lto       *lto
1064	afdo      *afdo
1065	orderfile *orderfile
1066
1067	library libraryInterface
1068
1069	outputFile android.OptionalPath
1070
1071	cachedToolchain config.Toolchain
1072
1073	subAndroidMkOnce map[subAndroidMkProviderInfoProducer]bool
1074
1075	// Flags used to compile this module
1076	flags Flags
1077
1078	// Shared flags among build rules of this module
1079	sharedFlags SharedFlags
1080
1081	// only non-nil when this is a shared library that reuses the objects of a static library
1082	staticAnalogue *StaticLibraryInfo
1083
1084	makeLinkType string
1085
1086	// For apex variants, this is set as apex.min_sdk_version
1087	apexSdkVersion android.ApiLevel
1088
1089	hideApexVariantFromMake bool
1090
1091	logtagsPaths android.Paths
1092
1093	WholeRustStaticlib bool
1094
1095	hasAidl         bool
1096	hasLex          bool
1097	hasProto        bool
1098	hasRenderscript bool
1099	hasSysprop      bool
1100	hasWinMsg       bool
1101	hasYacc         bool
1102
1103	makeVarsInfo *CcMakeVarsInfo
1104}
1105
1106func (c *Module) IncrementalSupported() bool {
1107	return c.incremental
1108}
1109
1110var _ blueprint.Incremental = (*Module)(nil)
1111
1112func (c *Module) AddJSONData(d *map[string]interface{}) {
1113	c.AndroidModuleBase().AddJSONData(d)
1114	(*d)["Cc"] = map[string]interface{}{
1115		"SdkVersion":             c.SdkVersion(),
1116		"MinSdkVersion":          c.MinSdkVersion(),
1117		"VndkVersion":            c.VndkVersion(),
1118		"ProductSpecific":        c.ProductSpecific(),
1119		"SocSpecific":            c.SocSpecific(),
1120		"DeviceSpecific":         c.DeviceSpecific(),
1121		"InProduct":              c.InProduct(),
1122		"InVendor":               c.InVendor(),
1123		"InRamdisk":              c.InRamdisk(),
1124		"InVendorRamdisk":        c.InVendorRamdisk(),
1125		"InRecovery":             c.InRecovery(),
1126		"VendorAvailable":        c.VendorAvailable(),
1127		"ProductAvailable":       c.ProductAvailable(),
1128		"RamdiskAvailable":       c.RamdiskAvailable(),
1129		"VendorRamdiskAvailable": c.VendorRamdiskAvailable(),
1130		"RecoveryAvailable":      c.RecoveryAvailable(),
1131		"OdmAvailable":           c.OdmAvailable(),
1132		"InstallInData":          c.InstallInData(),
1133		"InstallInRamdisk":       c.InstallInRamdisk(),
1134		"InstallInSanitizerDir":  c.InstallInSanitizerDir(),
1135		"InstallInVendorRamdisk": c.InstallInVendorRamdisk(),
1136		"InstallInRecovery":      c.InstallInRecovery(),
1137		"InstallInRoot":          c.InstallInRoot(),
1138		"IsLlndk":                c.IsLlndk(),
1139		"IsVendorPublicLibrary":  c.IsVendorPublicLibrary(),
1140		"ApexSdkVersion":         c.apexSdkVersion,
1141		"AidlSrcs":               c.hasAidl,
1142		"LexSrcs":                c.hasLex,
1143		"ProtoSrcs":              c.hasProto,
1144		"RenderscriptSrcs":       c.hasRenderscript,
1145		"SyspropSrcs":            c.hasSysprop,
1146		"WinMsgSrcs":             c.hasWinMsg,
1147		"YaccSrsc":               c.hasYacc,
1148		"OnlyCSrcs":              !(c.hasAidl || c.hasLex || c.hasProto || c.hasRenderscript || c.hasSysprop || c.hasWinMsg || c.hasYacc),
1149		"OptimizeForSize":        c.OptimizeForSize(),
1150	}
1151}
1152
1153func (c *Module) SetPreventInstall() {
1154	c.Properties.PreventInstall = true
1155}
1156
1157func (c *Module) SetHideFromMake() {
1158	c.Properties.HideFromMake = true
1159}
1160
1161func (c *Module) HiddenFromMake() bool {
1162	return c.Properties.HideFromMake
1163}
1164
1165func (c *Module) RequiredModuleNames(ctx android.ConfigurableEvaluatorContext) []string {
1166	required := android.CopyOf(c.ModuleBase.RequiredModuleNames(ctx))
1167	if c.ImageVariation().Variation == android.CoreVariation {
1168		required = append(required, c.Properties.Target.Platform.Required...)
1169		required = removeListFromList(required, c.Properties.Target.Platform.Exclude_required)
1170	} else if c.InRecovery() {
1171		required = append(required, c.Properties.Target.Recovery.Required...)
1172		required = removeListFromList(required, c.Properties.Target.Recovery.Exclude_required)
1173	}
1174	return android.FirstUniqueStrings(required)
1175}
1176
1177func (c *Module) Toc() android.OptionalPath {
1178	if c.linker != nil {
1179		if library, ok := c.linker.(libraryInterface); ok {
1180			return library.toc()
1181		}
1182	}
1183	panic(fmt.Errorf("Toc() called on non-library module: %q", c.BaseModuleName()))
1184}
1185
1186func (c *Module) ApiLevel() string {
1187	if c.linker != nil {
1188		if stub, ok := c.linker.(*stubDecorator); ok {
1189			return stub.apiLevel.String()
1190		}
1191	}
1192	panic(fmt.Errorf("ApiLevel() called on non-stub library module: %q", c.BaseModuleName()))
1193}
1194
1195func (c *Module) Static() bool {
1196	if c.linker != nil {
1197		if library, ok := c.linker.(libraryInterface); ok {
1198			return library.static()
1199		}
1200	}
1201	panic(fmt.Errorf("Static() called on non-library module: %q", c.BaseModuleName()))
1202}
1203
1204func (c *Module) Shared() bool {
1205	if c.linker != nil {
1206		if library, ok := c.linker.(libraryInterface); ok {
1207			return library.shared()
1208		}
1209	}
1210
1211	panic(fmt.Errorf("Shared() called on non-library module: %q", c.BaseModuleName()))
1212}
1213
1214func (c *Module) SelectedStl() string {
1215	if c.stl != nil {
1216		return c.stl.Properties.SelectedStl
1217	}
1218	return ""
1219}
1220
1221func (c *Module) StubDecorator() bool {
1222	if _, ok := c.linker.(*stubDecorator); ok {
1223		return true
1224	}
1225	return false
1226}
1227
1228func (c *Module) OptimizeForSize() bool {
1229	return Bool(c.Properties.Optimize_for_size)
1230}
1231
1232func (c *Module) SdkVersion() string {
1233	return String(c.Properties.Sdk_version)
1234}
1235
1236func (c *Module) MinSdkVersion() string {
1237	return String(c.Properties.Min_sdk_version)
1238}
1239
1240func (c *Module) SetSdkVersion(s string) {
1241	c.Properties.Sdk_version = StringPtr(s)
1242}
1243
1244func (c *Module) SetMinSdkVersion(s string) {
1245	c.Properties.Min_sdk_version = StringPtr(s)
1246}
1247
1248func (c *Module) SetStl(s string) {
1249	if c.stl != nil {
1250		c.stl.Properties.Stl = StringPtr(s)
1251	}
1252}
1253
1254func (c *Module) IsCrt() bool {
1255	if linker, ok := c.linker.(*objectLinker); ok {
1256		return linker.isCrt()
1257	}
1258	return false
1259}
1260
1261func (c *Module) SplitPerApiLevel() bool {
1262	return CanUseSdk(c) && c.IsCrt()
1263}
1264
1265func (c *Module) AlwaysSdk() bool {
1266	return c.Properties.AlwaysSdk || Bool(c.Properties.Sdk_variant_only)
1267}
1268
1269func (c *Module) CcLibrary() bool {
1270	if c.linker != nil {
1271		if _, ok := c.linker.(*libraryDecorator); ok {
1272			return true
1273		}
1274		if _, ok := c.linker.(*prebuiltLibraryLinker); ok {
1275			return true
1276		}
1277	}
1278	return false
1279}
1280
1281func (c *Module) CcLibraryInterface() bool {
1282	if c.library != nil {
1283		return true
1284	}
1285	return false
1286}
1287
1288func (c *Module) RlibStd() bool {
1289	panic(fmt.Errorf("RlibStd called on non-Rust module: %q", c.BaseModuleName()))
1290}
1291
1292func (c *Module) RustLibraryInterface() bool {
1293	return false
1294}
1295
1296func (c *Module) CrateName() string {
1297	panic(fmt.Errorf("CrateName called on non-Rust module: %q", c.BaseModuleName()))
1298}
1299
1300func (c *Module) ExportedCrateLinkDirs() []string {
1301	panic(fmt.Errorf("ExportedCrateLinkDirs called on non-Rust module: %q", c.BaseModuleName()))
1302}
1303
1304func (c *Module) IsFuzzModule() bool {
1305	if _, ok := c.compiler.(*fuzzBinary); ok {
1306		return true
1307	}
1308	return false
1309}
1310
1311func (c *Module) FuzzModuleStruct() fuzz.FuzzModule {
1312	return c.FuzzModule
1313}
1314
1315func (c *Module) FuzzPackagedModule() fuzz.FuzzPackagedModule {
1316	if fuzzer, ok := c.compiler.(*fuzzBinary); ok {
1317		return fuzzer.fuzzPackagedModule
1318	}
1319	panic(fmt.Errorf("FuzzPackagedModule called on non-fuzz module: %q", c.BaseModuleName()))
1320}
1321
1322func (c *Module) FuzzSharedLibraries() android.RuleBuilderInstalls {
1323	if fuzzer, ok := c.compiler.(*fuzzBinary); ok {
1324		return fuzzer.sharedLibraries
1325	}
1326	panic(fmt.Errorf("FuzzSharedLibraries called on non-fuzz module: %q", c.BaseModuleName()))
1327}
1328
1329func (c *Module) NonCcVariants() bool {
1330	return false
1331}
1332
1333func (c *Module) SetStatic() {
1334	if c.linker != nil {
1335		if library, ok := c.linker.(libraryInterface); ok {
1336			library.setStatic()
1337			return
1338		}
1339	}
1340	panic(fmt.Errorf("SetStatic called on non-library module: %q", c.BaseModuleName()))
1341}
1342
1343func (c *Module) SetShared() {
1344	if c.linker != nil {
1345		if library, ok := c.linker.(libraryInterface); ok {
1346			library.setShared()
1347			return
1348		}
1349	}
1350	panic(fmt.Errorf("SetShared called on non-library module: %q", c.BaseModuleName()))
1351}
1352
1353func (c *Module) BuildStaticVariant() bool {
1354	if c.linker != nil {
1355		if library, ok := c.linker.(libraryInterface); ok {
1356			return library.buildStatic()
1357		}
1358	}
1359	panic(fmt.Errorf("BuildStaticVariant called on non-library module: %q", c.BaseModuleName()))
1360}
1361
1362func (c *Module) BuildSharedVariant() bool {
1363	if c.linker != nil {
1364		if library, ok := c.linker.(libraryInterface); ok {
1365			return library.buildShared()
1366		}
1367	}
1368	panic(fmt.Errorf("BuildSharedVariant called on non-library module: %q", c.BaseModuleName()))
1369}
1370
1371func (c *Module) BuildRlibVariant() bool {
1372	// cc modules can never build rlib variants
1373	return false
1374}
1375
1376func (c *Module) Module() android.Module {
1377	return c
1378}
1379
1380func (c *Module) OutputFile() android.OptionalPath {
1381	return c.outputFile
1382}
1383
1384func (c *Module) CoverageFiles() android.Paths {
1385	if c.linker != nil {
1386		if library, ok := c.linker.(libraryInterface); ok {
1387			return library.objs().coverageFiles
1388		}
1389	}
1390	panic(fmt.Errorf("CoverageFiles called on non-library module: %q", c.BaseModuleName()))
1391}
1392
1393var _ LinkableInterface = (*Module)(nil)
1394
1395func (c *Module) VersionedInterface() VersionedInterface {
1396	if c.library != nil {
1397		return c.library
1398	}
1399	return nil
1400}
1401
1402func (c *Module) UnstrippedOutputFile() android.Path {
1403	if c.linker != nil {
1404		return c.linker.unstrippedOutputFilePath()
1405	}
1406	return nil
1407}
1408
1409func (c *Module) CoverageOutputFile() android.OptionalPath {
1410	if c.linker != nil {
1411		return c.linker.coverageOutputFilePath()
1412	}
1413	return android.OptionalPath{}
1414}
1415
1416func (c *Module) RelativeInstallPath() string {
1417	if c.installer != nil {
1418		return c.installer.relativeInstallPath()
1419	}
1420	return ""
1421}
1422
1423func (c *Module) VndkVersion() string {
1424	return c.Properties.VndkVersion
1425}
1426
1427func (c *Module) Init() android.Module {
1428	c.AddProperties(&c.Properties, &c.VendorProperties)
1429	for _, generator := range c.generators {
1430		c.AddProperties(generator.GeneratorProps()...)
1431	}
1432	if c.compiler != nil {
1433		c.AddProperties(c.compiler.compilerProps()...)
1434	}
1435	if c.linker != nil {
1436		c.AddProperties(c.linker.linkerProps()...)
1437	}
1438	if c.installer != nil {
1439		c.AddProperties(c.installer.installerProps()...)
1440	}
1441	if c.stl != nil {
1442		c.AddProperties(c.stl.props()...)
1443	}
1444	if c.sanitize != nil {
1445		c.AddProperties(c.sanitize.props()...)
1446	}
1447	if c.coverage != nil {
1448		c.AddProperties(c.coverage.props()...)
1449	}
1450	if c.fuzzer != nil {
1451		c.AddProperties(c.fuzzer.props()...)
1452	}
1453	if c.sabi != nil {
1454		c.AddProperties(c.sabi.props()...)
1455	}
1456	if c.lto != nil {
1457		c.AddProperties(c.lto.props()...)
1458	}
1459	if c.afdo != nil {
1460		c.AddProperties(c.afdo.props()...)
1461	}
1462	if c.orderfile != nil {
1463		c.AddProperties(c.orderfile.props()...)
1464	}
1465	for _, feature := range c.features {
1466		c.AddProperties(feature.props()...)
1467	}
1468	// Allow test-only on libraries that are not cc_test_library
1469	if c.library != nil && !c.testLibrary() {
1470		c.AddProperties(&c.sourceProperties)
1471	}
1472
1473	android.InitAndroidArchModule(c, c.hod, c.multilib)
1474	android.InitApexModule(c)
1475	android.InitDefaultableModule(c)
1476
1477	return c
1478}
1479
1480// UseVndk() returns true if this module is built against VNDK.
1481// This means the vendor and product variants of a module.
1482func (c *Module) UseVndk() bool {
1483	return c.Properties.VndkVersion != ""
1484}
1485
1486func CanUseSdk(c LinkableInterface) bool {
1487	return c.Module().Target().Os == android.Android && c.Target().NativeBridge == android.NativeBridgeDisabled &&
1488		!c.InVendorOrProduct() && !c.InRamdisk() && !c.InRecovery() && !c.InVendorRamdisk()
1489}
1490
1491func (c *Module) UseSdk() bool {
1492	if CanUseSdk(c) {
1493		return String(c.Properties.Sdk_version) != ""
1494	}
1495	return false
1496}
1497
1498func (c *Module) isCoverageVariant() bool {
1499	return c.coverage.Properties.IsCoverageVariant
1500}
1501
1502func (c *Module) IsNdk(config android.Config) bool {
1503	return inList(c.BaseModuleName(), *getNDKKnownLibs(config))
1504}
1505
1506func (c *Module) IsLlndk() bool {
1507	return c.VendorProperties.IsLLNDK
1508}
1509
1510func (m *Module) NeedsLlndkVariants() bool {
1511	lib := moduleVersionedInterface(m)
1512	return lib != nil && (lib.HasLLNDKStubs() || lib.HasLLNDKHeaders())
1513}
1514
1515func (m *Module) NeedsVendorPublicLibraryVariants() bool {
1516	lib := moduleVersionedInterface(m)
1517	return lib != nil && (lib.HasVendorPublicLibrary())
1518}
1519
1520// IsVendorPublicLibrary returns true for vendor public libraries.
1521func (c *Module) IsVendorPublicLibrary() bool {
1522	return c.VendorProperties.IsVendorPublicLibrary
1523}
1524
1525func (c *Module) IsVndkPrebuiltLibrary() bool {
1526	if _, ok := c.linker.(*vndkPrebuiltLibraryDecorator); ok {
1527		return true
1528	}
1529	return false
1530}
1531
1532func (c *Module) SdkAndPlatformVariantVisibleToMake() bool {
1533	return c.Properties.SdkAndPlatformVariantVisibleToMake
1534}
1535
1536func (c *Module) HasLlndkStubs() bool {
1537	lib := moduleVersionedInterface(c)
1538	return lib != nil && lib.HasLLNDKStubs()
1539}
1540
1541func (c *Module) StubsVersion() string {
1542	if lib, ok := c.linker.(VersionedInterface); ok {
1543		return lib.StubsVersion()
1544	}
1545	panic(fmt.Errorf("StubsVersion called on non-versioned module: %q", c.BaseModuleName()))
1546}
1547
1548// isImplementationForLLNDKPublic returns true for any variant of a cc_library that has LLNDK stubs
1549// and does not set llndk.vendor_available: false.
1550func (c *Module) isImplementationForLLNDKPublic() bool {
1551	library, _ := c.library.(*libraryDecorator)
1552	return library != nil && library.HasLLNDKStubs() &&
1553		!Bool(library.Properties.Llndk.Private)
1554}
1555
1556func (c *Module) isAfdoCompile(ctx ModuleContext) bool {
1557	if afdo := c.afdo; afdo != nil {
1558		return afdo.isAfdoCompile(ctx)
1559	}
1560	return false
1561}
1562
1563func (c *Module) isOrderfileCompile() bool {
1564	if orderfile := c.orderfile; orderfile != nil {
1565		return orderfile.Properties.OrderfileLoad
1566	}
1567	return false
1568}
1569
1570func (c *Module) isCfi() bool {
1571	return c.sanitize.isSanitizerEnabled(cfi)
1572}
1573
1574func (c *Module) isFuzzer() bool {
1575	return c.sanitize.isSanitizerEnabled(Fuzzer)
1576}
1577
1578func (c *Module) isNDKStubLibrary() bool {
1579	if _, ok := c.compiler.(*stubDecorator); ok {
1580		return true
1581	}
1582	return false
1583}
1584
1585func (c *Module) SubName() string {
1586	return c.Properties.SubName
1587}
1588
1589func (c *Module) IsStubs() bool {
1590	if lib := c.library; lib != nil {
1591		return lib.BuildStubs()
1592	}
1593	return false
1594}
1595
1596func (c *Module) HasStubsVariants() bool {
1597	if lib := c.library; lib != nil {
1598		return lib.HasStubsVariants()
1599	}
1600	return false
1601}
1602
1603func (c *Module) RustApexExclude() bool {
1604	return false
1605}
1606
1607func (c *Module) IsStubsImplementationRequired() bool {
1608	if lib := c.library; lib != nil {
1609		return lib.IsStubsImplementationRequired()
1610	}
1611	return false
1612}
1613
1614// If this is a stubs library, ImplementationModuleName returns the name of the module that contains
1615// the implementation.  If it is an implementation library it returns its own name.
1616func (c *Module) ImplementationModuleName(ctx android.BaseModuleContext) string {
1617	name := ctx.OtherModuleName(c)
1618	if versioned, ok := c.linker.(VersionedInterface); ok {
1619		name = versioned.ImplementationModuleName(name)
1620	}
1621	return name
1622}
1623
1624// Similar to ImplementationModuleNameByCtx, but uses the Make variant of the module
1625// name as base name, for use in AndroidMk output. E.g. for a prebuilt module
1626// where the Soong name is prebuilt_foo, this returns foo (which works in Make
1627// under the premise that the prebuilt module overrides its source counterpart
1628// if it is exposed to Make).
1629func (c *Module) ImplementationModuleNameForMake() string {
1630	name := c.BaseModuleName()
1631	if versioned, ok := c.linker.(VersionedInterface); ok {
1632		name = versioned.ImplementationModuleName(name)
1633	}
1634	return name
1635}
1636
1637func (c *Module) Bootstrap() bool {
1638	return Bool(c.Properties.Bootstrap)
1639}
1640
1641func (c *Module) nativeCoverage() bool {
1642	// Bug: http://b/137883967 - native-bridge modules do not currently work with coverage
1643	if c.Target().NativeBridge == android.NativeBridgeEnabled {
1644		return false
1645	}
1646	return c.linker != nil && c.linker.nativeCoverage()
1647}
1648
1649func (c *Module) IsSnapshotPrebuilt() bool {
1650	if p, ok := c.linker.(SnapshotInterface); ok {
1651		return p.IsSnapshotPrebuilt()
1652	}
1653	return false
1654}
1655
1656func isBionic(name string) bool {
1657	switch name {
1658	case "libc", "libm", "libdl", "libdl_android", "linker":
1659		return true
1660	}
1661	return false
1662}
1663
1664func InstallToBootstrap(name string, config android.Config) bool {
1665	if name == "libclang_rt.hwasan" || name == "libc_hwasan" {
1666		return true
1667	}
1668	return isBionic(name)
1669}
1670
1671func (c *Module) isCfiAssemblySupportEnabled() bool {
1672	return c.sanitize != nil &&
1673		Bool(c.sanitize.Properties.Sanitize.Config.Cfi_assembly_support)
1674}
1675
1676func (c *Module) InstallInRoot() bool {
1677	return c.installer != nil && c.installer.installInRoot()
1678}
1679
1680type baseModuleContext struct {
1681	android.BaseModuleContext
1682	moduleContextImpl
1683}
1684
1685type depsContext struct {
1686	android.BottomUpMutatorContext
1687	moduleContextImpl
1688}
1689
1690type moduleContext struct {
1691	android.ModuleContext
1692	moduleContextImpl
1693}
1694
1695type moduleContextImpl struct {
1696	mod *Module
1697	ctx BaseModuleContext
1698}
1699
1700func (ctx *moduleContextImpl) toolchain() config.Toolchain {
1701	return ctx.mod.toolchain(ctx.ctx)
1702}
1703
1704func (ctx *moduleContextImpl) static() bool {
1705	return ctx.mod.static()
1706}
1707
1708func (ctx *moduleContextImpl) staticBinary() bool {
1709	return ctx.mod.staticBinary()
1710}
1711
1712func (ctx *moduleContextImpl) staticLibrary() bool {
1713	return ctx.mod.staticLibrary()
1714}
1715
1716func (ctx *moduleContextImpl) testBinary() bool {
1717	return ctx.mod.testBinary()
1718}
1719
1720func (ctx *moduleContextImpl) testLibrary() bool {
1721	return ctx.mod.testLibrary()
1722}
1723
1724func (ctx *moduleContextImpl) header() bool {
1725	return ctx.mod.Header()
1726}
1727
1728func (ctx *moduleContextImpl) binary() bool {
1729	return ctx.mod.Binary()
1730}
1731
1732func (ctx *moduleContextImpl) object() bool {
1733	return ctx.mod.Object()
1734}
1735
1736func (ctx *moduleContextImpl) optimizeForSize() bool {
1737	return ctx.mod.OptimizeForSize()
1738}
1739
1740func (ctx *moduleContextImpl) useSdk() bool {
1741	return ctx.mod.UseSdk()
1742}
1743
1744func (ctx *moduleContextImpl) sdkVersion() string {
1745	if ctx.ctx.Device() {
1746		return String(ctx.mod.Properties.Sdk_version)
1747	}
1748	return ""
1749}
1750
1751func MinSdkVersion(mod VersionedLinkableInterface, ctxIsForPlatform bool, device bool,
1752	platformSdkVersion string) string {
1753
1754	ver := mod.MinSdkVersion()
1755	if ver == "apex_inherit" && !ctxIsForPlatform {
1756		ver = mod.ApexSdkVersion().String()
1757	}
1758	if ver == "apex_inherit" || ver == "" {
1759		ver = mod.SdkVersion()
1760	}
1761
1762	if device {
1763		// When building for vendor/product, use the latest _stable_ API as "current".
1764		// This is passed to clang/aidl compilers so that compiled/generated code works
1765		// with the system.
1766		if (mod.InVendor() || mod.InProduct()) && (ver == "" || ver == "current") {
1767			ver = platformSdkVersion
1768		}
1769	}
1770
1771	// For crt objects, the meaning of min_sdk_version is very different from other types of
1772	// module. For them, min_sdk_version defines the oldest version that the build system will
1773	// create versioned variants for. For example, if min_sdk_version is 16, then sdk variant of
1774	// the crt object has local variants of 16, 17, ..., up to the latest version. sdk_version
1775	// and min_sdk_version properties of the variants are set to the corresponding version
1776	// numbers. However, the non-sdk variant (for apex or platform) of the crt object is left
1777	// untouched.  min_sdk_version: 16 doesn't actually mean that the non-sdk variant has to
1778	// support such an old version. The version is set to the later version in case when the
1779	// non-sdk variant is for the platform, or the min_sdk_version of the containing APEX if
1780	// it's for an APEX.
1781	if mod.IsCrt() && !mod.IsSdkVariant() {
1782		if ctxIsForPlatform {
1783			ver = strconv.Itoa(android.FutureApiLevelInt)
1784		} else { // for apex
1785			ver = mod.ApexSdkVersion().String()
1786			if ver == "" { // in case when min_sdk_version was not set by the APEX
1787				ver = mod.SdkVersion()
1788			}
1789		}
1790	}
1791
1792	// Also make sure that minSdkVersion is not greater than sdkVersion, if they are both numbers
1793	sdkVersionInt, err := strconv.Atoi(mod.SdkVersion())
1794	minSdkVersionInt, err2 := strconv.Atoi(ver)
1795	if err == nil && err2 == nil {
1796		if sdkVersionInt < minSdkVersionInt {
1797			return strconv.Itoa(sdkVersionInt)
1798		}
1799	}
1800	return ver
1801}
1802
1803func (ctx *moduleContextImpl) minSdkVersion() string {
1804	platformSdkVersion := ""
1805	if ctx.ctx.Device() {
1806		platformSdkVersion = ctx.ctx.Config().PlatformSdkVersion().String()
1807	}
1808	return MinSdkVersion(ctx.mod, CtxIsForPlatform(ctx.ctx), ctx.ctx.Device(), platformSdkVersion)
1809}
1810
1811func (ctx *moduleContextImpl) isSdkVariant() bool {
1812	return ctx.mod.IsSdkVariant()
1813}
1814
1815func (ctx *moduleContextImpl) useVndk() bool {
1816	return ctx.mod.UseVndk()
1817}
1818
1819func (ctx *moduleContextImpl) InVendorOrProduct() bool {
1820	return ctx.mod.InVendorOrProduct()
1821}
1822
1823func (ctx *moduleContextImpl) isNdk(config android.Config) bool {
1824	return ctx.mod.IsNdk(config)
1825}
1826
1827func (ctx *moduleContextImpl) IsLlndk() bool {
1828	return ctx.mod.IsLlndk()
1829}
1830
1831func (ctx *moduleContextImpl) isImplementationForLLNDKPublic() bool {
1832	return ctx.mod.isImplementationForLLNDKPublic()
1833}
1834
1835func (ctx *moduleContextImpl) isAfdoCompile(mctx ModuleContext) bool {
1836	return ctx.mod.isAfdoCompile(mctx)
1837}
1838
1839func (ctx *moduleContextImpl) isOrderfileCompile() bool {
1840	return ctx.mod.isOrderfileCompile()
1841}
1842
1843func (ctx *moduleContextImpl) isCfi() bool {
1844	return ctx.mod.isCfi()
1845}
1846
1847func (ctx *moduleContextImpl) isFuzzer() bool {
1848	return ctx.mod.isFuzzer()
1849}
1850
1851func (ctx *moduleContextImpl) isNDKStubLibrary() bool {
1852	return ctx.mod.isNDKStubLibrary()
1853}
1854
1855func (ctx *moduleContextImpl) IsVendorPublicLibrary() bool {
1856	return ctx.mod.IsVendorPublicLibrary()
1857}
1858
1859func (ctx *moduleContextImpl) selectedStl() string {
1860	if stl := ctx.mod.stl; stl != nil {
1861		return stl.Properties.SelectedStl
1862	}
1863	return ""
1864}
1865
1866func (ctx *moduleContextImpl) useClangLld(actx ModuleContext) bool {
1867	return ctx.mod.linker.useClangLld(actx)
1868}
1869
1870func (ctx *moduleContextImpl) baseModuleName() string {
1871	return ctx.mod.BaseModuleName()
1872}
1873
1874func CtxIsForPlatform(ctx android.BaseModuleContext) bool {
1875	apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider)
1876	return apexInfo.IsForPlatform()
1877}
1878
1879func (ctx *moduleContextImpl) apexVariationName() string {
1880	apexInfo, _ := android.ModuleProvider(ctx.ctx, android.ApexInfoProvider)
1881	return apexInfo.ApexVariationName
1882}
1883
1884func (ctx *moduleContextImpl) bootstrap() bool {
1885	return ctx.mod.Bootstrap()
1886}
1887
1888func (ctx *moduleContextImpl) nativeCoverage() bool {
1889	return ctx.mod.nativeCoverage()
1890}
1891
1892func (ctx *moduleContextImpl) isPreventInstall() bool {
1893	return ctx.mod.Properties.PreventInstall
1894}
1895
1896func (ctx *moduleContextImpl) getSharedFlags() *SharedFlags {
1897	shared := &ctx.mod.sharedFlags
1898	if shared.FlagsMap == nil {
1899		shared.NumSharedFlags = 0
1900		shared.FlagsMap = make(map[string]string)
1901	}
1902	return shared
1903}
1904
1905func (ctx *moduleContextImpl) isCfiAssemblySupportEnabled() bool {
1906	return ctx.mod.isCfiAssemblySupportEnabled()
1907}
1908
1909func (ctx *moduleContextImpl) notInPlatform() bool {
1910	return ctx.mod.NotInPlatform()
1911}
1912
1913func (ctx *moduleContextImpl) getOrCreateMakeVarsInfo() *CcMakeVarsInfo {
1914	if ctx.mod.makeVarsInfo == nil {
1915		ctx.mod.makeVarsInfo = &CcMakeVarsInfo{}
1916	}
1917	return ctx.mod.makeVarsInfo
1918}
1919
1920func newBaseModule(hod android.HostOrDeviceSupported, multilib android.Multilib) *Module {
1921	return &Module{
1922		hod:      hod,
1923		multilib: multilib,
1924	}
1925}
1926
1927func newModule(hod android.HostOrDeviceSupported, multilib android.Multilib) *Module {
1928	module := newBaseModule(hod, multilib)
1929	module.features = []feature{
1930		&tidyFeature{},
1931	}
1932	module.stl = &stl{}
1933	module.sanitize = &sanitize{}
1934	module.coverage = &coverage{}
1935	module.fuzzer = &fuzzer{}
1936	module.sabi = &sabi{}
1937	module.lto = &lto{}
1938	module.afdo = &afdo{}
1939	module.orderfile = &orderfile{}
1940	return module
1941}
1942
1943func (c *Module) Prebuilt() *android.Prebuilt {
1944	if p, ok := c.linker.(prebuiltLinkerInterface); ok {
1945		return p.prebuilt()
1946	}
1947	return nil
1948}
1949
1950func (c *Module) IsPrebuilt() bool {
1951	return c.Prebuilt() != nil
1952}
1953
1954func (c *Module) Name() string {
1955	name := c.ModuleBase.Name()
1956	if p, ok := c.linker.(interface {
1957		Name(string) string
1958	}); ok {
1959		name = p.Name(name)
1960	}
1961	return name
1962}
1963
1964func (c *Module) Multilib() string {
1965	return c.Arch().ArchType.Multilib
1966}
1967
1968func (c *Module) ApexSdkVersion() android.ApiLevel {
1969	return c.apexSdkVersion
1970}
1971
1972func (c *Module) Symlinks() []string {
1973	if p, ok := c.installer.(interface {
1974		symlinkList() []string
1975	}); ok {
1976		return p.symlinkList()
1977	}
1978	return nil
1979}
1980
1981func (c *Module) DataPaths() []android.DataPath {
1982	if p, ok := c.installer.(interface {
1983		dataPaths() []android.DataPath
1984	}); ok {
1985		return p.dataPaths()
1986	}
1987	return nil
1988}
1989
1990func getNameSuffixWithVndkVersion(ctx android.ModuleContext, c LinkableInterface) string {
1991	// Returns the name suffix for product and vendor variants. If the VNDK version is not
1992	// "current", it will append the VNDK version to the name suffix.
1993	var nameSuffix string
1994	if c.InProduct() {
1995		if c.ProductSpecific() {
1996			// If the module is product specific with 'product_specific: true',
1997			// do not add a name suffix because it is a base module.
1998			return ""
1999		}
2000		return ProductSuffix
2001	} else {
2002		nameSuffix = VendorSuffix
2003	}
2004	if c.VndkVersion() != "" {
2005		// add version suffix only if the module is using different vndk version than the
2006		// version in product or vendor partition.
2007		nameSuffix += "." + c.VndkVersion()
2008	}
2009	return nameSuffix
2010}
2011
2012func GetSubnameProperty(actx android.ModuleContext, c LinkableInterface) string {
2013	var subName = ""
2014
2015	if c.Target().NativeBridge == android.NativeBridgeEnabled {
2016		subName += NativeBridgeSuffix
2017	}
2018
2019	llndk := c.IsLlndk()
2020	if llndk || (c.InVendorOrProduct() && c.HasNonSystemVariants()) {
2021		// .vendor.{version} suffix is added for vendor variant or .product.{version} suffix is
2022		// added for product variant only when we have vendor and product variants with core
2023		// variant. The suffix is not added for vendor-only or product-only module.
2024		subName += getNameSuffixWithVndkVersion(actx, c)
2025	} else if c.IsVendorPublicLibrary() {
2026		subName += vendorPublicLibrarySuffix
2027	} else if c.IsVndkPrebuiltLibrary() {
2028		// .vendor suffix is added for backward compatibility with VNDK snapshot whose names with
2029		// such suffixes are already hard-coded in prebuilts/vndk/.../Android.bp.
2030		subName += VendorSuffix
2031	} else if c.InRamdisk() && !c.OnlyInRamdisk() {
2032		subName += RamdiskSuffix
2033	} else if c.InVendorRamdisk() && !c.OnlyInVendorRamdisk() {
2034		subName += VendorRamdiskSuffix
2035	} else if c.InRecovery() && !c.OnlyInRecovery() {
2036		subName += RecoverySuffix
2037	} else if c.IsSdkVariant() && (c.SdkAndPlatformVariantVisibleToMake() || c.SplitPerApiLevel()) {
2038		subName += sdkSuffix
2039		if c.SplitPerApiLevel() {
2040			subName += "." + c.SdkVersion()
2041		}
2042	} else if c.IsStubs() && c.IsSdkVariant() {
2043		// Public API surface (NDK)
2044		// Add a suffix to this stub variant to distinguish it from the module-lib stub variant.
2045		subName = sdkSuffix
2046	}
2047
2048	return subName
2049}
2050
2051func moduleContextFromAndroidModuleContext(actx android.ModuleContext, c *Module) ModuleContext {
2052	ctx := &moduleContext{
2053		ModuleContext: actx,
2054		moduleContextImpl: moduleContextImpl{
2055			mod: c,
2056		},
2057	}
2058	ctx.ctx = ctx
2059	return ctx
2060}
2061
2062// TODO (b/277651159): Remove this allowlist
2063var (
2064	skipStubLibraryMultipleApexViolation = map[string]bool{
2065		"libclang_rt.asan":   true,
2066		"libclang_rt.hwasan": true,
2067		// runtime apex
2068		"libc":          true,
2069		"libc_hwasan":   true,
2070		"libdl_android": true,
2071		"libm":          true,
2072		"libdl":         true,
2073		"libz":          true,
2074		// art apex
2075		// TODO(b/234351700): Remove this when com.android.art.debug is gone.
2076		"libandroidio":    true,
2077		"libdexfile":      true,
2078		"libdexfiled":     true, // com.android.art.debug only
2079		"libnativebridge": true,
2080		"libnativehelper": true,
2081		"libnativeloader": true,
2082		"libsigchain":     true,
2083	}
2084)
2085
2086// Returns true if a stub library could be installed in multiple apexes
2087func (c *Module) stubLibraryMultipleApexViolation(ctx android.ModuleContext) bool {
2088	// If this is not an apex variant, no check necessary
2089	if info, ok := android.ModuleProvider(ctx, android.ApexInfoProvider); !ok || info.IsForPlatform() {
2090		return false
2091	}
2092	// If this is not a stub library, no check necessary
2093	if !c.HasStubsVariants() {
2094		return false
2095	}
2096	// Skip the allowlist
2097	// Use BaseModuleName so that this matches prebuilts.
2098	if _, exists := skipStubLibraryMultipleApexViolation[c.BaseModuleName()]; exists {
2099		return false
2100	}
2101
2102	// Stub libraries should not have more than one apex_available
2103	apexAvailable := android.FirstUniqueStrings(c.ApexAvailable())
2104	if len(apexAvailable) > 1 {
2105		return true
2106	}
2107	// Stub libraries should not use the wildcard
2108	if apexAvailable[0] == android.AvailableToAnyApex {
2109		return true
2110	}
2111	// Default: no violation
2112	return false
2113}
2114
2115func (c *Module) GenerateAndroidBuildActions(actx android.ModuleContext) {
2116	ctx := moduleContextFromAndroidModuleContext(actx, c)
2117
2118	c.logtagsPaths = android.PathsForModuleSrc(actx, c.Properties.Logtags)
2119	android.SetProvider(ctx, android.LogtagsProviderKey, &android.LogtagsInfo{
2120		Logtags: c.logtagsPaths,
2121	})
2122
2123	// If Test_only is set on a module in bp file, respect the setting, otherwise
2124	// see if is a known test module type.
2125	testOnly := c.testModule || c.testLibrary()
2126	if c.sourceProperties.Test_only != nil {
2127		testOnly = Bool(c.sourceProperties.Test_only)
2128	}
2129	// Keep before any early returns.
2130	android.SetProvider(ctx, android.TestOnlyProviderKey, android.TestModuleInformation{
2131		TestOnly:       testOnly,
2132		TopLevelTarget: c.testModule,
2133	})
2134
2135	c.Properties.SubName = GetSubnameProperty(actx, c)
2136	apexInfo, _ := android.ModuleProvider(actx, android.ApexInfoProvider)
2137	if !apexInfo.IsForPlatform() {
2138		c.hideApexVariantFromMake = true
2139	}
2140
2141	c.makeLinkType = GetMakeLinkType(actx, c)
2142
2143	deps := c.depsToPaths(ctx)
2144	if ctx.Failed() {
2145		return
2146	}
2147
2148	for _, generator := range c.generators {
2149		gen := generator.GeneratorSources(ctx)
2150		deps.IncludeDirs = append(deps.IncludeDirs, gen.IncludeDirs...)
2151		deps.ReexportedDirs = append(deps.ReexportedDirs, gen.ReexportedDirs...)
2152		deps.GeneratedDeps = append(deps.GeneratedDeps, gen.Headers...)
2153		deps.ReexportedGeneratedHeaders = append(deps.ReexportedGeneratedHeaders, gen.Headers...)
2154		deps.ReexportedDeps = append(deps.ReexportedDeps, gen.Headers...)
2155		if len(deps.Objs.objFiles) == 0 {
2156			// If we are reusuing object files (which happens when we're a shared library and we're
2157			// reusing our static variant's object files), then skip adding the actual source files,
2158			// because we already have the object for it.
2159			deps.GeneratedSources = append(deps.GeneratedSources, gen.Sources...)
2160		}
2161	}
2162
2163	if ctx.Failed() {
2164		return
2165	}
2166
2167	if c.stubLibraryMultipleApexViolation(actx) {
2168		actx.PropertyErrorf("apex_available",
2169			"Stub libraries should have a single apex_available (test apexes excluded). Got %v", c.ApexAvailable())
2170	}
2171	if c.Properties.Clang != nil && *c.Properties.Clang == false {
2172		ctx.PropertyErrorf("clang", "false (GCC) is no longer supported")
2173	} else if c.Properties.Clang != nil && !ctx.DeviceConfig().BuildBrokenClangProperty() {
2174		ctx.PropertyErrorf("clang", "property is deprecated, see Changes.md file")
2175	}
2176
2177	flags := Flags{
2178		Toolchain: c.toolchain(ctx),
2179		EmitXrefs: ctx.Config().EmitXrefRules(),
2180	}
2181	for _, generator := range c.generators {
2182		flags = generator.GeneratorFlags(ctx, flags, deps)
2183	}
2184	if c.compiler != nil {
2185		flags = c.compiler.compilerFlags(ctx, flags, deps)
2186	}
2187	if c.linker != nil {
2188		flags = c.linker.linkerFlags(ctx, flags)
2189	}
2190	if c.stl != nil {
2191		flags = c.stl.flags(ctx, flags)
2192	}
2193	if c.sanitize != nil {
2194		flags = c.sanitize.flags(ctx, flags)
2195	}
2196	if c.coverage != nil {
2197		flags, deps = c.coverage.flags(ctx, flags, deps)
2198	}
2199	if c.fuzzer != nil {
2200		flags = c.fuzzer.flags(ctx, flags)
2201	}
2202	if c.lto != nil {
2203		flags = c.lto.flags(ctx, flags)
2204	}
2205	if c.afdo != nil {
2206		flags = c.afdo.flags(ctx, flags)
2207	}
2208	if c.orderfile != nil {
2209		flags = c.orderfile.flags(ctx, flags)
2210	}
2211	for _, feature := range c.features {
2212		flags = feature.flags(ctx, flags)
2213	}
2214	if ctx.Failed() {
2215		return
2216	}
2217
2218	flags.Local.CFlags, _ = filterList(flags.Local.CFlags, config.IllegalFlags)
2219	flags.Local.CppFlags, _ = filterList(flags.Local.CppFlags, config.IllegalFlags)
2220	flags.Local.ConlyFlags, _ = filterList(flags.Local.ConlyFlags, config.IllegalFlags)
2221
2222	flags.Local.CommonFlags = append(flags.Local.CommonFlags, deps.Flags...)
2223
2224	for _, dir := range deps.IncludeDirs {
2225		flags.Local.CommonFlags = append(flags.Local.CommonFlags, "-I"+dir.String())
2226	}
2227	for _, dir := range deps.SystemIncludeDirs {
2228		flags.Local.CommonFlags = append(flags.Local.CommonFlags, "-isystem "+dir.String())
2229	}
2230
2231	flags.Local.LdFlags = append(flags.Local.LdFlags, deps.LdFlags...)
2232
2233	c.flags = flags
2234	// We need access to all the flags seen by a source file.
2235	if c.sabi != nil {
2236		flags = c.sabi.flags(ctx, flags)
2237	}
2238
2239	flags.AssemblerWithCpp = inList("-xassembler-with-cpp", flags.Local.AsFlags)
2240
2241	for _, generator := range c.generators {
2242		generator.GeneratorBuildActions(ctx, flags, deps)
2243	}
2244
2245	var objs Objects
2246	if c.compiler != nil {
2247		objs = c.compiler.compile(ctx, flags, deps)
2248		if ctx.Failed() {
2249			return
2250		}
2251	}
2252
2253	if c.linker != nil {
2254		outputFile := c.linker.link(ctx, flags, deps, objs)
2255		if ctx.Failed() {
2256			return
2257		}
2258		c.outputFile = android.OptionalPathForPath(outputFile)
2259
2260		c.maybeUnhideFromMake()
2261
2262		android.SetProvider(ctx, ImplementationDepInfoProvider, &ImplementationDepInfo{
2263			ImplementationDeps: depset.New(depset.PREORDER, deps.directImplementationDeps, deps.transitiveImplementationDeps),
2264		})
2265	}
2266
2267	if Bool(c.Properties.Cmake_snapshot_supported) {
2268		android.SetProvider(ctx, cmakeSnapshotSourcesProvider, android.GlobFiles(ctx, ctx.ModuleDir()+"/**/*", nil))
2269	}
2270
2271	c.maybeInstall(ctx, apexInfo)
2272
2273	if c.linker != nil {
2274		moduleInfoJSON := ctx.ModuleInfoJSON()
2275		c.linker.moduleInfoJSON(ctx, moduleInfoJSON)
2276		moduleInfoJSON.SharedLibs = c.Properties.AndroidMkSharedLibs
2277		moduleInfoJSON.StaticLibs = c.Properties.AndroidMkStaticLibs
2278		moduleInfoJSON.SystemSharedLibs = c.Properties.AndroidMkSystemSharedLibs
2279		moduleInfoJSON.RuntimeDependencies = c.Properties.AndroidMkRuntimeLibs
2280
2281		moduleInfoJSON.Dependencies = append(moduleInfoJSON.Dependencies, c.Properties.AndroidMkSharedLibs...)
2282		moduleInfoJSON.Dependencies = append(moduleInfoJSON.Dependencies, c.Properties.AndroidMkStaticLibs...)
2283		moduleInfoJSON.Dependencies = append(moduleInfoJSON.Dependencies, c.Properties.AndroidMkHeaderLibs...)
2284		moduleInfoJSON.Dependencies = append(moduleInfoJSON.Dependencies, c.Properties.AndroidMkWholeStaticLibs...)
2285
2286		if c.sanitize != nil && len(moduleInfoJSON.Class) > 0 &&
2287			(moduleInfoJSON.Class[0] == "STATIC_LIBRARIES" || moduleInfoJSON.Class[0] == "HEADER_LIBRARIES") {
2288			if Bool(c.sanitize.Properties.SanitizeMutated.Cfi) {
2289				moduleInfoJSON.SubName += ".cfi"
2290			}
2291			if Bool(c.sanitize.Properties.SanitizeMutated.Hwaddress) {
2292				moduleInfoJSON.SubName += ".hwasan"
2293			}
2294			if Bool(c.sanitize.Properties.SanitizeMutated.Scs) {
2295				moduleInfoJSON.SubName += ".scs"
2296			}
2297		}
2298		moduleInfoJSON.SubName += c.Properties.SubName
2299
2300		if c.Properties.IsSdkVariant && c.Properties.SdkAndPlatformVariantVisibleToMake {
2301			moduleInfoJSON.Uninstallable = true
2302		}
2303	}
2304
2305	buildComplianceMetadataInfo(ctx, c, deps)
2306
2307	if b, ok := c.compiler.(*baseCompiler); ok {
2308		c.hasAidl = b.hasSrcExt(ctx, ".aidl")
2309		c.hasLex = b.hasSrcExt(ctx, ".l") || b.hasSrcExt(ctx, ".ll")
2310		c.hasProto = b.hasSrcExt(ctx, ".proto")
2311		c.hasRenderscript = b.hasSrcExt(ctx, ".rscript") || b.hasSrcExt(ctx, ".fs")
2312		c.hasSysprop = b.hasSrcExt(ctx, ".sysprop")
2313		c.hasWinMsg = b.hasSrcExt(ctx, ".mc")
2314		c.hasYacc = b.hasSrcExt(ctx, ".y") || b.hasSrcExt(ctx, ".yy")
2315	}
2316
2317	ccObjectInfo := CcObjectInfo{
2318		KytheFiles: objs.kytheFiles,
2319	}
2320	if !ctx.Config().KatiEnabled() || !android.ShouldSkipAndroidMkProcessing(ctx, c) {
2321		ccObjectInfo.ObjFiles = objs.objFiles
2322		ccObjectInfo.TidyFiles = objs.tidyFiles
2323	}
2324	if len(ccObjectInfo.KytheFiles)+len(ccObjectInfo.ObjFiles)+len(ccObjectInfo.TidyFiles) > 0 {
2325		android.SetProvider(ctx, CcObjectInfoProvider, ccObjectInfo)
2326	}
2327
2328	linkableInfo := CreateCommonLinkableInfo(ctx, c)
2329	if lib, ok := c.linker.(VersionedInterface); ok {
2330		linkableInfo.StubsVersion = lib.StubsVersion()
2331	}
2332	if c.linker != nil {
2333		if library, ok := c.linker.(libraryInterface); ok {
2334			linkableInfo.Static = library.static()
2335			linkableInfo.Shared = library.shared()
2336			linkableInfo.CoverageFiles = library.objs().coverageFiles
2337			linkableInfo.SAbiDumpFiles = library.objs().sAbiDumpFiles
2338		}
2339	}
2340	android.SetProvider(ctx, LinkableInfoProvider, linkableInfo)
2341
2342	ccInfo := CcInfo{
2343		IsPrebuilt:             c.IsPrebuilt(),
2344		CmakeSnapshotSupported: proptools.Bool(c.Properties.Cmake_snapshot_supported),
2345		HasLlndkStubs:          c.HasLlndkStubs(),
2346		DataPaths:              c.DataPaths(),
2347	}
2348	if c.compiler != nil {
2349		cflags := c.compiler.baseCompilerProps().Cflags
2350		ccInfo.CompilerInfo = &CompilerInfo{
2351			Srcs:   c.compiler.(CompiledInterface).Srcs(),
2352			Cflags: cflags.GetOrDefault(ctx, nil),
2353			AidlInterfaceInfo: AidlInterfaceInfo{
2354				Sources:  c.compiler.baseCompilerProps().AidlInterface.Sources,
2355				AidlRoot: c.compiler.baseCompilerProps().AidlInterface.AidlRoot,
2356				Lang:     c.compiler.baseCompilerProps().AidlInterface.Lang,
2357				Flags:    c.compiler.baseCompilerProps().AidlInterface.Flags,
2358			},
2359		}
2360		switch decorator := c.compiler.(type) {
2361		case *libraryDecorator:
2362			ccInfo.CompilerInfo.LibraryDecoratorInfo = &LibraryDecoratorInfo{
2363				ExportIncludeDirs: decorator.flagExporter.Properties.Export_include_dirs.GetOrDefault(ctx, nil),
2364			}
2365		}
2366	}
2367	if c.linker != nil {
2368		baseLinkerProps := c.linker.baseLinkerProps()
2369		ccInfo.LinkerInfo = &LinkerInfo{
2370			WholeStaticLibs: baseLinkerProps.Whole_static_libs.GetOrDefault(ctx, nil),
2371			StaticLibs:      baseLinkerProps.Static_libs.GetOrDefault(ctx, nil),
2372			SharedLibs:      baseLinkerProps.Shared_libs.GetOrDefault(ctx, nil),
2373			HeaderLibs:      baseLinkerProps.Header_libs.GetOrDefault(ctx, nil),
2374		}
2375		switch decorator := c.linker.(type) {
2376		case *binaryDecorator:
2377			ccInfo.LinkerInfo.BinaryDecoratorInfo = &BinaryDecoratorInfo{}
2378		case *libraryDecorator:
2379			lk := c.linker.(*libraryDecorator)
2380			ccInfo.LinkerInfo.LibraryDecoratorInfo = &LibraryDecoratorInfo{
2381				InjectBsslHash: Bool(lk.Properties.Inject_bssl_hash),
2382				NdkSysrootPath: lk.ndkSysrootPath,
2383				VndkFileName:   lk.getLibNameHelper(c.BaseModuleName(), true, false) + ".so",
2384			}
2385		case *testBinary:
2386			ccInfo.LinkerInfo.TestBinaryInfo = &TestBinaryInfo{
2387				Gtest: decorator.testDecorator.gtest(),
2388			}
2389		case *benchmarkDecorator:
2390			ccInfo.LinkerInfo.BenchmarkDecoratorInfo = &BenchmarkDecoratorInfo{}
2391		case *objectLinker:
2392			ccInfo.LinkerInfo.ObjectLinkerInfo = &ObjectLinkerInfo{
2393				NdkSysrootPath: c.linker.(*objectLinker).ndkSysrootPath,
2394			}
2395		case *stubDecorator:
2396			ccInfo.LinkerInfo.StubDecoratorInfo = &StubDecoratorInfo{}
2397		case *prebuiltLibraryLinker:
2398			ccInfo.LinkerInfo.PrebuiltLibraryLinkerInfo = &PrebuiltLibraryLinkerInfo{
2399				VndkFileName: c.linker.(*prebuiltLibraryLinker).getLibNameHelper(
2400					c.BaseModuleName(), true, false) + ".so",
2401			}
2402		}
2403
2404		if s, ok := c.linker.(SnapshotInterface); ok {
2405			ccInfo.SnapshotInfo = &SnapshotInfo{
2406				SnapshotAndroidMkSuffix: s.SnapshotAndroidMkSuffix(),
2407			}
2408		}
2409		if v, ok := c.linker.(VersionedInterface); ok {
2410			name := v.ImplementationModuleName(ctx.OtherModuleName(c))
2411			ccInfo.LinkerInfo.ImplementationModuleName = &name
2412		}
2413
2414		c.linker.testSuiteInfo(ctx)
2415	}
2416	if c.library != nil {
2417		ccInfo.LibraryInfo = &LibraryInfo{
2418			BuildStubs: c.library.BuildStubs(),
2419		}
2420	}
2421	if c.installer != nil {
2422		ccInfo.InstallerInfo = &InstallerInfo{}
2423		if installer, ok := c.installer.(*stubDecorator); ok {
2424			ccInfo.InstallerInfo.StubDecoratorInfo = &StubDecoratorInfo{
2425				HasAbiDump:   installer.hasAbiDump,
2426				AbiDumpPath:  installer.abiDumpPath,
2427				AbiDiffPaths: installer.abiDiffPaths,
2428				InstallPath:  installer.installPath,
2429			}
2430		}
2431	}
2432	android.SetProvider(ctx, CcInfoProvider, &ccInfo)
2433
2434	c.setOutputFiles(ctx)
2435
2436	if c.makeVarsInfo != nil {
2437		android.SetProvider(ctx, CcMakeVarsInfoProvider, c.makeVarsInfo)
2438	}
2439}
2440
2441func (c *Module) CleanupAfterBuildActions() {
2442	// Clear as much of Module as possible to reduce memory usage.
2443	c.generators = nil
2444	c.compiler = nil
2445	c.installer = nil
2446	c.features = nil
2447	c.coverage = nil
2448	c.fuzzer = nil
2449	c.sabi = nil
2450	c.lto = nil
2451	c.afdo = nil
2452	c.orderfile = nil
2453
2454	// TODO: these can be cleared after nativeBinaryInfoProperties and nativeLibInfoProperties are switched to
2455	//  using providers.
2456	// c.linker = nil
2457	// c.stl = nil
2458	// c.sanitize = nil
2459	// c.library = nil
2460}
2461
2462func CreateCommonLinkableInfo(ctx android.ModuleContext, mod VersionedLinkableInterface) *LinkableInfo {
2463	info := &LinkableInfo{
2464		StaticExecutable:     mod.StaticExecutable(),
2465		HasStubsVariants:     mod.HasStubsVariants(),
2466		OutputFile:           mod.OutputFile(),
2467		UnstrippedOutputFile: mod.UnstrippedOutputFile(),
2468		CoverageOutputFile:   mod.CoverageOutputFile(),
2469		Partition:            mod.Partition(),
2470		IsStubs:              mod.IsStubs(),
2471		CcLibrary:            mod.CcLibrary(),
2472		CcLibraryInterface:   mod.CcLibraryInterface(),
2473		RustLibraryInterface: mod.RustLibraryInterface(),
2474		IsLlndk:              mod.IsLlndk(),
2475		IsNdk:                mod.IsNdk(ctx.Config()),
2476		HasNonSystemVariants: mod.HasNonSystemVariants(),
2477		SubName:              mod.SubName(),
2478		InVendorOrProduct:    mod.InVendorOrProduct(),
2479		InRamdisk:            mod.InRamdisk(),
2480		OnlyInRamdisk:        mod.OnlyInRamdisk(),
2481		InVendorRamdisk:      mod.InVendorRamdisk(),
2482		OnlyInVendorRamdisk:  mod.OnlyInVendorRamdisk(),
2483		InRecovery:           mod.InRecovery(),
2484		OnlyInRecovery:       mod.OnlyInRecovery(),
2485		InVendor:             mod.InVendor(),
2486		Installable:          mod.Installable(),
2487		RelativeInstallPath:  mod.RelativeInstallPath(),
2488		// TODO(b/362509506): remove this once all apex_exclude uses are switched to stubs.
2489		RustApexExclude:                 mod.RustApexExclude(),
2490		Bootstrap:                       mod.Bootstrap(),
2491		Multilib:                        mod.Multilib(),
2492		ImplementationModuleNameForMake: mod.ImplementationModuleNameForMake(),
2493		Symlinks:                        mod.Symlinks(),
2494		Header:                          mod.Header(),
2495		IsVndkPrebuiltLibrary:           mod.IsVndkPrebuiltLibrary(),
2496	}
2497
2498	vi := mod.VersionedInterface()
2499	if vi != nil {
2500		info.IsStubsImplementationRequired = vi.IsStubsImplementationRequired()
2501		info.APIListCoverageXMLPath = vi.GetAPIListCoverageXMLPath()
2502		info.HasLLNDKStubs = vi.HasLLNDKStubs()
2503		info.IsLLNDKMovedToApex = vi.IsLLNDKMovedToApex()
2504		info.ImplementationModuleName = vi.ImplementationModuleName(mod.BaseModuleName())
2505	}
2506
2507	if !mod.PreventInstall() && fuzz.IsValid(ctx, mod.FuzzModuleStruct()) && mod.IsFuzzModule() {
2508		info.FuzzSharedLibraries = mod.FuzzSharedLibraries()
2509		fm := mod.FuzzPackagedModule()
2510		fuzz.SetFuzzPackagedModuleInfo(ctx, &fm)
2511	}
2512
2513	return info
2514}
2515
2516func (c *Module) setOutputFiles(ctx ModuleContext) {
2517	if c.outputFile.Valid() {
2518		ctx.SetOutputFiles(android.Paths{c.outputFile.Path()}, "")
2519	} else {
2520		ctx.SetOutputFiles(android.Paths{}, "")
2521	}
2522	if c.linker != nil {
2523		ctx.SetOutputFiles(android.PathsIfNonNil(c.linker.unstrippedOutputFilePath()), "unstripped")
2524		ctx.SetOutputFiles(android.PathsIfNonNil(c.linker.strippedAllOutputFilePath()), "stripped_all")
2525		defaultDistFiles := c.linker.defaultDistFiles()
2526		if len(defaultDistFiles) > 0 {
2527			ctx.SetOutputFiles(defaultDistFiles, android.DefaultDistTag)
2528		}
2529	}
2530}
2531
2532func buildComplianceMetadataInfo(ctx ModuleContext, c *Module, deps PathDeps) {
2533	// Dump metadata that can not be done in android/compliance-metadata.go
2534	complianceMetadataInfo := ctx.ComplianceMetadataInfo()
2535	complianceMetadataInfo.SetStringValue(android.ComplianceMetadataProp.IS_STATIC_LIB, strconv.FormatBool(ctx.static() || ctx.ModuleType() == "cc_object"))
2536	complianceMetadataInfo.SetStringValue(android.ComplianceMetadataProp.BUILT_FILES, c.outputFile.String())
2537
2538	// Static deps
2539	staticDeps := ctx.GetDirectDepsProxyWithTag(StaticDepTag(false))
2540	staticDepNames := make([]string, 0, len(staticDeps))
2541	for _, dep := range staticDeps {
2542		staticDepNames = append(staticDepNames, dep.Name())
2543	}
2544	// Process CrtBegin and CrtEnd as static libs
2545	ctx.VisitDirectDepsProxy(func(dep android.ModuleProxy) {
2546		depName := ctx.OtherModuleName(dep)
2547		depTag := ctx.OtherModuleDependencyTag(dep)
2548		switch depTag {
2549		case CrtBeginDepTag:
2550			staticDepNames = append(staticDepNames, depName)
2551		case CrtEndDepTag:
2552			staticDepNames = append(staticDepNames, depName)
2553		}
2554	})
2555
2556	staticDepPaths := make([]string, 0, len(deps.StaticLibs)+len(deps.CrtBegin)+len(deps.CrtEnd))
2557	for _, dep := range deps.StaticLibs {
2558		staticDepPaths = append(staticDepPaths, dep.String())
2559	}
2560	for _, dep := range deps.CrtBegin {
2561		staticDepPaths = append(staticDepPaths, dep.String())
2562	}
2563	for _, dep := range deps.CrtEnd {
2564		staticDepPaths = append(staticDepPaths, dep.String())
2565	}
2566	complianceMetadataInfo.SetListValue(android.ComplianceMetadataProp.STATIC_DEPS, android.FirstUniqueStrings(staticDepNames))
2567	complianceMetadataInfo.SetListValue(android.ComplianceMetadataProp.STATIC_DEP_FILES, android.FirstUniqueStrings(staticDepPaths))
2568
2569	// Whole static deps
2570	wholeStaticDeps := ctx.GetDirectDepsProxyWithTag(StaticDepTag(true))
2571	wholeStaticDepNames := make([]string, 0, len(wholeStaticDeps))
2572	for _, dep := range wholeStaticDeps {
2573		wholeStaticDepNames = append(wholeStaticDepNames, dep.Name())
2574	}
2575
2576	wholeStaticDepPaths := make([]string, 0, len(deps.WholeStaticLibs))
2577	for _, dep := range deps.WholeStaticLibs {
2578		wholeStaticDepPaths = append(wholeStaticDepPaths, dep.String())
2579	}
2580	complianceMetadataInfo.SetListValue(android.ComplianceMetadataProp.WHOLE_STATIC_DEPS, android.FirstUniqueStrings(wholeStaticDepNames))
2581	complianceMetadataInfo.SetListValue(android.ComplianceMetadataProp.WHOLE_STATIC_DEP_FILES, android.FirstUniqueStrings(wholeStaticDepPaths))
2582
2583	// Header libs
2584	headerLibDeps := ctx.GetDirectDepsProxyWithTag(HeaderDepTag())
2585	headerLibDepNames := make([]string, 0, len(headerLibDeps))
2586	for _, dep := range headerLibDeps {
2587		headerLibDepNames = append(headerLibDepNames, dep.Name())
2588	}
2589	complianceMetadataInfo.SetListValue(android.ComplianceMetadataProp.HEADER_LIBS, android.FirstUniqueStrings(headerLibDepNames))
2590}
2591
2592func (c *Module) maybeUnhideFromMake() {
2593	// If a lib is directly included in any of the APEXes or is not available to the
2594	// platform (which is often the case when the stub is provided as a prebuilt),
2595	// unhide the stubs variant having the latest version gets visible to make. In
2596	// addition, the non-stubs variant is renamed to <libname>.bootstrap. This is to
2597	// force anything in the make world to link against the stubs library.  (unless it
2598	// is explicitly referenced via .bootstrap suffix or the module is marked with
2599	// 'bootstrap: true').
2600	if c.HasStubsVariants() && c.NotInPlatform() && !c.InRamdisk() &&
2601		!c.InRecovery() && !c.InVendorOrProduct() && !c.static() && !c.isCoverageVariant() &&
2602		c.IsStubs() && !c.InVendorRamdisk() {
2603		c.Properties.HideFromMake = false // unhide
2604		// Note: this is still non-installable
2605	}
2606}
2607
2608// maybeInstall is called at the end of both GenerateAndroidBuildActions to run the
2609// install hooks for installable modules, like binaries and tests.
2610func (c *Module) maybeInstall(ctx ModuleContext, apexInfo android.ApexInfo) {
2611	if !proptools.BoolDefault(c.Installable(), true) {
2612		// If the module has been specifically configure to not be installed then
2613		// hide from make as otherwise it will break when running inside make
2614		// as the output path to install will not be specified. Not all uninstallable
2615		// modules can be hidden from make as some are needed for resolving make side
2616		// dependencies.
2617		c.HideFromMake()
2618		c.SkipInstall()
2619	} else if !installable(c, apexInfo) {
2620		c.SkipInstall()
2621	}
2622
2623	// Still call c.installer.install though, the installs will be stored as PackageSpecs
2624	// to allow using the outputs in a genrule.
2625	if c.installer != nil && c.outputFile.Valid() {
2626		c.installer.install(ctx, c.outputFile.Path())
2627		if ctx.Failed() {
2628			return
2629		}
2630	}
2631}
2632
2633func (c *Module) toolchain(ctx android.BaseModuleContext) config.Toolchain {
2634	if c.cachedToolchain == nil {
2635		c.cachedToolchain = config.FindToolchainWithContext(ctx)
2636	}
2637	return c.cachedToolchain
2638}
2639
2640func (c *Module) begin(ctx BaseModuleContext) {
2641	for _, generator := range c.generators {
2642		generator.GeneratorInit(ctx)
2643	}
2644	if c.compiler != nil {
2645		c.compiler.compilerInit(ctx)
2646	}
2647	if c.linker != nil {
2648		c.linker.linkerInit(ctx)
2649	}
2650	if c.stl != nil {
2651		c.stl.begin(ctx)
2652	}
2653	if c.sanitize != nil {
2654		c.sanitize.begin(ctx)
2655	}
2656	if c.coverage != nil {
2657		c.coverage.begin(ctx)
2658	}
2659	if c.afdo != nil {
2660		c.afdo.begin(ctx)
2661	}
2662	if c.lto != nil {
2663		c.lto.begin(ctx)
2664	}
2665	if c.orderfile != nil {
2666		c.orderfile.begin(ctx)
2667	}
2668	if ctx.useSdk() && c.IsSdkVariant() {
2669		version, err := NativeApiLevelFromUser(ctx, ctx.sdkVersion())
2670		if err != nil {
2671			ctx.PropertyErrorf("sdk_version", err.Error())
2672			c.Properties.Sdk_version = nil
2673		} else {
2674			c.Properties.Sdk_version = StringPtr(version.String())
2675		}
2676	}
2677}
2678
2679func (c *Module) deps(ctx DepsContext) Deps {
2680	deps := Deps{}
2681
2682	for _, generator := range c.generators {
2683		deps = generator.GeneratorDeps(ctx, deps)
2684	}
2685	if c.compiler != nil {
2686		deps = c.compiler.compilerDeps(ctx, deps)
2687	}
2688	if c.linker != nil {
2689		deps = c.linker.linkerDeps(ctx, deps)
2690	}
2691	if c.stl != nil {
2692		deps = c.stl.deps(ctx, deps)
2693	}
2694	if c.coverage != nil {
2695		deps = c.coverage.deps(ctx, deps)
2696	}
2697
2698	deps.WholeStaticLibs = android.LastUniqueStrings(deps.WholeStaticLibs)
2699	deps.StaticLibs = android.LastUniqueStrings(deps.StaticLibs)
2700	deps.LateStaticLibs = android.LastUniqueStrings(deps.LateStaticLibs)
2701	deps.SharedLibs = android.LastUniqueStrings(deps.SharedLibs)
2702	deps.LateSharedLibs = android.LastUniqueStrings(deps.LateSharedLibs)
2703	deps.HeaderLibs = android.LastUniqueStrings(deps.HeaderLibs)
2704	deps.RuntimeLibs = android.LastUniqueStrings(deps.RuntimeLibs)
2705	deps.LlndkHeaderLibs = android.LastUniqueStrings(deps.LlndkHeaderLibs)
2706
2707	if err := checkConflictingExplicitVersions(deps.SharedLibs); err != nil {
2708		ctx.PropertyErrorf("shared_libs", "%s", err.Error())
2709	}
2710
2711	for _, lib := range deps.ReexportSharedLibHeaders {
2712		if !inList(lib, deps.SharedLibs) {
2713			ctx.PropertyErrorf("export_shared_lib_headers", "Shared library not in shared_libs: '%s'", lib)
2714		}
2715	}
2716
2717	for _, lib := range deps.ReexportStaticLibHeaders {
2718		if !inList(lib, deps.StaticLibs) && !inList(lib, deps.WholeStaticLibs) {
2719			ctx.PropertyErrorf("export_static_lib_headers", "Static library not in static_libs or whole_static_libs: '%s'", lib)
2720		}
2721	}
2722
2723	for _, lib := range deps.ReexportHeaderLibHeaders {
2724		if !inList(lib, deps.HeaderLibs) {
2725			ctx.PropertyErrorf("export_header_lib_headers", "Header library not in header_libs: '%s'", lib)
2726		}
2727	}
2728
2729	for _, gen := range deps.ReexportGeneratedHeaders {
2730		if !inList(gen, deps.GeneratedHeaders) {
2731			ctx.PropertyErrorf("export_generated_headers", "Generated header module not in generated_headers: '%s'", gen)
2732		}
2733	}
2734
2735	return deps
2736}
2737
2738func checkConflictingExplicitVersions(libs []string) error {
2739	withoutVersion := func(s string) string {
2740		name, _ := StubsLibNameAndVersion(s)
2741		return name
2742	}
2743	var errs []error
2744	for i, lib := range libs {
2745		libName := withoutVersion(lib)
2746		libsToCompare := libs[i+1:]
2747		j := slices.IndexFunc(libsToCompare, func(s string) bool {
2748			return withoutVersion(s) == libName
2749		})
2750		if j >= 0 {
2751			errs = append(errs, fmt.Errorf("duplicate shared libraries with different explicit versions: %q and %q",
2752				lib, libsToCompare[j]))
2753		}
2754	}
2755	return errors.Join(errs...)
2756}
2757
2758func (c *Module) beginMutator(actx android.BottomUpMutatorContext) {
2759	ctx := &baseModuleContext{
2760		BaseModuleContext: actx,
2761		moduleContextImpl: moduleContextImpl{
2762			mod: c,
2763		},
2764	}
2765	ctx.ctx = ctx
2766
2767	c.begin(ctx)
2768}
2769
2770// Split name#version into name and version
2771func StubsLibNameAndVersion(name string) (string, string) {
2772	if sharp := strings.LastIndex(name, "#"); sharp != -1 && sharp != len(name)-1 {
2773		version := name[sharp+1:]
2774		libname := name[:sharp]
2775		return libname, version
2776	}
2777	return name, ""
2778}
2779
2780func GetCrtVariations(ctx android.BottomUpMutatorContext,
2781	m LinkableInterface) []blueprint.Variation {
2782	if ctx.Os() != android.Android {
2783		return nil
2784	}
2785	if m.UseSdk() {
2786		// Choose the CRT that best satisfies the min_sdk_version requirement of this module
2787		minSdkVersion := m.MinSdkVersion()
2788		if minSdkVersion == "" || minSdkVersion == "apex_inherit" {
2789			minSdkVersion = m.SdkVersion()
2790		}
2791		apiLevel, err := android.ApiLevelFromUser(ctx, minSdkVersion)
2792		if err != nil {
2793			ctx.PropertyErrorf("min_sdk_version", err.Error())
2794		}
2795
2796		// Raise the minSdkVersion to the minimum supported for the architecture.
2797		minApiForArch := MinApiForArch(ctx, m.Target().Arch.ArchType)
2798		if apiLevel.LessThan(minApiForArch) {
2799			apiLevel = minApiForArch
2800		}
2801
2802		return []blueprint.Variation{
2803			{Mutator: "sdk", Variation: "sdk"},
2804			{Mutator: "version", Variation: apiLevel.String()},
2805		}
2806	}
2807	return []blueprint.Variation{
2808		{Mutator: "sdk", Variation: ""},
2809	}
2810}
2811
2812func AddSharedLibDependenciesWithVersions(ctx android.BottomUpMutatorContext, mod LinkableInterface,
2813	variations []blueprint.Variation, depTag blueprint.DependencyTag, name, version string, far bool) {
2814
2815	variations = append([]blueprint.Variation(nil), variations...)
2816
2817	if version != "" && canBeOrLinkAgainstVersionVariants(mod) {
2818		// Version is explicitly specified. i.e. libFoo#30
2819		if version == "impl" {
2820			version = ""
2821		}
2822		variations = append(variations, blueprint.Variation{Mutator: "version", Variation: version})
2823		if tag, ok := depTag.(libraryDependencyTag); ok {
2824			tag.explicitlyVersioned = true
2825			if version == "" {
2826				tag.explicitlyImpl = true
2827			}
2828			// depTag is an interface that contains a concrete non-pointer struct.  That makes the local
2829			// tag variable a copy of the contents of depTag, and updating it doesn't change depTag.  Reassign
2830			// the modified copy to depTag.
2831			depTag = tag
2832		} else {
2833			panic(fmt.Errorf("Unexpected dependency tag: %T", depTag))
2834		}
2835	}
2836
2837	if far {
2838		ctx.AddFarVariationDependencies(variations, depTag, name)
2839	} else {
2840		ctx.AddVariationDependencies(variations, depTag, name)
2841	}
2842}
2843
2844func GetReplaceModuleName(lib string, replaceMap map[string]string) string {
2845	if snapshot, ok := replaceMap[lib]; ok {
2846		return snapshot
2847	}
2848
2849	return lib
2850}
2851
2852// FilterNdkLibs takes a list of names of shared libraries and scans it for two types
2853// of names:
2854//
2855// 1. Name of an NDK library that refers to an ndk_library module.
2856//
2857//	For each of these, it adds the name of the ndk_library module to the list of
2858//	variant libs.
2859//
2860// 2. Anything else (so anything that isn't an NDK library).
2861//
2862//	It adds these to the nonvariantLibs list.
2863//
2864// The caller can then know to add the variantLibs dependencies differently from the
2865// nonvariantLibs
2866func FilterNdkLibs(c LinkableInterface, config android.Config, list []string) (nonvariantLibs []string, variantLibs []string) {
2867	variantLibs = []string{}
2868
2869	nonvariantLibs = []string{}
2870	for _, entry := range list {
2871		// strip #version suffix out
2872		name, _ := StubsLibNameAndVersion(entry)
2873		if c.UseSdk() && inList(name, *getNDKKnownLibs(config)) {
2874			variantLibs = append(variantLibs, name+ndkLibrarySuffix)
2875		} else {
2876			nonvariantLibs = append(nonvariantLibs, entry)
2877		}
2878	}
2879	return nonvariantLibs, variantLibs
2880
2881}
2882
2883func rewriteLibsForApiImports(c LinkableInterface, libs []string, replaceList map[string]string, config android.Config) ([]string, []string) {
2884	nonVariantLibs := []string{}
2885	variantLibs := []string{}
2886
2887	for _, lib := range libs {
2888		replaceLibName := GetReplaceModuleName(lib, replaceList)
2889		if replaceLibName == lib {
2890			// Do not handle any libs which are not in API imports
2891			nonVariantLibs = append(nonVariantLibs, replaceLibName)
2892		} else if c.UseSdk() && inList(replaceLibName, *getNDKKnownLibs(config)) {
2893			variantLibs = append(variantLibs, replaceLibName)
2894		} else {
2895			nonVariantLibs = append(nonVariantLibs, replaceLibName)
2896		}
2897	}
2898
2899	return nonVariantLibs, variantLibs
2900}
2901
2902func (c *Module) shouldUseApiSurface() bool {
2903	if c.Os() == android.Android && c.Target().NativeBridge != android.NativeBridgeEnabled {
2904		if GetImageVariantType(c) == vendorImageVariant || GetImageVariantType(c) == productImageVariant {
2905			// LLNDK Variant
2906			return true
2907		}
2908
2909		if c.Properties.IsSdkVariant {
2910			// NDK Variant
2911			return true
2912		}
2913	}
2914
2915	return false
2916}
2917
2918func (c *Module) DepsMutator(actx android.BottomUpMutatorContext) {
2919	if !c.Enabled(actx) {
2920		return
2921	}
2922
2923	ctx := &depsContext{
2924		BottomUpMutatorContext: actx,
2925		moduleContextImpl: moduleContextImpl{
2926			mod: c,
2927		},
2928	}
2929	ctx.ctx = ctx
2930
2931	deps := c.deps(ctx)
2932
2933	apiNdkLibs := []string{}
2934	apiLateNdkLibs := []string{}
2935
2936	c.Properties.AndroidMkSystemSharedLibs = deps.SystemSharedLibs
2937
2938	variantNdkLibs := []string{}
2939	variantLateNdkLibs := []string{}
2940	if ctx.Os() == android.Android {
2941		deps.SharedLibs, variantNdkLibs = FilterNdkLibs(c, ctx.Config(), deps.SharedLibs)
2942		deps.LateSharedLibs, variantLateNdkLibs = FilterNdkLibs(c, ctx.Config(), deps.LateSharedLibs)
2943		deps.ReexportSharedLibHeaders, _ = FilterNdkLibs(c, ctx.Config(), deps.ReexportSharedLibHeaders)
2944	}
2945
2946	for _, lib := range deps.HeaderLibs {
2947		depTag := libraryDependencyTag{Kind: headerLibraryDependency}
2948		if inList(lib, deps.ReexportHeaderLibHeaders) {
2949			depTag.reexportFlags = true
2950		}
2951
2952		if c.isNDKStubLibrary() {
2953			variationExists := actx.OtherModuleDependencyVariantExists(nil, lib)
2954			if variationExists {
2955				actx.AddVariationDependencies(nil, depTag, lib)
2956			} else {
2957				// dependencies to ndk_headers fall here as ndk_headers do not have
2958				// any variants.
2959				actx.AddFarVariationDependencies([]blueprint.Variation{}, depTag, lib)
2960			}
2961		} else if c.IsStubs() {
2962			actx.AddFarVariationDependencies(append(ctx.Target().Variations(), c.ImageVariation()),
2963				depTag, lib)
2964		} else {
2965			actx.AddVariationDependencies(nil, depTag, lib)
2966		}
2967	}
2968
2969	if c.isNDKStubLibrary() {
2970		// NDK stubs depend on their implementation because the ABI dumps are
2971		// generated from the implementation library.
2972
2973		actx.AddFarVariationDependencies(append(ctx.Target().Variations(),
2974			c.ImageVariation(),
2975			blueprint.Variation{Mutator: "link", Variation: "shared"},
2976		), stubImplementation, c.BaseModuleName())
2977	}
2978
2979	// If this module is an LLNDK implementation library, let it depend on LlndkHeaderLibs.
2980	if c.ImageVariation().Variation == android.CoreVariation && c.Device() &&
2981		c.Target().NativeBridge == android.NativeBridgeDisabled {
2982		actx.AddVariationDependencies(
2983			[]blueprint.Variation{{Mutator: "image", Variation: android.VendorVariation}},
2984			llndkHeaderLibTag,
2985			deps.LlndkHeaderLibs...)
2986	}
2987
2988	for _, lib := range deps.WholeStaticLibs {
2989		depTag := libraryDependencyTag{Kind: staticLibraryDependency, wholeStatic: true, reexportFlags: true}
2990
2991		actx.AddVariationDependencies([]blueprint.Variation{
2992			{Mutator: "link", Variation: "static"},
2993		}, depTag, lib)
2994	}
2995
2996	for _, lib := range deps.StaticLibs {
2997		// Some dependencies listed in static_libs might actually be rust_ffi rlib variants.
2998		depTag := libraryDependencyTag{Kind: staticLibraryDependency}
2999
3000		if inList(lib, deps.ReexportStaticLibHeaders) {
3001			depTag.reexportFlags = true
3002		}
3003		if inList(lib, deps.ExcludeLibsForApex) {
3004			depTag.excludeInApex = true
3005		}
3006		actx.AddVariationDependencies([]blueprint.Variation{
3007			{Mutator: "link", Variation: "static"},
3008		}, depTag, lib)
3009	}
3010
3011	// staticUnwinderDep is treated as staticDep for Q apexes
3012	// so that native libraries/binaries are linked with static unwinder
3013	// because Q libc doesn't have unwinder APIs
3014	if deps.StaticUnwinderIfLegacy {
3015		depTag := libraryDependencyTag{Kind: staticLibraryDependency, staticUnwinder: true}
3016		actx.AddVariationDependencies([]blueprint.Variation{
3017			{Mutator: "link", Variation: "static"},
3018		}, depTag, staticUnwinder(actx))
3019	}
3020
3021	// shared lib names without the #version suffix
3022	var sharedLibNames []string
3023
3024	for _, lib := range deps.SharedLibs {
3025		depTag := libraryDependencyTag{Kind: sharedLibraryDependency}
3026		if inList(lib, deps.ReexportSharedLibHeaders) {
3027			depTag.reexportFlags = true
3028		}
3029		if inList(lib, deps.ExcludeLibsForApex) {
3030			depTag.excludeInApex = true
3031		}
3032		if inList(lib, deps.ExcludeLibsForNonApex) {
3033			depTag.excludeInNonApex = true
3034		}
3035
3036		name, version := StubsLibNameAndVersion(lib)
3037		sharedLibNames = append(sharedLibNames, name)
3038
3039		variations := []blueprint.Variation{
3040			{Mutator: "link", Variation: "shared"},
3041		}
3042		AddSharedLibDependenciesWithVersions(ctx, c, variations, depTag, name, version, false)
3043	}
3044
3045	for _, lib := range deps.LateStaticLibs {
3046		depTag := libraryDependencyTag{Kind: staticLibraryDependency, Order: lateLibraryDependency}
3047		actx.AddVariationDependencies([]blueprint.Variation{
3048			{Mutator: "link", Variation: "static"},
3049		}, depTag, lib)
3050	}
3051
3052	for _, lib := range deps.UnexportedStaticLibs {
3053		depTag := libraryDependencyTag{Kind: staticLibraryDependency, Order: lateLibraryDependency, unexportedSymbols: true}
3054		actx.AddVariationDependencies([]blueprint.Variation{
3055			{Mutator: "link", Variation: "static"},
3056		}, depTag, lib)
3057	}
3058
3059	for _, lib := range deps.LateSharedLibs {
3060		if inList(lib, sharedLibNames) {
3061			// This is to handle the case that some of the late shared libs (libc, libdl, libm, ...)
3062			// are added also to SharedLibs with version (e.g., libc#10). If not skipped, we will be
3063			// linking against both the stubs lib and the non-stubs lib at the same time.
3064			continue
3065		}
3066		depTag := libraryDependencyTag{Kind: sharedLibraryDependency, Order: lateLibraryDependency}
3067		variations := []blueprint.Variation{
3068			{Mutator: "link", Variation: "shared"},
3069		}
3070		AddSharedLibDependenciesWithVersions(ctx, c, variations, depTag, lib, "", false)
3071	}
3072
3073	actx.AddVariationDependencies([]blueprint.Variation{
3074		{Mutator: "link", Variation: "shared"},
3075	}, dataLibDepTag, deps.DataLibs...)
3076
3077	actx.AddVariationDependencies(nil, dataBinDepTag, deps.DataBins...)
3078
3079	actx.AddVariationDependencies([]blueprint.Variation{
3080		{Mutator: "link", Variation: "shared"},
3081	}, runtimeDepTag, deps.RuntimeLibs...)
3082
3083	actx.AddDependency(c, genSourceDepTag, deps.GeneratedSources...)
3084
3085	for _, gen := range deps.GeneratedHeaders {
3086		depTag := genHeaderDepTag
3087		if inList(gen, deps.ReexportGeneratedHeaders) {
3088			depTag = genHeaderExportDepTag
3089		}
3090		actx.AddDependency(c, depTag, gen)
3091	}
3092
3093	for _, gen := range deps.DeviceFirstGeneratedHeaders {
3094		depTag := genHeaderDepTag
3095		actx.AddVariationDependencies(ctx.Config().AndroidFirstDeviceTarget.Variations(), depTag, gen)
3096	}
3097
3098	crtVariations := GetCrtVariations(ctx, c)
3099	actx.AddVariationDependencies(crtVariations, objDepTag, deps.ObjFiles...)
3100	for _, crt := range deps.CrtBegin {
3101		actx.AddVariationDependencies(crtVariations, CrtBeginDepTag,
3102			crt)
3103	}
3104	for _, crt := range deps.CrtEnd {
3105		actx.AddVariationDependencies(crtVariations, CrtEndDepTag,
3106			crt)
3107	}
3108	if deps.DynamicLinker != "" {
3109		actx.AddDependency(c, dynamicLinkerDepTag, deps.DynamicLinker)
3110	}
3111
3112	version := ctx.sdkVersion()
3113
3114	ndkStubDepTag := libraryDependencyTag{Kind: sharedLibraryDependency, ndk: true, makeSuffix: "." + version}
3115	actx.AddVariationDependencies([]blueprint.Variation{
3116		{Mutator: "version", Variation: version},
3117		{Mutator: "link", Variation: "shared"},
3118	}, ndkStubDepTag, variantNdkLibs...)
3119	actx.AddVariationDependencies([]blueprint.Variation{
3120		{Mutator: "version", Variation: version},
3121		{Mutator: "link", Variation: "shared"},
3122	}, ndkStubDepTag, apiNdkLibs...)
3123
3124	ndkLateStubDepTag := libraryDependencyTag{Kind: sharedLibraryDependency, Order: lateLibraryDependency, ndk: true, makeSuffix: "." + version}
3125	actx.AddVariationDependencies([]blueprint.Variation{
3126		{Mutator: "version", Variation: version},
3127		{Mutator: "link", Variation: "shared"},
3128	}, ndkLateStubDepTag, variantLateNdkLibs...)
3129	actx.AddVariationDependencies([]blueprint.Variation{
3130		{Mutator: "version", Variation: version},
3131		{Mutator: "link", Variation: "shared"},
3132	}, ndkLateStubDepTag, apiLateNdkLibs...)
3133
3134	if len(deps.AidlLibs) > 0 {
3135		actx.AddDependency(
3136			c,
3137			aidlLibraryTag,
3138			deps.AidlLibs...,
3139		)
3140	}
3141
3142}
3143
3144func BeginMutator(ctx android.BottomUpMutatorContext) {
3145	if c, ok := ctx.Module().(*Module); ok && c.Enabled(ctx) {
3146		c.beginMutator(ctx)
3147	}
3148}
3149
3150// Whether a module can link to another module, taking into
3151// account NDK linking.
3152func checkLinkType(ctx android.BaseModuleContext, from LinkableInterface, to LinkableInterface,
3153	tag blueprint.DependencyTag) {
3154
3155	switch t := tag.(type) {
3156	case dependencyTag:
3157		if t != vndkExtDepTag {
3158			return
3159		}
3160	case libraryDependencyTag:
3161	default:
3162		return
3163	}
3164
3165	if from.Target().Os != android.Android {
3166		// Host code is not restricted
3167		return
3168	}
3169
3170	if from.SdkVersion() == "" {
3171		// Platform code can link to anything
3172		return
3173	}
3174	if from.InRamdisk() {
3175		// Ramdisk code is not NDK
3176		return
3177	}
3178	if from.InVendorRamdisk() {
3179		// Vendor ramdisk code is not NDK
3180		return
3181	}
3182	if from.InRecovery() {
3183		// Recovery code is not NDK
3184		return
3185	}
3186	// Change this to LinkableInterface if Rust gets NDK support, which stubDecorators are for
3187	if c, ok := to.(*Module); ok {
3188		if c.StubDecorator() {
3189			// These aren't real libraries, but are the stub shared libraries that are included in
3190			// the NDK.
3191			return
3192		}
3193	}
3194
3195	if strings.HasPrefix(ctx.ModuleName(), "libclang_rt.") && to.Module().Name() == "libc++" {
3196		// Bug: http://b/121358700 - Allow libclang_rt.* shared libraries (with sdk_version)
3197		// to link to libc++ (non-NDK and without sdk_version).
3198		return
3199	}
3200
3201	if to.SdkVersion() == "" {
3202		// NDK code linking to platform code is never okay.
3203		ctx.ModuleErrorf("depends on non-NDK-built library %q",
3204			ctx.OtherModuleName(to.Module()))
3205		return
3206	}
3207
3208	// At this point we know we have two NDK libraries, but we need to
3209	// check that we're not linking against anything built against a higher
3210	// API level, as it is only valid to link against older or equivalent
3211	// APIs.
3212
3213	// Current can link against anything.
3214	if from.SdkVersion() != "current" {
3215		// Otherwise we need to check.
3216		if to.SdkVersion() == "current" {
3217			// Current can't be linked against by anything else.
3218			ctx.ModuleErrorf("links %q built against newer API version %q",
3219				ctx.OtherModuleName(to.Module()), "current")
3220		} else {
3221			fromApi, err := android.ApiLevelFromUserWithConfig(ctx.Config(), from.SdkVersion())
3222			if err != nil {
3223				ctx.PropertyErrorf("sdk_version",
3224					"Invalid sdk_version value (must be int, preview or current): %q",
3225					from.SdkVersion())
3226			}
3227			toApi, err := android.ApiLevelFromUserWithConfig(ctx.Config(), to.SdkVersion())
3228			if err != nil {
3229				ctx.PropertyErrorf("sdk_version",
3230					"Invalid sdk_version value (must be int, preview or current): %q",
3231					to.SdkVersion())
3232			}
3233
3234			if toApi.GreaterThan(fromApi) {
3235				ctx.ModuleErrorf("links %q built against newer API version %q",
3236					ctx.OtherModuleName(to.Module()), to.SdkVersion())
3237			}
3238		}
3239	}
3240
3241	// Also check that the two STL choices are compatible.
3242	fromStl := from.SelectedStl()
3243	toStl := to.SelectedStl()
3244	if fromStl == "" || toStl == "" {
3245		// Libraries that don't use the STL are unrestricted.
3246	} else if fromStl == "ndk_system" || toStl == "ndk_system" {
3247		// We can be permissive with the system "STL" since it is only the C++
3248		// ABI layer, but in the future we should make sure that everyone is
3249		// using either libc++ or nothing.
3250	} else if getNdkStlFamily(from) != getNdkStlFamily(to) {
3251		ctx.ModuleErrorf("uses %q and depends on %q which uses incompatible %q",
3252			from.SelectedStl(), ctx.OtherModuleName(to.Module()),
3253			to.SelectedStl())
3254	}
3255}
3256
3257func checkLinkTypeMutator(ctx android.BottomUpMutatorContext) {
3258	if c, ok := ctx.Module().(*Module); ok {
3259		ctx.VisitDirectDeps(func(dep android.Module) {
3260			depTag := ctx.OtherModuleDependencyTag(dep)
3261			ccDep, ok := dep.(LinkableInterface)
3262			if ok {
3263				checkLinkType(ctx, c, ccDep, depTag)
3264			}
3265		})
3266	}
3267}
3268
3269// Tests whether the dependent library is okay to be double loaded inside a single process.
3270// If a library has a vendor variant and is a (transitive) dependency of an LLNDK library,
3271// it is subject to be double loaded. Such lib should be explicitly marked as double_loadable: true
3272// or as vndk-sp (vndk: { enabled: true, support_system_process: true}).
3273func checkDoubleLoadableLibraries(ctx android.BottomUpMutatorContext) {
3274	check := func(child, parent android.Module) bool {
3275		to, ok := child.(*Module)
3276		if !ok {
3277			return false
3278		}
3279
3280		if lib, ok := to.linker.(*libraryDecorator); !ok || !lib.shared() {
3281			return false
3282		}
3283
3284		// These dependencies are not excercised at runtime. Tracking these will give us
3285		// false negative, so skip.
3286		depTag := ctx.OtherModuleDependencyTag(child)
3287		if IsHeaderDepTag(depTag) {
3288			return false
3289		}
3290		if depTag == staticVariantTag {
3291			return false
3292		}
3293		if depTag == StubImplDepTag {
3294			return false
3295		}
3296		if depTag == android.RequiredDepTag {
3297			return false
3298		}
3299
3300		// Even if target lib has no vendor variant, keep checking dependency
3301		// graph in case it depends on vendor_available or product_available
3302		// but not double_loadable transtively.
3303		if !to.HasNonSystemVariants() {
3304			return true
3305		}
3306
3307		// The happy path. Keep tracking dependencies until we hit a non double-loadable
3308		// one.
3309		if Bool(to.VendorProperties.Double_loadable) {
3310			return true
3311		}
3312
3313		if to.IsLlndk() {
3314			return false
3315		}
3316
3317		ctx.ModuleErrorf("links a library %q which is not LL-NDK, "+
3318			"VNDK-SP, or explicitly marked as 'double_loadable:true'. "+
3319			"Dependency list: %s", ctx.OtherModuleName(to), ctx.GetPathString(false))
3320		return false
3321	}
3322	if module, ok := ctx.Module().(*Module); ok {
3323		if lib, ok := module.linker.(*libraryDecorator); ok && lib.shared() {
3324			if lib.HasLLNDKStubs() {
3325				ctx.WalkDeps(check)
3326			}
3327		}
3328	}
3329}
3330
3331func findApexSdkVersion(ctx android.BaseModuleContext, apexInfo android.ApexInfo) android.ApiLevel {
3332	// For the dependency from platform to apex, use the latest stubs
3333	apexSdkVersion := android.FutureApiLevel
3334	if !apexInfo.IsForPlatform() {
3335		apexSdkVersion = apexInfo.MinSdkVersion
3336	}
3337
3338	if android.InList("hwaddress", ctx.Config().SanitizeDevice()) {
3339		// In hwasan build, we override apexSdkVersion to the FutureApiLevel(10000)
3340		// so that even Q(29/Android10) apexes could use the dynamic unwinder by linking the newer stubs(e.g libc(R+)).
3341		// (b/144430859)
3342		apexSdkVersion = android.FutureApiLevel
3343	}
3344
3345	return apexSdkVersion
3346}
3347
3348// Convert dependencies to paths.  Returns a PathDeps containing paths
3349func (c *Module) depsToPaths(ctx android.ModuleContext) PathDeps {
3350	var depPaths PathDeps
3351
3352	var directStaticDeps []StaticLibraryInfo
3353	var directSharedDeps []SharedLibraryInfo
3354
3355	reexportExporter := func(exporter FlagExporterInfo) {
3356		depPaths.ReexportedDirs = append(depPaths.ReexportedDirs, exporter.IncludeDirs...)
3357		depPaths.ReexportedSystemDirs = append(depPaths.ReexportedSystemDirs, exporter.SystemIncludeDirs...)
3358		depPaths.ReexportedFlags = append(depPaths.ReexportedFlags, exporter.Flags...)
3359		depPaths.ReexportedDeps = append(depPaths.ReexportedDeps, exporter.Deps...)
3360		depPaths.ReexportedGeneratedHeaders = append(depPaths.ReexportedGeneratedHeaders, exporter.GeneratedHeaders...)
3361	}
3362
3363	apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider)
3364	c.apexSdkVersion = findApexSdkVersion(ctx, apexInfo)
3365
3366	skipModuleList := map[string]bool{}
3367
3368	ctx.VisitDirectDepsProxy(func(dep android.ModuleProxy) {
3369		depName := ctx.OtherModuleName(dep)
3370		depTag := ctx.OtherModuleDependencyTag(dep)
3371
3372		if _, ok := skipModuleList[depName]; ok {
3373			// skip this module because original module or API imported module matching with this should be used instead.
3374			return
3375		}
3376
3377		var ccInfo *CcInfo
3378		v, hasCcInfo := android.OtherModuleProvider(ctx, dep, CcInfoProvider)
3379		if hasCcInfo {
3380			ccInfo = v
3381		}
3382		linkableInfo, hasLinkableInfo := android.OtherModuleProvider(ctx, dep, LinkableInfoProvider)
3383		if depTag == android.DarwinUniversalVariantTag {
3384			if !hasCcInfo {
3385				panic(fmt.Errorf("dep is not a cc module: %s", dep.String()))
3386			}
3387			depPaths.DarwinSecondArchOutput = linkableInfo.OutputFile
3388			return
3389		}
3390
3391		if depTag == aidlLibraryTag {
3392			if aidlLibraryInfo, ok := android.OtherModuleProvider(ctx, dep, aidl_library.AidlLibraryProvider); ok {
3393				depPaths.AidlLibraryInfos = append(
3394					depPaths.AidlLibraryInfos,
3395					aidlLibraryInfo,
3396				)
3397			}
3398		}
3399
3400		if !hasLinkableInfo {
3401			// handling for a few module types that aren't cc Module but that are also supported
3402			genRule, ok := android.OtherModuleProvider(ctx, dep, android.GeneratedSourceInfoProvider)
3403			switch depTag {
3404			case genSourceDepTag:
3405				if ok {
3406					depPaths.GeneratedSources = append(depPaths.GeneratedSources,
3407						genRule.GeneratedSourceFiles...)
3408				} else {
3409					ctx.ModuleErrorf("module %q is not a gensrcs or genrule", depName)
3410				}
3411				// Support exported headers from a generated_sources dependency
3412				fallthrough
3413			case genHeaderDepTag, genHeaderExportDepTag:
3414				if ok {
3415					depPaths.GeneratedDeps = append(depPaths.GeneratedDeps,
3416						genRule.GeneratedDeps...)
3417					dirs := genRule.GeneratedHeaderDirs
3418					depPaths.IncludeDirs = append(depPaths.IncludeDirs, dirs...)
3419					if depTag == genHeaderExportDepTag {
3420						depPaths.ReexportedDirs = append(depPaths.ReexportedDirs, dirs...)
3421						depPaths.ReexportedGeneratedHeaders = append(depPaths.ReexportedGeneratedHeaders,
3422							genRule.GeneratedSourceFiles...)
3423						depPaths.ReexportedDeps = append(depPaths.ReexportedDeps, genRule.GeneratedDeps...)
3424						// Add these re-exported flags to help header-abi-dumper to infer the abi exported by a library.
3425						c.sabi.Properties.ReexportedIncludes = append(c.sabi.Properties.ReexportedIncludes, dirs.Strings()...)
3426					}
3427				} else {
3428					ctx.ModuleErrorf("module %q is not a genrule", depName)
3429				}
3430			case CrtBeginDepTag:
3431				depPaths.CrtBegin = append(depPaths.CrtBegin, android.OutputFileForModule(ctx, dep, ""))
3432			case CrtEndDepTag:
3433				depPaths.CrtEnd = append(depPaths.CrtEnd, android.OutputFileForModule(ctx, dep, ""))
3434			}
3435			return
3436		}
3437
3438		if depTag == android.ProtoPluginDepTag {
3439			return
3440		}
3441
3442		if depTag == android.RequiredDepTag {
3443			return
3444		}
3445
3446		commonInfo := android.OtherModulePointerProviderOrDefault(ctx, dep, android.CommonModuleInfoProvider)
3447		if commonInfo.Target.Os != ctx.Os() {
3448			ctx.ModuleErrorf("OS mismatch between %q (%s) and %q (%s)", ctx.ModuleName(), ctx.Os().Name, depName, dep.Target().Os.Name)
3449			return
3450		}
3451		if commonInfo.Target.Arch.ArchType != ctx.Arch().ArchType {
3452			ctx.ModuleErrorf("Arch mismatch between %q(%v) and %q(%v)",
3453				ctx.ModuleName(), ctx.Arch().ArchType, depName, commonInfo.Target.Arch.ArchType)
3454			return
3455		}
3456
3457		if depTag == reuseObjTag {
3458			// Skip reused objects for stub libraries, they use their own stub object file instead.
3459			// The reuseObjTag dependency still exists because the LinkageMutator runs before the
3460			// version mutator, so the stubs variant is created from the shared variant that
3461			// already has the reuseObjTag dependency on the static variant.
3462			if !c.library.BuildStubs() {
3463				staticAnalogue, _ := android.OtherModuleProvider(ctx, dep, StaticLibraryInfoProvider)
3464				objs := staticAnalogue.ReuseObjects
3465				depPaths.Objs = depPaths.Objs.Append(objs)
3466				depExporterInfo, _ := android.OtherModuleProvider(ctx, dep, FlagExporterInfoProvider)
3467				reexportExporter(depExporterInfo)
3468			}
3469			return
3470		}
3471
3472		if depTag == llndkHeaderLibTag {
3473			depExporterInfo, _ := android.OtherModuleProvider(ctx, dep, FlagExporterInfoProvider)
3474			depPaths.LlndkIncludeDirs = append(depPaths.LlndkIncludeDirs, depExporterInfo.IncludeDirs...)
3475			depPaths.LlndkSystemIncludeDirs = append(depPaths.LlndkSystemIncludeDirs, depExporterInfo.SystemIncludeDirs...)
3476		}
3477
3478		linkFile := linkableInfo.OutputFile
3479
3480		if libDepTag, ok := depTag.(libraryDependencyTag); ok {
3481			// Only use static unwinder for legacy (min_sdk_version = 29) apexes (b/144430859)
3482			if libDepTag.staticUnwinder && c.apexSdkVersion.GreaterThan(android.SdkVersion_Android10) {
3483				return
3484			}
3485
3486			if !apexInfo.IsForPlatform() && libDepTag.excludeInApex {
3487				return
3488			}
3489			if apexInfo.IsForPlatform() && libDepTag.excludeInNonApex {
3490				return
3491			}
3492
3493			depExporterInfo, _ := android.OtherModuleProvider(ctx, dep, FlagExporterInfoProvider)
3494
3495			var ptr *android.Paths
3496			var depPtr *android.Paths
3497
3498			depFile := android.OptionalPath{}
3499
3500			switch {
3501			case libDepTag.header():
3502				if _, isHeaderLib := android.OtherModuleProvider(ctx, dep, HeaderLibraryInfoProvider); !isHeaderLib {
3503					if !ctx.Config().AllowMissingDependencies() {
3504						ctx.ModuleErrorf("module %q is not a header library", depName)
3505					} else {
3506						ctx.AddMissingDependencies([]string{depName})
3507					}
3508					return
3509				}
3510			case libDepTag.shared():
3511				if _, isSharedLib := android.OtherModuleProvider(ctx, dep, SharedLibraryInfoProvider); !isSharedLib {
3512					if !ctx.Config().AllowMissingDependencies() {
3513						ctx.ModuleErrorf("module %q is not a shared library", depName)
3514					} else {
3515						ctx.AddMissingDependencies([]string{depName})
3516					}
3517					return
3518				}
3519
3520				sharedLibraryInfo, returnedDepExporterInfo := ChooseStubOrImpl(ctx, dep)
3521				depExporterInfo = returnedDepExporterInfo
3522
3523				// Stubs lib doesn't link to the shared lib dependencies. Don't set
3524				// linkFile, depFile, and ptr.
3525				if c.IsStubs() {
3526					break
3527				}
3528
3529				linkFile = android.OptionalPathForPath(sharedLibraryInfo.SharedLibrary)
3530				depFile = sharedLibraryInfo.TableOfContents
3531
3532				if !sharedLibraryInfo.IsStubs {
3533					// TODO(b/362509506): remove this additional check once all apex_exclude uses are switched to stubs.
3534					if !linkableInfo.RustApexExclude {
3535						depPaths.directImplementationDeps = append(depPaths.directImplementationDeps, android.OutputFileForModule(ctx, dep, ""))
3536						if info, ok := android.OtherModuleProvider(ctx, dep, ImplementationDepInfoProvider); ok {
3537							depPaths.transitiveImplementationDeps = append(depPaths.transitiveImplementationDeps, info.ImplementationDeps)
3538						}
3539					}
3540				}
3541
3542				ptr = &depPaths.SharedLibs
3543				switch libDepTag.Order {
3544				case earlyLibraryDependency:
3545					ptr = &depPaths.EarlySharedLibs
3546					depPtr = &depPaths.EarlySharedLibsDeps
3547				case normalLibraryDependency:
3548					ptr = &depPaths.SharedLibs
3549					depPtr = &depPaths.SharedLibsDeps
3550					directSharedDeps = append(directSharedDeps, sharedLibraryInfo)
3551				case lateLibraryDependency:
3552					ptr = &depPaths.LateSharedLibs
3553					depPtr = &depPaths.LateSharedLibsDeps
3554				default:
3555					panic(fmt.Errorf("unexpected library dependency order %d", libDepTag.Order))
3556				}
3557
3558			case libDepTag.static():
3559				if linkableInfo.RustLibraryInterface {
3560					rlibDep := RustRlibDep{LibPath: linkFile.Path(), CrateName: linkableInfo.CrateName, LinkDirs: linkableInfo.ExportedCrateLinkDirs}
3561					depPaths.RustRlibDeps = append(depPaths.RustRlibDeps, rlibDep)
3562					depPaths.IncludeDirs = append(depPaths.IncludeDirs, depExporterInfo.IncludeDirs...)
3563					if libDepTag.wholeStatic {
3564						depPaths.ReexportedDirs = append(depPaths.ReexportedDirs, depExporterInfo.IncludeDirs...)
3565						depPaths.ReexportedRustRlibDeps = append(depPaths.ReexportedRustRlibDeps, rlibDep)
3566
3567						// If whole_static, track this as we want to make sure that in a final linkage for a shared library,
3568						// exported functions from the rust generated staticlib still exported.
3569						if c.CcLibrary() && c.Shared() {
3570							c.WholeRustStaticlib = true
3571						}
3572					}
3573
3574				} else {
3575					staticLibraryInfo, isStaticLib := android.OtherModuleProvider(ctx, dep, StaticLibraryInfoProvider)
3576					if !isStaticLib {
3577						if !ctx.Config().AllowMissingDependencies() {
3578							ctx.ModuleErrorf("module %q is not a static library", depName)
3579						} else {
3580							ctx.AddMissingDependencies([]string{depName})
3581						}
3582						return
3583					}
3584
3585					// Stubs lib doesn't link to the static lib dependencies. Don't set
3586					// linkFile, depFile, and ptr.
3587					if c.IsStubs() {
3588						break
3589					}
3590
3591					linkFile = android.OptionalPathForPath(staticLibraryInfo.StaticLibrary)
3592					if libDepTag.wholeStatic {
3593						ptr = &depPaths.WholeStaticLibs
3594						if len(staticLibraryInfo.Objects.objFiles) > 0 {
3595							depPaths.WholeStaticLibObjs = depPaths.WholeStaticLibObjs.Append(staticLibraryInfo.Objects)
3596						} else {
3597							// This case normally catches prebuilt static
3598							// libraries, but it can also occur when
3599							// AllowMissingDependencies is on and the
3600							// dependencies has no sources of its own
3601							// but has a whole_static_libs dependency
3602							// on a missing library.  We want to depend
3603							// on the .a file so that there is something
3604							// in the dependency tree that contains the
3605							// error rule for the missing transitive
3606							// dependency.
3607							depPaths.WholeStaticLibsFromPrebuilts = append(depPaths.WholeStaticLibsFromPrebuilts, linkFile.Path())
3608						}
3609						depPaths.WholeStaticLibsFromPrebuilts = append(depPaths.WholeStaticLibsFromPrebuilts,
3610							staticLibraryInfo.WholeStaticLibsFromPrebuilts...)
3611					} else {
3612						switch libDepTag.Order {
3613						case earlyLibraryDependency:
3614							panic(fmt.Errorf("early static libs not supported"))
3615						case normalLibraryDependency:
3616							// static dependencies will be handled separately so they can be ordered
3617							// using transitive dependencies.
3618							ptr = nil
3619							directStaticDeps = append(directStaticDeps, staticLibraryInfo)
3620						case lateLibraryDependency:
3621							ptr = &depPaths.LateStaticLibs
3622						default:
3623							panic(fmt.Errorf("unexpected library dependency order %d", libDepTag.Order))
3624						}
3625					}
3626
3627					// Collect any exported Rust rlib deps from static libraries which have been included as whole_static_libs
3628					depPaths.RustRlibDeps = append(depPaths.RustRlibDeps, depExporterInfo.RustRlibDeps...)
3629
3630					if libDepTag.unexportedSymbols {
3631						depPaths.LdFlags = append(depPaths.LdFlags,
3632							"-Wl,--exclude-libs="+staticLibraryInfo.StaticLibrary.Base())
3633					}
3634				}
3635			}
3636
3637			if libDepTag.static() && !libDepTag.wholeStatic && !linkableInfo.RustLibraryInterface {
3638				if !linkableInfo.CcLibraryInterface || !linkableInfo.Static {
3639					ctx.ModuleErrorf("module %q not a static library", depName)
3640					return
3641				}
3642
3643				// When combining coverage files for shared libraries and executables, coverage files
3644				// in static libraries act as if they were whole static libraries. The same goes for
3645				// source based Abi dump files.
3646				if hasCcInfo {
3647					depPaths.StaticLibObjs.coverageFiles = append(depPaths.StaticLibObjs.coverageFiles,
3648						linkableInfo.CoverageFiles...)
3649					depPaths.StaticLibObjs.sAbiDumpFiles = append(depPaths.StaticLibObjs.sAbiDumpFiles,
3650						linkableInfo.SAbiDumpFiles...)
3651				} else {
3652					// Handle non-CC modules here
3653					depPaths.StaticLibObjs.coverageFiles = append(depPaths.StaticLibObjs.coverageFiles,
3654						linkableInfo.CoverageFiles...)
3655				}
3656			}
3657
3658			if ptr != nil {
3659				if !linkFile.Valid() {
3660					if !ctx.Config().AllowMissingDependencies() {
3661						ctx.ModuleErrorf("module %q missing output file", depName)
3662					} else {
3663						ctx.AddMissingDependencies([]string{depName})
3664					}
3665					return
3666				}
3667				*ptr = append(*ptr, linkFile.Path())
3668			}
3669
3670			if depPtr != nil {
3671				dep := depFile
3672				if !dep.Valid() {
3673					dep = linkFile
3674				}
3675				*depPtr = append(*depPtr, dep.Path())
3676			}
3677
3678			depPaths.IncludeDirs = append(depPaths.IncludeDirs, depExporterInfo.IncludeDirs...)
3679			depPaths.SystemIncludeDirs = append(depPaths.SystemIncludeDirs, depExporterInfo.SystemIncludeDirs...)
3680			depPaths.GeneratedDeps = append(depPaths.GeneratedDeps, depExporterInfo.Deps...)
3681			depPaths.Flags = append(depPaths.Flags, depExporterInfo.Flags...)
3682			depPaths.RustRlibDeps = append(depPaths.RustRlibDeps, depExporterInfo.RustRlibDeps...)
3683
3684			// Only re-export RustRlibDeps for cc static libs
3685			if c.static() {
3686				depPaths.ReexportedRustRlibDeps = append(depPaths.ReexportedRustRlibDeps, depExporterInfo.RustRlibDeps...)
3687			}
3688
3689			if libDepTag.reexportFlags {
3690				reexportExporter(depExporterInfo)
3691				// Add these re-exported flags to help header-abi-dumper to infer the abi exported by a library.
3692				// Re-exported shared library headers must be included as well since they can help us with type information
3693				// about template instantiations (instantiated from their headers).
3694				c.sabi.Properties.ReexportedIncludes = append(
3695					c.sabi.Properties.ReexportedIncludes, depExporterInfo.IncludeDirs.Strings()...)
3696				c.sabi.Properties.ReexportedSystemIncludes = append(
3697					c.sabi.Properties.ReexportedSystemIncludes, depExporterInfo.SystemIncludeDirs.Strings()...)
3698			}
3699
3700			makeLibName := MakeLibName(ccInfo, linkableInfo, commonInfo, commonInfo.BaseModuleName) + libDepTag.makeSuffix
3701			switch {
3702			case libDepTag.header():
3703				c.Properties.AndroidMkHeaderLibs = append(
3704					c.Properties.AndroidMkHeaderLibs, makeLibName)
3705			case libDepTag.shared():
3706				// Note: the order of libs in this list is not important because
3707				// they merely serve as Make dependencies and do not affect this lib itself.
3708				c.Properties.AndroidMkSharedLibs = append(
3709					c.Properties.AndroidMkSharedLibs, makeLibName)
3710			case libDepTag.static():
3711				if !linkableInfo.RustLibraryInterface {
3712					if libDepTag.wholeStatic {
3713						c.Properties.AndroidMkWholeStaticLibs = append(
3714							c.Properties.AndroidMkWholeStaticLibs, makeLibName)
3715					} else {
3716						c.Properties.AndroidMkStaticLibs = append(
3717							c.Properties.AndroidMkStaticLibs, makeLibName)
3718					}
3719				}
3720			}
3721		} else if !c.IsStubs() {
3722			// Stubs lib doesn't link to the runtime lib, object, crt, etc. dependencies.
3723
3724			switch depTag {
3725			case runtimeDepTag:
3726				c.Properties.AndroidMkRuntimeLibs = append(
3727					c.Properties.AndroidMkRuntimeLibs, MakeLibName(ccInfo, linkableInfo, commonInfo,
3728						commonInfo.BaseModuleName)+libDepTag.makeSuffix)
3729			case objDepTag:
3730				depPaths.Objs.objFiles = append(depPaths.Objs.objFiles, linkFile.Path())
3731			case CrtBeginDepTag:
3732				depPaths.CrtBegin = append(depPaths.CrtBegin, linkFile.Path())
3733			case CrtEndDepTag:
3734				depPaths.CrtEnd = append(depPaths.CrtEnd, linkFile.Path())
3735			case dynamicLinkerDepTag:
3736				depPaths.DynamicLinker = linkFile
3737			}
3738		}
3739	})
3740
3741	// use the ordered dependencies as this module's dependencies
3742	orderedStaticPaths, transitiveStaticLibs := orderStaticModuleDeps(directStaticDeps, directSharedDeps)
3743	depPaths.TranstiveStaticLibrariesForOrdering = transitiveStaticLibs
3744	depPaths.StaticLibs = append(depPaths.StaticLibs, orderedStaticPaths...)
3745
3746	// Dedup exported flags from dependencies
3747	depPaths.Flags = android.FirstUniqueStrings(depPaths.Flags)
3748	depPaths.IncludeDirs = android.FirstUniquePaths(depPaths.IncludeDirs)
3749	depPaths.SystemIncludeDirs = android.FirstUniquePaths(depPaths.SystemIncludeDirs)
3750	depPaths.GeneratedDeps = android.FirstUniquePaths(depPaths.GeneratedDeps)
3751	depPaths.RustRlibDeps = android.FirstUniqueFunc(depPaths.RustRlibDeps, EqRustRlibDeps)
3752
3753	depPaths.ReexportedDirs = android.FirstUniquePaths(depPaths.ReexportedDirs)
3754	depPaths.ReexportedSystemDirs = android.FirstUniquePaths(depPaths.ReexportedSystemDirs)
3755	depPaths.ReexportedFlags = android.FirstUniqueStrings(depPaths.ReexportedFlags)
3756	depPaths.ReexportedDeps = android.FirstUniquePaths(depPaths.ReexportedDeps)
3757	depPaths.ReexportedGeneratedHeaders = android.FirstUniquePaths(depPaths.ReexportedGeneratedHeaders)
3758	depPaths.ReexportedRustRlibDeps = android.FirstUniqueFunc(depPaths.ReexportedRustRlibDeps, EqRustRlibDeps)
3759
3760	if c.sabi != nil {
3761		c.sabi.Properties.ReexportedIncludes = android.FirstUniqueStrings(c.sabi.Properties.ReexportedIncludes)
3762		c.sabi.Properties.ReexportedSystemIncludes = android.FirstUniqueStrings(c.sabi.Properties.ReexportedSystemIncludes)
3763	}
3764
3765	return depPaths
3766}
3767
3768func ShouldUseStubForApex(ctx android.ModuleContext, parent android.Module, dep android.ModuleProxy) bool {
3769	inVendorOrProduct := false
3770	bootstrap := false
3771	if android.EqualModules(ctx.Module(), parent) {
3772		if linkable, ok := parent.(LinkableInterface); !ok {
3773			ctx.ModuleErrorf("Not a Linkable module: %q", ctx.ModuleName())
3774		} else {
3775			inVendorOrProduct = linkable.InVendorOrProduct()
3776			bootstrap = linkable.Bootstrap()
3777		}
3778	} else {
3779		if linkable, ok := android.OtherModuleProvider(ctx, parent, LinkableInfoProvider); !ok {
3780			ctx.ModuleErrorf("Not a Linkable module: %q", ctx.ModuleName())
3781		} else {
3782			inVendorOrProduct = linkable.InVendorOrProduct
3783			bootstrap = linkable.Bootstrap
3784		}
3785	}
3786
3787	apexInfo, _ := android.OtherModuleProvider(ctx, parent, android.ApexInfoProvider)
3788
3789	useStubs := false
3790
3791	if android.OtherModuleProviderOrDefault(ctx, dep, LinkableInfoProvider).IsStubs && inVendorOrProduct { // LLNDK
3792		if !apexInfo.IsForPlatform() {
3793			// For platform libraries, use current version of LLNDK
3794			// If this is for use_vendor apex we will apply the same rules
3795			// of apex sdk enforcement below to choose right version.
3796			useStubs = true
3797		}
3798	} else if apexInfo.IsForPlatform() || apexInfo.UsePlatformApis {
3799		// If not building for APEX or the containing APEX allows the use of
3800		// platform APIs, use stubs only when it is from an APEX (and not from
3801		// platform) However, for host, ramdisk, vendor_ramdisk, recovery or
3802		// bootstrap modules, always link to non-stub variant
3803		isNotInPlatform := android.OtherModulePointerProviderOrDefault(ctx, dep, android.CommonModuleInfoProvider).NotInPlatform
3804
3805		useStubs = isNotInPlatform && !bootstrap
3806	} else {
3807		// If building for APEX, always use stubs (can be bypassed by depending on <dep>#impl)
3808		useStubs = true
3809	}
3810
3811	return useStubs
3812}
3813
3814// ChooseStubOrImpl determines whether a given dependency should be redirected to the stub variant
3815// of the dependency or not, and returns the SharedLibraryInfo and FlagExporterInfo for the right
3816// dependency. The stub variant is selected when the dependency crosses a boundary where each side
3817// has different level of updatability. For example, if a library foo in an APEX depends on a
3818// library bar which provides stable interface and exists in the platform, foo uses the stub variant
3819// of bar. If bar doesn't provide a stable interface (i.e. buildStubs() == false) or is in the
3820// same APEX as foo, the non-stub variant of bar is used.
3821func ChooseStubOrImpl(ctx android.ModuleContext, dep android.ModuleProxy) (SharedLibraryInfo, FlagExporterInfo) {
3822	depTag := ctx.OtherModuleDependencyTag(dep)
3823	libDepTag, ok := depTag.(libraryDependencyTag)
3824	if !ok || !libDepTag.shared() {
3825		panic(fmt.Errorf("Unexpected dependency tag: %T", depTag))
3826	}
3827
3828	sharedLibraryInfo, _ := android.OtherModuleProvider(ctx, dep, SharedLibraryInfoProvider)
3829	depExporterInfo, _ := android.OtherModuleProvider(ctx, dep, FlagExporterInfoProvider)
3830	sharedLibraryStubsInfo, _ := android.OtherModuleProvider(ctx, dep, SharedLibraryStubsProvider)
3831
3832	if !libDepTag.explicitlyVersioned && len(sharedLibraryStubsInfo.SharedStubLibraries) > 0 {
3833		// when to use (unspecified) stubs, use the latest one.
3834		if ShouldUseStubForApex(ctx, ctx.Module(), dep) {
3835			stubs := sharedLibraryStubsInfo.SharedStubLibraries
3836			toUse := stubs[len(stubs)-1]
3837			sharedLibraryInfo = toUse.SharedLibraryInfo
3838			depExporterInfo = toUse.FlagExporterInfo
3839		}
3840	}
3841	return sharedLibraryInfo, depExporterInfo
3842}
3843
3844// orderStaticModuleDeps rearranges the order of the static library dependencies of the module
3845// to match the topological order of the dependency tree, including any static analogues of
3846// direct shared libraries.  It returns the ordered static dependencies, and a depset.DepSet
3847// of the transitive dependencies.
3848func orderStaticModuleDeps(staticDeps []StaticLibraryInfo, sharedDeps []SharedLibraryInfo) (ordered android.Paths, transitive depset.DepSet[android.Path]) {
3849	transitiveStaticLibsBuilder := depset.NewBuilder[android.Path](depset.TOPOLOGICAL)
3850	var staticPaths android.Paths
3851	for _, staticDep := range staticDeps {
3852		staticPaths = append(staticPaths, staticDep.StaticLibrary)
3853		transitiveStaticLibsBuilder.Transitive(staticDep.TransitiveStaticLibrariesForOrdering)
3854	}
3855	for _, sharedDep := range sharedDeps {
3856		transitiveStaticLibsBuilder.Transitive(sharedDep.TransitiveStaticLibrariesForOrdering)
3857	}
3858	transitiveStaticLibs := transitiveStaticLibsBuilder.Build()
3859
3860	orderedTransitiveStaticLibs := transitiveStaticLibs.ToList()
3861
3862	// reorder the dependencies based on transitive dependencies
3863	staticPaths = android.FirstUniquePaths(staticPaths)
3864	_, orderedStaticPaths := android.FilterPathList(orderedTransitiveStaticLibs, staticPaths)
3865
3866	if len(orderedStaticPaths) != len(staticPaths) {
3867		missing, _ := android.FilterPathList(staticPaths, orderedStaticPaths)
3868		panic(fmt.Errorf("expected %d ordered static paths , got %d, missing %q %q %q", len(staticPaths), len(orderedStaticPaths), missing, orderedStaticPaths, staticPaths))
3869	}
3870
3871	return orderedStaticPaths, transitiveStaticLibs
3872}
3873
3874// BaseLibName trims known prefixes and suffixes
3875func BaseLibName(depName string) string {
3876	libName := strings.TrimSuffix(depName, llndkLibrarySuffix)
3877	libName = strings.TrimSuffix(libName, vendorPublicLibrarySuffix)
3878	libName = android.RemoveOptionalPrebuiltPrefix(libName)
3879	return libName
3880}
3881
3882func MakeLibName(ccInfo *CcInfo, linkableInfo *LinkableInfo, commonInfo *android.CommonModuleInfo, depName string) string {
3883	libName := BaseLibName(depName)
3884	isLLndk := ccInfo != nil && linkableInfo.IsLlndk
3885	nonSystemVariantsExist := linkableInfo.HasNonSystemVariants || isLLndk
3886
3887	if ccInfo != nil {
3888		// Use base module name for snapshots when exporting to Makefile.
3889		if ccInfo.SnapshotInfo != nil {
3890			return commonInfo.BaseModuleName + ccInfo.SnapshotInfo.SnapshotAndroidMkSuffix
3891		}
3892	}
3893
3894	if linkableInfo.InVendorOrProduct && nonSystemVariantsExist {
3895		// The vendor and product modules in Make will have been renamed to not conflict with the
3896		// core module, so update the dependency name here accordingly.
3897		return libName + linkableInfo.SubName
3898	} else if linkableInfo.InRamdisk && !linkableInfo.OnlyInRamdisk {
3899		return libName + RamdiskSuffix
3900	} else if linkableInfo.InVendorRamdisk && !linkableInfo.OnlyInVendorRamdisk {
3901		return libName + VendorRamdiskSuffix
3902	} else if linkableInfo.InRecovery && !linkableInfo.OnlyInRecovery {
3903		return libName + RecoverySuffix
3904	} else if commonInfo.Target.NativeBridge == android.NativeBridgeEnabled {
3905		return libName + NativeBridgeSuffix
3906	} else {
3907		return libName
3908	}
3909}
3910
3911func (c *Module) InstallInData() bool {
3912	if c.installer == nil {
3913		return false
3914	}
3915	return c.installer.inData()
3916}
3917
3918func (c *Module) InstallInSanitizerDir() bool {
3919	if c.installer == nil {
3920		return false
3921	}
3922	if c.sanitize != nil && c.sanitize.inSanitizerDir() {
3923		return true
3924	}
3925	return c.installer.inSanitizerDir()
3926}
3927
3928func (c *Module) InstallInRamdisk() bool {
3929	return c.InRamdisk()
3930}
3931
3932func (c *Module) InstallInVendorRamdisk() bool {
3933	return c.InVendorRamdisk()
3934}
3935
3936func (c *Module) InstallInRecovery() bool {
3937	return c.InRecovery()
3938}
3939
3940func (c *Module) MakeUninstallable() {
3941	if c.installer == nil {
3942		c.ModuleBase.MakeUninstallable()
3943		return
3944	}
3945	c.installer.makeUninstallable(c)
3946}
3947
3948func (c *Module) HostToolPath() android.OptionalPath {
3949	if c.installer == nil {
3950		return android.OptionalPath{}
3951	}
3952	return c.installer.hostToolPath()
3953}
3954
3955func (c *Module) IntermPathForModuleOut() android.OptionalPath {
3956	return c.outputFile
3957}
3958
3959func (c *Module) static() bool {
3960	if static, ok := c.linker.(interface {
3961		static() bool
3962	}); ok {
3963		return static.static()
3964	}
3965	return false
3966}
3967
3968func (c *Module) staticLibrary() bool {
3969	if static, ok := c.linker.(interface {
3970		staticLibrary() bool
3971	}); ok {
3972		return static.staticLibrary()
3973	}
3974	return false
3975}
3976
3977func (c *Module) staticBinary() bool {
3978	if static, ok := c.linker.(interface {
3979		staticBinary() bool
3980	}); ok {
3981		return static.staticBinary()
3982	}
3983	return false
3984}
3985
3986func (c *Module) testBinary() bool {
3987	if test, ok := c.linker.(interface {
3988		testBinary() bool
3989	}); ok {
3990		return test.testBinary()
3991	}
3992	return false
3993}
3994
3995func (c *Module) testLibrary() bool {
3996	if test, ok := c.linker.(interface {
3997		testLibrary() bool
3998	}); ok {
3999		return test.testLibrary()
4000	}
4001	return false
4002}
4003
4004func (c *Module) benchmarkBinary() bool {
4005	if b, ok := c.linker.(interface {
4006		benchmarkBinary() bool
4007	}); ok {
4008		return b.benchmarkBinary()
4009	}
4010	return false
4011}
4012
4013func (c *Module) fuzzBinary() bool {
4014	if f, ok := c.linker.(interface {
4015		fuzzBinary() bool
4016	}); ok {
4017		return f.fuzzBinary()
4018	}
4019	return false
4020}
4021
4022// Header returns true if the module is a header-only variant. (See cc/library.go header()).
4023func (c *Module) Header() bool {
4024	if h, ok := c.linker.(interface {
4025		header() bool
4026	}); ok {
4027		return h.header()
4028	}
4029	return false
4030}
4031
4032func (c *Module) Binary() bool {
4033	if b, ok := c.linker.(interface {
4034		binary() bool
4035	}); ok {
4036		return b.binary()
4037	}
4038	return false
4039}
4040
4041func (c *Module) ForceDisableSanitizers() {
4042	c.sanitize.Properties.ForceDisable = true
4043}
4044
4045func (c *Module) StaticExecutable() bool {
4046	if b, ok := c.linker.(*binaryDecorator); ok {
4047		return b.static()
4048	}
4049	return false
4050}
4051
4052func (c *Module) Object() bool {
4053	if o, ok := c.linker.(interface {
4054		object() bool
4055	}); ok {
4056		return o.object()
4057	}
4058	return false
4059}
4060
4061func (m *Module) Dylib() bool {
4062	return false
4063}
4064
4065func (m *Module) Rlib() bool {
4066	return false
4067}
4068
4069func GetMakeLinkType(actx android.ModuleContext, c LinkableInterface) string {
4070	if c.InVendorOrProduct() {
4071		if c.IsLlndk() {
4072			return "native:vndk"
4073		}
4074		if c.InProduct() {
4075			return "native:product"
4076		}
4077		return "native:vendor"
4078	} else if c.InRamdisk() {
4079		return "native:ramdisk"
4080	} else if c.InVendorRamdisk() {
4081		return "native:vendor_ramdisk"
4082	} else if c.InRecovery() {
4083		return "native:recovery"
4084	} else if c.Target().Os == android.Android && c.SdkVersion() != "" {
4085		return "native:ndk:none:none"
4086		// TODO(b/114741097): use the correct ndk stl once build errors have been fixed
4087		//family, link := getNdkStlFamilyAndLinkType(c)
4088		//return fmt.Sprintf("native:ndk:%s:%s", family, link)
4089	} else {
4090		return "native:platform"
4091	}
4092}
4093
4094// Overrides ApexModule.IsInstallabeToApex()
4095// Only shared/runtime libraries .
4096func (c *Module) IsInstallableToApex() bool {
4097	if lib := c.library; lib != nil {
4098		// Stub libs and prebuilt libs in a versioned SDK are not
4099		// installable to APEX even though they are shared libs.
4100		return lib.shared() && !lib.BuildStubs()
4101	}
4102	return false
4103}
4104
4105func (c *Module) AvailableFor(what string) bool {
4106	return android.CheckAvailableForApex(what, c.ApexAvailableFor())
4107}
4108
4109func (c *Module) ApexAvailableFor() []string {
4110	list := c.ApexModuleBase.ApexAvailable()
4111	if linker, ok := c.linker.(interface {
4112		apexAvailable() []string
4113	}); ok {
4114		list = append(list, linker.apexAvailable()...)
4115	}
4116
4117	return android.FirstUniqueStrings(list)
4118}
4119
4120func (c *Module) EverInstallable() bool {
4121	return c.installer != nil &&
4122		// Check to see whether the module is actually ever installable.
4123		c.installer.everInstallable()
4124}
4125
4126func (c *Module) PreventInstall() bool {
4127	return c.Properties.PreventInstall
4128}
4129
4130func (c *Module) Installable() *bool {
4131	if c.library != nil {
4132		if i := c.library.installable(); i != nil {
4133			return i
4134		}
4135	}
4136	return c.Properties.Installable
4137}
4138
4139func installable(c LinkableInterface, apexInfo android.ApexInfo) bool {
4140	ret := c.EverInstallable() &&
4141		// Check to see whether the module has been configured to not be installed.
4142		proptools.BoolDefault(c.Installable(), true) &&
4143		!c.PreventInstall() && c.OutputFile().Valid()
4144
4145	// The platform variant doesn't need further condition. Apex variants however might not
4146	// be installable because it will likely to be included in the APEX and won't appear
4147	// in the system partition.
4148	if apexInfo.IsForPlatform() {
4149		return ret
4150	}
4151
4152	return false
4153}
4154
4155func (c *Module) AndroidMkWriteAdditionalDependenciesForSourceAbiDiff(w io.Writer) {
4156	if c.linker != nil {
4157		if library, ok := c.linker.(*libraryDecorator); ok {
4158			library.androidMkWriteAdditionalDependenciesForSourceAbiDiff(w)
4159		}
4160	}
4161}
4162
4163var _ android.ApexModule = (*Module)(nil)
4164
4165// Implements android.ApexModule
4166func (c *Module) GetDepInSameApexChecker() android.DepInSameApexChecker {
4167	return CcDepInSameApexChecker{
4168		Static:           c.static(),
4169		HasStubsVariants: c.HasStubsVariants(),
4170		IsLlndk:          c.IsLlndk(),
4171		Host:             c.Host(),
4172	}
4173}
4174
4175type CcDepInSameApexChecker struct {
4176	Static           bool
4177	HasStubsVariants bool
4178	IsLlndk          bool
4179	Host             bool
4180}
4181
4182func (c CcDepInSameApexChecker) OutgoingDepIsInSameApex(depTag blueprint.DependencyTag) bool {
4183	if depTag == StubImplDepTag {
4184		// We don't track from an implementation library to its stubs.
4185		return false
4186	}
4187	if depTag == staticVariantTag {
4188		// This dependency is for optimization (reuse *.o from the static lib). It doesn't
4189		// actually mean that the static lib (and its dependencies) are copied into the
4190		// APEX.
4191		return false
4192	}
4193
4194	libDepTag, isLibDepTag := depTag.(libraryDependencyTag)
4195	if isLibDepTag && c.Static && libDepTag.shared() {
4196		// shared_lib dependency from a static lib is considered as crossing
4197		// the APEX boundary because the dependency doesn't actually is
4198		// linked; the dependency is used only during the compilation phase.
4199		return false
4200	}
4201
4202	if isLibDepTag && libDepTag.excludeInApex {
4203		return false
4204	}
4205
4206	return true
4207}
4208
4209func (c CcDepInSameApexChecker) IncomingDepIsInSameApex(depTag blueprint.DependencyTag) bool {
4210	if c.Host {
4211		return false
4212	}
4213	if c.HasStubsVariants {
4214		if IsSharedDepTag(depTag) && !IsExplicitImplSharedDepTag(depTag) {
4215			// dynamic dep to a stubs lib crosses APEX boundary
4216			return false
4217		}
4218		if IsRuntimeDepTag(depTag) {
4219			// runtime dep to a stubs lib also crosses APEX boundary
4220			return false
4221		}
4222		if IsHeaderDepTag(depTag) {
4223			return false
4224		}
4225	}
4226	if c.IsLlndk {
4227		return false
4228	}
4229
4230	return true
4231}
4232
4233// Implements android.ApexModule
4234func (c *Module) MinSdkVersionSupported(ctx android.BaseModuleContext) android.ApiLevel {
4235	// We ignore libclang_rt.* prebuilt libs since they declare sdk_version: 14(b/121358700)
4236	if strings.HasPrefix(ctx.OtherModuleName(c), "libclang_rt") {
4237		return android.MinApiLevel
4238	}
4239	// We don't check for prebuilt modules
4240	if _, ok := c.linker.(prebuiltLinkerInterface); ok {
4241		return android.MinApiLevel
4242	}
4243
4244	minSdkVersion := c.MinSdkVersion()
4245	if minSdkVersion == "apex_inherit" {
4246		return android.MinApiLevel
4247	}
4248	if minSdkVersion == "" {
4249		// JNI libs within APK-in-APEX fall into here
4250		// Those are okay to set sdk_version instead
4251		// We don't have to check if this is a SDK variant because
4252		// non-SDK variant resets sdk_version, which works too.
4253		minSdkVersion = c.SdkVersion()
4254	}
4255
4256	if minSdkVersion == "" {
4257		return android.NoneApiLevel
4258	}
4259
4260	// Not using nativeApiLevelFromUser because the context here is not
4261	// necessarily a native context.
4262	ver, err := android.ApiLevelFromUserWithConfig(ctx.Config(), minSdkVersion)
4263	if err != nil {
4264		return android.NoneApiLevel
4265	}
4266
4267	// A dependency only needs to support a min_sdk_version at least
4268	// as high as  the api level that the architecture was introduced in.
4269	// This allows introducing new architectures in the platform that
4270	// need to be included in apexes that normally require an older
4271	// min_sdk_version.
4272	if c.Enabled(ctx) {
4273		minApiForArch := MinApiForArch(ctx, c.Target().Arch.ArchType)
4274		if ver.LessThanOrEqualTo(minApiForArch) {
4275			ver = android.MinApiLevel
4276		}
4277	}
4278
4279	return ver
4280}
4281
4282// Implements android.ApexModule
4283func (c *Module) AlwaysRequiresPlatformApexVariant() bool {
4284	// stub libraries and native bridge libraries are always available to platform
4285	return c.IsStubs() || c.Target().NativeBridge == android.NativeBridgeEnabled
4286}
4287
4288func (c *Module) overriddenModules() []string {
4289	if o, ok := c.linker.(overridable); ok {
4290		return o.overriddenModules()
4291	}
4292	return nil
4293}
4294
4295type moduleType int
4296
4297const (
4298	unknownType moduleType = iota
4299	binary
4300	object
4301	fullLibrary
4302	staticLibrary
4303	sharedLibrary
4304	headerLibrary
4305	testBin // testBinary already declared
4306	ndkLibrary
4307)
4308
4309func (c *Module) typ() moduleType {
4310	if c.testBinary() {
4311		// testBinary is also a binary, so this comes before the c.Binary()
4312		// conditional. A testBinary has additional implicit dependencies and
4313		// other test-only semantics.
4314		return testBin
4315	} else if c.Binary() {
4316		return binary
4317	} else if c.Object() {
4318		return object
4319	} else if c.testLibrary() {
4320		// TODO(b/244431896) properly convert cc_test_library to its own macro. This
4321		// will let them add implicit compile deps on gtest, for example.
4322		//
4323		// For now, treat them as regular libraries.
4324		return fullLibrary
4325	} else if c.CcLibrary() {
4326		static := false
4327		shared := false
4328		if library, ok := c.linker.(*libraryDecorator); ok {
4329			static = library.MutatedProperties.BuildStatic
4330			shared = library.MutatedProperties.BuildShared
4331		} else if library, ok := c.linker.(*prebuiltLibraryLinker); ok {
4332			static = library.MutatedProperties.BuildStatic
4333			shared = library.MutatedProperties.BuildShared
4334		}
4335		if static && shared {
4336			return fullLibrary
4337		} else if !static && !shared {
4338			return headerLibrary
4339		} else if static {
4340			return staticLibrary
4341		}
4342		return sharedLibrary
4343	} else if c.isNDKStubLibrary() {
4344		return ndkLibrary
4345	}
4346	return unknownType
4347}
4348
4349// Defaults
4350type Defaults struct {
4351	android.ModuleBase
4352	android.DefaultsModuleBase
4353}
4354
4355// cc_defaults provides a set of properties that can be inherited by other cc
4356// modules. A module can use the properties from a cc_defaults using
4357// `defaults: ["<:default_module_name>"]`. Properties of both modules are
4358// merged (when possible) by prepending the default module's values to the
4359// depending module's values.
4360func defaultsFactory() android.Module {
4361	return DefaultsFactory()
4362}
4363
4364func DefaultsFactory(props ...interface{}) android.Module {
4365	module := &Defaults{}
4366
4367	module.AddProperties(props...)
4368	module.AddProperties(
4369		&BaseProperties{},
4370		&VendorProperties{},
4371		&BaseCompilerProperties{},
4372		&BaseLinkerProperties{},
4373		&ObjectLinkerProperties{},
4374		&LibraryProperties{},
4375		&StaticProperties{},
4376		&SharedProperties{},
4377		&FlagExporterProperties{},
4378		&BinaryLinkerProperties{},
4379		&TestLinkerProperties{},
4380		&TestInstallerProperties{},
4381		&TestBinaryProperties{},
4382		&BenchmarkProperties{},
4383		&fuzz.FuzzProperties{},
4384		&StlProperties{},
4385		&SanitizeProperties{},
4386		&StripProperties{},
4387		&InstallerProperties{},
4388		&TidyProperties{},
4389		&CoverageProperties{},
4390		&SAbiProperties{},
4391		&LTOProperties{},
4392		&AfdoProperties{},
4393		&OrderfileProperties{},
4394		&android.ProtoProperties{},
4395		// RustBindgenProperties is included here so that cc_defaults can be used for rust_bindgen modules.
4396		&RustBindgenClangProperties{},
4397		&prebuiltLinkerProperties{},
4398	)
4399
4400	android.InitDefaultsModule(module)
4401
4402	return module
4403}
4404
4405func (c *Module) IsSdkVariant() bool {
4406	return c.Properties.IsSdkVariant
4407}
4408
4409func kytheExtractAllFactory() android.Singleton {
4410	return &kytheExtractAllSingleton{}
4411}
4412
4413type kytheExtractAllSingleton struct {
4414}
4415
4416func (ks *kytheExtractAllSingleton) GenerateBuildActions(ctx android.SingletonContext) {
4417	var xrefTargets android.Paths
4418	ctx.VisitAllModuleProxies(func(module android.ModuleProxy) {
4419		files := android.OtherModuleProviderOrDefault(ctx, module, CcObjectInfoProvider).KytheFiles
4420		if len(files) > 0 {
4421			xrefTargets = append(xrefTargets, files...)
4422		}
4423	})
4424	// TODO(asmundak): Perhaps emit a rule to output a warning if there were no xrefTargets
4425	if len(xrefTargets) > 0 {
4426		ctx.Phony("xref_cxx", xrefTargets...)
4427	}
4428}
4429
4430func (c *Module) Partition() string {
4431	if p, ok := c.installer.(interface {
4432		getPartition() string
4433	}); ok {
4434		return p.getPartition()
4435	}
4436	return ""
4437}
4438
4439type sourceModuleName interface {
4440	sourceModuleName() string
4441}
4442
4443func (c *Module) BaseModuleName() string {
4444	if smn, ok := c.linker.(sourceModuleName); ok && smn.sourceModuleName() != "" {
4445		// if the prebuilt module sets a source_module_name in Android.bp, use that
4446		return smn.sourceModuleName()
4447	}
4448	return c.ModuleBase.BaseModuleName()
4449}
4450
4451func (c *Module) stubsSymbolFilePath() android.Path {
4452	if library, ok := c.linker.(*libraryDecorator); ok {
4453		return library.stubsSymbolFilePath
4454	}
4455	return android.OptionalPath{}.Path()
4456}
4457
4458var Bool = proptools.Bool
4459var BoolDefault = proptools.BoolDefault
4460var BoolPtr = proptools.BoolPtr
4461var String = proptools.String
4462var StringPtr = proptools.StringPtr
4463