blob: ddfb4596b7ddfc92c6b92ecb881385fcd3fb5e70 [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
Jingwen Chena42d6412021-01-26 21:57:27 -050050 android.RegisterBp2BuildMutator("genrule", GenruleBp2Build)
Colin Cross463a90e2015-06-17 14:20:06 -070051}
52
Colin Cross5049f022015-03-18 13:28:46 -070053var (
Colin Cross635c3b02016-05-18 15:37:25 -070054 pctx = android.NewPackageContext("android/soong/genrule")
Colin Cross1a527682019-09-23 15:55:30 -070055
Alex Humesky29e3bbe2020-11-20 21:30:13 -050056 // Used by gensrcs when there is more than 1 shard to merge the outputs
57 // of each shard into a zip file.
Colin Cross1a527682019-09-23 15:55:30 -070058 gensrcsMerge = pctx.AndroidStaticRule("gensrcsMerge", blueprint.RuleParams{
59 Command: "${soongZip} -o ${tmpZip} @${tmpZip}.rsp && ${zipSync} -d ${genDir} ${tmpZip}",
60 CommandDeps: []string{"${soongZip}", "${zipSync}"},
61 Rspfile: "${tmpZip}.rsp",
62 RspfileContent: "${zipArgs}",
63 }, "tmpZip", "genDir", "zipArgs")
Colin Cross5049f022015-03-18 13:28:46 -070064)
65
Jeff Gastonefc1b412017-03-29 17:29:06 -070066func init() {
Dan Willemsenddf504c2019-08-09 16:21:29 -070067 pctx.Import("android/soong/android")
Jeff Gastonefc1b412017-03-29 17:29:06 -070068 pctx.HostBinToolVariable("sboxCmd", "sbox")
Colin Cross1a527682019-09-23 15:55:30 -070069
70 pctx.HostBinToolVariable("soongZip", "soong_zip")
71 pctx.HostBinToolVariable("zipSync", "zipsync")
Jeff Gastonefc1b412017-03-29 17:29:06 -070072}
73
Colin Cross5049f022015-03-18 13:28:46 -070074type SourceFileGenerator interface {
Colin Cross635c3b02016-05-18 15:37:25 -070075 GeneratedSourceFiles() android.Paths
Colin Cross5ed99c62016-11-22 12:55:55 -080076 GeneratedHeaderDirs() android.Paths
Dan Willemsen9da9d492018-02-21 18:28:18 -080077 GeneratedDeps() android.Paths
Colin Cross5049f022015-03-18 13:28:46 -070078}
79
Colin Crossfe17f6f2019-03-28 19:30:56 -070080// Alias for android.HostToolProvider
81// Deprecated: use android.HostToolProvider instead.
Colin Crossd350ecd2015-04-28 13:25:36 -070082type HostToolProvider interface {
Colin Crossfe17f6f2019-03-28 19:30:56 -070083 android.HostToolProvider
Colin Crossd350ecd2015-04-28 13:25:36 -070084}
Colin Cross5049f022015-03-18 13:28:46 -070085
Dan Willemsend6ba0d52017-09-13 15:46:47 -070086type hostToolDependencyTag struct {
87 blueprint.BaseDependencyTag
Colin Cross08f15ab2018-10-04 23:29:14 -070088 label string
Dan Willemsend6ba0d52017-09-13 15:46:47 -070089}
Colin Cross7d5136f2015-05-11 13:39:40 -070090type generatorProperties struct {
Jeff Gastonefc1b412017-03-29 17:29:06 -070091 // The command to run on one or more input files. Cmd supports substitution of a few variables
Jeff Gastonefc1b412017-03-29 17:29:06 -070092 //
93 // Available variables for substitution:
94 //
Colin Cross2296f5b2017-10-17 21:38:14 -070095 // $(location): the path to the first entry in tools or tool_files
Colin Cross08f15ab2018-10-04 23:29:14 -070096 // $(location <label>): the path to the tool, tool_file, input or output with name <label>
Colin Cross2296f5b2017-10-17 21:38:14 -070097 // $(in): one or more input files
98 // $(out): a single output file
99 // $(depfile): a file to which dependencies will be written, if the depfile property is set to true
100 // $(genDir): the sandbox directory for this tool; contains $(out)
101 // $$: a literal $
Nan Zhangea568a42017-11-08 21:20:04 -0800102 Cmd *string
Colin Cross7d5136f2015-05-11 13:39:40 -0700103
Colin Cross33bfb0a2016-11-21 17:23:08 -0800104 // Enable reading a file containing dependencies in gcc format after the command completes
Nan Zhangea568a42017-11-08 21:20:04 -0800105 Depfile *bool
Colin Cross33bfb0a2016-11-21 17:23:08 -0800106
Colin Cross6f080df2016-11-04 15:32:58 -0700107 // name of the modules (if any) that produces the host executable. Leave empty for
Colin Cross7d5136f2015-05-11 13:39:40 -0700108 // prebuilts or scripts that do not need a module to build them.
Colin Cross6f080df2016-11-04 15:32:58 -0700109 Tools []string
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700110
111 // Local file that is used as the tool
Colin Cross27b922f2019-03-04 22:35:41 -0800112 Tool_files []string `android:"path"`
Colin Cross5ed99c62016-11-22 12:55:55 -0800113
114 // List of directories to export generated headers from
115 Export_include_dirs []string
Colin Cross708c4242017-01-13 18:05:49 -0800116
117 // list of input files
Colin Cross27b922f2019-03-04 22:35:41 -0800118 Srcs []string `android:"path,arch_variant"`
Dan Willemseneefa0262018-11-17 14:01:18 -0800119
120 // input files to exclude
Colin Cross27b922f2019-03-04 22:35:41 -0800121 Exclude_srcs []string `android:"path,arch_variant"`
Colin Cross7d5136f2015-05-11 13:39:40 -0700122
Jingwen Chen30f5aaa2020-11-19 05:38:02 -0500123 // Properties for Bazel migration purposes.
124 bazel.Properties
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400125}
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500126
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700127type Module struct {
Colin Cross635c3b02016-05-18 15:37:25 -0700128 android.ModuleBase
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800129 android.DefaultableModuleBase
Jiyong Parkfc752ca2019-06-12 13:27:29 +0900130 android.ApexModuleBase
Colin Crossd350ecd2015-04-28 13:25:36 -0700131
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700132 // For other packages to make their own genrules with extra
133 // properties
134 Extra interface{}
Colin Cross7228ecd2019-11-18 16:00:16 -0800135 android.ImageInterface
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700136
Colin Cross7d5136f2015-05-11 13:39:40 -0700137 properties generatorProperties
Colin Crossd350ecd2015-04-28 13:25:36 -0700138
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500139 // For the different tasks that genrule and gensrc generate. genrule will
140 // generate 1 task, and gensrc will generate 1 or more tasks based on the
141 // number of shards the input files are sharded into.
Jeff Gaston437d23c2017-11-08 12:38:00 -0800142 taskGenerator taskFunc
Colin Crossd350ecd2015-04-28 13:25:36 -0700143
Colin Cross1a527682019-09-23 15:55:30 -0700144 rule blueprint.Rule
145 rawCommands []string
Colin Crossd350ecd2015-04-28 13:25:36 -0700146
Colin Cross5ed99c62016-11-22 12:55:55 -0800147 exportedIncludeDirs android.Paths
Dan Willemsenb40aab62016-04-20 14:21:14 -0700148
Colin Cross635c3b02016-05-18 15:37:25 -0700149 outputFiles android.Paths
Dan Willemsen9da9d492018-02-21 18:28:18 -0800150 outputDeps android.Paths
Colin Crossa4ad2b02019-03-18 22:15:32 -0700151
152 subName string
Colin Cross1a527682019-09-23 15:55:30 -0700153 subDir string
bralee1fbf4402020-05-21 10:11:59 +0800154
155 // Collect the module directory for IDE info in java/jdeps.go.
156 modulePaths []string
Colin Crossd350ecd2015-04-28 13:25:36 -0700157}
158
Colin Cross1a527682019-09-23 15:55:30 -0700159type taskFunc func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask
Colin Crossd350ecd2015-04-28 13:25:36 -0700160
161type generateTask struct {
Colin Cross3ea4eb82020-11-24 13:07:27 -0800162 in android.Paths
163 out android.WritablePaths
164 depFile android.WritablePath
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500165 copyTo android.WritablePaths // For gensrcs to set on gensrcsMerge rule.
Colin Cross3ea4eb82020-11-24 13:07:27 -0800166 genDir android.WritablePath
167 extraTools android.Paths // dependencies on tools used by the generator
168
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500169 cmd string
170 // For gensrsc sharding.
Colin Cross3ea4eb82020-11-24 13:07:27 -0800171 shard int
172 shards int
Colin Crossd350ecd2015-04-28 13:25:36 -0700173}
174
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700175func (g *Module) GeneratedSourceFiles() android.Paths {
Colin Crossd350ecd2015-04-28 13:25:36 -0700176 return g.outputFiles
177}
178
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700179func (g *Module) Srcs() android.Paths {
Nan Zhange42777a2018-03-27 16:19:42 -0700180 return append(android.Paths{}, g.outputFiles...)
Colin Cross068e0fe2016-12-13 15:23:47 -0800181}
182
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700183func (g *Module) GeneratedHeaderDirs() android.Paths {
Colin Cross5ed99c62016-11-22 12:55:55 -0800184 return g.exportedIncludeDirs
Dan Willemsenb40aab62016-04-20 14:21:14 -0700185}
186
Dan Willemsen9da9d492018-02-21 18:28:18 -0800187func (g *Module) GeneratedDeps() android.Paths {
188 return g.outputDeps
189}
190
Martin Stjernholm710ec3a2020-01-16 15:12:04 +0000191func toolDepsMutator(ctx android.BottomUpMutatorContext) {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700192 if g, ok := ctx.Module().(*Module); ok {
Colin Cross08f15ab2018-10-04 23:29:14 -0700193 for _, tool := range g.properties.Tools {
194 tag := hostToolDependencyTag{label: tool}
195 if m := android.SrcIsModule(tool); m != "" {
196 tool = m
197 }
Colin Cross0f7d2ef2019-10-16 11:03:10 -0700198 ctx.AddFarVariationDependencies(ctx.Config().BuildOSTarget.Variations(), tag, tool)
Colin Cross6362e272015-10-29 15:25:03 -0700199 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700200 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700201}
202
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400203// Returns true if information was available from Bazel, false if bazel invocation still needs to occur.
204func (c *Module) generateBazelBuildActions(ctx android.ModuleContext, label string) bool {
205 bazelCtx := ctx.Config().BazelContext
206 filePaths, ok := bazelCtx.GetAllFiles(label)
207 if ok {
208 var bazelOutputFiles android.Paths
209 for _, bazelOutputFile := range filePaths {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500210 bazelOutputFiles = append(bazelOutputFiles, android.PathForBazelOut(ctx, bazelOutputFile))
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400211 }
212 c.outputFiles = bazelOutputFiles
213 c.outputDeps = bazelOutputFiles
214 }
215 return ok
216}
Colin Crossf1885962020-11-20 15:28:30 -0800217
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700218func (g *Module) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Colin Crossa4ad2b02019-03-18 22:15:32 -0700219 g.subName = ctx.ModuleSubDir()
220
bralee1fbf4402020-05-21 10:11:59 +0800221 // Collect the module directory for IDE info in java/jdeps.go.
222 g.modulePaths = append(g.modulePaths, ctx.ModuleDir())
223
Colin Cross5ed99c62016-11-22 12:55:55 -0800224 if len(g.properties.Export_include_dirs) > 0 {
225 for _, dir := range g.properties.Export_include_dirs {
226 g.exportedIncludeDirs = append(g.exportedIncludeDirs,
Colin Cross1a527682019-09-23 15:55:30 -0700227 android.PathForModuleGen(ctx, g.subDir, ctx.ModuleDir(), dir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800228 }
229 } else {
Colin Cross1a527682019-09-23 15:55:30 -0700230 g.exportedIncludeDirs = append(g.exportedIncludeDirs, android.PathForModuleGen(ctx, g.subDir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800231 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700232
Colin Cross08f15ab2018-10-04 23:29:14 -0700233 locationLabels := map[string][]string{}
234 firstLabel := ""
235
236 addLocationLabel := func(label string, paths []string) {
237 if firstLabel == "" {
238 firstLabel = label
239 }
240 if _, exists := locationLabels[label]; !exists {
241 locationLabels[label] = paths
242 } else {
243 ctx.ModuleErrorf("multiple labels for %q, %q and %q",
244 label, strings.Join(locationLabels[label], " "), strings.Join(paths, " "))
245 }
246 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700247
Colin Crossba9e4032020-11-24 16:32:22 -0800248 var tools android.Paths
249 var packagedTools []android.PackagingSpec
Colin Cross6f080df2016-11-04 15:32:58 -0700250 if len(g.properties.Tools) > 0 {
Colin Crossba71a3f2019-03-18 12:12:48 -0700251 seenTools := make(map[string]bool)
252
Colin Cross35143d02017-11-16 00:11:20 -0800253 ctx.VisitDirectDepsBlueprint(func(module blueprint.Module) {
Colin Cross08f15ab2018-10-04 23:29:14 -0700254 switch tag := ctx.OtherModuleDependencyTag(module).(type) {
255 case hostToolDependencyTag:
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700256 tool := ctx.OtherModuleName(module)
257
Colin Crossba9e4032020-11-24 16:32:22 -0800258 switch t := module.(type) {
259 case android.HostToolProvider:
260 // A HostToolProvider provides the path to a tool, which will be copied
261 // into the sandbox.
Colin Cross35143d02017-11-16 00:11:20 -0800262 if !t.(android.Module).Enabled() {
Colin Cross6510f912017-11-29 00:27:14 -0800263 if ctx.Config().AllowMissingDependencies() {
Colin Cross35143d02017-11-16 00:11:20 -0800264 ctx.AddMissingDependencies([]string{tool})
265 } else {
266 ctx.ModuleErrorf("depends on disabled module %q", tool)
267 }
Colin Crossba9e4032020-11-24 16:32:22 -0800268 return
Colin Cross35143d02017-11-16 00:11:20 -0800269 }
Colin Crossba9e4032020-11-24 16:32:22 -0800270 path := t.HostToolPath()
271 if !path.Valid() {
272 ctx.ModuleErrorf("host tool %q missing output file", tool)
273 return
274 }
275 if specs := t.TransitivePackagingSpecs(); specs != nil {
276 // If the HostToolProvider has PackgingSpecs, which are definitions of the
277 // required relative locations of the tool and its dependencies, use those
278 // instead. They will be copied to those relative locations in the sbox
279 // sandbox.
280 packagedTools = append(packagedTools, specs...)
281 // Assume that the first PackagingSpec of the module is the tool.
282 addLocationLabel(tag.label, []string{android.SboxPathForPackagedTool(specs[0])})
283 } else {
284 tools = append(tools, path.Path())
285 addLocationLabel(tag.label, []string{android.SboxPathForTool(ctx, path.Path())})
286 }
287 case bootstrap.GoBinaryTool:
288 // A GoBinaryTool provides the install path to a tool, which will be copied.
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700289 if s, err := filepath.Rel(android.PathForOutput(ctx).String(), t.InstallPath()); err == nil {
Colin Crossba9e4032020-11-24 16:32:22 -0800290 toolPath := android.PathForOutput(ctx, s)
291 tools = append(tools, toolPath)
292 addLocationLabel(tag.label, []string{android.SboxPathForTool(ctx, toolPath)})
Colin Cross6f080df2016-11-04 15:32:58 -0700293 } else {
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700294 ctx.ModuleErrorf("cannot find path for %q: %v", tool, err)
Colin Crossba9e4032020-11-24 16:32:22 -0800295 return
Colin Cross6f080df2016-11-04 15:32:58 -0700296 }
Colin Crossba9e4032020-11-24 16:32:22 -0800297 default:
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700298 ctx.ModuleErrorf("%q is not a host tool provider", tool)
Colin Crossba9e4032020-11-24 16:32:22 -0800299 return
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700300 }
301
Colin Crossba9e4032020-11-24 16:32:22 -0800302 seenTools[tag.label] = true
Colin Crossd350ecd2015-04-28 13:25:36 -0700303 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700304 })
Colin Crossba71a3f2019-03-18 12:12:48 -0700305
306 // If AllowMissingDependencies is enabled, the build will not have stopped when
307 // AddFarVariationDependencies was called on a missing tool, which will result in nonsensical
Liz Kammer20ebfb42020-07-28 11:32:07 -0700308 // "cmd: unknown location label ..." errors later. Add a placeholder file to the local label.
309 // The command that uses this placeholder file will never be executed because the rule will be
310 // replaced with an android.Error rule reporting the missing dependencies.
Colin Crossba71a3f2019-03-18 12:12:48 -0700311 if ctx.Config().AllowMissingDependencies() {
312 for _, tool := range g.properties.Tools {
313 if !seenTools[tool] {
314 addLocationLabel(tool, []string{"***missing tool " + tool + "***"})
315 }
316 }
317 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700318 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700319
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700320 if ctx.Failed() {
321 return
322 }
323
Colin Cross08f15ab2018-10-04 23:29:14 -0700324 for _, toolFile := range g.properties.Tool_files {
Colin Cross8a497952019-03-05 22:25:09 -0800325 paths := android.PathsForModuleSrc(ctx, []string{toolFile})
Colin Crossba9e4032020-11-24 16:32:22 -0800326 tools = append(tools, paths...)
327 var sandboxPaths []string
328 for _, path := range paths {
329 sandboxPaths = append(sandboxPaths, android.SboxPathForTool(ctx, path))
330 }
331 addLocationLabel(toolFile, sandboxPaths)
Colin Cross08f15ab2018-10-04 23:29:14 -0700332 }
333
334 var srcFiles android.Paths
335 for _, in := range g.properties.Srcs {
Colin Crossba71a3f2019-03-18 12:12:48 -0700336 paths, missingDeps := android.PathsAndMissingDepsForModuleSrcExcludes(ctx, []string{in}, g.properties.Exclude_srcs)
337 if len(missingDeps) > 0 {
338 if !ctx.Config().AllowMissingDependencies() {
339 panic(fmt.Errorf("should never get here, the missing dependencies %q should have been reported in DepsMutator",
340 missingDeps))
341 }
342
343 // If AllowMissingDependencies is enabled, the build will not have stopped when
344 // the dependency was added on a missing SourceFileProducer module, which will result in nonsensical
Liz Kammer20ebfb42020-07-28 11:32:07 -0700345 // "cmd: label ":..." has no files" errors later. Add a placeholder file to the local label.
346 // The command that uses this placeholder file will never be executed because the rule will be
347 // replaced with an android.Error rule reporting the missing dependencies.
Colin Crossba71a3f2019-03-18 12:12:48 -0700348 ctx.AddMissingDependencies(missingDeps)
349 addLocationLabel(in, []string{"***missing srcs " + in + "***"})
350 } else {
351 srcFiles = append(srcFiles, paths...)
352 addLocationLabel(in, paths.Strings())
353 }
Colin Cross08f15ab2018-10-04 23:29:14 -0700354 }
355
Colin Cross1a527682019-09-23 15:55:30 -0700356 var copyFrom android.Paths
357 var outputFiles android.WritablePaths
358 var zipArgs strings.Builder
Colin Cross08f15ab2018-10-04 23:29:14 -0700359
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500360 // Generate tasks, either from genrule or gensrcs.
Colin Cross1a527682019-09-23 15:55:30 -0700361 for _, task := range g.taskGenerator(ctx, String(g.properties.Cmd), srcFiles) {
Colin Cross3d680512020-11-13 16:23:53 -0800362 if len(task.out) == 0 {
363 ctx.ModuleErrorf("must have at least one output file")
364 return
Colin Cross85a2e892018-07-09 09:45:06 -0700365 }
366
Colin Crossf1a035e2020-11-16 17:32:30 -0800367 // Pick a unique path outside the task.genDir for the sbox manifest textproto,
368 // a unique rule name, and the user-visible description.
369 manifestName := "genrule.sbox.textproto"
370 desc := "generate"
371 name := "generator"
372 if task.shards > 0 {
373 manifestName = "genrule_" + strconv.Itoa(task.shard) + ".sbox.textproto"
374 desc += " " + strconv.Itoa(task.shard)
375 name += strconv.Itoa(task.shard)
376 } else if len(task.out) == 1 {
377 desc += " " + task.out[0].Base()
378 }
379
380 manifestPath := android.PathForModuleOut(ctx, manifestName)
381
382 // Use a RuleBuilder to create a rule that runs the command inside an sbox sandbox.
Colin Crossba9e4032020-11-24 16:32:22 -0800383 rule := android.NewRuleBuilder(pctx, ctx).Sbox(task.genDir, manifestPath).SandboxTools()
Colin Crossf1a035e2020-11-16 17:32:30 -0800384 cmd := rule.Command()
385
Colin Cross3d680512020-11-13 16:23:53 -0800386 for _, out := range task.out {
Colin Crossf1a035e2020-11-16 17:32:30 -0800387 addLocationLabel(out.Rel(), []string{cmd.PathForOutput(out)})
Colin Cross3d680512020-11-13 16:23:53 -0800388 }
389
Colin Cross1a527682019-09-23 15:55:30 -0700390 referencedDepfile := false
391
Colin Cross3d680512020-11-13 16:23:53 -0800392 rawCommand, err := android.Expand(task.cmd, func(name string) (string, error) {
Colin Cross1a527682019-09-23 15:55:30 -0700393 // report the error directly without returning an error to android.Expand to catch multiple errors in a
394 // single run
Colin Cross3d680512020-11-13 16:23:53 -0800395 reportError := func(fmt string, args ...interface{}) (string, error) {
Colin Cross1a527682019-09-23 15:55:30 -0700396 ctx.PropertyErrorf("cmd", fmt, args...)
Colin Cross3d680512020-11-13 16:23:53 -0800397 return "SOONG_ERROR", nil
Colin Cross6f080df2016-11-04 15:32:58 -0700398 }
Colin Cross1a527682019-09-23 15:55:30 -0700399
400 switch name {
401 case "location":
402 if len(g.properties.Tools) == 0 && len(g.properties.Tool_files) == 0 {
403 return reportError("at least one `tools` or `tool_files` is required if $(location) is used")
Colin Cross6f080df2016-11-04 15:32:58 -0700404 }
Colin Cross1a527682019-09-23 15:55:30 -0700405 paths := locationLabels[firstLabel]
406 if len(paths) == 0 {
407 return reportError("default label %q has no files", firstLabel)
408 } else if len(paths) > 1 {
409 return reportError("default label %q has multiple files, use $(locations %s) to reference it",
410 firstLabel, firstLabel)
Colin Cross08f15ab2018-10-04 23:29:14 -0700411 }
Colin Cross3d680512020-11-13 16:23:53 -0800412 return locationLabels[firstLabel][0], nil
Colin Cross1a527682019-09-23 15:55:30 -0700413 case "in":
Colin Cross3d680512020-11-13 16:23:53 -0800414 return strings.Join(srcFiles.Strings(), " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700415 case "out":
Colin Cross3d680512020-11-13 16:23:53 -0800416 var sandboxOuts []string
417 for _, out := range task.out {
Colin Crossf1a035e2020-11-16 17:32:30 -0800418 sandboxOuts = append(sandboxOuts, cmd.PathForOutput(out))
Colin Cross3d680512020-11-13 16:23:53 -0800419 }
420 return strings.Join(sandboxOuts, " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700421 case "depfile":
422 referencedDepfile = true
423 if !Bool(g.properties.Depfile) {
424 return reportError("$(depfile) used without depfile property")
425 }
Colin Cross3d680512020-11-13 16:23:53 -0800426 return "__SBOX_DEPFILE__", nil
Colin Cross1a527682019-09-23 15:55:30 -0700427 case "genDir":
Colin Crossf1a035e2020-11-16 17:32:30 -0800428 return cmd.PathForOutput(task.genDir), nil
Colin Cross1a527682019-09-23 15:55:30 -0700429 default:
430 if strings.HasPrefix(name, "location ") {
431 label := strings.TrimSpace(strings.TrimPrefix(name, "location "))
432 if paths, ok := locationLabels[label]; ok {
433 if len(paths) == 0 {
434 return reportError("label %q has no files", label)
435 } else if len(paths) > 1 {
436 return reportError("label %q has multiple files, use $(locations %s) to reference it",
437 label, label)
438 }
Colin Cross3d680512020-11-13 16:23:53 -0800439 return paths[0], nil
Colin Cross1a527682019-09-23 15:55:30 -0700440 } else {
441 return reportError("unknown location label %q", label)
442 }
443 } else if strings.HasPrefix(name, "locations ") {
444 label := strings.TrimSpace(strings.TrimPrefix(name, "locations "))
445 if paths, ok := locationLabels[label]; ok {
446 if len(paths) == 0 {
447 return reportError("label %q has no files", label)
448 }
Colin Cross3d680512020-11-13 16:23:53 -0800449 return strings.Join(paths, " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700450 } else {
451 return reportError("unknown locations label %q", label)
452 }
453 } else {
454 return reportError("unknown variable '$(%s)'", name)
455 }
Colin Cross6f080df2016-11-04 15:32:58 -0700456 }
Colin Cross1a527682019-09-23 15:55:30 -0700457 })
458
459 if err != nil {
460 ctx.PropertyErrorf("cmd", "%s", err.Error())
461 return
Colin Cross6f080df2016-11-04 15:32:58 -0700462 }
Colin Cross6f080df2016-11-04 15:32:58 -0700463
Colin Cross1a527682019-09-23 15:55:30 -0700464 if Bool(g.properties.Depfile) && !referencedDepfile {
465 ctx.PropertyErrorf("cmd", "specified depfile=true but did not include a reference to '${depfile}' in cmd")
466 return
467 }
Colin Cross1a527682019-09-23 15:55:30 -0700468 g.rawCommands = append(g.rawCommands, rawCommand)
Bill Peckhamc087be12020-02-13 15:55:10 -0800469
Colin Cross3d680512020-11-13 16:23:53 -0800470 cmd.Text(rawCommand)
471 cmd.ImplicitOutputs(task.out)
472 cmd.Implicits(task.in)
Colin Crossba9e4032020-11-24 16:32:22 -0800473 cmd.ImplicitTools(tools)
474 cmd.ImplicitTools(task.extraTools)
475 cmd.ImplicitPackagedTools(packagedTools)
Colin Cross3d680512020-11-13 16:23:53 -0800476 if Bool(g.properties.Depfile) {
477 cmd.ImplicitDepFile(task.depFile)
478 }
479
480 // Create the rule to run the genrule command inside sbox.
Colin Crossf1a035e2020-11-16 17:32:30 -0800481 rule.Build(name, desc)
Colin Cross1a527682019-09-23 15:55:30 -0700482
483 if len(task.copyTo) > 0 {
Colin Cross3d680512020-11-13 16:23:53 -0800484 // If copyTo is set, multiple shards need to be copied into a single directory.
485 // task.out contains the per-shard paths, and copyTo contains the corresponding
486 // final path. The files need to be copied into the final directory by a
487 // single rule so it can remove the directory before it starts to ensure no
488 // old files remain. zipsync already does this, so build up zipArgs that
489 // zip all the per-shard directories into a single zip.
Colin Cross1a527682019-09-23 15:55:30 -0700490 outputFiles = append(outputFiles, task.copyTo...)
491 copyFrom = append(copyFrom, task.out.Paths()...)
492 zipArgs.WriteString(" -C " + task.genDir.String())
493 zipArgs.WriteString(android.JoinWithPrefix(task.out.Strings(), " -f "))
494 } else {
495 outputFiles = append(outputFiles, task.out...)
496 }
Colin Cross6f080df2016-11-04 15:32:58 -0700497 }
498
Colin Cross1a527682019-09-23 15:55:30 -0700499 if len(copyFrom) > 0 {
Colin Cross3d680512020-11-13 16:23:53 -0800500 // Create a rule that zips all the per-shard directories into a single zip and then
501 // uses zipsync to unzip it into the final directory.
Colin Cross1a527682019-09-23 15:55:30 -0700502 ctx.Build(pctx, android.BuildParams{
Colin Crossf1885962020-11-20 15:28:30 -0800503 Rule: gensrcsMerge,
504 Implicits: copyFrom,
505 Outputs: outputFiles,
506 Description: "merge shards",
Colin Cross1a527682019-09-23 15:55:30 -0700507 Args: map[string]string{
508 "zipArgs": zipArgs.String(),
509 "tmpZip": android.PathForModuleGen(ctx, g.subDir+".zip").String(),
510 "genDir": android.PathForModuleGen(ctx, g.subDir).String(),
511 },
512 })
Colin Cross85a2e892018-07-09 09:45:06 -0700513 }
514
Colin Cross1a527682019-09-23 15:55:30 -0700515 g.outputFiles = outputFiles.Paths()
Jeff Gastonefc1b412017-03-29 17:29:06 -0700516
Chris Parsonsaa8be052020-10-14 16:22:37 -0400517 bazelModuleLabel := g.properties.Bazel_module.Label
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400518 bazelActionsUsed := false
519 if ctx.Config().BazelContext.BazelEnabled() && len(bazelModuleLabel) > 0 {
520 bazelActionsUsed = g.generateBazelBuildActions(ctx, bazelModuleLabel)
Jeff Gaston02a684b2017-10-27 14:59:27 -0700521 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400522 if !bazelActionsUsed {
523 // For <= 6 outputs, just embed those directly in the users. Right now, that covers >90% of
524 // the genrules on AOSP. That will make things simpler to look at the graph in the common
525 // case. For larger sets of outputs, inject a phony target in between to limit ninja file
526 // growth.
527 if len(g.outputFiles) <= 6 {
528 g.outputDeps = g.outputFiles
529 } else {
530 phonyFile := android.PathForModuleGen(ctx, "genrule-phony")
531 ctx.Build(pctx, android.BuildParams{
532 Rule: blueprint.Phony,
533 Output: phonyFile,
534 Inputs: g.outputFiles,
535 })
536 g.outputDeps = android.Paths{phonyFile}
537 }
538 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700539}
Colin Crossd350ecd2015-04-28 13:25:36 -0700540
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700541// Collect information for opening IDE project files in java/jdeps.go.
542func (g *Module) IDEInfo(dpInfo *android.IdeInfo) {
543 dpInfo.Srcs = append(dpInfo.Srcs, g.Srcs().Strings()...)
544 for _, src := range g.properties.Srcs {
545 if strings.HasPrefix(src, ":") {
546 src = strings.Trim(src, ":")
547 dpInfo.Deps = append(dpInfo.Deps, src)
548 }
549 }
bralee1fbf4402020-05-21 10:11:59 +0800550 dpInfo.Paths = append(dpInfo.Paths, g.modulePaths...)
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700551}
552
Colin Crossa4ad2b02019-03-18 22:15:32 -0700553func (g *Module) AndroidMk() android.AndroidMkData {
554 return android.AndroidMkData{
Anton Hansson72f18492020-10-30 16:34:45 +0000555 Class: "ETC",
Colin Crossa4ad2b02019-03-18 22:15:32 -0700556 OutputFile: android.OptionalPathForPath(g.outputFiles[0]),
557 SubName: g.subName,
558 Extra: []android.AndroidMkExtraFunc{
559 func(w io.Writer, outputFile android.Path) {
Anton Hansson72f18492020-10-30 16:34:45 +0000560 fmt.Fprintln(w, "LOCAL_UNINSTALLABLE_MODULE := true")
Colin Crossa4ad2b02019-03-18 22:15:32 -0700561 },
562 },
563 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
564 android.WriteAndroidMkData(w, data)
565 if data.SubName != "" {
566 fmt.Fprintln(w, ".PHONY:", name)
567 fmt.Fprintln(w, name, ":", name+g.subName)
568 }
569 },
570 }
571}
572
Jiyong Park45bf82e2020-12-15 22:29:02 +0900573var _ android.ApexModule = (*Module)(nil)
574
575// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -0700576func (g *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
577 sdkVersion android.ApiLevel) error {
Jooyung Han749dc692020-04-15 11:03:39 +0900578 // Because generated outputs are checked by client modules(e.g. cc_library, ...)
579 // we can safely ignore the check here.
580 return nil
581}
582
Jeff Gaston437d23c2017-11-08 12:38:00 -0800583func generatorFactory(taskGenerator taskFunc, props ...interface{}) *Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700584 module := &Module{
Jeff Gaston437d23c2017-11-08 12:38:00 -0800585 taskGenerator: taskGenerator,
Colin Crossd350ecd2015-04-28 13:25:36 -0700586 }
587
Colin Cross36242852017-06-23 15:06:31 -0700588 module.AddProperties(props...)
589 module.AddProperties(&module.properties)
Colin Crossd350ecd2015-04-28 13:25:36 -0700590
Colin Cross7228ecd2019-11-18 16:00:16 -0800591 module.ImageInterface = noopImageInterface{}
592
Colin Cross36242852017-06-23 15:06:31 -0700593 return module
Colin Crossd350ecd2015-04-28 13:25:36 -0700594}
595
Colin Cross7228ecd2019-11-18 16:00:16 -0800596type noopImageInterface struct{}
597
598func (x noopImageInterface) ImageMutatorBegin(android.BaseModuleContext) {}
599func (x noopImageInterface) CoreVariantNeeded(android.BaseModuleContext) bool { return false }
Yifan Hong1b3348d2020-01-21 15:53:22 -0800600func (x noopImageInterface) RamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700601func (x noopImageInterface) VendorRamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Colin Cross7228ecd2019-11-18 16:00:16 -0800602func (x noopImageInterface) RecoveryVariantNeeded(android.BaseModuleContext) bool { return false }
603func (x noopImageInterface) ExtraImageVariations(ctx android.BaseModuleContext) []string { return nil }
604func (x noopImageInterface) SetImageVariation(ctx android.BaseModuleContext, variation string, module android.Module) {
605}
606
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700607func NewGenSrcs() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700608 properties := &genSrcsProperties{}
609
Colin Crossf1885962020-11-20 15:28:30 -0800610 // finalSubDir is the name of the subdirectory that output files will be generated into.
611 // It is used so that per-shard directories can be placed alongside it an then finally
612 // merged into it.
613 const finalSubDir = "gensrcs"
614
Colin Cross1a527682019-09-23 15:55:30 -0700615 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Colin Cross1a527682019-09-23 15:55:30 -0700616 shardSize := defaultShardSize
617 if s := properties.Shard_size; s != nil {
618 shardSize = int(*s)
619 }
Jeff Gaston437d23c2017-11-08 12:38:00 -0800620
Colin Crossf1885962020-11-20 15:28:30 -0800621 // gensrcs rules can easily hit command line limits by repeating the command for
622 // every input file. Shard the input files into groups.
Colin Cross1a527682019-09-23 15:55:30 -0700623 shards := android.ShardPaths(srcFiles, shardSize)
624 var generateTasks []generateTask
Colin Crossbaccf5b2018-02-21 14:07:48 -0800625
Colin Cross1a527682019-09-23 15:55:30 -0700626 for i, shard := range shards {
627 var commands []string
628 var outFiles android.WritablePaths
Colin Cross3ea4eb82020-11-24 13:07:27 -0800629 var commandDepFiles []string
Colin Cross1a527682019-09-23 15:55:30 -0700630 var copyTo android.WritablePaths
Colin Cross1a527682019-09-23 15:55:30 -0700631
Colin Crossf1885962020-11-20 15:28:30 -0800632 // When sharding is enabled (i.e. len(shards) > 1), the sbox rules for each
633 // shard will be write to their own directories and then be merged together
634 // into finalSubDir. If sharding is not enabled (i.e. len(shards) == 1),
635 // the sbox rule will write directly to finalSubDir.
636 genSubDir := finalSubDir
Colin Cross1a527682019-09-23 15:55:30 -0700637 if len(shards) > 1 {
Colin Crossf1885962020-11-20 15:28:30 -0800638 genSubDir = strconv.Itoa(i)
Jeff Gaston437d23c2017-11-08 12:38:00 -0800639 }
640
Colin Crossf1885962020-11-20 15:28:30 -0800641 genDir := android.PathForModuleGen(ctx, genSubDir)
Colin Crossf1a035e2020-11-16 17:32:30 -0800642 // TODO(ccross): this RuleBuilder is a hack to be able to call
643 // rule.Command().PathForOutput. Replace this with passing the rule into the
644 // generator.
Colin Crossba9e4032020-11-24 16:32:22 -0800645 rule := android.NewRuleBuilder(pctx, ctx).Sbox(genDir, nil).SandboxTools()
Jeff Gaston437d23c2017-11-08 12:38:00 -0800646
Colin Cross3ea4eb82020-11-24 13:07:27 -0800647 for _, in := range shard {
Colin Crossf1885962020-11-20 15:28:30 -0800648 outFile := android.GenPathWithExt(ctx, finalSubDir, in, String(properties.Output_extension))
649
650 // If sharding is enabled, then outFile is the path to the output file in
651 // the shard directory, and copyTo is the path to the output file in the
652 // final directory.
Colin Cross1a527682019-09-23 15:55:30 -0700653 if len(shards) > 1 {
Colin Crossf1885962020-11-20 15:28:30 -0800654 shardFile := android.GenPathWithExt(ctx, genSubDir, in, String(properties.Output_extension))
Colin Cross1a527682019-09-23 15:55:30 -0700655 copyTo = append(copyTo, outFile)
656 outFile = shardFile
657 }
658
659 outFiles = append(outFiles, outFile)
Colin Cross1a527682019-09-23 15:55:30 -0700660
Colin Crossf1885962020-11-20 15:28:30 -0800661 // pre-expand the command line to replace $in and $out with references to
662 // a single input and output file.
Colin Cross1a527682019-09-23 15:55:30 -0700663 command, err := android.Expand(rawCommand, func(name string) (string, error) {
664 switch name {
665 case "in":
666 return in.String(), nil
667 case "out":
Colin Crossf1a035e2020-11-16 17:32:30 -0800668 return rule.Command().PathForOutput(outFile), nil
Colin Cross3ea4eb82020-11-24 13:07:27 -0800669 case "depfile":
670 // Generate a depfile for each output file. Store the list for
671 // later in order to combine them all into a single depfile.
Colin Crossf1a035e2020-11-16 17:32:30 -0800672 depFile := rule.Command().PathForOutput(outFile.ReplaceExtension(ctx, "d"))
Colin Cross3ea4eb82020-11-24 13:07:27 -0800673 commandDepFiles = append(commandDepFiles, depFile)
674 return depFile, nil
Colin Cross1a527682019-09-23 15:55:30 -0700675 default:
676 return "$(" + name + ")", nil
677 }
678 })
679 if err != nil {
680 ctx.PropertyErrorf("cmd", err.Error())
681 }
682
683 // escape the command in case for example it contains '#', an odd number of '"', etc
684 command = fmt.Sprintf("bash -c %v", proptools.ShellEscape(command))
685 commands = append(commands, command)
686 }
687 fullCommand := strings.Join(commands, " && ")
688
Colin Cross3ea4eb82020-11-24 13:07:27 -0800689 var outputDepfile android.WritablePath
690 var extraTools android.Paths
691 if len(commandDepFiles) > 0 {
692 // Each command wrote to a depfile, but ninja can only handle one
693 // depfile per rule. Use the dep_fixer tool at the end of the
694 // command to combine all the depfiles into a single output depfile.
695 outputDepfile = android.PathForModuleGen(ctx, genSubDir, "gensrcs.d")
696 depFixerTool := ctx.Config().HostToolPath(ctx, "dep_fixer")
697 fullCommand += fmt.Sprintf(" && %s -o $(depfile) %s",
Colin Crossba9e4032020-11-24 16:32:22 -0800698 android.SboxPathForTool(ctx, depFixerTool),
699 strings.Join(commandDepFiles, " "))
Colin Cross3ea4eb82020-11-24 13:07:27 -0800700 extraTools = append(extraTools, depFixerTool)
701 }
702
Colin Cross1a527682019-09-23 15:55:30 -0700703 generateTasks = append(generateTasks, generateTask{
Colin Cross3ea4eb82020-11-24 13:07:27 -0800704 in: shard,
705 out: outFiles,
706 depFile: outputDepfile,
707 copyTo: copyTo,
708 genDir: genDir,
709 cmd: fullCommand,
710 shard: i,
711 shards: len(shards),
712 extraTools: extraTools,
Colin Cross1a527682019-09-23 15:55:30 -0700713 })
Jeff Gaston437d23c2017-11-08 12:38:00 -0800714 }
Colin Cross1a527682019-09-23 15:55:30 -0700715
716 return generateTasks
Colin Crossd350ecd2015-04-28 13:25:36 -0700717 }
718
Colin Cross1a527682019-09-23 15:55:30 -0700719 g := generatorFactory(taskGenerator, properties)
Colin Crossf1885962020-11-20 15:28:30 -0800720 g.subDir = finalSubDir
Colin Cross1a527682019-09-23 15:55:30 -0700721 return g
Colin Crossd350ecd2015-04-28 13:25:36 -0700722}
723
Colin Cross54190b32017-10-09 15:34:10 -0700724func GenSrcsFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700725 m := NewGenSrcs()
726 android.InitAndroidModule(m)
727 return m
728}
729
Colin Crossd350ecd2015-04-28 13:25:36 -0700730type genSrcsProperties struct {
Colin Cross7d5136f2015-05-11 13:39:40 -0700731 // extension that will be substituted for each output file
Nan Zhanga5e7cb42017-11-09 22:42:32 -0800732 Output_extension *string
Colin Cross1a527682019-09-23 15:55:30 -0700733
734 // maximum number of files that will be passed on a single command line.
735 Shard_size *int64
Colin Cross5049f022015-03-18 13:28:46 -0700736}
737
Evgenii Stepanovf47c90d2020-12-02 18:55:09 -0800738const defaultShardSize = 50
Colin Cross1a527682019-09-23 15:55:30 -0700739
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700740func NewGenRule() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700741 properties := &genRuleProperties{}
Colin Cross5049f022015-03-18 13:28:46 -0700742
Colin Cross1a527682019-09-23 15:55:30 -0700743 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700744 outs := make(android.WritablePaths, len(properties.Out))
Colin Cross3d680512020-11-13 16:23:53 -0800745 var depFile android.WritablePath
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700746 for i, out := range properties.Out {
Colin Cross3d680512020-11-13 16:23:53 -0800747 outPath := android.PathForModuleGen(ctx, out)
748 if i == 0 {
749 depFile = outPath.ReplaceExtension(ctx, "d")
750 }
751 outs[i] = outPath
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700752 }
Colin Cross1a527682019-09-23 15:55:30 -0700753 return []generateTask{{
Colin Cross3d680512020-11-13 16:23:53 -0800754 in: srcFiles,
755 out: outs,
756 depFile: depFile,
757 genDir: android.PathForModuleGen(ctx),
758 cmd: rawCommand,
Colin Cross1a527682019-09-23 15:55:30 -0700759 }}
Colin Cross5049f022015-03-18 13:28:46 -0700760 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700761
Jeff Gaston437d23c2017-11-08 12:38:00 -0800762 return generatorFactory(taskGenerator, properties)
Colin Cross5049f022015-03-18 13:28:46 -0700763}
764
Colin Cross54190b32017-10-09 15:34:10 -0700765func GenRuleFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700766 m := NewGenRule()
767 android.InitAndroidModule(m)
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800768 android.InitDefaultableModule(m)
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700769 return m
770}
771
Colin Crossd350ecd2015-04-28 13:25:36 -0700772type genRuleProperties struct {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700773 // names of the output files that will be generated
Colin Crossef354482018-10-23 11:27:50 -0700774 Out []string `android:"arch_variant"`
Colin Cross5049f022015-03-18 13:28:46 -0700775}
Nan Zhangea568a42017-11-08 21:20:04 -0800776
Jingwen Chen316e07c2020-12-14 09:09:52 -0500777type bazelGenruleAttributes struct {
778 Name *string
779 Srcs []string
780 Outs []string
781 Tools []string
782 Cmd string
783}
784
785type bazelGenrule struct {
786 android.BazelTargetModuleBase
787 bazelGenruleAttributes
788}
789
790func BazelGenruleFactory() android.Module {
791 module := &bazelGenrule{}
792 module.AddProperties(&module.bazelGenruleAttributes)
793 android.InitBazelTargetModule(module)
794 return module
795}
796
Jingwen Chena42d6412021-01-26 21:57:27 -0500797func GenruleBp2Build(ctx android.TopDownMutatorContext) {
Jingwen Chen316e07c2020-12-14 09:09:52 -0500798 if m, ok := ctx.Module().(*Module); ok {
799 name := "__bp2build__" + m.Name()
Jingwen Chen885ee7a2021-01-26 03:16:49 -0500800 // Bazel only has the "tools" attribute.
801 tools := append(m.properties.Tools, m.properties.Tool_files...)
802
Jingwen Chen316e07c2020-12-14 09:09:52 -0500803 // Replace in and out variables with $< and $@
804 var cmd string
805 if m.properties.Cmd != nil {
806 cmd = strings.Replace(*m.properties.Cmd, "$(in)", "$(SRCS)", -1)
807 cmd = strings.Replace(cmd, "$(out)", "$(OUTS)", -1)
808 cmd = strings.Replace(cmd, "$(genDir)", "$(GENDIR)", -1)
Jingwen Chen885ee7a2021-01-26 03:16:49 -0500809 if len(tools) > 0 {
810 cmd = strings.Replace(cmd, "$(location)", fmt.Sprintf("$(location %s)", tools[0]), -1)
811 cmd = strings.Replace(cmd, "$(locations)", fmt.Sprintf("$(locations %s)", tools[0]), -1)
812 }
Jingwen Chen316e07c2020-12-14 09:09:52 -0500813 }
814
815 // The Out prop is not in an immediately accessible field
816 // in the Module struct, so use GetProperties and cast it
817 // to the known struct prop.
818 var outs []string
819 for _, propIntf := range m.GetProperties() {
820 if props, ok := propIntf.(*genRuleProperties); ok {
821 outs = props.Out
822 break
823 }
824 }
825
Jingwen Chen316e07c2020-12-14 09:09:52 -0500826 // Create the BazelTargetModule.
827 ctx.CreateModule(BazelGenruleFactory, &bazelGenruleAttributes{
828 Name: proptools.StringPtr(name),
829 Srcs: m.properties.Srcs,
830 Outs: outs,
831 Cmd: cmd,
832 Tools: tools,
833 }, &bazel.BazelTargetModuleProperties{
834 Rule_class: "genrule",
835 })
836 }
837}
838
839func (m *bazelGenrule) Name() string {
840 return m.BaseModuleName()
841}
842
843func (m *bazelGenrule) GenerateAndroidBuildActions(ctx android.ModuleContext) {}
844
Nan Zhangea568a42017-11-08 21:20:04 -0800845var Bool = proptools.Bool
846var String = proptools.String
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800847
848//
849// Defaults
850//
851type Defaults struct {
852 android.ModuleBase
853 android.DefaultsModuleBase
854}
855
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800856func defaultsFactory() android.Module {
857 return DefaultsFactory()
858}
859
860func DefaultsFactory(props ...interface{}) android.Module {
861 module := &Defaults{}
862
863 module.AddProperties(props...)
864 module.AddProperties(
865 &generatorProperties{},
866 &genRuleProperties{},
867 )
868
869 android.InitDefaultsModule(module)
870
871 return module
872}