blob: f2a761cde56dedd61f3296f677327e2e702699b0 [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(
118 ctx, target, android.CommonPropertiesProviderKey).ReplacedByPrebuilt
119}
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
150 // input files to exclude
Colin Cross27b922f2019-03-04 22:35:41 -0800151 Exclude_srcs []string `android:"path,arch_variant"`
Justin Yun4da4ccc2023-07-06 10:56:29 +0900152
153 // Enable restat to update the output only if the output is changed
154 Write_if_changed *bool
Cole Faust78f3c3a2024-08-15 17:19:34 -0700155
156 // When set to true, an additional $(build_number_file) label will be available
157 // to use in the cmd. This will be the location of a text file containing the
158 // build number. The dependency on this file will be "order-only", meaning that
159 // the genrule will not rerun when only this file changes, to avoid rerunning
160 // the genrule every build, because the build number changes every build.
161 // This also means that you should not attempt to consume the build number from
162 // the result of this genrule in another build rule. If you do, the build number
163 // in the second build rule will be stale when the second build rule rebuilds
164 // but this genrule does not. Only certain allowlisted modules are allowed to
165 // use this property, usages of the build number should be kept to the absolute
166 // minimum. Particularly no modules on the system image may include the build
167 // number. Prefer using libbuildversion via the use_version_lib property on
168 // cc modules.
169 Uses_order_only_build_number_file *bool
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400170}
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500171
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700172type Module struct {
Colin Cross635c3b02016-05-18 15:37:25 -0700173 android.ModuleBase
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800174 android.DefaultableModuleBase
Jiyong Parkfc752ca2019-06-12 13:27:29 +0900175 android.ApexModuleBase
Colin Crossd350ecd2015-04-28 13:25:36 -0700176
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700177 // For other packages to make their own genrules with extra
178 // properties
179 Extra interface{}
Colin Crossf3bfd022021-09-27 15:15:06 -0700180
181 // CmdModifier can be set by wrappers around genrule to modify the command, for example to
182 // prefix environment variables to it.
183 CmdModifier func(ctx android.ModuleContext, cmd string) string
184
Colin Cross7228ecd2019-11-18 16:00:16 -0800185 android.ImageInterface
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700186
Colin Cross7d5136f2015-05-11 13:39:40 -0700187 properties generatorProperties
Colin Crossd350ecd2015-04-28 13:25:36 -0700188
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500189 // For the different tasks that genrule and gensrc generate. genrule will
190 // generate 1 task, and gensrc will generate 1 or more tasks based on the
191 // number of shards the input files are sharded into.
Jeff Gaston437d23c2017-11-08 12:38:00 -0800192 taskGenerator taskFunc
Colin Crossd350ecd2015-04-28 13:25:36 -0700193
Colin Cross1a527682019-09-23 15:55:30 -0700194 rule blueprint.Rule
195 rawCommands []string
Colin Crossd350ecd2015-04-28 13:25:36 -0700196
Colin Cross5ed99c62016-11-22 12:55:55 -0800197 exportedIncludeDirs android.Paths
Dan Willemsenb40aab62016-04-20 14:21:14 -0700198
Colin Cross635c3b02016-05-18 15:37:25 -0700199 outputFiles android.Paths
Dan Willemsen9da9d492018-02-21 18:28:18 -0800200 outputDeps android.Paths
Colin Crossa4ad2b02019-03-18 22:15:32 -0700201
202 subName string
Colin Cross1a527682019-09-23 15:55:30 -0700203 subDir string
Colin Crossd350ecd2015-04-28 13:25:36 -0700204}
205
Colin Cross1a527682019-09-23 15:55:30 -0700206type taskFunc func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask
Colin Crossd350ecd2015-04-28 13:25:36 -0700207
208type generateTask struct {
Liz Kammer81fec182023-06-09 13:33:45 -0400209 in android.Paths
210 out android.WritablePaths
Liz Kammer81fec182023-06-09 13:33:45 -0400211 copyTo android.WritablePaths // For gensrcs to set on gensrcsMerge rule.
212 genDir android.WritablePath
Liz Kammer81fec182023-06-09 13:33:45 -0400213 extraInputs map[string][]string
Colin Cross3ea4eb82020-11-24 13:07:27 -0800214
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500215 cmd string
216 // For gensrsc sharding.
Colin Cross3ea4eb82020-11-24 13:07:27 -0800217 shard int
218 shards int
Inseob Kimf7cd03e2024-09-06 17:25:00 +0900219
220 // For nsjail tasks
221 useNsjail bool
Inseob Kim76e19852024-10-10 17:57:22 +0900222 dirSrcs android.Paths
Colin Crossd350ecd2015-04-28 13:25:36 -0700223}
224
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700225func (g *Module) GeneratedSourceFiles() android.Paths {
Colin Crossd350ecd2015-04-28 13:25:36 -0700226 return g.outputFiles
227}
228
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700229func (g *Module) Srcs() android.Paths {
Nan Zhange42777a2018-03-27 16:19:42 -0700230 return append(android.Paths{}, g.outputFiles...)
Colin Cross068e0fe2016-12-13 15:23:47 -0800231}
232
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700233func (g *Module) GeneratedHeaderDirs() android.Paths {
Colin Cross5ed99c62016-11-22 12:55:55 -0800234 return g.exportedIncludeDirs
Dan Willemsenb40aab62016-04-20 14:21:14 -0700235}
236
Dan Willemsen9da9d492018-02-21 18:28:18 -0800237func (g *Module) GeneratedDeps() android.Paths {
238 return g.outputDeps
239}
240
Jooyung Han8c7e3ed2021-06-28 17:35:58 +0900241var _ android.SourceFileProducer = (*Module)(nil)
Jooyung Han8c7e3ed2021-06-28 17:35:58 +0900242
Martin Stjernholm710ec3a2020-01-16 15:12:04 +0000243func toolDepsMutator(ctx android.BottomUpMutatorContext) {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700244 if g, ok := ctx.Module().(*Module); ok {
Colin Cross08f15ab2018-10-04 23:29:14 -0700245 for _, tool := range g.properties.Tools {
246 tag := hostToolDependencyTag{label: tool}
247 if m := android.SrcIsModule(tool); m != "" {
248 tool = m
249 }
Colin Cross0f7d2ef2019-10-16 11:03:10 -0700250 ctx.AddFarVariationDependencies(ctx.Config().BuildOSTarget.Variations(), tag, tool)
Colin Cross6362e272015-10-29 15:25:03 -0700251 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700252 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700253}
254
Cole Faustf23fdc02024-08-23 15:21:13 -0700255var buildNumberAllowlistKey = android.NewOnceKey("genruleBuildNumberAllowlistKey")
256
Cole Faust78f3c3a2024-08-15 17:19:34 -0700257// This allowlist should be kept to the bare minimum, it's
258// intended for things that existed before the build number
259// was tightly controlled. Prefer using libbuildversion
260// via the use_version_lib property of cc modules.
Cole Faustf23fdc02024-08-23 15:21:13 -0700261// This is a function instead of a global map so that
262// soong plugins cannot add entries to the allowlist
263func isModuleInBuildNumberAllowlist(ctx android.ModuleContext) bool {
264 allowlist := ctx.Config().Once(buildNumberAllowlistKey, func() interface{} {
Cole Faustdc018782024-08-28 11:08:06 -0700265 // Define the allowlist as a list and then copy it into a map so that
266 // gofmt doesn't change unnecessary lines trying to align the values of the map.
267 allowlist := []string{
Cole Faustf23fdc02024-08-23 15:21:13 -0700268 // go/keep-sorted start
Cole Faustdc018782024-08-28 11:08:06 -0700269 "build/soong/tests:gen",
270 "hardware/google/camera/common/hal/aidl_service:aidl_camera_build_version",
271 "tools/tradefederation/core:tradefed_zip",
272 "vendor/google/services/LyricCameraHAL/src/apex:com.google.pixel.camera.hal.manifest",
Cole Faustf23fdc02024-08-23 15:21:13 -0700273 // go/keep-sorted end
274 }
Cole Faustdc018782024-08-28 11:08:06 -0700275 allowlistMap := make(map[string]bool, len(allowlist))
276 for _, a := range allowlist {
277 allowlistMap[a] = true
278 }
279 return allowlistMap
Cole Faustf23fdc02024-08-23 15:21:13 -0700280 }).(map[string]bool)
281
282 _, ok := allowlist[ctx.ModuleDir()+":"+ctx.ModuleName()]
283 return ok
Cole Faust78f3c3a2024-08-15 17:19:34 -0700284}
285
Chris Parsonsf874e462022-05-10 13:50:12 -0400286// generateCommonBuildActions contains build action generation logic
287// common to both the mixed build case and the legacy case of genrule processing.
288// To fully support genrule in mixed builds, the contents of this function should
289// approach zero; there should be no genrule action registration done directly
290// by Soong logic in the mixed-build case.
291func (g *Module) generateCommonBuildActions(ctx android.ModuleContext) {
Colin Crossa4ad2b02019-03-18 22:15:32 -0700292 g.subName = ctx.ModuleSubDir()
293
Colin Cross5ed99c62016-11-22 12:55:55 -0800294 if len(g.properties.Export_include_dirs) > 0 {
295 for _, dir := range g.properties.Export_include_dirs {
296 g.exportedIncludeDirs = append(g.exportedIncludeDirs,
Colin Cross1a527682019-09-23 15:55:30 -0700297 android.PathForModuleGen(ctx, g.subDir, ctx.ModuleDir(), dir))
Liz Kammerd38c87c2023-07-17 09:58:50 -0400298 // Also export without ModuleDir for consistency with Export_include_dirs not being set
299 g.exportedIncludeDirs = append(g.exportedIncludeDirs,
300 android.PathForModuleGen(ctx, g.subDir, dir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800301 }
302 } else {
Colin Cross1a527682019-09-23 15:55:30 -0700303 g.exportedIncludeDirs = append(g.exportedIncludeDirs, android.PathForModuleGen(ctx, g.subDir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800304 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700305
Colin Crossd11cf622021-03-23 22:30:35 -0700306 locationLabels := map[string]location{}
Colin Cross08f15ab2018-10-04 23:29:14 -0700307 firstLabel := ""
308
Colin Crossd11cf622021-03-23 22:30:35 -0700309 addLocationLabel := func(label string, loc location) {
Colin Cross08f15ab2018-10-04 23:29:14 -0700310 if firstLabel == "" {
311 firstLabel = label
312 }
313 if _, exists := locationLabels[label]; !exists {
Colin Crossd11cf622021-03-23 22:30:35 -0700314 locationLabels[label] = loc
Colin Cross08f15ab2018-10-04 23:29:14 -0700315 } else {
Anton Hansson7cd41e52021-10-08 16:13:10 +0100316 ctx.ModuleErrorf("multiple locations for label %q: %q and %q (do you have duplicate srcs entries?)",
Colin Crossd11cf622021-03-23 22:30:35 -0700317 label, locationLabels[label], loc)
Colin Cross08f15ab2018-10-04 23:29:14 -0700318 }
319 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700320
Colin Crossba9e4032020-11-24 16:32:22 -0800321 var tools android.Paths
322 var packagedTools []android.PackagingSpec
Colin Cross6f080df2016-11-04 15:32:58 -0700323 if len(g.properties.Tools) > 0 {
Colin Crossba71a3f2019-03-18 12:12:48 -0700324 seenTools := make(map[string]bool)
Yu Liud2a95952024-10-10 00:15:26 +0000325 ctx.VisitDirectDepsProxyAllowDisabled(func(proxy android.ModuleProxy) {
326 switch tag := ctx.OtherModuleDependencyTag(proxy).(type) {
Colin Cross08f15ab2018-10-04 23:29:14 -0700327 case hostToolDependencyTag:
Colin Cross648daea2024-09-12 14:35:29 -0700328 // Necessary to retrieve any prebuilt replacement for the tool, since
329 // toolDepsMutator runs too late for the prebuilt mutators to have
330 // replaced the dependency.
Yu Liud2a95952024-10-10 00:15:26 +0000331 module := android.PrebuiltGetPreferred(ctx, proxy)
332 tool := ctx.OtherModuleName(module)
333 if h, ok := android.OtherModuleProvider(ctx, module, android.HostToolProviderKey); ok {
Colin Crossba9e4032020-11-24 16:32:22 -0800334 // A HostToolProvider provides the path to a tool, which will be copied
335 // into the sandbox.
Yu Liud2a95952024-10-10 00:15:26 +0000336 if !android.OtherModuleProviderOrDefault(ctx, module, android.CommonPropertiesProviderKey).Enabled {
Colin Cross6510f912017-11-29 00:27:14 -0800337 if ctx.Config().AllowMissingDependencies() {
Colin Cross35143d02017-11-16 00:11:20 -0800338 ctx.AddMissingDependencies([]string{tool})
339 } else {
340 ctx.ModuleErrorf("depends on disabled module %q", tool)
341 }
Colin Crossba9e4032020-11-24 16:32:22 -0800342 return
Colin Cross35143d02017-11-16 00:11:20 -0800343 }
Yu Liud2a95952024-10-10 00:15:26 +0000344 path := h.HostToolPath
Colin Crossba9e4032020-11-24 16:32:22 -0800345 if !path.Valid() {
346 ctx.ModuleErrorf("host tool %q missing output file", tool)
347 return
348 }
Yu Liubad1eef2024-08-21 22:37:35 +0000349 if specs := android.OtherModuleProviderOrDefault(
Yu Liud2a95952024-10-10 00:15:26 +0000350 ctx, module, android.InstallFilesProvider).TransitivePackagingSpecs.ToList(); specs != nil {
Colin Crossba9e4032020-11-24 16:32:22 -0800351 // If the HostToolProvider has PackgingSpecs, which are definitions of the
352 // required relative locations of the tool and its dependencies, use those
353 // instead. They will be copied to those relative locations in the sbox
354 // sandbox.
Jiyong Park8fb0e972024-03-18 18:29:37 +0900355 // Care must be taken since TransitivePackagingSpec may return device-side
356 // paths via the required property. Filter them out.
357 for i, ps := range specs {
358 if ps.Partition() != "" {
359 if i == 0 {
360 panic("first PackagingSpec is assumed to be the host-side tool")
361 }
362 continue
363 }
364 packagedTools = append(packagedTools, ps)
365 }
Colin Crossba9e4032020-11-24 16:32:22 -0800366 // Assume that the first PackagingSpec of the module is the tool.
Colin Crossd11cf622021-03-23 22:30:35 -0700367 addLocationLabel(tag.label, packagedToolLocation{specs[0]})
Colin Crossba9e4032020-11-24 16:32:22 -0800368 } else {
369 tools = append(tools, path.Path())
Colin Crossd11cf622021-03-23 22:30:35 -0700370 addLocationLabel(tag.label, toolLocation{android.Paths{path.Path()}})
Colin Crossba9e4032020-11-24 16:32:22 -0800371 }
Yu Liud2a95952024-10-10 00:15:26 +0000372 } else {
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700373 ctx.ModuleErrorf("%q is not a host tool provider", tool)
Colin Crossba9e4032020-11-24 16:32:22 -0800374 return
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700375 }
376
Colin Crossba9e4032020-11-24 16:32:22 -0800377 seenTools[tag.label] = true
Colin Crossd350ecd2015-04-28 13:25:36 -0700378 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700379 })
Colin Crossba71a3f2019-03-18 12:12:48 -0700380
381 // If AllowMissingDependencies is enabled, the build will not have stopped when
382 // AddFarVariationDependencies was called on a missing tool, which will result in nonsensical
Liz Kammer20ebfb42020-07-28 11:32:07 -0700383 // "cmd: unknown location label ..." errors later. Add a placeholder file to the local label.
384 // The command that uses this placeholder file will never be executed because the rule will be
385 // replaced with an android.Error rule reporting the missing dependencies.
Colin Crossba71a3f2019-03-18 12:12:48 -0700386 if ctx.Config().AllowMissingDependencies() {
387 for _, tool := range g.properties.Tools {
388 if !seenTools[tool] {
Colin Crossd11cf622021-03-23 22:30:35 -0700389 addLocationLabel(tool, errorLocation{"***missing tool " + tool + "***"})
Colin Crossba71a3f2019-03-18 12:12:48 -0700390 }
391 }
392 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700393 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700394
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700395 if ctx.Failed() {
396 return
397 }
398
Colin Cross08f15ab2018-10-04 23:29:14 -0700399 for _, toolFile := range g.properties.Tool_files {
Colin Cross8a497952019-03-05 22:25:09 -0800400 paths := android.PathsForModuleSrc(ctx, []string{toolFile})
Colin Crossba9e4032020-11-24 16:32:22 -0800401 tools = append(tools, paths...)
Colin Crossd11cf622021-03-23 22:30:35 -0700402 addLocationLabel(toolFile, toolLocation{paths})
Colin Cross08f15ab2018-10-04 23:29:14 -0700403 }
404
Liz Kammer81fec182023-06-09 13:33:45 -0400405 addLabelsForInputs := func(propName string, include, exclude []string) android.Paths {
Liz Kammer81fec182023-06-09 13:33:45 -0400406 includeDirInPaths := ctx.DeviceConfig().BuildBrokenInputDir(g.Name())
407 var srcFiles android.Paths
408 for _, in := range include {
409 paths, missingDeps := android.PathsAndMissingDepsRelativeToModuleSourceDir(android.SourceInput{
410 Context: ctx, Paths: []string{in}, ExcludePaths: exclude, IncludeDirs: includeDirInPaths,
411 })
412 if len(missingDeps) > 0 {
413 if !ctx.Config().AllowMissingDependencies() {
414 panic(fmt.Errorf("should never get here, the missing dependencies %q should have been reported in DepsMutator",
415 missingDeps))
416 }
417
418 // If AllowMissingDependencies is enabled, the build will not have stopped when
419 // the dependency was added on a missing SourceFileProducer module, which will result in nonsensical
420 // "cmd: label ":..." has no files" errors later. Add a placeholder file to the local label.
421 // The command that uses this placeholder file will never be executed because the rule will be
422 // replaced with an android.Error rule reporting the missing dependencies.
423 ctx.AddMissingDependencies(missingDeps)
424 addLocationLabel(in, errorLocation{"***missing " + propName + " " + in + "***"})
425 } else {
426 srcFiles = append(srcFiles, paths...)
427 addLocationLabel(in, inputLocation{paths})
428 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700429 }
Liz Kammer81fec182023-06-09 13:33:45 -0400430 return srcFiles
Colin Cross08f15ab2018-10-04 23:29:14 -0700431 }
Cole Faustf966e382024-10-08 16:17:56 -0700432 srcs := g.properties.Srcs.GetOrDefault(ctx, nil)
433 srcFiles := addLabelsForInputs("srcs", srcs, g.properties.Exclude_srcs)
Colin Cross40213022023-12-13 15:19:49 -0800434 android.SetProvider(ctx, blueprint.SrcsFileProviderKey, blueprint.SrcsFileProviderData{SrcPaths: srcFiles.Strings()})
Colin Cross08f15ab2018-10-04 23:29:14 -0700435
Colin Cross1a527682019-09-23 15:55:30 -0700436 var copyFrom android.Paths
437 var outputFiles android.WritablePaths
438 var zipArgs strings.Builder
Colin Cross08f15ab2018-10-04 23:29:14 -0700439
Aleks Todorov1eb06c42024-06-03 15:23:56 +0100440 cmd := g.properties.Cmd.GetOrDefault(ctx, "")
Colin Crossf3bfd022021-09-27 15:15:06 -0700441 if g.CmdModifier != nil {
442 cmd = g.CmdModifier(ctx, cmd)
443 }
444
Liz Kammer796921d2023-07-11 08:21:41 -0400445 var extraInputs android.Paths
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500446 // Generate tasks, either from genrule or gensrcs.
Liz Kammer81fec182023-06-09 13:33:45 -0400447 for i, task := range g.taskGenerator(ctx, cmd, srcFiles) {
Colin Cross3d680512020-11-13 16:23:53 -0800448 if len(task.out) == 0 {
449 ctx.ModuleErrorf("must have at least one output file")
450 return
Colin Cross85a2e892018-07-09 09:45:06 -0700451 }
452
Liz Kammer81fec182023-06-09 13:33:45 -0400453 // Only handle extra inputs once as these currently are the same across all tasks
454 if i == 0 {
455 for name, values := range task.extraInputs {
456 extraInputs = append(extraInputs, addLabelsForInputs(name, values, []string{})...)
457 }
458 }
459
Colin Crossf1a035e2020-11-16 17:32:30 -0800460 // Pick a unique path outside the task.genDir for the sbox manifest textproto,
461 // a unique rule name, and the user-visible description.
Inseob Kimf7cd03e2024-09-06 17:25:00 +0900462 var rule *android.RuleBuilder
Colin Crossf1a035e2020-11-16 17:32:30 -0800463 desc := "generate"
464 name := "generator"
Inseob Kimf7cd03e2024-09-06 17:25:00 +0900465 if task.useNsjail {
466 rule = android.NewRuleBuilder(pctx, ctx).Nsjail(task.genDir, android.PathForModuleOut(ctx, "nsjail_build_sandbox"))
467 } else {
468 manifestName := "genrule.sbox.textproto"
469 if task.shards > 0 {
470 manifestName = "genrule_" + strconv.Itoa(task.shard) + ".sbox.textproto"
471 desc += " " + strconv.Itoa(task.shard)
472 name += strconv.Itoa(task.shard)
473 } else if len(task.out) == 1 {
474 desc += " " + task.out[0].Base()
475 }
476
477 manifestPath := android.PathForModuleOut(ctx, manifestName)
478
479 // Use a RuleBuilder to create a rule that runs the command inside an sbox sandbox.
480 rule = getSandboxedRuleBuilder(ctx, android.NewRuleBuilder(pctx, ctx).Sbox(task.genDir, manifestPath))
Colin Crossf1a035e2020-11-16 17:32:30 -0800481 }
Justin Yun4da4ccc2023-07-06 10:56:29 +0900482 if Bool(g.properties.Write_if_changed) {
483 rule.Restat()
484 }
Colin Crossf1a035e2020-11-16 17:32:30 -0800485 cmd := rule.Command()
486
Colin Cross3d680512020-11-13 16:23:53 -0800487 for _, out := range task.out {
Colin Crossd11cf622021-03-23 22:30:35 -0700488 addLocationLabel(out.Rel(), outputLocation{out})
Colin Cross3d680512020-11-13 16:23:53 -0800489 }
490
Colin Cross3d680512020-11-13 16:23:53 -0800491 rawCommand, err := android.Expand(task.cmd, func(name string) (string, error) {
Colin Cross1a527682019-09-23 15:55:30 -0700492 // report the error directly without returning an error to android.Expand to catch multiple errors in a
493 // single run
Colin Cross3d680512020-11-13 16:23:53 -0800494 reportError := func(fmt string, args ...interface{}) (string, error) {
Colin Cross1a527682019-09-23 15:55:30 -0700495 ctx.PropertyErrorf("cmd", fmt, args...)
Colin Cross3d680512020-11-13 16:23:53 -0800496 return "SOONG_ERROR", nil
Colin Cross6f080df2016-11-04 15:32:58 -0700497 }
Colin Cross1a527682019-09-23 15:55:30 -0700498
Jihoon Kangc170af42022-08-20 05:26:38 +0000499 // Apply shell escape to each cases to prevent source file paths containing $ from being evaluated in shell
Colin Cross1a527682019-09-23 15:55:30 -0700500 switch name {
501 case "location":
502 if len(g.properties.Tools) == 0 && len(g.properties.Tool_files) == 0 {
503 return reportError("at least one `tools` or `tool_files` is required if $(location) is used")
Colin Cross6f080df2016-11-04 15:32:58 -0700504 }
Colin Crossd11cf622021-03-23 22:30:35 -0700505 loc := locationLabels[firstLabel]
506 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700507 if len(paths) == 0 {
508 return reportError("default label %q has no files", firstLabel)
509 } else if len(paths) > 1 {
510 return reportError("default label %q has multiple files, use $(locations %s) to reference it",
511 firstLabel, firstLabel)
Colin Cross08f15ab2018-10-04 23:29:14 -0700512 }
Jihoon Kangc170af42022-08-20 05:26:38 +0000513 return proptools.ShellEscape(paths[0]), nil
Colin Cross1a527682019-09-23 15:55:30 -0700514 case "in":
Jihoon Kangc170af42022-08-20 05:26:38 +0000515 return strings.Join(proptools.ShellEscapeList(cmd.PathsForInputs(srcFiles)), " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700516 case "out":
Colin Cross3d680512020-11-13 16:23:53 -0800517 var sandboxOuts []string
518 for _, out := range task.out {
Colin Crossf1a035e2020-11-16 17:32:30 -0800519 sandboxOuts = append(sandboxOuts, cmd.PathForOutput(out))
Colin Cross3d680512020-11-13 16:23:53 -0800520 }
Jihoon Kangc170af42022-08-20 05:26:38 +0000521 return strings.Join(proptools.ShellEscapeList(sandboxOuts), " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700522 case "genDir":
Jihoon Kangc170af42022-08-20 05:26:38 +0000523 return proptools.ShellEscape(cmd.PathForOutput(task.genDir)), nil
Cole Faust78f3c3a2024-08-15 17:19:34 -0700524 case "build_number_file":
525 if !proptools.Bool(g.properties.Uses_order_only_build_number_file) {
526 return reportError("to use the $(build_number_file) label, you must set uses_order_only_build_number_file: true")
527 }
528 return proptools.ShellEscape(cmd.PathForInput(ctx.Config().BuildNumberFile(ctx))), nil
Colin Cross1a527682019-09-23 15:55:30 -0700529 default:
530 if strings.HasPrefix(name, "location ") {
531 label := strings.TrimSpace(strings.TrimPrefix(name, "location "))
Colin Crossd11cf622021-03-23 22:30:35 -0700532 if loc, ok := locationLabels[label]; ok {
533 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700534 if len(paths) == 0 {
535 return reportError("label %q has no files", label)
536 } else if len(paths) > 1 {
537 return reportError("label %q has multiple files, use $(locations %s) to reference it",
538 label, label)
539 }
Jihoon Kangc170af42022-08-20 05:26:38 +0000540 return proptools.ShellEscape(paths[0]), nil
Colin Cross1a527682019-09-23 15:55:30 -0700541 } else {
Anton Hanssonbebf5262022-02-23 11:42:38 +0000542 return reportError("unknown location label %q is not in srcs, out, tools or tool_files.", label)
Colin Cross1a527682019-09-23 15:55:30 -0700543 }
544 } else if strings.HasPrefix(name, "locations ") {
545 label := strings.TrimSpace(strings.TrimPrefix(name, "locations "))
Colin Crossd11cf622021-03-23 22:30:35 -0700546 if loc, ok := locationLabels[label]; ok {
547 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700548 if len(paths) == 0 {
549 return reportError("label %q has no files", label)
550 }
Cole Faustce74a592023-12-07 14:58:45 -0800551 return strings.Join(proptools.ShellEscapeList(paths), " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700552 } else {
Anton Hanssonbebf5262022-02-23 11:42:38 +0000553 return reportError("unknown locations label %q is not in srcs, out, tools or tool_files.", label)
Colin Cross1a527682019-09-23 15:55:30 -0700554 }
555 } else {
556 return reportError("unknown variable '$(%s)'", name)
557 }
Colin Cross6f080df2016-11-04 15:32:58 -0700558 }
Colin Cross1a527682019-09-23 15:55:30 -0700559 })
560
561 if err != nil {
562 ctx.PropertyErrorf("cmd", "%s", err.Error())
563 return
Colin Cross6f080df2016-11-04 15:32:58 -0700564 }
Colin Cross6f080df2016-11-04 15:32:58 -0700565
Colin Cross1a527682019-09-23 15:55:30 -0700566 g.rawCommands = append(g.rawCommands, rawCommand)
Bill Peckhamc087be12020-02-13 15:55:10 -0800567
Colin Cross3d680512020-11-13 16:23:53 -0800568 cmd.Text(rawCommand)
Liz Kammer81fec182023-06-09 13:33:45 -0400569 cmd.Implicits(srcFiles) // need to be able to reference other srcs
570 cmd.Implicits(extraInputs)
Colin Cross3d680512020-11-13 16:23:53 -0800571 cmd.ImplicitOutputs(task.out)
572 cmd.Implicits(task.in)
Colin Crossba9e4032020-11-24 16:32:22 -0800573 cmd.ImplicitTools(tools)
Colin Crossba9e4032020-11-24 16:32:22 -0800574 cmd.ImplicitPackagedTools(packagedTools)
Cole Faust78f3c3a2024-08-15 17:19:34 -0700575 if proptools.Bool(g.properties.Uses_order_only_build_number_file) {
Cole Faustf23fdc02024-08-23 15:21:13 -0700576 if !isModuleInBuildNumberAllowlist(ctx) {
Cole Faust78f3c3a2024-08-15 17:19:34 -0700577 ctx.ModuleErrorf("Only allowlisted modules may use uses_order_only_build_number_file: true")
578 }
579 cmd.OrderOnly(ctx.Config().BuildNumberFile(ctx))
580 }
Colin Cross3d680512020-11-13 16:23:53 -0800581
Inseob Kimf7cd03e2024-09-06 17:25:00 +0900582 if task.useNsjail {
Inseob Kim76e19852024-10-10 17:57:22 +0900583 for _, input := range task.dirSrcs {
584 cmd.Implicit(input)
Inseob Kimf7cd03e2024-09-06 17:25:00 +0900585 if paths, err := ctx.GlobWithDeps(filepath.Join(input.String(), "**/*"), nil); err == nil {
586 rule.NsjailImplicits(android.PathsForSource(ctx, paths))
Inseob Kim76e19852024-10-10 17:57:22 +0900587 } else {
588 ctx.PropertyErrorf("dir_srcs", "can't glob %q", input.String())
Inseob Kimf7cd03e2024-09-06 17:25:00 +0900589 }
590 }
591 }
592
Colin Cross3d680512020-11-13 16:23:53 -0800593 // Create the rule to run the genrule command inside sbox.
Colin Crossf1a035e2020-11-16 17:32:30 -0800594 rule.Build(name, desc)
Colin Cross1a527682019-09-23 15:55:30 -0700595
596 if len(task.copyTo) > 0 {
Colin Cross3d680512020-11-13 16:23:53 -0800597 // If copyTo is set, multiple shards need to be copied into a single directory.
598 // task.out contains the per-shard paths, and copyTo contains the corresponding
599 // final path. The files need to be copied into the final directory by a
600 // single rule so it can remove the directory before it starts to ensure no
601 // old files remain. zipsync already does this, so build up zipArgs that
602 // zip all the per-shard directories into a single zip.
Colin Cross1a527682019-09-23 15:55:30 -0700603 outputFiles = append(outputFiles, task.copyTo...)
604 copyFrom = append(copyFrom, task.out.Paths()...)
605 zipArgs.WriteString(" -C " + task.genDir.String())
606 zipArgs.WriteString(android.JoinWithPrefix(task.out.Strings(), " -f "))
607 } else {
608 outputFiles = append(outputFiles, task.out...)
609 }
Colin Cross6f080df2016-11-04 15:32:58 -0700610 }
611
Colin Cross1a527682019-09-23 15:55:30 -0700612 if len(copyFrom) > 0 {
Colin Cross3d680512020-11-13 16:23:53 -0800613 // Create a rule that zips all the per-shard directories into a single zip and then
614 // uses zipsync to unzip it into the final directory.
Colin Cross1a527682019-09-23 15:55:30 -0700615 ctx.Build(pctx, android.BuildParams{
Colin Crossf1885962020-11-20 15:28:30 -0800616 Rule: gensrcsMerge,
617 Implicits: copyFrom,
618 Outputs: outputFiles,
619 Description: "merge shards",
Colin Cross1a527682019-09-23 15:55:30 -0700620 Args: map[string]string{
621 "zipArgs": zipArgs.String(),
622 "tmpZip": android.PathForModuleGen(ctx, g.subDir+".zip").String(),
623 "genDir": android.PathForModuleGen(ctx, g.subDir).String(),
624 },
625 })
Colin Cross85a2e892018-07-09 09:45:06 -0700626 }
627
Colin Cross1a527682019-09-23 15:55:30 -0700628 g.outputFiles = outputFiles.Paths()
Chris Parsonsf874e462022-05-10 13:50:12 -0400629}
Jeff Gastonefc1b412017-03-29 17:29:06 -0700630
Chris Parsonsf874e462022-05-10 13:50:12 -0400631func (g *Module) GenerateAndroidBuildActions(ctx android.ModuleContext) {
632 g.generateCommonBuildActions(ctx)
633
634 // For <= 6 outputs, just embed those directly in the users. Right now, that covers >90% of
635 // the genrules on AOSP. That will make things simpler to look at the graph in the common
636 // case. For larger sets of outputs, inject a phony target in between to limit ninja file
637 // growth.
638 if len(g.outputFiles) <= 6 {
639 g.outputDeps = g.outputFiles
640 } else {
641 phonyFile := android.PathForModuleGen(ctx, "genrule-phony")
642 ctx.Build(pctx, android.BuildParams{
643 Rule: blueprint.Phony,
644 Output: phonyFile,
645 Inputs: g.outputFiles,
646 })
647 g.outputDeps = android.Paths{phonyFile}
Jeff Gaston02a684b2017-10-27 14:59:27 -0700648 }
mrziwang4514ef22024-06-07 13:31:48 -0700649
650 g.setOutputFiles(ctx)
Cole Faust481b6692024-10-11 16:25:07 -0700651
652 if ctx.Os() == android.Windows {
653 // Make doesn't support windows:
654 // https://cs.android.com/android/platform/superproject/main/+/main:build/make/core/module_arch_supported.mk;l=66;drc=f264690860bb6ee7762784d6b7201aae057ba6f2
655 g.HideFromMake()
656 }
mrziwang4514ef22024-06-07 13:31:48 -0700657}
658
659func (g *Module) setOutputFiles(ctx android.ModuleContext) {
660 if len(g.outputFiles) == 0 {
661 return
662 }
663 ctx.SetOutputFiles(g.outputFiles, "")
664 // non-empty-string-tag should match one of the outputs
665 for _, files := range g.outputFiles {
666 ctx.SetOutputFiles(android.Paths{files}, files.Rel())
667 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400668}
669
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700670// Collect information for opening IDE project files in java/jdeps.go.
Cole Faustb36d31d2024-08-27 16:04:28 -0700671func (g *Module) IDEInfo(ctx android.BaseModuleContext, dpInfo *android.IdeInfo) {
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700672 dpInfo.Srcs = append(dpInfo.Srcs, g.Srcs().Strings()...)
Cole Faustf966e382024-10-08 16:17:56 -0700673 for _, src := range g.properties.Srcs.GetOrDefault(ctx, nil) {
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700674 if strings.HasPrefix(src, ":") {
675 src = strings.Trim(src, ":")
676 dpInfo.Deps = append(dpInfo.Deps, src)
677 }
678 }
679}
680
Colin Crossa4ad2b02019-03-18 22:15:32 -0700681func (g *Module) AndroidMk() android.AndroidMkData {
682 return android.AndroidMkData{
Anton Hansson72f18492020-10-30 16:34:45 +0000683 Class: "ETC",
Colin Crossa4ad2b02019-03-18 22:15:32 -0700684 OutputFile: android.OptionalPathForPath(g.outputFiles[0]),
685 SubName: g.subName,
686 Extra: []android.AndroidMkExtraFunc{
687 func(w io.Writer, outputFile android.Path) {
Anton Hansson72f18492020-10-30 16:34:45 +0000688 fmt.Fprintln(w, "LOCAL_UNINSTALLABLE_MODULE := true")
Colin Crossa4ad2b02019-03-18 22:15:32 -0700689 },
690 },
691 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
692 android.WriteAndroidMkData(w, data)
693 if data.SubName != "" {
694 fmt.Fprintln(w, ".PHONY:", name)
695 fmt.Fprintln(w, name, ":", name+g.subName)
696 }
697 },
698 }
699}
700
Jiyong Park45bf82e2020-12-15 22:29:02 +0900701var _ android.ApexModule = (*Module)(nil)
702
703// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -0700704func (g *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
705 sdkVersion android.ApiLevel) error {
Jooyung Han749dc692020-04-15 11:03:39 +0900706 // Because generated outputs are checked by client modules(e.g. cc_library, ...)
707 // we can safely ignore the check here.
708 return nil
709}
710
Jeff Gaston437d23c2017-11-08 12:38:00 -0800711func generatorFactory(taskGenerator taskFunc, props ...interface{}) *Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700712 module := &Module{
Jeff Gaston437d23c2017-11-08 12:38:00 -0800713 taskGenerator: taskGenerator,
Colin Crossd350ecd2015-04-28 13:25:36 -0700714 }
715
Colin Cross36242852017-06-23 15:06:31 -0700716 module.AddProperties(props...)
717 module.AddProperties(&module.properties)
Colin Crossd350ecd2015-04-28 13:25:36 -0700718
Colin Cross7228ecd2019-11-18 16:00:16 -0800719 module.ImageInterface = noopImageInterface{}
720
Colin Cross36242852017-06-23 15:06:31 -0700721 return module
Colin Crossd350ecd2015-04-28 13:25:36 -0700722}
723
Colin Cross7228ecd2019-11-18 16:00:16 -0800724type noopImageInterface struct{}
725
726func (x noopImageInterface) ImageMutatorBegin(android.BaseModuleContext) {}
Jihoon Kang47e91842024-06-19 00:51:16 +0000727func (x noopImageInterface) VendorVariantNeeded(android.BaseModuleContext) bool { return false }
728func (x noopImageInterface) ProductVariantNeeded(android.BaseModuleContext) bool { return false }
Colin Cross7228ecd2019-11-18 16:00:16 -0800729func (x noopImageInterface) CoreVariantNeeded(android.BaseModuleContext) bool { return false }
Yifan Hong1b3348d2020-01-21 15:53:22 -0800730func (x noopImageInterface) RamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700731func (x noopImageInterface) VendorRamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Inseob Kim08758f02021-04-08 21:13:22 +0900732func (x noopImageInterface) DebugRamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Colin Cross7228ecd2019-11-18 16:00:16 -0800733func (x noopImageInterface) RecoveryVariantNeeded(android.BaseModuleContext) bool { return false }
734func (x noopImageInterface) ExtraImageVariations(ctx android.BaseModuleContext) []string { return nil }
Jihoon Kang7583e832024-06-13 21:25:45 +0000735func (x noopImageInterface) SetImageVariation(ctx android.BaseModuleContext, variation string) {
Colin Cross7228ecd2019-11-18 16:00:16 -0800736}
737
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700738func NewGenSrcs() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700739 properties := &genSrcsProperties{}
740
Colin Crossf1885962020-11-20 15:28:30 -0800741 // finalSubDir is the name of the subdirectory that output files will be generated into.
742 // It is used so that per-shard directories can be placed alongside it an then finally
743 // merged into it.
744 const finalSubDir = "gensrcs"
745
Colin Cross1a527682019-09-23 15:55:30 -0700746 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Colin Cross1a527682019-09-23 15:55:30 -0700747 shardSize := defaultShardSize
748 if s := properties.Shard_size; s != nil {
749 shardSize = int(*s)
750 }
Jeff Gaston437d23c2017-11-08 12:38:00 -0800751
Colin Crossf1885962020-11-20 15:28:30 -0800752 // gensrcs rules can easily hit command line limits by repeating the command for
753 // every input file. Shard the input files into groups.
Colin Cross1a527682019-09-23 15:55:30 -0700754 shards := android.ShardPaths(srcFiles, shardSize)
755 var generateTasks []generateTask
Colin Crossbaccf5b2018-02-21 14:07:48 -0800756
Colin Cross1a527682019-09-23 15:55:30 -0700757 for i, shard := range shards {
758 var commands []string
759 var outFiles android.WritablePaths
760 var copyTo android.WritablePaths
Colin Cross1a527682019-09-23 15:55:30 -0700761
Colin Crossf1885962020-11-20 15:28:30 -0800762 // When sharding is enabled (i.e. len(shards) > 1), the sbox rules for each
763 // shard will be write to their own directories and then be merged together
764 // into finalSubDir. If sharding is not enabled (i.e. len(shards) == 1),
765 // the sbox rule will write directly to finalSubDir.
766 genSubDir := finalSubDir
Colin Cross1a527682019-09-23 15:55:30 -0700767 if len(shards) > 1 {
Colin Crossf1885962020-11-20 15:28:30 -0800768 genSubDir = strconv.Itoa(i)
Jeff Gaston437d23c2017-11-08 12:38:00 -0800769 }
770
Colin Crossf1885962020-11-20 15:28:30 -0800771 genDir := android.PathForModuleGen(ctx, genSubDir)
Colin Crossf1a035e2020-11-16 17:32:30 -0800772 // TODO(ccross): this RuleBuilder is a hack to be able to call
773 // rule.Command().PathForOutput. Replace this with passing the rule into the
774 // generator.
Yu Liu6a7940c2023-05-09 17:12:22 -0700775 rule := getSandboxedRuleBuilder(ctx, android.NewRuleBuilder(pctx, ctx).Sbox(genDir, nil))
Jeff Gaston437d23c2017-11-08 12:38:00 -0800776
Colin Cross3ea4eb82020-11-24 13:07:27 -0800777 for _, in := range shard {
yangbill6d032dd2024-04-18 03:05:49 +0000778 outFile := android.GenPathWithExtAndTrimExt(ctx, finalSubDir, in, String(properties.Output_extension), String(properties.Trim_extension))
Colin Crossf1885962020-11-20 15:28:30 -0800779
780 // If sharding is enabled, then outFile is the path to the output file in
781 // the shard directory, and copyTo is the path to the output file in the
782 // final directory.
Colin Cross1a527682019-09-23 15:55:30 -0700783 if len(shards) > 1 {
yangbill6d032dd2024-04-18 03:05:49 +0000784 shardFile := android.GenPathWithExtAndTrimExt(ctx, genSubDir, in, String(properties.Output_extension), String(properties.Trim_extension))
Colin Cross1a527682019-09-23 15:55:30 -0700785 copyTo = append(copyTo, outFile)
786 outFile = shardFile
787 }
788
789 outFiles = append(outFiles, outFile)
Colin Cross1a527682019-09-23 15:55:30 -0700790
Colin Crossf1885962020-11-20 15:28:30 -0800791 // pre-expand the command line to replace $in and $out with references to
792 // a single input and output file.
Colin Cross1a527682019-09-23 15:55:30 -0700793 command, err := android.Expand(rawCommand, func(name string) (string, error) {
794 switch name {
795 case "in":
796 return in.String(), nil
797 case "out":
Colin Crossf1a035e2020-11-16 17:32:30 -0800798 return rule.Command().PathForOutput(outFile), nil
Colin Cross1a527682019-09-23 15:55:30 -0700799 default:
800 return "$(" + name + ")", nil
801 }
802 })
803 if err != nil {
804 ctx.PropertyErrorf("cmd", err.Error())
805 }
806
807 // escape the command in case for example it contains '#', an odd number of '"', etc
808 command = fmt.Sprintf("bash -c %v", proptools.ShellEscape(command))
809 commands = append(commands, command)
810 }
811 fullCommand := strings.Join(commands, " && ")
812
813 generateTasks = append(generateTasks, generateTask{
Cole Faust55492572024-01-25 18:00:33 -0800814 in: shard,
815 out: outFiles,
816 copyTo: copyTo,
817 genDir: genDir,
818 cmd: fullCommand,
819 shard: i,
820 shards: len(shards),
Liz Kammer81fec182023-06-09 13:33:45 -0400821 extraInputs: map[string][]string{
822 "data": properties.Data,
823 },
Colin Cross1a527682019-09-23 15:55:30 -0700824 })
Jeff Gaston437d23c2017-11-08 12:38:00 -0800825 }
Colin Cross1a527682019-09-23 15:55:30 -0700826
827 return generateTasks
Colin Crossd350ecd2015-04-28 13:25:36 -0700828 }
829
Colin Cross1a527682019-09-23 15:55:30 -0700830 g := generatorFactory(taskGenerator, properties)
Colin Crossf1885962020-11-20 15:28:30 -0800831 g.subDir = finalSubDir
Colin Cross1a527682019-09-23 15:55:30 -0700832 return g
Colin Crossd350ecd2015-04-28 13:25:36 -0700833}
834
Colin Cross54190b32017-10-09 15:34:10 -0700835func GenSrcsFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700836 m := NewGenSrcs()
837 android.InitAndroidModule(m)
Colin Cross483b4c42024-05-09 13:08:02 -0700838 android.InitDefaultableModule(m)
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700839 return m
840}
841
Colin Crossd350ecd2015-04-28 13:25:36 -0700842type genSrcsProperties struct {
Colin Cross7d5136f2015-05-11 13:39:40 -0700843 // extension that will be substituted for each output file
Nan Zhanga5e7cb42017-11-09 22:42:32 -0800844 Output_extension *string
Colin Cross1a527682019-09-23 15:55:30 -0700845
846 // maximum number of files that will be passed on a single command line.
847 Shard_size *int64
Liz Kammer81fec182023-06-09 13:33:45 -0400848
849 // Additional files needed for build that are not tooling related.
850 Data []string `android:"path"`
yangbill6d032dd2024-04-18 03:05:49 +0000851
852 // Trim the matched extension for each input file, and it should start with ".".
853 Trim_extension *string
Colin Cross5049f022015-03-18 13:28:46 -0700854}
855
Evgenii Stepanovf47c90d2020-12-02 18:55:09 -0800856const defaultShardSize = 50
Colin Cross1a527682019-09-23 15:55:30 -0700857
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700858func NewGenRule() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700859 properties := &genRuleProperties{}
Colin Cross5049f022015-03-18 13:28:46 -0700860
Colin Cross1a527682019-09-23 15:55:30 -0700861 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Inseob Kimf7cd03e2024-09-06 17:25:00 +0900862 useNsjail := Bool(properties.Use_nsjail)
863
Inseob Kim76e19852024-10-10 17:57:22 +0900864 dirSrcs := android.DirectoryPathsForModuleSrc(ctx, properties.Dir_srcs)
865 if len(dirSrcs) > 0 && !useNsjail {
866 ctx.PropertyErrorf("dir_srcs", "can't use dir_srcs if use_nsjail is false")
867 return nil
868 }
869
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700870 outs := make(android.WritablePaths, len(properties.Out))
871 for i, out := range properties.Out {
Cole Faust55492572024-01-25 18:00:33 -0800872 outs[i] = android.PathForModuleGen(ctx, out)
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700873 }
Colin Cross1a527682019-09-23 15:55:30 -0700874 return []generateTask{{
Inseob Kimf7cd03e2024-09-06 17:25:00 +0900875 in: srcFiles,
876 out: outs,
877 genDir: android.PathForModuleGen(ctx),
878 cmd: rawCommand,
879 useNsjail: useNsjail,
Inseob Kim76e19852024-10-10 17:57:22 +0900880 dirSrcs: dirSrcs,
Colin Cross1a527682019-09-23 15:55:30 -0700881 }}
Colin Cross5049f022015-03-18 13:28:46 -0700882 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700883
Jeff Gaston437d23c2017-11-08 12:38:00 -0800884 return generatorFactory(taskGenerator, properties)
Colin Cross5049f022015-03-18 13:28:46 -0700885}
886
Colin Cross54190b32017-10-09 15:34:10 -0700887func GenRuleFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700888 m := NewGenRule()
889 android.InitAndroidModule(m)
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800890 android.InitDefaultableModule(m)
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700891 return m
892}
893
Colin Crossd350ecd2015-04-28 13:25:36 -0700894type genRuleProperties struct {
Inseob Kimf7cd03e2024-09-06 17:25:00 +0900895 Use_nsjail *bool
896
Inseob Kim76e19852024-10-10 17:57:22 +0900897 // List of input directories. Can be set only when use_nsjail is true. Currently, usage of
898 // dir_srcs is limited only to Trusty build.
899 Dir_srcs []string `android:"path"`
900
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700901 // names of the output files that will be generated
kellyhung750334a2024-03-14 01:03:49 +0800902 Out []string `android:"arch_variant"`
Colin Cross5049f022015-03-18 13:28:46 -0700903}
Nan Zhangea568a42017-11-08 21:20:04 -0800904
905var Bool = proptools.Bool
906var String = proptools.String
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800907
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800908// Defaults
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800909type Defaults struct {
910 android.ModuleBase
911 android.DefaultsModuleBase
912}
913
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800914func defaultsFactory() android.Module {
915 return DefaultsFactory()
916}
917
918func DefaultsFactory(props ...interface{}) android.Module {
919 module := &Defaults{}
920
921 module.AddProperties(props...)
922 module.AddProperties(
923 &generatorProperties{},
924 &genRuleProperties{},
925 )
926
927 android.InitDefaultsModule(module)
928
929 return module
930}
Yu Liu6a7940c2023-05-09 17:12:22 -0700931
Yu Liue7f7cbf2023-06-13 18:50:03 +0000932var sandboxingAllowlistKey = android.NewOnceKey("genruleSandboxingAllowlistKey")
933
934type sandboxingAllowlistSets struct {
935 sandboxingDenyModuleSet map[string]bool
Yu Liue7f7cbf2023-06-13 18:50:03 +0000936}
937
938func getSandboxingAllowlistSets(ctx android.PathContext) *sandboxingAllowlistSets {
939 return ctx.Config().Once(sandboxingAllowlistKey, func() interface{} {
940 sandboxingDenyModuleSet := map[string]bool{}
Yu Liue7f7cbf2023-06-13 18:50:03 +0000941
Cole Faust55492572024-01-25 18:00:33 -0800942 android.AddToStringSet(sandboxingDenyModuleSet, SandboxingDenyModuleList)
Yu Liue7f7cbf2023-06-13 18:50:03 +0000943 return &sandboxingAllowlistSets{
944 sandboxingDenyModuleSet: sandboxingDenyModuleSet,
Yu Liue7f7cbf2023-06-13 18:50:03 +0000945 }
946 }).(*sandboxingAllowlistSets)
947}
Liz Kammer0db0e342023-07-18 11:39:30 -0400948
Yu Liu6a7940c2023-05-09 17:12:22 -0700949func getSandboxedRuleBuilder(ctx android.ModuleContext, r *android.RuleBuilder) *android.RuleBuilder {
Yu Liu45d6af52023-05-24 23:10:18 +0000950 if !ctx.DeviceConfig().GenruleSandboxing() {
951 return r.SandboxTools()
952 }
Yu Liue7f7cbf2023-06-13 18:50:03 +0000953 sandboxingAllowlistSets := getSandboxingAllowlistSets(ctx)
Cole Fauste762b942024-03-15 12:46:14 -0700954 if sandboxingAllowlistSets.sandboxingDenyModuleSet[ctx.ModuleName()] {
Yu Liu6a7940c2023-05-09 17:12:22 -0700955 return r.SandboxTools()
956 }
957 return r.SandboxInputs()
958}