blob: 4992625e556d04368c83fbb929c6bf3114bb0f27 [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 {
Colin Cross3ea4eb82020-11-24 13:07:27 -0800206 in android.Paths
207 out android.WritablePaths
208 depFile android.WritablePath
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500209 copyTo android.WritablePaths // For gensrcs to set on gensrcsMerge rule.
Colin Cross3ea4eb82020-11-24 13:07:27 -0800210 genDir android.WritablePath
211 extraTools android.Paths // dependencies on tools used by the generator
212
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500213 cmd string
214 // For gensrsc sharding.
Colin Cross3ea4eb82020-11-24 13:07:27 -0800215 shard int
216 shards int
Colin Crossd350ecd2015-04-28 13:25:36 -0700217}
218
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700219func (g *Module) GeneratedSourceFiles() android.Paths {
Colin Crossd350ecd2015-04-28 13:25:36 -0700220 return g.outputFiles
221}
222
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700223func (g *Module) Srcs() android.Paths {
Nan Zhange42777a2018-03-27 16:19:42 -0700224 return append(android.Paths{}, g.outputFiles...)
Colin Cross068e0fe2016-12-13 15:23:47 -0800225}
226
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700227func (g *Module) GeneratedHeaderDirs() android.Paths {
Colin Cross5ed99c62016-11-22 12:55:55 -0800228 return g.exportedIncludeDirs
Dan Willemsenb40aab62016-04-20 14:21:14 -0700229}
230
Dan Willemsen9da9d492018-02-21 18:28:18 -0800231func (g *Module) GeneratedDeps() android.Paths {
232 return g.outputDeps
233}
234
Jooyung Han8c7e3ed2021-06-28 17:35:58 +0900235func (g *Module) OutputFiles(tag string) (android.Paths, error) {
236 if tag == "" {
237 return append(android.Paths{}, g.outputFiles...), nil
238 }
239 // otherwise, tag should match one of outputs
240 for _, outputFile := range g.outputFiles {
241 if outputFile.Rel() == tag {
242 return android.Paths{outputFile}, nil
243 }
244 }
245 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
246}
247
248var _ android.SourceFileProducer = (*Module)(nil)
249var _ android.OutputFileProducer = (*Module)(nil)
250
Martin Stjernholm710ec3a2020-01-16 15:12:04 +0000251func toolDepsMutator(ctx android.BottomUpMutatorContext) {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700252 if g, ok := ctx.Module().(*Module); ok {
Colin Cross08f15ab2018-10-04 23:29:14 -0700253 for _, tool := range g.properties.Tools {
254 tag := hostToolDependencyTag{label: tool}
255 if m := android.SrcIsModule(tool); m != "" {
256 tool = m
257 }
Colin Cross0f7d2ef2019-10-16 11:03:10 -0700258 ctx.AddFarVariationDependencies(ctx.Config().BuildOSTarget.Variations(), tag, tool)
Colin Cross6362e272015-10-29 15:25:03 -0700259 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700260 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700261}
262
Chris Parsonsf874e462022-05-10 13:50:12 -0400263func (g *Module) ProcessBazelQueryResponse(ctx android.ModuleContext) {
264 g.generateCommonBuildActions(ctx)
265
266 label := g.GetBazelLabel(ctx, g)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400267 bazelCtx := ctx.Config().BazelContext
Chris Parsonsf874e462022-05-10 13:50:12 -0400268 filePaths, err := bazelCtx.GetOutputFiles(label, android.GetConfigKey(ctx))
269 if err != nil {
270 ctx.ModuleErrorf(err.Error())
271 return
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400272 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400273
274 var bazelOutputFiles android.Paths
275 exportIncludeDirs := map[string]bool{}
276 for _, bazelOutputFile := range filePaths {
Cole Faust01243362022-06-02 12:11:12 -0700277 bazelOutputFiles = append(bazelOutputFiles, android.PathForBazelOutRelative(ctx, ctx.ModuleDir(), bazelOutputFile))
Chris Parsonsf874e462022-05-10 13:50:12 -0400278 exportIncludeDirs[filepath.Dir(bazelOutputFile)] = true
279 }
280 g.outputFiles = bazelOutputFiles
281 g.outputDeps = bazelOutputFiles
282 for includePath, _ := range exportIncludeDirs {
283 g.exportedIncludeDirs = append(g.exportedIncludeDirs, android.PathForBazelOut(ctx, includePath))
284 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400285}
Colin Crossf1885962020-11-20 15:28:30 -0800286
Chris Parsonsf874e462022-05-10 13:50:12 -0400287// generateCommonBuildActions contains build action generation logic
288// common to both the mixed build case and the legacy case of genrule processing.
289// To fully support genrule in mixed builds, the contents of this function should
290// approach zero; there should be no genrule action registration done directly
291// by Soong logic in the mixed-build case.
292func (g *Module) generateCommonBuildActions(ctx android.ModuleContext) {
Colin Crossa4ad2b02019-03-18 22:15:32 -0700293 g.subName = ctx.ModuleSubDir()
294
bralee1fbf4402020-05-21 10:11:59 +0800295 // Collect the module directory for IDE info in java/jdeps.go.
296 g.modulePaths = append(g.modulePaths, ctx.ModuleDir())
297
Colin Cross5ed99c62016-11-22 12:55:55 -0800298 if len(g.properties.Export_include_dirs) > 0 {
299 for _, dir := range g.properties.Export_include_dirs {
300 g.exportedIncludeDirs = append(g.exportedIncludeDirs,
Colin Cross1a527682019-09-23 15:55:30 -0700301 android.PathForModuleGen(ctx, g.subDir, ctx.ModuleDir(), dir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800302 }
303 } else {
Colin Cross1a527682019-09-23 15:55:30 -0700304 g.exportedIncludeDirs = append(g.exportedIncludeDirs, android.PathForModuleGen(ctx, g.subDir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800305 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700306
Colin Crossd11cf622021-03-23 22:30:35 -0700307 locationLabels := map[string]location{}
Colin Cross08f15ab2018-10-04 23:29:14 -0700308 firstLabel := ""
309
Colin Crossd11cf622021-03-23 22:30:35 -0700310 addLocationLabel := func(label string, loc location) {
Colin Cross08f15ab2018-10-04 23:29:14 -0700311 if firstLabel == "" {
312 firstLabel = label
313 }
314 if _, exists := locationLabels[label]; !exists {
Colin Crossd11cf622021-03-23 22:30:35 -0700315 locationLabels[label] = loc
Colin Cross08f15ab2018-10-04 23:29:14 -0700316 } else {
Anton Hansson7cd41e52021-10-08 16:13:10 +0100317 ctx.ModuleErrorf("multiple locations for label %q: %q and %q (do you have duplicate srcs entries?)",
Colin Crossd11cf622021-03-23 22:30:35 -0700318 label, locationLabels[label], loc)
Colin Cross08f15ab2018-10-04 23:29:14 -0700319 }
320 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700321
Colin Crossba9e4032020-11-24 16:32:22 -0800322 var tools android.Paths
323 var packagedTools []android.PackagingSpec
Colin Cross6f080df2016-11-04 15:32:58 -0700324 if len(g.properties.Tools) > 0 {
Colin Crossba71a3f2019-03-18 12:12:48 -0700325 seenTools := make(map[string]bool)
326
Colin Cross35143d02017-11-16 00:11:20 -0800327 ctx.VisitDirectDepsBlueprint(func(module blueprint.Module) {
Colin Cross08f15ab2018-10-04 23:29:14 -0700328 switch tag := ctx.OtherModuleDependencyTag(module).(type) {
329 case hostToolDependencyTag:
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700330 tool := ctx.OtherModuleName(module)
Martin Stjernholmdbd814d2022-01-12 23:18:30 +0000331 if m, ok := module.(android.Module); ok {
332 // Necessary to retrieve any prebuilt replacement for the tool, since
333 // toolDepsMutator runs too late for the prebuilt mutators to have
334 // replaced the dependency.
335 module = android.PrebuiltGetPreferred(ctx, m)
336 }
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700337
Colin Crossba9e4032020-11-24 16:32:22 -0800338 switch t := module.(type) {
339 case android.HostToolProvider:
340 // A HostToolProvider provides the path to a tool, which will be copied
341 // into the sandbox.
Colin Cross35143d02017-11-16 00:11:20 -0800342 if !t.(android.Module).Enabled() {
Colin Cross6510f912017-11-29 00:27:14 -0800343 if ctx.Config().AllowMissingDependencies() {
Colin Cross35143d02017-11-16 00:11:20 -0800344 ctx.AddMissingDependencies([]string{tool})
345 } else {
346 ctx.ModuleErrorf("depends on disabled module %q", tool)
347 }
Colin Crossba9e4032020-11-24 16:32:22 -0800348 return
Colin Cross35143d02017-11-16 00:11:20 -0800349 }
Colin Crossba9e4032020-11-24 16:32:22 -0800350 path := t.HostToolPath()
351 if !path.Valid() {
352 ctx.ModuleErrorf("host tool %q missing output file", tool)
353 return
354 }
355 if specs := t.TransitivePackagingSpecs(); specs != nil {
356 // If the HostToolProvider has PackgingSpecs, which are definitions of the
357 // required relative locations of the tool and its dependencies, use those
358 // instead. They will be copied to those relative locations in the sbox
359 // sandbox.
360 packagedTools = append(packagedTools, specs...)
361 // Assume that the first PackagingSpec of the module is the tool.
Colin Crossd11cf622021-03-23 22:30:35 -0700362 addLocationLabel(tag.label, packagedToolLocation{specs[0]})
Colin Crossba9e4032020-11-24 16:32:22 -0800363 } else {
364 tools = append(tools, path.Path())
Colin Crossd11cf622021-03-23 22:30:35 -0700365 addLocationLabel(tag.label, toolLocation{android.Paths{path.Path()}})
Colin Crossba9e4032020-11-24 16:32:22 -0800366 }
367 case bootstrap.GoBinaryTool:
368 // A GoBinaryTool provides the install path to a tool, which will be copied.
Colin Crossa44551f2021-10-25 15:36:21 -0700369 p := android.PathForGoBinary(ctx, t)
370 tools = append(tools, p)
371 addLocationLabel(tag.label, toolLocation{android.Paths{p}})
Colin Crossba9e4032020-11-24 16:32:22 -0800372 default:
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700373 ctx.ModuleErrorf("%q is not a host tool provider", tool)
Colin Crossba9e4032020-11-24 16:32:22 -0800374 return
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700375 }
376
Colin Crossba9e4032020-11-24 16:32:22 -0800377 seenTools[tag.label] = true
Colin Crossd350ecd2015-04-28 13:25:36 -0700378 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700379 })
Colin Crossba71a3f2019-03-18 12:12:48 -0700380
381 // If AllowMissingDependencies is enabled, the build will not have stopped when
382 // AddFarVariationDependencies was called on a missing tool, which will result in nonsensical
Liz Kammer20ebfb42020-07-28 11:32:07 -0700383 // "cmd: unknown location label ..." errors later. Add a placeholder file to the local label.
384 // The command that uses this placeholder file will never be executed because the rule will be
385 // replaced with an android.Error rule reporting the missing dependencies.
Colin Crossba71a3f2019-03-18 12:12:48 -0700386 if ctx.Config().AllowMissingDependencies() {
387 for _, tool := range g.properties.Tools {
388 if !seenTools[tool] {
Colin Crossd11cf622021-03-23 22:30:35 -0700389 addLocationLabel(tool, errorLocation{"***missing tool " + tool + "***"})
Colin Crossba71a3f2019-03-18 12:12:48 -0700390 }
391 }
392 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700393 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700394
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700395 if ctx.Failed() {
396 return
397 }
398
Colin Cross08f15ab2018-10-04 23:29:14 -0700399 for _, toolFile := range g.properties.Tool_files {
Colin Cross8a497952019-03-05 22:25:09 -0800400 paths := android.PathsForModuleSrc(ctx, []string{toolFile})
Colin Crossba9e4032020-11-24 16:32:22 -0800401 tools = append(tools, paths...)
Colin Crossd11cf622021-03-23 22:30:35 -0700402 addLocationLabel(toolFile, toolLocation{paths})
Colin Cross08f15ab2018-10-04 23:29:14 -0700403 }
404
Liz Kammer619be462022-01-28 15:13:39 -0500405 includeDirInPaths := ctx.DeviceConfig().BuildBrokenInputDir(g.Name())
Colin Cross08f15ab2018-10-04 23:29:14 -0700406 var srcFiles android.Paths
407 for _, in := range g.properties.Srcs {
Liz Kammer619be462022-01-28 15:13:39 -0500408 paths, missingDeps := android.PathsAndMissingDepsRelativeToModuleSourceDir(android.SourceInput{
409 Context: ctx, Paths: []string{in}, ExcludePaths: g.properties.Exclude_srcs, IncludeDirs: includeDirInPaths,
410 })
Colin Crossba71a3f2019-03-18 12:12:48 -0700411 if len(missingDeps) > 0 {
412 if !ctx.Config().AllowMissingDependencies() {
413 panic(fmt.Errorf("should never get here, the missing dependencies %q should have been reported in DepsMutator",
414 missingDeps))
415 }
416
417 // If AllowMissingDependencies is enabled, the build will not have stopped when
418 // the dependency was added on a missing SourceFileProducer module, which will result in nonsensical
Liz Kammer20ebfb42020-07-28 11:32:07 -0700419 // "cmd: label ":..." has no files" errors later. Add a placeholder file to the local label.
420 // The command that uses this placeholder file will never be executed because the rule will be
421 // replaced with an android.Error rule reporting the missing dependencies.
Colin Crossba71a3f2019-03-18 12:12:48 -0700422 ctx.AddMissingDependencies(missingDeps)
Colin Crossd11cf622021-03-23 22:30:35 -0700423 addLocationLabel(in, errorLocation{"***missing srcs " + in + "***"})
Colin Crossba71a3f2019-03-18 12:12:48 -0700424 } else {
425 srcFiles = append(srcFiles, paths...)
Colin Crossd11cf622021-03-23 22:30:35 -0700426 addLocationLabel(in, inputLocation{paths})
Colin Crossba71a3f2019-03-18 12:12:48 -0700427 }
Colin Cross08f15ab2018-10-04 23:29:14 -0700428 }
429
Colin Cross1a527682019-09-23 15:55:30 -0700430 var copyFrom android.Paths
431 var outputFiles android.WritablePaths
432 var zipArgs strings.Builder
Colin Cross08f15ab2018-10-04 23:29:14 -0700433
Colin Crossf3bfd022021-09-27 15:15:06 -0700434 cmd := String(g.properties.Cmd)
435 if g.CmdModifier != nil {
436 cmd = g.CmdModifier(ctx, cmd)
437 }
438
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500439 // Generate tasks, either from genrule or gensrcs.
Colin Crossf3bfd022021-09-27 15:15:06 -0700440 for _, 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
Colin Crossf1a035e2020-11-16 17:32:30 -0800446 // Pick a unique path outside the task.genDir for the sbox manifest textproto,
447 // a unique rule name, and the user-visible description.
448 manifestName := "genrule.sbox.textproto"
449 desc := "generate"
450 name := "generator"
451 if task.shards > 0 {
452 manifestName = "genrule_" + strconv.Itoa(task.shard) + ".sbox.textproto"
453 desc += " " + strconv.Itoa(task.shard)
454 name += strconv.Itoa(task.shard)
455 } else if len(task.out) == 1 {
456 desc += " " + task.out[0].Base()
457 }
458
459 manifestPath := android.PathForModuleOut(ctx, manifestName)
460
461 // Use a RuleBuilder to create a rule that runs the command inside an sbox sandbox.
Yu Liu6a7940c2023-05-09 17:12:22 -0700462 rule := getSandboxedRuleBuilder(ctx, android.NewRuleBuilder(pctx, ctx).Sbox(task.genDir, manifestPath))
Colin Crossf1a035e2020-11-16 17:32:30 -0800463 cmd := rule.Command()
464
Colin Cross3d680512020-11-13 16:23:53 -0800465 for _, out := range task.out {
Colin Crossd11cf622021-03-23 22:30:35 -0700466 addLocationLabel(out.Rel(), outputLocation{out})
Colin Cross3d680512020-11-13 16:23:53 -0800467 }
468
Colin Cross1a527682019-09-23 15:55:30 -0700469 referencedDepfile := false
470
Colin Cross3d680512020-11-13 16:23:53 -0800471 rawCommand, err := android.Expand(task.cmd, func(name string) (string, error) {
Colin Cross1a527682019-09-23 15:55:30 -0700472 // report the error directly without returning an error to android.Expand to catch multiple errors in a
473 // single run
Colin Cross3d680512020-11-13 16:23:53 -0800474 reportError := func(fmt string, args ...interface{}) (string, error) {
Colin Cross1a527682019-09-23 15:55:30 -0700475 ctx.PropertyErrorf("cmd", fmt, args...)
Colin Cross3d680512020-11-13 16:23:53 -0800476 return "SOONG_ERROR", nil
Colin Cross6f080df2016-11-04 15:32:58 -0700477 }
Colin Cross1a527682019-09-23 15:55:30 -0700478
Jihoon Kangc170af42022-08-20 05:26:38 +0000479 // Apply shell escape to each cases to prevent source file paths containing $ from being evaluated in shell
Colin Cross1a527682019-09-23 15:55:30 -0700480 switch name {
481 case "location":
482 if len(g.properties.Tools) == 0 && len(g.properties.Tool_files) == 0 {
483 return reportError("at least one `tools` or `tool_files` is required if $(location) is used")
Colin Cross6f080df2016-11-04 15:32:58 -0700484 }
Colin Crossd11cf622021-03-23 22:30:35 -0700485 loc := locationLabels[firstLabel]
486 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700487 if len(paths) == 0 {
488 return reportError("default label %q has no files", firstLabel)
489 } else if len(paths) > 1 {
490 return reportError("default label %q has multiple files, use $(locations %s) to reference it",
491 firstLabel, firstLabel)
Colin Cross08f15ab2018-10-04 23:29:14 -0700492 }
Jihoon Kangc170af42022-08-20 05:26:38 +0000493 return proptools.ShellEscape(paths[0]), nil
Colin Cross1a527682019-09-23 15:55:30 -0700494 case "in":
Jihoon Kangc170af42022-08-20 05:26:38 +0000495 return strings.Join(proptools.ShellEscapeList(cmd.PathsForInputs(srcFiles)), " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700496 case "out":
Colin Cross3d680512020-11-13 16:23:53 -0800497 var sandboxOuts []string
498 for _, out := range task.out {
Colin Crossf1a035e2020-11-16 17:32:30 -0800499 sandboxOuts = append(sandboxOuts, cmd.PathForOutput(out))
Colin Cross3d680512020-11-13 16:23:53 -0800500 }
Jihoon Kangc170af42022-08-20 05:26:38 +0000501 return strings.Join(proptools.ShellEscapeList(sandboxOuts), " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700502 case "depfile":
503 referencedDepfile = true
504 if !Bool(g.properties.Depfile) {
505 return reportError("$(depfile) used without depfile property")
506 }
Colin Cross3d680512020-11-13 16:23:53 -0800507 return "__SBOX_DEPFILE__", nil
Colin Cross1a527682019-09-23 15:55:30 -0700508 case "genDir":
Jihoon Kangc170af42022-08-20 05:26:38 +0000509 return proptools.ShellEscape(cmd.PathForOutput(task.genDir)), nil
Colin Cross1a527682019-09-23 15:55:30 -0700510 default:
511 if strings.HasPrefix(name, "location ") {
512 label := strings.TrimSpace(strings.TrimPrefix(name, "location "))
Colin Crossd11cf622021-03-23 22:30:35 -0700513 if loc, ok := locationLabels[label]; ok {
514 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700515 if len(paths) == 0 {
516 return reportError("label %q has no files", label)
517 } else if len(paths) > 1 {
518 return reportError("label %q has multiple files, use $(locations %s) to reference it",
519 label, label)
520 }
Jihoon Kangc170af42022-08-20 05:26:38 +0000521 return proptools.ShellEscape(paths[0]), nil
Colin Cross1a527682019-09-23 15:55:30 -0700522 } else {
Anton Hanssonbebf5262022-02-23 11:42:38 +0000523 return reportError("unknown location label %q is not in srcs, out, tools or tool_files.", label)
Colin Cross1a527682019-09-23 15:55:30 -0700524 }
525 } else if strings.HasPrefix(name, "locations ") {
526 label := strings.TrimSpace(strings.TrimPrefix(name, "locations "))
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 }
Jihoon Kangc170af42022-08-20 05:26:38 +0000532 return proptools.ShellEscape(strings.Join(paths, " ")), nil
Colin Cross1a527682019-09-23 15:55:30 -0700533 } else {
Anton Hanssonbebf5262022-02-23 11:42:38 +0000534 return reportError("unknown locations label %q is not in srcs, out, tools or tool_files.", label)
Colin Cross1a527682019-09-23 15:55:30 -0700535 }
536 } else {
537 return reportError("unknown variable '$(%s)'", name)
538 }
Colin Cross6f080df2016-11-04 15:32:58 -0700539 }
Colin Cross1a527682019-09-23 15:55:30 -0700540 })
541
542 if err != nil {
543 ctx.PropertyErrorf("cmd", "%s", err.Error())
544 return
Colin Cross6f080df2016-11-04 15:32:58 -0700545 }
Colin Cross6f080df2016-11-04 15:32:58 -0700546
Colin Cross1a527682019-09-23 15:55:30 -0700547 if Bool(g.properties.Depfile) && !referencedDepfile {
548 ctx.PropertyErrorf("cmd", "specified depfile=true but did not include a reference to '${depfile}' in cmd")
549 return
550 }
Colin Cross1a527682019-09-23 15:55:30 -0700551 g.rawCommands = append(g.rawCommands, rawCommand)
Bill Peckhamc087be12020-02-13 15:55:10 -0800552
Colin Cross3d680512020-11-13 16:23:53 -0800553 cmd.Text(rawCommand)
554 cmd.ImplicitOutputs(task.out)
555 cmd.Implicits(task.in)
Colin Crossba9e4032020-11-24 16:32:22 -0800556 cmd.ImplicitTools(tools)
557 cmd.ImplicitTools(task.extraTools)
558 cmd.ImplicitPackagedTools(packagedTools)
Colin Cross3d680512020-11-13 16:23:53 -0800559 if Bool(g.properties.Depfile) {
560 cmd.ImplicitDepFile(task.depFile)
561 }
562
563 // Create the rule to run the genrule command inside sbox.
Colin Crossf1a035e2020-11-16 17:32:30 -0800564 rule.Build(name, desc)
Colin Cross1a527682019-09-23 15:55:30 -0700565
566 if len(task.copyTo) > 0 {
Colin Cross3d680512020-11-13 16:23:53 -0800567 // If copyTo is set, multiple shards need to be copied into a single directory.
568 // task.out contains the per-shard paths, and copyTo contains the corresponding
569 // final path. The files need to be copied into the final directory by a
570 // single rule so it can remove the directory before it starts to ensure no
571 // old files remain. zipsync already does this, so build up zipArgs that
572 // zip all the per-shard directories into a single zip.
Colin Cross1a527682019-09-23 15:55:30 -0700573 outputFiles = append(outputFiles, task.copyTo...)
574 copyFrom = append(copyFrom, task.out.Paths()...)
575 zipArgs.WriteString(" -C " + task.genDir.String())
576 zipArgs.WriteString(android.JoinWithPrefix(task.out.Strings(), " -f "))
577 } else {
578 outputFiles = append(outputFiles, task.out...)
579 }
Colin Cross6f080df2016-11-04 15:32:58 -0700580 }
581
Colin Cross1a527682019-09-23 15:55:30 -0700582 if len(copyFrom) > 0 {
Colin Cross3d680512020-11-13 16:23:53 -0800583 // Create a rule that zips all the per-shard directories into a single zip and then
584 // uses zipsync to unzip it into the final directory.
Colin Cross1a527682019-09-23 15:55:30 -0700585 ctx.Build(pctx, android.BuildParams{
Colin Crossf1885962020-11-20 15:28:30 -0800586 Rule: gensrcsMerge,
587 Implicits: copyFrom,
588 Outputs: outputFiles,
589 Description: "merge shards",
Colin Cross1a527682019-09-23 15:55:30 -0700590 Args: map[string]string{
591 "zipArgs": zipArgs.String(),
592 "tmpZip": android.PathForModuleGen(ctx, g.subDir+".zip").String(),
593 "genDir": android.PathForModuleGen(ctx, g.subDir).String(),
594 },
595 })
Colin Cross85a2e892018-07-09 09:45:06 -0700596 }
597
Colin Cross1a527682019-09-23 15:55:30 -0700598 g.outputFiles = outputFiles.Paths()
Chris Parsonsf874e462022-05-10 13:50:12 -0400599}
Jeff Gastonefc1b412017-03-29 17:29:06 -0700600
Chris Parsonsf874e462022-05-10 13:50:12 -0400601func (g *Module) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Vinh Tran140d5882022-06-10 14:23:27 -0400602 // Allowlist genrule to use depfile until we have a solution to remove it.
603 // TODO(b/235582219): Remove allowlist for genrule
Yu Liu6a7940c2023-05-09 17:12:22 -0700604 if Bool(g.properties.Depfile) {
Yu Liu45d6af52023-05-24 23:10:18 +0000605 if DepfileAllowSet == nil {
606 DepfileAllowSetLock.Lock()
607 defer DepfileAllowSetLock.Unlock()
608 DepfileAllowSet = map[string]bool{}
609 android.AddToStringSet(DepfileAllowSet, DepfileAllowList)
610 }
Yu Liu6a7940c2023-05-09 17:12:22 -0700611 // TODO(b/283852474): Checking the GenruleSandboxing flag is temporary in
612 // order to pass the presubmit before internal master is updated.
613 if ctx.DeviceConfig().GenruleSandboxing() && !DepfileAllowSet[g.Name()] {
614 ctx.PropertyErrorf(
615 "depfile",
616 "Deprecated to ensure the module type is convertible to Bazel. "+
617 "Try specifying the dependencies explicitly so that there is no need to use depfile. "+
618 "If not possible, the escape hatch is to add the module to allowlists.go to bypass the error.")
619 }
Vinh Tran140d5882022-06-10 14:23:27 -0400620 }
621
Chris Parsonsf874e462022-05-10 13:50:12 -0400622 g.generateCommonBuildActions(ctx)
623
624 // For <= 6 outputs, just embed those directly in the users. Right now, that covers >90% of
625 // the genrules on AOSP. That will make things simpler to look at the graph in the common
626 // case. For larger sets of outputs, inject a phony target in between to limit ninja file
627 // growth.
628 if len(g.outputFiles) <= 6 {
629 g.outputDeps = g.outputFiles
630 } else {
631 phonyFile := android.PathForModuleGen(ctx, "genrule-phony")
632 ctx.Build(pctx, android.BuildParams{
633 Rule: blueprint.Phony,
634 Output: phonyFile,
635 Inputs: g.outputFiles,
636 })
637 g.outputDeps = android.Paths{phonyFile}
Jeff Gaston02a684b2017-10-27 14:59:27 -0700638 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400639}
640
641func (g *Module) QueueBazelCall(ctx android.BaseModuleContext) {
642 bazelCtx := ctx.Config().BazelContext
643 bazelCtx.QueueBazelRequest(g.GetBazelLabel(ctx, g), cquery.GetOutputFiles, android.GetConfigKey(ctx))
644}
645
646func (g *Module) IsMixedBuildSupported(ctx android.BaseModuleContext) bool {
647 return true
Colin Crossd350ecd2015-04-28 13:25:36 -0700648}
Colin Crossd350ecd2015-04-28 13:25:36 -0700649
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700650// Collect information for opening IDE project files in java/jdeps.go.
651func (g *Module) IDEInfo(dpInfo *android.IdeInfo) {
652 dpInfo.Srcs = append(dpInfo.Srcs, g.Srcs().Strings()...)
653 for _, src := range g.properties.Srcs {
654 if strings.HasPrefix(src, ":") {
655 src = strings.Trim(src, ":")
656 dpInfo.Deps = append(dpInfo.Deps, src)
657 }
658 }
bralee1fbf4402020-05-21 10:11:59 +0800659 dpInfo.Paths = append(dpInfo.Paths, g.modulePaths...)
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700660}
661
Colin Crossa4ad2b02019-03-18 22:15:32 -0700662func (g *Module) AndroidMk() android.AndroidMkData {
663 return android.AndroidMkData{
Anton Hansson72f18492020-10-30 16:34:45 +0000664 Class: "ETC",
Colin Crossa4ad2b02019-03-18 22:15:32 -0700665 OutputFile: android.OptionalPathForPath(g.outputFiles[0]),
666 SubName: g.subName,
667 Extra: []android.AndroidMkExtraFunc{
668 func(w io.Writer, outputFile android.Path) {
Anton Hansson72f18492020-10-30 16:34:45 +0000669 fmt.Fprintln(w, "LOCAL_UNINSTALLABLE_MODULE := true")
Colin Crossa4ad2b02019-03-18 22:15:32 -0700670 },
671 },
672 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
673 android.WriteAndroidMkData(w, data)
674 if data.SubName != "" {
675 fmt.Fprintln(w, ".PHONY:", name)
676 fmt.Fprintln(w, name, ":", name+g.subName)
677 }
678 },
679 }
680}
681
Jiyong Park45bf82e2020-12-15 22:29:02 +0900682var _ android.ApexModule = (*Module)(nil)
683
684// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -0700685func (g *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
686 sdkVersion android.ApiLevel) error {
Jooyung Han749dc692020-04-15 11:03:39 +0900687 // Because generated outputs are checked by client modules(e.g. cc_library, ...)
688 // we can safely ignore the check here.
689 return nil
690}
691
Jeff Gaston437d23c2017-11-08 12:38:00 -0800692func generatorFactory(taskGenerator taskFunc, props ...interface{}) *Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700693 module := &Module{
Jeff Gaston437d23c2017-11-08 12:38:00 -0800694 taskGenerator: taskGenerator,
Colin Crossd350ecd2015-04-28 13:25:36 -0700695 }
696
Colin Cross36242852017-06-23 15:06:31 -0700697 module.AddProperties(props...)
698 module.AddProperties(&module.properties)
Colin Crossd350ecd2015-04-28 13:25:36 -0700699
Colin Cross7228ecd2019-11-18 16:00:16 -0800700 module.ImageInterface = noopImageInterface{}
701
Colin Cross36242852017-06-23 15:06:31 -0700702 return module
Colin Crossd350ecd2015-04-28 13:25:36 -0700703}
704
Colin Cross7228ecd2019-11-18 16:00:16 -0800705type noopImageInterface struct{}
706
707func (x noopImageInterface) ImageMutatorBegin(android.BaseModuleContext) {}
708func (x noopImageInterface) CoreVariantNeeded(android.BaseModuleContext) bool { return false }
Yifan Hong1b3348d2020-01-21 15:53:22 -0800709func (x noopImageInterface) RamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700710func (x noopImageInterface) VendorRamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Inseob Kim08758f02021-04-08 21:13:22 +0900711func (x noopImageInterface) DebugRamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Colin Cross7228ecd2019-11-18 16:00:16 -0800712func (x noopImageInterface) RecoveryVariantNeeded(android.BaseModuleContext) bool { return false }
713func (x noopImageInterface) ExtraImageVariations(ctx android.BaseModuleContext) []string { return nil }
714func (x noopImageInterface) SetImageVariation(ctx android.BaseModuleContext, variation string, module android.Module) {
715}
716
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700717func NewGenSrcs() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700718 properties := &genSrcsProperties{}
719
Colin Crossf1885962020-11-20 15:28:30 -0800720 // finalSubDir is the name of the subdirectory that output files will be generated into.
721 // It is used so that per-shard directories can be placed alongside it an then finally
722 // merged into it.
723 const finalSubDir = "gensrcs"
724
Colin Cross1a527682019-09-23 15:55:30 -0700725 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Colin Cross1a527682019-09-23 15:55:30 -0700726 shardSize := defaultShardSize
727 if s := properties.Shard_size; s != nil {
728 shardSize = int(*s)
729 }
Jeff Gaston437d23c2017-11-08 12:38:00 -0800730
Colin Crossf1885962020-11-20 15:28:30 -0800731 // gensrcs rules can easily hit command line limits by repeating the command for
732 // every input file. Shard the input files into groups.
Colin Cross1a527682019-09-23 15:55:30 -0700733 shards := android.ShardPaths(srcFiles, shardSize)
734 var generateTasks []generateTask
Colin Crossbaccf5b2018-02-21 14:07:48 -0800735
Colin Cross1a527682019-09-23 15:55:30 -0700736 for i, shard := range shards {
737 var commands []string
738 var outFiles android.WritablePaths
Colin Cross3ea4eb82020-11-24 13:07:27 -0800739 var commandDepFiles []string
Colin Cross1a527682019-09-23 15:55:30 -0700740 var copyTo android.WritablePaths
Colin Cross1a527682019-09-23 15:55:30 -0700741
Colin Crossf1885962020-11-20 15:28:30 -0800742 // When sharding is enabled (i.e. len(shards) > 1), the sbox rules for each
743 // shard will be write to their own directories and then be merged together
744 // into finalSubDir. If sharding is not enabled (i.e. len(shards) == 1),
745 // the sbox rule will write directly to finalSubDir.
746 genSubDir := finalSubDir
Colin Cross1a527682019-09-23 15:55:30 -0700747 if len(shards) > 1 {
Colin Crossf1885962020-11-20 15:28:30 -0800748 genSubDir = strconv.Itoa(i)
Jeff Gaston437d23c2017-11-08 12:38:00 -0800749 }
750
Colin Crossf1885962020-11-20 15:28:30 -0800751 genDir := android.PathForModuleGen(ctx, genSubDir)
Colin Crossf1a035e2020-11-16 17:32:30 -0800752 // TODO(ccross): this RuleBuilder is a hack to be able to call
753 // rule.Command().PathForOutput. Replace this with passing the rule into the
754 // generator.
Yu Liu6a7940c2023-05-09 17:12:22 -0700755 rule := getSandboxedRuleBuilder(ctx, android.NewRuleBuilder(pctx, ctx).Sbox(genDir, nil))
Jeff Gaston437d23c2017-11-08 12:38:00 -0800756
Colin Cross3ea4eb82020-11-24 13:07:27 -0800757 for _, in := range shard {
Colin Crossf1885962020-11-20 15:28:30 -0800758 outFile := android.GenPathWithExt(ctx, finalSubDir, in, String(properties.Output_extension))
759
760 // If sharding is enabled, then outFile is the path to the output file in
761 // the shard directory, and copyTo is the path to the output file in the
762 // final directory.
Colin Cross1a527682019-09-23 15:55:30 -0700763 if len(shards) > 1 {
Colin Crossf1885962020-11-20 15:28:30 -0800764 shardFile := android.GenPathWithExt(ctx, genSubDir, in, String(properties.Output_extension))
Colin Cross1a527682019-09-23 15:55:30 -0700765 copyTo = append(copyTo, outFile)
766 outFile = shardFile
767 }
768
769 outFiles = append(outFiles, outFile)
Colin Cross1a527682019-09-23 15:55:30 -0700770
Colin Crossf1885962020-11-20 15:28:30 -0800771 // pre-expand the command line to replace $in and $out with references to
772 // a single input and output file.
Colin Cross1a527682019-09-23 15:55:30 -0700773 command, err := android.Expand(rawCommand, func(name string) (string, error) {
774 switch name {
775 case "in":
776 return in.String(), nil
777 case "out":
Colin Crossf1a035e2020-11-16 17:32:30 -0800778 return rule.Command().PathForOutput(outFile), nil
Colin Cross3ea4eb82020-11-24 13:07:27 -0800779 case "depfile":
780 // Generate a depfile for each output file. Store the list for
781 // later in order to combine them all into a single depfile.
Colin Crossf1a035e2020-11-16 17:32:30 -0800782 depFile := rule.Command().PathForOutput(outFile.ReplaceExtension(ctx, "d"))
Colin Cross3ea4eb82020-11-24 13:07:27 -0800783 commandDepFiles = append(commandDepFiles, depFile)
784 return depFile, nil
Colin Cross1a527682019-09-23 15:55:30 -0700785 default:
786 return "$(" + name + ")", nil
787 }
788 })
789 if err != nil {
790 ctx.PropertyErrorf("cmd", err.Error())
791 }
792
793 // escape the command in case for example it contains '#', an odd number of '"', etc
794 command = fmt.Sprintf("bash -c %v", proptools.ShellEscape(command))
795 commands = append(commands, command)
796 }
797 fullCommand := strings.Join(commands, " && ")
798
Colin Cross3ea4eb82020-11-24 13:07:27 -0800799 var outputDepfile android.WritablePath
800 var extraTools android.Paths
801 if len(commandDepFiles) > 0 {
802 // Each command wrote to a depfile, but ninja can only handle one
803 // depfile per rule. Use the dep_fixer tool at the end of the
804 // command to combine all the depfiles into a single output depfile.
805 outputDepfile = android.PathForModuleGen(ctx, genSubDir, "gensrcs.d")
806 depFixerTool := ctx.Config().HostToolPath(ctx, "dep_fixer")
807 fullCommand += fmt.Sprintf(" && %s -o $(depfile) %s",
Colin Crossd11cf622021-03-23 22:30:35 -0700808 rule.Command().PathForTool(depFixerTool),
Colin Crossba9e4032020-11-24 16:32:22 -0800809 strings.Join(commandDepFiles, " "))
Colin Cross3ea4eb82020-11-24 13:07:27 -0800810 extraTools = append(extraTools, depFixerTool)
811 }
812
Colin Cross1a527682019-09-23 15:55:30 -0700813 generateTasks = append(generateTasks, generateTask{
Colin Cross3ea4eb82020-11-24 13:07:27 -0800814 in: shard,
815 out: outFiles,
816 depFile: outputDepfile,
817 copyTo: copyTo,
818 genDir: genDir,
819 cmd: fullCommand,
820 shard: i,
821 shards: len(shards),
822 extraTools: extraTools,
Colin Cross1a527682019-09-23 15:55:30 -0700823 })
Jeff Gaston437d23c2017-11-08 12:38:00 -0800824 }
Colin Cross1a527682019-09-23 15:55:30 -0700825
826 return generateTasks
Colin Crossd350ecd2015-04-28 13:25:36 -0700827 }
828
Colin Cross1a527682019-09-23 15:55:30 -0700829 g := generatorFactory(taskGenerator, properties)
Colin Crossf1885962020-11-20 15:28:30 -0800830 g.subDir = finalSubDir
Colin Cross1a527682019-09-23 15:55:30 -0700831 return g
Colin Crossd350ecd2015-04-28 13:25:36 -0700832}
833
Colin Cross54190b32017-10-09 15:34:10 -0700834func GenSrcsFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700835 m := NewGenSrcs()
836 android.InitAndroidModule(m)
Vinh Tranb69e1ae2022-05-20 18:54:09 -0400837 android.InitBazelModule(m)
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700838 return m
839}
840
Colin Crossd350ecd2015-04-28 13:25:36 -0700841type genSrcsProperties struct {
Colin Cross7d5136f2015-05-11 13:39:40 -0700842 // extension that will be substituted for each output file
Nan Zhanga5e7cb42017-11-09 22:42:32 -0800843 Output_extension *string
Colin Cross1a527682019-09-23 15:55:30 -0700844
845 // maximum number of files that will be passed on a single command line.
846 Shard_size *int64
Colin Cross5049f022015-03-18 13:28:46 -0700847}
848
Vinh Tranb69e1ae2022-05-20 18:54:09 -0400849type bazelGensrcsAttributes struct {
850 Srcs bazel.LabelListAttribute
851 Output_extension *string
852 Tools bazel.LabelListAttribute
853 Cmd string
854}
855
Evgenii Stepanovf47c90d2020-12-02 18:55:09 -0800856const defaultShardSize = 50
Colin Cross1a527682019-09-23 15:55:30 -0700857
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700858func NewGenRule() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700859 properties := &genRuleProperties{}
Colin Cross5049f022015-03-18 13:28:46 -0700860
Colin Cross1a527682019-09-23 15:55:30 -0700861 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700862 outs := make(android.WritablePaths, len(properties.Out))
Colin Cross3d680512020-11-13 16:23:53 -0800863 var depFile android.WritablePath
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700864 for i, out := range properties.Out {
Colin Cross3d680512020-11-13 16:23:53 -0800865 outPath := android.PathForModuleGen(ctx, out)
866 if i == 0 {
867 depFile = outPath.ReplaceExtension(ctx, "d")
868 }
869 outs[i] = outPath
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700870 }
Colin Cross1a527682019-09-23 15:55:30 -0700871 return []generateTask{{
Colin Cross3d680512020-11-13 16:23:53 -0800872 in: srcFiles,
873 out: outs,
874 depFile: depFile,
875 genDir: android.PathForModuleGen(ctx),
876 cmd: rawCommand,
Colin Cross1a527682019-09-23 15:55:30 -0700877 }}
Colin Cross5049f022015-03-18 13:28:46 -0700878 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700879
Jeff Gaston437d23c2017-11-08 12:38:00 -0800880 return generatorFactory(taskGenerator, properties)
Colin Cross5049f022015-03-18 13:28:46 -0700881}
882
Colin Cross54190b32017-10-09 15:34:10 -0700883func GenRuleFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700884 m := NewGenRule()
885 android.InitAndroidModule(m)
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800886 android.InitDefaultableModule(m)
Liz Kammerea6666f2021-02-17 10:17:28 -0500887 android.InitBazelModule(m)
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700888 return m
889}
890
Colin Crossd350ecd2015-04-28 13:25:36 -0700891type genRuleProperties struct {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700892 // names of the output files that will be generated
Yu Liud6201012022-10-17 12:29:15 -0700893 Out []string
Colin Cross5049f022015-03-18 13:28:46 -0700894}
Nan Zhangea568a42017-11-08 21:20:04 -0800895
Jingwen Chen316e07c2020-12-14 09:09:52 -0500896type bazelGenruleAttributes struct {
Jingwen Chen07027912021-03-15 06:02:43 -0400897 Srcs bazel.LabelListAttribute
Jingwen Chen316e07c2020-12-14 09:09:52 -0500898 Outs []string
Jingwen Chen07027912021-03-15 06:02:43 -0400899 Tools bazel.LabelListAttribute
Jingwen Chen316e07c2020-12-14 09:09:52 -0500900 Cmd string
901}
902
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400903// ConvertWithBp2build converts a Soong module -> Bazel target.
904func (m *Module) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
Liz Kammer356f7d42021-01-26 09:18:53 -0500905 // Bazel only has the "tools" attribute.
Jingwen Chen07027912021-03-15 06:02:43 -0400906 tools_prop := android.BazelLabelForModuleDeps(ctx, m.properties.Tools)
907 tool_files_prop := android.BazelLabelForModuleSrc(ctx, m.properties.Tool_files)
908 tools_prop.Append(tool_files_prop)
Liz Kammer356f7d42021-01-26 09:18:53 -0500909
Jingwen Chen07027912021-03-15 06:02:43 -0400910 tools := bazel.MakeLabelListAttribute(tools_prop)
Yu Liud6201012022-10-17 12:29:15 -0700911 srcs := bazel.LabelListAttribute{}
912 srcs_labels := bazel.LabelList{}
913 // Only cc_genrule is arch specific
914 if ctx.ModuleType() == "cc_genrule" {
915 for axis, configToProps := range m.GetArchVariantProperties(ctx, &generatorProperties{}) {
916 for config, props := range configToProps {
917 if props, ok := props.(*generatorProperties); ok {
918 labels := android.BazelLabelForModuleSrcExcludes(ctx, props.Srcs, props.Exclude_srcs)
919 srcs_labels.Append(labels)
920 srcs.SetSelectValue(axis, config, labels)
921 }
922 }
923 }
924 } else {
925 srcs_labels = android.BazelLabelForModuleSrcExcludes(ctx, m.properties.Srcs, m.properties.Exclude_srcs)
926 srcs = bazel.MakeLabelListAttribute(srcs_labels)
927 }
Liz Kammer356f7d42021-01-26 09:18:53 -0500928
929 var allReplacements bazel.LabelList
Jingwen Chen07027912021-03-15 06:02:43 -0400930 allReplacements.Append(tools.Value)
Yu Liud6201012022-10-17 12:29:15 -0700931 allReplacements.Append(bazel.FirstUniqueBazelLabelList(srcs_labels))
Liz Kammer356f7d42021-01-26 09:18:53 -0500932
933 // Replace in and out variables with $< and $@
934 var cmd string
935 if m.properties.Cmd != nil {
Vinh Tranb69e1ae2022-05-20 18:54:09 -0400936 if ctx.ModuleType() == "gensrcs" {
937 cmd = strings.ReplaceAll(*m.properties.Cmd, "$(in)", "$(SRC)")
938 cmd = strings.ReplaceAll(cmd, "$(out)", "$(OUT)")
939 } else {
940 cmd = strings.Replace(*m.properties.Cmd, "$(in)", "$(SRCS)", -1)
941 cmd = strings.Replace(cmd, "$(out)", "$(OUTS)", -1)
942 }
Vinh Tran32a98a52022-09-23 13:08:34 -0400943 cmd = strings.Replace(cmd, "$(genDir)", "$(RULEDIR)", -1)
Jingwen Chen07027912021-03-15 06:02:43 -0400944 if len(tools.Value.Includes) > 0 {
945 cmd = strings.Replace(cmd, "$(location)", fmt.Sprintf("$(location %s)", tools.Value.Includes[0].Label), -1)
946 cmd = strings.Replace(cmd, "$(locations)", fmt.Sprintf("$(locations %s)", tools.Value.Includes[0].Label), -1)
Liz Kammer356f7d42021-01-26 09:18:53 -0500947 }
948 for _, l := range allReplacements.Includes {
Jingwen Chen38e62642021-04-19 05:00:15 +0000949 bpLoc := fmt.Sprintf("$(location %s)", l.OriginalModuleName)
950 bpLocs := fmt.Sprintf("$(locations %s)", l.OriginalModuleName)
Liz Kammer356f7d42021-01-26 09:18:53 -0500951 bazelLoc := fmt.Sprintf("$(location %s)", l.Label)
952 bazelLocs := fmt.Sprintf("$(locations %s)", l.Label)
953 cmd = strings.Replace(cmd, bpLoc, bazelLoc, -1)
954 cmd = strings.Replace(cmd, bpLocs, bazelLocs, -1)
955 }
956 }
957
Spandan Das39b6cc52023-04-12 19:05:49 +0000958 tags := android.ApexAvailableTagsWithoutTestApexes(ctx, m)
Sam Delmericoeddd3c02022-12-02 17:31:58 -0500959
Vinh Tranb69e1ae2022-05-20 18:54:09 -0400960 if ctx.ModuleType() == "gensrcs" {
961 // The Output_extension prop is not in an immediately accessible field
962 // in the Module struct, so use GetProperties and cast it
963 // to the known struct prop.
964 var outputExtension *string
965 for _, propIntf := range m.GetProperties() {
966 if props, ok := propIntf.(*genSrcsProperties); ok {
967 outputExtension = props.Output_extension
968 break
969 }
Liz Kammer356f7d42021-01-26 09:18:53 -0500970 }
Vinh Tranb69e1ae2022-05-20 18:54:09 -0400971 props := bazel.BazelTargetModuleProperties{
972 Rule_class: "gensrcs",
973 Bzl_load_location: "//build/bazel/rules:gensrcs.bzl",
974 }
975 attrs := &bazelGensrcsAttributes{
976 Srcs: srcs,
977 Output_extension: outputExtension,
978 Cmd: cmd,
979 Tools: tools,
980 }
Sam Delmericoeddd3c02022-12-02 17:31:58 -0500981 ctx.CreateBazelTargetModule(props, android.CommonAttributes{
982 Name: m.Name(),
983 Tags: tags,
984 }, attrs)
Vinh Tranb69e1ae2022-05-20 18:54:09 -0400985 } else {
986 // The Out prop is not in an immediately accessible field
987 // in the Module struct, so use GetProperties and cast it
988 // to the known struct prop.
989 var outs []string
990 for _, propIntf := range m.GetProperties() {
991 if props, ok := propIntf.(*genRuleProperties); ok {
992 outs = props.Out
993 break
994 }
995 }
996 attrs := &bazelGenruleAttributes{
997 Srcs: srcs,
998 Outs: outs,
999 Cmd: cmd,
1000 Tools: tools,
1001 }
1002 props := bazel.BazelTargetModuleProperties{
1003 Rule_class: "genrule",
1004 }
Sam Delmericoeddd3c02022-12-02 17:31:58 -05001005 ctx.CreateBazelTargetModule(props, android.CommonAttributes{
1006 Name: m.Name(),
1007 Tags: tags,
1008 }, attrs)
Liz Kammer356f7d42021-01-26 09:18:53 -05001009 }
Jingwen Chen316e07c2020-12-14 09:09:52 -05001010}
1011
Nan Zhangea568a42017-11-08 21:20:04 -08001012var Bool = proptools.Bool
1013var String = proptools.String
Jaewoong Jung98716bd2018-12-10 08:13:18 -08001014
Jaewoong Jung98716bd2018-12-10 08:13:18 -08001015// Defaults
Jaewoong Jung98716bd2018-12-10 08:13:18 -08001016type Defaults struct {
1017 android.ModuleBase
1018 android.DefaultsModuleBase
1019}
1020
Jaewoong Jung98716bd2018-12-10 08:13:18 -08001021func defaultsFactory() android.Module {
1022 return DefaultsFactory()
1023}
1024
1025func DefaultsFactory(props ...interface{}) android.Module {
1026 module := &Defaults{}
1027
1028 module.AddProperties(props...)
1029 module.AddProperties(
1030 &generatorProperties{},
1031 &genRuleProperties{},
1032 )
1033
1034 android.InitDefaultsModule(module)
1035
1036 return module
1037}
Yu Liu6a7940c2023-05-09 17:12:22 -07001038
1039func getSandboxedRuleBuilder(ctx android.ModuleContext, r *android.RuleBuilder) *android.RuleBuilder {
Yu Liu45d6af52023-05-24 23:10:18 +00001040 if !ctx.DeviceConfig().GenruleSandboxing() {
1041 return r.SandboxTools()
1042 }
1043 if SandboxingDenyModuleSet == nil {
1044 SandboxingDenyModuleSetLock.Lock()
1045 defer SandboxingDenyModuleSetLock.Unlock()
1046 SandboxingDenyModuleSet = map[string]bool{}
1047 SandboxingDenyPathSet = map[string]bool{}
1048 android.AddToStringSet(SandboxingDenyModuleSet, append(DepfileAllowList, SandboxingDenyModuleList...))
1049 android.AddToStringSet(SandboxingDenyPathSet, SandboxingDenyPathList)
1050 }
1051
1052 if SandboxingDenyPathSet[ctx.ModuleDir()] || SandboxingDenyModuleSet[ctx.ModuleName()] {
Yu Liu6a7940c2023-05-09 17:12:22 -07001053 return r.SandboxTools()
1054 }
1055 return r.SandboxInputs()
1056}