blob: d8f4f77c59437b18e9fc841dc38fbb7911b486ee [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 Cross6ff51382015-12-17 16:39:19 -080018 "fmt"
Bob Badour4101c712022-02-09 11:54:35 -080019 "net/url"
Colin Cross988414c2020-01-11 01:11:46 +000020 "os"
Alex Lightfb4353d2019-01-17 13:57:45 -080021 "path"
Colin Cross3f40fa42015-01-30 17:27:36 -080022 "path/filepath"
Liz Kammer9525e712022-01-05 13:46:24 -050023 "reflect"
Jiyong Park1c7e9622020-05-07 16:12:13 +090024 "regexp"
Bob Badour4101c712022-02-09 11:54:35 -080025 "sort"
Colin Cross6ff51382015-12-17 16:39:19 -080026 "strings"
Colin Crossaabf6792017-11-29 00:27:14 -080027 "text/scanner"
Colin Crossf6566ed2015-03-24 11:13:38 -070028
Paul Duffinb42fa672021-09-09 16:37:49 +010029 "android/soong/bazel"
Tahsin Loqman77dc7d02022-12-19 16:27:25 +000030
Colin Crossf6566ed2015-03-24 11:13:38 -070031 "github.com/google/blueprint"
Colin Crossfe4bc362018-09-12 10:02:13 -070032 "github.com/google/blueprint/proptools"
Colin Cross3f40fa42015-01-30 17:27:36 -080033)
34
35var (
36 DeviceSharedLibrary = "shared_library"
37 DeviceStaticLibrary = "static_library"
Colin Cross3f40fa42015-01-30 17:27:36 -080038)
39
Liz Kammerdaefe0c2023-03-15 16:50:18 -040040// BuildParameters describes the set of potential parameters to build a Ninja rule.
41// In general, these correspond to a Ninja concept.
Colin Crossae887032017-10-23 17:16:14 -070042type BuildParams struct {
Liz Kammerdaefe0c2023-03-15 16:50:18 -040043 // A Ninja Rule that will be written to the Ninja file. This allows factoring out common code
44 // among multiple modules to reduce repetition in the Ninja file of action requirements. A rule
45 // can contain variables that should be provided in Args.
46 Rule blueprint.Rule
47 // Deps represents the depfile format. When using RuleBuilder, this defaults to GCC when depfiles
48 // are used.
49 Deps blueprint.Deps
50 // Depfile is a writeable path that allows correct incremental builds when the inputs have not
51 // been fully specified by the Ninja rule. Ninja supports a subset of the Makefile depfile syntax.
52 Depfile WritablePath
53 // A description of the build action.
54 Description string
55 // Output is an output file of the action. When using this field, references to $out in the Ninja
56 // command will refer to this file.
57 Output WritablePath
58 // Outputs is a slice of output file of the action. When using this field, references to $out in
59 // the Ninja command will refer to these files.
60 Outputs WritablePaths
61 // SymlinkOutput is an output file specifically that is a symlink.
62 SymlinkOutput WritablePath
63 // SymlinkOutputs is a slice of output files specifically that is a symlink.
64 SymlinkOutputs WritablePaths
65 // ImplicitOutput is an output file generated by the action. Note: references to `$out` in the
66 // Ninja command will NOT include references to this file.
67 ImplicitOutput WritablePath
68 // ImplicitOutputs is a slice of output files generated by the action. Note: references to `$out`
69 // in the Ninja command will NOT include references to these files.
Dan Willemsen9f3c5742016-11-03 14:28:31 -070070 ImplicitOutputs WritablePaths
Liz Kammerdaefe0c2023-03-15 16:50:18 -040071 // Input is an input file to the Ninja action. When using this field, references to $in in the
72 // Ninja command will refer to this file.
73 Input Path
74 // Inputs is a slice of input files to the Ninja action. When using this field, references to $in
75 // in the Ninja command will refer to these files.
76 Inputs Paths
77 // Implicit is an input file to the Ninja action. Note: references to `$in` in the Ninja command
78 // will NOT include references to this file.
79 Implicit Path
80 // Implicits is a slice of input files to the Ninja action. Note: references to `$in` in the Ninja
81 // command will NOT include references to these files.
82 Implicits Paths
83 // OrderOnly are Ninja order-only inputs to the action. When these are out of date, the output is
84 // not rebuilt until they are built, but changes in order-only dependencies alone do not cause the
85 // output to be rebuilt.
86 OrderOnly Paths
87 // Validation is an output path for a validation action. Validation outputs imply lower
88 // non-blocking priority to building non-validation outputs.
89 Validation Path
90 // Validations is a slice of output path for a validation action. Validation outputs imply lower
91 // non-blocking priority to building non-validation outputs.
92 Validations Paths
93 // Whether to skip outputting a default target statement which will be built by Ninja when no
94 // targets are specified on Ninja's command line.
95 Default bool
96 // Args is a key value mapping for replacements of variables within the Rule
97 Args map[string]string
Dan Willemsen34cc69e2015-09-23 15:26:20 -070098}
99
Colin Crossae887032017-10-23 17:16:14 -0700100type ModuleBuildParams BuildParams
101
Colin Cross1184b642019-12-30 18:43:07 -0800102// EarlyModuleContext provides methods that can be called early, as soon as the properties have
103// been parsed into the module and before any mutators have run.
104type EarlyModuleContext interface {
Colin Cross9f35c3d2020-09-16 19:04:41 -0700105 // Module returns the current module as a Module. It should rarely be necessary, as the module already has a
106 // reference to itself.
Colin Cross1184b642019-12-30 18:43:07 -0800107 Module() Module
Colin Cross9f35c3d2020-09-16 19:04:41 -0700108
109 // ModuleName returns the name of the module. This is generally the value that was returned by Module.Name() when
110 // the module was created, but may have been modified by calls to BaseMutatorContext.Rename.
Colin Cross1184b642019-12-30 18:43:07 -0800111 ModuleName() string
Colin Cross9f35c3d2020-09-16 19:04:41 -0700112
113 // ModuleDir returns the path to the directory that contains the definition of the module.
Colin Cross1184b642019-12-30 18:43:07 -0800114 ModuleDir() string
Colin Cross9f35c3d2020-09-16 19:04:41 -0700115
116 // ModuleType returns the name of the module type that was used to create the module, as specified in
117 // RegisterModuleType.
Colin Cross1184b642019-12-30 18:43:07 -0800118 ModuleType() string
Colin Cross9f35c3d2020-09-16 19:04:41 -0700119
120 // BlueprintFile returns the name of the blueprint file that contains the definition of this
121 // module.
Colin Cross9d34f352019-11-22 16:03:51 -0800122 BlueprintsFile() string
Colin Cross1184b642019-12-30 18:43:07 -0800123
Colin Cross9f35c3d2020-09-16 19:04:41 -0700124 // ContainsProperty returns true if the specified property name was set in the module definition.
Colin Cross1184b642019-12-30 18:43:07 -0800125 ContainsProperty(name string) bool
Colin Cross9f35c3d2020-09-16 19:04:41 -0700126
127 // Errorf reports an error at the specified position of the module definition file.
Colin Cross1184b642019-12-30 18:43:07 -0800128 Errorf(pos scanner.Position, fmt string, args ...interface{})
Colin Cross9f35c3d2020-09-16 19:04:41 -0700129
130 // ModuleErrorf reports an error at the line number of the module type in the module definition.
Colin Cross1184b642019-12-30 18:43:07 -0800131 ModuleErrorf(fmt string, args ...interface{})
Colin Cross9f35c3d2020-09-16 19:04:41 -0700132
133 // PropertyErrorf reports an error at the line number of a property in the module definition.
Colin Cross1184b642019-12-30 18:43:07 -0800134 PropertyErrorf(property, fmt string, args ...interface{})
Colin Cross9f35c3d2020-09-16 19:04:41 -0700135
136 // Failed returns true if any errors have been reported. In most cases the module can continue with generating
137 // build rules after an error, allowing it to report additional errors in a single run, but in cases where the error
138 // has prevented the module from creating necessary data it can return early when Failed returns true.
Colin Cross1184b642019-12-30 18:43:07 -0800139 Failed() bool
140
Colin Cross9f35c3d2020-09-16 19:04:41 -0700141 // AddNinjaFileDeps adds dependencies on the specified files to the rule that creates the ninja manifest. The
142 // primary builder will be rerun whenever the specified files are modified.
Colin Cross1184b642019-12-30 18:43:07 -0800143 AddNinjaFileDeps(deps ...string)
144
145 DeviceSpecific() bool
146 SocSpecific() bool
147 ProductSpecific() bool
148 SystemExtSpecific() bool
149 Platform() bool
150
151 Config() Config
152 DeviceConfig() DeviceConfig
153
154 // Deprecated: use Config()
155 AConfig() Config
156
157 // GlobWithDeps returns a list of files that match the specified pattern but do not match any
158 // of the patterns in excludes. It also adds efficient dependencies to rerun the primary
159 // builder whenever a file matching the pattern as added or removed, without rerunning if a
160 // file that does not match the pattern is added to a searched directory.
161 GlobWithDeps(pattern string, excludes []string) ([]string, error)
162
163 Glob(globPattern string, excludes []string) Paths
164 GlobFiles(globPattern string, excludes []string) Paths
Colin Cross988414c2020-01-11 01:11:46 +0000165 IsSymlink(path Path) bool
166 Readlink(path Path) string
Colin Cross133ebef2020-08-14 17:38:45 -0700167
Colin Cross9f35c3d2020-09-16 19:04:41 -0700168 // Namespace returns the Namespace object provided by the NameInterface set by Context.SetNameInterface, or the
169 // default SimpleNameInterface if Context.SetNameInterface was not called.
Colin Cross133ebef2020-08-14 17:38:45 -0700170 Namespace() *Namespace
Colin Cross1184b642019-12-30 18:43:07 -0800171}
172
Colin Cross0ea8ba82019-06-06 14:33:29 -0700173// BaseModuleContext is the same as blueprint.BaseModuleContext except that Config() returns
Colin Crossdc35e212019-06-06 16:13:11 -0700174// a Config instead of an interface{}, and some methods have been wrapped to use an android.Module
175// instead of a blueprint.Module, plus some extra methods that return Android-specific information
Colin Cross0ea8ba82019-06-06 14:33:29 -0700176// about the current module.
177type BaseModuleContext interface {
Colin Cross1184b642019-12-30 18:43:07 -0800178 EarlyModuleContext
Colin Cross0ea8ba82019-06-06 14:33:29 -0700179
Paul Duffinf88d8e02020-05-07 20:21:34 +0100180 blueprintBaseModuleContext() blueprint.BaseModuleContext
181
Colin Cross9f35c3d2020-09-16 19:04:41 -0700182 // OtherModuleName returns the name of another Module. See BaseModuleContext.ModuleName for more information.
183 // It is intended for use inside the visit functions of Visit* and WalkDeps.
Colin Crossdc35e212019-06-06 16:13:11 -0700184 OtherModuleName(m blueprint.Module) string
Colin Cross9f35c3d2020-09-16 19:04:41 -0700185
186 // OtherModuleDir returns the directory of another Module. See BaseModuleContext.ModuleDir for more information.
187 // It is intended for use inside the visit functions of Visit* and WalkDeps.
Colin Crossdc35e212019-06-06 16:13:11 -0700188 OtherModuleDir(m blueprint.Module) string
Colin Cross9f35c3d2020-09-16 19:04:41 -0700189
190 // OtherModuleErrorf reports an error on another Module. See BaseModuleContext.ModuleErrorf for more information.
191 // It is intended for use inside the visit functions of Visit* and WalkDeps.
Colin Crossdc35e212019-06-06 16:13:11 -0700192 OtherModuleErrorf(m blueprint.Module, fmt string, args ...interface{})
Colin Cross9f35c3d2020-09-16 19:04:41 -0700193
194 // OtherModuleDependencyTag returns the dependency tag used to depend on a module, or nil if there is no dependency
195 // on the module. When called inside a Visit* method with current module being visited, and there are multiple
196 // dependencies on the module being visited, it returns the dependency tag used for the current dependency.
Colin Crossdc35e212019-06-06 16:13:11 -0700197 OtherModuleDependencyTag(m blueprint.Module) blueprint.DependencyTag
Colin Cross9f35c3d2020-09-16 19:04:41 -0700198
199 // OtherModuleExists returns true if a module with the specified name exists, as determined by the NameInterface
200 // passed to Context.SetNameInterface, or SimpleNameInterface if it was not called.
Colin Crossdc35e212019-06-06 16:13:11 -0700201 OtherModuleExists(name string) bool
Colin Cross9f35c3d2020-09-16 19:04:41 -0700202
203 // OtherModuleDependencyVariantExists returns true if a module with the
204 // specified name and variant exists. The variant must match the given
205 // variations. It must also match all the non-local variations of the current
Martin Stjernholm408ffd82021-05-05 15:27:31 +0100206 // module. In other words, it checks for the module that AddVariationDependencies
Colin Cross9f35c3d2020-09-16 19:04:41 -0700207 // would add a dependency on with the same arguments.
Martin Stjernholm009a9dc2020-03-05 17:34:13 +0000208 OtherModuleDependencyVariantExists(variations []blueprint.Variation, name string) bool
Colin Cross9f35c3d2020-09-16 19:04:41 -0700209
Martin Stjernholm408ffd82021-05-05 15:27:31 +0100210 // OtherModuleFarDependencyVariantExists returns true if a module with the
211 // specified name and variant exists. The variant must match the given
212 // variations, but not the non-local variations of the current module. In
213 // other words, it checks for the module that AddFarVariationDependencies
214 // would add a dependency on with the same arguments.
215 OtherModuleFarDependencyVariantExists(variations []blueprint.Variation, name string) bool
216
Colin Cross9f35c3d2020-09-16 19:04:41 -0700217 // OtherModuleReverseDependencyVariantExists returns true if a module with the
218 // specified name exists with the same variations as the current module. In
Martin Stjernholm408ffd82021-05-05 15:27:31 +0100219 // other words, it checks for the module that AddReverseDependency would add a
Colin Cross9f35c3d2020-09-16 19:04:41 -0700220 // dependency on with the same argument.
Martin Stjernholm009a9dc2020-03-05 17:34:13 +0000221 OtherModuleReverseDependencyVariantExists(name string) bool
Colin Cross9f35c3d2020-09-16 19:04:41 -0700222
223 // OtherModuleType returns the type of another Module. See BaseModuleContext.ModuleType for more information.
224 // It is intended for use inside the visit functions of Visit* and WalkDeps.
Jiyong Park9e6c2422019-08-09 20:39:45 +0900225 OtherModuleType(m blueprint.Module) string
Colin Crossdc35e212019-06-06 16:13:11 -0700226
Colin Crossd27e7b82020-07-02 11:38:17 -0700227 // OtherModuleProvider returns the value for a provider for the given module. If the value is
228 // not set it returns the zero value of the type of the provider, so the return value can always
229 // be type asserted to the type of the provider. The value returned may be a deep copy of the
230 // value originally passed to SetProvider.
231 OtherModuleProvider(m blueprint.Module, provider blueprint.ProviderKey) interface{}
232
233 // OtherModuleHasProvider returns true if the provider for the given module has been set.
234 OtherModuleHasProvider(m blueprint.Module, provider blueprint.ProviderKey) bool
235
236 // Provider returns the value for a provider for the current module. If the value is
237 // not set it returns the zero value of the type of the provider, so the return value can always
238 // be type asserted to the type of the provider. It panics if called before the appropriate
239 // mutator or GenerateBuildActions pass for the provider. The value returned may be a deep
240 // copy of the value originally passed to SetProvider.
241 Provider(provider blueprint.ProviderKey) interface{}
242
243 // HasProvider returns true if the provider for the current module has been set.
244 HasProvider(provider blueprint.ProviderKey) bool
245
246 // SetProvider sets the value for a provider for the current module. It panics if not called
247 // during the appropriate mutator or GenerateBuildActions pass for the provider, if the value
248 // is not of the appropriate type, or if the value has already been set. The value should not
249 // be modified after being passed to SetProvider.
250 SetProvider(provider blueprint.ProviderKey, value interface{})
251
Colin Crossdc35e212019-06-06 16:13:11 -0700252 GetDirectDepsWithTag(tag blueprint.DependencyTag) []Module
Colin Cross9f35c3d2020-09-16 19:04:41 -0700253
254 // GetDirectDepWithTag returns the Module the direct dependency with the specified name, or nil if
255 // none exists. It panics if the dependency does not have the specified tag. It skips any
256 // dependencies that are not an android.Module.
Colin Crossdc35e212019-06-06 16:13:11 -0700257 GetDirectDepWithTag(name string, tag blueprint.DependencyTag) blueprint.Module
Colin Cross9f35c3d2020-09-16 19:04:41 -0700258
259 // GetDirectDep returns the Module and DependencyTag for the direct dependency with the specified
260 // name, or nil if none exists. If there are multiple dependencies on the same module it returns
Liz Kammer2b50ce62021-04-26 15:47:28 -0400261 // the first DependencyTag.
Colin Crossdc35e212019-06-06 16:13:11 -0700262 GetDirectDep(name string) (blueprint.Module, blueprint.DependencyTag)
263
Chris Parsons5a34ffb2021-07-21 14:34:58 -0400264 ModuleFromName(name string) (blueprint.Module, bool)
265
Colin Cross9f35c3d2020-09-16 19:04:41 -0700266 // VisitDirectDepsBlueprint calls visit for each direct dependency. If there are multiple
267 // direct dependencies on the same module visit will be called multiple times on that module
268 // and OtherModuleDependencyTag will return a different tag for each.
269 //
270 // The Module passed to the visit function should not be retained outside of the visit
271 // function, it may be invalidated by future mutators.
Colin Crossdc35e212019-06-06 16:13:11 -0700272 VisitDirectDepsBlueprint(visit func(blueprint.Module))
Colin Cross9f35c3d2020-09-16 19:04:41 -0700273
274 // VisitDirectDeps calls visit for each direct dependency. If there are multiple
275 // direct dependencies on the same module visit will be called multiple times on that module
Spandan Dasda7f3622021-08-04 20:50:04 +0000276 // and OtherModuleDependencyTag will return a different tag for each. It raises an error if any of the
277 // dependencies are not an android.Module.
Colin Cross9f35c3d2020-09-16 19:04:41 -0700278 //
279 // The Module passed to the visit function should not be retained outside of the visit
280 // function, it may be invalidated by future mutators.
Colin Crossdc35e212019-06-06 16:13:11 -0700281 VisitDirectDeps(visit func(Module))
Colin Cross9f35c3d2020-09-16 19:04:41 -0700282
Colin Crossdc35e212019-06-06 16:13:11 -0700283 VisitDirectDepsWithTag(tag blueprint.DependencyTag, visit func(Module))
Colin Cross9f35c3d2020-09-16 19:04:41 -0700284
285 // VisitDirectDepsIf calls pred for each direct dependency, and if pred returns true calls visit. If there are
286 // multiple direct dependencies on the same module pred and visit will be called multiple times on that module and
287 // OtherModuleDependencyTag will return a different tag for each. It skips any
288 // dependencies that are not an android.Module.
289 //
290 // The Module passed to the visit function should not be retained outside of the visit function, it may be
291 // invalidated by future mutators.
Colin Crossdc35e212019-06-06 16:13:11 -0700292 VisitDirectDepsIf(pred func(Module) bool, visit func(Module))
293 // Deprecated: use WalkDeps instead to support multiple dependency tags on the same module
294 VisitDepsDepthFirst(visit func(Module))
295 // Deprecated: use WalkDeps instead to support multiple dependency tags on the same module
296 VisitDepsDepthFirstIf(pred func(Module) bool, visit func(Module))
Colin Cross9f35c3d2020-09-16 19:04:41 -0700297
298 // WalkDeps calls visit for each transitive dependency, traversing the dependency tree in top down order. visit may
299 // be called multiple times for the same (child, parent) pair if there are multiple direct dependencies between the
300 // child and parent with different tags. OtherModuleDependencyTag will return the tag for the currently visited
301 // (child, parent) pair. If visit returns false WalkDeps will not continue recursing down to child. It skips
302 // any dependencies that are not an android.Module.
303 //
304 // The Modules passed to the visit function should not be retained outside of the visit function, they may be
305 // invalidated by future mutators.
Usta6b1ffa42021-12-15 12:45:49 -0500306 WalkDeps(visit func(child, parent Module) bool)
Colin Cross9f35c3d2020-09-16 19:04:41 -0700307
308 // WalkDepsBlueprint calls visit for each transitive dependency, traversing the dependency
309 // tree in top down order. visit may be called multiple times for the same (child, parent)
310 // pair if there are multiple direct dependencies between the child and parent with different
311 // tags. OtherModuleDependencyTag will return the tag for the currently visited
312 // (child, parent) pair. If visit returns false WalkDeps will not continue recursing down
313 // to child.
314 //
315 // The Modules passed to the visit function should not be retained outside of the visit function, they may be
316 // invalidated by future mutators.
Colin Crossdc35e212019-06-06 16:13:11 -0700317 WalkDepsBlueprint(visit func(blueprint.Module, blueprint.Module) bool)
Colin Cross9f35c3d2020-09-16 19:04:41 -0700318
Colin Crossdc35e212019-06-06 16:13:11 -0700319 // GetWalkPath is supposed to be called in visit function passed in WalkDeps()
320 // and returns a top-down dependency path from a start module to current child module.
321 GetWalkPath() []Module
322
Colin Cross4dfacf92020-09-16 19:22:27 -0700323 // PrimaryModule returns the first variant of the current module. Variants of a module are always visited in
324 // order by mutators and GenerateBuildActions, so the data created by the current mutator can be read from the
325 // Module returned by PrimaryModule without data races. This can be used to perform singleton actions that are
326 // only done once for all variants of a module.
327 PrimaryModule() Module
328
329 // FinalModule returns the last variant of the current module. Variants of a module are always visited in
330 // order by mutators and GenerateBuildActions, so the data created by the current mutator can be read from all
331 // variants using VisitAllModuleVariants if the current module == FinalModule(). This can be used to perform
332 // singleton actions that are only done once for all variants of a module.
333 FinalModule() Module
334
335 // VisitAllModuleVariants calls visit for each variant of the current module. Variants of a module are always
336 // visited in order by mutators and GenerateBuildActions, so the data created by the current mutator can be read
337 // from all variants if the current module == FinalModule(). Otherwise, care must be taken to not access any
338 // data modified by the current mutator.
339 VisitAllModuleVariants(visit func(Module))
340
Paul Duffinc5192442020-03-31 11:31:36 +0100341 // GetTagPath is supposed to be called in visit function passed in WalkDeps()
342 // and returns a top-down dependency tags path from a start module to current child module.
343 // It has one less entry than GetWalkPath() as it contains the dependency tags that
344 // exist between each adjacent pair of modules in the GetWalkPath().
345 // GetTagPath()[i] is the tag between GetWalkPath()[i] and GetWalkPath()[i+1]
346 GetTagPath() []blueprint.DependencyTag
347
Jiyong Park1c7e9622020-05-07 16:12:13 +0900348 // GetPathString is supposed to be called in visit function passed in WalkDeps()
349 // and returns a multi-line string showing the modules and dependency tags
350 // among them along the top-down dependency path from a start module to current child module.
351 // skipFirst when set to true, the output doesn't include the start module,
352 // which is already printed when this function is used along with ModuleErrorf().
353 GetPathString(skipFirst bool) string
354
Colin Crossdc35e212019-06-06 16:13:11 -0700355 AddMissingDependencies(missingDeps []string)
356
Liz Kammerc13f7852023-05-17 13:01:48 -0400357 // getMissingDependencies returns the list of missing dependencies.
358 // Calling this function prevents adding new dependencies.
359 getMissingDependencies() []string
360
Liz Kammer6eff3232021-08-26 08:37:59 -0400361 // AddUnconvertedBp2buildDep stores module name of a direct dependency that was not converted via bp2build
362 AddUnconvertedBp2buildDep(dep string)
363
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500364 // AddMissingBp2buildDep stores the module name of a direct dependency that was not found.
365 AddMissingBp2buildDep(dep string)
366
Colin Crossa1ad8d12016-06-01 17:09:44 -0700367 Target() Target
Colin Cross8b74d172016-09-13 09:59:14 -0700368 TargetPrimary() bool
Paul Duffinca7f0ef2020-02-25 15:50:49 +0000369
370 // The additional arch specific targets (e.g. 32/64 bit) that this module variant is
371 // responsible for creating.
Colin Crossee0bc3b2018-10-02 22:01:37 -0700372 MultiTargets() []Target
Colin Crossf6566ed2015-03-24 11:13:38 -0700373 Arch() Arch
Colin Crossa1ad8d12016-06-01 17:09:44 -0700374 Os() OsType
Colin Crossf6566ed2015-03-24 11:13:38 -0700375 Host() bool
376 Device() bool
Colin Cross0af4b842015-04-30 16:36:18 -0700377 Darwin() bool
Colin Cross3edeee12017-04-04 12:59:48 -0700378 Windows() bool
Colin Crossf6566ed2015-03-24 11:13:38 -0700379 Debug() bool
Colin Cross1e7d3702016-08-24 15:25:47 -0700380 PrimaryArch() bool
Colin Crossf6566ed2015-03-24 11:13:38 -0700381}
382
Colin Cross1184b642019-12-30 18:43:07 -0800383// Deprecated: use EarlyModuleContext instead
Colin Cross635c3b02016-05-18 15:37:25 -0700384type BaseContext interface {
Colin Cross1184b642019-12-30 18:43:07 -0800385 EarlyModuleContext
Colin Crossaabf6792017-11-29 00:27:14 -0800386}
387
Colin Cross635c3b02016-05-18 15:37:25 -0700388type ModuleContext interface {
Colin Crossaabf6792017-11-29 00:27:14 -0800389 BaseModuleContext
Colin Cross3f40fa42015-01-30 17:27:36 -0800390
Colin Crossc20dc852020-11-10 12:27:45 -0800391 blueprintModuleContext() blueprint.ModuleContext
392
Colin Crossae887032017-10-23 17:16:14 -0700393 // Deprecated: use ModuleContext.Build instead.
Colin Cross0875c522017-11-28 17:34:01 -0800394 ModuleBuild(pctx PackageContext, params ModuleBuildParams)
Colin Cross8f101b42015-06-17 15:09:06 -0700395
Paul Duffind5cf92e2021-07-09 17:38:55 +0100396 // Returns a list of paths expanded from globs and modules referenced using ":module" syntax. The property must
397 // be tagged with `android:"path" to support automatic source module dependency resolution.
398 //
399 // Deprecated: use PathsForModuleSrc or PathsForModuleSrcExcludes instead.
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700400 ExpandSources(srcFiles, excludes []string) Paths
Paul Duffind5cf92e2021-07-09 17:38:55 +0100401
402 // Returns a single path expanded from globs and modules referenced using ":module" syntax. The property must
403 // be tagged with `android:"path" to support automatic source module dependency resolution.
404 //
405 // Deprecated: use PathForModuleSrc instead.
Colin Cross366938f2017-12-11 16:29:02 -0800406 ExpandSource(srcFile, prop string) Path
Paul Duffind5cf92e2021-07-09 17:38:55 +0100407
Colin Cross2383f3b2018-02-06 14:40:13 -0800408 ExpandOptionalSource(srcFile *string, prop string) OptionalPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700409
Colin Cross41589502020-12-01 14:00:21 -0800410 // InstallExecutable creates a rule to copy srcPath to name in the installPath directory,
411 // with the given additional dependencies. The file is marked executable after copying.
412 //
413 // The installed file will be returned by FilesToInstall(), and the PackagingSpec for the
414 // installed file will be returned by PackagingSpecs() on this module or by
415 // TransitivePackagingSpecs() on modules that depend on this module through dependency tags
416 // for which IsInstallDepNeeded returns true.
Colin Cross70dda7e2019-10-01 22:05:35 -0700417 InstallExecutable(installPath InstallPath, name string, srcPath Path, deps ...Path) InstallPath
Colin Cross41589502020-12-01 14:00:21 -0800418
419 // InstallFile creates a rule to copy srcPath to name in the installPath directory,
420 // with the given additional dependencies.
421 //
422 // The installed file will be returned by FilesToInstall(), and the PackagingSpec for the
423 // installed file will be returned by PackagingSpecs() on this module or by
424 // TransitivePackagingSpecs() on modules that depend on this module through dependency tags
425 // for which IsInstallDepNeeded returns true.
Colin Cross70dda7e2019-10-01 22:05:35 -0700426 InstallFile(installPath InstallPath, name string, srcPath Path, deps ...Path) InstallPath
Colin Cross41589502020-12-01 14:00:21 -0800427
Colin Cross50ed1f92021-11-12 17:41:02 -0800428 // InstallFileWithExtraFilesZip creates a rule to copy srcPath to name in the installPath
429 // directory, and also unzip a zip file containing extra files to install into the same
430 // directory.
431 //
432 // The installed file will be returned by FilesToInstall(), and the PackagingSpec for the
433 // installed file will be returned by PackagingSpecs() on this module or by
434 // TransitivePackagingSpecs() on modules that depend on this module through dependency tags
435 // for which IsInstallDepNeeded returns true.
436 InstallFileWithExtraFilesZip(installPath InstallPath, name string, srcPath Path, extraZip Path, deps ...Path) InstallPath
437
Colin Cross41589502020-12-01 14:00:21 -0800438 // InstallSymlink creates a rule to create a symlink from src srcPath to name in the installPath
439 // directory.
440 //
441 // The installed symlink will be returned by FilesToInstall(), and the PackagingSpec for the
442 // installed file will be returned by PackagingSpecs() on this module or by
443 // TransitivePackagingSpecs() on modules that depend on this module through dependency tags
444 // for which IsInstallDepNeeded returns true.
Colin Cross70dda7e2019-10-01 22:05:35 -0700445 InstallSymlink(installPath InstallPath, name string, srcPath InstallPath) InstallPath
Colin Cross41589502020-12-01 14:00:21 -0800446
447 // InstallAbsoluteSymlink creates a rule to create an absolute symlink from src srcPath to name
448 // in the installPath directory.
449 //
450 // The installed symlink will be returned by FilesToInstall(), and the PackagingSpec for the
451 // installed file will be returned by PackagingSpecs() on this module or by
452 // TransitivePackagingSpecs() on modules that depend on this module through dependency tags
453 // for which IsInstallDepNeeded returns true.
Colin Cross70dda7e2019-10-01 22:05:35 -0700454 InstallAbsoluteSymlink(installPath InstallPath, name string, absPath string) InstallPath
Colin Cross41589502020-12-01 14:00:21 -0800455
456 // PackageFile creates a PackagingSpec as if InstallFile was called, but without creating
457 // the rule to copy the file. This is useful to define how a module would be packaged
458 // without installing it into the global installation directories.
459 //
460 // The created PackagingSpec for the will be returned by PackagingSpecs() on this module or by
461 // TransitivePackagingSpecs() on modules that depend on this module through dependency tags
462 // for which IsInstallDepNeeded returns true.
463 PackageFile(installPath InstallPath, name string, srcPath Path) PackagingSpec
464
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700465 CheckbuildFile(srcPath Path)
Dan Willemsen6553f5e2016-03-10 18:14:25 -0800466
Colin Cross8d8f8e22016-08-03 11:57:50 -0700467 InstallInData() bool
Jaewoong Jung0949f312019-09-11 10:25:18 -0700468 InstallInTestcases() bool
Vishwath Mohan1dd88392017-03-29 22:00:18 -0700469 InstallInSanitizerDir() bool
Yifan Hong1b3348d2020-01-21 15:53:22 -0800470 InstallInRamdisk() bool
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700471 InstallInVendorRamdisk() bool
Inseob Kim08758f02021-04-08 21:13:22 +0900472 InstallInDebugRamdisk() bool
Jiyong Parkf9332f12018-02-01 00:54:12 +0900473 InstallInRecovery() bool
Colin Cross90ba5f42019-10-02 11:10:58 -0700474 InstallInRoot() bool
Kiyoung Kimae11c232021-07-19 11:38:04 +0900475 InstallInVendor() bool
Jiyong Park87788b52020-09-01 12:37:45 +0900476 InstallForceOS() (*OsType, *ArchType)
Nan Zhang6d34b302017-02-04 17:47:46 -0800477
478 RequiredModuleNames() []string
Sasha Smundakb6d23052019-04-01 18:37:36 -0700479 HostRequiredModuleNames() []string
480 TargetRequiredModuleNames() []string
Colin Cross3f68a132017-10-23 17:10:29 -0700481
Colin Cross3f68a132017-10-23 17:10:29 -0700482 ModuleSubDir() string
483
Colin Cross0875c522017-11-28 17:34:01 -0800484 Variable(pctx PackageContext, name, value string)
485 Rule(pctx PackageContext, name string, params blueprint.RuleParams, argNames ...string) blueprint.Rule
Colin Crossae887032017-10-23 17:16:14 -0700486 // Similar to blueprint.ModuleContext.Build, but takes Paths instead of []string,
487 // and performs more verification.
Colin Cross0875c522017-11-28 17:34:01 -0800488 Build(pctx PackageContext, params BuildParams)
Colin Crossc3d87d32020-06-04 13:25:17 -0700489 // Phony creates a Make-style phony rule, a rule with no commands that can depend on other
490 // phony rules or real files. Phony can be called on the same name multiple times to add
491 // additional dependencies.
492 Phony(phony string, deps ...Path)
Colin Cross3f68a132017-10-23 17:10:29 -0700493
Colin Cross9f35c3d2020-09-16 19:04:41 -0700494 // GetMissingDependencies returns the list of dependencies that were passed to AddDependencies or related methods,
495 // but do not exist.
Colin Cross3f68a132017-10-23 17:10:29 -0700496 GetMissingDependencies() []string
Colin Crosse7fe0962022-03-15 17:49:24 -0700497
498 // LicenseMetadataFile returns the path where the license metadata for this module will be
499 // generated.
500 LicenseMetadataFile() Path
Colin Cross3f40fa42015-01-30 17:27:36 -0800501}
502
Colin Cross635c3b02016-05-18 15:37:25 -0700503type Module interface {
Colin Cross3f40fa42015-01-30 17:27:36 -0800504 blueprint.Module
505
Jeff Gastonaf3cc2d2017-09-27 17:01:44 -0700506 // GenerateAndroidBuildActions is analogous to Blueprints' GenerateBuildActions,
507 // but GenerateAndroidBuildActions also has access to Android-specific information.
508 // For more information, see Module.GenerateBuildActions within Blueprint's module_ctx.go
Colin Cross635c3b02016-05-18 15:37:25 -0700509 GenerateAndroidBuildActions(ModuleContext)
Jeff Gastonaf3cc2d2017-09-27 17:01:44 -0700510
Paul Duffin44f1d842020-06-26 20:17:02 +0100511 // Add dependencies to the components of a module, i.e. modules that are created
512 // by the module and which are considered to be part of the creating module.
513 //
514 // This is called before prebuilts are renamed so as to allow a dependency to be
515 // added directly to a prebuilt child module instead of depending on a source module
516 // and relying on prebuilt processing to switch to the prebuilt module if preferred.
517 //
518 // A dependency on a prebuilt must include the "prebuilt_" prefix.
519 ComponentDepsMutator(ctx BottomUpMutatorContext)
520
Colin Cross1e676be2016-10-12 14:38:15 -0700521 DepsMutator(BottomUpMutatorContext)
Colin Cross3f40fa42015-01-30 17:27:36 -0800522
Colin Cross635c3b02016-05-18 15:37:25 -0700523 base() *ModuleBase
Inseob Kimeec88e12020-01-22 11:11:29 +0900524 Disable()
Dan Willemsen0effe062015-11-30 16:06:01 -0800525 Enabled() bool
Colin Crossa1ad8d12016-06-01 17:09:44 -0700526 Target() Target
Paul Duffinc04fb9e2021-03-01 12:25:10 +0000527 MultiTargets() []Target
Paul Duffinb42fa672021-09-09 16:37:49 +0100528
529 // ImageVariation returns the image variation of this module.
530 //
531 // The returned structure has its Mutator field set to "image" and its Variation field set to the
532 // image variation, e.g. recovery, ramdisk, etc.. The Variation field is "" for host modules and
533 // device modules that have no image variation.
534 ImageVariation() blueprint.Variation
535
Anton Hansson1ee62c02020-06-30 11:51:53 +0100536 Owner() string
Dan Willemsen782a2d12015-12-21 14:55:28 -0800537 InstallInData() bool
Jaewoong Jung0949f312019-09-11 10:25:18 -0700538 InstallInTestcases() bool
Vishwath Mohan1dd88392017-03-29 22:00:18 -0700539 InstallInSanitizerDir() bool
Yifan Hong1b3348d2020-01-21 15:53:22 -0800540 InstallInRamdisk() bool
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700541 InstallInVendorRamdisk() bool
Inseob Kim08758f02021-04-08 21:13:22 +0900542 InstallInDebugRamdisk() bool
Jiyong Parkf9332f12018-02-01 00:54:12 +0900543 InstallInRecovery() bool
Colin Cross90ba5f42019-10-02 11:10:58 -0700544 InstallInRoot() bool
Kiyoung Kimae11c232021-07-19 11:38:04 +0900545 InstallInVendor() bool
Jiyong Park87788b52020-09-01 12:37:45 +0900546 InstallForceOS() (*OsType, *ArchType)
Jiyong Parkce243632023-02-17 18:22:25 +0900547 PartitionTag(DeviceConfig) string
Colin Crossa9c8c9f2020-12-16 10:20:23 -0800548 HideFromMake()
549 IsHideFromMake() bool
Martin Stjernholm9e7f45e2020-12-23 03:50:30 +0000550 IsSkipInstall() bool
Iván Budnik295da162023-03-10 16:11:26 +0000551 MakeUninstallable()
Liz Kammer5ca3a622020-08-05 15:40:41 -0700552 ReplacedByPrebuilt()
553 IsReplacedByPrebuilt() bool
Jiyong Park374510b2018-03-19 18:23:01 +0900554 ExportedToMake() bool
Inseob Kim8471cda2019-11-15 09:59:12 +0900555 InitRc() Paths
556 VintfFragments() Paths
Justin Yun1871f902023-04-07 20:13:19 +0900557 EffectiveLicenseKinds() []string
Justin Yun885a7de2021-06-29 20:34:53 +0900558 EffectiveLicenseFiles() Paths
Colin Cross36242852017-06-23 15:06:31 -0700559
560 AddProperties(props ...interface{})
561 GetProperties() []interface{}
Colin Crosscec81712017-07-13 14:43:27 -0700562
Liz Kammer2ada09a2021-08-11 00:17:36 -0400563 // IsConvertedByBp2build returns whether this module was converted via bp2build
564 IsConvertedByBp2build() bool
565 // Bp2buildTargets returns the target(s) generated for Bazel via bp2build for this module
566 Bp2buildTargets() []bp2buildInfo
Liz Kammer6eff3232021-08-26 08:37:59 -0400567 GetUnconvertedBp2buildDeps() []string
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500568 GetMissingBp2buildDeps() []string
Liz Kammer2ada09a2021-08-11 00:17:36 -0400569
Colin Crossae887032017-10-23 17:16:14 -0700570 BuildParamsForTests() []BuildParams
Colin Cross4c83e5c2019-02-25 14:54:28 -0800571 RuleParamsForTests() map[blueprint.Rule]blueprint.RuleParams
Jaewoong Jung38e4fb22018-12-12 09:01:34 -0800572 VariablesForTests() map[string]string
Paul Duffine2453c72019-05-31 14:00:04 +0100573
Colin Cross9a362232019-07-01 15:32:45 -0700574 // String returns a string that includes the module name and variants for printing during debugging.
575 String() string
576
Paul Duffine2453c72019-05-31 14:00:04 +0100577 // Get the qualified module id for this module.
578 qualifiedModuleId(ctx BaseModuleContext) qualifiedModuleName
579
580 // Get information about the properties that can contain visibility rules.
581 visibilityProperties() []visibilityProperty
Paul Duffin63c6e182019-07-24 14:24:38 +0100582
Jiyong Park6a8cf5f2019-12-30 16:31:09 +0900583 RequiredModuleNames() []string
584 HostRequiredModuleNames() []string
585 TargetRequiredModuleNames() []string
Colin Cross897266e2020-02-13 13:22:08 -0800586
Jiyong Park4dc2a1a2020-09-28 17:46:22 +0900587 FilesToInstall() InstallPaths
Jiyong Park073ea552020-11-09 14:08:34 +0900588 PackagingSpecs() []PackagingSpec
Colin Crossffe6b9d2020-12-01 15:40:06 -0800589
590 // TransitivePackagingSpecs returns the PackagingSpecs for this module and any transitive
591 // dependencies with dependency tags for which IsInstallDepNeeded() returns true.
592 TransitivePackagingSpecs() []PackagingSpec
Paul Duffine2453c72019-05-31 14:00:04 +0100593}
594
595// Qualified id for a module
596type qualifiedModuleName struct {
597 // The package (i.e. directory) in which the module is defined, without trailing /
598 pkg string
599
600 // The name of the module, empty string if package.
601 name string
602}
603
604func (q qualifiedModuleName) String() string {
605 if q.name == "" {
606 return "//" + q.pkg
607 }
608 return "//" + q.pkg + ":" + q.name
609}
610
Paul Duffine484f472019-06-20 16:38:08 +0100611func (q qualifiedModuleName) isRootPackage() bool {
612 return q.pkg == "" && q.name == ""
613}
614
Paul Duffine2453c72019-05-31 14:00:04 +0100615// Get the id for the package containing this module.
616func (q qualifiedModuleName) getContainingPackageId() qualifiedModuleName {
617 pkg := q.pkg
618 if q.name == "" {
Paul Duffine484f472019-06-20 16:38:08 +0100619 if pkg == "" {
620 panic(fmt.Errorf("Cannot get containing package id of root package"))
621 }
622
623 index := strings.LastIndex(pkg, "/")
624 if index == -1 {
625 pkg = ""
626 } else {
627 pkg = pkg[:index]
628 }
Paul Duffine2453c72019-05-31 14:00:04 +0100629 }
630 return newPackageId(pkg)
631}
632
633func newPackageId(pkg string) qualifiedModuleName {
634 // A qualified id for a package module has no name.
635 return qualifiedModuleName{pkg: pkg, name: ""}
Colin Cross3f40fa42015-01-30 17:27:36 -0800636}
637
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000638type Dist struct {
639 // Copy the output of this module to the $DIST_DIR when `dist` is specified on the
640 // command line and any of these targets are also on the command line, or otherwise
641 // built
642 Targets []string `android:"arch_variant"`
643
644 // The name of the output artifact. This defaults to the basename of the output of
645 // the module.
646 Dest *string `android:"arch_variant"`
647
648 // The directory within the dist directory to store the artifact. Defaults to the
649 // top level directory ("").
650 Dir *string `android:"arch_variant"`
651
652 // A suffix to add to the artifact file name (before any extension).
653 Suffix *string `android:"arch_variant"`
654
Trevor Radcliffe90727f42022-03-21 19:34:02 +0000655 // If true, then the artifact file will be appended with _<product name>. For
656 // example, if the product is coral and the module is an android_app module
657 // of name foo, then the artifact would be foo_coral.apk. If false, there is
658 // no change to the artifact file name.
659 Append_artifact_with_product *bool `android:"arch_variant"`
660
Paul Duffin74f05592020-11-25 16:37:46 +0000661 // A string tag to select the OutputFiles associated with the tag.
662 //
663 // If no tag is specified then it will select the default dist paths provided
664 // by the module type. If a tag of "" is specified then it will return the
665 // default output files provided by the modules, i.e. the result of calling
666 // OutputFiles("").
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000667 Tag *string `android:"arch_variant"`
668}
669
Bob Badour4101c712022-02-09 11:54:35 -0800670// NamedPath associates a path with a name. e.g. a license text path with a package name
671type NamedPath struct {
672 Path Path
673 Name string
674}
675
676// String returns an escaped string representing the `NamedPath`.
677func (p NamedPath) String() string {
678 if len(p.Name) > 0 {
679 return p.Path.String() + ":" + url.QueryEscape(p.Name)
680 }
681 return p.Path.String()
682}
683
684// NamedPaths describes a list of paths each associated with a name.
685type NamedPaths []NamedPath
686
687// Strings returns a list of escaped strings representing each `NamedPath` in the list.
688func (l NamedPaths) Strings() []string {
689 result := make([]string, 0, len(l))
690 for _, p := range l {
691 result = append(result, p.String())
692 }
693 return result
694}
695
696// SortedUniqueNamedPaths modifies `l` in place to return the sorted unique subset.
697func SortedUniqueNamedPaths(l NamedPaths) NamedPaths {
698 if len(l) == 0 {
699 return l
700 }
701 sort.Slice(l, func(i, j int) bool {
702 return l[i].String() < l[j].String()
703 })
704 k := 0
705 for i := 1; i < len(l); i++ {
706 if l[i].String() == l[k].String() {
707 continue
708 }
709 k++
710 if k < i {
711 l[k] = l[i]
712 }
713 }
714 return l[:k+1]
715}
716
Colin Crossfc754582016-05-17 16:34:16 -0700717type nameProperties struct {
718 // The name of the module. Must be unique across all modules.
Nan Zhang0007d812017-11-07 10:57:05 -0800719 Name *string
Colin Crossfc754582016-05-17 16:34:16 -0700720}
721
Colin Cross08d6f8f2020-11-19 02:33:19 +0000722type commonProperties struct {
Dan Willemsen0effe062015-11-30 16:06:01 -0800723 // emit build rules for this module
Paul Duffin54d9bb72020-02-12 10:20:56 +0000724 //
725 // Disabling a module should only be done for those modules that cannot be built
726 // in the current environment. Modules that can build in the current environment
727 // but are not usually required (e.g. superceded by a prebuilt) should not be
728 // disabled as that will prevent them from being built by the checkbuild target
729 // and so prevent early detection of changes that have broken those modules.
Dan Willemsen0effe062015-11-30 16:06:01 -0800730 Enabled *bool `android:"arch_variant"`
Colin Cross3f40fa42015-01-30 17:27:36 -0800731
Paul Duffin2e61fa62019-03-28 14:10:57 +0000732 // Controls the visibility of this module to other modules. Allowable values are one or more of
733 // these formats:
734 //
735 // ["//visibility:public"]: Anyone can use this module.
736 // ["//visibility:private"]: Only rules in the module's package (not its subpackages) can use
737 // this module.
Paul Duffin51084ff2020-05-05 19:19:22 +0100738 // ["//visibility:override"]: Discards any rules inherited from defaults or a creating module.
739 // Can only be used at the beginning of a list of visibility rules.
Paul Duffin2e61fa62019-03-28 14:10:57 +0000740 // ["//some/package:__pkg__", "//other/package:__pkg__"]: Only modules in some/package and
741 // other/package (defined in some/package/*.bp and other/package/*.bp) have access to
742 // this module. Note that sub-packages do not have access to the rule; for example,
743 // //some/package/foo:bar or //other/package/testing:bla wouldn't have access. __pkg__
744 // is a special module and must be used verbatim. It represents all of the modules in the
745 // package.
746 // ["//project:__subpackages__", "//other:__subpackages__"]: Only modules in packages project
747 // or other or in one of their sub-packages have access to this module. For example,
748 // //project:rule, //project/library:lib or //other/testing/internal:munge are allowed
749 // to depend on this rule (but not //independent:evil)
750 // ["//project"]: This is shorthand for ["//project:__pkg__"]
751 // [":__subpackages__"]: This is shorthand for ["//project:__subpackages__"] where
752 // //project is the module's package. e.g. using [":__subpackages__"] in
753 // packages/apps/Settings/Android.bp is equivalent to
754 // //packages/apps/Settings:__subpackages__.
755 // ["//visibility:legacy_public"]: The default visibility, behaves as //visibility:public
756 // for now. It is an error if it is used in a module.
Paul Duffine2453c72019-05-31 14:00:04 +0100757 //
758 // If a module does not specify the `visibility` property then it uses the
759 // `default_visibility` property of the `package` module in the module's package.
760 //
761 // If the `default_visibility` property is not set for the module's package then
Paul Duffine484f472019-06-20 16:38:08 +0100762 // it will use the `default_visibility` of its closest ancestor package for which
763 // a `default_visibility` property is specified.
764 //
765 // If no `default_visibility` property can be found then the module uses the
766 // global default of `//visibility:legacy_public`.
Paul Duffine2453c72019-05-31 14:00:04 +0100767 //
Paul Duffin95d53b52019-07-24 13:45:05 +0100768 // The `visibility` property has no effect on a defaults module although it does
769 // apply to any non-defaults module that uses it. To set the visibility of a
770 // defaults module, use the `defaults_visibility` property on the defaults module;
771 // not to be confused with the `default_visibility` property on the package module.
772 //
Paul Duffin2e61fa62019-03-28 14:10:57 +0000773 // See https://android.googlesource.com/platform/build/soong/+/master/README.md#visibility for
774 // more details.
775 Visibility []string
776
Bob Badour37af0462021-01-07 03:34:31 +0000777 // Describes the licenses applicable to this module. Must reference license modules.
778 Licenses []string
779
780 // Flattened from direct license dependencies. Equal to Licenses unless particular module adds more.
781 Effective_licenses []string `blueprint:"mutated"`
782 // Override of module name when reporting licenses
783 Effective_package_name *string `blueprint:"mutated"`
784 // Notice files
Bob Badour4101c712022-02-09 11:54:35 -0800785 Effective_license_text NamedPaths `blueprint:"mutated"`
Bob Badour37af0462021-01-07 03:34:31 +0000786 // License names
787 Effective_license_kinds []string `blueprint:"mutated"`
788 // License conditions
789 Effective_license_conditions []string `blueprint:"mutated"`
790
Colin Cross7d5136f2015-05-11 13:39:40 -0700791 // control whether this module compiles for 32-bit, 64-bit, or both. Possible values
Colin Cross3f40fa42015-01-30 17:27:36 -0800792 // are "32" (compile for 32-bit only), "64" (compile for 64-bit only), "both" (compile for both
793 // 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 +0000794 // platform).
Colin Cross7d716ba2017-11-01 10:38:29 -0700795 Compile_multilib *string `android:"arch_variant"`
Colin Cross69617d32016-09-06 10:39:07 -0700796
797 Target struct {
798 Host struct {
Colin Cross7d716ba2017-11-01 10:38:29 -0700799 Compile_multilib *string
Colin Cross69617d32016-09-06 10:39:07 -0700800 }
801 Android struct {
Colin Cross7d716ba2017-11-01 10:38:29 -0700802 Compile_multilib *string
Colin Cross69617d32016-09-06 10:39:07 -0700803 }
804 }
805
Paul Duffinca7f0ef2020-02-25 15:50:49 +0000806 // If set to true then the archMutator will create variants for each arch specific target
807 // (e.g. 32/64) that the module is required to produce. If set to false then it will only
808 // create a variant for the architecture and will list the additional arch specific targets
809 // that the variant needs to produce in the CompileMultiTargets property.
Colin Crossee0bc3b2018-10-02 22:01:37 -0700810 UseTargetVariants bool `blueprint:"mutated"`
811 Default_multilib string `blueprint:"mutated"`
Colin Cross3f40fa42015-01-30 17:27:36 -0800812
Dan Willemsen782a2d12015-12-21 14:55:28 -0800813 // whether this is a proprietary vendor module, and should be installed into /vendor
Colin Cross7d716ba2017-11-01 10:38:29 -0700814 Proprietary *bool
Dan Willemsen782a2d12015-12-21 14:55:28 -0800815
Colin Cross55708f32017-03-20 13:23:34 -0700816 // vendor who owns this module
Dan Willemsenefac4a82017-07-18 19:42:09 -0700817 Owner *string
Colin Cross55708f32017-03-20 13:23:34 -0700818
Jiyong Park2db76922017-11-08 16:03:48 +0900819 // whether this module is specific to an SoC (System-On-a-Chip). When set to true,
820 // it is installed into /vendor (or /system/vendor if vendor partition does not exist).
821 // Use `soc_specific` instead for better meaning.
Colin Cross7d716ba2017-11-01 10:38:29 -0700822 Vendor *bool
Dan Willemsenaa118f92017-04-06 12:49:58 -0700823
Jiyong Park2db76922017-11-08 16:03:48 +0900824 // whether this module is specific to an SoC (System-On-a-Chip). When set to true,
825 // it is installed into /vendor (or /system/vendor if vendor partition does not exist).
826 Soc_specific *bool
827
828 // whether this module is specific to a device, not only for SoC, but also for off-chip
829 // peripherals. When set to true, it is installed into /odm (or /vendor/odm if odm partition
830 // does not exist, or /system/vendor/odm if both odm and vendor partitions do not exist).
831 // This implies `soc_specific:true`.
832 Device_specific *bool
833
834 // whether this module is specific to a software configuration of a product (e.g. country,
Jaekyun Seok5cfbfbb2018-01-10 19:00:15 +0900835 // network operator, etc). When set to true, it is installed into /product (or
836 // /system/product if product partition does not exist).
Jiyong Park2db76922017-11-08 16:03:48 +0900837 Product_specific *bool
838
Justin Yund5f6c822019-06-25 16:47:17 +0900839 // whether this module extends system. When set to true, it is installed into /system_ext
840 // (or /system/system_ext if system_ext partition does not exist).
841 System_ext_specific *bool
842
Jiyong Parkf9332f12018-02-01 00:54:12 +0900843 // Whether this module is installed to recovery partition
844 Recovery *bool
845
Yifan Hong1b3348d2020-01-21 15:53:22 -0800846 // Whether this module is installed to ramdisk
847 Ramdisk *bool
848
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700849 // Whether this module is installed to vendor ramdisk
850 Vendor_ramdisk *bool
851
Inseob Kim08758f02021-04-08 21:13:22 +0900852 // Whether this module is installed to debug ramdisk
853 Debug_ramdisk *bool
854
Jaewoong Jung8e93aba2021-03-02 16:58:08 -0800855 // Whether this module is built for non-native architectures (also known as native bridge binary)
dimitry1f33e402019-03-26 12:39:31 +0100856 Native_bridge_supported *bool `android:"arch_variant"`
857
Dan Willemsen2277bcb2016-07-25 20:27:39 -0700858 // init.rc files to be installed if this module is installed
Colin Cross0bab8772020-09-25 14:01:21 -0700859 Init_rc []string `android:"arch_variant,path"`
Dan Willemsen2277bcb2016-07-25 20:27:39 -0700860
Steven Moreland57a23d22018-04-04 15:42:19 -0700861 // VINTF manifest fragments to be installed if this module is installed
Colin Cross27b922f2019-03-04 22:35:41 -0800862 Vintf_fragments []string `android:"path"`
Steven Moreland57a23d22018-04-04 15:42:19 -0700863
Chris Wolfe998306e2016-08-15 14:47:23 -0400864 // names of other modules to install if this module is installed
Colin Crossc602b7d2017-05-05 13:36:36 -0700865 Required []string `android:"arch_variant"`
Chris Wolfe998306e2016-08-15 14:47:23 -0400866
Sasha Smundakb6d23052019-04-01 18:37:36 -0700867 // names of other modules to install on host if this module is installed
868 Host_required []string `android:"arch_variant"`
869
870 // names of other modules to install on target if this module is installed
871 Target_required []string `android:"arch_variant"`
872
Paul Duffinca7f0ef2020-02-25 15:50:49 +0000873 // The OsType of artifacts that this module variant is responsible for creating.
874 //
875 // Set by osMutator
876 CompileOS OsType `blueprint:"mutated"`
877
878 // The Target of artifacts that this module variant is responsible for creating.
879 //
880 // Set by archMutator
881 CompileTarget Target `blueprint:"mutated"`
882
883 // The additional arch specific targets (e.g. 32/64 bit) that this module variant is
884 // responsible for creating.
885 //
886 // By default this is nil as, where necessary, separate variants are created for the
887 // different multilib types supported and that information is encapsulated in the
888 // CompileTarget so the module variant simply needs to create artifacts for that.
889 //
890 // However, if UseTargetVariants is set to false (e.g. by
891 // InitAndroidMultiTargetsArchModule) then no separate variants are created for the
892 // multilib targets. Instead a single variant is created for the architecture and
893 // this contains the multilib specific targets that this variant should create.
894 //
895 // Set by archMutator
Colin Crossee0bc3b2018-10-02 22:01:37 -0700896 CompileMultiTargets []Target `blueprint:"mutated"`
Paul Duffinca7f0ef2020-02-25 15:50:49 +0000897
898 // True if the module variant's CompileTarget is the primary target
899 //
900 // Set by archMutator
901 CompilePrimary bool `blueprint:"mutated"`
Colin Cross3f40fa42015-01-30 17:27:36 -0800902
903 // Set by InitAndroidModule
904 HostOrDeviceSupported HostOrDeviceSupported `blueprint:"mutated"`
Dan Willemsen0b24c742016-10-04 15:13:37 -0700905 ArchSpecific bool `blueprint:"mutated"`
Colin Crossce75d2c2016-10-06 16:12:58 -0700906
Paul Duffin1356d8c2020-02-25 19:26:33 +0000907 // If set to true then a CommonOS variant will be created which will have dependencies
908 // on all its OsType specific variants. Used by sdk/module_exports to create a snapshot
909 // that covers all os and architecture variants.
910 //
911 // The OsType specific variants can be retrieved by calling
912 // GetOsSpecificVariantsOfCommonOSVariant
913 //
914 // Set at module initialization time by calling InitCommonOSAndroidMultiTargetsArchModule
915 CreateCommonOSVariant bool `blueprint:"mutated"`
916
917 // If set to true then this variant is the CommonOS variant that has dependencies on its
918 // OsType specific variants.
919 //
920 // Set by osMutator.
921 CommonOSVariant bool `blueprint:"mutated"`
922
Colin Crossa9c8c9f2020-12-16 10:20:23 -0800923 // When HideFromMake is set to true, no entry for this variant will be emitted in the
924 // generated Android.mk file.
925 HideFromMake bool `blueprint:"mutated"`
926
927 // When SkipInstall is set to true, calls to ctx.InstallFile, ctx.InstallExecutable,
928 // ctx.InstallSymlink and ctx.InstallAbsoluteSymlink act like calls to ctx.PackageFile
929 // and don't create a rule to install the file.
Colin Crossce75d2c2016-10-06 16:12:58 -0700930 SkipInstall bool `blueprint:"mutated"`
Jeff Gaston088e29e2017-11-29 16:47:17 -0800931
Colin Crossbd3a16b2023-04-25 11:30:51 -0700932 // UninstallableApexPlatformVariant is set by MakeUninstallable called by the apex
933 // mutator. MakeUninstallable also sets HideFromMake. UninstallableApexPlatformVariant
934 // is used to avoid adding install or packaging dependencies into libraries provided
935 // by apexes.
936 UninstallableApexPlatformVariant bool `blueprint:"mutated"`
937
Liz Kammer5ca3a622020-08-05 15:40:41 -0700938 // Whether the module has been replaced by a prebuilt
939 ReplacedByPrebuilt bool `blueprint:"mutated"`
940
Justin Yun32f053b2020-07-31 23:07:17 +0900941 // Disabled by mutators. If set to true, it overrides Enabled property.
942 ForcedDisabled bool `blueprint:"mutated"`
943
Jeff Gaston088e29e2017-11-29 16:47:17 -0800944 NamespaceExportedToMake bool `blueprint:"mutated"`
Colin Cross6c4f21f2019-06-06 15:41:36 -0700945
Liz Kammerc13f7852023-05-17 13:01:48 -0400946 MissingDeps []string `blueprint:"mutated"`
947 CheckedMissingDeps bool `blueprint:"mutated"`
Colin Cross9a362232019-07-01 15:32:45 -0700948
949 // Name and variant strings stored by mutators to enable Module.String()
950 DebugName string `blueprint:"mutated"`
951 DebugMutators []string `blueprint:"mutated"`
952 DebugVariations []string `blueprint:"mutated"`
Colin Cross7228ecd2019-11-18 16:00:16 -0800953
Colin Crossa6845402020-11-16 15:08:19 -0800954 // ImageVariation is set by ImageMutator to specify which image this variation is for,
955 // for example "" for core or "recovery" for recovery. It will often be set to one of the
956 // constants in image.go, but can also be set to a custom value by individual module types.
Colin Cross7228ecd2019-11-18 16:00:16 -0800957 ImageVariation string `blueprint:"mutated"`
Liz Kammer2ada09a2021-08-11 00:17:36 -0400958
Sasha Smundaka0954062022-08-02 18:23:58 -0700959 // Bazel conversion status
960 BazelConversionStatus BazelConversionStatus `blueprint:"mutated"`
Colin Cross3f40fa42015-01-30 17:27:36 -0800961}
962
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000963// CommonAttributes represents the common Bazel attributes from which properties
964// in `commonProperties` are translated/mapped; such properties are annotated in
965// a list their corresponding attribute. It is embedded within `bp2buildInfo`.
966type CommonAttributes struct {
967 // Soong nameProperties -> Bazel name
968 Name string
Spandan Das4238c652022-09-09 01:38:47 +0000969
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000970 // Data mapped from: Required
971 Data bazel.LabelListAttribute
Jingwen Chenfbff97a2022-09-16 02:32:03 +0000972
Spandan Das4238c652022-09-09 01:38:47 +0000973 // SkipData is neither a Soong nor Bazel target attribute
974 // If true, this will not fill the data attribute automatically
975 // This is useful for Soong modules that have 1:many Bazel targets
976 // Some of the generated Bazel targets might not have a data attribute
977 SkipData *bool
978
Jingwen Chenfbff97a2022-09-16 02:32:03 +0000979 Tags bazel.StringListAttribute
Sasha Smundak05b0ba62022-09-26 18:15:45 -0700980
981 Applicable_licenses bazel.LabelListAttribute
Yu Liu4c212ce2022-10-14 12:20:20 -0700982
983 Testonly *bool
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000984}
985
Chris Parsons58852a02021-12-09 18:10:18 -0500986// constraintAttributes represents Bazel attributes pertaining to build constraints,
987// which make restrict building a Bazel target for some set of platforms.
988type constraintAttributes struct {
989 // Constraint values this target can be built for.
990 Target_compatible_with bazel.LabelListAttribute
991}
992
Paul Duffined875132020-09-02 13:08:57 +0100993type distProperties struct {
994 // configuration to distribute output files from this module to the distribution
995 // directory (default: $OUT/dist, configurable with $DIST_DIR)
996 Dist Dist `android:"arch_variant"`
997
998 // a list of configurations to distribute output files from this module to the
999 // distribution directory (default: $OUT/dist, configurable with $DIST_DIR)
1000 Dists []Dist `android:"arch_variant"`
1001}
1002
Zhenhuang Wang0ac5a432022-08-12 18:49:20 +08001003// CommonTestOptions represents the common `test_options` properties in
1004// Android.bp.
1005type CommonTestOptions struct {
1006 // If the test is a hostside (no device required) unittest that shall be run
1007 // during presubmit check.
1008 Unit_test *bool
Zhenhuang Wang409d2772022-08-22 16:00:05 +08001009
1010 // Tags provide additional metadata to customize test execution by downstream
1011 // test runners. The tags have no special meaning to Soong.
1012 Tags []string
Zhenhuang Wang0ac5a432022-08-12 18:49:20 +08001013}
1014
1015// SetAndroidMkEntries sets AndroidMkEntries according to the value of base
1016// `test_options`.
1017func (t *CommonTestOptions) SetAndroidMkEntries(entries *AndroidMkEntries) {
1018 entries.SetBoolIfTrue("LOCAL_IS_UNIT_TEST", Bool(t.Unit_test))
Zhenhuang Wang409d2772022-08-22 16:00:05 +08001019 if len(t.Tags) > 0 {
1020 entries.AddStrings("LOCAL_TEST_OPTIONS_TAGS", t.Tags...)
1021 }
Zhenhuang Wang0ac5a432022-08-12 18:49:20 +08001022}
1023
Paul Duffin74f05592020-11-25 16:37:46 +00001024// The key to use in TaggedDistFiles when a Dist structure does not specify a
1025// tag property. This intentionally does not use "" as the default because that
1026// would mean that an empty tag would have a different meaning when used in a dist
1027// structure that when used to reference a specific set of output paths using the
1028// :module{tag} syntax, which passes tag to the OutputFiles(tag) method.
1029const DefaultDistTag = "<default-dist-tag>"
1030
Jingwen Chen40fd90a2020-06-15 05:24:19 +00001031// A map of OutputFile tag keys to Paths, for disting purposes.
1032type TaggedDistFiles map[string]Paths
1033
Paul Duffin74f05592020-11-25 16:37:46 +00001034// addPathsForTag adds a mapping from the tag to the paths. If the map is nil
1035// then it will create a map, update it and then return it. If a mapping already
1036// exists for the tag then the paths are appended to the end of the current list
1037// of paths, ignoring any duplicates.
1038func (t TaggedDistFiles) addPathsForTag(tag string, paths ...Path) TaggedDistFiles {
1039 if t == nil {
1040 t = make(TaggedDistFiles)
1041 }
1042
1043 for _, distFile := range paths {
1044 if distFile != nil && !t[tag].containsPath(distFile) {
1045 t[tag] = append(t[tag], distFile)
1046 }
1047 }
1048
1049 return t
1050}
1051
1052// merge merges the entries from the other TaggedDistFiles object into this one.
1053// If the TaggedDistFiles is nil then it will create a new instance, merge the
1054// other into it, and then return it.
1055func (t TaggedDistFiles) merge(other TaggedDistFiles) TaggedDistFiles {
1056 for tag, paths := range other {
1057 t = t.addPathsForTag(tag, paths...)
1058 }
1059
1060 return t
1061}
1062
Jingwen Chen40fd90a2020-06-15 05:24:19 +00001063func MakeDefaultDistFiles(paths ...Path) TaggedDistFiles {
Sasha Smundake198eaf2022-08-04 13:07:02 -07001064 for _, p := range paths {
1065 if p == nil {
Jingwen Chen7b27ca72020-07-24 09:13:49 +00001066 panic("The path to a dist file cannot be nil.")
1067 }
1068 }
1069
Jingwen Chen40fd90a2020-06-15 05:24:19 +00001070 // The default OutputFile tag is the empty "" string.
Paul Duffin74f05592020-11-25 16:37:46 +00001071 return TaggedDistFiles{DefaultDistTag: paths}
Jingwen Chen40fd90a2020-06-15 05:24:19 +00001072}
1073
Colin Cross3f40fa42015-01-30 17:27:36 -08001074type hostAndDeviceProperties struct {
Colin Cross4e81d702018-11-09 10:36:55 -08001075 // If set to true, build a variant of the module for the host. Defaults to false.
1076 Host_supported *bool
1077
1078 // If set to true, build a variant of the module for the device. Defaults to true.
Colin Crossa4190c12016-07-12 13:11:25 -07001079 Device_supported *bool
Colin Cross3f40fa42015-01-30 17:27:36 -08001080}
1081
Colin Crossc472d572015-03-17 15:06:21 -07001082type Multilib string
1083
1084const (
Colin Cross6b4a32d2017-12-05 13:42:45 -08001085 MultilibBoth Multilib = "both"
1086 MultilibFirst Multilib = "first"
1087 MultilibCommon Multilib = "common"
1088 MultilibCommonFirst Multilib = "common_first"
Colin Crossc472d572015-03-17 15:06:21 -07001089)
1090
Colin Crossa1ad8d12016-06-01 17:09:44 -07001091type HostOrDeviceSupported int
1092
1093const (
Colin Cross34037c62020-11-17 13:19:17 -08001094 hostSupported = 1 << iota
1095 hostCrossSupported
1096 deviceSupported
1097 hostDefault
1098 deviceDefault
Dan Albert0981b5c2018-08-02 13:46:35 -07001099
1100 // Host and HostCross are built by default. Device is not supported.
Colin Cross34037c62020-11-17 13:19:17 -08001101 HostSupported = hostSupported | hostCrossSupported | hostDefault
Dan Albert0981b5c2018-08-02 13:46:35 -07001102
1103 // Host is built by default. HostCross and Device are not supported.
Colin Cross34037c62020-11-17 13:19:17 -08001104 HostSupportedNoCross = hostSupported | hostDefault
Dan Albert0981b5c2018-08-02 13:46:35 -07001105
1106 // Device is built by default. Host and HostCross are not supported.
Colin Cross34037c62020-11-17 13:19:17 -08001107 DeviceSupported = deviceSupported | deviceDefault
Dan Albert0981b5c2018-08-02 13:46:35 -07001108
Liz Kammer8631cc72021-08-23 21:12:07 +00001109 // By default, _only_ device variant is built. Device variant can be disabled with `device_supported: false`
Chih-Hung Hsiehd0f82fe2021-09-05 20:15:38 -07001110 // Host and HostCross are disabled by default and can be enabled with `host_supported: true`
Colin Cross34037c62020-11-17 13:19:17 -08001111 HostAndDeviceSupported = hostSupported | hostCrossSupported | deviceSupported | deviceDefault
Dan Albert0981b5c2018-08-02 13:46:35 -07001112
1113 // Host, HostCross, and Device are built by default.
Chih-Hung Hsiehd0f82fe2021-09-05 20:15:38 -07001114 // Building Device can be disabled with `device_supported: false`
1115 // Building Host and HostCross can be disabled with `host_supported: false`
Colin Cross34037c62020-11-17 13:19:17 -08001116 HostAndDeviceDefault = hostSupported | hostCrossSupported | hostDefault |
1117 deviceSupported | deviceDefault
Dan Albert0981b5c2018-08-02 13:46:35 -07001118
1119 // Nothing is supported. This is not exposed to the user, but used to mark a
1120 // host only module as unsupported when the module type is not supported on
1121 // the host OS. E.g. benchmarks are supported on Linux but not Darwin.
Colin Cross34037c62020-11-17 13:19:17 -08001122 NeitherHostNorDeviceSupported = 0
Colin Crossa1ad8d12016-06-01 17:09:44 -07001123)
1124
Jiyong Park2db76922017-11-08 16:03:48 +09001125type moduleKind int
1126
1127const (
1128 platformModule moduleKind = iota
1129 deviceSpecificModule
1130 socSpecificModule
1131 productSpecificModule
Justin Yund5f6c822019-06-25 16:47:17 +09001132 systemExtSpecificModule
Jiyong Park2db76922017-11-08 16:03:48 +09001133)
1134
1135func (k moduleKind) String() string {
1136 switch k {
1137 case platformModule:
1138 return "platform"
1139 case deviceSpecificModule:
1140 return "device-specific"
1141 case socSpecificModule:
1142 return "soc-specific"
1143 case productSpecificModule:
1144 return "product-specific"
Justin Yund5f6c822019-06-25 16:47:17 +09001145 case systemExtSpecificModule:
1146 return "systemext-specific"
Jiyong Park2db76922017-11-08 16:03:48 +09001147 default:
1148 panic(fmt.Errorf("unknown module kind %d", k))
1149 }
1150}
1151
Colin Cross9d34f352019-11-22 16:03:51 -08001152func initAndroidModuleBase(m Module) {
1153 m.base().module = m
1154}
1155
Colin Crossa6845402020-11-16 15:08:19 -08001156// InitAndroidModule initializes the Module as an Android module that is not architecture-specific.
1157// It adds the common properties, for example "name" and "enabled".
Colin Cross36242852017-06-23 15:06:31 -07001158func InitAndroidModule(m Module) {
Colin Cross9d34f352019-11-22 16:03:51 -08001159 initAndroidModuleBase(m)
Colin Cross3f40fa42015-01-30 17:27:36 -08001160 base := m.base()
Colin Cross5049f022015-03-18 13:28:46 -07001161
Colin Cross36242852017-06-23 15:06:31 -07001162 m.AddProperties(
Colin Crossfc754582016-05-17 16:34:16 -07001163 &base.nameProperties,
Paul Duffined875132020-09-02 13:08:57 +01001164 &base.commonProperties,
1165 &base.distProperties)
Colin Cross18c46802019-09-24 22:19:02 -07001166
Colin Crosseabaedd2020-02-06 17:01:55 -08001167 initProductVariableModule(m)
Colin Cross18c46802019-09-24 22:19:02 -07001168
Paul Duffin63c6e182019-07-24 14:24:38 +01001169 // The default_visibility property needs to be checked and parsed by the visibility module during
Paul Duffin5ec73ec2020-05-01 17:52:01 +01001170 // its checking and parsing phases so make it the primary visibility property.
1171 setPrimaryVisibilityProperty(m, "visibility", &base.commonProperties.Visibility)
Bob Badour37af0462021-01-07 03:34:31 +00001172
1173 // The default_applicable_licenses property needs to be checked and parsed by the licenses module during
1174 // its checking and parsing phases so make it the primary licenses property.
1175 setPrimaryLicensesProperty(m, "licenses", &base.commonProperties.Licenses)
Colin Cross5049f022015-03-18 13:28:46 -07001176}
1177
Colin Crossa6845402020-11-16 15:08:19 -08001178// InitAndroidArchModule initializes the Module as an Android module that is architecture-specific.
1179// It adds the common properties, for example "name" and "enabled", as well as runtime generated
1180// property structs for architecture-specific versions of generic properties tagged with
1181// `android:"arch_variant"`.
1182//
Colin Crossd079e0b2022-08-16 10:27:33 -07001183// InitAndroidModule should not be called if InitAndroidArchModule was called.
Colin Cross36242852017-06-23 15:06:31 -07001184func InitAndroidArchModule(m Module, hod HostOrDeviceSupported, defaultMultilib Multilib) {
1185 InitAndroidModule(m)
Colin Cross5049f022015-03-18 13:28:46 -07001186
1187 base := m.base()
Colin Cross3f40fa42015-01-30 17:27:36 -08001188 base.commonProperties.HostOrDeviceSupported = hod
Colin Cross69617d32016-09-06 10:39:07 -07001189 base.commonProperties.Default_multilib = string(defaultMultilib)
Dan Willemsen0b24c742016-10-04 15:13:37 -07001190 base.commonProperties.ArchSpecific = true
Colin Crossee0bc3b2018-10-02 22:01:37 -07001191 base.commonProperties.UseTargetVariants = true
Colin Cross3f40fa42015-01-30 17:27:36 -08001192
Colin Cross34037c62020-11-17 13:19:17 -08001193 if hod&hostSupported != 0 && hod&deviceSupported != 0 {
Colin Cross36242852017-06-23 15:06:31 -07001194 m.AddProperties(&base.hostAndDeviceProperties)
Colin Cross3f40fa42015-01-30 17:27:36 -08001195 }
1196
Colin Crossa6845402020-11-16 15:08:19 -08001197 initArchModule(m)
Colin Cross3f40fa42015-01-30 17:27:36 -08001198}
1199
Colin Crossa6845402020-11-16 15:08:19 -08001200// InitAndroidMultiTargetsArchModule initializes the Module as an Android module that is
1201// architecture-specific, but will only have a single variant per OS that handles all the
1202// architectures simultaneously. The list of Targets that it must handle will be available from
1203// ModuleContext.MultiTargets. It adds the common properties, for example "name" and "enabled", as
1204// well as runtime generated property structs for architecture-specific versions of generic
1205// properties tagged with `android:"arch_variant"`.
1206//
1207// InitAndroidModule or InitAndroidArchModule should not be called if
1208// InitAndroidMultiTargetsArchModule was called.
Colin Crossee0bc3b2018-10-02 22:01:37 -07001209func InitAndroidMultiTargetsArchModule(m Module, hod HostOrDeviceSupported, defaultMultilib Multilib) {
1210 InitAndroidArchModule(m, hod, defaultMultilib)
1211 m.base().commonProperties.UseTargetVariants = false
1212}
1213
Colin Crossa6845402020-11-16 15:08:19 -08001214// InitCommonOSAndroidMultiTargetsArchModule initializes the Module as an Android module that is
1215// architecture-specific, but will only have a single variant per OS that handles all the
1216// architectures simultaneously, and will also have an additional CommonOS variant that has
1217// dependencies on all the OS-specific variants. The list of Targets that it must handle will be
1218// available from ModuleContext.MultiTargets. It adds the common properties, for example "name" and
1219// "enabled", as well as runtime generated property structs for architecture-specific versions of
1220// generic properties tagged with `android:"arch_variant"`.
1221//
1222// InitAndroidModule, InitAndroidArchModule or InitAndroidMultiTargetsArchModule should not be
1223// called if InitCommonOSAndroidMultiTargetsArchModule was called.
Paul Duffin1356d8c2020-02-25 19:26:33 +00001224func InitCommonOSAndroidMultiTargetsArchModule(m Module, hod HostOrDeviceSupported, defaultMultilib Multilib) {
1225 InitAndroidArchModule(m, hod, defaultMultilib)
1226 m.base().commonProperties.UseTargetVariants = false
1227 m.base().commonProperties.CreateCommonOSVariant = true
1228}
1229
Chris Parsons58852a02021-12-09 18:10:18 -05001230func (attrs *CommonAttributes) fillCommonBp2BuildModuleAttrs(ctx *topDownMutatorContext,
1231 enabledPropertyOverrides bazel.BoolAttribute) constraintAttributes {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +00001232
1233 mod := ctx.Module().base()
Sasha Smundake198eaf2022-08-04 13:07:02 -07001234 // Assert passed-in attributes include Name
1235 if len(attrs.Name) == 0 {
Sasha Smundakfb589492022-08-04 11:13:27 -07001236 if ctx.ModuleType() != "package" {
1237 ctx.ModuleErrorf("CommonAttributes in fillCommonBp2BuildModuleAttrs expects a `.Name`!")
1238 }
Sasha Smundake198eaf2022-08-04 13:07:02 -07001239 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +00001240
1241 depsToLabelList := func(deps []string) bazel.LabelListAttribute {
1242 return bazel.MakeLabelListAttribute(BazelLabelForModuleDeps(ctx, deps))
1243 }
1244
Chris Parsons58852a02021-12-09 18:10:18 -05001245 var enabledProperty bazel.BoolAttribute
Liz Kammerdfeb1202022-05-13 17:20:20 -04001246
1247 onlyAndroid := false
1248 neitherHostNorDevice := false
1249
1250 osSupport := map[string]bool{}
1251
1252 // if the target is enabled and supports arch variance, determine the defaults based on the module
1253 // type's host or device property and host_supported/device_supported properties
1254 if mod.commonProperties.ArchSpecific {
1255 moduleSupportsDevice := mod.DeviceSupported()
1256 moduleSupportsHost := mod.HostSupported()
1257 if moduleSupportsHost && !moduleSupportsDevice {
1258 // for host only, we specify as unsupported on android rather than listing all host osSupport
1259 // TODO(b/220874839): consider replacing this with a constraint that covers all host osSupport
1260 // instead
1261 enabledProperty.SetSelectValue(bazel.OsConfigurationAxis, Android.Name, proptools.BoolPtr(false))
1262 } else if moduleSupportsDevice && !moduleSupportsHost {
1263 enabledProperty.SetSelectValue(bazel.OsConfigurationAxis, Android.Name, proptools.BoolPtr(true))
1264 // specify as a positive to ensure any target-specific enabled can be resolved
1265 // also save that a target is only android, as if there is only the positive restriction on
1266 // android, it'll be dropped, so we may need to add it back later
1267 onlyAndroid = true
1268 } else if !moduleSupportsHost && !moduleSupportsDevice {
1269 neitherHostNorDevice = true
1270 }
1271
Sasha Smundake198eaf2022-08-04 13:07:02 -07001272 for _, osType := range OsTypeList() {
1273 if osType.Class == Host {
1274 osSupport[osType.Name] = moduleSupportsHost
1275 } else if osType.Class == Device {
1276 osSupport[osType.Name] = moduleSupportsDevice
Liz Kammerdfeb1202022-05-13 17:20:20 -04001277 }
1278 }
1279 }
1280
1281 if neitherHostNorDevice {
1282 // we can't build this, disable
1283 enabledProperty.Value = proptools.BoolPtr(false)
Sasha Smundake198eaf2022-08-04 13:07:02 -07001284 } else if mod.commonProperties.Enabled != nil {
1285 enabledProperty.SetValue(mod.commonProperties.Enabled)
1286 if !*mod.commonProperties.Enabled {
1287 for oss, enabled := range osSupport {
1288 if val := enabledProperty.SelectValue(bazel.OsConfigurationAxis, oss); enabled && val != nil && *val {
Liz Kammerdfeb1202022-05-13 17:20:20 -04001289 // if this should be disabled by default, clear out any enabling we've done
Sasha Smundake198eaf2022-08-04 13:07:02 -07001290 enabledProperty.SetSelectValue(bazel.OsConfigurationAxis, oss, nil)
Liz Kammerdfeb1202022-05-13 17:20:20 -04001291 }
1292 }
1293 }
Chris Parsons58852a02021-12-09 18:10:18 -05001294 }
1295
Sasha Smundak05b0ba62022-09-26 18:15:45 -07001296 attrs.Applicable_licenses = bazel.MakeLabelListAttribute(BazelLabelForModuleDeps(ctx, mod.commonProperties.Licenses))
1297
Jingwen Chena5ecb372022-09-21 09:05:37 +00001298 // The required property can contain the module itself. This causes a cycle
1299 // when generated as the 'data' label list attribute in Bazel. Remove it if
1300 // it exists. See b/247985196.
1301 _, requiredWithoutCycles := RemoveFromList(ctx.ModuleName(), mod.commonProperties.Required)
Wei Li7d8f6182022-10-11 14:38:16 -07001302 requiredWithoutCycles = FirstUniqueStrings(requiredWithoutCycles)
Jingwen Chena5ecb372022-09-21 09:05:37 +00001303 required := depsToLabelList(requiredWithoutCycles)
Sasha Smundake198eaf2022-08-04 13:07:02 -07001304 archVariantProps := mod.GetArchVariantProperties(ctx, &commonProperties{})
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +00001305 for axis, configToProps := range archVariantProps {
1306 for config, _props := range configToProps {
1307 if archProps, ok := _props.(*commonProperties); ok {
Jingwen Chena5ecb372022-09-21 09:05:37 +00001308 _, requiredWithoutCycles := RemoveFromList(ctx.ModuleName(), archProps.Required)
Wei Li7d8f6182022-10-11 14:38:16 -07001309 requiredWithoutCycles = FirstUniqueStrings(requiredWithoutCycles)
Jingwen Chena5ecb372022-09-21 09:05:37 +00001310 required.SetSelectValue(axis, config, depsToLabelList(requiredWithoutCycles).Value)
Liz Kammerdfeb1202022-05-13 17:20:20 -04001311 if !neitherHostNorDevice {
1312 if archProps.Enabled != nil {
1313 if axis != bazel.OsConfigurationAxis || osSupport[config] {
1314 enabledProperty.SetSelectValue(axis, config, archProps.Enabled)
1315 }
1316 }
Chris Parsons58852a02021-12-09 18:10:18 -05001317 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +00001318 }
1319 }
1320 }
Chris Parsons58852a02021-12-09 18:10:18 -05001321
Liz Kammerdfeb1202022-05-13 17:20:20 -04001322 if !neitherHostNorDevice {
1323 if enabledPropertyOverrides.Value != nil {
1324 enabledProperty.Value = enabledPropertyOverrides.Value
1325 }
1326 for _, axis := range enabledPropertyOverrides.SortedConfigurationAxes() {
1327 configToBools := enabledPropertyOverrides.ConfigurableValues[axis]
1328 for cfg, val := range configToBools {
1329 if axis != bazel.OsConfigurationAxis || osSupport[cfg] {
1330 enabledProperty.SetSelectValue(axis, cfg, &val)
1331 }
1332 }
Chris Parsons58852a02021-12-09 18:10:18 -05001333 }
1334 }
1335
Sam Delmerico0e33c9d2022-01-07 20:39:21 +00001336 productConfigEnabledLabels := []bazel.Label{}
Liz Kammerdfeb1202022-05-13 17:20:20 -04001337 // TODO(b/234497586): Soong config variables and product variables have different overriding behavior, we
1338 // should handle it correctly
1339 if !proptools.BoolDefault(enabledProperty.Value, true) && !neitherHostNorDevice {
Sam Delmerico0e33c9d2022-01-07 20:39:21 +00001340 // If the module is not enabled by default, then we can check if a
1341 // product variable enables it
1342 productConfigEnabledLabels = productVariableConfigEnableLabels(ctx)
Chris Parsons58852a02021-12-09 18:10:18 -05001343
Sam Delmerico0e33c9d2022-01-07 20:39:21 +00001344 if len(productConfigEnabledLabels) > 0 {
1345 // In this case, an existing product variable configuration overrides any
1346 // module-level `enable: false` definition
1347 newValue := true
1348 enabledProperty.Value = &newValue
1349 }
1350 }
1351
1352 productConfigEnabledAttribute := bazel.MakeLabelListAttribute(bazel.LabelList{
1353 productConfigEnabledLabels, nil,
1354 })
1355
1356 platformEnabledAttribute, err := enabledProperty.ToLabelListAttribute(
Sasha Smundake198eaf2022-08-04 13:07:02 -07001357 bazel.LabelList{[]bazel.Label{{Label: "@platforms//:incompatible"}}, nil},
Chris Parsons58852a02021-12-09 18:10:18 -05001358 bazel.LabelList{[]bazel.Label{}, nil})
Chris Parsons58852a02021-12-09 18:10:18 -05001359 if err != nil {
Sam Delmerico0e33c9d2022-01-07 20:39:21 +00001360 ctx.ModuleErrorf("Error processing platform enabled attribute: %s", err)
Chris Parsons58852a02021-12-09 18:10:18 -05001361 }
Sam Delmerico0e33c9d2022-01-07 20:39:21 +00001362
Liz Kammerdfeb1202022-05-13 17:20:20 -04001363 // if android is the only arch/os enabled, then add a restriction to only be compatible with android
1364 if platformEnabledAttribute.IsNil() && onlyAndroid {
1365 l := bazel.LabelAttribute{}
1366 l.SetValue(bazel.Label{Label: bazel.OsConfigurationAxis.SelectKey(Android.Name)})
1367 platformEnabledAttribute.Add(&l)
1368 }
1369
Spandan Das4238c652022-09-09 01:38:47 +00001370 if !proptools.Bool(attrs.SkipData) {
1371 attrs.Data.Append(required)
1372 }
1373 // SkipData is not an attribute of any Bazel target
1374 // Set this to nil so that it does not appear in the generated build file
1375 attrs.SkipData = nil
Sam Delmerico0e33c9d2022-01-07 20:39:21 +00001376
Sam Delmerico0e33c9d2022-01-07 20:39:21 +00001377 moduleEnableConstraints := bazel.LabelListAttribute{}
1378 moduleEnableConstraints.Append(platformEnabledAttribute)
1379 moduleEnableConstraints.Append(productConfigEnabledAttribute)
Sam Delmerico0e33c9d2022-01-07 20:39:21 +00001380
Sasha Smundake198eaf2022-08-04 13:07:02 -07001381 return constraintAttributes{Target_compatible_with: moduleEnableConstraints}
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +00001382}
1383
Sam Delmerico0e33c9d2022-01-07 20:39:21 +00001384// Check product variables for `enabled: true` flag override.
1385// Returns a list of the constraint_value targets who enable this override.
1386func productVariableConfigEnableLabels(ctx *topDownMutatorContext) []bazel.Label {
Cole Faust912bc882023-03-08 12:29:50 -08001387 productVariableProps := ProductVariableProperties(ctx, ctx.Module())
Sam Delmerico0e33c9d2022-01-07 20:39:21 +00001388 productConfigEnablingTargets := []bazel.Label{}
1389 const propName = "Enabled"
1390 if productConfigProps, exists := productVariableProps[propName]; exists {
1391 for productConfigProp, prop := range productConfigProps {
1392 flag, ok := prop.(*bool)
1393 if !ok {
1394 ctx.ModuleErrorf("Could not convert product variable %s property", proptools.PropertyNameForField(propName))
1395 }
1396
1397 if *flag {
1398 axis := productConfigProp.ConfigurationAxis()
1399 targetLabel := axis.SelectKey(productConfigProp.SelectKey())
1400 productConfigEnablingTargets = append(productConfigEnablingTargets, bazel.Label{
1401 Label: targetLabel,
1402 })
1403 } else {
1404 // TODO(b/210546943): handle negative case where `enabled: false`
1405 ctx.ModuleErrorf("`enabled: false` is not currently supported for configuration variables. See b/210546943", proptools.PropertyNameForField(propName))
1406 }
1407 }
1408 }
1409
1410 return productConfigEnablingTargets
1411}
1412
Nan Zhangb9eeb1d2017-02-02 10:46:07 -08001413// A ModuleBase object contains the properties that are common to all Android
Colin Cross3f40fa42015-01-30 17:27:36 -08001414// modules. It should be included as an anonymous field in every module
1415// struct definition. InitAndroidModule should then be called from the module's
1416// factory function, and the return values from InitAndroidModule should be
1417// returned from the factory function.
1418//
Nan Zhangb9eeb1d2017-02-02 10:46:07 -08001419// The ModuleBase type is responsible for implementing the GenerateBuildActions
1420// method to support the blueprint.Module interface. This method will then call
1421// the module's GenerateAndroidBuildActions method once for each build variant
Colin Cross25de6c32019-06-06 14:29:25 -07001422// that is to be built. GenerateAndroidBuildActions is passed a ModuleContext
1423// rather than the usual blueprint.ModuleContext.
1424// ModuleContext exposes extra functionality specific to the Android build
Colin Cross3f40fa42015-01-30 17:27:36 -08001425// system including details about the particular build variant that is to be
1426// generated.
1427//
1428// For example:
1429//
Zhenhuang Wang0ac5a432022-08-12 18:49:20 +08001430// import (
1431// "android/soong/android"
1432// )
Colin Cross3f40fa42015-01-30 17:27:36 -08001433//
Zhenhuang Wang0ac5a432022-08-12 18:49:20 +08001434// type myModule struct {
1435// android.ModuleBase
1436// properties struct {
1437// MyProperty string
1438// }
1439// }
Colin Cross3f40fa42015-01-30 17:27:36 -08001440//
Zhenhuang Wang0ac5a432022-08-12 18:49:20 +08001441// func NewMyModule() android.Module {
1442// m := &myModule{}
1443// m.AddProperties(&m.properties)
1444// android.InitAndroidModule(m)
1445// return m
1446// }
Colin Cross3f40fa42015-01-30 17:27:36 -08001447//
Zhenhuang Wang0ac5a432022-08-12 18:49:20 +08001448// func (m *myModule) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1449// // Get the CPU architecture for the current build variant.
1450// variantArch := ctx.Arch()
Colin Cross3f40fa42015-01-30 17:27:36 -08001451//
Zhenhuang Wang0ac5a432022-08-12 18:49:20 +08001452// // ...
1453// }
Colin Cross635c3b02016-05-18 15:37:25 -07001454type ModuleBase struct {
Colin Cross3f40fa42015-01-30 17:27:36 -08001455 // Putting the curiously recurring thing pointing to the thing that contains
1456 // the thing pattern to good use.
Colin Cross36242852017-06-23 15:06:31 -07001457 // TODO: remove this
Colin Cross635c3b02016-05-18 15:37:25 -07001458 module Module
Colin Cross3f40fa42015-01-30 17:27:36 -08001459
Colin Crossfc754582016-05-17 16:34:16 -07001460 nameProperties nameProperties
Colin Cross3f40fa42015-01-30 17:27:36 -08001461 commonProperties commonProperties
Paul Duffined875132020-09-02 13:08:57 +01001462 distProperties distProperties
Colin Cross18c46802019-09-24 22:19:02 -07001463 variableProperties interface{}
Colin Cross3f40fa42015-01-30 17:27:36 -08001464 hostAndDeviceProperties hostAndDeviceProperties
Jingwen Chen5d864492021-02-24 07:20:12 -05001465
Usta851a3272022-01-05 23:42:33 -05001466 // Arch specific versions of structs in GetProperties() prior to
1467 // initialization in InitAndroidArchModule, lets call it `generalProperties`.
1468 // The outer index has the same order as generalProperties and the inner index
1469 // chooses the props specific to the architecture. The interface{} value is an
1470 // archPropRoot that is filled with arch specific values by the arch mutator.
Jingwen Chen5d864492021-02-24 07:20:12 -05001471 archProperties [][]interface{}
1472
Jingwen Chen73850672020-12-14 08:25:34 -05001473 // Properties specific to the Blueprint to BUILD migration.
1474 bazelTargetModuleProperties bazel.BazelTargetModuleProperties
1475
Paul Duffin63c6e182019-07-24 14:24:38 +01001476 // Information about all the properties on the module that contains visibility rules that need
1477 // checking.
1478 visibilityPropertyInfo []visibilityProperty
1479
1480 // The primary visibility property, may be nil, that controls access to the module.
1481 primaryVisibilityProperty visibilityProperty
1482
Bob Badour37af0462021-01-07 03:34:31 +00001483 // The primary licenses property, may be nil, records license metadata for the module.
1484 primaryLicensesProperty applicableLicensesProperty
1485
Colin Crossffe6b9d2020-12-01 15:40:06 -08001486 noAddressSanitizer bool
1487 installFiles InstallPaths
1488 installFilesDepSet *installPathsDepSet
1489 checkbuildFiles Paths
1490 packagingSpecs []PackagingSpec
1491 packagingSpecsDepSet *packagingSpecsDepSet
Colin Cross6301c3c2021-09-28 17:40:21 -07001492 // katiInstalls tracks the install rules that were created by Soong but are being exported
1493 // to Make to convert to ninja rules so that Make can add additional dependencies.
1494 katiInstalls katiInstalls
1495 katiSymlinks katiInstalls
Colin Cross1f8c52b2015-06-16 16:38:17 -07001496
Paul Duffinaf970a22020-11-23 23:32:56 +00001497 // The files to copy to the dist as explicitly specified in the .bp file.
1498 distFiles TaggedDistFiles
1499
Colin Cross1f8c52b2015-06-16 16:38:17 -07001500 // Used by buildTargetSingleton to create checkbuild and per-directory build targets
1501 // Only set on the final variant of each module
Colin Cross0875c522017-11-28 17:34:01 -08001502 installTarget WritablePath
1503 checkbuildTarget WritablePath
Colin Cross1f8c52b2015-06-16 16:38:17 -07001504 blueprintDir string
Colin Crossa120ec12016-08-19 16:07:38 -07001505
Colin Cross178a5092016-09-13 13:42:32 -07001506 hooks hooks
Colin Cross36242852017-06-23 15:06:31 -07001507
1508 registerProps []interface{}
Colin Crosscec81712017-07-13 14:43:27 -07001509
1510 // For tests
Colin Crossae887032017-10-23 17:16:14 -07001511 buildParams []BuildParams
Colin Cross4c83e5c2019-02-25 14:54:28 -08001512 ruleParams map[blueprint.Rule]blueprint.RuleParams
Jaewoong Jung38e4fb22018-12-12 09:01:34 -08001513 variables map[string]string
Colin Crossa9d8bee2018-10-02 13:59:46 -07001514
Inseob Kim8471cda2019-11-15 09:59:12 +09001515 initRcPaths Paths
1516 vintfFragmentsPaths Paths
Colin Cross4acaea92021-12-10 23:05:02 +00001517
1518 // set of dependency module:location mappings used to populate the license metadata for
1519 // apex containers.
1520 licenseInstallMap []string
Colin Crossaa1cab02022-01-28 14:49:24 -08001521
1522 // The path to the generated license metadata file for the module.
1523 licenseMetadataFile WritablePath
Colin Cross36242852017-06-23 15:06:31 -07001524}
1525
Liz Kammer2ada09a2021-08-11 00:17:36 -04001526// A struct containing all relevant information about a Bazel target converted via bp2build.
1527type bp2buildInfo struct {
Chris Parsons58852a02021-12-09 18:10:18 -05001528 Dir string
1529 BazelProps bazel.BazelTargetModuleProperties
1530 CommonAttrs CommonAttributes
1531 ConstraintAttrs constraintAttributes
1532 Attrs interface{}
Liz Kammer2ada09a2021-08-11 00:17:36 -04001533}
1534
1535// TargetName returns the Bazel target name of a bp2build converted target.
1536func (b bp2buildInfo) TargetName() string {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +00001537 return b.CommonAttrs.Name
Liz Kammer2ada09a2021-08-11 00:17:36 -04001538}
1539
1540// TargetPackage returns the Bazel package of a bp2build converted target.
1541func (b bp2buildInfo) TargetPackage() string {
1542 return b.Dir
1543}
1544
1545// BazelRuleClass returns the Bazel rule class of a bp2build converted target.
1546func (b bp2buildInfo) BazelRuleClass() string {
1547 return b.BazelProps.Rule_class
1548}
1549
1550// BazelRuleLoadLocation returns the location of the Bazel rule of a bp2build converted target.
1551// This may be empty as native Bazel rules do not need to be loaded.
1552func (b bp2buildInfo) BazelRuleLoadLocation() string {
1553 return b.BazelProps.Bzl_load_location
1554}
1555
1556// 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 +00001557func (b bp2buildInfo) BazelAttributes() []interface{} {
Chris Parsons58852a02021-12-09 18:10:18 -05001558 return []interface{}{&b.CommonAttrs, &b.ConstraintAttrs, b.Attrs}
Liz Kammer2ada09a2021-08-11 00:17:36 -04001559}
1560
1561func (m *ModuleBase) addBp2buildInfo(info bp2buildInfo) {
Sasha Smundaka0954062022-08-02 18:23:58 -07001562 m.commonProperties.BazelConversionStatus.Bp2buildInfo = append(m.commonProperties.BazelConversionStatus.Bp2buildInfo, info)
Liz Kammer2ada09a2021-08-11 00:17:36 -04001563}
1564
1565// IsConvertedByBp2build returns whether this module was converted via bp2build.
1566func (m *ModuleBase) IsConvertedByBp2build() bool {
Sasha Smundaka0954062022-08-02 18:23:58 -07001567 return len(m.commonProperties.BazelConversionStatus.Bp2buildInfo) > 0
Liz Kammer2ada09a2021-08-11 00:17:36 -04001568}
1569
1570// Bp2buildTargets returns the Bazel targets bp2build generated for this module.
1571func (m *ModuleBase) Bp2buildTargets() []bp2buildInfo {
Sasha Smundaka0954062022-08-02 18:23:58 -07001572 return m.commonProperties.BazelConversionStatus.Bp2buildInfo
Liz Kammer2ada09a2021-08-11 00:17:36 -04001573}
1574
Liz Kammer6eff3232021-08-26 08:37:59 -04001575// AddUnconvertedBp2buildDep stores module name of a dependency that was not converted to Bazel.
1576func (b *baseModuleContext) AddUnconvertedBp2buildDep(dep string) {
Sasha Smundaka0954062022-08-02 18:23:58 -07001577 unconvertedDeps := &b.Module().base().commonProperties.BazelConversionStatus.UnconvertedDeps
Liz Kammer6eff3232021-08-26 08:37:59 -04001578 *unconvertedDeps = append(*unconvertedDeps, dep)
1579}
1580
Liz Kammerdaa09ef2021-12-15 15:35:38 -05001581// AddMissingBp2buildDep stores module name of a dependency that was not found in a Android.bp file.
1582func (b *baseModuleContext) AddMissingBp2buildDep(dep string) {
Sasha Smundaka0954062022-08-02 18:23:58 -07001583 missingDeps := &b.Module().base().commonProperties.BazelConversionStatus.MissingDeps
Liz Kammerdaa09ef2021-12-15 15:35:38 -05001584 *missingDeps = append(*missingDeps, dep)
1585}
1586
Liz Kammer6eff3232021-08-26 08:37:59 -04001587// GetUnconvertedBp2buildDeps returns the list of module names of this module's direct dependencies that
1588// were not converted to Bazel.
1589func (m *ModuleBase) GetUnconvertedBp2buildDeps() []string {
Sasha Smundaka0954062022-08-02 18:23:58 -07001590 return FirstUniqueStrings(m.commonProperties.BazelConversionStatus.UnconvertedDeps)
Liz Kammer6eff3232021-08-26 08:37:59 -04001591}
1592
Usta Shrestha56b84e72022-09-24 00:26:47 -04001593// GetMissingBp2buildDeps returns the list of module names that were not found in Android.bp files.
Liz Kammerdaa09ef2021-12-15 15:35:38 -05001594func (m *ModuleBase) GetMissingBp2buildDeps() []string {
Sasha Smundaka0954062022-08-02 18:23:58 -07001595 return FirstUniqueStrings(m.commonProperties.BazelConversionStatus.MissingDeps)
Liz Kammerdaa09ef2021-12-15 15:35:38 -05001596}
1597
Lukacs T. Berkid18d8ca2021-06-25 09:11:22 +02001598func (m *ModuleBase) AddJSONData(d *map[string]interface{}) {
Liz Kammer9525e712022-01-05 13:46:24 -05001599 (*d)["Android"] = map[string]interface{}{
1600 // Properties set in Blueprint or in blueprint of a defaults modules
1601 "SetProperties": m.propertiesWithValues(),
1602 }
1603}
1604
1605type propInfo struct {
Liz Kammer898e0762022-03-22 11:27:26 -04001606 Name string
1607 Type string
1608 Value string
1609 Values []string
Liz Kammer9525e712022-01-05 13:46:24 -05001610}
1611
1612func (m *ModuleBase) propertiesWithValues() []propInfo {
1613 var info []propInfo
1614 props := m.GetProperties()
1615
1616 var propsWithValues func(name string, v reflect.Value)
1617 propsWithValues = func(name string, v reflect.Value) {
1618 kind := v.Kind()
1619 switch kind {
1620 case reflect.Ptr, reflect.Interface:
1621 if v.IsNil() {
1622 return
1623 }
1624 propsWithValues(name, v.Elem())
1625 case reflect.Struct:
1626 if v.IsZero() {
1627 return
1628 }
1629 for i := 0; i < v.NumField(); i++ {
1630 namePrefix := name
1631 sTyp := v.Type().Field(i)
1632 if proptools.ShouldSkipProperty(sTyp) {
1633 continue
1634 }
1635 if name != "" && !strings.HasSuffix(namePrefix, ".") {
1636 namePrefix += "."
1637 }
1638 if !proptools.IsEmbedded(sTyp) {
1639 namePrefix += sTyp.Name
1640 }
1641 sVal := v.Field(i)
1642 propsWithValues(namePrefix, sVal)
1643 }
1644 case reflect.Array, reflect.Slice:
1645 if v.IsNil() {
1646 return
1647 }
1648 elKind := v.Type().Elem().Kind()
Liz Kammer898e0762022-03-22 11:27:26 -04001649 info = append(info, propInfo{Name: name, Type: elKind.String() + " " + kind.String(), Values: sliceReflectionValue(v)})
Liz Kammer9525e712022-01-05 13:46:24 -05001650 default:
Liz Kammer898e0762022-03-22 11:27:26 -04001651 info = append(info, propInfo{Name: name, Type: kind.String(), Value: reflectionValue(v)})
Liz Kammer9525e712022-01-05 13:46:24 -05001652 }
1653 }
1654
1655 for _, p := range props {
1656 propsWithValues("", reflect.ValueOf(p).Elem())
1657 }
Liz Kammer898e0762022-03-22 11:27:26 -04001658 sort.Slice(info, func(i, j int) bool {
1659 return info[i].Name < info[j].Name
1660 })
Liz Kammer9525e712022-01-05 13:46:24 -05001661 return info
Lukacs T. Berkid18d8ca2021-06-25 09:11:22 +02001662}
1663
Liz Kammer898e0762022-03-22 11:27:26 -04001664func reflectionValue(value reflect.Value) string {
1665 switch value.Kind() {
1666 case reflect.Bool:
1667 return fmt.Sprintf("%t", value.Bool())
1668 case reflect.Int64:
1669 return fmt.Sprintf("%d", value.Int())
1670 case reflect.String:
1671 return fmt.Sprintf("%s", value.String())
1672 case reflect.Struct:
1673 if value.IsZero() {
1674 return "{}"
1675 }
1676 length := value.NumField()
1677 vals := make([]string, length, length)
1678 for i := 0; i < length; i++ {
1679 sTyp := value.Type().Field(i)
1680 if proptools.ShouldSkipProperty(sTyp) {
1681 continue
1682 }
1683 name := sTyp.Name
1684 vals[i] = fmt.Sprintf("%s: %s", name, reflectionValue(value.Field(i)))
1685 }
1686 return fmt.Sprintf("%s{%s}", value.Type(), strings.Join(vals, ", "))
1687 case reflect.Array, reflect.Slice:
1688 vals := sliceReflectionValue(value)
1689 return fmt.Sprintf("[%s]", strings.Join(vals, ", "))
1690 }
1691 return ""
1692}
1693
1694func sliceReflectionValue(value reflect.Value) []string {
1695 length := value.Len()
1696 vals := make([]string, length, length)
1697 for i := 0; i < length; i++ {
1698 vals[i] = reflectionValue(value.Index(i))
1699 }
1700 return vals
1701}
1702
Paul Duffin44f1d842020-06-26 20:17:02 +01001703func (m *ModuleBase) ComponentDepsMutator(BottomUpMutatorContext) {}
1704
Colin Cross4157e882019-06-06 16:57:04 -07001705func (m *ModuleBase) DepsMutator(BottomUpMutatorContext) {}
Colin Cross5f692ec2019-02-01 16:53:07 -08001706
Usta355a5872021-12-01 15:16:32 -05001707// AddProperties "registers" the provided props
1708// each value in props MUST be a pointer to a struct
Colin Cross4157e882019-06-06 16:57:04 -07001709func (m *ModuleBase) AddProperties(props ...interface{}) {
1710 m.registerProps = append(m.registerProps, props...)
Colin Cross36242852017-06-23 15:06:31 -07001711}
1712
Colin Cross4157e882019-06-06 16:57:04 -07001713func (m *ModuleBase) GetProperties() []interface{} {
1714 return m.registerProps
Colin Cross3f40fa42015-01-30 17:27:36 -08001715}
1716
Colin Cross4157e882019-06-06 16:57:04 -07001717func (m *ModuleBase) BuildParamsForTests() []BuildParams {
Chih-Hung Hsiehb8082292021-09-09 23:20:39 -07001718 // Expand the references to module variables like $flags[0-9]*,
1719 // so we do not need to change many existing unit tests.
1720 // This looks like undoing the shareFlags optimization in cc's
1721 // transformSourceToObj, and should only affects unit tests.
1722 vars := m.VariablesForTests()
1723 buildParams := append([]BuildParams(nil), m.buildParams...)
Sasha Smundake198eaf2022-08-04 13:07:02 -07001724 for i := range buildParams {
Chih-Hung Hsiehb8082292021-09-09 23:20:39 -07001725 newArgs := make(map[string]string)
1726 for k, v := range buildParams[i].Args {
1727 newArgs[k] = v
1728 // Replaces both ${flags1} and $flags1 syntax.
1729 if strings.HasPrefix(v, "${") && strings.HasSuffix(v, "}") {
1730 if value, found := vars[v[2:len(v)-1]]; found {
1731 newArgs[k] = value
1732 }
1733 } else if strings.HasPrefix(v, "$") {
1734 if value, found := vars[v[1:]]; found {
1735 newArgs[k] = value
1736 }
1737 }
1738 }
1739 buildParams[i].Args = newArgs
1740 }
1741 return buildParams
Colin Crosscec81712017-07-13 14:43:27 -07001742}
1743
Colin Cross4157e882019-06-06 16:57:04 -07001744func (m *ModuleBase) RuleParamsForTests() map[blueprint.Rule]blueprint.RuleParams {
1745 return m.ruleParams
Colin Cross4c83e5c2019-02-25 14:54:28 -08001746}
1747
Colin Cross4157e882019-06-06 16:57:04 -07001748func (m *ModuleBase) VariablesForTests() map[string]string {
1749 return m.variables
Jaewoong Jung38e4fb22018-12-12 09:01:34 -08001750}
1751
Colin Crossce75d2c2016-10-06 16:12:58 -07001752// Name returns the name of the module. It may be overridden by individual module types, for
1753// example prebuilts will prepend prebuilt_ to the name.
Colin Cross4157e882019-06-06 16:57:04 -07001754func (m *ModuleBase) Name() string {
1755 return String(m.nameProperties.Name)
Colin Crossfc754582016-05-17 16:34:16 -07001756}
1757
Colin Cross9a362232019-07-01 15:32:45 -07001758// String returns a string that includes the module name and variants for printing during debugging.
1759func (m *ModuleBase) String() string {
1760 sb := strings.Builder{}
1761 sb.WriteString(m.commonProperties.DebugName)
1762 sb.WriteString("{")
1763 for i := range m.commonProperties.DebugMutators {
1764 if i != 0 {
1765 sb.WriteString(",")
1766 }
1767 sb.WriteString(m.commonProperties.DebugMutators[i])
1768 sb.WriteString(":")
1769 sb.WriteString(m.commonProperties.DebugVariations[i])
1770 }
1771 sb.WriteString("}")
1772 return sb.String()
1773}
1774
Colin Crossce75d2c2016-10-06 16:12:58 -07001775// BaseModuleName returns the name of the module as specified in the blueprints file.
Colin Cross4157e882019-06-06 16:57:04 -07001776func (m *ModuleBase) BaseModuleName() string {
1777 return String(m.nameProperties.Name)
Colin Crossce75d2c2016-10-06 16:12:58 -07001778}
1779
Colin Cross4157e882019-06-06 16:57:04 -07001780func (m *ModuleBase) base() *ModuleBase {
1781 return m
Colin Cross3f40fa42015-01-30 17:27:36 -08001782}
1783
Paul Duffine2453c72019-05-31 14:00:04 +01001784func (m *ModuleBase) qualifiedModuleId(ctx BaseModuleContext) qualifiedModuleName {
1785 return qualifiedModuleName{pkg: ctx.ModuleDir(), name: ctx.ModuleName()}
1786}
1787
1788func (m *ModuleBase) visibilityProperties() []visibilityProperty {
Paul Duffin63c6e182019-07-24 14:24:38 +01001789 return m.visibilityPropertyInfo
1790}
1791
Jingwen Chen40fd90a2020-06-15 05:24:19 +00001792func (m *ModuleBase) Dists() []Dist {
Paul Duffined875132020-09-02 13:08:57 +01001793 if len(m.distProperties.Dist.Targets) > 0 {
Jingwen Chen40fd90a2020-06-15 05:24:19 +00001794 // Make a copy of the underlying Dists slice to protect against
1795 // backing array modifications with repeated calls to this method.
Paul Duffined875132020-09-02 13:08:57 +01001796 distsCopy := append([]Dist(nil), m.distProperties.Dists...)
1797 return append(distsCopy, m.distProperties.Dist)
Jingwen Chen40fd90a2020-06-15 05:24:19 +00001798 } else {
Paul Duffined875132020-09-02 13:08:57 +01001799 return m.distProperties.Dists
Jingwen Chen40fd90a2020-06-15 05:24:19 +00001800 }
1801}
1802
1803func (m *ModuleBase) GenerateTaggedDistFiles(ctx BaseModuleContext) TaggedDistFiles {
Paul Duffin74f05592020-11-25 16:37:46 +00001804 var distFiles TaggedDistFiles
Jingwen Chen40fd90a2020-06-15 05:24:19 +00001805 for _, dist := range m.Dists() {
Paul Duffin74f05592020-11-25 16:37:46 +00001806 // If no tag is specified then it means to use the default dist paths so use
1807 // the special tag name which represents that.
1808 tag := proptools.StringDefault(dist.Tag, DefaultDistTag)
1809
Paul Duffinaf970a22020-11-23 23:32:56 +00001810 if outputFileProducer, ok := m.module.(OutputFileProducer); ok {
1811 // Call the OutputFiles(tag) method to get the paths associated with the tag.
1812 distFilesForTag, err := outputFileProducer.OutputFiles(tag)
Paul Duffin74f05592020-11-25 16:37:46 +00001813
Paul Duffinaf970a22020-11-23 23:32:56 +00001814 // If the tag was not supported and is not DefaultDistTag then it is an error.
1815 // Failing to find paths for DefaultDistTag is not an error. It just means
1816 // that the module type requires the legacy behavior.
1817 if err != nil && tag != DefaultDistTag {
1818 ctx.PropertyErrorf("dist.tag", "%s", err.Error())
1819 }
1820
1821 distFiles = distFiles.addPathsForTag(tag, distFilesForTag...)
1822 } else if tag != DefaultDistTag {
1823 // If the tag was specified then it is an error if the module does not
1824 // implement OutputFileProducer because there is no other way of accessing
1825 // the paths for the specified tag.
1826 ctx.PropertyErrorf("dist.tag",
1827 "tag %s not supported because the module does not implement OutputFileProducer", tag)
Jingwen Chen40fd90a2020-06-15 05:24:19 +00001828 }
Jingwen Chen40fd90a2020-06-15 05:24:19 +00001829 }
1830
1831 return distFiles
1832}
1833
Colin Cross4157e882019-06-06 16:57:04 -07001834func (m *ModuleBase) Target() Target {
1835 return m.commonProperties.CompileTarget
Dan Willemsen490fd492015-11-24 17:53:15 -08001836}
1837
Colin Cross4157e882019-06-06 16:57:04 -07001838func (m *ModuleBase) TargetPrimary() bool {
1839 return m.commonProperties.CompilePrimary
Colin Cross8b74d172016-09-13 09:59:14 -07001840}
1841
Colin Cross4157e882019-06-06 16:57:04 -07001842func (m *ModuleBase) MultiTargets() []Target {
1843 return m.commonProperties.CompileMultiTargets
Colin Crossee0bc3b2018-10-02 22:01:37 -07001844}
1845
Colin Cross4157e882019-06-06 16:57:04 -07001846func (m *ModuleBase) Os() OsType {
1847 return m.Target().Os
Dan Willemsen490fd492015-11-24 17:53:15 -08001848}
1849
Colin Cross4157e882019-06-06 16:57:04 -07001850func (m *ModuleBase) Host() bool {
Jiyong Park1613e552020-09-14 19:43:17 +09001851 return m.Os().Class == Host
Dan Willemsen97750522016-02-09 17:43:51 -08001852}
1853
Yo Chiangbba545e2020-06-09 16:15:37 +08001854func (m *ModuleBase) Device() bool {
1855 return m.Os().Class == Device
1856}
1857
Colin Cross4157e882019-06-06 16:57:04 -07001858func (m *ModuleBase) Arch() Arch {
1859 return m.Target().Arch
Dan Willemsen97750522016-02-09 17:43:51 -08001860}
1861
Colin Cross4157e882019-06-06 16:57:04 -07001862func (m *ModuleBase) ArchSpecific() bool {
1863 return m.commonProperties.ArchSpecific
Dan Willemsen0b24c742016-10-04 15:13:37 -07001864}
1865
Paul Duffin1356d8c2020-02-25 19:26:33 +00001866// True if the current variant is a CommonOS variant, false otherwise.
1867func (m *ModuleBase) IsCommonOSVariant() bool {
1868 return m.commonProperties.CommonOSVariant
1869}
1870
Colin Cross34037c62020-11-17 13:19:17 -08001871// supportsTarget returns true if the given Target is supported by the current module.
1872func (m *ModuleBase) supportsTarget(target Target) bool {
1873 switch target.Os.Class {
1874 case Host:
1875 if target.HostCross {
1876 return m.HostCrossSupported()
1877 } else {
1878 return m.HostSupported()
Colin Crossa1ad8d12016-06-01 17:09:44 -07001879 }
Colin Cross34037c62020-11-17 13:19:17 -08001880 case Device:
1881 return m.DeviceSupported()
Colin Crossa1ad8d12016-06-01 17:09:44 -07001882 default:
Jiyong Park1613e552020-09-14 19:43:17 +09001883 return false
Colin Crossa1ad8d12016-06-01 17:09:44 -07001884 }
Colin Cross3f40fa42015-01-30 17:27:36 -08001885}
1886
Colin Cross34037c62020-11-17 13:19:17 -08001887// DeviceSupported returns true if the current module is supported and enabled for device targets,
1888// i.e. the factory method set the HostOrDeviceSupported value to include device support and
1889// the device support is enabled by default or enabled by the device_supported property.
Colin Cross4157e882019-06-06 16:57:04 -07001890func (m *ModuleBase) DeviceSupported() bool {
Colin Cross34037c62020-11-17 13:19:17 -08001891 hod := m.commonProperties.HostOrDeviceSupported
1892 // deviceEnabled is true if the device_supported property is true or the HostOrDeviceSupported
1893 // value has the deviceDefault bit set.
1894 deviceEnabled := proptools.BoolDefault(m.hostAndDeviceProperties.Device_supported, hod&deviceDefault != 0)
1895 return hod&deviceSupported != 0 && deviceEnabled
Colin Cross3f40fa42015-01-30 17:27:36 -08001896}
1897
Colin Cross34037c62020-11-17 13:19:17 -08001898// HostSupported returns true if the current module is supported and enabled for host targets,
1899// i.e. the factory method set the HostOrDeviceSupported value to include host support and
1900// the host support is enabled by default or enabled by the host_supported property.
Paul Duffine44358f2019-11-26 18:04:12 +00001901func (m *ModuleBase) HostSupported() bool {
Colin Cross34037c62020-11-17 13:19:17 -08001902 hod := m.commonProperties.HostOrDeviceSupported
1903 // hostEnabled is true if the host_supported property is true or the HostOrDeviceSupported
1904 // value has the hostDefault bit set.
1905 hostEnabled := proptools.BoolDefault(m.hostAndDeviceProperties.Host_supported, hod&hostDefault != 0)
1906 return hod&hostSupported != 0 && hostEnabled
1907}
1908
1909// HostCrossSupported returns true if the current module is supported and enabled for host cross
1910// targets, i.e. the factory method set the HostOrDeviceSupported value to include host cross
1911// support and the host cross support is enabled by default or enabled by the
1912// host_supported property.
1913func (m *ModuleBase) HostCrossSupported() bool {
1914 hod := m.commonProperties.HostOrDeviceSupported
1915 // hostEnabled is true if the host_supported property is true or the HostOrDeviceSupported
1916 // value has the hostDefault bit set.
1917 hostEnabled := proptools.BoolDefault(m.hostAndDeviceProperties.Host_supported, hod&hostDefault != 0)
1918 return hod&hostCrossSupported != 0 && hostEnabled
Paul Duffine44358f2019-11-26 18:04:12 +00001919}
1920
Colin Cross4157e882019-06-06 16:57:04 -07001921func (m *ModuleBase) Platform() bool {
Justin Yund5f6c822019-06-25 16:47:17 +09001922 return !m.DeviceSpecific() && !m.SocSpecific() && !m.ProductSpecific() && !m.SystemExtSpecific()
Jiyong Parkc678ad32018-04-10 13:07:10 +09001923}
1924
Colin Cross4157e882019-06-06 16:57:04 -07001925func (m *ModuleBase) DeviceSpecific() bool {
1926 return Bool(m.commonProperties.Device_specific)
Jiyong Parkc678ad32018-04-10 13:07:10 +09001927}
1928
Colin Cross4157e882019-06-06 16:57:04 -07001929func (m *ModuleBase) SocSpecific() bool {
1930 return Bool(m.commonProperties.Vendor) || Bool(m.commonProperties.Proprietary) || Bool(m.commonProperties.Soc_specific)
Jiyong Parkc678ad32018-04-10 13:07:10 +09001931}
1932
Colin Cross4157e882019-06-06 16:57:04 -07001933func (m *ModuleBase) ProductSpecific() bool {
1934 return Bool(m.commonProperties.Product_specific)
Jiyong Parkc678ad32018-04-10 13:07:10 +09001935}
1936
Justin Yund5f6c822019-06-25 16:47:17 +09001937func (m *ModuleBase) SystemExtSpecific() bool {
1938 return Bool(m.commonProperties.System_ext_specific)
Dario Frenifd05a742018-05-29 13:28:54 +01001939}
1940
Colin Crossc2d24052020-05-13 11:05:02 -07001941// RequiresStableAPIs returns true if the module will be installed to a partition that may
1942// be updated separately from the system image.
1943func (m *ModuleBase) RequiresStableAPIs(ctx BaseModuleContext) bool {
1944 return m.SocSpecific() || m.DeviceSpecific() ||
1945 (m.ProductSpecific() && ctx.Config().EnforceProductPartitionInterface())
1946}
1947
Bill Peckhamfff3f8a2020-03-20 18:33:20 -07001948func (m *ModuleBase) PartitionTag(config DeviceConfig) string {
1949 partition := "system"
1950 if m.SocSpecific() {
1951 // A SoC-specific module could be on the vendor partition at
1952 // "vendor" or the system partition at "system/vendor".
1953 if config.VendorPath() == "vendor" {
1954 partition = "vendor"
1955 }
1956 } else if m.DeviceSpecific() {
1957 // A device-specific module could be on the odm partition at
1958 // "odm", the vendor partition at "vendor/odm", or the system
1959 // partition at "system/vendor/odm".
1960 if config.OdmPath() == "odm" {
1961 partition = "odm"
Ramy Medhat944839a2020-03-31 22:14:52 -04001962 } else if strings.HasPrefix(config.OdmPath(), "vendor/") {
Bill Peckhamfff3f8a2020-03-20 18:33:20 -07001963 partition = "vendor"
1964 }
1965 } else if m.ProductSpecific() {
1966 // A product-specific module could be on the product partition
1967 // at "product" or the system partition at "system/product".
1968 if config.ProductPath() == "product" {
1969 partition = "product"
1970 }
1971 } else if m.SystemExtSpecific() {
1972 // A system_ext-specific module could be on the system_ext
1973 // partition at "system_ext" or the system partition at
1974 // "system/system_ext".
1975 if config.SystemExtPath() == "system_ext" {
1976 partition = "system_ext"
1977 }
1978 }
1979 return partition
1980}
1981
Colin Cross4157e882019-06-06 16:57:04 -07001982func (m *ModuleBase) Enabled() bool {
Justin Yun32f053b2020-07-31 23:07:17 +09001983 if m.commonProperties.ForcedDisabled {
1984 return false
1985 }
Colin Cross08d6f8f2020-11-19 02:33:19 +00001986 if m.commonProperties.Enabled == nil {
1987 return !m.Os().DefaultDisabled
1988 }
1989 return *m.commonProperties.Enabled
Colin Cross3f40fa42015-01-30 17:27:36 -08001990}
1991
Inseob Kimeec88e12020-01-22 11:11:29 +09001992func (m *ModuleBase) Disable() {
Justin Yun32f053b2020-07-31 23:07:17 +09001993 m.commonProperties.ForcedDisabled = true
Inseob Kimeec88e12020-01-22 11:11:29 +09001994}
1995
Colin Crossa9c8c9f2020-12-16 10:20:23 -08001996// HideFromMake marks this variant so that it is not emitted in the generated Android.mk file.
1997func (m *ModuleBase) HideFromMake() {
1998 m.commonProperties.HideFromMake = true
1999}
2000
2001// IsHideFromMake returns true if HideFromMake was previously called.
2002func (m *ModuleBase) IsHideFromMake() bool {
2003 return m.commonProperties.HideFromMake == true
2004}
2005
2006// SkipInstall marks this variant to not create install rules when ctx.Install* are called.
Colin Cross4157e882019-06-06 16:57:04 -07002007func (m *ModuleBase) SkipInstall() {
2008 m.commonProperties.SkipInstall = true
Colin Crossce75d2c2016-10-06 16:12:58 -07002009}
2010
Martin Stjernholm9e7f45e2020-12-23 03:50:30 +00002011// IsSkipInstall returns true if this variant is marked to not create install
2012// rules when ctx.Install* are called.
2013func (m *ModuleBase) IsSkipInstall() bool {
2014 return m.commonProperties.SkipInstall
2015}
2016
Iván Budnik295da162023-03-10 16:11:26 +00002017// Similar to HideFromMake, but if the AndroidMk entry would set
2018// LOCAL_UNINSTALLABLE_MODULE then this variant may still output that entry
2019// rather than leaving it out altogether. That happens in cases where it would
2020// have other side effects, in particular when it adds a NOTICE file target,
2021// which other install targets might depend on.
2022func (m *ModuleBase) MakeUninstallable() {
Colin Crossbd3a16b2023-04-25 11:30:51 -07002023 m.commonProperties.UninstallableApexPlatformVariant = true
Iván Budnik295da162023-03-10 16:11:26 +00002024 m.HideFromMake()
2025}
2026
Liz Kammer5ca3a622020-08-05 15:40:41 -07002027func (m *ModuleBase) ReplacedByPrebuilt() {
2028 m.commonProperties.ReplacedByPrebuilt = true
Colin Crossa9c8c9f2020-12-16 10:20:23 -08002029 m.HideFromMake()
Liz Kammer5ca3a622020-08-05 15:40:41 -07002030}
2031
2032func (m *ModuleBase) IsReplacedByPrebuilt() bool {
2033 return m.commonProperties.ReplacedByPrebuilt
2034}
2035
Colin Cross4157e882019-06-06 16:57:04 -07002036func (m *ModuleBase) ExportedToMake() bool {
2037 return m.commonProperties.NamespaceExportedToMake
Jiyong Park374510b2018-03-19 18:23:01 +09002038}
2039
Justin Yun1871f902023-04-07 20:13:19 +09002040func (m *ModuleBase) EffectiveLicenseKinds() []string {
2041 return m.commonProperties.Effective_license_kinds
2042}
2043
Justin Yun885a7de2021-06-29 20:34:53 +09002044func (m *ModuleBase) EffectiveLicenseFiles() Paths {
Bob Badour4101c712022-02-09 11:54:35 -08002045 result := make(Paths, 0, len(m.commonProperties.Effective_license_text))
2046 for _, p := range m.commonProperties.Effective_license_text {
2047 result = append(result, p.Path)
2048 }
2049 return result
Justin Yun885a7de2021-06-29 20:34:53 +09002050}
2051
Colin Crosse9fe2942020-11-10 18:12:15 -08002052// computeInstallDeps finds the installed paths of all dependencies that have a dependency
Colin Crossbd3a16b2023-04-25 11:30:51 -07002053// tag that is annotated as needing installation via the isInstallDepNeeded method.
Colin Crossffe6b9d2020-12-01 15:40:06 -08002054func (m *ModuleBase) computeInstallDeps(ctx ModuleContext) ([]*installPathsDepSet, []*packagingSpecsDepSet) {
Colin Cross5d583952020-11-24 16:21:24 -08002055 var installDeps []*installPathsDepSet
Colin Crossffe6b9d2020-12-01 15:40:06 -08002056 var packagingSpecs []*packagingSpecsDepSet
Colin Cross5d583952020-11-24 16:21:24 -08002057 ctx.VisitDirectDeps(func(dep Module) {
Colin Crossbd3a16b2023-04-25 11:30:51 -07002058 if isInstallDepNeeded(dep, ctx.OtherModuleDependencyTag(dep)) {
2059 // Installation is still handled by Make, so anything hidden from Make is not
2060 // installable.
2061 if !dep.IsHideFromMake() && !dep.IsSkipInstall() {
2062 installDeps = append(installDeps, dep.base().installFilesDepSet)
2063 }
2064 // Add packaging deps even when the dependency is not installed so that uninstallable
2065 // modules can still be packaged. Often the package will be installed instead.
Colin Crossffe6b9d2020-12-01 15:40:06 -08002066 packagingSpecs = append(packagingSpecs, dep.base().packagingSpecsDepSet)
Colin Cross897266e2020-02-13 13:22:08 -08002067 }
2068 })
Colin Cross3f40fa42015-01-30 17:27:36 -08002069
Colin Crossffe6b9d2020-12-01 15:40:06 -08002070 return installDeps, packagingSpecs
Colin Cross3f40fa42015-01-30 17:27:36 -08002071}
2072
Colin Crossbd3a16b2023-04-25 11:30:51 -07002073// isInstallDepNeeded returns true if installing the output files of the current module
2074// should also install the output files of the given dependency and dependency tag.
2075func isInstallDepNeeded(dep Module, tag blueprint.DependencyTag) bool {
2076 // Don't add a dependency from the platform to a library provided by an apex.
2077 if dep.base().commonProperties.UninstallableApexPlatformVariant {
2078 return false
2079 }
2080 // Only install modules if the dependency tag is an InstallDepNeeded tag.
2081 return IsInstallDepNeededTag(tag)
2082}
2083
Jiyong Park4dc2a1a2020-09-28 17:46:22 +09002084func (m *ModuleBase) FilesToInstall() InstallPaths {
Colin Cross4157e882019-06-06 16:57:04 -07002085 return m.installFiles
Colin Cross3f40fa42015-01-30 17:27:36 -08002086}
2087
Jiyong Park073ea552020-11-09 14:08:34 +09002088func (m *ModuleBase) PackagingSpecs() []PackagingSpec {
2089 return m.packagingSpecs
2090}
2091
Colin Crossffe6b9d2020-12-01 15:40:06 -08002092func (m *ModuleBase) TransitivePackagingSpecs() []PackagingSpec {
2093 return m.packagingSpecsDepSet.ToList()
2094}
2095
Colin Cross4157e882019-06-06 16:57:04 -07002096func (m *ModuleBase) NoAddressSanitizer() bool {
2097 return m.noAddressSanitizer
Colin Cross3f40fa42015-01-30 17:27:36 -08002098}
2099
Colin Cross4157e882019-06-06 16:57:04 -07002100func (m *ModuleBase) InstallInData() bool {
Dan Willemsen782a2d12015-12-21 14:55:28 -08002101 return false
2102}
2103
Jaewoong Jung0949f312019-09-11 10:25:18 -07002104func (m *ModuleBase) InstallInTestcases() bool {
2105 return false
2106}
2107
Colin Cross4157e882019-06-06 16:57:04 -07002108func (m *ModuleBase) InstallInSanitizerDir() bool {
Vishwath Mohan1dd88392017-03-29 22:00:18 -07002109 return false
2110}
2111
Yifan Hong1b3348d2020-01-21 15:53:22 -08002112func (m *ModuleBase) InstallInRamdisk() bool {
2113 return Bool(m.commonProperties.Ramdisk)
2114}
2115
Yifan Hong60e0cfb2020-10-21 15:17:56 -07002116func (m *ModuleBase) InstallInVendorRamdisk() bool {
2117 return Bool(m.commonProperties.Vendor_ramdisk)
2118}
2119
Inseob Kim08758f02021-04-08 21:13:22 +09002120func (m *ModuleBase) InstallInDebugRamdisk() bool {
2121 return Bool(m.commonProperties.Debug_ramdisk)
2122}
2123
Colin Cross4157e882019-06-06 16:57:04 -07002124func (m *ModuleBase) InstallInRecovery() bool {
2125 return Bool(m.commonProperties.Recovery)
Jiyong Parkf9332f12018-02-01 00:54:12 +09002126}
2127
Kiyoung Kimae11c232021-07-19 11:38:04 +09002128func (m *ModuleBase) InstallInVendor() bool {
Kiyoung Kimf160f7f2022-11-29 10:58:08 +09002129 return Bool(m.commonProperties.Vendor) || Bool(m.commonProperties.Soc_specific) || Bool(m.commonProperties.Proprietary)
Kiyoung Kimae11c232021-07-19 11:38:04 +09002130}
2131
Colin Cross90ba5f42019-10-02 11:10:58 -07002132func (m *ModuleBase) InstallInRoot() bool {
2133 return false
2134}
2135
Jiyong Park87788b52020-09-01 12:37:45 +09002136func (m *ModuleBase) InstallForceOS() (*OsType, *ArchType) {
2137 return nil, nil
Colin Cross6e359402020-02-10 15:29:54 -08002138}
2139
Colin Cross4157e882019-06-06 16:57:04 -07002140func (m *ModuleBase) Owner() string {
2141 return String(m.commonProperties.Owner)
Sundong Ahn4fd04bb2018-08-31 18:01:37 +09002142}
2143
Colin Cross7228ecd2019-11-18 16:00:16 -08002144func (m *ModuleBase) setImageVariation(variant string) {
2145 m.commonProperties.ImageVariation = variant
2146}
2147
2148func (m *ModuleBase) ImageVariation() blueprint.Variation {
2149 return blueprint.Variation{
2150 Mutator: "image",
2151 Variation: m.base().commonProperties.ImageVariation,
2152 }
2153}
2154
Paul Duffin9b76c0b2020-03-12 10:24:35 +00002155func (m *ModuleBase) getVariationByMutatorName(mutator string) string {
2156 for i, v := range m.commonProperties.DebugMutators {
2157 if v == mutator {
2158 return m.commonProperties.DebugVariations[i]
2159 }
2160 }
2161
2162 return ""
2163}
2164
Yifan Hong1b3348d2020-01-21 15:53:22 -08002165func (m *ModuleBase) InRamdisk() bool {
2166 return m.base().commonProperties.ImageVariation == RamdiskVariation
2167}
2168
Yifan Hong60e0cfb2020-10-21 15:17:56 -07002169func (m *ModuleBase) InVendorRamdisk() bool {
2170 return m.base().commonProperties.ImageVariation == VendorRamdiskVariation
2171}
2172
Inseob Kim08758f02021-04-08 21:13:22 +09002173func (m *ModuleBase) InDebugRamdisk() bool {
2174 return m.base().commonProperties.ImageVariation == DebugRamdiskVariation
2175}
2176
Colin Cross7228ecd2019-11-18 16:00:16 -08002177func (m *ModuleBase) InRecovery() bool {
2178 return m.base().commonProperties.ImageVariation == RecoveryVariation
2179}
2180
Jiyong Park6a8cf5f2019-12-30 16:31:09 +09002181func (m *ModuleBase) RequiredModuleNames() []string {
2182 return m.base().commonProperties.Required
2183}
2184
2185func (m *ModuleBase) HostRequiredModuleNames() []string {
2186 return m.base().commonProperties.Host_required
2187}
2188
2189func (m *ModuleBase) TargetRequiredModuleNames() []string {
2190 return m.base().commonProperties.Target_required
2191}
2192
Inseob Kim8471cda2019-11-15 09:59:12 +09002193func (m *ModuleBase) InitRc() Paths {
2194 return append(Paths{}, m.initRcPaths...)
2195}
2196
2197func (m *ModuleBase) VintfFragments() Paths {
2198 return append(Paths{}, m.vintfFragmentsPaths...)
2199}
2200
Yu Liu4ae55d12022-01-05 17:17:23 -08002201func (m *ModuleBase) CompileMultilib() *string {
2202 return m.base().commonProperties.Compile_multilib
2203}
2204
Colin Cross4acaea92021-12-10 23:05:02 +00002205// SetLicenseInstallMap stores the set of dependency module:location mappings for files in an
2206// apex container for use when generation the license metadata file.
2207func (m *ModuleBase) SetLicenseInstallMap(installMap []string) {
2208 m.licenseInstallMap = append(m.licenseInstallMap, installMap...)
2209}
2210
Colin Cross4157e882019-06-06 16:57:04 -07002211func (m *ModuleBase) generateModuleTarget(ctx ModuleContext) {
Colin Cross897266e2020-02-13 13:22:08 -08002212 var allInstalledFiles InstallPaths
2213 var allCheckbuildFiles Paths
Colin Cross0875c522017-11-28 17:34:01 -08002214 ctx.VisitAllModuleVariants(func(module Module) {
2215 a := module.base()
Colin Crossc9404352015-03-26 16:10:12 -07002216 allInstalledFiles = append(allInstalledFiles, a.installFiles...)
Chih-Hung Hsieh80783772021-10-11 16:46:56 -07002217 // A module's -checkbuild phony targets should
Chih-Hung Hsieha3d135b2021-10-14 20:32:53 -07002218 // not be created if the module is not exported to make.
2219 // Those could depend on the build target and fail to compile
2220 // for the current build target.
2221 if !ctx.Config().KatiEnabled() || !shouldSkipAndroidMkProcessing(a) {
2222 allCheckbuildFiles = append(allCheckbuildFiles, a.checkbuildFiles...)
Chih-Hung Hsieha3d135b2021-10-14 20:32:53 -07002223 }
Colin Cross3f40fa42015-01-30 17:27:36 -08002224 })
2225
Colin Cross0875c522017-11-28 17:34:01 -08002226 var deps Paths
Colin Cross9454bfa2015-03-17 13:24:18 -07002227
Colin Cross133ebef2020-08-14 17:38:45 -07002228 namespacePrefix := ctx.Namespace().id
Jeff Gaston088e29e2017-11-29 16:47:17 -08002229 if namespacePrefix != "" {
2230 namespacePrefix = namespacePrefix + "-"
2231 }
2232
Colin Cross3f40fa42015-01-30 17:27:36 -08002233 if len(allInstalledFiles) > 0 {
Colin Crossc3d87d32020-06-04 13:25:17 -07002234 name := namespacePrefix + ctx.ModuleName() + "-install"
2235 ctx.Phony(name, allInstalledFiles.Paths()...)
2236 m.installTarget = PathForPhony(ctx, name)
2237 deps = append(deps, m.installTarget)
Colin Cross9454bfa2015-03-17 13:24:18 -07002238 }
2239
2240 if len(allCheckbuildFiles) > 0 {
Colin Crossc3d87d32020-06-04 13:25:17 -07002241 name := namespacePrefix + ctx.ModuleName() + "-checkbuild"
2242 ctx.Phony(name, allCheckbuildFiles...)
2243 m.checkbuildTarget = PathForPhony(ctx, name)
2244 deps = append(deps, m.checkbuildTarget)
Colin Cross9454bfa2015-03-17 13:24:18 -07002245 }
2246
2247 if len(deps) > 0 {
Dan Willemsen5ba07e82015-12-11 13:51:06 -08002248 suffix := ""
Jingwen Chencda22c92020-11-23 00:22:30 -05002249 if ctx.Config().KatiEnabled() {
Dan Willemsen5ba07e82015-12-11 13:51:06 -08002250 suffix = "-soong"
2251 }
2252
Colin Crossc3d87d32020-06-04 13:25:17 -07002253 ctx.Phony(namespacePrefix+ctx.ModuleName()+suffix, deps...)
Colin Cross1f8c52b2015-06-16 16:38:17 -07002254
Colin Cross4157e882019-06-06 16:57:04 -07002255 m.blueprintDir = ctx.ModuleDir()
Colin Cross3f40fa42015-01-30 17:27:36 -08002256 }
2257}
2258
Colin Crossc34d2322020-01-03 15:23:27 -08002259func determineModuleKind(m *ModuleBase, ctx blueprint.EarlyModuleContext) moduleKind {
Colin Cross4157e882019-06-06 16:57:04 -07002260 var socSpecific = Bool(m.commonProperties.Vendor) || Bool(m.commonProperties.Proprietary) || Bool(m.commonProperties.Soc_specific)
2261 var deviceSpecific = Bool(m.commonProperties.Device_specific)
2262 var productSpecific = Bool(m.commonProperties.Product_specific)
Justin Yund5f6c822019-06-25 16:47:17 +09002263 var systemExtSpecific = Bool(m.commonProperties.System_ext_specific)
Jiyong Park2db76922017-11-08 16:03:48 +09002264
Dario Frenifd05a742018-05-29 13:28:54 +01002265 msg := "conflicting value set here"
2266 if socSpecific && deviceSpecific {
2267 ctx.PropertyErrorf("device_specific", "a module cannot be specific to SoC and device at the same time.")
Colin Cross4157e882019-06-06 16:57:04 -07002268 if Bool(m.commonProperties.Vendor) {
Jiyong Park2db76922017-11-08 16:03:48 +09002269 ctx.PropertyErrorf("vendor", msg)
2270 }
Colin Cross4157e882019-06-06 16:57:04 -07002271 if Bool(m.commonProperties.Proprietary) {
Jiyong Park2db76922017-11-08 16:03:48 +09002272 ctx.PropertyErrorf("proprietary", msg)
2273 }
Colin Cross4157e882019-06-06 16:57:04 -07002274 if Bool(m.commonProperties.Soc_specific) {
Jiyong Park2db76922017-11-08 16:03:48 +09002275 ctx.PropertyErrorf("soc_specific", msg)
2276 }
2277 }
2278
Justin Yund5f6c822019-06-25 16:47:17 +09002279 if productSpecific && systemExtSpecific {
2280 ctx.PropertyErrorf("product_specific", "a module cannot be specific to product and system_ext at the same time.")
2281 ctx.PropertyErrorf("system_ext_specific", msg)
Dario Frenifd05a742018-05-29 13:28:54 +01002282 }
2283
Justin Yund5f6c822019-06-25 16:47:17 +09002284 if (socSpecific || deviceSpecific) && (productSpecific || systemExtSpecific) {
Dario Frenifd05a742018-05-29 13:28:54 +01002285 if productSpecific {
2286 ctx.PropertyErrorf("product_specific", "a module cannot be specific to SoC or device and product at the same time.")
2287 } else {
Justin Yund5f6c822019-06-25 16:47:17 +09002288 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 +01002289 }
2290 if deviceSpecific {
2291 ctx.PropertyErrorf("device_specific", msg)
2292 } else {
Colin Cross4157e882019-06-06 16:57:04 -07002293 if Bool(m.commonProperties.Vendor) {
Dario Frenifd05a742018-05-29 13:28:54 +01002294 ctx.PropertyErrorf("vendor", msg)
2295 }
Colin Cross4157e882019-06-06 16:57:04 -07002296 if Bool(m.commonProperties.Proprietary) {
Dario Frenifd05a742018-05-29 13:28:54 +01002297 ctx.PropertyErrorf("proprietary", msg)
2298 }
Colin Cross4157e882019-06-06 16:57:04 -07002299 if Bool(m.commonProperties.Soc_specific) {
Dario Frenifd05a742018-05-29 13:28:54 +01002300 ctx.PropertyErrorf("soc_specific", msg)
2301 }
2302 }
2303 }
2304
Jiyong Park2db76922017-11-08 16:03:48 +09002305 if productSpecific {
2306 return productSpecificModule
Justin Yund5f6c822019-06-25 16:47:17 +09002307 } else if systemExtSpecific {
2308 return systemExtSpecificModule
Jiyong Park2db76922017-11-08 16:03:48 +09002309 } else if deviceSpecific {
2310 return deviceSpecificModule
2311 } else if socSpecific {
2312 return socSpecificModule
2313 } else {
2314 return platformModule
2315 }
2316}
2317
Colin Crossc34d2322020-01-03 15:23:27 -08002318func (m *ModuleBase) earlyModuleContextFactory(ctx blueprint.EarlyModuleContext) earlyModuleContext {
Colin Cross1184b642019-12-30 18:43:07 -08002319 return earlyModuleContext{
Colin Crossc34d2322020-01-03 15:23:27 -08002320 EarlyModuleContext: ctx,
2321 kind: determineModuleKind(m, ctx),
2322 config: ctx.Config().(Config),
Colin Cross3f40fa42015-01-30 17:27:36 -08002323 }
Colin Cross3f40fa42015-01-30 17:27:36 -08002324}
2325
Colin Cross1184b642019-12-30 18:43:07 -08002326func (m *ModuleBase) baseModuleContextFactory(ctx blueprint.BaseModuleContext) baseModuleContext {
2327 return baseModuleContext{
2328 bp: ctx,
2329 earlyModuleContext: m.earlyModuleContextFactory(ctx),
2330 os: m.commonProperties.CompileOS,
2331 target: m.commonProperties.CompileTarget,
2332 targetPrimary: m.commonProperties.CompilePrimary,
2333 multiTargets: m.commonProperties.CompileMultiTargets,
2334 }
2335}
2336
Colin Cross4157e882019-06-06 16:57:04 -07002337func (m *ModuleBase) GenerateBuildActions(blueprintCtx blueprint.ModuleContext) {
Colin Cross25de6c32019-06-06 14:29:25 -07002338 ctx := &moduleContext{
Colin Cross0ea8ba82019-06-06 14:33:29 -07002339 module: m.module,
Colin Crossdc35e212019-06-06 16:13:11 -07002340 bp: blueprintCtx,
Colin Cross0ea8ba82019-06-06 14:33:29 -07002341 baseModuleContext: m.baseModuleContextFactory(blueprintCtx),
Colin Cross0ea8ba82019-06-06 14:33:29 -07002342 variables: make(map[string]string),
Colin Cross3f40fa42015-01-30 17:27:36 -08002343 }
2344
Colin Crossaa1cab02022-01-28 14:49:24 -08002345 m.licenseMetadataFile = PathForModuleOut(ctx, "meta_lic")
2346
Colin Crossffe6b9d2020-12-01 15:40:06 -08002347 dependencyInstallFiles, dependencyPackagingSpecs := m.computeInstallDeps(ctx)
Colin Cross5d583952020-11-24 16:21:24 -08002348 // set m.installFilesDepSet to only the transitive dependencies to be used as the dependencies
2349 // of installed files of this module. It will be replaced by a depset including the installed
2350 // files of this module at the end for use by modules that depend on this one.
2351 m.installFilesDepSet = newInstallPathsDepSet(nil, dependencyInstallFiles)
2352
Colin Cross6c4f21f2019-06-06 15:41:36 -07002353 // Temporarily continue to call blueprintCtx.GetMissingDependencies() to maintain the previous behavior of never
2354 // reporting missing dependency errors in Blueprint when AllowMissingDependencies == true.
2355 // TODO: This will be removed once defaults modules handle missing dependency errors
2356 blueprintCtx.GetMissingDependencies()
2357
Colin Crossdc35e212019-06-06 16:13:11 -07002358 // For the final GenerateAndroidBuildActions pass, require that all visited dependencies Soong modules and
Paul Duffin1356d8c2020-02-25 19:26:33 +00002359 // are enabled. Unless the module is a CommonOS variant which may have dependencies on disabled variants
2360 // (because the dependencies are added before the modules are disabled). The
2361 // GetOsSpecificVariantsOfCommonOSVariant(...) method will ensure that the disabled variants are
2362 // ignored.
2363 ctx.baseModuleContext.strictVisitDeps = !m.IsCommonOSVariant()
Colin Crossdc35e212019-06-06 16:13:11 -07002364
Colin Cross4c83e5c2019-02-25 14:54:28 -08002365 if ctx.config.captureBuild {
2366 ctx.ruleParams = make(map[blueprint.Rule]blueprint.RuleParams)
2367 }
2368
Colin Cross67a5c132017-05-09 13:45:28 -07002369 desc := "//" + ctx.ModuleDir() + ":" + ctx.ModuleName() + " "
2370 var suffix []string
Colin Cross0875c522017-11-28 17:34:01 -08002371 if ctx.Os().Class != Device && ctx.Os().Class != Generic {
2372 suffix = append(suffix, ctx.Os().String())
Colin Cross67a5c132017-05-09 13:45:28 -07002373 }
Colin Cross0875c522017-11-28 17:34:01 -08002374 if !ctx.PrimaryArch() {
2375 suffix = append(suffix, ctx.Arch().ArchType.String())
Colin Cross67a5c132017-05-09 13:45:28 -07002376 }
Colin Cross56a83212020-09-15 18:30:11 -07002377 if apexInfo := ctx.Provider(ApexInfoProvider).(ApexInfo); !apexInfo.IsForPlatform() {
2378 suffix = append(suffix, apexInfo.ApexVariationName)
Dan Willemsenb13a9482020-02-14 11:25:54 -08002379 }
Colin Cross67a5c132017-05-09 13:45:28 -07002380
2381 ctx.Variable(pctx, "moduleDesc", desc)
2382
2383 s := ""
2384 if len(suffix) > 0 {
2385 s = " [" + strings.Join(suffix, " ") + "]"
2386 }
2387 ctx.Variable(pctx, "moduleDescSuffix", s)
2388
Dan Willemsen569edc52018-11-19 09:33:29 -08002389 // Some common property checks for properties that will be used later in androidmk.go
Paul Duffin89968e32020-11-23 18:17:03 +00002390 checkDistProperties(ctx, "dist", &m.distProperties.Dist)
Sasha Smundake198eaf2022-08-04 13:07:02 -07002391 for i := range m.distProperties.Dists {
Paul Duffin89968e32020-11-23 18:17:03 +00002392 checkDistProperties(ctx, fmt.Sprintf("dists[%d]", i), &m.distProperties.Dists[i])
Dan Willemsen569edc52018-11-19 09:33:29 -08002393 }
2394
Colin Cross4157e882019-06-06 16:57:04 -07002395 if m.Enabled() {
Jooyung Hand48f3c32019-08-23 11:18:57 +09002396 // ensure all direct android.Module deps are enabled
2397 ctx.VisitDirectDepsBlueprint(func(bm blueprint.Module) {
Martin Stjernholm0e4cceb2021-05-13 02:38:35 +01002398 if m, ok := bm.(Module); ok {
2399 ctx.validateAndroidModule(bm, ctx.OtherModuleDependencyTag(m), ctx.baseModuleContext.strictVisitDeps)
Jooyung Hand48f3c32019-08-23 11:18:57 +09002400 }
2401 })
2402
Bob Badour37af0462021-01-07 03:34:31 +00002403 licensesPropertyFlattener(ctx)
2404 if ctx.Failed() {
2405 return
2406 }
2407
Chris Parsonsf874e462022-05-10 13:50:12 -04002408 if mixedBuildMod, handled := m.isHandledByBazel(ctx); handled {
2409 mixedBuildMod.ProcessBazelQueryResponse(ctx)
2410 } else {
2411 m.module.GenerateAndroidBuildActions(ctx)
2412 }
Jaewoong Jung5b425e22019-06-17 17:40:56 -07002413 if ctx.Failed() {
2414 return
2415 }
2416
Jiyong Park4d861072021-03-03 20:02:42 +09002417 m.initRcPaths = PathsForModuleSrc(ctx, m.commonProperties.Init_rc)
2418 rcDir := PathForModuleInstall(ctx, "etc", "init")
2419 for _, src := range m.initRcPaths {
2420 ctx.PackageFile(rcDir, filepath.Base(src.String()), src)
2421 }
2422
2423 m.vintfFragmentsPaths = PathsForModuleSrc(ctx, m.commonProperties.Vintf_fragments)
2424 vintfDir := PathForModuleInstall(ctx, "etc", "vintf", "manifest")
2425 for _, src := range m.vintfFragmentsPaths {
2426 ctx.PackageFile(vintfDir, filepath.Base(src.String()), src)
2427 }
2428
Paul Duffinaf970a22020-11-23 23:32:56 +00002429 // Create the set of tagged dist files after calling GenerateAndroidBuildActions
2430 // as GenerateTaggedDistFiles() calls OutputFiles(tag) and so relies on the
2431 // output paths being set which must be done before or during
2432 // GenerateAndroidBuildActions.
2433 m.distFiles = m.GenerateTaggedDistFiles(ctx)
2434 if ctx.Failed() {
2435 return
2436 }
2437
Jaewoong Jung5b425e22019-06-17 17:40:56 -07002438 m.installFiles = append(m.installFiles, ctx.installFiles...)
2439 m.checkbuildFiles = append(m.checkbuildFiles, ctx.checkbuildFiles...)
Jiyong Park073ea552020-11-09 14:08:34 +09002440 m.packagingSpecs = append(m.packagingSpecs, ctx.packagingSpecs...)
Colin Cross6301c3c2021-09-28 17:40:21 -07002441 m.katiInstalls = append(m.katiInstalls, ctx.katiInstalls...)
2442 m.katiSymlinks = append(m.katiSymlinks, ctx.katiSymlinks...)
Colin Crossdc35e212019-06-06 16:13:11 -07002443 } else if ctx.Config().AllowMissingDependencies() {
2444 // If the module is not enabled it will not create any build rules, nothing will call
2445 // ctx.GetMissingDependencies(), and blueprint will consider the missing dependencies to be unhandled
2446 // and report them as an error even when AllowMissingDependencies = true. Call
2447 // ctx.GetMissingDependencies() here to tell blueprint not to handle them.
2448 ctx.GetMissingDependencies()
Colin Cross3f40fa42015-01-30 17:27:36 -08002449 }
2450
Colin Cross4157e882019-06-06 16:57:04 -07002451 if m == ctx.FinalModule().(Module).base() {
2452 m.generateModuleTarget(ctx)
Colin Cross9b1d13d2016-09-19 15:18:11 -07002453 if ctx.Failed() {
2454 return
2455 }
Colin Cross3f40fa42015-01-30 17:27:36 -08002456 }
Colin Crosscec81712017-07-13 14:43:27 -07002457
Colin Cross5d583952020-11-24 16:21:24 -08002458 m.installFilesDepSet = newInstallPathsDepSet(m.installFiles, dependencyInstallFiles)
Colin Crossffe6b9d2020-12-01 15:40:06 -08002459 m.packagingSpecsDepSet = newPackagingSpecsDepSet(m.packagingSpecs, dependencyPackagingSpecs)
Colin Cross5d583952020-11-24 16:21:24 -08002460
Colin Crossaa1cab02022-01-28 14:49:24 -08002461 buildLicenseMetadata(ctx, m.licenseMetadataFile)
Colin Cross4acaea92021-12-10 23:05:02 +00002462
Colin Cross4157e882019-06-06 16:57:04 -07002463 m.buildParams = ctx.buildParams
2464 m.ruleParams = ctx.ruleParams
2465 m.variables = ctx.variables
Colin Cross3f40fa42015-01-30 17:27:36 -08002466}
2467
Chris Parsonsf874e462022-05-10 13:50:12 -04002468func (m *ModuleBase) isHandledByBazel(ctx ModuleContext) (MixedBuildBuildable, bool) {
Chris Parsonsf874e462022-05-10 13:50:12 -04002469 if mixedBuildMod, ok := m.module.(MixedBuildBuildable); ok {
MarkDacekf47e1422023-04-19 16:47:36 +00002470 if mixedBuildMod.IsMixedBuildSupported(ctx) && (MixedBuildsEnabled(ctx) == MixedBuildEnabled) {
Chris Parsonsf874e462022-05-10 13:50:12 -04002471 return mixedBuildMod, true
2472 }
2473 }
2474 return nil, false
2475}
2476
Paul Duffin89968e32020-11-23 18:17:03 +00002477// Check the supplied dist structure to make sure that it is valid.
2478//
2479// property - the base property, e.g. dist or dists[1], which is combined with the
2480// name of the nested property to produce the full property, e.g. dist.dest or
2481// dists[1].dir.
2482func checkDistProperties(ctx *moduleContext, property string, dist *Dist) {
2483 if dist.Dest != nil {
2484 _, err := validateSafePath(*dist.Dest)
2485 if err != nil {
2486 ctx.PropertyErrorf(property+".dest", "%s", err.Error())
2487 }
2488 }
2489 if dist.Dir != nil {
2490 _, err := validateSafePath(*dist.Dir)
2491 if err != nil {
2492 ctx.PropertyErrorf(property+".dir", "%s", err.Error())
2493 }
2494 }
2495 if dist.Suffix != nil {
2496 if strings.Contains(*dist.Suffix, "/") {
2497 ctx.PropertyErrorf(property+".suffix", "Suffix may not contain a '/' character.")
2498 }
2499 }
2500
2501}
2502
Colin Cross1184b642019-12-30 18:43:07 -08002503type earlyModuleContext struct {
Colin Crossc34d2322020-01-03 15:23:27 -08002504 blueprint.EarlyModuleContext
Colin Cross1184b642019-12-30 18:43:07 -08002505
2506 kind moduleKind
2507 config Config
2508}
2509
2510func (e *earlyModuleContext) Glob(globPattern string, excludes []string) Paths {
Liz Kammera830f3a2020-11-10 10:50:34 -08002511 return Glob(e, globPattern, excludes)
Colin Cross1184b642019-12-30 18:43:07 -08002512}
2513
2514func (e *earlyModuleContext) GlobFiles(globPattern string, excludes []string) Paths {
Liz Kammera830f3a2020-11-10 10:50:34 -08002515 return GlobFiles(e, globPattern, excludes)
Colin Cross1184b642019-12-30 18:43:07 -08002516}
2517
Ustaeabf0f32021-12-06 15:17:23 -05002518func (e *earlyModuleContext) IsSymlink(path Path) bool {
2519 fileInfo, err := e.config.fs.Lstat(path.String())
Colin Cross988414c2020-01-11 01:11:46 +00002520 if err != nil {
Ustaeabf0f32021-12-06 15:17:23 -05002521 e.ModuleErrorf("os.Lstat(%q) failed: %s", path.String(), err)
Colin Cross988414c2020-01-11 01:11:46 +00002522 }
2523 return fileInfo.Mode()&os.ModeSymlink == os.ModeSymlink
2524}
2525
Ustaeabf0f32021-12-06 15:17:23 -05002526func (e *earlyModuleContext) Readlink(path Path) string {
2527 dest, err := e.config.fs.Readlink(path.String())
Colin Cross988414c2020-01-11 01:11:46 +00002528 if err != nil {
Ustaeabf0f32021-12-06 15:17:23 -05002529 e.ModuleErrorf("os.Readlink(%q) failed: %s", path.String(), err)
Colin Cross988414c2020-01-11 01:11:46 +00002530 }
2531 return dest
2532}
2533
Colin Cross1184b642019-12-30 18:43:07 -08002534func (e *earlyModuleContext) Module() Module {
Colin Crossc34d2322020-01-03 15:23:27 -08002535 module, _ := e.EarlyModuleContext.Module().(Module)
Colin Cross1184b642019-12-30 18:43:07 -08002536 return module
2537}
2538
2539func (e *earlyModuleContext) Config() Config {
Colin Crossc34d2322020-01-03 15:23:27 -08002540 return e.EarlyModuleContext.Config().(Config)
Colin Cross1184b642019-12-30 18:43:07 -08002541}
2542
2543func (e *earlyModuleContext) AConfig() Config {
2544 return e.config
2545}
2546
2547func (e *earlyModuleContext) DeviceConfig() DeviceConfig {
2548 return DeviceConfig{e.config.deviceConfig}
2549}
2550
2551func (e *earlyModuleContext) Platform() bool {
2552 return e.kind == platformModule
2553}
2554
2555func (e *earlyModuleContext) DeviceSpecific() bool {
2556 return e.kind == deviceSpecificModule
2557}
2558
2559func (e *earlyModuleContext) SocSpecific() bool {
2560 return e.kind == socSpecificModule
2561}
2562
2563func (e *earlyModuleContext) ProductSpecific() bool {
2564 return e.kind == productSpecificModule
2565}
2566
2567func (e *earlyModuleContext) SystemExtSpecific() bool {
2568 return e.kind == systemExtSpecificModule
2569}
2570
Colin Cross133ebef2020-08-14 17:38:45 -07002571func (e *earlyModuleContext) Namespace() *Namespace {
2572 return e.EarlyModuleContext.Namespace().(*Namespace)
2573}
2574
Colin Cross1184b642019-12-30 18:43:07 -08002575type baseModuleContext struct {
2576 bp blueprint.BaseModuleContext
2577 earlyModuleContext
Colin Crossfb0c16e2019-11-20 17:12:35 -08002578 os OsType
Colin Cross8b74d172016-09-13 09:59:14 -07002579 target Target
Colin Crossee0bc3b2018-10-02 22:01:37 -07002580 multiTargets []Target
Colin Cross8b74d172016-09-13 09:59:14 -07002581 targetPrimary bool
2582 debug bool
Colin Crossdc35e212019-06-06 16:13:11 -07002583
2584 walkPath []Module
Paul Duffinc5192442020-03-31 11:31:36 +01002585 tagPath []blueprint.DependencyTag
Colin Crossdc35e212019-06-06 16:13:11 -07002586
2587 strictVisitDeps bool // If true, enforce that all dependencies are enabled
Chris Parsons5a34ffb2021-07-21 14:34:58 -04002588
2589 bazelConversionMode bool
Colin Crossf6566ed2015-03-24 11:13:38 -07002590}
2591
Liz Kammer3bf97bd2022-04-26 09:38:20 -04002592func (b *baseModuleContext) isBazelConversionMode() bool {
Chris Parsons5a34ffb2021-07-21 14:34:58 -04002593 return b.bazelConversionMode
2594}
Paul Duffinca7f0ef2020-02-25 15:50:49 +00002595func (b *baseModuleContext) OtherModuleName(m blueprint.Module) string {
2596 return b.bp.OtherModuleName(m)
2597}
2598func (b *baseModuleContext) OtherModuleDir(m blueprint.Module) string { return b.bp.OtherModuleDir(m) }
Colin Cross1184b642019-12-30 18:43:07 -08002599func (b *baseModuleContext) OtherModuleErrorf(m blueprint.Module, fmt string, args ...interface{}) {
Jooyung Hancd87c692020-02-26 02:05:18 +09002600 b.bp.OtherModuleErrorf(m, fmt, args...)
Colin Cross1184b642019-12-30 18:43:07 -08002601}
2602func (b *baseModuleContext) OtherModuleDependencyTag(m blueprint.Module) blueprint.DependencyTag {
2603 return b.bp.OtherModuleDependencyTag(m)
2604}
Paul Duffinca7f0ef2020-02-25 15:50:49 +00002605func (b *baseModuleContext) OtherModuleExists(name string) bool { return b.bp.OtherModuleExists(name) }
Martin Stjernholm009a9dc2020-03-05 17:34:13 +00002606func (b *baseModuleContext) OtherModuleDependencyVariantExists(variations []blueprint.Variation, name string) bool {
2607 return b.bp.OtherModuleDependencyVariantExists(variations, name)
2608}
Martin Stjernholm408ffd82021-05-05 15:27:31 +01002609func (b *baseModuleContext) OtherModuleFarDependencyVariantExists(variations []blueprint.Variation, name string) bool {
2610 return b.bp.OtherModuleFarDependencyVariantExists(variations, name)
2611}
Martin Stjernholm009a9dc2020-03-05 17:34:13 +00002612func (b *baseModuleContext) OtherModuleReverseDependencyVariantExists(name string) bool {
2613 return b.bp.OtherModuleReverseDependencyVariantExists(name)
2614}
Paul Duffinca7f0ef2020-02-25 15:50:49 +00002615func (b *baseModuleContext) OtherModuleType(m blueprint.Module) string {
2616 return b.bp.OtherModuleType(m)
2617}
Colin Crossd27e7b82020-07-02 11:38:17 -07002618func (b *baseModuleContext) OtherModuleProvider(m blueprint.Module, provider blueprint.ProviderKey) interface{} {
2619 return b.bp.OtherModuleProvider(m, provider)
2620}
2621func (b *baseModuleContext) OtherModuleHasProvider(m blueprint.Module, provider blueprint.ProviderKey) bool {
2622 return b.bp.OtherModuleHasProvider(m, provider)
2623}
2624func (b *baseModuleContext) Provider(provider blueprint.ProviderKey) interface{} {
2625 return b.bp.Provider(provider)
2626}
2627func (b *baseModuleContext) HasProvider(provider blueprint.ProviderKey) bool {
2628 return b.bp.HasProvider(provider)
2629}
2630func (b *baseModuleContext) SetProvider(provider blueprint.ProviderKey, value interface{}) {
2631 b.bp.SetProvider(provider, value)
2632}
Colin Cross1184b642019-12-30 18:43:07 -08002633
2634func (b *baseModuleContext) GetDirectDepWithTag(name string, tag blueprint.DependencyTag) blueprint.Module {
2635 return b.bp.GetDirectDepWithTag(name, tag)
2636}
2637
Paul Duffinf88d8e02020-05-07 20:21:34 +01002638func (b *baseModuleContext) blueprintBaseModuleContext() blueprint.BaseModuleContext {
2639 return b.bp
2640}
2641
Colin Cross25de6c32019-06-06 14:29:25 -07002642type moduleContext struct {
Colin Crossdc35e212019-06-06 16:13:11 -07002643 bp blueprint.ModuleContext
Colin Cross0ea8ba82019-06-06 14:33:29 -07002644 baseModuleContext
Jiyong Park073ea552020-11-09 14:08:34 +09002645 packagingSpecs []PackagingSpec
Colin Cross897266e2020-02-13 13:22:08 -08002646 installFiles InstallPaths
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002647 checkbuildFiles Paths
Colin Cross8d8f8e22016-08-03 11:57:50 -07002648 module Module
Colin Crossc3d87d32020-06-04 13:25:17 -07002649 phonies map[string]Paths
Colin Crosscec81712017-07-13 14:43:27 -07002650
Colin Cross6301c3c2021-09-28 17:40:21 -07002651 katiInstalls []katiInstall
2652 katiSymlinks []katiInstall
2653
Colin Crosscec81712017-07-13 14:43:27 -07002654 // For tests
Colin Crossae887032017-10-23 17:16:14 -07002655 buildParams []BuildParams
Colin Cross4c83e5c2019-02-25 14:54:28 -08002656 ruleParams map[blueprint.Rule]blueprint.RuleParams
Jaewoong Jung38e4fb22018-12-12 09:01:34 -08002657 variables map[string]string
Colin Cross6ff51382015-12-17 16:39:19 -08002658}
2659
Colin Cross6301c3c2021-09-28 17:40:21 -07002660// katiInstall stores a request from Soong to Make to create an install rule.
2661type katiInstall struct {
2662 from Path
2663 to InstallPath
2664 implicitDeps Paths
2665 orderOnlyDeps Paths
2666 executable bool
Colin Cross50ed1f92021-11-12 17:41:02 -08002667 extraFiles *extraFilesZip
Colin Cross6301c3c2021-09-28 17:40:21 -07002668
2669 absFrom string
2670}
2671
Colin Cross50ed1f92021-11-12 17:41:02 -08002672type extraFilesZip struct {
2673 zip Path
2674 dir InstallPath
2675}
2676
Colin Cross6301c3c2021-09-28 17:40:21 -07002677type katiInstalls []katiInstall
2678
2679// BuiltInstalled returns the katiInstalls in the form used by $(call copy-many-files) in Make, a
2680// space separated list of from:to tuples.
2681func (installs katiInstalls) BuiltInstalled() string {
2682 sb := strings.Builder{}
2683 for i, install := range installs {
2684 if i != 0 {
2685 sb.WriteRune(' ')
2686 }
2687 sb.WriteString(install.from.String())
2688 sb.WriteRune(':')
2689 sb.WriteString(install.to.String())
2690 }
2691 return sb.String()
2692}
2693
2694// InstallPaths returns the install path of each entry.
2695func (installs katiInstalls) InstallPaths() InstallPaths {
2696 paths := make(InstallPaths, 0, len(installs))
2697 for _, install := range installs {
2698 paths = append(paths, install.to)
2699 }
2700 return paths
2701}
2702
Colin Crossb88b3c52019-06-10 15:15:17 -07002703func (m *moduleContext) ninjaError(params BuildParams, err error) (PackageContext, BuildParams) {
2704 return pctx, BuildParams{
Colin Cross4b69c492019-06-07 13:06:06 -07002705 Rule: ErrorRule,
2706 Description: params.Description,
2707 Output: params.Output,
2708 Outputs: params.Outputs,
2709 ImplicitOutput: params.ImplicitOutput,
2710 ImplicitOutputs: params.ImplicitOutputs,
Colin Cross6ff51382015-12-17 16:39:19 -08002711 Args: map[string]string{
2712 "error": err.Error(),
2713 },
Colin Crossb88b3c52019-06-10 15:15:17 -07002714 }
Colin Cross3f40fa42015-01-30 17:27:36 -08002715}
2716
Colin Cross25de6c32019-06-06 14:29:25 -07002717func (m *moduleContext) ModuleBuild(pctx PackageContext, params ModuleBuildParams) {
2718 m.Build(pctx, BuildParams(params))
Colin Cross3f40fa42015-01-30 17:27:36 -08002719}
2720
Jingwen Chence679d22020-09-23 04:30:02 +00002721func validateBuildParams(params blueprint.BuildParams) error {
2722 // Validate that the symlink outputs are declared outputs or implicit outputs
2723 allOutputs := map[string]bool{}
2724 for _, output := range params.Outputs {
2725 allOutputs[output] = true
2726 }
2727 for _, output := range params.ImplicitOutputs {
2728 allOutputs[output] = true
2729 }
2730 for _, symlinkOutput := range params.SymlinkOutputs {
2731 if !allOutputs[symlinkOutput] {
2732 return fmt.Errorf(
2733 "Symlink output %s is not a declared output or implicit output",
2734 symlinkOutput)
2735 }
2736 }
2737 return nil
2738}
2739
2740// Convert build parameters from their concrete Android types into their string representations,
2741// and combine the singular and plural fields of the same type (e.g. Output and Outputs).
Colin Cross0875c522017-11-28 17:34:01 -08002742func convertBuildParams(params BuildParams) blueprint.BuildParams {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002743 bparams := blueprint.BuildParams{
Dan Willemsen9f3c5742016-11-03 14:28:31 -07002744 Rule: params.Rule,
Colin Cross0875c522017-11-28 17:34:01 -08002745 Description: params.Description,
Colin Cross33bfb0a2016-11-21 17:23:08 -08002746 Deps: params.Deps,
Dan Willemsen9f3c5742016-11-03 14:28:31 -07002747 Outputs: params.Outputs.Strings(),
2748 ImplicitOutputs: params.ImplicitOutputs.Strings(),
Jingwen Chence679d22020-09-23 04:30:02 +00002749 SymlinkOutputs: params.SymlinkOutputs.Strings(),
Dan Willemsen9f3c5742016-11-03 14:28:31 -07002750 Inputs: params.Inputs.Strings(),
2751 Implicits: params.Implicits.Strings(),
2752 OrderOnly: params.OrderOnly.Strings(),
Colin Cross824f1162020-07-16 13:07:51 -07002753 Validations: params.Validations.Strings(),
Dan Willemsen9f3c5742016-11-03 14:28:31 -07002754 Args: params.Args,
2755 Optional: !params.Default,
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002756 }
2757
Colin Cross33bfb0a2016-11-21 17:23:08 -08002758 if params.Depfile != nil {
2759 bparams.Depfile = params.Depfile.String()
2760 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002761 if params.Output != nil {
2762 bparams.Outputs = append(bparams.Outputs, params.Output.String())
2763 }
Jingwen Chence679d22020-09-23 04:30:02 +00002764 if params.SymlinkOutput != nil {
2765 bparams.SymlinkOutputs = append(bparams.SymlinkOutputs, params.SymlinkOutput.String())
2766 }
Dan Willemsen9f3c5742016-11-03 14:28:31 -07002767 if params.ImplicitOutput != nil {
2768 bparams.ImplicitOutputs = append(bparams.ImplicitOutputs, params.ImplicitOutput.String())
2769 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002770 if params.Input != nil {
2771 bparams.Inputs = append(bparams.Inputs, params.Input.String())
2772 }
2773 if params.Implicit != nil {
2774 bparams.Implicits = append(bparams.Implicits, params.Implicit.String())
2775 }
Colin Cross824f1162020-07-16 13:07:51 -07002776 if params.Validation != nil {
2777 bparams.Validations = append(bparams.Validations, params.Validation.String())
2778 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002779
Colin Cross0b9f31f2019-02-28 11:00:01 -08002780 bparams.Outputs = proptools.NinjaEscapeList(bparams.Outputs)
2781 bparams.ImplicitOutputs = proptools.NinjaEscapeList(bparams.ImplicitOutputs)
Jingwen Chence679d22020-09-23 04:30:02 +00002782 bparams.SymlinkOutputs = proptools.NinjaEscapeList(bparams.SymlinkOutputs)
Colin Cross0b9f31f2019-02-28 11:00:01 -08002783 bparams.Inputs = proptools.NinjaEscapeList(bparams.Inputs)
2784 bparams.Implicits = proptools.NinjaEscapeList(bparams.Implicits)
2785 bparams.OrderOnly = proptools.NinjaEscapeList(bparams.OrderOnly)
Colin Cross824f1162020-07-16 13:07:51 -07002786 bparams.Validations = proptools.NinjaEscapeList(bparams.Validations)
2787 bparams.Depfile = proptools.NinjaEscape(bparams.Depfile)
Colin Crossfe4bc362018-09-12 10:02:13 -07002788
Colin Cross0875c522017-11-28 17:34:01 -08002789 return bparams
2790}
2791
Colin Cross25de6c32019-06-06 14:29:25 -07002792func (m *moduleContext) Variable(pctx PackageContext, name, value string) {
2793 if m.config.captureBuild {
2794 m.variables[name] = value
Jaewoong Jung38e4fb22018-12-12 09:01:34 -08002795 }
2796
Colin Crossdc35e212019-06-06 16:13:11 -07002797 m.bp.Variable(pctx.PackageContext, name, value)
Colin Cross0875c522017-11-28 17:34:01 -08002798}
2799
Colin Cross25de6c32019-06-06 14:29:25 -07002800func (m *moduleContext) Rule(pctx PackageContext, name string, params blueprint.RuleParams,
Colin Cross0875c522017-11-28 17:34:01 -08002801 argNames ...string) blueprint.Rule {
2802
Ramy Medhat944839a2020-03-31 22:14:52 -04002803 if m.config.UseRemoteBuild() {
2804 if params.Pool == nil {
2805 // When USE_GOMA=true or USE_RBE=true are set and the rule is not supported by goma/RBE, restrict
2806 // jobs to the local parallelism value
2807 params.Pool = localPool
2808 } else if params.Pool == remotePool {
2809 // remotePool is a fake pool used to identify rule that are supported for remoting. If the rule's
2810 // pool is the remotePool, replace with nil so that ninja runs it at NINJA_REMOTE_NUM_JOBS
2811 // parallelism.
2812 params.Pool = nil
2813 }
Colin Cross2e2dbc22019-09-25 13:31:46 -07002814 }
2815
Colin Crossdc35e212019-06-06 16:13:11 -07002816 rule := m.bp.Rule(pctx.PackageContext, name, params, argNames...)
Colin Cross4c83e5c2019-02-25 14:54:28 -08002817
Colin Cross25de6c32019-06-06 14:29:25 -07002818 if m.config.captureBuild {
2819 m.ruleParams[rule] = params
Colin Cross4c83e5c2019-02-25 14:54:28 -08002820 }
2821
2822 return rule
Colin Cross0875c522017-11-28 17:34:01 -08002823}
2824
Colin Cross25de6c32019-06-06 14:29:25 -07002825func (m *moduleContext) Build(pctx PackageContext, params BuildParams) {
Colin Crossb88b3c52019-06-10 15:15:17 -07002826 if params.Description != "" {
2827 params.Description = "${moduleDesc}" + params.Description + "${moduleDescSuffix}"
2828 }
2829
2830 if missingDeps := m.GetMissingDependencies(); len(missingDeps) > 0 {
2831 pctx, params = m.ninjaError(params, fmt.Errorf("module %s missing dependencies: %s\n",
2832 m.ModuleName(), strings.Join(missingDeps, ", ")))
2833 }
2834
Colin Cross25de6c32019-06-06 14:29:25 -07002835 if m.config.captureBuild {
2836 m.buildParams = append(m.buildParams, params)
Colin Cross0875c522017-11-28 17:34:01 -08002837 }
2838
Jingwen Chence679d22020-09-23 04:30:02 +00002839 bparams := convertBuildParams(params)
2840 err := validateBuildParams(bparams)
2841 if err != nil {
2842 m.ModuleErrorf(
2843 "%s: build parameter validation failed: %s",
2844 m.ModuleName(),
2845 err.Error())
2846 }
2847 m.bp.Build(pctx.PackageContext, bparams)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002848}
Colin Crossc3d87d32020-06-04 13:25:17 -07002849
2850func (m *moduleContext) Phony(name string, deps ...Path) {
2851 addPhony(m.config, name, deps...)
2852}
2853
Colin Cross25de6c32019-06-06 14:29:25 -07002854func (m *moduleContext) GetMissingDependencies() []string {
Colin Cross6c4f21f2019-06-06 15:41:36 -07002855 var missingDeps []string
2856 missingDeps = append(missingDeps, m.Module().base().commonProperties.MissingDeps...)
Colin Crossdc35e212019-06-06 16:13:11 -07002857 missingDeps = append(missingDeps, m.bp.GetMissingDependencies()...)
Colin Cross6c4f21f2019-06-06 15:41:36 -07002858 missingDeps = FirstUniqueStrings(missingDeps)
2859 return missingDeps
Colin Cross6ff51382015-12-17 16:39:19 -08002860}
2861
Colin Crossdc35e212019-06-06 16:13:11 -07002862func (b *baseModuleContext) AddMissingDependencies(deps []string) {
Dan Willemsen6553f5e2016-03-10 18:14:25 -08002863 if deps != nil {
Colin Crossdc35e212019-06-06 16:13:11 -07002864 missingDeps := &b.Module().base().commonProperties.MissingDeps
Colin Cross6c4f21f2019-06-06 15:41:36 -07002865 *missingDeps = append(*missingDeps, deps...)
2866 *missingDeps = FirstUniqueStrings(*missingDeps)
Dan Willemsen6553f5e2016-03-10 18:14:25 -08002867 }
2868}
2869
Liz Kammerc13f7852023-05-17 13:01:48 -04002870func (b *baseModuleContext) checkedMissingDeps() bool {
2871 return b.Module().base().commonProperties.CheckedMissingDeps
2872}
2873
2874func (b *baseModuleContext) getMissingDependencies() []string {
2875 checked := &b.Module().base().commonProperties.CheckedMissingDeps
2876 *checked = true
2877 var missingDeps []string
2878 missingDeps = append(missingDeps, b.Module().base().commonProperties.MissingDeps...)
2879 missingDeps = append(missingDeps, b.bp.EarlyGetMissingDependencies()...)
2880 missingDeps = FirstUniqueStrings(missingDeps)
2881 return missingDeps
2882}
2883
Martin Stjernholm0e4cceb2021-05-13 02:38:35 +01002884type AllowDisabledModuleDependency interface {
2885 blueprint.DependencyTag
2886 AllowDisabledModuleDependency(target Module) bool
2887}
2888
2889func (b *baseModuleContext) validateAndroidModule(module blueprint.Module, tag blueprint.DependencyTag, strict bool) Module {
Colin Crossd11fcda2017-10-23 17:59:01 -07002890 aModule, _ := module.(Module)
Colin Crossdc35e212019-06-06 16:13:11 -07002891
2892 if !strict {
2893 return aModule
2894 }
2895
Colin Cross380c69a2019-06-10 17:49:58 +00002896 if aModule == nil {
Liz Kammer55146982022-01-24 16:17:30 -05002897 b.ModuleErrorf("module %q (%#v) not an android module", b.OtherModuleName(module), tag)
Colin Cross380c69a2019-06-10 17:49:58 +00002898 return nil
2899 }
2900
2901 if !aModule.Enabled() {
Martin Stjernholm0e4cceb2021-05-13 02:38:35 +01002902 if t, ok := tag.(AllowDisabledModuleDependency); !ok || !t.AllowDisabledModuleDependency(aModule) {
2903 if b.Config().AllowMissingDependencies() {
2904 b.AddMissingDependencies([]string{b.OtherModuleName(aModule)})
2905 } else {
2906 b.ModuleErrorf("depends on disabled module %q", b.OtherModuleName(aModule))
2907 }
Colin Cross380c69a2019-06-10 17:49:58 +00002908 }
2909 return nil
2910 }
Colin Crossd11fcda2017-10-23 17:59:01 -07002911 return aModule
2912}
2913
Liz Kammer2b50ce62021-04-26 15:47:28 -04002914type dep struct {
2915 mod blueprint.Module
2916 tag blueprint.DependencyTag
2917}
2918
2919func (b *baseModuleContext) getDirectDepsInternal(name string, tag blueprint.DependencyTag) []dep {
Jiyong Parkf2976302019-04-17 21:47:37 +09002920 var deps []dep
Colin Crossdc35e212019-06-06 16:13:11 -07002921 b.VisitDirectDepsBlueprint(func(module blueprint.Module) {
Liz Kammer356f7d42021-01-26 09:18:53 -05002922 if aModule, _ := module.(Module); aModule != nil {
2923 if aModule.base().BaseModuleName() == name {
2924 returnedTag := b.bp.OtherModuleDependencyTag(aModule)
2925 if tag == nil || returnedTag == tag {
2926 deps = append(deps, dep{aModule, returnedTag})
2927 }
2928 }
2929 } else if b.bp.OtherModuleName(module) == name {
2930 returnedTag := b.bp.OtherModuleDependencyTag(module)
Jiyong Parkf2976302019-04-17 21:47:37 +09002931 if tag == nil || returnedTag == tag {
Liz Kammer356f7d42021-01-26 09:18:53 -05002932 deps = append(deps, dep{module, returnedTag})
Jiyong Parkf2976302019-04-17 21:47:37 +09002933 }
2934 }
2935 })
Liz Kammer2b50ce62021-04-26 15:47:28 -04002936 return deps
2937}
2938
2939func (b *baseModuleContext) getDirectDepInternal(name string, tag blueprint.DependencyTag) (blueprint.Module, blueprint.DependencyTag) {
2940 deps := b.getDirectDepsInternal(name, tag)
Jiyong Parkf2976302019-04-17 21:47:37 +09002941 if len(deps) == 1 {
2942 return deps[0].mod, deps[0].tag
2943 } else if len(deps) >= 2 {
2944 panic(fmt.Errorf("Multiple dependencies having same BaseModuleName() %q found from %q",
Colin Crossdc35e212019-06-06 16:13:11 -07002945 name, b.ModuleName()))
Jiyong Parkf2976302019-04-17 21:47:37 +09002946 } else {
2947 return nil, nil
2948 }
2949}
2950
Liz Kammer2b50ce62021-04-26 15:47:28 -04002951func (b *baseModuleContext) getDirectDepFirstTag(name string) (blueprint.Module, blueprint.DependencyTag) {
2952 foundDeps := b.getDirectDepsInternal(name, nil)
2953 deps := map[blueprint.Module]bool{}
2954 for _, dep := range foundDeps {
2955 deps[dep.mod] = true
2956 }
2957 if len(deps) == 1 {
2958 return foundDeps[0].mod, foundDeps[0].tag
2959 } else if len(deps) >= 2 {
2960 // this could happen if two dependencies have the same name in different namespaces
2961 // TODO(b/186554727): this should not occur if namespaces are handled within
2962 // getDirectDepsInternal.
2963 panic(fmt.Errorf("Multiple dependencies having same BaseModuleName() %q found from %q",
2964 name, b.ModuleName()))
2965 } else {
2966 return nil, nil
2967 }
2968}
2969
Colin Crossdc35e212019-06-06 16:13:11 -07002970func (b *baseModuleContext) GetDirectDepsWithTag(tag blueprint.DependencyTag) []Module {
Colin Cross0ef08162019-05-01 15:50:51 -07002971 var deps []Module
Colin Crossdc35e212019-06-06 16:13:11 -07002972 b.VisitDirectDepsBlueprint(func(module blueprint.Module) {
Colin Cross25de6c32019-06-06 14:29:25 -07002973 if aModule, _ := module.(Module); aModule != nil {
Colin Cross1184b642019-12-30 18:43:07 -08002974 if b.bp.OtherModuleDependencyTag(aModule) == tag {
Colin Cross0ef08162019-05-01 15:50:51 -07002975 deps = append(deps, aModule)
2976 }
2977 }
2978 })
2979 return deps
2980}
2981
Colin Cross25de6c32019-06-06 14:29:25 -07002982func (m *moduleContext) GetDirectDepWithTag(name string, tag blueprint.DependencyTag) blueprint.Module {
2983 module, _ := m.getDirectDepInternal(name, tag)
2984 return module
Jiyong Parkf2976302019-04-17 21:47:37 +09002985}
2986
Liz Kammer2b50ce62021-04-26 15:47:28 -04002987// GetDirectDep returns the Module and DependencyTag for the direct dependency with the specified
2988// name, or nil if none exists. If there are multiple dependencies on the same module it returns the
2989// first DependencyTag.
Colin Crossdc35e212019-06-06 16:13:11 -07002990func (b *baseModuleContext) GetDirectDep(name string) (blueprint.Module, blueprint.DependencyTag) {
Liz Kammer2b50ce62021-04-26 15:47:28 -04002991 return b.getDirectDepFirstTag(name)
Jiyong Parkf2976302019-04-17 21:47:37 +09002992}
2993
Chris Parsons5a34ffb2021-07-21 14:34:58 -04002994func (b *baseModuleContext) ModuleFromName(name string) (blueprint.Module, bool) {
Liz Kammer3bf97bd2022-04-26 09:38:20 -04002995 if !b.isBazelConversionMode() {
Chris Parsons5a34ffb2021-07-21 14:34:58 -04002996 panic("cannot call ModuleFromName if not in bazel conversion mode")
2997 }
Chris Parsonsa66c0b52021-07-23 11:02:07 -04002998 if moduleName, _ := SrcIsModuleWithTag(name); moduleName != "" {
Chris Parsons5a34ffb2021-07-21 14:34:58 -04002999 return b.bp.ModuleFromName(moduleName)
3000 } else {
3001 return b.bp.ModuleFromName(name)
3002 }
3003}
3004
Colin Crossdc35e212019-06-06 16:13:11 -07003005func (b *baseModuleContext) VisitDirectDepsBlueprint(visit func(blueprint.Module)) {
Colin Cross1184b642019-12-30 18:43:07 -08003006 b.bp.VisitDirectDeps(visit)
Colin Cross35143d02017-11-16 00:11:20 -08003007}
3008
Colin Crossdc35e212019-06-06 16:13:11 -07003009func (b *baseModuleContext) VisitDirectDeps(visit func(Module)) {
Colin Cross1184b642019-12-30 18:43:07 -08003010 b.bp.VisitDirectDeps(func(module blueprint.Module) {
Martin Stjernholm0e4cceb2021-05-13 02:38:35 +01003011 if aModule := b.validateAndroidModule(module, b.bp.OtherModuleDependencyTag(module), b.strictVisitDeps); aModule != nil {
Colin Crossd11fcda2017-10-23 17:59:01 -07003012 visit(aModule)
3013 }
3014 })
3015}
3016
Colin Crossdc35e212019-06-06 16:13:11 -07003017func (b *baseModuleContext) VisitDirectDepsWithTag(tag blueprint.DependencyTag, visit func(Module)) {
Colin Cross1184b642019-12-30 18:43:07 -08003018 b.bp.VisitDirectDeps(func(module blueprint.Module) {
Liz Kammer55146982022-01-24 16:17:30 -05003019 if b.bp.OtherModuleDependencyTag(module) == tag {
3020 if aModule := b.validateAndroidModule(module, b.bp.OtherModuleDependencyTag(module), b.strictVisitDeps); aModule != nil {
Colin Crossee6143c2017-12-30 17:54:27 -08003021 visit(aModule)
3022 }
3023 }
3024 })
3025}
3026
Colin Crossdc35e212019-06-06 16:13:11 -07003027func (b *baseModuleContext) VisitDirectDepsIf(pred func(Module) bool, visit func(Module)) {
Colin Cross1184b642019-12-30 18:43:07 -08003028 b.bp.VisitDirectDepsIf(
Colin Crossd11fcda2017-10-23 17:59:01 -07003029 // pred
3030 func(module blueprint.Module) bool {
Martin Stjernholm0e4cceb2021-05-13 02:38:35 +01003031 if aModule := b.validateAndroidModule(module, b.bp.OtherModuleDependencyTag(module), b.strictVisitDeps); aModule != nil {
Colin Crossd11fcda2017-10-23 17:59:01 -07003032 return pred(aModule)
3033 } else {
3034 return false
3035 }
3036 },
3037 // visit
3038 func(module blueprint.Module) {
3039 visit(module.(Module))
3040 })
3041}
3042
Colin Crossdc35e212019-06-06 16:13:11 -07003043func (b *baseModuleContext) VisitDepsDepthFirst(visit func(Module)) {
Colin Cross1184b642019-12-30 18:43:07 -08003044 b.bp.VisitDepsDepthFirst(func(module blueprint.Module) {
Martin Stjernholm0e4cceb2021-05-13 02:38:35 +01003045 if aModule := b.validateAndroidModule(module, b.bp.OtherModuleDependencyTag(module), b.strictVisitDeps); aModule != nil {
Colin Crossd11fcda2017-10-23 17:59:01 -07003046 visit(aModule)
3047 }
3048 })
3049}
3050
Colin Crossdc35e212019-06-06 16:13:11 -07003051func (b *baseModuleContext) VisitDepsDepthFirstIf(pred func(Module) bool, visit func(Module)) {
Colin Cross1184b642019-12-30 18:43:07 -08003052 b.bp.VisitDepsDepthFirstIf(
Colin Crossd11fcda2017-10-23 17:59:01 -07003053 // pred
3054 func(module blueprint.Module) bool {
Martin Stjernholm0e4cceb2021-05-13 02:38:35 +01003055 if aModule := b.validateAndroidModule(module, b.bp.OtherModuleDependencyTag(module), b.strictVisitDeps); aModule != nil {
Colin Crossd11fcda2017-10-23 17:59:01 -07003056 return pred(aModule)
3057 } else {
3058 return false
3059 }
3060 },
3061 // visit
3062 func(module blueprint.Module) {
3063 visit(module.(Module))
3064 })
3065}
3066
Colin Crossdc35e212019-06-06 16:13:11 -07003067func (b *baseModuleContext) WalkDepsBlueprint(visit func(blueprint.Module, blueprint.Module) bool) {
Colin Cross1184b642019-12-30 18:43:07 -08003068 b.bp.WalkDeps(visit)
Alex Light778127a2019-02-27 14:19:50 -08003069}
3070
Colin Crossdc35e212019-06-06 16:13:11 -07003071func (b *baseModuleContext) WalkDeps(visit func(Module, Module) bool) {
3072 b.walkPath = []Module{b.Module()}
Paul Duffinc5192442020-03-31 11:31:36 +01003073 b.tagPath = []blueprint.DependencyTag{}
Colin Cross1184b642019-12-30 18:43:07 -08003074 b.bp.WalkDeps(func(child, parent blueprint.Module) bool {
Colin Crossdc35e212019-06-06 16:13:11 -07003075 childAndroidModule, _ := child.(Module)
3076 parentAndroidModule, _ := parent.(Module)
Colin Crossd11fcda2017-10-23 17:59:01 -07003077 if childAndroidModule != nil && parentAndroidModule != nil {
Colin Crossdc35e212019-06-06 16:13:11 -07003078 // record walkPath before visit
3079 for b.walkPath[len(b.walkPath)-1] != parentAndroidModule {
3080 b.walkPath = b.walkPath[0 : len(b.walkPath)-1]
Paul Duffinc5192442020-03-31 11:31:36 +01003081 b.tagPath = b.tagPath[0 : len(b.tagPath)-1]
Colin Crossdc35e212019-06-06 16:13:11 -07003082 }
3083 b.walkPath = append(b.walkPath, childAndroidModule)
Paul Duffinc5192442020-03-31 11:31:36 +01003084 b.tagPath = append(b.tagPath, b.OtherModuleDependencyTag(childAndroidModule))
Colin Crossd11fcda2017-10-23 17:59:01 -07003085 return visit(childAndroidModule, parentAndroidModule)
3086 } else {
3087 return false
3088 }
3089 })
3090}
3091
Colin Crossdc35e212019-06-06 16:13:11 -07003092func (b *baseModuleContext) GetWalkPath() []Module {
3093 return b.walkPath
3094}
3095
Paul Duffinc5192442020-03-31 11:31:36 +01003096func (b *baseModuleContext) GetTagPath() []blueprint.DependencyTag {
3097 return b.tagPath
3098}
3099
Colin Cross4dfacf92020-09-16 19:22:27 -07003100func (b *baseModuleContext) VisitAllModuleVariants(visit func(Module)) {
3101 b.bp.VisitAllModuleVariants(func(module blueprint.Module) {
3102 visit(module.(Module))
3103 })
3104}
3105
3106func (b *baseModuleContext) PrimaryModule() Module {
3107 return b.bp.PrimaryModule().(Module)
3108}
3109
3110func (b *baseModuleContext) FinalModule() Module {
3111 return b.bp.FinalModule().(Module)
3112}
3113
Bob Badour07065cd2021-02-05 19:59:11 -08003114// IsMetaDependencyTag returns true for cross-cutting metadata dependencies.
3115func IsMetaDependencyTag(tag blueprint.DependencyTag) bool {
3116 if tag == licenseKindTag {
3117 return true
3118 } else if tag == licensesTag {
3119 return true
3120 }
3121 return false
3122}
3123
Jiyong Park1c7e9622020-05-07 16:12:13 +09003124// A regexp for removing boilerplate from BaseDependencyTag from the string representation of
3125// a dependency tag.
Colin Cross6e511a92020-07-27 21:26:48 -07003126var tagCleaner = regexp.MustCompile(`\QBaseDependencyTag:{}\E(, )?`)
Jiyong Park1c7e9622020-05-07 16:12:13 +09003127
3128// PrettyPrintTag returns string representation of the tag, but prefers
3129// custom String() method if available.
3130func PrettyPrintTag(tag blueprint.DependencyTag) string {
3131 // Use tag's custom String() method if available.
3132 if stringer, ok := tag.(fmt.Stringer); ok {
3133 return stringer.String()
3134 }
3135
3136 // Otherwise, get a default string representation of the tag's struct.
Colin Cross6e511a92020-07-27 21:26:48 -07003137 tagString := fmt.Sprintf("%T: %+v", tag, tag)
Jiyong Park1c7e9622020-05-07 16:12:13 +09003138
3139 // Remove the boilerplate from BaseDependencyTag as it adds no value.
3140 tagString = tagCleaner.ReplaceAllString(tagString, "")
3141 return tagString
3142}
3143
3144func (b *baseModuleContext) GetPathString(skipFirst bool) string {
3145 sb := strings.Builder{}
3146 tagPath := b.GetTagPath()
3147 walkPath := b.GetWalkPath()
3148 if !skipFirst {
3149 sb.WriteString(walkPath[0].String())
3150 }
3151 for i, m := range walkPath[1:] {
3152 sb.WriteString("\n")
3153 sb.WriteString(fmt.Sprintf(" via tag %s\n", PrettyPrintTag(tagPath[i])))
3154 sb.WriteString(fmt.Sprintf(" -> %s", m.String()))
3155 }
3156 return sb.String()
3157}
3158
Colin Crossdc35e212019-06-06 16:13:11 -07003159func (m *moduleContext) ModuleSubDir() string {
3160 return m.bp.ModuleSubDir()
Colin Cross0875c522017-11-28 17:34:01 -08003161}
3162
Colin Cross0ea8ba82019-06-06 14:33:29 -07003163func (b *baseModuleContext) Target() Target {
Colin Cross25de6c32019-06-06 14:29:25 -07003164 return b.target
Colin Crossa1ad8d12016-06-01 17:09:44 -07003165}
3166
Colin Cross0ea8ba82019-06-06 14:33:29 -07003167func (b *baseModuleContext) TargetPrimary() bool {
Colin Cross25de6c32019-06-06 14:29:25 -07003168 return b.targetPrimary
Colin Cross8b74d172016-09-13 09:59:14 -07003169}
3170
Colin Cross0ea8ba82019-06-06 14:33:29 -07003171func (b *baseModuleContext) MultiTargets() []Target {
Colin Cross25de6c32019-06-06 14:29:25 -07003172 return b.multiTargets
Colin Crossee0bc3b2018-10-02 22:01:37 -07003173}
3174
Colin Cross0ea8ba82019-06-06 14:33:29 -07003175func (b *baseModuleContext) Arch() Arch {
Colin Cross25de6c32019-06-06 14:29:25 -07003176 return b.target.Arch
Colin Cross3f40fa42015-01-30 17:27:36 -08003177}
3178
Colin Cross0ea8ba82019-06-06 14:33:29 -07003179func (b *baseModuleContext) Os() OsType {
Colin Crossfb0c16e2019-11-20 17:12:35 -08003180 return b.os
Dan Willemsen490fd492015-11-24 17:53:15 -08003181}
3182
Colin Cross0ea8ba82019-06-06 14:33:29 -07003183func (b *baseModuleContext) Host() bool {
Jiyong Park1613e552020-09-14 19:43:17 +09003184 return b.os.Class == Host
Colin Crossf6566ed2015-03-24 11:13:38 -07003185}
3186
Colin Cross0ea8ba82019-06-06 14:33:29 -07003187func (b *baseModuleContext) Device() bool {
Colin Crossfb0c16e2019-11-20 17:12:35 -08003188 return b.os.Class == Device
Colin Crossf6566ed2015-03-24 11:13:38 -07003189}
3190
Colin Cross0ea8ba82019-06-06 14:33:29 -07003191func (b *baseModuleContext) Darwin() bool {
Colin Crossfb0c16e2019-11-20 17:12:35 -08003192 return b.os == Darwin
Colin Cross0af4b842015-04-30 16:36:18 -07003193}
3194
Colin Cross0ea8ba82019-06-06 14:33:29 -07003195func (b *baseModuleContext) Windows() bool {
Colin Crossfb0c16e2019-11-20 17:12:35 -08003196 return b.os == Windows
Colin Cross3edeee12017-04-04 12:59:48 -07003197}
3198
Colin Cross0ea8ba82019-06-06 14:33:29 -07003199func (b *baseModuleContext) Debug() bool {
Colin Cross25de6c32019-06-06 14:29:25 -07003200 return b.debug
Colin Crossf6566ed2015-03-24 11:13:38 -07003201}
3202
Colin Cross0ea8ba82019-06-06 14:33:29 -07003203func (b *baseModuleContext) PrimaryArch() bool {
Colin Cross25de6c32019-06-06 14:29:25 -07003204 if len(b.config.Targets[b.target.Os]) <= 1 {
Colin Cross67a5c132017-05-09 13:45:28 -07003205 return true
3206 }
Colin Cross25de6c32019-06-06 14:29:25 -07003207 return b.target.Arch.ArchType == b.config.Targets[b.target.Os][0].Arch.ArchType
Colin Cross1e7d3702016-08-24 15:25:47 -07003208}
3209
Jiyong Park5baac542018-08-28 09:55:37 +09003210// Makes this module a platform module, i.e. not specific to soc, device,
Justin Yund5f6c822019-06-25 16:47:17 +09003211// product, or system_ext.
Colin Cross4157e882019-06-06 16:57:04 -07003212func (m *ModuleBase) MakeAsPlatform() {
3213 m.commonProperties.Vendor = boolPtr(false)
3214 m.commonProperties.Proprietary = boolPtr(false)
3215 m.commonProperties.Soc_specific = boolPtr(false)
3216 m.commonProperties.Product_specific = boolPtr(false)
Justin Yund5f6c822019-06-25 16:47:17 +09003217 m.commonProperties.System_ext_specific = boolPtr(false)
Jiyong Park5baac542018-08-28 09:55:37 +09003218}
3219
Sundong Ahnd95aa2d2019-10-08 19:34:03 +09003220func (m *ModuleBase) MakeAsSystemExt() {
Jooyung Han91df2082019-11-20 01:49:42 +09003221 m.commonProperties.Vendor = boolPtr(false)
3222 m.commonProperties.Proprietary = boolPtr(false)
3223 m.commonProperties.Soc_specific = boolPtr(false)
3224 m.commonProperties.Product_specific = boolPtr(false)
3225 m.commonProperties.System_ext_specific = boolPtr(true)
Sundong Ahnd95aa2d2019-10-08 19:34:03 +09003226}
3227
Jooyung Han344d5432019-08-23 11:17:39 +09003228// IsNativeBridgeSupported returns true if "native_bridge_supported" is explicitly set as "true"
3229func (m *ModuleBase) IsNativeBridgeSupported() bool {
3230 return proptools.Bool(m.commonProperties.Native_bridge_supported)
3231}
3232
Colin Cross25de6c32019-06-06 14:29:25 -07003233func (m *moduleContext) InstallInData() bool {
3234 return m.module.InstallInData()
Dan Willemsen782a2d12015-12-21 14:55:28 -08003235}
3236
Jaewoong Jung0949f312019-09-11 10:25:18 -07003237func (m *moduleContext) InstallInTestcases() bool {
3238 return m.module.InstallInTestcases()
3239}
3240
Colin Cross25de6c32019-06-06 14:29:25 -07003241func (m *moduleContext) InstallInSanitizerDir() bool {
3242 return m.module.InstallInSanitizerDir()
Vishwath Mohan1dd88392017-03-29 22:00:18 -07003243}
3244
Yifan Hong1b3348d2020-01-21 15:53:22 -08003245func (m *moduleContext) InstallInRamdisk() bool {
3246 return m.module.InstallInRamdisk()
3247}
3248
Yifan Hong60e0cfb2020-10-21 15:17:56 -07003249func (m *moduleContext) InstallInVendorRamdisk() bool {
3250 return m.module.InstallInVendorRamdisk()
3251}
3252
Inseob Kim08758f02021-04-08 21:13:22 +09003253func (m *moduleContext) InstallInDebugRamdisk() bool {
3254 return m.module.InstallInDebugRamdisk()
3255}
3256
Colin Cross25de6c32019-06-06 14:29:25 -07003257func (m *moduleContext) InstallInRecovery() bool {
3258 return m.module.InstallInRecovery()
Jiyong Parkf9332f12018-02-01 00:54:12 +09003259}
3260
Colin Cross90ba5f42019-10-02 11:10:58 -07003261func (m *moduleContext) InstallInRoot() bool {
3262 return m.module.InstallInRoot()
3263}
3264
Jiyong Park87788b52020-09-01 12:37:45 +09003265func (m *moduleContext) InstallForceOS() (*OsType, *ArchType) {
Colin Cross6e359402020-02-10 15:29:54 -08003266 return m.module.InstallForceOS()
3267}
3268
Kiyoung Kimae11c232021-07-19 11:38:04 +09003269func (m *moduleContext) InstallInVendor() bool {
3270 return m.module.InstallInVendor()
3271}
3272
Colin Crossa9c8c9f2020-12-16 10:20:23 -08003273func (m *moduleContext) skipInstall() bool {
Colin Cross25de6c32019-06-06 14:29:25 -07003274 if m.module.base().commonProperties.SkipInstall {
Colin Cross893d8162017-04-26 17:34:03 -07003275 return true
3276 }
3277
Colin Crossa9c8c9f2020-12-16 10:20:23 -08003278 if m.module.base().commonProperties.HideFromMake {
3279 return true
3280 }
3281
Colin Cross3607f212018-05-07 15:28:05 -07003282 // We'll need a solution for choosing which of modules with the same name in different
3283 // namespaces to install. For now, reuse the list of namespaces exported to Make as the
3284 // list of namespaces to install in a Soong-only build.
Colin Cross25de6c32019-06-06 14:29:25 -07003285 if !m.module.base().commonProperties.NamespaceExportedToMake {
Colin Cross3607f212018-05-07 15:28:05 -07003286 return true
3287 }
3288
Colin Cross893d8162017-04-26 17:34:03 -07003289 return false
3290}
3291
Colin Cross70dda7e2019-10-01 22:05:35 -07003292func (m *moduleContext) InstallFile(installPath InstallPath, name string, srcPath Path,
3293 deps ...Path) InstallPath {
Colin Cross50ed1f92021-11-12 17:41:02 -08003294 return m.installFile(installPath, name, srcPath, deps, false, nil)
Colin Cross5c517922017-08-31 12:29:17 -07003295}
3296
Colin Cross70dda7e2019-10-01 22:05:35 -07003297func (m *moduleContext) InstallExecutable(installPath InstallPath, name string, srcPath Path,
3298 deps ...Path) InstallPath {
Colin Cross50ed1f92021-11-12 17:41:02 -08003299 return m.installFile(installPath, name, srcPath, deps, true, nil)
3300}
3301
3302func (m *moduleContext) InstallFileWithExtraFilesZip(installPath InstallPath, name string, srcPath Path,
3303 extraZip Path, deps ...Path) InstallPath {
3304 return m.installFile(installPath, name, srcPath, deps, false, &extraFilesZip{
3305 zip: extraZip,
3306 dir: installPath,
3307 })
Colin Cross5c517922017-08-31 12:29:17 -07003308}
3309
Colin Cross41589502020-12-01 14:00:21 -08003310func (m *moduleContext) PackageFile(installPath InstallPath, name string, srcPath Path) PackagingSpec {
3311 fullInstallPath := installPath.Join(m, name)
3312 return m.packageFile(fullInstallPath, srcPath, false)
3313}
3314
3315func (m *moduleContext) packageFile(fullInstallPath InstallPath, srcPath Path, executable bool) PackagingSpec {
Dan Willemsen9fe14102021-07-13 21:52:04 -07003316 licenseFiles := m.Module().EffectiveLicenseFiles()
Colin Cross41589502020-12-01 14:00:21 -08003317 spec := PackagingSpec{
Dan Willemsen9fe14102021-07-13 21:52:04 -07003318 relPathInPackage: Rel(m, fullInstallPath.PartitionDir(), fullInstallPath.String()),
3319 srcPath: srcPath,
3320 symlinkTarget: "",
3321 executable: executable,
3322 effectiveLicenseFiles: &licenseFiles,
Jooyung Han99c5fe62022-03-21 15:13:38 +09003323 partition: fullInstallPath.partition,
Colin Cross41589502020-12-01 14:00:21 -08003324 }
3325 m.packagingSpecs = append(m.packagingSpecs, spec)
3326 return spec
3327}
3328
Colin Cross50ed1f92021-11-12 17:41:02 -08003329func (m *moduleContext) installFile(installPath InstallPath, name string, srcPath Path, deps []Path,
3330 executable bool, extraZip *extraFilesZip) InstallPath {
Colin Cross35cec122015-04-02 14:37:16 -07003331
Colin Cross25de6c32019-06-06 14:29:25 -07003332 fullInstallPath := installPath.Join(m, name)
David Srbecky07656412020-06-04 01:26:16 +01003333 m.module.base().hooks.runInstallHooks(m, srcPath, fullInstallPath, false)
Colin Cross3f40fa42015-01-30 17:27:36 -08003334
Colin Crossa9c8c9f2020-12-16 10:20:23 -08003335 if !m.skipInstall() {
Colin Cross5d583952020-11-24 16:21:24 -08003336 deps = append(deps, m.module.base().installFilesDepSet.ToList().Paths()...)
Colin Cross35cec122015-04-02 14:37:16 -07003337
Colin Cross89562dc2016-10-03 17:47:19 -07003338 var implicitDeps, orderOnlyDeps Paths
3339
Colin Cross25de6c32019-06-06 14:29:25 -07003340 if m.Host() {
Colin Cross89562dc2016-10-03 17:47:19 -07003341 // Installed host modules might be used during the build, depend directly on their
3342 // dependencies so their timestamp is updated whenever their dependency is updated
3343 implicitDeps = deps
3344 } else {
3345 orderOnlyDeps = deps
3346 }
3347
Colin Crossc68db4b2021-11-11 18:59:15 -08003348 if m.Config().KatiEnabled() {
Colin Cross6301c3c2021-09-28 17:40:21 -07003349 // When creating the install rule in Soong but embedding in Make, write the rule to a
3350 // makefile instead of directly to the ninja file so that main.mk can add the
3351 // dependencies from the `required` property that are hard to resolve in Soong.
3352 m.katiInstalls = append(m.katiInstalls, katiInstall{
3353 from: srcPath,
3354 to: fullInstallPath,
3355 implicitDeps: implicitDeps,
3356 orderOnlyDeps: orderOnlyDeps,
3357 executable: executable,
Colin Cross50ed1f92021-11-12 17:41:02 -08003358 extraFiles: extraZip,
Colin Cross6301c3c2021-09-28 17:40:21 -07003359 })
3360 } else {
3361 rule := Cp
3362 if executable {
3363 rule = CpExecutable
3364 }
Jiyong Park073ea552020-11-09 14:08:34 +09003365
Colin Cross50ed1f92021-11-12 17:41:02 -08003366 extraCmds := ""
3367 if extraZip != nil {
Romain Jobredeaux1cef6292022-05-19 11:11:51 -04003368 extraCmds += fmt.Sprintf(" && ( unzip -qDD -d '%s' '%s' 2>&1 | grep -v \"zipfile is empty\"; exit $${PIPESTATUS[0]} )",
Colin Cross50ed1f92021-11-12 17:41:02 -08003369 extraZip.dir.String(), extraZip.zip.String())
Romain Jobredeaux1cef6292022-05-19 11:11:51 -04003370 extraCmds += " || ( code=$$?; if [ $$code -ne 0 -a $$code -ne 1 ]; then exit $$code; fi )"
Colin Cross50ed1f92021-11-12 17:41:02 -08003371 implicitDeps = append(implicitDeps, extraZip.zip)
3372 }
3373
Colin Cross6301c3c2021-09-28 17:40:21 -07003374 m.Build(pctx, BuildParams{
3375 Rule: rule,
3376 Description: "install " + fullInstallPath.Base(),
3377 Output: fullInstallPath,
3378 Input: srcPath,
3379 Implicits: implicitDeps,
3380 OrderOnly: orderOnlyDeps,
3381 Default: !m.Config().KatiEnabled(),
Colin Cross50ed1f92021-11-12 17:41:02 -08003382 Args: map[string]string{
3383 "extraCmds": extraCmds,
3384 },
Colin Cross6301c3c2021-09-28 17:40:21 -07003385 })
3386 }
Colin Cross3f40fa42015-01-30 17:27:36 -08003387
Colin Cross25de6c32019-06-06 14:29:25 -07003388 m.installFiles = append(m.installFiles, fullInstallPath)
Dan Willemsen322acaf2016-01-12 23:07:05 -08003389 }
Jiyong Park073ea552020-11-09 14:08:34 +09003390
Colin Cross41589502020-12-01 14:00:21 -08003391 m.packageFile(fullInstallPath, srcPath, executable)
Jiyong Park073ea552020-11-09 14:08:34 +09003392
Colin Cross25de6c32019-06-06 14:29:25 -07003393 m.checkbuildFiles = append(m.checkbuildFiles, srcPath)
Colin Crossa9c8c9f2020-12-16 10:20:23 -08003394
Colin Cross35cec122015-04-02 14:37:16 -07003395 return fullInstallPath
3396}
3397
Colin Cross70dda7e2019-10-01 22:05:35 -07003398func (m *moduleContext) InstallSymlink(installPath InstallPath, name string, srcPath InstallPath) InstallPath {
Colin Cross25de6c32019-06-06 14:29:25 -07003399 fullInstallPath := installPath.Join(m, name)
David Srbecky07656412020-06-04 01:26:16 +01003400 m.module.base().hooks.runInstallHooks(m, srcPath, fullInstallPath, true)
Colin Cross3854a602016-01-11 12:49:11 -08003401
Jiyong Park073ea552020-11-09 14:08:34 +09003402 relPath, err := filepath.Rel(path.Dir(fullInstallPath.String()), srcPath.String())
3403 if err != nil {
3404 panic(fmt.Sprintf("Unable to generate symlink between %q and %q: %s", fullInstallPath.Base(), srcPath.Base(), err))
3405 }
Colin Crossa9c8c9f2020-12-16 10:20:23 -08003406 if !m.skipInstall() {
Colin Crossce75d2c2016-10-06 16:12:58 -07003407
Colin Crossc68db4b2021-11-11 18:59:15 -08003408 if m.Config().KatiEnabled() {
Colin Cross6301c3c2021-09-28 17:40:21 -07003409 // When creating the symlink rule in Soong but embedding in Make, write the rule to a
3410 // makefile instead of directly to the ninja file so that main.mk can add the
3411 // dependencies from the `required` property that are hard to resolve in Soong.
3412 m.katiSymlinks = append(m.katiSymlinks, katiInstall{
3413 from: srcPath,
3414 to: fullInstallPath,
3415 })
3416 } else {
Colin Cross64002af2021-11-09 16:37:52 -08003417 // The symlink doesn't need updating when the target is modified, but we sometimes
3418 // have a dependency on a symlink to a binary instead of to the binary directly, and
3419 // the mtime of the symlink must be updated when the binary is modified, so use a
3420 // normal dependency here instead of an order-only dependency.
Colin Cross6301c3c2021-09-28 17:40:21 -07003421 m.Build(pctx, BuildParams{
3422 Rule: Symlink,
3423 Description: "install symlink " + fullInstallPath.Base(),
3424 Output: fullInstallPath,
3425 Input: srcPath,
3426 Default: !m.Config().KatiEnabled(),
3427 Args: map[string]string{
3428 "fromPath": relPath,
3429 },
3430 })
3431 }
Colin Cross3854a602016-01-11 12:49:11 -08003432
Colin Cross25de6c32019-06-06 14:29:25 -07003433 m.installFiles = append(m.installFiles, fullInstallPath)
3434 m.checkbuildFiles = append(m.checkbuildFiles, srcPath)
Colin Cross12fc4972016-01-11 12:49:11 -08003435 }
Jiyong Park073ea552020-11-09 14:08:34 +09003436
3437 m.packagingSpecs = append(m.packagingSpecs, PackagingSpec{
3438 relPathInPackage: Rel(m, fullInstallPath.PartitionDir(), fullInstallPath.String()),
3439 srcPath: nil,
3440 symlinkTarget: relPath,
3441 executable: false,
Jooyung Han99c5fe62022-03-21 15:13:38 +09003442 partition: fullInstallPath.partition,
Jiyong Park073ea552020-11-09 14:08:34 +09003443 })
3444
Colin Cross3854a602016-01-11 12:49:11 -08003445 return fullInstallPath
3446}
3447
Jiyong Parkf1194352019-02-25 11:05:47 +09003448// installPath/name -> absPath where absPath might be a path that is available only at runtime
3449// (e.g. /apex/...)
Colin Cross70dda7e2019-10-01 22:05:35 -07003450func (m *moduleContext) InstallAbsoluteSymlink(installPath InstallPath, name string, absPath string) InstallPath {
Colin Cross25de6c32019-06-06 14:29:25 -07003451 fullInstallPath := installPath.Join(m, name)
David Srbecky07656412020-06-04 01:26:16 +01003452 m.module.base().hooks.runInstallHooks(m, nil, fullInstallPath, true)
Jiyong Parkf1194352019-02-25 11:05:47 +09003453
Colin Crossa9c8c9f2020-12-16 10:20:23 -08003454 if !m.skipInstall() {
Colin Crossc68db4b2021-11-11 18:59:15 -08003455 if m.Config().KatiEnabled() {
Colin Cross6301c3c2021-09-28 17:40:21 -07003456 // When creating the symlink rule in Soong but embedding in Make, write the rule to a
3457 // makefile instead of directly to the ninja file so that main.mk can add the
3458 // dependencies from the `required` property that are hard to resolve in Soong.
3459 m.katiSymlinks = append(m.katiSymlinks, katiInstall{
3460 absFrom: absPath,
3461 to: fullInstallPath,
3462 })
3463 } else {
3464 m.Build(pctx, BuildParams{
3465 Rule: Symlink,
3466 Description: "install symlink " + fullInstallPath.Base() + " -> " + absPath,
3467 Output: fullInstallPath,
3468 Default: !m.Config().KatiEnabled(),
3469 Args: map[string]string{
3470 "fromPath": absPath,
3471 },
3472 })
3473 }
Jiyong Parkf1194352019-02-25 11:05:47 +09003474
Colin Cross25de6c32019-06-06 14:29:25 -07003475 m.installFiles = append(m.installFiles, fullInstallPath)
Jiyong Parkf1194352019-02-25 11:05:47 +09003476 }
Jiyong Park073ea552020-11-09 14:08:34 +09003477
3478 m.packagingSpecs = append(m.packagingSpecs, PackagingSpec{
3479 relPathInPackage: Rel(m, fullInstallPath.PartitionDir(), fullInstallPath.String()),
3480 srcPath: nil,
3481 symlinkTarget: absPath,
3482 executable: false,
Jooyung Han99c5fe62022-03-21 15:13:38 +09003483 partition: fullInstallPath.partition,
Jiyong Park073ea552020-11-09 14:08:34 +09003484 })
3485
Jiyong Parkf1194352019-02-25 11:05:47 +09003486 return fullInstallPath
3487}
3488
Colin Cross25de6c32019-06-06 14:29:25 -07003489func (m *moduleContext) CheckbuildFile(srcPath Path) {
3490 m.checkbuildFiles = append(m.checkbuildFiles, srcPath)
Colin Cross3f40fa42015-01-30 17:27:36 -08003491}
3492
Colin Crossc20dc852020-11-10 12:27:45 -08003493func (m *moduleContext) blueprintModuleContext() blueprint.ModuleContext {
3494 return m.bp
3495}
3496
Colin Crosse7fe0962022-03-15 17:49:24 -07003497func (m *moduleContext) LicenseMetadataFile() Path {
3498 return m.module.base().licenseMetadataFile
3499}
3500
Paul Duffine6ba0722021-07-12 20:12:12 +01003501// SrcIsModule decodes module references in the format ":unqualified-name" or "//namespace:name"
3502// into the module name, or empty string if the input was not a module reference.
Colin Cross41955e82019-05-29 14:40:35 -07003503func SrcIsModule(s string) (module string) {
Paul Duffine6ba0722021-07-12 20:12:12 +01003504 if len(s) > 1 {
3505 if s[0] == ':' {
3506 module = s[1:]
3507 if !isUnqualifiedModuleName(module) {
3508 // The module name should be unqualified but is not so do not treat it as a module.
3509 module = ""
3510 }
3511 } else if s[0] == '/' && s[1] == '/' {
3512 module = s
3513 }
Colin Cross068e0fe2016-12-13 15:23:47 -08003514 }
Paul Duffine6ba0722021-07-12 20:12:12 +01003515 return module
Colin Cross068e0fe2016-12-13 15:23:47 -08003516}
3517
Yi-Yo Chiangba9ea322021-07-15 17:18:21 +08003518// SrcIsModuleWithTag decodes module references in the format ":unqualified-name{.tag}" or
3519// "//namespace:name{.tag}" into the module name and tag, ":unqualified-name" or "//namespace:name"
3520// into the module name and an empty string for the tag, or empty strings if the input was not a
3521// module reference.
Colin Cross41955e82019-05-29 14:40:35 -07003522func SrcIsModuleWithTag(s string) (module, tag string) {
Paul Duffine6ba0722021-07-12 20:12:12 +01003523 if len(s) > 1 {
3524 if s[0] == ':' {
3525 module = s[1:]
3526 } else if s[0] == '/' && s[1] == '/' {
3527 module = s
3528 }
3529
3530 if module != "" {
3531 if tagStart := strings.IndexByte(module, '{'); tagStart > 0 {
3532 if module[len(module)-1] == '}' {
3533 tag = module[tagStart+1 : len(module)-1]
3534 module = module[:tagStart]
3535 }
3536 }
3537
3538 if s[0] == ':' && !isUnqualifiedModuleName(module) {
3539 // The module name should be unqualified but is not so do not treat it as a module.
3540 module = ""
3541 tag = ""
Colin Cross41955e82019-05-29 14:40:35 -07003542 }
3543 }
Colin Cross41955e82019-05-29 14:40:35 -07003544 }
Paul Duffine6ba0722021-07-12 20:12:12 +01003545
3546 return module, tag
3547}
3548
3549// isUnqualifiedModuleName makes sure that the supplied module is an unqualified module name, i.e.
3550// does not contain any /.
3551func isUnqualifiedModuleName(module string) bool {
3552 return strings.IndexByte(module, '/') == -1
Colin Cross068e0fe2016-12-13 15:23:47 -08003553}
3554
Paul Duffin40131a32021-07-09 17:10:35 +01003555// sourceOrOutputDependencyTag is the dependency tag added automatically by pathDepsMutator for any
3556// module reference in a property annotated with `android:"path"` or passed to ExtractSourceDeps
3557// or ExtractSourcesDeps.
3558//
3559// If uniquely identifies the dependency that was added as it contains both the module name used to
3560// add the dependency as well as the tag. That makes it very simple to find the matching dependency
3561// in GetModuleFromPathDep as all it needs to do is find the dependency whose tag matches the tag
3562// used to add it. It does not need to check that the module name as returned by one of
3563// Module.Name(), BaseModuleContext.OtherModuleName() or ModuleBase.BaseModuleName() matches the
3564// name supplied in the tag. That means it does not need to handle differences in module names
3565// caused by prebuilt_ prefix, or fully qualified module names.
Colin Cross41955e82019-05-29 14:40:35 -07003566type sourceOrOutputDependencyTag struct {
3567 blueprint.BaseDependencyTag
Paul Duffin40131a32021-07-09 17:10:35 +01003568
3569 // The name of the module.
3570 moduleName string
3571
3572 // The tag that will be passed to the module's OutputFileProducer.OutputFiles(tag) method.
Colin Cross41955e82019-05-29 14:40:35 -07003573 tag string
3574}
3575
Paul Duffin40131a32021-07-09 17:10:35 +01003576func sourceOrOutputDepTag(moduleName, tag string) blueprint.DependencyTag {
3577 return sourceOrOutputDependencyTag{moduleName: moduleName, tag: tag}
Colin Cross41955e82019-05-29 14:40:35 -07003578}
3579
Paul Duffind5cf92e2021-07-09 17:38:55 +01003580// IsSourceDepTagWithOutputTag returns true if the supplied blueprint.DependencyTag is one that was
3581// used to add dependencies by either ExtractSourceDeps, ExtractSourcesDeps or automatically for
3582// properties tagged with `android:"path"` AND it was added using a module reference of
3583// :moduleName{outputTag}.
3584func IsSourceDepTagWithOutputTag(depTag blueprint.DependencyTag, outputTag string) bool {
3585 t, ok := depTag.(sourceOrOutputDependencyTag)
3586 return ok && t.tag == outputTag
3587}
3588
Colin Cross366938f2017-12-11 16:29:02 -08003589// Adds necessary dependencies to satisfy filegroup or generated sources modules listed in srcFiles
3590// using ":module" syntax, if any.
Colin Cross27b922f2019-03-04 22:35:41 -08003591//
3592// Deprecated: tag the property with `android:"path"` instead.
Colin Cross068e0fe2016-12-13 15:23:47 -08003593func ExtractSourcesDeps(ctx BottomUpMutatorContext, srcFiles []string) {
Nan Zhang2439eb72017-04-10 11:27:50 -07003594 set := make(map[string]bool)
3595
Colin Cross068e0fe2016-12-13 15:23:47 -08003596 for _, s := range srcFiles {
Colin Cross41955e82019-05-29 14:40:35 -07003597 if m, t := SrcIsModuleWithTag(s); m != "" {
3598 if _, found := set[s]; found {
3599 ctx.ModuleErrorf("found source dependency duplicate: %q!", s)
Nan Zhang2439eb72017-04-10 11:27:50 -07003600 } else {
Colin Cross41955e82019-05-29 14:40:35 -07003601 set[s] = true
Paul Duffin40131a32021-07-09 17:10:35 +01003602 ctx.AddDependency(ctx.Module(), sourceOrOutputDepTag(m, t), m)
Nan Zhang2439eb72017-04-10 11:27:50 -07003603 }
Colin Cross068e0fe2016-12-13 15:23:47 -08003604 }
3605 }
Colin Cross068e0fe2016-12-13 15:23:47 -08003606}
3607
Colin Cross366938f2017-12-11 16:29:02 -08003608// Adds necessary dependencies to satisfy filegroup or generated sources modules specified in s
3609// using ":module" syntax, if any.
Colin Cross27b922f2019-03-04 22:35:41 -08003610//
3611// Deprecated: tag the property with `android:"path"` instead.
Colin Cross366938f2017-12-11 16:29:02 -08003612func ExtractSourceDeps(ctx BottomUpMutatorContext, s *string) {
3613 if s != nil {
Colin Cross41955e82019-05-29 14:40:35 -07003614 if m, t := SrcIsModuleWithTag(*s); m != "" {
Paul Duffin40131a32021-07-09 17:10:35 +01003615 ctx.AddDependency(ctx.Module(), sourceOrOutputDepTag(m, t), m)
Colin Cross366938f2017-12-11 16:29:02 -08003616 }
3617 }
3618}
3619
Colin Cross41955e82019-05-29 14:40:35 -07003620// A module that implements SourceFileProducer can be referenced from any property that is tagged with `android:"path"`
3621// 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 -08003622type SourceFileProducer interface {
3623 Srcs() Paths
3624}
3625
Colin Cross41955e82019-05-29 14:40:35 -07003626// A module that implements OutputFileProducer can be referenced from any property that is tagged with `android:"path"`
Roland Levillain97c1f342019-11-22 14:20:54 +00003627// 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 -07003628// listed in the property.
3629type OutputFileProducer interface {
3630 OutputFiles(tag string) (Paths, error)
3631}
3632
Colin Cross5e708052019-08-06 13:59:50 -07003633// OutputFilesForModule returns the paths from an OutputFileProducer with the given tag. On error, including if the
3634// module produced zero paths, it reports errors to the ctx and returns nil.
3635func OutputFilesForModule(ctx PathContext, module blueprint.Module, tag string) Paths {
3636 paths, err := outputFilesForModule(ctx, module, tag)
3637 if err != nil {
3638 reportPathError(ctx, err)
3639 return nil
3640 }
3641 return paths
3642}
3643
3644// OutputFileForModule returns the path from an OutputFileProducer with the given tag. On error, including if the
3645// module produced zero or multiple paths, it reports errors to the ctx and returns nil.
3646func OutputFileForModule(ctx PathContext, module blueprint.Module, tag string) Path {
3647 paths, err := outputFilesForModule(ctx, module, tag)
3648 if err != nil {
3649 reportPathError(ctx, err)
3650 return nil
3651 }
Colin Cross14ec66c2022-10-03 21:02:27 -07003652 if len(paths) == 0 {
3653 type addMissingDependenciesIntf interface {
3654 AddMissingDependencies([]string)
3655 OtherModuleName(blueprint.Module) string
3656 }
3657 if mctx, ok := ctx.(addMissingDependenciesIntf); ok && ctx.Config().AllowMissingDependencies() {
3658 mctx.AddMissingDependencies([]string{mctx.OtherModuleName(module)})
3659 } else {
3660 ReportPathErrorf(ctx, "failed to get output files from module %q", pathContextName(ctx, module))
3661 }
3662 // Return a fake output file to avoid nil dereferences of Path objects later.
3663 // This should never get used for an actual build as the error or missing
3664 // dependency has already been reported.
3665 p, err := pathForSource(ctx, filepath.Join("missing_output_file", pathContextName(ctx, module)))
3666 if err != nil {
3667 reportPathError(ctx, err)
3668 return nil
3669 }
3670 return p
3671 }
Colin Cross5e708052019-08-06 13:59:50 -07003672 if len(paths) > 1 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01003673 ReportPathErrorf(ctx, "got multiple output files from module %q, expected exactly one",
Colin Cross5e708052019-08-06 13:59:50 -07003674 pathContextName(ctx, module))
Colin Cross5e708052019-08-06 13:59:50 -07003675 }
3676 return paths[0]
3677}
3678
3679func outputFilesForModule(ctx PathContext, module blueprint.Module, tag string) (Paths, error) {
3680 if outputFileProducer, ok := module.(OutputFileProducer); ok {
3681 paths, err := outputFileProducer.OutputFiles(tag)
3682 if err != nil {
3683 return nil, fmt.Errorf("failed to get output file from module %q: %s",
3684 pathContextName(ctx, module), err.Error())
3685 }
Colin Cross5e708052019-08-06 13:59:50 -07003686 return paths, nil
Colin Cross74b1e2b2020-11-22 20:23:02 -08003687 } else if sourceFileProducer, ok := module.(SourceFileProducer); ok {
3688 if tag != "" {
3689 return nil, fmt.Errorf("module %q is a SourceFileProducer, not an OutputFileProducer, and so does not support tag %q", pathContextName(ctx, module), tag)
3690 }
3691 paths := sourceFileProducer.Srcs()
Colin Cross74b1e2b2020-11-22 20:23:02 -08003692 return paths, nil
Colin Cross5e708052019-08-06 13:59:50 -07003693 } else {
3694 return nil, fmt.Errorf("module %q is not an OutputFileProducer", pathContextName(ctx, module))
3695 }
3696}
3697
Colin Cross41589502020-12-01 14:00:21 -08003698// Modules can implement HostToolProvider and return a valid OptionalPath from HostToolPath() to
3699// specify that they can be used as a tool by a genrule module.
Colin Crossfe17f6f2019-03-28 19:30:56 -07003700type HostToolProvider interface {
Colin Crossba9e4032020-11-24 16:32:22 -08003701 Module
Colin Cross41589502020-12-01 14:00:21 -08003702 // HostToolPath returns the path to the host tool for the module if it is one, or an invalid
3703 // OptionalPath.
Colin Crossfe17f6f2019-03-28 19:30:56 -07003704 HostToolPath() OptionalPath
3705}
3706
Colin Cross27b922f2019-03-04 22:35:41 -08003707// Returns a list of paths expanded from globs and modules referenced using ":module" syntax. The property must
3708// be tagged with `android:"path" to support automatic source module dependency resolution.
Colin Cross8a497952019-03-05 22:25:09 -08003709//
3710// Deprecated: use PathsForModuleSrc or PathsForModuleSrcExcludes instead.
Colin Cross25de6c32019-06-06 14:29:25 -07003711func (m *moduleContext) ExpandSources(srcFiles, excludes []string) Paths {
3712 return PathsForModuleSrcExcludes(m, srcFiles, excludes)
Colin Cross8f101b42015-06-17 15:09:06 -07003713}
3714
Colin Cross2fafa3e2019-03-05 12:39:51 -08003715// Returns a single path expanded from globs and modules referenced using ":module" syntax. The property must
3716// be tagged with `android:"path" to support automatic source module dependency resolution.
Colin Cross8a497952019-03-05 22:25:09 -08003717//
3718// Deprecated: use PathForModuleSrc instead.
Sasha Smundake198eaf2022-08-04 13:07:02 -07003719func (m *moduleContext) ExpandSource(srcFile, _ string) Path {
Colin Cross25de6c32019-06-06 14:29:25 -07003720 return PathForModuleSrc(m, srcFile)
Colin Cross2fafa3e2019-03-05 12:39:51 -08003721}
3722
3723// Returns an optional single path expanded from globs and modules referenced using ":module" syntax if
3724// the srcFile is non-nil. The property must be tagged with `android:"path" to support automatic source module
3725// dependency resolution.
Sasha Smundake198eaf2022-08-04 13:07:02 -07003726func (m *moduleContext) ExpandOptionalSource(srcFile *string, _ string) OptionalPath {
Colin Cross2fafa3e2019-03-05 12:39:51 -08003727 if srcFile != nil {
Colin Cross25de6c32019-06-06 14:29:25 -07003728 return OptionalPathForPath(PathForModuleSrc(m, *srcFile))
Colin Cross2fafa3e2019-03-05 12:39:51 -08003729 }
3730 return OptionalPath{}
3731}
3732
Colin Cross25de6c32019-06-06 14:29:25 -07003733func (m *moduleContext) RequiredModuleNames() []string {
Jiyong Park6a8cf5f2019-12-30 16:31:09 +09003734 return m.module.RequiredModuleNames()
Nan Zhang6d34b302017-02-04 17:47:46 -08003735}
3736
Colin Cross25de6c32019-06-06 14:29:25 -07003737func (m *moduleContext) HostRequiredModuleNames() []string {
Jiyong Park6a8cf5f2019-12-30 16:31:09 +09003738 return m.module.HostRequiredModuleNames()
Sasha Smundakb6d23052019-04-01 18:37:36 -07003739}
3740
Colin Cross25de6c32019-06-06 14:29:25 -07003741func (m *moduleContext) TargetRequiredModuleNames() []string {
Jiyong Park6a8cf5f2019-12-30 16:31:09 +09003742 return m.module.TargetRequiredModuleNames()
Sasha Smundakb6d23052019-04-01 18:37:36 -07003743}
3744
Colin Cross463a90e2015-06-17 14:20:06 -07003745func init() {
Colin Cross798bfce2016-10-12 14:28:16 -07003746 RegisterSingletonType("buildtarget", BuildTargetSingleton)
Colin Cross463a90e2015-06-17 14:20:06 -07003747}
3748
Colin Cross0875c522017-11-28 17:34:01 -08003749func BuildTargetSingleton() Singleton {
Colin Cross1f8c52b2015-06-16 16:38:17 -07003750 return &buildTargetSingleton{}
3751}
3752
Colin Cross87d8b562017-04-25 10:01:55 -07003753func parentDir(dir string) string {
3754 dir, _ = filepath.Split(dir)
3755 return filepath.Clean(dir)
3756}
3757
Colin Cross1f8c52b2015-06-16 16:38:17 -07003758type buildTargetSingleton struct{}
3759
Chih-Hung Hsieh80783772021-10-11 16:46:56 -07003760func AddAncestors(ctx SingletonContext, dirMap map[string]Paths, mmName func(string) string) ([]string, []string) {
Chih-Hung Hsiehd0f82fe2021-09-05 20:15:38 -07003761 // Ensure ancestor directories are in dirMap
3762 // Make directories build their direct subdirectories
Chih-Hung Hsieh80783772021-10-11 16:46:56 -07003763 // Returns a slice of all directories and a slice of top-level directories.
Cole Faust18994c72023-02-28 16:02:16 -08003764 dirs := SortedKeys(dirMap)
Chih-Hung Hsiehd0f82fe2021-09-05 20:15:38 -07003765 for _, dir := range dirs {
3766 dir := parentDir(dir)
3767 for dir != "." && dir != "/" {
3768 if _, exists := dirMap[dir]; exists {
3769 break
3770 }
3771 dirMap[dir] = nil
3772 dir = parentDir(dir)
3773 }
3774 }
Cole Faust18994c72023-02-28 16:02:16 -08003775 dirs = SortedKeys(dirMap)
Chih-Hung Hsieh80783772021-10-11 16:46:56 -07003776 var topDirs []string
Chih-Hung Hsiehd0f82fe2021-09-05 20:15:38 -07003777 for _, dir := range dirs {
3778 p := parentDir(dir)
3779 if p != "." && p != "/" {
3780 dirMap[p] = append(dirMap[p], PathForPhony(ctx, mmName(dir)))
Chih-Hung Hsieh80783772021-10-11 16:46:56 -07003781 } else if dir != "." && dir != "/" && dir != "" {
3782 topDirs = append(topDirs, dir)
Chih-Hung Hsiehd0f82fe2021-09-05 20:15:38 -07003783 }
3784 }
Cole Faust18994c72023-02-28 16:02:16 -08003785 return SortedKeys(dirMap), topDirs
Chih-Hung Hsiehd0f82fe2021-09-05 20:15:38 -07003786}
3787
Colin Cross0875c522017-11-28 17:34:01 -08003788func (c *buildTargetSingleton) GenerateBuildActions(ctx SingletonContext) {
3789 var checkbuildDeps Paths
Colin Cross1f8c52b2015-06-16 16:38:17 -07003790
Colin Crossc3d87d32020-06-04 13:25:17 -07003791 mmTarget := func(dir string) string {
3792 return "MODULES-IN-" + strings.Replace(filepath.Clean(dir), "/", "-", -1)
Colin Cross87d8b562017-04-25 10:01:55 -07003793 }
3794
Colin Cross0875c522017-11-28 17:34:01 -08003795 modulesInDir := make(map[string]Paths)
Colin Cross1f8c52b2015-06-16 16:38:17 -07003796
Colin Cross0875c522017-11-28 17:34:01 -08003797 ctx.VisitAllModules(func(module Module) {
3798 blueprintDir := module.base().blueprintDir
3799 installTarget := module.base().installTarget
3800 checkbuildTarget := module.base().checkbuildTarget
Colin Cross1f8c52b2015-06-16 16:38:17 -07003801
Colin Cross0875c522017-11-28 17:34:01 -08003802 if checkbuildTarget != nil {
3803 checkbuildDeps = append(checkbuildDeps, checkbuildTarget)
3804 modulesInDir[blueprintDir] = append(modulesInDir[blueprintDir], checkbuildTarget)
3805 }
Colin Cross1f8c52b2015-06-16 16:38:17 -07003806
Colin Cross0875c522017-11-28 17:34:01 -08003807 if installTarget != nil {
3808 modulesInDir[blueprintDir] = append(modulesInDir[blueprintDir], installTarget)
Colin Cross1f8c52b2015-06-16 16:38:17 -07003809 }
3810 })
3811
Dan Willemsen5ba07e82015-12-11 13:51:06 -08003812 suffix := ""
Jingwen Chencda22c92020-11-23 00:22:30 -05003813 if ctx.Config().KatiEnabled() {
Dan Willemsen5ba07e82015-12-11 13:51:06 -08003814 suffix = "-soong"
3815 }
3816
Colin Cross1f8c52b2015-06-16 16:38:17 -07003817 // Create a top-level checkbuild target that depends on all modules
Colin Crossc3d87d32020-06-04 13:25:17 -07003818 ctx.Phony("checkbuild"+suffix, checkbuildDeps...)
Colin Cross1f8c52b2015-06-16 16:38:17 -07003819
Dan Willemsend2e95fb2017-09-20 14:30:50 -07003820 // Make will generate the MODULES-IN-* targets
Jingwen Chencda22c92020-11-23 00:22:30 -05003821 if ctx.Config().KatiEnabled() {
Dan Willemsend2e95fb2017-09-20 14:30:50 -07003822 return
3823 }
3824
Chih-Hung Hsieh80783772021-10-11 16:46:56 -07003825 dirs, _ := AddAncestors(ctx, modulesInDir, mmTarget)
Colin Cross87d8b562017-04-25 10:01:55 -07003826
Dan Willemsend2e95fb2017-09-20 14:30:50 -07003827 // Create a MODULES-IN-<directory> target that depends on all modules in a directory, and
3828 // depends on the MODULES-IN-* targets of all of its subdirectories that contain Android.bp
3829 // files.
Colin Cross1f8c52b2015-06-16 16:38:17 -07003830 for _, dir := range dirs {
Colin Crossc3d87d32020-06-04 13:25:17 -07003831 ctx.Phony(mmTarget(dir), modulesInDir[dir]...)
Colin Cross1f8c52b2015-06-16 16:38:17 -07003832 }
Dan Willemsen61d88b82017-09-20 17:29:08 -07003833
3834 // Create (host|host-cross|target)-<OS> phony rules to build a reduced checkbuild.
Jiyong Park1613e552020-09-14 19:43:17 +09003835 type osAndCross struct {
3836 os OsType
3837 hostCross bool
3838 }
3839 osDeps := map[osAndCross]Paths{}
Colin Cross0875c522017-11-28 17:34:01 -08003840 ctx.VisitAllModules(func(module Module) {
3841 if module.Enabled() {
Jiyong Park1613e552020-09-14 19:43:17 +09003842 key := osAndCross{os: module.Target().Os, hostCross: module.Target().HostCross}
3843 osDeps[key] = append(osDeps[key], module.base().checkbuildFiles...)
Dan Willemsen61d88b82017-09-20 17:29:08 -07003844 }
3845 })
3846
Colin Cross0875c522017-11-28 17:34:01 -08003847 osClass := make(map[string]Paths)
Jiyong Park1613e552020-09-14 19:43:17 +09003848 for key, deps := range osDeps {
Dan Willemsen61d88b82017-09-20 17:29:08 -07003849 var className string
3850
Jiyong Park1613e552020-09-14 19:43:17 +09003851 switch key.os.Class {
Dan Willemsen61d88b82017-09-20 17:29:08 -07003852 case Host:
Jiyong Park1613e552020-09-14 19:43:17 +09003853 if key.hostCross {
3854 className = "host-cross"
3855 } else {
3856 className = "host"
3857 }
Dan Willemsen61d88b82017-09-20 17:29:08 -07003858 case Device:
3859 className = "target"
3860 default:
3861 continue
3862 }
3863
Jiyong Park1613e552020-09-14 19:43:17 +09003864 name := className + "-" + key.os.Name
Colin Crossc3d87d32020-06-04 13:25:17 -07003865 osClass[className] = append(osClass[className], PathForPhony(ctx, name))
Dan Willemsen61d88b82017-09-20 17:29:08 -07003866
Colin Crossc3d87d32020-06-04 13:25:17 -07003867 ctx.Phony(name, deps...)
Dan Willemsen61d88b82017-09-20 17:29:08 -07003868 }
3869
3870 // Wrap those into host|host-cross|target phony rules
Cole Faust18994c72023-02-28 16:02:16 -08003871 for _, class := range SortedKeys(osClass) {
Colin Crossc3d87d32020-06-04 13:25:17 -07003872 ctx.Phony(class, osClass[class]...)
Dan Willemsen61d88b82017-09-20 17:29:08 -07003873 }
Colin Cross1f8c52b2015-06-16 16:38:17 -07003874}
Colin Crossd779da42015-12-17 18:00:23 -08003875
Brandon Lee5d45c6f2018-08-15 15:35:38 -07003876// Collect information for opening IDE project files in java/jdeps.go.
3877type IDEInfo interface {
3878 IDEInfo(ideInfo *IdeInfo)
3879 BaseModuleName() string
3880}
3881
3882// Extract the base module name from the Import name.
3883// Often the Import name has a prefix "prebuilt_".
3884// Remove the prefix explicitly if needed
3885// until we find a better solution to get the Import name.
3886type IDECustomizedModuleName interface {
3887 IDECustomizedModuleName() string
3888}
3889
3890type IdeInfo struct {
3891 Deps []string `json:"dependencies,omitempty"`
3892 Srcs []string `json:"srcs,omitempty"`
3893 Aidl_include_dirs []string `json:"aidl_include_dirs,omitempty"`
3894 Jarjar_rules []string `json:"jarjar_rules,omitempty"`
3895 Jars []string `json:"jars,omitempty"`
3896 Classes []string `json:"class,omitempty"`
3897 Installed_paths []string `json:"installed,omitempty"`
patricktu18c82ff2019-05-10 15:48:50 +08003898 SrcJars []string `json:"srcjars,omitempty"`
bralee1fbf4402020-05-21 10:11:59 +08003899 Paths []string `json:"path,omitempty"`
Yikef6282022022-04-13 20:41:01 +08003900 Static_libs []string `json:"static_libs,omitempty"`
3901 Libs []string `json:"libs,omitempty"`
Brandon Lee5d45c6f2018-08-15 15:35:38 -07003902}
Paul Duffinf88d8e02020-05-07 20:21:34 +01003903
3904func CheckBlueprintSyntax(ctx BaseModuleContext, filename string, contents string) []error {
3905 bpctx := ctx.blueprintBaseModuleContext()
3906 return blueprint.CheckBlueprintSyntax(bpctx.ModuleFactories(), filename, contents)
3907}
Colin Cross5d583952020-11-24 16:21:24 -08003908
3909// installPathsDepSet is a thin type-safe wrapper around the generic depSet. It always uses
3910// topological order.
3911type installPathsDepSet struct {
3912 depSet
3913}
3914
3915// newInstallPathsDepSet returns an immutable packagingSpecsDepSet with the given direct and
3916// transitive contents.
3917func newInstallPathsDepSet(direct InstallPaths, transitive []*installPathsDepSet) *installPathsDepSet {
3918 return &installPathsDepSet{*newDepSet(TOPOLOGICAL, direct, transitive)}
3919}
3920
3921// ToList returns the installPathsDepSet flattened to a list in topological order.
3922func (d *installPathsDepSet) ToList() InstallPaths {
3923 if d == nil {
3924 return nil
3925 }
3926 return d.depSet.ToList().(InstallPaths)
3927}