blob: 4db4e8654ec9d76b24538cfd015e6968b64617db [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"
Colin Cross3d680512020-11-13 16:23:53 -080024 "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
Chris Parsonsf874e462022-05-10 13:50:12 -040028 "android/soong/bazel/cquery"
Jihoon Kangc170af42022-08-20 05:26:38 +000029
Colin Cross70b40592015-03-23 12:57:34 -070030 "github.com/google/blueprint"
Dan Willemsen8eded0a2017-09-13 16:07:44 -070031 "github.com/google/blueprint/bootstrap"
Nan Zhangea568a42017-11-08 21:20:04 -080032 "github.com/google/blueprint/proptools"
Colin Cross5049f022015-03-18 13:28:46 -070033
Colin Cross635c3b02016-05-18 15:37:25 -070034 "android/soong/android"
Jingwen Chen30f5aaa2020-11-19 05:38:02 -050035 "android/soong/bazel"
Colin Cross5049f022015-03-18 13:28:46 -070036)
37
Colin Cross463a90e2015-06-17 14:20:06 -070038func init() {
Colin Crosse9fe2942020-11-10 18:12:15 -080039 RegisterGenruleBuildComponents(android.InitRegistrationContext)
Martin Stjernholm710ec3a2020-01-16 15:12:04 +000040}
Jaewoong Jung98716bd2018-12-10 08:13:18 -080041
Paul Duffin672cb9f2021-03-03 02:30:37 +000042// Test fixture preparer that will register most genrule build components.
43//
44// Singletons and mutators should only be added here if they are needed for a majority of genrule
45// module types, otherwise they should be added under a separate preparer to allow them to be
46// selected only when needed to reduce test execution time.
47//
48// Module types do not have much of an overhead unless they are used so this should include as many
49// module types as possible. The exceptions are those module types that require mutators and/or
50// singletons in order to function in which case they should be kept together in a separate
51// preparer.
52var PrepareForTestWithGenRuleBuildComponents = android.GroupFixturePreparers(
53 android.FixtureRegisterWithContext(RegisterGenruleBuildComponents),
54)
55
56// Prepare a fixture to use all genrule module types, mutators and singletons fully.
57//
58// This should only be used by tests that want to run with as much of the build enabled as possible.
59var PrepareForIntegrationTestWithGenrule = android.GroupFixturePreparers(
60 PrepareForTestWithGenRuleBuildComponents,
61)
62
Colin Crosse9fe2942020-11-10 18:12:15 -080063func RegisterGenruleBuildComponents(ctx android.RegistrationContext) {
Martin Stjernholm710ec3a2020-01-16 15:12:04 +000064 ctx.RegisterModuleType("genrule_defaults", defaultsFactory)
65
66 ctx.RegisterModuleType("gensrcs", GenSrcsFactory)
67 ctx.RegisterModuleType("genrule", GenRuleFactory)
68
69 ctx.FinalDepsMutators(func(ctx android.RegisterMutatorsContext) {
70 ctx.BottomUp("genrule_tool_deps", toolDepsMutator).Parallel()
71 })
Liz Kammer356f7d42021-01-26 09:18:53 -050072}
73
Colin Cross5049f022015-03-18 13:28:46 -070074var (
Colin Cross635c3b02016-05-18 15:37:25 -070075 pctx = android.NewPackageContext("android/soong/genrule")
Colin Cross1a527682019-09-23 15:55:30 -070076
Alex Humesky29e3bbe2020-11-20 21:30:13 -050077 // Used by gensrcs when there is more than 1 shard to merge the outputs
78 // of each shard into a zip file.
Colin Cross1a527682019-09-23 15:55:30 -070079 gensrcsMerge = pctx.AndroidStaticRule("gensrcsMerge", blueprint.RuleParams{
80 Command: "${soongZip} -o ${tmpZip} @${tmpZip}.rsp && ${zipSync} -d ${genDir} ${tmpZip}",
81 CommandDeps: []string{"${soongZip}", "${zipSync}"},
82 Rspfile: "${tmpZip}.rsp",
83 RspfileContent: "${zipArgs}",
84 }, "tmpZip", "genDir", "zipArgs")
Colin Cross5049f022015-03-18 13:28:46 -070085)
86
Jeff Gastonefc1b412017-03-29 17:29:06 -070087func init() {
Dan Willemsenddf504c2019-08-09 16:21:29 -070088 pctx.Import("android/soong/android")
Colin Cross1a527682019-09-23 15:55:30 -070089
90 pctx.HostBinToolVariable("soongZip", "soong_zip")
91 pctx.HostBinToolVariable("zipSync", "zipsync")
Jeff Gastonefc1b412017-03-29 17:29:06 -070092}
93
Colin Cross5049f022015-03-18 13:28:46 -070094type SourceFileGenerator interface {
Colin Cross635c3b02016-05-18 15:37:25 -070095 GeneratedSourceFiles() android.Paths
Colin Cross5ed99c62016-11-22 12:55:55 -080096 GeneratedHeaderDirs() android.Paths
Dan Willemsen9da9d492018-02-21 18:28:18 -080097 GeneratedDeps() android.Paths
Colin Cross5049f022015-03-18 13:28:46 -070098}
99
Colin Crossfe17f6f2019-03-28 19:30:56 -0700100// Alias for android.HostToolProvider
101// Deprecated: use android.HostToolProvider instead.
Colin Crossd350ecd2015-04-28 13:25:36 -0700102type HostToolProvider interface {
Colin Crossfe17f6f2019-03-28 19:30:56 -0700103 android.HostToolProvider
Colin Crossd350ecd2015-04-28 13:25:36 -0700104}
Colin Cross5049f022015-03-18 13:28:46 -0700105
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700106type hostToolDependencyTag struct {
107 blueprint.BaseDependencyTag
Colin Cross65cb3142021-12-10 23:05:02 +0000108 android.LicenseAnnotationToolchainDependencyTag
Colin Cross08f15ab2018-10-04 23:29:14 -0700109 label string
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700110}
Martin Stjernholmdbd814d2022-01-12 23:18:30 +0000111
112func (t hostToolDependencyTag) AllowDisabledModuleDependency(target android.Module) bool {
113 // Allow depending on a disabled module if it's replaced by a prebuilt
114 // counterpart. We get the prebuilt through android.PrebuiltGetPreferred in
115 // GenerateAndroidBuildActions.
116 return target.IsReplacedByPrebuilt()
117}
118
119var _ android.AllowDisabledModuleDependency = (*hostToolDependencyTag)(nil)
120
Colin Cross7d5136f2015-05-11 13:39:40 -0700121type generatorProperties struct {
Spandan Das93e95992021-07-29 18:26:39 +0000122 // The command to run on one or more input files. Cmd supports substitution of a few variables.
Jeff Gastonefc1b412017-03-29 17:29:06 -0700123 //
124 // Available variables for substitution:
125 //
Spandan Das93e95992021-07-29 18:26:39 +0000126 // $(location): the path to the first entry in tools or tool_files.
127 // $(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.
128 // $(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.
129 // $(in): one or more input files.
130 // $(out): a single output file.
131 // $(depfile): a file to which dependencies will be written, if the depfile property is set to true.
132 // $(genDir): the sandbox directory for this tool; contains $(out).
Colin Cross2296f5b2017-10-17 21:38:14 -0700133 // $$: a literal $
Nan Zhangea568a42017-11-08 21:20:04 -0800134 Cmd *string
Colin Cross7d5136f2015-05-11 13:39:40 -0700135
Colin Cross33bfb0a2016-11-21 17:23:08 -0800136 // Enable reading a file containing dependencies in gcc format after the command completes
Nan Zhangea568a42017-11-08 21:20:04 -0800137 Depfile *bool
Colin Cross33bfb0a2016-11-21 17:23:08 -0800138
Colin Cross6f080df2016-11-04 15:32:58 -0700139 // name of the modules (if any) that produces the host executable. Leave empty for
Colin Cross7d5136f2015-05-11 13:39:40 -0700140 // prebuilts or scripts that do not need a module to build them.
Colin Cross6f080df2016-11-04 15:32:58 -0700141 Tools []string
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700142
Sam Delmericof8775632023-08-14 23:45:41 +0000143 // Local files that are used by the tool
Colin Cross27b922f2019-03-04 22:35:41 -0800144 Tool_files []string `android:"path"`
Colin Cross5ed99c62016-11-22 12:55:55 -0800145
146 // List of directories to export generated headers from
147 Export_include_dirs []string
Colin Cross708c4242017-01-13 18:05:49 -0800148
149 // list of input files
Colin Cross27b922f2019-03-04 22:35:41 -0800150 Srcs []string `android:"path,arch_variant"`
Dan Willemseneefa0262018-11-17 14:01:18 -0800151
152 // input files to exclude
Colin Cross27b922f2019-03-04 22:35:41 -0800153 Exclude_srcs []string `android:"path,arch_variant"`
Justin Yun4da4ccc2023-07-06 10:56:29 +0900154
155 // Enable restat to update the output only if the output is changed
156 Write_if_changed *bool
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400157}
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500158
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700159type Module struct {
Colin Cross635c3b02016-05-18 15:37:25 -0700160 android.ModuleBase
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800161 android.DefaultableModuleBase
Liz Kammerea6666f2021-02-17 10:17:28 -0500162 android.BazelModuleBase
Jiyong Parkfc752ca2019-06-12 13:27:29 +0900163 android.ApexModuleBase
Colin Crossd350ecd2015-04-28 13:25:36 -0700164
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700165 // For other packages to make their own genrules with extra
166 // properties
167 Extra interface{}
Colin Crossf3bfd022021-09-27 15:15:06 -0700168
169 // CmdModifier can be set by wrappers around genrule to modify the command, for example to
170 // prefix environment variables to it.
171 CmdModifier func(ctx android.ModuleContext, cmd string) string
172
Colin Cross7228ecd2019-11-18 16:00:16 -0800173 android.ImageInterface
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700174
Colin Cross7d5136f2015-05-11 13:39:40 -0700175 properties generatorProperties
Colin Crossd350ecd2015-04-28 13:25:36 -0700176
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500177 // For the different tasks that genrule and gensrc generate. genrule will
178 // generate 1 task, and gensrc will generate 1 or more tasks based on the
179 // number of shards the input files are sharded into.
Jeff Gaston437d23c2017-11-08 12:38:00 -0800180 taskGenerator taskFunc
Colin Crossd350ecd2015-04-28 13:25:36 -0700181
Colin Cross1a527682019-09-23 15:55:30 -0700182 rule blueprint.Rule
183 rawCommands []string
Colin Crossd350ecd2015-04-28 13:25:36 -0700184
Colin Cross5ed99c62016-11-22 12:55:55 -0800185 exportedIncludeDirs android.Paths
Dan Willemsenb40aab62016-04-20 14:21:14 -0700186
Colin Cross635c3b02016-05-18 15:37:25 -0700187 outputFiles android.Paths
Dan Willemsen9da9d492018-02-21 18:28:18 -0800188 outputDeps android.Paths
Colin Crossa4ad2b02019-03-18 22:15:32 -0700189
190 subName string
Colin Cross1a527682019-09-23 15:55:30 -0700191 subDir string
Colin Crossd350ecd2015-04-28 13:25:36 -0700192}
193
Chris Parsonsf874e462022-05-10 13:50:12 -0400194var _ android.MixedBuildBuildable = (*Module)(nil)
195
Colin Cross1a527682019-09-23 15:55:30 -0700196type taskFunc func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask
Colin Crossd350ecd2015-04-28 13:25:36 -0700197
198type generateTask struct {
Liz Kammer81fec182023-06-09 13:33:45 -0400199 in android.Paths
200 out android.WritablePaths
201 depFile android.WritablePath
202 copyTo android.WritablePaths // For gensrcs to set on gensrcsMerge rule.
203 genDir android.WritablePath
204 extraTools android.Paths // dependencies on tools used by the generator
205 extraInputs map[string][]string
Colin Cross3ea4eb82020-11-24 13:07:27 -0800206
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500207 cmd string
208 // For gensrsc sharding.
Colin Cross3ea4eb82020-11-24 13:07:27 -0800209 shard int
210 shards int
Colin Crossd350ecd2015-04-28 13:25:36 -0700211}
212
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700213func (g *Module) GeneratedSourceFiles() android.Paths {
Colin Crossd350ecd2015-04-28 13:25:36 -0700214 return g.outputFiles
215}
216
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700217func (g *Module) Srcs() android.Paths {
Nan Zhange42777a2018-03-27 16:19:42 -0700218 return append(android.Paths{}, g.outputFiles...)
Colin Cross068e0fe2016-12-13 15:23:47 -0800219}
220
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700221func (g *Module) GeneratedHeaderDirs() android.Paths {
Colin Cross5ed99c62016-11-22 12:55:55 -0800222 return g.exportedIncludeDirs
Dan Willemsenb40aab62016-04-20 14:21:14 -0700223}
224
Dan Willemsen9da9d492018-02-21 18:28:18 -0800225func (g *Module) GeneratedDeps() android.Paths {
226 return g.outputDeps
227}
228
Jooyung Han8c7e3ed2021-06-28 17:35:58 +0900229func (g *Module) OutputFiles(tag string) (android.Paths, error) {
230 if tag == "" {
231 return append(android.Paths{}, g.outputFiles...), nil
232 }
233 // otherwise, tag should match one of outputs
234 for _, outputFile := range g.outputFiles {
235 if outputFile.Rel() == tag {
236 return android.Paths{outputFile}, nil
237 }
238 }
239 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
240}
241
242var _ android.SourceFileProducer = (*Module)(nil)
243var _ android.OutputFileProducer = (*Module)(nil)
244
Martin Stjernholm710ec3a2020-01-16 15:12:04 +0000245func toolDepsMutator(ctx android.BottomUpMutatorContext) {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700246 if g, ok := ctx.Module().(*Module); ok {
Colin Cross08f15ab2018-10-04 23:29:14 -0700247 for _, tool := range g.properties.Tools {
248 tag := hostToolDependencyTag{label: tool}
249 if m := android.SrcIsModule(tool); m != "" {
250 tool = m
251 }
Colin Cross0f7d2ef2019-10-16 11:03:10 -0700252 ctx.AddFarVariationDependencies(ctx.Config().BuildOSTarget.Variations(), tag, tool)
Colin Cross6362e272015-10-29 15:25:03 -0700253 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700254 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700255}
256
Chris Parsonsf874e462022-05-10 13:50:12 -0400257func (g *Module) ProcessBazelQueryResponse(ctx android.ModuleContext) {
258 g.generateCommonBuildActions(ctx)
259
260 label := g.GetBazelLabel(ctx, g)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400261 bazelCtx := ctx.Config().BazelContext
Chris Parsonsf874e462022-05-10 13:50:12 -0400262 filePaths, err := bazelCtx.GetOutputFiles(label, android.GetConfigKey(ctx))
263 if err != nil {
264 ctx.ModuleErrorf(err.Error())
265 return
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400266 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400267
268 var bazelOutputFiles android.Paths
269 exportIncludeDirs := map[string]bool{}
270 for _, bazelOutputFile := range filePaths {
Cole Faust01243362022-06-02 12:11:12 -0700271 bazelOutputFiles = append(bazelOutputFiles, android.PathForBazelOutRelative(ctx, ctx.ModuleDir(), bazelOutputFile))
Chris Parsonsf874e462022-05-10 13:50:12 -0400272 exportIncludeDirs[filepath.Dir(bazelOutputFile)] = true
273 }
274 g.outputFiles = bazelOutputFiles
275 g.outputDeps = bazelOutputFiles
276 for includePath, _ := range exportIncludeDirs {
277 g.exportedIncludeDirs = append(g.exportedIncludeDirs, android.PathForBazelOut(ctx, includePath))
278 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400279}
Colin Crossf1885962020-11-20 15:28:30 -0800280
Chris Parsonsf874e462022-05-10 13:50:12 -0400281// generateCommonBuildActions contains build action generation logic
282// common to both the mixed build case and the legacy case of genrule processing.
283// To fully support genrule in mixed builds, the contents of this function should
284// approach zero; there should be no genrule action registration done directly
285// by Soong logic in the mixed-build case.
286func (g *Module) generateCommonBuildActions(ctx android.ModuleContext) {
Colin Crossa4ad2b02019-03-18 22:15:32 -0700287 g.subName = ctx.ModuleSubDir()
288
Colin Cross5ed99c62016-11-22 12:55:55 -0800289 if len(g.properties.Export_include_dirs) > 0 {
290 for _, dir := range g.properties.Export_include_dirs {
291 g.exportedIncludeDirs = append(g.exportedIncludeDirs,
Colin Cross1a527682019-09-23 15:55:30 -0700292 android.PathForModuleGen(ctx, g.subDir, ctx.ModuleDir(), dir))
Liz Kammerd38c87c2023-07-17 09:58:50 -0400293 // Also export without ModuleDir for consistency with Export_include_dirs not being set
294 g.exportedIncludeDirs = append(g.exportedIncludeDirs,
295 android.PathForModuleGen(ctx, g.subDir, dir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800296 }
297 } else {
Colin Cross1a527682019-09-23 15:55:30 -0700298 g.exportedIncludeDirs = append(g.exportedIncludeDirs, android.PathForModuleGen(ctx, g.subDir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800299 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700300
Colin Crossd11cf622021-03-23 22:30:35 -0700301 locationLabels := map[string]location{}
Colin Cross08f15ab2018-10-04 23:29:14 -0700302 firstLabel := ""
303
Colin Crossd11cf622021-03-23 22:30:35 -0700304 addLocationLabel := func(label string, loc location) {
Colin Cross08f15ab2018-10-04 23:29:14 -0700305 if firstLabel == "" {
306 firstLabel = label
307 }
308 if _, exists := locationLabels[label]; !exists {
Colin Crossd11cf622021-03-23 22:30:35 -0700309 locationLabels[label] = loc
Colin Cross08f15ab2018-10-04 23:29:14 -0700310 } else {
Anton Hansson7cd41e52021-10-08 16:13:10 +0100311 ctx.ModuleErrorf("multiple locations for label %q: %q and %q (do you have duplicate srcs entries?)",
Colin Crossd11cf622021-03-23 22:30:35 -0700312 label, locationLabels[label], loc)
Colin Cross08f15ab2018-10-04 23:29:14 -0700313 }
314 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700315
Colin Crossba9e4032020-11-24 16:32:22 -0800316 var tools android.Paths
317 var packagedTools []android.PackagingSpec
Colin Cross6f080df2016-11-04 15:32:58 -0700318 if len(g.properties.Tools) > 0 {
Colin Crossba71a3f2019-03-18 12:12:48 -0700319 seenTools := make(map[string]bool)
320
Colin Cross35143d02017-11-16 00:11:20 -0800321 ctx.VisitDirectDepsBlueprint(func(module blueprint.Module) {
Colin Cross08f15ab2018-10-04 23:29:14 -0700322 switch tag := ctx.OtherModuleDependencyTag(module).(type) {
323 case hostToolDependencyTag:
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700324 tool := ctx.OtherModuleName(module)
Martin Stjernholmdbd814d2022-01-12 23:18:30 +0000325 if m, ok := module.(android.Module); ok {
326 // Necessary to retrieve any prebuilt replacement for the tool, since
327 // toolDepsMutator runs too late for the prebuilt mutators to have
328 // replaced the dependency.
329 module = android.PrebuiltGetPreferred(ctx, m)
330 }
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700331
Colin Crossba9e4032020-11-24 16:32:22 -0800332 switch t := module.(type) {
333 case android.HostToolProvider:
334 // A HostToolProvider provides the path to a tool, which will be copied
335 // into the sandbox.
Colin Cross35143d02017-11-16 00:11:20 -0800336 if !t.(android.Module).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 }
Colin Crossba9e4032020-11-24 16:32:22 -0800344 path := t.HostToolPath()
345 if !path.Valid() {
346 ctx.ModuleErrorf("host tool %q missing output file", tool)
347 return
348 }
349 if specs := t.TransitivePackagingSpecs(); specs != nil {
350 // If the HostToolProvider has PackgingSpecs, which are definitions of the
351 // required relative locations of the tool and its dependencies, use those
352 // instead. They will be copied to those relative locations in the sbox
353 // sandbox.
354 packagedTools = append(packagedTools, specs...)
355 // Assume that the first PackagingSpec of the module is the tool.
Colin Crossd11cf622021-03-23 22:30:35 -0700356 addLocationLabel(tag.label, packagedToolLocation{specs[0]})
Colin Crossba9e4032020-11-24 16:32:22 -0800357 } else {
358 tools = append(tools, path.Path())
Colin Crossd11cf622021-03-23 22:30:35 -0700359 addLocationLabel(tag.label, toolLocation{android.Paths{path.Path()}})
Colin Crossba9e4032020-11-24 16:32:22 -0800360 }
361 case bootstrap.GoBinaryTool:
362 // A GoBinaryTool provides the install path to a tool, which will be copied.
Colin Crossa44551f2021-10-25 15:36:21 -0700363 p := android.PathForGoBinary(ctx, t)
364 tools = append(tools, p)
365 addLocationLabel(tag.label, toolLocation{android.Paths{p}})
Colin Crossba9e4032020-11-24 16:32:22 -0800366 default:
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700367 ctx.ModuleErrorf("%q is not a host tool provider", tool)
Colin Crossba9e4032020-11-24 16:32:22 -0800368 return
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700369 }
370
Colin Crossba9e4032020-11-24 16:32:22 -0800371 seenTools[tag.label] = true
Colin Crossd350ecd2015-04-28 13:25:36 -0700372 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700373 })
Colin Crossba71a3f2019-03-18 12:12:48 -0700374
375 // If AllowMissingDependencies is enabled, the build will not have stopped when
376 // AddFarVariationDependencies was called on a missing tool, which will result in nonsensical
Liz Kammer20ebfb42020-07-28 11:32:07 -0700377 // "cmd: unknown location label ..." errors later. Add a placeholder file to the local label.
378 // The command that uses this placeholder file will never be executed because the rule will be
379 // replaced with an android.Error rule reporting the missing dependencies.
Colin Crossba71a3f2019-03-18 12:12:48 -0700380 if ctx.Config().AllowMissingDependencies() {
381 for _, tool := range g.properties.Tools {
382 if !seenTools[tool] {
Colin Crossd11cf622021-03-23 22:30:35 -0700383 addLocationLabel(tool, errorLocation{"***missing tool " + tool + "***"})
Colin Crossba71a3f2019-03-18 12:12:48 -0700384 }
385 }
386 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700387 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700388
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700389 if ctx.Failed() {
390 return
391 }
392
Colin Cross08f15ab2018-10-04 23:29:14 -0700393 for _, toolFile := range g.properties.Tool_files {
Colin Cross8a497952019-03-05 22:25:09 -0800394 paths := android.PathsForModuleSrc(ctx, []string{toolFile})
Colin Crossba9e4032020-11-24 16:32:22 -0800395 tools = append(tools, paths...)
Colin Crossd11cf622021-03-23 22:30:35 -0700396 addLocationLabel(toolFile, toolLocation{paths})
Colin Cross08f15ab2018-10-04 23:29:14 -0700397 }
398
Liz Kammer81fec182023-06-09 13:33:45 -0400399 addLabelsForInputs := func(propName string, include, exclude []string) android.Paths {
Liz Kammer81fec182023-06-09 13:33:45 -0400400 includeDirInPaths := ctx.DeviceConfig().BuildBrokenInputDir(g.Name())
401 var srcFiles android.Paths
402 for _, in := range include {
403 paths, missingDeps := android.PathsAndMissingDepsRelativeToModuleSourceDir(android.SourceInput{
404 Context: ctx, Paths: []string{in}, ExcludePaths: exclude, IncludeDirs: includeDirInPaths,
405 })
406 if len(missingDeps) > 0 {
407 if !ctx.Config().AllowMissingDependencies() {
408 panic(fmt.Errorf("should never get here, the missing dependencies %q should have been reported in DepsMutator",
409 missingDeps))
410 }
411
412 // If AllowMissingDependencies is enabled, the build will not have stopped when
413 // the dependency was added on a missing SourceFileProducer module, which will result in nonsensical
414 // "cmd: label ":..." has no files" errors later. Add a placeholder file to the local label.
415 // The command that uses this placeholder file will never be executed because the rule will be
416 // replaced with an android.Error rule reporting the missing dependencies.
417 ctx.AddMissingDependencies(missingDeps)
418 addLocationLabel(in, errorLocation{"***missing " + propName + " " + in + "***"})
419 } else {
420 srcFiles = append(srcFiles, paths...)
421 addLocationLabel(in, inputLocation{paths})
422 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700423 }
Liz Kammer81fec182023-06-09 13:33:45 -0400424 return srcFiles
Colin Cross08f15ab2018-10-04 23:29:14 -0700425 }
Liz Kammer81fec182023-06-09 13:33:45 -0400426 srcFiles := addLabelsForInputs("srcs", g.properties.Srcs, g.properties.Exclude_srcs)
Aditya Choudhary26df39f2023-11-29 16:42:42 +0000427 ctx.SetProvider(blueprint.SrcsFileProviderKey, blueprint.SrcsFileProviderData{SrcPaths: srcFiles.Strings()})
Colin Cross08f15ab2018-10-04 23:29:14 -0700428
Colin Cross1a527682019-09-23 15:55:30 -0700429 var copyFrom android.Paths
430 var outputFiles android.WritablePaths
431 var zipArgs strings.Builder
Colin Cross08f15ab2018-10-04 23:29:14 -0700432
Colin Crossf3bfd022021-09-27 15:15:06 -0700433 cmd := String(g.properties.Cmd)
434 if g.CmdModifier != nil {
435 cmd = g.CmdModifier(ctx, cmd)
436 }
437
Liz Kammer796921d2023-07-11 08:21:41 -0400438 var extraInputs android.Paths
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500439 // Generate tasks, either from genrule or gensrcs.
Liz Kammer81fec182023-06-09 13:33:45 -0400440 for i, task := range g.taskGenerator(ctx, cmd, srcFiles) {
Colin Cross3d680512020-11-13 16:23:53 -0800441 if len(task.out) == 0 {
442 ctx.ModuleErrorf("must have at least one output file")
443 return
Colin Cross85a2e892018-07-09 09:45:06 -0700444 }
445
Liz Kammer81fec182023-06-09 13:33:45 -0400446 // Only handle extra inputs once as these currently are the same across all tasks
447 if i == 0 {
448 for name, values := range task.extraInputs {
449 extraInputs = append(extraInputs, addLabelsForInputs(name, values, []string{})...)
450 }
451 }
452
Colin Crossf1a035e2020-11-16 17:32:30 -0800453 // Pick a unique path outside the task.genDir for the sbox manifest textproto,
454 // a unique rule name, and the user-visible description.
455 manifestName := "genrule.sbox.textproto"
456 desc := "generate"
457 name := "generator"
458 if task.shards > 0 {
459 manifestName = "genrule_" + strconv.Itoa(task.shard) + ".sbox.textproto"
460 desc += " " + strconv.Itoa(task.shard)
461 name += strconv.Itoa(task.shard)
462 } else if len(task.out) == 1 {
463 desc += " " + task.out[0].Base()
464 }
465
466 manifestPath := android.PathForModuleOut(ctx, manifestName)
467
468 // Use a RuleBuilder to create a rule that runs the command inside an sbox sandbox.
Yu Liu6a7940c2023-05-09 17:12:22 -0700469 rule := getSandboxedRuleBuilder(ctx, android.NewRuleBuilder(pctx, ctx).Sbox(task.genDir, manifestPath))
Justin Yun4da4ccc2023-07-06 10:56:29 +0900470 if Bool(g.properties.Write_if_changed) {
471 rule.Restat()
472 }
Colin Crossf1a035e2020-11-16 17:32:30 -0800473 cmd := rule.Command()
474
Colin Cross3d680512020-11-13 16:23:53 -0800475 for _, out := range task.out {
Colin Crossd11cf622021-03-23 22:30:35 -0700476 addLocationLabel(out.Rel(), outputLocation{out})
Colin Cross3d680512020-11-13 16:23:53 -0800477 }
478
Colin Cross1a527682019-09-23 15:55:30 -0700479 referencedDepfile := false
480
Colin Cross3d680512020-11-13 16:23:53 -0800481 rawCommand, err := android.Expand(task.cmd, func(name string) (string, error) {
Colin Cross1a527682019-09-23 15:55:30 -0700482 // report the error directly without returning an error to android.Expand to catch multiple errors in a
483 // single run
Colin Cross3d680512020-11-13 16:23:53 -0800484 reportError := func(fmt string, args ...interface{}) (string, error) {
Colin Cross1a527682019-09-23 15:55:30 -0700485 ctx.PropertyErrorf("cmd", fmt, args...)
Colin Cross3d680512020-11-13 16:23:53 -0800486 return "SOONG_ERROR", nil
Colin Cross6f080df2016-11-04 15:32:58 -0700487 }
Colin Cross1a527682019-09-23 15:55:30 -0700488
Jihoon Kangc170af42022-08-20 05:26:38 +0000489 // Apply shell escape to each cases to prevent source file paths containing $ from being evaluated in shell
Colin Cross1a527682019-09-23 15:55:30 -0700490 switch name {
491 case "location":
492 if len(g.properties.Tools) == 0 && len(g.properties.Tool_files) == 0 {
493 return reportError("at least one `tools` or `tool_files` is required if $(location) is used")
Colin Cross6f080df2016-11-04 15:32:58 -0700494 }
Colin Crossd11cf622021-03-23 22:30:35 -0700495 loc := locationLabels[firstLabel]
496 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700497 if len(paths) == 0 {
498 return reportError("default label %q has no files", firstLabel)
499 } else if len(paths) > 1 {
500 return reportError("default label %q has multiple files, use $(locations %s) to reference it",
501 firstLabel, firstLabel)
Colin Cross08f15ab2018-10-04 23:29:14 -0700502 }
Jihoon Kangc170af42022-08-20 05:26:38 +0000503 return proptools.ShellEscape(paths[0]), nil
Colin Cross1a527682019-09-23 15:55:30 -0700504 case "in":
Jihoon Kangc170af42022-08-20 05:26:38 +0000505 return strings.Join(proptools.ShellEscapeList(cmd.PathsForInputs(srcFiles)), " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700506 case "out":
Colin Cross3d680512020-11-13 16:23:53 -0800507 var sandboxOuts []string
508 for _, out := range task.out {
Colin Crossf1a035e2020-11-16 17:32:30 -0800509 sandboxOuts = append(sandboxOuts, cmd.PathForOutput(out))
Colin Cross3d680512020-11-13 16:23:53 -0800510 }
Jihoon Kangc170af42022-08-20 05:26:38 +0000511 return strings.Join(proptools.ShellEscapeList(sandboxOuts), " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700512 case "depfile":
513 referencedDepfile = true
514 if !Bool(g.properties.Depfile) {
515 return reportError("$(depfile) used without depfile property")
516 }
Colin Cross3d680512020-11-13 16:23:53 -0800517 return "__SBOX_DEPFILE__", nil
Colin Cross1a527682019-09-23 15:55:30 -0700518 case "genDir":
Jihoon Kangc170af42022-08-20 05:26:38 +0000519 return proptools.ShellEscape(cmd.PathForOutput(task.genDir)), nil
Colin Cross1a527682019-09-23 15:55:30 -0700520 default:
521 if strings.HasPrefix(name, "location ") {
522 label := strings.TrimSpace(strings.TrimPrefix(name, "location "))
Colin Crossd11cf622021-03-23 22:30:35 -0700523 if loc, ok := locationLabels[label]; ok {
524 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700525 if len(paths) == 0 {
526 return reportError("label %q has no files", label)
527 } else if len(paths) > 1 {
528 return reportError("label %q has multiple files, use $(locations %s) to reference it",
529 label, label)
530 }
Jihoon Kangc170af42022-08-20 05:26:38 +0000531 return proptools.ShellEscape(paths[0]), nil
Colin Cross1a527682019-09-23 15:55:30 -0700532 } else {
Anton Hanssonbebf5262022-02-23 11:42:38 +0000533 return reportError("unknown location label %q is not in srcs, out, tools or tool_files.", label)
Colin Cross1a527682019-09-23 15:55:30 -0700534 }
535 } else if strings.HasPrefix(name, "locations ") {
536 label := strings.TrimSpace(strings.TrimPrefix(name, "locations "))
Colin Crossd11cf622021-03-23 22:30:35 -0700537 if loc, ok := locationLabels[label]; ok {
538 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700539 if len(paths) == 0 {
540 return reportError("label %q has no files", label)
541 }
Cole Faustce74a592023-12-07 14:58:45 -0800542 return strings.Join(proptools.ShellEscapeList(paths), " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700543 } else {
Anton Hanssonbebf5262022-02-23 11:42:38 +0000544 return reportError("unknown locations label %q is not in srcs, out, tools or tool_files.", label)
Colin Cross1a527682019-09-23 15:55:30 -0700545 }
546 } else {
547 return reportError("unknown variable '$(%s)'", name)
548 }
Colin Cross6f080df2016-11-04 15:32:58 -0700549 }
Colin Cross1a527682019-09-23 15:55:30 -0700550 })
551
552 if err != nil {
553 ctx.PropertyErrorf("cmd", "%s", err.Error())
554 return
Colin Cross6f080df2016-11-04 15:32:58 -0700555 }
Colin Cross6f080df2016-11-04 15:32:58 -0700556
Colin Cross1a527682019-09-23 15:55:30 -0700557 if Bool(g.properties.Depfile) && !referencedDepfile {
558 ctx.PropertyErrorf("cmd", "specified depfile=true but did not include a reference to '${depfile}' in cmd")
559 return
560 }
Colin Cross1a527682019-09-23 15:55:30 -0700561 g.rawCommands = append(g.rawCommands, rawCommand)
Bill Peckhamc087be12020-02-13 15:55:10 -0800562
Colin Cross3d680512020-11-13 16:23:53 -0800563 cmd.Text(rawCommand)
Liz Kammer81fec182023-06-09 13:33:45 -0400564 cmd.Implicits(srcFiles) // need to be able to reference other srcs
565 cmd.Implicits(extraInputs)
Colin Cross3d680512020-11-13 16:23:53 -0800566 cmd.ImplicitOutputs(task.out)
567 cmd.Implicits(task.in)
Colin Crossba9e4032020-11-24 16:32:22 -0800568 cmd.ImplicitTools(tools)
569 cmd.ImplicitTools(task.extraTools)
570 cmd.ImplicitPackagedTools(packagedTools)
Colin Cross3d680512020-11-13 16:23:53 -0800571 if Bool(g.properties.Depfile) {
572 cmd.ImplicitDepFile(task.depFile)
573 }
574
575 // Create the rule to run the genrule command inside sbox.
Colin Crossf1a035e2020-11-16 17:32:30 -0800576 rule.Build(name, desc)
Colin Cross1a527682019-09-23 15:55:30 -0700577
578 if len(task.copyTo) > 0 {
Colin Cross3d680512020-11-13 16:23:53 -0800579 // If copyTo is set, multiple shards need to be copied into a single directory.
580 // task.out contains the per-shard paths, and copyTo contains the corresponding
581 // final path. The files need to be copied into the final directory by a
582 // single rule so it can remove the directory before it starts to ensure no
583 // old files remain. zipsync already does this, so build up zipArgs that
584 // zip all the per-shard directories into a single zip.
Colin Cross1a527682019-09-23 15:55:30 -0700585 outputFiles = append(outputFiles, task.copyTo...)
586 copyFrom = append(copyFrom, task.out.Paths()...)
587 zipArgs.WriteString(" -C " + task.genDir.String())
588 zipArgs.WriteString(android.JoinWithPrefix(task.out.Strings(), " -f "))
589 } else {
590 outputFiles = append(outputFiles, task.out...)
591 }
Colin Cross6f080df2016-11-04 15:32:58 -0700592 }
593
Colin Cross1a527682019-09-23 15:55:30 -0700594 if len(copyFrom) > 0 {
Colin Cross3d680512020-11-13 16:23:53 -0800595 // Create a rule that zips all the per-shard directories into a single zip and then
596 // uses zipsync to unzip it into the final directory.
Colin Cross1a527682019-09-23 15:55:30 -0700597 ctx.Build(pctx, android.BuildParams{
Colin Crossf1885962020-11-20 15:28:30 -0800598 Rule: gensrcsMerge,
599 Implicits: copyFrom,
600 Outputs: outputFiles,
601 Description: "merge shards",
Colin Cross1a527682019-09-23 15:55:30 -0700602 Args: map[string]string{
603 "zipArgs": zipArgs.String(),
604 "tmpZip": android.PathForModuleGen(ctx, g.subDir+".zip").String(),
605 "genDir": android.PathForModuleGen(ctx, g.subDir).String(),
606 },
607 })
Colin Cross85a2e892018-07-09 09:45:06 -0700608 }
609
Colin Cross1a527682019-09-23 15:55:30 -0700610 g.outputFiles = outputFiles.Paths()
Chris Parsonsf874e462022-05-10 13:50:12 -0400611}
Jeff Gastonefc1b412017-03-29 17:29:06 -0700612
Chris Parsonsf874e462022-05-10 13:50:12 -0400613func (g *Module) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Vinh Tran140d5882022-06-10 14:23:27 -0400614 // Allowlist genrule to use depfile until we have a solution to remove it.
615 // TODO(b/235582219): Remove allowlist for genrule
Yu Liu6a7940c2023-05-09 17:12:22 -0700616 if Bool(g.properties.Depfile) {
Yu Liue7f7cbf2023-06-13 18:50:03 +0000617 sandboxingAllowlistSets := getSandboxingAllowlistSets(ctx)
Yu Liu6a7940c2023-05-09 17:12:22 -0700618 // TODO(b/283852474): Checking the GenruleSandboxing flag is temporary in
619 // order to pass the presubmit before internal master is updated.
Yu Liue7f7cbf2023-06-13 18:50:03 +0000620 if ctx.DeviceConfig().GenruleSandboxing() && !sandboxingAllowlistSets.depfileAllowSet[g.Name()] {
Yu Liu6a7940c2023-05-09 17:12:22 -0700621 ctx.PropertyErrorf(
622 "depfile",
623 "Deprecated to ensure the module type is convertible to Bazel. "+
624 "Try specifying the dependencies explicitly so that there is no need to use depfile. "+
625 "If not possible, the escape hatch is to add the module to allowlists.go to bypass the error.")
626 }
Vinh Tran140d5882022-06-10 14:23:27 -0400627 }
628
Chris Parsonsf874e462022-05-10 13:50:12 -0400629 g.generateCommonBuildActions(ctx)
630
631 // For <= 6 outputs, just embed those directly in the users. Right now, that covers >90% of
632 // the genrules on AOSP. That will make things simpler to look at the graph in the common
633 // case. For larger sets of outputs, inject a phony target in between to limit ninja file
634 // growth.
635 if len(g.outputFiles) <= 6 {
636 g.outputDeps = g.outputFiles
637 } else {
638 phonyFile := android.PathForModuleGen(ctx, "genrule-phony")
639 ctx.Build(pctx, android.BuildParams{
640 Rule: blueprint.Phony,
641 Output: phonyFile,
642 Inputs: g.outputFiles,
643 })
644 g.outputDeps = android.Paths{phonyFile}
Jeff Gaston02a684b2017-10-27 14:59:27 -0700645 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400646}
647
648func (g *Module) QueueBazelCall(ctx android.BaseModuleContext) {
649 bazelCtx := ctx.Config().BazelContext
650 bazelCtx.QueueBazelRequest(g.GetBazelLabel(ctx, g), cquery.GetOutputFiles, android.GetConfigKey(ctx))
651}
652
653func (g *Module) IsMixedBuildSupported(ctx android.BaseModuleContext) bool {
654 return true
Colin Crossd350ecd2015-04-28 13:25:36 -0700655}
Colin Crossd350ecd2015-04-28 13:25:36 -0700656
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700657// Collect information for opening IDE project files in java/jdeps.go.
658func (g *Module) IDEInfo(dpInfo *android.IdeInfo) {
659 dpInfo.Srcs = append(dpInfo.Srcs, g.Srcs().Strings()...)
660 for _, src := range g.properties.Srcs {
661 if strings.HasPrefix(src, ":") {
662 src = strings.Trim(src, ":")
663 dpInfo.Deps = append(dpInfo.Deps, src)
664 }
665 }
666}
667
Colin Crossa4ad2b02019-03-18 22:15:32 -0700668func (g *Module) AndroidMk() android.AndroidMkData {
669 return android.AndroidMkData{
Anton Hansson72f18492020-10-30 16:34:45 +0000670 Class: "ETC",
Colin Crossa4ad2b02019-03-18 22:15:32 -0700671 OutputFile: android.OptionalPathForPath(g.outputFiles[0]),
672 SubName: g.subName,
673 Extra: []android.AndroidMkExtraFunc{
674 func(w io.Writer, outputFile android.Path) {
Anton Hansson72f18492020-10-30 16:34:45 +0000675 fmt.Fprintln(w, "LOCAL_UNINSTALLABLE_MODULE := true")
Colin Crossa4ad2b02019-03-18 22:15:32 -0700676 },
677 },
678 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
679 android.WriteAndroidMkData(w, data)
680 if data.SubName != "" {
681 fmt.Fprintln(w, ".PHONY:", name)
682 fmt.Fprintln(w, name, ":", name+g.subName)
683 }
684 },
685 }
686}
687
Jiyong Park45bf82e2020-12-15 22:29:02 +0900688var _ android.ApexModule = (*Module)(nil)
689
690// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -0700691func (g *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
692 sdkVersion android.ApiLevel) error {
Jooyung Han749dc692020-04-15 11:03:39 +0900693 // Because generated outputs are checked by client modules(e.g. cc_library, ...)
694 // we can safely ignore the check here.
695 return nil
696}
697
Jeff Gaston437d23c2017-11-08 12:38:00 -0800698func generatorFactory(taskGenerator taskFunc, props ...interface{}) *Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700699 module := &Module{
Jeff Gaston437d23c2017-11-08 12:38:00 -0800700 taskGenerator: taskGenerator,
Colin Crossd350ecd2015-04-28 13:25:36 -0700701 }
702
Colin Cross36242852017-06-23 15:06:31 -0700703 module.AddProperties(props...)
704 module.AddProperties(&module.properties)
Colin Crossd350ecd2015-04-28 13:25:36 -0700705
Colin Cross7228ecd2019-11-18 16:00:16 -0800706 module.ImageInterface = noopImageInterface{}
707
Colin Cross36242852017-06-23 15:06:31 -0700708 return module
Colin Crossd350ecd2015-04-28 13:25:36 -0700709}
710
Colin Cross7228ecd2019-11-18 16:00:16 -0800711type noopImageInterface struct{}
712
713func (x noopImageInterface) ImageMutatorBegin(android.BaseModuleContext) {}
714func (x noopImageInterface) CoreVariantNeeded(android.BaseModuleContext) bool { return false }
Yifan Hong1b3348d2020-01-21 15:53:22 -0800715func (x noopImageInterface) RamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700716func (x noopImageInterface) VendorRamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Inseob Kim08758f02021-04-08 21:13:22 +0900717func (x noopImageInterface) DebugRamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Colin Cross7228ecd2019-11-18 16:00:16 -0800718func (x noopImageInterface) RecoveryVariantNeeded(android.BaseModuleContext) bool { return false }
719func (x noopImageInterface) ExtraImageVariations(ctx android.BaseModuleContext) []string { return nil }
720func (x noopImageInterface) SetImageVariation(ctx android.BaseModuleContext, variation string, module android.Module) {
721}
722
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700723func NewGenSrcs() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700724 properties := &genSrcsProperties{}
725
Colin Crossf1885962020-11-20 15:28:30 -0800726 // finalSubDir is the name of the subdirectory that output files will be generated into.
727 // It is used so that per-shard directories can be placed alongside it an then finally
728 // merged into it.
729 const finalSubDir = "gensrcs"
730
Colin Cross1a527682019-09-23 15:55:30 -0700731 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Colin Cross1a527682019-09-23 15:55:30 -0700732 shardSize := defaultShardSize
733 if s := properties.Shard_size; s != nil {
734 shardSize = int(*s)
735 }
Jeff Gaston437d23c2017-11-08 12:38:00 -0800736
Colin Crossf1885962020-11-20 15:28:30 -0800737 // gensrcs rules can easily hit command line limits by repeating the command for
738 // every input file. Shard the input files into groups.
Colin Cross1a527682019-09-23 15:55:30 -0700739 shards := android.ShardPaths(srcFiles, shardSize)
740 var generateTasks []generateTask
Colin Crossbaccf5b2018-02-21 14:07:48 -0800741
Colin Cross1a527682019-09-23 15:55:30 -0700742 for i, shard := range shards {
743 var commands []string
744 var outFiles android.WritablePaths
Colin Cross3ea4eb82020-11-24 13:07:27 -0800745 var commandDepFiles []string
Colin Cross1a527682019-09-23 15:55:30 -0700746 var copyTo android.WritablePaths
Colin Cross1a527682019-09-23 15:55:30 -0700747
Colin Crossf1885962020-11-20 15:28:30 -0800748 // When sharding is enabled (i.e. len(shards) > 1), the sbox rules for each
749 // shard will be write to their own directories and then be merged together
750 // into finalSubDir. If sharding is not enabled (i.e. len(shards) == 1),
751 // the sbox rule will write directly to finalSubDir.
752 genSubDir := finalSubDir
Colin Cross1a527682019-09-23 15:55:30 -0700753 if len(shards) > 1 {
Colin Crossf1885962020-11-20 15:28:30 -0800754 genSubDir = strconv.Itoa(i)
Jeff Gaston437d23c2017-11-08 12:38:00 -0800755 }
756
Colin Crossf1885962020-11-20 15:28:30 -0800757 genDir := android.PathForModuleGen(ctx, genSubDir)
Colin Crossf1a035e2020-11-16 17:32:30 -0800758 // TODO(ccross): this RuleBuilder is a hack to be able to call
759 // rule.Command().PathForOutput. Replace this with passing the rule into the
760 // generator.
Yu Liu6a7940c2023-05-09 17:12:22 -0700761 rule := getSandboxedRuleBuilder(ctx, android.NewRuleBuilder(pctx, ctx).Sbox(genDir, nil))
Jeff Gaston437d23c2017-11-08 12:38:00 -0800762
Colin Cross3ea4eb82020-11-24 13:07:27 -0800763 for _, in := range shard {
Colin Crossf1885962020-11-20 15:28:30 -0800764 outFile := android.GenPathWithExt(ctx, finalSubDir, in, String(properties.Output_extension))
765
766 // If sharding is enabled, then outFile is the path to the output file in
767 // the shard directory, and copyTo is the path to the output file in the
768 // final directory.
Colin Cross1a527682019-09-23 15:55:30 -0700769 if len(shards) > 1 {
Colin Crossf1885962020-11-20 15:28:30 -0800770 shardFile := android.GenPathWithExt(ctx, genSubDir, in, String(properties.Output_extension))
Colin Cross1a527682019-09-23 15:55:30 -0700771 copyTo = append(copyTo, outFile)
772 outFile = shardFile
773 }
774
775 outFiles = append(outFiles, outFile)
Colin Cross1a527682019-09-23 15:55:30 -0700776
Colin Crossf1885962020-11-20 15:28:30 -0800777 // pre-expand the command line to replace $in and $out with references to
778 // a single input and output file.
Colin Cross1a527682019-09-23 15:55:30 -0700779 command, err := android.Expand(rawCommand, func(name string) (string, error) {
780 switch name {
781 case "in":
782 return in.String(), nil
783 case "out":
Colin Crossf1a035e2020-11-16 17:32:30 -0800784 return rule.Command().PathForOutput(outFile), nil
Colin Cross3ea4eb82020-11-24 13:07:27 -0800785 case "depfile":
786 // Generate a depfile for each output file. Store the list for
787 // later in order to combine them all into a single depfile.
Colin Crossf1a035e2020-11-16 17:32:30 -0800788 depFile := rule.Command().PathForOutput(outFile.ReplaceExtension(ctx, "d"))
Colin Cross3ea4eb82020-11-24 13:07:27 -0800789 commandDepFiles = append(commandDepFiles, depFile)
790 return depFile, nil
Colin Cross1a527682019-09-23 15:55:30 -0700791 default:
792 return "$(" + name + ")", nil
793 }
794 })
795 if err != nil {
796 ctx.PropertyErrorf("cmd", err.Error())
797 }
798
799 // escape the command in case for example it contains '#', an odd number of '"', etc
800 command = fmt.Sprintf("bash -c %v", proptools.ShellEscape(command))
801 commands = append(commands, command)
802 }
803 fullCommand := strings.Join(commands, " && ")
804
Colin Cross3ea4eb82020-11-24 13:07:27 -0800805 var outputDepfile android.WritablePath
806 var extraTools android.Paths
807 if len(commandDepFiles) > 0 {
808 // Each command wrote to a depfile, but ninja can only handle one
809 // depfile per rule. Use the dep_fixer tool at the end of the
810 // command to combine all the depfiles into a single output depfile.
811 outputDepfile = android.PathForModuleGen(ctx, genSubDir, "gensrcs.d")
812 depFixerTool := ctx.Config().HostToolPath(ctx, "dep_fixer")
813 fullCommand += fmt.Sprintf(" && %s -o $(depfile) %s",
Colin Crossd11cf622021-03-23 22:30:35 -0700814 rule.Command().PathForTool(depFixerTool),
Colin Crossba9e4032020-11-24 16:32:22 -0800815 strings.Join(commandDepFiles, " "))
Colin Cross3ea4eb82020-11-24 13:07:27 -0800816 extraTools = append(extraTools, depFixerTool)
817 }
818
Colin Cross1a527682019-09-23 15:55:30 -0700819 generateTasks = append(generateTasks, generateTask{
Colin Cross3ea4eb82020-11-24 13:07:27 -0800820 in: shard,
821 out: outFiles,
822 depFile: outputDepfile,
823 copyTo: copyTo,
824 genDir: genDir,
825 cmd: fullCommand,
826 shard: i,
827 shards: len(shards),
828 extraTools: extraTools,
Liz Kammer81fec182023-06-09 13:33:45 -0400829 extraInputs: map[string][]string{
830 "data": properties.Data,
831 },
Colin Cross1a527682019-09-23 15:55:30 -0700832 })
Jeff Gaston437d23c2017-11-08 12:38:00 -0800833 }
Colin Cross1a527682019-09-23 15:55:30 -0700834
835 return generateTasks
Colin Crossd350ecd2015-04-28 13:25:36 -0700836 }
837
Colin Cross1a527682019-09-23 15:55:30 -0700838 g := generatorFactory(taskGenerator, properties)
Colin Crossf1885962020-11-20 15:28:30 -0800839 g.subDir = finalSubDir
Colin Cross1a527682019-09-23 15:55:30 -0700840 return g
Colin Crossd350ecd2015-04-28 13:25:36 -0700841}
842
Colin Cross54190b32017-10-09 15:34:10 -0700843func GenSrcsFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700844 m := NewGenSrcs()
845 android.InitAndroidModule(m)
Vinh Tranb69e1ae2022-05-20 18:54:09 -0400846 android.InitBazelModule(m)
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700847 return m
848}
849
Colin Crossd350ecd2015-04-28 13:25:36 -0700850type genSrcsProperties struct {
Colin Cross7d5136f2015-05-11 13:39:40 -0700851 // extension that will be substituted for each output file
Nan Zhanga5e7cb42017-11-09 22:42:32 -0800852 Output_extension *string
Colin Cross1a527682019-09-23 15:55:30 -0700853
854 // maximum number of files that will be passed on a single command line.
855 Shard_size *int64
Liz Kammer81fec182023-06-09 13:33:45 -0400856
857 // Additional files needed for build that are not tooling related.
858 Data []string `android:"path"`
Colin Cross5049f022015-03-18 13:28:46 -0700859}
860
Vinh Tranb69e1ae2022-05-20 18:54:09 -0400861type bazelGensrcsAttributes struct {
862 Srcs bazel.LabelListAttribute
863 Output_extension *string
864 Tools bazel.LabelListAttribute
Cole Faustf0d4d4f2023-08-14 11:37:54 -0700865 Cmd bazel.StringAttribute
Liz Kammer8bd92422023-06-09 13:41:08 -0400866 Data bazel.LabelListAttribute
Vinh Tranb69e1ae2022-05-20 18:54:09 -0400867}
868
Evgenii Stepanovf47c90d2020-12-02 18:55:09 -0800869const defaultShardSize = 50
Colin Cross1a527682019-09-23 15:55:30 -0700870
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700871func NewGenRule() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700872 properties := &genRuleProperties{}
Colin Cross5049f022015-03-18 13:28:46 -0700873
Colin Cross1a527682019-09-23 15:55:30 -0700874 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700875 outs := make(android.WritablePaths, len(properties.Out))
Colin Cross3d680512020-11-13 16:23:53 -0800876 var depFile android.WritablePath
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700877 for i, out := range properties.Out {
Colin Cross3d680512020-11-13 16:23:53 -0800878 outPath := android.PathForModuleGen(ctx, out)
879 if i == 0 {
880 depFile = outPath.ReplaceExtension(ctx, "d")
881 }
882 outs[i] = outPath
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700883 }
Colin Cross1a527682019-09-23 15:55:30 -0700884 return []generateTask{{
Colin Cross3d680512020-11-13 16:23:53 -0800885 in: srcFiles,
886 out: outs,
887 depFile: depFile,
888 genDir: android.PathForModuleGen(ctx),
889 cmd: rawCommand,
Colin Cross1a527682019-09-23 15:55:30 -0700890 }}
Colin Cross5049f022015-03-18 13:28:46 -0700891 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700892
Jeff Gaston437d23c2017-11-08 12:38:00 -0800893 return generatorFactory(taskGenerator, properties)
Colin Cross5049f022015-03-18 13:28:46 -0700894}
895
Colin Cross54190b32017-10-09 15:34:10 -0700896func GenRuleFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700897 m := NewGenRule()
898 android.InitAndroidModule(m)
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800899 android.InitDefaultableModule(m)
Liz Kammerea6666f2021-02-17 10:17:28 -0500900 android.InitBazelModule(m)
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700901 return m
902}
903
Colin Crossd350ecd2015-04-28 13:25:36 -0700904type genRuleProperties struct {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700905 // names of the output files that will be generated
Yu Liud6201012022-10-17 12:29:15 -0700906 Out []string
Colin Cross5049f022015-03-18 13:28:46 -0700907}
Nan Zhangea568a42017-11-08 21:20:04 -0800908
Romain Jobredeaux9973ace2023-08-30 00:27:09 -0400909type BazelGenruleAttributes struct {
Jingwen Chen07027912021-03-15 06:02:43 -0400910 Srcs bazel.LabelListAttribute
Jingwen Chen316e07c2020-12-14 09:09:52 -0500911 Outs []string
Jingwen Chen07027912021-03-15 06:02:43 -0400912 Tools bazel.LabelListAttribute
Cole Faustf0d4d4f2023-08-14 11:37:54 -0700913 Cmd bazel.StringAttribute
Jingwen Chen316e07c2020-12-14 09:09:52 -0500914}
915
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400916// ConvertWithBp2build converts a Soong module -> Bazel target.
Chris Parsons637458d2023-09-19 20:09:00 +0000917func (m *Module) ConvertWithBp2build(ctx android.Bp2buildMutatorContext) {
Liz Kammer356f7d42021-01-26 09:18:53 -0500918 // Bazel only has the "tools" attribute.
Jingwen Chen07027912021-03-15 06:02:43 -0400919 tools_prop := android.BazelLabelForModuleDeps(ctx, m.properties.Tools)
920 tool_files_prop := android.BazelLabelForModuleSrc(ctx, m.properties.Tool_files)
921 tools_prop.Append(tool_files_prop)
Liz Kammer356f7d42021-01-26 09:18:53 -0500922
Jingwen Chen07027912021-03-15 06:02:43 -0400923 tools := bazel.MakeLabelListAttribute(tools_prop)
Yu Liud6201012022-10-17 12:29:15 -0700924 srcs := bazel.LabelListAttribute{}
925 srcs_labels := bazel.LabelList{}
926 // Only cc_genrule is arch specific
927 if ctx.ModuleType() == "cc_genrule" {
928 for axis, configToProps := range m.GetArchVariantProperties(ctx, &generatorProperties{}) {
929 for config, props := range configToProps {
930 if props, ok := props.(*generatorProperties); ok {
931 labels := android.BazelLabelForModuleSrcExcludes(ctx, props.Srcs, props.Exclude_srcs)
932 srcs_labels.Append(labels)
933 srcs.SetSelectValue(axis, config, labels)
934 }
935 }
936 }
937 } else {
938 srcs_labels = android.BazelLabelForModuleSrcExcludes(ctx, m.properties.Srcs, m.properties.Exclude_srcs)
939 srcs = bazel.MakeLabelListAttribute(srcs_labels)
940 }
Liz Kammer356f7d42021-01-26 09:18:53 -0500941
942 var allReplacements bazel.LabelList
Jingwen Chen07027912021-03-15 06:02:43 -0400943 allReplacements.Append(tools.Value)
Yu Liud6201012022-10-17 12:29:15 -0700944 allReplacements.Append(bazel.FirstUniqueBazelLabelList(srcs_labels))
Liz Kammer356f7d42021-01-26 09:18:53 -0500945
Liz Kammer8bd92422023-06-09 13:41:08 -0400946 // The Output_extension prop is not in an immediately accessible field
947 // in the Module struct, so use GetProperties and cast it
948 // to the known struct prop.
949 var outputExtension *string
950 var data bazel.LabelListAttribute
951 if ctx.ModuleType() == "gensrcs" {
952 for _, propIntf := range m.GetProperties() {
953 if props, ok := propIntf.(*genSrcsProperties); ok {
954 outputExtension = props.Output_extension
955 dataFiles := android.BazelLabelForModuleSrc(ctx, props.Data)
956 allReplacements.Append(bazel.FirstUniqueBazelLabelList(dataFiles))
957 data = bazel.MakeLabelListAttribute(dataFiles)
958 break
959 }
960 }
961 }
962
Cole Faustf0d4d4f2023-08-14 11:37:54 -0700963 replaceVariables := func(cmd string) string {
964 // Replace in and out variables with $< and $@
Vinh Tranb69e1ae2022-05-20 18:54:09 -0400965 if ctx.ModuleType() == "gensrcs" {
Cole Faustf0d4d4f2023-08-14 11:37:54 -0700966 cmd = strings.ReplaceAll(cmd, "$(in)", "$(SRC)")
Vinh Tranb69e1ae2022-05-20 18:54:09 -0400967 cmd = strings.ReplaceAll(cmd, "$(out)", "$(OUT)")
968 } else {
Cole Faustf0d4d4f2023-08-14 11:37:54 -0700969 cmd = strings.Replace(cmd, "$(in)", "$(SRCS)", -1)
Vinh Tranb69e1ae2022-05-20 18:54:09 -0400970 cmd = strings.Replace(cmd, "$(out)", "$(OUTS)", -1)
971 }
Vinh Tran32a98a52022-09-23 13:08:34 -0400972 cmd = strings.Replace(cmd, "$(genDir)", "$(RULEDIR)", -1)
Jingwen Chen07027912021-03-15 06:02:43 -0400973 if len(tools.Value.Includes) > 0 {
974 cmd = strings.Replace(cmd, "$(location)", fmt.Sprintf("$(location %s)", tools.Value.Includes[0].Label), -1)
975 cmd = strings.Replace(cmd, "$(locations)", fmt.Sprintf("$(locations %s)", tools.Value.Includes[0].Label), -1)
Liz Kammer356f7d42021-01-26 09:18:53 -0500976 }
977 for _, l := range allReplacements.Includes {
Jingwen Chen38e62642021-04-19 05:00:15 +0000978 bpLoc := fmt.Sprintf("$(location %s)", l.OriginalModuleName)
979 bpLocs := fmt.Sprintf("$(locations %s)", l.OriginalModuleName)
Liz Kammer356f7d42021-01-26 09:18:53 -0500980 bazelLoc := fmt.Sprintf("$(location %s)", l.Label)
981 bazelLocs := fmt.Sprintf("$(locations %s)", l.Label)
982 cmd = strings.Replace(cmd, bpLoc, bazelLoc, -1)
983 cmd = strings.Replace(cmd, bpLocs, bazelLocs, -1)
984 }
Cole Faustf0d4d4f2023-08-14 11:37:54 -0700985 return cmd
986 }
987
988 var cmdProp bazel.StringAttribute
989 cmdProp.SetValue(replaceVariables(proptools.String(m.properties.Cmd)))
Liz Kammer9e2a5a72023-09-19 08:41:14 -0400990 allProductVariableProps, errs := android.ProductVariableProperties(ctx, m)
991 for _, err := range errs {
992 ctx.ModuleErrorf("ProductVariableProperties error: %s", err)
993 }
Cole Faustf0d4d4f2023-08-14 11:37:54 -0700994 if productVariableProps, ok := allProductVariableProps["Cmd"]; ok {
995 for productVariable, value := range productVariableProps {
996 var cmd string
997 if strValue, ok := value.(*string); ok && strValue != nil {
998 cmd = *strValue
999 }
1000 cmd = replaceVariables(cmd)
1001 cmdProp.SetSelectValue(productVariable.ConfigurationAxis(), productVariable.SelectKey(), &cmd)
1002 }
Liz Kammer356f7d42021-01-26 09:18:53 -05001003 }
1004
Spandan Das39b6cc52023-04-12 19:05:49 +00001005 tags := android.ApexAvailableTagsWithoutTestApexes(ctx, m)
Sam Delmericoeddd3c02022-12-02 17:31:58 -05001006
Liz Kammer0db0e342023-07-18 11:39:30 -04001007 bazelName := m.Name()
Vinh Tranb69e1ae2022-05-20 18:54:09 -04001008 if ctx.ModuleType() == "gensrcs" {
Vinh Tranb69e1ae2022-05-20 18:54:09 -04001009 props := bazel.BazelTargetModuleProperties{
1010 Rule_class: "gensrcs",
1011 Bzl_load_location: "//build/bazel/rules:gensrcs.bzl",
1012 }
1013 attrs := &bazelGensrcsAttributes{
1014 Srcs: srcs,
1015 Output_extension: outputExtension,
Cole Faustf0d4d4f2023-08-14 11:37:54 -07001016 Cmd: cmdProp,
Vinh Tranb69e1ae2022-05-20 18:54:09 -04001017 Tools: tools,
Liz Kammer8bd92422023-06-09 13:41:08 -04001018 Data: data,
Vinh Tranb69e1ae2022-05-20 18:54:09 -04001019 }
Sam Delmericoeddd3c02022-12-02 17:31:58 -05001020 ctx.CreateBazelTargetModule(props, android.CommonAttributes{
1021 Name: m.Name(),
1022 Tags: tags,
1023 }, attrs)
Vinh Tranb69e1ae2022-05-20 18:54:09 -04001024 } else {
Spandan Dasa99348d2023-08-01 23:10:05 +00001025 outs := m.RawOutputFiles(ctx)
Chris Parsonsb7950a92023-06-16 17:41:42 +00001026 for _, out := range outs {
1027 if out == bazelName {
1028 // This is a workaround to circumvent a Bazel warning where a genrule's
1029 // out may not have the same name as the target itself. This makes no
1030 // difference for reverse dependencies, because they may depend on the
1031 // out file by name.
1032 bazelName = bazelName + "-gen"
1033 break
1034 }
1035 }
Romain Jobredeaux9973ace2023-08-30 00:27:09 -04001036 attrs := &BazelGenruleAttributes{
Vinh Tranb69e1ae2022-05-20 18:54:09 -04001037 Srcs: srcs,
1038 Outs: outs,
Cole Faustf0d4d4f2023-08-14 11:37:54 -07001039 Cmd: cmdProp,
Vinh Tranb69e1ae2022-05-20 18:54:09 -04001040 Tools: tools,
1041 }
1042 props := bazel.BazelTargetModuleProperties{
1043 Rule_class: "genrule",
1044 }
Sam Delmericoeddd3c02022-12-02 17:31:58 -05001045 ctx.CreateBazelTargetModule(props, android.CommonAttributes{
Chris Parsonsb7950a92023-06-16 17:41:42 +00001046 Name: bazelName,
Sam Delmericoeddd3c02022-12-02 17:31:58 -05001047 Tags: tags,
1048 }, attrs)
Liz Kammer356f7d42021-01-26 09:18:53 -05001049 }
Liz Kammer0db0e342023-07-18 11:39:30 -04001050
1051 if m.needsCcLibraryHeadersBp2build() {
1052 includeDirs := make([]string, len(m.properties.Export_include_dirs)*2)
1053 for i, dir := range m.properties.Export_include_dirs {
1054 includeDirs[i*2] = dir
1055 includeDirs[i*2+1] = filepath.Clean(filepath.Join(ctx.ModuleDir(), dir))
1056 }
1057 attrs := &ccHeaderLibraryAttrs{
1058 Hdrs: []string{":" + bazelName},
1059 Export_includes: includeDirs,
1060 }
1061 props := bazel.BazelTargetModuleProperties{
1062 Rule_class: "cc_library_headers",
1063 Bzl_load_location: "//build/bazel/rules/cc:cc_library_headers.bzl",
1064 }
1065 ctx.CreateBazelTargetModule(props, android.CommonAttributes{
1066 Name: m.Name() + genruleHeaderLibrarySuffix,
1067 Tags: tags,
1068 }, attrs)
Liz Kammer0db0e342023-07-18 11:39:30 -04001069 }
1070}
1071
1072const genruleHeaderLibrarySuffix = "__header_library"
1073
1074func (m *Module) needsCcLibraryHeadersBp2build() bool {
1075 return len(m.properties.Export_include_dirs) > 0
1076}
1077
1078// GenruleCcHeaderMapper is a bazel.LabelMapper function to map genrules to a cc_library_headers
1079// target when they export multiple include directories.
1080func GenruleCcHeaderLabelMapper(ctx bazel.OtherModuleContext, label bazel.Label) (string, bool) {
1081 mod, exists := ctx.ModuleFromName(label.OriginalModuleName)
1082 if !exists {
1083 return label.Label, false
1084 }
1085 if m, ok := mod.(*Module); ok {
1086 if m.needsCcLibraryHeadersBp2build() {
1087 return label.Label + genruleHeaderLibrarySuffix, true
1088 }
1089 }
1090 return label.Label, false
1091}
1092
1093type ccHeaderLibraryAttrs struct {
1094 Hdrs []string
1095
1096 Export_includes []string
Jingwen Chen316e07c2020-12-14 09:09:52 -05001097}
1098
Spandan Dasa99348d2023-08-01 23:10:05 +00001099// RawOutputFfiles returns the raw outputs specified in Android.bp
1100// This does not contain the fully resolved path relative to the top of the tree
1101func (g *Module) RawOutputFiles(ctx android.BazelConversionContext) []string {
1102 if ctx.Config().BuildMode != android.Bp2build {
1103 ctx.ModuleErrorf("RawOutputFiles is only supported in bp2build mode")
1104 }
1105 // The Out prop is not in an immediately accessible field
1106 // in the Module struct, so use GetProperties and cast it
1107 // to the known struct prop.
1108 var outs []string
1109 for _, propIntf := range g.GetProperties() {
1110 if props, ok := propIntf.(*genRuleProperties); ok {
1111 outs = props.Out
1112 break
1113 }
1114 }
1115 return outs
1116}
1117
Nan Zhangea568a42017-11-08 21:20:04 -08001118var Bool = proptools.Bool
1119var String = proptools.String
Jaewoong Jung98716bd2018-12-10 08:13:18 -08001120
Jaewoong Jung98716bd2018-12-10 08:13:18 -08001121// Defaults
Jaewoong Jung98716bd2018-12-10 08:13:18 -08001122type Defaults struct {
1123 android.ModuleBase
1124 android.DefaultsModuleBase
1125}
1126
Jaewoong Jung98716bd2018-12-10 08:13:18 -08001127func defaultsFactory() android.Module {
1128 return DefaultsFactory()
1129}
1130
1131func DefaultsFactory(props ...interface{}) android.Module {
1132 module := &Defaults{}
1133
1134 module.AddProperties(props...)
1135 module.AddProperties(
1136 &generatorProperties{},
1137 &genRuleProperties{},
1138 )
1139
1140 android.InitDefaultsModule(module)
1141
1142 return module
1143}
Yu Liu6a7940c2023-05-09 17:12:22 -07001144
Yu Liue7f7cbf2023-06-13 18:50:03 +00001145var sandboxingAllowlistKey = android.NewOnceKey("genruleSandboxingAllowlistKey")
1146
1147type sandboxingAllowlistSets struct {
1148 sandboxingDenyModuleSet map[string]bool
1149 sandboxingDenyPathSet map[string]bool
1150 depfileAllowSet map[string]bool
1151}
1152
1153func getSandboxingAllowlistSets(ctx android.PathContext) *sandboxingAllowlistSets {
1154 return ctx.Config().Once(sandboxingAllowlistKey, func() interface{} {
1155 sandboxingDenyModuleSet := map[string]bool{}
1156 sandboxingDenyPathSet := map[string]bool{}
1157 depfileAllowSet := map[string]bool{}
1158
1159 android.AddToStringSet(sandboxingDenyModuleSet, append(DepfileAllowList, SandboxingDenyModuleList...))
1160 android.AddToStringSet(sandboxingDenyPathSet, SandboxingDenyPathList)
1161 android.AddToStringSet(depfileAllowSet, DepfileAllowList)
1162 return &sandboxingAllowlistSets{
1163 sandboxingDenyModuleSet: sandboxingDenyModuleSet,
1164 sandboxingDenyPathSet: sandboxingDenyPathSet,
1165 depfileAllowSet: depfileAllowSet,
1166 }
1167 }).(*sandboxingAllowlistSets)
1168}
Liz Kammer0db0e342023-07-18 11:39:30 -04001169
Yu Liu6a7940c2023-05-09 17:12:22 -07001170func getSandboxedRuleBuilder(ctx android.ModuleContext, r *android.RuleBuilder) *android.RuleBuilder {
Yu Liu45d6af52023-05-24 23:10:18 +00001171 if !ctx.DeviceConfig().GenruleSandboxing() {
1172 return r.SandboxTools()
1173 }
Yu Liue7f7cbf2023-06-13 18:50:03 +00001174 sandboxingAllowlistSets := getSandboxingAllowlistSets(ctx)
1175 if sandboxingAllowlistSets.sandboxingDenyPathSet[ctx.ModuleDir()] ||
1176 sandboxingAllowlistSets.sandboxingDenyModuleSet[ctx.ModuleName()] {
Yu Liu6a7940c2023-05-09 17:12:22 -07001177 return r.SandboxTools()
1178 }
1179 return r.SandboxInputs()
1180}