blob: e7343a22dfdbba9435ead6539ea6077fd4fb3c20 [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
Jingwen Chena42d6412021-01-26 21:57:27 -050071 android.RegisterBp2BuildMutator("genrule", GenruleBp2Build)
Wei Libcd39942021-09-16 23:57:28 +000072 android.RegisterBp2BuildMutator("cc_genrule", CcGenruleBp2Build)
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 Cross65cb3142021-12-10 23:05:02 +0000113 android.LicenseAnnotationToolchainDependencyTag
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 {
Spandan Das93e95992021-07-29 18:26:39 +0000117 // 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 //
Spandan Das93e95992021-07-29 18:26:39 +0000121 // $(location): the path to the first entry in tools or tool_files.
122 // $(location <label>): the path to the tool, tool_file, input or output with name <label>. Use $(location) if <label> refers to a rule that outputs exactly one file.
123 // $(locations <label>): the paths to the tools, tool_files, inputs or outputs with name <label>. Use $(locations) if <label> refers to a rule that outputs two or more files.
124 // $(in): one or more input files.
125 // $(out): a single output file.
126 // $(depfile): a file to which dependencies will be written, if the depfile property is set to true.
127 // $(genDir): the sandbox directory for this tool; contains $(out).
Colin Cross2296f5b2017-10-17 21:38:14 -0700128 // $$: a literal $
Nan Zhangea568a42017-11-08 21:20:04 -0800129 Cmd *string
Colin Cross7d5136f2015-05-11 13:39:40 -0700130
Colin Cross33bfb0a2016-11-21 17:23:08 -0800131 // Enable reading a file containing dependencies in gcc format after the command completes
Nan Zhangea568a42017-11-08 21:20:04 -0800132 Depfile *bool
Colin Cross33bfb0a2016-11-21 17:23:08 -0800133
Colin Cross6f080df2016-11-04 15:32:58 -0700134 // name of the modules (if any) that produces the host executable. Leave empty for
Colin Cross7d5136f2015-05-11 13:39:40 -0700135 // prebuilts or scripts that do not need a module to build them.
Colin Cross6f080df2016-11-04 15:32:58 -0700136 Tools []string
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700137
138 // Local file that is used as the tool
Colin Cross27b922f2019-03-04 22:35:41 -0800139 Tool_files []string `android:"path"`
Colin Cross5ed99c62016-11-22 12:55:55 -0800140
141 // List of directories to export generated headers from
142 Export_include_dirs []string
Colin Cross708c4242017-01-13 18:05:49 -0800143
144 // list of input files
Colin Cross27b922f2019-03-04 22:35:41 -0800145 Srcs []string `android:"path,arch_variant"`
Dan Willemseneefa0262018-11-17 14:01:18 -0800146
147 // input files to exclude
Colin Cross27b922f2019-03-04 22:35:41 -0800148 Exclude_srcs []string `android:"path,arch_variant"`
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400149}
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500150
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700151type Module struct {
Colin Cross635c3b02016-05-18 15:37:25 -0700152 android.ModuleBase
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800153 android.DefaultableModuleBase
Liz Kammerea6666f2021-02-17 10:17:28 -0500154 android.BazelModuleBase
Jiyong Parkfc752ca2019-06-12 13:27:29 +0900155 android.ApexModuleBase
Colin Crossd350ecd2015-04-28 13:25:36 -0700156
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700157 // For other packages to make their own genrules with extra
158 // properties
159 Extra interface{}
Colin Crossf3bfd022021-09-27 15:15:06 -0700160
161 // CmdModifier can be set by wrappers around genrule to modify the command, for example to
162 // prefix environment variables to it.
163 CmdModifier func(ctx android.ModuleContext, cmd string) string
164
Colin Cross7228ecd2019-11-18 16:00:16 -0800165 android.ImageInterface
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700166
Colin Cross7d5136f2015-05-11 13:39:40 -0700167 properties generatorProperties
Colin Crossd350ecd2015-04-28 13:25:36 -0700168
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500169 // For the different tasks that genrule and gensrc generate. genrule will
170 // generate 1 task, and gensrc will generate 1 or more tasks based on the
171 // number of shards the input files are sharded into.
Jeff Gaston437d23c2017-11-08 12:38:00 -0800172 taskGenerator taskFunc
Colin Crossd350ecd2015-04-28 13:25:36 -0700173
Colin Cross1a527682019-09-23 15:55:30 -0700174 rule blueprint.Rule
175 rawCommands []string
Colin Crossd350ecd2015-04-28 13:25:36 -0700176
Colin Cross5ed99c62016-11-22 12:55:55 -0800177 exportedIncludeDirs android.Paths
Dan Willemsenb40aab62016-04-20 14:21:14 -0700178
Colin Cross635c3b02016-05-18 15:37:25 -0700179 outputFiles android.Paths
Dan Willemsen9da9d492018-02-21 18:28:18 -0800180 outputDeps android.Paths
Colin Crossa4ad2b02019-03-18 22:15:32 -0700181
182 subName string
Colin Cross1a527682019-09-23 15:55:30 -0700183 subDir string
bralee1fbf4402020-05-21 10:11:59 +0800184
185 // Collect the module directory for IDE info in java/jdeps.go.
186 modulePaths []string
Colin Crossd350ecd2015-04-28 13:25:36 -0700187}
188
Colin Cross1a527682019-09-23 15:55:30 -0700189type taskFunc func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask
Colin Crossd350ecd2015-04-28 13:25:36 -0700190
191type generateTask struct {
Colin Cross3ea4eb82020-11-24 13:07:27 -0800192 in android.Paths
193 out android.WritablePaths
194 depFile android.WritablePath
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500195 copyTo android.WritablePaths // For gensrcs to set on gensrcsMerge rule.
Colin Cross3ea4eb82020-11-24 13:07:27 -0800196 genDir android.WritablePath
197 extraTools android.Paths // dependencies on tools used by the generator
198
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500199 cmd string
200 // For gensrsc sharding.
Colin Cross3ea4eb82020-11-24 13:07:27 -0800201 shard int
202 shards int
Colin Crossd350ecd2015-04-28 13:25:36 -0700203}
204
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700205func (g *Module) GeneratedSourceFiles() android.Paths {
Colin Crossd350ecd2015-04-28 13:25:36 -0700206 return g.outputFiles
207}
208
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700209func (g *Module) Srcs() android.Paths {
Nan Zhange42777a2018-03-27 16:19:42 -0700210 return append(android.Paths{}, g.outputFiles...)
Colin Cross068e0fe2016-12-13 15:23:47 -0800211}
212
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700213func (g *Module) GeneratedHeaderDirs() android.Paths {
Colin Cross5ed99c62016-11-22 12:55:55 -0800214 return g.exportedIncludeDirs
Dan Willemsenb40aab62016-04-20 14:21:14 -0700215}
216
Dan Willemsen9da9d492018-02-21 18:28:18 -0800217func (g *Module) GeneratedDeps() android.Paths {
218 return g.outputDeps
219}
220
Jooyung Han8c7e3ed2021-06-28 17:35:58 +0900221func (g *Module) OutputFiles(tag string) (android.Paths, error) {
222 if tag == "" {
223 return append(android.Paths{}, g.outputFiles...), nil
224 }
225 // otherwise, tag should match one of outputs
226 for _, outputFile := range g.outputFiles {
227 if outputFile.Rel() == tag {
228 return android.Paths{outputFile}, nil
229 }
230 }
231 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
232}
233
234var _ android.SourceFileProducer = (*Module)(nil)
235var _ android.OutputFileProducer = (*Module)(nil)
236
Martin Stjernholm710ec3a2020-01-16 15:12:04 +0000237func toolDepsMutator(ctx android.BottomUpMutatorContext) {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700238 if g, ok := ctx.Module().(*Module); ok {
Colin Cross08f15ab2018-10-04 23:29:14 -0700239 for _, tool := range g.properties.Tools {
240 tag := hostToolDependencyTag{label: tool}
241 if m := android.SrcIsModule(tool); m != "" {
242 tool = m
243 }
Colin Cross0f7d2ef2019-10-16 11:03:10 -0700244 ctx.AddFarVariationDependencies(ctx.Config().BuildOSTarget.Variations(), tag, tool)
Colin Cross6362e272015-10-29 15:25:03 -0700245 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700246 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700247}
248
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400249// Returns true if information was available from Bazel, false if bazel invocation still needs to occur.
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux0d990452021-08-11 16:46:13 +0000250func (c *Module) GenerateBazelBuildActions(ctx android.ModuleContext, label string) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400251 bazelCtx := ctx.Config().BazelContext
Chris Parsons787fb362021-10-14 18:43:51 -0400252 filePaths, ok := bazelCtx.GetOutputFiles(label, android.GetConfigKey(ctx))
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400253 if ok {
254 var bazelOutputFiles android.Paths
Chris Parsonse59af4e2021-03-31 13:32:41 -0400255 exportIncludeDirs := map[string]bool{}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400256 for _, bazelOutputFile := range filePaths {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500257 bazelOutputFiles = append(bazelOutputFiles, android.PathForBazelOut(ctx, bazelOutputFile))
Chris Parsonse59af4e2021-03-31 13:32:41 -0400258 exportIncludeDirs[filepath.Dir(bazelOutputFile)] = true
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400259 }
260 c.outputFiles = bazelOutputFiles
261 c.outputDeps = bazelOutputFiles
Chris Parsonse59af4e2021-03-31 13:32:41 -0400262 for includePath, _ := range exportIncludeDirs {
263 c.exportedIncludeDirs = append(c.exportedIncludeDirs, android.PathForBazelOut(ctx, includePath))
264 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400265 }
266 return ok
267}
Colin Crossf1885962020-11-20 15:28:30 -0800268
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700269func (g *Module) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Colin Crossa4ad2b02019-03-18 22:15:32 -0700270 g.subName = ctx.ModuleSubDir()
271
bralee1fbf4402020-05-21 10:11:59 +0800272 // Collect the module directory for IDE info in java/jdeps.go.
273 g.modulePaths = append(g.modulePaths, ctx.ModuleDir())
274
Colin Cross5ed99c62016-11-22 12:55:55 -0800275 if len(g.properties.Export_include_dirs) > 0 {
276 for _, dir := range g.properties.Export_include_dirs {
277 g.exportedIncludeDirs = append(g.exportedIncludeDirs,
Colin Cross1a527682019-09-23 15:55:30 -0700278 android.PathForModuleGen(ctx, g.subDir, ctx.ModuleDir(), dir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800279 }
280 } else {
Colin Cross1a527682019-09-23 15:55:30 -0700281 g.exportedIncludeDirs = append(g.exportedIncludeDirs, android.PathForModuleGen(ctx, g.subDir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800282 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700283
Colin Crossd11cf622021-03-23 22:30:35 -0700284 locationLabels := map[string]location{}
Colin Cross08f15ab2018-10-04 23:29:14 -0700285 firstLabel := ""
286
Colin Crossd11cf622021-03-23 22:30:35 -0700287 addLocationLabel := func(label string, loc location) {
Colin Cross08f15ab2018-10-04 23:29:14 -0700288 if firstLabel == "" {
289 firstLabel = label
290 }
291 if _, exists := locationLabels[label]; !exists {
Colin Crossd11cf622021-03-23 22:30:35 -0700292 locationLabels[label] = loc
Colin Cross08f15ab2018-10-04 23:29:14 -0700293 } else {
294 ctx.ModuleErrorf("multiple labels for %q, %q and %q",
Colin Crossd11cf622021-03-23 22:30:35 -0700295 label, locationLabels[label], loc)
Colin Cross08f15ab2018-10-04 23:29:14 -0700296 }
297 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700298
Colin Crossba9e4032020-11-24 16:32:22 -0800299 var tools android.Paths
300 var packagedTools []android.PackagingSpec
Colin Cross6f080df2016-11-04 15:32:58 -0700301 if len(g.properties.Tools) > 0 {
Colin Crossba71a3f2019-03-18 12:12:48 -0700302 seenTools := make(map[string]bool)
303
Colin Cross35143d02017-11-16 00:11:20 -0800304 ctx.VisitDirectDepsBlueprint(func(module blueprint.Module) {
Colin Cross08f15ab2018-10-04 23:29:14 -0700305 switch tag := ctx.OtherModuleDependencyTag(module).(type) {
306 case hostToolDependencyTag:
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700307 tool := ctx.OtherModuleName(module)
308
Colin Crossba9e4032020-11-24 16:32:22 -0800309 switch t := module.(type) {
310 case android.HostToolProvider:
311 // A HostToolProvider provides the path to a tool, which will be copied
312 // into the sandbox.
Colin Cross35143d02017-11-16 00:11:20 -0800313 if !t.(android.Module).Enabled() {
Colin Cross6510f912017-11-29 00:27:14 -0800314 if ctx.Config().AllowMissingDependencies() {
Colin Cross35143d02017-11-16 00:11:20 -0800315 ctx.AddMissingDependencies([]string{tool})
316 } else {
317 ctx.ModuleErrorf("depends on disabled module %q", tool)
318 }
Colin Crossba9e4032020-11-24 16:32:22 -0800319 return
Colin Cross35143d02017-11-16 00:11:20 -0800320 }
Colin Crossba9e4032020-11-24 16:32:22 -0800321 path := t.HostToolPath()
322 if !path.Valid() {
323 ctx.ModuleErrorf("host tool %q missing output file", tool)
324 return
325 }
326 if specs := t.TransitivePackagingSpecs(); specs != nil {
327 // If the HostToolProvider has PackgingSpecs, which are definitions of the
328 // required relative locations of the tool and its dependencies, use those
329 // instead. They will be copied to those relative locations in the sbox
330 // sandbox.
331 packagedTools = append(packagedTools, specs...)
332 // Assume that the first PackagingSpec of the module is the tool.
Colin Crossd11cf622021-03-23 22:30:35 -0700333 addLocationLabel(tag.label, packagedToolLocation{specs[0]})
Colin Crossba9e4032020-11-24 16:32:22 -0800334 } else {
335 tools = append(tools, path.Path())
Colin Crossd11cf622021-03-23 22:30:35 -0700336 addLocationLabel(tag.label, toolLocation{android.Paths{path.Path()}})
Colin Crossba9e4032020-11-24 16:32:22 -0800337 }
338 case bootstrap.GoBinaryTool:
339 // A GoBinaryTool provides the install path to a tool, which will be copied.
Colin Crossa44551f2021-10-25 15:36:21 -0700340 p := android.PathForGoBinary(ctx, t)
341 tools = append(tools, p)
342 addLocationLabel(tag.label, toolLocation{android.Paths{p}})
Colin Crossba9e4032020-11-24 16:32:22 -0800343 default:
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700344 ctx.ModuleErrorf("%q is not a host tool provider", tool)
Colin Crossba9e4032020-11-24 16:32:22 -0800345 return
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700346 }
347
Colin Crossba9e4032020-11-24 16:32:22 -0800348 seenTools[tag.label] = true
Colin Crossd350ecd2015-04-28 13:25:36 -0700349 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700350 })
Colin Crossba71a3f2019-03-18 12:12:48 -0700351
352 // If AllowMissingDependencies is enabled, the build will not have stopped when
353 // AddFarVariationDependencies was called on a missing tool, which will result in nonsensical
Liz Kammer20ebfb42020-07-28 11:32:07 -0700354 // "cmd: unknown location label ..." errors later. Add a placeholder file to the local label.
355 // The command that uses this placeholder file will never be executed because the rule will be
356 // replaced with an android.Error rule reporting the missing dependencies.
Colin Crossba71a3f2019-03-18 12:12:48 -0700357 if ctx.Config().AllowMissingDependencies() {
358 for _, tool := range g.properties.Tools {
359 if !seenTools[tool] {
Colin Crossd11cf622021-03-23 22:30:35 -0700360 addLocationLabel(tool, errorLocation{"***missing tool " + tool + "***"})
Colin Crossba71a3f2019-03-18 12:12:48 -0700361 }
362 }
363 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700364 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700365
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700366 if ctx.Failed() {
367 return
368 }
369
Colin Cross08f15ab2018-10-04 23:29:14 -0700370 for _, toolFile := range g.properties.Tool_files {
Colin Cross8a497952019-03-05 22:25:09 -0800371 paths := android.PathsForModuleSrc(ctx, []string{toolFile})
Colin Crossba9e4032020-11-24 16:32:22 -0800372 tools = append(tools, paths...)
Colin Crossd11cf622021-03-23 22:30:35 -0700373 addLocationLabel(toolFile, toolLocation{paths})
Colin Cross08f15ab2018-10-04 23:29:14 -0700374 }
375
376 var srcFiles android.Paths
377 for _, in := range g.properties.Srcs {
Colin Crossba71a3f2019-03-18 12:12:48 -0700378 paths, missingDeps := android.PathsAndMissingDepsForModuleSrcExcludes(ctx, []string{in}, g.properties.Exclude_srcs)
379 if len(missingDeps) > 0 {
380 if !ctx.Config().AllowMissingDependencies() {
381 panic(fmt.Errorf("should never get here, the missing dependencies %q should have been reported in DepsMutator",
382 missingDeps))
383 }
384
385 // If AllowMissingDependencies is enabled, the build will not have stopped when
386 // the dependency was added on a missing SourceFileProducer module, which will result in nonsensical
Liz Kammer20ebfb42020-07-28 11:32:07 -0700387 // "cmd: label ":..." has no files" errors later. Add a placeholder file to the local label.
388 // The command that uses this placeholder file will never be executed because the rule will be
389 // replaced with an android.Error rule reporting the missing dependencies.
Colin Crossba71a3f2019-03-18 12:12:48 -0700390 ctx.AddMissingDependencies(missingDeps)
Colin Crossd11cf622021-03-23 22:30:35 -0700391 addLocationLabel(in, errorLocation{"***missing srcs " + in + "***"})
Colin Crossba71a3f2019-03-18 12:12:48 -0700392 } else {
393 srcFiles = append(srcFiles, paths...)
Colin Crossd11cf622021-03-23 22:30:35 -0700394 addLocationLabel(in, inputLocation{paths})
Colin Crossba71a3f2019-03-18 12:12:48 -0700395 }
Colin Cross08f15ab2018-10-04 23:29:14 -0700396 }
397
Colin Cross1a527682019-09-23 15:55:30 -0700398 var copyFrom android.Paths
399 var outputFiles android.WritablePaths
400 var zipArgs strings.Builder
Colin Cross08f15ab2018-10-04 23:29:14 -0700401
Colin Crossf3bfd022021-09-27 15:15:06 -0700402 cmd := String(g.properties.Cmd)
403 if g.CmdModifier != nil {
404 cmd = g.CmdModifier(ctx, cmd)
405 }
406
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500407 // Generate tasks, either from genrule or gensrcs.
Colin Crossf3bfd022021-09-27 15:15:06 -0700408 for _, task := range g.taskGenerator(ctx, cmd, srcFiles) {
Colin Cross3d680512020-11-13 16:23:53 -0800409 if len(task.out) == 0 {
410 ctx.ModuleErrorf("must have at least one output file")
411 return
Colin Cross85a2e892018-07-09 09:45:06 -0700412 }
413
Colin Crossf1a035e2020-11-16 17:32:30 -0800414 // Pick a unique path outside the task.genDir for the sbox manifest textproto,
415 // a unique rule name, and the user-visible description.
416 manifestName := "genrule.sbox.textproto"
417 desc := "generate"
418 name := "generator"
419 if task.shards > 0 {
420 manifestName = "genrule_" + strconv.Itoa(task.shard) + ".sbox.textproto"
421 desc += " " + strconv.Itoa(task.shard)
422 name += strconv.Itoa(task.shard)
423 } else if len(task.out) == 1 {
424 desc += " " + task.out[0].Base()
425 }
426
427 manifestPath := android.PathForModuleOut(ctx, manifestName)
428
429 // Use a RuleBuilder to create a rule that runs the command inside an sbox sandbox.
Colin Crossba9e4032020-11-24 16:32:22 -0800430 rule := android.NewRuleBuilder(pctx, ctx).Sbox(task.genDir, manifestPath).SandboxTools()
Colin Crossf1a035e2020-11-16 17:32:30 -0800431 cmd := rule.Command()
432
Colin Cross3d680512020-11-13 16:23:53 -0800433 for _, out := range task.out {
Colin Crossd11cf622021-03-23 22:30:35 -0700434 addLocationLabel(out.Rel(), outputLocation{out})
Colin Cross3d680512020-11-13 16:23:53 -0800435 }
436
Colin Cross1a527682019-09-23 15:55:30 -0700437 referencedDepfile := false
438
Colin Cross3d680512020-11-13 16:23:53 -0800439 rawCommand, err := android.Expand(task.cmd, func(name string) (string, error) {
Colin Cross1a527682019-09-23 15:55:30 -0700440 // report the error directly without returning an error to android.Expand to catch multiple errors in a
441 // single run
Colin Cross3d680512020-11-13 16:23:53 -0800442 reportError := func(fmt string, args ...interface{}) (string, error) {
Colin Cross1a527682019-09-23 15:55:30 -0700443 ctx.PropertyErrorf("cmd", fmt, args...)
Colin Cross3d680512020-11-13 16:23:53 -0800444 return "SOONG_ERROR", nil
Colin Cross6f080df2016-11-04 15:32:58 -0700445 }
Colin Cross1a527682019-09-23 15:55:30 -0700446
447 switch name {
448 case "location":
449 if len(g.properties.Tools) == 0 && len(g.properties.Tool_files) == 0 {
450 return reportError("at least one `tools` or `tool_files` is required if $(location) is used")
Colin Cross6f080df2016-11-04 15:32:58 -0700451 }
Colin Crossd11cf622021-03-23 22:30:35 -0700452 loc := locationLabels[firstLabel]
453 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700454 if len(paths) == 0 {
455 return reportError("default label %q has no files", firstLabel)
456 } else if len(paths) > 1 {
457 return reportError("default label %q has multiple files, use $(locations %s) to reference it",
458 firstLabel, firstLabel)
Colin Cross08f15ab2018-10-04 23:29:14 -0700459 }
Colin Crossd11cf622021-03-23 22:30:35 -0700460 return paths[0], nil
Colin Cross1a527682019-09-23 15:55:30 -0700461 case "in":
Colin Crossd11cf622021-03-23 22:30:35 -0700462 return strings.Join(cmd.PathsForInputs(srcFiles), " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700463 case "out":
Colin Cross3d680512020-11-13 16:23:53 -0800464 var sandboxOuts []string
465 for _, out := range task.out {
Colin Crossf1a035e2020-11-16 17:32:30 -0800466 sandboxOuts = append(sandboxOuts, cmd.PathForOutput(out))
Colin Cross3d680512020-11-13 16:23:53 -0800467 }
468 return strings.Join(sandboxOuts, " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700469 case "depfile":
470 referencedDepfile = true
471 if !Bool(g.properties.Depfile) {
472 return reportError("$(depfile) used without depfile property")
473 }
Colin Cross3d680512020-11-13 16:23:53 -0800474 return "__SBOX_DEPFILE__", nil
Colin Cross1a527682019-09-23 15:55:30 -0700475 case "genDir":
Colin Crossf1a035e2020-11-16 17:32:30 -0800476 return cmd.PathForOutput(task.genDir), nil
Colin Cross1a527682019-09-23 15:55:30 -0700477 default:
478 if strings.HasPrefix(name, "location ") {
479 label := strings.TrimSpace(strings.TrimPrefix(name, "location "))
Colin Crossd11cf622021-03-23 22:30:35 -0700480 if loc, ok := locationLabels[label]; ok {
481 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700482 if len(paths) == 0 {
483 return reportError("label %q has no files", label)
484 } else if len(paths) > 1 {
485 return reportError("label %q has multiple files, use $(locations %s) to reference it",
486 label, label)
487 }
Colin Cross3d680512020-11-13 16:23:53 -0800488 return paths[0], nil
Colin Cross1a527682019-09-23 15:55:30 -0700489 } else {
490 return reportError("unknown location label %q", label)
491 }
492 } else if strings.HasPrefix(name, "locations ") {
493 label := strings.TrimSpace(strings.TrimPrefix(name, "locations "))
Colin Crossd11cf622021-03-23 22:30:35 -0700494 if loc, ok := locationLabels[label]; ok {
495 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700496 if len(paths) == 0 {
497 return reportError("label %q has no files", label)
498 }
Colin Cross3d680512020-11-13 16:23:53 -0800499 return strings.Join(paths, " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700500 } else {
501 return reportError("unknown locations label %q", label)
502 }
503 } else {
504 return reportError("unknown variable '$(%s)'", name)
505 }
Colin Cross6f080df2016-11-04 15:32:58 -0700506 }
Colin Cross1a527682019-09-23 15:55:30 -0700507 })
508
509 if err != nil {
510 ctx.PropertyErrorf("cmd", "%s", err.Error())
511 return
Colin Cross6f080df2016-11-04 15:32:58 -0700512 }
Colin Cross6f080df2016-11-04 15:32:58 -0700513
Colin Cross1a527682019-09-23 15:55:30 -0700514 if Bool(g.properties.Depfile) && !referencedDepfile {
515 ctx.PropertyErrorf("cmd", "specified depfile=true but did not include a reference to '${depfile}' in cmd")
516 return
517 }
Colin Cross1a527682019-09-23 15:55:30 -0700518 g.rawCommands = append(g.rawCommands, rawCommand)
Bill Peckhamc087be12020-02-13 15:55:10 -0800519
Colin Cross3d680512020-11-13 16:23:53 -0800520 cmd.Text(rawCommand)
521 cmd.ImplicitOutputs(task.out)
522 cmd.Implicits(task.in)
Colin Crossba9e4032020-11-24 16:32:22 -0800523 cmd.ImplicitTools(tools)
524 cmd.ImplicitTools(task.extraTools)
525 cmd.ImplicitPackagedTools(packagedTools)
Colin Cross3d680512020-11-13 16:23:53 -0800526 if Bool(g.properties.Depfile) {
527 cmd.ImplicitDepFile(task.depFile)
528 }
529
530 // Create the rule to run the genrule command inside sbox.
Colin Crossf1a035e2020-11-16 17:32:30 -0800531 rule.Build(name, desc)
Colin Cross1a527682019-09-23 15:55:30 -0700532
533 if len(task.copyTo) > 0 {
Colin Cross3d680512020-11-13 16:23:53 -0800534 // If copyTo is set, multiple shards need to be copied into a single directory.
535 // task.out contains the per-shard paths, and copyTo contains the corresponding
536 // final path. The files need to be copied into the final directory by a
537 // single rule so it can remove the directory before it starts to ensure no
538 // old files remain. zipsync already does this, so build up zipArgs that
539 // zip all the per-shard directories into a single zip.
Colin Cross1a527682019-09-23 15:55:30 -0700540 outputFiles = append(outputFiles, task.copyTo...)
541 copyFrom = append(copyFrom, task.out.Paths()...)
542 zipArgs.WriteString(" -C " + task.genDir.String())
543 zipArgs.WriteString(android.JoinWithPrefix(task.out.Strings(), " -f "))
544 } else {
545 outputFiles = append(outputFiles, task.out...)
546 }
Colin Cross6f080df2016-11-04 15:32:58 -0700547 }
548
Colin Cross1a527682019-09-23 15:55:30 -0700549 if len(copyFrom) > 0 {
Colin Cross3d680512020-11-13 16:23:53 -0800550 // Create a rule that zips all the per-shard directories into a single zip and then
551 // uses zipsync to unzip it into the final directory.
Colin Cross1a527682019-09-23 15:55:30 -0700552 ctx.Build(pctx, android.BuildParams{
Colin Crossf1885962020-11-20 15:28:30 -0800553 Rule: gensrcsMerge,
554 Implicits: copyFrom,
555 Outputs: outputFiles,
556 Description: "merge shards",
Colin Cross1a527682019-09-23 15:55:30 -0700557 Args: map[string]string{
558 "zipArgs": zipArgs.String(),
559 "tmpZip": android.PathForModuleGen(ctx, g.subDir+".zip").String(),
560 "genDir": android.PathForModuleGen(ctx, g.subDir).String(),
561 },
562 })
Colin Cross85a2e892018-07-09 09:45:06 -0700563 }
564
Colin Cross1a527682019-09-23 15:55:30 -0700565 g.outputFiles = outputFiles.Paths()
Jeff Gastonefc1b412017-03-29 17:29:06 -0700566
Liz Kammerbdc60992021-02-24 16:55:11 -0500567 bazelModuleLabel := g.GetBazelLabel(ctx, g)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400568 bazelActionsUsed := false
Chris Parsonsbab4d7e2021-04-15 17:27:08 -0400569 if g.MixedBuildsEnabled(ctx) {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux0d990452021-08-11 16:46:13 +0000570 bazelActionsUsed = g.GenerateBazelBuildActions(ctx, bazelModuleLabel)
Jeff Gaston02a684b2017-10-27 14:59:27 -0700571 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400572 if !bazelActionsUsed {
573 // For <= 6 outputs, just embed those directly in the users. Right now, that covers >90% of
574 // the genrules on AOSP. That will make things simpler to look at the graph in the common
575 // case. For larger sets of outputs, inject a phony target in between to limit ninja file
576 // growth.
577 if len(g.outputFiles) <= 6 {
578 g.outputDeps = g.outputFiles
579 } else {
580 phonyFile := android.PathForModuleGen(ctx, "genrule-phony")
581 ctx.Build(pctx, android.BuildParams{
582 Rule: blueprint.Phony,
583 Output: phonyFile,
584 Inputs: g.outputFiles,
585 })
586 g.outputDeps = android.Paths{phonyFile}
587 }
588 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700589}
Colin Crossd350ecd2015-04-28 13:25:36 -0700590
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700591// Collect information for opening IDE project files in java/jdeps.go.
592func (g *Module) IDEInfo(dpInfo *android.IdeInfo) {
593 dpInfo.Srcs = append(dpInfo.Srcs, g.Srcs().Strings()...)
594 for _, src := range g.properties.Srcs {
595 if strings.HasPrefix(src, ":") {
596 src = strings.Trim(src, ":")
597 dpInfo.Deps = append(dpInfo.Deps, src)
598 }
599 }
bralee1fbf4402020-05-21 10:11:59 +0800600 dpInfo.Paths = append(dpInfo.Paths, g.modulePaths...)
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700601}
602
Colin Crossa4ad2b02019-03-18 22:15:32 -0700603func (g *Module) AndroidMk() android.AndroidMkData {
604 return android.AndroidMkData{
Anton Hansson72f18492020-10-30 16:34:45 +0000605 Class: "ETC",
Colin Crossa4ad2b02019-03-18 22:15:32 -0700606 OutputFile: android.OptionalPathForPath(g.outputFiles[0]),
607 SubName: g.subName,
608 Extra: []android.AndroidMkExtraFunc{
609 func(w io.Writer, outputFile android.Path) {
Anton Hansson72f18492020-10-30 16:34:45 +0000610 fmt.Fprintln(w, "LOCAL_UNINSTALLABLE_MODULE := true")
Colin Crossa4ad2b02019-03-18 22:15:32 -0700611 },
612 },
613 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
614 android.WriteAndroidMkData(w, data)
615 if data.SubName != "" {
616 fmt.Fprintln(w, ".PHONY:", name)
617 fmt.Fprintln(w, name, ":", name+g.subName)
618 }
619 },
620 }
621}
622
Jiyong Park45bf82e2020-12-15 22:29:02 +0900623var _ android.ApexModule = (*Module)(nil)
624
625// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -0700626func (g *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
627 sdkVersion android.ApiLevel) error {
Jooyung Han749dc692020-04-15 11:03:39 +0900628 // Because generated outputs are checked by client modules(e.g. cc_library, ...)
629 // we can safely ignore the check here.
630 return nil
631}
632
Jeff Gaston437d23c2017-11-08 12:38:00 -0800633func generatorFactory(taskGenerator taskFunc, props ...interface{}) *Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700634 module := &Module{
Jeff Gaston437d23c2017-11-08 12:38:00 -0800635 taskGenerator: taskGenerator,
Colin Crossd350ecd2015-04-28 13:25:36 -0700636 }
637
Colin Cross36242852017-06-23 15:06:31 -0700638 module.AddProperties(props...)
639 module.AddProperties(&module.properties)
Colin Crossd350ecd2015-04-28 13:25:36 -0700640
Colin Cross7228ecd2019-11-18 16:00:16 -0800641 module.ImageInterface = noopImageInterface{}
642
Colin Cross36242852017-06-23 15:06:31 -0700643 return module
Colin Crossd350ecd2015-04-28 13:25:36 -0700644}
645
Colin Cross7228ecd2019-11-18 16:00:16 -0800646type noopImageInterface struct{}
647
648func (x noopImageInterface) ImageMutatorBegin(android.BaseModuleContext) {}
649func (x noopImageInterface) CoreVariantNeeded(android.BaseModuleContext) bool { return false }
Yifan Hong1b3348d2020-01-21 15:53:22 -0800650func (x noopImageInterface) RamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700651func (x noopImageInterface) VendorRamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Inseob Kim08758f02021-04-08 21:13:22 +0900652func (x noopImageInterface) DebugRamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Colin Cross7228ecd2019-11-18 16:00:16 -0800653func (x noopImageInterface) RecoveryVariantNeeded(android.BaseModuleContext) bool { return false }
654func (x noopImageInterface) ExtraImageVariations(ctx android.BaseModuleContext) []string { return nil }
655func (x noopImageInterface) SetImageVariation(ctx android.BaseModuleContext, variation string, module android.Module) {
656}
657
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700658func NewGenSrcs() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700659 properties := &genSrcsProperties{}
660
Colin Crossf1885962020-11-20 15:28:30 -0800661 // finalSubDir is the name of the subdirectory that output files will be generated into.
662 // It is used so that per-shard directories can be placed alongside it an then finally
663 // merged into it.
664 const finalSubDir = "gensrcs"
665
Colin Cross1a527682019-09-23 15:55:30 -0700666 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Colin Cross1a527682019-09-23 15:55:30 -0700667 shardSize := defaultShardSize
668 if s := properties.Shard_size; s != nil {
669 shardSize = int(*s)
670 }
Jeff Gaston437d23c2017-11-08 12:38:00 -0800671
Colin Crossf1885962020-11-20 15:28:30 -0800672 // gensrcs rules can easily hit command line limits by repeating the command for
673 // every input file. Shard the input files into groups.
Colin Cross1a527682019-09-23 15:55:30 -0700674 shards := android.ShardPaths(srcFiles, shardSize)
675 var generateTasks []generateTask
Colin Crossbaccf5b2018-02-21 14:07:48 -0800676
Colin Cross1a527682019-09-23 15:55:30 -0700677 for i, shard := range shards {
678 var commands []string
679 var outFiles android.WritablePaths
Colin Cross3ea4eb82020-11-24 13:07:27 -0800680 var commandDepFiles []string
Colin Cross1a527682019-09-23 15:55:30 -0700681 var copyTo android.WritablePaths
Colin Cross1a527682019-09-23 15:55:30 -0700682
Colin Crossf1885962020-11-20 15:28:30 -0800683 // When sharding is enabled (i.e. len(shards) > 1), the sbox rules for each
684 // shard will be write to their own directories and then be merged together
685 // into finalSubDir. If sharding is not enabled (i.e. len(shards) == 1),
686 // the sbox rule will write directly to finalSubDir.
687 genSubDir := finalSubDir
Colin Cross1a527682019-09-23 15:55:30 -0700688 if len(shards) > 1 {
Colin Crossf1885962020-11-20 15:28:30 -0800689 genSubDir = strconv.Itoa(i)
Jeff Gaston437d23c2017-11-08 12:38:00 -0800690 }
691
Colin Crossf1885962020-11-20 15:28:30 -0800692 genDir := android.PathForModuleGen(ctx, genSubDir)
Colin Crossf1a035e2020-11-16 17:32:30 -0800693 // TODO(ccross): this RuleBuilder is a hack to be able to call
694 // rule.Command().PathForOutput. Replace this with passing the rule into the
695 // generator.
Colin Crossba9e4032020-11-24 16:32:22 -0800696 rule := android.NewRuleBuilder(pctx, ctx).Sbox(genDir, nil).SandboxTools()
Jeff Gaston437d23c2017-11-08 12:38:00 -0800697
Colin Cross3ea4eb82020-11-24 13:07:27 -0800698 for _, in := range shard {
Colin Crossf1885962020-11-20 15:28:30 -0800699 outFile := android.GenPathWithExt(ctx, finalSubDir, in, String(properties.Output_extension))
700
701 // If sharding is enabled, then outFile is the path to the output file in
702 // the shard directory, and copyTo is the path to the output file in the
703 // final directory.
Colin Cross1a527682019-09-23 15:55:30 -0700704 if len(shards) > 1 {
Colin Crossf1885962020-11-20 15:28:30 -0800705 shardFile := android.GenPathWithExt(ctx, genSubDir, in, String(properties.Output_extension))
Colin Cross1a527682019-09-23 15:55:30 -0700706 copyTo = append(copyTo, outFile)
707 outFile = shardFile
708 }
709
710 outFiles = append(outFiles, outFile)
Colin Cross1a527682019-09-23 15:55:30 -0700711
Colin Crossf1885962020-11-20 15:28:30 -0800712 // pre-expand the command line to replace $in and $out with references to
713 // a single input and output file.
Colin Cross1a527682019-09-23 15:55:30 -0700714 command, err := android.Expand(rawCommand, func(name string) (string, error) {
715 switch name {
716 case "in":
717 return in.String(), nil
718 case "out":
Colin Crossf1a035e2020-11-16 17:32:30 -0800719 return rule.Command().PathForOutput(outFile), nil
Colin Cross3ea4eb82020-11-24 13:07:27 -0800720 case "depfile":
721 // Generate a depfile for each output file. Store the list for
722 // later in order to combine them all into a single depfile.
Colin Crossf1a035e2020-11-16 17:32:30 -0800723 depFile := rule.Command().PathForOutput(outFile.ReplaceExtension(ctx, "d"))
Colin Cross3ea4eb82020-11-24 13:07:27 -0800724 commandDepFiles = append(commandDepFiles, depFile)
725 return depFile, nil
Colin Cross1a527682019-09-23 15:55:30 -0700726 default:
727 return "$(" + name + ")", nil
728 }
729 })
730 if err != nil {
731 ctx.PropertyErrorf("cmd", err.Error())
732 }
733
734 // escape the command in case for example it contains '#', an odd number of '"', etc
735 command = fmt.Sprintf("bash -c %v", proptools.ShellEscape(command))
736 commands = append(commands, command)
737 }
738 fullCommand := strings.Join(commands, " && ")
739
Colin Cross3ea4eb82020-11-24 13:07:27 -0800740 var outputDepfile android.WritablePath
741 var extraTools android.Paths
742 if len(commandDepFiles) > 0 {
743 // Each command wrote to a depfile, but ninja can only handle one
744 // depfile per rule. Use the dep_fixer tool at the end of the
745 // command to combine all the depfiles into a single output depfile.
746 outputDepfile = android.PathForModuleGen(ctx, genSubDir, "gensrcs.d")
747 depFixerTool := ctx.Config().HostToolPath(ctx, "dep_fixer")
748 fullCommand += fmt.Sprintf(" && %s -o $(depfile) %s",
Colin Crossd11cf622021-03-23 22:30:35 -0700749 rule.Command().PathForTool(depFixerTool),
Colin Crossba9e4032020-11-24 16:32:22 -0800750 strings.Join(commandDepFiles, " "))
Colin Cross3ea4eb82020-11-24 13:07:27 -0800751 extraTools = append(extraTools, depFixerTool)
752 }
753
Colin Cross1a527682019-09-23 15:55:30 -0700754 generateTasks = append(generateTasks, generateTask{
Colin Cross3ea4eb82020-11-24 13:07:27 -0800755 in: shard,
756 out: outFiles,
757 depFile: outputDepfile,
758 copyTo: copyTo,
759 genDir: genDir,
760 cmd: fullCommand,
761 shard: i,
762 shards: len(shards),
763 extraTools: extraTools,
Colin Cross1a527682019-09-23 15:55:30 -0700764 })
Jeff Gaston437d23c2017-11-08 12:38:00 -0800765 }
Colin Cross1a527682019-09-23 15:55:30 -0700766
767 return generateTasks
Colin Crossd350ecd2015-04-28 13:25:36 -0700768 }
769
Colin Cross1a527682019-09-23 15:55:30 -0700770 g := generatorFactory(taskGenerator, properties)
Colin Crossf1885962020-11-20 15:28:30 -0800771 g.subDir = finalSubDir
Colin Cross1a527682019-09-23 15:55:30 -0700772 return g
Colin Crossd350ecd2015-04-28 13:25:36 -0700773}
774
Colin Cross54190b32017-10-09 15:34:10 -0700775func GenSrcsFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700776 m := NewGenSrcs()
777 android.InitAndroidModule(m)
778 return m
779}
780
Colin Crossd350ecd2015-04-28 13:25:36 -0700781type genSrcsProperties struct {
Colin Cross7d5136f2015-05-11 13:39:40 -0700782 // extension that will be substituted for each output file
Nan Zhanga5e7cb42017-11-09 22:42:32 -0800783 Output_extension *string
Colin Cross1a527682019-09-23 15:55:30 -0700784
785 // maximum number of files that will be passed on a single command line.
786 Shard_size *int64
Colin Cross5049f022015-03-18 13:28:46 -0700787}
788
Evgenii Stepanovf47c90d2020-12-02 18:55:09 -0800789const defaultShardSize = 50
Colin Cross1a527682019-09-23 15:55:30 -0700790
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700791func NewGenRule() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700792 properties := &genRuleProperties{}
Colin Cross5049f022015-03-18 13:28:46 -0700793
Colin Cross1a527682019-09-23 15:55:30 -0700794 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700795 outs := make(android.WritablePaths, len(properties.Out))
Colin Cross3d680512020-11-13 16:23:53 -0800796 var depFile android.WritablePath
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700797 for i, out := range properties.Out {
Colin Cross3d680512020-11-13 16:23:53 -0800798 outPath := android.PathForModuleGen(ctx, out)
799 if i == 0 {
800 depFile = outPath.ReplaceExtension(ctx, "d")
801 }
802 outs[i] = outPath
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700803 }
Colin Cross1a527682019-09-23 15:55:30 -0700804 return []generateTask{{
Colin Cross3d680512020-11-13 16:23:53 -0800805 in: srcFiles,
806 out: outs,
807 depFile: depFile,
808 genDir: android.PathForModuleGen(ctx),
809 cmd: rawCommand,
Colin Cross1a527682019-09-23 15:55:30 -0700810 }}
Colin Cross5049f022015-03-18 13:28:46 -0700811 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700812
Jeff Gaston437d23c2017-11-08 12:38:00 -0800813 return generatorFactory(taskGenerator, properties)
Colin Cross5049f022015-03-18 13:28:46 -0700814}
815
Colin Cross54190b32017-10-09 15:34:10 -0700816func GenRuleFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700817 m := NewGenRule()
818 android.InitAndroidModule(m)
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800819 android.InitDefaultableModule(m)
Liz Kammerea6666f2021-02-17 10:17:28 -0500820 android.InitBazelModule(m)
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700821 return m
822}
823
Colin Crossd350ecd2015-04-28 13:25:36 -0700824type genRuleProperties struct {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700825 // names of the output files that will be generated
Colin Crossef354482018-10-23 11:27:50 -0700826 Out []string `android:"arch_variant"`
Colin Cross5049f022015-03-18 13:28:46 -0700827}
Nan Zhangea568a42017-11-08 21:20:04 -0800828
Jingwen Chen316e07c2020-12-14 09:09:52 -0500829type bazelGenruleAttributes struct {
Jingwen Chen07027912021-03-15 06:02:43 -0400830 Srcs bazel.LabelListAttribute
Jingwen Chen316e07c2020-12-14 09:09:52 -0500831 Outs []string
Jingwen Chen07027912021-03-15 06:02:43 -0400832 Tools bazel.LabelListAttribute
Jingwen Chen316e07c2020-12-14 09:09:52 -0500833 Cmd string
834}
835
Wei Libcd39942021-09-16 23:57:28 +0000836// CcGenruleBp2Build is for cc_genrule.
837func CcGenruleBp2Build(ctx android.TopDownMutatorContext) {
838 m, ok := ctx.Module().(*Module)
839 if !ok || !m.ConvertWithBp2build(ctx) {
840 return
841 }
842
843 if ctx.ModuleType() != "cc_genrule" {
844 // Not a cc_genrule.
845 return
846 }
847
848 genruleBp2Build(ctx)
849}
850
851// GenruleBp2Build is used for genrule.
Jingwen Chena42d6412021-01-26 21:57:27 -0500852func GenruleBp2Build(ctx android.TopDownMutatorContext) {
Liz Kammer356f7d42021-01-26 09:18:53 -0500853 m, ok := ctx.Module().(*Module)
Jingwen Chen12b4c272021-03-10 02:05:59 -0500854 if !ok || !m.ConvertWithBp2build(ctx) {
Liz Kammer356f7d42021-01-26 09:18:53 -0500855 return
Jingwen Chen316e07c2020-12-14 09:09:52 -0500856 }
Jingwen Chen1fd14692021-02-05 03:01:50 -0500857
Jingwen Chen66480452021-03-18 03:41:55 -0400858 if ctx.ModuleType() != "genrule" {
Wei Libcd39942021-09-16 23:57:28 +0000859 // Not a regular genrule.
Jingwen Chen66480452021-03-18 03:41:55 -0400860 return
861 }
862
Wei Libcd39942021-09-16 23:57:28 +0000863 genruleBp2Build(ctx)
864}
865
866func genruleBp2Build(ctx android.TopDownMutatorContext) {
867 m, _ := ctx.Module().(*Module)
Liz Kammer356f7d42021-01-26 09:18:53 -0500868 // Bazel only has the "tools" attribute.
Jingwen Chen07027912021-03-15 06:02:43 -0400869 tools_prop := android.BazelLabelForModuleDeps(ctx, m.properties.Tools)
870 tool_files_prop := android.BazelLabelForModuleSrc(ctx, m.properties.Tool_files)
871 tools_prop.Append(tool_files_prop)
Liz Kammer356f7d42021-01-26 09:18:53 -0500872
Jingwen Chen07027912021-03-15 06:02:43 -0400873 tools := bazel.MakeLabelListAttribute(tools_prop)
874 srcs := bazel.MakeLabelListAttribute(android.BazelLabelForModuleSrc(ctx, m.properties.Srcs))
Liz Kammer356f7d42021-01-26 09:18:53 -0500875
876 var allReplacements bazel.LabelList
Jingwen Chen07027912021-03-15 06:02:43 -0400877 allReplacements.Append(tools.Value)
878 allReplacements.Append(srcs.Value)
Liz Kammer356f7d42021-01-26 09:18:53 -0500879
880 // Replace in and out variables with $< and $@
881 var cmd string
882 if m.properties.Cmd != nil {
883 cmd = strings.Replace(*m.properties.Cmd, "$(in)", "$(SRCS)", -1)
884 cmd = strings.Replace(cmd, "$(out)", "$(OUTS)", -1)
Wei Libcd39942021-09-16 23:57:28 +0000885 genDir := "$(GENDIR)"
886 if ctx.ModuleType() == "cc_genrule" {
887 genDir = "$(RULEDIR)"
888 }
889 cmd = strings.Replace(cmd, "$(genDir)", genDir, -1)
Jingwen Chen07027912021-03-15 06:02:43 -0400890 if len(tools.Value.Includes) > 0 {
891 cmd = strings.Replace(cmd, "$(location)", fmt.Sprintf("$(location %s)", tools.Value.Includes[0].Label), -1)
892 cmd = strings.Replace(cmd, "$(locations)", fmt.Sprintf("$(locations %s)", tools.Value.Includes[0].Label), -1)
Liz Kammer356f7d42021-01-26 09:18:53 -0500893 }
894 for _, l := range allReplacements.Includes {
Jingwen Chen38e62642021-04-19 05:00:15 +0000895 bpLoc := fmt.Sprintf("$(location %s)", l.OriginalModuleName)
896 bpLocs := fmt.Sprintf("$(locations %s)", l.OriginalModuleName)
Liz Kammer356f7d42021-01-26 09:18:53 -0500897 bazelLoc := fmt.Sprintf("$(location %s)", l.Label)
898 bazelLocs := fmt.Sprintf("$(locations %s)", l.Label)
899 cmd = strings.Replace(cmd, bpLoc, bazelLoc, -1)
900 cmd = strings.Replace(cmd, bpLocs, bazelLocs, -1)
901 }
902 }
903
904 // The Out prop is not in an immediately accessible field
905 // in the Module struct, so use GetProperties and cast it
906 // to the known struct prop.
907 var outs []string
908 for _, propIntf := range m.GetProperties() {
909 if props, ok := propIntf.(*genRuleProperties); ok {
910 outs = props.Out
911 break
912 }
913 }
914
Jingwen Chen1fd14692021-02-05 03:01:50 -0500915 attrs := &bazelGenruleAttributes{
Liz Kammer356f7d42021-01-26 09:18:53 -0500916 Srcs: srcs,
917 Outs: outs,
918 Cmd: cmd,
919 Tools: tools,
Jingwen Chen1fd14692021-02-05 03:01:50 -0500920 }
921
Liz Kammerfc46bc12021-02-19 11:06:17 -0500922 props := bazel.BazelTargetModuleProperties{
923 Rule_class: "genrule",
924 }
Jingwen Chen1fd14692021-02-05 03:01:50 -0500925
926 // Create the BazelTargetModule.
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000927 ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: m.Name()}, attrs)
Jingwen Chen316e07c2020-12-14 09:09:52 -0500928}
929
Nan Zhangea568a42017-11-08 21:20:04 -0800930var Bool = proptools.Bool
931var String = proptools.String
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800932
933//
934// Defaults
935//
936type Defaults struct {
937 android.ModuleBase
938 android.DefaultsModuleBase
939}
940
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800941func defaultsFactory() android.Module {
942 return DefaultsFactory()
943}
944
945func DefaultsFactory(props ...interface{}) android.Module {
946 module := &Defaults{}
947
948 module.AddProperties(props...)
949 module.AddProperties(
950 &generatorProperties{},
951 &genRuleProperties{},
952 )
953
954 android.InitDefaultsModule(module)
955
956 return module
957}