blob: fdb3618e97e1c03f50a43d415ae75bcbfa1f70d2 [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)
Colin Cross463a90e2015-06-17 14:20:06 -070072}
73
Liz Kammer356f7d42021-01-26 09:18:53 -050074func RegisterGenruleBp2BuildDeps(ctx android.RegisterMutatorsContext) {
75 ctx.BottomUp("genrule_tool_deps", toolDepsMutator)
76}
77
Colin Cross5049f022015-03-18 13:28:46 -070078var (
Colin Cross635c3b02016-05-18 15:37:25 -070079 pctx = android.NewPackageContext("android/soong/genrule")
Colin Cross1a527682019-09-23 15:55:30 -070080
Alex Humesky29e3bbe2020-11-20 21:30:13 -050081 // Used by gensrcs when there is more than 1 shard to merge the outputs
82 // of each shard into a zip file.
Colin Cross1a527682019-09-23 15:55:30 -070083 gensrcsMerge = pctx.AndroidStaticRule("gensrcsMerge", blueprint.RuleParams{
84 Command: "${soongZip} -o ${tmpZip} @${tmpZip}.rsp && ${zipSync} -d ${genDir} ${tmpZip}",
85 CommandDeps: []string{"${soongZip}", "${zipSync}"},
86 Rspfile: "${tmpZip}.rsp",
87 RspfileContent: "${zipArgs}",
88 }, "tmpZip", "genDir", "zipArgs")
Colin Cross5049f022015-03-18 13:28:46 -070089)
90
Jeff Gastonefc1b412017-03-29 17:29:06 -070091func init() {
Dan Willemsenddf504c2019-08-09 16:21:29 -070092 pctx.Import("android/soong/android")
Colin Cross1a527682019-09-23 15:55:30 -070093
94 pctx.HostBinToolVariable("soongZip", "soong_zip")
95 pctx.HostBinToolVariable("zipSync", "zipsync")
Jeff Gastonefc1b412017-03-29 17:29:06 -070096}
97
Colin Cross5049f022015-03-18 13:28:46 -070098type SourceFileGenerator interface {
Colin Cross635c3b02016-05-18 15:37:25 -070099 GeneratedSourceFiles() android.Paths
Colin Cross5ed99c62016-11-22 12:55:55 -0800100 GeneratedHeaderDirs() android.Paths
Dan Willemsen9da9d492018-02-21 18:28:18 -0800101 GeneratedDeps() android.Paths
Colin Cross5049f022015-03-18 13:28:46 -0700102}
103
Colin Crossfe17f6f2019-03-28 19:30:56 -0700104// Alias for android.HostToolProvider
105// Deprecated: use android.HostToolProvider instead.
Colin Crossd350ecd2015-04-28 13:25:36 -0700106type HostToolProvider interface {
Colin Crossfe17f6f2019-03-28 19:30:56 -0700107 android.HostToolProvider
Colin Crossd350ecd2015-04-28 13:25:36 -0700108}
Colin Cross5049f022015-03-18 13:28:46 -0700109
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700110type hostToolDependencyTag struct {
111 blueprint.BaseDependencyTag
Colin Cross08f15ab2018-10-04 23:29:14 -0700112 label string
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700113}
Colin Cross7d5136f2015-05-11 13:39:40 -0700114type generatorProperties struct {
Spandan Das93e95992021-07-29 18:26:39 +0000115 // The command to run on one or more input files. Cmd supports substitution of a few variables.
Jeff Gastonefc1b412017-03-29 17:29:06 -0700116 //
117 // Available variables for substitution:
118 //
Spandan Das93e95992021-07-29 18:26:39 +0000119 // $(location): the path to the first entry in tools or tool_files.
120 // $(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.
121 // $(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.
122 // $(in): one or more input files.
123 // $(out): a single output file.
124 // $(depfile): a file to which dependencies will be written, if the depfile property is set to true.
125 // $(genDir): the sandbox directory for this tool; contains $(out).
Colin Cross2296f5b2017-10-17 21:38:14 -0700126 // $$: a literal $
Nan Zhangea568a42017-11-08 21:20:04 -0800127 Cmd *string
Colin Cross7d5136f2015-05-11 13:39:40 -0700128
Colin Cross33bfb0a2016-11-21 17:23:08 -0800129 // Enable reading a file containing dependencies in gcc format after the command completes
Nan Zhangea568a42017-11-08 21:20:04 -0800130 Depfile *bool
Colin Cross33bfb0a2016-11-21 17:23:08 -0800131
Colin Cross6f080df2016-11-04 15:32:58 -0700132 // name of the modules (if any) that produces the host executable. Leave empty for
Colin Cross7d5136f2015-05-11 13:39:40 -0700133 // prebuilts or scripts that do not need a module to build them.
Colin Cross6f080df2016-11-04 15:32:58 -0700134 Tools []string
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700135
136 // Local file that is used as the tool
Colin Cross27b922f2019-03-04 22:35:41 -0800137 Tool_files []string `android:"path"`
Colin Cross5ed99c62016-11-22 12:55:55 -0800138
139 // List of directories to export generated headers from
140 Export_include_dirs []string
Colin Cross708c4242017-01-13 18:05:49 -0800141
142 // list of input files
Colin Cross27b922f2019-03-04 22:35:41 -0800143 Srcs []string `android:"path,arch_variant"`
Dan Willemseneefa0262018-11-17 14:01:18 -0800144
145 // input files to exclude
Colin Cross27b922f2019-03-04 22:35:41 -0800146 Exclude_srcs []string `android:"path,arch_variant"`
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400147}
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500148
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700149type Module struct {
Colin Cross635c3b02016-05-18 15:37:25 -0700150 android.ModuleBase
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800151 android.DefaultableModuleBase
Liz Kammerea6666f2021-02-17 10:17:28 -0500152 android.BazelModuleBase
Jiyong Parkfc752ca2019-06-12 13:27:29 +0900153 android.ApexModuleBase
Colin Crossd350ecd2015-04-28 13:25:36 -0700154
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700155 // For other packages to make their own genrules with extra
156 // properties
157 Extra interface{}
Colin Cross7228ecd2019-11-18 16:00:16 -0800158 android.ImageInterface
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700159
Colin Cross7d5136f2015-05-11 13:39:40 -0700160 properties generatorProperties
Colin Crossd350ecd2015-04-28 13:25:36 -0700161
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500162 // For the different tasks that genrule and gensrc generate. genrule will
163 // generate 1 task, and gensrc will generate 1 or more tasks based on the
164 // number of shards the input files are sharded into.
Jeff Gaston437d23c2017-11-08 12:38:00 -0800165 taskGenerator taskFunc
Colin Crossd350ecd2015-04-28 13:25:36 -0700166
Colin Cross1a527682019-09-23 15:55:30 -0700167 rule blueprint.Rule
168 rawCommands []string
Colin Crossd350ecd2015-04-28 13:25:36 -0700169
Colin Cross5ed99c62016-11-22 12:55:55 -0800170 exportedIncludeDirs android.Paths
Dan Willemsenb40aab62016-04-20 14:21:14 -0700171
Colin Cross635c3b02016-05-18 15:37:25 -0700172 outputFiles android.Paths
Dan Willemsen9da9d492018-02-21 18:28:18 -0800173 outputDeps android.Paths
Colin Crossa4ad2b02019-03-18 22:15:32 -0700174
175 subName string
Colin Cross1a527682019-09-23 15:55:30 -0700176 subDir string
bralee1fbf4402020-05-21 10:11:59 +0800177
178 // Collect the module directory for IDE info in java/jdeps.go.
179 modulePaths []string
Colin Crossd350ecd2015-04-28 13:25:36 -0700180}
181
Colin Cross1a527682019-09-23 15:55:30 -0700182type taskFunc func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask
Colin Crossd350ecd2015-04-28 13:25:36 -0700183
184type generateTask struct {
Colin Cross3ea4eb82020-11-24 13:07:27 -0800185 in android.Paths
186 out android.WritablePaths
187 depFile android.WritablePath
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500188 copyTo android.WritablePaths // For gensrcs to set on gensrcsMerge rule.
Colin Cross3ea4eb82020-11-24 13:07:27 -0800189 genDir android.WritablePath
190 extraTools android.Paths // dependencies on tools used by the generator
191
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500192 cmd string
193 // For gensrsc sharding.
Colin Cross3ea4eb82020-11-24 13:07:27 -0800194 shard int
195 shards int
Colin Crossd350ecd2015-04-28 13:25:36 -0700196}
197
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700198func (g *Module) GeneratedSourceFiles() android.Paths {
Colin Crossd350ecd2015-04-28 13:25:36 -0700199 return g.outputFiles
200}
201
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700202func (g *Module) Srcs() android.Paths {
Nan Zhange42777a2018-03-27 16:19:42 -0700203 return append(android.Paths{}, g.outputFiles...)
Colin Cross068e0fe2016-12-13 15:23:47 -0800204}
205
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700206func (g *Module) GeneratedHeaderDirs() android.Paths {
Colin Cross5ed99c62016-11-22 12:55:55 -0800207 return g.exportedIncludeDirs
Dan Willemsenb40aab62016-04-20 14:21:14 -0700208}
209
Dan Willemsen9da9d492018-02-21 18:28:18 -0800210func (g *Module) GeneratedDeps() android.Paths {
211 return g.outputDeps
212}
213
Jooyung Han8c7e3ed2021-06-28 17:35:58 +0900214func (g *Module) OutputFiles(tag string) (android.Paths, error) {
215 if tag == "" {
216 return append(android.Paths{}, g.outputFiles...), nil
217 }
218 // otherwise, tag should match one of outputs
219 for _, outputFile := range g.outputFiles {
220 if outputFile.Rel() == tag {
221 return android.Paths{outputFile}, nil
222 }
223 }
224 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
225}
226
227var _ android.SourceFileProducer = (*Module)(nil)
228var _ android.OutputFileProducer = (*Module)(nil)
229
Martin Stjernholm710ec3a2020-01-16 15:12:04 +0000230func toolDepsMutator(ctx android.BottomUpMutatorContext) {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700231 if g, ok := ctx.Module().(*Module); ok {
Colin Cross08f15ab2018-10-04 23:29:14 -0700232 for _, tool := range g.properties.Tools {
233 tag := hostToolDependencyTag{label: tool}
234 if m := android.SrcIsModule(tool); m != "" {
235 tool = m
236 }
Colin Cross0f7d2ef2019-10-16 11:03:10 -0700237 ctx.AddFarVariationDependencies(ctx.Config().BuildOSTarget.Variations(), tag, tool)
Colin Cross6362e272015-10-29 15:25:03 -0700238 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700239 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700240}
241
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400242// 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 +0000243func (c *Module) GenerateBazelBuildActions(ctx android.ModuleContext, label string) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400244 bazelCtx := ctx.Config().BazelContext
Chris Parsons944e7d02021-03-11 11:08:46 -0500245 filePaths, ok := bazelCtx.GetOutputFiles(label, ctx.Arch().ArchType)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400246 if ok {
247 var bazelOutputFiles android.Paths
Chris Parsonse59af4e2021-03-31 13:32:41 -0400248 exportIncludeDirs := map[string]bool{}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400249 for _, bazelOutputFile := range filePaths {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500250 bazelOutputFiles = append(bazelOutputFiles, android.PathForBazelOut(ctx, bazelOutputFile))
Chris Parsonse59af4e2021-03-31 13:32:41 -0400251 exportIncludeDirs[filepath.Dir(bazelOutputFile)] = true
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400252 }
253 c.outputFiles = bazelOutputFiles
254 c.outputDeps = bazelOutputFiles
Chris Parsonse59af4e2021-03-31 13:32:41 -0400255 for includePath, _ := range exportIncludeDirs {
256 c.exportedIncludeDirs = append(c.exportedIncludeDirs, android.PathForBazelOut(ctx, includePath))
257 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400258 }
259 return ok
260}
Colin Crossf1885962020-11-20 15:28:30 -0800261
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700262func (g *Module) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Colin Crossa4ad2b02019-03-18 22:15:32 -0700263 g.subName = ctx.ModuleSubDir()
264
bralee1fbf4402020-05-21 10:11:59 +0800265 // Collect the module directory for IDE info in java/jdeps.go.
266 g.modulePaths = append(g.modulePaths, ctx.ModuleDir())
267
Colin Cross5ed99c62016-11-22 12:55:55 -0800268 if len(g.properties.Export_include_dirs) > 0 {
269 for _, dir := range g.properties.Export_include_dirs {
270 g.exportedIncludeDirs = append(g.exportedIncludeDirs,
Colin Cross1a527682019-09-23 15:55:30 -0700271 android.PathForModuleGen(ctx, g.subDir, ctx.ModuleDir(), dir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800272 }
273 } else {
Colin Cross1a527682019-09-23 15:55:30 -0700274 g.exportedIncludeDirs = append(g.exportedIncludeDirs, android.PathForModuleGen(ctx, g.subDir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800275 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700276
Colin Crossd11cf622021-03-23 22:30:35 -0700277 locationLabels := map[string]location{}
Colin Cross08f15ab2018-10-04 23:29:14 -0700278 firstLabel := ""
279
Colin Crossd11cf622021-03-23 22:30:35 -0700280 addLocationLabel := func(label string, loc location) {
Colin Cross08f15ab2018-10-04 23:29:14 -0700281 if firstLabel == "" {
282 firstLabel = label
283 }
284 if _, exists := locationLabels[label]; !exists {
Colin Crossd11cf622021-03-23 22:30:35 -0700285 locationLabels[label] = loc
Colin Cross08f15ab2018-10-04 23:29:14 -0700286 } else {
287 ctx.ModuleErrorf("multiple labels for %q, %q and %q",
Colin Crossd11cf622021-03-23 22:30:35 -0700288 label, locationLabels[label], loc)
Colin Cross08f15ab2018-10-04 23:29:14 -0700289 }
290 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700291
Colin Crossba9e4032020-11-24 16:32:22 -0800292 var tools android.Paths
293 var packagedTools []android.PackagingSpec
Colin Cross6f080df2016-11-04 15:32:58 -0700294 if len(g.properties.Tools) > 0 {
Colin Crossba71a3f2019-03-18 12:12:48 -0700295 seenTools := make(map[string]bool)
296
Colin Cross35143d02017-11-16 00:11:20 -0800297 ctx.VisitDirectDepsBlueprint(func(module blueprint.Module) {
Colin Cross08f15ab2018-10-04 23:29:14 -0700298 switch tag := ctx.OtherModuleDependencyTag(module).(type) {
299 case hostToolDependencyTag:
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700300 tool := ctx.OtherModuleName(module)
301
Colin Crossba9e4032020-11-24 16:32:22 -0800302 switch t := module.(type) {
303 case android.HostToolProvider:
304 // A HostToolProvider provides the path to a tool, which will be copied
305 // into the sandbox.
Colin Cross35143d02017-11-16 00:11:20 -0800306 if !t.(android.Module).Enabled() {
Colin Cross6510f912017-11-29 00:27:14 -0800307 if ctx.Config().AllowMissingDependencies() {
Colin Cross35143d02017-11-16 00:11:20 -0800308 ctx.AddMissingDependencies([]string{tool})
309 } else {
310 ctx.ModuleErrorf("depends on disabled module %q", tool)
311 }
Colin Crossba9e4032020-11-24 16:32:22 -0800312 return
Colin Cross35143d02017-11-16 00:11:20 -0800313 }
Colin Crossba9e4032020-11-24 16:32:22 -0800314 path := t.HostToolPath()
315 if !path.Valid() {
316 ctx.ModuleErrorf("host tool %q missing output file", tool)
317 return
318 }
319 if specs := t.TransitivePackagingSpecs(); specs != nil {
320 // If the HostToolProvider has PackgingSpecs, which are definitions of the
321 // required relative locations of the tool and its dependencies, use those
322 // instead. They will be copied to those relative locations in the sbox
323 // sandbox.
324 packagedTools = append(packagedTools, specs...)
325 // Assume that the first PackagingSpec of the module is the tool.
Colin Crossd11cf622021-03-23 22:30:35 -0700326 addLocationLabel(tag.label, packagedToolLocation{specs[0]})
Colin Crossba9e4032020-11-24 16:32:22 -0800327 } else {
328 tools = append(tools, path.Path())
Colin Crossd11cf622021-03-23 22:30:35 -0700329 addLocationLabel(tag.label, toolLocation{android.Paths{path.Path()}})
Colin Crossba9e4032020-11-24 16:32:22 -0800330 }
331 case bootstrap.GoBinaryTool:
332 // A GoBinaryTool provides the install path to a tool, which will be copied.
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700333 if s, err := filepath.Rel(android.PathForOutput(ctx).String(), t.InstallPath()); err == nil {
Colin Crossba9e4032020-11-24 16:32:22 -0800334 toolPath := android.PathForOutput(ctx, s)
335 tools = append(tools, toolPath)
Colin Crossd11cf622021-03-23 22:30:35 -0700336 addLocationLabel(tag.label, toolLocation{android.Paths{toolPath}})
Colin Cross6f080df2016-11-04 15:32:58 -0700337 } else {
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700338 ctx.ModuleErrorf("cannot find path for %q: %v", tool, err)
Colin Crossba9e4032020-11-24 16:32:22 -0800339 return
Colin Cross6f080df2016-11-04 15:32:58 -0700340 }
Colin Crossba9e4032020-11-24 16:32:22 -0800341 default:
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700342 ctx.ModuleErrorf("%q is not a host tool provider", tool)
Colin Crossba9e4032020-11-24 16:32:22 -0800343 return
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700344 }
345
Colin Crossba9e4032020-11-24 16:32:22 -0800346 seenTools[tag.label] = true
Colin Crossd350ecd2015-04-28 13:25:36 -0700347 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700348 })
Colin Crossba71a3f2019-03-18 12:12:48 -0700349
350 // If AllowMissingDependencies is enabled, the build will not have stopped when
351 // AddFarVariationDependencies was called on a missing tool, which will result in nonsensical
Liz Kammer20ebfb42020-07-28 11:32:07 -0700352 // "cmd: unknown location label ..." errors later. Add a placeholder file to the local label.
353 // The command that uses this placeholder file will never be executed because the rule will be
354 // replaced with an android.Error rule reporting the missing dependencies.
Colin Crossba71a3f2019-03-18 12:12:48 -0700355 if ctx.Config().AllowMissingDependencies() {
356 for _, tool := range g.properties.Tools {
357 if !seenTools[tool] {
Colin Crossd11cf622021-03-23 22:30:35 -0700358 addLocationLabel(tool, errorLocation{"***missing tool " + tool + "***"})
Colin Crossba71a3f2019-03-18 12:12:48 -0700359 }
360 }
361 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700362 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700363
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700364 if ctx.Failed() {
365 return
366 }
367
Colin Cross08f15ab2018-10-04 23:29:14 -0700368 for _, toolFile := range g.properties.Tool_files {
Colin Cross8a497952019-03-05 22:25:09 -0800369 paths := android.PathsForModuleSrc(ctx, []string{toolFile})
Colin Crossba9e4032020-11-24 16:32:22 -0800370 tools = append(tools, paths...)
Colin Crossd11cf622021-03-23 22:30:35 -0700371 addLocationLabel(toolFile, toolLocation{paths})
Colin Cross08f15ab2018-10-04 23:29:14 -0700372 }
373
374 var srcFiles android.Paths
375 for _, in := range g.properties.Srcs {
Colin Crossba71a3f2019-03-18 12:12:48 -0700376 paths, missingDeps := android.PathsAndMissingDepsForModuleSrcExcludes(ctx, []string{in}, g.properties.Exclude_srcs)
377 if len(missingDeps) > 0 {
378 if !ctx.Config().AllowMissingDependencies() {
379 panic(fmt.Errorf("should never get here, the missing dependencies %q should have been reported in DepsMutator",
380 missingDeps))
381 }
382
383 // If AllowMissingDependencies is enabled, the build will not have stopped when
384 // the dependency was added on a missing SourceFileProducer module, which will result in nonsensical
Liz Kammer20ebfb42020-07-28 11:32:07 -0700385 // "cmd: label ":..." has no files" errors later. Add a placeholder file to the local label.
386 // The command that uses this placeholder file will never be executed because the rule will be
387 // replaced with an android.Error rule reporting the missing dependencies.
Colin Crossba71a3f2019-03-18 12:12:48 -0700388 ctx.AddMissingDependencies(missingDeps)
Colin Crossd11cf622021-03-23 22:30:35 -0700389 addLocationLabel(in, errorLocation{"***missing srcs " + in + "***"})
Colin Crossba71a3f2019-03-18 12:12:48 -0700390 } else {
391 srcFiles = append(srcFiles, paths...)
Colin Crossd11cf622021-03-23 22:30:35 -0700392 addLocationLabel(in, inputLocation{paths})
Colin Crossba71a3f2019-03-18 12:12:48 -0700393 }
Colin Cross08f15ab2018-10-04 23:29:14 -0700394 }
395
Colin Cross1a527682019-09-23 15:55:30 -0700396 var copyFrom android.Paths
397 var outputFiles android.WritablePaths
398 var zipArgs strings.Builder
Colin Cross08f15ab2018-10-04 23:29:14 -0700399
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500400 // Generate tasks, either from genrule or gensrcs.
Colin Cross1a527682019-09-23 15:55:30 -0700401 for _, task := range g.taskGenerator(ctx, String(g.properties.Cmd), srcFiles) {
Colin Cross3d680512020-11-13 16:23:53 -0800402 if len(task.out) == 0 {
403 ctx.ModuleErrorf("must have at least one output file")
404 return
Colin Cross85a2e892018-07-09 09:45:06 -0700405 }
406
Colin Crossf1a035e2020-11-16 17:32:30 -0800407 // Pick a unique path outside the task.genDir for the sbox manifest textproto,
408 // a unique rule name, and the user-visible description.
409 manifestName := "genrule.sbox.textproto"
410 desc := "generate"
411 name := "generator"
412 if task.shards > 0 {
413 manifestName = "genrule_" + strconv.Itoa(task.shard) + ".sbox.textproto"
414 desc += " " + strconv.Itoa(task.shard)
415 name += strconv.Itoa(task.shard)
416 } else if len(task.out) == 1 {
417 desc += " " + task.out[0].Base()
418 }
419
420 manifestPath := android.PathForModuleOut(ctx, manifestName)
421
422 // Use a RuleBuilder to create a rule that runs the command inside an sbox sandbox.
Colin Crossba9e4032020-11-24 16:32:22 -0800423 rule := android.NewRuleBuilder(pctx, ctx).Sbox(task.genDir, manifestPath).SandboxTools()
Colin Crossf1a035e2020-11-16 17:32:30 -0800424 cmd := rule.Command()
425
Colin Cross3d680512020-11-13 16:23:53 -0800426 for _, out := range task.out {
Colin Crossd11cf622021-03-23 22:30:35 -0700427 addLocationLabel(out.Rel(), outputLocation{out})
Colin Cross3d680512020-11-13 16:23:53 -0800428 }
429
Colin Cross1a527682019-09-23 15:55:30 -0700430 referencedDepfile := false
431
Colin Cross3d680512020-11-13 16:23:53 -0800432 rawCommand, err := android.Expand(task.cmd, func(name string) (string, error) {
Colin Cross1a527682019-09-23 15:55:30 -0700433 // report the error directly without returning an error to android.Expand to catch multiple errors in a
434 // single run
Colin Cross3d680512020-11-13 16:23:53 -0800435 reportError := func(fmt string, args ...interface{}) (string, error) {
Colin Cross1a527682019-09-23 15:55:30 -0700436 ctx.PropertyErrorf("cmd", fmt, args...)
Colin Cross3d680512020-11-13 16:23:53 -0800437 return "SOONG_ERROR", nil
Colin Cross6f080df2016-11-04 15:32:58 -0700438 }
Colin Cross1a527682019-09-23 15:55:30 -0700439
440 switch name {
441 case "location":
442 if len(g.properties.Tools) == 0 && len(g.properties.Tool_files) == 0 {
443 return reportError("at least one `tools` or `tool_files` is required if $(location) is used")
Colin Cross6f080df2016-11-04 15:32:58 -0700444 }
Colin Crossd11cf622021-03-23 22:30:35 -0700445 loc := locationLabels[firstLabel]
446 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700447 if len(paths) == 0 {
448 return reportError("default label %q has no files", firstLabel)
449 } else if len(paths) > 1 {
450 return reportError("default label %q has multiple files, use $(locations %s) to reference it",
451 firstLabel, firstLabel)
Colin Cross08f15ab2018-10-04 23:29:14 -0700452 }
Colin Crossd11cf622021-03-23 22:30:35 -0700453 return paths[0], nil
Colin Cross1a527682019-09-23 15:55:30 -0700454 case "in":
Colin Crossd11cf622021-03-23 22:30:35 -0700455 return strings.Join(cmd.PathsForInputs(srcFiles), " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700456 case "out":
Colin Cross3d680512020-11-13 16:23:53 -0800457 var sandboxOuts []string
458 for _, out := range task.out {
Colin Crossf1a035e2020-11-16 17:32:30 -0800459 sandboxOuts = append(sandboxOuts, cmd.PathForOutput(out))
Colin Cross3d680512020-11-13 16:23:53 -0800460 }
461 return strings.Join(sandboxOuts, " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700462 case "depfile":
463 referencedDepfile = true
464 if !Bool(g.properties.Depfile) {
465 return reportError("$(depfile) used without depfile property")
466 }
Colin Cross3d680512020-11-13 16:23:53 -0800467 return "__SBOX_DEPFILE__", nil
Colin Cross1a527682019-09-23 15:55:30 -0700468 case "genDir":
Colin Crossf1a035e2020-11-16 17:32:30 -0800469 return cmd.PathForOutput(task.genDir), nil
Colin Cross1a527682019-09-23 15:55:30 -0700470 default:
471 if strings.HasPrefix(name, "location ") {
472 label := strings.TrimSpace(strings.TrimPrefix(name, "location "))
Colin Crossd11cf622021-03-23 22:30:35 -0700473 if loc, ok := locationLabels[label]; ok {
474 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700475 if len(paths) == 0 {
476 return reportError("label %q has no files", label)
477 } else if len(paths) > 1 {
478 return reportError("label %q has multiple files, use $(locations %s) to reference it",
479 label, label)
480 }
Colin Cross3d680512020-11-13 16:23:53 -0800481 return paths[0], nil
Colin Cross1a527682019-09-23 15:55:30 -0700482 } else {
483 return reportError("unknown location label %q", label)
484 }
485 } else if strings.HasPrefix(name, "locations ") {
486 label := strings.TrimSpace(strings.TrimPrefix(name, "locations "))
Colin Crossd11cf622021-03-23 22:30:35 -0700487 if loc, ok := locationLabels[label]; ok {
488 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700489 if len(paths) == 0 {
490 return reportError("label %q has no files", label)
491 }
Colin Cross3d680512020-11-13 16:23:53 -0800492 return strings.Join(paths, " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700493 } else {
494 return reportError("unknown locations label %q", label)
495 }
496 } else {
497 return reportError("unknown variable '$(%s)'", name)
498 }
Colin Cross6f080df2016-11-04 15:32:58 -0700499 }
Colin Cross1a527682019-09-23 15:55:30 -0700500 })
501
502 if err != nil {
503 ctx.PropertyErrorf("cmd", "%s", err.Error())
504 return
Colin Cross6f080df2016-11-04 15:32:58 -0700505 }
Colin Cross6f080df2016-11-04 15:32:58 -0700506
Colin Cross1a527682019-09-23 15:55:30 -0700507 if Bool(g.properties.Depfile) && !referencedDepfile {
508 ctx.PropertyErrorf("cmd", "specified depfile=true but did not include a reference to '${depfile}' in cmd")
509 return
510 }
Colin Cross1a527682019-09-23 15:55:30 -0700511 g.rawCommands = append(g.rawCommands, rawCommand)
Bill Peckhamc087be12020-02-13 15:55:10 -0800512
Colin Cross3d680512020-11-13 16:23:53 -0800513 cmd.Text(rawCommand)
514 cmd.ImplicitOutputs(task.out)
515 cmd.Implicits(task.in)
Colin Crossba9e4032020-11-24 16:32:22 -0800516 cmd.ImplicitTools(tools)
517 cmd.ImplicitTools(task.extraTools)
518 cmd.ImplicitPackagedTools(packagedTools)
Colin Cross3d680512020-11-13 16:23:53 -0800519 if Bool(g.properties.Depfile) {
520 cmd.ImplicitDepFile(task.depFile)
521 }
522
523 // Create the rule to run the genrule command inside sbox.
Colin Crossf1a035e2020-11-16 17:32:30 -0800524 rule.Build(name, desc)
Colin Cross1a527682019-09-23 15:55:30 -0700525
526 if len(task.copyTo) > 0 {
Colin Cross3d680512020-11-13 16:23:53 -0800527 // If copyTo is set, multiple shards need to be copied into a single directory.
528 // task.out contains the per-shard paths, and copyTo contains the corresponding
529 // final path. The files need to be copied into the final directory by a
530 // single rule so it can remove the directory before it starts to ensure no
531 // old files remain. zipsync already does this, so build up zipArgs that
532 // zip all the per-shard directories into a single zip.
Colin Cross1a527682019-09-23 15:55:30 -0700533 outputFiles = append(outputFiles, task.copyTo...)
534 copyFrom = append(copyFrom, task.out.Paths()...)
535 zipArgs.WriteString(" -C " + task.genDir.String())
536 zipArgs.WriteString(android.JoinWithPrefix(task.out.Strings(), " -f "))
537 } else {
538 outputFiles = append(outputFiles, task.out...)
539 }
Colin Cross6f080df2016-11-04 15:32:58 -0700540 }
541
Colin Cross1a527682019-09-23 15:55:30 -0700542 if len(copyFrom) > 0 {
Colin Cross3d680512020-11-13 16:23:53 -0800543 // Create a rule that zips all the per-shard directories into a single zip and then
544 // uses zipsync to unzip it into the final directory.
Colin Cross1a527682019-09-23 15:55:30 -0700545 ctx.Build(pctx, android.BuildParams{
Colin Crossf1885962020-11-20 15:28:30 -0800546 Rule: gensrcsMerge,
547 Implicits: copyFrom,
548 Outputs: outputFiles,
549 Description: "merge shards",
Colin Cross1a527682019-09-23 15:55:30 -0700550 Args: map[string]string{
551 "zipArgs": zipArgs.String(),
552 "tmpZip": android.PathForModuleGen(ctx, g.subDir+".zip").String(),
553 "genDir": android.PathForModuleGen(ctx, g.subDir).String(),
554 },
555 })
Colin Cross85a2e892018-07-09 09:45:06 -0700556 }
557
Colin Cross1a527682019-09-23 15:55:30 -0700558 g.outputFiles = outputFiles.Paths()
Jeff Gastonefc1b412017-03-29 17:29:06 -0700559
Liz Kammerbdc60992021-02-24 16:55:11 -0500560 bazelModuleLabel := g.GetBazelLabel(ctx, g)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400561 bazelActionsUsed := false
Chris Parsonsbab4d7e2021-04-15 17:27:08 -0400562 if g.MixedBuildsEnabled(ctx) {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux0d990452021-08-11 16:46:13 +0000563 bazelActionsUsed = g.GenerateBazelBuildActions(ctx, bazelModuleLabel)
Jeff Gaston02a684b2017-10-27 14:59:27 -0700564 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400565 if !bazelActionsUsed {
566 // For <= 6 outputs, just embed those directly in the users. Right now, that covers >90% of
567 // the genrules on AOSP. That will make things simpler to look at the graph in the common
568 // case. For larger sets of outputs, inject a phony target in between to limit ninja file
569 // growth.
570 if len(g.outputFiles) <= 6 {
571 g.outputDeps = g.outputFiles
572 } else {
573 phonyFile := android.PathForModuleGen(ctx, "genrule-phony")
574 ctx.Build(pctx, android.BuildParams{
575 Rule: blueprint.Phony,
576 Output: phonyFile,
577 Inputs: g.outputFiles,
578 })
579 g.outputDeps = android.Paths{phonyFile}
580 }
581 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700582}
Colin Crossd350ecd2015-04-28 13:25:36 -0700583
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700584// Collect information for opening IDE project files in java/jdeps.go.
585func (g *Module) IDEInfo(dpInfo *android.IdeInfo) {
586 dpInfo.Srcs = append(dpInfo.Srcs, g.Srcs().Strings()...)
587 for _, src := range g.properties.Srcs {
588 if strings.HasPrefix(src, ":") {
589 src = strings.Trim(src, ":")
590 dpInfo.Deps = append(dpInfo.Deps, src)
591 }
592 }
bralee1fbf4402020-05-21 10:11:59 +0800593 dpInfo.Paths = append(dpInfo.Paths, g.modulePaths...)
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700594}
595
Colin Crossa4ad2b02019-03-18 22:15:32 -0700596func (g *Module) AndroidMk() android.AndroidMkData {
597 return android.AndroidMkData{
Anton Hansson72f18492020-10-30 16:34:45 +0000598 Class: "ETC",
Colin Crossa4ad2b02019-03-18 22:15:32 -0700599 OutputFile: android.OptionalPathForPath(g.outputFiles[0]),
600 SubName: g.subName,
601 Extra: []android.AndroidMkExtraFunc{
602 func(w io.Writer, outputFile android.Path) {
Anton Hansson72f18492020-10-30 16:34:45 +0000603 fmt.Fprintln(w, "LOCAL_UNINSTALLABLE_MODULE := true")
Colin Crossa4ad2b02019-03-18 22:15:32 -0700604 },
605 },
606 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
607 android.WriteAndroidMkData(w, data)
608 if data.SubName != "" {
609 fmt.Fprintln(w, ".PHONY:", name)
610 fmt.Fprintln(w, name, ":", name+g.subName)
611 }
612 },
613 }
614}
615
Jiyong Park45bf82e2020-12-15 22:29:02 +0900616var _ android.ApexModule = (*Module)(nil)
617
618// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -0700619func (g *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
620 sdkVersion android.ApiLevel) error {
Jooyung Han749dc692020-04-15 11:03:39 +0900621 // Because generated outputs are checked by client modules(e.g. cc_library, ...)
622 // we can safely ignore the check here.
623 return nil
624}
625
Jeff Gaston437d23c2017-11-08 12:38:00 -0800626func generatorFactory(taskGenerator taskFunc, props ...interface{}) *Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700627 module := &Module{
Jeff Gaston437d23c2017-11-08 12:38:00 -0800628 taskGenerator: taskGenerator,
Colin Crossd350ecd2015-04-28 13:25:36 -0700629 }
630
Colin Cross36242852017-06-23 15:06:31 -0700631 module.AddProperties(props...)
632 module.AddProperties(&module.properties)
Colin Crossd350ecd2015-04-28 13:25:36 -0700633
Colin Cross7228ecd2019-11-18 16:00:16 -0800634 module.ImageInterface = noopImageInterface{}
635
Colin Cross36242852017-06-23 15:06:31 -0700636 return module
Colin Crossd350ecd2015-04-28 13:25:36 -0700637}
638
Colin Cross7228ecd2019-11-18 16:00:16 -0800639type noopImageInterface struct{}
640
641func (x noopImageInterface) ImageMutatorBegin(android.BaseModuleContext) {}
642func (x noopImageInterface) CoreVariantNeeded(android.BaseModuleContext) bool { return false }
Yifan Hong1b3348d2020-01-21 15:53:22 -0800643func (x noopImageInterface) RamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700644func (x noopImageInterface) VendorRamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Inseob Kim08758f02021-04-08 21:13:22 +0900645func (x noopImageInterface) DebugRamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Colin Cross7228ecd2019-11-18 16:00:16 -0800646func (x noopImageInterface) RecoveryVariantNeeded(android.BaseModuleContext) bool { return false }
647func (x noopImageInterface) ExtraImageVariations(ctx android.BaseModuleContext) []string { return nil }
648func (x noopImageInterface) SetImageVariation(ctx android.BaseModuleContext, variation string, module android.Module) {
649}
650
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700651func NewGenSrcs() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700652 properties := &genSrcsProperties{}
653
Colin Crossf1885962020-11-20 15:28:30 -0800654 // finalSubDir is the name of the subdirectory that output files will be generated into.
655 // It is used so that per-shard directories can be placed alongside it an then finally
656 // merged into it.
657 const finalSubDir = "gensrcs"
658
Colin Cross1a527682019-09-23 15:55:30 -0700659 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Colin Cross1a527682019-09-23 15:55:30 -0700660 shardSize := defaultShardSize
661 if s := properties.Shard_size; s != nil {
662 shardSize = int(*s)
663 }
Jeff Gaston437d23c2017-11-08 12:38:00 -0800664
Colin Crossf1885962020-11-20 15:28:30 -0800665 // gensrcs rules can easily hit command line limits by repeating the command for
666 // every input file. Shard the input files into groups.
Colin Cross1a527682019-09-23 15:55:30 -0700667 shards := android.ShardPaths(srcFiles, shardSize)
668 var generateTasks []generateTask
Colin Crossbaccf5b2018-02-21 14:07:48 -0800669
Colin Cross1a527682019-09-23 15:55:30 -0700670 for i, shard := range shards {
671 var commands []string
672 var outFiles android.WritablePaths
Colin Cross3ea4eb82020-11-24 13:07:27 -0800673 var commandDepFiles []string
Colin Cross1a527682019-09-23 15:55:30 -0700674 var copyTo android.WritablePaths
Colin Cross1a527682019-09-23 15:55:30 -0700675
Colin Crossf1885962020-11-20 15:28:30 -0800676 // When sharding is enabled (i.e. len(shards) > 1), the sbox rules for each
677 // shard will be write to their own directories and then be merged together
678 // into finalSubDir. If sharding is not enabled (i.e. len(shards) == 1),
679 // the sbox rule will write directly to finalSubDir.
680 genSubDir := finalSubDir
Colin Cross1a527682019-09-23 15:55:30 -0700681 if len(shards) > 1 {
Colin Crossf1885962020-11-20 15:28:30 -0800682 genSubDir = strconv.Itoa(i)
Jeff Gaston437d23c2017-11-08 12:38:00 -0800683 }
684
Colin Crossf1885962020-11-20 15:28:30 -0800685 genDir := android.PathForModuleGen(ctx, genSubDir)
Colin Crossf1a035e2020-11-16 17:32:30 -0800686 // TODO(ccross): this RuleBuilder is a hack to be able to call
687 // rule.Command().PathForOutput. Replace this with passing the rule into the
688 // generator.
Colin Crossba9e4032020-11-24 16:32:22 -0800689 rule := android.NewRuleBuilder(pctx, ctx).Sbox(genDir, nil).SandboxTools()
Jeff Gaston437d23c2017-11-08 12:38:00 -0800690
Colin Cross3ea4eb82020-11-24 13:07:27 -0800691 for _, in := range shard {
Colin Crossf1885962020-11-20 15:28:30 -0800692 outFile := android.GenPathWithExt(ctx, finalSubDir, in, String(properties.Output_extension))
693
694 // If sharding is enabled, then outFile is the path to the output file in
695 // the shard directory, and copyTo is the path to the output file in the
696 // final directory.
Colin Cross1a527682019-09-23 15:55:30 -0700697 if len(shards) > 1 {
Colin Crossf1885962020-11-20 15:28:30 -0800698 shardFile := android.GenPathWithExt(ctx, genSubDir, in, String(properties.Output_extension))
Colin Cross1a527682019-09-23 15:55:30 -0700699 copyTo = append(copyTo, outFile)
700 outFile = shardFile
701 }
702
703 outFiles = append(outFiles, outFile)
Colin Cross1a527682019-09-23 15:55:30 -0700704
Colin Crossf1885962020-11-20 15:28:30 -0800705 // pre-expand the command line to replace $in and $out with references to
706 // a single input and output file.
Colin Cross1a527682019-09-23 15:55:30 -0700707 command, err := android.Expand(rawCommand, func(name string) (string, error) {
708 switch name {
709 case "in":
710 return in.String(), nil
711 case "out":
Colin Crossf1a035e2020-11-16 17:32:30 -0800712 return rule.Command().PathForOutput(outFile), nil
Colin Cross3ea4eb82020-11-24 13:07:27 -0800713 case "depfile":
714 // Generate a depfile for each output file. Store the list for
715 // later in order to combine them all into a single depfile.
Colin Crossf1a035e2020-11-16 17:32:30 -0800716 depFile := rule.Command().PathForOutput(outFile.ReplaceExtension(ctx, "d"))
Colin Cross3ea4eb82020-11-24 13:07:27 -0800717 commandDepFiles = append(commandDepFiles, depFile)
718 return depFile, nil
Colin Cross1a527682019-09-23 15:55:30 -0700719 default:
720 return "$(" + name + ")", nil
721 }
722 })
723 if err != nil {
724 ctx.PropertyErrorf("cmd", err.Error())
725 }
726
727 // escape the command in case for example it contains '#', an odd number of '"', etc
728 command = fmt.Sprintf("bash -c %v", proptools.ShellEscape(command))
729 commands = append(commands, command)
730 }
731 fullCommand := strings.Join(commands, " && ")
732
Colin Cross3ea4eb82020-11-24 13:07:27 -0800733 var outputDepfile android.WritablePath
734 var extraTools android.Paths
735 if len(commandDepFiles) > 0 {
736 // Each command wrote to a depfile, but ninja can only handle one
737 // depfile per rule. Use the dep_fixer tool at the end of the
738 // command to combine all the depfiles into a single output depfile.
739 outputDepfile = android.PathForModuleGen(ctx, genSubDir, "gensrcs.d")
740 depFixerTool := ctx.Config().HostToolPath(ctx, "dep_fixer")
741 fullCommand += fmt.Sprintf(" && %s -o $(depfile) %s",
Colin Crossd11cf622021-03-23 22:30:35 -0700742 rule.Command().PathForTool(depFixerTool),
Colin Crossba9e4032020-11-24 16:32:22 -0800743 strings.Join(commandDepFiles, " "))
Colin Cross3ea4eb82020-11-24 13:07:27 -0800744 extraTools = append(extraTools, depFixerTool)
745 }
746
Colin Cross1a527682019-09-23 15:55:30 -0700747 generateTasks = append(generateTasks, generateTask{
Colin Cross3ea4eb82020-11-24 13:07:27 -0800748 in: shard,
749 out: outFiles,
750 depFile: outputDepfile,
751 copyTo: copyTo,
752 genDir: genDir,
753 cmd: fullCommand,
754 shard: i,
755 shards: len(shards),
756 extraTools: extraTools,
Colin Cross1a527682019-09-23 15:55:30 -0700757 })
Jeff Gaston437d23c2017-11-08 12:38:00 -0800758 }
Colin Cross1a527682019-09-23 15:55:30 -0700759
760 return generateTasks
Colin Crossd350ecd2015-04-28 13:25:36 -0700761 }
762
Colin Cross1a527682019-09-23 15:55:30 -0700763 g := generatorFactory(taskGenerator, properties)
Colin Crossf1885962020-11-20 15:28:30 -0800764 g.subDir = finalSubDir
Colin Cross1a527682019-09-23 15:55:30 -0700765 return g
Colin Crossd350ecd2015-04-28 13:25:36 -0700766}
767
Colin Cross54190b32017-10-09 15:34:10 -0700768func GenSrcsFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700769 m := NewGenSrcs()
770 android.InitAndroidModule(m)
771 return m
772}
773
Colin Crossd350ecd2015-04-28 13:25:36 -0700774type genSrcsProperties struct {
Colin Cross7d5136f2015-05-11 13:39:40 -0700775 // extension that will be substituted for each output file
Nan Zhanga5e7cb42017-11-09 22:42:32 -0800776 Output_extension *string
Colin Cross1a527682019-09-23 15:55:30 -0700777
778 // maximum number of files that will be passed on a single command line.
779 Shard_size *int64
Colin Cross5049f022015-03-18 13:28:46 -0700780}
781
Evgenii Stepanovf47c90d2020-12-02 18:55:09 -0800782const defaultShardSize = 50
Colin Cross1a527682019-09-23 15:55:30 -0700783
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700784func NewGenRule() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700785 properties := &genRuleProperties{}
Colin Cross5049f022015-03-18 13:28:46 -0700786
Colin Cross1a527682019-09-23 15:55:30 -0700787 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700788 outs := make(android.WritablePaths, len(properties.Out))
Colin Cross3d680512020-11-13 16:23:53 -0800789 var depFile android.WritablePath
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700790 for i, out := range properties.Out {
Colin Cross3d680512020-11-13 16:23:53 -0800791 outPath := android.PathForModuleGen(ctx, out)
792 if i == 0 {
793 depFile = outPath.ReplaceExtension(ctx, "d")
794 }
795 outs[i] = outPath
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700796 }
Colin Cross1a527682019-09-23 15:55:30 -0700797 return []generateTask{{
Colin Cross3d680512020-11-13 16:23:53 -0800798 in: srcFiles,
799 out: outs,
800 depFile: depFile,
801 genDir: android.PathForModuleGen(ctx),
802 cmd: rawCommand,
Colin Cross1a527682019-09-23 15:55:30 -0700803 }}
Colin Cross5049f022015-03-18 13:28:46 -0700804 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700805
Jeff Gaston437d23c2017-11-08 12:38:00 -0800806 return generatorFactory(taskGenerator, properties)
Colin Cross5049f022015-03-18 13:28:46 -0700807}
808
Colin Cross54190b32017-10-09 15:34:10 -0700809func GenRuleFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700810 m := NewGenRule()
811 android.InitAndroidModule(m)
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800812 android.InitDefaultableModule(m)
Liz Kammerea6666f2021-02-17 10:17:28 -0500813 android.InitBazelModule(m)
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700814 return m
815}
816
Colin Crossd350ecd2015-04-28 13:25:36 -0700817type genRuleProperties struct {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700818 // names of the output files that will be generated
Colin Crossef354482018-10-23 11:27:50 -0700819 Out []string `android:"arch_variant"`
Colin Cross5049f022015-03-18 13:28:46 -0700820}
Nan Zhangea568a42017-11-08 21:20:04 -0800821
Jingwen Chen316e07c2020-12-14 09:09:52 -0500822type bazelGenruleAttributes struct {
Jingwen Chen07027912021-03-15 06:02:43 -0400823 Srcs bazel.LabelListAttribute
Jingwen Chen316e07c2020-12-14 09:09:52 -0500824 Outs []string
Jingwen Chen07027912021-03-15 06:02:43 -0400825 Tools bazel.LabelListAttribute
Jingwen Chen316e07c2020-12-14 09:09:52 -0500826 Cmd string
827}
828
829type bazelGenrule struct {
830 android.BazelTargetModuleBase
831 bazelGenruleAttributes
832}
833
834func BazelGenruleFactory() android.Module {
835 module := &bazelGenrule{}
836 module.AddProperties(&module.bazelGenruleAttributes)
837 android.InitBazelTargetModule(module)
838 return module
839}
840
Jingwen Chena42d6412021-01-26 21:57:27 -0500841func GenruleBp2Build(ctx android.TopDownMutatorContext) {
Liz Kammer356f7d42021-01-26 09:18:53 -0500842 m, ok := ctx.Module().(*Module)
Jingwen Chen12b4c272021-03-10 02:05:59 -0500843 if !ok || !m.ConvertWithBp2build(ctx) {
Liz Kammer356f7d42021-01-26 09:18:53 -0500844 return
Jingwen Chen316e07c2020-12-14 09:09:52 -0500845 }
Jingwen Chen1fd14692021-02-05 03:01:50 -0500846
Jingwen Chen66480452021-03-18 03:41:55 -0400847 if ctx.ModuleType() != "genrule" {
848 // Not a regular genrule. Could be a cc_genrule or java_genrule.
849 return
850 }
851
Liz Kammer356f7d42021-01-26 09:18:53 -0500852 // Bazel only has the "tools" attribute.
Jingwen Chen07027912021-03-15 06:02:43 -0400853 tools_prop := android.BazelLabelForModuleDeps(ctx, m.properties.Tools)
854 tool_files_prop := android.BazelLabelForModuleSrc(ctx, m.properties.Tool_files)
855 tools_prop.Append(tool_files_prop)
Liz Kammer356f7d42021-01-26 09:18:53 -0500856
Jingwen Chen07027912021-03-15 06:02:43 -0400857 tools := bazel.MakeLabelListAttribute(tools_prop)
858 srcs := bazel.MakeLabelListAttribute(android.BazelLabelForModuleSrc(ctx, m.properties.Srcs))
Liz Kammer356f7d42021-01-26 09:18:53 -0500859
860 var allReplacements bazel.LabelList
Jingwen Chen07027912021-03-15 06:02:43 -0400861 allReplacements.Append(tools.Value)
862 allReplacements.Append(srcs.Value)
Liz Kammer356f7d42021-01-26 09:18:53 -0500863
864 // Replace in and out variables with $< and $@
865 var cmd string
866 if m.properties.Cmd != nil {
867 cmd = strings.Replace(*m.properties.Cmd, "$(in)", "$(SRCS)", -1)
868 cmd = strings.Replace(cmd, "$(out)", "$(OUTS)", -1)
869 cmd = strings.Replace(cmd, "$(genDir)", "$(GENDIR)", -1)
Jingwen Chen07027912021-03-15 06:02:43 -0400870 if len(tools.Value.Includes) > 0 {
871 cmd = strings.Replace(cmd, "$(location)", fmt.Sprintf("$(location %s)", tools.Value.Includes[0].Label), -1)
872 cmd = strings.Replace(cmd, "$(locations)", fmt.Sprintf("$(locations %s)", tools.Value.Includes[0].Label), -1)
Liz Kammer356f7d42021-01-26 09:18:53 -0500873 }
874 for _, l := range allReplacements.Includes {
Jingwen Chen38e62642021-04-19 05:00:15 +0000875 bpLoc := fmt.Sprintf("$(location %s)", l.OriginalModuleName)
876 bpLocs := fmt.Sprintf("$(locations %s)", l.OriginalModuleName)
Liz Kammer356f7d42021-01-26 09:18:53 -0500877 bazelLoc := fmt.Sprintf("$(location %s)", l.Label)
878 bazelLocs := fmt.Sprintf("$(locations %s)", l.Label)
879 cmd = strings.Replace(cmd, bpLoc, bazelLoc, -1)
880 cmd = strings.Replace(cmd, bpLocs, bazelLocs, -1)
881 }
882 }
883
884 // The Out prop is not in an immediately accessible field
885 // in the Module struct, so use GetProperties and cast it
886 // to the known struct prop.
887 var outs []string
888 for _, propIntf := range m.GetProperties() {
889 if props, ok := propIntf.(*genRuleProperties); ok {
890 outs = props.Out
891 break
892 }
893 }
894
Jingwen Chen1fd14692021-02-05 03:01:50 -0500895 attrs := &bazelGenruleAttributes{
Liz Kammer356f7d42021-01-26 09:18:53 -0500896 Srcs: srcs,
897 Outs: outs,
898 Cmd: cmd,
899 Tools: tools,
Jingwen Chen1fd14692021-02-05 03:01:50 -0500900 }
901
Liz Kammerfc46bc12021-02-19 11:06:17 -0500902 props := bazel.BazelTargetModuleProperties{
903 Rule_class: "genrule",
904 }
Jingwen Chen1fd14692021-02-05 03:01:50 -0500905
906 // Create the BazelTargetModule.
Liz Kammerfc46bc12021-02-19 11:06:17 -0500907 ctx.CreateBazelTargetModule(BazelGenruleFactory, m.Name(), props, attrs)
Jingwen Chen316e07c2020-12-14 09:09:52 -0500908}
909
910func (m *bazelGenrule) Name() string {
911 return m.BaseModuleName()
912}
913
914func (m *bazelGenrule) GenerateAndroidBuildActions(ctx android.ModuleContext) {}
915
Nan Zhangea568a42017-11-08 21:20:04 -0800916var Bool = proptools.Bool
917var String = proptools.String
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800918
919//
920// Defaults
921//
922type Defaults struct {
923 android.ModuleBase
924 android.DefaultsModuleBase
925}
926
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800927func defaultsFactory() android.Module {
928 return DefaultsFactory()
929}
930
931func DefaultsFactory(props ...interface{}) android.Module {
932 module := &Defaults{}
933
934 module.AddProperties(props...)
935 module.AddProperties(
936 &generatorProperties{},
937 &genRuleProperties{},
938 )
939
940 android.InitDefaultsModule(module)
941
942 return module
943}