blob: 7dbe6fa8d0fdc284f0decfc93620261605d0fe60 [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 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 {
Spandan Das93e95992021-07-29 18:26:39 +0000116 // 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 //
Spandan Das93e95992021-07-29 18:26:39 +0000120 // $(location): the path to the first entry in tools or tool_files.
121 // $(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.
122 // $(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.
123 // $(in): one or more input files.
124 // $(out): a single output file.
125 // $(depfile): a file to which dependencies will be written, if the depfile property is set to true.
126 // $(genDir): the sandbox directory for this tool; contains $(out).
Colin Cross2296f5b2017-10-17 21:38:14 -0700127 // $$: a literal $
Nan Zhangea568a42017-11-08 21:20:04 -0800128 Cmd *string
Colin Cross7d5136f2015-05-11 13:39:40 -0700129
Colin Cross33bfb0a2016-11-21 17:23:08 -0800130 // Enable reading a file containing dependencies in gcc format after the command completes
Nan Zhangea568a42017-11-08 21:20:04 -0800131 Depfile *bool
Colin Cross33bfb0a2016-11-21 17:23:08 -0800132
Colin Cross6f080df2016-11-04 15:32:58 -0700133 // name of the modules (if any) that produces the host executable. Leave empty for
Colin Cross7d5136f2015-05-11 13:39:40 -0700134 // prebuilts or scripts that do not need a module to build them.
Colin Cross6f080df2016-11-04 15:32:58 -0700135 Tools []string
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700136
137 // Local file that is used as the tool
Colin Cross27b922f2019-03-04 22:35:41 -0800138 Tool_files []string `android:"path"`
Colin Cross5ed99c62016-11-22 12:55:55 -0800139
140 // List of directories to export generated headers from
141 Export_include_dirs []string
Colin Cross708c4242017-01-13 18:05:49 -0800142
143 // list of input files
Colin Cross27b922f2019-03-04 22:35:41 -0800144 Srcs []string `android:"path,arch_variant"`
Dan Willemseneefa0262018-11-17 14:01:18 -0800145
146 // input files to exclude
Colin Cross27b922f2019-03-04 22:35:41 -0800147 Exclude_srcs []string `android:"path,arch_variant"`
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400148}
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500149
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700150type Module struct {
Colin Cross635c3b02016-05-18 15:37:25 -0700151 android.ModuleBase
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800152 android.DefaultableModuleBase
Liz Kammerea6666f2021-02-17 10:17:28 -0500153 android.BazelModuleBase
Jiyong Parkfc752ca2019-06-12 13:27:29 +0900154 android.ApexModuleBase
Colin Crossd350ecd2015-04-28 13:25:36 -0700155
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700156 // For other packages to make their own genrules with extra
157 // properties
158 Extra interface{}
Colin Crossf3bfd022021-09-27 15:15:06 -0700159
160 // CmdModifier can be set by wrappers around genrule to modify the command, for example to
161 // prefix environment variables to it.
162 CmdModifier func(ctx android.ModuleContext, cmd string) string
163
Colin Cross7228ecd2019-11-18 16:00:16 -0800164 android.ImageInterface
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700165
Colin Cross7d5136f2015-05-11 13:39:40 -0700166 properties generatorProperties
Colin Crossd350ecd2015-04-28 13:25:36 -0700167
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500168 // For the different tasks that genrule and gensrc generate. genrule will
169 // generate 1 task, and gensrc will generate 1 or more tasks based on the
170 // number of shards the input files are sharded into.
Jeff Gaston437d23c2017-11-08 12:38:00 -0800171 taskGenerator taskFunc
Colin Crossd350ecd2015-04-28 13:25:36 -0700172
Colin Cross1a527682019-09-23 15:55:30 -0700173 rule blueprint.Rule
174 rawCommands []string
Colin Crossd350ecd2015-04-28 13:25:36 -0700175
Colin Cross5ed99c62016-11-22 12:55:55 -0800176 exportedIncludeDirs android.Paths
Dan Willemsenb40aab62016-04-20 14:21:14 -0700177
Colin Cross635c3b02016-05-18 15:37:25 -0700178 outputFiles android.Paths
Dan Willemsen9da9d492018-02-21 18:28:18 -0800179 outputDeps android.Paths
Colin Crossa4ad2b02019-03-18 22:15:32 -0700180
181 subName string
Colin Cross1a527682019-09-23 15:55:30 -0700182 subDir string
bralee1fbf4402020-05-21 10:11:59 +0800183
184 // Collect the module directory for IDE info in java/jdeps.go.
185 modulePaths []string
Colin Crossd350ecd2015-04-28 13:25:36 -0700186}
187
Colin Cross1a527682019-09-23 15:55:30 -0700188type taskFunc func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask
Colin Crossd350ecd2015-04-28 13:25:36 -0700189
190type generateTask struct {
Colin Cross3ea4eb82020-11-24 13:07:27 -0800191 in android.Paths
192 out android.WritablePaths
193 depFile android.WritablePath
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500194 copyTo android.WritablePaths // For gensrcs to set on gensrcsMerge rule.
Colin Cross3ea4eb82020-11-24 13:07:27 -0800195 genDir android.WritablePath
196 extraTools android.Paths // dependencies on tools used by the generator
197
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500198 cmd string
199 // For gensrsc sharding.
Colin Cross3ea4eb82020-11-24 13:07:27 -0800200 shard int
201 shards int
Colin Crossd350ecd2015-04-28 13:25:36 -0700202}
203
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700204func (g *Module) GeneratedSourceFiles() android.Paths {
Colin Crossd350ecd2015-04-28 13:25:36 -0700205 return g.outputFiles
206}
207
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700208func (g *Module) Srcs() android.Paths {
Nan Zhange42777a2018-03-27 16:19:42 -0700209 return append(android.Paths{}, g.outputFiles...)
Colin Cross068e0fe2016-12-13 15:23:47 -0800210}
211
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700212func (g *Module) GeneratedHeaderDirs() android.Paths {
Colin Cross5ed99c62016-11-22 12:55:55 -0800213 return g.exportedIncludeDirs
Dan Willemsenb40aab62016-04-20 14:21:14 -0700214}
215
Dan Willemsen9da9d492018-02-21 18:28:18 -0800216func (g *Module) GeneratedDeps() android.Paths {
217 return g.outputDeps
218}
219
Jooyung Han8c7e3ed2021-06-28 17:35:58 +0900220func (g *Module) OutputFiles(tag string) (android.Paths, error) {
221 if tag == "" {
222 return append(android.Paths{}, g.outputFiles...), nil
223 }
224 // otherwise, tag should match one of outputs
225 for _, outputFile := range g.outputFiles {
226 if outputFile.Rel() == tag {
227 return android.Paths{outputFile}, nil
228 }
229 }
230 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
231}
232
233var _ android.SourceFileProducer = (*Module)(nil)
234var _ android.OutputFileProducer = (*Module)(nil)
235
Martin Stjernholm710ec3a2020-01-16 15:12:04 +0000236func toolDepsMutator(ctx android.BottomUpMutatorContext) {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700237 if g, ok := ctx.Module().(*Module); ok {
Colin Cross08f15ab2018-10-04 23:29:14 -0700238 for _, tool := range g.properties.Tools {
239 tag := hostToolDependencyTag{label: tool}
240 if m := android.SrcIsModule(tool); m != "" {
241 tool = m
242 }
Colin Cross0f7d2ef2019-10-16 11:03:10 -0700243 ctx.AddFarVariationDependencies(ctx.Config().BuildOSTarget.Variations(), tag, tool)
Colin Cross6362e272015-10-29 15:25:03 -0700244 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700245 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700246}
247
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400248// 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 +0000249func (c *Module) GenerateBazelBuildActions(ctx android.ModuleContext, label string) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400250 bazelCtx := ctx.Config().BazelContext
Chris Parsons944e7d02021-03-11 11:08:46 -0500251 filePaths, ok := bazelCtx.GetOutputFiles(label, ctx.Arch().ArchType)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400252 if ok {
253 var bazelOutputFiles android.Paths
Chris Parsonse59af4e2021-03-31 13:32:41 -0400254 exportIncludeDirs := map[string]bool{}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400255 for _, bazelOutputFile := range filePaths {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500256 bazelOutputFiles = append(bazelOutputFiles, android.PathForBazelOut(ctx, bazelOutputFile))
Chris Parsonse59af4e2021-03-31 13:32:41 -0400257 exportIncludeDirs[filepath.Dir(bazelOutputFile)] = true
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400258 }
259 c.outputFiles = bazelOutputFiles
260 c.outputDeps = bazelOutputFiles
Chris Parsonse59af4e2021-03-31 13:32:41 -0400261 for includePath, _ := range exportIncludeDirs {
262 c.exportedIncludeDirs = append(c.exportedIncludeDirs, android.PathForBazelOut(ctx, includePath))
263 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400264 }
265 return ok
266}
Colin Crossf1885962020-11-20 15:28:30 -0800267
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700268func (g *Module) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Colin Crossa4ad2b02019-03-18 22:15:32 -0700269 g.subName = ctx.ModuleSubDir()
270
bralee1fbf4402020-05-21 10:11:59 +0800271 // Collect the module directory for IDE info in java/jdeps.go.
272 g.modulePaths = append(g.modulePaths, ctx.ModuleDir())
273
Colin Cross5ed99c62016-11-22 12:55:55 -0800274 if len(g.properties.Export_include_dirs) > 0 {
275 for _, dir := range g.properties.Export_include_dirs {
276 g.exportedIncludeDirs = append(g.exportedIncludeDirs,
Colin Cross1a527682019-09-23 15:55:30 -0700277 android.PathForModuleGen(ctx, g.subDir, ctx.ModuleDir(), dir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800278 }
279 } else {
Colin Cross1a527682019-09-23 15:55:30 -0700280 g.exportedIncludeDirs = append(g.exportedIncludeDirs, android.PathForModuleGen(ctx, g.subDir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800281 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700282
Colin Crossd11cf622021-03-23 22:30:35 -0700283 locationLabels := map[string]location{}
Colin Cross08f15ab2018-10-04 23:29:14 -0700284 firstLabel := ""
285
Colin Crossd11cf622021-03-23 22:30:35 -0700286 addLocationLabel := func(label string, loc location) {
Colin Cross08f15ab2018-10-04 23:29:14 -0700287 if firstLabel == "" {
288 firstLabel = label
289 }
290 if _, exists := locationLabels[label]; !exists {
Colin Crossd11cf622021-03-23 22:30:35 -0700291 locationLabels[label] = loc
Colin Cross08f15ab2018-10-04 23:29:14 -0700292 } else {
Anton Hansson7cd41e52021-10-08 16:13:10 +0100293 ctx.ModuleErrorf("multiple locations for label %q: %q and %q (do you have duplicate srcs entries?)",
Colin Crossd11cf622021-03-23 22:30:35 -0700294 label, locationLabels[label], loc)
Colin Cross08f15ab2018-10-04 23:29:14 -0700295 }
296 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700297
Colin Crossba9e4032020-11-24 16:32:22 -0800298 var tools android.Paths
299 var packagedTools []android.PackagingSpec
Colin Cross6f080df2016-11-04 15:32:58 -0700300 if len(g.properties.Tools) > 0 {
Colin Crossba71a3f2019-03-18 12:12:48 -0700301 seenTools := make(map[string]bool)
302
Colin Cross35143d02017-11-16 00:11:20 -0800303 ctx.VisitDirectDepsBlueprint(func(module blueprint.Module) {
Colin Cross08f15ab2018-10-04 23:29:14 -0700304 switch tag := ctx.OtherModuleDependencyTag(module).(type) {
305 case hostToolDependencyTag:
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700306 tool := ctx.OtherModuleName(module)
307
Colin Crossba9e4032020-11-24 16:32:22 -0800308 switch t := module.(type) {
309 case android.HostToolProvider:
310 // A HostToolProvider provides the path to a tool, which will be copied
311 // into the sandbox.
Colin Cross35143d02017-11-16 00:11:20 -0800312 if !t.(android.Module).Enabled() {
Colin Cross6510f912017-11-29 00:27:14 -0800313 if ctx.Config().AllowMissingDependencies() {
Colin Cross35143d02017-11-16 00:11:20 -0800314 ctx.AddMissingDependencies([]string{tool})
315 } else {
316 ctx.ModuleErrorf("depends on disabled module %q", tool)
317 }
Colin Crossba9e4032020-11-24 16:32:22 -0800318 return
Colin Cross35143d02017-11-16 00:11:20 -0800319 }
Colin Crossba9e4032020-11-24 16:32:22 -0800320 path := t.HostToolPath()
321 if !path.Valid() {
322 ctx.ModuleErrorf("host tool %q missing output file", tool)
323 return
324 }
325 if specs := t.TransitivePackagingSpecs(); specs != nil {
326 // If the HostToolProvider has PackgingSpecs, which are definitions of the
327 // required relative locations of the tool and its dependencies, use those
328 // instead. They will be copied to those relative locations in the sbox
329 // sandbox.
330 packagedTools = append(packagedTools, specs...)
331 // Assume that the first PackagingSpec of the module is the tool.
Colin Crossd11cf622021-03-23 22:30:35 -0700332 addLocationLabel(tag.label, packagedToolLocation{specs[0]})
Colin Crossba9e4032020-11-24 16:32:22 -0800333 } else {
334 tools = append(tools, path.Path())
Colin Crossd11cf622021-03-23 22:30:35 -0700335 addLocationLabel(tag.label, toolLocation{android.Paths{path.Path()}})
Colin Crossba9e4032020-11-24 16:32:22 -0800336 }
337 case bootstrap.GoBinaryTool:
338 // A GoBinaryTool provides the install path to a tool, which will be copied.
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700339 if s, err := filepath.Rel(android.PathForOutput(ctx).String(), t.InstallPath()); err == nil {
Colin Crossba9e4032020-11-24 16:32:22 -0800340 toolPath := android.PathForOutput(ctx, s)
341 tools = append(tools, toolPath)
Colin Crossd11cf622021-03-23 22:30:35 -0700342 addLocationLabel(tag.label, toolLocation{android.Paths{toolPath}})
Colin Cross6f080df2016-11-04 15:32:58 -0700343 } else {
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700344 ctx.ModuleErrorf("cannot find path for %q: %v", tool, err)
Colin Crossba9e4032020-11-24 16:32:22 -0800345 return
Colin Cross6f080df2016-11-04 15:32:58 -0700346 }
Colin Crossba9e4032020-11-24 16:32:22 -0800347 default:
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700348 ctx.ModuleErrorf("%q is not a host tool provider", tool)
Colin Crossba9e4032020-11-24 16:32:22 -0800349 return
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700350 }
351
Colin Crossba9e4032020-11-24 16:32:22 -0800352 seenTools[tag.label] = true
Colin Crossd350ecd2015-04-28 13:25:36 -0700353 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700354 })
Colin Crossba71a3f2019-03-18 12:12:48 -0700355
356 // If AllowMissingDependencies is enabled, the build will not have stopped when
357 // AddFarVariationDependencies was called on a missing tool, which will result in nonsensical
Liz Kammer20ebfb42020-07-28 11:32:07 -0700358 // "cmd: unknown location label ..." errors later. Add a placeholder file to the local label.
359 // The command that uses this placeholder file will never be executed because the rule will be
360 // replaced with an android.Error rule reporting the missing dependencies.
Colin Crossba71a3f2019-03-18 12:12:48 -0700361 if ctx.Config().AllowMissingDependencies() {
362 for _, tool := range g.properties.Tools {
363 if !seenTools[tool] {
Colin Crossd11cf622021-03-23 22:30:35 -0700364 addLocationLabel(tool, errorLocation{"***missing tool " + tool + "***"})
Colin Crossba71a3f2019-03-18 12:12:48 -0700365 }
366 }
367 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700368 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700369
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700370 if ctx.Failed() {
371 return
372 }
373
Colin Cross08f15ab2018-10-04 23:29:14 -0700374 for _, toolFile := range g.properties.Tool_files {
Colin Cross8a497952019-03-05 22:25:09 -0800375 paths := android.PathsForModuleSrc(ctx, []string{toolFile})
Colin Crossba9e4032020-11-24 16:32:22 -0800376 tools = append(tools, paths...)
Colin Crossd11cf622021-03-23 22:30:35 -0700377 addLocationLabel(toolFile, toolLocation{paths})
Colin Cross08f15ab2018-10-04 23:29:14 -0700378 }
379
380 var srcFiles android.Paths
381 for _, in := range g.properties.Srcs {
Colin Crossba71a3f2019-03-18 12:12:48 -0700382 paths, missingDeps := android.PathsAndMissingDepsForModuleSrcExcludes(ctx, []string{in}, g.properties.Exclude_srcs)
383 if len(missingDeps) > 0 {
384 if !ctx.Config().AllowMissingDependencies() {
385 panic(fmt.Errorf("should never get here, the missing dependencies %q should have been reported in DepsMutator",
386 missingDeps))
387 }
388
389 // If AllowMissingDependencies is enabled, the build will not have stopped when
390 // the dependency was added on a missing SourceFileProducer module, which will result in nonsensical
Liz Kammer20ebfb42020-07-28 11:32:07 -0700391 // "cmd: label ":..." has no files" errors later. Add a placeholder file to the local label.
392 // The command that uses this placeholder file will never be executed because the rule will be
393 // replaced with an android.Error rule reporting the missing dependencies.
Colin Crossba71a3f2019-03-18 12:12:48 -0700394 ctx.AddMissingDependencies(missingDeps)
Colin Crossd11cf622021-03-23 22:30:35 -0700395 addLocationLabel(in, errorLocation{"***missing srcs " + in + "***"})
Colin Crossba71a3f2019-03-18 12:12:48 -0700396 } else {
397 srcFiles = append(srcFiles, paths...)
Colin Crossd11cf622021-03-23 22:30:35 -0700398 addLocationLabel(in, inputLocation{paths})
Colin Crossba71a3f2019-03-18 12:12:48 -0700399 }
Colin Cross08f15ab2018-10-04 23:29:14 -0700400 }
401
Colin Cross1a527682019-09-23 15:55:30 -0700402 var copyFrom android.Paths
403 var outputFiles android.WritablePaths
404 var zipArgs strings.Builder
Colin Cross08f15ab2018-10-04 23:29:14 -0700405
Colin Crossf3bfd022021-09-27 15:15:06 -0700406 cmd := String(g.properties.Cmd)
407 if g.CmdModifier != nil {
408 cmd = g.CmdModifier(ctx, cmd)
409 }
410
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500411 // Generate tasks, either from genrule or gensrcs.
Colin Crossf3bfd022021-09-27 15:15:06 -0700412 for _, task := range g.taskGenerator(ctx, cmd, srcFiles) {
Colin Cross3d680512020-11-13 16:23:53 -0800413 if len(task.out) == 0 {
414 ctx.ModuleErrorf("must have at least one output file")
415 return
Colin Cross85a2e892018-07-09 09:45:06 -0700416 }
417
Colin Crossf1a035e2020-11-16 17:32:30 -0800418 // Pick a unique path outside the task.genDir for the sbox manifest textproto,
419 // a unique rule name, and the user-visible description.
420 manifestName := "genrule.sbox.textproto"
421 desc := "generate"
422 name := "generator"
423 if task.shards > 0 {
424 manifestName = "genrule_" + strconv.Itoa(task.shard) + ".sbox.textproto"
425 desc += " " + strconv.Itoa(task.shard)
426 name += strconv.Itoa(task.shard)
427 } else if len(task.out) == 1 {
428 desc += " " + task.out[0].Base()
429 }
430
431 manifestPath := android.PathForModuleOut(ctx, manifestName)
432
433 // Use a RuleBuilder to create a rule that runs the command inside an sbox sandbox.
Colin Crossba9e4032020-11-24 16:32:22 -0800434 rule := android.NewRuleBuilder(pctx, ctx).Sbox(task.genDir, manifestPath).SandboxTools()
Colin Crossf1a035e2020-11-16 17:32:30 -0800435 cmd := rule.Command()
436
Colin Cross3d680512020-11-13 16:23:53 -0800437 for _, out := range task.out {
Colin Crossd11cf622021-03-23 22:30:35 -0700438 addLocationLabel(out.Rel(), outputLocation{out})
Colin Cross3d680512020-11-13 16:23:53 -0800439 }
440
Colin Cross1a527682019-09-23 15:55:30 -0700441 referencedDepfile := false
442
Colin Cross3d680512020-11-13 16:23:53 -0800443 rawCommand, err := android.Expand(task.cmd, func(name string) (string, error) {
Colin Cross1a527682019-09-23 15:55:30 -0700444 // report the error directly without returning an error to android.Expand to catch multiple errors in a
445 // single run
Colin Cross3d680512020-11-13 16:23:53 -0800446 reportError := func(fmt string, args ...interface{}) (string, error) {
Colin Cross1a527682019-09-23 15:55:30 -0700447 ctx.PropertyErrorf("cmd", fmt, args...)
Colin Cross3d680512020-11-13 16:23:53 -0800448 return "SOONG_ERROR", nil
Colin Cross6f080df2016-11-04 15:32:58 -0700449 }
Colin Cross1a527682019-09-23 15:55:30 -0700450
451 switch name {
452 case "location":
453 if len(g.properties.Tools) == 0 && len(g.properties.Tool_files) == 0 {
454 return reportError("at least one `tools` or `tool_files` is required if $(location) is used")
Colin Cross6f080df2016-11-04 15:32:58 -0700455 }
Colin Crossd11cf622021-03-23 22:30:35 -0700456 loc := locationLabels[firstLabel]
457 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700458 if len(paths) == 0 {
459 return reportError("default label %q has no files", firstLabel)
460 } else if len(paths) > 1 {
461 return reportError("default label %q has multiple files, use $(locations %s) to reference it",
462 firstLabel, firstLabel)
Colin Cross08f15ab2018-10-04 23:29:14 -0700463 }
Colin Crossd11cf622021-03-23 22:30:35 -0700464 return paths[0], nil
Colin Cross1a527682019-09-23 15:55:30 -0700465 case "in":
Colin Crossd11cf622021-03-23 22:30:35 -0700466 return strings.Join(cmd.PathsForInputs(srcFiles), " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700467 case "out":
Colin Cross3d680512020-11-13 16:23:53 -0800468 var sandboxOuts []string
469 for _, out := range task.out {
Colin Crossf1a035e2020-11-16 17:32:30 -0800470 sandboxOuts = append(sandboxOuts, cmd.PathForOutput(out))
Colin Cross3d680512020-11-13 16:23:53 -0800471 }
472 return strings.Join(sandboxOuts, " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700473 case "depfile":
474 referencedDepfile = true
475 if !Bool(g.properties.Depfile) {
476 return reportError("$(depfile) used without depfile property")
477 }
Colin Cross3d680512020-11-13 16:23:53 -0800478 return "__SBOX_DEPFILE__", nil
Colin Cross1a527682019-09-23 15:55:30 -0700479 case "genDir":
Colin Crossf1a035e2020-11-16 17:32:30 -0800480 return cmd.PathForOutput(task.genDir), nil
Colin Cross1a527682019-09-23 15:55:30 -0700481 default:
482 if strings.HasPrefix(name, "location ") {
483 label := strings.TrimSpace(strings.TrimPrefix(name, "location "))
Colin Crossd11cf622021-03-23 22:30:35 -0700484 if loc, ok := locationLabels[label]; ok {
485 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700486 if len(paths) == 0 {
487 return reportError("label %q has no files", label)
488 } else if len(paths) > 1 {
489 return reportError("label %q has multiple files, use $(locations %s) to reference it",
490 label, label)
491 }
Colin Cross3d680512020-11-13 16:23:53 -0800492 return paths[0], nil
Colin Cross1a527682019-09-23 15:55:30 -0700493 } else {
494 return reportError("unknown location label %q", label)
495 }
496 } else if strings.HasPrefix(name, "locations ") {
497 label := strings.TrimSpace(strings.TrimPrefix(name, "locations "))
Colin Crossd11cf622021-03-23 22:30:35 -0700498 if loc, ok := locationLabels[label]; ok {
499 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700500 if len(paths) == 0 {
501 return reportError("label %q has no files", label)
502 }
Colin Cross3d680512020-11-13 16:23:53 -0800503 return strings.Join(paths, " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700504 } else {
505 return reportError("unknown locations label %q", label)
506 }
507 } else {
508 return reportError("unknown variable '$(%s)'", name)
509 }
Colin Cross6f080df2016-11-04 15:32:58 -0700510 }
Colin Cross1a527682019-09-23 15:55:30 -0700511 })
512
513 if err != nil {
514 ctx.PropertyErrorf("cmd", "%s", err.Error())
515 return
Colin Cross6f080df2016-11-04 15:32:58 -0700516 }
Colin Cross6f080df2016-11-04 15:32:58 -0700517
Colin Cross1a527682019-09-23 15:55:30 -0700518 if Bool(g.properties.Depfile) && !referencedDepfile {
519 ctx.PropertyErrorf("cmd", "specified depfile=true but did not include a reference to '${depfile}' in cmd")
520 return
521 }
Colin Cross1a527682019-09-23 15:55:30 -0700522 g.rawCommands = append(g.rawCommands, rawCommand)
Bill Peckhamc087be12020-02-13 15:55:10 -0800523
Colin Cross3d680512020-11-13 16:23:53 -0800524 cmd.Text(rawCommand)
525 cmd.ImplicitOutputs(task.out)
526 cmd.Implicits(task.in)
Colin Crossba9e4032020-11-24 16:32:22 -0800527 cmd.ImplicitTools(tools)
528 cmd.ImplicitTools(task.extraTools)
529 cmd.ImplicitPackagedTools(packagedTools)
Colin Cross3d680512020-11-13 16:23:53 -0800530 if Bool(g.properties.Depfile) {
531 cmd.ImplicitDepFile(task.depFile)
532 }
533
534 // Create the rule to run the genrule command inside sbox.
Colin Crossf1a035e2020-11-16 17:32:30 -0800535 rule.Build(name, desc)
Colin Cross1a527682019-09-23 15:55:30 -0700536
537 if len(task.copyTo) > 0 {
Colin Cross3d680512020-11-13 16:23:53 -0800538 // If copyTo is set, multiple shards need to be copied into a single directory.
539 // task.out contains the per-shard paths, and copyTo contains the corresponding
540 // final path. The files need to be copied into the final directory by a
541 // single rule so it can remove the directory before it starts to ensure no
542 // old files remain. zipsync already does this, so build up zipArgs that
543 // zip all the per-shard directories into a single zip.
Colin Cross1a527682019-09-23 15:55:30 -0700544 outputFiles = append(outputFiles, task.copyTo...)
545 copyFrom = append(copyFrom, task.out.Paths()...)
546 zipArgs.WriteString(" -C " + task.genDir.String())
547 zipArgs.WriteString(android.JoinWithPrefix(task.out.Strings(), " -f "))
548 } else {
549 outputFiles = append(outputFiles, task.out...)
550 }
Colin Cross6f080df2016-11-04 15:32:58 -0700551 }
552
Colin Cross1a527682019-09-23 15:55:30 -0700553 if len(copyFrom) > 0 {
Colin Cross3d680512020-11-13 16:23:53 -0800554 // Create a rule that zips all the per-shard directories into a single zip and then
555 // uses zipsync to unzip it into the final directory.
Colin Cross1a527682019-09-23 15:55:30 -0700556 ctx.Build(pctx, android.BuildParams{
Colin Crossf1885962020-11-20 15:28:30 -0800557 Rule: gensrcsMerge,
558 Implicits: copyFrom,
559 Outputs: outputFiles,
560 Description: "merge shards",
Colin Cross1a527682019-09-23 15:55:30 -0700561 Args: map[string]string{
562 "zipArgs": zipArgs.String(),
563 "tmpZip": android.PathForModuleGen(ctx, g.subDir+".zip").String(),
564 "genDir": android.PathForModuleGen(ctx, g.subDir).String(),
565 },
566 })
Colin Cross85a2e892018-07-09 09:45:06 -0700567 }
568
Colin Cross1a527682019-09-23 15:55:30 -0700569 g.outputFiles = outputFiles.Paths()
Jeff Gastonefc1b412017-03-29 17:29:06 -0700570
Liz Kammerbdc60992021-02-24 16:55:11 -0500571 bazelModuleLabel := g.GetBazelLabel(ctx, g)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400572 bazelActionsUsed := false
Chris Parsonsbab4d7e2021-04-15 17:27:08 -0400573 if g.MixedBuildsEnabled(ctx) {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux0d990452021-08-11 16:46:13 +0000574 bazelActionsUsed = g.GenerateBazelBuildActions(ctx, bazelModuleLabel)
Jeff Gaston02a684b2017-10-27 14:59:27 -0700575 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400576 if !bazelActionsUsed {
577 // For <= 6 outputs, just embed those directly in the users. Right now, that covers >90% of
578 // the genrules on AOSP. That will make things simpler to look at the graph in the common
579 // case. For larger sets of outputs, inject a phony target in between to limit ninja file
580 // growth.
581 if len(g.outputFiles) <= 6 {
582 g.outputDeps = g.outputFiles
583 } else {
584 phonyFile := android.PathForModuleGen(ctx, "genrule-phony")
585 ctx.Build(pctx, android.BuildParams{
586 Rule: blueprint.Phony,
587 Output: phonyFile,
588 Inputs: g.outputFiles,
589 })
590 g.outputDeps = android.Paths{phonyFile}
591 }
592 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700593}
Colin Crossd350ecd2015-04-28 13:25:36 -0700594
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700595// Collect information for opening IDE project files in java/jdeps.go.
596func (g *Module) IDEInfo(dpInfo *android.IdeInfo) {
597 dpInfo.Srcs = append(dpInfo.Srcs, g.Srcs().Strings()...)
598 for _, src := range g.properties.Srcs {
599 if strings.HasPrefix(src, ":") {
600 src = strings.Trim(src, ":")
601 dpInfo.Deps = append(dpInfo.Deps, src)
602 }
603 }
bralee1fbf4402020-05-21 10:11:59 +0800604 dpInfo.Paths = append(dpInfo.Paths, g.modulePaths...)
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700605}
606
Colin Crossa4ad2b02019-03-18 22:15:32 -0700607func (g *Module) AndroidMk() android.AndroidMkData {
608 return android.AndroidMkData{
Anton Hansson72f18492020-10-30 16:34:45 +0000609 Class: "ETC",
Colin Crossa4ad2b02019-03-18 22:15:32 -0700610 OutputFile: android.OptionalPathForPath(g.outputFiles[0]),
611 SubName: g.subName,
612 Extra: []android.AndroidMkExtraFunc{
613 func(w io.Writer, outputFile android.Path) {
Anton Hansson72f18492020-10-30 16:34:45 +0000614 fmt.Fprintln(w, "LOCAL_UNINSTALLABLE_MODULE := true")
Colin Crossa4ad2b02019-03-18 22:15:32 -0700615 },
616 },
617 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
618 android.WriteAndroidMkData(w, data)
619 if data.SubName != "" {
620 fmt.Fprintln(w, ".PHONY:", name)
621 fmt.Fprintln(w, name, ":", name+g.subName)
622 }
623 },
624 }
625}
626
Jiyong Park45bf82e2020-12-15 22:29:02 +0900627var _ android.ApexModule = (*Module)(nil)
628
629// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -0700630func (g *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
631 sdkVersion android.ApiLevel) error {
Jooyung Han749dc692020-04-15 11:03:39 +0900632 // Because generated outputs are checked by client modules(e.g. cc_library, ...)
633 // we can safely ignore the check here.
634 return nil
635}
636
Jeff Gaston437d23c2017-11-08 12:38:00 -0800637func generatorFactory(taskGenerator taskFunc, props ...interface{}) *Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700638 module := &Module{
Jeff Gaston437d23c2017-11-08 12:38:00 -0800639 taskGenerator: taskGenerator,
Colin Crossd350ecd2015-04-28 13:25:36 -0700640 }
641
Colin Cross36242852017-06-23 15:06:31 -0700642 module.AddProperties(props...)
643 module.AddProperties(&module.properties)
Colin Crossd350ecd2015-04-28 13:25:36 -0700644
Colin Cross7228ecd2019-11-18 16:00:16 -0800645 module.ImageInterface = noopImageInterface{}
646
Colin Cross36242852017-06-23 15:06:31 -0700647 return module
Colin Crossd350ecd2015-04-28 13:25:36 -0700648}
649
Colin Cross7228ecd2019-11-18 16:00:16 -0800650type noopImageInterface struct{}
651
652func (x noopImageInterface) ImageMutatorBegin(android.BaseModuleContext) {}
653func (x noopImageInterface) CoreVariantNeeded(android.BaseModuleContext) bool { return false }
Yifan Hong1b3348d2020-01-21 15:53:22 -0800654func (x noopImageInterface) RamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700655func (x noopImageInterface) VendorRamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Inseob Kim08758f02021-04-08 21:13:22 +0900656func (x noopImageInterface) DebugRamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Colin Cross7228ecd2019-11-18 16:00:16 -0800657func (x noopImageInterface) RecoveryVariantNeeded(android.BaseModuleContext) bool { return false }
658func (x noopImageInterface) ExtraImageVariations(ctx android.BaseModuleContext) []string { return nil }
659func (x noopImageInterface) SetImageVariation(ctx android.BaseModuleContext, variation string, module android.Module) {
660}
661
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700662func NewGenSrcs() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700663 properties := &genSrcsProperties{}
664
Colin Crossf1885962020-11-20 15:28:30 -0800665 // finalSubDir is the name of the subdirectory that output files will be generated into.
666 // It is used so that per-shard directories can be placed alongside it an then finally
667 // merged into it.
668 const finalSubDir = "gensrcs"
669
Colin Cross1a527682019-09-23 15:55:30 -0700670 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Colin Cross1a527682019-09-23 15:55:30 -0700671 shardSize := defaultShardSize
672 if s := properties.Shard_size; s != nil {
673 shardSize = int(*s)
674 }
Jeff Gaston437d23c2017-11-08 12:38:00 -0800675
Colin Crossf1885962020-11-20 15:28:30 -0800676 // gensrcs rules can easily hit command line limits by repeating the command for
677 // every input file. Shard the input files into groups.
Colin Cross1a527682019-09-23 15:55:30 -0700678 shards := android.ShardPaths(srcFiles, shardSize)
679 var generateTasks []generateTask
Colin Crossbaccf5b2018-02-21 14:07:48 -0800680
Colin Cross1a527682019-09-23 15:55:30 -0700681 for i, shard := range shards {
682 var commands []string
683 var outFiles android.WritablePaths
Colin Cross3ea4eb82020-11-24 13:07:27 -0800684 var commandDepFiles []string
Colin Cross1a527682019-09-23 15:55:30 -0700685 var copyTo android.WritablePaths
Colin Cross1a527682019-09-23 15:55:30 -0700686
Colin Crossf1885962020-11-20 15:28:30 -0800687 // When sharding is enabled (i.e. len(shards) > 1), the sbox rules for each
688 // shard will be write to their own directories and then be merged together
689 // into finalSubDir. If sharding is not enabled (i.e. len(shards) == 1),
690 // the sbox rule will write directly to finalSubDir.
691 genSubDir := finalSubDir
Colin Cross1a527682019-09-23 15:55:30 -0700692 if len(shards) > 1 {
Colin Crossf1885962020-11-20 15:28:30 -0800693 genSubDir = strconv.Itoa(i)
Jeff Gaston437d23c2017-11-08 12:38:00 -0800694 }
695
Colin Crossf1885962020-11-20 15:28:30 -0800696 genDir := android.PathForModuleGen(ctx, genSubDir)
Colin Crossf1a035e2020-11-16 17:32:30 -0800697 // TODO(ccross): this RuleBuilder is a hack to be able to call
698 // rule.Command().PathForOutput. Replace this with passing the rule into the
699 // generator.
Colin Crossba9e4032020-11-24 16:32:22 -0800700 rule := android.NewRuleBuilder(pctx, ctx).Sbox(genDir, nil).SandboxTools()
Jeff Gaston437d23c2017-11-08 12:38:00 -0800701
Colin Cross3ea4eb82020-11-24 13:07:27 -0800702 for _, in := range shard {
Colin Crossf1885962020-11-20 15:28:30 -0800703 outFile := android.GenPathWithExt(ctx, finalSubDir, in, String(properties.Output_extension))
704
705 // If sharding is enabled, then outFile is the path to the output file in
706 // the shard directory, and copyTo is the path to the output file in the
707 // final directory.
Colin Cross1a527682019-09-23 15:55:30 -0700708 if len(shards) > 1 {
Colin Crossf1885962020-11-20 15:28:30 -0800709 shardFile := android.GenPathWithExt(ctx, genSubDir, in, String(properties.Output_extension))
Colin Cross1a527682019-09-23 15:55:30 -0700710 copyTo = append(copyTo, outFile)
711 outFile = shardFile
712 }
713
714 outFiles = append(outFiles, outFile)
Colin Cross1a527682019-09-23 15:55:30 -0700715
Colin Crossf1885962020-11-20 15:28:30 -0800716 // pre-expand the command line to replace $in and $out with references to
717 // a single input and output file.
Colin Cross1a527682019-09-23 15:55:30 -0700718 command, err := android.Expand(rawCommand, func(name string) (string, error) {
719 switch name {
720 case "in":
721 return in.String(), nil
722 case "out":
Colin Crossf1a035e2020-11-16 17:32:30 -0800723 return rule.Command().PathForOutput(outFile), nil
Colin Cross3ea4eb82020-11-24 13:07:27 -0800724 case "depfile":
725 // Generate a depfile for each output file. Store the list for
726 // later in order to combine them all into a single depfile.
Colin Crossf1a035e2020-11-16 17:32:30 -0800727 depFile := rule.Command().PathForOutput(outFile.ReplaceExtension(ctx, "d"))
Colin Cross3ea4eb82020-11-24 13:07:27 -0800728 commandDepFiles = append(commandDepFiles, depFile)
729 return depFile, nil
Colin Cross1a527682019-09-23 15:55:30 -0700730 default:
731 return "$(" + name + ")", nil
732 }
733 })
734 if err != nil {
735 ctx.PropertyErrorf("cmd", err.Error())
736 }
737
738 // escape the command in case for example it contains '#', an odd number of '"', etc
739 command = fmt.Sprintf("bash -c %v", proptools.ShellEscape(command))
740 commands = append(commands, command)
741 }
742 fullCommand := strings.Join(commands, " && ")
743
Colin Cross3ea4eb82020-11-24 13:07:27 -0800744 var outputDepfile android.WritablePath
745 var extraTools android.Paths
746 if len(commandDepFiles) > 0 {
747 // Each command wrote to a depfile, but ninja can only handle one
748 // depfile per rule. Use the dep_fixer tool at the end of the
749 // command to combine all the depfiles into a single output depfile.
750 outputDepfile = android.PathForModuleGen(ctx, genSubDir, "gensrcs.d")
751 depFixerTool := ctx.Config().HostToolPath(ctx, "dep_fixer")
752 fullCommand += fmt.Sprintf(" && %s -o $(depfile) %s",
Colin Crossd11cf622021-03-23 22:30:35 -0700753 rule.Command().PathForTool(depFixerTool),
Colin Crossba9e4032020-11-24 16:32:22 -0800754 strings.Join(commandDepFiles, " "))
Colin Cross3ea4eb82020-11-24 13:07:27 -0800755 extraTools = append(extraTools, depFixerTool)
756 }
757
Colin Cross1a527682019-09-23 15:55:30 -0700758 generateTasks = append(generateTasks, generateTask{
Colin Cross3ea4eb82020-11-24 13:07:27 -0800759 in: shard,
760 out: outFiles,
761 depFile: outputDepfile,
762 copyTo: copyTo,
763 genDir: genDir,
764 cmd: fullCommand,
765 shard: i,
766 shards: len(shards),
767 extraTools: extraTools,
Colin Cross1a527682019-09-23 15:55:30 -0700768 })
Jeff Gaston437d23c2017-11-08 12:38:00 -0800769 }
Colin Cross1a527682019-09-23 15:55:30 -0700770
771 return generateTasks
Colin Crossd350ecd2015-04-28 13:25:36 -0700772 }
773
Colin Cross1a527682019-09-23 15:55:30 -0700774 g := generatorFactory(taskGenerator, properties)
Colin Crossf1885962020-11-20 15:28:30 -0800775 g.subDir = finalSubDir
Colin Cross1a527682019-09-23 15:55:30 -0700776 return g
Colin Crossd350ecd2015-04-28 13:25:36 -0700777}
778
Colin Cross54190b32017-10-09 15:34:10 -0700779func GenSrcsFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700780 m := NewGenSrcs()
781 android.InitAndroidModule(m)
782 return m
783}
784
Colin Crossd350ecd2015-04-28 13:25:36 -0700785type genSrcsProperties struct {
Colin Cross7d5136f2015-05-11 13:39:40 -0700786 // extension that will be substituted for each output file
Nan Zhanga5e7cb42017-11-09 22:42:32 -0800787 Output_extension *string
Colin Cross1a527682019-09-23 15:55:30 -0700788
789 // maximum number of files that will be passed on a single command line.
790 Shard_size *int64
Colin Cross5049f022015-03-18 13:28:46 -0700791}
792
Evgenii Stepanovf47c90d2020-12-02 18:55:09 -0800793const defaultShardSize = 50
Colin Cross1a527682019-09-23 15:55:30 -0700794
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700795func NewGenRule() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700796 properties := &genRuleProperties{}
Colin Cross5049f022015-03-18 13:28:46 -0700797
Colin Cross1a527682019-09-23 15:55:30 -0700798 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700799 outs := make(android.WritablePaths, len(properties.Out))
Colin Cross3d680512020-11-13 16:23:53 -0800800 var depFile android.WritablePath
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700801 for i, out := range properties.Out {
Colin Cross3d680512020-11-13 16:23:53 -0800802 outPath := android.PathForModuleGen(ctx, out)
803 if i == 0 {
804 depFile = outPath.ReplaceExtension(ctx, "d")
805 }
806 outs[i] = outPath
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700807 }
Colin Cross1a527682019-09-23 15:55:30 -0700808 return []generateTask{{
Colin Cross3d680512020-11-13 16:23:53 -0800809 in: srcFiles,
810 out: outs,
811 depFile: depFile,
812 genDir: android.PathForModuleGen(ctx),
813 cmd: rawCommand,
Colin Cross1a527682019-09-23 15:55:30 -0700814 }}
Colin Cross5049f022015-03-18 13:28:46 -0700815 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700816
Jeff Gaston437d23c2017-11-08 12:38:00 -0800817 return generatorFactory(taskGenerator, properties)
Colin Cross5049f022015-03-18 13:28:46 -0700818}
819
Colin Cross54190b32017-10-09 15:34:10 -0700820func GenRuleFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700821 m := NewGenRule()
822 android.InitAndroidModule(m)
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800823 android.InitDefaultableModule(m)
Liz Kammerea6666f2021-02-17 10:17:28 -0500824 android.InitBazelModule(m)
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700825 return m
826}
827
Colin Crossd350ecd2015-04-28 13:25:36 -0700828type genRuleProperties struct {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700829 // names of the output files that will be generated
Colin Crossef354482018-10-23 11:27:50 -0700830 Out []string `android:"arch_variant"`
Colin Cross5049f022015-03-18 13:28:46 -0700831}
Nan Zhangea568a42017-11-08 21:20:04 -0800832
Jingwen Chen316e07c2020-12-14 09:09:52 -0500833type bazelGenruleAttributes struct {
Jingwen Chen07027912021-03-15 06:02:43 -0400834 Srcs bazel.LabelListAttribute
Jingwen Chen316e07c2020-12-14 09:09:52 -0500835 Outs []string
Jingwen Chen07027912021-03-15 06:02:43 -0400836 Tools bazel.LabelListAttribute
Jingwen Chen316e07c2020-12-14 09:09:52 -0500837 Cmd string
838}
839
Wei Libcd39942021-09-16 23:57:28 +0000840// CcGenruleBp2Build is for cc_genrule.
841func CcGenruleBp2Build(ctx android.TopDownMutatorContext) {
842 m, ok := ctx.Module().(*Module)
843 if !ok || !m.ConvertWithBp2build(ctx) {
844 return
845 }
846
847 if ctx.ModuleType() != "cc_genrule" {
848 // Not a cc_genrule.
849 return
850 }
851
852 genruleBp2Build(ctx)
853}
854
855// GenruleBp2Build is used for genrule.
Jingwen Chena42d6412021-01-26 21:57:27 -0500856func GenruleBp2Build(ctx android.TopDownMutatorContext) {
Liz Kammer356f7d42021-01-26 09:18:53 -0500857 m, ok := ctx.Module().(*Module)
Jingwen Chen12b4c272021-03-10 02:05:59 -0500858 if !ok || !m.ConvertWithBp2build(ctx) {
Liz Kammer356f7d42021-01-26 09:18:53 -0500859 return
Jingwen Chen316e07c2020-12-14 09:09:52 -0500860 }
Jingwen Chen1fd14692021-02-05 03:01:50 -0500861
Jingwen Chen66480452021-03-18 03:41:55 -0400862 if ctx.ModuleType() != "genrule" {
Wei Libcd39942021-09-16 23:57:28 +0000863 // Not a regular genrule.
Jingwen Chen66480452021-03-18 03:41:55 -0400864 return
865 }
866
Wei Libcd39942021-09-16 23:57:28 +0000867 genruleBp2Build(ctx)
868}
869
870func genruleBp2Build(ctx android.TopDownMutatorContext) {
871 m, _ := ctx.Module().(*Module)
Liz Kammer356f7d42021-01-26 09:18:53 -0500872 // Bazel only has the "tools" attribute.
Jingwen Chen07027912021-03-15 06:02:43 -0400873 tools_prop := android.BazelLabelForModuleDeps(ctx, m.properties.Tools)
874 tool_files_prop := android.BazelLabelForModuleSrc(ctx, m.properties.Tool_files)
875 tools_prop.Append(tool_files_prop)
Liz Kammer356f7d42021-01-26 09:18:53 -0500876
Jingwen Chen07027912021-03-15 06:02:43 -0400877 tools := bazel.MakeLabelListAttribute(tools_prop)
878 srcs := bazel.MakeLabelListAttribute(android.BazelLabelForModuleSrc(ctx, m.properties.Srcs))
Liz Kammer356f7d42021-01-26 09:18:53 -0500879
880 var allReplacements bazel.LabelList
Jingwen Chen07027912021-03-15 06:02:43 -0400881 allReplacements.Append(tools.Value)
882 allReplacements.Append(srcs.Value)
Liz Kammer356f7d42021-01-26 09:18:53 -0500883
884 // Replace in and out variables with $< and $@
885 var cmd string
886 if m.properties.Cmd != nil {
887 cmd = strings.Replace(*m.properties.Cmd, "$(in)", "$(SRCS)", -1)
888 cmd = strings.Replace(cmd, "$(out)", "$(OUTS)", -1)
Wei Libcd39942021-09-16 23:57:28 +0000889 genDir := "$(GENDIR)"
890 if ctx.ModuleType() == "cc_genrule" {
891 genDir = "$(RULEDIR)"
892 }
893 cmd = strings.Replace(cmd, "$(genDir)", genDir, -1)
Jingwen Chen07027912021-03-15 06:02:43 -0400894 if len(tools.Value.Includes) > 0 {
895 cmd = strings.Replace(cmd, "$(location)", fmt.Sprintf("$(location %s)", tools.Value.Includes[0].Label), -1)
896 cmd = strings.Replace(cmd, "$(locations)", fmt.Sprintf("$(locations %s)", tools.Value.Includes[0].Label), -1)
Liz Kammer356f7d42021-01-26 09:18:53 -0500897 }
898 for _, l := range allReplacements.Includes {
Jingwen Chen38e62642021-04-19 05:00:15 +0000899 bpLoc := fmt.Sprintf("$(location %s)", l.OriginalModuleName)
900 bpLocs := fmt.Sprintf("$(locations %s)", l.OriginalModuleName)
Liz Kammer356f7d42021-01-26 09:18:53 -0500901 bazelLoc := fmt.Sprintf("$(location %s)", l.Label)
902 bazelLocs := fmt.Sprintf("$(locations %s)", l.Label)
903 cmd = strings.Replace(cmd, bpLoc, bazelLoc, -1)
904 cmd = strings.Replace(cmd, bpLocs, bazelLocs, -1)
905 }
906 }
907
908 // The Out prop is not in an immediately accessible field
909 // in the Module struct, so use GetProperties and cast it
910 // to the known struct prop.
911 var outs []string
912 for _, propIntf := range m.GetProperties() {
913 if props, ok := propIntf.(*genRuleProperties); ok {
914 outs = props.Out
915 break
916 }
917 }
918
Jingwen Chen1fd14692021-02-05 03:01:50 -0500919 attrs := &bazelGenruleAttributes{
Liz Kammer356f7d42021-01-26 09:18:53 -0500920 Srcs: srcs,
921 Outs: outs,
922 Cmd: cmd,
923 Tools: tools,
Jingwen Chen1fd14692021-02-05 03:01:50 -0500924 }
925
Liz Kammerfc46bc12021-02-19 11:06:17 -0500926 props := bazel.BazelTargetModuleProperties{
927 Rule_class: "genrule",
928 }
Jingwen Chen1fd14692021-02-05 03:01:50 -0500929
930 // Create the BazelTargetModule.
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000931 ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: m.Name()}, attrs)
Jingwen Chen316e07c2020-12-14 09:09:52 -0500932}
933
Nan Zhangea568a42017-11-08 21:20:04 -0800934var Bool = proptools.Bool
935var String = proptools.String
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800936
937//
938// Defaults
939//
940type Defaults struct {
941 android.ModuleBase
942 android.DefaultsModuleBase
943}
944
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800945func defaultsFactory() android.Module {
946 return DefaultsFactory()
947}
948
949func DefaultsFactory(props ...interface{}) android.Module {
950 module := &Defaults{}
951
952 module.AddProperties(props...)
953 module.AddProperties(
954 &generatorProperties{},
955 &genRuleProperties{},
956 )
957
958 android.InitDefaultsModule(module)
959
960 return module
961}