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