blob: ac62b8d06cf3eeb3edc92494e2743e70443d389f [file] [log] [blame]
Colin Cross5049f022015-03-18 13:28:46 -07001// 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
Alex Humesky29e3bbe2020-11-20 21:30:13 -050015// A genrule module takes a list of source files ("srcs" property), an optional
16// list of tools ("tools" property), and a command line ("cmd" property), to
17// generate output files ("out" property).
18
Colin Cross5049f022015-03-18 13:28:46 -070019package genrule
20
21import (
Colin Cross6f080df2016-11-04 15:32:58 -070022 "fmt"
Colin Crossa4ad2b02019-03-18 22:15:32 -070023 "io"
Inseob Kimf7cd03e2024-09-06 17:25:00 +090024 "path/filepath"
Colin Cross1a527682019-09-23 15:55:30 -070025 "strconv"
Colin Cross6f080df2016-11-04 15:32:58 -070026 "strings"
Dan Willemsen3f4539b2016-09-28 16:19:10 -070027
Colin Cross70b40592015-03-23 12:57:34 -070028 "github.com/google/blueprint"
Nan Zhangea568a42017-11-08 21:20:04 -080029 "github.com/google/blueprint/proptools"
Colin Cross5049f022015-03-18 13:28:46 -070030
Colin Cross635c3b02016-05-18 15:37:25 -070031 "android/soong/android"
Colin Cross5049f022015-03-18 13:28:46 -070032)
33
Colin Cross463a90e2015-06-17 14:20:06 -070034func init() {
Colin Crosse9fe2942020-11-10 18:12:15 -080035 RegisterGenruleBuildComponents(android.InitRegistrationContext)
Martin Stjernholm710ec3a2020-01-16 15:12:04 +000036}
Jaewoong Jung98716bd2018-12-10 08:13:18 -080037
Paul Duffin672cb9f2021-03-03 02:30:37 +000038// Test fixture preparer that will register most genrule build components.
39//
40// Singletons and mutators should only be added here if they are needed for a majority of genrule
41// module types, otherwise they should be added under a separate preparer to allow them to be
42// selected only when needed to reduce test execution time.
43//
44// Module types do not have much of an overhead unless they are used so this should include as many
45// module types as possible. The exceptions are those module types that require mutators and/or
46// singletons in order to function in which case they should be kept together in a separate
47// preparer.
48var PrepareForTestWithGenRuleBuildComponents = android.GroupFixturePreparers(
49 android.FixtureRegisterWithContext(RegisterGenruleBuildComponents),
50)
51
52// Prepare a fixture to use all genrule module types, mutators and singletons fully.
53//
54// This should only be used by tests that want to run with as much of the build enabled as possible.
55var PrepareForIntegrationTestWithGenrule = android.GroupFixturePreparers(
56 PrepareForTestWithGenRuleBuildComponents,
57)
58
Colin Crosse9fe2942020-11-10 18:12:15 -080059func RegisterGenruleBuildComponents(ctx android.RegistrationContext) {
Martin Stjernholm710ec3a2020-01-16 15:12:04 +000060 ctx.RegisterModuleType("genrule_defaults", defaultsFactory)
61
62 ctx.RegisterModuleType("gensrcs", GenSrcsFactory)
63 ctx.RegisterModuleType("genrule", GenRuleFactory)
64
65 ctx.FinalDepsMutators(func(ctx android.RegisterMutatorsContext) {
Colin Cross8a962802024-10-09 15:29:27 -070066 ctx.BottomUp("genrule_tool_deps", toolDepsMutator)
Martin Stjernholm710ec3a2020-01-16 15:12:04 +000067 })
Liz Kammer356f7d42021-01-26 09:18:53 -050068}
69
Colin Cross5049f022015-03-18 13:28:46 -070070var (
Colin Cross635c3b02016-05-18 15:37:25 -070071 pctx = android.NewPackageContext("android/soong/genrule")
Colin Cross1a527682019-09-23 15:55:30 -070072
Alex Humesky29e3bbe2020-11-20 21:30:13 -050073 // Used by gensrcs when there is more than 1 shard to merge the outputs
74 // of each shard into a zip file.
Colin Cross1a527682019-09-23 15:55:30 -070075 gensrcsMerge = pctx.AndroidStaticRule("gensrcsMerge", blueprint.RuleParams{
76 Command: "${soongZip} -o ${tmpZip} @${tmpZip}.rsp && ${zipSync} -d ${genDir} ${tmpZip}",
77 CommandDeps: []string{"${soongZip}", "${zipSync}"},
78 Rspfile: "${tmpZip}.rsp",
79 RspfileContent: "${zipArgs}",
80 }, "tmpZip", "genDir", "zipArgs")
Colin Cross5049f022015-03-18 13:28:46 -070081)
82
Jeff Gastonefc1b412017-03-29 17:29:06 -070083func init() {
Dan Willemsenddf504c2019-08-09 16:21:29 -070084 pctx.Import("android/soong/android")
Colin Cross1a527682019-09-23 15:55:30 -070085
86 pctx.HostBinToolVariable("soongZip", "soong_zip")
87 pctx.HostBinToolVariable("zipSync", "zipsync")
Jeff Gastonefc1b412017-03-29 17:29:06 -070088}
89
Colin Cross5049f022015-03-18 13:28:46 -070090type SourceFileGenerator interface {
Colin Cross635c3b02016-05-18 15:37:25 -070091 GeneratedSourceFiles() android.Paths
Colin Cross5ed99c62016-11-22 12:55:55 -080092 GeneratedHeaderDirs() android.Paths
Dan Willemsen9da9d492018-02-21 18:28:18 -080093 GeneratedDeps() android.Paths
Colin Cross5049f022015-03-18 13:28:46 -070094}
95
Colin Crossfe17f6f2019-03-28 19:30:56 -070096// Alias for android.HostToolProvider
97// Deprecated: use android.HostToolProvider instead.
Colin Crossd350ecd2015-04-28 13:25:36 -070098type HostToolProvider interface {
Colin Crossfe17f6f2019-03-28 19:30:56 -070099 android.HostToolProvider
Colin Crossd350ecd2015-04-28 13:25:36 -0700100}
Colin Cross5049f022015-03-18 13:28:46 -0700101
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700102type hostToolDependencyTag struct {
103 blueprint.BaseDependencyTag
Colin Cross65cb3142021-12-10 23:05:02 +0000104 android.LicenseAnnotationToolchainDependencyTag
Colin Cross08f15ab2018-10-04 23:29:14 -0700105 label string
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700106}
Martin Stjernholmdbd814d2022-01-12 23:18:30 +0000107
108func (t hostToolDependencyTag) AllowDisabledModuleDependency(target android.Module) bool {
109 // Allow depending on a disabled module if it's replaced by a prebuilt
110 // counterpart. We get the prebuilt through android.PrebuiltGetPreferred in
111 // GenerateAndroidBuildActions.
112 return target.IsReplacedByPrebuilt()
113}
114
Yu Liud2a95952024-10-10 00:15:26 +0000115func (t hostToolDependencyTag) AllowDisabledModuleDependencyProxy(
116 ctx android.OtherModuleProviderContext, target android.ModuleProxy) bool {
117 return android.OtherModuleProviderOrDefault(
Yu Liub5275322024-11-13 18:40:43 +0000118 ctx, target, android.CommonModuleInfoKey).ReplacedByPrebuilt
Yu Liud2a95952024-10-10 00:15:26 +0000119}
120
Martin Stjernholmdbd814d2022-01-12 23:18:30 +0000121var _ android.AllowDisabledModuleDependency = (*hostToolDependencyTag)(nil)
122
Colin Cross7d5136f2015-05-11 13:39:40 -0700123type generatorProperties struct {
Spandan Das93e95992021-07-29 18:26:39 +0000124 // The command to run on one or more input files. Cmd supports substitution of a few variables.
Jeff Gastonefc1b412017-03-29 17:29:06 -0700125 //
126 // Available variables for substitution:
127 //
Spandan Das93e95992021-07-29 18:26:39 +0000128 // $(location): the path to the first entry in tools or tool_files.
129 // $(location <label>): the path to the tool, tool_file, input or output with name <label>. Use $(location) if <label> refers to a rule that outputs exactly one file.
130 // $(locations <label>): the paths to the tools, tool_files, inputs or outputs with name <label>. Use $(locations) if <label> refers to a rule that outputs two or more files.
131 // $(in): one or more input files.
132 // $(out): a single output file.
Spandan Das93e95992021-07-29 18:26:39 +0000133 // $(genDir): the sandbox directory for this tool; contains $(out).
Colin Cross2296f5b2017-10-17 21:38:14 -0700134 // $$: a literal $
Aleks Todorov1eb06c42024-06-03 15:23:56 +0100135 Cmd proptools.Configurable[string] `android:"replace_instead_of_append"`
Colin Cross7d5136f2015-05-11 13:39:40 -0700136
Colin Cross6f080df2016-11-04 15:32:58 -0700137 // name of the modules (if any) that produces the host executable. Leave empty for
Colin Cross7d5136f2015-05-11 13:39:40 -0700138 // prebuilts or scripts that do not need a module to build them.
Colin Cross6f080df2016-11-04 15:32:58 -0700139 Tools []string
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700140
Sam Delmericof8775632023-08-14 23:45:41 +0000141 // Local files that are used by the tool
Colin Cross27b922f2019-03-04 22:35:41 -0800142 Tool_files []string `android:"path"`
Colin Cross5ed99c62016-11-22 12:55:55 -0800143
144 // List of directories to export generated headers from
145 Export_include_dirs []string
Colin Cross708c4242017-01-13 18:05:49 -0800146
147 // list of input files
Cole Faustf966e382024-10-08 16:17:56 -0700148 Srcs proptools.Configurable[[]string] `android:"path,arch_variant"`
Dan Willemseneefa0262018-11-17 14:01:18 -0800149
Cole Faust65cb40a2024-10-21 15:41:42 -0700150 // Same as srcs, but will add dependencies on modules via a device os variation and the device's
151 // first supported arch's variation. Can be used to add a dependency from a host genrule to
152 // a device module.
153 Device_first_srcs proptools.Configurable[[]string] `android:"path_device_first"`
154
155 // Same as srcs, but will add dependencies on modules via a device os variation and the common
156 // arch variation. Can be used to add a dependency from a host genrule to a device module.
157 Device_common_srcs proptools.Configurable[[]string] `android:"path_device_common"`
158
159 // Same as srcs, but will add dependencies on modules via a common_os os variation.
160 Common_os_srcs proptools.Configurable[[]string] `android:"path_common_os"`
161
Dan Willemseneefa0262018-11-17 14:01:18 -0800162 // input files to exclude
Colin Cross27b922f2019-03-04 22:35:41 -0800163 Exclude_srcs []string `android:"path,arch_variant"`
Justin Yun4da4ccc2023-07-06 10:56:29 +0900164
165 // Enable restat to update the output only if the output is changed
166 Write_if_changed *bool
Cole Faust78f3c3a2024-08-15 17:19:34 -0700167
168 // When set to true, an additional $(build_number_file) label will be available
169 // to use in the cmd. This will be the location of a text file containing the
170 // build number. The dependency on this file will be "order-only", meaning that
171 // the genrule will not rerun when only this file changes, to avoid rerunning
172 // the genrule every build, because the build number changes every build.
173 // This also means that you should not attempt to consume the build number from
174 // the result of this genrule in another build rule. If you do, the build number
175 // in the second build rule will be stale when the second build rule rebuilds
176 // but this genrule does not. Only certain allowlisted modules are allowed to
177 // use this property, usages of the build number should be kept to the absolute
178 // minimum. Particularly no modules on the system image may include the build
179 // number. Prefer using libbuildversion via the use_version_lib property on
180 // cc modules.
181 Uses_order_only_build_number_file *bool
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400182}
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500183
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700184type Module struct {
Colin Cross635c3b02016-05-18 15:37:25 -0700185 android.ModuleBase
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800186 android.DefaultableModuleBase
Jiyong Parkfc752ca2019-06-12 13:27:29 +0900187 android.ApexModuleBase
Colin Crossd350ecd2015-04-28 13:25:36 -0700188
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700189 // For other packages to make their own genrules with extra
190 // properties
191 Extra interface{}
Colin Crossf3bfd022021-09-27 15:15:06 -0700192
193 // CmdModifier can be set by wrappers around genrule to modify the command, for example to
194 // prefix environment variables to it.
195 CmdModifier func(ctx android.ModuleContext, cmd string) string
196
Colin Cross7228ecd2019-11-18 16:00:16 -0800197 android.ImageInterface
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700198
Colin Cross7d5136f2015-05-11 13:39:40 -0700199 properties generatorProperties
Colin Crossd350ecd2015-04-28 13:25:36 -0700200
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500201 // For the different tasks that genrule and gensrc generate. genrule will
202 // generate 1 task, and gensrc will generate 1 or more tasks based on the
203 // number of shards the input files are sharded into.
Jeff Gaston437d23c2017-11-08 12:38:00 -0800204 taskGenerator taskFunc
Colin Crossd350ecd2015-04-28 13:25:36 -0700205
Colin Cross1a527682019-09-23 15:55:30 -0700206 rule blueprint.Rule
207 rawCommands []string
Colin Crossd350ecd2015-04-28 13:25:36 -0700208
Colin Cross5ed99c62016-11-22 12:55:55 -0800209 exportedIncludeDirs android.Paths
Dan Willemsenb40aab62016-04-20 14:21:14 -0700210
Colin Cross635c3b02016-05-18 15:37:25 -0700211 outputFiles android.Paths
Dan Willemsen9da9d492018-02-21 18:28:18 -0800212 outputDeps android.Paths
Colin Crossa4ad2b02019-03-18 22:15:32 -0700213
214 subName string
Colin Cross1a527682019-09-23 15:55:30 -0700215 subDir string
Colin Crossd350ecd2015-04-28 13:25:36 -0700216}
217
Colin Cross1a527682019-09-23 15:55:30 -0700218type taskFunc func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask
Colin Crossd350ecd2015-04-28 13:25:36 -0700219
220type generateTask struct {
Liz Kammer81fec182023-06-09 13:33:45 -0400221 in android.Paths
222 out android.WritablePaths
Liz Kammer81fec182023-06-09 13:33:45 -0400223 copyTo android.WritablePaths // For gensrcs to set on gensrcsMerge rule.
224 genDir android.WritablePath
Liz Kammer81fec182023-06-09 13:33:45 -0400225 extraInputs map[string][]string
Colin Cross3ea4eb82020-11-24 13:07:27 -0800226
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500227 cmd string
228 // For gensrsc sharding.
Colin Cross3ea4eb82020-11-24 13:07:27 -0800229 shard int
230 shards int
Inseob Kimf7cd03e2024-09-06 17:25:00 +0900231
232 // For nsjail tasks
Inseob Kim7195b062024-11-29 15:40:49 +0900233 useNsjail bool
234 dirSrcs android.DirectoryPaths
235 keepGendir bool
Colin Crossd350ecd2015-04-28 13:25:36 -0700236}
237
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700238func (g *Module) GeneratedSourceFiles() android.Paths {
Colin Crossd350ecd2015-04-28 13:25:36 -0700239 return g.outputFiles
240}
241
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700242func (g *Module) Srcs() android.Paths {
Nan Zhange42777a2018-03-27 16:19:42 -0700243 return append(android.Paths{}, g.outputFiles...)
Colin Cross068e0fe2016-12-13 15:23:47 -0800244}
245
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700246func (g *Module) GeneratedHeaderDirs() android.Paths {
Colin Cross5ed99c62016-11-22 12:55:55 -0800247 return g.exportedIncludeDirs
Dan Willemsenb40aab62016-04-20 14:21:14 -0700248}
249
Dan Willemsen9da9d492018-02-21 18:28:18 -0800250func (g *Module) GeneratedDeps() android.Paths {
251 return g.outputDeps
252}
253
Jooyung Han8c7e3ed2021-06-28 17:35:58 +0900254var _ android.SourceFileProducer = (*Module)(nil)
Jooyung Han8c7e3ed2021-06-28 17:35:58 +0900255
Martin Stjernholm710ec3a2020-01-16 15:12:04 +0000256func toolDepsMutator(ctx android.BottomUpMutatorContext) {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700257 if g, ok := ctx.Module().(*Module); ok {
Colin Cross08f15ab2018-10-04 23:29:14 -0700258 for _, tool := range g.properties.Tools {
259 tag := hostToolDependencyTag{label: tool}
260 if m := android.SrcIsModule(tool); m != "" {
261 tool = m
262 }
Colin Cross0f7d2ef2019-10-16 11:03:10 -0700263 ctx.AddFarVariationDependencies(ctx.Config().BuildOSTarget.Variations(), tag, tool)
Colin Cross6362e272015-10-29 15:25:03 -0700264 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700265 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700266}
267
Cole Faustf23fdc02024-08-23 15:21:13 -0700268var buildNumberAllowlistKey = android.NewOnceKey("genruleBuildNumberAllowlistKey")
269
Cole Faust78f3c3a2024-08-15 17:19:34 -0700270// This allowlist should be kept to the bare minimum, it's
271// intended for things that existed before the build number
272// was tightly controlled. Prefer using libbuildversion
273// via the use_version_lib property of cc modules.
Cole Faustf23fdc02024-08-23 15:21:13 -0700274// This is a function instead of a global map so that
275// soong plugins cannot add entries to the allowlist
276func isModuleInBuildNumberAllowlist(ctx android.ModuleContext) bool {
277 allowlist := ctx.Config().Once(buildNumberAllowlistKey, func() interface{} {
Cole Faustdc018782024-08-28 11:08:06 -0700278 // Define the allowlist as a list and then copy it into a map so that
279 // gofmt doesn't change unnecessary lines trying to align the values of the map.
280 allowlist := []string{
Cole Faustf23fdc02024-08-23 15:21:13 -0700281 // go/keep-sorted start
Cole Faustdc018782024-08-28 11:08:06 -0700282 "build/soong/tests:gen",
283 "hardware/google/camera/common/hal/aidl_service:aidl_camera_build_version",
284 "tools/tradefederation/core:tradefed_zip",
285 "vendor/google/services/LyricCameraHAL/src/apex:com.google.pixel.camera.hal.manifest",
Cole Faustf23fdc02024-08-23 15:21:13 -0700286 // go/keep-sorted end
287 }
Cole Faustdc018782024-08-28 11:08:06 -0700288 allowlistMap := make(map[string]bool, len(allowlist))
289 for _, a := range allowlist {
290 allowlistMap[a] = true
291 }
292 return allowlistMap
Cole Faustf23fdc02024-08-23 15:21:13 -0700293 }).(map[string]bool)
294
295 _, ok := allowlist[ctx.ModuleDir()+":"+ctx.ModuleName()]
296 return ok
Cole Faust78f3c3a2024-08-15 17:19:34 -0700297}
298
Chris Parsonsf874e462022-05-10 13:50:12 -0400299// generateCommonBuildActions contains build action generation logic
300// common to both the mixed build case and the legacy case of genrule processing.
301// To fully support genrule in mixed builds, the contents of this function should
302// approach zero; there should be no genrule action registration done directly
303// by Soong logic in the mixed-build case.
304func (g *Module) generateCommonBuildActions(ctx android.ModuleContext) {
Cole Faust65cb40a2024-10-21 15:41:42 -0700305 // Add the variant as a suffix to the make modules to create, so that the make modules
306 // don't conflict because make doesn't know about variants. However, this causes issues with
307 // tracking required dependencies as the required property in soong is passed straight to make
308 // without accounting for these suffixes. To make it a little easier to work with, don't use
309 // a suffix for android_common variants so that java_genrules look like regular 1-variant
310 // genrules to make.
311 if ctx.ModuleSubDir() != "android_common" {
312 g.subName = ctx.ModuleSubDir()
313 }
Colin Crossa4ad2b02019-03-18 22:15:32 -0700314
Colin Cross5ed99c62016-11-22 12:55:55 -0800315 if len(g.properties.Export_include_dirs) > 0 {
316 for _, dir := range g.properties.Export_include_dirs {
317 g.exportedIncludeDirs = append(g.exportedIncludeDirs,
Colin Cross1a527682019-09-23 15:55:30 -0700318 android.PathForModuleGen(ctx, g.subDir, ctx.ModuleDir(), dir))
Liz Kammerd38c87c2023-07-17 09:58:50 -0400319 // Also export without ModuleDir for consistency with Export_include_dirs not being set
320 g.exportedIncludeDirs = append(g.exportedIncludeDirs,
321 android.PathForModuleGen(ctx, g.subDir, dir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800322 }
323 } else {
Colin Cross1a527682019-09-23 15:55:30 -0700324 g.exportedIncludeDirs = append(g.exportedIncludeDirs, android.PathForModuleGen(ctx, g.subDir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800325 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700326
Colin Crossd11cf622021-03-23 22:30:35 -0700327 locationLabels := map[string]location{}
Colin Cross08f15ab2018-10-04 23:29:14 -0700328 firstLabel := ""
329
Colin Crossd11cf622021-03-23 22:30:35 -0700330 addLocationLabel := func(label string, loc location) {
Colin Cross08f15ab2018-10-04 23:29:14 -0700331 if firstLabel == "" {
332 firstLabel = label
333 }
334 if _, exists := locationLabels[label]; !exists {
Colin Crossd11cf622021-03-23 22:30:35 -0700335 locationLabels[label] = loc
Colin Cross08f15ab2018-10-04 23:29:14 -0700336 } else {
Anton Hansson7cd41e52021-10-08 16:13:10 +0100337 ctx.ModuleErrorf("multiple locations for label %q: %q and %q (do you have duplicate srcs entries?)",
Colin Crossd11cf622021-03-23 22:30:35 -0700338 label, locationLabels[label], loc)
Colin Cross08f15ab2018-10-04 23:29:14 -0700339 }
340 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700341
Colin Crossba9e4032020-11-24 16:32:22 -0800342 var tools android.Paths
343 var packagedTools []android.PackagingSpec
Colin Cross6f080df2016-11-04 15:32:58 -0700344 if len(g.properties.Tools) > 0 {
Colin Crossba71a3f2019-03-18 12:12:48 -0700345 seenTools := make(map[string]bool)
Yu Liud2a95952024-10-10 00:15:26 +0000346 ctx.VisitDirectDepsProxyAllowDisabled(func(proxy android.ModuleProxy) {
347 switch tag := ctx.OtherModuleDependencyTag(proxy).(type) {
Colin Cross08f15ab2018-10-04 23:29:14 -0700348 case hostToolDependencyTag:
Colin Cross648daea2024-09-12 14:35:29 -0700349 // Necessary to retrieve any prebuilt replacement for the tool, since
350 // toolDepsMutator runs too late for the prebuilt mutators to have
351 // replaced the dependency.
Yu Liud2a95952024-10-10 00:15:26 +0000352 module := android.PrebuiltGetPreferred(ctx, proxy)
353 tool := ctx.OtherModuleName(module)
354 if h, ok := android.OtherModuleProvider(ctx, module, android.HostToolProviderKey); ok {
Colin Crossba9e4032020-11-24 16:32:22 -0800355 // A HostToolProvider provides the path to a tool, which will be copied
356 // into the sandbox.
Yu Liub5275322024-11-13 18:40:43 +0000357 if !android.OtherModuleProviderOrDefault(ctx, module, android.CommonModuleInfoKey).Enabled {
Colin Cross6510f912017-11-29 00:27:14 -0800358 if ctx.Config().AllowMissingDependencies() {
Colin Cross35143d02017-11-16 00:11:20 -0800359 ctx.AddMissingDependencies([]string{tool})
360 } else {
361 ctx.ModuleErrorf("depends on disabled module %q", tool)
362 }
Colin Crossba9e4032020-11-24 16:32:22 -0800363 return
Colin Cross35143d02017-11-16 00:11:20 -0800364 }
Yu Liud2a95952024-10-10 00:15:26 +0000365 path := h.HostToolPath
Colin Crossba9e4032020-11-24 16:32:22 -0800366 if !path.Valid() {
367 ctx.ModuleErrorf("host tool %q missing output file", tool)
368 return
369 }
Yu Liubad1eef2024-08-21 22:37:35 +0000370 if specs := android.OtherModuleProviderOrDefault(
Yu Liud2a95952024-10-10 00:15:26 +0000371 ctx, module, android.InstallFilesProvider).TransitivePackagingSpecs.ToList(); specs != nil {
Colin Crossba9e4032020-11-24 16:32:22 -0800372 // If the HostToolProvider has PackgingSpecs, which are definitions of the
373 // required relative locations of the tool and its dependencies, use those
374 // instead. They will be copied to those relative locations in the sbox
375 // sandbox.
Jiyong Park8fb0e972024-03-18 18:29:37 +0900376 // Care must be taken since TransitivePackagingSpec may return device-side
377 // paths via the required property. Filter them out.
378 for i, ps := range specs {
379 if ps.Partition() != "" {
380 if i == 0 {
381 panic("first PackagingSpec is assumed to be the host-side tool")
382 }
383 continue
384 }
385 packagedTools = append(packagedTools, ps)
386 }
Colin Crossba9e4032020-11-24 16:32:22 -0800387 // Assume that the first PackagingSpec of the module is the tool.
Colin Crossd11cf622021-03-23 22:30:35 -0700388 addLocationLabel(tag.label, packagedToolLocation{specs[0]})
Colin Crossba9e4032020-11-24 16:32:22 -0800389 } else {
390 tools = append(tools, path.Path())
Colin Crossd11cf622021-03-23 22:30:35 -0700391 addLocationLabel(tag.label, toolLocation{android.Paths{path.Path()}})
Colin Crossba9e4032020-11-24 16:32:22 -0800392 }
Yu Liud2a95952024-10-10 00:15:26 +0000393 } else {
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700394 ctx.ModuleErrorf("%q is not a host tool provider", tool)
Colin Crossba9e4032020-11-24 16:32:22 -0800395 return
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700396 }
397
Colin Crossba9e4032020-11-24 16:32:22 -0800398 seenTools[tag.label] = true
Colin Crossd350ecd2015-04-28 13:25:36 -0700399 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700400 })
Colin Crossba71a3f2019-03-18 12:12:48 -0700401
402 // If AllowMissingDependencies is enabled, the build will not have stopped when
403 // AddFarVariationDependencies was called on a missing tool, which will result in nonsensical
Liz Kammer20ebfb42020-07-28 11:32:07 -0700404 // "cmd: unknown location label ..." errors later. Add a placeholder file to the local label.
405 // The command that uses this placeholder file will never be executed because the rule will be
406 // replaced with an android.Error rule reporting the missing dependencies.
Colin Crossba71a3f2019-03-18 12:12:48 -0700407 if ctx.Config().AllowMissingDependencies() {
408 for _, tool := range g.properties.Tools {
409 if !seenTools[tool] {
Colin Crossd11cf622021-03-23 22:30:35 -0700410 addLocationLabel(tool, errorLocation{"***missing tool " + tool + "***"})
Colin Crossba71a3f2019-03-18 12:12:48 -0700411 }
412 }
413 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700414 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700415
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700416 if ctx.Failed() {
417 return
418 }
419
Colin Cross08f15ab2018-10-04 23:29:14 -0700420 for _, toolFile := range g.properties.Tool_files {
Colin Cross8a497952019-03-05 22:25:09 -0800421 paths := android.PathsForModuleSrc(ctx, []string{toolFile})
Colin Crossba9e4032020-11-24 16:32:22 -0800422 tools = append(tools, paths...)
Colin Crossd11cf622021-03-23 22:30:35 -0700423 addLocationLabel(toolFile, toolLocation{paths})
Colin Cross08f15ab2018-10-04 23:29:14 -0700424 }
425
Liz Kammer81fec182023-06-09 13:33:45 -0400426 addLabelsForInputs := func(propName string, include, exclude []string) android.Paths {
Liz Kammer81fec182023-06-09 13:33:45 -0400427 includeDirInPaths := ctx.DeviceConfig().BuildBrokenInputDir(g.Name())
428 var srcFiles android.Paths
429 for _, in := range include {
430 paths, missingDeps := android.PathsAndMissingDepsRelativeToModuleSourceDir(android.SourceInput{
431 Context: ctx, Paths: []string{in}, ExcludePaths: exclude, IncludeDirs: includeDirInPaths,
432 })
433 if len(missingDeps) > 0 {
434 if !ctx.Config().AllowMissingDependencies() {
435 panic(fmt.Errorf("should never get here, the missing dependencies %q should have been reported in DepsMutator",
436 missingDeps))
437 }
438
439 // If AllowMissingDependencies is enabled, the build will not have stopped when
440 // the dependency was added on a missing SourceFileProducer module, which will result in nonsensical
441 // "cmd: label ":..." has no files" errors later. Add a placeholder file to the local label.
442 // The command that uses this placeholder file will never be executed because the rule will be
443 // replaced with an android.Error rule reporting the missing dependencies.
444 ctx.AddMissingDependencies(missingDeps)
445 addLocationLabel(in, errorLocation{"***missing " + propName + " " + in + "***"})
446 } else {
447 srcFiles = append(srcFiles, paths...)
448 addLocationLabel(in, inputLocation{paths})
449 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700450 }
Liz Kammer81fec182023-06-09 13:33:45 -0400451 return srcFiles
Colin Cross08f15ab2018-10-04 23:29:14 -0700452 }
Cole Faustf966e382024-10-08 16:17:56 -0700453 srcs := g.properties.Srcs.GetOrDefault(ctx, nil)
454 srcFiles := addLabelsForInputs("srcs", srcs, g.properties.Exclude_srcs)
Cole Faust65cb40a2024-10-21 15:41:42 -0700455 srcFiles = append(srcFiles, addLabelsForInputs("device_first_srcs", g.properties.Device_first_srcs.GetOrDefault(ctx, nil), nil)...)
456 srcFiles = append(srcFiles, addLabelsForInputs("device_common_srcs", g.properties.Device_common_srcs.GetOrDefault(ctx, nil), nil)...)
457 srcFiles = append(srcFiles, addLabelsForInputs("common_os_srcs", g.properties.Common_os_srcs.GetOrDefault(ctx, nil), nil)...)
Colin Cross40213022023-12-13 15:19:49 -0800458 android.SetProvider(ctx, blueprint.SrcsFileProviderKey, blueprint.SrcsFileProviderData{SrcPaths: srcFiles.Strings()})
Colin Cross08f15ab2018-10-04 23:29:14 -0700459
Colin Cross1a527682019-09-23 15:55:30 -0700460 var copyFrom android.Paths
461 var outputFiles android.WritablePaths
462 var zipArgs strings.Builder
Colin Cross08f15ab2018-10-04 23:29:14 -0700463
Aleks Todorov1eb06c42024-06-03 15:23:56 +0100464 cmd := g.properties.Cmd.GetOrDefault(ctx, "")
Colin Crossf3bfd022021-09-27 15:15:06 -0700465 if g.CmdModifier != nil {
466 cmd = g.CmdModifier(ctx, cmd)
467 }
468
Liz Kammer796921d2023-07-11 08:21:41 -0400469 var extraInputs android.Paths
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500470 // Generate tasks, either from genrule or gensrcs.
Liz Kammer81fec182023-06-09 13:33:45 -0400471 for i, task := range g.taskGenerator(ctx, cmd, srcFiles) {
Colin Cross3d680512020-11-13 16:23:53 -0800472 if len(task.out) == 0 {
473 ctx.ModuleErrorf("must have at least one output file")
474 return
Colin Cross85a2e892018-07-09 09:45:06 -0700475 }
476
Liz Kammer81fec182023-06-09 13:33:45 -0400477 // Only handle extra inputs once as these currently are the same across all tasks
478 if i == 0 {
479 for name, values := range task.extraInputs {
480 extraInputs = append(extraInputs, addLabelsForInputs(name, values, []string{})...)
481 }
482 }
483
Colin Crossf1a035e2020-11-16 17:32:30 -0800484 // Pick a unique path outside the task.genDir for the sbox manifest textproto,
485 // a unique rule name, and the user-visible description.
Inseob Kimf7cd03e2024-09-06 17:25:00 +0900486 var rule *android.RuleBuilder
Colin Crossf1a035e2020-11-16 17:32:30 -0800487 desc := "generate"
488 name := "generator"
Inseob Kimf7cd03e2024-09-06 17:25:00 +0900489 if task.useNsjail {
490 rule = android.NewRuleBuilder(pctx, ctx).Nsjail(task.genDir, android.PathForModuleOut(ctx, "nsjail_build_sandbox"))
Inseob Kim7195b062024-11-29 15:40:49 +0900491 if task.keepGendir {
492 rule.NsjailKeepGendir()
493 }
Inseob Kimf7cd03e2024-09-06 17:25:00 +0900494 } else {
495 manifestName := "genrule.sbox.textproto"
496 if task.shards > 0 {
497 manifestName = "genrule_" + strconv.Itoa(task.shard) + ".sbox.textproto"
498 desc += " " + strconv.Itoa(task.shard)
499 name += strconv.Itoa(task.shard)
500 } else if len(task.out) == 1 {
501 desc += " " + task.out[0].Base()
502 }
503
504 manifestPath := android.PathForModuleOut(ctx, manifestName)
505
506 // Use a RuleBuilder to create a rule that runs the command inside an sbox sandbox.
507 rule = getSandboxedRuleBuilder(ctx, android.NewRuleBuilder(pctx, ctx).Sbox(task.genDir, manifestPath))
Colin Crossf1a035e2020-11-16 17:32:30 -0800508 }
Justin Yun4da4ccc2023-07-06 10:56:29 +0900509 if Bool(g.properties.Write_if_changed) {
510 rule.Restat()
511 }
Colin Crossf1a035e2020-11-16 17:32:30 -0800512 cmd := rule.Command()
513
Colin Cross3d680512020-11-13 16:23:53 -0800514 for _, out := range task.out {
Colin Crossd11cf622021-03-23 22:30:35 -0700515 addLocationLabel(out.Rel(), outputLocation{out})
Colin Cross3d680512020-11-13 16:23:53 -0800516 }
517
Colin Cross3d680512020-11-13 16:23:53 -0800518 rawCommand, err := android.Expand(task.cmd, func(name string) (string, error) {
Colin Cross1a527682019-09-23 15:55:30 -0700519 // report the error directly without returning an error to android.Expand to catch multiple errors in a
520 // single run
Colin Cross3d680512020-11-13 16:23:53 -0800521 reportError := func(fmt string, args ...interface{}) (string, error) {
Colin Cross1a527682019-09-23 15:55:30 -0700522 ctx.PropertyErrorf("cmd", fmt, args...)
Colin Cross3d680512020-11-13 16:23:53 -0800523 return "SOONG_ERROR", nil
Colin Cross6f080df2016-11-04 15:32:58 -0700524 }
Colin Cross1a527682019-09-23 15:55:30 -0700525
Jihoon Kangc170af42022-08-20 05:26:38 +0000526 // Apply shell escape to each cases to prevent source file paths containing $ from being evaluated in shell
Colin Cross1a527682019-09-23 15:55:30 -0700527 switch name {
528 case "location":
529 if len(g.properties.Tools) == 0 && len(g.properties.Tool_files) == 0 {
530 return reportError("at least one `tools` or `tool_files` is required if $(location) is used")
Colin Cross6f080df2016-11-04 15:32:58 -0700531 }
Colin Crossd11cf622021-03-23 22:30:35 -0700532 loc := locationLabels[firstLabel]
533 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700534 if len(paths) == 0 {
535 return reportError("default label %q has no files", firstLabel)
536 } else if len(paths) > 1 {
537 return reportError("default label %q has multiple files, use $(locations %s) to reference it",
538 firstLabel, firstLabel)
Colin Cross08f15ab2018-10-04 23:29:14 -0700539 }
Jihoon Kangc170af42022-08-20 05:26:38 +0000540 return proptools.ShellEscape(paths[0]), nil
Colin Cross1a527682019-09-23 15:55:30 -0700541 case "in":
Jihoon Kangc170af42022-08-20 05:26:38 +0000542 return strings.Join(proptools.ShellEscapeList(cmd.PathsForInputs(srcFiles)), " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700543 case "out":
Colin Cross3d680512020-11-13 16:23:53 -0800544 var sandboxOuts []string
545 for _, out := range task.out {
Colin Crossf1a035e2020-11-16 17:32:30 -0800546 sandboxOuts = append(sandboxOuts, cmd.PathForOutput(out))
Colin Cross3d680512020-11-13 16:23:53 -0800547 }
Jihoon Kangc170af42022-08-20 05:26:38 +0000548 return strings.Join(proptools.ShellEscapeList(sandboxOuts), " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700549 case "genDir":
Jihoon Kangc170af42022-08-20 05:26:38 +0000550 return proptools.ShellEscape(cmd.PathForOutput(task.genDir)), nil
Cole Faust78f3c3a2024-08-15 17:19:34 -0700551 case "build_number_file":
552 if !proptools.Bool(g.properties.Uses_order_only_build_number_file) {
553 return reportError("to use the $(build_number_file) label, you must set uses_order_only_build_number_file: true")
554 }
555 return proptools.ShellEscape(cmd.PathForInput(ctx.Config().BuildNumberFile(ctx))), nil
Colin Cross1a527682019-09-23 15:55:30 -0700556 default:
557 if strings.HasPrefix(name, "location ") {
558 label := strings.TrimSpace(strings.TrimPrefix(name, "location "))
Colin Crossd11cf622021-03-23 22:30:35 -0700559 if loc, ok := locationLabels[label]; ok {
560 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700561 if len(paths) == 0 {
562 return reportError("label %q has no files", label)
563 } else if len(paths) > 1 {
564 return reportError("label %q has multiple files, use $(locations %s) to reference it",
565 label, label)
566 }
Jihoon Kangc170af42022-08-20 05:26:38 +0000567 return proptools.ShellEscape(paths[0]), nil
Colin Cross1a527682019-09-23 15:55:30 -0700568 } else {
Anton Hanssonbebf5262022-02-23 11:42:38 +0000569 return reportError("unknown location label %q is not in srcs, out, tools or tool_files.", label)
Colin Cross1a527682019-09-23 15:55:30 -0700570 }
571 } else if strings.HasPrefix(name, "locations ") {
572 label := strings.TrimSpace(strings.TrimPrefix(name, "locations "))
Colin Crossd11cf622021-03-23 22:30:35 -0700573 if loc, ok := locationLabels[label]; ok {
574 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700575 if len(paths) == 0 {
576 return reportError("label %q has no files", label)
577 }
Cole Faustce74a592023-12-07 14:58:45 -0800578 return strings.Join(proptools.ShellEscapeList(paths), " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700579 } else {
Anton Hanssonbebf5262022-02-23 11:42:38 +0000580 return reportError("unknown locations label %q is not in srcs, out, tools or tool_files.", label)
Colin Cross1a527682019-09-23 15:55:30 -0700581 }
582 } else {
583 return reportError("unknown variable '$(%s)'", name)
584 }
Colin Cross6f080df2016-11-04 15:32:58 -0700585 }
Colin Cross1a527682019-09-23 15:55:30 -0700586 })
587
588 if err != nil {
589 ctx.PropertyErrorf("cmd", "%s", err.Error())
590 return
Colin Cross6f080df2016-11-04 15:32:58 -0700591 }
Colin Cross6f080df2016-11-04 15:32:58 -0700592
Colin Cross1a527682019-09-23 15:55:30 -0700593 g.rawCommands = append(g.rawCommands, rawCommand)
Bill Peckhamc087be12020-02-13 15:55:10 -0800594
Colin Cross3d680512020-11-13 16:23:53 -0800595 cmd.Text(rawCommand)
Liz Kammer81fec182023-06-09 13:33:45 -0400596 cmd.Implicits(srcFiles) // need to be able to reference other srcs
597 cmd.Implicits(extraInputs)
Colin Cross3d680512020-11-13 16:23:53 -0800598 cmd.ImplicitOutputs(task.out)
599 cmd.Implicits(task.in)
Colin Crossba9e4032020-11-24 16:32:22 -0800600 cmd.ImplicitTools(tools)
Colin Crossba9e4032020-11-24 16:32:22 -0800601 cmd.ImplicitPackagedTools(packagedTools)
Cole Faust78f3c3a2024-08-15 17:19:34 -0700602 if proptools.Bool(g.properties.Uses_order_only_build_number_file) {
Cole Faustf23fdc02024-08-23 15:21:13 -0700603 if !isModuleInBuildNumberAllowlist(ctx) {
Cole Faust78f3c3a2024-08-15 17:19:34 -0700604 ctx.ModuleErrorf("Only allowlisted modules may use uses_order_only_build_number_file: true")
605 }
606 cmd.OrderOnly(ctx.Config().BuildNumberFile(ctx))
607 }
Colin Cross3d680512020-11-13 16:23:53 -0800608
Inseob Kimf7cd03e2024-09-06 17:25:00 +0900609 if task.useNsjail {
Inseob Kim76e19852024-10-10 17:57:22 +0900610 for _, input := range task.dirSrcs {
Inseob Kim93036a52024-10-25 17:02:21 +0900611 cmd.ImplicitDirectory(input)
612 // TODO(b/375551969): remove glob
Inseob Kimf7cd03e2024-09-06 17:25:00 +0900613 if paths, err := ctx.GlobWithDeps(filepath.Join(input.String(), "**/*"), nil); err == nil {
614 rule.NsjailImplicits(android.PathsForSource(ctx, paths))
Inseob Kim76e19852024-10-10 17:57:22 +0900615 } else {
616 ctx.PropertyErrorf("dir_srcs", "can't glob %q", input.String())
Inseob Kimf7cd03e2024-09-06 17:25:00 +0900617 }
618 }
619 }
620
Colin Cross3d680512020-11-13 16:23:53 -0800621 // Create the rule to run the genrule command inside sbox.
Colin Crossf1a035e2020-11-16 17:32:30 -0800622 rule.Build(name, desc)
Colin Cross1a527682019-09-23 15:55:30 -0700623
624 if len(task.copyTo) > 0 {
Colin Cross3d680512020-11-13 16:23:53 -0800625 // If copyTo is set, multiple shards need to be copied into a single directory.
626 // task.out contains the per-shard paths, and copyTo contains the corresponding
627 // final path. The files need to be copied into the final directory by a
628 // single rule so it can remove the directory before it starts to ensure no
629 // old files remain. zipsync already does this, so build up zipArgs that
630 // zip all the per-shard directories into a single zip.
Colin Cross1a527682019-09-23 15:55:30 -0700631 outputFiles = append(outputFiles, task.copyTo...)
632 copyFrom = append(copyFrom, task.out.Paths()...)
633 zipArgs.WriteString(" -C " + task.genDir.String())
634 zipArgs.WriteString(android.JoinWithPrefix(task.out.Strings(), " -f "))
635 } else {
636 outputFiles = append(outputFiles, task.out...)
637 }
Colin Cross6f080df2016-11-04 15:32:58 -0700638 }
639
Colin Cross1a527682019-09-23 15:55:30 -0700640 if len(copyFrom) > 0 {
Colin Cross3d680512020-11-13 16:23:53 -0800641 // Create a rule that zips all the per-shard directories into a single zip and then
642 // uses zipsync to unzip it into the final directory.
Colin Cross1a527682019-09-23 15:55:30 -0700643 ctx.Build(pctx, android.BuildParams{
Colin Crossf1885962020-11-20 15:28:30 -0800644 Rule: gensrcsMerge,
645 Implicits: copyFrom,
646 Outputs: outputFiles,
647 Description: "merge shards",
Colin Cross1a527682019-09-23 15:55:30 -0700648 Args: map[string]string{
649 "zipArgs": zipArgs.String(),
650 "tmpZip": android.PathForModuleGen(ctx, g.subDir+".zip").String(),
651 "genDir": android.PathForModuleGen(ctx, g.subDir).String(),
652 },
653 })
Colin Cross85a2e892018-07-09 09:45:06 -0700654 }
655
Colin Cross1a527682019-09-23 15:55:30 -0700656 g.outputFiles = outputFiles.Paths()
Chris Parsonsf874e462022-05-10 13:50:12 -0400657}
Jeff Gastonefc1b412017-03-29 17:29:06 -0700658
Chris Parsonsf874e462022-05-10 13:50:12 -0400659func (g *Module) GenerateAndroidBuildActions(ctx android.ModuleContext) {
660 g.generateCommonBuildActions(ctx)
661
662 // For <= 6 outputs, just embed those directly in the users. Right now, that covers >90% of
663 // the genrules on AOSP. That will make things simpler to look at the graph in the common
664 // case. For larger sets of outputs, inject a phony target in between to limit ninja file
665 // growth.
666 if len(g.outputFiles) <= 6 {
667 g.outputDeps = g.outputFiles
668 } else {
669 phonyFile := android.PathForModuleGen(ctx, "genrule-phony")
670 ctx.Build(pctx, android.BuildParams{
671 Rule: blueprint.Phony,
672 Output: phonyFile,
673 Inputs: g.outputFiles,
674 })
675 g.outputDeps = android.Paths{phonyFile}
Jeff Gaston02a684b2017-10-27 14:59:27 -0700676 }
mrziwang4514ef22024-06-07 13:31:48 -0700677
678 g.setOutputFiles(ctx)
Cole Faust481b6692024-10-11 16:25:07 -0700679
680 if ctx.Os() == android.Windows {
681 // Make doesn't support windows:
682 // https://cs.android.com/android/platform/superproject/main/+/main:build/make/core/module_arch_supported.mk;l=66;drc=f264690860bb6ee7762784d6b7201aae057ba6f2
683 g.HideFromMake()
684 }
mrziwang4514ef22024-06-07 13:31:48 -0700685}
686
687func (g *Module) setOutputFiles(ctx android.ModuleContext) {
688 if len(g.outputFiles) == 0 {
689 return
690 }
691 ctx.SetOutputFiles(g.outputFiles, "")
692 // non-empty-string-tag should match one of the outputs
693 for _, files := range g.outputFiles {
694 ctx.SetOutputFiles(android.Paths{files}, files.Rel())
695 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400696}
697
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700698// Collect information for opening IDE project files in java/jdeps.go.
Cole Faustb36d31d2024-08-27 16:04:28 -0700699func (g *Module) IDEInfo(ctx android.BaseModuleContext, dpInfo *android.IdeInfo) {
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700700 dpInfo.Srcs = append(dpInfo.Srcs, g.Srcs().Strings()...)
Cole Faustf966e382024-10-08 16:17:56 -0700701 for _, src := range g.properties.Srcs.GetOrDefault(ctx, nil) {
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700702 if strings.HasPrefix(src, ":") {
703 src = strings.Trim(src, ":")
704 dpInfo.Deps = append(dpInfo.Deps, src)
705 }
706 }
707}
708
Colin Crossa4ad2b02019-03-18 22:15:32 -0700709func (g *Module) AndroidMk() android.AndroidMkData {
710 return android.AndroidMkData{
Anton Hansson72f18492020-10-30 16:34:45 +0000711 Class: "ETC",
Colin Crossa4ad2b02019-03-18 22:15:32 -0700712 OutputFile: android.OptionalPathForPath(g.outputFiles[0]),
713 SubName: g.subName,
714 Extra: []android.AndroidMkExtraFunc{
715 func(w io.Writer, outputFile android.Path) {
Anton Hansson72f18492020-10-30 16:34:45 +0000716 fmt.Fprintln(w, "LOCAL_UNINSTALLABLE_MODULE := true")
Colin Crossa4ad2b02019-03-18 22:15:32 -0700717 },
718 },
719 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
720 android.WriteAndroidMkData(w, data)
721 if data.SubName != "" {
722 fmt.Fprintln(w, ".PHONY:", name)
723 fmt.Fprintln(w, name, ":", name+g.subName)
724 }
725 },
726 }
727}
728
Jiyong Park45bf82e2020-12-15 22:29:02 +0900729var _ android.ApexModule = (*Module)(nil)
730
731// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -0700732func (g *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
733 sdkVersion android.ApiLevel) error {
Jooyung Han749dc692020-04-15 11:03:39 +0900734 // Because generated outputs are checked by client modules(e.g. cc_library, ...)
735 // we can safely ignore the check here.
736 return nil
737}
738
Jeff Gaston437d23c2017-11-08 12:38:00 -0800739func generatorFactory(taskGenerator taskFunc, props ...interface{}) *Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700740 module := &Module{
Jeff Gaston437d23c2017-11-08 12:38:00 -0800741 taskGenerator: taskGenerator,
Colin Crossd350ecd2015-04-28 13:25:36 -0700742 }
743
Colin Cross36242852017-06-23 15:06:31 -0700744 module.AddProperties(props...)
745 module.AddProperties(&module.properties)
Colin Crossd350ecd2015-04-28 13:25:36 -0700746
Colin Cross7228ecd2019-11-18 16:00:16 -0800747 module.ImageInterface = noopImageInterface{}
748
Colin Cross36242852017-06-23 15:06:31 -0700749 return module
Colin Crossd350ecd2015-04-28 13:25:36 -0700750}
751
Colin Cross7228ecd2019-11-18 16:00:16 -0800752type noopImageInterface struct{}
753
Cole Faustfa6e0fd2024-10-15 15:22:57 -0700754func (x noopImageInterface) ImageMutatorBegin(android.ImageInterfaceContext) {}
755func (x noopImageInterface) VendorVariantNeeded(android.ImageInterfaceContext) bool { return false }
756func (x noopImageInterface) ProductVariantNeeded(android.ImageInterfaceContext) bool { return false }
757func (x noopImageInterface) CoreVariantNeeded(android.ImageInterfaceContext) bool { return false }
758func (x noopImageInterface) RamdiskVariantNeeded(android.ImageInterfaceContext) bool { return false }
759func (x noopImageInterface) VendorRamdiskVariantNeeded(android.ImageInterfaceContext) bool {
760 return false
761}
762func (x noopImageInterface) DebugRamdiskVariantNeeded(android.ImageInterfaceContext) bool {
763 return false
764}
765func (x noopImageInterface) RecoveryVariantNeeded(android.ImageInterfaceContext) bool { return false }
766func (x noopImageInterface) ExtraImageVariations(ctx android.ImageInterfaceContext) []string {
767 return nil
768}
769func (x noopImageInterface) SetImageVariation(ctx android.ImageInterfaceContext, variation string) {
Colin Cross7228ecd2019-11-18 16:00:16 -0800770}
771
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700772func NewGenSrcs() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700773 properties := &genSrcsProperties{}
774
Colin Crossf1885962020-11-20 15:28:30 -0800775 // finalSubDir is the name of the subdirectory that output files will be generated into.
776 // It is used so that per-shard directories can be placed alongside it an then finally
777 // merged into it.
778 const finalSubDir = "gensrcs"
779
Colin Cross1a527682019-09-23 15:55:30 -0700780 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Colin Cross1a527682019-09-23 15:55:30 -0700781 shardSize := defaultShardSize
782 if s := properties.Shard_size; s != nil {
783 shardSize = int(*s)
784 }
Jeff Gaston437d23c2017-11-08 12:38:00 -0800785
Colin Crossf1885962020-11-20 15:28:30 -0800786 // gensrcs rules can easily hit command line limits by repeating the command for
787 // every input file. Shard the input files into groups.
Colin Cross1a527682019-09-23 15:55:30 -0700788 shards := android.ShardPaths(srcFiles, shardSize)
789 var generateTasks []generateTask
Colin Crossbaccf5b2018-02-21 14:07:48 -0800790
Colin Cross1a527682019-09-23 15:55:30 -0700791 for i, shard := range shards {
792 var commands []string
793 var outFiles android.WritablePaths
794 var copyTo android.WritablePaths
Colin Cross1a527682019-09-23 15:55:30 -0700795
Colin Crossf1885962020-11-20 15:28:30 -0800796 // When sharding is enabled (i.e. len(shards) > 1), the sbox rules for each
797 // shard will be write to their own directories and then be merged together
798 // into finalSubDir. If sharding is not enabled (i.e. len(shards) == 1),
799 // the sbox rule will write directly to finalSubDir.
800 genSubDir := finalSubDir
Colin Cross1a527682019-09-23 15:55:30 -0700801 if len(shards) > 1 {
Colin Crossf1885962020-11-20 15:28:30 -0800802 genSubDir = strconv.Itoa(i)
Jeff Gaston437d23c2017-11-08 12:38:00 -0800803 }
804
Colin Crossf1885962020-11-20 15:28:30 -0800805 genDir := android.PathForModuleGen(ctx, genSubDir)
Colin Crossf1a035e2020-11-16 17:32:30 -0800806 // TODO(ccross): this RuleBuilder is a hack to be able to call
807 // rule.Command().PathForOutput. Replace this with passing the rule into the
808 // generator.
Yu Liu6a7940c2023-05-09 17:12:22 -0700809 rule := getSandboxedRuleBuilder(ctx, android.NewRuleBuilder(pctx, ctx).Sbox(genDir, nil))
Jeff Gaston437d23c2017-11-08 12:38:00 -0800810
Colin Cross3ea4eb82020-11-24 13:07:27 -0800811 for _, in := range shard {
yangbill6d032dd2024-04-18 03:05:49 +0000812 outFile := android.GenPathWithExtAndTrimExt(ctx, finalSubDir, in, String(properties.Output_extension), String(properties.Trim_extension))
Colin Crossf1885962020-11-20 15:28:30 -0800813
814 // If sharding is enabled, then outFile is the path to the output file in
815 // the shard directory, and copyTo is the path to the output file in the
816 // final directory.
Colin Cross1a527682019-09-23 15:55:30 -0700817 if len(shards) > 1 {
yangbill6d032dd2024-04-18 03:05:49 +0000818 shardFile := android.GenPathWithExtAndTrimExt(ctx, genSubDir, in, String(properties.Output_extension), String(properties.Trim_extension))
Colin Cross1a527682019-09-23 15:55:30 -0700819 copyTo = append(copyTo, outFile)
820 outFile = shardFile
821 }
822
823 outFiles = append(outFiles, outFile)
Colin Cross1a527682019-09-23 15:55:30 -0700824
Colin Crossf1885962020-11-20 15:28:30 -0800825 // pre-expand the command line to replace $in and $out with references to
826 // a single input and output file.
Colin Cross1a527682019-09-23 15:55:30 -0700827 command, err := android.Expand(rawCommand, func(name string) (string, error) {
828 switch name {
829 case "in":
830 return in.String(), nil
831 case "out":
Colin Crossf1a035e2020-11-16 17:32:30 -0800832 return rule.Command().PathForOutput(outFile), nil
Colin Cross1a527682019-09-23 15:55:30 -0700833 default:
834 return "$(" + name + ")", nil
835 }
836 })
837 if err != nil {
838 ctx.PropertyErrorf("cmd", err.Error())
839 }
840
841 // escape the command in case for example it contains '#', an odd number of '"', etc
842 command = fmt.Sprintf("bash -c %v", proptools.ShellEscape(command))
843 commands = append(commands, command)
844 }
845 fullCommand := strings.Join(commands, " && ")
846
847 generateTasks = append(generateTasks, generateTask{
Cole Faust55492572024-01-25 18:00:33 -0800848 in: shard,
849 out: outFiles,
850 copyTo: copyTo,
851 genDir: genDir,
852 cmd: fullCommand,
853 shard: i,
854 shards: len(shards),
Liz Kammer81fec182023-06-09 13:33:45 -0400855 extraInputs: map[string][]string{
856 "data": properties.Data,
857 },
Colin Cross1a527682019-09-23 15:55:30 -0700858 })
Jeff Gaston437d23c2017-11-08 12:38:00 -0800859 }
Colin Cross1a527682019-09-23 15:55:30 -0700860
861 return generateTasks
Colin Crossd350ecd2015-04-28 13:25:36 -0700862 }
863
Colin Cross1a527682019-09-23 15:55:30 -0700864 g := generatorFactory(taskGenerator, properties)
Colin Crossf1885962020-11-20 15:28:30 -0800865 g.subDir = finalSubDir
Colin Cross1a527682019-09-23 15:55:30 -0700866 return g
Colin Crossd350ecd2015-04-28 13:25:36 -0700867}
868
Colin Cross54190b32017-10-09 15:34:10 -0700869func GenSrcsFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700870 m := NewGenSrcs()
871 android.InitAndroidModule(m)
Colin Cross483b4c42024-05-09 13:08:02 -0700872 android.InitDefaultableModule(m)
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700873 return m
874}
875
Colin Crossd350ecd2015-04-28 13:25:36 -0700876type genSrcsProperties struct {
Colin Cross7d5136f2015-05-11 13:39:40 -0700877 // extension that will be substituted for each output file
Nan Zhanga5e7cb42017-11-09 22:42:32 -0800878 Output_extension *string
Colin Cross1a527682019-09-23 15:55:30 -0700879
880 // maximum number of files that will be passed on a single command line.
881 Shard_size *int64
Liz Kammer81fec182023-06-09 13:33:45 -0400882
883 // Additional files needed for build that are not tooling related.
884 Data []string `android:"path"`
yangbill6d032dd2024-04-18 03:05:49 +0000885
886 // Trim the matched extension for each input file, and it should start with ".".
887 Trim_extension *string
Colin Cross5049f022015-03-18 13:28:46 -0700888}
889
Evgenii Stepanovf47c90d2020-12-02 18:55:09 -0800890const defaultShardSize = 50
Colin Cross1a527682019-09-23 15:55:30 -0700891
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700892func NewGenRule() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700893 properties := &genRuleProperties{}
Colin Cross5049f022015-03-18 13:28:46 -0700894
Colin Cross1a527682019-09-23 15:55:30 -0700895 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Inseob Kimf7cd03e2024-09-06 17:25:00 +0900896 useNsjail := Bool(properties.Use_nsjail)
897
Inseob Kim76e19852024-10-10 17:57:22 +0900898 dirSrcs := android.DirectoryPathsForModuleSrc(ctx, properties.Dir_srcs)
899 if len(dirSrcs) > 0 && !useNsjail {
900 ctx.PropertyErrorf("dir_srcs", "can't use dir_srcs if use_nsjail is false")
901 return nil
902 }
903
Inseob Kim7195b062024-11-29 15:40:49 +0900904 keepGendir := Bool(properties.Keep_gendir)
905 if keepGendir && !useNsjail {
906 ctx.PropertyErrorf("keep_gendir", "can't use keep_gendir if use_nsjail is false")
907 return nil
908 }
909
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700910 outs := make(android.WritablePaths, len(properties.Out))
911 for i, out := range properties.Out {
Cole Faust55492572024-01-25 18:00:33 -0800912 outs[i] = android.PathForModuleGen(ctx, out)
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700913 }
Colin Cross1a527682019-09-23 15:55:30 -0700914 return []generateTask{{
Inseob Kim7195b062024-11-29 15:40:49 +0900915 in: srcFiles,
916 out: outs,
917 genDir: android.PathForModuleGen(ctx),
918 cmd: rawCommand,
919 useNsjail: useNsjail,
920 dirSrcs: dirSrcs,
921 keepGendir: keepGendir,
Colin Cross1a527682019-09-23 15:55:30 -0700922 }}
Colin Cross5049f022015-03-18 13:28:46 -0700923 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700924
Jeff Gaston437d23c2017-11-08 12:38:00 -0800925 return generatorFactory(taskGenerator, properties)
Colin Cross5049f022015-03-18 13:28:46 -0700926}
927
Colin Cross54190b32017-10-09 15:34:10 -0700928func GenRuleFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700929 m := NewGenRule()
930 android.InitAndroidModule(m)
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800931 android.InitDefaultableModule(m)
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700932 return m
933}
934
Colin Crossd350ecd2015-04-28 13:25:36 -0700935type genRuleProperties struct {
Inseob Kimf7cd03e2024-09-06 17:25:00 +0900936 Use_nsjail *bool
937
Inseob Kim76e19852024-10-10 17:57:22 +0900938 // List of input directories. Can be set only when use_nsjail is true. Currently, usage of
939 // dir_srcs is limited only to Trusty build.
940 Dir_srcs []string `android:"path"`
941
Inseob Kim7195b062024-11-29 15:40:49 +0900942 // If set to true, $(genDir) is not truncated. Useful when this genrule can be incrementally
943 // built. Can be set only when use_nsjail is true.
944 Keep_gendir *bool
945
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700946 // names of the output files that will be generated
kellyhung750334a2024-03-14 01:03:49 +0800947 Out []string `android:"arch_variant"`
Colin Cross5049f022015-03-18 13:28:46 -0700948}
Nan Zhangea568a42017-11-08 21:20:04 -0800949
950var Bool = proptools.Bool
951var String = proptools.String
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800952
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800953// Defaults
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800954type Defaults struct {
955 android.ModuleBase
956 android.DefaultsModuleBase
957}
958
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800959func defaultsFactory() android.Module {
960 return DefaultsFactory()
961}
962
963func DefaultsFactory(props ...interface{}) android.Module {
964 module := &Defaults{}
965
966 module.AddProperties(props...)
967 module.AddProperties(
968 &generatorProperties{},
969 &genRuleProperties{},
970 )
971
972 android.InitDefaultsModule(module)
973
974 return module
975}
Yu Liu6a7940c2023-05-09 17:12:22 -0700976
Yu Liue7f7cbf2023-06-13 18:50:03 +0000977var sandboxingAllowlistKey = android.NewOnceKey("genruleSandboxingAllowlistKey")
978
979type sandboxingAllowlistSets struct {
980 sandboxingDenyModuleSet map[string]bool
Yu Liue7f7cbf2023-06-13 18:50:03 +0000981}
982
983func getSandboxingAllowlistSets(ctx android.PathContext) *sandboxingAllowlistSets {
984 return ctx.Config().Once(sandboxingAllowlistKey, func() interface{} {
985 sandboxingDenyModuleSet := map[string]bool{}
Yu Liue7f7cbf2023-06-13 18:50:03 +0000986
Cole Faust55492572024-01-25 18:00:33 -0800987 android.AddToStringSet(sandboxingDenyModuleSet, SandboxingDenyModuleList)
Yu Liue7f7cbf2023-06-13 18:50:03 +0000988 return &sandboxingAllowlistSets{
989 sandboxingDenyModuleSet: sandboxingDenyModuleSet,
Yu Liue7f7cbf2023-06-13 18:50:03 +0000990 }
991 }).(*sandboxingAllowlistSets)
992}
Liz Kammer0db0e342023-07-18 11:39:30 -0400993
Yu Liu6a7940c2023-05-09 17:12:22 -0700994func getSandboxedRuleBuilder(ctx android.ModuleContext, r *android.RuleBuilder) *android.RuleBuilder {
Yu Liu45d6af52023-05-24 23:10:18 +0000995 if !ctx.DeviceConfig().GenruleSandboxing() {
996 return r.SandboxTools()
997 }
Yu Liue7f7cbf2023-06-13 18:50:03 +0000998 sandboxingAllowlistSets := getSandboxingAllowlistSets(ctx)
Cole Fauste762b942024-03-15 12:46:14 -0700999 if sandboxingAllowlistSets.sandboxingDenyModuleSet[ctx.ModuleName()] {
Yu Liu6a7940c2023-05-09 17:12:22 -07001000 return r.SandboxTools()
1001 }
1002 return r.SandboxInputs()
1003}