blob: 77dae755ab8d5ff95eb8d7ba3684c6f9a0965cb9 [file] [log] [blame]
Colin Cross5049f022015-03-18 13:28:46 -07001// Copyright 2015 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Alex Humesky29e3bbe2020-11-20 21:30:13 -050015// A genrule module takes a list of source files ("srcs" property), an optional
16// list of tools ("tools" property), and a command line ("cmd" property), to
17// generate output files ("out" property).
18
Colin Cross5049f022015-03-18 13:28:46 -070019package genrule
20
21import (
Colin Cross6f080df2016-11-04 15:32:58 -070022 "fmt"
Colin Crossa4ad2b02019-03-18 22:15:32 -070023 "io"
Colin Cross3d680512020-11-13 16:23:53 -080024 "path/filepath"
Colin Cross1a527682019-09-23 15:55:30 -070025 "strconv"
Colin Cross6f080df2016-11-04 15:32:58 -070026 "strings"
Dan Willemsen3f4539b2016-09-28 16:19:10 -070027
Colin Cross70b40592015-03-23 12:57:34 -070028 "github.com/google/blueprint"
Dan Willemsen8eded0a2017-09-13 16:07:44 -070029 "github.com/google/blueprint/bootstrap"
Nan Zhangea568a42017-11-08 21:20:04 -080030 "github.com/google/blueprint/proptools"
Colin Cross5049f022015-03-18 13:28:46 -070031
Colin Cross635c3b02016-05-18 15:37:25 -070032 "android/soong/android"
Jingwen Chen30f5aaa2020-11-19 05:38:02 -050033 "android/soong/bazel"
Colin Cross5049f022015-03-18 13:28:46 -070034)
35
Colin Cross463a90e2015-06-17 14:20:06 -070036func init() {
Colin Crosse9fe2942020-11-10 18:12:15 -080037 RegisterGenruleBuildComponents(android.InitRegistrationContext)
Martin Stjernholm710ec3a2020-01-16 15:12:04 +000038}
Jaewoong Jung98716bd2018-12-10 08:13:18 -080039
Paul Duffin672cb9f2021-03-03 02:30:37 +000040// Test fixture preparer that will register most genrule build components.
41//
42// Singletons and mutators should only be added here if they are needed for a majority of genrule
43// module types, otherwise they should be added under a separate preparer to allow them to be
44// selected only when needed to reduce test execution time.
45//
46// Module types do not have much of an overhead unless they are used so this should include as many
47// module types as possible. The exceptions are those module types that require mutators and/or
48// singletons in order to function in which case they should be kept together in a separate
49// preparer.
50var PrepareForTestWithGenRuleBuildComponents = android.GroupFixturePreparers(
51 android.FixtureRegisterWithContext(RegisterGenruleBuildComponents),
52)
53
54// Prepare a fixture to use all genrule module types, mutators and singletons fully.
55//
56// This should only be used by tests that want to run with as much of the build enabled as possible.
57var PrepareForIntegrationTestWithGenrule = android.GroupFixturePreparers(
58 PrepareForTestWithGenRuleBuildComponents,
59)
60
Colin Crosse9fe2942020-11-10 18:12:15 -080061func RegisterGenruleBuildComponents(ctx android.RegistrationContext) {
Martin Stjernholm710ec3a2020-01-16 15:12:04 +000062 ctx.RegisterModuleType("genrule_defaults", defaultsFactory)
63
64 ctx.RegisterModuleType("gensrcs", GenSrcsFactory)
65 ctx.RegisterModuleType("genrule", GenRuleFactory)
66
67 ctx.FinalDepsMutators(func(ctx android.RegisterMutatorsContext) {
68 ctx.BottomUp("genrule_tool_deps", toolDepsMutator).Parallel()
69 })
Jingwen Chen316e07c2020-12-14 09:09:52 -050070
Liz Kammer356f7d42021-01-26 09:18:53 -050071 android.DepsBp2BuildMutators(RegisterGenruleBp2BuildDeps)
Jingwen Chena42d6412021-01-26 21:57:27 -050072 android.RegisterBp2BuildMutator("genrule", GenruleBp2Build)
Colin Cross463a90e2015-06-17 14:20:06 -070073}
74
Liz Kammer356f7d42021-01-26 09:18:53 -050075func RegisterGenruleBp2BuildDeps(ctx android.RegisterMutatorsContext) {
76 ctx.BottomUp("genrule_tool_deps", toolDepsMutator)
77}
78
Colin Cross5049f022015-03-18 13:28:46 -070079var (
Colin Cross635c3b02016-05-18 15:37:25 -070080 pctx = android.NewPackageContext("android/soong/genrule")
Colin Cross1a527682019-09-23 15:55:30 -070081
Alex Humesky29e3bbe2020-11-20 21:30:13 -050082 // Used by gensrcs when there is more than 1 shard to merge the outputs
83 // of each shard into a zip file.
Colin Cross1a527682019-09-23 15:55:30 -070084 gensrcsMerge = pctx.AndroidStaticRule("gensrcsMerge", blueprint.RuleParams{
85 Command: "${soongZip} -o ${tmpZip} @${tmpZip}.rsp && ${zipSync} -d ${genDir} ${tmpZip}",
86 CommandDeps: []string{"${soongZip}", "${zipSync}"},
87 Rspfile: "${tmpZip}.rsp",
88 RspfileContent: "${zipArgs}",
89 }, "tmpZip", "genDir", "zipArgs")
Colin Cross5049f022015-03-18 13:28:46 -070090)
91
Jeff Gastonefc1b412017-03-29 17:29:06 -070092func init() {
Dan Willemsenddf504c2019-08-09 16:21:29 -070093 pctx.Import("android/soong/android")
Colin Cross1a527682019-09-23 15:55:30 -070094
95 pctx.HostBinToolVariable("soongZip", "soong_zip")
96 pctx.HostBinToolVariable("zipSync", "zipsync")
Jeff Gastonefc1b412017-03-29 17:29:06 -070097}
98
Colin Cross5049f022015-03-18 13:28:46 -070099type SourceFileGenerator interface {
Colin Cross635c3b02016-05-18 15:37:25 -0700100 GeneratedSourceFiles() android.Paths
Colin Cross5ed99c62016-11-22 12:55:55 -0800101 GeneratedHeaderDirs() android.Paths
Dan Willemsen9da9d492018-02-21 18:28:18 -0800102 GeneratedDeps() android.Paths
Colin Cross5049f022015-03-18 13:28:46 -0700103}
104
Colin Crossfe17f6f2019-03-28 19:30:56 -0700105// Alias for android.HostToolProvider
106// Deprecated: use android.HostToolProvider instead.
Colin Crossd350ecd2015-04-28 13:25:36 -0700107type HostToolProvider interface {
Colin Crossfe17f6f2019-03-28 19:30:56 -0700108 android.HostToolProvider
Colin Crossd350ecd2015-04-28 13:25:36 -0700109}
Colin Cross5049f022015-03-18 13:28:46 -0700110
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700111type hostToolDependencyTag struct {
112 blueprint.BaseDependencyTag
Colin Cross08f15ab2018-10-04 23:29:14 -0700113 label string
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700114}
Colin Cross7d5136f2015-05-11 13:39:40 -0700115type generatorProperties struct {
Jeff Gastonefc1b412017-03-29 17:29:06 -0700116 // The command to run on one or more input files. Cmd supports substitution of a few variables
Jeff Gastonefc1b412017-03-29 17:29:06 -0700117 //
118 // Available variables for substitution:
119 //
Colin Cross2296f5b2017-10-17 21:38:14 -0700120 // $(location): the path to the first entry in tools or tool_files
Colin Cross08f15ab2018-10-04 23:29:14 -0700121 // $(location <label>): the path to the tool, tool_file, input or output with name <label>
Colin Cross2296f5b2017-10-17 21:38:14 -0700122 // $(in): one or more input files
123 // $(out): a single output file
124 // $(depfile): a file to which dependencies will be written, if the depfile property is set to true
125 // $(genDir): the sandbox directory for this tool; contains $(out)
126 // $$: a literal $
Nan Zhangea568a42017-11-08 21:20:04 -0800127 Cmd *string
Colin Cross7d5136f2015-05-11 13:39:40 -0700128
Colin Cross33bfb0a2016-11-21 17:23:08 -0800129 // Enable reading a file containing dependencies in gcc format after the command completes
Nan Zhangea568a42017-11-08 21:20:04 -0800130 Depfile *bool
Colin Cross33bfb0a2016-11-21 17:23:08 -0800131
Colin Cross6f080df2016-11-04 15:32:58 -0700132 // name of the modules (if any) that produces the host executable. Leave empty for
Colin Cross7d5136f2015-05-11 13:39:40 -0700133 // prebuilts or scripts that do not need a module to build them.
Colin Cross6f080df2016-11-04 15:32:58 -0700134 Tools []string
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700135
136 // Local file that is used as the tool
Colin Cross27b922f2019-03-04 22:35:41 -0800137 Tool_files []string `android:"path"`
Colin Cross5ed99c62016-11-22 12:55:55 -0800138
139 // List of directories to export generated headers from
140 Export_include_dirs []string
Colin Cross708c4242017-01-13 18:05:49 -0800141
142 // list of input files
Colin Cross27b922f2019-03-04 22:35:41 -0800143 Srcs []string `android:"path,arch_variant"`
Dan Willemseneefa0262018-11-17 14:01:18 -0800144
145 // input files to exclude
Colin Cross27b922f2019-03-04 22:35:41 -0800146 Exclude_srcs []string `android:"path,arch_variant"`
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400147}
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500148
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700149type Module struct {
Colin Cross635c3b02016-05-18 15:37:25 -0700150 android.ModuleBase
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800151 android.DefaultableModuleBase
Liz Kammerea6666f2021-02-17 10:17:28 -0500152 android.BazelModuleBase
Jiyong Parkfc752ca2019-06-12 13:27:29 +0900153 android.ApexModuleBase
Colin Crossd350ecd2015-04-28 13:25:36 -0700154
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700155 // For other packages to make their own genrules with extra
156 // properties
157 Extra interface{}
Colin Cross7228ecd2019-11-18 16:00:16 -0800158 android.ImageInterface
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700159
Colin Cross7d5136f2015-05-11 13:39:40 -0700160 properties generatorProperties
Colin Crossd350ecd2015-04-28 13:25:36 -0700161
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500162 // For the different tasks that genrule and gensrc generate. genrule will
163 // generate 1 task, and gensrc will generate 1 or more tasks based on the
164 // number of shards the input files are sharded into.
Jeff Gaston437d23c2017-11-08 12:38:00 -0800165 taskGenerator taskFunc
Colin Crossd350ecd2015-04-28 13:25:36 -0700166
Colin Cross1a527682019-09-23 15:55:30 -0700167 rule blueprint.Rule
168 rawCommands []string
Colin Crossd350ecd2015-04-28 13:25:36 -0700169
Colin Cross5ed99c62016-11-22 12:55:55 -0800170 exportedIncludeDirs android.Paths
Dan Willemsenb40aab62016-04-20 14:21:14 -0700171
Colin Cross635c3b02016-05-18 15:37:25 -0700172 outputFiles android.Paths
Dan Willemsen9da9d492018-02-21 18:28:18 -0800173 outputDeps android.Paths
Colin Crossa4ad2b02019-03-18 22:15:32 -0700174
175 subName string
Colin Cross1a527682019-09-23 15:55:30 -0700176 subDir string
bralee1fbf4402020-05-21 10:11:59 +0800177
178 // Collect the module directory for IDE info in java/jdeps.go.
179 modulePaths []string
Colin Crossd350ecd2015-04-28 13:25:36 -0700180}
181
Colin Cross1a527682019-09-23 15:55:30 -0700182type taskFunc func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask
Colin Crossd350ecd2015-04-28 13:25:36 -0700183
184type generateTask struct {
Colin Cross3ea4eb82020-11-24 13:07:27 -0800185 in android.Paths
186 out android.WritablePaths
187 depFile android.WritablePath
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500188 copyTo android.WritablePaths // For gensrcs to set on gensrcsMerge rule.
Colin Cross3ea4eb82020-11-24 13:07:27 -0800189 genDir android.WritablePath
190 extraTools android.Paths // dependencies on tools used by the generator
191
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500192 cmd string
193 // For gensrsc sharding.
Colin Cross3ea4eb82020-11-24 13:07:27 -0800194 shard int
195 shards int
Colin Crossd350ecd2015-04-28 13:25:36 -0700196}
197
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700198func (g *Module) GeneratedSourceFiles() android.Paths {
Colin Crossd350ecd2015-04-28 13:25:36 -0700199 return g.outputFiles
200}
201
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700202func (g *Module) Srcs() android.Paths {
Nan Zhange42777a2018-03-27 16:19:42 -0700203 return append(android.Paths{}, g.outputFiles...)
Colin Cross068e0fe2016-12-13 15:23:47 -0800204}
205
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700206func (g *Module) GeneratedHeaderDirs() android.Paths {
Colin Cross5ed99c62016-11-22 12:55:55 -0800207 return g.exportedIncludeDirs
Dan Willemsenb40aab62016-04-20 14:21:14 -0700208}
209
Dan Willemsen9da9d492018-02-21 18:28:18 -0800210func (g *Module) GeneratedDeps() android.Paths {
211 return g.outputDeps
212}
213
Martin Stjernholm710ec3a2020-01-16 15:12:04 +0000214func toolDepsMutator(ctx android.BottomUpMutatorContext) {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700215 if g, ok := ctx.Module().(*Module); ok {
Colin Cross08f15ab2018-10-04 23:29:14 -0700216 for _, tool := range g.properties.Tools {
217 tag := hostToolDependencyTag{label: tool}
218 if m := android.SrcIsModule(tool); m != "" {
219 tool = m
220 }
Colin Cross0f7d2ef2019-10-16 11:03:10 -0700221 ctx.AddFarVariationDependencies(ctx.Config().BuildOSTarget.Variations(), tag, tool)
Colin Cross6362e272015-10-29 15:25:03 -0700222 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700223 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700224}
225
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400226// Returns true if information was available from Bazel, false if bazel invocation still needs to occur.
227func (c *Module) generateBazelBuildActions(ctx android.ModuleContext, label string) bool {
228 bazelCtx := ctx.Config().BazelContext
Chris Parsons944e7d02021-03-11 11:08:46 -0500229 filePaths, ok := bazelCtx.GetOutputFiles(label, ctx.Arch().ArchType)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400230 if ok {
231 var bazelOutputFiles android.Paths
Chris Parsonse59af4e2021-03-31 13:32:41 -0400232 exportIncludeDirs := map[string]bool{}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400233 for _, bazelOutputFile := range filePaths {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500234 bazelOutputFiles = append(bazelOutputFiles, android.PathForBazelOut(ctx, bazelOutputFile))
Chris Parsonse59af4e2021-03-31 13:32:41 -0400235 exportIncludeDirs[filepath.Dir(bazelOutputFile)] = true
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400236 }
237 c.outputFiles = bazelOutputFiles
238 c.outputDeps = bazelOutputFiles
Chris Parsonse59af4e2021-03-31 13:32:41 -0400239 for includePath, _ := range exportIncludeDirs {
240 c.exportedIncludeDirs = append(c.exportedIncludeDirs, android.PathForBazelOut(ctx, includePath))
241 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400242 }
243 return ok
244}
Colin Crossf1885962020-11-20 15:28:30 -0800245
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700246func (g *Module) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Colin Crossa4ad2b02019-03-18 22:15:32 -0700247 g.subName = ctx.ModuleSubDir()
248
bralee1fbf4402020-05-21 10:11:59 +0800249 // Collect the module directory for IDE info in java/jdeps.go.
250 g.modulePaths = append(g.modulePaths, ctx.ModuleDir())
251
Colin Cross5ed99c62016-11-22 12:55:55 -0800252 if len(g.properties.Export_include_dirs) > 0 {
253 for _, dir := range g.properties.Export_include_dirs {
254 g.exportedIncludeDirs = append(g.exportedIncludeDirs,
Colin Cross1a527682019-09-23 15:55:30 -0700255 android.PathForModuleGen(ctx, g.subDir, ctx.ModuleDir(), dir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800256 }
257 } else {
Colin Cross1a527682019-09-23 15:55:30 -0700258 g.exportedIncludeDirs = append(g.exportedIncludeDirs, android.PathForModuleGen(ctx, g.subDir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800259 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700260
Colin Crossd11cf622021-03-23 22:30:35 -0700261 locationLabels := map[string]location{}
Colin Cross08f15ab2018-10-04 23:29:14 -0700262 firstLabel := ""
263
Colin Crossd11cf622021-03-23 22:30:35 -0700264 addLocationLabel := func(label string, loc location) {
Colin Cross08f15ab2018-10-04 23:29:14 -0700265 if firstLabel == "" {
266 firstLabel = label
267 }
268 if _, exists := locationLabels[label]; !exists {
Colin Crossd11cf622021-03-23 22:30:35 -0700269 locationLabels[label] = loc
Colin Cross08f15ab2018-10-04 23:29:14 -0700270 } else {
271 ctx.ModuleErrorf("multiple labels for %q, %q and %q",
Colin Crossd11cf622021-03-23 22:30:35 -0700272 label, locationLabels[label], loc)
Colin Cross08f15ab2018-10-04 23:29:14 -0700273 }
274 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700275
Colin Crossba9e4032020-11-24 16:32:22 -0800276 var tools android.Paths
277 var packagedTools []android.PackagingSpec
Colin Cross6f080df2016-11-04 15:32:58 -0700278 if len(g.properties.Tools) > 0 {
Colin Crossba71a3f2019-03-18 12:12:48 -0700279 seenTools := make(map[string]bool)
280
Colin Cross35143d02017-11-16 00:11:20 -0800281 ctx.VisitDirectDepsBlueprint(func(module blueprint.Module) {
Colin Cross08f15ab2018-10-04 23:29:14 -0700282 switch tag := ctx.OtherModuleDependencyTag(module).(type) {
283 case hostToolDependencyTag:
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700284 tool := ctx.OtherModuleName(module)
285
Colin Crossba9e4032020-11-24 16:32:22 -0800286 switch t := module.(type) {
287 case android.HostToolProvider:
288 // A HostToolProvider provides the path to a tool, which will be copied
289 // into the sandbox.
Colin Cross35143d02017-11-16 00:11:20 -0800290 if !t.(android.Module).Enabled() {
Colin Cross6510f912017-11-29 00:27:14 -0800291 if ctx.Config().AllowMissingDependencies() {
Colin Cross35143d02017-11-16 00:11:20 -0800292 ctx.AddMissingDependencies([]string{tool})
293 } else {
294 ctx.ModuleErrorf("depends on disabled module %q", tool)
295 }
Colin Crossba9e4032020-11-24 16:32:22 -0800296 return
Colin Cross35143d02017-11-16 00:11:20 -0800297 }
Colin Crossba9e4032020-11-24 16:32:22 -0800298 path := t.HostToolPath()
299 if !path.Valid() {
300 ctx.ModuleErrorf("host tool %q missing output file", tool)
301 return
302 }
303 if specs := t.TransitivePackagingSpecs(); specs != nil {
304 // If the HostToolProvider has PackgingSpecs, which are definitions of the
305 // required relative locations of the tool and its dependencies, use those
306 // instead. They will be copied to those relative locations in the sbox
307 // sandbox.
308 packagedTools = append(packagedTools, specs...)
309 // Assume that the first PackagingSpec of the module is the tool.
Colin Crossd11cf622021-03-23 22:30:35 -0700310 addLocationLabel(tag.label, packagedToolLocation{specs[0]})
Colin Crossba9e4032020-11-24 16:32:22 -0800311 } else {
312 tools = append(tools, path.Path())
Colin Crossd11cf622021-03-23 22:30:35 -0700313 addLocationLabel(tag.label, toolLocation{android.Paths{path.Path()}})
Colin Crossba9e4032020-11-24 16:32:22 -0800314 }
315 case bootstrap.GoBinaryTool:
316 // A GoBinaryTool provides the install path to a tool, which will be copied.
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700317 if s, err := filepath.Rel(android.PathForOutput(ctx).String(), t.InstallPath()); err == nil {
Colin Crossba9e4032020-11-24 16:32:22 -0800318 toolPath := android.PathForOutput(ctx, s)
319 tools = append(tools, toolPath)
Colin Crossd11cf622021-03-23 22:30:35 -0700320 addLocationLabel(tag.label, toolLocation{android.Paths{toolPath}})
Colin Cross6f080df2016-11-04 15:32:58 -0700321 } else {
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700322 ctx.ModuleErrorf("cannot find path for %q: %v", tool, err)
Colin Crossba9e4032020-11-24 16:32:22 -0800323 return
Colin Cross6f080df2016-11-04 15:32:58 -0700324 }
Colin Crossba9e4032020-11-24 16:32:22 -0800325 default:
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700326 ctx.ModuleErrorf("%q is not a host tool provider", tool)
Colin Crossba9e4032020-11-24 16:32:22 -0800327 return
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700328 }
329
Colin Crossba9e4032020-11-24 16:32:22 -0800330 seenTools[tag.label] = true
Colin Crossd350ecd2015-04-28 13:25:36 -0700331 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700332 })
Colin Crossba71a3f2019-03-18 12:12:48 -0700333
334 // If AllowMissingDependencies is enabled, the build will not have stopped when
335 // AddFarVariationDependencies was called on a missing tool, which will result in nonsensical
Liz Kammer20ebfb42020-07-28 11:32:07 -0700336 // "cmd: unknown location label ..." errors later. Add a placeholder file to the local label.
337 // The command that uses this placeholder file will never be executed because the rule will be
338 // replaced with an android.Error rule reporting the missing dependencies.
Colin Crossba71a3f2019-03-18 12:12:48 -0700339 if ctx.Config().AllowMissingDependencies() {
340 for _, tool := range g.properties.Tools {
341 if !seenTools[tool] {
Colin Crossd11cf622021-03-23 22:30:35 -0700342 addLocationLabel(tool, errorLocation{"***missing tool " + tool + "***"})
Colin Crossba71a3f2019-03-18 12:12:48 -0700343 }
344 }
345 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700346 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700347
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700348 if ctx.Failed() {
349 return
350 }
351
Colin Cross08f15ab2018-10-04 23:29:14 -0700352 for _, toolFile := range g.properties.Tool_files {
Colin Cross8a497952019-03-05 22:25:09 -0800353 paths := android.PathsForModuleSrc(ctx, []string{toolFile})
Colin Crossba9e4032020-11-24 16:32:22 -0800354 tools = append(tools, paths...)
Colin Crossd11cf622021-03-23 22:30:35 -0700355 addLocationLabel(toolFile, toolLocation{paths})
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)
Colin Crossd11cf622021-03-23 22:30:35 -0700373 addLocationLabel(in, errorLocation{"***missing srcs " + in + "***"})
Colin Crossba71a3f2019-03-18 12:12:48 -0700374 } else {
375 srcFiles = append(srcFiles, paths...)
Colin Crossd11cf622021-03-23 22:30:35 -0700376 addLocationLabel(in, inputLocation{paths})
Colin Crossba71a3f2019-03-18 12:12:48 -0700377 }
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 Crossd11cf622021-03-23 22:30:35 -0700411 addLocationLabel(out.Rel(), outputLocation{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 Crossd11cf622021-03-23 22:30:35 -0700429 loc := locationLabels[firstLabel]
430 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700431 if len(paths) == 0 {
432 return reportError("default label %q has no files", firstLabel)
433 } else if len(paths) > 1 {
434 return reportError("default label %q has multiple files, use $(locations %s) to reference it",
435 firstLabel, firstLabel)
Colin Cross08f15ab2018-10-04 23:29:14 -0700436 }
Colin Crossd11cf622021-03-23 22:30:35 -0700437 return paths[0], nil
Colin Cross1a527682019-09-23 15:55:30 -0700438 case "in":
Colin Crossd11cf622021-03-23 22:30:35 -0700439 return strings.Join(cmd.PathsForInputs(srcFiles), " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700440 case "out":
Colin Cross3d680512020-11-13 16:23:53 -0800441 var sandboxOuts []string
442 for _, out := range task.out {
Colin Crossf1a035e2020-11-16 17:32:30 -0800443 sandboxOuts = append(sandboxOuts, cmd.PathForOutput(out))
Colin Cross3d680512020-11-13 16:23:53 -0800444 }
445 return strings.Join(sandboxOuts, " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700446 case "depfile":
447 referencedDepfile = true
448 if !Bool(g.properties.Depfile) {
449 return reportError("$(depfile) used without depfile property")
450 }
Colin Cross3d680512020-11-13 16:23:53 -0800451 return "__SBOX_DEPFILE__", nil
Colin Cross1a527682019-09-23 15:55:30 -0700452 case "genDir":
Colin Crossf1a035e2020-11-16 17:32:30 -0800453 return cmd.PathForOutput(task.genDir), nil
Colin Cross1a527682019-09-23 15:55:30 -0700454 default:
455 if strings.HasPrefix(name, "location ") {
456 label := strings.TrimSpace(strings.TrimPrefix(name, "location "))
Colin Crossd11cf622021-03-23 22:30:35 -0700457 if loc, ok := locationLabels[label]; ok {
458 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700459 if len(paths) == 0 {
460 return reportError("label %q has no files", label)
461 } else if len(paths) > 1 {
462 return reportError("label %q has multiple files, use $(locations %s) to reference it",
463 label, label)
464 }
Colin Cross3d680512020-11-13 16:23:53 -0800465 return paths[0], nil
Colin Cross1a527682019-09-23 15:55:30 -0700466 } else {
467 return reportError("unknown location label %q", label)
468 }
469 } else if strings.HasPrefix(name, "locations ") {
470 label := strings.TrimSpace(strings.TrimPrefix(name, "locations "))
Colin Crossd11cf622021-03-23 22:30:35 -0700471 if loc, ok := locationLabels[label]; ok {
472 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700473 if len(paths) == 0 {
474 return reportError("label %q has no files", label)
475 }
Colin Cross3d680512020-11-13 16:23:53 -0800476 return strings.Join(paths, " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700477 } else {
478 return reportError("unknown locations label %q", label)
479 }
480 } else {
481 return reportError("unknown variable '$(%s)'", name)
482 }
Colin Cross6f080df2016-11-04 15:32:58 -0700483 }
Colin Cross1a527682019-09-23 15:55:30 -0700484 })
485
486 if err != nil {
487 ctx.PropertyErrorf("cmd", "%s", err.Error())
488 return
Colin Cross6f080df2016-11-04 15:32:58 -0700489 }
Colin Cross6f080df2016-11-04 15:32:58 -0700490
Colin Cross1a527682019-09-23 15:55:30 -0700491 if Bool(g.properties.Depfile) && !referencedDepfile {
492 ctx.PropertyErrorf("cmd", "specified depfile=true but did not include a reference to '${depfile}' in cmd")
493 return
494 }
Colin Cross1a527682019-09-23 15:55:30 -0700495 g.rawCommands = append(g.rawCommands, rawCommand)
Bill Peckhamc087be12020-02-13 15:55:10 -0800496
Colin Cross3d680512020-11-13 16:23:53 -0800497 cmd.Text(rawCommand)
498 cmd.ImplicitOutputs(task.out)
499 cmd.Implicits(task.in)
Colin Crossba9e4032020-11-24 16:32:22 -0800500 cmd.ImplicitTools(tools)
501 cmd.ImplicitTools(task.extraTools)
502 cmd.ImplicitPackagedTools(packagedTools)
Colin Cross3d680512020-11-13 16:23:53 -0800503 if Bool(g.properties.Depfile) {
504 cmd.ImplicitDepFile(task.depFile)
505 }
506
507 // Create the rule to run the genrule command inside sbox.
Colin Crossf1a035e2020-11-16 17:32:30 -0800508 rule.Build(name, desc)
Colin Cross1a527682019-09-23 15:55:30 -0700509
510 if len(task.copyTo) > 0 {
Colin Cross3d680512020-11-13 16:23:53 -0800511 // If copyTo is set, multiple shards need to be copied into a single directory.
512 // task.out contains the per-shard paths, and copyTo contains the corresponding
513 // final path. The files need to be copied into the final directory by a
514 // single rule so it can remove the directory before it starts to ensure no
515 // old files remain. zipsync already does this, so build up zipArgs that
516 // zip all the per-shard directories into a single zip.
Colin Cross1a527682019-09-23 15:55:30 -0700517 outputFiles = append(outputFiles, task.copyTo...)
518 copyFrom = append(copyFrom, task.out.Paths()...)
519 zipArgs.WriteString(" -C " + task.genDir.String())
520 zipArgs.WriteString(android.JoinWithPrefix(task.out.Strings(), " -f "))
521 } else {
522 outputFiles = append(outputFiles, task.out...)
523 }
Colin Cross6f080df2016-11-04 15:32:58 -0700524 }
525
Colin Cross1a527682019-09-23 15:55:30 -0700526 if len(copyFrom) > 0 {
Colin Cross3d680512020-11-13 16:23:53 -0800527 // Create a rule that zips all the per-shard directories into a single zip and then
528 // uses zipsync to unzip it into the final directory.
Colin Cross1a527682019-09-23 15:55:30 -0700529 ctx.Build(pctx, android.BuildParams{
Colin Crossf1885962020-11-20 15:28:30 -0800530 Rule: gensrcsMerge,
531 Implicits: copyFrom,
532 Outputs: outputFiles,
533 Description: "merge shards",
Colin Cross1a527682019-09-23 15:55:30 -0700534 Args: map[string]string{
535 "zipArgs": zipArgs.String(),
536 "tmpZip": android.PathForModuleGen(ctx, g.subDir+".zip").String(),
537 "genDir": android.PathForModuleGen(ctx, g.subDir).String(),
538 },
539 })
Colin Cross85a2e892018-07-09 09:45:06 -0700540 }
541
Colin Cross1a527682019-09-23 15:55:30 -0700542 g.outputFiles = outputFiles.Paths()
Jeff Gastonefc1b412017-03-29 17:29:06 -0700543
Liz Kammerbdc60992021-02-24 16:55:11 -0500544 bazelModuleLabel := g.GetBazelLabel(ctx, g)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400545 bazelActionsUsed := false
Chris Parsonsbab4d7e2021-04-15 17:27:08 -0400546 if g.MixedBuildsEnabled(ctx) {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400547 bazelActionsUsed = g.generateBazelBuildActions(ctx, bazelModuleLabel)
Jeff Gaston02a684b2017-10-27 14:59:27 -0700548 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400549 if !bazelActionsUsed {
550 // For <= 6 outputs, just embed those directly in the users. Right now, that covers >90% of
551 // the genrules on AOSP. That will make things simpler to look at the graph in the common
552 // case. For larger sets of outputs, inject a phony target in between to limit ninja file
553 // growth.
554 if len(g.outputFiles) <= 6 {
555 g.outputDeps = g.outputFiles
556 } else {
557 phonyFile := android.PathForModuleGen(ctx, "genrule-phony")
558 ctx.Build(pctx, android.BuildParams{
559 Rule: blueprint.Phony,
560 Output: phonyFile,
561 Inputs: g.outputFiles,
562 })
563 g.outputDeps = android.Paths{phonyFile}
564 }
565 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700566}
Colin Crossd350ecd2015-04-28 13:25:36 -0700567
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700568// Collect information for opening IDE project files in java/jdeps.go.
569func (g *Module) IDEInfo(dpInfo *android.IdeInfo) {
570 dpInfo.Srcs = append(dpInfo.Srcs, g.Srcs().Strings()...)
571 for _, src := range g.properties.Srcs {
572 if strings.HasPrefix(src, ":") {
573 src = strings.Trim(src, ":")
574 dpInfo.Deps = append(dpInfo.Deps, src)
575 }
576 }
bralee1fbf4402020-05-21 10:11:59 +0800577 dpInfo.Paths = append(dpInfo.Paths, g.modulePaths...)
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700578}
579
Colin Crossa4ad2b02019-03-18 22:15:32 -0700580func (g *Module) AndroidMk() android.AndroidMkData {
581 return android.AndroidMkData{
Anton Hansson72f18492020-10-30 16:34:45 +0000582 Class: "ETC",
Colin Crossa4ad2b02019-03-18 22:15:32 -0700583 OutputFile: android.OptionalPathForPath(g.outputFiles[0]),
584 SubName: g.subName,
585 Extra: []android.AndroidMkExtraFunc{
586 func(w io.Writer, outputFile android.Path) {
Anton Hansson72f18492020-10-30 16:34:45 +0000587 fmt.Fprintln(w, "LOCAL_UNINSTALLABLE_MODULE := true")
Colin Crossa4ad2b02019-03-18 22:15:32 -0700588 },
589 },
590 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
591 android.WriteAndroidMkData(w, data)
592 if data.SubName != "" {
593 fmt.Fprintln(w, ".PHONY:", name)
594 fmt.Fprintln(w, name, ":", name+g.subName)
595 }
596 },
597 }
598}
599
Jiyong Park45bf82e2020-12-15 22:29:02 +0900600var _ android.ApexModule = (*Module)(nil)
601
602// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -0700603func (g *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
604 sdkVersion android.ApiLevel) error {
Jooyung Han749dc692020-04-15 11:03:39 +0900605 // Because generated outputs are checked by client modules(e.g. cc_library, ...)
606 // we can safely ignore the check here.
607 return nil
608}
609
Jeff Gaston437d23c2017-11-08 12:38:00 -0800610func generatorFactory(taskGenerator taskFunc, props ...interface{}) *Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700611 module := &Module{
Jeff Gaston437d23c2017-11-08 12:38:00 -0800612 taskGenerator: taskGenerator,
Colin Crossd350ecd2015-04-28 13:25:36 -0700613 }
614
Colin Cross36242852017-06-23 15:06:31 -0700615 module.AddProperties(props...)
616 module.AddProperties(&module.properties)
Colin Crossd350ecd2015-04-28 13:25:36 -0700617
Colin Cross7228ecd2019-11-18 16:00:16 -0800618 module.ImageInterface = noopImageInterface{}
619
Colin Cross36242852017-06-23 15:06:31 -0700620 return module
Colin Crossd350ecd2015-04-28 13:25:36 -0700621}
622
Colin Cross7228ecd2019-11-18 16:00:16 -0800623type noopImageInterface struct{}
624
625func (x noopImageInterface) ImageMutatorBegin(android.BaseModuleContext) {}
626func (x noopImageInterface) CoreVariantNeeded(android.BaseModuleContext) bool { return false }
Yifan Hong1b3348d2020-01-21 15:53:22 -0800627func (x noopImageInterface) RamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700628func (x noopImageInterface) VendorRamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Inseob Kimf84e9c02021-04-08 21:13:22 +0900629func (x noopImageInterface) DebugRamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Colin Cross7228ecd2019-11-18 16:00:16 -0800630func (x noopImageInterface) RecoveryVariantNeeded(android.BaseModuleContext) bool { return false }
631func (x noopImageInterface) ExtraImageVariations(ctx android.BaseModuleContext) []string { return nil }
632func (x noopImageInterface) SetImageVariation(ctx android.BaseModuleContext, variation string, module android.Module) {
633}
634
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700635func NewGenSrcs() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700636 properties := &genSrcsProperties{}
637
Colin Crossf1885962020-11-20 15:28:30 -0800638 // finalSubDir is the name of the subdirectory that output files will be generated into.
639 // It is used so that per-shard directories can be placed alongside it an then finally
640 // merged into it.
641 const finalSubDir = "gensrcs"
642
Colin Cross1a527682019-09-23 15:55:30 -0700643 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Colin Cross1a527682019-09-23 15:55:30 -0700644 shardSize := defaultShardSize
645 if s := properties.Shard_size; s != nil {
646 shardSize = int(*s)
647 }
Jeff Gaston437d23c2017-11-08 12:38:00 -0800648
Colin Crossf1885962020-11-20 15:28:30 -0800649 // gensrcs rules can easily hit command line limits by repeating the command for
650 // every input file. Shard the input files into groups.
Colin Cross1a527682019-09-23 15:55:30 -0700651 shards := android.ShardPaths(srcFiles, shardSize)
652 var generateTasks []generateTask
Colin Crossbaccf5b2018-02-21 14:07:48 -0800653
Colin Cross1a527682019-09-23 15:55:30 -0700654 for i, shard := range shards {
655 var commands []string
656 var outFiles android.WritablePaths
Colin Cross3ea4eb82020-11-24 13:07:27 -0800657 var commandDepFiles []string
Colin Cross1a527682019-09-23 15:55:30 -0700658 var copyTo android.WritablePaths
Colin Cross1a527682019-09-23 15:55:30 -0700659
Colin Crossf1885962020-11-20 15:28:30 -0800660 // When sharding is enabled (i.e. len(shards) > 1), the sbox rules for each
661 // shard will be write to their own directories and then be merged together
662 // into finalSubDir. If sharding is not enabled (i.e. len(shards) == 1),
663 // the sbox rule will write directly to finalSubDir.
664 genSubDir := finalSubDir
Colin Cross1a527682019-09-23 15:55:30 -0700665 if len(shards) > 1 {
Colin Crossf1885962020-11-20 15:28:30 -0800666 genSubDir = strconv.Itoa(i)
Jeff Gaston437d23c2017-11-08 12:38:00 -0800667 }
668
Colin Crossf1885962020-11-20 15:28:30 -0800669 genDir := android.PathForModuleGen(ctx, genSubDir)
Colin Crossf1a035e2020-11-16 17:32:30 -0800670 // TODO(ccross): this RuleBuilder is a hack to be able to call
671 // rule.Command().PathForOutput. Replace this with passing the rule into the
672 // generator.
Colin Crossba9e4032020-11-24 16:32:22 -0800673 rule := android.NewRuleBuilder(pctx, ctx).Sbox(genDir, nil).SandboxTools()
Jeff Gaston437d23c2017-11-08 12:38:00 -0800674
Colin Cross3ea4eb82020-11-24 13:07:27 -0800675 for _, in := range shard {
Colin Crossf1885962020-11-20 15:28:30 -0800676 outFile := android.GenPathWithExt(ctx, finalSubDir, in, String(properties.Output_extension))
677
678 // If sharding is enabled, then outFile is the path to the output file in
679 // the shard directory, and copyTo is the path to the output file in the
680 // final directory.
Colin Cross1a527682019-09-23 15:55:30 -0700681 if len(shards) > 1 {
Colin Crossf1885962020-11-20 15:28:30 -0800682 shardFile := android.GenPathWithExt(ctx, genSubDir, in, String(properties.Output_extension))
Colin Cross1a527682019-09-23 15:55:30 -0700683 copyTo = append(copyTo, outFile)
684 outFile = shardFile
685 }
686
687 outFiles = append(outFiles, outFile)
Colin Cross1a527682019-09-23 15:55:30 -0700688
Colin Crossf1885962020-11-20 15:28:30 -0800689 // pre-expand the command line to replace $in and $out with references to
690 // a single input and output file.
Colin Cross1a527682019-09-23 15:55:30 -0700691 command, err := android.Expand(rawCommand, func(name string) (string, error) {
692 switch name {
693 case "in":
694 return in.String(), nil
695 case "out":
Colin Crossf1a035e2020-11-16 17:32:30 -0800696 return rule.Command().PathForOutput(outFile), nil
Colin Cross3ea4eb82020-11-24 13:07:27 -0800697 case "depfile":
698 // Generate a depfile for each output file. Store the list for
699 // later in order to combine them all into a single depfile.
Colin Crossf1a035e2020-11-16 17:32:30 -0800700 depFile := rule.Command().PathForOutput(outFile.ReplaceExtension(ctx, "d"))
Colin Cross3ea4eb82020-11-24 13:07:27 -0800701 commandDepFiles = append(commandDepFiles, depFile)
702 return depFile, nil
Colin Cross1a527682019-09-23 15:55:30 -0700703 default:
704 return "$(" + name + ")", nil
705 }
706 })
707 if err != nil {
708 ctx.PropertyErrorf("cmd", err.Error())
709 }
710
711 // escape the command in case for example it contains '#', an odd number of '"', etc
712 command = fmt.Sprintf("bash -c %v", proptools.ShellEscape(command))
713 commands = append(commands, command)
714 }
715 fullCommand := strings.Join(commands, " && ")
716
Colin Cross3ea4eb82020-11-24 13:07:27 -0800717 var outputDepfile android.WritablePath
718 var extraTools android.Paths
719 if len(commandDepFiles) > 0 {
720 // Each command wrote to a depfile, but ninja can only handle one
721 // depfile per rule. Use the dep_fixer tool at the end of the
722 // command to combine all the depfiles into a single output depfile.
723 outputDepfile = android.PathForModuleGen(ctx, genSubDir, "gensrcs.d")
724 depFixerTool := ctx.Config().HostToolPath(ctx, "dep_fixer")
725 fullCommand += fmt.Sprintf(" && %s -o $(depfile) %s",
Colin Crossd11cf622021-03-23 22:30:35 -0700726 rule.Command().PathForTool(depFixerTool),
Colin Crossba9e4032020-11-24 16:32:22 -0800727 strings.Join(commandDepFiles, " "))
Colin Cross3ea4eb82020-11-24 13:07:27 -0800728 extraTools = append(extraTools, depFixerTool)
729 }
730
Colin Cross1a527682019-09-23 15:55:30 -0700731 generateTasks = append(generateTasks, generateTask{
Colin Cross3ea4eb82020-11-24 13:07:27 -0800732 in: shard,
733 out: outFiles,
734 depFile: outputDepfile,
735 copyTo: copyTo,
736 genDir: genDir,
737 cmd: fullCommand,
738 shard: i,
739 shards: len(shards),
740 extraTools: extraTools,
Colin Cross1a527682019-09-23 15:55:30 -0700741 })
Jeff Gaston437d23c2017-11-08 12:38:00 -0800742 }
Colin Cross1a527682019-09-23 15:55:30 -0700743
744 return generateTasks
Colin Crossd350ecd2015-04-28 13:25:36 -0700745 }
746
Colin Cross1a527682019-09-23 15:55:30 -0700747 g := generatorFactory(taskGenerator, properties)
Colin Crossf1885962020-11-20 15:28:30 -0800748 g.subDir = finalSubDir
Colin Cross1a527682019-09-23 15:55:30 -0700749 return g
Colin Crossd350ecd2015-04-28 13:25:36 -0700750}
751
Colin Cross54190b32017-10-09 15:34:10 -0700752func GenSrcsFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700753 m := NewGenSrcs()
754 android.InitAndroidModule(m)
755 return m
756}
757
Colin Crossd350ecd2015-04-28 13:25:36 -0700758type genSrcsProperties struct {
Colin Cross7d5136f2015-05-11 13:39:40 -0700759 // extension that will be substituted for each output file
Nan Zhanga5e7cb42017-11-09 22:42:32 -0800760 Output_extension *string
Colin Cross1a527682019-09-23 15:55:30 -0700761
762 // maximum number of files that will be passed on a single command line.
763 Shard_size *int64
Colin Cross5049f022015-03-18 13:28:46 -0700764}
765
Evgenii Stepanovf47c90d2020-12-02 18:55:09 -0800766const defaultShardSize = 50
Colin Cross1a527682019-09-23 15:55:30 -0700767
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700768func NewGenRule() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700769 properties := &genRuleProperties{}
Colin Cross5049f022015-03-18 13:28:46 -0700770
Colin Cross1a527682019-09-23 15:55:30 -0700771 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700772 outs := make(android.WritablePaths, len(properties.Out))
Colin Cross3d680512020-11-13 16:23:53 -0800773 var depFile android.WritablePath
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700774 for i, out := range properties.Out {
Colin Cross3d680512020-11-13 16:23:53 -0800775 outPath := android.PathForModuleGen(ctx, out)
776 if i == 0 {
777 depFile = outPath.ReplaceExtension(ctx, "d")
778 }
779 outs[i] = outPath
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700780 }
Colin Cross1a527682019-09-23 15:55:30 -0700781 return []generateTask{{
Colin Cross3d680512020-11-13 16:23:53 -0800782 in: srcFiles,
783 out: outs,
784 depFile: depFile,
785 genDir: android.PathForModuleGen(ctx),
786 cmd: rawCommand,
Colin Cross1a527682019-09-23 15:55:30 -0700787 }}
Colin Cross5049f022015-03-18 13:28:46 -0700788 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700789
Jeff Gaston437d23c2017-11-08 12:38:00 -0800790 return generatorFactory(taskGenerator, properties)
Colin Cross5049f022015-03-18 13:28:46 -0700791}
792
Colin Cross54190b32017-10-09 15:34:10 -0700793func GenRuleFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700794 m := NewGenRule()
795 android.InitAndroidModule(m)
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800796 android.InitDefaultableModule(m)
Liz Kammerea6666f2021-02-17 10:17:28 -0500797 android.InitBazelModule(m)
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700798 return m
799}
800
Colin Crossd350ecd2015-04-28 13:25:36 -0700801type genRuleProperties struct {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700802 // names of the output files that will be generated
Colin Crossef354482018-10-23 11:27:50 -0700803 Out []string `android:"arch_variant"`
Colin Cross5049f022015-03-18 13:28:46 -0700804}
Nan Zhangea568a42017-11-08 21:20:04 -0800805
Jingwen Chen316e07c2020-12-14 09:09:52 -0500806type bazelGenruleAttributes struct {
Jingwen Chen07027912021-03-15 06:02:43 -0400807 Srcs bazel.LabelListAttribute
Jingwen Chen316e07c2020-12-14 09:09:52 -0500808 Outs []string
Jingwen Chen07027912021-03-15 06:02:43 -0400809 Tools bazel.LabelListAttribute
Jingwen Chen316e07c2020-12-14 09:09:52 -0500810 Cmd string
811}
812
813type bazelGenrule struct {
814 android.BazelTargetModuleBase
815 bazelGenruleAttributes
816}
817
818func BazelGenruleFactory() android.Module {
819 module := &bazelGenrule{}
820 module.AddProperties(&module.bazelGenruleAttributes)
821 android.InitBazelTargetModule(module)
822 return module
823}
824
Jingwen Chena42d6412021-01-26 21:57:27 -0500825func GenruleBp2Build(ctx android.TopDownMutatorContext) {
Liz Kammer356f7d42021-01-26 09:18:53 -0500826 m, ok := ctx.Module().(*Module)
Jingwen Chen12b4c272021-03-10 02:05:59 -0500827 if !ok || !m.ConvertWithBp2build(ctx) {
Liz Kammer356f7d42021-01-26 09:18:53 -0500828 return
Jingwen Chen316e07c2020-12-14 09:09:52 -0500829 }
Jingwen Chen1fd14692021-02-05 03:01:50 -0500830
Jingwen Chen66480452021-03-18 03:41:55 -0400831 if ctx.ModuleType() != "genrule" {
832 // Not a regular genrule. Could be a cc_genrule or java_genrule.
833 return
834 }
835
Liz Kammer356f7d42021-01-26 09:18:53 -0500836 // Bazel only has the "tools" attribute.
Jingwen Chen07027912021-03-15 06:02:43 -0400837 tools_prop := android.BazelLabelForModuleDeps(ctx, m.properties.Tools)
838 tool_files_prop := android.BazelLabelForModuleSrc(ctx, m.properties.Tool_files)
839 tools_prop.Append(tool_files_prop)
Liz Kammer356f7d42021-01-26 09:18:53 -0500840
Jingwen Chen07027912021-03-15 06:02:43 -0400841 tools := bazel.MakeLabelListAttribute(tools_prop)
842 srcs := bazel.MakeLabelListAttribute(android.BazelLabelForModuleSrc(ctx, m.properties.Srcs))
Liz Kammer356f7d42021-01-26 09:18:53 -0500843
844 var allReplacements bazel.LabelList
Jingwen Chen07027912021-03-15 06:02:43 -0400845 allReplacements.Append(tools.Value)
846 allReplacements.Append(srcs.Value)
Liz Kammer356f7d42021-01-26 09:18:53 -0500847
848 // Replace in and out variables with $< and $@
849 var cmd string
850 if m.properties.Cmd != nil {
851 cmd = strings.Replace(*m.properties.Cmd, "$(in)", "$(SRCS)", -1)
852 cmd = strings.Replace(cmd, "$(out)", "$(OUTS)", -1)
853 cmd = strings.Replace(cmd, "$(genDir)", "$(GENDIR)", -1)
Jingwen Chen07027912021-03-15 06:02:43 -0400854 if len(tools.Value.Includes) > 0 {
855 cmd = strings.Replace(cmd, "$(location)", fmt.Sprintf("$(location %s)", tools.Value.Includes[0].Label), -1)
856 cmd = strings.Replace(cmd, "$(locations)", fmt.Sprintf("$(locations %s)", tools.Value.Includes[0].Label), -1)
Liz Kammer356f7d42021-01-26 09:18:53 -0500857 }
858 for _, l := range allReplacements.Includes {
Jingwen Chen38e62642021-04-19 05:00:15 +0000859 bpLoc := fmt.Sprintf("$(location %s)", l.OriginalModuleName)
860 bpLocs := fmt.Sprintf("$(locations %s)", l.OriginalModuleName)
Liz Kammer356f7d42021-01-26 09:18:53 -0500861 bazelLoc := fmt.Sprintf("$(location %s)", l.Label)
862 bazelLocs := fmt.Sprintf("$(locations %s)", l.Label)
863 cmd = strings.Replace(cmd, bpLoc, bazelLoc, -1)
864 cmd = strings.Replace(cmd, bpLocs, bazelLocs, -1)
865 }
866 }
867
868 // The Out prop is not in an immediately accessible field
869 // in the Module struct, so use GetProperties and cast it
870 // to the known struct prop.
871 var outs []string
872 for _, propIntf := range m.GetProperties() {
873 if props, ok := propIntf.(*genRuleProperties); ok {
874 outs = props.Out
875 break
876 }
877 }
878
Jingwen Chen1fd14692021-02-05 03:01:50 -0500879 attrs := &bazelGenruleAttributes{
Liz Kammer356f7d42021-01-26 09:18:53 -0500880 Srcs: srcs,
881 Outs: outs,
882 Cmd: cmd,
883 Tools: tools,
Jingwen Chen1fd14692021-02-05 03:01:50 -0500884 }
885
Liz Kammerfc46bc12021-02-19 11:06:17 -0500886 props := bazel.BazelTargetModuleProperties{
887 Rule_class: "genrule",
888 }
Jingwen Chen1fd14692021-02-05 03:01:50 -0500889
890 // Create the BazelTargetModule.
Liz Kammerfc46bc12021-02-19 11:06:17 -0500891 ctx.CreateBazelTargetModule(BazelGenruleFactory, m.Name(), props, attrs)
Jingwen Chen316e07c2020-12-14 09:09:52 -0500892}
893
894func (m *bazelGenrule) Name() string {
895 return m.BaseModuleName()
896}
897
898func (m *bazelGenrule) GenerateAndroidBuildActions(ctx android.ModuleContext) {}
899
Nan Zhangea568a42017-11-08 21:20:04 -0800900var Bool = proptools.Bool
901var String = proptools.String
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800902
903//
904// Defaults
905//
906type Defaults struct {
907 android.ModuleBase
908 android.DefaultsModuleBase
909}
910
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800911func defaultsFactory() android.Module {
912 return DefaultsFactory()
913}
914
915func DefaultsFactory(props ...interface{}) android.Module {
916 module := &Defaults{}
917
918 module.AddProperties(props...)
919 module.AddProperties(
920 &generatorProperties{},
921 &genRuleProperties{},
922 )
923
924 android.InitDefaultsModule(module)
925
926 return module
927}