blob: 9d746426f587f364426e4a264f53ebdc6172f4e9 [file] [log] [blame]
Colin Cross3f40fa42015-01-30 17:27:36 -08001// 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
Colin Cross635c3b02016-05-18 15:37:25 -070015package android
Colin Cross3f40fa42015-01-30 17:27:36 -080016
17import (
Colin Cross69452e12023-11-15 11:20:53 -080018 "android/soong/bazel"
19 "android/soong/ui/metrics/bp2build_metrics_proto"
Inseob Kim81b00a82023-05-15 18:06:31 +090020 "crypto/md5"
21 "encoding/hex"
22 "encoding/json"
Colin Cross6ff51382015-12-17 16:39:19 -080023 "fmt"
Bob Badour4101c712022-02-09 11:54:35 -080024 "net/url"
Colin Cross3f40fa42015-01-30 17:27:36 -080025 "path/filepath"
Liz Kammer9525e712022-01-05 13:46:24 -050026 "reflect"
Bob Badour4101c712022-02-09 11:54:35 -080027 "sort"
Colin Cross6ff51382015-12-17 16:39:19 -080028 "strings"
Tahsin Loqman77dc7d02022-12-19 16:27:25 +000029
Colin Crossf6566ed2015-03-24 11:13:38 -070030 "github.com/google/blueprint"
Colin Crossfe4bc362018-09-12 10:02:13 -070031 "github.com/google/blueprint/proptools"
Colin Cross3f40fa42015-01-30 17:27:36 -080032)
33
34var (
35 DeviceSharedLibrary = "shared_library"
36 DeviceStaticLibrary = "static_library"
Colin Cross3f40fa42015-01-30 17:27:36 -080037)
38
Colin Cross635c3b02016-05-18 15:37:25 -070039type Module interface {
Colin Cross3f40fa42015-01-30 17:27:36 -080040 blueprint.Module
41
Jeff Gastonaf3cc2d2017-09-27 17:01:44 -070042 // GenerateAndroidBuildActions is analogous to Blueprints' GenerateBuildActions,
43 // but GenerateAndroidBuildActions also has access to Android-specific information.
44 // For more information, see Module.GenerateBuildActions within Blueprint's module_ctx.go
Colin Cross635c3b02016-05-18 15:37:25 -070045 GenerateAndroidBuildActions(ModuleContext)
Jeff Gastonaf3cc2d2017-09-27 17:01:44 -070046
Paul Duffin44f1d842020-06-26 20:17:02 +010047 // Add dependencies to the components of a module, i.e. modules that are created
48 // by the module and which are considered to be part of the creating module.
49 //
50 // This is called before prebuilts are renamed so as to allow a dependency to be
51 // added directly to a prebuilt child module instead of depending on a source module
52 // and relying on prebuilt processing to switch to the prebuilt module if preferred.
53 //
54 // A dependency on a prebuilt must include the "prebuilt_" prefix.
55 ComponentDepsMutator(ctx BottomUpMutatorContext)
56
Colin Cross1e676be2016-10-12 14:38:15 -070057 DepsMutator(BottomUpMutatorContext)
Colin Cross3f40fa42015-01-30 17:27:36 -080058
Colin Cross635c3b02016-05-18 15:37:25 -070059 base() *ModuleBase
Inseob Kimeec88e12020-01-22 11:11:29 +090060 Disable()
Dan Willemsen0effe062015-11-30 16:06:01 -080061 Enabled() bool
Colin Crossa1ad8d12016-06-01 17:09:44 -070062 Target() Target
Paul Duffinc04fb9e2021-03-01 12:25:10 +000063 MultiTargets() []Target
Paul Duffinb42fa672021-09-09 16:37:49 +010064
65 // ImageVariation returns the image variation of this module.
66 //
67 // The returned structure has its Mutator field set to "image" and its Variation field set to the
68 // image variation, e.g. recovery, ramdisk, etc.. The Variation field is "" for host modules and
69 // device modules that have no image variation.
70 ImageVariation() blueprint.Variation
71
Anton Hansson1ee62c02020-06-30 11:51:53 +010072 Owner() string
Dan Willemsen782a2d12015-12-21 14:55:28 -080073 InstallInData() bool
Jaewoong Jung0949f312019-09-11 10:25:18 -070074 InstallInTestcases() bool
Vishwath Mohan1dd88392017-03-29 22:00:18 -070075 InstallInSanitizerDir() bool
Yifan Hong1b3348d2020-01-21 15:53:22 -080076 InstallInRamdisk() bool
Yifan Hong60e0cfb2020-10-21 15:17:56 -070077 InstallInVendorRamdisk() bool
Inseob Kim08758f02021-04-08 21:13:22 +090078 InstallInDebugRamdisk() bool
Jiyong Parkf9332f12018-02-01 00:54:12 +090079 InstallInRecovery() bool
Colin Cross90ba5f42019-10-02 11:10:58 -070080 InstallInRoot() bool
Kiyoung Kimae11c232021-07-19 11:38:04 +090081 InstallInVendor() bool
Jiyong Park87788b52020-09-01 12:37:45 +090082 InstallForceOS() (*OsType, *ArchType)
Jiyong Parkce243632023-02-17 18:22:25 +090083 PartitionTag(DeviceConfig) string
Colin Crossa9c8c9f2020-12-16 10:20:23 -080084 HideFromMake()
85 IsHideFromMake() bool
Martin Stjernholm9e7f45e2020-12-23 03:50:30 +000086 IsSkipInstall() bool
Iván Budnik295da162023-03-10 16:11:26 +000087 MakeUninstallable()
Liz Kammer5ca3a622020-08-05 15:40:41 -070088 ReplacedByPrebuilt()
89 IsReplacedByPrebuilt() bool
Jiyong Park374510b2018-03-19 18:23:01 +090090 ExportedToMake() bool
Inseob Kim8471cda2019-11-15 09:59:12 +090091 InitRc() Paths
92 VintfFragments() Paths
Justin Yun1871f902023-04-07 20:13:19 +090093 EffectiveLicenseKinds() []string
Justin Yun885a7de2021-06-29 20:34:53 +090094 EffectiveLicenseFiles() Paths
Colin Cross36242852017-06-23 15:06:31 -070095
96 AddProperties(props ...interface{})
97 GetProperties() []interface{}
Colin Crosscec81712017-07-13 14:43:27 -070098
Chris Parsons0c4de1f2023-09-21 20:36:35 +000099 // If this module should not have bazel BUILD definitions generated by bp2build,
100 // GetUnconvertedReason returns a reason this is the case.
Chris Parsons39a16972023-06-08 14:28:51 +0000101 GetUnconvertedReason() *UnconvertedReason
102
Liz Kammer2ada09a2021-08-11 00:17:36 -0400103 // Bp2buildTargets returns the target(s) generated for Bazel via bp2build for this module
104 Bp2buildTargets() []bp2buildInfo
Liz Kammer6eff3232021-08-26 08:37:59 -0400105 GetUnconvertedBp2buildDeps() []string
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500106 GetMissingBp2buildDeps() []string
Cole Faust11edf552023-10-13 11:32:14 -0700107 GetPartitionForBp2build() string
Liz Kammer2ada09a2021-08-11 00:17:36 -0400108
Colin Crossae887032017-10-23 17:16:14 -0700109 BuildParamsForTests() []BuildParams
Colin Cross4c83e5c2019-02-25 14:54:28 -0800110 RuleParamsForTests() map[blueprint.Rule]blueprint.RuleParams
Jaewoong Jung38e4fb22018-12-12 09:01:34 -0800111 VariablesForTests() map[string]string
Paul Duffine2453c72019-05-31 14:00:04 +0100112
Colin Cross9a362232019-07-01 15:32:45 -0700113 // String returns a string that includes the module name and variants for printing during debugging.
114 String() string
115
Paul Duffine2453c72019-05-31 14:00:04 +0100116 // Get the qualified module id for this module.
117 qualifiedModuleId(ctx BaseModuleContext) qualifiedModuleName
118
119 // Get information about the properties that can contain visibility rules.
120 visibilityProperties() []visibilityProperty
Paul Duffin63c6e182019-07-24 14:24:38 +0100121
Jiyong Park6a8cf5f2019-12-30 16:31:09 +0900122 RequiredModuleNames() []string
123 HostRequiredModuleNames() []string
124 TargetRequiredModuleNames() []string
Colin Cross897266e2020-02-13 13:22:08 -0800125
Jiyong Park4dc2a1a2020-09-28 17:46:22 +0900126 FilesToInstall() InstallPaths
Jiyong Park073ea552020-11-09 14:08:34 +0900127 PackagingSpecs() []PackagingSpec
Colin Crossffe6b9d2020-12-01 15:40:06 -0800128
129 // TransitivePackagingSpecs returns the PackagingSpecs for this module and any transitive
130 // dependencies with dependency tags for which IsInstallDepNeeded() returns true.
131 TransitivePackagingSpecs() []PackagingSpec
Paul Duffine2453c72019-05-31 14:00:04 +0100132}
133
134// Qualified id for a module
135type qualifiedModuleName struct {
136 // The package (i.e. directory) in which the module is defined, without trailing /
137 pkg string
138
139 // The name of the module, empty string if package.
140 name string
141}
142
143func (q qualifiedModuleName) String() string {
144 if q.name == "" {
145 return "//" + q.pkg
146 }
147 return "//" + q.pkg + ":" + q.name
148}
149
Paul Duffine484f472019-06-20 16:38:08 +0100150func (q qualifiedModuleName) isRootPackage() bool {
151 return q.pkg == "" && q.name == ""
152}
153
Paul Duffine2453c72019-05-31 14:00:04 +0100154// Get the id for the package containing this module.
155func (q qualifiedModuleName) getContainingPackageId() qualifiedModuleName {
156 pkg := q.pkg
157 if q.name == "" {
Paul Duffine484f472019-06-20 16:38:08 +0100158 if pkg == "" {
159 panic(fmt.Errorf("Cannot get containing package id of root package"))
160 }
161
162 index := strings.LastIndex(pkg, "/")
163 if index == -1 {
164 pkg = ""
165 } else {
166 pkg = pkg[:index]
167 }
Paul Duffine2453c72019-05-31 14:00:04 +0100168 }
169 return newPackageId(pkg)
170}
171
172func newPackageId(pkg string) qualifiedModuleName {
173 // A qualified id for a package module has no name.
174 return qualifiedModuleName{pkg: pkg, name: ""}
Colin Cross3f40fa42015-01-30 17:27:36 -0800175}
176
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000177type Dist struct {
178 // Copy the output of this module to the $DIST_DIR when `dist` is specified on the
179 // command line and any of these targets are also on the command line, or otherwise
180 // built
181 Targets []string `android:"arch_variant"`
182
183 // The name of the output artifact. This defaults to the basename of the output of
184 // the module.
185 Dest *string `android:"arch_variant"`
186
187 // The directory within the dist directory to store the artifact. Defaults to the
188 // top level directory ("").
189 Dir *string `android:"arch_variant"`
190
191 // A suffix to add to the artifact file name (before any extension).
192 Suffix *string `android:"arch_variant"`
193
Trevor Radcliffe90727f42022-03-21 19:34:02 +0000194 // If true, then the artifact file will be appended with _<product name>. For
195 // example, if the product is coral and the module is an android_app module
196 // of name foo, then the artifact would be foo_coral.apk. If false, there is
197 // no change to the artifact file name.
198 Append_artifact_with_product *bool `android:"arch_variant"`
199
Paul Duffin74f05592020-11-25 16:37:46 +0000200 // A string tag to select the OutputFiles associated with the tag.
201 //
202 // If no tag is specified then it will select the default dist paths provided
203 // by the module type. If a tag of "" is specified then it will return the
204 // default output files provided by the modules, i.e. the result of calling
205 // OutputFiles("").
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000206 Tag *string `android:"arch_variant"`
207}
208
Bob Badour4101c712022-02-09 11:54:35 -0800209// NamedPath associates a path with a name. e.g. a license text path with a package name
210type NamedPath struct {
211 Path Path
212 Name string
213}
214
215// String returns an escaped string representing the `NamedPath`.
216func (p NamedPath) String() string {
217 if len(p.Name) > 0 {
218 return p.Path.String() + ":" + url.QueryEscape(p.Name)
219 }
220 return p.Path.String()
221}
222
223// NamedPaths describes a list of paths each associated with a name.
224type NamedPaths []NamedPath
225
226// Strings returns a list of escaped strings representing each `NamedPath` in the list.
227func (l NamedPaths) Strings() []string {
228 result := make([]string, 0, len(l))
229 for _, p := range l {
230 result = append(result, p.String())
231 }
232 return result
233}
234
235// SortedUniqueNamedPaths modifies `l` in place to return the sorted unique subset.
236func SortedUniqueNamedPaths(l NamedPaths) NamedPaths {
237 if len(l) == 0 {
238 return l
239 }
240 sort.Slice(l, func(i, j int) bool {
241 return l[i].String() < l[j].String()
242 })
243 k := 0
244 for i := 1; i < len(l); i++ {
245 if l[i].String() == l[k].String() {
246 continue
247 }
248 k++
249 if k < i {
250 l[k] = l[i]
251 }
252 }
253 return l[:k+1]
254}
255
Inseob Kim81b00a82023-05-15 18:06:31 +0900256// soongConfigTrace holds all references to VendorVars. Uses []string for blueprint:"mutated"
257type soongConfigTrace struct {
258 Bools []string `json:",omitempty"`
259 Strings []string `json:",omitempty"`
260 IsSets []string `json:",omitempty"`
261}
262
263func (c *soongConfigTrace) isEmpty() bool {
264 return len(c.Bools) == 0 && len(c.Strings) == 0 && len(c.IsSets) == 0
265}
266
267// Returns hash of serialized trace records (empty string if there's no trace recorded)
268func (c *soongConfigTrace) hash() string {
269 // Use MD5 for speed. We don't care collision or preimage attack
270 if c.isEmpty() {
271 return ""
272 }
273 j, err := json.Marshal(c)
274 if err != nil {
275 panic(fmt.Errorf("json marshal of %#v failed: %#v", *c, err))
276 }
277 hash := md5.Sum(j)
278 return hex.EncodeToString(hash[:])
279}
280
Colin Crossfc754582016-05-17 16:34:16 -0700281type nameProperties struct {
282 // The name of the module. Must be unique across all modules.
Nan Zhang0007d812017-11-07 10:57:05 -0800283 Name *string
Colin Crossfc754582016-05-17 16:34:16 -0700284}
285
Colin Cross08d6f8f2020-11-19 02:33:19 +0000286type commonProperties struct {
Dan Willemsen0effe062015-11-30 16:06:01 -0800287 // emit build rules for this module
Paul Duffin54d9bb72020-02-12 10:20:56 +0000288 //
289 // Disabling a module should only be done for those modules that cannot be built
290 // in the current environment. Modules that can build in the current environment
291 // but are not usually required (e.g. superceded by a prebuilt) should not be
292 // disabled as that will prevent them from being built by the checkbuild target
293 // and so prevent early detection of changes that have broken those modules.
Dan Willemsen0effe062015-11-30 16:06:01 -0800294 Enabled *bool `android:"arch_variant"`
Colin Cross3f40fa42015-01-30 17:27:36 -0800295
Paul Duffin2e61fa62019-03-28 14:10:57 +0000296 // Controls the visibility of this module to other modules. Allowable values are one or more of
297 // these formats:
298 //
299 // ["//visibility:public"]: Anyone can use this module.
300 // ["//visibility:private"]: Only rules in the module's package (not its subpackages) can use
301 // this module.
Paul Duffin51084ff2020-05-05 19:19:22 +0100302 // ["//visibility:override"]: Discards any rules inherited from defaults or a creating module.
303 // Can only be used at the beginning of a list of visibility rules.
Paul Duffin2e61fa62019-03-28 14:10:57 +0000304 // ["//some/package:__pkg__", "//other/package:__pkg__"]: Only modules in some/package and
305 // other/package (defined in some/package/*.bp and other/package/*.bp) have access to
306 // this module. Note that sub-packages do not have access to the rule; for example,
307 // //some/package/foo:bar or //other/package/testing:bla wouldn't have access. __pkg__
308 // is a special module and must be used verbatim. It represents all of the modules in the
309 // package.
310 // ["//project:__subpackages__", "//other:__subpackages__"]: Only modules in packages project
311 // or other or in one of their sub-packages have access to this module. For example,
312 // //project:rule, //project/library:lib or //other/testing/internal:munge are allowed
313 // to depend on this rule (but not //independent:evil)
314 // ["//project"]: This is shorthand for ["//project:__pkg__"]
315 // [":__subpackages__"]: This is shorthand for ["//project:__subpackages__"] where
316 // //project is the module's package. e.g. using [":__subpackages__"] in
317 // packages/apps/Settings/Android.bp is equivalent to
318 // //packages/apps/Settings:__subpackages__.
319 // ["//visibility:legacy_public"]: The default visibility, behaves as //visibility:public
320 // for now. It is an error if it is used in a module.
Paul Duffine2453c72019-05-31 14:00:04 +0100321 //
322 // If a module does not specify the `visibility` property then it uses the
323 // `default_visibility` property of the `package` module in the module's package.
324 //
325 // If the `default_visibility` property is not set for the module's package then
Paul Duffine484f472019-06-20 16:38:08 +0100326 // it will use the `default_visibility` of its closest ancestor package for which
327 // a `default_visibility` property is specified.
328 //
329 // If no `default_visibility` property can be found then the module uses the
330 // global default of `//visibility:legacy_public`.
Paul Duffine2453c72019-05-31 14:00:04 +0100331 //
Paul Duffin95d53b52019-07-24 13:45:05 +0100332 // The `visibility` property has no effect on a defaults module although it does
333 // apply to any non-defaults module that uses it. To set the visibility of a
334 // defaults module, use the `defaults_visibility` property on the defaults module;
335 // not to be confused with the `default_visibility` property on the package module.
336 //
Paul Duffin2e61fa62019-03-28 14:10:57 +0000337 // See https://android.googlesource.com/platform/build/soong/+/master/README.md#visibility for
338 // more details.
339 Visibility []string
340
Bob Badour37af0462021-01-07 03:34:31 +0000341 // Describes the licenses applicable to this module. Must reference license modules.
342 Licenses []string
343
344 // Flattened from direct license dependencies. Equal to Licenses unless particular module adds more.
345 Effective_licenses []string `blueprint:"mutated"`
346 // Override of module name when reporting licenses
347 Effective_package_name *string `blueprint:"mutated"`
348 // Notice files
Bob Badour4101c712022-02-09 11:54:35 -0800349 Effective_license_text NamedPaths `blueprint:"mutated"`
Bob Badour37af0462021-01-07 03:34:31 +0000350 // License names
351 Effective_license_kinds []string `blueprint:"mutated"`
352 // License conditions
353 Effective_license_conditions []string `blueprint:"mutated"`
354
Colin Cross7d5136f2015-05-11 13:39:40 -0700355 // control whether this module compiles for 32-bit, 64-bit, or both. Possible values
Colin Cross3f40fa42015-01-30 17:27:36 -0800356 // are "32" (compile for 32-bit only), "64" (compile for 64-bit only), "both" (compile for both
357 // architectures), or "first" (compile for 64-bit on a 64-bit platform, and 32-bit on a 32-bit
Roland Levillain24bb2e62020-09-22 11:18:38 +0000358 // platform).
Colin Cross7d716ba2017-11-01 10:38:29 -0700359 Compile_multilib *string `android:"arch_variant"`
Colin Cross69617d32016-09-06 10:39:07 -0700360
361 Target struct {
362 Host struct {
Colin Cross7d716ba2017-11-01 10:38:29 -0700363 Compile_multilib *string
Colin Cross69617d32016-09-06 10:39:07 -0700364 }
365 Android struct {
Colin Cross7d716ba2017-11-01 10:38:29 -0700366 Compile_multilib *string
Colin Cross69617d32016-09-06 10:39:07 -0700367 }
368 }
369
Paul Duffinca7f0ef2020-02-25 15:50:49 +0000370 // If set to true then the archMutator will create variants for each arch specific target
371 // (e.g. 32/64) that the module is required to produce. If set to false then it will only
372 // create a variant for the architecture and will list the additional arch specific targets
373 // that the variant needs to produce in the CompileMultiTargets property.
Colin Crossee0bc3b2018-10-02 22:01:37 -0700374 UseTargetVariants bool `blueprint:"mutated"`
375 Default_multilib string `blueprint:"mutated"`
Colin Cross3f40fa42015-01-30 17:27:36 -0800376
Dan Willemsen782a2d12015-12-21 14:55:28 -0800377 // whether this is a proprietary vendor module, and should be installed into /vendor
Colin Cross7d716ba2017-11-01 10:38:29 -0700378 Proprietary *bool
Dan Willemsen782a2d12015-12-21 14:55:28 -0800379
Colin Cross55708f32017-03-20 13:23:34 -0700380 // vendor who owns this module
Dan Willemsenefac4a82017-07-18 19:42:09 -0700381 Owner *string
Colin Cross55708f32017-03-20 13:23:34 -0700382
Jiyong Park2db76922017-11-08 16:03:48 +0900383 // whether this module is specific to an SoC (System-On-a-Chip). When set to true,
384 // it is installed into /vendor (or /system/vendor if vendor partition does not exist).
385 // Use `soc_specific` instead for better meaning.
Colin Cross7d716ba2017-11-01 10:38:29 -0700386 Vendor *bool
Dan Willemsenaa118f92017-04-06 12:49:58 -0700387
Jiyong Park2db76922017-11-08 16:03:48 +0900388 // whether this module is specific to an SoC (System-On-a-Chip). When set to true,
389 // it is installed into /vendor (or /system/vendor if vendor partition does not exist).
390 Soc_specific *bool
391
392 // whether this module is specific to a device, not only for SoC, but also for off-chip
393 // peripherals. When set to true, it is installed into /odm (or /vendor/odm if odm partition
394 // does not exist, or /system/vendor/odm if both odm and vendor partitions do not exist).
395 // This implies `soc_specific:true`.
396 Device_specific *bool
397
398 // whether this module is specific to a software configuration of a product (e.g. country,
Jaekyun Seok5cfbfbb2018-01-10 19:00:15 +0900399 // network operator, etc). When set to true, it is installed into /product (or
400 // /system/product if product partition does not exist).
Jiyong Park2db76922017-11-08 16:03:48 +0900401 Product_specific *bool
402
Justin Yund5f6c822019-06-25 16:47:17 +0900403 // whether this module extends system. When set to true, it is installed into /system_ext
404 // (or /system/system_ext if system_ext partition does not exist).
405 System_ext_specific *bool
406
Jiyong Parkf9332f12018-02-01 00:54:12 +0900407 // Whether this module is installed to recovery partition
408 Recovery *bool
409
Yifan Hong1b3348d2020-01-21 15:53:22 -0800410 // Whether this module is installed to ramdisk
411 Ramdisk *bool
412
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700413 // Whether this module is installed to vendor ramdisk
414 Vendor_ramdisk *bool
415
Inseob Kim08758f02021-04-08 21:13:22 +0900416 // Whether this module is installed to debug ramdisk
417 Debug_ramdisk *bool
418
Jaewoong Jung8e93aba2021-03-02 16:58:08 -0800419 // Whether this module is built for non-native architectures (also known as native bridge binary)
dimitry1f33e402019-03-26 12:39:31 +0100420 Native_bridge_supported *bool `android:"arch_variant"`
421
Dan Willemsen2277bcb2016-07-25 20:27:39 -0700422 // init.rc files to be installed if this module is installed
Colin Cross0bab8772020-09-25 14:01:21 -0700423 Init_rc []string `android:"arch_variant,path"`
Dan Willemsen2277bcb2016-07-25 20:27:39 -0700424
Steven Moreland57a23d22018-04-04 15:42:19 -0700425 // VINTF manifest fragments to be installed if this module is installed
Colin Cross27b922f2019-03-04 22:35:41 -0800426 Vintf_fragments []string `android:"path"`
Steven Moreland57a23d22018-04-04 15:42:19 -0700427
Chris Wolfe998306e2016-08-15 14:47:23 -0400428 // names of other modules to install if this module is installed
Colin Crossc602b7d2017-05-05 13:36:36 -0700429 Required []string `android:"arch_variant"`
Chris Wolfe998306e2016-08-15 14:47:23 -0400430
Sasha Smundakb6d23052019-04-01 18:37:36 -0700431 // names of other modules to install on host if this module is installed
432 Host_required []string `android:"arch_variant"`
433
434 // names of other modules to install on target if this module is installed
435 Target_required []string `android:"arch_variant"`
436
Paul Duffinca7f0ef2020-02-25 15:50:49 +0000437 // The OsType of artifacts that this module variant is responsible for creating.
438 //
439 // Set by osMutator
440 CompileOS OsType `blueprint:"mutated"`
441
442 // The Target of artifacts that this module variant is responsible for creating.
443 //
444 // Set by archMutator
445 CompileTarget Target `blueprint:"mutated"`
446
447 // The additional arch specific targets (e.g. 32/64 bit) that this module variant is
448 // responsible for creating.
449 //
450 // By default this is nil as, where necessary, separate variants are created for the
451 // different multilib types supported and that information is encapsulated in the
452 // CompileTarget so the module variant simply needs to create artifacts for that.
453 //
454 // However, if UseTargetVariants is set to false (e.g. by
455 // InitAndroidMultiTargetsArchModule) then no separate variants are created for the
456 // multilib targets. Instead a single variant is created for the architecture and
457 // this contains the multilib specific targets that this variant should create.
458 //
459 // Set by archMutator
Colin Crossee0bc3b2018-10-02 22:01:37 -0700460 CompileMultiTargets []Target `blueprint:"mutated"`
Paul Duffinca7f0ef2020-02-25 15:50:49 +0000461
462 // True if the module variant's CompileTarget is the primary target
463 //
464 // Set by archMutator
465 CompilePrimary bool `blueprint:"mutated"`
Colin Cross3f40fa42015-01-30 17:27:36 -0800466
467 // Set by InitAndroidModule
468 HostOrDeviceSupported HostOrDeviceSupported `blueprint:"mutated"`
Dan Willemsen0b24c742016-10-04 15:13:37 -0700469 ArchSpecific bool `blueprint:"mutated"`
Colin Crossce75d2c2016-10-06 16:12:58 -0700470
Paul Duffin1356d8c2020-02-25 19:26:33 +0000471 // If set to true then a CommonOS variant will be created which will have dependencies
472 // on all its OsType specific variants. Used by sdk/module_exports to create a snapshot
473 // that covers all os and architecture variants.
474 //
475 // The OsType specific variants can be retrieved by calling
476 // GetOsSpecificVariantsOfCommonOSVariant
477 //
478 // Set at module initialization time by calling InitCommonOSAndroidMultiTargetsArchModule
479 CreateCommonOSVariant bool `blueprint:"mutated"`
480
481 // If set to true then this variant is the CommonOS variant that has dependencies on its
482 // OsType specific variants.
483 //
484 // Set by osMutator.
485 CommonOSVariant bool `blueprint:"mutated"`
486
Colin Crossa9c8c9f2020-12-16 10:20:23 -0800487 // When HideFromMake is set to true, no entry for this variant will be emitted in the
488 // generated Android.mk file.
489 HideFromMake bool `blueprint:"mutated"`
490
491 // When SkipInstall is set to true, calls to ctx.InstallFile, ctx.InstallExecutable,
492 // ctx.InstallSymlink and ctx.InstallAbsoluteSymlink act like calls to ctx.PackageFile
493 // and don't create a rule to install the file.
Colin Crossce75d2c2016-10-06 16:12:58 -0700494 SkipInstall bool `blueprint:"mutated"`
Jeff Gaston088e29e2017-11-29 16:47:17 -0800495
Colin Crossbd3a16b2023-04-25 11:30:51 -0700496 // UninstallableApexPlatformVariant is set by MakeUninstallable called by the apex
497 // mutator. MakeUninstallable also sets HideFromMake. UninstallableApexPlatformVariant
498 // is used to avoid adding install or packaging dependencies into libraries provided
499 // by apexes.
500 UninstallableApexPlatformVariant bool `blueprint:"mutated"`
501
Liz Kammer5ca3a622020-08-05 15:40:41 -0700502 // Whether the module has been replaced by a prebuilt
503 ReplacedByPrebuilt bool `blueprint:"mutated"`
504
Justin Yun32f053b2020-07-31 23:07:17 +0900505 // Disabled by mutators. If set to true, it overrides Enabled property.
506 ForcedDisabled bool `blueprint:"mutated"`
507
Jeff Gaston088e29e2017-11-29 16:47:17 -0800508 NamespaceExportedToMake bool `blueprint:"mutated"`
Colin Cross6c4f21f2019-06-06 15:41:36 -0700509
Liz Kammerc13f7852023-05-17 13:01:48 -0400510 MissingDeps []string `blueprint:"mutated"`
511 CheckedMissingDeps bool `blueprint:"mutated"`
Colin Cross9a362232019-07-01 15:32:45 -0700512
513 // Name and variant strings stored by mutators to enable Module.String()
514 DebugName string `blueprint:"mutated"`
515 DebugMutators []string `blueprint:"mutated"`
516 DebugVariations []string `blueprint:"mutated"`
Colin Cross7228ecd2019-11-18 16:00:16 -0800517
Colin Crossa6845402020-11-16 15:08:19 -0800518 // ImageVariation is set by ImageMutator to specify which image this variation is for,
519 // for example "" for core or "recovery" for recovery. It will often be set to one of the
520 // constants in image.go, but can also be set to a custom value by individual module types.
Colin Cross7228ecd2019-11-18 16:00:16 -0800521 ImageVariation string `blueprint:"mutated"`
Liz Kammer2ada09a2021-08-11 00:17:36 -0400522
Sasha Smundaka0954062022-08-02 18:23:58 -0700523 // Bazel conversion status
524 BazelConversionStatus BazelConversionStatus `blueprint:"mutated"`
Inseob Kim81b00a82023-05-15 18:06:31 +0900525
Inseob Kim8ff69de2023-06-16 14:19:33 +0900526 // SoongConfigTrace records accesses to VendorVars (soong_config). The trace will be hashed
527 // and used as a subdir of PathForModuleOut. Note that we mainly focus on incremental
528 // builds among similar products (e.g. aosp_cf_x86_64_phone and aosp_cf_x86_64_foldable),
529 // and there are variables other than soong_config, which isn't captured by soong config
530 // trace, but influence modules among products.
Inseob Kim81b00a82023-05-15 18:06:31 +0900531 SoongConfigTrace soongConfigTrace `blueprint:"mutated"`
532 SoongConfigTraceHash string `blueprint:"mutated"`
Colin Cross3f40fa42015-01-30 17:27:36 -0800533}
534
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000535// CommonAttributes represents the common Bazel attributes from which properties
536// in `commonProperties` are translated/mapped; such properties are annotated in
537// a list their corresponding attribute. It is embedded within `bp2buildInfo`.
538type CommonAttributes struct {
539 // Soong nameProperties -> Bazel name
540 Name string
Spandan Das4238c652022-09-09 01:38:47 +0000541
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000542 // Data mapped from: Required
543 Data bazel.LabelListAttribute
Jingwen Chenfbff97a2022-09-16 02:32:03 +0000544
Spandan Das4238c652022-09-09 01:38:47 +0000545 // SkipData is neither a Soong nor Bazel target attribute
546 // If true, this will not fill the data attribute automatically
547 // This is useful for Soong modules that have 1:many Bazel targets
548 // Some of the generated Bazel targets might not have a data attribute
549 SkipData *bool
550
Jingwen Chenfbff97a2022-09-16 02:32:03 +0000551 Tags bazel.StringListAttribute
Sasha Smundak05b0ba62022-09-26 18:15:45 -0700552
553 Applicable_licenses bazel.LabelListAttribute
Yu Liu4c212ce2022-10-14 12:20:20 -0700554
555 Testonly *bool
Spandan Das3131d672023-08-03 22:33:47 +0000556
557 // Dir is neither a Soong nor Bazel target attribute
558 // If set, the bazel target will be created in this directory
559 // If unset, the bazel target will default to be created in the directory of the visited soong module
560 Dir *string
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000561}
562
Chris Parsons58852a02021-12-09 18:10:18 -0500563// constraintAttributes represents Bazel attributes pertaining to build constraints,
564// which make restrict building a Bazel target for some set of platforms.
565type constraintAttributes struct {
566 // Constraint values this target can be built for.
567 Target_compatible_with bazel.LabelListAttribute
568}
569
Paul Duffined875132020-09-02 13:08:57 +0100570type distProperties struct {
571 // configuration to distribute output files from this module to the distribution
572 // directory (default: $OUT/dist, configurable with $DIST_DIR)
573 Dist Dist `android:"arch_variant"`
574
575 // a list of configurations to distribute output files from this module to the
576 // distribution directory (default: $OUT/dist, configurable with $DIST_DIR)
577 Dists []Dist `android:"arch_variant"`
578}
579
Zhenhuang Wang0ac5a432022-08-12 18:49:20 +0800580// CommonTestOptions represents the common `test_options` properties in
581// Android.bp.
582type CommonTestOptions struct {
583 // If the test is a hostside (no device required) unittest that shall be run
584 // during presubmit check.
585 Unit_test *bool
Zhenhuang Wang409d2772022-08-22 16:00:05 +0800586
587 // Tags provide additional metadata to customize test execution by downstream
588 // test runners. The tags have no special meaning to Soong.
589 Tags []string
Zhenhuang Wang0ac5a432022-08-12 18:49:20 +0800590}
591
592// SetAndroidMkEntries sets AndroidMkEntries according to the value of base
593// `test_options`.
594func (t *CommonTestOptions) SetAndroidMkEntries(entries *AndroidMkEntries) {
595 entries.SetBoolIfTrue("LOCAL_IS_UNIT_TEST", Bool(t.Unit_test))
Zhenhuang Wang409d2772022-08-22 16:00:05 +0800596 if len(t.Tags) > 0 {
597 entries.AddStrings("LOCAL_TEST_OPTIONS_TAGS", t.Tags...)
598 }
Zhenhuang Wang0ac5a432022-08-12 18:49:20 +0800599}
600
Paul Duffin74f05592020-11-25 16:37:46 +0000601// The key to use in TaggedDistFiles when a Dist structure does not specify a
602// tag property. This intentionally does not use "" as the default because that
603// would mean that an empty tag would have a different meaning when used in a dist
604// structure that when used to reference a specific set of output paths using the
605// :module{tag} syntax, which passes tag to the OutputFiles(tag) method.
606const DefaultDistTag = "<default-dist-tag>"
607
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000608// A map of OutputFile tag keys to Paths, for disting purposes.
609type TaggedDistFiles map[string]Paths
610
Paul Duffin74f05592020-11-25 16:37:46 +0000611// addPathsForTag adds a mapping from the tag to the paths. If the map is nil
612// then it will create a map, update it and then return it. If a mapping already
613// exists for the tag then the paths are appended to the end of the current list
614// of paths, ignoring any duplicates.
615func (t TaggedDistFiles) addPathsForTag(tag string, paths ...Path) TaggedDistFiles {
616 if t == nil {
617 t = make(TaggedDistFiles)
618 }
619
620 for _, distFile := range paths {
621 if distFile != nil && !t[tag].containsPath(distFile) {
622 t[tag] = append(t[tag], distFile)
623 }
624 }
625
626 return t
627}
628
629// merge merges the entries from the other TaggedDistFiles object into this one.
630// If the TaggedDistFiles is nil then it will create a new instance, merge the
631// other into it, and then return it.
632func (t TaggedDistFiles) merge(other TaggedDistFiles) TaggedDistFiles {
633 for tag, paths := range other {
634 t = t.addPathsForTag(tag, paths...)
635 }
636
637 return t
638}
639
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000640func MakeDefaultDistFiles(paths ...Path) TaggedDistFiles {
Sasha Smundake198eaf2022-08-04 13:07:02 -0700641 for _, p := range paths {
642 if p == nil {
Jingwen Chen7b27ca72020-07-24 09:13:49 +0000643 panic("The path to a dist file cannot be nil.")
644 }
645 }
646
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000647 // The default OutputFile tag is the empty "" string.
Paul Duffin74f05592020-11-25 16:37:46 +0000648 return TaggedDistFiles{DefaultDistTag: paths}
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000649}
650
Colin Cross3f40fa42015-01-30 17:27:36 -0800651type hostAndDeviceProperties struct {
Colin Cross4e81d702018-11-09 10:36:55 -0800652 // If set to true, build a variant of the module for the host. Defaults to false.
653 Host_supported *bool
654
655 // If set to true, build a variant of the module for the device. Defaults to true.
Colin Crossa4190c12016-07-12 13:11:25 -0700656 Device_supported *bool
Colin Cross3f40fa42015-01-30 17:27:36 -0800657}
658
Colin Crossc472d572015-03-17 15:06:21 -0700659type Multilib string
660
661const (
Colin Cross6b4a32d2017-12-05 13:42:45 -0800662 MultilibBoth Multilib = "both"
663 MultilibFirst Multilib = "first"
664 MultilibCommon Multilib = "common"
665 MultilibCommonFirst Multilib = "common_first"
Colin Crossc472d572015-03-17 15:06:21 -0700666)
667
Colin Crossa1ad8d12016-06-01 17:09:44 -0700668type HostOrDeviceSupported int
669
670const (
Colin Cross34037c62020-11-17 13:19:17 -0800671 hostSupported = 1 << iota
672 hostCrossSupported
673 deviceSupported
674 hostDefault
675 deviceDefault
Dan Albert0981b5c2018-08-02 13:46:35 -0700676
677 // Host and HostCross are built by default. Device is not supported.
Colin Cross34037c62020-11-17 13:19:17 -0800678 HostSupported = hostSupported | hostCrossSupported | hostDefault
Dan Albert0981b5c2018-08-02 13:46:35 -0700679
680 // Host is built by default. HostCross and Device are not supported.
Colin Cross34037c62020-11-17 13:19:17 -0800681 HostSupportedNoCross = hostSupported | hostDefault
Dan Albert0981b5c2018-08-02 13:46:35 -0700682
683 // Device is built by default. Host and HostCross are not supported.
Colin Cross34037c62020-11-17 13:19:17 -0800684 DeviceSupported = deviceSupported | deviceDefault
Dan Albert0981b5c2018-08-02 13:46:35 -0700685
Liz Kammer8631cc72021-08-23 21:12:07 +0000686 // By default, _only_ device variant is built. Device variant can be disabled with `device_supported: false`
Chih-Hung Hsiehd0f82fe2021-09-05 20:15:38 -0700687 // Host and HostCross are disabled by default and can be enabled with `host_supported: true`
Colin Cross34037c62020-11-17 13:19:17 -0800688 HostAndDeviceSupported = hostSupported | hostCrossSupported | deviceSupported | deviceDefault
Dan Albert0981b5c2018-08-02 13:46:35 -0700689
690 // Host, HostCross, and Device are built by default.
Chih-Hung Hsiehd0f82fe2021-09-05 20:15:38 -0700691 // Building Device can be disabled with `device_supported: false`
692 // Building Host and HostCross can be disabled with `host_supported: false`
Colin Cross34037c62020-11-17 13:19:17 -0800693 HostAndDeviceDefault = hostSupported | hostCrossSupported | hostDefault |
694 deviceSupported | deviceDefault
Dan Albert0981b5c2018-08-02 13:46:35 -0700695
696 // Nothing is supported. This is not exposed to the user, but used to mark a
697 // host only module as unsupported when the module type is not supported on
698 // the host OS. E.g. benchmarks are supported on Linux but not Darwin.
Colin Cross34037c62020-11-17 13:19:17 -0800699 NeitherHostNorDeviceSupported = 0
Colin Crossa1ad8d12016-06-01 17:09:44 -0700700)
701
Jiyong Park2db76922017-11-08 16:03:48 +0900702type moduleKind int
703
704const (
705 platformModule moduleKind = iota
706 deviceSpecificModule
707 socSpecificModule
708 productSpecificModule
Justin Yund5f6c822019-06-25 16:47:17 +0900709 systemExtSpecificModule
Jiyong Park2db76922017-11-08 16:03:48 +0900710)
711
712func (k moduleKind) String() string {
713 switch k {
714 case platformModule:
715 return "platform"
716 case deviceSpecificModule:
717 return "device-specific"
718 case socSpecificModule:
719 return "soc-specific"
720 case productSpecificModule:
721 return "product-specific"
Justin Yund5f6c822019-06-25 16:47:17 +0900722 case systemExtSpecificModule:
723 return "systemext-specific"
Jiyong Park2db76922017-11-08 16:03:48 +0900724 default:
725 panic(fmt.Errorf("unknown module kind %d", k))
726 }
727}
728
Colin Cross9d34f352019-11-22 16:03:51 -0800729func initAndroidModuleBase(m Module) {
730 m.base().module = m
731}
732
Colin Crossa6845402020-11-16 15:08:19 -0800733// InitAndroidModule initializes the Module as an Android module that is not architecture-specific.
734// It adds the common properties, for example "name" and "enabled".
Colin Cross36242852017-06-23 15:06:31 -0700735func InitAndroidModule(m Module) {
Colin Cross9d34f352019-11-22 16:03:51 -0800736 initAndroidModuleBase(m)
Colin Cross3f40fa42015-01-30 17:27:36 -0800737 base := m.base()
Colin Cross5049f022015-03-18 13:28:46 -0700738
Colin Cross36242852017-06-23 15:06:31 -0700739 m.AddProperties(
Colin Crossfc754582016-05-17 16:34:16 -0700740 &base.nameProperties,
Paul Duffined875132020-09-02 13:08:57 +0100741 &base.commonProperties,
742 &base.distProperties)
Colin Cross18c46802019-09-24 22:19:02 -0700743
Colin Crosseabaedd2020-02-06 17:01:55 -0800744 initProductVariableModule(m)
Colin Cross18c46802019-09-24 22:19:02 -0700745
Paul Duffin63c6e182019-07-24 14:24:38 +0100746 // The default_visibility property needs to be checked and parsed by the visibility module during
Paul Duffin5ec73ec2020-05-01 17:52:01 +0100747 // its checking and parsing phases so make it the primary visibility property.
748 setPrimaryVisibilityProperty(m, "visibility", &base.commonProperties.Visibility)
Bob Badour37af0462021-01-07 03:34:31 +0000749
750 // The default_applicable_licenses property needs to be checked and parsed by the licenses module during
751 // its checking and parsing phases so make it the primary licenses property.
752 setPrimaryLicensesProperty(m, "licenses", &base.commonProperties.Licenses)
Colin Cross5049f022015-03-18 13:28:46 -0700753}
754
Colin Crossa6845402020-11-16 15:08:19 -0800755// InitAndroidArchModule initializes the Module as an Android module that is architecture-specific.
756// It adds the common properties, for example "name" and "enabled", as well as runtime generated
757// property structs for architecture-specific versions of generic properties tagged with
758// `android:"arch_variant"`.
759//
Colin Crossd079e0b2022-08-16 10:27:33 -0700760// InitAndroidModule should not be called if InitAndroidArchModule was called.
Colin Cross36242852017-06-23 15:06:31 -0700761func InitAndroidArchModule(m Module, hod HostOrDeviceSupported, defaultMultilib Multilib) {
762 InitAndroidModule(m)
Colin Cross5049f022015-03-18 13:28:46 -0700763
764 base := m.base()
Colin Cross3f40fa42015-01-30 17:27:36 -0800765 base.commonProperties.HostOrDeviceSupported = hod
Colin Cross69617d32016-09-06 10:39:07 -0700766 base.commonProperties.Default_multilib = string(defaultMultilib)
Dan Willemsen0b24c742016-10-04 15:13:37 -0700767 base.commonProperties.ArchSpecific = true
Colin Crossee0bc3b2018-10-02 22:01:37 -0700768 base.commonProperties.UseTargetVariants = true
Colin Cross3f40fa42015-01-30 17:27:36 -0800769
Colin Cross34037c62020-11-17 13:19:17 -0800770 if hod&hostSupported != 0 && hod&deviceSupported != 0 {
Colin Cross36242852017-06-23 15:06:31 -0700771 m.AddProperties(&base.hostAndDeviceProperties)
Colin Cross3f40fa42015-01-30 17:27:36 -0800772 }
773
Colin Crossa6845402020-11-16 15:08:19 -0800774 initArchModule(m)
Colin Cross3f40fa42015-01-30 17:27:36 -0800775}
776
Colin Crossa6845402020-11-16 15:08:19 -0800777// InitAndroidMultiTargetsArchModule initializes the Module as an Android module that is
778// architecture-specific, but will only have a single variant per OS that handles all the
779// architectures simultaneously. The list of Targets that it must handle will be available from
780// ModuleContext.MultiTargets. It adds the common properties, for example "name" and "enabled", as
781// well as runtime generated property structs for architecture-specific versions of generic
782// properties tagged with `android:"arch_variant"`.
783//
784// InitAndroidModule or InitAndroidArchModule should not be called if
785// InitAndroidMultiTargetsArchModule was called.
Colin Crossee0bc3b2018-10-02 22:01:37 -0700786func InitAndroidMultiTargetsArchModule(m Module, hod HostOrDeviceSupported, defaultMultilib Multilib) {
787 InitAndroidArchModule(m, hod, defaultMultilib)
788 m.base().commonProperties.UseTargetVariants = false
789}
790
Colin Crossa6845402020-11-16 15:08:19 -0800791// InitCommonOSAndroidMultiTargetsArchModule initializes the Module as an Android module that is
792// architecture-specific, but will only have a single variant per OS that handles all the
793// architectures simultaneously, and will also have an additional CommonOS variant that has
794// dependencies on all the OS-specific variants. The list of Targets that it must handle will be
795// available from ModuleContext.MultiTargets. It adds the common properties, for example "name" and
796// "enabled", as well as runtime generated property structs for architecture-specific versions of
797// generic properties tagged with `android:"arch_variant"`.
798//
799// InitAndroidModule, InitAndroidArchModule or InitAndroidMultiTargetsArchModule should not be
800// called if InitCommonOSAndroidMultiTargetsArchModule was called.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000801func InitCommonOSAndroidMultiTargetsArchModule(m Module, hod HostOrDeviceSupported, defaultMultilib Multilib) {
802 InitAndroidArchModule(m, hod, defaultMultilib)
803 m.base().commonProperties.UseTargetVariants = false
804 m.base().commonProperties.CreateCommonOSVariant = true
805}
806
Chris Parsons7123cc52023-10-04 22:27:40 +0000807func (attrs *CommonAttributes) getRequiredWithoutCycles(ctx *bottomUpMutatorContext, props *commonProperties) []string {
808 // Treat `required` as if it's empty if data should be skipped for this target,
809 // as `required` is only used for the `data` attribute at this time, and we want
810 // to avoid lookups of labels that won't actually be dependencies of this target.
811 // TODO: b/202299295 - Refactor this to use `required` dependencies, once they
812 // are handled other than passing to `data`.
813 if proptools.Bool(attrs.SkipData) {
814 return []string{}
815 }
816 // The required property can contain the module itself. This causes a cycle
817 // when generated as the 'data' label list attribute in Bazel. Remove it if
818 // it exists. See b/247985196.
819 _, requiredWithoutCycles := RemoveFromList(ctx.ModuleName(), props.Required)
820 return FirstUniqueStrings(requiredWithoutCycles)
821}
822
Chris Parsons6666d0f2023-09-22 16:21:53 +0000823func (attrs *CommonAttributes) fillCommonBp2BuildModuleAttrs(ctx *bottomUpMutatorContext,
Chris Parsons58852a02021-12-09 18:10:18 -0500824 enabledPropertyOverrides bazel.BoolAttribute) constraintAttributes {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000825
826 mod := ctx.Module().base()
Sasha Smundake198eaf2022-08-04 13:07:02 -0700827 // Assert passed-in attributes include Name
828 if len(attrs.Name) == 0 {
Sasha Smundakfb589492022-08-04 11:13:27 -0700829 if ctx.ModuleType() != "package" {
830 ctx.ModuleErrorf("CommonAttributes in fillCommonBp2BuildModuleAttrs expects a `.Name`!")
831 }
Sasha Smundake198eaf2022-08-04 13:07:02 -0700832 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000833
834 depsToLabelList := func(deps []string) bazel.LabelListAttribute {
835 return bazel.MakeLabelListAttribute(BazelLabelForModuleDeps(ctx, deps))
836 }
837
Chris Parsons58852a02021-12-09 18:10:18 -0500838 var enabledProperty bazel.BoolAttribute
Liz Kammerdfeb1202022-05-13 17:20:20 -0400839
840 onlyAndroid := false
841 neitherHostNorDevice := false
842
843 osSupport := map[string]bool{}
844
845 // if the target is enabled and supports arch variance, determine the defaults based on the module
846 // type's host or device property and host_supported/device_supported properties
847 if mod.commonProperties.ArchSpecific {
848 moduleSupportsDevice := mod.DeviceSupported()
849 moduleSupportsHost := mod.HostSupported()
850 if moduleSupportsHost && !moduleSupportsDevice {
851 // for host only, we specify as unsupported on android rather than listing all host osSupport
852 // TODO(b/220874839): consider replacing this with a constraint that covers all host osSupport
853 // instead
854 enabledProperty.SetSelectValue(bazel.OsConfigurationAxis, Android.Name, proptools.BoolPtr(false))
855 } else if moduleSupportsDevice && !moduleSupportsHost {
856 enabledProperty.SetSelectValue(bazel.OsConfigurationAxis, Android.Name, proptools.BoolPtr(true))
857 // specify as a positive to ensure any target-specific enabled can be resolved
858 // also save that a target is only android, as if there is only the positive restriction on
859 // android, it'll be dropped, so we may need to add it back later
860 onlyAndroid = true
861 } else if !moduleSupportsHost && !moduleSupportsDevice {
862 neitherHostNorDevice = true
863 }
864
Sasha Smundake198eaf2022-08-04 13:07:02 -0700865 for _, osType := range OsTypeList() {
866 if osType.Class == Host {
867 osSupport[osType.Name] = moduleSupportsHost
868 } else if osType.Class == Device {
869 osSupport[osType.Name] = moduleSupportsDevice
Liz Kammerdfeb1202022-05-13 17:20:20 -0400870 }
871 }
872 }
873
874 if neitherHostNorDevice {
875 // we can't build this, disable
876 enabledProperty.Value = proptools.BoolPtr(false)
Sasha Smundake198eaf2022-08-04 13:07:02 -0700877 } else if mod.commonProperties.Enabled != nil {
878 enabledProperty.SetValue(mod.commonProperties.Enabled)
879 if !*mod.commonProperties.Enabled {
880 for oss, enabled := range osSupport {
881 if val := enabledProperty.SelectValue(bazel.OsConfigurationAxis, oss); enabled && val != nil && *val {
Liz Kammerdfeb1202022-05-13 17:20:20 -0400882 // if this should be disabled by default, clear out any enabling we've done
Sasha Smundake198eaf2022-08-04 13:07:02 -0700883 enabledProperty.SetSelectValue(bazel.OsConfigurationAxis, oss, nil)
Liz Kammerdfeb1202022-05-13 17:20:20 -0400884 }
885 }
886 }
Chris Parsons58852a02021-12-09 18:10:18 -0500887 }
888
Sasha Smundak05b0ba62022-09-26 18:15:45 -0700889 attrs.Applicable_licenses = bazel.MakeLabelListAttribute(BazelLabelForModuleDeps(ctx, mod.commonProperties.Licenses))
890
Chris Parsons7123cc52023-10-04 22:27:40 +0000891 requiredWithoutCycles := attrs.getRequiredWithoutCycles(ctx, &mod.commonProperties)
Jingwen Chena5ecb372022-09-21 09:05:37 +0000892 required := depsToLabelList(requiredWithoutCycles)
Sasha Smundake198eaf2022-08-04 13:07:02 -0700893 archVariantProps := mod.GetArchVariantProperties(ctx, &commonProperties{})
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000894 for axis, configToProps := range archVariantProps {
895 for config, _props := range configToProps {
896 if archProps, ok := _props.(*commonProperties); ok {
Chris Parsons7123cc52023-10-04 22:27:40 +0000897 requiredWithoutCycles := attrs.getRequiredWithoutCycles(ctx, archProps)
Jingwen Chena5ecb372022-09-21 09:05:37 +0000898 required.SetSelectValue(axis, config, depsToLabelList(requiredWithoutCycles).Value)
Liz Kammerdfeb1202022-05-13 17:20:20 -0400899 if !neitherHostNorDevice {
900 if archProps.Enabled != nil {
901 if axis != bazel.OsConfigurationAxis || osSupport[config] {
902 enabledProperty.SetSelectValue(axis, config, archProps.Enabled)
903 }
904 }
Chris Parsons58852a02021-12-09 18:10:18 -0500905 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000906 }
907 }
908 }
Chris Parsons58852a02021-12-09 18:10:18 -0500909
Liz Kammerdfeb1202022-05-13 17:20:20 -0400910 if !neitherHostNorDevice {
911 if enabledPropertyOverrides.Value != nil {
912 enabledProperty.Value = enabledPropertyOverrides.Value
913 }
914 for _, axis := range enabledPropertyOverrides.SortedConfigurationAxes() {
915 configToBools := enabledPropertyOverrides.ConfigurableValues[axis]
916 for cfg, val := range configToBools {
Spandan Dasab29f572023-09-01 19:43:56 +0000917 if axis != bazel.OsConfigurationAxis || osSupport[cfg] || val /*If enabled is explicitly requested via overrides */ {
Liz Kammerdfeb1202022-05-13 17:20:20 -0400918 enabledProperty.SetSelectValue(axis, cfg, &val)
919 }
920 }
Chris Parsons58852a02021-12-09 18:10:18 -0500921 }
922 }
923
Cole Faust87c0c332023-07-31 12:10:12 -0700924 productConfigEnabledAttribute := bazel.LabelListAttribute{}
Liz Kammerdfeb1202022-05-13 17:20:20 -0400925 // TODO(b/234497586): Soong config variables and product variables have different overriding behavior, we
926 // should handle it correctly
927 if !proptools.BoolDefault(enabledProperty.Value, true) && !neitherHostNorDevice {
Sam Delmerico0e33c9d2022-01-07 20:39:21 +0000928 // If the module is not enabled by default, then we can check if a
929 // product variable enables it
Cole Faust87c0c332023-07-31 12:10:12 -0700930 productConfigEnabledAttribute = productVariableConfigEnableAttribute(ctx)
Chris Parsons58852a02021-12-09 18:10:18 -0500931
Cole Faust87c0c332023-07-31 12:10:12 -0700932 if len(productConfigEnabledAttribute.ConfigurableValues) > 0 {
Sam Delmerico0e33c9d2022-01-07 20:39:21 +0000933 // In this case, an existing product variable configuration overrides any
934 // module-level `enable: false` definition
935 newValue := true
936 enabledProperty.Value = &newValue
937 }
938 }
939
Sam Delmerico0e33c9d2022-01-07 20:39:21 +0000940 platformEnabledAttribute, err := enabledProperty.ToLabelListAttribute(
Sasha Smundake198eaf2022-08-04 13:07:02 -0700941 bazel.LabelList{[]bazel.Label{{Label: "@platforms//:incompatible"}}, nil},
Chris Parsons58852a02021-12-09 18:10:18 -0500942 bazel.LabelList{[]bazel.Label{}, nil})
Chris Parsons58852a02021-12-09 18:10:18 -0500943 if err != nil {
Sam Delmerico0e33c9d2022-01-07 20:39:21 +0000944 ctx.ModuleErrorf("Error processing platform enabled attribute: %s", err)
Chris Parsons58852a02021-12-09 18:10:18 -0500945 }
Sam Delmerico0e33c9d2022-01-07 20:39:21 +0000946
Liz Kammerdfeb1202022-05-13 17:20:20 -0400947 // if android is the only arch/os enabled, then add a restriction to only be compatible with android
948 if platformEnabledAttribute.IsNil() && onlyAndroid {
949 l := bazel.LabelAttribute{}
950 l.SetValue(bazel.Label{Label: bazel.OsConfigurationAxis.SelectKey(Android.Name)})
951 platformEnabledAttribute.Add(&l)
952 }
953
Chris Parsons7123cc52023-10-04 22:27:40 +0000954 attrs.Data.Append(required)
955
Spandan Das4238c652022-09-09 01:38:47 +0000956 // SkipData is not an attribute of any Bazel target
957 // Set this to nil so that it does not appear in the generated build file
958 attrs.SkipData = nil
Sam Delmerico0e33c9d2022-01-07 20:39:21 +0000959
Sam Delmerico0e33c9d2022-01-07 20:39:21 +0000960 moduleEnableConstraints := bazel.LabelListAttribute{}
961 moduleEnableConstraints.Append(platformEnabledAttribute)
962 moduleEnableConstraints.Append(productConfigEnabledAttribute)
Spandan Dase1cb14b2023-09-05 19:31:12 +0000963 addCompatibilityConstraintForCompileMultilib(ctx, &moduleEnableConstraints)
Sam Delmerico0e33c9d2022-01-07 20:39:21 +0000964
Sasha Smundake198eaf2022-08-04 13:07:02 -0700965 return constraintAttributes{Target_compatible_with: moduleEnableConstraints}
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000966}
967
Spandan Dase1cb14b2023-09-05 19:31:12 +0000968var (
969 incompatible = bazel.LabelList{[]bazel.Label{{Label: "@platforms//:incompatible"}}, nil}
970)
971
972// If compile_mulitilib is set to
973// 1. 32: Add an incompatibility constraint for non-32 arches
974// 1. 64: Add an incompatibility constraint for non-64 arches
Chris Parsons6666d0f2023-09-22 16:21:53 +0000975func addCompatibilityConstraintForCompileMultilib(ctx *bottomUpMutatorContext, enabled *bazel.LabelListAttribute) {
Spandan Dase1cb14b2023-09-05 19:31:12 +0000976 mod := ctx.Module().base()
977 multilib, _ := decodeMultilib(mod, mod.commonProperties.CompileOS, ctx.Config().IgnorePrefer32OnDevice())
978
979 switch multilib {
980 case "32":
981 // Add an incompatibility constraint for all known 64-bit arches
982 enabled.SetSelectValue(bazel.ArchConfigurationAxis, "arm64", incompatible)
983 enabled.SetSelectValue(bazel.ArchConfigurationAxis, "x86_64", incompatible)
984 enabled.SetSelectValue(bazel.ArchConfigurationAxis, "riscv64", incompatible)
985 case "64":
986 // Add an incompatibility constraint for all known 32-bit arches
987 enabled.SetSelectValue(bazel.ArchConfigurationAxis, "arm", incompatible)
988 enabled.SetSelectValue(bazel.ArchConfigurationAxis, "x86", incompatible)
989 case "both":
990 // Do nothing: "both" is trivially compatible with 32-bit and 64-bit
991 // The top level rule (e.g. apex/partition) will be responsible for building this module in both variants via an
992 // outgoing_transition.
993 default: // e.g. first, common
994 // TODO - b/299135307: Add bp2build support for these properties.
995 }
996
997}
998
Sam Delmerico0e33c9d2022-01-07 20:39:21 +0000999// Check product variables for `enabled: true` flag override.
1000// Returns a list of the constraint_value targets who enable this override.
Chris Parsons6666d0f2023-09-22 16:21:53 +00001001func productVariableConfigEnableAttribute(ctx *bottomUpMutatorContext) bazel.LabelListAttribute {
Cole Faust87c0c332023-07-31 12:10:12 -07001002 result := bazel.LabelListAttribute{}
Liz Kammer9e2a5a72023-09-19 08:41:14 -04001003 productVariableProps, errs := ProductVariableProperties(ctx, ctx.Module())
1004 for _, err := range errs {
1005 ctx.ModuleErrorf("ProductVariableProperties error: %s", err)
1006 }
Cole Faust87c0c332023-07-31 12:10:12 -07001007 if productConfigProps, exists := productVariableProps["Enabled"]; exists {
Sam Delmerico0e33c9d2022-01-07 20:39:21 +00001008 for productConfigProp, prop := range productConfigProps {
1009 flag, ok := prop.(*bool)
1010 if !ok {
Cole Faust87c0c332023-07-31 12:10:12 -07001011 ctx.ModuleErrorf("Could not convert product variable enabled property")
Sam Delmerico0e33c9d2022-01-07 20:39:21 +00001012 }
1013
Spandan Das479e39f2023-08-07 22:43:58 +00001014 if flag == nil {
1015 // soong config var is not used to set `enabled`. nothing to do.
1016 continue
1017 } else if *flag {
Sam Delmerico0e33c9d2022-01-07 20:39:21 +00001018 axis := productConfigProp.ConfigurationAxis()
Cole Faust87c0c332023-07-31 12:10:12 -07001019 result.SetSelectValue(axis, bazel.ConditionsDefaultConfigKey, bazel.MakeLabelList([]bazel.Label{{Label: "@platforms//:incompatible"}}))
1020 result.SetSelectValue(axis, productConfigProp.SelectKey(), bazel.LabelList{Includes: []bazel.Label{}})
Spandan Das846ce682023-08-08 02:00:22 +00001021 } else if scp, isSoongConfigProperty := productConfigProp.(SoongConfigProperty); isSoongConfigProperty && scp.value == bazel.ConditionsDefaultConfigKey {
1022 // productVariableConfigEnableAttribute runs only if `enabled: false` is set at the top-level outside soong_config_variables
1023 // conditions_default { enabled: false} is a no-op in this case
1024 continue
Sam Delmerico0e33c9d2022-01-07 20:39:21 +00001025 } else {
1026 // TODO(b/210546943): handle negative case where `enabled: false`
Cole Faust87c0c332023-07-31 12:10:12 -07001027 ctx.ModuleErrorf("`enabled: false` is not currently supported for configuration variables. See b/210546943")
Sam Delmerico0e33c9d2022-01-07 20:39:21 +00001028 }
1029 }
1030 }
1031
Cole Faust87c0c332023-07-31 12:10:12 -07001032 return result
Sam Delmerico0e33c9d2022-01-07 20:39:21 +00001033}
1034
Nan Zhangb9eeb1d2017-02-02 10:46:07 -08001035// A ModuleBase object contains the properties that are common to all Android
Colin Cross3f40fa42015-01-30 17:27:36 -08001036// modules. It should be included as an anonymous field in every module
1037// struct definition. InitAndroidModule should then be called from the module's
1038// factory function, and the return values from InitAndroidModule should be
1039// returned from the factory function.
1040//
Nan Zhangb9eeb1d2017-02-02 10:46:07 -08001041// The ModuleBase type is responsible for implementing the GenerateBuildActions
1042// method to support the blueprint.Module interface. This method will then call
1043// the module's GenerateAndroidBuildActions method once for each build variant
Colin Cross25de6c32019-06-06 14:29:25 -07001044// that is to be built. GenerateAndroidBuildActions is passed a ModuleContext
1045// rather than the usual blueprint.ModuleContext.
1046// ModuleContext exposes extra functionality specific to the Android build
Colin Cross3f40fa42015-01-30 17:27:36 -08001047// system including details about the particular build variant that is to be
1048// generated.
1049//
1050// For example:
1051//
Zhenhuang Wang0ac5a432022-08-12 18:49:20 +08001052// import (
1053// "android/soong/android"
1054// )
Colin Cross3f40fa42015-01-30 17:27:36 -08001055//
Zhenhuang Wang0ac5a432022-08-12 18:49:20 +08001056// type myModule struct {
1057// android.ModuleBase
1058// properties struct {
1059// MyProperty string
1060// }
1061// }
Colin Cross3f40fa42015-01-30 17:27:36 -08001062//
Zhenhuang Wang0ac5a432022-08-12 18:49:20 +08001063// func NewMyModule() android.Module {
1064// m := &myModule{}
1065// m.AddProperties(&m.properties)
1066// android.InitAndroidModule(m)
1067// return m
1068// }
Colin Cross3f40fa42015-01-30 17:27:36 -08001069//
Zhenhuang Wang0ac5a432022-08-12 18:49:20 +08001070// func (m *myModule) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1071// // Get the CPU architecture for the current build variant.
1072// variantArch := ctx.Arch()
Colin Cross3f40fa42015-01-30 17:27:36 -08001073//
Zhenhuang Wang0ac5a432022-08-12 18:49:20 +08001074// // ...
1075// }
Colin Cross635c3b02016-05-18 15:37:25 -07001076type ModuleBase struct {
Colin Cross3f40fa42015-01-30 17:27:36 -08001077 // Putting the curiously recurring thing pointing to the thing that contains
1078 // the thing pattern to good use.
Colin Cross36242852017-06-23 15:06:31 -07001079 // TODO: remove this
Colin Cross635c3b02016-05-18 15:37:25 -07001080 module Module
Colin Cross3f40fa42015-01-30 17:27:36 -08001081
Colin Crossfc754582016-05-17 16:34:16 -07001082 nameProperties nameProperties
Colin Cross3f40fa42015-01-30 17:27:36 -08001083 commonProperties commonProperties
Paul Duffined875132020-09-02 13:08:57 +01001084 distProperties distProperties
Colin Cross18c46802019-09-24 22:19:02 -07001085 variableProperties interface{}
Colin Cross3f40fa42015-01-30 17:27:36 -08001086 hostAndDeviceProperties hostAndDeviceProperties
Jingwen Chen5d864492021-02-24 07:20:12 -05001087
Usta851a3272022-01-05 23:42:33 -05001088 // Arch specific versions of structs in GetProperties() prior to
1089 // initialization in InitAndroidArchModule, lets call it `generalProperties`.
1090 // The outer index has the same order as generalProperties and the inner index
1091 // chooses the props specific to the architecture. The interface{} value is an
1092 // archPropRoot that is filled with arch specific values by the arch mutator.
Jingwen Chen5d864492021-02-24 07:20:12 -05001093 archProperties [][]interface{}
1094
Jingwen Chen73850672020-12-14 08:25:34 -05001095 // Properties specific to the Blueprint to BUILD migration.
1096 bazelTargetModuleProperties bazel.BazelTargetModuleProperties
1097
Paul Duffin63c6e182019-07-24 14:24:38 +01001098 // Information about all the properties on the module that contains visibility rules that need
1099 // checking.
1100 visibilityPropertyInfo []visibilityProperty
1101
1102 // The primary visibility property, may be nil, that controls access to the module.
1103 primaryVisibilityProperty visibilityProperty
1104
Bob Badour37af0462021-01-07 03:34:31 +00001105 // The primary licenses property, may be nil, records license metadata for the module.
1106 primaryLicensesProperty applicableLicensesProperty
1107
Colin Crossffe6b9d2020-12-01 15:40:06 -08001108 noAddressSanitizer bool
1109 installFiles InstallPaths
Colin Crossc85750b2022-04-21 12:50:51 -07001110 installFilesDepSet *DepSet[InstallPath]
Colin Crossffe6b9d2020-12-01 15:40:06 -08001111 checkbuildFiles Paths
1112 packagingSpecs []PackagingSpec
Colin Crossc85750b2022-04-21 12:50:51 -07001113 packagingSpecsDepSet *DepSet[PackagingSpec]
Colin Cross6301c3c2021-09-28 17:40:21 -07001114 // katiInstalls tracks the install rules that were created by Soong but are being exported
1115 // to Make to convert to ninja rules so that Make can add additional dependencies.
1116 katiInstalls katiInstalls
1117 katiSymlinks katiInstalls
Colin Cross5c1d5fb2023-11-15 12:39:40 -08001118 testData []DataPath
Colin Cross1f8c52b2015-06-16 16:38:17 -07001119
Paul Duffinaf970a22020-11-23 23:32:56 +00001120 // The files to copy to the dist as explicitly specified in the .bp file.
1121 distFiles TaggedDistFiles
1122
Colin Cross1f8c52b2015-06-16 16:38:17 -07001123 // Used by buildTargetSingleton to create checkbuild and per-directory build targets
1124 // Only set on the final variant of each module
Colin Cross0875c522017-11-28 17:34:01 -08001125 installTarget WritablePath
1126 checkbuildTarget WritablePath
Colin Cross1f8c52b2015-06-16 16:38:17 -07001127 blueprintDir string
Colin Crossa120ec12016-08-19 16:07:38 -07001128
Colin Cross178a5092016-09-13 13:42:32 -07001129 hooks hooks
Colin Cross36242852017-06-23 15:06:31 -07001130
1131 registerProps []interface{}
Colin Crosscec81712017-07-13 14:43:27 -07001132
1133 // For tests
Colin Crossae887032017-10-23 17:16:14 -07001134 buildParams []BuildParams
Colin Cross4c83e5c2019-02-25 14:54:28 -08001135 ruleParams map[blueprint.Rule]blueprint.RuleParams
Jaewoong Jung38e4fb22018-12-12 09:01:34 -08001136 variables map[string]string
Colin Crossa9d8bee2018-10-02 13:59:46 -07001137
Inseob Kim8471cda2019-11-15 09:59:12 +09001138 initRcPaths Paths
1139 vintfFragmentsPaths Paths
Colin Cross4acaea92021-12-10 23:05:02 +00001140
1141 // set of dependency module:location mappings used to populate the license metadata for
1142 // apex containers.
1143 licenseInstallMap []string
Colin Crossaa1cab02022-01-28 14:49:24 -08001144
1145 // The path to the generated license metadata file for the module.
1146 licenseMetadataFile WritablePath
Colin Cross36242852017-06-23 15:06:31 -07001147}
1148
Liz Kammer2ada09a2021-08-11 00:17:36 -04001149// A struct containing all relevant information about a Bazel target converted via bp2build.
1150type bp2buildInfo struct {
Chris Parsons58852a02021-12-09 18:10:18 -05001151 Dir string
1152 BazelProps bazel.BazelTargetModuleProperties
1153 CommonAttrs CommonAttributes
1154 ConstraintAttrs constraintAttributes
1155 Attrs interface{}
Liz Kammer2ada09a2021-08-11 00:17:36 -04001156}
1157
1158// TargetName returns the Bazel target name of a bp2build converted target.
1159func (b bp2buildInfo) TargetName() string {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +00001160 return b.CommonAttrs.Name
Liz Kammer2ada09a2021-08-11 00:17:36 -04001161}
1162
1163// TargetPackage returns the Bazel package of a bp2build converted target.
1164func (b bp2buildInfo) TargetPackage() string {
1165 return b.Dir
1166}
1167
1168// BazelRuleClass returns the Bazel rule class of a bp2build converted target.
1169func (b bp2buildInfo) BazelRuleClass() string {
1170 return b.BazelProps.Rule_class
1171}
1172
1173// BazelRuleLoadLocation returns the location of the Bazel rule of a bp2build converted target.
1174// This may be empty as native Bazel rules do not need to be loaded.
1175func (b bp2buildInfo) BazelRuleLoadLocation() string {
1176 return b.BazelProps.Bzl_load_location
1177}
1178
1179// BazelAttributes returns the Bazel attributes of a bp2build converted target.
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +00001180func (b bp2buildInfo) BazelAttributes() []interface{} {
Chris Parsons58852a02021-12-09 18:10:18 -05001181 return []interface{}{&b.CommonAttrs, &b.ConstraintAttrs, b.Attrs}
Liz Kammer2ada09a2021-08-11 00:17:36 -04001182}
1183
1184func (m *ModuleBase) addBp2buildInfo(info bp2buildInfo) {
Sasha Smundaka0954062022-08-02 18:23:58 -07001185 m.commonProperties.BazelConversionStatus.Bp2buildInfo = append(m.commonProperties.BazelConversionStatus.Bp2buildInfo, info)
Liz Kammer2ada09a2021-08-11 00:17:36 -04001186}
1187
Cole Faust11edf552023-10-13 11:32:14 -07001188func (m *ModuleBase) setPartitionForBp2build(partition string) {
1189 m.commonProperties.BazelConversionStatus.Partition = partition
1190}
1191
Chris Parsons39a16972023-06-08 14:28:51 +00001192func (m *ModuleBase) setBp2buildUnconvertible(reasonType bp2build_metrics_proto.UnconvertedReasonType, detail string) {
Chris Parsons39a16972023-06-08 14:28:51 +00001193 m.commonProperties.BazelConversionStatus.UnconvertedReason = &UnconvertedReason{
1194 ReasonType: int(reasonType),
1195 Detail: detail,
1196 }
1197}
1198
Chris Parsons39a16972023-06-08 14:28:51 +00001199func (m *ModuleBase) GetUnconvertedReason() *UnconvertedReason {
1200 return m.commonProperties.BazelConversionStatus.UnconvertedReason
1201}
1202
Liz Kammer2ada09a2021-08-11 00:17:36 -04001203// Bp2buildTargets returns the Bazel targets bp2build generated for this module.
1204func (m *ModuleBase) Bp2buildTargets() []bp2buildInfo {
Sasha Smundaka0954062022-08-02 18:23:58 -07001205 return m.commonProperties.BazelConversionStatus.Bp2buildInfo
Liz Kammer2ada09a2021-08-11 00:17:36 -04001206}
1207
Cole Faust11edf552023-10-13 11:32:14 -07001208// Bp2buildTargets returns the Bazel targets bp2build generated for this module.
1209func (m *ModuleBase) GetPartitionForBp2build() string {
1210 return m.commonProperties.BazelConversionStatus.Partition
1211}
1212
Liz Kammer6eff3232021-08-26 08:37:59 -04001213// GetUnconvertedBp2buildDeps returns the list of module names of this module's direct dependencies that
1214// were not converted to Bazel.
1215func (m *ModuleBase) GetUnconvertedBp2buildDeps() []string {
Sasha Smundaka0954062022-08-02 18:23:58 -07001216 return FirstUniqueStrings(m.commonProperties.BazelConversionStatus.UnconvertedDeps)
Liz Kammer6eff3232021-08-26 08:37:59 -04001217}
1218
Usta Shrestha56b84e72022-09-24 00:26:47 -04001219// GetMissingBp2buildDeps returns the list of module names that were not found in Android.bp files.
Liz Kammerdaa09ef2021-12-15 15:35:38 -05001220func (m *ModuleBase) GetMissingBp2buildDeps() []string {
Sasha Smundaka0954062022-08-02 18:23:58 -07001221 return FirstUniqueStrings(m.commonProperties.BazelConversionStatus.MissingDeps)
Liz Kammerdaa09ef2021-12-15 15:35:38 -05001222}
1223
Lukacs T. Berkid18d8ca2021-06-25 09:11:22 +02001224func (m *ModuleBase) AddJSONData(d *map[string]interface{}) {
Liz Kammer9525e712022-01-05 13:46:24 -05001225 (*d)["Android"] = map[string]interface{}{
1226 // Properties set in Blueprint or in blueprint of a defaults modules
1227 "SetProperties": m.propertiesWithValues(),
1228 }
1229}
1230
1231type propInfo struct {
Liz Kammer898e0762022-03-22 11:27:26 -04001232 Name string
1233 Type string
1234 Value string
1235 Values []string
Liz Kammer9525e712022-01-05 13:46:24 -05001236}
1237
1238func (m *ModuleBase) propertiesWithValues() []propInfo {
1239 var info []propInfo
1240 props := m.GetProperties()
1241
1242 var propsWithValues func(name string, v reflect.Value)
1243 propsWithValues = func(name string, v reflect.Value) {
1244 kind := v.Kind()
1245 switch kind {
1246 case reflect.Ptr, reflect.Interface:
1247 if v.IsNil() {
1248 return
1249 }
1250 propsWithValues(name, v.Elem())
1251 case reflect.Struct:
1252 if v.IsZero() {
1253 return
1254 }
1255 for i := 0; i < v.NumField(); i++ {
1256 namePrefix := name
1257 sTyp := v.Type().Field(i)
1258 if proptools.ShouldSkipProperty(sTyp) {
1259 continue
1260 }
1261 if name != "" && !strings.HasSuffix(namePrefix, ".") {
1262 namePrefix += "."
1263 }
1264 if !proptools.IsEmbedded(sTyp) {
1265 namePrefix += sTyp.Name
1266 }
1267 sVal := v.Field(i)
1268 propsWithValues(namePrefix, sVal)
1269 }
1270 case reflect.Array, reflect.Slice:
1271 if v.IsNil() {
1272 return
1273 }
1274 elKind := v.Type().Elem().Kind()
Liz Kammer898e0762022-03-22 11:27:26 -04001275 info = append(info, propInfo{Name: name, Type: elKind.String() + " " + kind.String(), Values: sliceReflectionValue(v)})
Liz Kammer9525e712022-01-05 13:46:24 -05001276 default:
Liz Kammer898e0762022-03-22 11:27:26 -04001277 info = append(info, propInfo{Name: name, Type: kind.String(), Value: reflectionValue(v)})
Liz Kammer9525e712022-01-05 13:46:24 -05001278 }
1279 }
1280
1281 for _, p := range props {
1282 propsWithValues("", reflect.ValueOf(p).Elem())
1283 }
Liz Kammer898e0762022-03-22 11:27:26 -04001284 sort.Slice(info, func(i, j int) bool {
1285 return info[i].Name < info[j].Name
1286 })
Liz Kammer9525e712022-01-05 13:46:24 -05001287 return info
Lukacs T. Berkid18d8ca2021-06-25 09:11:22 +02001288}
1289
Liz Kammer898e0762022-03-22 11:27:26 -04001290func reflectionValue(value reflect.Value) string {
1291 switch value.Kind() {
1292 case reflect.Bool:
1293 return fmt.Sprintf("%t", value.Bool())
1294 case reflect.Int64:
1295 return fmt.Sprintf("%d", value.Int())
1296 case reflect.String:
1297 return fmt.Sprintf("%s", value.String())
1298 case reflect.Struct:
1299 if value.IsZero() {
1300 return "{}"
1301 }
1302 length := value.NumField()
1303 vals := make([]string, length, length)
1304 for i := 0; i < length; i++ {
1305 sTyp := value.Type().Field(i)
1306 if proptools.ShouldSkipProperty(sTyp) {
1307 continue
1308 }
1309 name := sTyp.Name
1310 vals[i] = fmt.Sprintf("%s: %s", name, reflectionValue(value.Field(i)))
1311 }
1312 return fmt.Sprintf("%s{%s}", value.Type(), strings.Join(vals, ", "))
1313 case reflect.Array, reflect.Slice:
1314 vals := sliceReflectionValue(value)
1315 return fmt.Sprintf("[%s]", strings.Join(vals, ", "))
1316 }
1317 return ""
1318}
1319
1320func sliceReflectionValue(value reflect.Value) []string {
1321 length := value.Len()
1322 vals := make([]string, length, length)
1323 for i := 0; i < length; i++ {
1324 vals[i] = reflectionValue(value.Index(i))
1325 }
1326 return vals
1327}
1328
Paul Duffin44f1d842020-06-26 20:17:02 +01001329func (m *ModuleBase) ComponentDepsMutator(BottomUpMutatorContext) {}
1330
Colin Cross4157e882019-06-06 16:57:04 -07001331func (m *ModuleBase) DepsMutator(BottomUpMutatorContext) {}
Colin Cross5f692ec2019-02-01 16:53:07 -08001332
Usta355a5872021-12-01 15:16:32 -05001333// AddProperties "registers" the provided props
1334// each value in props MUST be a pointer to a struct
Colin Cross4157e882019-06-06 16:57:04 -07001335func (m *ModuleBase) AddProperties(props ...interface{}) {
1336 m.registerProps = append(m.registerProps, props...)
Colin Cross36242852017-06-23 15:06:31 -07001337}
1338
Colin Cross4157e882019-06-06 16:57:04 -07001339func (m *ModuleBase) GetProperties() []interface{} {
1340 return m.registerProps
Colin Cross3f40fa42015-01-30 17:27:36 -08001341}
1342
Colin Cross4157e882019-06-06 16:57:04 -07001343func (m *ModuleBase) BuildParamsForTests() []BuildParams {
Chih-Hung Hsiehb8082292021-09-09 23:20:39 -07001344 // Expand the references to module variables like $flags[0-9]*,
1345 // so we do not need to change many existing unit tests.
1346 // This looks like undoing the shareFlags optimization in cc's
1347 // transformSourceToObj, and should only affects unit tests.
1348 vars := m.VariablesForTests()
1349 buildParams := append([]BuildParams(nil), m.buildParams...)
Sasha Smundake198eaf2022-08-04 13:07:02 -07001350 for i := range buildParams {
Chih-Hung Hsiehb8082292021-09-09 23:20:39 -07001351 newArgs := make(map[string]string)
1352 for k, v := range buildParams[i].Args {
1353 newArgs[k] = v
1354 // Replaces both ${flags1} and $flags1 syntax.
1355 if strings.HasPrefix(v, "${") && strings.HasSuffix(v, "}") {
1356 if value, found := vars[v[2:len(v)-1]]; found {
1357 newArgs[k] = value
1358 }
1359 } else if strings.HasPrefix(v, "$") {
1360 if value, found := vars[v[1:]]; found {
1361 newArgs[k] = value
1362 }
1363 }
1364 }
1365 buildParams[i].Args = newArgs
1366 }
1367 return buildParams
Colin Crosscec81712017-07-13 14:43:27 -07001368}
1369
Colin Cross4157e882019-06-06 16:57:04 -07001370func (m *ModuleBase) RuleParamsForTests() map[blueprint.Rule]blueprint.RuleParams {
1371 return m.ruleParams
Colin Cross4c83e5c2019-02-25 14:54:28 -08001372}
1373
Colin Cross4157e882019-06-06 16:57:04 -07001374func (m *ModuleBase) VariablesForTests() map[string]string {
1375 return m.variables
Jaewoong Jung38e4fb22018-12-12 09:01:34 -08001376}
1377
Colin Crossce75d2c2016-10-06 16:12:58 -07001378// Name returns the name of the module. It may be overridden by individual module types, for
1379// example prebuilts will prepend prebuilt_ to the name.
Colin Cross4157e882019-06-06 16:57:04 -07001380func (m *ModuleBase) Name() string {
1381 return String(m.nameProperties.Name)
Colin Crossfc754582016-05-17 16:34:16 -07001382}
1383
Colin Cross9a362232019-07-01 15:32:45 -07001384// String returns a string that includes the module name and variants for printing during debugging.
1385func (m *ModuleBase) String() string {
1386 sb := strings.Builder{}
1387 sb.WriteString(m.commonProperties.DebugName)
1388 sb.WriteString("{")
1389 for i := range m.commonProperties.DebugMutators {
1390 if i != 0 {
1391 sb.WriteString(",")
1392 }
1393 sb.WriteString(m.commonProperties.DebugMutators[i])
1394 sb.WriteString(":")
1395 sb.WriteString(m.commonProperties.DebugVariations[i])
1396 }
1397 sb.WriteString("}")
1398 return sb.String()
1399}
1400
Colin Crossce75d2c2016-10-06 16:12:58 -07001401// BaseModuleName returns the name of the module as specified in the blueprints file.
Colin Cross4157e882019-06-06 16:57:04 -07001402func (m *ModuleBase) BaseModuleName() string {
1403 return String(m.nameProperties.Name)
Colin Crossce75d2c2016-10-06 16:12:58 -07001404}
1405
Colin Cross4157e882019-06-06 16:57:04 -07001406func (m *ModuleBase) base() *ModuleBase {
1407 return m
Colin Cross3f40fa42015-01-30 17:27:36 -08001408}
1409
Paul Duffine2453c72019-05-31 14:00:04 +01001410func (m *ModuleBase) qualifiedModuleId(ctx BaseModuleContext) qualifiedModuleName {
1411 return qualifiedModuleName{pkg: ctx.ModuleDir(), name: ctx.ModuleName()}
1412}
1413
1414func (m *ModuleBase) visibilityProperties() []visibilityProperty {
Paul Duffin63c6e182019-07-24 14:24:38 +01001415 return m.visibilityPropertyInfo
1416}
1417
Jingwen Chen40fd90a2020-06-15 05:24:19 +00001418func (m *ModuleBase) Dists() []Dist {
Paul Duffined875132020-09-02 13:08:57 +01001419 if len(m.distProperties.Dist.Targets) > 0 {
Jingwen Chen40fd90a2020-06-15 05:24:19 +00001420 // Make a copy of the underlying Dists slice to protect against
1421 // backing array modifications with repeated calls to this method.
Paul Duffined875132020-09-02 13:08:57 +01001422 distsCopy := append([]Dist(nil), m.distProperties.Dists...)
1423 return append(distsCopy, m.distProperties.Dist)
Jingwen Chen40fd90a2020-06-15 05:24:19 +00001424 } else {
Paul Duffined875132020-09-02 13:08:57 +01001425 return m.distProperties.Dists
Jingwen Chen40fd90a2020-06-15 05:24:19 +00001426 }
1427}
1428
1429func (m *ModuleBase) GenerateTaggedDistFiles(ctx BaseModuleContext) TaggedDistFiles {
Paul Duffin74f05592020-11-25 16:37:46 +00001430 var distFiles TaggedDistFiles
Jingwen Chen40fd90a2020-06-15 05:24:19 +00001431 for _, dist := range m.Dists() {
Paul Duffin74f05592020-11-25 16:37:46 +00001432 // If no tag is specified then it means to use the default dist paths so use
1433 // the special tag name which represents that.
1434 tag := proptools.StringDefault(dist.Tag, DefaultDistTag)
1435
Paul Duffinaf970a22020-11-23 23:32:56 +00001436 if outputFileProducer, ok := m.module.(OutputFileProducer); ok {
1437 // Call the OutputFiles(tag) method to get the paths associated with the tag.
1438 distFilesForTag, err := outputFileProducer.OutputFiles(tag)
Paul Duffin74f05592020-11-25 16:37:46 +00001439
Paul Duffinaf970a22020-11-23 23:32:56 +00001440 // If the tag was not supported and is not DefaultDistTag then it is an error.
1441 // Failing to find paths for DefaultDistTag is not an error. It just means
1442 // that the module type requires the legacy behavior.
1443 if err != nil && tag != DefaultDistTag {
1444 ctx.PropertyErrorf("dist.tag", "%s", err.Error())
1445 }
1446
1447 distFiles = distFiles.addPathsForTag(tag, distFilesForTag...)
1448 } else if tag != DefaultDistTag {
1449 // If the tag was specified then it is an error if the module does not
1450 // implement OutputFileProducer because there is no other way of accessing
1451 // the paths for the specified tag.
1452 ctx.PropertyErrorf("dist.tag",
1453 "tag %s not supported because the module does not implement OutputFileProducer", tag)
Jingwen Chen40fd90a2020-06-15 05:24:19 +00001454 }
Jingwen Chen40fd90a2020-06-15 05:24:19 +00001455 }
1456
1457 return distFiles
1458}
1459
Colin Cross4157e882019-06-06 16:57:04 -07001460func (m *ModuleBase) Target() Target {
1461 return m.commonProperties.CompileTarget
Dan Willemsen490fd492015-11-24 17:53:15 -08001462}
1463
Colin Cross4157e882019-06-06 16:57:04 -07001464func (m *ModuleBase) TargetPrimary() bool {
1465 return m.commonProperties.CompilePrimary
Colin Cross8b74d172016-09-13 09:59:14 -07001466}
1467
Colin Cross4157e882019-06-06 16:57:04 -07001468func (m *ModuleBase) MultiTargets() []Target {
1469 return m.commonProperties.CompileMultiTargets
Colin Crossee0bc3b2018-10-02 22:01:37 -07001470}
1471
Colin Cross4157e882019-06-06 16:57:04 -07001472func (m *ModuleBase) Os() OsType {
1473 return m.Target().Os
Dan Willemsen490fd492015-11-24 17:53:15 -08001474}
1475
Colin Cross4157e882019-06-06 16:57:04 -07001476func (m *ModuleBase) Host() bool {
Jiyong Park1613e552020-09-14 19:43:17 +09001477 return m.Os().Class == Host
Dan Willemsen97750522016-02-09 17:43:51 -08001478}
1479
Yo Chiangbba545e2020-06-09 16:15:37 +08001480func (m *ModuleBase) Device() bool {
1481 return m.Os().Class == Device
1482}
1483
Colin Cross4157e882019-06-06 16:57:04 -07001484func (m *ModuleBase) Arch() Arch {
1485 return m.Target().Arch
Dan Willemsen97750522016-02-09 17:43:51 -08001486}
1487
Colin Cross4157e882019-06-06 16:57:04 -07001488func (m *ModuleBase) ArchSpecific() bool {
1489 return m.commonProperties.ArchSpecific
Dan Willemsen0b24c742016-10-04 15:13:37 -07001490}
1491
Paul Duffin1356d8c2020-02-25 19:26:33 +00001492// True if the current variant is a CommonOS variant, false otherwise.
1493func (m *ModuleBase) IsCommonOSVariant() bool {
1494 return m.commonProperties.CommonOSVariant
1495}
1496
Colin Cross34037c62020-11-17 13:19:17 -08001497// supportsTarget returns true if the given Target is supported by the current module.
1498func (m *ModuleBase) supportsTarget(target Target) bool {
1499 switch target.Os.Class {
1500 case Host:
1501 if target.HostCross {
1502 return m.HostCrossSupported()
1503 } else {
1504 return m.HostSupported()
Colin Crossa1ad8d12016-06-01 17:09:44 -07001505 }
Colin Cross34037c62020-11-17 13:19:17 -08001506 case Device:
1507 return m.DeviceSupported()
Colin Crossa1ad8d12016-06-01 17:09:44 -07001508 default:
Jiyong Park1613e552020-09-14 19:43:17 +09001509 return false
Colin Crossa1ad8d12016-06-01 17:09:44 -07001510 }
Colin Cross3f40fa42015-01-30 17:27:36 -08001511}
1512
Colin Cross34037c62020-11-17 13:19:17 -08001513// DeviceSupported returns true if the current module is supported and enabled for device targets,
1514// i.e. the factory method set the HostOrDeviceSupported value to include device support and
1515// the device support is enabled by default or enabled by the device_supported property.
Colin Cross4157e882019-06-06 16:57:04 -07001516func (m *ModuleBase) DeviceSupported() bool {
Colin Cross34037c62020-11-17 13:19:17 -08001517 hod := m.commonProperties.HostOrDeviceSupported
1518 // deviceEnabled is true if the device_supported property is true or the HostOrDeviceSupported
1519 // value has the deviceDefault bit set.
1520 deviceEnabled := proptools.BoolDefault(m.hostAndDeviceProperties.Device_supported, hod&deviceDefault != 0)
1521 return hod&deviceSupported != 0 && deviceEnabled
Colin Cross3f40fa42015-01-30 17:27:36 -08001522}
1523
Colin Cross34037c62020-11-17 13:19:17 -08001524// HostSupported returns true if the current module is supported and enabled for host targets,
1525// i.e. the factory method set the HostOrDeviceSupported value to include host support and
1526// the host support is enabled by default or enabled by the host_supported property.
Paul Duffine44358f2019-11-26 18:04:12 +00001527func (m *ModuleBase) HostSupported() bool {
Colin Cross34037c62020-11-17 13:19:17 -08001528 hod := m.commonProperties.HostOrDeviceSupported
1529 // hostEnabled is true if the host_supported property is true or the HostOrDeviceSupported
1530 // value has the hostDefault bit set.
1531 hostEnabled := proptools.BoolDefault(m.hostAndDeviceProperties.Host_supported, hod&hostDefault != 0)
1532 return hod&hostSupported != 0 && hostEnabled
1533}
1534
1535// HostCrossSupported returns true if the current module is supported and enabled for host cross
1536// targets, i.e. the factory method set the HostOrDeviceSupported value to include host cross
1537// support and the host cross support is enabled by default or enabled by the
1538// host_supported property.
1539func (m *ModuleBase) HostCrossSupported() bool {
1540 hod := m.commonProperties.HostOrDeviceSupported
1541 // hostEnabled is true if the host_supported property is true or the HostOrDeviceSupported
1542 // value has the hostDefault bit set.
1543 hostEnabled := proptools.BoolDefault(m.hostAndDeviceProperties.Host_supported, hod&hostDefault != 0)
1544 return hod&hostCrossSupported != 0 && hostEnabled
Paul Duffine44358f2019-11-26 18:04:12 +00001545}
1546
Colin Cross4157e882019-06-06 16:57:04 -07001547func (m *ModuleBase) Platform() bool {
Justin Yund5f6c822019-06-25 16:47:17 +09001548 return !m.DeviceSpecific() && !m.SocSpecific() && !m.ProductSpecific() && !m.SystemExtSpecific()
Jiyong Parkc678ad32018-04-10 13:07:10 +09001549}
1550
Colin Cross4157e882019-06-06 16:57:04 -07001551func (m *ModuleBase) DeviceSpecific() bool {
1552 return Bool(m.commonProperties.Device_specific)
Jiyong Parkc678ad32018-04-10 13:07:10 +09001553}
1554
Colin Cross4157e882019-06-06 16:57:04 -07001555func (m *ModuleBase) SocSpecific() bool {
1556 return Bool(m.commonProperties.Vendor) || Bool(m.commonProperties.Proprietary) || Bool(m.commonProperties.Soc_specific)
Jiyong Parkc678ad32018-04-10 13:07:10 +09001557}
1558
Colin Cross4157e882019-06-06 16:57:04 -07001559func (m *ModuleBase) ProductSpecific() bool {
1560 return Bool(m.commonProperties.Product_specific)
Jiyong Parkc678ad32018-04-10 13:07:10 +09001561}
1562
Justin Yund5f6c822019-06-25 16:47:17 +09001563func (m *ModuleBase) SystemExtSpecific() bool {
1564 return Bool(m.commonProperties.System_ext_specific)
Dario Frenifd05a742018-05-29 13:28:54 +01001565}
1566
Colin Crossc2d24052020-05-13 11:05:02 -07001567// RequiresStableAPIs returns true if the module will be installed to a partition that may
1568// be updated separately from the system image.
1569func (m *ModuleBase) RequiresStableAPIs(ctx BaseModuleContext) bool {
1570 return m.SocSpecific() || m.DeviceSpecific() ||
1571 (m.ProductSpecific() && ctx.Config().EnforceProductPartitionInterface())
1572}
1573
Bill Peckhamfff3f8a2020-03-20 18:33:20 -07001574func (m *ModuleBase) PartitionTag(config DeviceConfig) string {
1575 partition := "system"
1576 if m.SocSpecific() {
1577 // A SoC-specific module could be on the vendor partition at
1578 // "vendor" or the system partition at "system/vendor".
1579 if config.VendorPath() == "vendor" {
1580 partition = "vendor"
1581 }
1582 } else if m.DeviceSpecific() {
1583 // A device-specific module could be on the odm partition at
1584 // "odm", the vendor partition at "vendor/odm", or the system
1585 // partition at "system/vendor/odm".
1586 if config.OdmPath() == "odm" {
1587 partition = "odm"
Ramy Medhat944839a2020-03-31 22:14:52 -04001588 } else if strings.HasPrefix(config.OdmPath(), "vendor/") {
Bill Peckhamfff3f8a2020-03-20 18:33:20 -07001589 partition = "vendor"
1590 }
1591 } else if m.ProductSpecific() {
1592 // A product-specific module could be on the product partition
1593 // at "product" or the system partition at "system/product".
1594 if config.ProductPath() == "product" {
1595 partition = "product"
1596 }
1597 } else if m.SystemExtSpecific() {
1598 // A system_ext-specific module could be on the system_ext
1599 // partition at "system_ext" or the system partition at
1600 // "system/system_ext".
1601 if config.SystemExtPath() == "system_ext" {
1602 partition = "system_ext"
1603 }
1604 }
1605 return partition
1606}
1607
Colin Cross4157e882019-06-06 16:57:04 -07001608func (m *ModuleBase) Enabled() bool {
Justin Yun32f053b2020-07-31 23:07:17 +09001609 if m.commonProperties.ForcedDisabled {
1610 return false
1611 }
Colin Cross08d6f8f2020-11-19 02:33:19 +00001612 if m.commonProperties.Enabled == nil {
1613 return !m.Os().DefaultDisabled
1614 }
1615 return *m.commonProperties.Enabled
Colin Cross3f40fa42015-01-30 17:27:36 -08001616}
1617
Inseob Kimeec88e12020-01-22 11:11:29 +09001618func (m *ModuleBase) Disable() {
Justin Yun32f053b2020-07-31 23:07:17 +09001619 m.commonProperties.ForcedDisabled = true
Inseob Kimeec88e12020-01-22 11:11:29 +09001620}
1621
Colin Crossa9c8c9f2020-12-16 10:20:23 -08001622// HideFromMake marks this variant so that it is not emitted in the generated Android.mk file.
1623func (m *ModuleBase) HideFromMake() {
1624 m.commonProperties.HideFromMake = true
1625}
1626
1627// IsHideFromMake returns true if HideFromMake was previously called.
1628func (m *ModuleBase) IsHideFromMake() bool {
1629 return m.commonProperties.HideFromMake == true
1630}
1631
1632// SkipInstall marks this variant to not create install rules when ctx.Install* are called.
Colin Cross4157e882019-06-06 16:57:04 -07001633func (m *ModuleBase) SkipInstall() {
1634 m.commonProperties.SkipInstall = true
Colin Crossce75d2c2016-10-06 16:12:58 -07001635}
1636
Martin Stjernholm9e7f45e2020-12-23 03:50:30 +00001637// IsSkipInstall returns true if this variant is marked to not create install
1638// rules when ctx.Install* are called.
1639func (m *ModuleBase) IsSkipInstall() bool {
1640 return m.commonProperties.SkipInstall
1641}
1642
Iván Budnik295da162023-03-10 16:11:26 +00001643// Similar to HideFromMake, but if the AndroidMk entry would set
1644// LOCAL_UNINSTALLABLE_MODULE then this variant may still output that entry
1645// rather than leaving it out altogether. That happens in cases where it would
1646// have other side effects, in particular when it adds a NOTICE file target,
1647// which other install targets might depend on.
1648func (m *ModuleBase) MakeUninstallable() {
Colin Crossbd3a16b2023-04-25 11:30:51 -07001649 m.commonProperties.UninstallableApexPlatformVariant = true
Iván Budnik295da162023-03-10 16:11:26 +00001650 m.HideFromMake()
1651}
1652
Liz Kammer5ca3a622020-08-05 15:40:41 -07001653func (m *ModuleBase) ReplacedByPrebuilt() {
1654 m.commonProperties.ReplacedByPrebuilt = true
Colin Crossa9c8c9f2020-12-16 10:20:23 -08001655 m.HideFromMake()
Liz Kammer5ca3a622020-08-05 15:40:41 -07001656}
1657
1658func (m *ModuleBase) IsReplacedByPrebuilt() bool {
1659 return m.commonProperties.ReplacedByPrebuilt
1660}
1661
Colin Cross4157e882019-06-06 16:57:04 -07001662func (m *ModuleBase) ExportedToMake() bool {
1663 return m.commonProperties.NamespaceExportedToMake
Jiyong Park374510b2018-03-19 18:23:01 +09001664}
1665
Justin Yun1871f902023-04-07 20:13:19 +09001666func (m *ModuleBase) EffectiveLicenseKinds() []string {
1667 return m.commonProperties.Effective_license_kinds
1668}
1669
Justin Yun885a7de2021-06-29 20:34:53 +09001670func (m *ModuleBase) EffectiveLicenseFiles() Paths {
Bob Badour4101c712022-02-09 11:54:35 -08001671 result := make(Paths, 0, len(m.commonProperties.Effective_license_text))
1672 for _, p := range m.commonProperties.Effective_license_text {
1673 result = append(result, p.Path)
1674 }
1675 return result
Justin Yun885a7de2021-06-29 20:34:53 +09001676}
1677
Colin Crosse9fe2942020-11-10 18:12:15 -08001678// computeInstallDeps finds the installed paths of all dependencies that have a dependency
Colin Crossbd3a16b2023-04-25 11:30:51 -07001679// tag that is annotated as needing installation via the isInstallDepNeeded method.
Colin Crossc85750b2022-04-21 12:50:51 -07001680func (m *ModuleBase) computeInstallDeps(ctx ModuleContext) ([]*DepSet[InstallPath], []*DepSet[PackagingSpec]) {
1681 var installDeps []*DepSet[InstallPath]
1682 var packagingSpecs []*DepSet[PackagingSpec]
Colin Cross5d583952020-11-24 16:21:24 -08001683 ctx.VisitDirectDeps(func(dep Module) {
Colin Crossbd3a16b2023-04-25 11:30:51 -07001684 if isInstallDepNeeded(dep, ctx.OtherModuleDependencyTag(dep)) {
1685 // Installation is still handled by Make, so anything hidden from Make is not
1686 // installable.
1687 if !dep.IsHideFromMake() && !dep.IsSkipInstall() {
1688 installDeps = append(installDeps, dep.base().installFilesDepSet)
1689 }
1690 // Add packaging deps even when the dependency is not installed so that uninstallable
1691 // modules can still be packaged. Often the package will be installed instead.
Colin Crossffe6b9d2020-12-01 15:40:06 -08001692 packagingSpecs = append(packagingSpecs, dep.base().packagingSpecsDepSet)
Colin Cross897266e2020-02-13 13:22:08 -08001693 }
1694 })
Colin Cross3f40fa42015-01-30 17:27:36 -08001695
Colin Crossffe6b9d2020-12-01 15:40:06 -08001696 return installDeps, packagingSpecs
Colin Cross3f40fa42015-01-30 17:27:36 -08001697}
1698
Colin Crossbd3a16b2023-04-25 11:30:51 -07001699// isInstallDepNeeded returns true if installing the output files of the current module
1700// should also install the output files of the given dependency and dependency tag.
1701func isInstallDepNeeded(dep Module, tag blueprint.DependencyTag) bool {
1702 // Don't add a dependency from the platform to a library provided by an apex.
1703 if dep.base().commonProperties.UninstallableApexPlatformVariant {
1704 return false
1705 }
1706 // Only install modules if the dependency tag is an InstallDepNeeded tag.
1707 return IsInstallDepNeededTag(tag)
1708}
1709
Jiyong Park4dc2a1a2020-09-28 17:46:22 +09001710func (m *ModuleBase) FilesToInstall() InstallPaths {
Colin Cross4157e882019-06-06 16:57:04 -07001711 return m.installFiles
Colin Cross3f40fa42015-01-30 17:27:36 -08001712}
1713
Jiyong Park073ea552020-11-09 14:08:34 +09001714func (m *ModuleBase) PackagingSpecs() []PackagingSpec {
1715 return m.packagingSpecs
1716}
1717
Colin Crossffe6b9d2020-12-01 15:40:06 -08001718func (m *ModuleBase) TransitivePackagingSpecs() []PackagingSpec {
1719 return m.packagingSpecsDepSet.ToList()
1720}
1721
Colin Cross4157e882019-06-06 16:57:04 -07001722func (m *ModuleBase) NoAddressSanitizer() bool {
1723 return m.noAddressSanitizer
Colin Cross3f40fa42015-01-30 17:27:36 -08001724}
1725
Colin Cross4157e882019-06-06 16:57:04 -07001726func (m *ModuleBase) InstallInData() bool {
Dan Willemsen782a2d12015-12-21 14:55:28 -08001727 return false
1728}
1729
Jaewoong Jung0949f312019-09-11 10:25:18 -07001730func (m *ModuleBase) InstallInTestcases() bool {
1731 return false
1732}
1733
Colin Cross4157e882019-06-06 16:57:04 -07001734func (m *ModuleBase) InstallInSanitizerDir() bool {
Vishwath Mohan1dd88392017-03-29 22:00:18 -07001735 return false
1736}
1737
Yifan Hong1b3348d2020-01-21 15:53:22 -08001738func (m *ModuleBase) InstallInRamdisk() bool {
1739 return Bool(m.commonProperties.Ramdisk)
1740}
1741
Yifan Hong60e0cfb2020-10-21 15:17:56 -07001742func (m *ModuleBase) InstallInVendorRamdisk() bool {
1743 return Bool(m.commonProperties.Vendor_ramdisk)
1744}
1745
Inseob Kim08758f02021-04-08 21:13:22 +09001746func (m *ModuleBase) InstallInDebugRamdisk() bool {
1747 return Bool(m.commonProperties.Debug_ramdisk)
1748}
1749
Colin Cross4157e882019-06-06 16:57:04 -07001750func (m *ModuleBase) InstallInRecovery() bool {
1751 return Bool(m.commonProperties.Recovery)
Jiyong Parkf9332f12018-02-01 00:54:12 +09001752}
1753
Kiyoung Kimae11c232021-07-19 11:38:04 +09001754func (m *ModuleBase) InstallInVendor() bool {
Kiyoung Kimf160f7f2022-11-29 10:58:08 +09001755 return Bool(m.commonProperties.Vendor) || Bool(m.commonProperties.Soc_specific) || Bool(m.commonProperties.Proprietary)
Kiyoung Kimae11c232021-07-19 11:38:04 +09001756}
1757
Colin Cross90ba5f42019-10-02 11:10:58 -07001758func (m *ModuleBase) InstallInRoot() bool {
1759 return false
1760}
1761
Jiyong Park87788b52020-09-01 12:37:45 +09001762func (m *ModuleBase) InstallForceOS() (*OsType, *ArchType) {
1763 return nil, nil
Colin Cross6e359402020-02-10 15:29:54 -08001764}
1765
Colin Cross4157e882019-06-06 16:57:04 -07001766func (m *ModuleBase) Owner() string {
1767 return String(m.commonProperties.Owner)
Sundong Ahn4fd04bb2018-08-31 18:01:37 +09001768}
1769
Colin Cross7228ecd2019-11-18 16:00:16 -08001770func (m *ModuleBase) setImageVariation(variant string) {
1771 m.commonProperties.ImageVariation = variant
1772}
1773
1774func (m *ModuleBase) ImageVariation() blueprint.Variation {
1775 return blueprint.Variation{
1776 Mutator: "image",
1777 Variation: m.base().commonProperties.ImageVariation,
1778 }
1779}
1780
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001781func (m *ModuleBase) getVariationByMutatorName(mutator string) string {
1782 for i, v := range m.commonProperties.DebugMutators {
1783 if v == mutator {
1784 return m.commonProperties.DebugVariations[i]
1785 }
1786 }
1787
1788 return ""
1789}
1790
Yifan Hong1b3348d2020-01-21 15:53:22 -08001791func (m *ModuleBase) InRamdisk() bool {
1792 return m.base().commonProperties.ImageVariation == RamdiskVariation
1793}
1794
Yifan Hong60e0cfb2020-10-21 15:17:56 -07001795func (m *ModuleBase) InVendorRamdisk() bool {
1796 return m.base().commonProperties.ImageVariation == VendorRamdiskVariation
1797}
1798
Inseob Kim08758f02021-04-08 21:13:22 +09001799func (m *ModuleBase) InDebugRamdisk() bool {
1800 return m.base().commonProperties.ImageVariation == DebugRamdiskVariation
1801}
1802
Colin Cross7228ecd2019-11-18 16:00:16 -08001803func (m *ModuleBase) InRecovery() bool {
1804 return m.base().commonProperties.ImageVariation == RecoveryVariation
1805}
1806
Jiyong Park6a8cf5f2019-12-30 16:31:09 +09001807func (m *ModuleBase) RequiredModuleNames() []string {
1808 return m.base().commonProperties.Required
1809}
1810
1811func (m *ModuleBase) HostRequiredModuleNames() []string {
1812 return m.base().commonProperties.Host_required
1813}
1814
1815func (m *ModuleBase) TargetRequiredModuleNames() []string {
1816 return m.base().commonProperties.Target_required
1817}
1818
Inseob Kim8471cda2019-11-15 09:59:12 +09001819func (m *ModuleBase) InitRc() Paths {
1820 return append(Paths{}, m.initRcPaths...)
1821}
1822
1823func (m *ModuleBase) VintfFragments() Paths {
1824 return append(Paths{}, m.vintfFragmentsPaths...)
1825}
1826
Yu Liu4ae55d12022-01-05 17:17:23 -08001827func (m *ModuleBase) CompileMultilib() *string {
1828 return m.base().commonProperties.Compile_multilib
1829}
1830
Colin Cross4acaea92021-12-10 23:05:02 +00001831// SetLicenseInstallMap stores the set of dependency module:location mappings for files in an
1832// apex container for use when generation the license metadata file.
1833func (m *ModuleBase) SetLicenseInstallMap(installMap []string) {
1834 m.licenseInstallMap = append(m.licenseInstallMap, installMap...)
1835}
1836
Colin Cross4157e882019-06-06 16:57:04 -07001837func (m *ModuleBase) generateModuleTarget(ctx ModuleContext) {
Colin Cross897266e2020-02-13 13:22:08 -08001838 var allInstalledFiles InstallPaths
1839 var allCheckbuildFiles Paths
Colin Cross0875c522017-11-28 17:34:01 -08001840 ctx.VisitAllModuleVariants(func(module Module) {
1841 a := module.base()
Colin Crossc9404352015-03-26 16:10:12 -07001842 allInstalledFiles = append(allInstalledFiles, a.installFiles...)
Chih-Hung Hsieh80783772021-10-11 16:46:56 -07001843 // A module's -checkbuild phony targets should
Chih-Hung Hsieha3d135b2021-10-14 20:32:53 -07001844 // not be created if the module is not exported to make.
1845 // Those could depend on the build target and fail to compile
1846 // for the current build target.
1847 if !ctx.Config().KatiEnabled() || !shouldSkipAndroidMkProcessing(a) {
1848 allCheckbuildFiles = append(allCheckbuildFiles, a.checkbuildFiles...)
Chih-Hung Hsieha3d135b2021-10-14 20:32:53 -07001849 }
Colin Cross3f40fa42015-01-30 17:27:36 -08001850 })
1851
Colin Cross0875c522017-11-28 17:34:01 -08001852 var deps Paths
Colin Cross9454bfa2015-03-17 13:24:18 -07001853
Colin Cross133ebef2020-08-14 17:38:45 -07001854 namespacePrefix := ctx.Namespace().id
Jeff Gaston088e29e2017-11-29 16:47:17 -08001855 if namespacePrefix != "" {
1856 namespacePrefix = namespacePrefix + "-"
1857 }
1858
Colin Cross3f40fa42015-01-30 17:27:36 -08001859 if len(allInstalledFiles) > 0 {
Colin Crossc3d87d32020-06-04 13:25:17 -07001860 name := namespacePrefix + ctx.ModuleName() + "-install"
1861 ctx.Phony(name, allInstalledFiles.Paths()...)
1862 m.installTarget = PathForPhony(ctx, name)
1863 deps = append(deps, m.installTarget)
Colin Cross9454bfa2015-03-17 13:24:18 -07001864 }
1865
1866 if len(allCheckbuildFiles) > 0 {
Colin Crossc3d87d32020-06-04 13:25:17 -07001867 name := namespacePrefix + ctx.ModuleName() + "-checkbuild"
1868 ctx.Phony(name, allCheckbuildFiles...)
1869 m.checkbuildTarget = PathForPhony(ctx, name)
1870 deps = append(deps, m.checkbuildTarget)
Colin Cross9454bfa2015-03-17 13:24:18 -07001871 }
1872
1873 if len(deps) > 0 {
Dan Willemsen5ba07e82015-12-11 13:51:06 -08001874 suffix := ""
Jingwen Chencda22c92020-11-23 00:22:30 -05001875 if ctx.Config().KatiEnabled() {
Dan Willemsen5ba07e82015-12-11 13:51:06 -08001876 suffix = "-soong"
1877 }
1878
Colin Crossc3d87d32020-06-04 13:25:17 -07001879 ctx.Phony(namespacePrefix+ctx.ModuleName()+suffix, deps...)
Colin Cross1f8c52b2015-06-16 16:38:17 -07001880
Colin Cross4157e882019-06-06 16:57:04 -07001881 m.blueprintDir = ctx.ModuleDir()
Colin Cross3f40fa42015-01-30 17:27:36 -08001882 }
1883}
1884
Colin Crossc34d2322020-01-03 15:23:27 -08001885func determineModuleKind(m *ModuleBase, ctx blueprint.EarlyModuleContext) moduleKind {
Colin Cross4157e882019-06-06 16:57:04 -07001886 var socSpecific = Bool(m.commonProperties.Vendor) || Bool(m.commonProperties.Proprietary) || Bool(m.commonProperties.Soc_specific)
1887 var deviceSpecific = Bool(m.commonProperties.Device_specific)
1888 var productSpecific = Bool(m.commonProperties.Product_specific)
Justin Yund5f6c822019-06-25 16:47:17 +09001889 var systemExtSpecific = Bool(m.commonProperties.System_ext_specific)
Jiyong Park2db76922017-11-08 16:03:48 +09001890
Dario Frenifd05a742018-05-29 13:28:54 +01001891 msg := "conflicting value set here"
1892 if socSpecific && deviceSpecific {
1893 ctx.PropertyErrorf("device_specific", "a module cannot be specific to SoC and device at the same time.")
Colin Cross4157e882019-06-06 16:57:04 -07001894 if Bool(m.commonProperties.Vendor) {
Jiyong Park2db76922017-11-08 16:03:48 +09001895 ctx.PropertyErrorf("vendor", msg)
1896 }
Colin Cross4157e882019-06-06 16:57:04 -07001897 if Bool(m.commonProperties.Proprietary) {
Jiyong Park2db76922017-11-08 16:03:48 +09001898 ctx.PropertyErrorf("proprietary", msg)
1899 }
Colin Cross4157e882019-06-06 16:57:04 -07001900 if Bool(m.commonProperties.Soc_specific) {
Jiyong Park2db76922017-11-08 16:03:48 +09001901 ctx.PropertyErrorf("soc_specific", msg)
1902 }
1903 }
1904
Justin Yund5f6c822019-06-25 16:47:17 +09001905 if productSpecific && systemExtSpecific {
1906 ctx.PropertyErrorf("product_specific", "a module cannot be specific to product and system_ext at the same time.")
1907 ctx.PropertyErrorf("system_ext_specific", msg)
Dario Frenifd05a742018-05-29 13:28:54 +01001908 }
1909
Justin Yund5f6c822019-06-25 16:47:17 +09001910 if (socSpecific || deviceSpecific) && (productSpecific || systemExtSpecific) {
Dario Frenifd05a742018-05-29 13:28:54 +01001911 if productSpecific {
1912 ctx.PropertyErrorf("product_specific", "a module cannot be specific to SoC or device and product at the same time.")
1913 } else {
Justin Yund5f6c822019-06-25 16:47:17 +09001914 ctx.PropertyErrorf("system_ext_specific", "a module cannot be specific to SoC or device and system_ext at the same time.")
Dario Frenifd05a742018-05-29 13:28:54 +01001915 }
1916 if deviceSpecific {
1917 ctx.PropertyErrorf("device_specific", msg)
1918 } else {
Colin Cross4157e882019-06-06 16:57:04 -07001919 if Bool(m.commonProperties.Vendor) {
Dario Frenifd05a742018-05-29 13:28:54 +01001920 ctx.PropertyErrorf("vendor", msg)
1921 }
Colin Cross4157e882019-06-06 16:57:04 -07001922 if Bool(m.commonProperties.Proprietary) {
Dario Frenifd05a742018-05-29 13:28:54 +01001923 ctx.PropertyErrorf("proprietary", msg)
1924 }
Colin Cross4157e882019-06-06 16:57:04 -07001925 if Bool(m.commonProperties.Soc_specific) {
Dario Frenifd05a742018-05-29 13:28:54 +01001926 ctx.PropertyErrorf("soc_specific", msg)
1927 }
1928 }
1929 }
1930
Jiyong Park2db76922017-11-08 16:03:48 +09001931 if productSpecific {
1932 return productSpecificModule
Justin Yund5f6c822019-06-25 16:47:17 +09001933 } else if systemExtSpecific {
1934 return systemExtSpecificModule
Jiyong Park2db76922017-11-08 16:03:48 +09001935 } else if deviceSpecific {
1936 return deviceSpecificModule
1937 } else if socSpecific {
1938 return socSpecificModule
1939 } else {
1940 return platformModule
1941 }
1942}
1943
Colin Crossc34d2322020-01-03 15:23:27 -08001944func (m *ModuleBase) earlyModuleContextFactory(ctx blueprint.EarlyModuleContext) earlyModuleContext {
Colin Cross1184b642019-12-30 18:43:07 -08001945 return earlyModuleContext{
Colin Crossc34d2322020-01-03 15:23:27 -08001946 EarlyModuleContext: ctx,
1947 kind: determineModuleKind(m, ctx),
1948 config: ctx.Config().(Config),
Colin Cross3f40fa42015-01-30 17:27:36 -08001949 }
Colin Cross3f40fa42015-01-30 17:27:36 -08001950}
1951
Colin Cross1184b642019-12-30 18:43:07 -08001952func (m *ModuleBase) baseModuleContextFactory(ctx blueprint.BaseModuleContext) baseModuleContext {
1953 return baseModuleContext{
1954 bp: ctx,
1955 earlyModuleContext: m.earlyModuleContextFactory(ctx),
1956 os: m.commonProperties.CompileOS,
1957 target: m.commonProperties.CompileTarget,
1958 targetPrimary: m.commonProperties.CompilePrimary,
1959 multiTargets: m.commonProperties.CompileMultiTargets,
1960 }
1961}
1962
Colin Cross4157e882019-06-06 16:57:04 -07001963func (m *ModuleBase) GenerateBuildActions(blueprintCtx blueprint.ModuleContext) {
Colin Cross25de6c32019-06-06 14:29:25 -07001964 ctx := &moduleContext{
Colin Cross0ea8ba82019-06-06 14:33:29 -07001965 module: m.module,
Colin Crossdc35e212019-06-06 16:13:11 -07001966 bp: blueprintCtx,
Colin Cross0ea8ba82019-06-06 14:33:29 -07001967 baseModuleContext: m.baseModuleContextFactory(blueprintCtx),
Colin Cross0ea8ba82019-06-06 14:33:29 -07001968 variables: make(map[string]string),
Colin Cross3f40fa42015-01-30 17:27:36 -08001969 }
1970
Colin Crossaa1cab02022-01-28 14:49:24 -08001971 m.licenseMetadataFile = PathForModuleOut(ctx, "meta_lic")
1972
Colin Crossffe6b9d2020-12-01 15:40:06 -08001973 dependencyInstallFiles, dependencyPackagingSpecs := m.computeInstallDeps(ctx)
Colin Cross5d583952020-11-24 16:21:24 -08001974 // set m.installFilesDepSet to only the transitive dependencies to be used as the dependencies
1975 // of installed files of this module. It will be replaced by a depset including the installed
1976 // files of this module at the end for use by modules that depend on this one.
Colin Crossc85750b2022-04-21 12:50:51 -07001977 m.installFilesDepSet = NewDepSet[InstallPath](TOPOLOGICAL, nil, dependencyInstallFiles)
Colin Cross5d583952020-11-24 16:21:24 -08001978
Colin Cross6c4f21f2019-06-06 15:41:36 -07001979 // Temporarily continue to call blueprintCtx.GetMissingDependencies() to maintain the previous behavior of never
1980 // reporting missing dependency errors in Blueprint when AllowMissingDependencies == true.
1981 // TODO: This will be removed once defaults modules handle missing dependency errors
1982 blueprintCtx.GetMissingDependencies()
1983
Colin Crossdc35e212019-06-06 16:13:11 -07001984 // For the final GenerateAndroidBuildActions pass, require that all visited dependencies Soong modules and
Paul Duffin1356d8c2020-02-25 19:26:33 +00001985 // are enabled. Unless the module is a CommonOS variant which may have dependencies on disabled variants
1986 // (because the dependencies are added before the modules are disabled). The
1987 // GetOsSpecificVariantsOfCommonOSVariant(...) method will ensure that the disabled variants are
1988 // ignored.
1989 ctx.baseModuleContext.strictVisitDeps = !m.IsCommonOSVariant()
Colin Crossdc35e212019-06-06 16:13:11 -07001990
Colin Cross4c83e5c2019-02-25 14:54:28 -08001991 if ctx.config.captureBuild {
1992 ctx.ruleParams = make(map[blueprint.Rule]blueprint.RuleParams)
1993 }
1994
Colin Cross67a5c132017-05-09 13:45:28 -07001995 desc := "//" + ctx.ModuleDir() + ":" + ctx.ModuleName() + " "
1996 var suffix []string
Colin Cross0875c522017-11-28 17:34:01 -08001997 if ctx.Os().Class != Device && ctx.Os().Class != Generic {
1998 suffix = append(suffix, ctx.Os().String())
Colin Cross67a5c132017-05-09 13:45:28 -07001999 }
Colin Cross0875c522017-11-28 17:34:01 -08002000 if !ctx.PrimaryArch() {
2001 suffix = append(suffix, ctx.Arch().ArchType.String())
Colin Cross67a5c132017-05-09 13:45:28 -07002002 }
Colin Cross56a83212020-09-15 18:30:11 -07002003 if apexInfo := ctx.Provider(ApexInfoProvider).(ApexInfo); !apexInfo.IsForPlatform() {
2004 suffix = append(suffix, apexInfo.ApexVariationName)
Dan Willemsenb13a9482020-02-14 11:25:54 -08002005 }
Colin Cross67a5c132017-05-09 13:45:28 -07002006
2007 ctx.Variable(pctx, "moduleDesc", desc)
2008
2009 s := ""
2010 if len(suffix) > 0 {
2011 s = " [" + strings.Join(suffix, " ") + "]"
2012 }
2013 ctx.Variable(pctx, "moduleDescSuffix", s)
2014
Dan Willemsen569edc52018-11-19 09:33:29 -08002015 // Some common property checks for properties that will be used later in androidmk.go
Paul Duffin89968e32020-11-23 18:17:03 +00002016 checkDistProperties(ctx, "dist", &m.distProperties.Dist)
Sasha Smundake198eaf2022-08-04 13:07:02 -07002017 for i := range m.distProperties.Dists {
Paul Duffin89968e32020-11-23 18:17:03 +00002018 checkDistProperties(ctx, fmt.Sprintf("dists[%d]", i), &m.distProperties.Dists[i])
Dan Willemsen569edc52018-11-19 09:33:29 -08002019 }
2020
Colin Cross4157e882019-06-06 16:57:04 -07002021 if m.Enabled() {
Jooyung Hand48f3c32019-08-23 11:18:57 +09002022 // ensure all direct android.Module deps are enabled
2023 ctx.VisitDirectDepsBlueprint(func(bm blueprint.Module) {
Martin Stjernholm0e4cceb2021-05-13 02:38:35 +01002024 if m, ok := bm.(Module); ok {
2025 ctx.validateAndroidModule(bm, ctx.OtherModuleDependencyTag(m), ctx.baseModuleContext.strictVisitDeps)
Jooyung Hand48f3c32019-08-23 11:18:57 +09002026 }
2027 })
2028
Bob Badour37af0462021-01-07 03:34:31 +00002029 licensesPropertyFlattener(ctx)
2030 if ctx.Failed() {
2031 return
2032 }
2033
Chris Parsonsf874e462022-05-10 13:50:12 -04002034 if mixedBuildMod, handled := m.isHandledByBazel(ctx); handled {
2035 mixedBuildMod.ProcessBazelQueryResponse(ctx)
2036 } else {
2037 m.module.GenerateAndroidBuildActions(ctx)
2038 }
Jaewoong Jung5b425e22019-06-17 17:40:56 -07002039 if ctx.Failed() {
2040 return
2041 }
2042
Jiyong Park4d861072021-03-03 20:02:42 +09002043 m.initRcPaths = PathsForModuleSrc(ctx, m.commonProperties.Init_rc)
2044 rcDir := PathForModuleInstall(ctx, "etc", "init")
2045 for _, src := range m.initRcPaths {
2046 ctx.PackageFile(rcDir, filepath.Base(src.String()), src)
2047 }
2048
2049 m.vintfFragmentsPaths = PathsForModuleSrc(ctx, m.commonProperties.Vintf_fragments)
2050 vintfDir := PathForModuleInstall(ctx, "etc", "vintf", "manifest")
2051 for _, src := range m.vintfFragmentsPaths {
2052 ctx.PackageFile(vintfDir, filepath.Base(src.String()), src)
2053 }
2054
Paul Duffinaf970a22020-11-23 23:32:56 +00002055 // Create the set of tagged dist files after calling GenerateAndroidBuildActions
2056 // as GenerateTaggedDistFiles() calls OutputFiles(tag) and so relies on the
2057 // output paths being set which must be done before or during
2058 // GenerateAndroidBuildActions.
2059 m.distFiles = m.GenerateTaggedDistFiles(ctx)
2060 if ctx.Failed() {
2061 return
2062 }
2063
Jaewoong Jung5b425e22019-06-17 17:40:56 -07002064 m.installFiles = append(m.installFiles, ctx.installFiles...)
2065 m.checkbuildFiles = append(m.checkbuildFiles, ctx.checkbuildFiles...)
Jiyong Park073ea552020-11-09 14:08:34 +09002066 m.packagingSpecs = append(m.packagingSpecs, ctx.packagingSpecs...)
Colin Cross6301c3c2021-09-28 17:40:21 -07002067 m.katiInstalls = append(m.katiInstalls, ctx.katiInstalls...)
2068 m.katiSymlinks = append(m.katiSymlinks, ctx.katiSymlinks...)
Colin Cross5c1d5fb2023-11-15 12:39:40 -08002069 m.testData = append(m.testData, ctx.testData...)
Colin Crossdc35e212019-06-06 16:13:11 -07002070 } else if ctx.Config().AllowMissingDependencies() {
2071 // If the module is not enabled it will not create any build rules, nothing will call
2072 // ctx.GetMissingDependencies(), and blueprint will consider the missing dependencies to be unhandled
2073 // and report them as an error even when AllowMissingDependencies = true. Call
2074 // ctx.GetMissingDependencies() here to tell blueprint not to handle them.
2075 ctx.GetMissingDependencies()
Colin Cross3f40fa42015-01-30 17:27:36 -08002076 }
2077
Colin Cross4157e882019-06-06 16:57:04 -07002078 if m == ctx.FinalModule().(Module).base() {
2079 m.generateModuleTarget(ctx)
Colin Cross9b1d13d2016-09-19 15:18:11 -07002080 if ctx.Failed() {
2081 return
2082 }
Colin Cross3f40fa42015-01-30 17:27:36 -08002083 }
Colin Crosscec81712017-07-13 14:43:27 -07002084
Colin Crossc85750b2022-04-21 12:50:51 -07002085 m.installFilesDepSet = NewDepSet[InstallPath](TOPOLOGICAL, m.installFiles, dependencyInstallFiles)
2086 m.packagingSpecsDepSet = NewDepSet[PackagingSpec](TOPOLOGICAL, m.packagingSpecs, dependencyPackagingSpecs)
Colin Cross5d583952020-11-24 16:21:24 -08002087
Colin Crossaa1cab02022-01-28 14:49:24 -08002088 buildLicenseMetadata(ctx, m.licenseMetadataFile)
Colin Cross4acaea92021-12-10 23:05:02 +00002089
Colin Cross4157e882019-06-06 16:57:04 -07002090 m.buildParams = ctx.buildParams
2091 m.ruleParams = ctx.ruleParams
2092 m.variables = ctx.variables
Colin Cross3f40fa42015-01-30 17:27:36 -08002093}
2094
Chris Parsonsf874e462022-05-10 13:50:12 -04002095func (m *ModuleBase) isHandledByBazel(ctx ModuleContext) (MixedBuildBuildable, bool) {
Chris Parsonsf874e462022-05-10 13:50:12 -04002096 if mixedBuildMod, ok := m.module.(MixedBuildBuildable); ok {
MarkDacekf47e1422023-04-19 16:47:36 +00002097 if mixedBuildMod.IsMixedBuildSupported(ctx) && (MixedBuildsEnabled(ctx) == MixedBuildEnabled) {
Chris Parsonsf874e462022-05-10 13:50:12 -04002098 return mixedBuildMod, true
2099 }
2100 }
2101 return nil, false
2102}
2103
Paul Duffin89968e32020-11-23 18:17:03 +00002104// Check the supplied dist structure to make sure that it is valid.
2105//
2106// property - the base property, e.g. dist or dists[1], which is combined with the
2107// name of the nested property to produce the full property, e.g. dist.dest or
2108// dists[1].dir.
2109func checkDistProperties(ctx *moduleContext, property string, dist *Dist) {
2110 if dist.Dest != nil {
2111 _, err := validateSafePath(*dist.Dest)
2112 if err != nil {
2113 ctx.PropertyErrorf(property+".dest", "%s", err.Error())
2114 }
2115 }
2116 if dist.Dir != nil {
2117 _, err := validateSafePath(*dist.Dir)
2118 if err != nil {
2119 ctx.PropertyErrorf(property+".dir", "%s", err.Error())
2120 }
2121 }
2122 if dist.Suffix != nil {
2123 if strings.Contains(*dist.Suffix, "/") {
2124 ctx.PropertyErrorf(property+".suffix", "Suffix may not contain a '/' character.")
2125 }
2126 }
2127
2128}
2129
Colin Cross6301c3c2021-09-28 17:40:21 -07002130// katiInstall stores a request from Soong to Make to create an install rule.
2131type katiInstall struct {
2132 from Path
2133 to InstallPath
2134 implicitDeps Paths
2135 orderOnlyDeps Paths
2136 executable bool
Colin Cross50ed1f92021-11-12 17:41:02 -08002137 extraFiles *extraFilesZip
Colin Cross6301c3c2021-09-28 17:40:21 -07002138
2139 absFrom string
2140}
2141
Colin Cross50ed1f92021-11-12 17:41:02 -08002142type extraFilesZip struct {
2143 zip Path
2144 dir InstallPath
2145}
2146
Colin Cross6301c3c2021-09-28 17:40:21 -07002147type katiInstalls []katiInstall
2148
2149// BuiltInstalled returns the katiInstalls in the form used by $(call copy-many-files) in Make, a
2150// space separated list of from:to tuples.
2151func (installs katiInstalls) BuiltInstalled() string {
2152 sb := strings.Builder{}
2153 for i, install := range installs {
2154 if i != 0 {
2155 sb.WriteRune(' ')
2156 }
2157 sb.WriteString(install.from.String())
2158 sb.WriteRune(':')
2159 sb.WriteString(install.to.String())
2160 }
2161 return sb.String()
2162}
2163
2164// InstallPaths returns the install path of each entry.
2165func (installs katiInstalls) InstallPaths() InstallPaths {
2166 paths := make(InstallPaths, 0, len(installs))
2167 for _, install := range installs {
2168 paths = append(paths, install.to)
2169 }
2170 return paths
2171}
2172
Jiyong Park5baac542018-08-28 09:55:37 +09002173// Makes this module a platform module, i.e. not specific to soc, device,
Justin Yund5f6c822019-06-25 16:47:17 +09002174// product, or system_ext.
Colin Cross4157e882019-06-06 16:57:04 -07002175func (m *ModuleBase) MakeAsPlatform() {
2176 m.commonProperties.Vendor = boolPtr(false)
2177 m.commonProperties.Proprietary = boolPtr(false)
2178 m.commonProperties.Soc_specific = boolPtr(false)
2179 m.commonProperties.Product_specific = boolPtr(false)
Justin Yund5f6c822019-06-25 16:47:17 +09002180 m.commonProperties.System_ext_specific = boolPtr(false)
Jiyong Park5baac542018-08-28 09:55:37 +09002181}
2182
Sundong Ahnd95aa2d2019-10-08 19:34:03 +09002183func (m *ModuleBase) MakeAsSystemExt() {
Jooyung Han91df2082019-11-20 01:49:42 +09002184 m.commonProperties.Vendor = boolPtr(false)
2185 m.commonProperties.Proprietary = boolPtr(false)
2186 m.commonProperties.Soc_specific = boolPtr(false)
2187 m.commonProperties.Product_specific = boolPtr(false)
2188 m.commonProperties.System_ext_specific = boolPtr(true)
Sundong Ahnd95aa2d2019-10-08 19:34:03 +09002189}
2190
Jooyung Han344d5432019-08-23 11:17:39 +09002191// IsNativeBridgeSupported returns true if "native_bridge_supported" is explicitly set as "true"
2192func (m *ModuleBase) IsNativeBridgeSupported() bool {
2193 return proptools.Bool(m.commonProperties.Native_bridge_supported)
2194}
2195
Paul Duffine6ba0722021-07-12 20:12:12 +01002196// SrcIsModule decodes module references in the format ":unqualified-name" or "//namespace:name"
2197// into the module name, or empty string if the input was not a module reference.
Colin Cross41955e82019-05-29 14:40:35 -07002198func SrcIsModule(s string) (module string) {
Paul Duffine6ba0722021-07-12 20:12:12 +01002199 if len(s) > 1 {
2200 if s[0] == ':' {
2201 module = s[1:]
2202 if !isUnqualifiedModuleName(module) {
2203 // The module name should be unqualified but is not so do not treat it as a module.
2204 module = ""
2205 }
2206 } else if s[0] == '/' && s[1] == '/' {
2207 module = s
2208 }
Colin Cross068e0fe2016-12-13 15:23:47 -08002209 }
Paul Duffine6ba0722021-07-12 20:12:12 +01002210 return module
Colin Cross068e0fe2016-12-13 15:23:47 -08002211}
2212
Yi-Yo Chiangba9ea322021-07-15 17:18:21 +08002213// SrcIsModuleWithTag decodes module references in the format ":unqualified-name{.tag}" or
2214// "//namespace:name{.tag}" into the module name and tag, ":unqualified-name" or "//namespace:name"
2215// into the module name and an empty string for the tag, or empty strings if the input was not a
2216// module reference.
Colin Cross41955e82019-05-29 14:40:35 -07002217func SrcIsModuleWithTag(s string) (module, tag string) {
Paul Duffine6ba0722021-07-12 20:12:12 +01002218 if len(s) > 1 {
2219 if s[0] == ':' {
2220 module = s[1:]
2221 } else if s[0] == '/' && s[1] == '/' {
2222 module = s
2223 }
2224
2225 if module != "" {
2226 if tagStart := strings.IndexByte(module, '{'); tagStart > 0 {
2227 if module[len(module)-1] == '}' {
2228 tag = module[tagStart+1 : len(module)-1]
2229 module = module[:tagStart]
2230 }
2231 }
2232
2233 if s[0] == ':' && !isUnqualifiedModuleName(module) {
2234 // The module name should be unqualified but is not so do not treat it as a module.
2235 module = ""
2236 tag = ""
Colin Cross41955e82019-05-29 14:40:35 -07002237 }
2238 }
Colin Cross41955e82019-05-29 14:40:35 -07002239 }
Paul Duffine6ba0722021-07-12 20:12:12 +01002240
2241 return module, tag
2242}
2243
2244// isUnqualifiedModuleName makes sure that the supplied module is an unqualified module name, i.e.
2245// does not contain any /.
2246func isUnqualifiedModuleName(module string) bool {
2247 return strings.IndexByte(module, '/') == -1
Colin Cross068e0fe2016-12-13 15:23:47 -08002248}
2249
Paul Duffin40131a32021-07-09 17:10:35 +01002250// sourceOrOutputDependencyTag is the dependency tag added automatically by pathDepsMutator for any
2251// module reference in a property annotated with `android:"path"` or passed to ExtractSourceDeps
2252// or ExtractSourcesDeps.
2253//
2254// If uniquely identifies the dependency that was added as it contains both the module name used to
2255// add the dependency as well as the tag. That makes it very simple to find the matching dependency
2256// in GetModuleFromPathDep as all it needs to do is find the dependency whose tag matches the tag
2257// used to add it. It does not need to check that the module name as returned by one of
2258// Module.Name(), BaseModuleContext.OtherModuleName() or ModuleBase.BaseModuleName() matches the
2259// name supplied in the tag. That means it does not need to handle differences in module names
2260// caused by prebuilt_ prefix, or fully qualified module names.
Colin Cross41955e82019-05-29 14:40:35 -07002261type sourceOrOutputDependencyTag struct {
2262 blueprint.BaseDependencyTag
Paul Duffin40131a32021-07-09 17:10:35 +01002263
2264 // The name of the module.
2265 moduleName string
2266
2267 // The tag that will be passed to the module's OutputFileProducer.OutputFiles(tag) method.
Colin Cross41955e82019-05-29 14:40:35 -07002268 tag string
2269}
2270
Paul Duffin40131a32021-07-09 17:10:35 +01002271func sourceOrOutputDepTag(moduleName, tag string) blueprint.DependencyTag {
2272 return sourceOrOutputDependencyTag{moduleName: moduleName, tag: tag}
Colin Cross41955e82019-05-29 14:40:35 -07002273}
2274
Paul Duffind5cf92e2021-07-09 17:38:55 +01002275// IsSourceDepTagWithOutputTag returns true if the supplied blueprint.DependencyTag is one that was
2276// used to add dependencies by either ExtractSourceDeps, ExtractSourcesDeps or automatically for
2277// properties tagged with `android:"path"` AND it was added using a module reference of
2278// :moduleName{outputTag}.
2279func IsSourceDepTagWithOutputTag(depTag blueprint.DependencyTag, outputTag string) bool {
2280 t, ok := depTag.(sourceOrOutputDependencyTag)
2281 return ok && t.tag == outputTag
2282}
2283
Colin Cross366938f2017-12-11 16:29:02 -08002284// Adds necessary dependencies to satisfy filegroup or generated sources modules listed in srcFiles
2285// using ":module" syntax, if any.
Colin Cross27b922f2019-03-04 22:35:41 -08002286//
2287// Deprecated: tag the property with `android:"path"` instead.
Colin Cross068e0fe2016-12-13 15:23:47 -08002288func ExtractSourcesDeps(ctx BottomUpMutatorContext, srcFiles []string) {
Nan Zhang2439eb72017-04-10 11:27:50 -07002289 set := make(map[string]bool)
2290
Colin Cross068e0fe2016-12-13 15:23:47 -08002291 for _, s := range srcFiles {
Colin Cross41955e82019-05-29 14:40:35 -07002292 if m, t := SrcIsModuleWithTag(s); m != "" {
2293 if _, found := set[s]; found {
2294 ctx.ModuleErrorf("found source dependency duplicate: %q!", s)
Nan Zhang2439eb72017-04-10 11:27:50 -07002295 } else {
Colin Cross41955e82019-05-29 14:40:35 -07002296 set[s] = true
Paul Duffin40131a32021-07-09 17:10:35 +01002297 ctx.AddDependency(ctx.Module(), sourceOrOutputDepTag(m, t), m)
Nan Zhang2439eb72017-04-10 11:27:50 -07002298 }
Colin Cross068e0fe2016-12-13 15:23:47 -08002299 }
2300 }
Colin Cross068e0fe2016-12-13 15:23:47 -08002301}
2302
Colin Cross366938f2017-12-11 16:29:02 -08002303// Adds necessary dependencies to satisfy filegroup or generated sources modules specified in s
2304// using ":module" syntax, if any.
Colin Cross27b922f2019-03-04 22:35:41 -08002305//
2306// Deprecated: tag the property with `android:"path"` instead.
Colin Cross366938f2017-12-11 16:29:02 -08002307func ExtractSourceDeps(ctx BottomUpMutatorContext, s *string) {
2308 if s != nil {
Colin Cross41955e82019-05-29 14:40:35 -07002309 if m, t := SrcIsModuleWithTag(*s); m != "" {
Paul Duffin40131a32021-07-09 17:10:35 +01002310 ctx.AddDependency(ctx.Module(), sourceOrOutputDepTag(m, t), m)
Colin Cross366938f2017-12-11 16:29:02 -08002311 }
2312 }
2313}
2314
Colin Cross41955e82019-05-29 14:40:35 -07002315// A module that implements SourceFileProducer can be referenced from any property that is tagged with `android:"path"`
2316// using the ":module" syntax and provides a list of paths to be used as if they were listed in the property.
Colin Cross068e0fe2016-12-13 15:23:47 -08002317type SourceFileProducer interface {
2318 Srcs() Paths
2319}
2320
Colin Cross41955e82019-05-29 14:40:35 -07002321// A module that implements OutputFileProducer can be referenced from any property that is tagged with `android:"path"`
Roland Levillain97c1f342019-11-22 14:20:54 +00002322// using the ":module" syntax or ":module{.tag}" syntax and provides a list of output files to be used as if they were
Colin Cross41955e82019-05-29 14:40:35 -07002323// listed in the property.
2324type OutputFileProducer interface {
2325 OutputFiles(tag string) (Paths, error)
2326}
2327
Colin Cross5e708052019-08-06 13:59:50 -07002328// OutputFilesForModule returns the paths from an OutputFileProducer with the given tag. On error, including if the
2329// module produced zero paths, it reports errors to the ctx and returns nil.
2330func OutputFilesForModule(ctx PathContext, module blueprint.Module, tag string) Paths {
2331 paths, err := outputFilesForModule(ctx, module, tag)
2332 if err != nil {
2333 reportPathError(ctx, err)
2334 return nil
2335 }
2336 return paths
2337}
2338
2339// OutputFileForModule returns the path from an OutputFileProducer with the given tag. On error, including if the
2340// module produced zero or multiple paths, it reports errors to the ctx and returns nil.
2341func OutputFileForModule(ctx PathContext, module blueprint.Module, tag string) Path {
2342 paths, err := outputFilesForModule(ctx, module, tag)
2343 if err != nil {
2344 reportPathError(ctx, err)
2345 return nil
2346 }
Colin Cross14ec66c2022-10-03 21:02:27 -07002347 if len(paths) == 0 {
2348 type addMissingDependenciesIntf interface {
2349 AddMissingDependencies([]string)
2350 OtherModuleName(blueprint.Module) string
2351 }
2352 if mctx, ok := ctx.(addMissingDependenciesIntf); ok && ctx.Config().AllowMissingDependencies() {
2353 mctx.AddMissingDependencies([]string{mctx.OtherModuleName(module)})
2354 } else {
2355 ReportPathErrorf(ctx, "failed to get output files from module %q", pathContextName(ctx, module))
2356 }
2357 // Return a fake output file to avoid nil dereferences of Path objects later.
2358 // This should never get used for an actual build as the error or missing
2359 // dependency has already been reported.
2360 p, err := pathForSource(ctx, filepath.Join("missing_output_file", pathContextName(ctx, module)))
2361 if err != nil {
2362 reportPathError(ctx, err)
2363 return nil
2364 }
2365 return p
2366 }
Colin Cross5e708052019-08-06 13:59:50 -07002367 if len(paths) > 1 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01002368 ReportPathErrorf(ctx, "got multiple output files from module %q, expected exactly one",
Colin Cross5e708052019-08-06 13:59:50 -07002369 pathContextName(ctx, module))
Colin Cross5e708052019-08-06 13:59:50 -07002370 }
2371 return paths[0]
2372}
2373
2374func outputFilesForModule(ctx PathContext, module blueprint.Module, tag string) (Paths, error) {
2375 if outputFileProducer, ok := module.(OutputFileProducer); ok {
2376 paths, err := outputFileProducer.OutputFiles(tag)
2377 if err != nil {
2378 return nil, fmt.Errorf("failed to get output file from module %q: %s",
2379 pathContextName(ctx, module), err.Error())
2380 }
Colin Cross5e708052019-08-06 13:59:50 -07002381 return paths, nil
Colin Cross74b1e2b2020-11-22 20:23:02 -08002382 } else if sourceFileProducer, ok := module.(SourceFileProducer); ok {
2383 if tag != "" {
2384 return nil, fmt.Errorf("module %q is a SourceFileProducer, not an OutputFileProducer, and so does not support tag %q", pathContextName(ctx, module), tag)
2385 }
2386 paths := sourceFileProducer.Srcs()
Colin Cross74b1e2b2020-11-22 20:23:02 -08002387 return paths, nil
Colin Cross5e708052019-08-06 13:59:50 -07002388 } else {
2389 return nil, fmt.Errorf("module %q is not an OutputFileProducer", pathContextName(ctx, module))
2390 }
2391}
2392
Colin Cross41589502020-12-01 14:00:21 -08002393// Modules can implement HostToolProvider and return a valid OptionalPath from HostToolPath() to
2394// specify that they can be used as a tool by a genrule module.
Colin Crossfe17f6f2019-03-28 19:30:56 -07002395type HostToolProvider interface {
Colin Crossba9e4032020-11-24 16:32:22 -08002396 Module
Colin Cross41589502020-12-01 14:00:21 -08002397 // HostToolPath returns the path to the host tool for the module if it is one, or an invalid
2398 // OptionalPath.
Colin Crossfe17f6f2019-03-28 19:30:56 -07002399 HostToolPath() OptionalPath
2400}
2401
Colin Cross463a90e2015-06-17 14:20:06 -07002402func init() {
LaMont Jones0c10e4d2023-05-16 00:58:37 +00002403 RegisterParallelSingletonType("buildtarget", BuildTargetSingleton)
Inseob Kim81b00a82023-05-15 18:06:31 +09002404 RegisterParallelSingletonType("soongconfigtrace", soongConfigTraceSingletonFunc)
2405 FinalDepsMutators(registerSoongConfigTraceMutator)
Colin Cross463a90e2015-06-17 14:20:06 -07002406}
2407
Colin Cross0875c522017-11-28 17:34:01 -08002408func BuildTargetSingleton() Singleton {
Colin Cross1f8c52b2015-06-16 16:38:17 -07002409 return &buildTargetSingleton{}
2410}
2411
Colin Cross87d8b562017-04-25 10:01:55 -07002412func parentDir(dir string) string {
2413 dir, _ = filepath.Split(dir)
2414 return filepath.Clean(dir)
2415}
2416
Colin Cross1f8c52b2015-06-16 16:38:17 -07002417type buildTargetSingleton struct{}
2418
Chih-Hung Hsieh80783772021-10-11 16:46:56 -07002419func AddAncestors(ctx SingletonContext, dirMap map[string]Paths, mmName func(string) string) ([]string, []string) {
Chih-Hung Hsiehd0f82fe2021-09-05 20:15:38 -07002420 // Ensure ancestor directories are in dirMap
2421 // Make directories build their direct subdirectories
Chih-Hung Hsieh80783772021-10-11 16:46:56 -07002422 // Returns a slice of all directories and a slice of top-level directories.
Cole Faust18994c72023-02-28 16:02:16 -08002423 dirs := SortedKeys(dirMap)
Chih-Hung Hsiehd0f82fe2021-09-05 20:15:38 -07002424 for _, dir := range dirs {
2425 dir := parentDir(dir)
2426 for dir != "." && dir != "/" {
2427 if _, exists := dirMap[dir]; exists {
2428 break
2429 }
2430 dirMap[dir] = nil
2431 dir = parentDir(dir)
2432 }
2433 }
Cole Faust18994c72023-02-28 16:02:16 -08002434 dirs = SortedKeys(dirMap)
Chih-Hung Hsieh80783772021-10-11 16:46:56 -07002435 var topDirs []string
Chih-Hung Hsiehd0f82fe2021-09-05 20:15:38 -07002436 for _, dir := range dirs {
2437 p := parentDir(dir)
2438 if p != "." && p != "/" {
2439 dirMap[p] = append(dirMap[p], PathForPhony(ctx, mmName(dir)))
Chih-Hung Hsieh80783772021-10-11 16:46:56 -07002440 } else if dir != "." && dir != "/" && dir != "" {
2441 topDirs = append(topDirs, dir)
Chih-Hung Hsiehd0f82fe2021-09-05 20:15:38 -07002442 }
2443 }
Cole Faust18994c72023-02-28 16:02:16 -08002444 return SortedKeys(dirMap), topDirs
Chih-Hung Hsiehd0f82fe2021-09-05 20:15:38 -07002445}
2446
Colin Cross0875c522017-11-28 17:34:01 -08002447func (c *buildTargetSingleton) GenerateBuildActions(ctx SingletonContext) {
2448 var checkbuildDeps Paths
Colin Cross1f8c52b2015-06-16 16:38:17 -07002449
Colin Crossc3d87d32020-06-04 13:25:17 -07002450 mmTarget := func(dir string) string {
2451 return "MODULES-IN-" + strings.Replace(filepath.Clean(dir), "/", "-", -1)
Colin Cross87d8b562017-04-25 10:01:55 -07002452 }
2453
Colin Cross0875c522017-11-28 17:34:01 -08002454 modulesInDir := make(map[string]Paths)
Colin Cross1f8c52b2015-06-16 16:38:17 -07002455
Colin Cross0875c522017-11-28 17:34:01 -08002456 ctx.VisitAllModules(func(module Module) {
2457 blueprintDir := module.base().blueprintDir
2458 installTarget := module.base().installTarget
2459 checkbuildTarget := module.base().checkbuildTarget
Colin Cross1f8c52b2015-06-16 16:38:17 -07002460
Colin Cross0875c522017-11-28 17:34:01 -08002461 if checkbuildTarget != nil {
2462 checkbuildDeps = append(checkbuildDeps, checkbuildTarget)
2463 modulesInDir[blueprintDir] = append(modulesInDir[blueprintDir], checkbuildTarget)
2464 }
Colin Cross1f8c52b2015-06-16 16:38:17 -07002465
Colin Cross0875c522017-11-28 17:34:01 -08002466 if installTarget != nil {
2467 modulesInDir[blueprintDir] = append(modulesInDir[blueprintDir], installTarget)
Colin Cross1f8c52b2015-06-16 16:38:17 -07002468 }
2469 })
2470
Dan Willemsen5ba07e82015-12-11 13:51:06 -08002471 suffix := ""
Jingwen Chencda22c92020-11-23 00:22:30 -05002472 if ctx.Config().KatiEnabled() {
Dan Willemsen5ba07e82015-12-11 13:51:06 -08002473 suffix = "-soong"
2474 }
2475
Colin Cross1f8c52b2015-06-16 16:38:17 -07002476 // Create a top-level checkbuild target that depends on all modules
Colin Crossc3d87d32020-06-04 13:25:17 -07002477 ctx.Phony("checkbuild"+suffix, checkbuildDeps...)
Colin Cross1f8c52b2015-06-16 16:38:17 -07002478
Dan Willemsend2e95fb2017-09-20 14:30:50 -07002479 // Make will generate the MODULES-IN-* targets
Jingwen Chencda22c92020-11-23 00:22:30 -05002480 if ctx.Config().KatiEnabled() {
Dan Willemsend2e95fb2017-09-20 14:30:50 -07002481 return
2482 }
2483
Chih-Hung Hsieh80783772021-10-11 16:46:56 -07002484 dirs, _ := AddAncestors(ctx, modulesInDir, mmTarget)
Colin Cross87d8b562017-04-25 10:01:55 -07002485
Dan Willemsend2e95fb2017-09-20 14:30:50 -07002486 // Create a MODULES-IN-<directory> target that depends on all modules in a directory, and
2487 // depends on the MODULES-IN-* targets of all of its subdirectories that contain Android.bp
2488 // files.
Colin Cross1f8c52b2015-06-16 16:38:17 -07002489 for _, dir := range dirs {
Colin Crossc3d87d32020-06-04 13:25:17 -07002490 ctx.Phony(mmTarget(dir), modulesInDir[dir]...)
Colin Cross1f8c52b2015-06-16 16:38:17 -07002491 }
Dan Willemsen61d88b82017-09-20 17:29:08 -07002492
2493 // Create (host|host-cross|target)-<OS> phony rules to build a reduced checkbuild.
Jiyong Park1613e552020-09-14 19:43:17 +09002494 type osAndCross struct {
2495 os OsType
2496 hostCross bool
2497 }
2498 osDeps := map[osAndCross]Paths{}
Colin Cross0875c522017-11-28 17:34:01 -08002499 ctx.VisitAllModules(func(module Module) {
2500 if module.Enabled() {
Jiyong Park1613e552020-09-14 19:43:17 +09002501 key := osAndCross{os: module.Target().Os, hostCross: module.Target().HostCross}
2502 osDeps[key] = append(osDeps[key], module.base().checkbuildFiles...)
Dan Willemsen61d88b82017-09-20 17:29:08 -07002503 }
2504 })
2505
Colin Cross0875c522017-11-28 17:34:01 -08002506 osClass := make(map[string]Paths)
Jiyong Park1613e552020-09-14 19:43:17 +09002507 for key, deps := range osDeps {
Dan Willemsen61d88b82017-09-20 17:29:08 -07002508 var className string
2509
Jiyong Park1613e552020-09-14 19:43:17 +09002510 switch key.os.Class {
Dan Willemsen61d88b82017-09-20 17:29:08 -07002511 case Host:
Jiyong Park1613e552020-09-14 19:43:17 +09002512 if key.hostCross {
2513 className = "host-cross"
2514 } else {
2515 className = "host"
2516 }
Dan Willemsen61d88b82017-09-20 17:29:08 -07002517 case Device:
2518 className = "target"
2519 default:
2520 continue
2521 }
2522
Jiyong Park1613e552020-09-14 19:43:17 +09002523 name := className + "-" + key.os.Name
Colin Crossc3d87d32020-06-04 13:25:17 -07002524 osClass[className] = append(osClass[className], PathForPhony(ctx, name))
Dan Willemsen61d88b82017-09-20 17:29:08 -07002525
Colin Crossc3d87d32020-06-04 13:25:17 -07002526 ctx.Phony(name, deps...)
Dan Willemsen61d88b82017-09-20 17:29:08 -07002527 }
2528
2529 // Wrap those into host|host-cross|target phony rules
Cole Faust18994c72023-02-28 16:02:16 -08002530 for _, class := range SortedKeys(osClass) {
Colin Crossc3d87d32020-06-04 13:25:17 -07002531 ctx.Phony(class, osClass[class]...)
Dan Willemsen61d88b82017-09-20 17:29:08 -07002532 }
Colin Cross1f8c52b2015-06-16 16:38:17 -07002533}
Colin Crossd779da42015-12-17 18:00:23 -08002534
Brandon Lee5d45c6f2018-08-15 15:35:38 -07002535// Collect information for opening IDE project files in java/jdeps.go.
2536type IDEInfo interface {
2537 IDEInfo(ideInfo *IdeInfo)
2538 BaseModuleName() string
2539}
2540
2541// Extract the base module name from the Import name.
2542// Often the Import name has a prefix "prebuilt_".
2543// Remove the prefix explicitly if needed
2544// until we find a better solution to get the Import name.
2545type IDECustomizedModuleName interface {
2546 IDECustomizedModuleName() string
2547}
2548
2549type IdeInfo struct {
2550 Deps []string `json:"dependencies,omitempty"`
2551 Srcs []string `json:"srcs,omitempty"`
2552 Aidl_include_dirs []string `json:"aidl_include_dirs,omitempty"`
2553 Jarjar_rules []string `json:"jarjar_rules,omitempty"`
2554 Jars []string `json:"jars,omitempty"`
2555 Classes []string `json:"class,omitempty"`
2556 Installed_paths []string `json:"installed,omitempty"`
patricktu18c82ff2019-05-10 15:48:50 +08002557 SrcJars []string `json:"srcjars,omitempty"`
bralee1fbf4402020-05-21 10:11:59 +08002558 Paths []string `json:"path,omitempty"`
Yikef6282022022-04-13 20:41:01 +08002559 Static_libs []string `json:"static_libs,omitempty"`
2560 Libs []string `json:"libs,omitempty"`
Brandon Lee5d45c6f2018-08-15 15:35:38 -07002561}
Paul Duffinf88d8e02020-05-07 20:21:34 +01002562
2563func CheckBlueprintSyntax(ctx BaseModuleContext, filename string, contents string) []error {
2564 bpctx := ctx.blueprintBaseModuleContext()
2565 return blueprint.CheckBlueprintSyntax(bpctx.ModuleFactories(), filename, contents)
2566}
Colin Cross5d583952020-11-24 16:21:24 -08002567
Inseob Kim81b00a82023-05-15 18:06:31 +09002568func registerSoongConfigTraceMutator(ctx RegisterMutatorsContext) {
2569 ctx.BottomUp("soongconfigtrace", soongConfigTraceMutator).Parallel()
2570}
2571
2572// soongConfigTraceMutator accumulates recorded soong_config trace from children. Also it normalizes
2573// SoongConfigTrace to make it consistent.
2574func soongConfigTraceMutator(ctx BottomUpMutatorContext) {
2575 trace := &ctx.Module().base().commonProperties.SoongConfigTrace
2576 ctx.VisitDirectDeps(func(m Module) {
2577 childTrace := &m.base().commonProperties.SoongConfigTrace
2578 trace.Bools = append(trace.Bools, childTrace.Bools...)
2579 trace.Strings = append(trace.Strings, childTrace.Strings...)
2580 trace.IsSets = append(trace.IsSets, childTrace.IsSets...)
2581 })
2582 trace.Bools = SortedUniqueStrings(trace.Bools)
2583 trace.Strings = SortedUniqueStrings(trace.Strings)
2584 trace.IsSets = SortedUniqueStrings(trace.IsSets)
2585
2586 ctx.Module().base().commonProperties.SoongConfigTraceHash = trace.hash()
2587}
2588
2589// soongConfigTraceSingleton writes a map from each module's config hash value to trace data.
2590func soongConfigTraceSingletonFunc() Singleton {
2591 return &soongConfigTraceSingleton{}
2592}
2593
2594type soongConfigTraceSingleton struct {
2595}
2596
2597func (s *soongConfigTraceSingleton) GenerateBuildActions(ctx SingletonContext) {
2598 outFile := PathForOutput(ctx, "soong_config_trace.json")
2599
2600 traces := make(map[string]*soongConfigTrace)
2601 ctx.VisitAllModules(func(module Module) {
2602 trace := &module.base().commonProperties.SoongConfigTrace
2603 if !trace.isEmpty() {
2604 hash := module.base().commonProperties.SoongConfigTraceHash
2605 traces[hash] = trace
2606 }
2607 })
2608
2609 j, err := json.Marshal(traces)
2610 if err != nil {
2611 ctx.Errorf("json marshal to %q failed: %#v", outFile, err)
2612 return
2613 }
2614
2615 WriteFileRule(ctx, outFile, string(j))
2616 ctx.Phony("soong_config_trace", outFile)
2617}
Spandan Das370f13c2023-05-31 22:03:33 +00002618
2619// Interface implemented by xsd_config which has 1:many mappings in bp2build workspace
2620// This interface exists because we want to
2621// 1. Determine the name of the additional targets generated by the primary soong module
2622// 2. Enable distinguishing an xsd_config module from other Soong modules using type assertion
2623type XsdConfigBp2buildTargets interface {
2624 CppBp2buildTargetName() string
2625 JavaBp2buildTargetName() string
2626}
2627
Liz Kammer5f5dbaa2023-07-17 17:44:08 -04002628// XsdModuleToTargetName is a function that takes an XsdConfigBp2buildTarget
2629type XsdModuleToTargetName func(xsd XsdConfigBp2buildTargets) string
2630
2631// XsdLabelMapper returns a bazel.LabelMapper for partitioning XSD sources/headers given an
2632// XsdModuleToTargetName function.
2633func XsdLabelMapper(targetName XsdModuleToTargetName) bazel.LabelMapper {
2634 return func(ctx bazel.OtherModuleContext, label bazel.Label) (string, bool) {
2635 mod, exists := ctx.ModuleFromName(label.OriginalModuleName)
Spandan Das370f13c2023-05-31 22:03:33 +00002636 if !exists {
Liz Kammer5f5dbaa2023-07-17 17:44:08 -04002637 return label.Label, false
Spandan Das370f13c2023-05-31 22:03:33 +00002638 }
Liz Kammer5f5dbaa2023-07-17 17:44:08 -04002639 xsdMod, isXsd := mod.(XsdConfigBp2buildTargets)
2640 if !isXsd {
2641 return label.Label, false
Spandan Das370f13c2023-05-31 22:03:33 +00002642 }
Spandan Das370f13c2023-05-31 22:03:33 +00002643
Liz Kammer5f5dbaa2023-07-17 17:44:08 -04002644 // Remove the base module name
2645 ret := strings.TrimSuffix(label.Label, mod.Name())
2646 // Append the language specific target name
2647 ret += targetName(xsdMod)
2648 return ret, true
Spandan Das370f13c2023-05-31 22:03:33 +00002649 }
Spandan Das370f13c2023-05-31 22:03:33 +00002650}