blob: 6306c2750116e3e60dcdd37ed4fdfe47d6c4b2c4 [file] [log] [blame]
Colin Cross5049f022015-03-18 13:28:46 -07001// Copyright 2015 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Alex Humesky29e3bbe2020-11-20 21:30:13 -050015// A genrule module takes a list of source files ("srcs" property), an optional
16// list of tools ("tools" property), and a command line ("cmd" property), to
17// generate output files ("out" property).
18
Colin Cross5049f022015-03-18 13:28:46 -070019package genrule
20
21import (
Colin Cross6f080df2016-11-04 15:32:58 -070022 "fmt"
Colin Crossa4ad2b02019-03-18 22:15:32 -070023 "io"
Colin Cross3d680512020-11-13 16:23:53 -080024 "path/filepath"
Colin Cross1a527682019-09-23 15:55:30 -070025 "strconv"
Colin Cross6f080df2016-11-04 15:32:58 -070026 "strings"
Dan Willemsen3f4539b2016-09-28 16:19:10 -070027
Chris Parsonsf874e462022-05-10 13:50:12 -040028 "android/soong/bazel/cquery"
Jihoon Kangc170af42022-08-20 05:26:38 +000029
Colin Cross70b40592015-03-23 12:57:34 -070030 "github.com/google/blueprint"
Dan Willemsen8eded0a2017-09-13 16:07:44 -070031 "github.com/google/blueprint/bootstrap"
Nan Zhangea568a42017-11-08 21:20:04 -080032 "github.com/google/blueprint/proptools"
Colin Cross5049f022015-03-18 13:28:46 -070033
Colin Cross635c3b02016-05-18 15:37:25 -070034 "android/soong/android"
Jingwen Chen30f5aaa2020-11-19 05:38:02 -050035 "android/soong/bazel"
Colin Cross5049f022015-03-18 13:28:46 -070036)
37
Colin Cross463a90e2015-06-17 14:20:06 -070038func init() {
Colin Crosse9fe2942020-11-10 18:12:15 -080039 RegisterGenruleBuildComponents(android.InitRegistrationContext)
Martin Stjernholm710ec3a2020-01-16 15:12:04 +000040}
Jaewoong Jung98716bd2018-12-10 08:13:18 -080041
Paul Duffin672cb9f2021-03-03 02:30:37 +000042// Test fixture preparer that will register most genrule build components.
43//
44// Singletons and mutators should only be added here if they are needed for a majority of genrule
45// module types, otherwise they should be added under a separate preparer to allow them to be
46// selected only when needed to reduce test execution time.
47//
48// Module types do not have much of an overhead unless they are used so this should include as many
49// module types as possible. The exceptions are those module types that require mutators and/or
50// singletons in order to function in which case they should be kept together in a separate
51// preparer.
52var PrepareForTestWithGenRuleBuildComponents = android.GroupFixturePreparers(
53 android.FixtureRegisterWithContext(RegisterGenruleBuildComponents),
54)
55
56// Prepare a fixture to use all genrule module types, mutators and singletons fully.
57//
58// This should only be used by tests that want to run with as much of the build enabled as possible.
59var PrepareForIntegrationTestWithGenrule = android.GroupFixturePreparers(
60 PrepareForTestWithGenRuleBuildComponents,
61)
62
Colin Crosse9fe2942020-11-10 18:12:15 -080063func RegisterGenruleBuildComponents(ctx android.RegistrationContext) {
Martin Stjernholm710ec3a2020-01-16 15:12:04 +000064 ctx.RegisterModuleType("genrule_defaults", defaultsFactory)
65
66 ctx.RegisterModuleType("gensrcs", GenSrcsFactory)
67 ctx.RegisterModuleType("genrule", GenRuleFactory)
68
69 ctx.FinalDepsMutators(func(ctx android.RegisterMutatorsContext) {
70 ctx.BottomUp("genrule_tool_deps", toolDepsMutator).Parallel()
71 })
Liz Kammer356f7d42021-01-26 09:18:53 -050072}
73
Colin Cross5049f022015-03-18 13:28:46 -070074var (
Colin Cross635c3b02016-05-18 15:37:25 -070075 pctx = android.NewPackageContext("android/soong/genrule")
Colin Cross1a527682019-09-23 15:55:30 -070076
Alex Humesky29e3bbe2020-11-20 21:30:13 -050077 // Used by gensrcs when there is more than 1 shard to merge the outputs
78 // of each shard into a zip file.
Colin Cross1a527682019-09-23 15:55:30 -070079 gensrcsMerge = pctx.AndroidStaticRule("gensrcsMerge", blueprint.RuleParams{
80 Command: "${soongZip} -o ${tmpZip} @${tmpZip}.rsp && ${zipSync} -d ${genDir} ${tmpZip}",
81 CommandDeps: []string{"${soongZip}", "${zipSync}"},
82 Rspfile: "${tmpZip}.rsp",
83 RspfileContent: "${zipArgs}",
84 }, "tmpZip", "genDir", "zipArgs")
Colin Cross5049f022015-03-18 13:28:46 -070085)
86
Jeff Gastonefc1b412017-03-29 17:29:06 -070087func init() {
Dan Willemsenddf504c2019-08-09 16:21:29 -070088 pctx.Import("android/soong/android")
Colin Cross1a527682019-09-23 15:55:30 -070089
90 pctx.HostBinToolVariable("soongZip", "soong_zip")
91 pctx.HostBinToolVariable("zipSync", "zipsync")
Jeff Gastonefc1b412017-03-29 17:29:06 -070092}
93
Colin Cross5049f022015-03-18 13:28:46 -070094type SourceFileGenerator interface {
Colin Cross635c3b02016-05-18 15:37:25 -070095 GeneratedSourceFiles() android.Paths
Colin Cross5ed99c62016-11-22 12:55:55 -080096 GeneratedHeaderDirs() android.Paths
Dan Willemsen9da9d492018-02-21 18:28:18 -080097 GeneratedDeps() android.Paths
Colin Cross5049f022015-03-18 13:28:46 -070098}
99
Colin Crossfe17f6f2019-03-28 19:30:56 -0700100// Alias for android.HostToolProvider
101// Deprecated: use android.HostToolProvider instead.
Colin Crossd350ecd2015-04-28 13:25:36 -0700102type HostToolProvider interface {
Colin Crossfe17f6f2019-03-28 19:30:56 -0700103 android.HostToolProvider
Colin Crossd350ecd2015-04-28 13:25:36 -0700104}
Colin Cross5049f022015-03-18 13:28:46 -0700105
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700106type hostToolDependencyTag struct {
107 blueprint.BaseDependencyTag
Colin Cross65cb3142021-12-10 23:05:02 +0000108 android.LicenseAnnotationToolchainDependencyTag
Colin Cross08f15ab2018-10-04 23:29:14 -0700109 label string
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700110}
Martin Stjernholmdbd814d2022-01-12 23:18:30 +0000111
112func (t hostToolDependencyTag) AllowDisabledModuleDependency(target android.Module) bool {
113 // Allow depending on a disabled module if it's replaced by a prebuilt
114 // counterpart. We get the prebuilt through android.PrebuiltGetPreferred in
115 // GenerateAndroidBuildActions.
116 return target.IsReplacedByPrebuilt()
117}
118
119var _ android.AllowDisabledModuleDependency = (*hostToolDependencyTag)(nil)
120
Colin Cross7d5136f2015-05-11 13:39:40 -0700121type generatorProperties struct {
Spandan Das93e95992021-07-29 18:26:39 +0000122 // The command to run on one or more input files. Cmd supports substitution of a few variables.
Jeff Gastonefc1b412017-03-29 17:29:06 -0700123 //
124 // Available variables for substitution:
125 //
Spandan Das93e95992021-07-29 18:26:39 +0000126 // $(location): the path to the first entry in tools or tool_files.
127 // $(location <label>): the path to the tool, tool_file, input or output with name <label>. Use $(location) if <label> refers to a rule that outputs exactly one file.
128 // $(locations <label>): the paths to the tools, tool_files, inputs or outputs with name <label>. Use $(locations) if <label> refers to a rule that outputs two or more files.
129 // $(in): one or more input files.
130 // $(out): a single output file.
131 // $(depfile): a file to which dependencies will be written, if the depfile property is set to true.
132 // $(genDir): the sandbox directory for this tool; contains $(out).
Colin Cross2296f5b2017-10-17 21:38:14 -0700133 // $$: a literal $
Nan Zhangea568a42017-11-08 21:20:04 -0800134 Cmd *string
Colin Cross7d5136f2015-05-11 13:39:40 -0700135
Colin Cross33bfb0a2016-11-21 17:23:08 -0800136 // Enable reading a file containing dependencies in gcc format after the command completes
Nan Zhangea568a42017-11-08 21:20:04 -0800137 Depfile *bool
Colin Cross33bfb0a2016-11-21 17:23:08 -0800138
Colin Cross6f080df2016-11-04 15:32:58 -0700139 // name of the modules (if any) that produces the host executable. Leave empty for
Colin Cross7d5136f2015-05-11 13:39:40 -0700140 // prebuilts or scripts that do not need a module to build them.
Colin Cross6f080df2016-11-04 15:32:58 -0700141 Tools []string
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700142
143 // Local file that is used as the tool
Colin Cross27b922f2019-03-04 22:35:41 -0800144 Tool_files []string `android:"path"`
Colin Cross5ed99c62016-11-22 12:55:55 -0800145
146 // List of directories to export generated headers from
147 Export_include_dirs []string
Colin Cross708c4242017-01-13 18:05:49 -0800148
149 // list of input files
Colin Cross27b922f2019-03-04 22:35:41 -0800150 Srcs []string `android:"path,arch_variant"`
Dan Willemseneefa0262018-11-17 14:01:18 -0800151
152 // input files to exclude
Colin Cross27b922f2019-03-04 22:35:41 -0800153 Exclude_srcs []string `android:"path,arch_variant"`
Justin Yun4da4ccc2023-07-06 10:56:29 +0900154
155 // Enable restat to update the output only if the output is changed
156 Write_if_changed *bool
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400157}
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500158
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700159type Module struct {
Colin Cross635c3b02016-05-18 15:37:25 -0700160 android.ModuleBase
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800161 android.DefaultableModuleBase
Liz Kammerea6666f2021-02-17 10:17:28 -0500162 android.BazelModuleBase
Jiyong Parkfc752ca2019-06-12 13:27:29 +0900163 android.ApexModuleBase
Colin Crossd350ecd2015-04-28 13:25:36 -0700164
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700165 // For other packages to make their own genrules with extra
166 // properties
167 Extra interface{}
Colin Crossf3bfd022021-09-27 15:15:06 -0700168
169 // CmdModifier can be set by wrappers around genrule to modify the command, for example to
170 // prefix environment variables to it.
171 CmdModifier func(ctx android.ModuleContext, cmd string) string
172
Colin Cross7228ecd2019-11-18 16:00:16 -0800173 android.ImageInterface
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700174
Colin Cross7d5136f2015-05-11 13:39:40 -0700175 properties generatorProperties
Colin Crossd350ecd2015-04-28 13:25:36 -0700176
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500177 // For the different tasks that genrule and gensrc generate. genrule will
178 // generate 1 task, and gensrc will generate 1 or more tasks based on the
179 // number of shards the input files are sharded into.
Jeff Gaston437d23c2017-11-08 12:38:00 -0800180 taskGenerator taskFunc
Colin Crossd350ecd2015-04-28 13:25:36 -0700181
Colin Cross1a527682019-09-23 15:55:30 -0700182 rule blueprint.Rule
183 rawCommands []string
Colin Crossd350ecd2015-04-28 13:25:36 -0700184
Colin Cross5ed99c62016-11-22 12:55:55 -0800185 exportedIncludeDirs android.Paths
Dan Willemsenb40aab62016-04-20 14:21:14 -0700186
Colin Cross635c3b02016-05-18 15:37:25 -0700187 outputFiles android.Paths
Dan Willemsen9da9d492018-02-21 18:28:18 -0800188 outputDeps android.Paths
Colin Crossa4ad2b02019-03-18 22:15:32 -0700189
190 subName string
Colin Cross1a527682019-09-23 15:55:30 -0700191 subDir string
bralee1fbf4402020-05-21 10:11:59 +0800192
193 // Collect the module directory for IDE info in java/jdeps.go.
194 modulePaths []string
Colin Crossd350ecd2015-04-28 13:25:36 -0700195}
196
Chris Parsonsf874e462022-05-10 13:50:12 -0400197var _ android.MixedBuildBuildable = (*Module)(nil)
198
Colin Cross1a527682019-09-23 15:55:30 -0700199type taskFunc func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask
Colin Crossd350ecd2015-04-28 13:25:36 -0700200
201type generateTask struct {
Liz Kammer81fec182023-06-09 13:33:45 -0400202 in android.Paths
203 out android.WritablePaths
204 depFile android.WritablePath
205 copyTo android.WritablePaths // For gensrcs to set on gensrcsMerge rule.
206 genDir android.WritablePath
207 extraTools android.Paths // dependencies on tools used by the generator
208 extraInputs map[string][]string
Colin Cross3ea4eb82020-11-24 13:07:27 -0800209
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500210 cmd string
211 // For gensrsc sharding.
Colin Cross3ea4eb82020-11-24 13:07:27 -0800212 shard int
213 shards int
Colin Crossd350ecd2015-04-28 13:25:36 -0700214}
215
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700216func (g *Module) GeneratedSourceFiles() android.Paths {
Colin Crossd350ecd2015-04-28 13:25:36 -0700217 return g.outputFiles
218}
219
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700220func (g *Module) Srcs() android.Paths {
Nan Zhange42777a2018-03-27 16:19:42 -0700221 return append(android.Paths{}, g.outputFiles...)
Colin Cross068e0fe2016-12-13 15:23:47 -0800222}
223
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700224func (g *Module) GeneratedHeaderDirs() android.Paths {
Colin Cross5ed99c62016-11-22 12:55:55 -0800225 return g.exportedIncludeDirs
Dan Willemsenb40aab62016-04-20 14:21:14 -0700226}
227
Dan Willemsen9da9d492018-02-21 18:28:18 -0800228func (g *Module) GeneratedDeps() android.Paths {
229 return g.outputDeps
230}
231
Jooyung Han8c7e3ed2021-06-28 17:35:58 +0900232func (g *Module) OutputFiles(tag string) (android.Paths, error) {
233 if tag == "" {
234 return append(android.Paths{}, g.outputFiles...), nil
235 }
236 // otherwise, tag should match one of outputs
237 for _, outputFile := range g.outputFiles {
238 if outputFile.Rel() == tag {
239 return android.Paths{outputFile}, nil
240 }
241 }
242 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
243}
244
245var _ android.SourceFileProducer = (*Module)(nil)
246var _ android.OutputFileProducer = (*Module)(nil)
247
Martin Stjernholm710ec3a2020-01-16 15:12:04 +0000248func toolDepsMutator(ctx android.BottomUpMutatorContext) {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700249 if g, ok := ctx.Module().(*Module); ok {
Colin Cross08f15ab2018-10-04 23:29:14 -0700250 for _, tool := range g.properties.Tools {
251 tag := hostToolDependencyTag{label: tool}
252 if m := android.SrcIsModule(tool); m != "" {
253 tool = m
254 }
Colin Cross0f7d2ef2019-10-16 11:03:10 -0700255 ctx.AddFarVariationDependencies(ctx.Config().BuildOSTarget.Variations(), tag, tool)
Colin Cross6362e272015-10-29 15:25:03 -0700256 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700257 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700258}
259
Chris Parsonsf874e462022-05-10 13:50:12 -0400260func (g *Module) ProcessBazelQueryResponse(ctx android.ModuleContext) {
261 g.generateCommonBuildActions(ctx)
262
263 label := g.GetBazelLabel(ctx, g)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400264 bazelCtx := ctx.Config().BazelContext
Chris Parsonsf874e462022-05-10 13:50:12 -0400265 filePaths, err := bazelCtx.GetOutputFiles(label, android.GetConfigKey(ctx))
266 if err != nil {
267 ctx.ModuleErrorf(err.Error())
268 return
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400269 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400270
271 var bazelOutputFiles android.Paths
272 exportIncludeDirs := map[string]bool{}
273 for _, bazelOutputFile := range filePaths {
Cole Faust01243362022-06-02 12:11:12 -0700274 bazelOutputFiles = append(bazelOutputFiles, android.PathForBazelOutRelative(ctx, ctx.ModuleDir(), bazelOutputFile))
Chris Parsonsf874e462022-05-10 13:50:12 -0400275 exportIncludeDirs[filepath.Dir(bazelOutputFile)] = true
276 }
277 g.outputFiles = bazelOutputFiles
278 g.outputDeps = bazelOutputFiles
279 for includePath, _ := range exportIncludeDirs {
280 g.exportedIncludeDirs = append(g.exportedIncludeDirs, android.PathForBazelOut(ctx, includePath))
281 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400282}
Colin Crossf1885962020-11-20 15:28:30 -0800283
Chris Parsonsf874e462022-05-10 13:50:12 -0400284// generateCommonBuildActions contains build action generation logic
285// common to both the mixed build case and the legacy case of genrule processing.
286// To fully support genrule in mixed builds, the contents of this function should
287// approach zero; there should be no genrule action registration done directly
288// by Soong logic in the mixed-build case.
289func (g *Module) generateCommonBuildActions(ctx android.ModuleContext) {
Colin Crossa4ad2b02019-03-18 22:15:32 -0700290 g.subName = ctx.ModuleSubDir()
291
bralee1fbf4402020-05-21 10:11:59 +0800292 // Collect the module directory for IDE info in java/jdeps.go.
293 g.modulePaths = append(g.modulePaths, ctx.ModuleDir())
294
Colin Cross5ed99c62016-11-22 12:55:55 -0800295 if len(g.properties.Export_include_dirs) > 0 {
296 for _, dir := range g.properties.Export_include_dirs {
297 g.exportedIncludeDirs = append(g.exportedIncludeDirs,
Colin Cross1a527682019-09-23 15:55:30 -0700298 android.PathForModuleGen(ctx, g.subDir, ctx.ModuleDir(), dir))
Liz Kammerd38c87c2023-07-17 09:58:50 -0400299 // Also export without ModuleDir for consistency with Export_include_dirs not being set
300 g.exportedIncludeDirs = append(g.exportedIncludeDirs,
301 android.PathForModuleGen(ctx, g.subDir, 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 Kammer81fec182023-06-09 13:33:45 -0400405 addLabelsForInputs := func(propName string, include, exclude []string) android.Paths {
Colin Crossba71a3f2019-03-18 12:12:48 -0700406
Liz Kammer81fec182023-06-09 13:33:45 -0400407 includeDirInPaths := ctx.DeviceConfig().BuildBrokenInputDir(g.Name())
408 var srcFiles android.Paths
409 for _, in := range include {
410 paths, missingDeps := android.PathsAndMissingDepsRelativeToModuleSourceDir(android.SourceInput{
411 Context: ctx, Paths: []string{in}, ExcludePaths: exclude, IncludeDirs: includeDirInPaths,
412 })
413 if len(missingDeps) > 0 {
414 if !ctx.Config().AllowMissingDependencies() {
415 panic(fmt.Errorf("should never get here, the missing dependencies %q should have been reported in DepsMutator",
416 missingDeps))
417 }
418
419 // If AllowMissingDependencies is enabled, the build will not have stopped when
420 // the dependency was added on a missing SourceFileProducer module, which will result in nonsensical
421 // "cmd: label ":..." has no files" errors later. Add a placeholder file to the local label.
422 // The command that uses this placeholder file will never be executed because the rule will be
423 // replaced with an android.Error rule reporting the missing dependencies.
424 ctx.AddMissingDependencies(missingDeps)
425 addLocationLabel(in, errorLocation{"***missing " + propName + " " + in + "***"})
426 } else {
427 srcFiles = append(srcFiles, paths...)
428 addLocationLabel(in, inputLocation{paths})
429 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700430 }
Liz Kammer81fec182023-06-09 13:33:45 -0400431 return srcFiles
Colin Cross08f15ab2018-10-04 23:29:14 -0700432 }
Liz Kammer81fec182023-06-09 13:33:45 -0400433 srcFiles := addLabelsForInputs("srcs", g.properties.Srcs, g.properties.Exclude_srcs)
Colin Cross08f15ab2018-10-04 23:29:14 -0700434
Colin Cross1a527682019-09-23 15:55:30 -0700435 var copyFrom android.Paths
436 var outputFiles android.WritablePaths
437 var zipArgs strings.Builder
Colin Cross08f15ab2018-10-04 23:29:14 -0700438
Colin Crossf3bfd022021-09-27 15:15:06 -0700439 cmd := String(g.properties.Cmd)
440 if g.CmdModifier != nil {
441 cmd = g.CmdModifier(ctx, cmd)
442 }
443
Liz Kammer796921d2023-07-11 08:21:41 -0400444 var extraInputs android.Paths
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 // Only handle extra inputs once as these currently are the same across all tasks
453 if i == 0 {
454 for name, values := range task.extraInputs {
455 extraInputs = append(extraInputs, addLabelsForInputs(name, values, []string{})...)
456 }
457 }
458
Colin Crossf1a035e2020-11-16 17:32:30 -0800459 // Pick a unique path outside the task.genDir for the sbox manifest textproto,
460 // a unique rule name, and the user-visible description.
461 manifestName := "genrule.sbox.textproto"
462 desc := "generate"
463 name := "generator"
464 if task.shards > 0 {
465 manifestName = "genrule_" + strconv.Itoa(task.shard) + ".sbox.textproto"
466 desc += " " + strconv.Itoa(task.shard)
467 name += strconv.Itoa(task.shard)
468 } else if len(task.out) == 1 {
469 desc += " " + task.out[0].Base()
470 }
471
472 manifestPath := android.PathForModuleOut(ctx, manifestName)
473
474 // Use a RuleBuilder to create a rule that runs the command inside an sbox sandbox.
Yu Liu6a7940c2023-05-09 17:12:22 -0700475 rule := getSandboxedRuleBuilder(ctx, android.NewRuleBuilder(pctx, ctx).Sbox(task.genDir, manifestPath))
Justin Yun4da4ccc2023-07-06 10:56:29 +0900476 if Bool(g.properties.Write_if_changed) {
477 rule.Restat()
478 }
Colin Crossf1a035e2020-11-16 17:32:30 -0800479 cmd := rule.Command()
480
Colin Cross3d680512020-11-13 16:23:53 -0800481 for _, out := range task.out {
Colin Crossd11cf622021-03-23 22:30:35 -0700482 addLocationLabel(out.Rel(), outputLocation{out})
Colin Cross3d680512020-11-13 16:23:53 -0800483 }
484
Colin Cross1a527682019-09-23 15:55:30 -0700485 referencedDepfile := false
486
Colin Cross3d680512020-11-13 16:23:53 -0800487 rawCommand, err := android.Expand(task.cmd, func(name string) (string, error) {
Colin Cross1a527682019-09-23 15:55:30 -0700488 // report the error directly without returning an error to android.Expand to catch multiple errors in a
489 // single run
Colin Cross3d680512020-11-13 16:23:53 -0800490 reportError := func(fmt string, args ...interface{}) (string, error) {
Colin Cross1a527682019-09-23 15:55:30 -0700491 ctx.PropertyErrorf("cmd", fmt, args...)
Colin Cross3d680512020-11-13 16:23:53 -0800492 return "SOONG_ERROR", nil
Colin Cross6f080df2016-11-04 15:32:58 -0700493 }
Colin Cross1a527682019-09-23 15:55:30 -0700494
Jihoon Kangc170af42022-08-20 05:26:38 +0000495 // Apply shell escape to each cases to prevent source file paths containing $ from being evaluated in shell
Colin Cross1a527682019-09-23 15:55:30 -0700496 switch name {
497 case "location":
498 if len(g.properties.Tools) == 0 && len(g.properties.Tool_files) == 0 {
499 return reportError("at least one `tools` or `tool_files` is required if $(location) is used")
Colin Cross6f080df2016-11-04 15:32:58 -0700500 }
Colin Crossd11cf622021-03-23 22:30:35 -0700501 loc := locationLabels[firstLabel]
502 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700503 if len(paths) == 0 {
504 return reportError("default label %q has no files", firstLabel)
505 } else if len(paths) > 1 {
506 return reportError("default label %q has multiple files, use $(locations %s) to reference it",
507 firstLabel, firstLabel)
Colin Cross08f15ab2018-10-04 23:29:14 -0700508 }
Jihoon Kangc170af42022-08-20 05:26:38 +0000509 return proptools.ShellEscape(paths[0]), nil
Colin Cross1a527682019-09-23 15:55:30 -0700510 case "in":
Jihoon Kangc170af42022-08-20 05:26:38 +0000511 return strings.Join(proptools.ShellEscapeList(cmd.PathsForInputs(srcFiles)), " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700512 case "out":
Colin Cross3d680512020-11-13 16:23:53 -0800513 var sandboxOuts []string
514 for _, out := range task.out {
Colin Crossf1a035e2020-11-16 17:32:30 -0800515 sandboxOuts = append(sandboxOuts, cmd.PathForOutput(out))
Colin Cross3d680512020-11-13 16:23:53 -0800516 }
Jihoon Kangc170af42022-08-20 05:26:38 +0000517 return strings.Join(proptools.ShellEscapeList(sandboxOuts), " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700518 case "depfile":
519 referencedDepfile = true
520 if !Bool(g.properties.Depfile) {
521 return reportError("$(depfile) used without depfile property")
522 }
Colin Cross3d680512020-11-13 16:23:53 -0800523 return "__SBOX_DEPFILE__", nil
Colin Cross1a527682019-09-23 15:55:30 -0700524 case "genDir":
Jihoon Kangc170af42022-08-20 05:26:38 +0000525 return proptools.ShellEscape(cmd.PathForOutput(task.genDir)), nil
Colin Cross1a527682019-09-23 15:55:30 -0700526 default:
527 if strings.HasPrefix(name, "location ") {
528 label := strings.TrimSpace(strings.TrimPrefix(name, "location "))
Colin Crossd11cf622021-03-23 22:30:35 -0700529 if loc, ok := locationLabels[label]; ok {
530 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700531 if len(paths) == 0 {
532 return reportError("label %q has no files", label)
533 } else if len(paths) > 1 {
534 return reportError("label %q has multiple files, use $(locations %s) to reference it",
535 label, label)
536 }
Jihoon Kangc170af42022-08-20 05:26:38 +0000537 return proptools.ShellEscape(paths[0]), nil
Colin Cross1a527682019-09-23 15:55:30 -0700538 } else {
Anton Hanssonbebf5262022-02-23 11:42:38 +0000539 return reportError("unknown location label %q is not in srcs, out, tools or tool_files.", label)
Colin Cross1a527682019-09-23 15:55:30 -0700540 }
541 } else if strings.HasPrefix(name, "locations ") {
542 label := strings.TrimSpace(strings.TrimPrefix(name, "locations "))
Colin Crossd11cf622021-03-23 22:30:35 -0700543 if loc, ok := locationLabels[label]; ok {
544 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700545 if len(paths) == 0 {
546 return reportError("label %q has no files", label)
547 }
Jihoon Kangc170af42022-08-20 05:26:38 +0000548 return proptools.ShellEscape(strings.Join(paths, " ")), nil
Colin Cross1a527682019-09-23 15:55:30 -0700549 } else {
Anton Hanssonbebf5262022-02-23 11:42:38 +0000550 return reportError("unknown locations label %q is not in srcs, out, tools or tool_files.", label)
Colin Cross1a527682019-09-23 15:55:30 -0700551 }
552 } else {
553 return reportError("unknown variable '$(%s)'", name)
554 }
Colin Cross6f080df2016-11-04 15:32:58 -0700555 }
Colin Cross1a527682019-09-23 15:55:30 -0700556 })
557
558 if err != nil {
559 ctx.PropertyErrorf("cmd", "%s", err.Error())
560 return
Colin Cross6f080df2016-11-04 15:32:58 -0700561 }
Colin Cross6f080df2016-11-04 15:32:58 -0700562
Colin Cross1a527682019-09-23 15:55:30 -0700563 if Bool(g.properties.Depfile) && !referencedDepfile {
564 ctx.PropertyErrorf("cmd", "specified depfile=true but did not include a reference to '${depfile}' in cmd")
565 return
566 }
Colin Cross1a527682019-09-23 15:55:30 -0700567 g.rawCommands = append(g.rawCommands, rawCommand)
Bill Peckhamc087be12020-02-13 15:55:10 -0800568
Colin Cross3d680512020-11-13 16:23:53 -0800569 cmd.Text(rawCommand)
Liz Kammer81fec182023-06-09 13:33:45 -0400570 cmd.Implicits(srcFiles) // need to be able to reference other srcs
571 cmd.Implicits(extraInputs)
Colin Cross3d680512020-11-13 16:23:53 -0800572 cmd.ImplicitOutputs(task.out)
573 cmd.Implicits(task.in)
Colin Crossba9e4032020-11-24 16:32:22 -0800574 cmd.ImplicitTools(tools)
575 cmd.ImplicitTools(task.extraTools)
576 cmd.ImplicitPackagedTools(packagedTools)
Colin Cross3d680512020-11-13 16:23:53 -0800577 if Bool(g.properties.Depfile) {
578 cmd.ImplicitDepFile(task.depFile)
579 }
580
581 // Create the rule to run the genrule command inside sbox.
Colin Crossf1a035e2020-11-16 17:32:30 -0800582 rule.Build(name, desc)
Colin Cross1a527682019-09-23 15:55:30 -0700583
584 if len(task.copyTo) > 0 {
Colin Cross3d680512020-11-13 16:23:53 -0800585 // If copyTo is set, multiple shards need to be copied into a single directory.
586 // task.out contains the per-shard paths, and copyTo contains the corresponding
587 // final path. The files need to be copied into the final directory by a
588 // single rule so it can remove the directory before it starts to ensure no
589 // old files remain. zipsync already does this, so build up zipArgs that
590 // zip all the per-shard directories into a single zip.
Colin Cross1a527682019-09-23 15:55:30 -0700591 outputFiles = append(outputFiles, task.copyTo...)
592 copyFrom = append(copyFrom, task.out.Paths()...)
593 zipArgs.WriteString(" -C " + task.genDir.String())
594 zipArgs.WriteString(android.JoinWithPrefix(task.out.Strings(), " -f "))
595 } else {
596 outputFiles = append(outputFiles, task.out...)
597 }
Colin Cross6f080df2016-11-04 15:32:58 -0700598 }
599
Colin Cross1a527682019-09-23 15:55:30 -0700600 if len(copyFrom) > 0 {
Colin Cross3d680512020-11-13 16:23:53 -0800601 // Create a rule that zips all the per-shard directories into a single zip and then
602 // uses zipsync to unzip it into the final directory.
Colin Cross1a527682019-09-23 15:55:30 -0700603 ctx.Build(pctx, android.BuildParams{
Colin Crossf1885962020-11-20 15:28:30 -0800604 Rule: gensrcsMerge,
605 Implicits: copyFrom,
606 Outputs: outputFiles,
607 Description: "merge shards",
Colin Cross1a527682019-09-23 15:55:30 -0700608 Args: map[string]string{
609 "zipArgs": zipArgs.String(),
610 "tmpZip": android.PathForModuleGen(ctx, g.subDir+".zip").String(),
611 "genDir": android.PathForModuleGen(ctx, g.subDir).String(),
612 },
613 })
Colin Cross85a2e892018-07-09 09:45:06 -0700614 }
615
Colin Cross1a527682019-09-23 15:55:30 -0700616 g.outputFiles = outputFiles.Paths()
Chris Parsonsf874e462022-05-10 13:50:12 -0400617}
Jeff Gastonefc1b412017-03-29 17:29:06 -0700618
Chris Parsonsf874e462022-05-10 13:50:12 -0400619func (g *Module) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Vinh Tran140d5882022-06-10 14:23:27 -0400620 // Allowlist genrule to use depfile until we have a solution to remove it.
621 // TODO(b/235582219): Remove allowlist for genrule
Yu Liu6a7940c2023-05-09 17:12:22 -0700622 if Bool(g.properties.Depfile) {
Yu Liue7f7cbf2023-06-13 18:50:03 +0000623 sandboxingAllowlistSets := getSandboxingAllowlistSets(ctx)
Yu Liu6a7940c2023-05-09 17:12:22 -0700624 // TODO(b/283852474): Checking the GenruleSandboxing flag is temporary in
625 // order to pass the presubmit before internal master is updated.
Yu Liue7f7cbf2023-06-13 18:50:03 +0000626 if ctx.DeviceConfig().GenruleSandboxing() && !sandboxingAllowlistSets.depfileAllowSet[g.Name()] {
Yu Liu6a7940c2023-05-09 17:12:22 -0700627 ctx.PropertyErrorf(
628 "depfile",
629 "Deprecated to ensure the module type is convertible to Bazel. "+
630 "Try specifying the dependencies explicitly so that there is no need to use depfile. "+
631 "If not possible, the escape hatch is to add the module to allowlists.go to bypass the error.")
632 }
Vinh Tran140d5882022-06-10 14:23:27 -0400633 }
634
Chris Parsonsf874e462022-05-10 13:50:12 -0400635 g.generateCommonBuildActions(ctx)
636
637 // For <= 6 outputs, just embed those directly in the users. Right now, that covers >90% of
638 // the genrules on AOSP. That will make things simpler to look at the graph in the common
639 // case. For larger sets of outputs, inject a phony target in between to limit ninja file
640 // growth.
641 if len(g.outputFiles) <= 6 {
642 g.outputDeps = g.outputFiles
643 } else {
644 phonyFile := android.PathForModuleGen(ctx, "genrule-phony")
645 ctx.Build(pctx, android.BuildParams{
646 Rule: blueprint.Phony,
647 Output: phonyFile,
648 Inputs: g.outputFiles,
649 })
650 g.outputDeps = android.Paths{phonyFile}
Jeff Gaston02a684b2017-10-27 14:59:27 -0700651 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400652}
653
654func (g *Module) QueueBazelCall(ctx android.BaseModuleContext) {
655 bazelCtx := ctx.Config().BazelContext
656 bazelCtx.QueueBazelRequest(g.GetBazelLabel(ctx, g), cquery.GetOutputFiles, android.GetConfigKey(ctx))
657}
658
659func (g *Module) IsMixedBuildSupported(ctx android.BaseModuleContext) bool {
660 return true
Colin Crossd350ecd2015-04-28 13:25:36 -0700661}
Colin Crossd350ecd2015-04-28 13:25:36 -0700662
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700663// Collect information for opening IDE project files in java/jdeps.go.
664func (g *Module) IDEInfo(dpInfo *android.IdeInfo) {
665 dpInfo.Srcs = append(dpInfo.Srcs, g.Srcs().Strings()...)
666 for _, src := range g.properties.Srcs {
667 if strings.HasPrefix(src, ":") {
668 src = strings.Trim(src, ":")
669 dpInfo.Deps = append(dpInfo.Deps, src)
670 }
671 }
bralee1fbf4402020-05-21 10:11:59 +0800672 dpInfo.Paths = append(dpInfo.Paths, g.modulePaths...)
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700673}
674
Colin Crossa4ad2b02019-03-18 22:15:32 -0700675func (g *Module) AndroidMk() android.AndroidMkData {
676 return android.AndroidMkData{
Anton Hansson72f18492020-10-30 16:34:45 +0000677 Class: "ETC",
Colin Crossa4ad2b02019-03-18 22:15:32 -0700678 OutputFile: android.OptionalPathForPath(g.outputFiles[0]),
679 SubName: g.subName,
680 Extra: []android.AndroidMkExtraFunc{
681 func(w io.Writer, outputFile android.Path) {
Anton Hansson72f18492020-10-30 16:34:45 +0000682 fmt.Fprintln(w, "LOCAL_UNINSTALLABLE_MODULE := true")
Colin Crossa4ad2b02019-03-18 22:15:32 -0700683 },
684 },
685 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
686 android.WriteAndroidMkData(w, data)
687 if data.SubName != "" {
688 fmt.Fprintln(w, ".PHONY:", name)
689 fmt.Fprintln(w, name, ":", name+g.subName)
690 }
691 },
692 }
693}
694
Jiyong Park45bf82e2020-12-15 22:29:02 +0900695var _ android.ApexModule = (*Module)(nil)
696
697// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -0700698func (g *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
699 sdkVersion android.ApiLevel) error {
Jooyung Han749dc692020-04-15 11:03:39 +0900700 // Because generated outputs are checked by client modules(e.g. cc_library, ...)
701 // we can safely ignore the check here.
702 return nil
703}
704
Jeff Gaston437d23c2017-11-08 12:38:00 -0800705func generatorFactory(taskGenerator taskFunc, props ...interface{}) *Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700706 module := &Module{
Jeff Gaston437d23c2017-11-08 12:38:00 -0800707 taskGenerator: taskGenerator,
Colin Crossd350ecd2015-04-28 13:25:36 -0700708 }
709
Colin Cross36242852017-06-23 15:06:31 -0700710 module.AddProperties(props...)
711 module.AddProperties(&module.properties)
Colin Crossd350ecd2015-04-28 13:25:36 -0700712
Colin Cross7228ecd2019-11-18 16:00:16 -0800713 module.ImageInterface = noopImageInterface{}
714
Colin Cross36242852017-06-23 15:06:31 -0700715 return module
Colin Crossd350ecd2015-04-28 13:25:36 -0700716}
717
Colin Cross7228ecd2019-11-18 16:00:16 -0800718type noopImageInterface struct{}
719
720func (x noopImageInterface) ImageMutatorBegin(android.BaseModuleContext) {}
721func (x noopImageInterface) CoreVariantNeeded(android.BaseModuleContext) bool { return false }
Yifan Hong1b3348d2020-01-21 15:53:22 -0800722func (x noopImageInterface) RamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700723func (x noopImageInterface) VendorRamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Inseob Kim08758f02021-04-08 21:13:22 +0900724func (x noopImageInterface) DebugRamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Colin Cross7228ecd2019-11-18 16:00:16 -0800725func (x noopImageInterface) RecoveryVariantNeeded(android.BaseModuleContext) bool { return false }
726func (x noopImageInterface) ExtraImageVariations(ctx android.BaseModuleContext) []string { return nil }
727func (x noopImageInterface) SetImageVariation(ctx android.BaseModuleContext, variation string, module android.Module) {
728}
729
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700730func NewGenSrcs() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700731 properties := &genSrcsProperties{}
732
Colin Crossf1885962020-11-20 15:28:30 -0800733 // finalSubDir is the name of the subdirectory that output files will be generated into.
734 // It is used so that per-shard directories can be placed alongside it an then finally
735 // merged into it.
736 const finalSubDir = "gensrcs"
737
Colin Cross1a527682019-09-23 15:55:30 -0700738 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Colin Cross1a527682019-09-23 15:55:30 -0700739 shardSize := defaultShardSize
740 if s := properties.Shard_size; s != nil {
741 shardSize = int(*s)
742 }
Jeff Gaston437d23c2017-11-08 12:38:00 -0800743
Colin Crossf1885962020-11-20 15:28:30 -0800744 // gensrcs rules can easily hit command line limits by repeating the command for
745 // every input file. Shard the input files into groups.
Colin Cross1a527682019-09-23 15:55:30 -0700746 shards := android.ShardPaths(srcFiles, shardSize)
747 var generateTasks []generateTask
Colin Crossbaccf5b2018-02-21 14:07:48 -0800748
Colin Cross1a527682019-09-23 15:55:30 -0700749 for i, shard := range shards {
750 var commands []string
751 var outFiles android.WritablePaths
Colin Cross3ea4eb82020-11-24 13:07:27 -0800752 var commandDepFiles []string
Colin Cross1a527682019-09-23 15:55:30 -0700753 var copyTo android.WritablePaths
Colin Cross1a527682019-09-23 15:55:30 -0700754
Colin Crossf1885962020-11-20 15:28:30 -0800755 // When sharding is enabled (i.e. len(shards) > 1), the sbox rules for each
756 // shard will be write to their own directories and then be merged together
757 // into finalSubDir. If sharding is not enabled (i.e. len(shards) == 1),
758 // the sbox rule will write directly to finalSubDir.
759 genSubDir := finalSubDir
Colin Cross1a527682019-09-23 15:55:30 -0700760 if len(shards) > 1 {
Colin Crossf1885962020-11-20 15:28:30 -0800761 genSubDir = strconv.Itoa(i)
Jeff Gaston437d23c2017-11-08 12:38:00 -0800762 }
763
Colin Crossf1885962020-11-20 15:28:30 -0800764 genDir := android.PathForModuleGen(ctx, genSubDir)
Colin Crossf1a035e2020-11-16 17:32:30 -0800765 // TODO(ccross): this RuleBuilder is a hack to be able to call
766 // rule.Command().PathForOutput. Replace this with passing the rule into the
767 // generator.
Yu Liu6a7940c2023-05-09 17:12:22 -0700768 rule := getSandboxedRuleBuilder(ctx, android.NewRuleBuilder(pctx, ctx).Sbox(genDir, nil))
Jeff Gaston437d23c2017-11-08 12:38:00 -0800769
Colin Cross3ea4eb82020-11-24 13:07:27 -0800770 for _, in := range shard {
Colin Crossf1885962020-11-20 15:28:30 -0800771 outFile := android.GenPathWithExt(ctx, finalSubDir, in, String(properties.Output_extension))
772
773 // If sharding is enabled, then outFile is the path to the output file in
774 // the shard directory, and copyTo is the path to the output file in the
775 // final directory.
Colin Cross1a527682019-09-23 15:55:30 -0700776 if len(shards) > 1 {
Colin Crossf1885962020-11-20 15:28:30 -0800777 shardFile := android.GenPathWithExt(ctx, genSubDir, in, String(properties.Output_extension))
Colin Cross1a527682019-09-23 15:55:30 -0700778 copyTo = append(copyTo, outFile)
779 outFile = shardFile
780 }
781
782 outFiles = append(outFiles, outFile)
Colin Cross1a527682019-09-23 15:55:30 -0700783
Colin Crossf1885962020-11-20 15:28:30 -0800784 // pre-expand the command line to replace $in and $out with references to
785 // a single input and output file.
Colin Cross1a527682019-09-23 15:55:30 -0700786 command, err := android.Expand(rawCommand, func(name string) (string, error) {
787 switch name {
788 case "in":
789 return in.String(), nil
790 case "out":
Colin Crossf1a035e2020-11-16 17:32:30 -0800791 return rule.Command().PathForOutput(outFile), nil
Colin Cross3ea4eb82020-11-24 13:07:27 -0800792 case "depfile":
793 // Generate a depfile for each output file. Store the list for
794 // later in order to combine them all into a single depfile.
Colin Crossf1a035e2020-11-16 17:32:30 -0800795 depFile := rule.Command().PathForOutput(outFile.ReplaceExtension(ctx, "d"))
Colin Cross3ea4eb82020-11-24 13:07:27 -0800796 commandDepFiles = append(commandDepFiles, depFile)
797 return depFile, nil
Colin Cross1a527682019-09-23 15:55:30 -0700798 default:
799 return "$(" + name + ")", nil
800 }
801 })
802 if err != nil {
803 ctx.PropertyErrorf("cmd", err.Error())
804 }
805
806 // escape the command in case for example it contains '#', an odd number of '"', etc
807 command = fmt.Sprintf("bash -c %v", proptools.ShellEscape(command))
808 commands = append(commands, command)
809 }
810 fullCommand := strings.Join(commands, " && ")
811
Colin Cross3ea4eb82020-11-24 13:07:27 -0800812 var outputDepfile android.WritablePath
813 var extraTools android.Paths
814 if len(commandDepFiles) > 0 {
815 // Each command wrote to a depfile, but ninja can only handle one
816 // depfile per rule. Use the dep_fixer tool at the end of the
817 // command to combine all the depfiles into a single output depfile.
818 outputDepfile = android.PathForModuleGen(ctx, genSubDir, "gensrcs.d")
819 depFixerTool := ctx.Config().HostToolPath(ctx, "dep_fixer")
820 fullCommand += fmt.Sprintf(" && %s -o $(depfile) %s",
Colin Crossd11cf622021-03-23 22:30:35 -0700821 rule.Command().PathForTool(depFixerTool),
Colin Crossba9e4032020-11-24 16:32:22 -0800822 strings.Join(commandDepFiles, " "))
Colin Cross3ea4eb82020-11-24 13:07:27 -0800823 extraTools = append(extraTools, depFixerTool)
824 }
825
Colin Cross1a527682019-09-23 15:55:30 -0700826 generateTasks = append(generateTasks, generateTask{
Colin Cross3ea4eb82020-11-24 13:07:27 -0800827 in: shard,
828 out: outFiles,
829 depFile: outputDepfile,
830 copyTo: copyTo,
831 genDir: genDir,
832 cmd: fullCommand,
833 shard: i,
834 shards: len(shards),
835 extraTools: extraTools,
Liz Kammer81fec182023-06-09 13:33:45 -0400836 extraInputs: map[string][]string{
837 "data": properties.Data,
838 },
Colin Cross1a527682019-09-23 15:55:30 -0700839 })
Jeff Gaston437d23c2017-11-08 12:38:00 -0800840 }
Colin Cross1a527682019-09-23 15:55:30 -0700841
842 return generateTasks
Colin Crossd350ecd2015-04-28 13:25:36 -0700843 }
844
Colin Cross1a527682019-09-23 15:55:30 -0700845 g := generatorFactory(taskGenerator, properties)
Colin Crossf1885962020-11-20 15:28:30 -0800846 g.subDir = finalSubDir
Colin Cross1a527682019-09-23 15:55:30 -0700847 return g
Colin Crossd350ecd2015-04-28 13:25:36 -0700848}
849
Colin Cross54190b32017-10-09 15:34:10 -0700850func GenSrcsFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700851 m := NewGenSrcs()
852 android.InitAndroidModule(m)
Vinh Tranb69e1ae2022-05-20 18:54:09 -0400853 android.InitBazelModule(m)
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700854 return m
855}
856
Colin Crossd350ecd2015-04-28 13:25:36 -0700857type genSrcsProperties struct {
Colin Cross7d5136f2015-05-11 13:39:40 -0700858 // extension that will be substituted for each output file
Nan Zhanga5e7cb42017-11-09 22:42:32 -0800859 Output_extension *string
Colin Cross1a527682019-09-23 15:55:30 -0700860
861 // maximum number of files that will be passed on a single command line.
862 Shard_size *int64
Liz Kammer81fec182023-06-09 13:33:45 -0400863
864 // Additional files needed for build that are not tooling related.
865 Data []string `android:"path"`
Colin Cross5049f022015-03-18 13:28:46 -0700866}
867
Vinh Tranb69e1ae2022-05-20 18:54:09 -0400868type bazelGensrcsAttributes struct {
869 Srcs bazel.LabelListAttribute
870 Output_extension *string
871 Tools bazel.LabelListAttribute
872 Cmd string
Liz Kammer8bd92422023-06-09 13:41:08 -0400873 Data bazel.LabelListAttribute
Vinh Tranb69e1ae2022-05-20 18:54:09 -0400874}
875
Evgenii Stepanovf47c90d2020-12-02 18:55:09 -0800876const defaultShardSize = 50
Colin Cross1a527682019-09-23 15:55:30 -0700877
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700878func NewGenRule() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700879 properties := &genRuleProperties{}
Colin Cross5049f022015-03-18 13:28:46 -0700880
Colin Cross1a527682019-09-23 15:55:30 -0700881 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700882 outs := make(android.WritablePaths, len(properties.Out))
Colin Cross3d680512020-11-13 16:23:53 -0800883 var depFile android.WritablePath
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700884 for i, out := range properties.Out {
Colin Cross3d680512020-11-13 16:23:53 -0800885 outPath := android.PathForModuleGen(ctx, out)
886 if i == 0 {
887 depFile = outPath.ReplaceExtension(ctx, "d")
888 }
889 outs[i] = outPath
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700890 }
Colin Cross1a527682019-09-23 15:55:30 -0700891 return []generateTask{{
Colin Cross3d680512020-11-13 16:23:53 -0800892 in: srcFiles,
893 out: outs,
894 depFile: depFile,
895 genDir: android.PathForModuleGen(ctx),
896 cmd: rawCommand,
Colin Cross1a527682019-09-23 15:55:30 -0700897 }}
Colin Cross5049f022015-03-18 13:28:46 -0700898 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700899
Jeff Gaston437d23c2017-11-08 12:38:00 -0800900 return generatorFactory(taskGenerator, properties)
Colin Cross5049f022015-03-18 13:28:46 -0700901}
902
Colin Cross54190b32017-10-09 15:34:10 -0700903func GenRuleFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700904 m := NewGenRule()
905 android.InitAndroidModule(m)
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800906 android.InitDefaultableModule(m)
Liz Kammerea6666f2021-02-17 10:17:28 -0500907 android.InitBazelModule(m)
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700908 return m
909}
910
Colin Crossd350ecd2015-04-28 13:25:36 -0700911type genRuleProperties struct {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700912 // names of the output files that will be generated
Yu Liud6201012022-10-17 12:29:15 -0700913 Out []string
Colin Cross5049f022015-03-18 13:28:46 -0700914}
Nan Zhangea568a42017-11-08 21:20:04 -0800915
Jingwen Chen316e07c2020-12-14 09:09:52 -0500916type bazelGenruleAttributes struct {
Jingwen Chen07027912021-03-15 06:02:43 -0400917 Srcs bazel.LabelListAttribute
Jingwen Chen316e07c2020-12-14 09:09:52 -0500918 Outs []string
Jingwen Chen07027912021-03-15 06:02:43 -0400919 Tools bazel.LabelListAttribute
Jingwen Chen316e07c2020-12-14 09:09:52 -0500920 Cmd string
921}
922
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400923// ConvertWithBp2build converts a Soong module -> Bazel target.
924func (m *Module) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
Liz Kammer356f7d42021-01-26 09:18:53 -0500925 // Bazel only has the "tools" attribute.
Jingwen Chen07027912021-03-15 06:02:43 -0400926 tools_prop := android.BazelLabelForModuleDeps(ctx, m.properties.Tools)
927 tool_files_prop := android.BazelLabelForModuleSrc(ctx, m.properties.Tool_files)
928 tools_prop.Append(tool_files_prop)
Liz Kammer356f7d42021-01-26 09:18:53 -0500929
Jingwen Chen07027912021-03-15 06:02:43 -0400930 tools := bazel.MakeLabelListAttribute(tools_prop)
Yu Liud6201012022-10-17 12:29:15 -0700931 srcs := bazel.LabelListAttribute{}
932 srcs_labels := bazel.LabelList{}
933 // Only cc_genrule is arch specific
934 if ctx.ModuleType() == "cc_genrule" {
935 for axis, configToProps := range m.GetArchVariantProperties(ctx, &generatorProperties{}) {
936 for config, props := range configToProps {
937 if props, ok := props.(*generatorProperties); ok {
938 labels := android.BazelLabelForModuleSrcExcludes(ctx, props.Srcs, props.Exclude_srcs)
939 srcs_labels.Append(labels)
940 srcs.SetSelectValue(axis, config, labels)
941 }
942 }
943 }
944 } else {
945 srcs_labels = android.BazelLabelForModuleSrcExcludes(ctx, m.properties.Srcs, m.properties.Exclude_srcs)
946 srcs = bazel.MakeLabelListAttribute(srcs_labels)
947 }
Liz Kammer356f7d42021-01-26 09:18:53 -0500948
949 var allReplacements bazel.LabelList
Jingwen Chen07027912021-03-15 06:02:43 -0400950 allReplacements.Append(tools.Value)
Yu Liud6201012022-10-17 12:29:15 -0700951 allReplacements.Append(bazel.FirstUniqueBazelLabelList(srcs_labels))
Liz Kammer356f7d42021-01-26 09:18:53 -0500952
Liz Kammer8bd92422023-06-09 13:41:08 -0400953 // The Output_extension prop is not in an immediately accessible field
954 // in the Module struct, so use GetProperties and cast it
955 // to the known struct prop.
956 var outputExtension *string
957 var data bazel.LabelListAttribute
958 if ctx.ModuleType() == "gensrcs" {
959 for _, propIntf := range m.GetProperties() {
960 if props, ok := propIntf.(*genSrcsProperties); ok {
961 outputExtension = props.Output_extension
962 dataFiles := android.BazelLabelForModuleSrc(ctx, props.Data)
963 allReplacements.Append(bazel.FirstUniqueBazelLabelList(dataFiles))
964 data = bazel.MakeLabelListAttribute(dataFiles)
965 break
966 }
967 }
968 }
969
Liz Kammer356f7d42021-01-26 09:18:53 -0500970 // Replace in and out variables with $< and $@
971 var cmd string
972 if m.properties.Cmd != nil {
Vinh Tranb69e1ae2022-05-20 18:54:09 -0400973 if ctx.ModuleType() == "gensrcs" {
974 cmd = strings.ReplaceAll(*m.properties.Cmd, "$(in)", "$(SRC)")
975 cmd = strings.ReplaceAll(cmd, "$(out)", "$(OUT)")
976 } else {
977 cmd = strings.Replace(*m.properties.Cmd, "$(in)", "$(SRCS)", -1)
978 cmd = strings.Replace(cmd, "$(out)", "$(OUTS)", -1)
979 }
Vinh Tran32a98a52022-09-23 13:08:34 -0400980 cmd = strings.Replace(cmd, "$(genDir)", "$(RULEDIR)", -1)
Jingwen Chen07027912021-03-15 06:02:43 -0400981 if len(tools.Value.Includes) > 0 {
982 cmd = strings.Replace(cmd, "$(location)", fmt.Sprintf("$(location %s)", tools.Value.Includes[0].Label), -1)
983 cmd = strings.Replace(cmd, "$(locations)", fmt.Sprintf("$(locations %s)", tools.Value.Includes[0].Label), -1)
Liz Kammer356f7d42021-01-26 09:18:53 -0500984 }
985 for _, l := range allReplacements.Includes {
Jingwen Chen38e62642021-04-19 05:00:15 +0000986 bpLoc := fmt.Sprintf("$(location %s)", l.OriginalModuleName)
987 bpLocs := fmt.Sprintf("$(locations %s)", l.OriginalModuleName)
Liz Kammer356f7d42021-01-26 09:18:53 -0500988 bazelLoc := fmt.Sprintf("$(location %s)", l.Label)
989 bazelLocs := fmt.Sprintf("$(locations %s)", l.Label)
990 cmd = strings.Replace(cmd, bpLoc, bazelLoc, -1)
991 cmd = strings.Replace(cmd, bpLocs, bazelLocs, -1)
992 }
993 }
994
Spandan Das39b6cc52023-04-12 19:05:49 +0000995 tags := android.ApexAvailableTagsWithoutTestApexes(ctx, m)
Sam Delmericoeddd3c02022-12-02 17:31:58 -0500996
Vinh Tranb69e1ae2022-05-20 18:54:09 -0400997 if ctx.ModuleType() == "gensrcs" {
Vinh Tranb69e1ae2022-05-20 18:54:09 -0400998 props := bazel.BazelTargetModuleProperties{
999 Rule_class: "gensrcs",
1000 Bzl_load_location: "//build/bazel/rules:gensrcs.bzl",
1001 }
1002 attrs := &bazelGensrcsAttributes{
1003 Srcs: srcs,
1004 Output_extension: outputExtension,
1005 Cmd: cmd,
1006 Tools: tools,
Liz Kammer8bd92422023-06-09 13:41:08 -04001007 Data: data,
Vinh Tranb69e1ae2022-05-20 18:54:09 -04001008 }
Sam Delmericoeddd3c02022-12-02 17:31:58 -05001009 ctx.CreateBazelTargetModule(props, android.CommonAttributes{
1010 Name: m.Name(),
1011 Tags: tags,
1012 }, attrs)
Vinh Tranb69e1ae2022-05-20 18:54:09 -04001013 } else {
1014 // The Out prop is not in an immediately accessible field
1015 // in the Module struct, so use GetProperties and cast it
1016 // to the known struct prop.
1017 var outs []string
1018 for _, propIntf := range m.GetProperties() {
1019 if props, ok := propIntf.(*genRuleProperties); ok {
1020 outs = props.Out
1021 break
1022 }
1023 }
Chris Parsonsb7950a92023-06-16 17:41:42 +00001024 bazelName := m.Name()
1025 for _, out := range outs {
1026 if out == bazelName {
1027 // This is a workaround to circumvent a Bazel warning where a genrule's
1028 // out may not have the same name as the target itself. This makes no
1029 // difference for reverse dependencies, because they may depend on the
1030 // out file by name.
1031 bazelName = bazelName + "-gen"
1032 break
1033 }
1034 }
Vinh Tranb69e1ae2022-05-20 18:54:09 -04001035 attrs := &bazelGenruleAttributes{
1036 Srcs: srcs,
1037 Outs: outs,
1038 Cmd: cmd,
1039 Tools: tools,
1040 }
1041 props := bazel.BazelTargetModuleProperties{
1042 Rule_class: "genrule",
1043 }
Sam Delmericoeddd3c02022-12-02 17:31:58 -05001044 ctx.CreateBazelTargetModule(props, android.CommonAttributes{
Chris Parsonsb7950a92023-06-16 17:41:42 +00001045 Name: bazelName,
Sam Delmericoeddd3c02022-12-02 17:31:58 -05001046 Tags: tags,
1047 }, attrs)
Liz Kammer356f7d42021-01-26 09:18:53 -05001048 }
Jingwen Chen316e07c2020-12-14 09:09:52 -05001049}
1050
Nan Zhangea568a42017-11-08 21:20:04 -08001051var Bool = proptools.Bool
1052var String = proptools.String
Jaewoong Jung98716bd2018-12-10 08:13:18 -08001053
Jaewoong Jung98716bd2018-12-10 08:13:18 -08001054// Defaults
Jaewoong Jung98716bd2018-12-10 08:13:18 -08001055type Defaults struct {
1056 android.ModuleBase
1057 android.DefaultsModuleBase
1058}
1059
Jaewoong Jung98716bd2018-12-10 08:13:18 -08001060func defaultsFactory() android.Module {
1061 return DefaultsFactory()
1062}
1063
1064func DefaultsFactory(props ...interface{}) android.Module {
1065 module := &Defaults{}
1066
1067 module.AddProperties(props...)
1068 module.AddProperties(
1069 &generatorProperties{},
1070 &genRuleProperties{},
1071 )
1072
1073 android.InitDefaultsModule(module)
1074
1075 return module
1076}
Yu Liu6a7940c2023-05-09 17:12:22 -07001077
Yu Liue7f7cbf2023-06-13 18:50:03 +00001078var sandboxingAllowlistKey = android.NewOnceKey("genruleSandboxingAllowlistKey")
1079
1080type sandboxingAllowlistSets struct {
1081 sandboxingDenyModuleSet map[string]bool
1082 sandboxingDenyPathSet map[string]bool
1083 depfileAllowSet map[string]bool
1084}
1085
1086func getSandboxingAllowlistSets(ctx android.PathContext) *sandboxingAllowlistSets {
1087 return ctx.Config().Once(sandboxingAllowlistKey, func() interface{} {
1088 sandboxingDenyModuleSet := map[string]bool{}
1089 sandboxingDenyPathSet := map[string]bool{}
1090 depfileAllowSet := map[string]bool{}
1091
1092 android.AddToStringSet(sandboxingDenyModuleSet, append(DepfileAllowList, SandboxingDenyModuleList...))
1093 android.AddToStringSet(sandboxingDenyPathSet, SandboxingDenyPathList)
1094 android.AddToStringSet(depfileAllowSet, DepfileAllowList)
1095 return &sandboxingAllowlistSets{
1096 sandboxingDenyModuleSet: sandboxingDenyModuleSet,
1097 sandboxingDenyPathSet: sandboxingDenyPathSet,
1098 depfileAllowSet: depfileAllowSet,
1099 }
1100 }).(*sandboxingAllowlistSets)
1101}
Yu Liu6a7940c2023-05-09 17:12:22 -07001102func getSandboxedRuleBuilder(ctx android.ModuleContext, r *android.RuleBuilder) *android.RuleBuilder {
Yu Liu45d6af52023-05-24 23:10:18 +00001103 if !ctx.DeviceConfig().GenruleSandboxing() {
1104 return r.SandboxTools()
1105 }
Yu Liue7f7cbf2023-06-13 18:50:03 +00001106 sandboxingAllowlistSets := getSandboxingAllowlistSets(ctx)
1107 if sandboxingAllowlistSets.sandboxingDenyPathSet[ctx.ModuleDir()] ||
1108 sandboxingAllowlistSets.sandboxingDenyModuleSet[ctx.ModuleName()] {
Yu Liu6a7940c2023-05-09 17:12:22 -07001109 return r.SandboxTools()
1110 }
1111 return r.SandboxInputs()
1112}