blob: 889bccd31e9a06a74f245a5ab05192e23d373224 [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"
Yu Liu45d6af52023-05-24 23:10:18 +000027 "sync"
Dan Willemsen3f4539b2016-09-28 16:19:10 -070028
Chris Parsonsf874e462022-05-10 13:50:12 -040029 "android/soong/bazel/cquery"
Jihoon Kangc170af42022-08-20 05:26:38 +000030
Colin Cross70b40592015-03-23 12:57:34 -070031 "github.com/google/blueprint"
Dan Willemsen8eded0a2017-09-13 16:07:44 -070032 "github.com/google/blueprint/bootstrap"
Nan Zhangea568a42017-11-08 21:20:04 -080033 "github.com/google/blueprint/proptools"
Colin Cross5049f022015-03-18 13:28:46 -070034
Colin Cross635c3b02016-05-18 15:37:25 -070035 "android/soong/android"
Jingwen Chen30f5aaa2020-11-19 05:38:02 -050036 "android/soong/bazel"
Colin Cross5049f022015-03-18 13:28:46 -070037)
38
Colin Cross463a90e2015-06-17 14:20:06 -070039func init() {
Colin Crosse9fe2942020-11-10 18:12:15 -080040 RegisterGenruleBuildComponents(android.InitRegistrationContext)
Martin Stjernholm710ec3a2020-01-16 15:12:04 +000041}
Jaewoong Jung98716bd2018-12-10 08:13:18 -080042
Paul Duffin672cb9f2021-03-03 02:30:37 +000043// Test fixture preparer that will register most genrule build components.
44//
45// Singletons and mutators should only be added here if they are needed for a majority of genrule
46// module types, otherwise they should be added under a separate preparer to allow them to be
47// selected only when needed to reduce test execution time.
48//
49// Module types do not have much of an overhead unless they are used so this should include as many
50// module types as possible. The exceptions are those module types that require mutators and/or
51// singletons in order to function in which case they should be kept together in a separate
52// preparer.
53var PrepareForTestWithGenRuleBuildComponents = android.GroupFixturePreparers(
54 android.FixtureRegisterWithContext(RegisterGenruleBuildComponents),
55)
56
57// Prepare a fixture to use all genrule module types, mutators and singletons fully.
58//
59// This should only be used by tests that want to run with as much of the build enabled as possible.
60var PrepareForIntegrationTestWithGenrule = android.GroupFixturePreparers(
61 PrepareForTestWithGenRuleBuildComponents,
62)
63
Yu Liu45d6af52023-05-24 23:10:18 +000064var DepfileAllowSet map[string]bool
65var SandboxingDenyModuleSet map[string]bool
66var SandboxingDenyPathSet map[string]bool
67var SandboxingDenyModuleSetLock sync.Mutex
68var DepfileAllowSetLock sync.Mutex
69
Colin Crosse9fe2942020-11-10 18:12:15 -080070func RegisterGenruleBuildComponents(ctx android.RegistrationContext) {
Martin Stjernholm710ec3a2020-01-16 15:12:04 +000071 ctx.RegisterModuleType("genrule_defaults", defaultsFactory)
72
73 ctx.RegisterModuleType("gensrcs", GenSrcsFactory)
74 ctx.RegisterModuleType("genrule", GenRuleFactory)
75
76 ctx.FinalDepsMutators(func(ctx android.RegisterMutatorsContext) {
77 ctx.BottomUp("genrule_tool_deps", toolDepsMutator).Parallel()
78 })
Liz Kammer356f7d42021-01-26 09:18:53 -050079}
80
Colin Cross5049f022015-03-18 13:28:46 -070081var (
Colin Cross635c3b02016-05-18 15:37:25 -070082 pctx = android.NewPackageContext("android/soong/genrule")
Colin Cross1a527682019-09-23 15:55:30 -070083
Alex Humesky29e3bbe2020-11-20 21:30:13 -050084 // Used by gensrcs when there is more than 1 shard to merge the outputs
85 // of each shard into a zip file.
Colin Cross1a527682019-09-23 15:55:30 -070086 gensrcsMerge = pctx.AndroidStaticRule("gensrcsMerge", blueprint.RuleParams{
87 Command: "${soongZip} -o ${tmpZip} @${tmpZip}.rsp && ${zipSync} -d ${genDir} ${tmpZip}",
88 CommandDeps: []string{"${soongZip}", "${zipSync}"},
89 Rspfile: "${tmpZip}.rsp",
90 RspfileContent: "${zipArgs}",
91 }, "tmpZip", "genDir", "zipArgs")
Colin Cross5049f022015-03-18 13:28:46 -070092)
93
Jeff Gastonefc1b412017-03-29 17:29:06 -070094func init() {
Dan Willemsenddf504c2019-08-09 16:21:29 -070095 pctx.Import("android/soong/android")
Colin Cross1a527682019-09-23 15:55:30 -070096
97 pctx.HostBinToolVariable("soongZip", "soong_zip")
98 pctx.HostBinToolVariable("zipSync", "zipsync")
Jeff Gastonefc1b412017-03-29 17:29:06 -070099}
100
Colin Cross5049f022015-03-18 13:28:46 -0700101type SourceFileGenerator interface {
Colin Cross635c3b02016-05-18 15:37:25 -0700102 GeneratedSourceFiles() android.Paths
Colin Cross5ed99c62016-11-22 12:55:55 -0800103 GeneratedHeaderDirs() android.Paths
Dan Willemsen9da9d492018-02-21 18:28:18 -0800104 GeneratedDeps() android.Paths
Colin Cross5049f022015-03-18 13:28:46 -0700105}
106
Colin Crossfe17f6f2019-03-28 19:30:56 -0700107// Alias for android.HostToolProvider
108// Deprecated: use android.HostToolProvider instead.
Colin Crossd350ecd2015-04-28 13:25:36 -0700109type HostToolProvider interface {
Colin Crossfe17f6f2019-03-28 19:30:56 -0700110 android.HostToolProvider
Colin Crossd350ecd2015-04-28 13:25:36 -0700111}
Colin Cross5049f022015-03-18 13:28:46 -0700112
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700113type hostToolDependencyTag struct {
114 blueprint.BaseDependencyTag
Colin Cross65cb3142021-12-10 23:05:02 +0000115 android.LicenseAnnotationToolchainDependencyTag
Colin Cross08f15ab2018-10-04 23:29:14 -0700116 label string
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700117}
Martin Stjernholmdbd814d2022-01-12 23:18:30 +0000118
119func (t hostToolDependencyTag) AllowDisabledModuleDependency(target android.Module) bool {
120 // Allow depending on a disabled module if it's replaced by a prebuilt
121 // counterpart. We get the prebuilt through android.PrebuiltGetPreferred in
122 // GenerateAndroidBuildActions.
123 return target.IsReplacedByPrebuilt()
124}
125
126var _ android.AllowDisabledModuleDependency = (*hostToolDependencyTag)(nil)
127
Colin Cross7d5136f2015-05-11 13:39:40 -0700128type generatorProperties struct {
Spandan Das93e95992021-07-29 18:26:39 +0000129 // The command to run on one or more input files. Cmd supports substitution of a few variables.
Jeff Gastonefc1b412017-03-29 17:29:06 -0700130 //
131 // Available variables for substitution:
132 //
Spandan Das93e95992021-07-29 18:26:39 +0000133 // $(location): the path to the first entry in tools or tool_files.
134 // $(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.
135 // $(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.
136 // $(in): one or more input files.
137 // $(out): a single output file.
138 // $(depfile): a file to which dependencies will be written, if the depfile property is set to true.
139 // $(genDir): the sandbox directory for this tool; contains $(out).
Colin Cross2296f5b2017-10-17 21:38:14 -0700140 // $$: a literal $
Nan Zhangea568a42017-11-08 21:20:04 -0800141 Cmd *string
Colin Cross7d5136f2015-05-11 13:39:40 -0700142
Colin Cross33bfb0a2016-11-21 17:23:08 -0800143 // Enable reading a file containing dependencies in gcc format after the command completes
Nan Zhangea568a42017-11-08 21:20:04 -0800144 Depfile *bool
Colin Cross33bfb0a2016-11-21 17:23:08 -0800145
Colin Cross6f080df2016-11-04 15:32:58 -0700146 // name of the modules (if any) that produces the host executable. Leave empty for
Colin Cross7d5136f2015-05-11 13:39:40 -0700147 // prebuilts or scripts that do not need a module to build them.
Colin Cross6f080df2016-11-04 15:32:58 -0700148 Tools []string
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700149
150 // Local file that is used as the tool
Colin Cross27b922f2019-03-04 22:35:41 -0800151 Tool_files []string `android:"path"`
Colin Cross5ed99c62016-11-22 12:55:55 -0800152
153 // List of directories to export generated headers from
154 Export_include_dirs []string
Colin Cross708c4242017-01-13 18:05:49 -0800155
156 // list of input files
Colin Cross27b922f2019-03-04 22:35:41 -0800157 Srcs []string `android:"path,arch_variant"`
Dan Willemseneefa0262018-11-17 14:01:18 -0800158
159 // input files to exclude
Colin Cross27b922f2019-03-04 22:35:41 -0800160 Exclude_srcs []string `android:"path,arch_variant"`
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400161}
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500162
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700163type Module struct {
Colin Cross635c3b02016-05-18 15:37:25 -0700164 android.ModuleBase
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800165 android.DefaultableModuleBase
Liz Kammerea6666f2021-02-17 10:17:28 -0500166 android.BazelModuleBase
Jiyong Parkfc752ca2019-06-12 13:27:29 +0900167 android.ApexModuleBase
Colin Crossd350ecd2015-04-28 13:25:36 -0700168
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700169 // For other packages to make their own genrules with extra
170 // properties
171 Extra interface{}
Colin Crossf3bfd022021-09-27 15:15:06 -0700172
173 // CmdModifier can be set by wrappers around genrule to modify the command, for example to
174 // prefix environment variables to it.
175 CmdModifier func(ctx android.ModuleContext, cmd string) string
176
Colin Cross7228ecd2019-11-18 16:00:16 -0800177 android.ImageInterface
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700178
Colin Cross7d5136f2015-05-11 13:39:40 -0700179 properties generatorProperties
Colin Crossd350ecd2015-04-28 13:25:36 -0700180
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500181 // For the different tasks that genrule and gensrc generate. genrule will
182 // generate 1 task, and gensrc will generate 1 or more tasks based on the
183 // number of shards the input files are sharded into.
Jeff Gaston437d23c2017-11-08 12:38:00 -0800184 taskGenerator taskFunc
Colin Crossd350ecd2015-04-28 13:25:36 -0700185
Colin Cross1a527682019-09-23 15:55:30 -0700186 rule blueprint.Rule
187 rawCommands []string
Colin Crossd350ecd2015-04-28 13:25:36 -0700188
Colin Cross5ed99c62016-11-22 12:55:55 -0800189 exportedIncludeDirs android.Paths
Dan Willemsenb40aab62016-04-20 14:21:14 -0700190
Colin Cross635c3b02016-05-18 15:37:25 -0700191 outputFiles android.Paths
Dan Willemsen9da9d492018-02-21 18:28:18 -0800192 outputDeps android.Paths
Colin Crossa4ad2b02019-03-18 22:15:32 -0700193
194 subName string
Colin Cross1a527682019-09-23 15:55:30 -0700195 subDir string
bralee1fbf4402020-05-21 10:11:59 +0800196
197 // Collect the module directory for IDE info in java/jdeps.go.
198 modulePaths []string
Colin Crossd350ecd2015-04-28 13:25:36 -0700199}
200
Chris Parsonsf874e462022-05-10 13:50:12 -0400201var _ android.MixedBuildBuildable = (*Module)(nil)
202
Colin Cross1a527682019-09-23 15:55:30 -0700203type taskFunc func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask
Colin Crossd350ecd2015-04-28 13:25:36 -0700204
205type generateTask struct {
Liz Kammer81fec182023-06-09 13:33:45 -0400206 in android.Paths
207 out android.WritablePaths
208 depFile android.WritablePath
209 copyTo android.WritablePaths // For gensrcs to set on gensrcsMerge rule.
210 genDir android.WritablePath
211 extraTools android.Paths // dependencies on tools used by the generator
212 extraInputs map[string][]string
Colin Cross3ea4eb82020-11-24 13:07:27 -0800213
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500214 cmd string
215 // For gensrsc sharding.
Colin Cross3ea4eb82020-11-24 13:07:27 -0800216 shard int
217 shards int
Colin Crossd350ecd2015-04-28 13:25:36 -0700218}
219
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700220func (g *Module) GeneratedSourceFiles() android.Paths {
Colin Crossd350ecd2015-04-28 13:25:36 -0700221 return g.outputFiles
222}
223
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700224func (g *Module) Srcs() android.Paths {
Nan Zhange42777a2018-03-27 16:19:42 -0700225 return append(android.Paths{}, g.outputFiles...)
Colin Cross068e0fe2016-12-13 15:23:47 -0800226}
227
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700228func (g *Module) GeneratedHeaderDirs() android.Paths {
Colin Cross5ed99c62016-11-22 12:55:55 -0800229 return g.exportedIncludeDirs
Dan Willemsenb40aab62016-04-20 14:21:14 -0700230}
231
Dan Willemsen9da9d492018-02-21 18:28:18 -0800232func (g *Module) GeneratedDeps() android.Paths {
233 return g.outputDeps
234}
235
Jooyung Han8c7e3ed2021-06-28 17:35:58 +0900236func (g *Module) OutputFiles(tag string) (android.Paths, error) {
237 if tag == "" {
238 return append(android.Paths{}, g.outputFiles...), nil
239 }
240 // otherwise, tag should match one of outputs
241 for _, outputFile := range g.outputFiles {
242 if outputFile.Rel() == tag {
243 return android.Paths{outputFile}, nil
244 }
245 }
246 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
247}
248
249var _ android.SourceFileProducer = (*Module)(nil)
250var _ android.OutputFileProducer = (*Module)(nil)
251
Martin Stjernholm710ec3a2020-01-16 15:12:04 +0000252func toolDepsMutator(ctx android.BottomUpMutatorContext) {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700253 if g, ok := ctx.Module().(*Module); ok {
Colin Cross08f15ab2018-10-04 23:29:14 -0700254 for _, tool := range g.properties.Tools {
255 tag := hostToolDependencyTag{label: tool}
256 if m := android.SrcIsModule(tool); m != "" {
257 tool = m
258 }
Colin Cross0f7d2ef2019-10-16 11:03:10 -0700259 ctx.AddFarVariationDependencies(ctx.Config().BuildOSTarget.Variations(), tag, tool)
Colin Cross6362e272015-10-29 15:25:03 -0700260 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700261 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700262}
263
Chris Parsonsf874e462022-05-10 13:50:12 -0400264func (g *Module) ProcessBazelQueryResponse(ctx android.ModuleContext) {
265 g.generateCommonBuildActions(ctx)
266
267 label := g.GetBazelLabel(ctx, g)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400268 bazelCtx := ctx.Config().BazelContext
Chris Parsonsf874e462022-05-10 13:50:12 -0400269 filePaths, err := bazelCtx.GetOutputFiles(label, android.GetConfigKey(ctx))
270 if err != nil {
271 ctx.ModuleErrorf(err.Error())
272 return
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400273 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400274
275 var bazelOutputFiles android.Paths
276 exportIncludeDirs := map[string]bool{}
277 for _, bazelOutputFile := range filePaths {
Cole Faust01243362022-06-02 12:11:12 -0700278 bazelOutputFiles = append(bazelOutputFiles, android.PathForBazelOutRelative(ctx, ctx.ModuleDir(), bazelOutputFile))
Chris Parsonsf874e462022-05-10 13:50:12 -0400279 exportIncludeDirs[filepath.Dir(bazelOutputFile)] = true
280 }
281 g.outputFiles = bazelOutputFiles
282 g.outputDeps = bazelOutputFiles
283 for includePath, _ := range exportIncludeDirs {
284 g.exportedIncludeDirs = append(g.exportedIncludeDirs, android.PathForBazelOut(ctx, includePath))
285 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400286}
Colin Crossf1885962020-11-20 15:28:30 -0800287
Chris Parsonsf874e462022-05-10 13:50:12 -0400288// generateCommonBuildActions contains build action generation logic
289// common to both the mixed build case and the legacy case of genrule processing.
290// To fully support genrule in mixed builds, the contents of this function should
291// approach zero; there should be no genrule action registration done directly
292// by Soong logic in the mixed-build case.
293func (g *Module) generateCommonBuildActions(ctx android.ModuleContext) {
Colin Crossa4ad2b02019-03-18 22:15:32 -0700294 g.subName = ctx.ModuleSubDir()
295
bralee1fbf4402020-05-21 10:11:59 +0800296 // Collect the module directory for IDE info in java/jdeps.go.
297 g.modulePaths = append(g.modulePaths, ctx.ModuleDir())
298
Colin Cross5ed99c62016-11-22 12:55:55 -0800299 if len(g.properties.Export_include_dirs) > 0 {
300 for _, dir := range g.properties.Export_include_dirs {
301 g.exportedIncludeDirs = append(g.exportedIncludeDirs,
Colin Cross1a527682019-09-23 15:55:30 -0700302 android.PathForModuleGen(ctx, g.subDir, ctx.ModuleDir(), dir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800303 }
304 } else {
Colin Cross1a527682019-09-23 15:55:30 -0700305 g.exportedIncludeDirs = append(g.exportedIncludeDirs, android.PathForModuleGen(ctx, g.subDir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800306 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700307
Colin Crossd11cf622021-03-23 22:30:35 -0700308 locationLabels := map[string]location{}
Colin Cross08f15ab2018-10-04 23:29:14 -0700309 firstLabel := ""
310
Colin Crossd11cf622021-03-23 22:30:35 -0700311 addLocationLabel := func(label string, loc location) {
Colin Cross08f15ab2018-10-04 23:29:14 -0700312 if firstLabel == "" {
313 firstLabel = label
314 }
315 if _, exists := locationLabels[label]; !exists {
Colin Crossd11cf622021-03-23 22:30:35 -0700316 locationLabels[label] = loc
Colin Cross08f15ab2018-10-04 23:29:14 -0700317 } else {
Anton Hansson7cd41e52021-10-08 16:13:10 +0100318 ctx.ModuleErrorf("multiple locations for label %q: %q and %q (do you have duplicate srcs entries?)",
Colin Crossd11cf622021-03-23 22:30:35 -0700319 label, locationLabels[label], loc)
Colin Cross08f15ab2018-10-04 23:29:14 -0700320 }
321 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700322
Colin Crossba9e4032020-11-24 16:32:22 -0800323 var tools android.Paths
324 var packagedTools []android.PackagingSpec
Colin Cross6f080df2016-11-04 15:32:58 -0700325 if len(g.properties.Tools) > 0 {
Colin Crossba71a3f2019-03-18 12:12:48 -0700326 seenTools := make(map[string]bool)
327
Colin Cross35143d02017-11-16 00:11:20 -0800328 ctx.VisitDirectDepsBlueprint(func(module blueprint.Module) {
Colin Cross08f15ab2018-10-04 23:29:14 -0700329 switch tag := ctx.OtherModuleDependencyTag(module).(type) {
330 case hostToolDependencyTag:
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700331 tool := ctx.OtherModuleName(module)
Martin Stjernholmdbd814d2022-01-12 23:18:30 +0000332 if m, ok := module.(android.Module); ok {
333 // Necessary to retrieve any prebuilt replacement for the tool, since
334 // toolDepsMutator runs too late for the prebuilt mutators to have
335 // replaced the dependency.
336 module = android.PrebuiltGetPreferred(ctx, m)
337 }
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700338
Colin Crossba9e4032020-11-24 16:32:22 -0800339 switch t := module.(type) {
340 case android.HostToolProvider:
341 // A HostToolProvider provides the path to a tool, which will be copied
342 // into the sandbox.
Colin Cross35143d02017-11-16 00:11:20 -0800343 if !t.(android.Module).Enabled() {
Colin Cross6510f912017-11-29 00:27:14 -0800344 if ctx.Config().AllowMissingDependencies() {
Colin Cross35143d02017-11-16 00:11:20 -0800345 ctx.AddMissingDependencies([]string{tool})
346 } else {
347 ctx.ModuleErrorf("depends on disabled module %q", tool)
348 }
Colin Crossba9e4032020-11-24 16:32:22 -0800349 return
Colin Cross35143d02017-11-16 00:11:20 -0800350 }
Colin Crossba9e4032020-11-24 16:32:22 -0800351 path := t.HostToolPath()
352 if !path.Valid() {
353 ctx.ModuleErrorf("host tool %q missing output file", tool)
354 return
355 }
356 if specs := t.TransitivePackagingSpecs(); specs != nil {
357 // If the HostToolProvider has PackgingSpecs, which are definitions of the
358 // required relative locations of the tool and its dependencies, use those
359 // instead. They will be copied to those relative locations in the sbox
360 // sandbox.
361 packagedTools = append(packagedTools, specs...)
362 // Assume that the first PackagingSpec of the module is the tool.
Colin Crossd11cf622021-03-23 22:30:35 -0700363 addLocationLabel(tag.label, packagedToolLocation{specs[0]})
Colin Crossba9e4032020-11-24 16:32:22 -0800364 } else {
365 tools = append(tools, path.Path())
Colin Crossd11cf622021-03-23 22:30:35 -0700366 addLocationLabel(tag.label, toolLocation{android.Paths{path.Path()}})
Colin Crossba9e4032020-11-24 16:32:22 -0800367 }
368 case bootstrap.GoBinaryTool:
369 // A GoBinaryTool provides the install path to a tool, which will be copied.
Colin Crossa44551f2021-10-25 15:36:21 -0700370 p := android.PathForGoBinary(ctx, t)
371 tools = append(tools, p)
372 addLocationLabel(tag.label, toolLocation{android.Paths{p}})
Colin Crossba9e4032020-11-24 16:32:22 -0800373 default:
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700374 ctx.ModuleErrorf("%q is not a host tool provider", tool)
Colin Crossba9e4032020-11-24 16:32:22 -0800375 return
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700376 }
377
Colin Crossba9e4032020-11-24 16:32:22 -0800378 seenTools[tag.label] = true
Colin Crossd350ecd2015-04-28 13:25:36 -0700379 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700380 })
Colin Crossba71a3f2019-03-18 12:12:48 -0700381
382 // If AllowMissingDependencies is enabled, the build will not have stopped when
383 // AddFarVariationDependencies was called on a missing tool, which will result in nonsensical
Liz Kammer20ebfb42020-07-28 11:32:07 -0700384 // "cmd: unknown location label ..." errors later. Add a placeholder file to the local label.
385 // The command that uses this placeholder file will never be executed because the rule will be
386 // replaced with an android.Error rule reporting the missing dependencies.
Colin Crossba71a3f2019-03-18 12:12:48 -0700387 if ctx.Config().AllowMissingDependencies() {
388 for _, tool := range g.properties.Tools {
389 if !seenTools[tool] {
Colin Crossd11cf622021-03-23 22:30:35 -0700390 addLocationLabel(tool, errorLocation{"***missing tool " + tool + "***"})
Colin Crossba71a3f2019-03-18 12:12:48 -0700391 }
392 }
393 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700394 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700395
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700396 if ctx.Failed() {
397 return
398 }
399
Colin Cross08f15ab2018-10-04 23:29:14 -0700400 for _, toolFile := range g.properties.Tool_files {
Colin Cross8a497952019-03-05 22:25:09 -0800401 paths := android.PathsForModuleSrc(ctx, []string{toolFile})
Colin Crossba9e4032020-11-24 16:32:22 -0800402 tools = append(tools, paths...)
Colin Crossd11cf622021-03-23 22:30:35 -0700403 addLocationLabel(toolFile, toolLocation{paths})
Colin Cross08f15ab2018-10-04 23:29:14 -0700404 }
405
Liz Kammer81fec182023-06-09 13:33:45 -0400406 addLabelsForInputs := func(propName string, include, exclude []string) android.Paths {
Colin Crossba71a3f2019-03-18 12:12:48 -0700407
Liz Kammer81fec182023-06-09 13:33:45 -0400408 includeDirInPaths := ctx.DeviceConfig().BuildBrokenInputDir(g.Name())
409 var srcFiles android.Paths
410 for _, in := range include {
411 paths, missingDeps := android.PathsAndMissingDepsRelativeToModuleSourceDir(android.SourceInput{
412 Context: ctx, Paths: []string{in}, ExcludePaths: exclude, IncludeDirs: includeDirInPaths,
413 })
414 if len(missingDeps) > 0 {
415 if !ctx.Config().AllowMissingDependencies() {
416 panic(fmt.Errorf("should never get here, the missing dependencies %q should have been reported in DepsMutator",
417 missingDeps))
418 }
419
420 // If AllowMissingDependencies is enabled, the build will not have stopped when
421 // the dependency was added on a missing SourceFileProducer module, which will result in nonsensical
422 // "cmd: label ":..." has no files" errors later. Add a placeholder file to the local label.
423 // The command that uses this placeholder file will never be executed because the rule will be
424 // replaced with an android.Error rule reporting the missing dependencies.
425 ctx.AddMissingDependencies(missingDeps)
426 addLocationLabel(in, errorLocation{"***missing " + propName + " " + in + "***"})
427 } else {
428 srcFiles = append(srcFiles, paths...)
429 addLocationLabel(in, inputLocation{paths})
430 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700431 }
Liz Kammer81fec182023-06-09 13:33:45 -0400432 return srcFiles
Colin Cross08f15ab2018-10-04 23:29:14 -0700433 }
Liz Kammer81fec182023-06-09 13:33:45 -0400434 srcFiles := addLabelsForInputs("srcs", g.properties.Srcs, g.properties.Exclude_srcs)
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
Colin Crossf3bfd022021-09-27 15:15:06 -0700440 cmd := String(g.properties.Cmd)
441 if g.CmdModifier != nil {
442 cmd = g.CmdModifier(ctx, cmd)
443 }
444
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500445 // Generate tasks, either from genrule or gensrcs.
Liz Kammer81fec182023-06-09 13:33:45 -0400446 for i, task := range g.taskGenerator(ctx, cmd, srcFiles) {
Colin Cross3d680512020-11-13 16:23:53 -0800447 if len(task.out) == 0 {
448 ctx.ModuleErrorf("must have at least one output file")
449 return
Colin Cross85a2e892018-07-09 09:45:06 -0700450 }
451
Liz Kammer81fec182023-06-09 13:33:45 -0400452 var extraInputs android.Paths
453 // 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.
462 manifestName := "genrule.sbox.textproto"
463 desc := "generate"
464 name := "generator"
465 if task.shards > 0 {
466 manifestName = "genrule_" + strconv.Itoa(task.shard) + ".sbox.textproto"
467 desc += " " + strconv.Itoa(task.shard)
468 name += strconv.Itoa(task.shard)
469 } else if len(task.out) == 1 {
470 desc += " " + task.out[0].Base()
471 }
472
473 manifestPath := android.PathForModuleOut(ctx, manifestName)
474
475 // Use a RuleBuilder to create a rule that runs the command inside an sbox sandbox.
Yu Liu6a7940c2023-05-09 17:12:22 -0700476 rule := getSandboxedRuleBuilder(ctx, android.NewRuleBuilder(pctx, ctx).Sbox(task.genDir, manifestPath))
Colin Crossf1a035e2020-11-16 17:32:30 -0800477 cmd := rule.Command()
478
Colin Cross3d680512020-11-13 16:23:53 -0800479 for _, out := range task.out {
Colin Crossd11cf622021-03-23 22:30:35 -0700480 addLocationLabel(out.Rel(), outputLocation{out})
Colin Cross3d680512020-11-13 16:23:53 -0800481 }
482
Colin Cross1a527682019-09-23 15:55:30 -0700483 referencedDepfile := false
484
Colin Cross3d680512020-11-13 16:23:53 -0800485 rawCommand, err := android.Expand(task.cmd, func(name string) (string, error) {
Colin Cross1a527682019-09-23 15:55:30 -0700486 // report the error directly without returning an error to android.Expand to catch multiple errors in a
487 // single run
Colin Cross3d680512020-11-13 16:23:53 -0800488 reportError := func(fmt string, args ...interface{}) (string, error) {
Colin Cross1a527682019-09-23 15:55:30 -0700489 ctx.PropertyErrorf("cmd", fmt, args...)
Colin Cross3d680512020-11-13 16:23:53 -0800490 return "SOONG_ERROR", nil
Colin Cross6f080df2016-11-04 15:32:58 -0700491 }
Colin Cross1a527682019-09-23 15:55:30 -0700492
Jihoon Kangc170af42022-08-20 05:26:38 +0000493 // Apply shell escape to each cases to prevent source file paths containing $ from being evaluated in shell
Colin Cross1a527682019-09-23 15:55:30 -0700494 switch name {
495 case "location":
496 if len(g.properties.Tools) == 0 && len(g.properties.Tool_files) == 0 {
497 return reportError("at least one `tools` or `tool_files` is required if $(location) is used")
Colin Cross6f080df2016-11-04 15:32:58 -0700498 }
Colin Crossd11cf622021-03-23 22:30:35 -0700499 loc := locationLabels[firstLabel]
500 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700501 if len(paths) == 0 {
502 return reportError("default label %q has no files", firstLabel)
503 } else if len(paths) > 1 {
504 return reportError("default label %q has multiple files, use $(locations %s) to reference it",
505 firstLabel, firstLabel)
Colin Cross08f15ab2018-10-04 23:29:14 -0700506 }
Jihoon Kangc170af42022-08-20 05:26:38 +0000507 return proptools.ShellEscape(paths[0]), nil
Colin Cross1a527682019-09-23 15:55:30 -0700508 case "in":
Jihoon Kangc170af42022-08-20 05:26:38 +0000509 return strings.Join(proptools.ShellEscapeList(cmd.PathsForInputs(srcFiles)), " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700510 case "out":
Colin Cross3d680512020-11-13 16:23:53 -0800511 var sandboxOuts []string
512 for _, out := range task.out {
Colin Crossf1a035e2020-11-16 17:32:30 -0800513 sandboxOuts = append(sandboxOuts, cmd.PathForOutput(out))
Colin Cross3d680512020-11-13 16:23:53 -0800514 }
Jihoon Kangc170af42022-08-20 05:26:38 +0000515 return strings.Join(proptools.ShellEscapeList(sandboxOuts), " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700516 case "depfile":
517 referencedDepfile = true
518 if !Bool(g.properties.Depfile) {
519 return reportError("$(depfile) used without depfile property")
520 }
Colin Cross3d680512020-11-13 16:23:53 -0800521 return "__SBOX_DEPFILE__", 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
Colin Cross1a527682019-09-23 15:55:30 -0700524 default:
525 if strings.HasPrefix(name, "location ") {
526 label := strings.TrimSpace(strings.TrimPrefix(name, "location "))
Colin Crossd11cf622021-03-23 22:30:35 -0700527 if loc, ok := locationLabels[label]; ok {
528 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700529 if len(paths) == 0 {
530 return reportError("label %q has no files", label)
531 } else if len(paths) > 1 {
532 return reportError("label %q has multiple files, use $(locations %s) to reference it",
533 label, label)
534 }
Jihoon Kangc170af42022-08-20 05:26:38 +0000535 return proptools.ShellEscape(paths[0]), nil
Colin Cross1a527682019-09-23 15:55:30 -0700536 } else {
Anton Hanssonbebf5262022-02-23 11:42:38 +0000537 return reportError("unknown location label %q is not in srcs, out, tools or tool_files.", label)
Colin Cross1a527682019-09-23 15:55:30 -0700538 }
539 } else if strings.HasPrefix(name, "locations ") {
540 label := strings.TrimSpace(strings.TrimPrefix(name, "locations "))
Colin Crossd11cf622021-03-23 22:30:35 -0700541 if loc, ok := locationLabels[label]; ok {
542 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700543 if len(paths) == 0 {
544 return reportError("label %q has no files", label)
545 }
Jihoon Kangc170af42022-08-20 05:26:38 +0000546 return proptools.ShellEscape(strings.Join(paths, " ")), nil
Colin Cross1a527682019-09-23 15:55:30 -0700547 } else {
Anton Hanssonbebf5262022-02-23 11:42:38 +0000548 return reportError("unknown locations label %q is not in srcs, out, tools or tool_files.", label)
Colin Cross1a527682019-09-23 15:55:30 -0700549 }
550 } else {
551 return reportError("unknown variable '$(%s)'", name)
552 }
Colin Cross6f080df2016-11-04 15:32:58 -0700553 }
Colin Cross1a527682019-09-23 15:55:30 -0700554 })
555
556 if err != nil {
557 ctx.PropertyErrorf("cmd", "%s", err.Error())
558 return
Colin Cross6f080df2016-11-04 15:32:58 -0700559 }
Colin Cross6f080df2016-11-04 15:32:58 -0700560
Colin Cross1a527682019-09-23 15:55:30 -0700561 if Bool(g.properties.Depfile) && !referencedDepfile {
562 ctx.PropertyErrorf("cmd", "specified depfile=true but did not include a reference to '${depfile}' in cmd")
563 return
564 }
Colin Cross1a527682019-09-23 15:55:30 -0700565 g.rawCommands = append(g.rawCommands, rawCommand)
Bill Peckhamc087be12020-02-13 15:55:10 -0800566
Colin Cross3d680512020-11-13 16:23:53 -0800567 cmd.Text(rawCommand)
Liz Kammer81fec182023-06-09 13:33:45 -0400568 cmd.Implicits(srcFiles) // need to be able to reference other srcs
569 cmd.Implicits(extraInputs)
Colin Cross3d680512020-11-13 16:23:53 -0800570 cmd.ImplicitOutputs(task.out)
571 cmd.Implicits(task.in)
Colin Crossba9e4032020-11-24 16:32:22 -0800572 cmd.ImplicitTools(tools)
573 cmd.ImplicitTools(task.extraTools)
574 cmd.ImplicitPackagedTools(packagedTools)
Colin Cross3d680512020-11-13 16:23:53 -0800575 if Bool(g.properties.Depfile) {
576 cmd.ImplicitDepFile(task.depFile)
577 }
578
579 // Create the rule to run the genrule command inside sbox.
Colin Crossf1a035e2020-11-16 17:32:30 -0800580 rule.Build(name, desc)
Colin Cross1a527682019-09-23 15:55:30 -0700581
582 if len(task.copyTo) > 0 {
Colin Cross3d680512020-11-13 16:23:53 -0800583 // If copyTo is set, multiple shards need to be copied into a single directory.
584 // task.out contains the per-shard paths, and copyTo contains the corresponding
585 // final path. The files need to be copied into the final directory by a
586 // single rule so it can remove the directory before it starts to ensure no
587 // old files remain. zipsync already does this, so build up zipArgs that
588 // zip all the per-shard directories into a single zip.
Colin Cross1a527682019-09-23 15:55:30 -0700589 outputFiles = append(outputFiles, task.copyTo...)
590 copyFrom = append(copyFrom, task.out.Paths()...)
591 zipArgs.WriteString(" -C " + task.genDir.String())
592 zipArgs.WriteString(android.JoinWithPrefix(task.out.Strings(), " -f "))
593 } else {
594 outputFiles = append(outputFiles, task.out...)
595 }
Colin Cross6f080df2016-11-04 15:32:58 -0700596 }
597
Colin Cross1a527682019-09-23 15:55:30 -0700598 if len(copyFrom) > 0 {
Colin Cross3d680512020-11-13 16:23:53 -0800599 // Create a rule that zips all the per-shard directories into a single zip and then
600 // uses zipsync to unzip it into the final directory.
Colin Cross1a527682019-09-23 15:55:30 -0700601 ctx.Build(pctx, android.BuildParams{
Colin Crossf1885962020-11-20 15:28:30 -0800602 Rule: gensrcsMerge,
603 Implicits: copyFrom,
604 Outputs: outputFiles,
605 Description: "merge shards",
Colin Cross1a527682019-09-23 15:55:30 -0700606 Args: map[string]string{
607 "zipArgs": zipArgs.String(),
608 "tmpZip": android.PathForModuleGen(ctx, g.subDir+".zip").String(),
609 "genDir": android.PathForModuleGen(ctx, g.subDir).String(),
610 },
611 })
Colin Cross85a2e892018-07-09 09:45:06 -0700612 }
613
Colin Cross1a527682019-09-23 15:55:30 -0700614 g.outputFiles = outputFiles.Paths()
Chris Parsonsf874e462022-05-10 13:50:12 -0400615}
Jeff Gastonefc1b412017-03-29 17:29:06 -0700616
Chris Parsonsf874e462022-05-10 13:50:12 -0400617func (g *Module) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Vinh Tran140d5882022-06-10 14:23:27 -0400618 // Allowlist genrule to use depfile until we have a solution to remove it.
619 // TODO(b/235582219): Remove allowlist for genrule
Yu Liu6a7940c2023-05-09 17:12:22 -0700620 if Bool(g.properties.Depfile) {
Yu Liu45d6af52023-05-24 23:10:18 +0000621 if DepfileAllowSet == nil {
622 DepfileAllowSetLock.Lock()
623 defer DepfileAllowSetLock.Unlock()
624 DepfileAllowSet = map[string]bool{}
625 android.AddToStringSet(DepfileAllowSet, DepfileAllowList)
626 }
Yu Liu6a7940c2023-05-09 17:12:22 -0700627 // TODO(b/283852474): Checking the GenruleSandboxing flag is temporary in
628 // order to pass the presubmit before internal master is updated.
629 if ctx.DeviceConfig().GenruleSandboxing() && !DepfileAllowSet[g.Name()] {
630 ctx.PropertyErrorf(
631 "depfile",
632 "Deprecated to ensure the module type is convertible to Bazel. "+
633 "Try specifying the dependencies explicitly so that there is no need to use depfile. "+
634 "If not possible, the escape hatch is to add the module to allowlists.go to bypass the error.")
635 }
Vinh Tran140d5882022-06-10 14:23:27 -0400636 }
637
Chris Parsonsf874e462022-05-10 13:50:12 -0400638 g.generateCommonBuildActions(ctx)
639
640 // For <= 6 outputs, just embed those directly in the users. Right now, that covers >90% of
641 // the genrules on AOSP. That will make things simpler to look at the graph in the common
642 // case. For larger sets of outputs, inject a phony target in between to limit ninja file
643 // growth.
644 if len(g.outputFiles) <= 6 {
645 g.outputDeps = g.outputFiles
646 } else {
647 phonyFile := android.PathForModuleGen(ctx, "genrule-phony")
648 ctx.Build(pctx, android.BuildParams{
649 Rule: blueprint.Phony,
650 Output: phonyFile,
651 Inputs: g.outputFiles,
652 })
653 g.outputDeps = android.Paths{phonyFile}
Jeff Gaston02a684b2017-10-27 14:59:27 -0700654 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400655}
656
657func (g *Module) QueueBazelCall(ctx android.BaseModuleContext) {
658 bazelCtx := ctx.Config().BazelContext
659 bazelCtx.QueueBazelRequest(g.GetBazelLabel(ctx, g), cquery.GetOutputFiles, android.GetConfigKey(ctx))
660}
661
662func (g *Module) IsMixedBuildSupported(ctx android.BaseModuleContext) bool {
663 return true
Colin Crossd350ecd2015-04-28 13:25:36 -0700664}
Colin Crossd350ecd2015-04-28 13:25:36 -0700665
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700666// Collect information for opening IDE project files in java/jdeps.go.
667func (g *Module) IDEInfo(dpInfo *android.IdeInfo) {
668 dpInfo.Srcs = append(dpInfo.Srcs, g.Srcs().Strings()...)
669 for _, src := range g.properties.Srcs {
670 if strings.HasPrefix(src, ":") {
671 src = strings.Trim(src, ":")
672 dpInfo.Deps = append(dpInfo.Deps, src)
673 }
674 }
bralee1fbf4402020-05-21 10:11:59 +0800675 dpInfo.Paths = append(dpInfo.Paths, g.modulePaths...)
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700676}
677
Colin Crossa4ad2b02019-03-18 22:15:32 -0700678func (g *Module) AndroidMk() android.AndroidMkData {
679 return android.AndroidMkData{
Anton Hansson72f18492020-10-30 16:34:45 +0000680 Class: "ETC",
Colin Crossa4ad2b02019-03-18 22:15:32 -0700681 OutputFile: android.OptionalPathForPath(g.outputFiles[0]),
682 SubName: g.subName,
683 Extra: []android.AndroidMkExtraFunc{
684 func(w io.Writer, outputFile android.Path) {
Anton Hansson72f18492020-10-30 16:34:45 +0000685 fmt.Fprintln(w, "LOCAL_UNINSTALLABLE_MODULE := true")
Colin Crossa4ad2b02019-03-18 22:15:32 -0700686 },
687 },
688 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
689 android.WriteAndroidMkData(w, data)
690 if data.SubName != "" {
691 fmt.Fprintln(w, ".PHONY:", name)
692 fmt.Fprintln(w, name, ":", name+g.subName)
693 }
694 },
695 }
696}
697
Jiyong Park45bf82e2020-12-15 22:29:02 +0900698var _ android.ApexModule = (*Module)(nil)
699
700// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -0700701func (g *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
702 sdkVersion android.ApiLevel) error {
Jooyung Han749dc692020-04-15 11:03:39 +0900703 // Because generated outputs are checked by client modules(e.g. cc_library, ...)
704 // we can safely ignore the check here.
705 return nil
706}
707
Jeff Gaston437d23c2017-11-08 12:38:00 -0800708func generatorFactory(taskGenerator taskFunc, props ...interface{}) *Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700709 module := &Module{
Jeff Gaston437d23c2017-11-08 12:38:00 -0800710 taskGenerator: taskGenerator,
Colin Crossd350ecd2015-04-28 13:25:36 -0700711 }
712
Colin Cross36242852017-06-23 15:06:31 -0700713 module.AddProperties(props...)
714 module.AddProperties(&module.properties)
Colin Crossd350ecd2015-04-28 13:25:36 -0700715
Colin Cross7228ecd2019-11-18 16:00:16 -0800716 module.ImageInterface = noopImageInterface{}
717
Colin Cross36242852017-06-23 15:06:31 -0700718 return module
Colin Crossd350ecd2015-04-28 13:25:36 -0700719}
720
Colin Cross7228ecd2019-11-18 16:00:16 -0800721type noopImageInterface struct{}
722
723func (x noopImageInterface) ImageMutatorBegin(android.BaseModuleContext) {}
724func (x noopImageInterface) CoreVariantNeeded(android.BaseModuleContext) bool { return false }
Yifan Hong1b3348d2020-01-21 15:53:22 -0800725func (x noopImageInterface) RamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700726func (x noopImageInterface) VendorRamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Inseob Kim08758f02021-04-08 21:13:22 +0900727func (x noopImageInterface) DebugRamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Colin Cross7228ecd2019-11-18 16:00:16 -0800728func (x noopImageInterface) RecoveryVariantNeeded(android.BaseModuleContext) bool { return false }
729func (x noopImageInterface) ExtraImageVariations(ctx android.BaseModuleContext) []string { return nil }
730func (x noopImageInterface) SetImageVariation(ctx android.BaseModuleContext, variation string, module android.Module) {
731}
732
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700733func NewGenSrcs() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700734 properties := &genSrcsProperties{}
735
Colin Crossf1885962020-11-20 15:28:30 -0800736 // finalSubDir is the name of the subdirectory that output files will be generated into.
737 // It is used so that per-shard directories can be placed alongside it an then finally
738 // merged into it.
739 const finalSubDir = "gensrcs"
740
Colin Cross1a527682019-09-23 15:55:30 -0700741 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Colin Cross1a527682019-09-23 15:55:30 -0700742 shardSize := defaultShardSize
743 if s := properties.Shard_size; s != nil {
744 shardSize = int(*s)
745 }
Jeff Gaston437d23c2017-11-08 12:38:00 -0800746
Colin Crossf1885962020-11-20 15:28:30 -0800747 // gensrcs rules can easily hit command line limits by repeating the command for
748 // every input file. Shard the input files into groups.
Colin Cross1a527682019-09-23 15:55:30 -0700749 shards := android.ShardPaths(srcFiles, shardSize)
750 var generateTasks []generateTask
Colin Crossbaccf5b2018-02-21 14:07:48 -0800751
Colin Cross1a527682019-09-23 15:55:30 -0700752 for i, shard := range shards {
753 var commands []string
754 var outFiles android.WritablePaths
Colin Cross3ea4eb82020-11-24 13:07:27 -0800755 var commandDepFiles []string
Colin Cross1a527682019-09-23 15:55:30 -0700756 var copyTo android.WritablePaths
Colin Cross1a527682019-09-23 15:55:30 -0700757
Colin Crossf1885962020-11-20 15:28:30 -0800758 // When sharding is enabled (i.e. len(shards) > 1), the sbox rules for each
759 // shard will be write to their own directories and then be merged together
760 // into finalSubDir. If sharding is not enabled (i.e. len(shards) == 1),
761 // the sbox rule will write directly to finalSubDir.
762 genSubDir := finalSubDir
Colin Cross1a527682019-09-23 15:55:30 -0700763 if len(shards) > 1 {
Colin Crossf1885962020-11-20 15:28:30 -0800764 genSubDir = strconv.Itoa(i)
Jeff Gaston437d23c2017-11-08 12:38:00 -0800765 }
766
Colin Crossf1885962020-11-20 15:28:30 -0800767 genDir := android.PathForModuleGen(ctx, genSubDir)
Colin Crossf1a035e2020-11-16 17:32:30 -0800768 // TODO(ccross): this RuleBuilder is a hack to be able to call
769 // rule.Command().PathForOutput. Replace this with passing the rule into the
770 // generator.
Yu Liu6a7940c2023-05-09 17:12:22 -0700771 rule := getSandboxedRuleBuilder(ctx, android.NewRuleBuilder(pctx, ctx).Sbox(genDir, nil))
Jeff Gaston437d23c2017-11-08 12:38:00 -0800772
Colin Cross3ea4eb82020-11-24 13:07:27 -0800773 for _, in := range shard {
Colin Crossf1885962020-11-20 15:28:30 -0800774 outFile := android.GenPathWithExt(ctx, finalSubDir, in, String(properties.Output_extension))
775
776 // If sharding is enabled, then outFile is the path to the output file in
777 // the shard directory, and copyTo is the path to the output file in the
778 // final directory.
Colin Cross1a527682019-09-23 15:55:30 -0700779 if len(shards) > 1 {
Colin Crossf1885962020-11-20 15:28:30 -0800780 shardFile := android.GenPathWithExt(ctx, genSubDir, in, String(properties.Output_extension))
Colin Cross1a527682019-09-23 15:55:30 -0700781 copyTo = append(copyTo, outFile)
782 outFile = shardFile
783 }
784
785 outFiles = append(outFiles, outFile)
Colin Cross1a527682019-09-23 15:55:30 -0700786
Colin Crossf1885962020-11-20 15:28:30 -0800787 // pre-expand the command line to replace $in and $out with references to
788 // a single input and output file.
Colin Cross1a527682019-09-23 15:55:30 -0700789 command, err := android.Expand(rawCommand, func(name string) (string, error) {
790 switch name {
791 case "in":
792 return in.String(), nil
793 case "out":
Colin Crossf1a035e2020-11-16 17:32:30 -0800794 return rule.Command().PathForOutput(outFile), nil
Colin Cross3ea4eb82020-11-24 13:07:27 -0800795 case "depfile":
796 // Generate a depfile for each output file. Store the list for
797 // later in order to combine them all into a single depfile.
Colin Crossf1a035e2020-11-16 17:32:30 -0800798 depFile := rule.Command().PathForOutput(outFile.ReplaceExtension(ctx, "d"))
Colin Cross3ea4eb82020-11-24 13:07:27 -0800799 commandDepFiles = append(commandDepFiles, depFile)
800 return depFile, nil
Colin Cross1a527682019-09-23 15:55:30 -0700801 default:
802 return "$(" + name + ")", nil
803 }
804 })
805 if err != nil {
806 ctx.PropertyErrorf("cmd", err.Error())
807 }
808
809 // escape the command in case for example it contains '#', an odd number of '"', etc
810 command = fmt.Sprintf("bash -c %v", proptools.ShellEscape(command))
811 commands = append(commands, command)
812 }
813 fullCommand := strings.Join(commands, " && ")
814
Colin Cross3ea4eb82020-11-24 13:07:27 -0800815 var outputDepfile android.WritablePath
816 var extraTools android.Paths
817 if len(commandDepFiles) > 0 {
818 // Each command wrote to a depfile, but ninja can only handle one
819 // depfile per rule. Use the dep_fixer tool at the end of the
820 // command to combine all the depfiles into a single output depfile.
821 outputDepfile = android.PathForModuleGen(ctx, genSubDir, "gensrcs.d")
822 depFixerTool := ctx.Config().HostToolPath(ctx, "dep_fixer")
823 fullCommand += fmt.Sprintf(" && %s -o $(depfile) %s",
Colin Crossd11cf622021-03-23 22:30:35 -0700824 rule.Command().PathForTool(depFixerTool),
Colin Crossba9e4032020-11-24 16:32:22 -0800825 strings.Join(commandDepFiles, " "))
Colin Cross3ea4eb82020-11-24 13:07:27 -0800826 extraTools = append(extraTools, depFixerTool)
827 }
828
Colin Cross1a527682019-09-23 15:55:30 -0700829 generateTasks = append(generateTasks, generateTask{
Colin Cross3ea4eb82020-11-24 13:07:27 -0800830 in: shard,
831 out: outFiles,
832 depFile: outputDepfile,
833 copyTo: copyTo,
834 genDir: genDir,
835 cmd: fullCommand,
836 shard: i,
837 shards: len(shards),
838 extraTools: extraTools,
Liz Kammer81fec182023-06-09 13:33:45 -0400839 extraInputs: map[string][]string{
840 "data": properties.Data,
841 },
Colin Cross1a527682019-09-23 15:55:30 -0700842 })
Jeff Gaston437d23c2017-11-08 12:38:00 -0800843 }
Colin Cross1a527682019-09-23 15:55:30 -0700844
845 return generateTasks
Colin Crossd350ecd2015-04-28 13:25:36 -0700846 }
847
Colin Cross1a527682019-09-23 15:55:30 -0700848 g := generatorFactory(taskGenerator, properties)
Colin Crossf1885962020-11-20 15:28:30 -0800849 g.subDir = finalSubDir
Colin Cross1a527682019-09-23 15:55:30 -0700850 return g
Colin Crossd350ecd2015-04-28 13:25:36 -0700851}
852
Colin Cross54190b32017-10-09 15:34:10 -0700853func GenSrcsFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700854 m := NewGenSrcs()
855 android.InitAndroidModule(m)
Vinh Tranb69e1ae2022-05-20 18:54:09 -0400856 android.InitBazelModule(m)
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700857 return m
858}
859
Colin Crossd350ecd2015-04-28 13:25:36 -0700860type genSrcsProperties struct {
Colin Cross7d5136f2015-05-11 13:39:40 -0700861 // extension that will be substituted for each output file
Nan Zhanga5e7cb42017-11-09 22:42:32 -0800862 Output_extension *string
Colin Cross1a527682019-09-23 15:55:30 -0700863
864 // maximum number of files that will be passed on a single command line.
865 Shard_size *int64
Liz Kammer81fec182023-06-09 13:33:45 -0400866
867 // Additional files needed for build that are not tooling related.
868 Data []string `android:"path"`
Colin Cross5049f022015-03-18 13:28:46 -0700869}
870
Vinh Tranb69e1ae2022-05-20 18:54:09 -0400871type bazelGensrcsAttributes struct {
872 Srcs bazel.LabelListAttribute
873 Output_extension *string
874 Tools bazel.LabelListAttribute
875 Cmd string
Liz Kammer8bd92422023-06-09 13:41:08 -0400876 Data bazel.LabelListAttribute
Vinh Tranb69e1ae2022-05-20 18:54:09 -0400877}
878
Evgenii Stepanovf47c90d2020-12-02 18:55:09 -0800879const defaultShardSize = 50
Colin Cross1a527682019-09-23 15:55:30 -0700880
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700881func NewGenRule() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700882 properties := &genRuleProperties{}
Colin Cross5049f022015-03-18 13:28:46 -0700883
Colin Cross1a527682019-09-23 15:55:30 -0700884 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700885 outs := make(android.WritablePaths, len(properties.Out))
Colin Cross3d680512020-11-13 16:23:53 -0800886 var depFile android.WritablePath
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700887 for i, out := range properties.Out {
Colin Cross3d680512020-11-13 16:23:53 -0800888 outPath := android.PathForModuleGen(ctx, out)
889 if i == 0 {
890 depFile = outPath.ReplaceExtension(ctx, "d")
891 }
892 outs[i] = outPath
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700893 }
Colin Cross1a527682019-09-23 15:55:30 -0700894 return []generateTask{{
Colin Cross3d680512020-11-13 16:23:53 -0800895 in: srcFiles,
896 out: outs,
897 depFile: depFile,
898 genDir: android.PathForModuleGen(ctx),
899 cmd: rawCommand,
Colin Cross1a527682019-09-23 15:55:30 -0700900 }}
Colin Cross5049f022015-03-18 13:28:46 -0700901 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700902
Jeff Gaston437d23c2017-11-08 12:38:00 -0800903 return generatorFactory(taskGenerator, properties)
Colin Cross5049f022015-03-18 13:28:46 -0700904}
905
Colin Cross54190b32017-10-09 15:34:10 -0700906func GenRuleFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700907 m := NewGenRule()
908 android.InitAndroidModule(m)
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800909 android.InitDefaultableModule(m)
Liz Kammerea6666f2021-02-17 10:17:28 -0500910 android.InitBazelModule(m)
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700911 return m
912}
913
Colin Crossd350ecd2015-04-28 13:25:36 -0700914type genRuleProperties struct {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700915 // names of the output files that will be generated
Yu Liud6201012022-10-17 12:29:15 -0700916 Out []string
Colin Cross5049f022015-03-18 13:28:46 -0700917}
Nan Zhangea568a42017-11-08 21:20:04 -0800918
Jingwen Chen316e07c2020-12-14 09:09:52 -0500919type bazelGenruleAttributes struct {
Jingwen Chen07027912021-03-15 06:02:43 -0400920 Srcs bazel.LabelListAttribute
Jingwen Chen316e07c2020-12-14 09:09:52 -0500921 Outs []string
Jingwen Chen07027912021-03-15 06:02:43 -0400922 Tools bazel.LabelListAttribute
Jingwen Chen316e07c2020-12-14 09:09:52 -0500923 Cmd string
924}
925
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400926// ConvertWithBp2build converts a Soong module -> Bazel target.
927func (m *Module) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
Liz Kammer356f7d42021-01-26 09:18:53 -0500928 // Bazel only has the "tools" attribute.
Jingwen Chen07027912021-03-15 06:02:43 -0400929 tools_prop := android.BazelLabelForModuleDeps(ctx, m.properties.Tools)
930 tool_files_prop := android.BazelLabelForModuleSrc(ctx, m.properties.Tool_files)
931 tools_prop.Append(tool_files_prop)
Liz Kammer356f7d42021-01-26 09:18:53 -0500932
Jingwen Chen07027912021-03-15 06:02:43 -0400933 tools := bazel.MakeLabelListAttribute(tools_prop)
Yu Liud6201012022-10-17 12:29:15 -0700934 srcs := bazel.LabelListAttribute{}
935 srcs_labels := bazel.LabelList{}
936 // Only cc_genrule is arch specific
937 if ctx.ModuleType() == "cc_genrule" {
938 for axis, configToProps := range m.GetArchVariantProperties(ctx, &generatorProperties{}) {
939 for config, props := range configToProps {
940 if props, ok := props.(*generatorProperties); ok {
941 labels := android.BazelLabelForModuleSrcExcludes(ctx, props.Srcs, props.Exclude_srcs)
942 srcs_labels.Append(labels)
943 srcs.SetSelectValue(axis, config, labels)
944 }
945 }
946 }
947 } else {
948 srcs_labels = android.BazelLabelForModuleSrcExcludes(ctx, m.properties.Srcs, m.properties.Exclude_srcs)
949 srcs = bazel.MakeLabelListAttribute(srcs_labels)
950 }
Liz Kammer356f7d42021-01-26 09:18:53 -0500951
952 var allReplacements bazel.LabelList
Jingwen Chen07027912021-03-15 06:02:43 -0400953 allReplacements.Append(tools.Value)
Yu Liud6201012022-10-17 12:29:15 -0700954 allReplacements.Append(bazel.FirstUniqueBazelLabelList(srcs_labels))
Liz Kammer356f7d42021-01-26 09:18:53 -0500955
Liz Kammer8bd92422023-06-09 13:41:08 -0400956 // The Output_extension prop is not in an immediately accessible field
957 // in the Module struct, so use GetProperties and cast it
958 // to the known struct prop.
959 var outputExtension *string
960 var data bazel.LabelListAttribute
961 if ctx.ModuleType() == "gensrcs" {
962 for _, propIntf := range m.GetProperties() {
963 if props, ok := propIntf.(*genSrcsProperties); ok {
964 outputExtension = props.Output_extension
965 dataFiles := android.BazelLabelForModuleSrc(ctx, props.Data)
966 allReplacements.Append(bazel.FirstUniqueBazelLabelList(dataFiles))
967 data = bazel.MakeLabelListAttribute(dataFiles)
968 break
969 }
970 }
971 }
972
Liz Kammer356f7d42021-01-26 09:18:53 -0500973 // Replace in and out variables with $< and $@
974 var cmd string
975 if m.properties.Cmd != nil {
Vinh Tranb69e1ae2022-05-20 18:54:09 -0400976 if ctx.ModuleType() == "gensrcs" {
977 cmd = strings.ReplaceAll(*m.properties.Cmd, "$(in)", "$(SRC)")
978 cmd = strings.ReplaceAll(cmd, "$(out)", "$(OUT)")
979 } else {
980 cmd = strings.Replace(*m.properties.Cmd, "$(in)", "$(SRCS)", -1)
981 cmd = strings.Replace(cmd, "$(out)", "$(OUTS)", -1)
982 }
Vinh Tran32a98a52022-09-23 13:08:34 -0400983 cmd = strings.Replace(cmd, "$(genDir)", "$(RULEDIR)", -1)
Jingwen Chen07027912021-03-15 06:02:43 -0400984 if len(tools.Value.Includes) > 0 {
985 cmd = strings.Replace(cmd, "$(location)", fmt.Sprintf("$(location %s)", tools.Value.Includes[0].Label), -1)
986 cmd = strings.Replace(cmd, "$(locations)", fmt.Sprintf("$(locations %s)", tools.Value.Includes[0].Label), -1)
Liz Kammer356f7d42021-01-26 09:18:53 -0500987 }
988 for _, l := range allReplacements.Includes {
Jingwen Chen38e62642021-04-19 05:00:15 +0000989 bpLoc := fmt.Sprintf("$(location %s)", l.OriginalModuleName)
990 bpLocs := fmt.Sprintf("$(locations %s)", l.OriginalModuleName)
Liz Kammer356f7d42021-01-26 09:18:53 -0500991 bazelLoc := fmt.Sprintf("$(location %s)", l.Label)
992 bazelLocs := fmt.Sprintf("$(locations %s)", l.Label)
993 cmd = strings.Replace(cmd, bpLoc, bazelLoc, -1)
994 cmd = strings.Replace(cmd, bpLocs, bazelLocs, -1)
995 }
996 }
997
Spandan Das39b6cc52023-04-12 19:05:49 +0000998 tags := android.ApexAvailableTagsWithoutTestApexes(ctx, m)
Sam Delmericoeddd3c02022-12-02 17:31:58 -0500999
Vinh Tranb69e1ae2022-05-20 18:54:09 -04001000 if ctx.ModuleType() == "gensrcs" {
Vinh Tranb69e1ae2022-05-20 18:54:09 -04001001 props := bazel.BazelTargetModuleProperties{
1002 Rule_class: "gensrcs",
1003 Bzl_load_location: "//build/bazel/rules:gensrcs.bzl",
1004 }
1005 attrs := &bazelGensrcsAttributes{
1006 Srcs: srcs,
1007 Output_extension: outputExtension,
1008 Cmd: cmd,
1009 Tools: tools,
Liz Kammer8bd92422023-06-09 13:41:08 -04001010 Data: data,
Vinh Tranb69e1ae2022-05-20 18:54:09 -04001011 }
Sam Delmericoeddd3c02022-12-02 17:31:58 -05001012 ctx.CreateBazelTargetModule(props, android.CommonAttributes{
1013 Name: m.Name(),
1014 Tags: tags,
1015 }, attrs)
Vinh Tranb69e1ae2022-05-20 18:54:09 -04001016 } else {
1017 // The Out prop is not in an immediately accessible field
1018 // in the Module struct, so use GetProperties and cast it
1019 // to the known struct prop.
1020 var outs []string
1021 for _, propIntf := range m.GetProperties() {
1022 if props, ok := propIntf.(*genRuleProperties); ok {
1023 outs = props.Out
1024 break
1025 }
1026 }
1027 attrs := &bazelGenruleAttributes{
1028 Srcs: srcs,
1029 Outs: outs,
1030 Cmd: cmd,
1031 Tools: tools,
1032 }
1033 props := bazel.BazelTargetModuleProperties{
1034 Rule_class: "genrule",
1035 }
Sam Delmericoeddd3c02022-12-02 17:31:58 -05001036 ctx.CreateBazelTargetModule(props, android.CommonAttributes{
1037 Name: m.Name(),
1038 Tags: tags,
1039 }, attrs)
Liz Kammer356f7d42021-01-26 09:18:53 -05001040 }
Jingwen Chen316e07c2020-12-14 09:09:52 -05001041}
1042
Nan Zhangea568a42017-11-08 21:20:04 -08001043var Bool = proptools.Bool
1044var String = proptools.String
Jaewoong Jung98716bd2018-12-10 08:13:18 -08001045
Jaewoong Jung98716bd2018-12-10 08:13:18 -08001046// Defaults
Jaewoong Jung98716bd2018-12-10 08:13:18 -08001047type Defaults struct {
1048 android.ModuleBase
1049 android.DefaultsModuleBase
1050}
1051
Jaewoong Jung98716bd2018-12-10 08:13:18 -08001052func defaultsFactory() android.Module {
1053 return DefaultsFactory()
1054}
1055
1056func DefaultsFactory(props ...interface{}) android.Module {
1057 module := &Defaults{}
1058
1059 module.AddProperties(props...)
1060 module.AddProperties(
1061 &generatorProperties{},
1062 &genRuleProperties{},
1063 )
1064
1065 android.InitDefaultsModule(module)
1066
1067 return module
1068}
Yu Liu6a7940c2023-05-09 17:12:22 -07001069
1070func getSandboxedRuleBuilder(ctx android.ModuleContext, r *android.RuleBuilder) *android.RuleBuilder {
Yu Liu45d6af52023-05-24 23:10:18 +00001071 if !ctx.DeviceConfig().GenruleSandboxing() {
1072 return r.SandboxTools()
1073 }
1074 if SandboxingDenyModuleSet == nil {
1075 SandboxingDenyModuleSetLock.Lock()
1076 defer SandboxingDenyModuleSetLock.Unlock()
1077 SandboxingDenyModuleSet = map[string]bool{}
1078 SandboxingDenyPathSet = map[string]bool{}
1079 android.AddToStringSet(SandboxingDenyModuleSet, append(DepfileAllowList, SandboxingDenyModuleList...))
1080 android.AddToStringSet(SandboxingDenyPathSet, SandboxingDenyPathList)
1081 }
1082
1083 if SandboxingDenyPathSet[ctx.ModuleDir()] || SandboxingDenyModuleSet[ctx.ModuleName()] {
Yu Liu6a7940c2023-05-09 17:12:22 -07001084 return r.SandboxTools()
1085 }
1086 return r.SandboxInputs()
1087}