Home | History | Annotate | Download | only in cc
      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 
     15 package 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 
     21 import (
     22 	"strconv"
     23 	"strings"
     24 
     25 	"github.com/google/blueprint"
     26 	"github.com/google/blueprint/proptools"
     27 
     28 	"android/soong/android"
     29 	"android/soong/cc/config"
     30 	"android/soong/genrule"
     31 )
     32 
     33 func init() {
     34 	android.RegisterModuleType("cc_defaults", defaultsFactory)
     35 
     36 	android.PreDepsMutators(func(ctx android.RegisterMutatorsContext) {
     37 		ctx.BottomUp("image", vendorMutator).Parallel()
     38 		ctx.BottomUp("link", linkageMutator).Parallel()
     39 		ctx.BottomUp("vndk", vndkMutator).Parallel()
     40 		ctx.BottomUp("ndk_api", ndkApiMutator).Parallel()
     41 		ctx.BottomUp("test_per_src", testPerSrcMutator).Parallel()
     42 		ctx.BottomUp("begin", beginMutator).Parallel()
     43 	})
     44 
     45 	android.PostDepsMutators(func(ctx android.RegisterMutatorsContext) {
     46 		ctx.TopDown("asan_deps", sanitizerDepsMutator(asan))
     47 		ctx.BottomUp("asan", sanitizerMutator(asan)).Parallel()
     48 
     49 		ctx.TopDown("cfi_deps", sanitizerDepsMutator(cfi))
     50 		ctx.BottomUp("cfi", sanitizerMutator(cfi)).Parallel()
     51 
     52 		ctx.TopDown("tsan_deps", sanitizerDepsMutator(tsan))
     53 		ctx.BottomUp("tsan", sanitizerMutator(tsan)).Parallel()
     54 
     55 		ctx.TopDown("minimal_runtime_deps", minimalRuntimeDepsMutator())
     56 
     57 		ctx.BottomUp("coverage", coverageLinkingMutator).Parallel()
     58 		ctx.TopDown("vndk_deps", sabiDepsMutator)
     59 
     60 		ctx.TopDown("lto_deps", ltoDepsMutator)
     61 		ctx.BottomUp("lto", ltoMutator).Parallel()
     62 	})
     63 
     64 	pctx.Import("android/soong/cc/config")
     65 }
     66 
     67 type Deps struct {
     68 	SharedLibs, LateSharedLibs                  []string
     69 	StaticLibs, LateStaticLibs, WholeStaticLibs []string
     70 	HeaderLibs                                  []string
     71 
     72 	ReexportSharedLibHeaders, ReexportStaticLibHeaders, ReexportHeaderLibHeaders []string
     73 
     74 	ObjFiles []string
     75 
     76 	GeneratedSources []string
     77 	GeneratedHeaders []string
     78 
     79 	ReexportGeneratedHeaders []string
     80 
     81 	CrtBegin, CrtEnd string
     82 	LinkerScript     string
     83 }
     84 
     85 type PathDeps struct {
     86 	// Paths to .so files
     87 	SharedLibs, LateSharedLibs android.Paths
     88 	// Paths to the dependencies to use for .so files (.so.toc files)
     89 	SharedLibsDeps, LateSharedLibsDeps android.Paths
     90 	// Paths to .a files
     91 	StaticLibs, LateStaticLibs, WholeStaticLibs android.Paths
     92 
     93 	// Paths to .o files
     94 	Objs               Objects
     95 	StaticLibObjs      Objects
     96 	WholeStaticLibObjs Objects
     97 
     98 	// Paths to generated source files
     99 	GeneratedSources android.Paths
    100 	GeneratedHeaders android.Paths
    101 
    102 	Flags, ReexportedFlags []string
    103 	ReexportedFlagsDeps    android.Paths
    104 
    105 	// Paths to crt*.o files
    106 	CrtBegin, CrtEnd android.OptionalPath
    107 	LinkerScript     android.OptionalPath
    108 }
    109 
    110 type Flags struct {
    111 	GlobalFlags     []string // Flags that apply to C, C++, and assembly source files
    112 	ArFlags         []string // Flags that apply to ar
    113 	AsFlags         []string // Flags that apply to assembly source files
    114 	CFlags          []string // Flags that apply to C and C++ source files
    115 	ToolingCFlags   []string // Flags that apply to C and C++ source files parsed by clang LibTooling tools
    116 	ConlyFlags      []string // Flags that apply to C source files
    117 	CppFlags        []string // Flags that apply to C++ source files
    118 	ToolingCppFlags []string // Flags that apply to C++ source files parsed by clang LibTooling tools
    119 	YaccFlags       []string // Flags that apply to Yacc source files
    120 	protoFlags      []string // Flags that apply to proto source files
    121 	protoOutParams  []string // Flags that modify the output of proto generated files
    122 	aidlFlags       []string // Flags that apply to aidl source files
    123 	rsFlags         []string // Flags that apply to renderscript source files
    124 	LdFlags         []string // Flags that apply to linker command lines
    125 	libFlags        []string // Flags to add libraries early to the link order
    126 	TidyFlags       []string // Flags that apply to clang-tidy
    127 	SAbiFlags       []string // Flags that apply to header-abi-dumper
    128 	YasmFlags       []string // Flags that apply to yasm assembly source files
    129 
    130 	// Global include flags that apply to C, C++, and assembly source files
    131 	// These must be after any module include flags, which will be in GlobalFlags.
    132 	SystemIncludeFlags []string
    133 
    134 	Toolchain config.Toolchain
    135 	Clang     bool
    136 	Tidy      bool
    137 	Coverage  bool
    138 	SAbiDump  bool
    139 	ProtoRoot bool
    140 
    141 	RequiredInstructionSet string
    142 	DynamicLinker          string
    143 
    144 	CFlagsDeps  android.Paths // Files depended on by compiler flags
    145 	LdFlagsDeps android.Paths // Files depended on by linker flags
    146 
    147 	GroupStaticLibs bool
    148 	ArGoldPlugin    bool // Whether LLVM gold plugin option is passed to llvm-ar
    149 }
    150 
    151 type ObjectLinkerProperties struct {
    152 	// names of other cc_object modules to link into this module using partial linking
    153 	Objs []string `android:"arch_variant"`
    154 
    155 	// if set, add an extra objcopy --prefix-symbols= step
    156 	Prefix_symbols *string
    157 }
    158 
    159 // Properties used to compile all C or C++ modules
    160 type BaseProperties struct {
    161 	// compile module with clang instead of gcc
    162 	Clang *bool `android:"arch_variant"`
    163 
    164 	// Minimum sdk version supported when compiling against the ndk
    165 	Sdk_version *string
    166 
    167 	AndroidMkSharedLibs []string `blueprint:"mutated"`
    168 	HideFromMake        bool     `blueprint:"mutated"`
    169 	PreventInstall      bool     `blueprint:"mutated"`
    170 
    171 	UseVndk bool `blueprint:"mutated"`
    172 
    173 	// *.logtags files, to combine together in order to generate the /system/etc/event-log-tags
    174 	// file
    175 	Logtags []string
    176 }
    177 
    178 type VendorProperties struct {
    179 	// whether this module should be allowed to be directly depended by other
    180 	// modules with `vendor: true`, `proprietary: true`, or `vendor_available:true`.
    181 	// If set to true, two variants will be built separately, one like
    182 	// normal, and the other limited to the set of libraries and headers
    183 	// that are exposed to /vendor modules.
    184 	//
    185 	// The vendor variant may be used with a different (newer) /system,
    186 	// so it shouldn't have any unversioned runtime dependencies, or
    187 	// make assumptions about the system that may not be true in the
    188 	// future.
    189 	//
    190 	// If set to false, this module becomes inaccessible from /vendor modules.
    191 	//
    192 	// Default value is true when vndk: {enabled: true} or vendor: true.
    193 	//
    194 	// Nothing happens if BOARD_VNDK_VERSION isn't set in the BoardConfig.mk
    195 	Vendor_available *bool
    196 }
    197 
    198 type UnusedProperties struct {
    199 	Tags []string
    200 }
    201 
    202 type ModuleContextIntf interface {
    203 	static() bool
    204 	staticBinary() bool
    205 	clang() bool
    206 	toolchain() config.Toolchain
    207 	useSdk() bool
    208 	sdkVersion() string
    209 	useVndk() bool
    210 	isVndk() bool
    211 	isVndkSp() bool
    212 	isVndkExt() bool
    213 	createVndkSourceAbiDump() bool
    214 	selectedStl() string
    215 	baseModuleName() string
    216 	getVndkExtendsModuleName() string
    217 	isPgoCompile() bool
    218 }
    219 
    220 type ModuleContext interface {
    221 	android.ModuleContext
    222 	ModuleContextIntf
    223 }
    224 
    225 type BaseModuleContext interface {
    226 	android.BaseContext
    227 	ModuleContextIntf
    228 }
    229 
    230 type DepsContext interface {
    231 	android.BottomUpMutatorContext
    232 	ModuleContextIntf
    233 }
    234 
    235 type feature interface {
    236 	begin(ctx BaseModuleContext)
    237 	deps(ctx DepsContext, deps Deps) Deps
    238 	flags(ctx ModuleContext, flags Flags) Flags
    239 	props() []interface{}
    240 }
    241 
    242 type compiler interface {
    243 	compilerInit(ctx BaseModuleContext)
    244 	compilerDeps(ctx DepsContext, deps Deps) Deps
    245 	compilerFlags(ctx ModuleContext, flags Flags, deps PathDeps) Flags
    246 	compilerProps() []interface{}
    247 
    248 	appendCflags([]string)
    249 	appendAsflags([]string)
    250 	compile(ctx ModuleContext, flags Flags, deps PathDeps) Objects
    251 }
    252 
    253 type linker interface {
    254 	linkerInit(ctx BaseModuleContext)
    255 	linkerDeps(ctx DepsContext, deps Deps) Deps
    256 	linkerFlags(ctx ModuleContext, flags Flags) Flags
    257 	linkerProps() []interface{}
    258 
    259 	link(ctx ModuleContext, flags Flags, deps PathDeps, objs Objects) android.Path
    260 	appendLdflags([]string)
    261 }
    262 
    263 type installer interface {
    264 	installerProps() []interface{}
    265 	install(ctx ModuleContext, path android.Path)
    266 	inData() bool
    267 	inSanitizerDir() bool
    268 	hostToolPath() android.OptionalPath
    269 }
    270 
    271 type dependencyTag struct {
    272 	blueprint.BaseDependencyTag
    273 	name    string
    274 	library bool
    275 
    276 	reexportFlags bool
    277 }
    278 
    279 var (
    280 	sharedDepTag          = dependencyTag{name: "shared", library: true}
    281 	sharedExportDepTag    = dependencyTag{name: "shared", library: true, reexportFlags: true}
    282 	lateSharedDepTag      = dependencyTag{name: "late shared", library: true}
    283 	staticDepTag          = dependencyTag{name: "static", library: true}
    284 	staticExportDepTag    = dependencyTag{name: "static", library: true, reexportFlags: true}
    285 	lateStaticDepTag      = dependencyTag{name: "late static", library: true}
    286 	wholeStaticDepTag     = dependencyTag{name: "whole static", library: true, reexportFlags: true}
    287 	headerDepTag          = dependencyTag{name: "header", library: true}
    288 	headerExportDepTag    = dependencyTag{name: "header", library: true, reexportFlags: true}
    289 	genSourceDepTag       = dependencyTag{name: "gen source"}
    290 	genHeaderDepTag       = dependencyTag{name: "gen header"}
    291 	genHeaderExportDepTag = dependencyTag{name: "gen header", reexportFlags: true}
    292 	objDepTag             = dependencyTag{name: "obj"}
    293 	crtBeginDepTag        = dependencyTag{name: "crtbegin"}
    294 	crtEndDepTag          = dependencyTag{name: "crtend"}
    295 	linkerScriptDepTag    = dependencyTag{name: "linker script"}
    296 	reuseObjTag           = dependencyTag{name: "reuse objects"}
    297 	ndkStubDepTag         = dependencyTag{name: "ndk stub", library: true}
    298 	ndkLateStubDepTag     = dependencyTag{name: "ndk late stub", library: true}
    299 	vndkExtDepTag         = dependencyTag{name: "vndk extends", library: true}
    300 )
    301 
    302 // Module contains the properties and members used by all C/C++ module types, and implements
    303 // the blueprint.Module interface.  It delegates to compiler, linker, and installer interfaces
    304 // to construct the output file.  Behavior can be customized with a Customizer interface
    305 type Module struct {
    306 	android.ModuleBase
    307 	android.DefaultableModuleBase
    308 
    309 	Properties       BaseProperties
    310 	VendorProperties VendorProperties
    311 	unused           UnusedProperties
    312 
    313 	// initialize before calling Init
    314 	hod      android.HostOrDeviceSupported
    315 	multilib android.Multilib
    316 
    317 	// delegates, initialize before calling Init
    318 	features  []feature
    319 	compiler  compiler
    320 	linker    linker
    321 	installer installer
    322 	stl       *stl
    323 	sanitize  *sanitize
    324 	coverage  *coverage
    325 	sabi      *sabi
    326 	vndkdep   *vndkdep
    327 	lto       *lto
    328 	pgo       *pgo
    329 
    330 	androidMkSharedLibDeps []string
    331 
    332 	outputFile android.OptionalPath
    333 
    334 	cachedToolchain config.Toolchain
    335 
    336 	subAndroidMkOnce map[subAndroidMkProvider]bool
    337 
    338 	// Flags used to compile this module
    339 	flags Flags
    340 
    341 	// When calling a linker, if module A depends on module B, then A must precede B in its command
    342 	// line invocation. depsInLinkOrder stores the proper ordering of all of the transitive
    343 	// deps of this module
    344 	depsInLinkOrder android.Paths
    345 
    346 	// only non-nil when this is a shared library that reuses the objects of a static library
    347 	staticVariant *Module
    348 }
    349 
    350 func (c *Module) Init() android.Module {
    351 	c.AddProperties(&c.Properties, &c.VendorProperties, &c.unused)
    352 	if c.compiler != nil {
    353 		c.AddProperties(c.compiler.compilerProps()...)
    354 	}
    355 	if c.linker != nil {
    356 		c.AddProperties(c.linker.linkerProps()...)
    357 	}
    358 	if c.installer != nil {
    359 		c.AddProperties(c.installer.installerProps()...)
    360 	}
    361 	if c.stl != nil {
    362 		c.AddProperties(c.stl.props()...)
    363 	}
    364 	if c.sanitize != nil {
    365 		c.AddProperties(c.sanitize.props()...)
    366 	}
    367 	if c.coverage != nil {
    368 		c.AddProperties(c.coverage.props()...)
    369 	}
    370 	if c.sabi != nil {
    371 		c.AddProperties(c.sabi.props()...)
    372 	}
    373 	if c.vndkdep != nil {
    374 		c.AddProperties(c.vndkdep.props()...)
    375 	}
    376 	if c.lto != nil {
    377 		c.AddProperties(c.lto.props()...)
    378 	}
    379 	if c.pgo != nil {
    380 		c.AddProperties(c.pgo.props()...)
    381 	}
    382 	for _, feature := range c.features {
    383 		c.AddProperties(feature.props()...)
    384 	}
    385 
    386 	android.InitAndroidArchModule(c, c.hod, c.multilib)
    387 
    388 	android.InitDefaultableModule(c)
    389 
    390 	return c
    391 }
    392 
    393 // Returns true for dependency roots (binaries)
    394 // TODO(ccross): also handle dlopenable libraries
    395 func (c *Module) isDependencyRoot() bool {
    396 	if root, ok := c.linker.(interface {
    397 		isDependencyRoot() bool
    398 	}); ok {
    399 		return root.isDependencyRoot()
    400 	}
    401 	return false
    402 }
    403 
    404 func (c *Module) useVndk() bool {
    405 	return c.Properties.UseVndk
    406 }
    407 
    408 func (c *Module) isVndk() bool {
    409 	if vndkdep := c.vndkdep; vndkdep != nil {
    410 		return vndkdep.isVndk()
    411 	}
    412 	return false
    413 }
    414 
    415 func (c *Module) isPgoCompile() bool {
    416 	if pgo := c.pgo; pgo != nil {
    417 		return pgo.Properties.PgoCompile
    418 	}
    419 	return false
    420 }
    421 
    422 func (c *Module) isVndkSp() bool {
    423 	if vndkdep := c.vndkdep; vndkdep != nil {
    424 		return vndkdep.isVndkSp()
    425 	}
    426 	return false
    427 }
    428 
    429 func (c *Module) isVndkExt() bool {
    430 	if vndkdep := c.vndkdep; vndkdep != nil {
    431 		return vndkdep.isVndkExt()
    432 	}
    433 	return false
    434 }
    435 
    436 func (c *Module) getVndkExtendsModuleName() string {
    437 	if vndkdep := c.vndkdep; vndkdep != nil {
    438 		return vndkdep.getVndkExtendsModuleName()
    439 	}
    440 	return ""
    441 }
    442 
    443 // Returns true only when this module is configured to have core and vendor
    444 // variants.
    445 func (c *Module) hasVendorVariant() bool {
    446 	return c.isVndk() || Bool(c.VendorProperties.Vendor_available)
    447 }
    448 
    449 type baseModuleContext struct {
    450 	android.BaseContext
    451 	moduleContextImpl
    452 }
    453 
    454 type depsContext struct {
    455 	android.BottomUpMutatorContext
    456 	moduleContextImpl
    457 }
    458 
    459 type moduleContext struct {
    460 	android.ModuleContext
    461 	moduleContextImpl
    462 }
    463 
    464 func (ctx *moduleContext) SocSpecific() bool {
    465 	return ctx.ModuleContext.SocSpecific() ||
    466 		(ctx.mod.hasVendorVariant() && ctx.mod.useVndk() && !ctx.mod.isVndk())
    467 }
    468 
    469 type moduleContextImpl struct {
    470 	mod *Module
    471 	ctx BaseModuleContext
    472 }
    473 
    474 func (ctx *moduleContextImpl) clang() bool {
    475 	return ctx.mod.clang(ctx.ctx)
    476 }
    477 
    478 func (ctx *moduleContextImpl) toolchain() config.Toolchain {
    479 	return ctx.mod.toolchain(ctx.ctx)
    480 }
    481 
    482 func (ctx *moduleContextImpl) static() bool {
    483 	return ctx.mod.static()
    484 }
    485 
    486 func (ctx *moduleContextImpl) staticBinary() bool {
    487 	if static, ok := ctx.mod.linker.(interface {
    488 		staticBinary() bool
    489 	}); ok {
    490 		return static.staticBinary()
    491 	}
    492 	return false
    493 }
    494 
    495 func (ctx *moduleContextImpl) useSdk() bool {
    496 	if ctx.ctx.Device() && !ctx.useVndk() {
    497 		return String(ctx.mod.Properties.Sdk_version) != ""
    498 	}
    499 	return false
    500 }
    501 
    502 func (ctx *moduleContextImpl) sdkVersion() string {
    503 	if ctx.ctx.Device() {
    504 		if ctx.useVndk() {
    505 			vndk_ver := ctx.ctx.DeviceConfig().VndkVersion()
    506 			if vndk_ver == "current" {
    507 				platform_vndk_ver := ctx.ctx.DeviceConfig().PlatformVndkVersion()
    508 				if inList(platform_vndk_ver, ctx.ctx.Config().PlatformVersionCombinedCodenames()) {
    509 					return "current"
    510 				}
    511 				return platform_vndk_ver
    512 			}
    513 			return vndk_ver
    514 		}
    515 		return String(ctx.mod.Properties.Sdk_version)
    516 	}
    517 	return ""
    518 }
    519 
    520 func (ctx *moduleContextImpl) useVndk() bool {
    521 	return ctx.mod.useVndk()
    522 }
    523 
    524 func (ctx *moduleContextImpl) isVndk() bool {
    525 	return ctx.mod.isVndk()
    526 }
    527 
    528 func (ctx *moduleContextImpl) isPgoCompile() bool {
    529 	return ctx.mod.isPgoCompile()
    530 }
    531 
    532 func (ctx *moduleContextImpl) isVndkSp() bool {
    533 	return ctx.mod.isVndkSp()
    534 }
    535 
    536 func (ctx *moduleContextImpl) isVndkExt() bool {
    537 	return ctx.mod.isVndkExt()
    538 }
    539 
    540 // Create source abi dumps if the module belongs to the list of VndkLibraries.
    541 func (ctx *moduleContextImpl) createVndkSourceAbiDump() bool {
    542 	skipAbiChecks := ctx.ctx.Config().IsEnvTrue("SKIP_ABI_CHECKS")
    543 	isVariantOnProductionDevice := true
    544 	sanitize := ctx.mod.sanitize
    545 	if sanitize != nil {
    546 		isVariantOnProductionDevice = sanitize.isVariantOnProductionDevice()
    547 	}
    548 	vendorAvailable := Bool(ctx.mod.VendorProperties.Vendor_available)
    549 	return !skipAbiChecks && isVariantOnProductionDevice && ctx.ctx.Device() && ((ctx.useVndk() && ctx.isVndk() && (vendorAvailable || ctx.isVndkExt())) || inList(ctx.baseModuleName(), llndkLibraries))
    550 }
    551 
    552 func (ctx *moduleContextImpl) selectedStl() string {
    553 	if stl := ctx.mod.stl; stl != nil {
    554 		return stl.Properties.SelectedStl
    555 	}
    556 	return ""
    557 }
    558 
    559 func (ctx *moduleContextImpl) baseModuleName() string {
    560 	return ctx.mod.ModuleBase.BaseModuleName()
    561 }
    562 
    563 func (ctx *moduleContextImpl) getVndkExtendsModuleName() string {
    564 	return ctx.mod.getVndkExtendsModuleName()
    565 }
    566 
    567 func newBaseModule(hod android.HostOrDeviceSupported, multilib android.Multilib) *Module {
    568 	return &Module{
    569 		hod:      hod,
    570 		multilib: multilib,
    571 	}
    572 }
    573 
    574 func newModule(hod android.HostOrDeviceSupported, multilib android.Multilib) *Module {
    575 	module := newBaseModule(hod, multilib)
    576 	module.features = []feature{
    577 		&tidyFeature{},
    578 	}
    579 	module.stl = &stl{}
    580 	module.sanitize = &sanitize{}
    581 	module.coverage = &coverage{}
    582 	module.sabi = &sabi{}
    583 	module.vndkdep = &vndkdep{}
    584 	module.lto = &lto{}
    585 	module.pgo = &pgo{}
    586 	return module
    587 }
    588 
    589 func (c *Module) Prebuilt() *android.Prebuilt {
    590 	if p, ok := c.linker.(prebuiltLinkerInterface); ok {
    591 		return p.prebuilt()
    592 	}
    593 	return nil
    594 }
    595 
    596 func (c *Module) Name() string {
    597 	name := c.ModuleBase.Name()
    598 	if p, ok := c.linker.(interface {
    599 		Name(string) string
    600 	}); ok {
    601 		name = p.Name(name)
    602 	}
    603 	return name
    604 }
    605 
    606 // orderDeps reorders dependencies into a list such that if module A depends on B, then
    607 // A will precede B in the resultant list.
    608 // This is convenient for passing into a linker.
    609 // Note that directSharedDeps should be the analogous static library for each shared lib dep
    610 func orderDeps(directStaticDeps []android.Path, directSharedDeps []android.Path, allTransitiveDeps map[android.Path][]android.Path) (orderedAllDeps []android.Path, orderedDeclaredDeps []android.Path) {
    611 	// If A depends on B, then
    612 	//   Every list containing A will also contain B later in the list
    613 	//   So, after concatenating all lists, the final instance of B will have come from the same
    614 	//     original list as the final instance of A
    615 	//   So, the final instance of B will be later in the concatenation than the final A
    616 	//   So, keeping only the final instance of A and of B ensures that A is earlier in the output
    617 	//     list than B
    618 	for _, dep := range directStaticDeps {
    619 		orderedAllDeps = append(orderedAllDeps, dep)
    620 		orderedAllDeps = append(orderedAllDeps, allTransitiveDeps[dep]...)
    621 	}
    622 	for _, dep := range directSharedDeps {
    623 		orderedAllDeps = append(orderedAllDeps, dep)
    624 		orderedAllDeps = append(orderedAllDeps, allTransitiveDeps[dep]...)
    625 	}
    626 
    627 	orderedAllDeps = android.LastUniquePaths(orderedAllDeps)
    628 
    629 	// We don't want to add any new dependencies into directStaticDeps (to allow the caller to
    630 	// intentionally exclude or replace any unwanted transitive dependencies), so we limit the
    631 	// resultant list to only what the caller has chosen to include in directStaticDeps
    632 	_, orderedDeclaredDeps = android.FilterPathList(orderedAllDeps, directStaticDeps)
    633 
    634 	return orderedAllDeps, orderedDeclaredDeps
    635 }
    636 
    637 func orderStaticModuleDeps(module *Module, staticDeps []*Module, sharedDeps []*Module) (results []android.Path) {
    638 	// convert Module to Path
    639 	allTransitiveDeps := make(map[android.Path][]android.Path, len(staticDeps))
    640 	staticDepFiles := []android.Path{}
    641 	for _, dep := range staticDeps {
    642 		allTransitiveDeps[dep.outputFile.Path()] = dep.depsInLinkOrder
    643 		staticDepFiles = append(staticDepFiles, dep.outputFile.Path())
    644 	}
    645 	sharedDepFiles := []android.Path{}
    646 	for _, sharedDep := range sharedDeps {
    647 		staticAnalogue := sharedDep.staticVariant
    648 		if staticAnalogue != nil {
    649 			allTransitiveDeps[staticAnalogue.outputFile.Path()] = staticAnalogue.depsInLinkOrder
    650 			sharedDepFiles = append(sharedDepFiles, staticAnalogue.outputFile.Path())
    651 		}
    652 	}
    653 
    654 	// reorder the dependencies based on transitive dependencies
    655 	module.depsInLinkOrder, results = orderDeps(staticDepFiles, sharedDepFiles, allTransitiveDeps)
    656 
    657 	return results
    658 }
    659 
    660 func (c *Module) GenerateAndroidBuildActions(actx android.ModuleContext) {
    661 
    662 	ctx := &moduleContext{
    663 		ModuleContext: actx,
    664 		moduleContextImpl: moduleContextImpl{
    665 			mod: c,
    666 		},
    667 	}
    668 	ctx.ctx = ctx
    669 
    670 	deps := c.depsToPaths(ctx)
    671 	if ctx.Failed() {
    672 		return
    673 	}
    674 
    675 	flags := Flags{
    676 		Toolchain: c.toolchain(ctx),
    677 		Clang:     c.clang(ctx),
    678 	}
    679 	if c.compiler != nil {
    680 		flags = c.compiler.compilerFlags(ctx, flags, deps)
    681 	}
    682 	if c.linker != nil {
    683 		flags = c.linker.linkerFlags(ctx, flags)
    684 	}
    685 	if c.stl != nil {
    686 		flags = c.stl.flags(ctx, flags)
    687 	}
    688 	if c.sanitize != nil {
    689 		flags = c.sanitize.flags(ctx, flags)
    690 	}
    691 	if c.coverage != nil {
    692 		flags = c.coverage.flags(ctx, flags)
    693 	}
    694 	if c.lto != nil {
    695 		flags = c.lto.flags(ctx, flags)
    696 	}
    697 	if c.pgo != nil {
    698 		flags = c.pgo.flags(ctx, flags)
    699 	}
    700 	for _, feature := range c.features {
    701 		flags = feature.flags(ctx, flags)
    702 	}
    703 	if ctx.Failed() {
    704 		return
    705 	}
    706 
    707 	flags.CFlags, _ = filterList(flags.CFlags, config.IllegalFlags)
    708 	flags.CppFlags, _ = filterList(flags.CppFlags, config.IllegalFlags)
    709 	flags.ConlyFlags, _ = filterList(flags.ConlyFlags, config.IllegalFlags)
    710 
    711 	flags.GlobalFlags = append(flags.GlobalFlags, deps.Flags...)
    712 	c.flags = flags
    713 	// We need access to all the flags seen by a source file.
    714 	if c.sabi != nil {
    715 		flags = c.sabi.flags(ctx, flags)
    716 	}
    717 	// Optimization to reduce size of build.ninja
    718 	// Replace the long list of flags for each file with a module-local variable
    719 	ctx.Variable(pctx, "cflags", strings.Join(flags.CFlags, " "))
    720 	ctx.Variable(pctx, "cppflags", strings.Join(flags.CppFlags, " "))
    721 	ctx.Variable(pctx, "asflags", strings.Join(flags.AsFlags, " "))
    722 	flags.CFlags = []string{"$cflags"}
    723 	flags.CppFlags = []string{"$cppflags"}
    724 	flags.AsFlags = []string{"$asflags"}
    725 
    726 	var objs Objects
    727 	if c.compiler != nil {
    728 		objs = c.compiler.compile(ctx, flags, deps)
    729 		if ctx.Failed() {
    730 			return
    731 		}
    732 	}
    733 
    734 	if c.linker != nil {
    735 		outputFile := c.linker.link(ctx, flags, deps, objs)
    736 		if ctx.Failed() {
    737 			return
    738 		}
    739 		c.outputFile = android.OptionalPathForPath(outputFile)
    740 	}
    741 
    742 	if c.installer != nil && !c.Properties.PreventInstall && c.outputFile.Valid() {
    743 		c.installer.install(ctx, c.outputFile.Path())
    744 		if ctx.Failed() {
    745 			return
    746 		}
    747 	}
    748 }
    749 
    750 func (c *Module) toolchain(ctx BaseModuleContext) config.Toolchain {
    751 	if c.cachedToolchain == nil {
    752 		c.cachedToolchain = config.FindToolchain(ctx.Os(), ctx.Arch())
    753 	}
    754 	return c.cachedToolchain
    755 }
    756 
    757 func (c *Module) begin(ctx BaseModuleContext) {
    758 	if c.compiler != nil {
    759 		c.compiler.compilerInit(ctx)
    760 	}
    761 	if c.linker != nil {
    762 		c.linker.linkerInit(ctx)
    763 	}
    764 	if c.stl != nil {
    765 		c.stl.begin(ctx)
    766 	}
    767 	if c.sanitize != nil {
    768 		c.sanitize.begin(ctx)
    769 	}
    770 	if c.coverage != nil {
    771 		c.coverage.begin(ctx)
    772 	}
    773 	if c.sabi != nil {
    774 		c.sabi.begin(ctx)
    775 	}
    776 	if c.vndkdep != nil {
    777 		c.vndkdep.begin(ctx)
    778 	}
    779 	if c.lto != nil {
    780 		c.lto.begin(ctx)
    781 	}
    782 	if c.pgo != nil {
    783 		c.pgo.begin(ctx)
    784 	}
    785 	for _, feature := range c.features {
    786 		feature.begin(ctx)
    787 	}
    788 	if ctx.useSdk() {
    789 		version, err := normalizeNdkApiLevel(ctx, ctx.sdkVersion(), ctx.Arch())
    790 		if err != nil {
    791 			ctx.PropertyErrorf("sdk_version", err.Error())
    792 		}
    793 		c.Properties.Sdk_version = StringPtr(version)
    794 	}
    795 }
    796 
    797 func (c *Module) deps(ctx DepsContext) Deps {
    798 	deps := Deps{}
    799 
    800 	if c.compiler != nil {
    801 		deps = c.compiler.compilerDeps(ctx, deps)
    802 	}
    803 	// Add the PGO dependency (the clang_rt.profile runtime library), which
    804 	// sometimes depends on symbols from libgcc, before libgcc gets added
    805 	// in linkerDeps().
    806 	if c.pgo != nil {
    807 		deps = c.pgo.deps(ctx, deps)
    808 	}
    809 	if c.linker != nil {
    810 		deps = c.linker.linkerDeps(ctx, deps)
    811 	}
    812 	if c.stl != nil {
    813 		deps = c.stl.deps(ctx, deps)
    814 	}
    815 	if c.sanitize != nil {
    816 		deps = c.sanitize.deps(ctx, deps)
    817 	}
    818 	if c.coverage != nil {
    819 		deps = c.coverage.deps(ctx, deps)
    820 	}
    821 	if c.sabi != nil {
    822 		deps = c.sabi.deps(ctx, deps)
    823 	}
    824 	if c.vndkdep != nil {
    825 		deps = c.vndkdep.deps(ctx, deps)
    826 	}
    827 	if c.lto != nil {
    828 		deps = c.lto.deps(ctx, deps)
    829 	}
    830 	for _, feature := range c.features {
    831 		deps = feature.deps(ctx, deps)
    832 	}
    833 
    834 	deps.WholeStaticLibs = android.LastUniqueStrings(deps.WholeStaticLibs)
    835 	deps.StaticLibs = android.LastUniqueStrings(deps.StaticLibs)
    836 	deps.LateStaticLibs = android.LastUniqueStrings(deps.LateStaticLibs)
    837 	deps.SharedLibs = android.LastUniqueStrings(deps.SharedLibs)
    838 	deps.LateSharedLibs = android.LastUniqueStrings(deps.LateSharedLibs)
    839 	deps.HeaderLibs = android.LastUniqueStrings(deps.HeaderLibs)
    840 
    841 	for _, lib := range deps.ReexportSharedLibHeaders {
    842 		if !inList(lib, deps.SharedLibs) {
    843 			ctx.PropertyErrorf("export_shared_lib_headers", "Shared library not in shared_libs: '%s'", lib)
    844 		}
    845 	}
    846 
    847 	for _, lib := range deps.ReexportStaticLibHeaders {
    848 		if !inList(lib, deps.StaticLibs) {
    849 			ctx.PropertyErrorf("export_static_lib_headers", "Static library not in static_libs: '%s'", lib)
    850 		}
    851 	}
    852 
    853 	for _, lib := range deps.ReexportHeaderLibHeaders {
    854 		if !inList(lib, deps.HeaderLibs) {
    855 			ctx.PropertyErrorf("export_header_lib_headers", "Header library not in header_libs: '%s'", lib)
    856 		}
    857 	}
    858 
    859 	for _, gen := range deps.ReexportGeneratedHeaders {
    860 		if !inList(gen, deps.GeneratedHeaders) {
    861 			ctx.PropertyErrorf("export_generated_headers", "Generated header module not in generated_headers: '%s'", gen)
    862 		}
    863 	}
    864 
    865 	return deps
    866 }
    867 
    868 func (c *Module) beginMutator(actx android.BottomUpMutatorContext) {
    869 	ctx := &baseModuleContext{
    870 		BaseContext: actx,
    871 		moduleContextImpl: moduleContextImpl{
    872 			mod: c,
    873 		},
    874 	}
    875 	ctx.ctx = ctx
    876 
    877 	c.begin(ctx)
    878 }
    879 
    880 func (c *Module) DepsMutator(actx android.BottomUpMutatorContext) {
    881 	if !c.Enabled() {
    882 		return
    883 	}
    884 
    885 	ctx := &depsContext{
    886 		BottomUpMutatorContext: actx,
    887 		moduleContextImpl: moduleContextImpl{
    888 			mod: c,
    889 		},
    890 	}
    891 	ctx.ctx = ctx
    892 
    893 	deps := c.deps(ctx)
    894 
    895 	variantNdkLibs := []string{}
    896 	variantLateNdkLibs := []string{}
    897 	if ctx.Os() == android.Android {
    898 		version := ctx.sdkVersion()
    899 
    900 		// rewriteNdkLibs takes a list of names of shared libraries and scans it for three types
    901 		// of names:
    902 		//
    903 		// 1. Name of an NDK library that refers to a prebuilt module.
    904 		//    For each of these, it adds the name of the prebuilt module (which will be in
    905 		//    prebuilts/ndk) to the list of nonvariant libs.
    906 		// 2. Name of an NDK library that refers to an ndk_library module.
    907 		//    For each of these, it adds the name of the ndk_library module to the list of
    908 		//    variant libs.
    909 		// 3. Anything else (so anything that isn't an NDK library).
    910 		//    It adds these to the nonvariantLibs list.
    911 		//
    912 		// The caller can then know to add the variantLibs dependencies differently from the
    913 		// nonvariantLibs
    914 		rewriteNdkLibs := func(list []string) (nonvariantLibs []string, variantLibs []string) {
    915 			variantLibs = []string{}
    916 			nonvariantLibs = []string{}
    917 			for _, entry := range list {
    918 				if ctx.useSdk() && inList(entry, ndkPrebuiltSharedLibraries) {
    919 					if !inList(entry, ndkMigratedLibs) {
    920 						nonvariantLibs = append(nonvariantLibs, entry+".ndk."+version)
    921 					} else {
    922 						variantLibs = append(variantLibs, entry+ndkLibrarySuffix)
    923 					}
    924 				} else if ctx.useVndk() && inList(entry, llndkLibraries) {
    925 					nonvariantLibs = append(nonvariantLibs, entry+llndkLibrarySuffix)
    926 				} else if (ctx.Platform() || ctx.ProductSpecific()) && inList(entry, vendorPublicLibraries) {
    927 					vendorPublicLib := entry + vendorPublicLibrarySuffix
    928 					if actx.OtherModuleExists(vendorPublicLib) {
    929 						nonvariantLibs = append(nonvariantLibs, vendorPublicLib)
    930 					} else {
    931 						// This can happen if vendor_public_library module is defined in a
    932 						// namespace that isn't visible to the current module. In that case,
    933 						// link to the original library.
    934 						nonvariantLibs = append(nonvariantLibs, entry)
    935 					}
    936 				} else {
    937 					nonvariantLibs = append(nonvariantLibs, entry)
    938 				}
    939 			}
    940 			return nonvariantLibs, variantLibs
    941 		}
    942 
    943 		deps.SharedLibs, variantNdkLibs = rewriteNdkLibs(deps.SharedLibs)
    944 		deps.LateSharedLibs, variantLateNdkLibs = rewriteNdkLibs(deps.LateSharedLibs)
    945 		deps.ReexportSharedLibHeaders, _ = rewriteNdkLibs(deps.ReexportSharedLibHeaders)
    946 	}
    947 
    948 	for _, lib := range deps.HeaderLibs {
    949 		depTag := headerDepTag
    950 		if inList(lib, deps.ReexportHeaderLibHeaders) {
    951 			depTag = headerExportDepTag
    952 		}
    953 		actx.AddVariationDependencies(nil, depTag, lib)
    954 	}
    955 
    956 	actx.AddVariationDependencies([]blueprint.Variation{{"link", "static"}}, wholeStaticDepTag,
    957 		deps.WholeStaticLibs...)
    958 
    959 	for _, lib := range deps.StaticLibs {
    960 		depTag := staticDepTag
    961 		if inList(lib, deps.ReexportStaticLibHeaders) {
    962 			depTag = staticExportDepTag
    963 		}
    964 		actx.AddVariationDependencies([]blueprint.Variation{{"link", "static"}}, depTag, lib)
    965 	}
    966 
    967 	actx.AddVariationDependencies([]blueprint.Variation{{"link", "static"}}, lateStaticDepTag,
    968 		deps.LateStaticLibs...)
    969 
    970 	for _, lib := range deps.SharedLibs {
    971 		depTag := sharedDepTag
    972 		if inList(lib, deps.ReexportSharedLibHeaders) {
    973 			depTag = sharedExportDepTag
    974 		}
    975 		actx.AddVariationDependencies([]blueprint.Variation{{"link", "shared"}}, depTag, lib)
    976 	}
    977 
    978 	actx.AddVariationDependencies([]blueprint.Variation{{"link", "shared"}}, lateSharedDepTag,
    979 		deps.LateSharedLibs...)
    980 
    981 	actx.AddDependency(c, genSourceDepTag, deps.GeneratedSources...)
    982 
    983 	for _, gen := range deps.GeneratedHeaders {
    984 		depTag := genHeaderDepTag
    985 		if inList(gen, deps.ReexportGeneratedHeaders) {
    986 			depTag = genHeaderExportDepTag
    987 		}
    988 		actx.AddDependency(c, depTag, gen)
    989 	}
    990 
    991 	actx.AddDependency(c, objDepTag, deps.ObjFiles...)
    992 
    993 	if deps.CrtBegin != "" {
    994 		actx.AddDependency(c, crtBeginDepTag, deps.CrtBegin)
    995 	}
    996 	if deps.CrtEnd != "" {
    997 		actx.AddDependency(c, crtEndDepTag, deps.CrtEnd)
    998 	}
    999 	if deps.LinkerScript != "" {
   1000 		actx.AddDependency(c, linkerScriptDepTag, deps.LinkerScript)
   1001 	}
   1002 
   1003 	version := ctx.sdkVersion()
   1004 	actx.AddVariationDependencies([]blueprint.Variation{
   1005 		{"ndk_api", version}, {"link", "shared"}}, ndkStubDepTag, variantNdkLibs...)
   1006 	actx.AddVariationDependencies([]blueprint.Variation{
   1007 		{"ndk_api", version}, {"link", "shared"}}, ndkLateStubDepTag, variantLateNdkLibs...)
   1008 
   1009 	if vndkdep := c.vndkdep; vndkdep != nil {
   1010 		if vndkdep.isVndkExt() {
   1011 			baseModuleMode := vendorMode
   1012 			if actx.DeviceConfig().VndkVersion() == "" {
   1013 				baseModuleMode = coreMode
   1014 			}
   1015 			actx.AddVariationDependencies([]blueprint.Variation{
   1016 				{"image", baseModuleMode}, {"link", "shared"}}, vndkExtDepTag,
   1017 				vndkdep.getVndkExtendsModuleName())
   1018 		}
   1019 	}
   1020 }
   1021 
   1022 func beginMutator(ctx android.BottomUpMutatorContext) {
   1023 	if c, ok := ctx.Module().(*Module); ok && c.Enabled() {
   1024 		c.beginMutator(ctx)
   1025 	}
   1026 }
   1027 
   1028 func (c *Module) clang(ctx BaseModuleContext) bool {
   1029 	clang := Bool(c.Properties.Clang)
   1030 
   1031 	if c.Properties.Clang == nil {
   1032 		clang = true
   1033 	}
   1034 
   1035 	if !c.toolchain(ctx).ClangSupported() {
   1036 		clang = false
   1037 	}
   1038 
   1039 	return clang
   1040 }
   1041 
   1042 // Whether a module can link to another module, taking into
   1043 // account NDK linking.
   1044 func checkLinkType(ctx android.ModuleContext, from *Module, to *Module, tag dependencyTag) {
   1045 	if from.Target().Os != android.Android {
   1046 		// Host code is not restricted
   1047 		return
   1048 	}
   1049 	if from.Properties.UseVndk {
   1050 		// Though vendor code is limited by the vendor mutator,
   1051 		// each vendor-available module needs to check
   1052 		// link-type for VNDK.
   1053 		if from.vndkdep != nil {
   1054 			from.vndkdep.vndkCheckLinkType(ctx, to, tag)
   1055 		}
   1056 		return
   1057 	}
   1058 	if String(from.Properties.Sdk_version) == "" {
   1059 		// Platform code can link to anything
   1060 		return
   1061 	}
   1062 	if _, ok := to.linker.(*toolchainLibraryDecorator); ok {
   1063 		// These are always allowed
   1064 		return
   1065 	}
   1066 	if _, ok := to.linker.(*ndkPrebuiltLibraryLinker); ok {
   1067 		// These are allowed, but they don't set sdk_version
   1068 		return
   1069 	}
   1070 	if _, ok := to.linker.(*ndkPrebuiltStlLinker); ok {
   1071 		// These are allowed, but they don't set sdk_version
   1072 		return
   1073 	}
   1074 	if _, ok := to.linker.(*stubDecorator); ok {
   1075 		// These aren't real libraries, but are the stub shared libraries that are included in
   1076 		// the NDK.
   1077 		return
   1078 	}
   1079 	if String(to.Properties.Sdk_version) == "" {
   1080 		// NDK code linking to platform code is never okay.
   1081 		ctx.ModuleErrorf("depends on non-NDK-built library %q",
   1082 			ctx.OtherModuleName(to))
   1083 	}
   1084 
   1085 	// At this point we know we have two NDK libraries, but we need to
   1086 	// check that we're not linking against anything built against a higher
   1087 	// API level, as it is only valid to link against older or equivalent
   1088 	// APIs.
   1089 
   1090 	if String(from.Properties.Sdk_version) == "current" {
   1091 		// Current can link against anything.
   1092 		return
   1093 	} else if String(to.Properties.Sdk_version) == "current" {
   1094 		// Current can't be linked against by anything else.
   1095 		ctx.ModuleErrorf("links %q built against newer API version %q",
   1096 			ctx.OtherModuleName(to), "current")
   1097 	}
   1098 
   1099 	fromApi, err := strconv.Atoi(String(from.Properties.Sdk_version))
   1100 	if err != nil {
   1101 		ctx.PropertyErrorf("sdk_version",
   1102 			"Invalid sdk_version value (must be int): %q",
   1103 			String(from.Properties.Sdk_version))
   1104 	}
   1105 	toApi, err := strconv.Atoi(String(to.Properties.Sdk_version))
   1106 	if err != nil {
   1107 		ctx.PropertyErrorf("sdk_version",
   1108 			"Invalid sdk_version value (must be int): %q",
   1109 			String(to.Properties.Sdk_version))
   1110 	}
   1111 
   1112 	if toApi > fromApi {
   1113 		ctx.ModuleErrorf("links %q built against newer API version %q",
   1114 			ctx.OtherModuleName(to), String(to.Properties.Sdk_version))
   1115 	}
   1116 
   1117 	// Also check that the two STL choices are compatible.
   1118 	fromStl := from.stl.Properties.SelectedStl
   1119 	toStl := to.stl.Properties.SelectedStl
   1120 	if fromStl == "" || toStl == "" {
   1121 		// Libraries that don't use the STL are unrestricted.
   1122 		return
   1123 	}
   1124 
   1125 	if fromStl == "ndk_system" || toStl == "ndk_system" {
   1126 		// We can be permissive with the system "STL" since it is only the C++
   1127 		// ABI layer, but in the future we should make sure that everyone is
   1128 		// using either libc++ or nothing.
   1129 		return
   1130 	}
   1131 
   1132 	if getNdkStlFamily(ctx, from) != getNdkStlFamily(ctx, to) {
   1133 		ctx.ModuleErrorf("uses %q and depends on %q which uses incompatible %q",
   1134 			from.stl.Properties.SelectedStl, ctx.OtherModuleName(to),
   1135 			to.stl.Properties.SelectedStl)
   1136 	}
   1137 }
   1138 
   1139 // Convert dependencies to paths.  Returns a PathDeps containing paths
   1140 func (c *Module) depsToPaths(ctx android.ModuleContext) PathDeps {
   1141 	var depPaths PathDeps
   1142 
   1143 	directStaticDeps := []*Module{}
   1144 	directSharedDeps := []*Module{}
   1145 
   1146 	ctx.VisitDirectDeps(func(dep android.Module) {
   1147 		depName := ctx.OtherModuleName(dep)
   1148 		depTag := ctx.OtherModuleDependencyTag(dep)
   1149 
   1150 		ccDep, _ := dep.(*Module)
   1151 		if ccDep == nil {
   1152 			// handling for a few module types that aren't cc Module but that are also supported
   1153 			switch depTag {
   1154 			case android.DefaultsDepTag, android.SourceDepTag:
   1155 				// Nothing to do
   1156 			case genSourceDepTag:
   1157 				if genRule, ok := dep.(genrule.SourceFileGenerator); ok {
   1158 					depPaths.GeneratedSources = append(depPaths.GeneratedSources,
   1159 						genRule.GeneratedSourceFiles()...)
   1160 				} else {
   1161 					ctx.ModuleErrorf("module %q is not a gensrcs or genrule", depName)
   1162 				}
   1163 				// Support exported headers from a generated_sources dependency
   1164 				fallthrough
   1165 			case genHeaderDepTag, genHeaderExportDepTag:
   1166 				if genRule, ok := dep.(genrule.SourceFileGenerator); ok {
   1167 					depPaths.GeneratedHeaders = append(depPaths.GeneratedHeaders,
   1168 						genRule.GeneratedDeps()...)
   1169 					flags := includeDirsToFlags(genRule.GeneratedHeaderDirs())
   1170 					depPaths.Flags = append(depPaths.Flags, flags)
   1171 					if depTag == genHeaderExportDepTag {
   1172 						depPaths.ReexportedFlags = append(depPaths.ReexportedFlags, flags)
   1173 						depPaths.ReexportedFlagsDeps = append(depPaths.ReexportedFlagsDeps,
   1174 							genRule.GeneratedDeps()...)
   1175 						// Add these re-exported flags to help header-abi-dumper to infer the abi exported by a library.
   1176 						c.sabi.Properties.ReexportedIncludeFlags = append(c.sabi.Properties.ReexportedIncludeFlags, flags)
   1177 
   1178 					}
   1179 				} else {
   1180 					ctx.ModuleErrorf("module %q is not a genrule", depName)
   1181 				}
   1182 			case linkerScriptDepTag:
   1183 				if genRule, ok := dep.(genrule.SourceFileGenerator); ok {
   1184 					files := genRule.GeneratedSourceFiles()
   1185 					if len(files) == 1 {
   1186 						depPaths.LinkerScript = android.OptionalPathForPath(files[0])
   1187 					} else if len(files) > 1 {
   1188 						ctx.ModuleErrorf("module %q can only generate a single file if used for a linker script", depName)
   1189 					}
   1190 				} else {
   1191 					ctx.ModuleErrorf("module %q is not a genrule", depName)
   1192 				}
   1193 			default:
   1194 				ctx.ModuleErrorf("depends on non-cc module %q", depName)
   1195 			}
   1196 			return
   1197 		}
   1198 
   1199 		if dep.Target().Os != ctx.Os() {
   1200 			ctx.ModuleErrorf("OS mismatch between %q and %q", ctx.ModuleName(), depName)
   1201 			return
   1202 		}
   1203 		if dep.Target().Arch.ArchType != ctx.Arch().ArchType {
   1204 			ctx.ModuleErrorf("Arch mismatch between %q and %q", ctx.ModuleName(), depName)
   1205 			return
   1206 		}
   1207 
   1208 		// re-exporting flags
   1209 		if depTag == reuseObjTag {
   1210 			if l, ok := ccDep.compiler.(libraryInterface); ok {
   1211 				c.staticVariant = ccDep
   1212 				objs, flags, deps := l.reuseObjs()
   1213 				depPaths.Objs = depPaths.Objs.Append(objs)
   1214 				depPaths.ReexportedFlags = append(depPaths.ReexportedFlags, flags...)
   1215 				depPaths.ReexportedFlagsDeps = append(depPaths.ReexportedFlagsDeps, deps...)
   1216 				return
   1217 			}
   1218 		}
   1219 		if t, ok := depTag.(dependencyTag); ok && t.library {
   1220 			if i, ok := ccDep.linker.(exportedFlagsProducer); ok {
   1221 				flags := i.exportedFlags()
   1222 				deps := i.exportedFlagsDeps()
   1223 				depPaths.Flags = append(depPaths.Flags, flags...)
   1224 				depPaths.GeneratedHeaders = append(depPaths.GeneratedHeaders, deps...)
   1225 
   1226 				if t.reexportFlags {
   1227 					depPaths.ReexportedFlags = append(depPaths.ReexportedFlags, flags...)
   1228 					depPaths.ReexportedFlagsDeps = append(depPaths.ReexportedFlagsDeps, deps...)
   1229 					// Add these re-exported flags to help header-abi-dumper to infer the abi exported by a library.
   1230 					// Re-exported shared library headers must be included as well since they can help us with type information
   1231 					// about template instantiations (instantiated from their headers).
   1232 					c.sabi.Properties.ReexportedIncludeFlags = append(c.sabi.Properties.ReexportedIncludeFlags, flags...)
   1233 				}
   1234 			}
   1235 
   1236 			checkLinkType(ctx, c, ccDep, t)
   1237 		}
   1238 
   1239 		var ptr *android.Paths
   1240 		var depPtr *android.Paths
   1241 
   1242 		linkFile := ccDep.outputFile
   1243 		depFile := android.OptionalPath{}
   1244 
   1245 		switch depTag {
   1246 		case ndkStubDepTag, sharedDepTag, sharedExportDepTag:
   1247 			ptr = &depPaths.SharedLibs
   1248 			depPtr = &depPaths.SharedLibsDeps
   1249 			depFile = ccDep.linker.(libraryInterface).toc()
   1250 			directSharedDeps = append(directSharedDeps, ccDep)
   1251 		case lateSharedDepTag, ndkLateStubDepTag:
   1252 			ptr = &depPaths.LateSharedLibs
   1253 			depPtr = &depPaths.LateSharedLibsDeps
   1254 			depFile = ccDep.linker.(libraryInterface).toc()
   1255 		case staticDepTag, staticExportDepTag:
   1256 			ptr = nil
   1257 			directStaticDeps = append(directStaticDeps, ccDep)
   1258 		case lateStaticDepTag:
   1259 			ptr = &depPaths.LateStaticLibs
   1260 		case wholeStaticDepTag:
   1261 			ptr = &depPaths.WholeStaticLibs
   1262 			staticLib, ok := ccDep.linker.(libraryInterface)
   1263 			if !ok || !staticLib.static() {
   1264 				ctx.ModuleErrorf("module %q not a static library", depName)
   1265 				return
   1266 			}
   1267 
   1268 			if missingDeps := staticLib.getWholeStaticMissingDeps(); missingDeps != nil {
   1269 				postfix := " (required by " + ctx.OtherModuleName(dep) + ")"
   1270 				for i := range missingDeps {
   1271 					missingDeps[i] += postfix
   1272 				}
   1273 				ctx.AddMissingDependencies(missingDeps)
   1274 			}
   1275 			depPaths.WholeStaticLibObjs = depPaths.WholeStaticLibObjs.Append(staticLib.objs())
   1276 		case headerDepTag:
   1277 			// Nothing
   1278 		case objDepTag:
   1279 			depPaths.Objs.objFiles = append(depPaths.Objs.objFiles, linkFile.Path())
   1280 		case crtBeginDepTag:
   1281 			depPaths.CrtBegin = linkFile
   1282 		case crtEndDepTag:
   1283 			depPaths.CrtEnd = linkFile
   1284 		}
   1285 
   1286 		switch depTag {
   1287 		case staticDepTag, staticExportDepTag, lateStaticDepTag:
   1288 			staticLib, ok := ccDep.linker.(libraryInterface)
   1289 			if !ok || !staticLib.static() {
   1290 				ctx.ModuleErrorf("module %q not a static library", depName)
   1291 				return
   1292 			}
   1293 
   1294 			// When combining coverage files for shared libraries and executables, coverage files
   1295 			// in static libraries act as if they were whole static libraries. The same goes for
   1296 			// source based Abi dump files.
   1297 			depPaths.StaticLibObjs.coverageFiles = append(depPaths.StaticLibObjs.coverageFiles,
   1298 				staticLib.objs().coverageFiles...)
   1299 			depPaths.StaticLibObjs.sAbiDumpFiles = append(depPaths.StaticLibObjs.sAbiDumpFiles,
   1300 				staticLib.objs().sAbiDumpFiles...)
   1301 
   1302 		}
   1303 
   1304 		if ptr != nil {
   1305 			if !linkFile.Valid() {
   1306 				ctx.ModuleErrorf("module %q missing output file", depName)
   1307 				return
   1308 			}
   1309 			*ptr = append(*ptr, linkFile.Path())
   1310 		}
   1311 
   1312 		if depPtr != nil {
   1313 			dep := depFile
   1314 			if !dep.Valid() {
   1315 				dep = linkFile
   1316 			}
   1317 			*depPtr = append(*depPtr, dep.Path())
   1318 		}
   1319 
   1320 		// Export the shared libs to Make.
   1321 		switch depTag {
   1322 		case sharedDepTag, sharedExportDepTag, lateSharedDepTag:
   1323 			libName := strings.TrimSuffix(depName, llndkLibrarySuffix)
   1324 			libName = strings.TrimSuffix(libName, vendorPublicLibrarySuffix)
   1325 			libName = strings.TrimPrefix(libName, "prebuilt_")
   1326 			isLLndk := inList(libName, llndkLibraries)
   1327 			isVendorPublicLib := inList(libName, vendorPublicLibraries)
   1328 			var makeLibName string
   1329 			bothVendorAndCoreVariantsExist := ccDep.hasVendorVariant() || isLLndk
   1330 			if c.useVndk() && bothVendorAndCoreVariantsExist {
   1331 				// The vendor module in Make will have been renamed to not conflict with the core
   1332 				// module, so update the dependency name here accordingly.
   1333 				makeLibName = libName + vendorSuffix
   1334 			} else if (ctx.Platform() || ctx.ProductSpecific()) && isVendorPublicLib {
   1335 				makeLibName = libName + vendorPublicLibrarySuffix
   1336 			} else {
   1337 				makeLibName = libName
   1338 			}
   1339 			// Note: the order of libs in this list is not important because
   1340 			// they merely serve as Make dependencies and do not affect this lib itself.
   1341 			c.Properties.AndroidMkSharedLibs = append(c.Properties.AndroidMkSharedLibs, makeLibName)
   1342 		}
   1343 	})
   1344 
   1345 	// use the ordered dependencies as this module's dependencies
   1346 	depPaths.StaticLibs = append(depPaths.StaticLibs, orderStaticModuleDeps(c, directStaticDeps, directSharedDeps)...)
   1347 
   1348 	// Dedup exported flags from dependencies
   1349 	depPaths.Flags = android.FirstUniqueStrings(depPaths.Flags)
   1350 	depPaths.GeneratedHeaders = android.FirstUniquePaths(depPaths.GeneratedHeaders)
   1351 	depPaths.ReexportedFlags = android.FirstUniqueStrings(depPaths.ReexportedFlags)
   1352 	depPaths.ReexportedFlagsDeps = android.FirstUniquePaths(depPaths.ReexportedFlagsDeps)
   1353 
   1354 	if c.sabi != nil {
   1355 		c.sabi.Properties.ReexportedIncludeFlags = android.FirstUniqueStrings(c.sabi.Properties.ReexportedIncludeFlags)
   1356 	}
   1357 
   1358 	return depPaths
   1359 }
   1360 
   1361 func (c *Module) InstallInData() bool {
   1362 	if c.installer == nil {
   1363 		return false
   1364 	}
   1365 	return c.installer.inData()
   1366 }
   1367 
   1368 func (c *Module) InstallInSanitizerDir() bool {
   1369 	if c.installer == nil {
   1370 		return false
   1371 	}
   1372 	if c.sanitize != nil && c.sanitize.inSanitizerDir() {
   1373 		return true
   1374 	}
   1375 	return c.installer.inSanitizerDir()
   1376 }
   1377 
   1378 func (c *Module) HostToolPath() android.OptionalPath {
   1379 	if c.installer == nil {
   1380 		return android.OptionalPath{}
   1381 	}
   1382 	return c.installer.hostToolPath()
   1383 }
   1384 
   1385 func (c *Module) IntermPathForModuleOut() android.OptionalPath {
   1386 	return c.outputFile
   1387 }
   1388 
   1389 func (c *Module) Srcs() android.Paths {
   1390 	if c.outputFile.Valid() {
   1391 		return android.Paths{c.outputFile.Path()}
   1392 	}
   1393 	return android.Paths{}
   1394 }
   1395 
   1396 func (c *Module) static() bool {
   1397 	if static, ok := c.linker.(interface {
   1398 		static() bool
   1399 	}); ok {
   1400 		return static.static()
   1401 	}
   1402 	return false
   1403 }
   1404 
   1405 //
   1406 // Defaults
   1407 //
   1408 type Defaults struct {
   1409 	android.ModuleBase
   1410 	android.DefaultsModuleBase
   1411 }
   1412 
   1413 func (*Defaults) GenerateAndroidBuildActions(ctx android.ModuleContext) {
   1414 }
   1415 
   1416 func (d *Defaults) DepsMutator(ctx android.BottomUpMutatorContext) {
   1417 }
   1418 
   1419 func defaultsFactory() android.Module {
   1420 	return DefaultsFactory()
   1421 }
   1422 
   1423 func DefaultsFactory(props ...interface{}) android.Module {
   1424 	module := &Defaults{}
   1425 
   1426 	module.AddProperties(props...)
   1427 	module.AddProperties(
   1428 		&BaseProperties{},
   1429 		&VendorProperties{},
   1430 		&BaseCompilerProperties{},
   1431 		&BaseLinkerProperties{},
   1432 		&LibraryProperties{},
   1433 		&FlagExporterProperties{},
   1434 		&BinaryLinkerProperties{},
   1435 		&TestProperties{},
   1436 		&TestBinaryProperties{},
   1437 		&UnusedProperties{},
   1438 		&StlProperties{},
   1439 		&SanitizeProperties{},
   1440 		&StripProperties{},
   1441 		&InstallerProperties{},
   1442 		&TidyProperties{},
   1443 		&CoverageProperties{},
   1444 		&SAbiProperties{},
   1445 		&VndkProperties{},
   1446 		&LTOProperties{},
   1447 		&PgoProperties{},
   1448 		&android.ProtoProperties{},
   1449 	)
   1450 
   1451 	android.InitDefaultsModule(module)
   1452 
   1453 	return module
   1454 }
   1455 
   1456 const (
   1457 	// coreMode is the variant used for framework-private libraries, or
   1458 	// SDK libraries. (which framework-private libraries can use)
   1459 	coreMode = "core"
   1460 
   1461 	// vendorMode is the variant used for /vendor code that compiles
   1462 	// against the VNDK.
   1463 	vendorMode = "vendor"
   1464 )
   1465 
   1466 func squashVendorSrcs(m *Module) {
   1467 	if lib, ok := m.compiler.(*libraryDecorator); ok {
   1468 		lib.baseCompiler.Properties.Srcs = append(lib.baseCompiler.Properties.Srcs,
   1469 			lib.baseCompiler.Properties.Target.Vendor.Srcs...)
   1470 
   1471 		lib.baseCompiler.Properties.Exclude_srcs = append(lib.baseCompiler.Properties.Exclude_srcs,
   1472 			lib.baseCompiler.Properties.Target.Vendor.Exclude_srcs...)
   1473 	}
   1474 }
   1475 
   1476 func vendorMutator(mctx android.BottomUpMutatorContext) {
   1477 	if mctx.Os() != android.Android {
   1478 		return
   1479 	}
   1480 
   1481 	if genrule, ok := mctx.Module().(*genrule.Module); ok {
   1482 		if props, ok := genrule.Extra.(*VendorProperties); ok {
   1483 			if mctx.DeviceConfig().VndkVersion() == "" {
   1484 				mctx.CreateVariations(coreMode)
   1485 			} else if Bool(props.Vendor_available) {
   1486 				mctx.CreateVariations(coreMode, vendorMode)
   1487 			} else if mctx.SocSpecific() || mctx.DeviceSpecific() {
   1488 				mctx.CreateVariations(vendorMode)
   1489 			} else {
   1490 				mctx.CreateVariations(coreMode)
   1491 			}
   1492 		}
   1493 	}
   1494 
   1495 	m, ok := mctx.Module().(*Module)
   1496 	if !ok {
   1497 		return
   1498 	}
   1499 
   1500 	// Sanity check
   1501 	vendorSpecific := mctx.SocSpecific() || mctx.DeviceSpecific()
   1502 
   1503 	if m.VendorProperties.Vendor_available != nil && vendorSpecific {
   1504 		mctx.PropertyErrorf("vendor_available",
   1505 			"doesn't make sense at the same time as `vendor: true`, `proprietary: true`, or `device_specific:true`")
   1506 		return
   1507 	}
   1508 
   1509 	if vndkdep := m.vndkdep; vndkdep != nil {
   1510 		if vndkdep.isVndk() {
   1511 			if vendorSpecific {
   1512 				if !vndkdep.isVndkExt() {
   1513 					mctx.PropertyErrorf("vndk",
   1514 						"must set `extends: \"...\"` to vndk extension")
   1515 					return
   1516 				}
   1517 			} else {
   1518 				if vndkdep.isVndkExt() {
   1519 					mctx.PropertyErrorf("vndk",
   1520 						"must set `vendor: true` to set `extends: %q`",
   1521 						m.getVndkExtendsModuleName())
   1522 					return
   1523 				}
   1524 				if m.VendorProperties.Vendor_available == nil {
   1525 					mctx.PropertyErrorf("vndk",
   1526 						"vendor_available must be set to either true or false when `vndk: {enabled: true}`")
   1527 					return
   1528 				}
   1529 			}
   1530 		} else {
   1531 			if vndkdep.isVndkSp() {
   1532 				mctx.PropertyErrorf("vndk",
   1533 					"must set `enabled: true` to set `support_system_process: true`")
   1534 				return
   1535 			}
   1536 			if vndkdep.isVndkExt() {
   1537 				mctx.PropertyErrorf("vndk",
   1538 					"must set `enabled: true` to set `extends: %q`",
   1539 					m.getVndkExtendsModuleName())
   1540 				return
   1541 			}
   1542 		}
   1543 	}
   1544 
   1545 	if mctx.DeviceConfig().VndkVersion() == "" {
   1546 		// If the device isn't compiling against the VNDK, we always
   1547 		// use the core mode.
   1548 		mctx.CreateVariations(coreMode)
   1549 	} else if _, ok := m.linker.(*llndkStubDecorator); ok {
   1550 		// LL-NDK stubs only exist in the vendor variant, since the
   1551 		// real libraries will be used in the core variant.
   1552 		mctx.CreateVariations(vendorMode)
   1553 	} else if _, ok := m.linker.(*llndkHeadersDecorator); ok {
   1554 		// ... and LL-NDK headers as well
   1555 		mod := mctx.CreateVariations(vendorMode)
   1556 		vendor := mod[0].(*Module)
   1557 		vendor.Properties.UseVndk = true
   1558 	} else if _, ok := m.linker.(*vndkPrebuiltLibraryDecorator); ok {
   1559 		// Make vendor variants only for the versions in BOARD_VNDK_VERSION and
   1560 		// PRODUCT_EXTRA_VNDK_VERSIONS.
   1561 		mod := mctx.CreateVariations(vendorMode)
   1562 		vendor := mod[0].(*Module)
   1563 		vendor.Properties.UseVndk = true
   1564 	} else if m.hasVendorVariant() && !vendorSpecific {
   1565 		// This will be available in both /system and /vendor
   1566 		// or a /system directory that is available to vendor.
   1567 		mod := mctx.CreateVariations(coreMode, vendorMode)
   1568 		vendor := mod[1].(*Module)
   1569 		vendor.Properties.UseVndk = true
   1570 		squashVendorSrcs(vendor)
   1571 	} else if vendorSpecific && String(m.Properties.Sdk_version) == "" {
   1572 		// This will be available in /vendor (or /odm) only
   1573 		mod := mctx.CreateVariations(vendorMode)
   1574 		vendor := mod[0].(*Module)
   1575 		vendor.Properties.UseVndk = true
   1576 		squashVendorSrcs(vendor)
   1577 	} else {
   1578 		// This is either in /system (or similar: /data), or is a
   1579 		// modules built with the NDK. Modules built with the NDK
   1580 		// will be restricted using the existing link type checks.
   1581 		mctx.CreateVariations(coreMode)
   1582 	}
   1583 }
   1584 
   1585 func getCurrentNdkPrebuiltVersion(ctx DepsContext) string {
   1586 	if ctx.Config().PlatformSdkVersionInt() > config.NdkMaxPrebuiltVersionInt {
   1587 		return strconv.Itoa(config.NdkMaxPrebuiltVersionInt)
   1588 	}
   1589 	return ctx.Config().PlatformSdkVersion()
   1590 }
   1591 
   1592 var Bool = proptools.Bool
   1593 var BoolPtr = proptools.BoolPtr
   1594 var String = proptools.String
   1595 var StringPtr = proptools.StringPtr
   1596