blob: b43f28e2fbcd7e3f7ac4b40de0e99fe42d81eff5 [file] [log] [blame]
Colin Cross5049f022015-03-18 13:28:46 -07001// Copyright 2015 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Alex Humesky29e3bbe2020-11-20 21:30:13 -050015// A genrule module takes a list of source files ("srcs" property), an optional
16// list of tools ("tools" property), and a command line ("cmd" property), to
17// generate output files ("out" property).
18
Colin Cross5049f022015-03-18 13:28:46 -070019package genrule
20
21import (
Colin Cross6f080df2016-11-04 15:32:58 -070022 "fmt"
Colin Crossa4ad2b02019-03-18 22:15:32 -070023 "io"
Colin Cross3d680512020-11-13 16:23:53 -080024 "path/filepath"
Colin Cross1a527682019-09-23 15:55:30 -070025 "strconv"
Colin Cross6f080df2016-11-04 15:32:58 -070026 "strings"
Dan Willemsen3f4539b2016-09-28 16:19:10 -070027
Colin Cross70b40592015-03-23 12:57:34 -070028 "github.com/google/blueprint"
Dan Willemsen8eded0a2017-09-13 16:07:44 -070029 "github.com/google/blueprint/bootstrap"
Nan Zhangea568a42017-11-08 21:20:04 -080030 "github.com/google/blueprint/proptools"
Colin Cross5049f022015-03-18 13:28:46 -070031
Colin Cross635c3b02016-05-18 15:37:25 -070032 "android/soong/android"
Jingwen Chen30f5aaa2020-11-19 05:38:02 -050033 "android/soong/bazel"
Colin Cross5049f022015-03-18 13:28:46 -070034)
35
Colin Cross463a90e2015-06-17 14:20:06 -070036func init() {
Colin Crosse9fe2942020-11-10 18:12:15 -080037 RegisterGenruleBuildComponents(android.InitRegistrationContext)
Martin Stjernholm710ec3a2020-01-16 15:12:04 +000038}
Jaewoong Jung98716bd2018-12-10 08:13:18 -080039
Paul Duffin672cb9f2021-03-03 02:30:37 +000040// Test fixture preparer that will register most genrule build components.
41//
42// Singletons and mutators should only be added here if they are needed for a majority of genrule
43// module types, otherwise they should be added under a separate preparer to allow them to be
44// selected only when needed to reduce test execution time.
45//
46// Module types do not have much of an overhead unless they are used so this should include as many
47// module types as possible. The exceptions are those module types that require mutators and/or
48// singletons in order to function in which case they should be kept together in a separate
49// preparer.
50var PrepareForTestWithGenRuleBuildComponents = android.GroupFixturePreparers(
51 android.FixtureRegisterWithContext(RegisterGenruleBuildComponents),
52)
53
54// Prepare a fixture to use all genrule module types, mutators and singletons fully.
55//
56// This should only be used by tests that want to run with as much of the build enabled as possible.
57var PrepareForIntegrationTestWithGenrule = android.GroupFixturePreparers(
58 PrepareForTestWithGenRuleBuildComponents,
59)
60
Colin Crosse9fe2942020-11-10 18:12:15 -080061func RegisterGenruleBuildComponents(ctx android.RegistrationContext) {
Martin Stjernholm710ec3a2020-01-16 15:12:04 +000062 ctx.RegisterModuleType("genrule_defaults", defaultsFactory)
63
64 ctx.RegisterModuleType("gensrcs", GenSrcsFactory)
65 ctx.RegisterModuleType("genrule", GenRuleFactory)
66
67 ctx.FinalDepsMutators(func(ctx android.RegisterMutatorsContext) {
68 ctx.BottomUp("genrule_tool_deps", toolDepsMutator).Parallel()
69 })
Jingwen Chen316e07c2020-12-14 09:09:52 -050070
Liz Kammer356f7d42021-01-26 09:18:53 -050071 android.DepsBp2BuildMutators(RegisterGenruleBp2BuildDeps)
Jingwen Chena42d6412021-01-26 21:57:27 -050072 android.RegisterBp2BuildMutator("genrule", GenruleBp2Build)
Colin Cross463a90e2015-06-17 14:20:06 -070073}
74
Liz Kammer356f7d42021-01-26 09:18:53 -050075func RegisterGenruleBp2BuildDeps(ctx android.RegisterMutatorsContext) {
76 ctx.BottomUp("genrule_tool_deps", toolDepsMutator)
77}
78
Colin Cross5049f022015-03-18 13:28:46 -070079var (
Colin Cross635c3b02016-05-18 15:37:25 -070080 pctx = android.NewPackageContext("android/soong/genrule")
Colin Cross1a527682019-09-23 15:55:30 -070081
Alex Humesky29e3bbe2020-11-20 21:30:13 -050082 // Used by gensrcs when there is more than 1 shard to merge the outputs
83 // of each shard into a zip file.
Colin Cross1a527682019-09-23 15:55:30 -070084 gensrcsMerge = pctx.AndroidStaticRule("gensrcsMerge", blueprint.RuleParams{
85 Command: "${soongZip} -o ${tmpZip} @${tmpZip}.rsp && ${zipSync} -d ${genDir} ${tmpZip}",
86 CommandDeps: []string{"${soongZip}", "${zipSync}"},
87 Rspfile: "${tmpZip}.rsp",
88 RspfileContent: "${zipArgs}",
89 }, "tmpZip", "genDir", "zipArgs")
Colin Cross5049f022015-03-18 13:28:46 -070090)
91
Jeff Gastonefc1b412017-03-29 17:29:06 -070092func init() {
Dan Willemsenddf504c2019-08-09 16:21:29 -070093 pctx.Import("android/soong/android")
Jeff Gastonefc1b412017-03-29 17:29:06 -070094 pctx.HostBinToolVariable("sboxCmd", "sbox")
Colin Cross1a527682019-09-23 15:55:30 -070095
96 pctx.HostBinToolVariable("soongZip", "soong_zip")
97 pctx.HostBinToolVariable("zipSync", "zipsync")
Jeff Gastonefc1b412017-03-29 17:29:06 -070098}
99
Colin Cross5049f022015-03-18 13:28:46 -0700100type SourceFileGenerator interface {
Colin Cross635c3b02016-05-18 15:37:25 -0700101 GeneratedSourceFiles() android.Paths
Colin Cross5ed99c62016-11-22 12:55:55 -0800102 GeneratedHeaderDirs() android.Paths
Dan Willemsen9da9d492018-02-21 18:28:18 -0800103 GeneratedDeps() android.Paths
Colin Cross5049f022015-03-18 13:28:46 -0700104}
105
Colin Crossfe17f6f2019-03-28 19:30:56 -0700106// Alias for android.HostToolProvider
107// Deprecated: use android.HostToolProvider instead.
Colin Crossd350ecd2015-04-28 13:25:36 -0700108type HostToolProvider interface {
Colin Crossfe17f6f2019-03-28 19:30:56 -0700109 android.HostToolProvider
Colin Crossd350ecd2015-04-28 13:25:36 -0700110}
Colin Cross5049f022015-03-18 13:28:46 -0700111
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700112type hostToolDependencyTag struct {
113 blueprint.BaseDependencyTag
Colin Cross08f15ab2018-10-04 23:29:14 -0700114 label string
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700115}
Colin Cross7d5136f2015-05-11 13:39:40 -0700116type generatorProperties struct {
Jeff Gastonefc1b412017-03-29 17:29:06 -0700117 // The command to run on one or more input files. Cmd supports substitution of a few variables
Jeff Gastonefc1b412017-03-29 17:29:06 -0700118 //
119 // Available variables for substitution:
120 //
Colin Cross2296f5b2017-10-17 21:38:14 -0700121 // $(location): the path to the first entry in tools or tool_files
Colin Cross08f15ab2018-10-04 23:29:14 -0700122 // $(location <label>): the path to the tool, tool_file, input or output with name <label>
Colin Cross2296f5b2017-10-17 21:38:14 -0700123 // $(in): one or more input files
124 // $(out): a single output file
125 // $(depfile): a file to which dependencies will be written, if the depfile property is set to true
126 // $(genDir): the sandbox directory for this tool; contains $(out)
127 // $$: a literal $
Nan Zhangea568a42017-11-08 21:20:04 -0800128 Cmd *string
Colin Cross7d5136f2015-05-11 13:39:40 -0700129
Colin Cross33bfb0a2016-11-21 17:23:08 -0800130 // Enable reading a file containing dependencies in gcc format after the command completes
Nan Zhangea568a42017-11-08 21:20:04 -0800131 Depfile *bool
Colin Cross33bfb0a2016-11-21 17:23:08 -0800132
Colin Cross6f080df2016-11-04 15:32:58 -0700133 // name of the modules (if any) that produces the host executable. Leave empty for
Colin Cross7d5136f2015-05-11 13:39:40 -0700134 // prebuilts or scripts that do not need a module to build them.
Colin Cross6f080df2016-11-04 15:32:58 -0700135 Tools []string
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700136
137 // Local file that is used as the tool
Colin Cross27b922f2019-03-04 22:35:41 -0800138 Tool_files []string `android:"path"`
Colin Cross5ed99c62016-11-22 12:55:55 -0800139
140 // List of directories to export generated headers from
141 Export_include_dirs []string
Colin Cross708c4242017-01-13 18:05:49 -0800142
143 // list of input files
Colin Cross27b922f2019-03-04 22:35:41 -0800144 Srcs []string `android:"path,arch_variant"`
Dan Willemseneefa0262018-11-17 14:01:18 -0800145
146 // input files to exclude
Colin Cross27b922f2019-03-04 22:35:41 -0800147 Exclude_srcs []string `android:"path,arch_variant"`
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400148}
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500149
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700150type Module struct {
Colin Cross635c3b02016-05-18 15:37:25 -0700151 android.ModuleBase
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800152 android.DefaultableModuleBase
Liz Kammerea6666f2021-02-17 10:17:28 -0500153 android.BazelModuleBase
Jiyong Parkfc752ca2019-06-12 13:27:29 +0900154 android.ApexModuleBase
Colin Crossd350ecd2015-04-28 13:25:36 -0700155
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700156 // For other packages to make their own genrules with extra
157 // properties
158 Extra interface{}
Colin Cross7228ecd2019-11-18 16:00:16 -0800159 android.ImageInterface
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700160
Colin Cross7d5136f2015-05-11 13:39:40 -0700161 properties generatorProperties
Colin Crossd350ecd2015-04-28 13:25:36 -0700162
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500163 // For the different tasks that genrule and gensrc generate. genrule will
164 // generate 1 task, and gensrc will generate 1 or more tasks based on the
165 // number of shards the input files are sharded into.
Jeff Gaston437d23c2017-11-08 12:38:00 -0800166 taskGenerator taskFunc
Colin Crossd350ecd2015-04-28 13:25:36 -0700167
Colin Cross1a527682019-09-23 15:55:30 -0700168 rule blueprint.Rule
169 rawCommands []string
Colin Crossd350ecd2015-04-28 13:25:36 -0700170
Colin Cross5ed99c62016-11-22 12:55:55 -0800171 exportedIncludeDirs android.Paths
Dan Willemsenb40aab62016-04-20 14:21:14 -0700172
Colin Cross635c3b02016-05-18 15:37:25 -0700173 outputFiles android.Paths
Dan Willemsen9da9d492018-02-21 18:28:18 -0800174 outputDeps android.Paths
Colin Crossa4ad2b02019-03-18 22:15:32 -0700175
176 subName string
Colin Cross1a527682019-09-23 15:55:30 -0700177 subDir string
bralee1fbf4402020-05-21 10:11:59 +0800178
179 // Collect the module directory for IDE info in java/jdeps.go.
180 modulePaths []string
Colin Crossd350ecd2015-04-28 13:25:36 -0700181}
182
Colin Cross1a527682019-09-23 15:55:30 -0700183type taskFunc func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask
Colin Crossd350ecd2015-04-28 13:25:36 -0700184
185type generateTask struct {
Colin Cross3ea4eb82020-11-24 13:07:27 -0800186 in android.Paths
187 out android.WritablePaths
188 depFile android.WritablePath
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500189 copyTo android.WritablePaths // For gensrcs to set on gensrcsMerge rule.
Colin Cross3ea4eb82020-11-24 13:07:27 -0800190 genDir android.WritablePath
191 extraTools android.Paths // dependencies on tools used by the generator
192
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500193 cmd string
194 // For gensrsc sharding.
Colin Cross3ea4eb82020-11-24 13:07:27 -0800195 shard int
196 shards int
Colin Crossd350ecd2015-04-28 13:25:36 -0700197}
198
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700199func (g *Module) GeneratedSourceFiles() android.Paths {
Colin Crossd350ecd2015-04-28 13:25:36 -0700200 return g.outputFiles
201}
202
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700203func (g *Module) Srcs() android.Paths {
Nan Zhange42777a2018-03-27 16:19:42 -0700204 return append(android.Paths{}, g.outputFiles...)
Colin Cross068e0fe2016-12-13 15:23:47 -0800205}
206
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700207func (g *Module) GeneratedHeaderDirs() android.Paths {
Colin Cross5ed99c62016-11-22 12:55:55 -0800208 return g.exportedIncludeDirs
Dan Willemsenb40aab62016-04-20 14:21:14 -0700209}
210
Dan Willemsen9da9d492018-02-21 18:28:18 -0800211func (g *Module) GeneratedDeps() android.Paths {
212 return g.outputDeps
213}
214
Martin Stjernholm710ec3a2020-01-16 15:12:04 +0000215func toolDepsMutator(ctx android.BottomUpMutatorContext) {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700216 if g, ok := ctx.Module().(*Module); ok {
Colin Cross08f15ab2018-10-04 23:29:14 -0700217 for _, tool := range g.properties.Tools {
218 tag := hostToolDependencyTag{label: tool}
219 if m := android.SrcIsModule(tool); m != "" {
220 tool = m
221 }
Colin Cross0f7d2ef2019-10-16 11:03:10 -0700222 ctx.AddFarVariationDependencies(ctx.Config().BuildOSTarget.Variations(), tag, tool)
Colin Cross6362e272015-10-29 15:25:03 -0700223 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700224 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700225}
226
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400227// Returns true if information was available from Bazel, false if bazel invocation still needs to occur.
228func (c *Module) generateBazelBuildActions(ctx android.ModuleContext, label string) bool {
229 bazelCtx := ctx.Config().BazelContext
Chris Parsons944e7d02021-03-11 11:08:46 -0500230 filePaths, ok := bazelCtx.GetOutputFiles(label, ctx.Arch().ArchType)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400231 if ok {
232 var bazelOutputFiles android.Paths
233 for _, bazelOutputFile := range filePaths {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500234 bazelOutputFiles = append(bazelOutputFiles, android.PathForBazelOut(ctx, bazelOutputFile))
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400235 }
236 c.outputFiles = bazelOutputFiles
237 c.outputDeps = bazelOutputFiles
238 }
239 return ok
240}
Colin Crossf1885962020-11-20 15:28:30 -0800241
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700242func (g *Module) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Colin Crossa4ad2b02019-03-18 22:15:32 -0700243 g.subName = ctx.ModuleSubDir()
244
bralee1fbf4402020-05-21 10:11:59 +0800245 // Collect the module directory for IDE info in java/jdeps.go.
246 g.modulePaths = append(g.modulePaths, ctx.ModuleDir())
247
Colin Cross5ed99c62016-11-22 12:55:55 -0800248 if len(g.properties.Export_include_dirs) > 0 {
249 for _, dir := range g.properties.Export_include_dirs {
250 g.exportedIncludeDirs = append(g.exportedIncludeDirs,
Colin Cross1a527682019-09-23 15:55:30 -0700251 android.PathForModuleGen(ctx, g.subDir, ctx.ModuleDir(), dir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800252 }
253 } else {
Colin Cross1a527682019-09-23 15:55:30 -0700254 g.exportedIncludeDirs = append(g.exportedIncludeDirs, android.PathForModuleGen(ctx, g.subDir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800255 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700256
Colin Cross08f15ab2018-10-04 23:29:14 -0700257 locationLabels := map[string][]string{}
258 firstLabel := ""
259
260 addLocationLabel := func(label string, paths []string) {
261 if firstLabel == "" {
262 firstLabel = label
263 }
264 if _, exists := locationLabels[label]; !exists {
265 locationLabels[label] = paths
266 } else {
267 ctx.ModuleErrorf("multiple labels for %q, %q and %q",
268 label, strings.Join(locationLabels[label], " "), strings.Join(paths, " "))
269 }
270 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700271
Colin Crossba9e4032020-11-24 16:32:22 -0800272 var tools android.Paths
273 var packagedTools []android.PackagingSpec
Colin Cross6f080df2016-11-04 15:32:58 -0700274 if len(g.properties.Tools) > 0 {
Colin Crossba71a3f2019-03-18 12:12:48 -0700275 seenTools := make(map[string]bool)
276
Colin Cross35143d02017-11-16 00:11:20 -0800277 ctx.VisitDirectDepsBlueprint(func(module blueprint.Module) {
Colin Cross08f15ab2018-10-04 23:29:14 -0700278 switch tag := ctx.OtherModuleDependencyTag(module).(type) {
279 case hostToolDependencyTag:
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700280 tool := ctx.OtherModuleName(module)
281
Colin Crossba9e4032020-11-24 16:32:22 -0800282 switch t := module.(type) {
283 case android.HostToolProvider:
284 // A HostToolProvider provides the path to a tool, which will be copied
285 // into the sandbox.
Colin Cross35143d02017-11-16 00:11:20 -0800286 if !t.(android.Module).Enabled() {
Colin Cross6510f912017-11-29 00:27:14 -0800287 if ctx.Config().AllowMissingDependencies() {
Colin Cross35143d02017-11-16 00:11:20 -0800288 ctx.AddMissingDependencies([]string{tool})
289 } else {
290 ctx.ModuleErrorf("depends on disabled module %q", tool)
291 }
Colin Crossba9e4032020-11-24 16:32:22 -0800292 return
Colin Cross35143d02017-11-16 00:11:20 -0800293 }
Colin Crossba9e4032020-11-24 16:32:22 -0800294 path := t.HostToolPath()
295 if !path.Valid() {
296 ctx.ModuleErrorf("host tool %q missing output file", tool)
297 return
298 }
299 if specs := t.TransitivePackagingSpecs(); specs != nil {
300 // If the HostToolProvider has PackgingSpecs, which are definitions of the
301 // required relative locations of the tool and its dependencies, use those
302 // instead. They will be copied to those relative locations in the sbox
303 // sandbox.
304 packagedTools = append(packagedTools, specs...)
305 // Assume that the first PackagingSpec of the module is the tool.
306 addLocationLabel(tag.label, []string{android.SboxPathForPackagedTool(specs[0])})
307 } else {
308 tools = append(tools, path.Path())
309 addLocationLabel(tag.label, []string{android.SboxPathForTool(ctx, path.Path())})
310 }
311 case bootstrap.GoBinaryTool:
312 // A GoBinaryTool provides the install path to a tool, which will be copied.
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700313 if s, err := filepath.Rel(android.PathForOutput(ctx).String(), t.InstallPath()); err == nil {
Colin Crossba9e4032020-11-24 16:32:22 -0800314 toolPath := android.PathForOutput(ctx, s)
315 tools = append(tools, toolPath)
316 addLocationLabel(tag.label, []string{android.SboxPathForTool(ctx, toolPath)})
Colin Cross6f080df2016-11-04 15:32:58 -0700317 } else {
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700318 ctx.ModuleErrorf("cannot find path for %q: %v", tool, err)
Colin Crossba9e4032020-11-24 16:32:22 -0800319 return
Colin Cross6f080df2016-11-04 15:32:58 -0700320 }
Colin Crossba9e4032020-11-24 16:32:22 -0800321 default:
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700322 ctx.ModuleErrorf("%q is not a host tool provider", tool)
Colin Crossba9e4032020-11-24 16:32:22 -0800323 return
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700324 }
325
Colin Crossba9e4032020-11-24 16:32:22 -0800326 seenTools[tag.label] = true
Colin Crossd350ecd2015-04-28 13:25:36 -0700327 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700328 })
Colin Crossba71a3f2019-03-18 12:12:48 -0700329
330 // If AllowMissingDependencies is enabled, the build will not have stopped when
331 // AddFarVariationDependencies was called on a missing tool, which will result in nonsensical
Liz Kammer20ebfb42020-07-28 11:32:07 -0700332 // "cmd: unknown location label ..." errors later. Add a placeholder file to the local label.
333 // The command that uses this placeholder file will never be executed because the rule will be
334 // replaced with an android.Error rule reporting the missing dependencies.
Colin Crossba71a3f2019-03-18 12:12:48 -0700335 if ctx.Config().AllowMissingDependencies() {
336 for _, tool := range g.properties.Tools {
337 if !seenTools[tool] {
338 addLocationLabel(tool, []string{"***missing tool " + tool + "***"})
339 }
340 }
341 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700342 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700343
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700344 if ctx.Failed() {
345 return
346 }
347
Colin Cross08f15ab2018-10-04 23:29:14 -0700348 for _, toolFile := range g.properties.Tool_files {
Colin Cross8a497952019-03-05 22:25:09 -0800349 paths := android.PathsForModuleSrc(ctx, []string{toolFile})
Colin Crossba9e4032020-11-24 16:32:22 -0800350 tools = append(tools, paths...)
351 var sandboxPaths []string
352 for _, path := range paths {
353 sandboxPaths = append(sandboxPaths, android.SboxPathForTool(ctx, path))
354 }
355 addLocationLabel(toolFile, sandboxPaths)
Colin Cross08f15ab2018-10-04 23:29:14 -0700356 }
357
358 var srcFiles android.Paths
359 for _, in := range g.properties.Srcs {
Colin Crossba71a3f2019-03-18 12:12:48 -0700360 paths, missingDeps := android.PathsAndMissingDepsForModuleSrcExcludes(ctx, []string{in}, g.properties.Exclude_srcs)
361 if len(missingDeps) > 0 {
362 if !ctx.Config().AllowMissingDependencies() {
363 panic(fmt.Errorf("should never get here, the missing dependencies %q should have been reported in DepsMutator",
364 missingDeps))
365 }
366
367 // If AllowMissingDependencies is enabled, the build will not have stopped when
368 // the dependency was added on a missing SourceFileProducer module, which will result in nonsensical
Liz Kammer20ebfb42020-07-28 11:32:07 -0700369 // "cmd: label ":..." has no files" errors later. Add a placeholder file to the local label.
370 // The command that uses this placeholder file will never be executed because the rule will be
371 // replaced with an android.Error rule reporting the missing dependencies.
Colin Crossba71a3f2019-03-18 12:12:48 -0700372 ctx.AddMissingDependencies(missingDeps)
373 addLocationLabel(in, []string{"***missing srcs " + in + "***"})
374 } else {
375 srcFiles = append(srcFiles, paths...)
376 addLocationLabel(in, paths.Strings())
377 }
Colin Cross08f15ab2018-10-04 23:29:14 -0700378 }
379
Colin Cross1a527682019-09-23 15:55:30 -0700380 var copyFrom android.Paths
381 var outputFiles android.WritablePaths
382 var zipArgs strings.Builder
Colin Cross08f15ab2018-10-04 23:29:14 -0700383
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500384 // Generate tasks, either from genrule or gensrcs.
Colin Cross1a527682019-09-23 15:55:30 -0700385 for _, task := range g.taskGenerator(ctx, String(g.properties.Cmd), srcFiles) {
Colin Cross3d680512020-11-13 16:23:53 -0800386 if len(task.out) == 0 {
387 ctx.ModuleErrorf("must have at least one output file")
388 return
Colin Cross85a2e892018-07-09 09:45:06 -0700389 }
390
Colin Crossf1a035e2020-11-16 17:32:30 -0800391 // Pick a unique path outside the task.genDir for the sbox manifest textproto,
392 // a unique rule name, and the user-visible description.
393 manifestName := "genrule.sbox.textproto"
394 desc := "generate"
395 name := "generator"
396 if task.shards > 0 {
397 manifestName = "genrule_" + strconv.Itoa(task.shard) + ".sbox.textproto"
398 desc += " " + strconv.Itoa(task.shard)
399 name += strconv.Itoa(task.shard)
400 } else if len(task.out) == 1 {
401 desc += " " + task.out[0].Base()
402 }
403
404 manifestPath := android.PathForModuleOut(ctx, manifestName)
405
406 // Use a RuleBuilder to create a rule that runs the command inside an sbox sandbox.
Colin Crossba9e4032020-11-24 16:32:22 -0800407 rule := android.NewRuleBuilder(pctx, ctx).Sbox(task.genDir, manifestPath).SandboxTools()
Colin Crossf1a035e2020-11-16 17:32:30 -0800408 cmd := rule.Command()
409
Colin Cross3d680512020-11-13 16:23:53 -0800410 for _, out := range task.out {
Colin Crossf1a035e2020-11-16 17:32:30 -0800411 addLocationLabel(out.Rel(), []string{cmd.PathForOutput(out)})
Colin Cross3d680512020-11-13 16:23:53 -0800412 }
413
Colin Cross1a527682019-09-23 15:55:30 -0700414 referencedDepfile := false
415
Colin Cross3d680512020-11-13 16:23:53 -0800416 rawCommand, err := android.Expand(task.cmd, func(name string) (string, error) {
Colin Cross1a527682019-09-23 15:55:30 -0700417 // report the error directly without returning an error to android.Expand to catch multiple errors in a
418 // single run
Colin Cross3d680512020-11-13 16:23:53 -0800419 reportError := func(fmt string, args ...interface{}) (string, error) {
Colin Cross1a527682019-09-23 15:55:30 -0700420 ctx.PropertyErrorf("cmd", fmt, args...)
Colin Cross3d680512020-11-13 16:23:53 -0800421 return "SOONG_ERROR", nil
Colin Cross6f080df2016-11-04 15:32:58 -0700422 }
Colin Cross1a527682019-09-23 15:55:30 -0700423
424 switch name {
425 case "location":
426 if len(g.properties.Tools) == 0 && len(g.properties.Tool_files) == 0 {
427 return reportError("at least one `tools` or `tool_files` is required if $(location) is used")
Colin Cross6f080df2016-11-04 15:32:58 -0700428 }
Colin Cross1a527682019-09-23 15:55:30 -0700429 paths := locationLabels[firstLabel]
430 if len(paths) == 0 {
431 return reportError("default label %q has no files", firstLabel)
432 } else if len(paths) > 1 {
433 return reportError("default label %q has multiple files, use $(locations %s) to reference it",
434 firstLabel, firstLabel)
Colin Cross08f15ab2018-10-04 23:29:14 -0700435 }
Colin Cross3d680512020-11-13 16:23:53 -0800436 return locationLabels[firstLabel][0], nil
Colin Cross1a527682019-09-23 15:55:30 -0700437 case "in":
Colin Cross3d680512020-11-13 16:23:53 -0800438 return strings.Join(srcFiles.Strings(), " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700439 case "out":
Colin Cross3d680512020-11-13 16:23:53 -0800440 var sandboxOuts []string
441 for _, out := range task.out {
Colin Crossf1a035e2020-11-16 17:32:30 -0800442 sandboxOuts = append(sandboxOuts, cmd.PathForOutput(out))
Colin Cross3d680512020-11-13 16:23:53 -0800443 }
444 return strings.Join(sandboxOuts, " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700445 case "depfile":
446 referencedDepfile = true
447 if !Bool(g.properties.Depfile) {
448 return reportError("$(depfile) used without depfile property")
449 }
Colin Cross3d680512020-11-13 16:23:53 -0800450 return "__SBOX_DEPFILE__", nil
Colin Cross1a527682019-09-23 15:55:30 -0700451 case "genDir":
Colin Crossf1a035e2020-11-16 17:32:30 -0800452 return cmd.PathForOutput(task.genDir), nil
Colin Cross1a527682019-09-23 15:55:30 -0700453 default:
454 if strings.HasPrefix(name, "location ") {
455 label := strings.TrimSpace(strings.TrimPrefix(name, "location "))
456 if paths, ok := locationLabels[label]; ok {
457 if len(paths) == 0 {
458 return reportError("label %q has no files", label)
459 } else if len(paths) > 1 {
460 return reportError("label %q has multiple files, use $(locations %s) to reference it",
461 label, label)
462 }
Colin Cross3d680512020-11-13 16:23:53 -0800463 return paths[0], nil
Colin Cross1a527682019-09-23 15:55:30 -0700464 } else {
465 return reportError("unknown location label %q", label)
466 }
467 } else if strings.HasPrefix(name, "locations ") {
468 label := strings.TrimSpace(strings.TrimPrefix(name, "locations "))
469 if paths, ok := locationLabels[label]; ok {
470 if len(paths) == 0 {
471 return reportError("label %q has no files", label)
472 }
Colin Cross3d680512020-11-13 16:23:53 -0800473 return strings.Join(paths, " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700474 } else {
475 return reportError("unknown locations label %q", label)
476 }
477 } else {
478 return reportError("unknown variable '$(%s)'", name)
479 }
Colin Cross6f080df2016-11-04 15:32:58 -0700480 }
Colin Cross1a527682019-09-23 15:55:30 -0700481 })
482
483 if err != nil {
484 ctx.PropertyErrorf("cmd", "%s", err.Error())
485 return
Colin Cross6f080df2016-11-04 15:32:58 -0700486 }
Colin Cross6f080df2016-11-04 15:32:58 -0700487
Colin Cross1a527682019-09-23 15:55:30 -0700488 if Bool(g.properties.Depfile) && !referencedDepfile {
489 ctx.PropertyErrorf("cmd", "specified depfile=true but did not include a reference to '${depfile}' in cmd")
490 return
491 }
Colin Cross1a527682019-09-23 15:55:30 -0700492 g.rawCommands = append(g.rawCommands, rawCommand)
Bill Peckhamc087be12020-02-13 15:55:10 -0800493
Colin Cross3d680512020-11-13 16:23:53 -0800494 cmd.Text(rawCommand)
495 cmd.ImplicitOutputs(task.out)
496 cmd.Implicits(task.in)
Colin Crossba9e4032020-11-24 16:32:22 -0800497 cmd.ImplicitTools(tools)
498 cmd.ImplicitTools(task.extraTools)
499 cmd.ImplicitPackagedTools(packagedTools)
Colin Cross3d680512020-11-13 16:23:53 -0800500 if Bool(g.properties.Depfile) {
501 cmd.ImplicitDepFile(task.depFile)
502 }
503
504 // Create the rule to run the genrule command inside sbox.
Colin Crossf1a035e2020-11-16 17:32:30 -0800505 rule.Build(name, desc)
Colin Cross1a527682019-09-23 15:55:30 -0700506
507 if len(task.copyTo) > 0 {
Colin Cross3d680512020-11-13 16:23:53 -0800508 // If copyTo is set, multiple shards need to be copied into a single directory.
509 // task.out contains the per-shard paths, and copyTo contains the corresponding
510 // final path. The files need to be copied into the final directory by a
511 // single rule so it can remove the directory before it starts to ensure no
512 // old files remain. zipsync already does this, so build up zipArgs that
513 // zip all the per-shard directories into a single zip.
Colin Cross1a527682019-09-23 15:55:30 -0700514 outputFiles = append(outputFiles, task.copyTo...)
515 copyFrom = append(copyFrom, task.out.Paths()...)
516 zipArgs.WriteString(" -C " + task.genDir.String())
517 zipArgs.WriteString(android.JoinWithPrefix(task.out.Strings(), " -f "))
518 } else {
519 outputFiles = append(outputFiles, task.out...)
520 }
Colin Cross6f080df2016-11-04 15:32:58 -0700521 }
522
Colin Cross1a527682019-09-23 15:55:30 -0700523 if len(copyFrom) > 0 {
Colin Cross3d680512020-11-13 16:23:53 -0800524 // Create a rule that zips all the per-shard directories into a single zip and then
525 // uses zipsync to unzip it into the final directory.
Colin Cross1a527682019-09-23 15:55:30 -0700526 ctx.Build(pctx, android.BuildParams{
Colin Crossf1885962020-11-20 15:28:30 -0800527 Rule: gensrcsMerge,
528 Implicits: copyFrom,
529 Outputs: outputFiles,
530 Description: "merge shards",
Colin Cross1a527682019-09-23 15:55:30 -0700531 Args: map[string]string{
532 "zipArgs": zipArgs.String(),
533 "tmpZip": android.PathForModuleGen(ctx, g.subDir+".zip").String(),
534 "genDir": android.PathForModuleGen(ctx, g.subDir).String(),
535 },
536 })
Colin Cross85a2e892018-07-09 09:45:06 -0700537 }
538
Colin Cross1a527682019-09-23 15:55:30 -0700539 g.outputFiles = outputFiles.Paths()
Jeff Gastonefc1b412017-03-29 17:29:06 -0700540
Liz Kammerbdc60992021-02-24 16:55:11 -0500541 bazelModuleLabel := g.GetBazelLabel(ctx, g)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400542 bazelActionsUsed := false
543 if ctx.Config().BazelContext.BazelEnabled() && len(bazelModuleLabel) > 0 {
544 bazelActionsUsed = g.generateBazelBuildActions(ctx, bazelModuleLabel)
Jeff Gaston02a684b2017-10-27 14:59:27 -0700545 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400546 if !bazelActionsUsed {
547 // For <= 6 outputs, just embed those directly in the users. Right now, that covers >90% of
548 // the genrules on AOSP. That will make things simpler to look at the graph in the common
549 // case. For larger sets of outputs, inject a phony target in between to limit ninja file
550 // growth.
551 if len(g.outputFiles) <= 6 {
552 g.outputDeps = g.outputFiles
553 } else {
554 phonyFile := android.PathForModuleGen(ctx, "genrule-phony")
555 ctx.Build(pctx, android.BuildParams{
556 Rule: blueprint.Phony,
557 Output: phonyFile,
558 Inputs: g.outputFiles,
559 })
560 g.outputDeps = android.Paths{phonyFile}
561 }
562 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700563}
Colin Crossd350ecd2015-04-28 13:25:36 -0700564
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700565// Collect information for opening IDE project files in java/jdeps.go.
566func (g *Module) IDEInfo(dpInfo *android.IdeInfo) {
567 dpInfo.Srcs = append(dpInfo.Srcs, g.Srcs().Strings()...)
568 for _, src := range g.properties.Srcs {
569 if strings.HasPrefix(src, ":") {
570 src = strings.Trim(src, ":")
571 dpInfo.Deps = append(dpInfo.Deps, src)
572 }
573 }
bralee1fbf4402020-05-21 10:11:59 +0800574 dpInfo.Paths = append(dpInfo.Paths, g.modulePaths...)
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700575}
576
Colin Crossa4ad2b02019-03-18 22:15:32 -0700577func (g *Module) AndroidMk() android.AndroidMkData {
578 return android.AndroidMkData{
Anton Hansson72f18492020-10-30 16:34:45 +0000579 Class: "ETC",
Colin Crossa4ad2b02019-03-18 22:15:32 -0700580 OutputFile: android.OptionalPathForPath(g.outputFiles[0]),
581 SubName: g.subName,
582 Extra: []android.AndroidMkExtraFunc{
583 func(w io.Writer, outputFile android.Path) {
Anton Hansson72f18492020-10-30 16:34:45 +0000584 fmt.Fprintln(w, "LOCAL_UNINSTALLABLE_MODULE := true")
Colin Crossa4ad2b02019-03-18 22:15:32 -0700585 },
586 },
587 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
588 android.WriteAndroidMkData(w, data)
589 if data.SubName != "" {
590 fmt.Fprintln(w, ".PHONY:", name)
591 fmt.Fprintln(w, name, ":", name+g.subName)
592 }
593 },
594 }
595}
596
Jiyong Park45bf82e2020-12-15 22:29:02 +0900597var _ android.ApexModule = (*Module)(nil)
598
599// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -0700600func (g *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
601 sdkVersion android.ApiLevel) error {
Jooyung Han749dc692020-04-15 11:03:39 +0900602 // Because generated outputs are checked by client modules(e.g. cc_library, ...)
603 // we can safely ignore the check here.
604 return nil
605}
606
Jeff Gaston437d23c2017-11-08 12:38:00 -0800607func generatorFactory(taskGenerator taskFunc, props ...interface{}) *Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700608 module := &Module{
Jeff Gaston437d23c2017-11-08 12:38:00 -0800609 taskGenerator: taskGenerator,
Colin Crossd350ecd2015-04-28 13:25:36 -0700610 }
611
Colin Cross36242852017-06-23 15:06:31 -0700612 module.AddProperties(props...)
613 module.AddProperties(&module.properties)
Colin Crossd350ecd2015-04-28 13:25:36 -0700614
Colin Cross7228ecd2019-11-18 16:00:16 -0800615 module.ImageInterface = noopImageInterface{}
616
Colin Cross36242852017-06-23 15:06:31 -0700617 return module
Colin Crossd350ecd2015-04-28 13:25:36 -0700618}
619
Colin Cross7228ecd2019-11-18 16:00:16 -0800620type noopImageInterface struct{}
621
622func (x noopImageInterface) ImageMutatorBegin(android.BaseModuleContext) {}
623func (x noopImageInterface) CoreVariantNeeded(android.BaseModuleContext) bool { return false }
Yifan Hong1b3348d2020-01-21 15:53:22 -0800624func (x noopImageInterface) RamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700625func (x noopImageInterface) VendorRamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Colin Cross7228ecd2019-11-18 16:00:16 -0800626func (x noopImageInterface) RecoveryVariantNeeded(android.BaseModuleContext) bool { return false }
627func (x noopImageInterface) ExtraImageVariations(ctx android.BaseModuleContext) []string { return nil }
628func (x noopImageInterface) SetImageVariation(ctx android.BaseModuleContext, variation string, module android.Module) {
629}
630
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700631func NewGenSrcs() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700632 properties := &genSrcsProperties{}
633
Colin Crossf1885962020-11-20 15:28:30 -0800634 // finalSubDir is the name of the subdirectory that output files will be generated into.
635 // It is used so that per-shard directories can be placed alongside it an then finally
636 // merged into it.
637 const finalSubDir = "gensrcs"
638
Colin Cross1a527682019-09-23 15:55:30 -0700639 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Colin Cross1a527682019-09-23 15:55:30 -0700640 shardSize := defaultShardSize
641 if s := properties.Shard_size; s != nil {
642 shardSize = int(*s)
643 }
Jeff Gaston437d23c2017-11-08 12:38:00 -0800644
Colin Crossf1885962020-11-20 15:28:30 -0800645 // gensrcs rules can easily hit command line limits by repeating the command for
646 // every input file. Shard the input files into groups.
Colin Cross1a527682019-09-23 15:55:30 -0700647 shards := android.ShardPaths(srcFiles, shardSize)
648 var generateTasks []generateTask
Colin Crossbaccf5b2018-02-21 14:07:48 -0800649
Colin Cross1a527682019-09-23 15:55:30 -0700650 for i, shard := range shards {
651 var commands []string
652 var outFiles android.WritablePaths
Colin Cross3ea4eb82020-11-24 13:07:27 -0800653 var commandDepFiles []string
Colin Cross1a527682019-09-23 15:55:30 -0700654 var copyTo android.WritablePaths
Colin Cross1a527682019-09-23 15:55:30 -0700655
Colin Crossf1885962020-11-20 15:28:30 -0800656 // When sharding is enabled (i.e. len(shards) > 1), the sbox rules for each
657 // shard will be write to their own directories and then be merged together
658 // into finalSubDir. If sharding is not enabled (i.e. len(shards) == 1),
659 // the sbox rule will write directly to finalSubDir.
660 genSubDir := finalSubDir
Colin Cross1a527682019-09-23 15:55:30 -0700661 if len(shards) > 1 {
Colin Crossf1885962020-11-20 15:28:30 -0800662 genSubDir = strconv.Itoa(i)
Jeff Gaston437d23c2017-11-08 12:38:00 -0800663 }
664
Colin Crossf1885962020-11-20 15:28:30 -0800665 genDir := android.PathForModuleGen(ctx, genSubDir)
Colin Crossf1a035e2020-11-16 17:32:30 -0800666 // TODO(ccross): this RuleBuilder is a hack to be able to call
667 // rule.Command().PathForOutput. Replace this with passing the rule into the
668 // generator.
Colin Crossba9e4032020-11-24 16:32:22 -0800669 rule := android.NewRuleBuilder(pctx, ctx).Sbox(genDir, nil).SandboxTools()
Jeff Gaston437d23c2017-11-08 12:38:00 -0800670
Colin Cross3ea4eb82020-11-24 13:07:27 -0800671 for _, in := range shard {
Colin Crossf1885962020-11-20 15:28:30 -0800672 outFile := android.GenPathWithExt(ctx, finalSubDir, in, String(properties.Output_extension))
673
674 // If sharding is enabled, then outFile is the path to the output file in
675 // the shard directory, and copyTo is the path to the output file in the
676 // final directory.
Colin Cross1a527682019-09-23 15:55:30 -0700677 if len(shards) > 1 {
Colin Crossf1885962020-11-20 15:28:30 -0800678 shardFile := android.GenPathWithExt(ctx, genSubDir, in, String(properties.Output_extension))
Colin Cross1a527682019-09-23 15:55:30 -0700679 copyTo = append(copyTo, outFile)
680 outFile = shardFile
681 }
682
683 outFiles = append(outFiles, outFile)
Colin Cross1a527682019-09-23 15:55:30 -0700684
Colin Crossf1885962020-11-20 15:28:30 -0800685 // pre-expand the command line to replace $in and $out with references to
686 // a single input and output file.
Colin Cross1a527682019-09-23 15:55:30 -0700687 command, err := android.Expand(rawCommand, func(name string) (string, error) {
688 switch name {
689 case "in":
690 return in.String(), nil
691 case "out":
Colin Crossf1a035e2020-11-16 17:32:30 -0800692 return rule.Command().PathForOutput(outFile), nil
Colin Cross3ea4eb82020-11-24 13:07:27 -0800693 case "depfile":
694 // Generate a depfile for each output file. Store the list for
695 // later in order to combine them all into a single depfile.
Colin Crossf1a035e2020-11-16 17:32:30 -0800696 depFile := rule.Command().PathForOutput(outFile.ReplaceExtension(ctx, "d"))
Colin Cross3ea4eb82020-11-24 13:07:27 -0800697 commandDepFiles = append(commandDepFiles, depFile)
698 return depFile, nil
Colin Cross1a527682019-09-23 15:55:30 -0700699 default:
700 return "$(" + name + ")", nil
701 }
702 })
703 if err != nil {
704 ctx.PropertyErrorf("cmd", err.Error())
705 }
706
707 // escape the command in case for example it contains '#', an odd number of '"', etc
708 command = fmt.Sprintf("bash -c %v", proptools.ShellEscape(command))
709 commands = append(commands, command)
710 }
711 fullCommand := strings.Join(commands, " && ")
712
Colin Cross3ea4eb82020-11-24 13:07:27 -0800713 var outputDepfile android.WritablePath
714 var extraTools android.Paths
715 if len(commandDepFiles) > 0 {
716 // Each command wrote to a depfile, but ninja can only handle one
717 // depfile per rule. Use the dep_fixer tool at the end of the
718 // command to combine all the depfiles into a single output depfile.
719 outputDepfile = android.PathForModuleGen(ctx, genSubDir, "gensrcs.d")
720 depFixerTool := ctx.Config().HostToolPath(ctx, "dep_fixer")
721 fullCommand += fmt.Sprintf(" && %s -o $(depfile) %s",
Colin Crossba9e4032020-11-24 16:32:22 -0800722 android.SboxPathForTool(ctx, depFixerTool),
723 strings.Join(commandDepFiles, " "))
Colin Cross3ea4eb82020-11-24 13:07:27 -0800724 extraTools = append(extraTools, depFixerTool)
725 }
726
Colin Cross1a527682019-09-23 15:55:30 -0700727 generateTasks = append(generateTasks, generateTask{
Colin Cross3ea4eb82020-11-24 13:07:27 -0800728 in: shard,
729 out: outFiles,
730 depFile: outputDepfile,
731 copyTo: copyTo,
732 genDir: genDir,
733 cmd: fullCommand,
734 shard: i,
735 shards: len(shards),
736 extraTools: extraTools,
Colin Cross1a527682019-09-23 15:55:30 -0700737 })
Jeff Gaston437d23c2017-11-08 12:38:00 -0800738 }
Colin Cross1a527682019-09-23 15:55:30 -0700739
740 return generateTasks
Colin Crossd350ecd2015-04-28 13:25:36 -0700741 }
742
Colin Cross1a527682019-09-23 15:55:30 -0700743 g := generatorFactory(taskGenerator, properties)
Colin Crossf1885962020-11-20 15:28:30 -0800744 g.subDir = finalSubDir
Colin Cross1a527682019-09-23 15:55:30 -0700745 return g
Colin Crossd350ecd2015-04-28 13:25:36 -0700746}
747
Colin Cross54190b32017-10-09 15:34:10 -0700748func GenSrcsFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700749 m := NewGenSrcs()
750 android.InitAndroidModule(m)
751 return m
752}
753
Colin Crossd350ecd2015-04-28 13:25:36 -0700754type genSrcsProperties struct {
Colin Cross7d5136f2015-05-11 13:39:40 -0700755 // extension that will be substituted for each output file
Nan Zhanga5e7cb42017-11-09 22:42:32 -0800756 Output_extension *string
Colin Cross1a527682019-09-23 15:55:30 -0700757
758 // maximum number of files that will be passed on a single command line.
759 Shard_size *int64
Colin Cross5049f022015-03-18 13:28:46 -0700760}
761
Evgenii Stepanovf47c90d2020-12-02 18:55:09 -0800762const defaultShardSize = 50
Colin Cross1a527682019-09-23 15:55:30 -0700763
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700764func NewGenRule() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700765 properties := &genRuleProperties{}
Colin Cross5049f022015-03-18 13:28:46 -0700766
Colin Cross1a527682019-09-23 15:55:30 -0700767 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700768 outs := make(android.WritablePaths, len(properties.Out))
Colin Cross3d680512020-11-13 16:23:53 -0800769 var depFile android.WritablePath
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700770 for i, out := range properties.Out {
Colin Cross3d680512020-11-13 16:23:53 -0800771 outPath := android.PathForModuleGen(ctx, out)
772 if i == 0 {
773 depFile = outPath.ReplaceExtension(ctx, "d")
774 }
775 outs[i] = outPath
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700776 }
Colin Cross1a527682019-09-23 15:55:30 -0700777 return []generateTask{{
Colin Cross3d680512020-11-13 16:23:53 -0800778 in: srcFiles,
779 out: outs,
780 depFile: depFile,
781 genDir: android.PathForModuleGen(ctx),
782 cmd: rawCommand,
Colin Cross1a527682019-09-23 15:55:30 -0700783 }}
Colin Cross5049f022015-03-18 13:28:46 -0700784 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700785
Jeff Gaston437d23c2017-11-08 12:38:00 -0800786 return generatorFactory(taskGenerator, properties)
Colin Cross5049f022015-03-18 13:28:46 -0700787}
788
Colin Cross54190b32017-10-09 15:34:10 -0700789func GenRuleFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700790 m := NewGenRule()
791 android.InitAndroidModule(m)
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800792 android.InitDefaultableModule(m)
Liz Kammerea6666f2021-02-17 10:17:28 -0500793 android.InitBazelModule(m)
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700794 return m
795}
796
Colin Crossd350ecd2015-04-28 13:25:36 -0700797type genRuleProperties struct {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700798 // names of the output files that will be generated
Colin Crossef354482018-10-23 11:27:50 -0700799 Out []string `android:"arch_variant"`
Colin Cross5049f022015-03-18 13:28:46 -0700800}
Nan Zhangea568a42017-11-08 21:20:04 -0800801
Jingwen Chen316e07c2020-12-14 09:09:52 -0500802type bazelGenruleAttributes struct {
Liz Kammer356f7d42021-01-26 09:18:53 -0500803 Srcs bazel.LabelList
Jingwen Chen316e07c2020-12-14 09:09:52 -0500804 Outs []string
Liz Kammer356f7d42021-01-26 09:18:53 -0500805 Tools bazel.LabelList
Jingwen Chen316e07c2020-12-14 09:09:52 -0500806 Cmd string
807}
808
809type bazelGenrule struct {
810 android.BazelTargetModuleBase
811 bazelGenruleAttributes
812}
813
814func BazelGenruleFactory() android.Module {
815 module := &bazelGenrule{}
816 module.AddProperties(&module.bazelGenruleAttributes)
817 android.InitBazelTargetModule(module)
818 return module
819}
820
Jingwen Chena42d6412021-01-26 21:57:27 -0500821func GenruleBp2Build(ctx android.TopDownMutatorContext) {
Liz Kammer356f7d42021-01-26 09:18:53 -0500822 m, ok := ctx.Module().(*Module)
Liz Kammerea6666f2021-02-17 10:17:28 -0500823 if !ok || !m.ConvertWithBp2build() {
Liz Kammer356f7d42021-01-26 09:18:53 -0500824 return
Jingwen Chen316e07c2020-12-14 09:09:52 -0500825 }
Jingwen Chen1fd14692021-02-05 03:01:50 -0500826
Jingwen Chen66480452021-03-18 03:41:55 -0400827 if ctx.ModuleType() != "genrule" {
828 // Not a regular genrule. Could be a cc_genrule or java_genrule.
829 return
830 }
831
Liz Kammer356f7d42021-01-26 09:18:53 -0500832 // Bazel only has the "tools" attribute.
833 tools := android.BazelLabelForModuleDeps(ctx, m.properties.Tools)
834 tool_files := android.BazelLabelForModuleSrc(ctx, m.properties.Tool_files)
835 tools.Append(tool_files)
836
837 srcs := android.BazelLabelForModuleSrc(ctx, m.properties.Srcs)
838
839 var allReplacements bazel.LabelList
840 allReplacements.Append(tools)
841 allReplacements.Append(srcs)
842
843 // Replace in and out variables with $< and $@
844 var cmd string
845 if m.properties.Cmd != nil {
846 cmd = strings.Replace(*m.properties.Cmd, "$(in)", "$(SRCS)", -1)
847 cmd = strings.Replace(cmd, "$(out)", "$(OUTS)", -1)
848 cmd = strings.Replace(cmd, "$(genDir)", "$(GENDIR)", -1)
849 if len(tools.Includes) > 0 {
850 cmd = strings.Replace(cmd, "$(location)", fmt.Sprintf("$(location %s)", tools.Includes[0].Label), -1)
851 cmd = strings.Replace(cmd, "$(locations)", fmt.Sprintf("$(locations %s)", tools.Includes[0].Label), -1)
852 }
853 for _, l := range allReplacements.Includes {
854 bpLoc := fmt.Sprintf("$(location %s)", l.Bp_text)
855 bpLocs := fmt.Sprintf("$(locations %s)", l.Bp_text)
856 bazelLoc := fmt.Sprintf("$(location %s)", l.Label)
857 bazelLocs := fmt.Sprintf("$(locations %s)", l.Label)
858 cmd = strings.Replace(cmd, bpLoc, bazelLoc, -1)
859 cmd = strings.Replace(cmd, bpLocs, bazelLocs, -1)
860 }
861 }
862
863 // The Out prop is not in an immediately accessible field
864 // in the Module struct, so use GetProperties and cast it
865 // to the known struct prop.
866 var outs []string
867 for _, propIntf := range m.GetProperties() {
868 if props, ok := propIntf.(*genRuleProperties); ok {
869 outs = props.Out
870 break
871 }
872 }
873
Jingwen Chen1fd14692021-02-05 03:01:50 -0500874 attrs := &bazelGenruleAttributes{
Liz Kammer356f7d42021-01-26 09:18:53 -0500875 Srcs: srcs,
876 Outs: outs,
877 Cmd: cmd,
878 Tools: tools,
Jingwen Chen1fd14692021-02-05 03:01:50 -0500879 }
880
Liz Kammerfc46bc12021-02-19 11:06:17 -0500881 props := bazel.BazelTargetModuleProperties{
882 Rule_class: "genrule",
883 }
Jingwen Chen1fd14692021-02-05 03:01:50 -0500884
885 // Create the BazelTargetModule.
Liz Kammerfc46bc12021-02-19 11:06:17 -0500886 ctx.CreateBazelTargetModule(BazelGenruleFactory, m.Name(), props, attrs)
Jingwen Chen316e07c2020-12-14 09:09:52 -0500887}
888
889func (m *bazelGenrule) Name() string {
890 return m.BaseModuleName()
891}
892
893func (m *bazelGenrule) GenerateAndroidBuildActions(ctx android.ModuleContext) {}
894
Nan Zhangea568a42017-11-08 21:20:04 -0800895var Bool = proptools.Bool
896var String = proptools.String
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800897
898//
899// Defaults
900//
901type Defaults struct {
902 android.ModuleBase
903 android.DefaultsModuleBase
904}
905
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800906func defaultsFactory() android.Module {
907 return DefaultsFactory()
908}
909
910func DefaultsFactory(props ...interface{}) android.Module {
911 module := &Defaults{}
912
913 module.AddProperties(props...)
914 module.AddProperties(
915 &generatorProperties{},
916 &genRuleProperties{},
917 )
918
919 android.InitDefaultsModule(module)
920
921 return module
922}