blob: 5d438eac27c4018ffb302915006cf20f3b30b25f [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
Colin Cross70b40592015-03-23 12:57:34 -070028 "github.com/google/blueprint"
Dan Willemsen8eded0a2017-09-13 16:07:44 -070029 "github.com/google/blueprint/bootstrap"
Nan Zhangea568a42017-11-08 21:20:04 -080030 "github.com/google/blueprint/proptools"
Colin Cross5049f022015-03-18 13:28:46 -070031
Colin Cross635c3b02016-05-18 15:37:25 -070032 "android/soong/android"
Jingwen Chen30f5aaa2020-11-19 05:38:02 -050033 "android/soong/bazel"
Colin Cross5049f022015-03-18 13:28:46 -070034)
35
Colin Cross463a90e2015-06-17 14:20:06 -070036func init() {
Colin Crosse9fe2942020-11-10 18:12:15 -080037 RegisterGenruleBuildComponents(android.InitRegistrationContext)
Martin Stjernholm710ec3a2020-01-16 15:12:04 +000038}
Jaewoong Jung98716bd2018-12-10 08:13:18 -080039
Paul Duffin672cb9f2021-03-03 02:30:37 +000040// Test fixture preparer that will register most genrule build components.
41//
42// Singletons and mutators should only be added here if they are needed for a majority of genrule
43// module types, otherwise they should be added under a separate preparer to allow them to be
44// selected only when needed to reduce test execution time.
45//
46// Module types do not have much of an overhead unless they are used so this should include as many
47// module types as possible. The exceptions are those module types that require mutators and/or
48// singletons in order to function in which case they should be kept together in a separate
49// preparer.
50var PrepareForTestWithGenRuleBuildComponents = android.GroupFixturePreparers(
51 android.FixtureRegisterWithContext(RegisterGenruleBuildComponents),
52)
53
54// Prepare a fixture to use all genrule module types, mutators and singletons fully.
55//
56// This should only be used by tests that want to run with as much of the build enabled as possible.
57var PrepareForIntegrationTestWithGenrule = android.GroupFixturePreparers(
58 PrepareForTestWithGenRuleBuildComponents,
59)
60
Colin Crosse9fe2942020-11-10 18:12:15 -080061func RegisterGenruleBuildComponents(ctx android.RegistrationContext) {
Martin Stjernholm710ec3a2020-01-16 15:12:04 +000062 ctx.RegisterModuleType("genrule_defaults", defaultsFactory)
63
64 ctx.RegisterModuleType("gensrcs", GenSrcsFactory)
65 ctx.RegisterModuleType("genrule", GenRuleFactory)
66
67 ctx.FinalDepsMutators(func(ctx android.RegisterMutatorsContext) {
68 ctx.BottomUp("genrule_tool_deps", toolDepsMutator).Parallel()
69 })
Jingwen Chen316e07c2020-12-14 09:09:52 -050070
Liz Kammer356f7d42021-01-26 09:18:53 -050071 android.DepsBp2BuildMutators(RegisterGenruleBp2BuildDeps)
Jingwen Chena42d6412021-01-26 21:57:27 -050072 android.RegisterBp2BuildMutator("genrule", GenruleBp2Build)
Colin Cross463a90e2015-06-17 14:20:06 -070073}
74
Liz Kammer356f7d42021-01-26 09:18:53 -050075func RegisterGenruleBp2BuildDeps(ctx android.RegisterMutatorsContext) {
76 ctx.BottomUp("genrule_tool_deps", toolDepsMutator)
77}
78
Colin Cross5049f022015-03-18 13:28:46 -070079var (
Colin Cross635c3b02016-05-18 15:37:25 -070080 pctx = android.NewPackageContext("android/soong/genrule")
Colin Cross1a527682019-09-23 15:55:30 -070081
Alex Humesky29e3bbe2020-11-20 21:30:13 -050082 // Used by gensrcs when there is more than 1 shard to merge the outputs
83 // of each shard into a zip file.
Colin Cross1a527682019-09-23 15:55:30 -070084 gensrcsMerge = pctx.AndroidStaticRule("gensrcsMerge", blueprint.RuleParams{
85 Command: "${soongZip} -o ${tmpZip} @${tmpZip}.rsp && ${zipSync} -d ${genDir} ${tmpZip}",
86 CommandDeps: []string{"${soongZip}", "${zipSync}"},
87 Rspfile: "${tmpZip}.rsp",
88 RspfileContent: "${zipArgs}",
89 }, "tmpZip", "genDir", "zipArgs")
Colin Cross5049f022015-03-18 13:28:46 -070090)
91
Jeff Gastonefc1b412017-03-29 17:29:06 -070092func init() {
Dan Willemsenddf504c2019-08-09 16:21:29 -070093 pctx.Import("android/soong/android")
Colin Cross1a527682019-09-23 15:55:30 -070094
95 pctx.HostBinToolVariable("soongZip", "soong_zip")
96 pctx.HostBinToolVariable("zipSync", "zipsync")
Jeff Gastonefc1b412017-03-29 17:29:06 -070097}
98
Colin Cross5049f022015-03-18 13:28:46 -070099type SourceFileGenerator interface {
Colin Cross635c3b02016-05-18 15:37:25 -0700100 GeneratedSourceFiles() android.Paths
Colin Cross5ed99c62016-11-22 12:55:55 -0800101 GeneratedHeaderDirs() android.Paths
Dan Willemsen9da9d492018-02-21 18:28:18 -0800102 GeneratedDeps() android.Paths
Colin Cross5049f022015-03-18 13:28:46 -0700103}
104
Colin Crossfe17f6f2019-03-28 19:30:56 -0700105// Alias for android.HostToolProvider
106// Deprecated: use android.HostToolProvider instead.
Colin Crossd350ecd2015-04-28 13:25:36 -0700107type HostToolProvider interface {
Colin Crossfe17f6f2019-03-28 19:30:56 -0700108 android.HostToolProvider
Colin Crossd350ecd2015-04-28 13:25:36 -0700109}
Colin Cross5049f022015-03-18 13:28:46 -0700110
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700111type hostToolDependencyTag struct {
112 blueprint.BaseDependencyTag
Colin Cross08f15ab2018-10-04 23:29:14 -0700113 label string
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700114}
Colin Cross7d5136f2015-05-11 13:39:40 -0700115type generatorProperties struct {
Jeff Gastonefc1b412017-03-29 17:29:06 -0700116 // The command to run on one or more input files. Cmd supports substitution of a few variables
Jeff Gastonefc1b412017-03-29 17:29:06 -0700117 //
118 // Available variables for substitution:
119 //
Colin Cross2296f5b2017-10-17 21:38:14 -0700120 // $(location): the path to the first entry in tools or tool_files
Colin Cross08f15ab2018-10-04 23:29:14 -0700121 // $(location <label>): the path to the tool, tool_file, input or output with name <label>
Colin Cross2296f5b2017-10-17 21:38:14 -0700122 // $(in): one or more input files
123 // $(out): a single output file
124 // $(depfile): a file to which dependencies will be written, if the depfile property is set to true
125 // $(genDir): the sandbox directory for this tool; contains $(out)
126 // $$: a literal $
Nan Zhangea568a42017-11-08 21:20:04 -0800127 Cmd *string
Colin Cross7d5136f2015-05-11 13:39:40 -0700128
Colin Cross33bfb0a2016-11-21 17:23:08 -0800129 // Enable reading a file containing dependencies in gcc format after the command completes
Nan Zhangea568a42017-11-08 21:20:04 -0800130 Depfile *bool
Colin Cross33bfb0a2016-11-21 17:23:08 -0800131
Colin Cross6f080df2016-11-04 15:32:58 -0700132 // name of the modules (if any) that produces the host executable. Leave empty for
Colin Cross7d5136f2015-05-11 13:39:40 -0700133 // prebuilts or scripts that do not need a module to build them.
Colin Cross6f080df2016-11-04 15:32:58 -0700134 Tools []string
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700135
136 // Local file that is used as the tool
Colin Cross27b922f2019-03-04 22:35:41 -0800137 Tool_files []string `android:"path"`
Colin Cross5ed99c62016-11-22 12:55:55 -0800138
139 // List of directories to export generated headers from
140 Export_include_dirs []string
Colin Cross708c4242017-01-13 18:05:49 -0800141
142 // list of input files
Colin Cross27b922f2019-03-04 22:35:41 -0800143 Srcs []string `android:"path,arch_variant"`
Dan Willemseneefa0262018-11-17 14:01:18 -0800144
145 // input files to exclude
Colin Cross27b922f2019-03-04 22:35:41 -0800146 Exclude_srcs []string `android:"path,arch_variant"`
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400147}
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500148
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700149type Module struct {
Colin Cross635c3b02016-05-18 15:37:25 -0700150 android.ModuleBase
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800151 android.DefaultableModuleBase
Liz Kammerea6666f2021-02-17 10:17:28 -0500152 android.BazelModuleBase
Jiyong Parkfc752ca2019-06-12 13:27:29 +0900153 android.ApexModuleBase
Colin Crossd350ecd2015-04-28 13:25:36 -0700154
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700155 // For other packages to make their own genrules with extra
156 // properties
157 Extra interface{}
Colin Cross7228ecd2019-11-18 16:00:16 -0800158 android.ImageInterface
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700159
Colin Cross7d5136f2015-05-11 13:39:40 -0700160 properties generatorProperties
Colin Crossd350ecd2015-04-28 13:25:36 -0700161
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500162 // For the different tasks that genrule and gensrc generate. genrule will
163 // generate 1 task, and gensrc will generate 1 or more tasks based on the
164 // number of shards the input files are sharded into.
Jeff Gaston437d23c2017-11-08 12:38:00 -0800165 taskGenerator taskFunc
Colin Crossd350ecd2015-04-28 13:25:36 -0700166
Colin Cross1a527682019-09-23 15:55:30 -0700167 rule blueprint.Rule
168 rawCommands []string
Colin Crossd350ecd2015-04-28 13:25:36 -0700169
Colin Cross5ed99c62016-11-22 12:55:55 -0800170 exportedIncludeDirs android.Paths
Dan Willemsenb40aab62016-04-20 14:21:14 -0700171
Colin Cross635c3b02016-05-18 15:37:25 -0700172 outputFiles android.Paths
Dan Willemsen9da9d492018-02-21 18:28:18 -0800173 outputDeps android.Paths
Colin Crossa4ad2b02019-03-18 22:15:32 -0700174
175 subName string
Colin Cross1a527682019-09-23 15:55:30 -0700176 subDir string
bralee1fbf4402020-05-21 10:11:59 +0800177
178 // Collect the module directory for IDE info in java/jdeps.go.
179 modulePaths []string
Colin Crossd350ecd2015-04-28 13:25:36 -0700180}
181
Colin Cross1a527682019-09-23 15:55:30 -0700182type taskFunc func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask
Colin Crossd350ecd2015-04-28 13:25:36 -0700183
184type generateTask struct {
Colin Cross3ea4eb82020-11-24 13:07:27 -0800185 in android.Paths
186 out android.WritablePaths
187 depFile android.WritablePath
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500188 copyTo android.WritablePaths // For gensrcs to set on gensrcsMerge rule.
Colin Cross3ea4eb82020-11-24 13:07:27 -0800189 genDir android.WritablePath
190 extraTools android.Paths // dependencies on tools used by the generator
191
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500192 cmd string
193 // For gensrsc sharding.
Colin Cross3ea4eb82020-11-24 13:07:27 -0800194 shard int
195 shards int
Colin Crossd350ecd2015-04-28 13:25:36 -0700196}
197
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700198func (g *Module) GeneratedSourceFiles() android.Paths {
Colin Crossd350ecd2015-04-28 13:25:36 -0700199 return g.outputFiles
200}
201
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700202func (g *Module) Srcs() android.Paths {
Nan Zhange42777a2018-03-27 16:19:42 -0700203 return append(android.Paths{}, g.outputFiles...)
Colin Cross068e0fe2016-12-13 15:23:47 -0800204}
205
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700206func (g *Module) GeneratedHeaderDirs() android.Paths {
Colin Cross5ed99c62016-11-22 12:55:55 -0800207 return g.exportedIncludeDirs
Dan Willemsenb40aab62016-04-20 14:21:14 -0700208}
209
Dan Willemsen9da9d492018-02-21 18:28:18 -0800210func (g *Module) GeneratedDeps() android.Paths {
211 return g.outputDeps
212}
213
Martin Stjernholm710ec3a2020-01-16 15:12:04 +0000214func toolDepsMutator(ctx android.BottomUpMutatorContext) {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700215 if g, ok := ctx.Module().(*Module); ok {
Colin Cross08f15ab2018-10-04 23:29:14 -0700216 for _, tool := range g.properties.Tools {
217 tag := hostToolDependencyTag{label: tool}
218 if m := android.SrcIsModule(tool); m != "" {
219 tool = m
220 }
Colin Cross0f7d2ef2019-10-16 11:03:10 -0700221 ctx.AddFarVariationDependencies(ctx.Config().BuildOSTarget.Variations(), tag, tool)
Colin Cross6362e272015-10-29 15:25:03 -0700222 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700223 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700224}
225
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400226// Returns true if information was available from Bazel, false if bazel invocation still needs to occur.
227func (c *Module) generateBazelBuildActions(ctx android.ModuleContext, label string) bool {
228 bazelCtx := ctx.Config().BazelContext
Chris Parsons944e7d02021-03-11 11:08:46 -0500229 filePaths, ok := bazelCtx.GetOutputFiles(label, ctx.Arch().ArchType)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400230 if ok {
231 var bazelOutputFiles android.Paths
232 for _, bazelOutputFile := range filePaths {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500233 bazelOutputFiles = append(bazelOutputFiles, android.PathForBazelOut(ctx, bazelOutputFile))
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400234 }
235 c.outputFiles = bazelOutputFiles
236 c.outputDeps = bazelOutputFiles
237 }
238 return ok
239}
Colin Crossf1885962020-11-20 15:28:30 -0800240
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700241func (g *Module) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Colin Crossa4ad2b02019-03-18 22:15:32 -0700242 g.subName = ctx.ModuleSubDir()
243
bralee1fbf4402020-05-21 10:11:59 +0800244 // Collect the module directory for IDE info in java/jdeps.go.
245 g.modulePaths = append(g.modulePaths, ctx.ModuleDir())
246
Colin Cross5ed99c62016-11-22 12:55:55 -0800247 if len(g.properties.Export_include_dirs) > 0 {
248 for _, dir := range g.properties.Export_include_dirs {
249 g.exportedIncludeDirs = append(g.exportedIncludeDirs,
Colin Cross1a527682019-09-23 15:55:30 -0700250 android.PathForModuleGen(ctx, g.subDir, ctx.ModuleDir(), dir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800251 }
252 } else {
Colin Cross1a527682019-09-23 15:55:30 -0700253 g.exportedIncludeDirs = append(g.exportedIncludeDirs, android.PathForModuleGen(ctx, g.subDir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800254 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700255
Colin Crossd11cf622021-03-23 22:30:35 -0700256 locationLabels := map[string]location{}
Colin Cross08f15ab2018-10-04 23:29:14 -0700257 firstLabel := ""
258
Colin Crossd11cf622021-03-23 22:30:35 -0700259 addLocationLabel := func(label string, loc location) {
Colin Cross08f15ab2018-10-04 23:29:14 -0700260 if firstLabel == "" {
261 firstLabel = label
262 }
263 if _, exists := locationLabels[label]; !exists {
Colin Crossd11cf622021-03-23 22:30:35 -0700264 locationLabels[label] = loc
Colin Cross08f15ab2018-10-04 23:29:14 -0700265 } else {
266 ctx.ModuleErrorf("multiple labels for %q, %q and %q",
Colin Crossd11cf622021-03-23 22:30:35 -0700267 label, locationLabels[label], loc)
Colin Cross08f15ab2018-10-04 23:29:14 -0700268 }
269 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700270
Colin Crossba9e4032020-11-24 16:32:22 -0800271 var tools android.Paths
272 var packagedTools []android.PackagingSpec
Colin Cross6f080df2016-11-04 15:32:58 -0700273 if len(g.properties.Tools) > 0 {
Colin Crossba71a3f2019-03-18 12:12:48 -0700274 seenTools := make(map[string]bool)
275
Colin Cross35143d02017-11-16 00:11:20 -0800276 ctx.VisitDirectDepsBlueprint(func(module blueprint.Module) {
Colin Cross08f15ab2018-10-04 23:29:14 -0700277 switch tag := ctx.OtherModuleDependencyTag(module).(type) {
278 case hostToolDependencyTag:
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700279 tool := ctx.OtherModuleName(module)
280
Colin Crossba9e4032020-11-24 16:32:22 -0800281 switch t := module.(type) {
282 case android.HostToolProvider:
283 // A HostToolProvider provides the path to a tool, which will be copied
284 // into the sandbox.
Colin Cross35143d02017-11-16 00:11:20 -0800285 if !t.(android.Module).Enabled() {
Colin Cross6510f912017-11-29 00:27:14 -0800286 if ctx.Config().AllowMissingDependencies() {
Colin Cross35143d02017-11-16 00:11:20 -0800287 ctx.AddMissingDependencies([]string{tool})
288 } else {
289 ctx.ModuleErrorf("depends on disabled module %q", tool)
290 }
Colin Crossba9e4032020-11-24 16:32:22 -0800291 return
Colin Cross35143d02017-11-16 00:11:20 -0800292 }
Colin Crossba9e4032020-11-24 16:32:22 -0800293 path := t.HostToolPath()
294 if !path.Valid() {
295 ctx.ModuleErrorf("host tool %q missing output file", tool)
296 return
297 }
298 if specs := t.TransitivePackagingSpecs(); specs != nil {
299 // If the HostToolProvider has PackgingSpecs, which are definitions of the
300 // required relative locations of the tool and its dependencies, use those
301 // instead. They will be copied to those relative locations in the sbox
302 // sandbox.
303 packagedTools = append(packagedTools, specs...)
304 // Assume that the first PackagingSpec of the module is the tool.
Colin Crossd11cf622021-03-23 22:30:35 -0700305 addLocationLabel(tag.label, packagedToolLocation{specs[0]})
Colin Crossba9e4032020-11-24 16:32:22 -0800306 } else {
307 tools = append(tools, path.Path())
Colin Crossd11cf622021-03-23 22:30:35 -0700308 addLocationLabel(tag.label, toolLocation{android.Paths{path.Path()}})
Colin Crossba9e4032020-11-24 16:32:22 -0800309 }
310 case bootstrap.GoBinaryTool:
311 // A GoBinaryTool provides the install path to a tool, which will be copied.
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700312 if s, err := filepath.Rel(android.PathForOutput(ctx).String(), t.InstallPath()); err == nil {
Colin Crossba9e4032020-11-24 16:32:22 -0800313 toolPath := android.PathForOutput(ctx, s)
314 tools = append(tools, toolPath)
Colin Crossd11cf622021-03-23 22:30:35 -0700315 addLocationLabel(tag.label, toolLocation{android.Paths{toolPath}})
Colin Cross6f080df2016-11-04 15:32:58 -0700316 } else {
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700317 ctx.ModuleErrorf("cannot find path for %q: %v", tool, err)
Colin Crossba9e4032020-11-24 16:32:22 -0800318 return
Colin Cross6f080df2016-11-04 15:32:58 -0700319 }
Colin Crossba9e4032020-11-24 16:32:22 -0800320 default:
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700321 ctx.ModuleErrorf("%q is not a host tool provider", tool)
Colin Crossba9e4032020-11-24 16:32:22 -0800322 return
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700323 }
324
Colin Crossba9e4032020-11-24 16:32:22 -0800325 seenTools[tag.label] = true
Colin Crossd350ecd2015-04-28 13:25:36 -0700326 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700327 })
Colin Crossba71a3f2019-03-18 12:12:48 -0700328
329 // If AllowMissingDependencies is enabled, the build will not have stopped when
330 // AddFarVariationDependencies was called on a missing tool, which will result in nonsensical
Liz Kammer20ebfb42020-07-28 11:32:07 -0700331 // "cmd: unknown location label ..." errors later. Add a placeholder file to the local label.
332 // The command that uses this placeholder file will never be executed because the rule will be
333 // replaced with an android.Error rule reporting the missing dependencies.
Colin Crossba71a3f2019-03-18 12:12:48 -0700334 if ctx.Config().AllowMissingDependencies() {
335 for _, tool := range g.properties.Tools {
336 if !seenTools[tool] {
Colin Crossd11cf622021-03-23 22:30:35 -0700337 addLocationLabel(tool, errorLocation{"***missing tool " + tool + "***"})
Colin Crossba71a3f2019-03-18 12:12:48 -0700338 }
339 }
340 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700341 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700342
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700343 if ctx.Failed() {
344 return
345 }
346
Colin Cross08f15ab2018-10-04 23:29:14 -0700347 for _, toolFile := range g.properties.Tool_files {
Colin Cross8a497952019-03-05 22:25:09 -0800348 paths := android.PathsForModuleSrc(ctx, []string{toolFile})
Colin Crossba9e4032020-11-24 16:32:22 -0800349 tools = append(tools, paths...)
Colin Crossd11cf622021-03-23 22:30:35 -0700350 addLocationLabel(toolFile, toolLocation{paths})
Colin Cross08f15ab2018-10-04 23:29:14 -0700351 }
352
353 var srcFiles android.Paths
354 for _, in := range g.properties.Srcs {
Colin Crossba71a3f2019-03-18 12:12:48 -0700355 paths, missingDeps := android.PathsAndMissingDepsForModuleSrcExcludes(ctx, []string{in}, g.properties.Exclude_srcs)
356 if len(missingDeps) > 0 {
357 if !ctx.Config().AllowMissingDependencies() {
358 panic(fmt.Errorf("should never get here, the missing dependencies %q should have been reported in DepsMutator",
359 missingDeps))
360 }
361
362 // If AllowMissingDependencies is enabled, the build will not have stopped when
363 // the dependency was added on a missing SourceFileProducer module, which will result in nonsensical
Liz Kammer20ebfb42020-07-28 11:32:07 -0700364 // "cmd: label ":..." has no files" errors later. Add a placeholder file to the local label.
365 // The command that uses this placeholder file will never be executed because the rule will be
366 // replaced with an android.Error rule reporting the missing dependencies.
Colin Crossba71a3f2019-03-18 12:12:48 -0700367 ctx.AddMissingDependencies(missingDeps)
Colin Crossd11cf622021-03-23 22:30:35 -0700368 addLocationLabel(in, errorLocation{"***missing srcs " + in + "***"})
Colin Crossba71a3f2019-03-18 12:12:48 -0700369 } else {
370 srcFiles = append(srcFiles, paths...)
Colin Crossd11cf622021-03-23 22:30:35 -0700371 addLocationLabel(in, inputLocation{paths})
Colin Crossba71a3f2019-03-18 12:12:48 -0700372 }
Colin Cross08f15ab2018-10-04 23:29:14 -0700373 }
374
Colin Cross1a527682019-09-23 15:55:30 -0700375 var copyFrom android.Paths
376 var outputFiles android.WritablePaths
377 var zipArgs strings.Builder
Colin Cross08f15ab2018-10-04 23:29:14 -0700378
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500379 // Generate tasks, either from genrule or gensrcs.
Colin Cross1a527682019-09-23 15:55:30 -0700380 for _, task := range g.taskGenerator(ctx, String(g.properties.Cmd), srcFiles) {
Colin Cross3d680512020-11-13 16:23:53 -0800381 if len(task.out) == 0 {
382 ctx.ModuleErrorf("must have at least one output file")
383 return
Colin Cross85a2e892018-07-09 09:45:06 -0700384 }
385
Colin Crossf1a035e2020-11-16 17:32:30 -0800386 // Pick a unique path outside the task.genDir for the sbox manifest textproto,
387 // a unique rule name, and the user-visible description.
388 manifestName := "genrule.sbox.textproto"
389 desc := "generate"
390 name := "generator"
391 if task.shards > 0 {
392 manifestName = "genrule_" + strconv.Itoa(task.shard) + ".sbox.textproto"
393 desc += " " + strconv.Itoa(task.shard)
394 name += strconv.Itoa(task.shard)
395 } else if len(task.out) == 1 {
396 desc += " " + task.out[0].Base()
397 }
398
399 manifestPath := android.PathForModuleOut(ctx, manifestName)
400
401 // Use a RuleBuilder to create a rule that runs the command inside an sbox sandbox.
Colin Crossba9e4032020-11-24 16:32:22 -0800402 rule := android.NewRuleBuilder(pctx, ctx).Sbox(task.genDir, manifestPath).SandboxTools()
Colin Crossf1a035e2020-11-16 17:32:30 -0800403 cmd := rule.Command()
404
Colin Cross3d680512020-11-13 16:23:53 -0800405 for _, out := range task.out {
Colin Crossd11cf622021-03-23 22:30:35 -0700406 addLocationLabel(out.Rel(), outputLocation{out})
Colin Cross3d680512020-11-13 16:23:53 -0800407 }
408
Colin Cross1a527682019-09-23 15:55:30 -0700409 referencedDepfile := false
410
Colin Cross3d680512020-11-13 16:23:53 -0800411 rawCommand, err := android.Expand(task.cmd, func(name string) (string, error) {
Colin Cross1a527682019-09-23 15:55:30 -0700412 // report the error directly without returning an error to android.Expand to catch multiple errors in a
413 // single run
Colin Cross3d680512020-11-13 16:23:53 -0800414 reportError := func(fmt string, args ...interface{}) (string, error) {
Colin Cross1a527682019-09-23 15:55:30 -0700415 ctx.PropertyErrorf("cmd", fmt, args...)
Colin Cross3d680512020-11-13 16:23:53 -0800416 return "SOONG_ERROR", nil
Colin Cross6f080df2016-11-04 15:32:58 -0700417 }
Colin Cross1a527682019-09-23 15:55:30 -0700418
419 switch name {
420 case "location":
421 if len(g.properties.Tools) == 0 && len(g.properties.Tool_files) == 0 {
422 return reportError("at least one `tools` or `tool_files` is required if $(location) is used")
Colin Cross6f080df2016-11-04 15:32:58 -0700423 }
Colin Crossd11cf622021-03-23 22:30:35 -0700424 loc := locationLabels[firstLabel]
425 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700426 if len(paths) == 0 {
427 return reportError("default label %q has no files", firstLabel)
428 } else if len(paths) > 1 {
429 return reportError("default label %q has multiple files, use $(locations %s) to reference it",
430 firstLabel, firstLabel)
Colin Cross08f15ab2018-10-04 23:29:14 -0700431 }
Colin Crossd11cf622021-03-23 22:30:35 -0700432 return paths[0], nil
Colin Cross1a527682019-09-23 15:55:30 -0700433 case "in":
Colin Crossd11cf622021-03-23 22:30:35 -0700434 return strings.Join(cmd.PathsForInputs(srcFiles), " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700435 case "out":
Colin Cross3d680512020-11-13 16:23:53 -0800436 var sandboxOuts []string
437 for _, out := range task.out {
Colin Crossf1a035e2020-11-16 17:32:30 -0800438 sandboxOuts = append(sandboxOuts, cmd.PathForOutput(out))
Colin Cross3d680512020-11-13 16:23:53 -0800439 }
440 return strings.Join(sandboxOuts, " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700441 case "depfile":
442 referencedDepfile = true
443 if !Bool(g.properties.Depfile) {
444 return reportError("$(depfile) used without depfile property")
445 }
Colin Cross3d680512020-11-13 16:23:53 -0800446 return "__SBOX_DEPFILE__", nil
Colin Cross1a527682019-09-23 15:55:30 -0700447 case "genDir":
Colin Crossf1a035e2020-11-16 17:32:30 -0800448 return cmd.PathForOutput(task.genDir), nil
Colin Cross1a527682019-09-23 15:55:30 -0700449 default:
450 if strings.HasPrefix(name, "location ") {
451 label := strings.TrimSpace(strings.TrimPrefix(name, "location "))
Colin Crossd11cf622021-03-23 22:30:35 -0700452 if loc, ok := locationLabels[label]; ok {
453 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700454 if len(paths) == 0 {
455 return reportError("label %q has no files", label)
456 } else if len(paths) > 1 {
457 return reportError("label %q has multiple files, use $(locations %s) to reference it",
458 label, label)
459 }
Colin Cross3d680512020-11-13 16:23:53 -0800460 return paths[0], nil
Colin Cross1a527682019-09-23 15:55:30 -0700461 } else {
462 return reportError("unknown location label %q", label)
463 }
464 } else if strings.HasPrefix(name, "locations ") {
465 label := strings.TrimSpace(strings.TrimPrefix(name, "locations "))
Colin Crossd11cf622021-03-23 22:30:35 -0700466 if loc, ok := locationLabels[label]; ok {
467 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700468 if len(paths) == 0 {
469 return reportError("label %q has no files", label)
470 }
Colin Cross3d680512020-11-13 16:23:53 -0800471 return strings.Join(paths, " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700472 } else {
473 return reportError("unknown locations label %q", label)
474 }
475 } else {
476 return reportError("unknown variable '$(%s)'", name)
477 }
Colin Cross6f080df2016-11-04 15:32:58 -0700478 }
Colin Cross1a527682019-09-23 15:55:30 -0700479 })
480
481 if err != nil {
482 ctx.PropertyErrorf("cmd", "%s", err.Error())
483 return
Colin Cross6f080df2016-11-04 15:32:58 -0700484 }
Colin Cross6f080df2016-11-04 15:32:58 -0700485
Colin Cross1a527682019-09-23 15:55:30 -0700486 if Bool(g.properties.Depfile) && !referencedDepfile {
487 ctx.PropertyErrorf("cmd", "specified depfile=true but did not include a reference to '${depfile}' in cmd")
488 return
489 }
Colin Cross1a527682019-09-23 15:55:30 -0700490 g.rawCommands = append(g.rawCommands, rawCommand)
Bill Peckhamc087be12020-02-13 15:55:10 -0800491
Colin Cross3d680512020-11-13 16:23:53 -0800492 cmd.Text(rawCommand)
493 cmd.ImplicitOutputs(task.out)
494 cmd.Implicits(task.in)
Colin Crossba9e4032020-11-24 16:32:22 -0800495 cmd.ImplicitTools(tools)
496 cmd.ImplicitTools(task.extraTools)
497 cmd.ImplicitPackagedTools(packagedTools)
Colin Cross3d680512020-11-13 16:23:53 -0800498 if Bool(g.properties.Depfile) {
499 cmd.ImplicitDepFile(task.depFile)
500 }
501
502 // Create the rule to run the genrule command inside sbox.
Colin Crossf1a035e2020-11-16 17:32:30 -0800503 rule.Build(name, desc)
Colin Cross1a527682019-09-23 15:55:30 -0700504
505 if len(task.copyTo) > 0 {
Colin Cross3d680512020-11-13 16:23:53 -0800506 // If copyTo is set, multiple shards need to be copied into a single directory.
507 // task.out contains the per-shard paths, and copyTo contains the corresponding
508 // final path. The files need to be copied into the final directory by a
509 // single rule so it can remove the directory before it starts to ensure no
510 // old files remain. zipsync already does this, so build up zipArgs that
511 // zip all the per-shard directories into a single zip.
Colin Cross1a527682019-09-23 15:55:30 -0700512 outputFiles = append(outputFiles, task.copyTo...)
513 copyFrom = append(copyFrom, task.out.Paths()...)
514 zipArgs.WriteString(" -C " + task.genDir.String())
515 zipArgs.WriteString(android.JoinWithPrefix(task.out.Strings(), " -f "))
516 } else {
517 outputFiles = append(outputFiles, task.out...)
518 }
Colin Cross6f080df2016-11-04 15:32:58 -0700519 }
520
Colin Cross1a527682019-09-23 15:55:30 -0700521 if len(copyFrom) > 0 {
Colin Cross3d680512020-11-13 16:23:53 -0800522 // Create a rule that zips all the per-shard directories into a single zip and then
523 // uses zipsync to unzip it into the final directory.
Colin Cross1a527682019-09-23 15:55:30 -0700524 ctx.Build(pctx, android.BuildParams{
Colin Crossf1885962020-11-20 15:28:30 -0800525 Rule: gensrcsMerge,
526 Implicits: copyFrom,
527 Outputs: outputFiles,
528 Description: "merge shards",
Colin Cross1a527682019-09-23 15:55:30 -0700529 Args: map[string]string{
530 "zipArgs": zipArgs.String(),
531 "tmpZip": android.PathForModuleGen(ctx, g.subDir+".zip").String(),
532 "genDir": android.PathForModuleGen(ctx, g.subDir).String(),
533 },
534 })
Colin Cross85a2e892018-07-09 09:45:06 -0700535 }
536
Colin Cross1a527682019-09-23 15:55:30 -0700537 g.outputFiles = outputFiles.Paths()
Jeff Gastonefc1b412017-03-29 17:29:06 -0700538
Liz Kammerbdc60992021-02-24 16:55:11 -0500539 bazelModuleLabel := g.GetBazelLabel(ctx, g)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400540 bazelActionsUsed := false
541 if ctx.Config().BazelContext.BazelEnabled() && len(bazelModuleLabel) > 0 {
542 bazelActionsUsed = g.generateBazelBuildActions(ctx, bazelModuleLabel)
Jeff Gaston02a684b2017-10-27 14:59:27 -0700543 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400544 if !bazelActionsUsed {
545 // For <= 6 outputs, just embed those directly in the users. Right now, that covers >90% of
546 // the genrules on AOSP. That will make things simpler to look at the graph in the common
547 // case. For larger sets of outputs, inject a phony target in between to limit ninja file
548 // growth.
549 if len(g.outputFiles) <= 6 {
550 g.outputDeps = g.outputFiles
551 } else {
552 phonyFile := android.PathForModuleGen(ctx, "genrule-phony")
553 ctx.Build(pctx, android.BuildParams{
554 Rule: blueprint.Phony,
555 Output: phonyFile,
556 Inputs: g.outputFiles,
557 })
558 g.outputDeps = android.Paths{phonyFile}
559 }
560 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700561}
Colin Crossd350ecd2015-04-28 13:25:36 -0700562
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700563// Collect information for opening IDE project files in java/jdeps.go.
564func (g *Module) IDEInfo(dpInfo *android.IdeInfo) {
565 dpInfo.Srcs = append(dpInfo.Srcs, g.Srcs().Strings()...)
566 for _, src := range g.properties.Srcs {
567 if strings.HasPrefix(src, ":") {
568 src = strings.Trim(src, ":")
569 dpInfo.Deps = append(dpInfo.Deps, src)
570 }
571 }
bralee1fbf4402020-05-21 10:11:59 +0800572 dpInfo.Paths = append(dpInfo.Paths, g.modulePaths...)
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700573}
574
Colin Crossa4ad2b02019-03-18 22:15:32 -0700575func (g *Module) AndroidMk() android.AndroidMkData {
576 return android.AndroidMkData{
Anton Hansson72f18492020-10-30 16:34:45 +0000577 Class: "ETC",
Colin Crossa4ad2b02019-03-18 22:15:32 -0700578 OutputFile: android.OptionalPathForPath(g.outputFiles[0]),
579 SubName: g.subName,
580 Extra: []android.AndroidMkExtraFunc{
581 func(w io.Writer, outputFile android.Path) {
Anton Hansson72f18492020-10-30 16:34:45 +0000582 fmt.Fprintln(w, "LOCAL_UNINSTALLABLE_MODULE := true")
Colin Crossa4ad2b02019-03-18 22:15:32 -0700583 },
584 },
585 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
586 android.WriteAndroidMkData(w, data)
587 if data.SubName != "" {
588 fmt.Fprintln(w, ".PHONY:", name)
589 fmt.Fprintln(w, name, ":", name+g.subName)
590 }
591 },
592 }
593}
594
Jiyong Park45bf82e2020-12-15 22:29:02 +0900595var _ android.ApexModule = (*Module)(nil)
596
597// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -0700598func (g *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
599 sdkVersion android.ApiLevel) error {
Jooyung Han749dc692020-04-15 11:03:39 +0900600 // Because generated outputs are checked by client modules(e.g. cc_library, ...)
601 // we can safely ignore the check here.
602 return nil
603}
604
Jeff Gaston437d23c2017-11-08 12:38:00 -0800605func generatorFactory(taskGenerator taskFunc, props ...interface{}) *Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700606 module := &Module{
Jeff Gaston437d23c2017-11-08 12:38:00 -0800607 taskGenerator: taskGenerator,
Colin Crossd350ecd2015-04-28 13:25:36 -0700608 }
609
Colin Cross36242852017-06-23 15:06:31 -0700610 module.AddProperties(props...)
611 module.AddProperties(&module.properties)
Colin Crossd350ecd2015-04-28 13:25:36 -0700612
Colin Cross7228ecd2019-11-18 16:00:16 -0800613 module.ImageInterface = noopImageInterface{}
614
Colin Cross36242852017-06-23 15:06:31 -0700615 return module
Colin Crossd350ecd2015-04-28 13:25:36 -0700616}
617
Colin Cross7228ecd2019-11-18 16:00:16 -0800618type noopImageInterface struct{}
619
620func (x noopImageInterface) ImageMutatorBegin(android.BaseModuleContext) {}
621func (x noopImageInterface) CoreVariantNeeded(android.BaseModuleContext) bool { return false }
Yifan Hong1b3348d2020-01-21 15:53:22 -0800622func (x noopImageInterface) RamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700623func (x noopImageInterface) VendorRamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Colin Cross7228ecd2019-11-18 16:00:16 -0800624func (x noopImageInterface) RecoveryVariantNeeded(android.BaseModuleContext) bool { return false }
625func (x noopImageInterface) ExtraImageVariations(ctx android.BaseModuleContext) []string { return nil }
626func (x noopImageInterface) SetImageVariation(ctx android.BaseModuleContext, variation string, module android.Module) {
627}
628
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700629func NewGenSrcs() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700630 properties := &genSrcsProperties{}
631
Colin Crossf1885962020-11-20 15:28:30 -0800632 // finalSubDir is the name of the subdirectory that output files will be generated into.
633 // It is used so that per-shard directories can be placed alongside it an then finally
634 // merged into it.
635 const finalSubDir = "gensrcs"
636
Colin Cross1a527682019-09-23 15:55:30 -0700637 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Colin Cross1a527682019-09-23 15:55:30 -0700638 shardSize := defaultShardSize
639 if s := properties.Shard_size; s != nil {
640 shardSize = int(*s)
641 }
Jeff Gaston437d23c2017-11-08 12:38:00 -0800642
Colin Crossf1885962020-11-20 15:28:30 -0800643 // gensrcs rules can easily hit command line limits by repeating the command for
644 // every input file. Shard the input files into groups.
Colin Cross1a527682019-09-23 15:55:30 -0700645 shards := android.ShardPaths(srcFiles, shardSize)
646 var generateTasks []generateTask
Colin Crossbaccf5b2018-02-21 14:07:48 -0800647
Colin Cross1a527682019-09-23 15:55:30 -0700648 for i, shard := range shards {
649 var commands []string
650 var outFiles android.WritablePaths
Colin Cross3ea4eb82020-11-24 13:07:27 -0800651 var commandDepFiles []string
Colin Cross1a527682019-09-23 15:55:30 -0700652 var copyTo android.WritablePaths
Colin Cross1a527682019-09-23 15:55:30 -0700653
Colin Crossf1885962020-11-20 15:28:30 -0800654 // When sharding is enabled (i.e. len(shards) > 1), the sbox rules for each
655 // shard will be write to their own directories and then be merged together
656 // into finalSubDir. If sharding is not enabled (i.e. len(shards) == 1),
657 // the sbox rule will write directly to finalSubDir.
658 genSubDir := finalSubDir
Colin Cross1a527682019-09-23 15:55:30 -0700659 if len(shards) > 1 {
Colin Crossf1885962020-11-20 15:28:30 -0800660 genSubDir = strconv.Itoa(i)
Jeff Gaston437d23c2017-11-08 12:38:00 -0800661 }
662
Colin Crossf1885962020-11-20 15:28:30 -0800663 genDir := android.PathForModuleGen(ctx, genSubDir)
Colin Crossf1a035e2020-11-16 17:32:30 -0800664 // TODO(ccross): this RuleBuilder is a hack to be able to call
665 // rule.Command().PathForOutput. Replace this with passing the rule into the
666 // generator.
Colin Crossba9e4032020-11-24 16:32:22 -0800667 rule := android.NewRuleBuilder(pctx, ctx).Sbox(genDir, nil).SandboxTools()
Jeff Gaston437d23c2017-11-08 12:38:00 -0800668
Colin Cross3ea4eb82020-11-24 13:07:27 -0800669 for _, in := range shard {
Colin Crossf1885962020-11-20 15:28:30 -0800670 outFile := android.GenPathWithExt(ctx, finalSubDir, in, String(properties.Output_extension))
671
672 // If sharding is enabled, then outFile is the path to the output file in
673 // the shard directory, and copyTo is the path to the output file in the
674 // final directory.
Colin Cross1a527682019-09-23 15:55:30 -0700675 if len(shards) > 1 {
Colin Crossf1885962020-11-20 15:28:30 -0800676 shardFile := android.GenPathWithExt(ctx, genSubDir, in, String(properties.Output_extension))
Colin Cross1a527682019-09-23 15:55:30 -0700677 copyTo = append(copyTo, outFile)
678 outFile = shardFile
679 }
680
681 outFiles = append(outFiles, outFile)
Colin Cross1a527682019-09-23 15:55:30 -0700682
Colin Crossf1885962020-11-20 15:28:30 -0800683 // pre-expand the command line to replace $in and $out with references to
684 // a single input and output file.
Colin Cross1a527682019-09-23 15:55:30 -0700685 command, err := android.Expand(rawCommand, func(name string) (string, error) {
686 switch name {
687 case "in":
688 return in.String(), nil
689 case "out":
Colin Crossf1a035e2020-11-16 17:32:30 -0800690 return rule.Command().PathForOutput(outFile), nil
Colin Cross3ea4eb82020-11-24 13:07:27 -0800691 case "depfile":
692 // Generate a depfile for each output file. Store the list for
693 // later in order to combine them all into a single depfile.
Colin Crossf1a035e2020-11-16 17:32:30 -0800694 depFile := rule.Command().PathForOutput(outFile.ReplaceExtension(ctx, "d"))
Colin Cross3ea4eb82020-11-24 13:07:27 -0800695 commandDepFiles = append(commandDepFiles, depFile)
696 return depFile, nil
Colin Cross1a527682019-09-23 15:55:30 -0700697 default:
698 return "$(" + name + ")", nil
699 }
700 })
701 if err != nil {
702 ctx.PropertyErrorf("cmd", err.Error())
703 }
704
705 // escape the command in case for example it contains '#', an odd number of '"', etc
706 command = fmt.Sprintf("bash -c %v", proptools.ShellEscape(command))
707 commands = append(commands, command)
708 }
709 fullCommand := strings.Join(commands, " && ")
710
Colin Cross3ea4eb82020-11-24 13:07:27 -0800711 var outputDepfile android.WritablePath
712 var extraTools android.Paths
713 if len(commandDepFiles) > 0 {
714 // Each command wrote to a depfile, but ninja can only handle one
715 // depfile per rule. Use the dep_fixer tool at the end of the
716 // command to combine all the depfiles into a single output depfile.
717 outputDepfile = android.PathForModuleGen(ctx, genSubDir, "gensrcs.d")
718 depFixerTool := ctx.Config().HostToolPath(ctx, "dep_fixer")
719 fullCommand += fmt.Sprintf(" && %s -o $(depfile) %s",
Colin Crossd11cf622021-03-23 22:30:35 -0700720 rule.Command().PathForTool(depFixerTool),
Colin Crossba9e4032020-11-24 16:32:22 -0800721 strings.Join(commandDepFiles, " "))
Colin Cross3ea4eb82020-11-24 13:07:27 -0800722 extraTools = append(extraTools, depFixerTool)
723 }
724
Colin Cross1a527682019-09-23 15:55:30 -0700725 generateTasks = append(generateTasks, generateTask{
Colin Cross3ea4eb82020-11-24 13:07:27 -0800726 in: shard,
727 out: outFiles,
728 depFile: outputDepfile,
729 copyTo: copyTo,
730 genDir: genDir,
731 cmd: fullCommand,
732 shard: i,
733 shards: len(shards),
734 extraTools: extraTools,
Colin Cross1a527682019-09-23 15:55:30 -0700735 })
Jeff Gaston437d23c2017-11-08 12:38:00 -0800736 }
Colin Cross1a527682019-09-23 15:55:30 -0700737
738 return generateTasks
Colin Crossd350ecd2015-04-28 13:25:36 -0700739 }
740
Colin Cross1a527682019-09-23 15:55:30 -0700741 g := generatorFactory(taskGenerator, properties)
Colin Crossf1885962020-11-20 15:28:30 -0800742 g.subDir = finalSubDir
Colin Cross1a527682019-09-23 15:55:30 -0700743 return g
Colin Crossd350ecd2015-04-28 13:25:36 -0700744}
745
Colin Cross54190b32017-10-09 15:34:10 -0700746func GenSrcsFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700747 m := NewGenSrcs()
748 android.InitAndroidModule(m)
749 return m
750}
751
Colin Crossd350ecd2015-04-28 13:25:36 -0700752type genSrcsProperties struct {
Colin Cross7d5136f2015-05-11 13:39:40 -0700753 // extension that will be substituted for each output file
Nan Zhanga5e7cb42017-11-09 22:42:32 -0800754 Output_extension *string
Colin Cross1a527682019-09-23 15:55:30 -0700755
756 // maximum number of files that will be passed on a single command line.
757 Shard_size *int64
Colin Cross5049f022015-03-18 13:28:46 -0700758}
759
Evgenii Stepanovf47c90d2020-12-02 18:55:09 -0800760const defaultShardSize = 50
Colin Cross1a527682019-09-23 15:55:30 -0700761
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700762func NewGenRule() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700763 properties := &genRuleProperties{}
Colin Cross5049f022015-03-18 13:28:46 -0700764
Colin Cross1a527682019-09-23 15:55:30 -0700765 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700766 outs := make(android.WritablePaths, len(properties.Out))
Colin Cross3d680512020-11-13 16:23:53 -0800767 var depFile android.WritablePath
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700768 for i, out := range properties.Out {
Colin Cross3d680512020-11-13 16:23:53 -0800769 outPath := android.PathForModuleGen(ctx, out)
770 if i == 0 {
771 depFile = outPath.ReplaceExtension(ctx, "d")
772 }
773 outs[i] = outPath
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700774 }
Colin Cross1a527682019-09-23 15:55:30 -0700775 return []generateTask{{
Colin Cross3d680512020-11-13 16:23:53 -0800776 in: srcFiles,
777 out: outs,
778 depFile: depFile,
779 genDir: android.PathForModuleGen(ctx),
780 cmd: rawCommand,
Colin Cross1a527682019-09-23 15:55:30 -0700781 }}
Colin Cross5049f022015-03-18 13:28:46 -0700782 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700783
Jeff Gaston437d23c2017-11-08 12:38:00 -0800784 return generatorFactory(taskGenerator, properties)
Colin Cross5049f022015-03-18 13:28:46 -0700785}
786
Colin Cross54190b32017-10-09 15:34:10 -0700787func GenRuleFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700788 m := NewGenRule()
789 android.InitAndroidModule(m)
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800790 android.InitDefaultableModule(m)
Liz Kammerea6666f2021-02-17 10:17:28 -0500791 android.InitBazelModule(m)
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700792 return m
793}
794
Colin Crossd350ecd2015-04-28 13:25:36 -0700795type genRuleProperties struct {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700796 // names of the output files that will be generated
Colin Crossef354482018-10-23 11:27:50 -0700797 Out []string `android:"arch_variant"`
Colin Cross5049f022015-03-18 13:28:46 -0700798}
Nan Zhangea568a42017-11-08 21:20:04 -0800799
Jingwen Chen316e07c2020-12-14 09:09:52 -0500800type bazelGenruleAttributes struct {
Jingwen Chen07027912021-03-15 06:02:43 -0400801 Srcs bazel.LabelListAttribute
Jingwen Chen316e07c2020-12-14 09:09:52 -0500802 Outs []string
Jingwen Chen07027912021-03-15 06:02:43 -0400803 Tools bazel.LabelListAttribute
Jingwen Chen316e07c2020-12-14 09:09:52 -0500804 Cmd string
805}
806
807type bazelGenrule struct {
808 android.BazelTargetModuleBase
809 bazelGenruleAttributes
810}
811
812func BazelGenruleFactory() android.Module {
813 module := &bazelGenrule{}
814 module.AddProperties(&module.bazelGenruleAttributes)
815 android.InitBazelTargetModule(module)
816 return module
817}
818
Jingwen Chena42d6412021-01-26 21:57:27 -0500819func GenruleBp2Build(ctx android.TopDownMutatorContext) {
Liz Kammer356f7d42021-01-26 09:18:53 -0500820 m, ok := ctx.Module().(*Module)
Jingwen Chen12b4c272021-03-10 02:05:59 -0500821 if !ok || !m.ConvertWithBp2build(ctx) {
Liz Kammer356f7d42021-01-26 09:18:53 -0500822 return
Jingwen Chen316e07c2020-12-14 09:09:52 -0500823 }
Jingwen Chen1fd14692021-02-05 03:01:50 -0500824
Jingwen Chen66480452021-03-18 03:41:55 -0400825 if ctx.ModuleType() != "genrule" {
826 // Not a regular genrule. Could be a cc_genrule or java_genrule.
827 return
828 }
829
Liz Kammer356f7d42021-01-26 09:18:53 -0500830 // Bazel only has the "tools" attribute.
Jingwen Chen07027912021-03-15 06:02:43 -0400831 tools_prop := android.BazelLabelForModuleDeps(ctx, m.properties.Tools)
832 tool_files_prop := android.BazelLabelForModuleSrc(ctx, m.properties.Tool_files)
833 tools_prop.Append(tool_files_prop)
Liz Kammer356f7d42021-01-26 09:18:53 -0500834
Jingwen Chen07027912021-03-15 06:02:43 -0400835 tools := bazel.MakeLabelListAttribute(tools_prop)
836 srcs := bazel.MakeLabelListAttribute(android.BazelLabelForModuleSrc(ctx, m.properties.Srcs))
Liz Kammer356f7d42021-01-26 09:18:53 -0500837
838 var allReplacements bazel.LabelList
Jingwen Chen07027912021-03-15 06:02:43 -0400839 allReplacements.Append(tools.Value)
840 allReplacements.Append(srcs.Value)
Liz Kammer356f7d42021-01-26 09:18:53 -0500841
842 // Replace in and out variables with $< and $@
843 var cmd string
844 if m.properties.Cmd != nil {
845 cmd = strings.Replace(*m.properties.Cmd, "$(in)", "$(SRCS)", -1)
846 cmd = strings.Replace(cmd, "$(out)", "$(OUTS)", -1)
847 cmd = strings.Replace(cmd, "$(genDir)", "$(GENDIR)", -1)
Jingwen Chen07027912021-03-15 06:02:43 -0400848 if len(tools.Value.Includes) > 0 {
849 cmd = strings.Replace(cmd, "$(location)", fmt.Sprintf("$(location %s)", tools.Value.Includes[0].Label), -1)
850 cmd = strings.Replace(cmd, "$(locations)", fmt.Sprintf("$(locations %s)", tools.Value.Includes[0].Label), -1)
Liz Kammer356f7d42021-01-26 09:18:53 -0500851 }
852 for _, l := range allReplacements.Includes {
853 bpLoc := fmt.Sprintf("$(location %s)", l.Bp_text)
854 bpLocs := fmt.Sprintf("$(locations %s)", l.Bp_text)
855 bazelLoc := fmt.Sprintf("$(location %s)", l.Label)
856 bazelLocs := fmt.Sprintf("$(locations %s)", l.Label)
857 cmd = strings.Replace(cmd, bpLoc, bazelLoc, -1)
858 cmd = strings.Replace(cmd, bpLocs, bazelLocs, -1)
859 }
860 }
861
862 // The Out prop is not in an immediately accessible field
863 // in the Module struct, so use GetProperties and cast it
864 // to the known struct prop.
865 var outs []string
866 for _, propIntf := range m.GetProperties() {
867 if props, ok := propIntf.(*genRuleProperties); ok {
868 outs = props.Out
869 break
870 }
871 }
872
Jingwen Chen1fd14692021-02-05 03:01:50 -0500873 attrs := &bazelGenruleAttributes{
Liz Kammer356f7d42021-01-26 09:18:53 -0500874 Srcs: srcs,
875 Outs: outs,
876 Cmd: cmd,
877 Tools: tools,
Jingwen Chen1fd14692021-02-05 03:01:50 -0500878 }
879
Liz Kammerfc46bc12021-02-19 11:06:17 -0500880 props := bazel.BazelTargetModuleProperties{
881 Rule_class: "genrule",
882 }
Jingwen Chen1fd14692021-02-05 03:01:50 -0500883
884 // Create the BazelTargetModule.
Liz Kammerfc46bc12021-02-19 11:06:17 -0500885 ctx.CreateBazelTargetModule(BazelGenruleFactory, m.Name(), props, attrs)
Jingwen Chen316e07c2020-12-14 09:09:52 -0500886}
887
888func (m *bazelGenrule) Name() string {
889 return m.BaseModuleName()
890}
891
892func (m *bazelGenrule) GenerateAndroidBuildActions(ctx android.ModuleContext) {}
893
Nan Zhangea568a42017-11-08 21:20:04 -0800894var Bool = proptools.Bool
895var String = proptools.String
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800896
897//
898// Defaults
899//
900type Defaults struct {
901 android.ModuleBase
902 android.DefaultsModuleBase
903}
904
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800905func defaultsFactory() android.Module {
906 return DefaultsFactory()
907}
908
909func DefaultsFactory(props ...interface{}) android.Module {
910 module := &Defaults{}
911
912 module.AddProperties(props...)
913 module.AddProperties(
914 &generatorProperties{},
915 &genRuleProperties{},
916 )
917
918 android.InitDefaultsModule(module)
919
920 return module
921}