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