• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright 2015 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package cc
16
17// This file contains the module types for compiling C/C++ for Android, and converts the properties
18// into the flags and filenames necessary to pass to the compiler.  The final creation of the rules
19// is handled in builder.go
20
21import (
22	"fmt"
23	"io"
24	"strconv"
25	"strings"
26
27	"github.com/google/blueprint"
28	"github.com/google/blueprint/proptools"
29
30	"android/soong/android"
31	"android/soong/cc/config"
32	"android/soong/genrule"
33)
34
35func init() {
36	RegisterCCBuildComponents(android.InitRegistrationContext)
37
38	pctx.Import("android/soong/cc/config")
39}
40
41func RegisterCCBuildComponents(ctx android.RegistrationContext) {
42	ctx.RegisterModuleType("cc_defaults", defaultsFactory)
43
44	ctx.PreDepsMutators(func(ctx android.RegisterMutatorsContext) {
45		ctx.BottomUp("sdk", sdkMutator).Parallel()
46		ctx.BottomUp("vndk", VndkMutator).Parallel()
47		ctx.BottomUp("link", LinkageMutator).Parallel()
48		ctx.BottomUp("test_per_src", TestPerSrcMutator).Parallel()
49		ctx.BottomUp("version_selector", versionSelectorMutator).Parallel()
50		ctx.BottomUp("version", versionMutator).Parallel()
51		ctx.BottomUp("begin", BeginMutator).Parallel()
52		ctx.BottomUp("sysprop_cc", SyspropMutator).Parallel()
53	})
54
55	ctx.PostDepsMutators(func(ctx android.RegisterMutatorsContext) {
56		ctx.TopDown("asan_deps", sanitizerDepsMutator(Asan))
57		ctx.BottomUp("asan", sanitizerMutator(Asan)).Parallel()
58
59		ctx.TopDown("hwasan_deps", sanitizerDepsMutator(Hwasan))
60		ctx.BottomUp("hwasan", sanitizerMutator(Hwasan)).Parallel()
61
62		ctx.TopDown("fuzzer_deps", sanitizerDepsMutator(Fuzzer))
63		ctx.BottomUp("fuzzer", sanitizerMutator(Fuzzer)).Parallel()
64
65		// cfi mutator shouldn't run before sanitizers that return true for
66		// incompatibleWithCfi()
67		ctx.TopDown("cfi_deps", sanitizerDepsMutator(cfi))
68		ctx.BottomUp("cfi", sanitizerMutator(cfi)).Parallel()
69
70		ctx.TopDown("scs_deps", sanitizerDepsMutator(scs))
71		ctx.BottomUp("scs", sanitizerMutator(scs)).Parallel()
72
73		ctx.TopDown("tsan_deps", sanitizerDepsMutator(tsan))
74		ctx.BottomUp("tsan", sanitizerMutator(tsan)).Parallel()
75
76		ctx.TopDown("sanitize_runtime_deps", sanitizerRuntimeDepsMutator).Parallel()
77		ctx.BottomUp("sanitize_runtime", sanitizerRuntimeMutator).Parallel()
78
79		ctx.BottomUp("coverage", coverageMutator).Parallel()
80
81		ctx.TopDown("lto_deps", ltoDepsMutator)
82		ctx.BottomUp("lto", ltoMutator).Parallel()
83
84		ctx.BottomUp("check_linktype", checkLinkTypeMutator).Parallel()
85		ctx.TopDown("double_loadable", checkDoubleLoadableLibraries).Parallel()
86	})
87
88	ctx.FinalDepsMutators(func(ctx android.RegisterMutatorsContext) {
89		// sabi mutator needs to be run after apex mutator finishes.
90		ctx.TopDown("sabi_deps", sabiDepsMutator)
91	})
92
93	ctx.RegisterSingletonType("kythe_extract_all", kytheExtractAllFactory)
94}
95
96// Deps is a struct containing module names of dependencies, separated by the kind of dependency.
97// Mutators should use `AddVariationDependencies` or its sibling methods to add actual dependency
98// edges to these modules.
99// This object is constructed in DepsMutator, by calling to various module delegates to set
100// relevant fields. For example, `module.compiler.compilerDeps()` may append type-specific
101// dependencies.
102// This is then consumed by the same DepsMutator, which will call `ctx.AddVariationDependencies()`
103// (or its sibling methods) to set real dependencies on the given modules.
104type Deps struct {
105	SharedLibs, LateSharedLibs                  []string
106	StaticLibs, LateStaticLibs, WholeStaticLibs []string
107	HeaderLibs                                  []string
108	RuntimeLibs                                 []string
109
110	// Used for data dependencies adjacent to tests
111	DataLibs []string
112
113	// Used by DepsMutator to pass system_shared_libs information to check_elf_file.py.
114	SystemSharedLibs []string
115
116	// If true, statically link the unwinder into native libraries/binaries.
117	StaticUnwinderIfLegacy bool
118
119	ReexportSharedLibHeaders, ReexportStaticLibHeaders, ReexportHeaderLibHeaders []string
120
121	ObjFiles []string
122
123	GeneratedSources []string
124	GeneratedHeaders []string
125	GeneratedDeps    []string
126
127	ReexportGeneratedHeaders []string
128
129	CrtBegin, CrtEnd string
130
131	// Used for host bionic
132	LinkerFlagsFile string
133	DynamicLinker   string
134
135	// List of libs that need to be excluded for APEX variant
136	ExcludeLibsForApex []string
137}
138
139// PathDeps is a struct containing file paths to dependencies of a module.
140// It's constructed in depsToPath() by traversing the direct dependencies of the current module.
141// It's used to construct flags for various build statements (such as for compiling and linking).
142// It is then passed to module decorator functions responsible for registering build statements
143// (such as `module.compiler.compile()`).`
144type PathDeps struct {
145	// Paths to .so files
146	SharedLibs, EarlySharedLibs, LateSharedLibs android.Paths
147	// Paths to the dependencies to use for .so files (.so.toc files)
148	SharedLibsDeps, EarlySharedLibsDeps, LateSharedLibsDeps android.Paths
149	// Paths to .a files
150	StaticLibs, LateStaticLibs, WholeStaticLibs android.Paths
151
152	// Transitive static library dependencies of static libraries for use in ordering.
153	TranstiveStaticLibrariesForOrdering *android.DepSet
154
155	// Paths to .o files
156	Objs Objects
157	// Paths to .o files in dependencies that provide them. Note that these lists
158	// aren't complete since prebuilt modules don't provide the .o files.
159	StaticLibObjs      Objects
160	WholeStaticLibObjs Objects
161
162	// Paths to .a files in prebuilts. Complements WholeStaticLibObjs to contain
163	// the libs from all whole_static_lib dependencies.
164	WholeStaticLibsFromPrebuilts android.Paths
165
166	// Paths to generated source files
167	GeneratedSources android.Paths
168	GeneratedDeps    android.Paths
169
170	Flags                      []string
171	IncludeDirs                android.Paths
172	SystemIncludeDirs          android.Paths
173	ReexportedDirs             android.Paths
174	ReexportedSystemDirs       android.Paths
175	ReexportedFlags            []string
176	ReexportedGeneratedHeaders android.Paths
177	ReexportedDeps             android.Paths
178
179	// Paths to crt*.o files
180	CrtBegin, CrtEnd android.OptionalPath
181
182	// Path to the file container flags to use with the linker
183	LinkerFlagsFile android.OptionalPath
184
185	// Path to the dynamic linker binary
186	DynamicLinker android.OptionalPath
187}
188
189// LocalOrGlobalFlags contains flags that need to have values set globally by the build system or locally by the module
190// tracked separately, in order to maintain the required ordering (most of the global flags need to go first on the
191// command line so they can be overridden by the local module flags).
192type LocalOrGlobalFlags struct {
193	CommonFlags     []string // Flags that apply to C, C++, and assembly source files
194	AsFlags         []string // Flags that apply to assembly source files
195	YasmFlags       []string // Flags that apply to yasm assembly source files
196	CFlags          []string // Flags that apply to C and C++ source files
197	ToolingCFlags   []string // Flags that apply to C and C++ source files parsed by clang LibTooling tools
198	ConlyFlags      []string // Flags that apply to C source files
199	CppFlags        []string // Flags that apply to C++ source files
200	ToolingCppFlags []string // Flags that apply to C++ source files parsed by clang LibTooling tools
201	LdFlags         []string // Flags that apply to linker command lines
202}
203
204// Flags contains various types of command line flags (and settings) for use in building build
205// statements related to C++.
206type Flags struct {
207	// Local flags (which individual modules are responsible for). These may override global flags.
208	Local LocalOrGlobalFlags
209	// Global flags (which build system or toolchain is responsible for).
210	Global LocalOrGlobalFlags
211
212	aidlFlags     []string // Flags that apply to aidl source files
213	rsFlags       []string // Flags that apply to renderscript source files
214	libFlags      []string // Flags to add libraries early to the link order
215	extraLibFlags []string // Flags to add libraries late in the link order after LdFlags
216	TidyFlags     []string // Flags that apply to clang-tidy
217	SAbiFlags     []string // Flags that apply to header-abi-dumper
218
219	// Global include flags that apply to C, C++, and assembly source files
220	// These must be after any module include flags, which will be in CommonFlags.
221	SystemIncludeFlags []string
222
223	Toolchain    config.Toolchain
224	Tidy         bool // True if clang-tidy is enabled.
225	GcovCoverage bool // True if coverage files should be generated.
226	SAbiDump     bool // True if header abi dumps should be generated.
227	EmitXrefs    bool // If true, generate Ninja rules to generate emitXrefs input files for Kythe
228
229	// The instruction set required for clang ("arm" or "thumb").
230	RequiredInstructionSet string
231	// The target-device system path to the dynamic linker.
232	DynamicLinker string
233
234	CFlagsDeps  android.Paths // Files depended on by compiler flags
235	LdFlagsDeps android.Paths // Files depended on by linker flags
236
237	// True if .s files should be processed with the c preprocessor.
238	AssemblerWithCpp bool
239	// True if static libraries should be grouped (using `-Wl,--start-group` and `-Wl,--end-group`).
240	GroupStaticLibs bool
241
242	proto            android.ProtoFlags
243	protoC           bool // Whether to use C instead of C++
244	protoOptionsFile bool // Whether to look for a .options file next to the .proto
245
246	Yacc *YaccProperties
247	Lex  *LexProperties
248}
249
250// Properties used to compile all C or C++ modules
251type BaseProperties struct {
252	// Deprecated. true is the default, false is invalid.
253	Clang *bool `android:"arch_variant"`
254
255	// The API level that this module is built against. The APIs of this API level will be
256	// visible at build time, but use of any APIs newer than min_sdk_version will render the
257	// module unloadable on older devices.  In the future it will be possible to weakly-link new
258	// APIs, making the behavior match Java: such modules will load on older devices, but
259	// calling new APIs on devices that do not support them will result in a crash.
260	//
261	// This property has the same behavior as sdk_version does for Java modules. For those
262	// familiar with Android Gradle, the property behaves similarly to how compileSdkVersion
263	// does for Java code.
264	//
265	// In addition, setting this property causes two variants to be built, one for the platform
266	// and one for apps.
267	Sdk_version *string
268
269	// Minimum OS API level supported by this C or C++ module. This property becomes the value
270	// of the __ANDROID_API__ macro. When the C or C++ module is included in an APEX or an APK,
271	// this property is also used to ensure that the min_sdk_version of the containing module is
272	// not older (i.e. less) than this module's min_sdk_version. When not set, this property
273	// defaults to the value of sdk_version.  When this is set to "apex_inherit", this tracks
274	// min_sdk_version of the containing APEX. When the module
275	// is not built for an APEX, "apex_inherit" defaults to sdk_version.
276	Min_sdk_version *string
277
278	// If true, always create an sdk variant and don't create a platform variant.
279	Sdk_variant_only *bool
280
281	AndroidMkSharedLibs       []string `blueprint:"mutated"`
282	AndroidMkStaticLibs       []string `blueprint:"mutated"`
283	AndroidMkRuntimeLibs      []string `blueprint:"mutated"`
284	AndroidMkWholeStaticLibs  []string `blueprint:"mutated"`
285	AndroidMkHeaderLibs       []string `blueprint:"mutated"`
286	HideFromMake              bool     `blueprint:"mutated"`
287	PreventInstall            bool     `blueprint:"mutated"`
288	ApexesProvidingSharedLibs []string `blueprint:"mutated"`
289
290	// Set by DepsMutator.
291	AndroidMkSystemSharedLibs []string `blueprint:"mutated"`
292
293	ImageVariationPrefix string `blueprint:"mutated"`
294	VndkVersion          string `blueprint:"mutated"`
295	SubName              string `blueprint:"mutated"`
296
297	// *.logtags files, to combine together in order to generate the /system/etc/event-log-tags
298	// file
299	Logtags []string
300
301	// Make this module available when building for ramdisk.
302	// On device without a dedicated recovery partition, the module is only
303	// available after switching root into
304	// /first_stage_ramdisk. To expose the module before switching root, install
305	// the recovery variant instead.
306	Ramdisk_available *bool
307
308	// Make this module available when building for vendor ramdisk.
309	// On device without a dedicated recovery partition, the module is only
310	// available after switching root into
311	// /first_stage_ramdisk. To expose the module before switching root, install
312	// the recovery variant instead.
313	Vendor_ramdisk_available *bool
314
315	// Make this module available when building for recovery
316	Recovery_available *bool
317
318	// Set by imageMutator
319	CoreVariantNeeded          bool     `blueprint:"mutated"`
320	RamdiskVariantNeeded       bool     `blueprint:"mutated"`
321	VendorRamdiskVariantNeeded bool     `blueprint:"mutated"`
322	RecoveryVariantNeeded      bool     `blueprint:"mutated"`
323	ExtraVariants              []string `blueprint:"mutated"`
324
325	// Allows this module to use non-APEX version of libraries. Useful
326	// for building binaries that are started before APEXes are activated.
327	Bootstrap *bool
328
329	// Even if DeviceConfig().VndkUseCoreVariant() is set, this module must use vendor variant.
330	// see soong/cc/config/vndk.go
331	MustUseVendorVariant bool `blueprint:"mutated"`
332
333	// Used by vendor snapshot to record dependencies from snapshot modules.
334	SnapshotSharedLibs  []string `blueprint:"mutated"`
335	SnapshotRuntimeLibs []string `blueprint:"mutated"`
336
337	Installable *bool
338
339	// Set by factories of module types that can only be referenced from variants compiled against
340	// the SDK.
341	AlwaysSdk bool `blueprint:"mutated"`
342
343	// Variant is an SDK variant created by sdkMutator
344	IsSdkVariant bool `blueprint:"mutated"`
345	// Set when both SDK and platform variants are exported to Make to trigger renaming the SDK
346	// variant to have a ".sdk" suffix.
347	SdkAndPlatformVariantVisibleToMake bool `blueprint:"mutated"`
348
349	// Normally Soong uses the directory structure to decide which modules
350	// should be included (framework) or excluded (non-framework) from the
351	// different snapshots (vendor, recovery, etc.), but this property
352	// allows a partner to exclude a module normally thought of as a
353	// framework module from the vendor snapshot.
354	Exclude_from_vendor_snapshot *bool
355
356	// Normally Soong uses the directory structure to decide which modules
357	// should be included (framework) or excluded (non-framework) from the
358	// different snapshots (vendor, recovery, etc.), but this property
359	// allows a partner to exclude a module normally thought of as a
360	// framework module from the recovery snapshot.
361	Exclude_from_recovery_snapshot *bool
362
363	// List of APEXes that this module has private access to for testing purpose. The module
364	// can depend on libraries that are not exported by the APEXes and use private symbols
365	// from the exported libraries.
366	Test_for []string `android:"arch_variant"`
367}
368
369type VendorProperties struct {
370	// whether this module should be allowed to be directly depended by other
371	// modules with `vendor: true`, `proprietary: true`, or `vendor_available:true`.
372	// If set to true, two variants will be built separately, one like
373	// normal, and the other limited to the set of libraries and headers
374	// that are exposed to /vendor modules.
375	//
376	// The vendor variant may be used with a different (newer) /system,
377	// so it shouldn't have any unversioned runtime dependencies, or
378	// make assumptions about the system that may not be true in the
379	// future.
380	//
381	// If set to false, this module becomes inaccessible from /vendor modules.
382	//
383	// The modules with vndk: {enabled: true} must define 'vendor_available'
384	// to 'true'.
385	//
386	// Nothing happens if BOARD_VNDK_VERSION isn't set in the BoardConfig.mk
387	Vendor_available *bool
388
389	// This is the same as the "vendor_available" except that the install path
390	// of the vendor variant is /odm or /vendor/odm.
391	// By replacing "vendor_available: true" with "odm_available: true", the
392	// module will install its vendor variant to the /odm partition or /vendor/odm.
393	// As the modules with "odm_available: true" still create the vendor variants,
394	// they can link to the other vendor modules as the vendor_available modules do.
395	// Also, the vendor modules can link to odm_available modules.
396	//
397	// It may not be used for VNDK modules.
398	Odm_available *bool
399
400	// whether this module should be allowed to be directly depended by other
401	// modules with `product_specific: true` or `product_available: true`.
402	// If set to true, an additional product variant will be built separately
403	// that is limited to the set of libraries and headers that are exposed to
404	// /product modules.
405	//
406	// The product variant may be used with a different (newer) /system,
407	// so it shouldn't have any unversioned runtime dependencies, or
408	// make assumptions about the system that may not be true in the
409	// future.
410	//
411	// If set to false, this module becomes inaccessible from /product modules.
412	//
413	// Different from the 'vendor_available' property, the modules with
414	// vndk: {enabled: true} don't have to define 'product_available'. The VNDK
415	// library without 'product_available' may not be depended on by any other
416	// modules that has product variants including the product available VNDKs.
417	//
418	// Nothing happens if BOARD_VNDK_VERSION isn't set in the BoardConfig.mk
419	// and PRODUCT_PRODUCT_VNDK_VERSION isn't set.
420	Product_available *bool
421
422	// whether this module is capable of being loaded with other instance
423	// (possibly an older version) of the same module in the same process.
424	// Currently, a shared library that is a member of VNDK (vndk: {enabled: true})
425	// can be double loaded in a vendor process if the library is also a
426	// (direct and indirect) dependency of an LLNDK library. Such libraries must be
427	// explicitly marked as `double_loadable: true` by the owner, or the dependency
428	// from the LLNDK lib should be cut if the lib is not designed to be double loaded.
429	Double_loadable *bool
430
431	// IsLLNDK is set to true for the vendor variant of a cc_library module that has LLNDK stubs.
432	IsLLNDK bool `blueprint:"mutated"`
433
434	// IsVNDKUsingCoreVariant is true for VNDK modules if the global VndkUseCoreVariant option is
435	// set and the module is not listed in VndkMustUseVendorVariantList.
436	IsVNDKUsingCoreVariant bool `blueprint:"mutated"`
437
438	// IsVNDKCore is set if a VNDK module does not set the vndk.support_system_process property.
439	IsVNDKCore bool `blueprint:"mutated"`
440
441	// IsVNDKSP is set if a VNDK module sets the vndk.support_system_process property.
442	IsVNDKSP bool `blueprint:"mutated"`
443
444	// IsVNDKPrivate is set if a VNDK module sets the vndk.private property or an LLNDK
445	// module sets the llndk.private property.
446	IsVNDKPrivate bool `blueprint:"mutated"`
447
448	// IsVNDKProduct is set if a VNDK module sets the product_available property.
449	IsVNDKProduct bool `blueprint:"mutated"`
450
451	// IsVendorPublicLibrary is set for the core and product variants of a library that has
452	// vendor_public_library stubs.
453	IsVendorPublicLibrary bool `blueprint:"mutated"`
454}
455
456// ModuleContextIntf is an interface (on a module context helper) consisting of functions related
457// to understanding  details about the type of the current module.
458// For example, one might call these functions to determine whether the current module is a static
459// library and/or is installed in vendor directories.
460type ModuleContextIntf interface {
461	static() bool
462	staticBinary() bool
463	testBinary() bool
464	header() bool
465	binary() bool
466	object() bool
467	toolchain() config.Toolchain
468	canUseSdk() bool
469	useSdk() bool
470	sdkVersion() string
471	minSdkVersion() string
472	isSdkVariant() bool
473	useVndk() bool
474	isNdk(config android.Config) bool
475	IsLlndk() bool
476	IsLlndkPublic() bool
477	isImplementationForLLNDKPublic() bool
478	IsVndkPrivate() bool
479	isVndk() bool
480	isVndkSp() bool
481	IsVndkExt() bool
482	IsVendorPublicLibrary() bool
483	inProduct() bool
484	inVendor() bool
485	inRamdisk() bool
486	inVendorRamdisk() bool
487	inRecovery() bool
488	selectedStl() string
489	baseModuleName() string
490	getVndkExtendsModuleName() string
491	isPgoCompile() bool
492	isNDKStubLibrary() bool
493	useClangLld(actx ModuleContext) bool
494	isForPlatform() bool
495	apexVariationName() string
496	apexSdkVersion() android.ApiLevel
497	bootstrap() bool
498	mustUseVendorVariant() bool
499	nativeCoverage() bool
500	directlyInAnyApex() bool
501	isPreventInstall() bool
502	isCfiAssemblySupportEnabled() bool
503}
504
505type ModuleContext interface {
506	android.ModuleContext
507	ModuleContextIntf
508}
509
510type BaseModuleContext interface {
511	android.BaseModuleContext
512	ModuleContextIntf
513}
514
515type DepsContext interface {
516	android.BottomUpMutatorContext
517	ModuleContextIntf
518}
519
520// feature represents additional (optional) steps to building cc-related modules, such as invocation
521// of clang-tidy.
522type feature interface {
523	begin(ctx BaseModuleContext)
524	deps(ctx DepsContext, deps Deps) Deps
525	flags(ctx ModuleContext, flags Flags) Flags
526	props() []interface{}
527}
528
529// compiler is the interface for a compiler helper object. Different module decorators may implement
530// this helper differently. For example, compiling a `cc_library` may use a different build
531// statement than building a `toolchain_library`.
532type compiler interface {
533	compilerInit(ctx BaseModuleContext)
534	compilerDeps(ctx DepsContext, deps Deps) Deps
535	compilerFlags(ctx ModuleContext, flags Flags, deps PathDeps) Flags
536	compilerProps() []interface{}
537
538	appendCflags([]string)
539	appendAsflags([]string)
540	compile(ctx ModuleContext, flags Flags, deps PathDeps) Objects
541}
542
543// linker is the interface for a linker decorator object. Individual module types can provide
544// their own implementation for this decorator, and thus specify custom logic regarding build
545// statements pertaining to linking.
546type linker interface {
547	linkerInit(ctx BaseModuleContext)
548	linkerDeps(ctx DepsContext, deps Deps) Deps
549	linkerFlags(ctx ModuleContext, flags Flags) Flags
550	linkerProps() []interface{}
551	useClangLld(actx ModuleContext) bool
552
553	link(ctx ModuleContext, flags Flags, deps PathDeps, objs Objects) android.Path
554	appendLdflags([]string)
555	unstrippedOutputFilePath() android.Path
556
557	nativeCoverage() bool
558	coverageOutputFilePath() android.OptionalPath
559
560	// Get the deps that have been explicitly specified in the properties.
561	linkerSpecifiedDeps(specifiedDeps specifiedDeps) specifiedDeps
562}
563
564// specifiedDeps is a tuple struct representing dependencies of a linked binary owned by the linker.
565type specifiedDeps struct {
566	sharedLibs []string
567	// Note nil and [] are semantically distinct. [] prevents linking against the defaults (usually
568	// libc, libm, etc.)
569	systemSharedLibs []string
570}
571
572// installer is the interface for an installer helper object. This helper is responsible for
573// copying build outputs to the appropriate locations so that they may be installed on device.
574type installer interface {
575	installerProps() []interface{}
576	install(ctx ModuleContext, path android.Path)
577	everInstallable() bool
578	inData() bool
579	inSanitizerDir() bool
580	hostToolPath() android.OptionalPath
581	relativeInstallPath() string
582	makeUninstallable(mod *Module)
583}
584
585// bazelHandler is the interface for a helper object related to deferring to Bazel for
586// processing a module (during Bazel mixed builds). Individual module types should define
587// their own bazel handler if they support deferring to Bazel.
588type bazelHandler interface {
589	// Issue query to Bazel to retrieve information about Bazel's view of the current module.
590	// If Bazel returns this information, set module properties on the current module to reflect
591	// the returned information.
592	// Returns true if information was available from Bazel, false if bazel invocation still needs to occur.
593	generateBazelBuildActions(ctx android.ModuleContext, label string) bool
594}
595
596type xref interface {
597	XrefCcFiles() android.Paths
598}
599
600type libraryDependencyKind int
601
602const (
603	headerLibraryDependency = iota
604	sharedLibraryDependency
605	staticLibraryDependency
606)
607
608func (k libraryDependencyKind) String() string {
609	switch k {
610	case headerLibraryDependency:
611		return "headerLibraryDependency"
612	case sharedLibraryDependency:
613		return "sharedLibraryDependency"
614	case staticLibraryDependency:
615		return "staticLibraryDependency"
616	default:
617		panic(fmt.Errorf("unknown libraryDependencyKind %d", k))
618	}
619}
620
621type libraryDependencyOrder int
622
623const (
624	earlyLibraryDependency  = -1
625	normalLibraryDependency = 0
626	lateLibraryDependency   = 1
627)
628
629func (o libraryDependencyOrder) String() string {
630	switch o {
631	case earlyLibraryDependency:
632		return "earlyLibraryDependency"
633	case normalLibraryDependency:
634		return "normalLibraryDependency"
635	case lateLibraryDependency:
636		return "lateLibraryDependency"
637	default:
638		panic(fmt.Errorf("unknown libraryDependencyOrder %d", o))
639	}
640}
641
642// libraryDependencyTag is used to tag dependencies on libraries.  Unlike many dependency
643// tags that have a set of predefined tag objects that are reused for each dependency, a
644// libraryDependencyTag is designed to contain extra metadata and is constructed as needed.
645// That means that comparing a libraryDependencyTag for equality will only be equal if all
646// of the metadata is equal.  Most usages will want to type assert to libraryDependencyTag and
647// then check individual metadata fields instead.
648type libraryDependencyTag struct {
649	blueprint.BaseDependencyTag
650
651	// These are exported so that fmt.Printf("%#v") can call their String methods.
652	Kind  libraryDependencyKind
653	Order libraryDependencyOrder
654
655	wholeStatic bool
656
657	reexportFlags       bool
658	explicitlyVersioned bool
659	dataLib             bool
660	ndk                 bool
661
662	staticUnwinder bool
663
664	makeSuffix string
665
666	// Whether or not this dependency should skip the apex dependency check
667	skipApexAllowedDependenciesCheck bool
668
669	// Whether or not this dependency has to be followed for the apex variants
670	excludeInApex bool
671}
672
673// header returns true if the libraryDependencyTag is tagging a header lib dependency.
674func (d libraryDependencyTag) header() bool {
675	return d.Kind == headerLibraryDependency
676}
677
678// shared returns true if the libraryDependencyTag is tagging a shared lib dependency.
679func (d libraryDependencyTag) shared() bool {
680	return d.Kind == sharedLibraryDependency
681}
682
683// shared returns true if the libraryDependencyTag is tagging a static lib dependency.
684func (d libraryDependencyTag) static() bool {
685	return d.Kind == staticLibraryDependency
686}
687
688// InstallDepNeeded returns true for shared libraries so that shared library dependencies of
689// binaries or other shared libraries are installed as dependencies.
690func (d libraryDependencyTag) InstallDepNeeded() bool {
691	return d.shared()
692}
693
694var _ android.InstallNeededDependencyTag = libraryDependencyTag{}
695
696// dependencyTag is used for tagging miscellaneous dependency types that don't fit into
697// libraryDependencyTag.  Each tag object is created globally and reused for multiple
698// dependencies (although since the object contains no references, assigning a tag to a
699// variable and modifying it will not modify the original).  Users can compare the tag
700// returned by ctx.OtherModuleDependencyTag against the global original
701type dependencyTag struct {
702	blueprint.BaseDependencyTag
703	name string
704}
705
706// installDependencyTag is used for tagging miscellaneous dependency types that don't fit into
707// libraryDependencyTag, but where the dependency needs to be installed when the parent is
708// installed.
709type installDependencyTag struct {
710	blueprint.BaseDependencyTag
711	android.InstallAlwaysNeededDependencyTag
712	name string
713}
714
715var (
716	genSourceDepTag       = dependencyTag{name: "gen source"}
717	genHeaderDepTag       = dependencyTag{name: "gen header"}
718	genHeaderExportDepTag = dependencyTag{name: "gen header export"}
719	objDepTag             = dependencyTag{name: "obj"}
720	linkerFlagsDepTag     = dependencyTag{name: "linker flags file"}
721	dynamicLinkerDepTag   = installDependencyTag{name: "dynamic linker"}
722	reuseObjTag           = dependencyTag{name: "reuse objects"}
723	staticVariantTag      = dependencyTag{name: "static variant"}
724	vndkExtDepTag         = dependencyTag{name: "vndk extends"}
725	dataLibDepTag         = dependencyTag{name: "data lib"}
726	runtimeDepTag         = installDependencyTag{name: "runtime lib"}
727	testPerSrcDepTag      = dependencyTag{name: "test_per_src"}
728	stubImplDepTag        = dependencyTag{name: "stub_impl"}
729	llndkStubDepTag       = dependencyTag{name: "llndk stub"}
730)
731
732func IsSharedDepTag(depTag blueprint.DependencyTag) bool {
733	ccLibDepTag, ok := depTag.(libraryDependencyTag)
734	return ok && ccLibDepTag.shared()
735}
736
737func IsStaticDepTag(depTag blueprint.DependencyTag) bool {
738	ccLibDepTag, ok := depTag.(libraryDependencyTag)
739	return ok && ccLibDepTag.static()
740}
741
742func IsHeaderDepTag(depTag blueprint.DependencyTag) bool {
743	ccLibDepTag, ok := depTag.(libraryDependencyTag)
744	return ok && ccLibDepTag.header()
745}
746
747func IsRuntimeDepTag(depTag blueprint.DependencyTag) bool {
748	return depTag == runtimeDepTag
749}
750
751func IsTestPerSrcDepTag(depTag blueprint.DependencyTag) bool {
752	ccDepTag, ok := depTag.(dependencyTag)
753	return ok && ccDepTag == testPerSrcDepTag
754}
755
756// Module contains the properties and members used by all C/C++ module types, and implements
757// the blueprint.Module interface.  It delegates to compiler, linker, and installer interfaces
758// to construct the output file.  Behavior can be customized with a Customizer, or "decorator",
759// interface.
760//
761// To define a C/C++ related module, construct a new Module object and point its delegates to
762// type-specific structs. These delegates will be invoked to register module-specific build
763// statements which may be unique to the module type. For example, module.compiler.compile() should
764// be defined so as to register build statements which are responsible for compiling the module.
765//
766// Another example: to construct a cc_binary module, one can create a `cc.binaryDecorator` struct
767// which implements the `linker` and `installer` interfaces, and points the `linker` and `installer`
768// members of the cc.Module to this decorator. Thus, a cc_binary module has custom linker and
769// installer logic.
770type Module struct {
771	android.ModuleBase
772	android.DefaultableModuleBase
773	android.ApexModuleBase
774	android.SdkBase
775	android.BazelModuleBase
776
777	Properties       BaseProperties
778	VendorProperties VendorProperties
779
780	// initialize before calling Init
781	hod      android.HostOrDeviceSupported
782	multilib android.Multilib
783
784	// Allowable SdkMemberTypes of this module type.
785	sdkMemberTypes []android.SdkMemberType
786
787	// decorator delegates, initialize before calling Init
788	// these may contain module-specific implementations, and effectively allow for custom
789	// type-specific logic. These members may reference different objects or the same object.
790	// Functions of these decorators will be invoked to initialize and register type-specific
791	// build statements.
792	compiler     compiler
793	linker       linker
794	installer    installer
795	bazelHandler bazelHandler
796
797	features []feature
798	stl      *stl
799	sanitize *sanitize
800	coverage *coverage
801	sabi     *sabi
802	vndkdep  *vndkdep
803	lto      *lto
804	pgo      *pgo
805
806	library libraryInterface
807
808	outputFile android.OptionalPath
809
810	cachedToolchain config.Toolchain
811
812	subAndroidMkOnce map[subAndroidMkProvider]bool
813
814	// Flags used to compile this module
815	flags Flags
816
817	// only non-nil when this is a shared library that reuses the objects of a static library
818	staticAnalogue *StaticLibraryInfo
819
820	makeLinkType string
821	// Kythe (source file indexer) paths for this compilation module
822	kytheFiles android.Paths
823
824	// For apex variants, this is set as apex.min_sdk_version
825	apexSdkVersion android.ApiLevel
826
827	hideApexVariantFromMake bool
828}
829
830func (c *Module) SetPreventInstall() {
831	c.Properties.PreventInstall = true
832}
833
834func (c *Module) SetHideFromMake() {
835	c.Properties.HideFromMake = true
836}
837
838func (c *Module) HiddenFromMake() bool {
839	return c.Properties.HideFromMake
840}
841
842func (c *Module) Toc() android.OptionalPath {
843	if c.linker != nil {
844		if library, ok := c.linker.(libraryInterface); ok {
845			return library.toc()
846		}
847	}
848	panic(fmt.Errorf("Toc() called on non-library module: %q", c.BaseModuleName()))
849}
850
851func (c *Module) ApiLevel() string {
852	if c.linker != nil {
853		if stub, ok := c.linker.(*stubDecorator); ok {
854			return stub.apiLevel.String()
855		}
856	}
857	panic(fmt.Errorf("ApiLevel() called on non-stub library module: %q", c.BaseModuleName()))
858}
859
860func (c *Module) Static() bool {
861	if c.linker != nil {
862		if library, ok := c.linker.(libraryInterface); ok {
863			return library.static()
864		}
865	}
866	panic(fmt.Errorf("Static() called on non-library module: %q", c.BaseModuleName()))
867}
868
869func (c *Module) Shared() bool {
870	if c.linker != nil {
871		if library, ok := c.linker.(libraryInterface); ok {
872			return library.shared()
873		}
874	}
875	panic(fmt.Errorf("Shared() called on non-library module: %q", c.BaseModuleName()))
876}
877
878func (c *Module) SelectedStl() string {
879	if c.stl != nil {
880		return c.stl.Properties.SelectedStl
881	}
882	return ""
883}
884
885func (c *Module) ToolchainLibrary() bool {
886	if _, ok := c.linker.(*toolchainLibraryDecorator); ok {
887		return true
888	}
889	return false
890}
891
892func (c *Module) NdkPrebuiltStl() bool {
893	if _, ok := c.linker.(*ndkPrebuiltStlLinker); ok {
894		return true
895	}
896	return false
897}
898
899func (c *Module) StubDecorator() bool {
900	if _, ok := c.linker.(*stubDecorator); ok {
901		return true
902	}
903	return false
904}
905
906func (c *Module) SdkVersion() string {
907	return String(c.Properties.Sdk_version)
908}
909
910func (c *Module) MinSdkVersion() string {
911	return String(c.Properties.Min_sdk_version)
912}
913
914func (c *Module) SplitPerApiLevel() bool {
915	if !c.canUseSdk() {
916		return false
917	}
918	if linker, ok := c.linker.(*objectLinker); ok {
919		return linker.isCrt()
920	}
921	return false
922}
923
924func (c *Module) AlwaysSdk() bool {
925	return c.Properties.AlwaysSdk || Bool(c.Properties.Sdk_variant_only)
926}
927
928func (c *Module) CcLibrary() bool {
929	if c.linker != nil {
930		if _, ok := c.linker.(*libraryDecorator); ok {
931			return true
932		}
933		if _, ok := c.linker.(*prebuiltLibraryLinker); ok {
934			return true
935		}
936	}
937	return false
938}
939
940func (c *Module) CcLibraryInterface() bool {
941	if _, ok := c.linker.(libraryInterface); ok {
942		return true
943	}
944	return false
945}
946
947func (c *Module) NonCcVariants() bool {
948	return false
949}
950
951func (c *Module) SetStatic() {
952	if c.linker != nil {
953		if library, ok := c.linker.(libraryInterface); ok {
954			library.setStatic()
955			return
956		}
957	}
958	panic(fmt.Errorf("SetStatic called on non-library module: %q", c.BaseModuleName()))
959}
960
961func (c *Module) SetShared() {
962	if c.linker != nil {
963		if library, ok := c.linker.(libraryInterface); ok {
964			library.setShared()
965			return
966		}
967	}
968	panic(fmt.Errorf("SetShared called on non-library module: %q", c.BaseModuleName()))
969}
970
971func (c *Module) BuildStaticVariant() bool {
972	if c.linker != nil {
973		if library, ok := c.linker.(libraryInterface); ok {
974			return library.buildStatic()
975		}
976	}
977	panic(fmt.Errorf("BuildStaticVariant called on non-library module: %q", c.BaseModuleName()))
978}
979
980func (c *Module) BuildSharedVariant() bool {
981	if c.linker != nil {
982		if library, ok := c.linker.(libraryInterface); ok {
983			return library.buildShared()
984		}
985	}
986	panic(fmt.Errorf("BuildSharedVariant called on non-library module: %q", c.BaseModuleName()))
987}
988
989func (c *Module) Module() android.Module {
990	return c
991}
992
993func (c *Module) OutputFile() android.OptionalPath {
994	return c.outputFile
995}
996
997func (c *Module) CoverageFiles() android.Paths {
998	if c.linker != nil {
999		if library, ok := c.linker.(libraryInterface); ok {
1000			return library.objs().coverageFiles
1001		}
1002	}
1003	panic(fmt.Errorf("CoverageFiles called on non-library module: %q", c.BaseModuleName()))
1004}
1005
1006var _ LinkableInterface = (*Module)(nil)
1007
1008func (c *Module) UnstrippedOutputFile() android.Path {
1009	if c.linker != nil {
1010		return c.linker.unstrippedOutputFilePath()
1011	}
1012	return nil
1013}
1014
1015func (c *Module) CoverageOutputFile() android.OptionalPath {
1016	if c.linker != nil {
1017		return c.linker.coverageOutputFilePath()
1018	}
1019	return android.OptionalPath{}
1020}
1021
1022func (c *Module) RelativeInstallPath() string {
1023	if c.installer != nil {
1024		return c.installer.relativeInstallPath()
1025	}
1026	return ""
1027}
1028
1029func (c *Module) VndkVersion() string {
1030	return c.Properties.VndkVersion
1031}
1032
1033func (c *Module) Init() android.Module {
1034	c.AddProperties(&c.Properties, &c.VendorProperties)
1035	if c.compiler != nil {
1036		c.AddProperties(c.compiler.compilerProps()...)
1037	}
1038	if c.linker != nil {
1039		c.AddProperties(c.linker.linkerProps()...)
1040	}
1041	if c.installer != nil {
1042		c.AddProperties(c.installer.installerProps()...)
1043	}
1044	if c.stl != nil {
1045		c.AddProperties(c.stl.props()...)
1046	}
1047	if c.sanitize != nil {
1048		c.AddProperties(c.sanitize.props()...)
1049	}
1050	if c.coverage != nil {
1051		c.AddProperties(c.coverage.props()...)
1052	}
1053	if c.sabi != nil {
1054		c.AddProperties(c.sabi.props()...)
1055	}
1056	if c.vndkdep != nil {
1057		c.AddProperties(c.vndkdep.props()...)
1058	}
1059	if c.lto != nil {
1060		c.AddProperties(c.lto.props()...)
1061	}
1062	if c.pgo != nil {
1063		c.AddProperties(c.pgo.props()...)
1064	}
1065	for _, feature := range c.features {
1066		c.AddProperties(feature.props()...)
1067	}
1068
1069	android.InitAndroidArchModule(c, c.hod, c.multilib)
1070	android.InitBazelModule(c)
1071	android.InitApexModule(c)
1072	android.InitSdkAwareModule(c)
1073	android.InitDefaultableModule(c)
1074
1075	return c
1076}
1077
1078// Returns true for dependency roots (binaries)
1079// TODO(ccross): also handle dlopenable libraries
1080func (c *Module) IsDependencyRoot() bool {
1081	if root, ok := c.linker.(interface {
1082		isDependencyRoot() bool
1083	}); ok {
1084		return root.isDependencyRoot()
1085	}
1086	return false
1087}
1088
1089func (c *Module) UseVndk() bool {
1090	return c.Properties.VndkVersion != ""
1091}
1092
1093func (c *Module) canUseSdk() bool {
1094	return c.Os() == android.Android && c.Target().NativeBridge == android.NativeBridgeDisabled &&
1095		!c.UseVndk() && !c.InRamdisk() && !c.InRecovery() && !c.InVendorRamdisk()
1096}
1097
1098func (c *Module) UseSdk() bool {
1099	if c.canUseSdk() {
1100		return String(c.Properties.Sdk_version) != ""
1101	}
1102	return false
1103}
1104
1105func (c *Module) isCoverageVariant() bool {
1106	return c.coverage.Properties.IsCoverageVariant
1107}
1108
1109func (c *Module) IsNdk(config android.Config) bool {
1110	return inList(c.BaseModuleName(), *getNDKKnownLibs(config))
1111}
1112
1113func (c *Module) IsLlndk() bool {
1114	return c.VendorProperties.IsLLNDK
1115}
1116
1117func (c *Module) IsLlndkPublic() bool {
1118	return c.VendorProperties.IsLLNDK && !c.VendorProperties.IsVNDKPrivate
1119}
1120
1121func (m *Module) NeedsLlndkVariants() bool {
1122	lib := moduleLibraryInterface(m)
1123	return lib != nil && (lib.hasLLNDKStubs() || lib.hasLLNDKHeaders())
1124}
1125
1126func (m *Module) NeedsVendorPublicLibraryVariants() bool {
1127	lib := moduleLibraryInterface(m)
1128	return lib != nil && (lib.hasVendorPublicLibrary())
1129}
1130
1131// IsVendorPublicLibrary returns true for vendor public libraries.
1132func (c *Module) IsVendorPublicLibrary() bool {
1133	return c.VendorProperties.IsVendorPublicLibrary
1134}
1135
1136func (c *Module) HasLlndkStubs() bool {
1137	lib := moduleLibraryInterface(c)
1138	return lib != nil && lib.hasLLNDKStubs()
1139}
1140
1141func (c *Module) StubsVersion() string {
1142	if lib, ok := c.linker.(versionedInterface); ok {
1143		return lib.stubsVersion()
1144	}
1145	panic(fmt.Errorf("StubsVersion called on non-versioned module: %q", c.BaseModuleName()))
1146}
1147
1148// isImplementationForLLNDKPublic returns true for any variant of a cc_library that has LLNDK stubs
1149// and does not set llndk.vendor_available: false.
1150func (c *Module) isImplementationForLLNDKPublic() bool {
1151	library, _ := c.library.(*libraryDecorator)
1152	return library != nil && library.hasLLNDKStubs() &&
1153		!Bool(library.Properties.Llndk.Private)
1154}
1155
1156// Returns true for LLNDK-private, VNDK-SP-private, and VNDK-core-private.
1157func (c *Module) IsVndkPrivate() bool {
1158	// Check if VNDK-core-private or VNDK-SP-private
1159	if c.IsVndk() {
1160		return Bool(c.vndkdep.Properties.Vndk.Private)
1161	}
1162
1163	// Check if LLNDK-private
1164	if library, ok := c.library.(*libraryDecorator); ok && c.IsLlndk() {
1165		return Bool(library.Properties.Llndk.Private)
1166	}
1167
1168	return false
1169}
1170
1171func (c *Module) IsVndk() bool {
1172	if vndkdep := c.vndkdep; vndkdep != nil {
1173		return vndkdep.isVndk()
1174	}
1175	return false
1176}
1177
1178func (c *Module) isPgoCompile() bool {
1179	if pgo := c.pgo; pgo != nil {
1180		return pgo.Properties.PgoCompile
1181	}
1182	return false
1183}
1184
1185func (c *Module) isNDKStubLibrary() bool {
1186	if _, ok := c.compiler.(*stubDecorator); ok {
1187		return true
1188	}
1189	return false
1190}
1191
1192func (c *Module) IsVndkSp() bool {
1193	if vndkdep := c.vndkdep; vndkdep != nil {
1194		return vndkdep.isVndkSp()
1195	}
1196	return false
1197}
1198
1199func (c *Module) IsVndkExt() bool {
1200	if vndkdep := c.vndkdep; vndkdep != nil {
1201		return vndkdep.isVndkExt()
1202	}
1203	return false
1204}
1205
1206func (c *Module) SubName() string {
1207	return c.Properties.SubName
1208}
1209
1210func (c *Module) MustUseVendorVariant() bool {
1211	return c.IsVndkSp() || c.Properties.MustUseVendorVariant
1212}
1213
1214func (c *Module) getVndkExtendsModuleName() string {
1215	if vndkdep := c.vndkdep; vndkdep != nil {
1216		return vndkdep.getVndkExtendsModuleName()
1217	}
1218	return ""
1219}
1220
1221func (c *Module) IsStubs() bool {
1222	if lib := c.library; lib != nil {
1223		return lib.buildStubs()
1224	}
1225	return false
1226}
1227
1228func (c *Module) HasStubsVariants() bool {
1229	if lib := c.library; lib != nil {
1230		return lib.hasStubsVariants()
1231	}
1232	return false
1233}
1234
1235// If this is a stubs library, ImplementationModuleName returns the name of the module that contains
1236// the implementation.  If it is an implementation library it returns its own name.
1237func (c *Module) ImplementationModuleName(ctx android.BaseModuleContext) string {
1238	name := ctx.OtherModuleName(c)
1239	if versioned, ok := c.linker.(versionedInterface); ok {
1240		name = versioned.implementationModuleName(name)
1241	}
1242	return name
1243}
1244
1245// Similar to ImplementationModuleName, but uses the Make variant of the module
1246// name as base name, for use in AndroidMk output. E.g. for a prebuilt module
1247// where the Soong name is prebuilt_foo, this returns foo (which works in Make
1248// under the premise that the prebuilt module overrides its source counterpart
1249// if it is exposed to Make).
1250func (c *Module) ImplementationModuleNameForMake(ctx android.BaseModuleContext) string {
1251	name := c.BaseModuleName()
1252	if versioned, ok := c.linker.(versionedInterface); ok {
1253		name = versioned.implementationModuleName(name)
1254	}
1255	return name
1256}
1257
1258func (c *Module) bootstrap() bool {
1259	return Bool(c.Properties.Bootstrap)
1260}
1261
1262func (c *Module) nativeCoverage() bool {
1263	// Bug: http://b/137883967 - native-bridge modules do not currently work with coverage
1264	if c.Target().NativeBridge == android.NativeBridgeEnabled {
1265		return false
1266	}
1267	return c.linker != nil && c.linker.nativeCoverage()
1268}
1269
1270func (c *Module) IsSnapshotPrebuilt() bool {
1271	if p, ok := c.linker.(snapshotInterface); ok {
1272		return p.isSnapshotPrebuilt()
1273	}
1274	return false
1275}
1276
1277func (c *Module) ExcludeFromVendorSnapshot() bool {
1278	return Bool(c.Properties.Exclude_from_vendor_snapshot)
1279}
1280
1281func (c *Module) ExcludeFromRecoverySnapshot() bool {
1282	return Bool(c.Properties.Exclude_from_recovery_snapshot)
1283}
1284
1285func isBionic(name string) bool {
1286	switch name {
1287	case "libc", "libm", "libdl", "libdl_android", "linker", "linkerconfig":
1288		return true
1289	}
1290	return false
1291}
1292
1293func InstallToBootstrap(name string, config android.Config) bool {
1294	if name == "libclang_rt.hwasan-aarch64-android" {
1295		return true
1296	}
1297	return isBionic(name)
1298}
1299
1300func (c *Module) XrefCcFiles() android.Paths {
1301	return c.kytheFiles
1302}
1303
1304func (c *Module) isCfiAssemblySupportEnabled() bool {
1305	return c.sanitize != nil &&
1306		Bool(c.sanitize.Properties.Sanitize.Config.Cfi_assembly_support)
1307}
1308
1309type baseModuleContext struct {
1310	android.BaseModuleContext
1311	moduleContextImpl
1312}
1313
1314type depsContext struct {
1315	android.BottomUpMutatorContext
1316	moduleContextImpl
1317}
1318
1319type moduleContext struct {
1320	android.ModuleContext
1321	moduleContextImpl
1322}
1323
1324type moduleContextImpl struct {
1325	mod *Module
1326	ctx BaseModuleContext
1327}
1328
1329func (ctx *moduleContextImpl) toolchain() config.Toolchain {
1330	return ctx.mod.toolchain(ctx.ctx)
1331}
1332
1333func (ctx *moduleContextImpl) static() bool {
1334	return ctx.mod.static()
1335}
1336
1337func (ctx *moduleContextImpl) staticBinary() bool {
1338	return ctx.mod.staticBinary()
1339}
1340
1341func (ctx *moduleContextImpl) testBinary() bool {
1342	return ctx.mod.testBinary()
1343}
1344
1345func (ctx *moduleContextImpl) header() bool {
1346	return ctx.mod.Header()
1347}
1348
1349func (ctx *moduleContextImpl) binary() bool {
1350	return ctx.mod.Binary()
1351}
1352
1353func (ctx *moduleContextImpl) object() bool {
1354	return ctx.mod.Object()
1355}
1356
1357func (ctx *moduleContextImpl) canUseSdk() bool {
1358	return ctx.mod.canUseSdk()
1359}
1360
1361func (ctx *moduleContextImpl) useSdk() bool {
1362	return ctx.mod.UseSdk()
1363}
1364
1365func (ctx *moduleContextImpl) sdkVersion() string {
1366	if ctx.ctx.Device() {
1367		if ctx.useVndk() {
1368			vndkVer := ctx.mod.VndkVersion()
1369			if inList(vndkVer, ctx.ctx.Config().PlatformVersionActiveCodenames()) {
1370				return "current"
1371			}
1372			return vndkVer
1373		}
1374		return String(ctx.mod.Properties.Sdk_version)
1375	}
1376	return ""
1377}
1378
1379func (ctx *moduleContextImpl) minSdkVersion() string {
1380	ver := ctx.mod.MinSdkVersion()
1381	if ver == "apex_inherit" && !ctx.isForPlatform() {
1382		ver = ctx.apexSdkVersion().String()
1383	}
1384	if ver == "apex_inherit" || ver == "" {
1385		ver = ctx.sdkVersion()
1386	}
1387	// For crt objects, the meaning of min_sdk_version is very different from other types of
1388	// module. For them, min_sdk_version defines the oldest version that the build system will
1389	// create versioned variants for. For example, if min_sdk_version is 16, then sdk variant of
1390	// the crt object has local variants of 16, 17, ..., up to the latest version. sdk_version
1391	// and min_sdk_version properties of the variants are set to the corresponding version
1392	// numbers. However, the platform (non-sdk) variant of the crt object is left untouched.
1393	// min_sdk_version: 16 doesn't actually mean that the platform variant has to support such
1394	// an old version. Since the variant is for the platform, it's preferred to target the
1395	// latest version.
1396	if ctx.mod.SplitPerApiLevel() && !ctx.isSdkVariant() {
1397		ver = strconv.Itoa(android.FutureApiLevelInt)
1398	}
1399
1400	// Also make sure that minSdkVersion is not greater than sdkVersion, if they are both numbers
1401	sdkVersionInt, err := strconv.Atoi(ctx.sdkVersion())
1402	minSdkVersionInt, err2 := strconv.Atoi(ver)
1403	if err == nil && err2 == nil {
1404		if sdkVersionInt < minSdkVersionInt {
1405			return strconv.Itoa(sdkVersionInt)
1406		}
1407	}
1408	return ver
1409}
1410
1411func (ctx *moduleContextImpl) isSdkVariant() bool {
1412	return ctx.mod.IsSdkVariant()
1413}
1414
1415func (ctx *moduleContextImpl) useVndk() bool {
1416	return ctx.mod.UseVndk()
1417}
1418
1419func (ctx *moduleContextImpl) isNdk(config android.Config) bool {
1420	return ctx.mod.IsNdk(config)
1421}
1422
1423func (ctx *moduleContextImpl) IsLlndk() bool {
1424	return ctx.mod.IsLlndk()
1425}
1426
1427func (ctx *moduleContextImpl) IsLlndkPublic() bool {
1428	return ctx.mod.IsLlndkPublic()
1429}
1430
1431func (ctx *moduleContextImpl) isImplementationForLLNDKPublic() bool {
1432	return ctx.mod.isImplementationForLLNDKPublic()
1433}
1434
1435func (ctx *moduleContextImpl) IsVndkPrivate() bool {
1436	return ctx.mod.IsVndkPrivate()
1437}
1438
1439func (ctx *moduleContextImpl) isVndk() bool {
1440	return ctx.mod.IsVndk()
1441}
1442
1443func (ctx *moduleContextImpl) isPgoCompile() bool {
1444	return ctx.mod.isPgoCompile()
1445}
1446
1447func (ctx *moduleContextImpl) isNDKStubLibrary() bool {
1448	return ctx.mod.isNDKStubLibrary()
1449}
1450
1451func (ctx *moduleContextImpl) isVndkSp() bool {
1452	return ctx.mod.IsVndkSp()
1453}
1454
1455func (ctx *moduleContextImpl) IsVndkExt() bool {
1456	return ctx.mod.IsVndkExt()
1457}
1458
1459func (ctx *moduleContextImpl) IsVendorPublicLibrary() bool {
1460	return ctx.mod.IsVendorPublicLibrary()
1461}
1462
1463func (ctx *moduleContextImpl) mustUseVendorVariant() bool {
1464	return ctx.mod.MustUseVendorVariant()
1465}
1466
1467func (ctx *moduleContextImpl) selectedStl() string {
1468	if stl := ctx.mod.stl; stl != nil {
1469		return stl.Properties.SelectedStl
1470	}
1471	return ""
1472}
1473
1474func (ctx *moduleContextImpl) useClangLld(actx ModuleContext) bool {
1475	return ctx.mod.linker.useClangLld(actx)
1476}
1477
1478func (ctx *moduleContextImpl) baseModuleName() string {
1479	return ctx.mod.ModuleBase.BaseModuleName()
1480}
1481
1482func (ctx *moduleContextImpl) getVndkExtendsModuleName() string {
1483	return ctx.mod.getVndkExtendsModuleName()
1484}
1485
1486func (ctx *moduleContextImpl) isForPlatform() bool {
1487	return ctx.ctx.Provider(android.ApexInfoProvider).(android.ApexInfo).IsForPlatform()
1488}
1489
1490func (ctx *moduleContextImpl) apexVariationName() string {
1491	return ctx.ctx.Provider(android.ApexInfoProvider).(android.ApexInfo).ApexVariationName
1492}
1493
1494func (ctx *moduleContextImpl) apexSdkVersion() android.ApiLevel {
1495	return ctx.mod.apexSdkVersion
1496}
1497
1498func (ctx *moduleContextImpl) bootstrap() bool {
1499	return ctx.mod.bootstrap()
1500}
1501
1502func (ctx *moduleContextImpl) nativeCoverage() bool {
1503	return ctx.mod.nativeCoverage()
1504}
1505
1506func (ctx *moduleContextImpl) directlyInAnyApex() bool {
1507	return ctx.mod.DirectlyInAnyApex()
1508}
1509
1510func (ctx *moduleContextImpl) isPreventInstall() bool {
1511	return ctx.mod.Properties.PreventInstall
1512}
1513
1514func (ctx *moduleContextImpl) isCfiAssemblySupportEnabled() bool {
1515	return ctx.mod.isCfiAssemblySupportEnabled()
1516}
1517
1518func newBaseModule(hod android.HostOrDeviceSupported, multilib android.Multilib) *Module {
1519	return &Module{
1520		hod:      hod,
1521		multilib: multilib,
1522	}
1523}
1524
1525func newModule(hod android.HostOrDeviceSupported, multilib android.Multilib) *Module {
1526	module := newBaseModule(hod, multilib)
1527	module.features = []feature{
1528		&tidyFeature{},
1529	}
1530	module.stl = &stl{}
1531	module.sanitize = &sanitize{}
1532	module.coverage = &coverage{}
1533	module.sabi = &sabi{}
1534	module.vndkdep = &vndkdep{}
1535	module.lto = &lto{}
1536	module.pgo = &pgo{}
1537	return module
1538}
1539
1540func (c *Module) Prebuilt() *android.Prebuilt {
1541	if p, ok := c.linker.(prebuiltLinkerInterface); ok {
1542		return p.prebuilt()
1543	}
1544	return nil
1545}
1546
1547func (c *Module) IsPrebuilt() bool {
1548	return c.Prebuilt() != nil
1549}
1550
1551func (c *Module) Name() string {
1552	name := c.ModuleBase.Name()
1553	if p, ok := c.linker.(interface {
1554		Name(string) string
1555	}); ok {
1556		name = p.Name(name)
1557	}
1558	return name
1559}
1560
1561func (c *Module) Symlinks() []string {
1562	if p, ok := c.installer.(interface {
1563		symlinkList() []string
1564	}); ok {
1565		return p.symlinkList()
1566	}
1567	return nil
1568}
1569
1570func (c *Module) IsTestPerSrcAllTestsVariation() bool {
1571	test, ok := c.linker.(testPerSrc)
1572	return ok && test.isAllTestsVariation()
1573}
1574
1575func (c *Module) DataPaths() []android.DataPath {
1576	if p, ok := c.installer.(interface {
1577		dataPaths() []android.DataPath
1578	}); ok {
1579		return p.dataPaths()
1580	}
1581	return nil
1582}
1583
1584func (c *Module) getNameSuffixWithVndkVersion(ctx android.ModuleContext) string {
1585	// Returns the name suffix for product and vendor variants. If the VNDK version is not
1586	// "current", it will append the VNDK version to the name suffix.
1587	var vndkVersion string
1588	var nameSuffix string
1589	if c.InProduct() {
1590		if c.ProductSpecific() {
1591			// If the module is product specific with 'product_specific: true',
1592			// do not add a name suffix because it is a base module.
1593			return ""
1594		}
1595		vndkVersion = ctx.DeviceConfig().ProductVndkVersion()
1596		nameSuffix = productSuffix
1597	} else {
1598		vndkVersion = ctx.DeviceConfig().VndkVersion()
1599		nameSuffix = VendorSuffix
1600	}
1601	if vndkVersion == "current" {
1602		vndkVersion = ctx.DeviceConfig().PlatformVndkVersion()
1603	}
1604	if c.Properties.VndkVersion != vndkVersion && c.Properties.VndkVersion != "" {
1605		// add version suffix only if the module is using different vndk version than the
1606		// version in product or vendor partition.
1607		nameSuffix += "." + c.Properties.VndkVersion
1608	}
1609	return nameSuffix
1610}
1611
1612func (c *Module) setSubnameProperty(actx android.ModuleContext) {
1613	c.Properties.SubName = ""
1614
1615	if c.Target().NativeBridge == android.NativeBridgeEnabled {
1616		c.Properties.SubName += nativeBridgeSuffix
1617	}
1618
1619	llndk := c.IsLlndk()
1620	if llndk || (c.UseVndk() && c.HasNonSystemVariants()) {
1621		// .vendor.{version} suffix is added for vendor variant or .product.{version} suffix is
1622		// added for product variant only when we have vendor and product variants with core
1623		// variant. The suffix is not added for vendor-only or product-only module.
1624		c.Properties.SubName += c.getNameSuffixWithVndkVersion(actx)
1625	} else if c.IsVendorPublicLibrary() {
1626		c.Properties.SubName += vendorPublicLibrarySuffix
1627	} else if _, ok := c.linker.(*vndkPrebuiltLibraryDecorator); ok {
1628		// .vendor suffix is added for backward compatibility with VNDK snapshot whose names with
1629		// such suffixes are already hard-coded in prebuilts/vndk/.../Android.bp.
1630		c.Properties.SubName += VendorSuffix
1631	} else if c.InRamdisk() && !c.OnlyInRamdisk() {
1632		c.Properties.SubName += ramdiskSuffix
1633	} else if c.InVendorRamdisk() && !c.OnlyInVendorRamdisk() {
1634		c.Properties.SubName += VendorRamdiskSuffix
1635	} else if c.InRecovery() && !c.OnlyInRecovery() {
1636		c.Properties.SubName += recoverySuffix
1637	} else if c.IsSdkVariant() && (c.Properties.SdkAndPlatformVariantVisibleToMake || c.SplitPerApiLevel()) {
1638		c.Properties.SubName += sdkSuffix
1639		if c.SplitPerApiLevel() {
1640			c.Properties.SubName += "." + c.SdkVersion()
1641		}
1642	}
1643}
1644
1645// Returns true if Bazel was successfully used for the analysis of this module.
1646func (c *Module) maybeGenerateBazelActions(actx android.ModuleContext) bool {
1647	bazelModuleLabel := c.GetBazelLabel(actx, c)
1648	bazelActionsUsed := false
1649	if c.MixedBuildsEnabled(actx) && c.bazelHandler != nil {
1650		bazelActionsUsed = c.bazelHandler.generateBazelBuildActions(actx, bazelModuleLabel)
1651	}
1652	return bazelActionsUsed
1653}
1654
1655func (c *Module) GenerateAndroidBuildActions(actx android.ModuleContext) {
1656	// TODO(cparsons): Any logic in this method occurring prior to querying Bazel should be
1657	// requested from Bazel instead.
1658
1659	// Handle the case of a test module split by `test_per_src` mutator.
1660	//
1661	// The `test_per_src` mutator adds an extra variation named "", depending on all the other
1662	// `test_per_src` variations of the test module. Set `outputFile` to an empty path for this
1663	// module and return early, as this module does not produce an output file per se.
1664	if c.IsTestPerSrcAllTestsVariation() {
1665		c.outputFile = android.OptionalPath{}
1666		return
1667	}
1668
1669	c.setSubnameProperty(actx)
1670	apexInfo := actx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1671	if !apexInfo.IsForPlatform() {
1672		c.hideApexVariantFromMake = true
1673	}
1674
1675	c.makeLinkType = GetMakeLinkType(actx, c)
1676
1677	if c.maybeGenerateBazelActions(actx) {
1678		return
1679	}
1680
1681	ctx := &moduleContext{
1682		ModuleContext: actx,
1683		moduleContextImpl: moduleContextImpl{
1684			mod: c,
1685		},
1686	}
1687	ctx.ctx = ctx
1688
1689	deps := c.depsToPaths(ctx)
1690	if ctx.Failed() {
1691		return
1692	}
1693
1694	if c.Properties.Clang != nil && *c.Properties.Clang == false {
1695		ctx.PropertyErrorf("clang", "false (GCC) is no longer supported")
1696	}
1697
1698	flags := Flags{
1699		Toolchain: c.toolchain(ctx),
1700		EmitXrefs: ctx.Config().EmitXrefRules(),
1701	}
1702	if c.compiler != nil {
1703		flags = c.compiler.compilerFlags(ctx, flags, deps)
1704	}
1705	if c.linker != nil {
1706		flags = c.linker.linkerFlags(ctx, flags)
1707	}
1708	if c.stl != nil {
1709		flags = c.stl.flags(ctx, flags)
1710	}
1711	if c.sanitize != nil {
1712		flags = c.sanitize.flags(ctx, flags)
1713	}
1714	if c.coverage != nil {
1715		flags, deps = c.coverage.flags(ctx, flags, deps)
1716	}
1717	if c.lto != nil {
1718		flags = c.lto.flags(ctx, flags)
1719	}
1720	if c.pgo != nil {
1721		flags = c.pgo.flags(ctx, flags)
1722	}
1723	for _, feature := range c.features {
1724		flags = feature.flags(ctx, flags)
1725	}
1726	if ctx.Failed() {
1727		return
1728	}
1729
1730	flags.Local.CFlags, _ = filterList(flags.Local.CFlags, config.IllegalFlags)
1731	flags.Local.CppFlags, _ = filterList(flags.Local.CppFlags, config.IllegalFlags)
1732	flags.Local.ConlyFlags, _ = filterList(flags.Local.ConlyFlags, config.IllegalFlags)
1733
1734	flags.Local.CommonFlags = append(flags.Local.CommonFlags, deps.Flags...)
1735
1736	for _, dir := range deps.IncludeDirs {
1737		flags.Local.CommonFlags = append(flags.Local.CommonFlags, "-I"+dir.String())
1738	}
1739	for _, dir := range deps.SystemIncludeDirs {
1740		flags.Local.CommonFlags = append(flags.Local.CommonFlags, "-isystem "+dir.String())
1741	}
1742
1743	c.flags = flags
1744	// We need access to all the flags seen by a source file.
1745	if c.sabi != nil {
1746		flags = c.sabi.flags(ctx, flags)
1747	}
1748
1749	flags.AssemblerWithCpp = inList("-xassembler-with-cpp", flags.Local.AsFlags)
1750
1751	// Optimization to reduce size of build.ninja
1752	// Replace the long list of flags for each file with a module-local variable
1753	ctx.Variable(pctx, "cflags", strings.Join(flags.Local.CFlags, " "))
1754	ctx.Variable(pctx, "cppflags", strings.Join(flags.Local.CppFlags, " "))
1755	ctx.Variable(pctx, "asflags", strings.Join(flags.Local.AsFlags, " "))
1756	flags.Local.CFlags = []string{"$cflags"}
1757	flags.Local.CppFlags = []string{"$cppflags"}
1758	flags.Local.AsFlags = []string{"$asflags"}
1759
1760	var objs Objects
1761	if c.compiler != nil {
1762		objs = c.compiler.compile(ctx, flags, deps)
1763		if ctx.Failed() {
1764			return
1765		}
1766		c.kytheFiles = objs.kytheFiles
1767	}
1768
1769	if c.linker != nil {
1770		outputFile := c.linker.link(ctx, flags, deps, objs)
1771		if ctx.Failed() {
1772			return
1773		}
1774		c.outputFile = android.OptionalPathForPath(outputFile)
1775
1776		// If a lib is directly included in any of the APEXes or is not available to the
1777		// platform (which is often the case when the stub is provided as a prebuilt),
1778		// unhide the stubs variant having the latest version gets visible to make. In
1779		// addition, the non-stubs variant is renamed to <libname>.bootstrap. This is to
1780		// force anything in the make world to link against the stubs library.  (unless it
1781		// is explicitly referenced via .bootstrap suffix or the module is marked with
1782		// 'bootstrap: true').
1783		if c.HasStubsVariants() && c.NotInPlatform() && !c.InRamdisk() &&
1784			!c.InRecovery() && !c.UseVndk() && !c.static() && !c.isCoverageVariant() &&
1785			c.IsStubs() && !c.InVendorRamdisk() {
1786			c.Properties.HideFromMake = false // unhide
1787			// Note: this is still non-installable
1788		}
1789
1790		// glob exported headers for snapshot, if BOARD_VNDK_VERSION is current or
1791		// RECOVERY_SNAPSHOT_VERSION is current.
1792		if i, ok := c.linker.(snapshotLibraryInterface); ok {
1793			if ShouldCollectHeadersForSnapshot(ctx, c, apexInfo) {
1794				i.collectHeadersForSnapshot(ctx)
1795			}
1796		}
1797	}
1798
1799	if !proptools.BoolDefault(c.Properties.Installable, true) {
1800		// If the module has been specifically configure to not be installed then
1801		// hide from make as otherwise it will break when running inside make
1802		// as the output path to install will not be specified. Not all uninstallable
1803		// modules can be hidden from make as some are needed for resolving make side
1804		// dependencies.
1805		c.HideFromMake()
1806	} else if !installable(c, apexInfo) {
1807		c.SkipInstall()
1808	}
1809
1810	// Still call c.installer.install though, the installs will be stored as PackageSpecs
1811	// to allow using the outputs in a genrule.
1812	if c.installer != nil && c.outputFile.Valid() {
1813		c.installer.install(ctx, c.outputFile.Path())
1814		if ctx.Failed() {
1815			return
1816		}
1817	}
1818}
1819
1820func (c *Module) toolchain(ctx android.BaseModuleContext) config.Toolchain {
1821	if c.cachedToolchain == nil {
1822		c.cachedToolchain = config.FindToolchainWithContext(ctx)
1823	}
1824	return c.cachedToolchain
1825}
1826
1827func (c *Module) begin(ctx BaseModuleContext) {
1828	if c.compiler != nil {
1829		c.compiler.compilerInit(ctx)
1830	}
1831	if c.linker != nil {
1832		c.linker.linkerInit(ctx)
1833	}
1834	if c.stl != nil {
1835		c.stl.begin(ctx)
1836	}
1837	if c.sanitize != nil {
1838		c.sanitize.begin(ctx)
1839	}
1840	if c.coverage != nil {
1841		c.coverage.begin(ctx)
1842	}
1843	if c.sabi != nil {
1844		c.sabi.begin(ctx)
1845	}
1846	if c.vndkdep != nil {
1847		c.vndkdep.begin(ctx)
1848	}
1849	if c.lto != nil {
1850		c.lto.begin(ctx)
1851	}
1852	if c.pgo != nil {
1853		c.pgo.begin(ctx)
1854	}
1855	for _, feature := range c.features {
1856		feature.begin(ctx)
1857	}
1858	if ctx.useSdk() && c.IsSdkVariant() {
1859		version, err := nativeApiLevelFromUser(ctx, ctx.sdkVersion())
1860		if err != nil {
1861			ctx.PropertyErrorf("sdk_version", err.Error())
1862			c.Properties.Sdk_version = nil
1863		} else {
1864			c.Properties.Sdk_version = StringPtr(version.String())
1865		}
1866	}
1867}
1868
1869func (c *Module) deps(ctx DepsContext) Deps {
1870	deps := Deps{}
1871
1872	if c.compiler != nil {
1873		deps = c.compiler.compilerDeps(ctx, deps)
1874	}
1875	if c.linker != nil {
1876		deps = c.linker.linkerDeps(ctx, deps)
1877	}
1878	if c.stl != nil {
1879		deps = c.stl.deps(ctx, deps)
1880	}
1881	if c.sanitize != nil {
1882		deps = c.sanitize.deps(ctx, deps)
1883	}
1884	if c.coverage != nil {
1885		deps = c.coverage.deps(ctx, deps)
1886	}
1887	if c.sabi != nil {
1888		deps = c.sabi.deps(ctx, deps)
1889	}
1890	if c.vndkdep != nil {
1891		deps = c.vndkdep.deps(ctx, deps)
1892	}
1893	if c.lto != nil {
1894		deps = c.lto.deps(ctx, deps)
1895	}
1896	for _, feature := range c.features {
1897		deps = feature.deps(ctx, deps)
1898	}
1899
1900	deps.WholeStaticLibs = android.LastUniqueStrings(deps.WholeStaticLibs)
1901	deps.StaticLibs = android.LastUniqueStrings(deps.StaticLibs)
1902	deps.LateStaticLibs = android.LastUniqueStrings(deps.LateStaticLibs)
1903	deps.SharedLibs = android.LastUniqueStrings(deps.SharedLibs)
1904	deps.LateSharedLibs = android.LastUniqueStrings(deps.LateSharedLibs)
1905	deps.HeaderLibs = android.LastUniqueStrings(deps.HeaderLibs)
1906	deps.RuntimeLibs = android.LastUniqueStrings(deps.RuntimeLibs)
1907
1908	// In Bazel conversion mode, we dependency and build validations will occur in Bazel, so there is
1909	// no need to do so in Soong.
1910	if ctx.BazelConversionMode() {
1911		return deps
1912	}
1913
1914	for _, lib := range deps.ReexportSharedLibHeaders {
1915		if !inList(lib, deps.SharedLibs) {
1916			ctx.PropertyErrorf("export_shared_lib_headers", "Shared library not in shared_libs: '%s'", lib)
1917		}
1918	}
1919
1920	for _, lib := range deps.ReexportStaticLibHeaders {
1921		if !inList(lib, deps.StaticLibs) && !inList(lib, deps.WholeStaticLibs) {
1922			ctx.PropertyErrorf("export_static_lib_headers", "Static library not in static_libs or whole_static_libs: '%s'", lib)
1923		}
1924	}
1925
1926	for _, lib := range deps.ReexportHeaderLibHeaders {
1927		if !inList(lib, deps.HeaderLibs) {
1928			ctx.PropertyErrorf("export_header_lib_headers", "Header library not in header_libs: '%s'", lib)
1929		}
1930	}
1931
1932	for _, gen := range deps.ReexportGeneratedHeaders {
1933		if !inList(gen, deps.GeneratedHeaders) {
1934			ctx.PropertyErrorf("export_generated_headers", "Generated header module not in generated_headers: '%s'", gen)
1935		}
1936	}
1937
1938	return deps
1939}
1940
1941func (c *Module) beginMutator(actx android.BottomUpMutatorContext) {
1942	ctx := &baseModuleContext{
1943		BaseModuleContext: actx,
1944		moduleContextImpl: moduleContextImpl{
1945			mod: c,
1946		},
1947	}
1948	ctx.ctx = ctx
1949
1950	c.begin(ctx)
1951}
1952
1953// Split name#version into name and version
1954func StubsLibNameAndVersion(name string) (string, string) {
1955	if sharp := strings.LastIndex(name, "#"); sharp != -1 && sharp != len(name)-1 {
1956		version := name[sharp+1:]
1957		libname := name[:sharp]
1958		return libname, version
1959	}
1960	return name, ""
1961}
1962
1963func GetCrtVariations(ctx android.BottomUpMutatorContext,
1964	m LinkableInterface) []blueprint.Variation {
1965	if ctx.Os() != android.Android {
1966		return nil
1967	}
1968	if m.UseSdk() {
1969		// Choose the CRT that best satisfies the min_sdk_version requirement of this module
1970		minSdkVersion := m.MinSdkVersion()
1971		if minSdkVersion == "" || minSdkVersion == "apex_inherit" {
1972			minSdkVersion = m.SdkVersion()
1973		}
1974		apiLevel, err := android.ApiLevelFromUser(ctx, minSdkVersion)
1975		if err != nil {
1976			ctx.PropertyErrorf("min_sdk_version", err.Error())
1977		}
1978		return []blueprint.Variation{
1979			{Mutator: "sdk", Variation: "sdk"},
1980			{Mutator: "version", Variation: apiLevel.String()},
1981		}
1982	}
1983	return []blueprint.Variation{
1984		{Mutator: "sdk", Variation: ""},
1985	}
1986}
1987
1988func (c *Module) addSharedLibDependenciesWithVersions(ctx android.BottomUpMutatorContext,
1989	variations []blueprint.Variation, depTag libraryDependencyTag, name, version string, far bool) {
1990
1991	variations = append([]blueprint.Variation(nil), variations...)
1992
1993	if version != "" && CanBeOrLinkAgainstVersionVariants(c) {
1994		// Version is explicitly specified. i.e. libFoo#30
1995		variations = append(variations, blueprint.Variation{Mutator: "version", Variation: version})
1996		depTag.explicitlyVersioned = true
1997	}
1998
1999	if far {
2000		ctx.AddFarVariationDependencies(variations, depTag, name)
2001	} else {
2002		ctx.AddVariationDependencies(variations, depTag, name)
2003	}
2004}
2005
2006func (c *Module) DepsMutator(actx android.BottomUpMutatorContext) {
2007	if !c.Enabled() {
2008		return
2009	}
2010
2011	ctx := &depsContext{
2012		BottomUpMutatorContext: actx,
2013		moduleContextImpl: moduleContextImpl{
2014			mod: c,
2015		},
2016	}
2017	ctx.ctx = ctx
2018
2019	deps := c.deps(ctx)
2020
2021	c.Properties.AndroidMkSystemSharedLibs = deps.SystemSharedLibs
2022
2023	var snapshotInfo *SnapshotInfo
2024	getSnapshot := func() SnapshotInfo {
2025		// Only modules with BOARD_VNDK_VERSION uses snapshot.  Others use the zero value of
2026		// SnapshotInfo, which provides no mappings.
2027		if snapshotInfo == nil {
2028			// Only retrieve the snapshot on demand in order to avoid circular dependencies
2029			// between the modules in the snapshot and the snapshot itself.
2030			var snapshotModule []blueprint.Module
2031			if c.InVendor() && c.VndkVersion() == actx.DeviceConfig().VndkVersion() {
2032				snapshotModule = ctx.AddVariationDependencies(nil, nil, "vendor_snapshot")
2033			} else if recoverySnapshotVersion := actx.DeviceConfig().RecoverySnapshotVersion(); recoverySnapshotVersion != "current" && recoverySnapshotVersion != "" && c.InRecovery() {
2034				snapshotModule = ctx.AddVariationDependencies(nil, nil, "recovery_snapshot")
2035			}
2036			if len(snapshotModule) > 0 {
2037				snapshot := ctx.OtherModuleProvider(snapshotModule[0], SnapshotInfoProvider).(SnapshotInfo)
2038				snapshotInfo = &snapshot
2039				// republish the snapshot for use in later mutators on this module
2040				ctx.SetProvider(SnapshotInfoProvider, snapshot)
2041			} else {
2042				snapshotInfo = &SnapshotInfo{}
2043			}
2044		}
2045
2046		return *snapshotInfo
2047	}
2048
2049	rewriteSnapshotLib := func(lib string, snapshotMap map[string]string) string {
2050		if snapshot, ok := snapshotMap[lib]; ok {
2051			return snapshot
2052		}
2053
2054		return lib
2055	}
2056
2057	variantNdkLibs := []string{}
2058	variantLateNdkLibs := []string{}
2059	if ctx.Os() == android.Android {
2060		// rewriteLibs takes a list of names of shared libraries and scans it for three types
2061		// of names:
2062		//
2063		// 1. Name of an NDK library that refers to a prebuilt module.
2064		//    For each of these, it adds the name of the prebuilt module (which will be in
2065		//    prebuilts/ndk) to the list of nonvariant libs.
2066		// 2. Name of an NDK library that refers to an ndk_library module.
2067		//    For each of these, it adds the name of the ndk_library module to the list of
2068		//    variant libs.
2069		// 3. Anything else (so anything that isn't an NDK library).
2070		//    It adds these to the nonvariantLibs list.
2071		//
2072		// The caller can then know to add the variantLibs dependencies differently from the
2073		// nonvariantLibs
2074
2075		rewriteLibs := func(list []string) (nonvariantLibs []string, variantLibs []string) {
2076			variantLibs = []string{}
2077			nonvariantLibs = []string{}
2078			for _, entry := range list {
2079				// strip #version suffix out
2080				name, _ := StubsLibNameAndVersion(entry)
2081				if c.InRecovery() {
2082					nonvariantLibs = append(nonvariantLibs, rewriteSnapshotLib(entry, getSnapshot().SharedLibs))
2083				} else if ctx.useSdk() && inList(name, *getNDKKnownLibs(ctx.Config())) {
2084					variantLibs = append(variantLibs, name+ndkLibrarySuffix)
2085				} else if ctx.useVndk() {
2086					nonvariantLibs = append(nonvariantLibs, rewriteSnapshotLib(entry, getSnapshot().SharedLibs))
2087				} else {
2088					// put name#version back
2089					nonvariantLibs = append(nonvariantLibs, entry)
2090				}
2091			}
2092			return nonvariantLibs, variantLibs
2093		}
2094
2095		deps.SharedLibs, variantNdkLibs = rewriteLibs(deps.SharedLibs)
2096		deps.LateSharedLibs, variantLateNdkLibs = rewriteLibs(deps.LateSharedLibs)
2097		deps.ReexportSharedLibHeaders, _ = rewriteLibs(deps.ReexportSharedLibHeaders)
2098
2099		for idx, lib := range deps.RuntimeLibs {
2100			deps.RuntimeLibs[idx] = rewriteSnapshotLib(lib, getSnapshot().SharedLibs)
2101		}
2102	}
2103
2104	for _, lib := range deps.HeaderLibs {
2105		depTag := libraryDependencyTag{Kind: headerLibraryDependency}
2106		if inList(lib, deps.ReexportHeaderLibHeaders) {
2107			depTag.reexportFlags = true
2108		}
2109
2110		lib = rewriteSnapshotLib(lib, getSnapshot().HeaderLibs)
2111
2112		if c.IsStubs() {
2113			actx.AddFarVariationDependencies(append(ctx.Target().Variations(), c.ImageVariation()),
2114				depTag, lib)
2115		} else {
2116			actx.AddVariationDependencies(nil, depTag, lib)
2117		}
2118	}
2119
2120	// sysprop_library has to support both C++ and Java. So sysprop_library internally creates one
2121	// C++ implementation library and one Java implementation library. When a module links against
2122	// sysprop_library, the C++ implementation library has to be linked. syspropImplLibraries is a
2123	// map from sysprop_library to implementation library; it will be used in whole_static_libs,
2124	// static_libs, and shared_libs.
2125	syspropImplLibraries := syspropImplLibraries(actx.Config())
2126
2127	for _, lib := range deps.WholeStaticLibs {
2128		depTag := libraryDependencyTag{Kind: staticLibraryDependency, wholeStatic: true, reexportFlags: true}
2129		if impl, ok := syspropImplLibraries[lib]; ok {
2130			lib = impl
2131		}
2132
2133		lib = rewriteSnapshotLib(lib, getSnapshot().StaticLibs)
2134
2135		actx.AddVariationDependencies([]blueprint.Variation{
2136			{Mutator: "link", Variation: "static"},
2137		}, depTag, lib)
2138	}
2139
2140	for _, lib := range deps.StaticLibs {
2141		depTag := libraryDependencyTag{Kind: staticLibraryDependency}
2142		if inList(lib, deps.ReexportStaticLibHeaders) {
2143			depTag.reexportFlags = true
2144		}
2145		if inList(lib, deps.ExcludeLibsForApex) {
2146			depTag.excludeInApex = true
2147		}
2148
2149		if impl, ok := syspropImplLibraries[lib]; ok {
2150			lib = impl
2151		}
2152
2153		lib = rewriteSnapshotLib(lib, getSnapshot().StaticLibs)
2154
2155		actx.AddVariationDependencies([]blueprint.Variation{
2156			{Mutator: "link", Variation: "static"},
2157		}, depTag, lib)
2158	}
2159
2160	// staticUnwinderDep is treated as staticDep for Q apexes
2161	// so that native libraries/binaries are linked with static unwinder
2162	// because Q libc doesn't have unwinder APIs
2163	if deps.StaticUnwinderIfLegacy {
2164		depTag := libraryDependencyTag{Kind: staticLibraryDependency, staticUnwinder: true}
2165		actx.AddVariationDependencies([]blueprint.Variation{
2166			{Mutator: "link", Variation: "static"},
2167		}, depTag, rewriteSnapshotLib(staticUnwinder(actx), getSnapshot().StaticLibs))
2168	}
2169
2170	for _, lib := range deps.LateStaticLibs {
2171		depTag := libraryDependencyTag{Kind: staticLibraryDependency, Order: lateLibraryDependency}
2172		actx.AddVariationDependencies([]blueprint.Variation{
2173			{Mutator: "link", Variation: "static"},
2174		}, depTag, rewriteSnapshotLib(lib, getSnapshot().StaticLibs))
2175	}
2176
2177	// shared lib names without the #version suffix
2178	var sharedLibNames []string
2179
2180	for _, lib := range deps.SharedLibs {
2181		depTag := libraryDependencyTag{Kind: sharedLibraryDependency}
2182		if inList(lib, deps.ReexportSharedLibHeaders) {
2183			depTag.reexportFlags = true
2184		}
2185		if inList(lib, deps.ExcludeLibsForApex) {
2186			depTag.excludeInApex = true
2187		}
2188
2189		if impl, ok := syspropImplLibraries[lib]; ok {
2190			lib = impl
2191		}
2192
2193		name, version := StubsLibNameAndVersion(lib)
2194		sharedLibNames = append(sharedLibNames, name)
2195
2196		variations := []blueprint.Variation{
2197			{Mutator: "link", Variation: "shared"},
2198		}
2199		c.addSharedLibDependenciesWithVersions(ctx, variations, depTag, name, version, false)
2200	}
2201
2202	for _, lib := range deps.LateSharedLibs {
2203		if inList(lib, sharedLibNames) {
2204			// This is to handle the case that some of the late shared libs (libc, libdl, libm, ...)
2205			// are added also to SharedLibs with version (e.g., libc#10). If not skipped, we will be
2206			// linking against both the stubs lib and the non-stubs lib at the same time.
2207			continue
2208		}
2209		depTag := libraryDependencyTag{Kind: sharedLibraryDependency, Order: lateLibraryDependency}
2210		variations := []blueprint.Variation{
2211			{Mutator: "link", Variation: "shared"},
2212		}
2213		c.addSharedLibDependenciesWithVersions(ctx, variations, depTag, lib, "", false)
2214	}
2215
2216	actx.AddVariationDependencies([]blueprint.Variation{
2217		{Mutator: "link", Variation: "shared"},
2218	}, dataLibDepTag, deps.DataLibs...)
2219
2220	actx.AddVariationDependencies([]blueprint.Variation{
2221		{Mutator: "link", Variation: "shared"},
2222	}, runtimeDepTag, deps.RuntimeLibs...)
2223
2224	actx.AddDependency(c, genSourceDepTag, deps.GeneratedSources...)
2225
2226	for _, gen := range deps.GeneratedHeaders {
2227		depTag := genHeaderDepTag
2228		if inList(gen, deps.ReexportGeneratedHeaders) {
2229			depTag = genHeaderExportDepTag
2230		}
2231		actx.AddDependency(c, depTag, gen)
2232	}
2233
2234	crtVariations := GetCrtVariations(ctx, c)
2235	actx.AddVariationDependencies(crtVariations, objDepTag, deps.ObjFiles...)
2236	if deps.CrtBegin != "" {
2237		actx.AddVariationDependencies(crtVariations, CrtBeginDepTag,
2238			rewriteSnapshotLib(deps.CrtBegin, getSnapshot().Objects))
2239	}
2240	if deps.CrtEnd != "" {
2241		actx.AddVariationDependencies(crtVariations, CrtEndDepTag,
2242			rewriteSnapshotLib(deps.CrtEnd, getSnapshot().Objects))
2243	}
2244	if deps.LinkerFlagsFile != "" {
2245		actx.AddDependency(c, linkerFlagsDepTag, deps.LinkerFlagsFile)
2246	}
2247	if deps.DynamicLinker != "" {
2248		actx.AddDependency(c, dynamicLinkerDepTag, deps.DynamicLinker)
2249	}
2250
2251	version := ctx.sdkVersion()
2252
2253	ndkStubDepTag := libraryDependencyTag{Kind: sharedLibraryDependency, ndk: true, makeSuffix: "." + version}
2254	actx.AddVariationDependencies([]blueprint.Variation{
2255		{Mutator: "version", Variation: version},
2256		{Mutator: "link", Variation: "shared"},
2257	}, ndkStubDepTag, variantNdkLibs...)
2258
2259	ndkLateStubDepTag := libraryDependencyTag{Kind: sharedLibraryDependency, Order: lateLibraryDependency, ndk: true, makeSuffix: "." + version}
2260	actx.AddVariationDependencies([]blueprint.Variation{
2261		{Mutator: "version", Variation: version},
2262		{Mutator: "link", Variation: "shared"},
2263	}, ndkLateStubDepTag, variantLateNdkLibs...)
2264
2265	if vndkdep := c.vndkdep; vndkdep != nil {
2266		if vndkdep.isVndkExt() {
2267			actx.AddVariationDependencies([]blueprint.Variation{
2268				c.ImageVariation(),
2269				{Mutator: "link", Variation: "shared"},
2270			}, vndkExtDepTag, vndkdep.getVndkExtendsModuleName())
2271		}
2272	}
2273}
2274
2275func BeginMutator(ctx android.BottomUpMutatorContext) {
2276	if c, ok := ctx.Module().(*Module); ok && c.Enabled() {
2277		c.beginMutator(ctx)
2278	}
2279}
2280
2281// Whether a module can link to another module, taking into
2282// account NDK linking.
2283func checkLinkType(ctx android.BaseModuleContext, from LinkableInterface, to LinkableInterface,
2284	tag blueprint.DependencyTag) {
2285
2286	switch t := tag.(type) {
2287	case dependencyTag:
2288		if t != vndkExtDepTag {
2289			return
2290		}
2291	case libraryDependencyTag:
2292	default:
2293		return
2294	}
2295
2296	if from.Target().Os != android.Android {
2297		// Host code is not restricted
2298		return
2299	}
2300
2301	// VNDK is cc.Module supported only for now.
2302	if ccFrom, ok := from.(*Module); ok && from.UseVndk() {
2303		// Though allowed dependency is limited by the image mutator,
2304		// each vendor and product module needs to check link-type
2305		// for VNDK.
2306		if ccTo, ok := to.(*Module); ok {
2307			if ccFrom.vndkdep != nil {
2308				ccFrom.vndkdep.vndkCheckLinkType(ctx, ccTo, tag)
2309			}
2310		} else if _, ok := to.(LinkableInterface); !ok {
2311			ctx.ModuleErrorf("Attempting to link VNDK cc.Module with unsupported module type")
2312		}
2313		return
2314	}
2315	if from.SdkVersion() == "" {
2316		// Platform code can link to anything
2317		return
2318	}
2319	if from.InRamdisk() {
2320		// Ramdisk code is not NDK
2321		return
2322	}
2323	if from.InVendorRamdisk() {
2324		// Vendor ramdisk code is not NDK
2325		return
2326	}
2327	if from.InRecovery() {
2328		// Recovery code is not NDK
2329		return
2330	}
2331	if c, ok := to.(*Module); ok {
2332		if c.ToolchainLibrary() {
2333			// These are always allowed
2334			return
2335		}
2336		if c.NdkPrebuiltStl() {
2337			// These are allowed, but they don't set sdk_version
2338			return
2339		}
2340		if c.StubDecorator() {
2341			// These aren't real libraries, but are the stub shared libraries that are included in
2342			// the NDK.
2343			return
2344		}
2345	}
2346
2347	if strings.HasPrefix(ctx.ModuleName(), "libclang_rt.") && to.Module().Name() == "libc++" {
2348		// Bug: http://b/121358700 - Allow libclang_rt.* shared libraries (with sdk_version)
2349		// to link to libc++ (non-NDK and without sdk_version).
2350		return
2351	}
2352
2353	if to.SdkVersion() == "" {
2354		// NDK code linking to platform code is never okay.
2355		ctx.ModuleErrorf("depends on non-NDK-built library %q",
2356			ctx.OtherModuleName(to.Module()))
2357		return
2358	}
2359
2360	// At this point we know we have two NDK libraries, but we need to
2361	// check that we're not linking against anything built against a higher
2362	// API level, as it is only valid to link against older or equivalent
2363	// APIs.
2364
2365	// Current can link against anything.
2366	if from.SdkVersion() != "current" {
2367		// Otherwise we need to check.
2368		if to.SdkVersion() == "current" {
2369			// Current can't be linked against by anything else.
2370			ctx.ModuleErrorf("links %q built against newer API version %q",
2371				ctx.OtherModuleName(to.Module()), "current")
2372		} else {
2373			fromApi, err := strconv.Atoi(from.SdkVersion())
2374			if err != nil {
2375				ctx.PropertyErrorf("sdk_version",
2376					"Invalid sdk_version value (must be int or current): %q",
2377					from.SdkVersion())
2378			}
2379			toApi, err := strconv.Atoi(to.SdkVersion())
2380			if err != nil {
2381				ctx.PropertyErrorf("sdk_version",
2382					"Invalid sdk_version value (must be int or current): %q",
2383					to.SdkVersion())
2384			}
2385
2386			if toApi > fromApi {
2387				ctx.ModuleErrorf("links %q built against newer API version %q",
2388					ctx.OtherModuleName(to.Module()), to.SdkVersion())
2389			}
2390		}
2391	}
2392
2393	// Also check that the two STL choices are compatible.
2394	fromStl := from.SelectedStl()
2395	toStl := to.SelectedStl()
2396	if fromStl == "" || toStl == "" {
2397		// Libraries that don't use the STL are unrestricted.
2398	} else if fromStl == "ndk_system" || toStl == "ndk_system" {
2399		// We can be permissive with the system "STL" since it is only the C++
2400		// ABI layer, but in the future we should make sure that everyone is
2401		// using either libc++ or nothing.
2402	} else if getNdkStlFamily(from) != getNdkStlFamily(to) {
2403		ctx.ModuleErrorf("uses %q and depends on %q which uses incompatible %q",
2404			from.SelectedStl(), ctx.OtherModuleName(to.Module()),
2405			to.SelectedStl())
2406	}
2407}
2408
2409func checkLinkTypeMutator(ctx android.BottomUpMutatorContext) {
2410	if c, ok := ctx.Module().(*Module); ok {
2411		ctx.VisitDirectDeps(func(dep android.Module) {
2412			depTag := ctx.OtherModuleDependencyTag(dep)
2413			ccDep, ok := dep.(LinkableInterface)
2414			if ok {
2415				checkLinkType(ctx, c, ccDep, depTag)
2416			}
2417		})
2418	}
2419}
2420
2421// Tests whether the dependent library is okay to be double loaded inside a single process.
2422// If a library has a vendor variant and is a (transitive) dependency of an LLNDK library,
2423// it is subject to be double loaded. Such lib should be explicitly marked as double_loadable: true
2424// or as vndk-sp (vndk: { enabled: true, support_system_process: true}).
2425func checkDoubleLoadableLibraries(ctx android.TopDownMutatorContext) {
2426	check := func(child, parent android.Module) bool {
2427		to, ok := child.(*Module)
2428		if !ok {
2429			return false
2430		}
2431
2432		if lib, ok := to.linker.(*libraryDecorator); !ok || !lib.shared() {
2433			return false
2434		}
2435
2436		// These dependencies are not excercised at runtime. Tracking these will give us
2437		// false negative, so skip.
2438		depTag := ctx.OtherModuleDependencyTag(child)
2439		if IsHeaderDepTag(depTag) {
2440			return false
2441		}
2442		if depTag == staticVariantTag {
2443			return false
2444		}
2445		if depTag == stubImplDepTag {
2446			return false
2447		}
2448
2449		// Even if target lib has no vendor variant, keep checking dependency
2450		// graph in case it depends on vendor_available or product_available
2451		// but not double_loadable transtively.
2452		if !to.HasNonSystemVariants() {
2453			return true
2454		}
2455
2456		// The happy path. Keep tracking dependencies until we hit a non double-loadable
2457		// one.
2458		if Bool(to.VendorProperties.Double_loadable) {
2459			return true
2460		}
2461
2462		if to.IsVndkSp() || to.IsLlndk() {
2463			return false
2464		}
2465
2466		ctx.ModuleErrorf("links a library %q which is not LL-NDK, "+
2467			"VNDK-SP, or explicitly marked as 'double_loadable:true'. "+
2468			"Dependency list: %s", ctx.OtherModuleName(to), ctx.GetPathString(false))
2469		return false
2470	}
2471	if module, ok := ctx.Module().(*Module); ok {
2472		if lib, ok := module.linker.(*libraryDecorator); ok && lib.shared() {
2473			if lib.hasLLNDKStubs() {
2474				ctx.WalkDeps(check)
2475			}
2476		}
2477	}
2478}
2479
2480// Convert dependencies to paths.  Returns a PathDeps containing paths
2481func (c *Module) depsToPaths(ctx android.ModuleContext) PathDeps {
2482	var depPaths PathDeps
2483
2484	var directStaticDeps []StaticLibraryInfo
2485	var directSharedDeps []SharedLibraryInfo
2486
2487	reexportExporter := func(exporter FlagExporterInfo) {
2488		depPaths.ReexportedDirs = append(depPaths.ReexportedDirs, exporter.IncludeDirs...)
2489		depPaths.ReexportedSystemDirs = append(depPaths.ReexportedSystemDirs, exporter.SystemIncludeDirs...)
2490		depPaths.ReexportedFlags = append(depPaths.ReexportedFlags, exporter.Flags...)
2491		depPaths.ReexportedDeps = append(depPaths.ReexportedDeps, exporter.Deps...)
2492		depPaths.ReexportedGeneratedHeaders = append(depPaths.ReexportedGeneratedHeaders, exporter.GeneratedHeaders...)
2493	}
2494
2495	// For the dependency from platform to apex, use the latest stubs
2496	c.apexSdkVersion = android.FutureApiLevel
2497	apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
2498	if !apexInfo.IsForPlatform() {
2499		c.apexSdkVersion = apexInfo.MinSdkVersion
2500	}
2501
2502	if android.InList("hwaddress", ctx.Config().SanitizeDevice()) {
2503		// In hwasan build, we override apexSdkVersion to the FutureApiLevel(10000)
2504		// so that even Q(29/Android10) apexes could use the dynamic unwinder by linking the newer stubs(e.g libc(R+)).
2505		// (b/144430859)
2506		c.apexSdkVersion = android.FutureApiLevel
2507	}
2508
2509	ctx.VisitDirectDeps(func(dep android.Module) {
2510		depName := ctx.OtherModuleName(dep)
2511		depTag := ctx.OtherModuleDependencyTag(dep)
2512
2513		ccDep, ok := dep.(LinkableInterface)
2514		if !ok {
2515
2516			// handling for a few module types that aren't cc Module but that are also supported
2517			switch depTag {
2518			case genSourceDepTag:
2519				if genRule, ok := dep.(genrule.SourceFileGenerator); ok {
2520					depPaths.GeneratedSources = append(depPaths.GeneratedSources,
2521						genRule.GeneratedSourceFiles()...)
2522				} else {
2523					ctx.ModuleErrorf("module %q is not a gensrcs or genrule", depName)
2524				}
2525				// Support exported headers from a generated_sources dependency
2526				fallthrough
2527			case genHeaderDepTag, genHeaderExportDepTag:
2528				if genRule, ok := dep.(genrule.SourceFileGenerator); ok {
2529					depPaths.GeneratedDeps = append(depPaths.GeneratedDeps,
2530						genRule.GeneratedDeps()...)
2531					dirs := genRule.GeneratedHeaderDirs()
2532					depPaths.IncludeDirs = append(depPaths.IncludeDirs, dirs...)
2533					if depTag == genHeaderExportDepTag {
2534						depPaths.ReexportedDirs = append(depPaths.ReexportedDirs, dirs...)
2535						depPaths.ReexportedGeneratedHeaders = append(depPaths.ReexportedGeneratedHeaders,
2536							genRule.GeneratedSourceFiles()...)
2537						depPaths.ReexportedDeps = append(depPaths.ReexportedDeps, genRule.GeneratedDeps()...)
2538						// Add these re-exported flags to help header-abi-dumper to infer the abi exported by a library.
2539						c.sabi.Properties.ReexportedIncludes = append(c.sabi.Properties.ReexportedIncludes, dirs.Strings()...)
2540
2541					}
2542				} else {
2543					ctx.ModuleErrorf("module %q is not a genrule", depName)
2544				}
2545			case linkerFlagsDepTag:
2546				if genRule, ok := dep.(genrule.SourceFileGenerator); ok {
2547					files := genRule.GeneratedSourceFiles()
2548					if len(files) == 1 {
2549						depPaths.LinkerFlagsFile = android.OptionalPathForPath(files[0])
2550					} else if len(files) > 1 {
2551						ctx.ModuleErrorf("module %q can only generate a single file if used for a linker flag file", depName)
2552					}
2553				} else {
2554					ctx.ModuleErrorf("module %q is not a genrule", depName)
2555				}
2556			}
2557			return
2558		}
2559
2560		if depTag == android.ProtoPluginDepTag {
2561			return
2562		}
2563
2564		if dep.Target().Os != ctx.Os() {
2565			ctx.ModuleErrorf("OS mismatch between %q and %q", ctx.ModuleName(), depName)
2566			return
2567		}
2568		if dep.Target().Arch.ArchType != ctx.Arch().ArchType {
2569			ctx.ModuleErrorf("Arch mismatch between %q(%v) and %q(%v)",
2570				ctx.ModuleName(), ctx.Arch().ArchType, depName, dep.Target().Arch.ArchType)
2571			return
2572		}
2573
2574		if depTag == reuseObjTag {
2575			// Skip reused objects for stub libraries, they use their own stub object file instead.
2576			// The reuseObjTag dependency still exists because the LinkageMutator runs before the
2577			// version mutator, so the stubs variant is created from the shared variant that
2578			// already has the reuseObjTag dependency on the static variant.
2579			if !c.library.buildStubs() {
2580				staticAnalogue := ctx.OtherModuleProvider(dep, StaticLibraryInfoProvider).(StaticLibraryInfo)
2581				objs := staticAnalogue.ReuseObjects
2582				depPaths.Objs = depPaths.Objs.Append(objs)
2583				depExporterInfo := ctx.OtherModuleProvider(dep, FlagExporterInfoProvider).(FlagExporterInfo)
2584				reexportExporter(depExporterInfo)
2585			}
2586			return
2587		}
2588
2589		linkFile := ccDep.OutputFile()
2590
2591		if libDepTag, ok := depTag.(libraryDependencyTag); ok {
2592			// Only use static unwinder for legacy (min_sdk_version = 29) apexes (b/144430859)
2593			if libDepTag.staticUnwinder && c.apexSdkVersion.GreaterThan(android.SdkVersion_Android10) {
2594				return
2595			}
2596
2597			if !apexInfo.IsForPlatform() && libDepTag.excludeInApex {
2598				return
2599			}
2600
2601			depExporterInfo := ctx.OtherModuleProvider(dep, FlagExporterInfoProvider).(FlagExporterInfo)
2602
2603			var ptr *android.Paths
2604			var depPtr *android.Paths
2605
2606			depFile := android.OptionalPath{}
2607
2608			switch {
2609			case libDepTag.header():
2610				if !ctx.OtherModuleHasProvider(dep, HeaderLibraryInfoProvider) {
2611					if !ctx.Config().AllowMissingDependencies() {
2612						ctx.ModuleErrorf("module %q is not a header library", depName)
2613					} else {
2614						ctx.AddMissingDependencies([]string{depName})
2615					}
2616					return
2617				}
2618			case libDepTag.shared():
2619				if !ctx.OtherModuleHasProvider(dep, SharedLibraryInfoProvider) {
2620					if !ctx.Config().AllowMissingDependencies() {
2621						ctx.ModuleErrorf("module %q is not a shared library", depName)
2622					} else {
2623						ctx.AddMissingDependencies([]string{depName})
2624					}
2625					return
2626				}
2627
2628				sharedLibraryInfo := ctx.OtherModuleProvider(dep, SharedLibraryInfoProvider).(SharedLibraryInfo)
2629				sharedLibraryStubsInfo := ctx.OtherModuleProvider(dep, SharedLibraryStubsProvider).(SharedLibraryStubsInfo)
2630
2631				if !libDepTag.explicitlyVersioned && len(sharedLibraryStubsInfo.SharedStubLibraries) > 0 {
2632					useStubs := false
2633
2634					if lib := moduleLibraryInterface(dep); lib.buildStubs() && c.UseVndk() { // LLNDK
2635						if !apexInfo.IsForPlatform() {
2636							// For platform libraries, use current version of LLNDK
2637							useStubs = true
2638						}
2639					} else if apexInfo.IsForPlatform() {
2640						// If not building for APEX, use stubs only when it is from
2641						// an APEX (and not from platform)
2642						// However, for host, ramdisk, vendor_ramdisk, recovery or bootstrap modules,
2643						// always link to non-stub variant
2644						useStubs = dep.(android.ApexModule).NotInPlatform() && !c.bootstrap()
2645						if useStubs {
2646							// Another exception: if this module is a test for an APEX, then
2647							// it is linked with the non-stub variant of a module in the APEX
2648							// as if this is part of the APEX.
2649							testFor := ctx.Provider(android.ApexTestForInfoProvider).(android.ApexTestForInfo)
2650							for _, apexContents := range testFor.ApexContents {
2651								if apexContents.DirectlyInApex(depName) {
2652									useStubs = false
2653									break
2654								}
2655							}
2656						}
2657						if useStubs {
2658							// Yet another exception: If this module and the dependency are
2659							// available to the same APEXes then skip stubs between their
2660							// platform variants. This complements the test_for case above,
2661							// which avoids the stubs on a direct APEX library dependency, by
2662							// avoiding stubs for indirect test dependencies as well.
2663							//
2664							// TODO(b/183882457): This doesn't work if the two libraries have
2665							// only partially overlapping apex_available. For that test_for
2666							// modules would need to be split into APEX variants and resolved
2667							// separately for each APEX they have access to.
2668							if android.AvailableToSameApexes(c, dep.(android.ApexModule)) {
2669								useStubs = false
2670							}
2671						}
2672					} else {
2673						// If building for APEX, use stubs when the parent is in any APEX that
2674						// the child is not in.
2675						useStubs = !android.DirectlyInAllApexes(apexInfo, depName)
2676					}
2677
2678					// when to use (unspecified) stubs, use the latest one.
2679					if useStubs {
2680						stubs := sharedLibraryStubsInfo.SharedStubLibraries
2681						toUse := stubs[len(stubs)-1]
2682						sharedLibraryInfo = toUse.SharedLibraryInfo
2683						depExporterInfo = toUse.FlagExporterInfo
2684					}
2685				}
2686
2687				// Stubs lib doesn't link to the shared lib dependencies. Don't set
2688				// linkFile, depFile, and ptr.
2689				if c.IsStubs() {
2690					break
2691				}
2692
2693				linkFile = android.OptionalPathForPath(sharedLibraryInfo.SharedLibrary)
2694				depFile = sharedLibraryInfo.TableOfContents
2695
2696				ptr = &depPaths.SharedLibs
2697				switch libDepTag.Order {
2698				case earlyLibraryDependency:
2699					ptr = &depPaths.EarlySharedLibs
2700					depPtr = &depPaths.EarlySharedLibsDeps
2701				case normalLibraryDependency:
2702					ptr = &depPaths.SharedLibs
2703					depPtr = &depPaths.SharedLibsDeps
2704					directSharedDeps = append(directSharedDeps, sharedLibraryInfo)
2705				case lateLibraryDependency:
2706					ptr = &depPaths.LateSharedLibs
2707					depPtr = &depPaths.LateSharedLibsDeps
2708				default:
2709					panic(fmt.Errorf("unexpected library dependency order %d", libDepTag.Order))
2710				}
2711			case libDepTag.static():
2712				if !ctx.OtherModuleHasProvider(dep, StaticLibraryInfoProvider) {
2713					if !ctx.Config().AllowMissingDependencies() {
2714						ctx.ModuleErrorf("module %q is not a static library", depName)
2715					} else {
2716						ctx.AddMissingDependencies([]string{depName})
2717					}
2718					return
2719				}
2720
2721				// Stubs lib doesn't link to the static lib dependencies. Don't set
2722				// linkFile, depFile, and ptr.
2723				if c.IsStubs() {
2724					break
2725				}
2726
2727				staticLibraryInfo := ctx.OtherModuleProvider(dep, StaticLibraryInfoProvider).(StaticLibraryInfo)
2728				linkFile = android.OptionalPathForPath(staticLibraryInfo.StaticLibrary)
2729				if libDepTag.wholeStatic {
2730					ptr = &depPaths.WholeStaticLibs
2731					if len(staticLibraryInfo.Objects.objFiles) > 0 {
2732						depPaths.WholeStaticLibObjs = depPaths.WholeStaticLibObjs.Append(staticLibraryInfo.Objects)
2733					} else {
2734						// This case normally catches prebuilt static
2735						// libraries, but it can also occur when
2736						// AllowMissingDependencies is on and the
2737						// dependencies has no sources of its own
2738						// but has a whole_static_libs dependency
2739						// on a missing library.  We want to depend
2740						// on the .a file so that there is something
2741						// in the dependency tree that contains the
2742						// error rule for the missing transitive
2743						// dependency.
2744						depPaths.WholeStaticLibsFromPrebuilts = append(depPaths.WholeStaticLibsFromPrebuilts, linkFile.Path())
2745					}
2746				} else {
2747					switch libDepTag.Order {
2748					case earlyLibraryDependency:
2749						panic(fmt.Errorf("early static libs not suppported"))
2750					case normalLibraryDependency:
2751						// static dependencies will be handled separately so they can be ordered
2752						// using transitive dependencies.
2753						ptr = nil
2754						directStaticDeps = append(directStaticDeps, staticLibraryInfo)
2755					case lateLibraryDependency:
2756						ptr = &depPaths.LateStaticLibs
2757					default:
2758						panic(fmt.Errorf("unexpected library dependency order %d", libDepTag.Order))
2759					}
2760				}
2761			}
2762
2763			if libDepTag.static() && !libDepTag.wholeStatic {
2764				if !ccDep.CcLibraryInterface() || !ccDep.Static() {
2765					ctx.ModuleErrorf("module %q not a static library", depName)
2766					return
2767				}
2768
2769				// When combining coverage files for shared libraries and executables, coverage files
2770				// in static libraries act as if they were whole static libraries. The same goes for
2771				// source based Abi dump files.
2772				if c, ok := ccDep.(*Module); ok {
2773					staticLib := c.linker.(libraryInterface)
2774					depPaths.StaticLibObjs.coverageFiles = append(depPaths.StaticLibObjs.coverageFiles,
2775						staticLib.objs().coverageFiles...)
2776					depPaths.StaticLibObjs.sAbiDumpFiles = append(depPaths.StaticLibObjs.sAbiDumpFiles,
2777						staticLib.objs().sAbiDumpFiles...)
2778				} else {
2779					// Handle non-CC modules here
2780					depPaths.StaticLibObjs.coverageFiles = append(depPaths.StaticLibObjs.coverageFiles,
2781						ccDep.CoverageFiles()...)
2782				}
2783			}
2784
2785			if ptr != nil {
2786				if !linkFile.Valid() {
2787					if !ctx.Config().AllowMissingDependencies() {
2788						ctx.ModuleErrorf("module %q missing output file", depName)
2789					} else {
2790						ctx.AddMissingDependencies([]string{depName})
2791					}
2792					return
2793				}
2794				*ptr = append(*ptr, linkFile.Path())
2795			}
2796
2797			if depPtr != nil {
2798				dep := depFile
2799				if !dep.Valid() {
2800					dep = linkFile
2801				}
2802				*depPtr = append(*depPtr, dep.Path())
2803			}
2804
2805			depPaths.IncludeDirs = append(depPaths.IncludeDirs, depExporterInfo.IncludeDirs...)
2806			depPaths.SystemIncludeDirs = append(depPaths.SystemIncludeDirs, depExporterInfo.SystemIncludeDirs...)
2807			depPaths.GeneratedDeps = append(depPaths.GeneratedDeps, depExporterInfo.Deps...)
2808			depPaths.Flags = append(depPaths.Flags, depExporterInfo.Flags...)
2809
2810			if libDepTag.reexportFlags {
2811				reexportExporter(depExporterInfo)
2812				// Add these re-exported flags to help header-abi-dumper to infer the abi exported by a library.
2813				// Re-exported shared library headers must be included as well since they can help us with type information
2814				// about template instantiations (instantiated from their headers).
2815				// -isystem headers are not included since for bionic libraries, abi-filtering is taken care of by version
2816				// scripts.
2817				c.sabi.Properties.ReexportedIncludes = append(
2818					c.sabi.Properties.ReexportedIncludes, depExporterInfo.IncludeDirs.Strings()...)
2819			}
2820
2821			makeLibName := MakeLibName(ctx, c, ccDep, depName) + libDepTag.makeSuffix
2822			switch {
2823			case libDepTag.header():
2824				c.Properties.AndroidMkHeaderLibs = append(
2825					c.Properties.AndroidMkHeaderLibs, makeLibName)
2826			case libDepTag.shared():
2827				if lib := moduleLibraryInterface(dep); lib != nil {
2828					if lib.buildStubs() && dep.(android.ApexModule).InAnyApex() {
2829						// Add the dependency to the APEX(es) providing the library so that
2830						// m <module> can trigger building the APEXes as well.
2831						depApexInfo := ctx.OtherModuleProvider(dep, android.ApexInfoProvider).(android.ApexInfo)
2832						for _, an := range depApexInfo.InApexVariants {
2833							c.Properties.ApexesProvidingSharedLibs = append(
2834								c.Properties.ApexesProvidingSharedLibs, an)
2835						}
2836					}
2837				}
2838
2839				// Note: the order of libs in this list is not important because
2840				// they merely serve as Make dependencies and do not affect this lib itself.
2841				c.Properties.AndroidMkSharedLibs = append(
2842					c.Properties.AndroidMkSharedLibs, makeLibName)
2843				// Record baseLibName for snapshots.
2844				c.Properties.SnapshotSharedLibs = append(c.Properties.SnapshotSharedLibs, baseLibName(depName))
2845			case libDepTag.static():
2846				if libDepTag.wholeStatic {
2847					c.Properties.AndroidMkWholeStaticLibs = append(
2848						c.Properties.AndroidMkWholeStaticLibs, makeLibName)
2849				} else {
2850					c.Properties.AndroidMkStaticLibs = append(
2851						c.Properties.AndroidMkStaticLibs, makeLibName)
2852				}
2853			}
2854		} else if !c.IsStubs() {
2855			// Stubs lib doesn't link to the runtime lib, object, crt, etc. dependencies.
2856
2857			switch depTag {
2858			case runtimeDepTag:
2859				c.Properties.AndroidMkRuntimeLibs = append(
2860					c.Properties.AndroidMkRuntimeLibs, MakeLibName(ctx, c, ccDep, depName)+libDepTag.makeSuffix)
2861				// Record baseLibName for snapshots.
2862				c.Properties.SnapshotRuntimeLibs = append(c.Properties.SnapshotRuntimeLibs, baseLibName(depName))
2863			case objDepTag:
2864				depPaths.Objs.objFiles = append(depPaths.Objs.objFiles, linkFile.Path())
2865			case CrtBeginDepTag:
2866				depPaths.CrtBegin = linkFile
2867			case CrtEndDepTag:
2868				depPaths.CrtEnd = linkFile
2869			case dynamicLinkerDepTag:
2870				depPaths.DynamicLinker = linkFile
2871			}
2872		}
2873	})
2874
2875	// use the ordered dependencies as this module's dependencies
2876	orderedStaticPaths, transitiveStaticLibs := orderStaticModuleDeps(directStaticDeps, directSharedDeps)
2877	depPaths.TranstiveStaticLibrariesForOrdering = transitiveStaticLibs
2878	depPaths.StaticLibs = append(depPaths.StaticLibs, orderedStaticPaths...)
2879
2880	// Dedup exported flags from dependencies
2881	depPaths.Flags = android.FirstUniqueStrings(depPaths.Flags)
2882	depPaths.IncludeDirs = android.FirstUniquePaths(depPaths.IncludeDirs)
2883	depPaths.SystemIncludeDirs = android.FirstUniquePaths(depPaths.SystemIncludeDirs)
2884	depPaths.GeneratedDeps = android.FirstUniquePaths(depPaths.GeneratedDeps)
2885	depPaths.ReexportedDirs = android.FirstUniquePaths(depPaths.ReexportedDirs)
2886	depPaths.ReexportedSystemDirs = android.FirstUniquePaths(depPaths.ReexportedSystemDirs)
2887	depPaths.ReexportedFlags = android.FirstUniqueStrings(depPaths.ReexportedFlags)
2888	depPaths.ReexportedDeps = android.FirstUniquePaths(depPaths.ReexportedDeps)
2889	depPaths.ReexportedGeneratedHeaders = android.FirstUniquePaths(depPaths.ReexportedGeneratedHeaders)
2890
2891	if c.sabi != nil {
2892		c.sabi.Properties.ReexportedIncludes = android.FirstUniqueStrings(c.sabi.Properties.ReexportedIncludes)
2893	}
2894
2895	return depPaths
2896}
2897
2898// orderStaticModuleDeps rearranges the order of the static library dependencies of the module
2899// to match the topological order of the dependency tree, including any static analogues of
2900// direct shared libraries.  It returns the ordered static dependencies, and an android.DepSet
2901// of the transitive dependencies.
2902func orderStaticModuleDeps(staticDeps []StaticLibraryInfo, sharedDeps []SharedLibraryInfo) (ordered android.Paths, transitive *android.DepSet) {
2903	transitiveStaticLibsBuilder := android.NewDepSetBuilder(android.TOPOLOGICAL)
2904	var staticPaths android.Paths
2905	for _, staticDep := range staticDeps {
2906		staticPaths = append(staticPaths, staticDep.StaticLibrary)
2907		transitiveStaticLibsBuilder.Transitive(staticDep.TransitiveStaticLibrariesForOrdering)
2908	}
2909	for _, sharedDep := range sharedDeps {
2910		if sharedDep.StaticAnalogue != nil {
2911			transitiveStaticLibsBuilder.Transitive(sharedDep.StaticAnalogue.TransitiveStaticLibrariesForOrdering)
2912		}
2913	}
2914	transitiveStaticLibs := transitiveStaticLibsBuilder.Build()
2915
2916	orderedTransitiveStaticLibs := transitiveStaticLibs.ToList()
2917
2918	// reorder the dependencies based on transitive dependencies
2919	staticPaths = android.FirstUniquePaths(staticPaths)
2920	_, orderedStaticPaths := android.FilterPathList(orderedTransitiveStaticLibs, staticPaths)
2921
2922	if len(orderedStaticPaths) != len(staticPaths) {
2923		missing, _ := android.FilterPathList(staticPaths, orderedStaticPaths)
2924		panic(fmt.Errorf("expected %d ordered static paths , got %d, missing %q %q %q", len(staticPaths), len(orderedStaticPaths), missing, orderedStaticPaths, staticPaths))
2925	}
2926
2927	return orderedStaticPaths, transitiveStaticLibs
2928}
2929
2930// baseLibName trims known prefixes and suffixes
2931func baseLibName(depName string) string {
2932	libName := strings.TrimSuffix(depName, llndkLibrarySuffix)
2933	libName = strings.TrimSuffix(libName, vendorPublicLibrarySuffix)
2934	libName = android.RemoveOptionalPrebuiltPrefix(libName)
2935	return libName
2936}
2937
2938func MakeLibName(ctx android.ModuleContext, c LinkableInterface, ccDep LinkableInterface, depName string) string {
2939	libName := baseLibName(depName)
2940	ccDepModule, _ := ccDep.(*Module)
2941	isLLndk := ccDepModule != nil && ccDepModule.IsLlndk()
2942	nonSystemVariantsExist := ccDep.HasNonSystemVariants() || isLLndk
2943
2944	if ccDepModule != nil {
2945		// TODO(ivanlozano) Support snapshots for Rust-produced C library variants.
2946		// Use base module name for snapshots when exporting to Makefile.
2947		if snapshotPrebuilt, ok := ccDepModule.linker.(snapshotInterface); ok {
2948			baseName := ccDepModule.BaseModuleName()
2949
2950			return baseName + snapshotPrebuilt.snapshotAndroidMkSuffix()
2951		}
2952	}
2953
2954	if ctx.DeviceConfig().VndkUseCoreVariant() && ccDep.IsVndk() && !ccDep.MustUseVendorVariant() &&
2955		!c.InRamdisk() && !c.InVendorRamdisk() && !c.InRecovery() {
2956		// The vendor module is a no-vendor-variant VNDK library.  Depend on the
2957		// core module instead.
2958		return libName
2959	} else if ccDep.UseVndk() && nonSystemVariantsExist {
2960		// The vendor and product modules in Make will have been renamed to not conflict with the
2961		// core module, so update the dependency name here accordingly.
2962		return libName + ccDep.SubName()
2963	} else if ccDep.InRamdisk() && !ccDep.OnlyInRamdisk() {
2964		return libName + ramdiskSuffix
2965	} else if ccDep.InVendorRamdisk() && !ccDep.OnlyInVendorRamdisk() {
2966		return libName + VendorRamdiskSuffix
2967	} else if ccDep.InRecovery() && !ccDep.OnlyInRecovery() {
2968		return libName + recoverySuffix
2969	} else if ccDep.Target().NativeBridge == android.NativeBridgeEnabled {
2970		return libName + nativeBridgeSuffix
2971	} else {
2972		return libName
2973	}
2974}
2975
2976func (c *Module) InstallInData() bool {
2977	if c.installer == nil {
2978		return false
2979	}
2980	return c.installer.inData()
2981}
2982
2983func (c *Module) InstallInSanitizerDir() bool {
2984	if c.installer == nil {
2985		return false
2986	}
2987	if c.sanitize != nil && c.sanitize.inSanitizerDir() {
2988		return true
2989	}
2990	return c.installer.inSanitizerDir()
2991}
2992
2993func (c *Module) InstallInRamdisk() bool {
2994	return c.InRamdisk()
2995}
2996
2997func (c *Module) InstallInVendorRamdisk() bool {
2998	return c.InVendorRamdisk()
2999}
3000
3001func (c *Module) InstallInRecovery() bool {
3002	return c.InRecovery()
3003}
3004
3005func (c *Module) MakeUninstallable() {
3006	if c.installer == nil {
3007		c.ModuleBase.MakeUninstallable()
3008		return
3009	}
3010	c.installer.makeUninstallable(c)
3011}
3012
3013func (c *Module) HostToolPath() android.OptionalPath {
3014	if c.installer == nil {
3015		return android.OptionalPath{}
3016	}
3017	return c.installer.hostToolPath()
3018}
3019
3020func (c *Module) IntermPathForModuleOut() android.OptionalPath {
3021	return c.outputFile
3022}
3023
3024func (c *Module) OutputFiles(tag string) (android.Paths, error) {
3025	switch tag {
3026	case "":
3027		if c.outputFile.Valid() {
3028			return android.Paths{c.outputFile.Path()}, nil
3029		}
3030		return android.Paths{}, nil
3031	default:
3032		return nil, fmt.Errorf("unsupported module reference tag %q", tag)
3033	}
3034}
3035
3036func (c *Module) static() bool {
3037	if static, ok := c.linker.(interface {
3038		static() bool
3039	}); ok {
3040		return static.static()
3041	}
3042	return false
3043}
3044
3045func (c *Module) staticBinary() bool {
3046	if static, ok := c.linker.(interface {
3047		staticBinary() bool
3048	}); ok {
3049		return static.staticBinary()
3050	}
3051	return false
3052}
3053
3054func (c *Module) testBinary() bool {
3055	if test, ok := c.linker.(interface {
3056		testBinary() bool
3057	}); ok {
3058		return test.testBinary()
3059	}
3060	return false
3061}
3062
3063// Header returns true if the module is a header-only variant. (See cc/library.go header()).
3064func (c *Module) Header() bool {
3065	if h, ok := c.linker.(interface {
3066		header() bool
3067	}); ok {
3068		return h.header()
3069	}
3070	return false
3071}
3072
3073func (c *Module) Binary() bool {
3074	if b, ok := c.linker.(interface {
3075		binary() bool
3076	}); ok {
3077		return b.binary()
3078	}
3079	return false
3080}
3081
3082func (c *Module) Object() bool {
3083	if o, ok := c.linker.(interface {
3084		object() bool
3085	}); ok {
3086		return o.object()
3087	}
3088	return false
3089}
3090
3091func GetMakeLinkType(actx android.ModuleContext, c LinkableInterface) string {
3092	if c.UseVndk() {
3093		if c.IsLlndk() {
3094			if !c.IsLlndkPublic() {
3095				return "native:vndk_private"
3096			}
3097			return "native:vndk"
3098		}
3099		if c.IsVndk() && !c.IsVndkExt() {
3100			if c.IsVndkPrivate() {
3101				return "native:vndk_private"
3102			}
3103			return "native:vndk"
3104		}
3105		if c.InProduct() {
3106			return "native:product"
3107		}
3108		return "native:vendor"
3109	} else if c.InRamdisk() {
3110		return "native:ramdisk"
3111	} else if c.InVendorRamdisk() {
3112		return "native:vendor_ramdisk"
3113	} else if c.InRecovery() {
3114		return "native:recovery"
3115	} else if c.Target().Os == android.Android && c.SdkVersion() != "" {
3116		return "native:ndk:none:none"
3117		// TODO(b/114741097): use the correct ndk stl once build errors have been fixed
3118		//family, link := getNdkStlFamilyAndLinkType(c)
3119		//return fmt.Sprintf("native:ndk:%s:%s", family, link)
3120	} else if actx.DeviceConfig().VndkUseCoreVariant() && !c.MustUseVendorVariant() {
3121		return "native:platform_vndk"
3122	} else {
3123		return "native:platform"
3124	}
3125}
3126
3127// Overrides ApexModule.IsInstallabeToApex()
3128// Only shared/runtime libraries and "test_per_src" tests are installable to APEX.
3129func (c *Module) IsInstallableToApex() bool {
3130	if lib := c.library; lib != nil {
3131		// Stub libs and prebuilt libs in a versioned SDK are not
3132		// installable to APEX even though they are shared libs.
3133		return lib.shared() && !lib.buildStubs() && c.ContainingSdk().Unversioned()
3134	} else if _, ok := c.linker.(testPerSrc); ok {
3135		return true
3136	}
3137	return false
3138}
3139
3140func (c *Module) AvailableFor(what string) bool {
3141	if linker, ok := c.linker.(interface {
3142		availableFor(string) bool
3143	}); ok {
3144		return c.ApexModuleBase.AvailableFor(what) || linker.availableFor(what)
3145	} else {
3146		return c.ApexModuleBase.AvailableFor(what)
3147	}
3148}
3149
3150func (c *Module) TestFor() []string {
3151	return c.Properties.Test_for
3152}
3153
3154func (c *Module) UniqueApexVariations() bool {
3155	if u, ok := c.compiler.(interface {
3156		uniqueApexVariations() bool
3157	}); ok {
3158		return u.uniqueApexVariations()
3159	} else {
3160		return false
3161	}
3162}
3163
3164func (c *Module) EverInstallable() bool {
3165	return c.installer != nil &&
3166		// Check to see whether the module is actually ever installable.
3167		c.installer.everInstallable()
3168}
3169
3170func (c *Module) PreventInstall() bool {
3171	return c.Properties.PreventInstall
3172}
3173
3174func (c *Module) Installable() *bool {
3175	return c.Properties.Installable
3176}
3177
3178func installable(c LinkableInterface, apexInfo android.ApexInfo) bool {
3179	ret := c.EverInstallable() &&
3180		// Check to see whether the module has been configured to not be installed.
3181		proptools.BoolDefault(c.Installable(), true) &&
3182		!c.PreventInstall() && c.OutputFile().Valid()
3183
3184	// The platform variant doesn't need further condition. Apex variants however might not
3185	// be installable because it will likely to be included in the APEX and won't appear
3186	// in the system partition.
3187	if apexInfo.IsForPlatform() {
3188		return ret
3189	}
3190
3191	// Special case for modules that are configured to be installed to /data, which includes
3192	// test modules. For these modules, both APEX and non-APEX variants are considered as
3193	// installable. This is because even the APEX variants won't be included in the APEX, but
3194	// will anyway be installed to /data/*.
3195	// See b/146995717
3196	if c.InstallInData() {
3197		return ret
3198	}
3199
3200	return false
3201}
3202
3203func (c *Module) AndroidMkWriteAdditionalDependenciesForSourceAbiDiff(w io.Writer) {
3204	if c.linker != nil {
3205		if library, ok := c.linker.(*libraryDecorator); ok {
3206			library.androidMkWriteAdditionalDependenciesForSourceAbiDiff(w)
3207		}
3208	}
3209}
3210
3211var _ android.ApexModule = (*Module)(nil)
3212
3213// Implements android.ApexModule
3214func (c *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
3215	depTag := ctx.OtherModuleDependencyTag(dep)
3216	libDepTag, isLibDepTag := depTag.(libraryDependencyTag)
3217
3218	if cc, ok := dep.(*Module); ok {
3219		if cc.HasStubsVariants() {
3220			if isLibDepTag && libDepTag.shared() {
3221				// dynamic dep to a stubs lib crosses APEX boundary
3222				return false
3223			}
3224			if IsRuntimeDepTag(depTag) {
3225				// runtime dep to a stubs lib also crosses APEX boundary
3226				return false
3227			}
3228		}
3229		if cc.IsLlndk() {
3230			return false
3231		}
3232		if isLibDepTag && c.static() && libDepTag.shared() {
3233			// shared_lib dependency from a static lib is considered as crossing
3234			// the APEX boundary because the dependency doesn't actually is
3235			// linked; the dependency is used only during the compilation phase.
3236			return false
3237		}
3238
3239		if isLibDepTag && libDepTag.excludeInApex {
3240			return false
3241		}
3242	}
3243	if depTag == stubImplDepTag || depTag == llndkStubDepTag {
3244		// We don't track beyond LLNDK or from an implementation library to its stubs.
3245		return false
3246	}
3247	if depTag == staticVariantTag {
3248		// This dependency is for optimization (reuse *.o from the static lib). It doesn't
3249		// actually mean that the static lib (and its dependencies) are copied into the
3250		// APEX.
3251		return false
3252	}
3253	return true
3254}
3255
3256// Implements android.ApexModule
3257func (c *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
3258	sdkVersion android.ApiLevel) error {
3259	// We ignore libclang_rt.* prebuilt libs since they declare sdk_version: 14(b/121358700)
3260	if strings.HasPrefix(ctx.OtherModuleName(c), "libclang_rt") {
3261		return nil
3262	}
3263	// b/154569636: set min_sdk_version correctly for toolchain_libraries
3264	if c.ToolchainLibrary() {
3265		return nil
3266	}
3267	// We don't check for prebuilt modules
3268	if _, ok := c.linker.(prebuiltLinkerInterface); ok {
3269		return nil
3270	}
3271	minSdkVersion := c.MinSdkVersion()
3272	if minSdkVersion == "apex_inherit" {
3273		return nil
3274	}
3275	if minSdkVersion == "" {
3276		// JNI libs within APK-in-APEX fall into here
3277		// Those are okay to set sdk_version instead
3278		// We don't have to check if this is a SDK variant because
3279		// non-SDK variant resets sdk_version, which works too.
3280		minSdkVersion = c.SdkVersion()
3281	}
3282	if minSdkVersion == "" {
3283		return fmt.Errorf("neither min_sdk_version nor sdk_version specificed")
3284	}
3285	// Not using nativeApiLevelFromUser because the context here is not
3286	// necessarily a native context.
3287	ver, err := android.ApiLevelFromUser(ctx, minSdkVersion)
3288	if err != nil {
3289		return err
3290	}
3291
3292	if ver.GreaterThan(sdkVersion) {
3293		return fmt.Errorf("newer SDK(%v)", ver)
3294	}
3295	return nil
3296}
3297
3298// Implements android.ApexModule
3299func (c *Module) AlwaysRequiresPlatformApexVariant() bool {
3300	// stub libraries and native bridge libraries are always available to platform
3301	return c.IsStubs() || c.Target().NativeBridge == android.NativeBridgeEnabled
3302}
3303
3304//
3305// Defaults
3306//
3307type Defaults struct {
3308	android.ModuleBase
3309	android.DefaultsModuleBase
3310	// Included to support setting bazel_module.label for multiple Soong modules to the same Bazel
3311	// target. This is primarily useful for modules that were architecture specific and instead are
3312	// handled in Bazel as a select().
3313	android.BazelModuleBase
3314	android.ApexModuleBase
3315}
3316
3317// cc_defaults provides a set of properties that can be inherited by other cc
3318// modules. A module can use the properties from a cc_defaults using
3319// `defaults: ["<:default_module_name>"]`. Properties of both modules are
3320// merged (when possible) by prepending the default module's values to the
3321// depending module's values.
3322func defaultsFactory() android.Module {
3323	return DefaultsFactory()
3324}
3325
3326func DefaultsFactory(props ...interface{}) android.Module {
3327	module := &Defaults{}
3328
3329	module.AddProperties(props...)
3330	module.AddProperties(
3331		&BaseProperties{},
3332		&VendorProperties{},
3333		&BaseCompilerProperties{},
3334		&BaseLinkerProperties{},
3335		&ObjectLinkerProperties{},
3336		&LibraryProperties{},
3337		&StaticProperties{},
3338		&SharedProperties{},
3339		&FlagExporterProperties{},
3340		&BinaryLinkerProperties{},
3341		&TestProperties{},
3342		&TestBinaryProperties{},
3343		&BenchmarkProperties{},
3344		&FuzzProperties{},
3345		&StlProperties{},
3346		&SanitizeProperties{},
3347		&StripProperties{},
3348		&InstallerProperties{},
3349		&TidyProperties{},
3350		&CoverageProperties{},
3351		&SAbiProperties{},
3352		&VndkProperties{},
3353		&LTOProperties{},
3354		&PgoProperties{},
3355		&android.ProtoProperties{},
3356		// RustBindgenProperties is included here so that cc_defaults can be used for rust_bindgen modules.
3357		&RustBindgenClangProperties{},
3358		&prebuiltLinkerProperties{},
3359	)
3360
3361	// Bazel module must be initialized _before_ Defaults to be included in cc_defaults module.
3362	android.InitBazelModule(module)
3363	android.InitDefaultsModule(module)
3364
3365	return module
3366}
3367
3368func (c *Module) IsSdkVariant() bool {
3369	return c.Properties.IsSdkVariant || c.AlwaysSdk()
3370}
3371
3372func kytheExtractAllFactory() android.Singleton {
3373	return &kytheExtractAllSingleton{}
3374}
3375
3376type kytheExtractAllSingleton struct {
3377}
3378
3379func (ks *kytheExtractAllSingleton) GenerateBuildActions(ctx android.SingletonContext) {
3380	var xrefTargets android.Paths
3381	ctx.VisitAllModules(func(module android.Module) {
3382		if ccModule, ok := module.(xref); ok {
3383			xrefTargets = append(xrefTargets, ccModule.XrefCcFiles()...)
3384		}
3385	})
3386	// TODO(asmundak): Perhaps emit a rule to output a warning if there were no xrefTargets
3387	if len(xrefTargets) > 0 {
3388		ctx.Phony("xref_cxx", xrefTargets...)
3389	}
3390}
3391
3392var Bool = proptools.Bool
3393var BoolDefault = proptools.BoolDefault
3394var BoolPtr = proptools.BoolPtr
3395var String = proptools.String
3396var StringPtr = proptools.StringPtr
3397