blob: 62aa7f83459876f925d374dcc0429e3317b56ae7 [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"`
Colin Cross7d5136f2015-05-11 13:39:40 -0700127
Jingwen Chen30f5aaa2020-11-19 05:38:02 -0500128 // Properties for Bazel migration purposes.
129 bazel.Properties
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400130}
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500131
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700132type Module struct {
Colin Cross635c3b02016-05-18 15:37:25 -0700133 android.ModuleBase
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800134 android.DefaultableModuleBase
Jiyong Parkfc752ca2019-06-12 13:27:29 +0900135 android.ApexModuleBase
Colin Crossd350ecd2015-04-28 13:25:36 -0700136
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700137 // For other packages to make their own genrules with extra
138 // properties
139 Extra interface{}
Colin Cross7228ecd2019-11-18 16:00:16 -0800140 android.ImageInterface
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700141
Colin Cross7d5136f2015-05-11 13:39:40 -0700142 properties generatorProperties
Colin Crossd350ecd2015-04-28 13:25:36 -0700143
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500144 // For the different tasks that genrule and gensrc generate. genrule will
145 // generate 1 task, and gensrc will generate 1 or more tasks based on the
146 // number of shards the input files are sharded into.
Jeff Gaston437d23c2017-11-08 12:38:00 -0800147 taskGenerator taskFunc
Colin Crossd350ecd2015-04-28 13:25:36 -0700148
Colin Cross1a527682019-09-23 15:55:30 -0700149 rule blueprint.Rule
150 rawCommands []string
Colin Crossd350ecd2015-04-28 13:25:36 -0700151
Colin Cross5ed99c62016-11-22 12:55:55 -0800152 exportedIncludeDirs android.Paths
Dan Willemsenb40aab62016-04-20 14:21:14 -0700153
Colin Cross635c3b02016-05-18 15:37:25 -0700154 outputFiles android.Paths
Dan Willemsen9da9d492018-02-21 18:28:18 -0800155 outputDeps android.Paths
Colin Crossa4ad2b02019-03-18 22:15:32 -0700156
157 subName string
Colin Cross1a527682019-09-23 15:55:30 -0700158 subDir string
bralee1fbf4402020-05-21 10:11:59 +0800159
160 // Collect the module directory for IDE info in java/jdeps.go.
161 modulePaths []string
Colin Crossd350ecd2015-04-28 13:25:36 -0700162}
163
Colin Cross1a527682019-09-23 15:55:30 -0700164type taskFunc func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask
Colin Crossd350ecd2015-04-28 13:25:36 -0700165
166type generateTask struct {
Colin Cross3ea4eb82020-11-24 13:07:27 -0800167 in android.Paths
168 out android.WritablePaths
169 depFile android.WritablePath
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500170 copyTo android.WritablePaths // For gensrcs to set on gensrcsMerge rule.
Colin Cross3ea4eb82020-11-24 13:07:27 -0800171 genDir android.WritablePath
172 extraTools android.Paths // dependencies on tools used by the generator
173
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500174 cmd string
175 // For gensrsc sharding.
Colin Cross3ea4eb82020-11-24 13:07:27 -0800176 shard int
177 shards int
Colin Crossd350ecd2015-04-28 13:25:36 -0700178}
179
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700180func (g *Module) GeneratedSourceFiles() android.Paths {
Colin Crossd350ecd2015-04-28 13:25:36 -0700181 return g.outputFiles
182}
183
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700184func (g *Module) Srcs() android.Paths {
Nan Zhange42777a2018-03-27 16:19:42 -0700185 return append(android.Paths{}, g.outputFiles...)
Colin Cross068e0fe2016-12-13 15:23:47 -0800186}
187
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700188func (g *Module) GeneratedHeaderDirs() android.Paths {
Colin Cross5ed99c62016-11-22 12:55:55 -0800189 return g.exportedIncludeDirs
Dan Willemsenb40aab62016-04-20 14:21:14 -0700190}
191
Dan Willemsen9da9d492018-02-21 18:28:18 -0800192func (g *Module) GeneratedDeps() android.Paths {
193 return g.outputDeps
194}
195
Martin Stjernholm710ec3a2020-01-16 15:12:04 +0000196func toolDepsMutator(ctx android.BottomUpMutatorContext) {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700197 if g, ok := ctx.Module().(*Module); ok {
Colin Cross08f15ab2018-10-04 23:29:14 -0700198 for _, tool := range g.properties.Tools {
199 tag := hostToolDependencyTag{label: tool}
200 if m := android.SrcIsModule(tool); m != "" {
201 tool = m
202 }
Colin Cross0f7d2ef2019-10-16 11:03:10 -0700203 ctx.AddFarVariationDependencies(ctx.Config().BuildOSTarget.Variations(), tag, tool)
Colin Cross6362e272015-10-29 15:25:03 -0700204 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700205 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700206}
207
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400208// Returns true if information was available from Bazel, false if bazel invocation still needs to occur.
209func (c *Module) generateBazelBuildActions(ctx android.ModuleContext, label string) bool {
210 bazelCtx := ctx.Config().BazelContext
211 filePaths, ok := bazelCtx.GetAllFiles(label)
212 if ok {
213 var bazelOutputFiles android.Paths
214 for _, bazelOutputFile := range filePaths {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500215 bazelOutputFiles = append(bazelOutputFiles, android.PathForBazelOut(ctx, bazelOutputFile))
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400216 }
217 c.outputFiles = bazelOutputFiles
218 c.outputDeps = bazelOutputFiles
219 }
220 return ok
221}
Colin Crossf1885962020-11-20 15:28:30 -0800222
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700223func (g *Module) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Colin Crossa4ad2b02019-03-18 22:15:32 -0700224 g.subName = ctx.ModuleSubDir()
225
bralee1fbf4402020-05-21 10:11:59 +0800226 // Collect the module directory for IDE info in java/jdeps.go.
227 g.modulePaths = append(g.modulePaths, ctx.ModuleDir())
228
Colin Cross5ed99c62016-11-22 12:55:55 -0800229 if len(g.properties.Export_include_dirs) > 0 {
230 for _, dir := range g.properties.Export_include_dirs {
231 g.exportedIncludeDirs = append(g.exportedIncludeDirs,
Colin Cross1a527682019-09-23 15:55:30 -0700232 android.PathForModuleGen(ctx, g.subDir, ctx.ModuleDir(), dir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800233 }
234 } else {
Colin Cross1a527682019-09-23 15:55:30 -0700235 g.exportedIncludeDirs = append(g.exportedIncludeDirs, android.PathForModuleGen(ctx, g.subDir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800236 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700237
Colin Cross08f15ab2018-10-04 23:29:14 -0700238 locationLabels := map[string][]string{}
239 firstLabel := ""
240
241 addLocationLabel := func(label string, paths []string) {
242 if firstLabel == "" {
243 firstLabel = label
244 }
245 if _, exists := locationLabels[label]; !exists {
246 locationLabels[label] = paths
247 } else {
248 ctx.ModuleErrorf("multiple labels for %q, %q and %q",
249 label, strings.Join(locationLabels[label], " "), strings.Join(paths, " "))
250 }
251 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700252
Colin Crossba9e4032020-11-24 16:32:22 -0800253 var tools android.Paths
254 var packagedTools []android.PackagingSpec
Colin Cross6f080df2016-11-04 15:32:58 -0700255 if len(g.properties.Tools) > 0 {
Colin Crossba71a3f2019-03-18 12:12:48 -0700256 seenTools := make(map[string]bool)
257
Colin Cross35143d02017-11-16 00:11:20 -0800258 ctx.VisitDirectDepsBlueprint(func(module blueprint.Module) {
Colin Cross08f15ab2018-10-04 23:29:14 -0700259 switch tag := ctx.OtherModuleDependencyTag(module).(type) {
260 case hostToolDependencyTag:
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700261 tool := ctx.OtherModuleName(module)
262
Colin Crossba9e4032020-11-24 16:32:22 -0800263 switch t := module.(type) {
264 case android.HostToolProvider:
265 // A HostToolProvider provides the path to a tool, which will be copied
266 // into the sandbox.
Colin Cross35143d02017-11-16 00:11:20 -0800267 if !t.(android.Module).Enabled() {
Colin Cross6510f912017-11-29 00:27:14 -0800268 if ctx.Config().AllowMissingDependencies() {
Colin Cross35143d02017-11-16 00:11:20 -0800269 ctx.AddMissingDependencies([]string{tool})
270 } else {
271 ctx.ModuleErrorf("depends on disabled module %q", tool)
272 }
Colin Crossba9e4032020-11-24 16:32:22 -0800273 return
Colin Cross35143d02017-11-16 00:11:20 -0800274 }
Colin Crossba9e4032020-11-24 16:32:22 -0800275 path := t.HostToolPath()
276 if !path.Valid() {
277 ctx.ModuleErrorf("host tool %q missing output file", tool)
278 return
279 }
280 if specs := t.TransitivePackagingSpecs(); specs != nil {
281 // If the HostToolProvider has PackgingSpecs, which are definitions of the
282 // required relative locations of the tool and its dependencies, use those
283 // instead. They will be copied to those relative locations in the sbox
284 // sandbox.
285 packagedTools = append(packagedTools, specs...)
286 // Assume that the first PackagingSpec of the module is the tool.
287 addLocationLabel(tag.label, []string{android.SboxPathForPackagedTool(specs[0])})
288 } else {
289 tools = append(tools, path.Path())
290 addLocationLabel(tag.label, []string{android.SboxPathForTool(ctx, path.Path())})
291 }
292 case bootstrap.GoBinaryTool:
293 // A GoBinaryTool provides the install path to a tool, which will be copied.
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700294 if s, err := filepath.Rel(android.PathForOutput(ctx).String(), t.InstallPath()); err == nil {
Colin Crossba9e4032020-11-24 16:32:22 -0800295 toolPath := android.PathForOutput(ctx, s)
296 tools = append(tools, toolPath)
297 addLocationLabel(tag.label, []string{android.SboxPathForTool(ctx, toolPath)})
Colin Cross6f080df2016-11-04 15:32:58 -0700298 } else {
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700299 ctx.ModuleErrorf("cannot find path for %q: %v", tool, err)
Colin Crossba9e4032020-11-24 16:32:22 -0800300 return
Colin Cross6f080df2016-11-04 15:32:58 -0700301 }
Colin Crossba9e4032020-11-24 16:32:22 -0800302 default:
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700303 ctx.ModuleErrorf("%q is not a host tool provider", tool)
Colin Crossba9e4032020-11-24 16:32:22 -0800304 return
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700305 }
306
Colin Crossba9e4032020-11-24 16:32:22 -0800307 seenTools[tag.label] = true
Colin Crossd350ecd2015-04-28 13:25:36 -0700308 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700309 })
Colin Crossba71a3f2019-03-18 12:12:48 -0700310
311 // If AllowMissingDependencies is enabled, the build will not have stopped when
312 // AddFarVariationDependencies was called on a missing tool, which will result in nonsensical
Liz Kammer20ebfb42020-07-28 11:32:07 -0700313 // "cmd: unknown location label ..." errors later. Add a placeholder file to the local label.
314 // The command that uses this placeholder file will never be executed because the rule will be
315 // replaced with an android.Error rule reporting the missing dependencies.
Colin Crossba71a3f2019-03-18 12:12:48 -0700316 if ctx.Config().AllowMissingDependencies() {
317 for _, tool := range g.properties.Tools {
318 if !seenTools[tool] {
319 addLocationLabel(tool, []string{"***missing tool " + tool + "***"})
320 }
321 }
322 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700323 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700324
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700325 if ctx.Failed() {
326 return
327 }
328
Colin Cross08f15ab2018-10-04 23:29:14 -0700329 for _, toolFile := range g.properties.Tool_files {
Colin Cross8a497952019-03-05 22:25:09 -0800330 paths := android.PathsForModuleSrc(ctx, []string{toolFile})
Colin Crossba9e4032020-11-24 16:32:22 -0800331 tools = append(tools, paths...)
332 var sandboxPaths []string
333 for _, path := range paths {
334 sandboxPaths = append(sandboxPaths, android.SboxPathForTool(ctx, path))
335 }
336 addLocationLabel(toolFile, sandboxPaths)
Colin Cross08f15ab2018-10-04 23:29:14 -0700337 }
338
339 var srcFiles android.Paths
340 for _, in := range g.properties.Srcs {
Colin Crossba71a3f2019-03-18 12:12:48 -0700341 paths, missingDeps := android.PathsAndMissingDepsForModuleSrcExcludes(ctx, []string{in}, g.properties.Exclude_srcs)
342 if len(missingDeps) > 0 {
343 if !ctx.Config().AllowMissingDependencies() {
344 panic(fmt.Errorf("should never get here, the missing dependencies %q should have been reported in DepsMutator",
345 missingDeps))
346 }
347
348 // If AllowMissingDependencies is enabled, the build will not have stopped when
349 // the dependency was added on a missing SourceFileProducer module, which will result in nonsensical
Liz Kammer20ebfb42020-07-28 11:32:07 -0700350 // "cmd: label ":..." has no files" errors later. Add a placeholder file to the local label.
351 // The command that uses this placeholder file will never be executed because the rule will be
352 // replaced with an android.Error rule reporting the missing dependencies.
Colin Crossba71a3f2019-03-18 12:12:48 -0700353 ctx.AddMissingDependencies(missingDeps)
354 addLocationLabel(in, []string{"***missing srcs " + in + "***"})
355 } else {
356 srcFiles = append(srcFiles, paths...)
357 addLocationLabel(in, paths.Strings())
358 }
Colin Cross08f15ab2018-10-04 23:29:14 -0700359 }
360
Colin Cross1a527682019-09-23 15:55:30 -0700361 var copyFrom android.Paths
362 var outputFiles android.WritablePaths
363 var zipArgs strings.Builder
Colin Cross08f15ab2018-10-04 23:29:14 -0700364
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500365 // Generate tasks, either from genrule or gensrcs.
Colin Cross1a527682019-09-23 15:55:30 -0700366 for _, task := range g.taskGenerator(ctx, String(g.properties.Cmd), srcFiles) {
Colin Cross3d680512020-11-13 16:23:53 -0800367 if len(task.out) == 0 {
368 ctx.ModuleErrorf("must have at least one output file")
369 return
Colin Cross85a2e892018-07-09 09:45:06 -0700370 }
371
Colin Crossf1a035e2020-11-16 17:32:30 -0800372 // Pick a unique path outside the task.genDir for the sbox manifest textproto,
373 // a unique rule name, and the user-visible description.
374 manifestName := "genrule.sbox.textproto"
375 desc := "generate"
376 name := "generator"
377 if task.shards > 0 {
378 manifestName = "genrule_" + strconv.Itoa(task.shard) + ".sbox.textproto"
379 desc += " " + strconv.Itoa(task.shard)
380 name += strconv.Itoa(task.shard)
381 } else if len(task.out) == 1 {
382 desc += " " + task.out[0].Base()
383 }
384
385 manifestPath := android.PathForModuleOut(ctx, manifestName)
386
387 // Use a RuleBuilder to create a rule that runs the command inside an sbox sandbox.
Colin Crossba9e4032020-11-24 16:32:22 -0800388 rule := android.NewRuleBuilder(pctx, ctx).Sbox(task.genDir, manifestPath).SandboxTools()
Colin Crossf1a035e2020-11-16 17:32:30 -0800389 cmd := rule.Command()
390
Colin Cross3d680512020-11-13 16:23:53 -0800391 for _, out := range task.out {
Colin Crossf1a035e2020-11-16 17:32:30 -0800392 addLocationLabel(out.Rel(), []string{cmd.PathForOutput(out)})
Colin Cross3d680512020-11-13 16:23:53 -0800393 }
394
Colin Cross1a527682019-09-23 15:55:30 -0700395 referencedDepfile := false
396
Colin Cross3d680512020-11-13 16:23:53 -0800397 rawCommand, err := android.Expand(task.cmd, func(name string) (string, error) {
Colin Cross1a527682019-09-23 15:55:30 -0700398 // report the error directly without returning an error to android.Expand to catch multiple errors in a
399 // single run
Colin Cross3d680512020-11-13 16:23:53 -0800400 reportError := func(fmt string, args ...interface{}) (string, error) {
Colin Cross1a527682019-09-23 15:55:30 -0700401 ctx.PropertyErrorf("cmd", fmt, args...)
Colin Cross3d680512020-11-13 16:23:53 -0800402 return "SOONG_ERROR", nil
Colin Cross6f080df2016-11-04 15:32:58 -0700403 }
Colin Cross1a527682019-09-23 15:55:30 -0700404
405 switch name {
406 case "location":
407 if len(g.properties.Tools) == 0 && len(g.properties.Tool_files) == 0 {
408 return reportError("at least one `tools` or `tool_files` is required if $(location) is used")
Colin Cross6f080df2016-11-04 15:32:58 -0700409 }
Colin Cross1a527682019-09-23 15:55:30 -0700410 paths := locationLabels[firstLabel]
411 if len(paths) == 0 {
412 return reportError("default label %q has no files", firstLabel)
413 } else if len(paths) > 1 {
414 return reportError("default label %q has multiple files, use $(locations %s) to reference it",
415 firstLabel, firstLabel)
Colin Cross08f15ab2018-10-04 23:29:14 -0700416 }
Colin Cross3d680512020-11-13 16:23:53 -0800417 return locationLabels[firstLabel][0], nil
Colin Cross1a527682019-09-23 15:55:30 -0700418 case "in":
Colin Cross3d680512020-11-13 16:23:53 -0800419 return strings.Join(srcFiles.Strings(), " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700420 case "out":
Colin Cross3d680512020-11-13 16:23:53 -0800421 var sandboxOuts []string
422 for _, out := range task.out {
Colin Crossf1a035e2020-11-16 17:32:30 -0800423 sandboxOuts = append(sandboxOuts, cmd.PathForOutput(out))
Colin Cross3d680512020-11-13 16:23:53 -0800424 }
425 return strings.Join(sandboxOuts, " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700426 case "depfile":
427 referencedDepfile = true
428 if !Bool(g.properties.Depfile) {
429 return reportError("$(depfile) used without depfile property")
430 }
Colin Cross3d680512020-11-13 16:23:53 -0800431 return "__SBOX_DEPFILE__", nil
Colin Cross1a527682019-09-23 15:55:30 -0700432 case "genDir":
Colin Crossf1a035e2020-11-16 17:32:30 -0800433 return cmd.PathForOutput(task.genDir), nil
Colin Cross1a527682019-09-23 15:55:30 -0700434 default:
435 if strings.HasPrefix(name, "location ") {
436 label := strings.TrimSpace(strings.TrimPrefix(name, "location "))
437 if paths, ok := locationLabels[label]; ok {
438 if len(paths) == 0 {
439 return reportError("label %q has no files", label)
440 } else if len(paths) > 1 {
441 return reportError("label %q has multiple files, use $(locations %s) to reference it",
442 label, label)
443 }
Colin Cross3d680512020-11-13 16:23:53 -0800444 return paths[0], nil
Colin Cross1a527682019-09-23 15:55:30 -0700445 } else {
446 return reportError("unknown location label %q", label)
447 }
448 } else if strings.HasPrefix(name, "locations ") {
449 label := strings.TrimSpace(strings.TrimPrefix(name, "locations "))
450 if paths, ok := locationLabels[label]; ok {
451 if len(paths) == 0 {
452 return reportError("label %q has no files", label)
453 }
Colin Cross3d680512020-11-13 16:23:53 -0800454 return strings.Join(paths, " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700455 } else {
456 return reportError("unknown locations label %q", label)
457 }
458 } else {
459 return reportError("unknown variable '$(%s)'", name)
460 }
Colin Cross6f080df2016-11-04 15:32:58 -0700461 }
Colin Cross1a527682019-09-23 15:55:30 -0700462 })
463
464 if err != nil {
465 ctx.PropertyErrorf("cmd", "%s", err.Error())
466 return
Colin Cross6f080df2016-11-04 15:32:58 -0700467 }
Colin Cross6f080df2016-11-04 15:32:58 -0700468
Colin Cross1a527682019-09-23 15:55:30 -0700469 if Bool(g.properties.Depfile) && !referencedDepfile {
470 ctx.PropertyErrorf("cmd", "specified depfile=true but did not include a reference to '${depfile}' in cmd")
471 return
472 }
Colin Cross1a527682019-09-23 15:55:30 -0700473 g.rawCommands = append(g.rawCommands, rawCommand)
Bill Peckhamc087be12020-02-13 15:55:10 -0800474
Colin Cross3d680512020-11-13 16:23:53 -0800475 cmd.Text(rawCommand)
476 cmd.ImplicitOutputs(task.out)
477 cmd.Implicits(task.in)
Colin Crossba9e4032020-11-24 16:32:22 -0800478 cmd.ImplicitTools(tools)
479 cmd.ImplicitTools(task.extraTools)
480 cmd.ImplicitPackagedTools(packagedTools)
Colin Cross3d680512020-11-13 16:23:53 -0800481 if Bool(g.properties.Depfile) {
482 cmd.ImplicitDepFile(task.depFile)
483 }
484
485 // Create the rule to run the genrule command inside sbox.
Colin Crossf1a035e2020-11-16 17:32:30 -0800486 rule.Build(name, desc)
Colin Cross1a527682019-09-23 15:55:30 -0700487
488 if len(task.copyTo) > 0 {
Colin Cross3d680512020-11-13 16:23:53 -0800489 // If copyTo is set, multiple shards need to be copied into a single directory.
490 // task.out contains the per-shard paths, and copyTo contains the corresponding
491 // final path. The files need to be copied into the final directory by a
492 // single rule so it can remove the directory before it starts to ensure no
493 // old files remain. zipsync already does this, so build up zipArgs that
494 // zip all the per-shard directories into a single zip.
Colin Cross1a527682019-09-23 15:55:30 -0700495 outputFiles = append(outputFiles, task.copyTo...)
496 copyFrom = append(copyFrom, task.out.Paths()...)
497 zipArgs.WriteString(" -C " + task.genDir.String())
498 zipArgs.WriteString(android.JoinWithPrefix(task.out.Strings(), " -f "))
499 } else {
500 outputFiles = append(outputFiles, task.out...)
501 }
Colin Cross6f080df2016-11-04 15:32:58 -0700502 }
503
Colin Cross1a527682019-09-23 15:55:30 -0700504 if len(copyFrom) > 0 {
Colin Cross3d680512020-11-13 16:23:53 -0800505 // Create a rule that zips all the per-shard directories into a single zip and then
506 // uses zipsync to unzip it into the final directory.
Colin Cross1a527682019-09-23 15:55:30 -0700507 ctx.Build(pctx, android.BuildParams{
Colin Crossf1885962020-11-20 15:28:30 -0800508 Rule: gensrcsMerge,
509 Implicits: copyFrom,
510 Outputs: outputFiles,
511 Description: "merge shards",
Colin Cross1a527682019-09-23 15:55:30 -0700512 Args: map[string]string{
513 "zipArgs": zipArgs.String(),
514 "tmpZip": android.PathForModuleGen(ctx, g.subDir+".zip").String(),
515 "genDir": android.PathForModuleGen(ctx, g.subDir).String(),
516 },
517 })
Colin Cross85a2e892018-07-09 09:45:06 -0700518 }
519
Colin Cross1a527682019-09-23 15:55:30 -0700520 g.outputFiles = outputFiles.Paths()
Jeff Gastonefc1b412017-03-29 17:29:06 -0700521
Chris Parsonsaa8be052020-10-14 16:22:37 -0400522 bazelModuleLabel := g.properties.Bazel_module.Label
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400523 bazelActionsUsed := false
524 if ctx.Config().BazelContext.BazelEnabled() && len(bazelModuleLabel) > 0 {
525 bazelActionsUsed = g.generateBazelBuildActions(ctx, bazelModuleLabel)
Jeff Gaston02a684b2017-10-27 14:59:27 -0700526 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400527 if !bazelActionsUsed {
528 // For <= 6 outputs, just embed those directly in the users. Right now, that covers >90% of
529 // the genrules on AOSP. That will make things simpler to look at the graph in the common
530 // case. For larger sets of outputs, inject a phony target in between to limit ninja file
531 // growth.
532 if len(g.outputFiles) <= 6 {
533 g.outputDeps = g.outputFiles
534 } else {
535 phonyFile := android.PathForModuleGen(ctx, "genrule-phony")
536 ctx.Build(pctx, android.BuildParams{
537 Rule: blueprint.Phony,
538 Output: phonyFile,
539 Inputs: g.outputFiles,
540 })
541 g.outputDeps = android.Paths{phonyFile}
542 }
543 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700544}
Colin Crossd350ecd2015-04-28 13:25:36 -0700545
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700546// Collect information for opening IDE project files in java/jdeps.go.
547func (g *Module) IDEInfo(dpInfo *android.IdeInfo) {
548 dpInfo.Srcs = append(dpInfo.Srcs, g.Srcs().Strings()...)
549 for _, src := range g.properties.Srcs {
550 if strings.HasPrefix(src, ":") {
551 src = strings.Trim(src, ":")
552 dpInfo.Deps = append(dpInfo.Deps, src)
553 }
554 }
bralee1fbf4402020-05-21 10:11:59 +0800555 dpInfo.Paths = append(dpInfo.Paths, g.modulePaths...)
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700556}
557
Colin Crossa4ad2b02019-03-18 22:15:32 -0700558func (g *Module) AndroidMk() android.AndroidMkData {
559 return android.AndroidMkData{
Anton Hansson72f18492020-10-30 16:34:45 +0000560 Class: "ETC",
Colin Crossa4ad2b02019-03-18 22:15:32 -0700561 OutputFile: android.OptionalPathForPath(g.outputFiles[0]),
562 SubName: g.subName,
563 Extra: []android.AndroidMkExtraFunc{
564 func(w io.Writer, outputFile android.Path) {
Anton Hansson72f18492020-10-30 16:34:45 +0000565 fmt.Fprintln(w, "LOCAL_UNINSTALLABLE_MODULE := true")
Colin Crossa4ad2b02019-03-18 22:15:32 -0700566 },
567 },
568 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
569 android.WriteAndroidMkData(w, data)
570 if data.SubName != "" {
571 fmt.Fprintln(w, ".PHONY:", name)
572 fmt.Fprintln(w, name, ":", name+g.subName)
573 }
574 },
575 }
576}
577
Jiyong Park45bf82e2020-12-15 22:29:02 +0900578var _ android.ApexModule = (*Module)(nil)
579
580// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -0700581func (g *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
582 sdkVersion android.ApiLevel) error {
Jooyung Han749dc692020-04-15 11:03:39 +0900583 // Because generated outputs are checked by client modules(e.g. cc_library, ...)
584 // we can safely ignore the check here.
585 return nil
586}
587
Jeff Gaston437d23c2017-11-08 12:38:00 -0800588func generatorFactory(taskGenerator taskFunc, props ...interface{}) *Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700589 module := &Module{
Jeff Gaston437d23c2017-11-08 12:38:00 -0800590 taskGenerator: taskGenerator,
Colin Crossd350ecd2015-04-28 13:25:36 -0700591 }
592
Colin Cross36242852017-06-23 15:06:31 -0700593 module.AddProperties(props...)
594 module.AddProperties(&module.properties)
Colin Crossd350ecd2015-04-28 13:25:36 -0700595
Colin Cross7228ecd2019-11-18 16:00:16 -0800596 module.ImageInterface = noopImageInterface{}
597
Colin Cross36242852017-06-23 15:06:31 -0700598 return module
Colin Crossd350ecd2015-04-28 13:25:36 -0700599}
600
Colin Cross7228ecd2019-11-18 16:00:16 -0800601type noopImageInterface struct{}
602
603func (x noopImageInterface) ImageMutatorBegin(android.BaseModuleContext) {}
604func (x noopImageInterface) CoreVariantNeeded(android.BaseModuleContext) bool { return false }
Yifan Hong1b3348d2020-01-21 15:53:22 -0800605func (x noopImageInterface) RamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700606func (x noopImageInterface) VendorRamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Colin Cross7228ecd2019-11-18 16:00:16 -0800607func (x noopImageInterface) RecoveryVariantNeeded(android.BaseModuleContext) bool { return false }
608func (x noopImageInterface) ExtraImageVariations(ctx android.BaseModuleContext) []string { return nil }
609func (x noopImageInterface) SetImageVariation(ctx android.BaseModuleContext, variation string, module android.Module) {
610}
611
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700612func NewGenSrcs() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700613 properties := &genSrcsProperties{}
614
Colin Crossf1885962020-11-20 15:28:30 -0800615 // finalSubDir is the name of the subdirectory that output files will be generated into.
616 // It is used so that per-shard directories can be placed alongside it an then finally
617 // merged into it.
618 const finalSubDir = "gensrcs"
619
Colin Cross1a527682019-09-23 15:55:30 -0700620 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Colin Cross1a527682019-09-23 15:55:30 -0700621 shardSize := defaultShardSize
622 if s := properties.Shard_size; s != nil {
623 shardSize = int(*s)
624 }
Jeff Gaston437d23c2017-11-08 12:38:00 -0800625
Colin Crossf1885962020-11-20 15:28:30 -0800626 // gensrcs rules can easily hit command line limits by repeating the command for
627 // every input file. Shard the input files into groups.
Colin Cross1a527682019-09-23 15:55:30 -0700628 shards := android.ShardPaths(srcFiles, shardSize)
629 var generateTasks []generateTask
Colin Crossbaccf5b2018-02-21 14:07:48 -0800630
Colin Cross1a527682019-09-23 15:55:30 -0700631 for i, shard := range shards {
632 var commands []string
633 var outFiles android.WritablePaths
Colin Cross3ea4eb82020-11-24 13:07:27 -0800634 var commandDepFiles []string
Colin Cross1a527682019-09-23 15:55:30 -0700635 var copyTo android.WritablePaths
Colin Cross1a527682019-09-23 15:55:30 -0700636
Colin Crossf1885962020-11-20 15:28:30 -0800637 // When sharding is enabled (i.e. len(shards) > 1), the sbox rules for each
638 // shard will be write to their own directories and then be merged together
639 // into finalSubDir. If sharding is not enabled (i.e. len(shards) == 1),
640 // the sbox rule will write directly to finalSubDir.
641 genSubDir := finalSubDir
Colin Cross1a527682019-09-23 15:55:30 -0700642 if len(shards) > 1 {
Colin Crossf1885962020-11-20 15:28:30 -0800643 genSubDir = strconv.Itoa(i)
Jeff Gaston437d23c2017-11-08 12:38:00 -0800644 }
645
Colin Crossf1885962020-11-20 15:28:30 -0800646 genDir := android.PathForModuleGen(ctx, genSubDir)
Colin Crossf1a035e2020-11-16 17:32:30 -0800647 // TODO(ccross): this RuleBuilder is a hack to be able to call
648 // rule.Command().PathForOutput. Replace this with passing the rule into the
649 // generator.
Colin Crossba9e4032020-11-24 16:32:22 -0800650 rule := android.NewRuleBuilder(pctx, ctx).Sbox(genDir, nil).SandboxTools()
Jeff Gaston437d23c2017-11-08 12:38:00 -0800651
Colin Cross3ea4eb82020-11-24 13:07:27 -0800652 for _, in := range shard {
Colin Crossf1885962020-11-20 15:28:30 -0800653 outFile := android.GenPathWithExt(ctx, finalSubDir, in, String(properties.Output_extension))
654
655 // If sharding is enabled, then outFile is the path to the output file in
656 // the shard directory, and copyTo is the path to the output file in the
657 // final directory.
Colin Cross1a527682019-09-23 15:55:30 -0700658 if len(shards) > 1 {
Colin Crossf1885962020-11-20 15:28:30 -0800659 shardFile := android.GenPathWithExt(ctx, genSubDir, in, String(properties.Output_extension))
Colin Cross1a527682019-09-23 15:55:30 -0700660 copyTo = append(copyTo, outFile)
661 outFile = shardFile
662 }
663
664 outFiles = append(outFiles, outFile)
Colin Cross1a527682019-09-23 15:55:30 -0700665
Colin Crossf1885962020-11-20 15:28:30 -0800666 // pre-expand the command line to replace $in and $out with references to
667 // a single input and output file.
Colin Cross1a527682019-09-23 15:55:30 -0700668 command, err := android.Expand(rawCommand, func(name string) (string, error) {
669 switch name {
670 case "in":
671 return in.String(), nil
672 case "out":
Colin Crossf1a035e2020-11-16 17:32:30 -0800673 return rule.Command().PathForOutput(outFile), nil
Colin Cross3ea4eb82020-11-24 13:07:27 -0800674 case "depfile":
675 // Generate a depfile for each output file. Store the list for
676 // later in order to combine them all into a single depfile.
Colin Crossf1a035e2020-11-16 17:32:30 -0800677 depFile := rule.Command().PathForOutput(outFile.ReplaceExtension(ctx, "d"))
Colin Cross3ea4eb82020-11-24 13:07:27 -0800678 commandDepFiles = append(commandDepFiles, depFile)
679 return depFile, nil
Colin Cross1a527682019-09-23 15:55:30 -0700680 default:
681 return "$(" + name + ")", nil
682 }
683 })
684 if err != nil {
685 ctx.PropertyErrorf("cmd", err.Error())
686 }
687
688 // escape the command in case for example it contains '#', an odd number of '"', etc
689 command = fmt.Sprintf("bash -c %v", proptools.ShellEscape(command))
690 commands = append(commands, command)
691 }
692 fullCommand := strings.Join(commands, " && ")
693
Colin Cross3ea4eb82020-11-24 13:07:27 -0800694 var outputDepfile android.WritablePath
695 var extraTools android.Paths
696 if len(commandDepFiles) > 0 {
697 // Each command wrote to a depfile, but ninja can only handle one
698 // depfile per rule. Use the dep_fixer tool at the end of the
699 // command to combine all the depfiles into a single output depfile.
700 outputDepfile = android.PathForModuleGen(ctx, genSubDir, "gensrcs.d")
701 depFixerTool := ctx.Config().HostToolPath(ctx, "dep_fixer")
702 fullCommand += fmt.Sprintf(" && %s -o $(depfile) %s",
Colin Crossba9e4032020-11-24 16:32:22 -0800703 android.SboxPathForTool(ctx, depFixerTool),
704 strings.Join(commandDepFiles, " "))
Colin Cross3ea4eb82020-11-24 13:07:27 -0800705 extraTools = append(extraTools, depFixerTool)
706 }
707
Colin Cross1a527682019-09-23 15:55:30 -0700708 generateTasks = append(generateTasks, generateTask{
Colin Cross3ea4eb82020-11-24 13:07:27 -0800709 in: shard,
710 out: outFiles,
711 depFile: outputDepfile,
712 copyTo: copyTo,
713 genDir: genDir,
714 cmd: fullCommand,
715 shard: i,
716 shards: len(shards),
717 extraTools: extraTools,
Colin Cross1a527682019-09-23 15:55:30 -0700718 })
Jeff Gaston437d23c2017-11-08 12:38:00 -0800719 }
Colin Cross1a527682019-09-23 15:55:30 -0700720
721 return generateTasks
Colin Crossd350ecd2015-04-28 13:25:36 -0700722 }
723
Colin Cross1a527682019-09-23 15:55:30 -0700724 g := generatorFactory(taskGenerator, properties)
Colin Crossf1885962020-11-20 15:28:30 -0800725 g.subDir = finalSubDir
Colin Cross1a527682019-09-23 15:55:30 -0700726 return g
Colin Crossd350ecd2015-04-28 13:25:36 -0700727}
728
Colin Cross54190b32017-10-09 15:34:10 -0700729func GenSrcsFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700730 m := NewGenSrcs()
731 android.InitAndroidModule(m)
732 return m
733}
734
Colin Crossd350ecd2015-04-28 13:25:36 -0700735type genSrcsProperties struct {
Colin Cross7d5136f2015-05-11 13:39:40 -0700736 // extension that will be substituted for each output file
Nan Zhanga5e7cb42017-11-09 22:42:32 -0800737 Output_extension *string
Colin Cross1a527682019-09-23 15:55:30 -0700738
739 // maximum number of files that will be passed on a single command line.
740 Shard_size *int64
Colin Cross5049f022015-03-18 13:28:46 -0700741}
742
Evgenii Stepanovf47c90d2020-12-02 18:55:09 -0800743const defaultShardSize = 50
Colin Cross1a527682019-09-23 15:55:30 -0700744
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700745func NewGenRule() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700746 properties := &genRuleProperties{}
Colin Cross5049f022015-03-18 13:28:46 -0700747
Colin Cross1a527682019-09-23 15:55:30 -0700748 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700749 outs := make(android.WritablePaths, len(properties.Out))
Colin Cross3d680512020-11-13 16:23:53 -0800750 var depFile android.WritablePath
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700751 for i, out := range properties.Out {
Colin Cross3d680512020-11-13 16:23:53 -0800752 outPath := android.PathForModuleGen(ctx, out)
753 if i == 0 {
754 depFile = outPath.ReplaceExtension(ctx, "d")
755 }
756 outs[i] = outPath
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700757 }
Colin Cross1a527682019-09-23 15:55:30 -0700758 return []generateTask{{
Colin Cross3d680512020-11-13 16:23:53 -0800759 in: srcFiles,
760 out: outs,
761 depFile: depFile,
762 genDir: android.PathForModuleGen(ctx),
763 cmd: rawCommand,
Colin Cross1a527682019-09-23 15:55:30 -0700764 }}
Colin Cross5049f022015-03-18 13:28:46 -0700765 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700766
Jeff Gaston437d23c2017-11-08 12:38:00 -0800767 return generatorFactory(taskGenerator, properties)
Colin Cross5049f022015-03-18 13:28:46 -0700768}
769
Colin Cross54190b32017-10-09 15:34:10 -0700770func GenRuleFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700771 m := NewGenRule()
772 android.InitAndroidModule(m)
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800773 android.InitDefaultableModule(m)
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700774 return m
775}
776
Colin Crossd350ecd2015-04-28 13:25:36 -0700777type genRuleProperties struct {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700778 // names of the output files that will be generated
Colin Crossef354482018-10-23 11:27:50 -0700779 Out []string `android:"arch_variant"`
Colin Cross5049f022015-03-18 13:28:46 -0700780}
Nan Zhangea568a42017-11-08 21:20:04 -0800781
Jingwen Chen316e07c2020-12-14 09:09:52 -0500782type bazelGenruleAttributes struct {
783 Name *string
Liz Kammer356f7d42021-01-26 09:18:53 -0500784 Srcs bazel.LabelList
Jingwen Chen316e07c2020-12-14 09:09:52 -0500785 Outs []string
Liz Kammer356f7d42021-01-26 09:18:53 -0500786 Tools bazel.LabelList
Jingwen Chen316e07c2020-12-14 09:09:52 -0500787 Cmd string
788}
789
790type bazelGenrule struct {
791 android.BazelTargetModuleBase
792 bazelGenruleAttributes
793}
794
795func BazelGenruleFactory() android.Module {
796 module := &bazelGenrule{}
797 module.AddProperties(&module.bazelGenruleAttributes)
798 android.InitBazelTargetModule(module)
799 return module
800}
801
Jingwen Chena42d6412021-01-26 21:57:27 -0500802func GenruleBp2Build(ctx android.TopDownMutatorContext) {
Liz Kammer356f7d42021-01-26 09:18:53 -0500803 m, ok := ctx.Module().(*Module)
804 if !ok {
805 return
Jingwen Chen316e07c2020-12-14 09:09:52 -0500806 }
Liz Kammer356f7d42021-01-26 09:18:53 -0500807 name := "__bp2build__" + m.Name()
808 // Bazel only has the "tools" attribute.
809 tools := android.BazelLabelForModuleDeps(ctx, m.properties.Tools)
810 tool_files := android.BazelLabelForModuleSrc(ctx, m.properties.Tool_files)
811 tools.Append(tool_files)
812
813 srcs := android.BazelLabelForModuleSrc(ctx, m.properties.Srcs)
814
815 var allReplacements bazel.LabelList
816 allReplacements.Append(tools)
817 allReplacements.Append(srcs)
818
819 // Replace in and out variables with $< and $@
820 var cmd string
821 if m.properties.Cmd != nil {
822 cmd = strings.Replace(*m.properties.Cmd, "$(in)", "$(SRCS)", -1)
823 cmd = strings.Replace(cmd, "$(out)", "$(OUTS)", -1)
824 cmd = strings.Replace(cmd, "$(genDir)", "$(GENDIR)", -1)
825 if len(tools.Includes) > 0 {
826 cmd = strings.Replace(cmd, "$(location)", fmt.Sprintf("$(location %s)", tools.Includes[0].Label), -1)
827 cmd = strings.Replace(cmd, "$(locations)", fmt.Sprintf("$(locations %s)", tools.Includes[0].Label), -1)
828 }
829 for _, l := range allReplacements.Includes {
830 bpLoc := fmt.Sprintf("$(location %s)", l.Bp_text)
831 bpLocs := fmt.Sprintf("$(locations %s)", l.Bp_text)
832 bazelLoc := fmt.Sprintf("$(location %s)", l.Label)
833 bazelLocs := fmt.Sprintf("$(locations %s)", l.Label)
834 cmd = strings.Replace(cmd, bpLoc, bazelLoc, -1)
835 cmd = strings.Replace(cmd, bpLocs, bazelLocs, -1)
836 }
837 }
838
839 // The Out prop is not in an immediately accessible field
840 // in the Module struct, so use GetProperties and cast it
841 // to the known struct prop.
842 var outs []string
843 for _, propIntf := range m.GetProperties() {
844 if props, ok := propIntf.(*genRuleProperties); ok {
845 outs = props.Out
846 break
847 }
848 }
849
850 // Create the BazelTargetModule.
851 ctx.CreateModule(BazelGenruleFactory, &bazelGenruleAttributes{
852 Name: proptools.StringPtr(name),
853 Srcs: srcs,
854 Outs: outs,
855 Cmd: cmd,
856 Tools: tools,
857 }, &bazel.BazelTargetModuleProperties{
858 Rule_class: "genrule",
859 })
Jingwen Chen316e07c2020-12-14 09:09:52 -0500860}
861
862func (m *bazelGenrule) Name() string {
863 return m.BaseModuleName()
864}
865
866func (m *bazelGenrule) GenerateAndroidBuildActions(ctx android.ModuleContext) {}
867
Nan Zhangea568a42017-11-08 21:20:04 -0800868var Bool = proptools.Bool
869var String = proptools.String
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800870
871//
872// Defaults
873//
874type Defaults struct {
875 android.ModuleBase
876 android.DefaultsModuleBase
877}
878
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800879func defaultsFactory() android.Module {
880 return DefaultsFactory()
881}
882
883func DefaultsFactory(props ...interface{}) android.Module {
884 module := &Defaults{}
885
886 module.AddProperties(props...)
887 module.AddProperties(
888 &generatorProperties{},
889 &genRuleProperties{},
890 )
891
892 android.InitDefaultsModule(module)
893
894 return module
895}