blob: 50c77cf9a85fd06eeeca180a20d8fc8e7209b865 [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
Colin Crosse9fe2942020-11-10 18:12:15 -080040func RegisterGenruleBuildComponents(ctx android.RegistrationContext) {
Martin Stjernholm710ec3a2020-01-16 15:12:04 +000041 ctx.RegisterModuleType("genrule_defaults", defaultsFactory)
42
43 ctx.RegisterModuleType("gensrcs", GenSrcsFactory)
44 ctx.RegisterModuleType("genrule", GenRuleFactory)
45
46 ctx.FinalDepsMutators(func(ctx android.RegisterMutatorsContext) {
47 ctx.BottomUp("genrule_tool_deps", toolDepsMutator).Parallel()
48 })
Jingwen Chen316e07c2020-12-14 09:09:52 -050049
Liz Kammer356f7d42021-01-26 09:18:53 -050050 android.DepsBp2BuildMutators(RegisterGenruleBp2BuildDeps)
Jingwen Chena42d6412021-01-26 21:57:27 -050051 android.RegisterBp2BuildMutator("genrule", GenruleBp2Build)
Colin Cross463a90e2015-06-17 14:20:06 -070052}
53
Liz Kammer356f7d42021-01-26 09:18:53 -050054func RegisterGenruleBp2BuildDeps(ctx android.RegisterMutatorsContext) {
55 ctx.BottomUp("genrule_tool_deps", toolDepsMutator)
56}
57
Colin Cross5049f022015-03-18 13:28:46 -070058var (
Colin Cross635c3b02016-05-18 15:37:25 -070059 pctx = android.NewPackageContext("android/soong/genrule")
Colin Cross1a527682019-09-23 15:55:30 -070060
Alex Humesky29e3bbe2020-11-20 21:30:13 -050061 // Used by gensrcs when there is more than 1 shard to merge the outputs
62 // of each shard into a zip file.
Colin Cross1a527682019-09-23 15:55:30 -070063 gensrcsMerge = pctx.AndroidStaticRule("gensrcsMerge", blueprint.RuleParams{
64 Command: "${soongZip} -o ${tmpZip} @${tmpZip}.rsp && ${zipSync} -d ${genDir} ${tmpZip}",
65 CommandDeps: []string{"${soongZip}", "${zipSync}"},
66 Rspfile: "${tmpZip}.rsp",
67 RspfileContent: "${zipArgs}",
68 }, "tmpZip", "genDir", "zipArgs")
Colin Cross5049f022015-03-18 13:28:46 -070069)
70
Jeff Gastonefc1b412017-03-29 17:29:06 -070071func init() {
Dan Willemsenddf504c2019-08-09 16:21:29 -070072 pctx.Import("android/soong/android")
Jeff Gastonefc1b412017-03-29 17:29:06 -070073 pctx.HostBinToolVariable("sboxCmd", "sbox")
Colin Cross1a527682019-09-23 15:55:30 -070074
75 pctx.HostBinToolVariable("soongZip", "soong_zip")
76 pctx.HostBinToolVariable("zipSync", "zipsync")
Jeff Gastonefc1b412017-03-29 17:29:06 -070077}
78
Colin Cross5049f022015-03-18 13:28:46 -070079type SourceFileGenerator interface {
Colin Cross635c3b02016-05-18 15:37:25 -070080 GeneratedSourceFiles() android.Paths
Colin Cross5ed99c62016-11-22 12:55:55 -080081 GeneratedHeaderDirs() android.Paths
Dan Willemsen9da9d492018-02-21 18:28:18 -080082 GeneratedDeps() android.Paths
Colin Cross5049f022015-03-18 13:28:46 -070083}
84
Colin Crossfe17f6f2019-03-28 19:30:56 -070085// Alias for android.HostToolProvider
86// Deprecated: use android.HostToolProvider instead.
Colin Crossd350ecd2015-04-28 13:25:36 -070087type HostToolProvider interface {
Colin Crossfe17f6f2019-03-28 19:30:56 -070088 android.HostToolProvider
Colin Crossd350ecd2015-04-28 13:25:36 -070089}
Colin Cross5049f022015-03-18 13:28:46 -070090
Dan Willemsend6ba0d52017-09-13 15:46:47 -070091type hostToolDependencyTag struct {
92 blueprint.BaseDependencyTag
Colin Cross08f15ab2018-10-04 23:29:14 -070093 label string
Dan Willemsend6ba0d52017-09-13 15:46:47 -070094}
Colin Cross7d5136f2015-05-11 13:39:40 -070095type generatorProperties struct {
Jeff Gastonefc1b412017-03-29 17:29:06 -070096 // The command to run on one or more input files. Cmd supports substitution of a few variables
Jeff Gastonefc1b412017-03-29 17:29:06 -070097 //
98 // Available variables for substitution:
99 //
Colin Cross2296f5b2017-10-17 21:38:14 -0700100 // $(location): the path to the first entry in tools or tool_files
Colin Cross08f15ab2018-10-04 23:29:14 -0700101 // $(location <label>): the path to the tool, tool_file, input or output with name <label>
Colin Cross2296f5b2017-10-17 21:38:14 -0700102 // $(in): one or more input files
103 // $(out): a single output file
104 // $(depfile): a file to which dependencies will be written, if the depfile property is set to true
105 // $(genDir): the sandbox directory for this tool; contains $(out)
106 // $$: a literal $
Nan Zhangea568a42017-11-08 21:20:04 -0800107 Cmd *string
Colin Cross7d5136f2015-05-11 13:39:40 -0700108
Colin Cross33bfb0a2016-11-21 17:23:08 -0800109 // Enable reading a file containing dependencies in gcc format after the command completes
Nan Zhangea568a42017-11-08 21:20:04 -0800110 Depfile *bool
Colin Cross33bfb0a2016-11-21 17:23:08 -0800111
Colin Cross6f080df2016-11-04 15:32:58 -0700112 // name of the modules (if any) that produces the host executable. Leave empty for
Colin Cross7d5136f2015-05-11 13:39:40 -0700113 // prebuilts or scripts that do not need a module to build them.
Colin Cross6f080df2016-11-04 15:32:58 -0700114 Tools []string
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700115
116 // Local file that is used as the tool
Colin Cross27b922f2019-03-04 22:35:41 -0800117 Tool_files []string `android:"path"`
Colin Cross5ed99c62016-11-22 12:55:55 -0800118
119 // List of directories to export generated headers from
120 Export_include_dirs []string
Colin Cross708c4242017-01-13 18:05:49 -0800121
122 // list of input files
Colin Cross27b922f2019-03-04 22:35:41 -0800123 Srcs []string `android:"path,arch_variant"`
Dan Willemseneefa0262018-11-17 14:01:18 -0800124
125 // input files to exclude
Colin Cross27b922f2019-03-04 22:35:41 -0800126 Exclude_srcs []string `android:"path,arch_variant"`
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400127}
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500128
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700129type Module struct {
Colin Cross635c3b02016-05-18 15:37:25 -0700130 android.ModuleBase
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800131 android.DefaultableModuleBase
Liz Kammerea6666f2021-02-17 10:17:28 -0500132 android.BazelModuleBase
Jiyong Parkfc752ca2019-06-12 13:27:29 +0900133 android.ApexModuleBase
Colin Crossd350ecd2015-04-28 13:25:36 -0700134
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700135 // For other packages to make their own genrules with extra
136 // properties
137 Extra interface{}
Colin Cross7228ecd2019-11-18 16:00:16 -0800138 android.ImageInterface
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700139
Colin Cross7d5136f2015-05-11 13:39:40 -0700140 properties generatorProperties
Colin Crossd350ecd2015-04-28 13:25:36 -0700141
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500142 // For the different tasks that genrule and gensrc generate. genrule will
143 // generate 1 task, and gensrc will generate 1 or more tasks based on the
144 // number of shards the input files are sharded into.
Jeff Gaston437d23c2017-11-08 12:38:00 -0800145 taskGenerator taskFunc
Colin Crossd350ecd2015-04-28 13:25:36 -0700146
Colin Cross1a527682019-09-23 15:55:30 -0700147 rule blueprint.Rule
148 rawCommands []string
Colin Crossd350ecd2015-04-28 13:25:36 -0700149
Colin Cross5ed99c62016-11-22 12:55:55 -0800150 exportedIncludeDirs android.Paths
Dan Willemsenb40aab62016-04-20 14:21:14 -0700151
Colin Cross635c3b02016-05-18 15:37:25 -0700152 outputFiles android.Paths
Dan Willemsen9da9d492018-02-21 18:28:18 -0800153 outputDeps android.Paths
Colin Crossa4ad2b02019-03-18 22:15:32 -0700154
155 subName string
Colin Cross1a527682019-09-23 15:55:30 -0700156 subDir string
bralee1fbf4402020-05-21 10:11:59 +0800157
158 // Collect the module directory for IDE info in java/jdeps.go.
159 modulePaths []string
Colin Crossd350ecd2015-04-28 13:25:36 -0700160}
161
Colin Cross1a527682019-09-23 15:55:30 -0700162type taskFunc func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask
Colin Crossd350ecd2015-04-28 13:25:36 -0700163
164type generateTask struct {
Colin Cross3ea4eb82020-11-24 13:07:27 -0800165 in android.Paths
166 out android.WritablePaths
167 depFile android.WritablePath
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500168 copyTo android.WritablePaths // For gensrcs to set on gensrcsMerge rule.
Colin Cross3ea4eb82020-11-24 13:07:27 -0800169 genDir android.WritablePath
170 extraTools android.Paths // dependencies on tools used by the generator
171
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500172 cmd string
173 // For gensrsc sharding.
Colin Cross3ea4eb82020-11-24 13:07:27 -0800174 shard int
175 shards int
Colin Crossd350ecd2015-04-28 13:25:36 -0700176}
177
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700178func (g *Module) GeneratedSourceFiles() android.Paths {
Colin Crossd350ecd2015-04-28 13:25:36 -0700179 return g.outputFiles
180}
181
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700182func (g *Module) Srcs() android.Paths {
Nan Zhange42777a2018-03-27 16:19:42 -0700183 return append(android.Paths{}, g.outputFiles...)
Colin Cross068e0fe2016-12-13 15:23:47 -0800184}
185
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700186func (g *Module) GeneratedHeaderDirs() android.Paths {
Colin Cross5ed99c62016-11-22 12:55:55 -0800187 return g.exportedIncludeDirs
Dan Willemsenb40aab62016-04-20 14:21:14 -0700188}
189
Dan Willemsen9da9d492018-02-21 18:28:18 -0800190func (g *Module) GeneratedDeps() android.Paths {
191 return g.outputDeps
192}
193
Martin Stjernholm710ec3a2020-01-16 15:12:04 +0000194func toolDepsMutator(ctx android.BottomUpMutatorContext) {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700195 if g, ok := ctx.Module().(*Module); ok {
Colin Cross08f15ab2018-10-04 23:29:14 -0700196 for _, tool := range g.properties.Tools {
197 tag := hostToolDependencyTag{label: tool}
198 if m := android.SrcIsModule(tool); m != "" {
199 tool = m
200 }
Colin Cross0f7d2ef2019-10-16 11:03:10 -0700201 ctx.AddFarVariationDependencies(ctx.Config().BuildOSTarget.Variations(), tag, tool)
Colin Cross6362e272015-10-29 15:25:03 -0700202 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700203 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700204}
205
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400206// Returns true if information was available from Bazel, false if bazel invocation still needs to occur.
207func (c *Module) generateBazelBuildActions(ctx android.ModuleContext, label string) bool {
208 bazelCtx := ctx.Config().BazelContext
Chris Parsons8d6e4332021-02-22 16:13:50 -0500209 filePaths, ok := bazelCtx.GetAllFiles(label, ctx.Arch().ArchType)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400210 if ok {
211 var bazelOutputFiles android.Paths
212 for _, bazelOutputFile := range filePaths {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500213 bazelOutputFiles = append(bazelOutputFiles, android.PathForBazelOut(ctx, bazelOutputFile))
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400214 }
215 c.outputFiles = bazelOutputFiles
216 c.outputDeps = bazelOutputFiles
217 }
218 return ok
219}
Colin Crossf1885962020-11-20 15:28:30 -0800220
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700221func (g *Module) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Colin Crossa4ad2b02019-03-18 22:15:32 -0700222 g.subName = ctx.ModuleSubDir()
223
bralee1fbf4402020-05-21 10:11:59 +0800224 // Collect the module directory for IDE info in java/jdeps.go.
225 g.modulePaths = append(g.modulePaths, ctx.ModuleDir())
226
Colin Cross5ed99c62016-11-22 12:55:55 -0800227 if len(g.properties.Export_include_dirs) > 0 {
228 for _, dir := range g.properties.Export_include_dirs {
229 g.exportedIncludeDirs = append(g.exportedIncludeDirs,
Colin Cross1a527682019-09-23 15:55:30 -0700230 android.PathForModuleGen(ctx, g.subDir, ctx.ModuleDir(), dir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800231 }
232 } else {
Colin Cross1a527682019-09-23 15:55:30 -0700233 g.exportedIncludeDirs = append(g.exportedIncludeDirs, android.PathForModuleGen(ctx, g.subDir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800234 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700235
Colin Cross08f15ab2018-10-04 23:29:14 -0700236 locationLabels := map[string][]string{}
237 firstLabel := ""
238
239 addLocationLabel := func(label string, paths []string) {
240 if firstLabel == "" {
241 firstLabel = label
242 }
243 if _, exists := locationLabels[label]; !exists {
244 locationLabels[label] = paths
245 } else {
246 ctx.ModuleErrorf("multiple labels for %q, %q and %q",
247 label, strings.Join(locationLabels[label], " "), strings.Join(paths, " "))
248 }
249 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700250
Colin Crossba9e4032020-11-24 16:32:22 -0800251 var tools android.Paths
252 var packagedTools []android.PackagingSpec
Colin Cross6f080df2016-11-04 15:32:58 -0700253 if len(g.properties.Tools) > 0 {
Colin Crossba71a3f2019-03-18 12:12:48 -0700254 seenTools := make(map[string]bool)
255
Colin Cross35143d02017-11-16 00:11:20 -0800256 ctx.VisitDirectDepsBlueprint(func(module blueprint.Module) {
Colin Cross08f15ab2018-10-04 23:29:14 -0700257 switch tag := ctx.OtherModuleDependencyTag(module).(type) {
258 case hostToolDependencyTag:
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700259 tool := ctx.OtherModuleName(module)
260
Colin Crossba9e4032020-11-24 16:32:22 -0800261 switch t := module.(type) {
262 case android.HostToolProvider:
263 // A HostToolProvider provides the path to a tool, which will be copied
264 // into the sandbox.
Colin Cross35143d02017-11-16 00:11:20 -0800265 if !t.(android.Module).Enabled() {
Colin Cross6510f912017-11-29 00:27:14 -0800266 if ctx.Config().AllowMissingDependencies() {
Colin Cross35143d02017-11-16 00:11:20 -0800267 ctx.AddMissingDependencies([]string{tool})
268 } else {
269 ctx.ModuleErrorf("depends on disabled module %q", tool)
270 }
Colin Crossba9e4032020-11-24 16:32:22 -0800271 return
Colin Cross35143d02017-11-16 00:11:20 -0800272 }
Colin Crossba9e4032020-11-24 16:32:22 -0800273 path := t.HostToolPath()
274 if !path.Valid() {
275 ctx.ModuleErrorf("host tool %q missing output file", tool)
276 return
277 }
278 if specs := t.TransitivePackagingSpecs(); specs != nil {
279 // If the HostToolProvider has PackgingSpecs, which are definitions of the
280 // required relative locations of the tool and its dependencies, use those
281 // instead. They will be copied to those relative locations in the sbox
282 // sandbox.
283 packagedTools = append(packagedTools, specs...)
284 // Assume that the first PackagingSpec of the module is the tool.
285 addLocationLabel(tag.label, []string{android.SboxPathForPackagedTool(specs[0])})
286 } else {
287 tools = append(tools, path.Path())
288 addLocationLabel(tag.label, []string{android.SboxPathForTool(ctx, path.Path())})
289 }
290 case bootstrap.GoBinaryTool:
291 // A GoBinaryTool provides the install path to a tool, which will be copied.
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700292 if s, err := filepath.Rel(android.PathForOutput(ctx).String(), t.InstallPath()); err == nil {
Colin Crossba9e4032020-11-24 16:32:22 -0800293 toolPath := android.PathForOutput(ctx, s)
294 tools = append(tools, toolPath)
295 addLocationLabel(tag.label, []string{android.SboxPathForTool(ctx, toolPath)})
Colin Cross6f080df2016-11-04 15:32:58 -0700296 } else {
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700297 ctx.ModuleErrorf("cannot find path for %q: %v", tool, err)
Colin Crossba9e4032020-11-24 16:32:22 -0800298 return
Colin Cross6f080df2016-11-04 15:32:58 -0700299 }
Colin Crossba9e4032020-11-24 16:32:22 -0800300 default:
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700301 ctx.ModuleErrorf("%q is not a host tool provider", tool)
Colin Crossba9e4032020-11-24 16:32:22 -0800302 return
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700303 }
304
Colin Crossba9e4032020-11-24 16:32:22 -0800305 seenTools[tag.label] = true
Colin Crossd350ecd2015-04-28 13:25:36 -0700306 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700307 })
Colin Crossba71a3f2019-03-18 12:12:48 -0700308
309 // If AllowMissingDependencies is enabled, the build will not have stopped when
310 // AddFarVariationDependencies was called on a missing tool, which will result in nonsensical
Liz Kammer20ebfb42020-07-28 11:32:07 -0700311 // "cmd: unknown location label ..." errors later. Add a placeholder file to the local label.
312 // The command that uses this placeholder file will never be executed because the rule will be
313 // replaced with an android.Error rule reporting the missing dependencies.
Colin Crossba71a3f2019-03-18 12:12:48 -0700314 if ctx.Config().AllowMissingDependencies() {
315 for _, tool := range g.properties.Tools {
316 if !seenTools[tool] {
317 addLocationLabel(tool, []string{"***missing tool " + tool + "***"})
318 }
319 }
320 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700321 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700322
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700323 if ctx.Failed() {
324 return
325 }
326
Colin Cross08f15ab2018-10-04 23:29:14 -0700327 for _, toolFile := range g.properties.Tool_files {
Colin Cross8a497952019-03-05 22:25:09 -0800328 paths := android.PathsForModuleSrc(ctx, []string{toolFile})
Colin Crossba9e4032020-11-24 16:32:22 -0800329 tools = append(tools, paths...)
330 var sandboxPaths []string
331 for _, path := range paths {
332 sandboxPaths = append(sandboxPaths, android.SboxPathForTool(ctx, path))
333 }
334 addLocationLabel(toolFile, sandboxPaths)
Colin Cross08f15ab2018-10-04 23:29:14 -0700335 }
336
337 var srcFiles android.Paths
338 for _, in := range g.properties.Srcs {
Colin Crossba71a3f2019-03-18 12:12:48 -0700339 paths, missingDeps := android.PathsAndMissingDepsForModuleSrcExcludes(ctx, []string{in}, g.properties.Exclude_srcs)
340 if len(missingDeps) > 0 {
341 if !ctx.Config().AllowMissingDependencies() {
342 panic(fmt.Errorf("should never get here, the missing dependencies %q should have been reported in DepsMutator",
343 missingDeps))
344 }
345
346 // If AllowMissingDependencies is enabled, the build will not have stopped when
347 // the dependency was added on a missing SourceFileProducer module, which will result in nonsensical
Liz Kammer20ebfb42020-07-28 11:32:07 -0700348 // "cmd: label ":..." has no files" errors later. Add a placeholder file to the local label.
349 // The command that uses this placeholder file will never be executed because the rule will be
350 // replaced with an android.Error rule reporting the missing dependencies.
Colin Crossba71a3f2019-03-18 12:12:48 -0700351 ctx.AddMissingDependencies(missingDeps)
352 addLocationLabel(in, []string{"***missing srcs " + in + "***"})
353 } else {
354 srcFiles = append(srcFiles, paths...)
355 addLocationLabel(in, paths.Strings())
356 }
Colin Cross08f15ab2018-10-04 23:29:14 -0700357 }
358
Colin Cross1a527682019-09-23 15:55:30 -0700359 var copyFrom android.Paths
360 var outputFiles android.WritablePaths
361 var zipArgs strings.Builder
Colin Cross08f15ab2018-10-04 23:29:14 -0700362
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500363 // Generate tasks, either from genrule or gensrcs.
Colin Cross1a527682019-09-23 15:55:30 -0700364 for _, task := range g.taskGenerator(ctx, String(g.properties.Cmd), srcFiles) {
Colin Cross3d680512020-11-13 16:23:53 -0800365 if len(task.out) == 0 {
366 ctx.ModuleErrorf("must have at least one output file")
367 return
Colin Cross85a2e892018-07-09 09:45:06 -0700368 }
369
Colin Crossf1a035e2020-11-16 17:32:30 -0800370 // Pick a unique path outside the task.genDir for the sbox manifest textproto,
371 // a unique rule name, and the user-visible description.
372 manifestName := "genrule.sbox.textproto"
373 desc := "generate"
374 name := "generator"
375 if task.shards > 0 {
376 manifestName = "genrule_" + strconv.Itoa(task.shard) + ".sbox.textproto"
377 desc += " " + strconv.Itoa(task.shard)
378 name += strconv.Itoa(task.shard)
379 } else if len(task.out) == 1 {
380 desc += " " + task.out[0].Base()
381 }
382
383 manifestPath := android.PathForModuleOut(ctx, manifestName)
384
385 // Use a RuleBuilder to create a rule that runs the command inside an sbox sandbox.
Colin Crossba9e4032020-11-24 16:32:22 -0800386 rule := android.NewRuleBuilder(pctx, ctx).Sbox(task.genDir, manifestPath).SandboxTools()
Colin Crossf1a035e2020-11-16 17:32:30 -0800387 cmd := rule.Command()
388
Colin Cross3d680512020-11-13 16:23:53 -0800389 for _, out := range task.out {
Colin Crossf1a035e2020-11-16 17:32:30 -0800390 addLocationLabel(out.Rel(), []string{cmd.PathForOutput(out)})
Colin Cross3d680512020-11-13 16:23:53 -0800391 }
392
Colin Cross1a527682019-09-23 15:55:30 -0700393 referencedDepfile := false
394
Colin Cross3d680512020-11-13 16:23:53 -0800395 rawCommand, err := android.Expand(task.cmd, func(name string) (string, error) {
Colin Cross1a527682019-09-23 15:55:30 -0700396 // report the error directly without returning an error to android.Expand to catch multiple errors in a
397 // single run
Colin Cross3d680512020-11-13 16:23:53 -0800398 reportError := func(fmt string, args ...interface{}) (string, error) {
Colin Cross1a527682019-09-23 15:55:30 -0700399 ctx.PropertyErrorf("cmd", fmt, args...)
Colin Cross3d680512020-11-13 16:23:53 -0800400 return "SOONG_ERROR", nil
Colin Cross6f080df2016-11-04 15:32:58 -0700401 }
Colin Cross1a527682019-09-23 15:55:30 -0700402
403 switch name {
404 case "location":
405 if len(g.properties.Tools) == 0 && len(g.properties.Tool_files) == 0 {
406 return reportError("at least one `tools` or `tool_files` is required if $(location) is used")
Colin Cross6f080df2016-11-04 15:32:58 -0700407 }
Colin Cross1a527682019-09-23 15:55:30 -0700408 paths := locationLabels[firstLabel]
409 if len(paths) == 0 {
410 return reportError("default label %q has no files", firstLabel)
411 } else if len(paths) > 1 {
412 return reportError("default label %q has multiple files, use $(locations %s) to reference it",
413 firstLabel, firstLabel)
Colin Cross08f15ab2018-10-04 23:29:14 -0700414 }
Colin Cross3d680512020-11-13 16:23:53 -0800415 return locationLabels[firstLabel][0], nil
Colin Cross1a527682019-09-23 15:55:30 -0700416 case "in":
Colin Cross3d680512020-11-13 16:23:53 -0800417 return strings.Join(srcFiles.Strings(), " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700418 case "out":
Colin Cross3d680512020-11-13 16:23:53 -0800419 var sandboxOuts []string
420 for _, out := range task.out {
Colin Crossf1a035e2020-11-16 17:32:30 -0800421 sandboxOuts = append(sandboxOuts, cmd.PathForOutput(out))
Colin Cross3d680512020-11-13 16:23:53 -0800422 }
423 return strings.Join(sandboxOuts, " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700424 case "depfile":
425 referencedDepfile = true
426 if !Bool(g.properties.Depfile) {
427 return reportError("$(depfile) used without depfile property")
428 }
Colin Cross3d680512020-11-13 16:23:53 -0800429 return "__SBOX_DEPFILE__", nil
Colin Cross1a527682019-09-23 15:55:30 -0700430 case "genDir":
Colin Crossf1a035e2020-11-16 17:32:30 -0800431 return cmd.PathForOutput(task.genDir), nil
Colin Cross1a527682019-09-23 15:55:30 -0700432 default:
433 if strings.HasPrefix(name, "location ") {
434 label := strings.TrimSpace(strings.TrimPrefix(name, "location "))
435 if paths, ok := locationLabels[label]; ok {
436 if len(paths) == 0 {
437 return reportError("label %q has no files", label)
438 } else if len(paths) > 1 {
439 return reportError("label %q has multiple files, use $(locations %s) to reference it",
440 label, label)
441 }
Colin Cross3d680512020-11-13 16:23:53 -0800442 return paths[0], nil
Colin Cross1a527682019-09-23 15:55:30 -0700443 } else {
444 return reportError("unknown location label %q", label)
445 }
446 } else if strings.HasPrefix(name, "locations ") {
447 label := strings.TrimSpace(strings.TrimPrefix(name, "locations "))
448 if paths, ok := locationLabels[label]; ok {
449 if len(paths) == 0 {
450 return reportError("label %q has no files", label)
451 }
Colin Cross3d680512020-11-13 16:23:53 -0800452 return strings.Join(paths, " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700453 } else {
454 return reportError("unknown locations label %q", label)
455 }
456 } else {
457 return reportError("unknown variable '$(%s)'", name)
458 }
Colin Cross6f080df2016-11-04 15:32:58 -0700459 }
Colin Cross1a527682019-09-23 15:55:30 -0700460 })
461
462 if err != nil {
463 ctx.PropertyErrorf("cmd", "%s", err.Error())
464 return
Colin Cross6f080df2016-11-04 15:32:58 -0700465 }
Colin Cross6f080df2016-11-04 15:32:58 -0700466
Colin Cross1a527682019-09-23 15:55:30 -0700467 if Bool(g.properties.Depfile) && !referencedDepfile {
468 ctx.PropertyErrorf("cmd", "specified depfile=true but did not include a reference to '${depfile}' in cmd")
469 return
470 }
Colin Cross1a527682019-09-23 15:55:30 -0700471 g.rawCommands = append(g.rawCommands, rawCommand)
Bill Peckhamc087be12020-02-13 15:55:10 -0800472
Colin Cross3d680512020-11-13 16:23:53 -0800473 cmd.Text(rawCommand)
474 cmd.ImplicitOutputs(task.out)
475 cmd.Implicits(task.in)
Colin Crossba9e4032020-11-24 16:32:22 -0800476 cmd.ImplicitTools(tools)
477 cmd.ImplicitTools(task.extraTools)
478 cmd.ImplicitPackagedTools(packagedTools)
Colin Cross3d680512020-11-13 16:23:53 -0800479 if Bool(g.properties.Depfile) {
480 cmd.ImplicitDepFile(task.depFile)
481 }
482
483 // Create the rule to run the genrule command inside sbox.
Colin Crossf1a035e2020-11-16 17:32:30 -0800484 rule.Build(name, desc)
Colin Cross1a527682019-09-23 15:55:30 -0700485
486 if len(task.copyTo) > 0 {
Colin Cross3d680512020-11-13 16:23:53 -0800487 // If copyTo is set, multiple shards need to be copied into a single directory.
488 // task.out contains the per-shard paths, and copyTo contains the corresponding
489 // final path. The files need to be copied into the final directory by a
490 // single rule so it can remove the directory before it starts to ensure no
491 // old files remain. zipsync already does this, so build up zipArgs that
492 // zip all the per-shard directories into a single zip.
Colin Cross1a527682019-09-23 15:55:30 -0700493 outputFiles = append(outputFiles, task.copyTo...)
494 copyFrom = append(copyFrom, task.out.Paths()...)
495 zipArgs.WriteString(" -C " + task.genDir.String())
496 zipArgs.WriteString(android.JoinWithPrefix(task.out.Strings(), " -f "))
497 } else {
498 outputFiles = append(outputFiles, task.out...)
499 }
Colin Cross6f080df2016-11-04 15:32:58 -0700500 }
501
Colin Cross1a527682019-09-23 15:55:30 -0700502 if len(copyFrom) > 0 {
Colin Cross3d680512020-11-13 16:23:53 -0800503 // Create a rule that zips all the per-shard directories into a single zip and then
504 // uses zipsync to unzip it into the final directory.
Colin Cross1a527682019-09-23 15:55:30 -0700505 ctx.Build(pctx, android.BuildParams{
Colin Crossf1885962020-11-20 15:28:30 -0800506 Rule: gensrcsMerge,
507 Implicits: copyFrom,
508 Outputs: outputFiles,
509 Description: "merge shards",
Colin Cross1a527682019-09-23 15:55:30 -0700510 Args: map[string]string{
511 "zipArgs": zipArgs.String(),
512 "tmpZip": android.PathForModuleGen(ctx, g.subDir+".zip").String(),
513 "genDir": android.PathForModuleGen(ctx, g.subDir).String(),
514 },
515 })
Colin Cross85a2e892018-07-09 09:45:06 -0700516 }
517
Colin Cross1a527682019-09-23 15:55:30 -0700518 g.outputFiles = outputFiles.Paths()
Jeff Gastonefc1b412017-03-29 17:29:06 -0700519
Liz Kammerea6666f2021-02-17 10:17:28 -0500520 bazelModuleLabel := g.GetBazelLabel()
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400521 bazelActionsUsed := false
522 if ctx.Config().BazelContext.BazelEnabled() && len(bazelModuleLabel) > 0 {
523 bazelActionsUsed = g.generateBazelBuildActions(ctx, bazelModuleLabel)
Jeff Gaston02a684b2017-10-27 14:59:27 -0700524 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400525 if !bazelActionsUsed {
526 // For <= 6 outputs, just embed those directly in the users. Right now, that covers >90% of
527 // the genrules on AOSP. That will make things simpler to look at the graph in the common
528 // case. For larger sets of outputs, inject a phony target in between to limit ninja file
529 // growth.
530 if len(g.outputFiles) <= 6 {
531 g.outputDeps = g.outputFiles
532 } else {
533 phonyFile := android.PathForModuleGen(ctx, "genrule-phony")
534 ctx.Build(pctx, android.BuildParams{
535 Rule: blueprint.Phony,
536 Output: phonyFile,
537 Inputs: g.outputFiles,
538 })
539 g.outputDeps = android.Paths{phonyFile}
540 }
541 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700542}
Colin Crossd350ecd2015-04-28 13:25:36 -0700543
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700544// Collect information for opening IDE project files in java/jdeps.go.
545func (g *Module) IDEInfo(dpInfo *android.IdeInfo) {
546 dpInfo.Srcs = append(dpInfo.Srcs, g.Srcs().Strings()...)
547 for _, src := range g.properties.Srcs {
548 if strings.HasPrefix(src, ":") {
549 src = strings.Trim(src, ":")
550 dpInfo.Deps = append(dpInfo.Deps, src)
551 }
552 }
bralee1fbf4402020-05-21 10:11:59 +0800553 dpInfo.Paths = append(dpInfo.Paths, g.modulePaths...)
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700554}
555
Colin Crossa4ad2b02019-03-18 22:15:32 -0700556func (g *Module) AndroidMk() android.AndroidMkData {
557 return android.AndroidMkData{
Anton Hansson72f18492020-10-30 16:34:45 +0000558 Class: "ETC",
Colin Crossa4ad2b02019-03-18 22:15:32 -0700559 OutputFile: android.OptionalPathForPath(g.outputFiles[0]),
560 SubName: g.subName,
561 Extra: []android.AndroidMkExtraFunc{
562 func(w io.Writer, outputFile android.Path) {
Anton Hansson72f18492020-10-30 16:34:45 +0000563 fmt.Fprintln(w, "LOCAL_UNINSTALLABLE_MODULE := true")
Colin Crossa4ad2b02019-03-18 22:15:32 -0700564 },
565 },
566 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
567 android.WriteAndroidMkData(w, data)
568 if data.SubName != "" {
569 fmt.Fprintln(w, ".PHONY:", name)
570 fmt.Fprintln(w, name, ":", name+g.subName)
571 }
572 },
573 }
574}
575
Jiyong Park45bf82e2020-12-15 22:29:02 +0900576var _ android.ApexModule = (*Module)(nil)
577
578// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -0700579func (g *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
580 sdkVersion android.ApiLevel) error {
Jooyung Han749dc692020-04-15 11:03:39 +0900581 // Because generated outputs are checked by client modules(e.g. cc_library, ...)
582 // we can safely ignore the check here.
583 return nil
584}
585
Jeff Gaston437d23c2017-11-08 12:38:00 -0800586func generatorFactory(taskGenerator taskFunc, props ...interface{}) *Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700587 module := &Module{
Jeff Gaston437d23c2017-11-08 12:38:00 -0800588 taskGenerator: taskGenerator,
Colin Crossd350ecd2015-04-28 13:25:36 -0700589 }
590
Colin Cross36242852017-06-23 15:06:31 -0700591 module.AddProperties(props...)
592 module.AddProperties(&module.properties)
Colin Crossd350ecd2015-04-28 13:25:36 -0700593
Colin Cross7228ecd2019-11-18 16:00:16 -0800594 module.ImageInterface = noopImageInterface{}
595
Colin Cross36242852017-06-23 15:06:31 -0700596 return module
Colin Crossd350ecd2015-04-28 13:25:36 -0700597}
598
Colin Cross7228ecd2019-11-18 16:00:16 -0800599type noopImageInterface struct{}
600
601func (x noopImageInterface) ImageMutatorBegin(android.BaseModuleContext) {}
602func (x noopImageInterface) CoreVariantNeeded(android.BaseModuleContext) bool { return false }
Yifan Hong1b3348d2020-01-21 15:53:22 -0800603func (x noopImageInterface) RamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700604func (x noopImageInterface) VendorRamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Colin Cross7228ecd2019-11-18 16:00:16 -0800605func (x noopImageInterface) RecoveryVariantNeeded(android.BaseModuleContext) bool { return false }
606func (x noopImageInterface) ExtraImageVariations(ctx android.BaseModuleContext) []string { return nil }
607func (x noopImageInterface) SetImageVariation(ctx android.BaseModuleContext, variation string, module android.Module) {
608}
609
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700610func NewGenSrcs() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700611 properties := &genSrcsProperties{}
612
Colin Crossf1885962020-11-20 15:28:30 -0800613 // finalSubDir is the name of the subdirectory that output files will be generated into.
614 // It is used so that per-shard directories can be placed alongside it an then finally
615 // merged into it.
616 const finalSubDir = "gensrcs"
617
Colin Cross1a527682019-09-23 15:55:30 -0700618 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Colin Cross1a527682019-09-23 15:55:30 -0700619 shardSize := defaultShardSize
620 if s := properties.Shard_size; s != nil {
621 shardSize = int(*s)
622 }
Jeff Gaston437d23c2017-11-08 12:38:00 -0800623
Colin Crossf1885962020-11-20 15:28:30 -0800624 // gensrcs rules can easily hit command line limits by repeating the command for
625 // every input file. Shard the input files into groups.
Colin Cross1a527682019-09-23 15:55:30 -0700626 shards := android.ShardPaths(srcFiles, shardSize)
627 var generateTasks []generateTask
Colin Crossbaccf5b2018-02-21 14:07:48 -0800628
Colin Cross1a527682019-09-23 15:55:30 -0700629 for i, shard := range shards {
630 var commands []string
631 var outFiles android.WritablePaths
Colin Cross3ea4eb82020-11-24 13:07:27 -0800632 var commandDepFiles []string
Colin Cross1a527682019-09-23 15:55:30 -0700633 var copyTo android.WritablePaths
Colin Cross1a527682019-09-23 15:55:30 -0700634
Colin Crossf1885962020-11-20 15:28:30 -0800635 // When sharding is enabled (i.e. len(shards) > 1), the sbox rules for each
636 // shard will be write to their own directories and then be merged together
637 // into finalSubDir. If sharding is not enabled (i.e. len(shards) == 1),
638 // the sbox rule will write directly to finalSubDir.
639 genSubDir := finalSubDir
Colin Cross1a527682019-09-23 15:55:30 -0700640 if len(shards) > 1 {
Colin Crossf1885962020-11-20 15:28:30 -0800641 genSubDir = strconv.Itoa(i)
Jeff Gaston437d23c2017-11-08 12:38:00 -0800642 }
643
Colin Crossf1885962020-11-20 15:28:30 -0800644 genDir := android.PathForModuleGen(ctx, genSubDir)
Colin Crossf1a035e2020-11-16 17:32:30 -0800645 // TODO(ccross): this RuleBuilder is a hack to be able to call
646 // rule.Command().PathForOutput. Replace this with passing the rule into the
647 // generator.
Colin Crossba9e4032020-11-24 16:32:22 -0800648 rule := android.NewRuleBuilder(pctx, ctx).Sbox(genDir, nil).SandboxTools()
Jeff Gaston437d23c2017-11-08 12:38:00 -0800649
Colin Cross3ea4eb82020-11-24 13:07:27 -0800650 for _, in := range shard {
Colin Crossf1885962020-11-20 15:28:30 -0800651 outFile := android.GenPathWithExt(ctx, finalSubDir, in, String(properties.Output_extension))
652
653 // If sharding is enabled, then outFile is the path to the output file in
654 // the shard directory, and copyTo is the path to the output file in the
655 // final directory.
Colin Cross1a527682019-09-23 15:55:30 -0700656 if len(shards) > 1 {
Colin Crossf1885962020-11-20 15:28:30 -0800657 shardFile := android.GenPathWithExt(ctx, genSubDir, in, String(properties.Output_extension))
Colin Cross1a527682019-09-23 15:55:30 -0700658 copyTo = append(copyTo, outFile)
659 outFile = shardFile
660 }
661
662 outFiles = append(outFiles, outFile)
Colin Cross1a527682019-09-23 15:55:30 -0700663
Colin Crossf1885962020-11-20 15:28:30 -0800664 // pre-expand the command line to replace $in and $out with references to
665 // a single input and output file.
Colin Cross1a527682019-09-23 15:55:30 -0700666 command, err := android.Expand(rawCommand, func(name string) (string, error) {
667 switch name {
668 case "in":
669 return in.String(), nil
670 case "out":
Colin Crossf1a035e2020-11-16 17:32:30 -0800671 return rule.Command().PathForOutput(outFile), nil
Colin Cross3ea4eb82020-11-24 13:07:27 -0800672 case "depfile":
673 // Generate a depfile for each output file. Store the list for
674 // later in order to combine them all into a single depfile.
Colin Crossf1a035e2020-11-16 17:32:30 -0800675 depFile := rule.Command().PathForOutput(outFile.ReplaceExtension(ctx, "d"))
Colin Cross3ea4eb82020-11-24 13:07:27 -0800676 commandDepFiles = append(commandDepFiles, depFile)
677 return depFile, nil
Colin Cross1a527682019-09-23 15:55:30 -0700678 default:
679 return "$(" + name + ")", nil
680 }
681 })
682 if err != nil {
683 ctx.PropertyErrorf("cmd", err.Error())
684 }
685
686 // escape the command in case for example it contains '#', an odd number of '"', etc
687 command = fmt.Sprintf("bash -c %v", proptools.ShellEscape(command))
688 commands = append(commands, command)
689 }
690 fullCommand := strings.Join(commands, " && ")
691
Colin Cross3ea4eb82020-11-24 13:07:27 -0800692 var outputDepfile android.WritablePath
693 var extraTools android.Paths
694 if len(commandDepFiles) > 0 {
695 // Each command wrote to a depfile, but ninja can only handle one
696 // depfile per rule. Use the dep_fixer tool at the end of the
697 // command to combine all the depfiles into a single output depfile.
698 outputDepfile = android.PathForModuleGen(ctx, genSubDir, "gensrcs.d")
699 depFixerTool := ctx.Config().HostToolPath(ctx, "dep_fixer")
700 fullCommand += fmt.Sprintf(" && %s -o $(depfile) %s",
Colin Crossba9e4032020-11-24 16:32:22 -0800701 android.SboxPathForTool(ctx, depFixerTool),
702 strings.Join(commandDepFiles, " "))
Colin Cross3ea4eb82020-11-24 13:07:27 -0800703 extraTools = append(extraTools, depFixerTool)
704 }
705
Colin Cross1a527682019-09-23 15:55:30 -0700706 generateTasks = append(generateTasks, generateTask{
Colin Cross3ea4eb82020-11-24 13:07:27 -0800707 in: shard,
708 out: outFiles,
709 depFile: outputDepfile,
710 copyTo: copyTo,
711 genDir: genDir,
712 cmd: fullCommand,
713 shard: i,
714 shards: len(shards),
715 extraTools: extraTools,
Colin Cross1a527682019-09-23 15:55:30 -0700716 })
Jeff Gaston437d23c2017-11-08 12:38:00 -0800717 }
Colin Cross1a527682019-09-23 15:55:30 -0700718
719 return generateTasks
Colin Crossd350ecd2015-04-28 13:25:36 -0700720 }
721
Colin Cross1a527682019-09-23 15:55:30 -0700722 g := generatorFactory(taskGenerator, properties)
Colin Crossf1885962020-11-20 15:28:30 -0800723 g.subDir = finalSubDir
Colin Cross1a527682019-09-23 15:55:30 -0700724 return g
Colin Crossd350ecd2015-04-28 13:25:36 -0700725}
726
Colin Cross54190b32017-10-09 15:34:10 -0700727func GenSrcsFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700728 m := NewGenSrcs()
729 android.InitAndroidModule(m)
730 return m
731}
732
Colin Crossd350ecd2015-04-28 13:25:36 -0700733type genSrcsProperties struct {
Colin Cross7d5136f2015-05-11 13:39:40 -0700734 // extension that will be substituted for each output file
Nan Zhanga5e7cb42017-11-09 22:42:32 -0800735 Output_extension *string
Colin Cross1a527682019-09-23 15:55:30 -0700736
737 // maximum number of files that will be passed on a single command line.
738 Shard_size *int64
Colin Cross5049f022015-03-18 13:28:46 -0700739}
740
Evgenii Stepanovf47c90d2020-12-02 18:55:09 -0800741const defaultShardSize = 50
Colin Cross1a527682019-09-23 15:55:30 -0700742
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700743func NewGenRule() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700744 properties := &genRuleProperties{}
Colin Cross5049f022015-03-18 13:28:46 -0700745
Colin Cross1a527682019-09-23 15:55:30 -0700746 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700747 outs := make(android.WritablePaths, len(properties.Out))
Colin Cross3d680512020-11-13 16:23:53 -0800748 var depFile android.WritablePath
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700749 for i, out := range properties.Out {
Colin Cross3d680512020-11-13 16:23:53 -0800750 outPath := android.PathForModuleGen(ctx, out)
751 if i == 0 {
752 depFile = outPath.ReplaceExtension(ctx, "d")
753 }
754 outs[i] = outPath
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700755 }
Colin Cross1a527682019-09-23 15:55:30 -0700756 return []generateTask{{
Colin Cross3d680512020-11-13 16:23:53 -0800757 in: srcFiles,
758 out: outs,
759 depFile: depFile,
760 genDir: android.PathForModuleGen(ctx),
761 cmd: rawCommand,
Colin Cross1a527682019-09-23 15:55:30 -0700762 }}
Colin Cross5049f022015-03-18 13:28:46 -0700763 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700764
Jeff Gaston437d23c2017-11-08 12:38:00 -0800765 return generatorFactory(taskGenerator, properties)
Colin Cross5049f022015-03-18 13:28:46 -0700766}
767
Colin Cross54190b32017-10-09 15:34:10 -0700768func GenRuleFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700769 m := NewGenRule()
770 android.InitAndroidModule(m)
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800771 android.InitDefaultableModule(m)
Liz Kammerea6666f2021-02-17 10:17:28 -0500772 android.InitBazelModule(m)
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700773 return m
774}
775
Colin Crossd350ecd2015-04-28 13:25:36 -0700776type genRuleProperties struct {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700777 // names of the output files that will be generated
Colin Crossef354482018-10-23 11:27:50 -0700778 Out []string `android:"arch_variant"`
Colin Cross5049f022015-03-18 13:28:46 -0700779}
Nan Zhangea568a42017-11-08 21:20:04 -0800780
Jingwen Chen316e07c2020-12-14 09:09:52 -0500781type bazelGenruleAttributes struct {
Liz Kammer356f7d42021-01-26 09:18:53 -0500782 Srcs bazel.LabelList
Jingwen Chen316e07c2020-12-14 09:09:52 -0500783 Outs []string
Liz Kammer356f7d42021-01-26 09:18:53 -0500784 Tools bazel.LabelList
Jingwen Chen316e07c2020-12-14 09:09:52 -0500785 Cmd string
786}
787
788type bazelGenrule struct {
789 android.BazelTargetModuleBase
790 bazelGenruleAttributes
791}
792
793func BazelGenruleFactory() android.Module {
794 module := &bazelGenrule{}
795 module.AddProperties(&module.bazelGenruleAttributes)
796 android.InitBazelTargetModule(module)
797 return module
798}
799
Jingwen Chena42d6412021-01-26 21:57:27 -0500800func GenruleBp2Build(ctx android.TopDownMutatorContext) {
Liz Kammer356f7d42021-01-26 09:18:53 -0500801 m, ok := ctx.Module().(*Module)
Liz Kammerea6666f2021-02-17 10:17:28 -0500802 if !ok || !m.ConvertWithBp2build() {
Liz Kammer356f7d42021-01-26 09:18:53 -0500803 return
Jingwen Chen316e07c2020-12-14 09:09:52 -0500804 }
Jingwen Chen1fd14692021-02-05 03:01:50 -0500805
Liz Kammer356f7d42021-01-26 09:18:53 -0500806 // Bazel only has the "tools" attribute.
807 tools := android.BazelLabelForModuleDeps(ctx, m.properties.Tools)
808 tool_files := android.BazelLabelForModuleSrc(ctx, m.properties.Tool_files)
809 tools.Append(tool_files)
810
811 srcs := android.BazelLabelForModuleSrc(ctx, m.properties.Srcs)
812
813 var allReplacements bazel.LabelList
814 allReplacements.Append(tools)
815 allReplacements.Append(srcs)
816
817 // Replace in and out variables with $< and $@
818 var cmd string
819 if m.properties.Cmd != nil {
820 cmd = strings.Replace(*m.properties.Cmd, "$(in)", "$(SRCS)", -1)
821 cmd = strings.Replace(cmd, "$(out)", "$(OUTS)", -1)
822 cmd = strings.Replace(cmd, "$(genDir)", "$(GENDIR)", -1)
823 if len(tools.Includes) > 0 {
824 cmd = strings.Replace(cmd, "$(location)", fmt.Sprintf("$(location %s)", tools.Includes[0].Label), -1)
825 cmd = strings.Replace(cmd, "$(locations)", fmt.Sprintf("$(locations %s)", tools.Includes[0].Label), -1)
826 }
827 for _, l := range allReplacements.Includes {
828 bpLoc := fmt.Sprintf("$(location %s)", l.Bp_text)
829 bpLocs := fmt.Sprintf("$(locations %s)", l.Bp_text)
830 bazelLoc := fmt.Sprintf("$(location %s)", l.Label)
831 bazelLocs := fmt.Sprintf("$(locations %s)", l.Label)
832 cmd = strings.Replace(cmd, bpLoc, bazelLoc, -1)
833 cmd = strings.Replace(cmd, bpLocs, bazelLocs, -1)
834 }
835 }
836
837 // The Out prop is not in an immediately accessible field
838 // in the Module struct, so use GetProperties and cast it
839 // to the known struct prop.
840 var outs []string
841 for _, propIntf := range m.GetProperties() {
842 if props, ok := propIntf.(*genRuleProperties); ok {
843 outs = props.Out
844 break
845 }
846 }
847
Jingwen Chen1fd14692021-02-05 03:01:50 -0500848 attrs := &bazelGenruleAttributes{
Liz Kammer356f7d42021-01-26 09:18:53 -0500849 Srcs: srcs,
850 Outs: outs,
851 Cmd: cmd,
852 Tools: tools,
Jingwen Chen1fd14692021-02-05 03:01:50 -0500853 }
854
Liz Kammerfc46bc12021-02-19 11:06:17 -0500855 props := bazel.BazelTargetModuleProperties{
856 Rule_class: "genrule",
857 }
Jingwen Chen1fd14692021-02-05 03:01:50 -0500858
859 // Create the BazelTargetModule.
Liz Kammerfc46bc12021-02-19 11:06:17 -0500860 ctx.CreateBazelTargetModule(BazelGenruleFactory, m.Name(), props, attrs)
Jingwen Chen316e07c2020-12-14 09:09:52 -0500861}
862
863func (m *bazelGenrule) Name() string {
864 return m.BaseModuleName()
865}
866
867func (m *bazelGenrule) GenerateAndroidBuildActions(ctx android.ModuleContext) {}
868
Nan Zhangea568a42017-11-08 21:20:04 -0800869var Bool = proptools.Bool
870var String = proptools.String
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800871
872//
873// Defaults
874//
875type Defaults struct {
876 android.ModuleBase
877 android.DefaultsModuleBase
878}
879
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800880func defaultsFactory() android.Module {
881 return DefaultsFactory()
882}
883
884func DefaultsFactory(props ...interface{}) android.Module {
885 module := &Defaults{}
886
887 module.AddProperties(props...)
888 module.AddProperties(
889 &generatorProperties{},
890 &genRuleProperties{},
891 )
892
893 android.InitDefaultsModule(module)
894
895 return module
896}