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