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