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