blob: c52ddee53b172ff874a16ab1a8c2db9b801e579a [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 })
Liz Kammer356f7d42021-01-26 09:18:53 -050070}
71
Colin Cross5049f022015-03-18 13:28:46 -070072var (
Colin Cross635c3b02016-05-18 15:37:25 -070073 pctx = android.NewPackageContext("android/soong/genrule")
Colin Cross1a527682019-09-23 15:55:30 -070074
Alex Humesky29e3bbe2020-11-20 21:30:13 -050075 // Used by gensrcs when there is more than 1 shard to merge the outputs
76 // of each shard into a zip file.
Colin Cross1a527682019-09-23 15:55:30 -070077 gensrcsMerge = pctx.AndroidStaticRule("gensrcsMerge", blueprint.RuleParams{
78 Command: "${soongZip} -o ${tmpZip} @${tmpZip}.rsp && ${zipSync} -d ${genDir} ${tmpZip}",
79 CommandDeps: []string{"${soongZip}", "${zipSync}"},
80 Rspfile: "${tmpZip}.rsp",
81 RspfileContent: "${zipArgs}",
82 }, "tmpZip", "genDir", "zipArgs")
Colin Cross5049f022015-03-18 13:28:46 -070083)
84
Jeff Gastonefc1b412017-03-29 17:29:06 -070085func init() {
Dan Willemsenddf504c2019-08-09 16:21:29 -070086 pctx.Import("android/soong/android")
Colin Cross1a527682019-09-23 15:55:30 -070087
88 pctx.HostBinToolVariable("soongZip", "soong_zip")
89 pctx.HostBinToolVariable("zipSync", "zipsync")
Jeff Gastonefc1b412017-03-29 17:29:06 -070090}
91
Colin Cross5049f022015-03-18 13:28:46 -070092type SourceFileGenerator interface {
Colin Cross635c3b02016-05-18 15:37:25 -070093 GeneratedSourceFiles() android.Paths
Colin Cross5ed99c62016-11-22 12:55:55 -080094 GeneratedHeaderDirs() android.Paths
Dan Willemsen9da9d492018-02-21 18:28:18 -080095 GeneratedDeps() android.Paths
Colin Cross5049f022015-03-18 13:28:46 -070096}
97
Colin Crossfe17f6f2019-03-28 19:30:56 -070098// Alias for android.HostToolProvider
99// Deprecated: use android.HostToolProvider instead.
Colin Crossd350ecd2015-04-28 13:25:36 -0700100type HostToolProvider interface {
Colin Crossfe17f6f2019-03-28 19:30:56 -0700101 android.HostToolProvider
Colin Crossd350ecd2015-04-28 13:25:36 -0700102}
Colin Cross5049f022015-03-18 13:28:46 -0700103
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700104type hostToolDependencyTag struct {
105 blueprint.BaseDependencyTag
Colin Cross65cb3142021-12-10 23:05:02 +0000106 android.LicenseAnnotationToolchainDependencyTag
Colin Cross08f15ab2018-10-04 23:29:14 -0700107 label string
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700108}
Martin Stjernholmdbd814d2022-01-12 23:18:30 +0000109
110func (t hostToolDependencyTag) AllowDisabledModuleDependency(target android.Module) bool {
111 // Allow depending on a disabled module if it's replaced by a prebuilt
112 // counterpart. We get the prebuilt through android.PrebuiltGetPreferred in
113 // GenerateAndroidBuildActions.
114 return target.IsReplacedByPrebuilt()
115}
116
117var _ android.AllowDisabledModuleDependency = (*hostToolDependencyTag)(nil)
118
Colin Cross7d5136f2015-05-11 13:39:40 -0700119type generatorProperties struct {
Spandan Das93e95992021-07-29 18:26:39 +0000120 // The command to run on one or more input files. Cmd supports substitution of a few variables.
Jeff Gastonefc1b412017-03-29 17:29:06 -0700121 //
122 // Available variables for substitution:
123 //
Spandan Das93e95992021-07-29 18:26:39 +0000124 // $(location): the path to the first entry in tools or tool_files.
125 // $(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.
126 // $(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.
127 // $(in): one or more input files.
128 // $(out): a single output file.
129 // $(depfile): a file to which dependencies will be written, if the depfile property is set to true.
130 // $(genDir): the sandbox directory for this tool; contains $(out).
Colin Cross2296f5b2017-10-17 21:38:14 -0700131 // $$: a literal $
Nan Zhangea568a42017-11-08 21:20:04 -0800132 Cmd *string
Colin Cross7d5136f2015-05-11 13:39:40 -0700133
Colin Cross33bfb0a2016-11-21 17:23:08 -0800134 // Enable reading a file containing dependencies in gcc format after the command completes
Nan Zhangea568a42017-11-08 21:20:04 -0800135 Depfile *bool
Colin Cross33bfb0a2016-11-21 17:23:08 -0800136
Colin Cross6f080df2016-11-04 15:32:58 -0700137 // name of the modules (if any) that produces the host executable. Leave empty for
Colin Cross7d5136f2015-05-11 13:39:40 -0700138 // prebuilts or scripts that do not need a module to build them.
Colin Cross6f080df2016-11-04 15:32:58 -0700139 Tools []string
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700140
141 // Local file that is used as the tool
Colin Cross27b922f2019-03-04 22:35:41 -0800142 Tool_files []string `android:"path"`
Colin Cross5ed99c62016-11-22 12:55:55 -0800143
144 // List of directories to export generated headers from
145 Export_include_dirs []string
Colin Cross708c4242017-01-13 18:05:49 -0800146
147 // list of input files
Colin Cross27b922f2019-03-04 22:35:41 -0800148 Srcs []string `android:"path,arch_variant"`
Dan Willemseneefa0262018-11-17 14:01:18 -0800149
150 // input files to exclude
Colin Cross27b922f2019-03-04 22:35:41 -0800151 Exclude_srcs []string `android:"path,arch_variant"`
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400152}
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500153
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700154type Module struct {
Colin Cross635c3b02016-05-18 15:37:25 -0700155 android.ModuleBase
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800156 android.DefaultableModuleBase
Liz Kammerea6666f2021-02-17 10:17:28 -0500157 android.BazelModuleBase
Jiyong Parkfc752ca2019-06-12 13:27:29 +0900158 android.ApexModuleBase
Colin Crossd350ecd2015-04-28 13:25:36 -0700159
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700160 // For other packages to make their own genrules with extra
161 // properties
162 Extra interface{}
Colin Crossf3bfd022021-09-27 15:15:06 -0700163
164 // CmdModifier can be set by wrappers around genrule to modify the command, for example to
165 // prefix environment variables to it.
166 CmdModifier func(ctx android.ModuleContext, cmd string) string
167
Colin Cross7228ecd2019-11-18 16:00:16 -0800168 android.ImageInterface
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700169
Colin Cross7d5136f2015-05-11 13:39:40 -0700170 properties generatorProperties
Colin Crossd350ecd2015-04-28 13:25:36 -0700171
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500172 // For the different tasks that genrule and gensrc generate. genrule will
173 // generate 1 task, and gensrc will generate 1 or more tasks based on the
174 // number of shards the input files are sharded into.
Jeff Gaston437d23c2017-11-08 12:38:00 -0800175 taskGenerator taskFunc
Colin Crossd350ecd2015-04-28 13:25:36 -0700176
Colin Cross1a527682019-09-23 15:55:30 -0700177 rule blueprint.Rule
178 rawCommands []string
Colin Crossd350ecd2015-04-28 13:25:36 -0700179
Colin Cross5ed99c62016-11-22 12:55:55 -0800180 exportedIncludeDirs android.Paths
Dan Willemsenb40aab62016-04-20 14:21:14 -0700181
Colin Cross635c3b02016-05-18 15:37:25 -0700182 outputFiles android.Paths
Dan Willemsen9da9d492018-02-21 18:28:18 -0800183 outputDeps android.Paths
Colin Crossa4ad2b02019-03-18 22:15:32 -0700184
185 subName string
Colin Cross1a527682019-09-23 15:55:30 -0700186 subDir string
bralee1fbf4402020-05-21 10:11:59 +0800187
188 // Collect the module directory for IDE info in java/jdeps.go.
189 modulePaths []string
Colin Crossd350ecd2015-04-28 13:25:36 -0700190}
191
Colin Cross1a527682019-09-23 15:55:30 -0700192type taskFunc func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask
Colin Crossd350ecd2015-04-28 13:25:36 -0700193
194type generateTask struct {
Colin Cross3ea4eb82020-11-24 13:07:27 -0800195 in android.Paths
196 out android.WritablePaths
197 depFile android.WritablePath
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500198 copyTo android.WritablePaths // For gensrcs to set on gensrcsMerge rule.
Colin Cross3ea4eb82020-11-24 13:07:27 -0800199 genDir android.WritablePath
200 extraTools android.Paths // dependencies on tools used by the generator
201
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500202 cmd string
203 // For gensrsc sharding.
Colin Cross3ea4eb82020-11-24 13:07:27 -0800204 shard int
205 shards int
Colin Crossd350ecd2015-04-28 13:25:36 -0700206}
207
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700208func (g *Module) GeneratedSourceFiles() android.Paths {
Colin Crossd350ecd2015-04-28 13:25:36 -0700209 return g.outputFiles
210}
211
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700212func (g *Module) Srcs() android.Paths {
Nan Zhange42777a2018-03-27 16:19:42 -0700213 return append(android.Paths{}, g.outputFiles...)
Colin Cross068e0fe2016-12-13 15:23:47 -0800214}
215
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700216func (g *Module) GeneratedHeaderDirs() android.Paths {
Colin Cross5ed99c62016-11-22 12:55:55 -0800217 return g.exportedIncludeDirs
Dan Willemsenb40aab62016-04-20 14:21:14 -0700218}
219
Dan Willemsen9da9d492018-02-21 18:28:18 -0800220func (g *Module) GeneratedDeps() android.Paths {
221 return g.outputDeps
222}
223
Jooyung Han8c7e3ed2021-06-28 17:35:58 +0900224func (g *Module) OutputFiles(tag string) (android.Paths, error) {
225 if tag == "" {
226 return append(android.Paths{}, g.outputFiles...), nil
227 }
228 // otherwise, tag should match one of outputs
229 for _, outputFile := range g.outputFiles {
230 if outputFile.Rel() == tag {
231 return android.Paths{outputFile}, nil
232 }
233 }
234 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
235}
236
237var _ android.SourceFileProducer = (*Module)(nil)
238var _ android.OutputFileProducer = (*Module)(nil)
239
Martin Stjernholm710ec3a2020-01-16 15:12:04 +0000240func toolDepsMutator(ctx android.BottomUpMutatorContext) {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700241 if g, ok := ctx.Module().(*Module); ok {
Colin Cross08f15ab2018-10-04 23:29:14 -0700242 for _, tool := range g.properties.Tools {
243 tag := hostToolDependencyTag{label: tool}
244 if m := android.SrcIsModule(tool); m != "" {
245 tool = m
246 }
Colin Cross0f7d2ef2019-10-16 11:03:10 -0700247 ctx.AddFarVariationDependencies(ctx.Config().BuildOSTarget.Variations(), tag, tool)
Colin Cross6362e272015-10-29 15:25:03 -0700248 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700249 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700250}
251
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400252// 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 +0000253func (c *Module) GenerateBazelBuildActions(ctx android.ModuleContext, label string) bool {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400254 bazelCtx := ctx.Config().BazelContext
Chris Parsons787fb362021-10-14 18:43:51 -0400255 filePaths, ok := bazelCtx.GetOutputFiles(label, android.GetConfigKey(ctx))
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400256 if ok {
257 var bazelOutputFiles android.Paths
Chris Parsonse59af4e2021-03-31 13:32:41 -0400258 exportIncludeDirs := map[string]bool{}
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400259 for _, bazelOutputFile := range filePaths {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -0500260 bazelOutputFiles = append(bazelOutputFiles, android.PathForBazelOut(ctx, bazelOutputFile))
Chris Parsonse59af4e2021-03-31 13:32:41 -0400261 exportIncludeDirs[filepath.Dir(bazelOutputFile)] = true
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400262 }
263 c.outputFiles = bazelOutputFiles
264 c.outputDeps = bazelOutputFiles
Chris Parsonse59af4e2021-03-31 13:32:41 -0400265 for includePath, _ := range exportIncludeDirs {
266 c.exportedIncludeDirs = append(c.exportedIncludeDirs, android.PathForBazelOut(ctx, includePath))
267 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400268 }
269 return ok
270}
Colin Crossf1885962020-11-20 15:28:30 -0800271
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700272func (g *Module) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Colin Crossa4ad2b02019-03-18 22:15:32 -0700273 g.subName = ctx.ModuleSubDir()
274
bralee1fbf4402020-05-21 10:11:59 +0800275 // Collect the module directory for IDE info in java/jdeps.go.
276 g.modulePaths = append(g.modulePaths, ctx.ModuleDir())
277
Colin Cross5ed99c62016-11-22 12:55:55 -0800278 if len(g.properties.Export_include_dirs) > 0 {
279 for _, dir := range g.properties.Export_include_dirs {
280 g.exportedIncludeDirs = append(g.exportedIncludeDirs,
Colin Cross1a527682019-09-23 15:55:30 -0700281 android.PathForModuleGen(ctx, g.subDir, ctx.ModuleDir(), dir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800282 }
283 } else {
Colin Cross1a527682019-09-23 15:55:30 -0700284 g.exportedIncludeDirs = append(g.exportedIncludeDirs, android.PathForModuleGen(ctx, g.subDir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800285 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700286
Colin Crossd11cf622021-03-23 22:30:35 -0700287 locationLabels := map[string]location{}
Colin Cross08f15ab2018-10-04 23:29:14 -0700288 firstLabel := ""
289
Colin Crossd11cf622021-03-23 22:30:35 -0700290 addLocationLabel := func(label string, loc location) {
Colin Cross08f15ab2018-10-04 23:29:14 -0700291 if firstLabel == "" {
292 firstLabel = label
293 }
294 if _, exists := locationLabels[label]; !exists {
Colin Crossd11cf622021-03-23 22:30:35 -0700295 locationLabels[label] = loc
Colin Cross08f15ab2018-10-04 23:29:14 -0700296 } else {
Anton Hansson7cd41e52021-10-08 16:13:10 +0100297 ctx.ModuleErrorf("multiple locations for label %q: %q and %q (do you have duplicate srcs entries?)",
Colin Crossd11cf622021-03-23 22:30:35 -0700298 label, locationLabels[label], loc)
Colin Cross08f15ab2018-10-04 23:29:14 -0700299 }
300 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700301
Colin Crossba9e4032020-11-24 16:32:22 -0800302 var tools android.Paths
303 var packagedTools []android.PackagingSpec
Colin Cross6f080df2016-11-04 15:32:58 -0700304 if len(g.properties.Tools) > 0 {
Colin Crossba71a3f2019-03-18 12:12:48 -0700305 seenTools := make(map[string]bool)
306
Colin Cross35143d02017-11-16 00:11:20 -0800307 ctx.VisitDirectDepsBlueprint(func(module blueprint.Module) {
Colin Cross08f15ab2018-10-04 23:29:14 -0700308 switch tag := ctx.OtherModuleDependencyTag(module).(type) {
309 case hostToolDependencyTag:
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700310 tool := ctx.OtherModuleName(module)
Martin Stjernholmdbd814d2022-01-12 23:18:30 +0000311 if m, ok := module.(android.Module); ok {
312 // Necessary to retrieve any prebuilt replacement for the tool, since
313 // toolDepsMutator runs too late for the prebuilt mutators to have
314 // replaced the dependency.
315 module = android.PrebuiltGetPreferred(ctx, m)
316 }
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700317
Colin Crossba9e4032020-11-24 16:32:22 -0800318 switch t := module.(type) {
319 case android.HostToolProvider:
320 // A HostToolProvider provides the path to a tool, which will be copied
321 // into the sandbox.
Colin Cross35143d02017-11-16 00:11:20 -0800322 if !t.(android.Module).Enabled() {
Colin Cross6510f912017-11-29 00:27:14 -0800323 if ctx.Config().AllowMissingDependencies() {
Colin Cross35143d02017-11-16 00:11:20 -0800324 ctx.AddMissingDependencies([]string{tool})
325 } else {
326 ctx.ModuleErrorf("depends on disabled module %q", tool)
327 }
Colin Crossba9e4032020-11-24 16:32:22 -0800328 return
Colin Cross35143d02017-11-16 00:11:20 -0800329 }
Colin Crossba9e4032020-11-24 16:32:22 -0800330 path := t.HostToolPath()
331 if !path.Valid() {
332 ctx.ModuleErrorf("host tool %q missing output file", tool)
333 return
334 }
335 if specs := t.TransitivePackagingSpecs(); specs != nil {
336 // If the HostToolProvider has PackgingSpecs, which are definitions of the
337 // required relative locations of the tool and its dependencies, use those
338 // instead. They will be copied to those relative locations in the sbox
339 // sandbox.
340 packagedTools = append(packagedTools, specs...)
341 // Assume that the first PackagingSpec of the module is the tool.
Colin Crossd11cf622021-03-23 22:30:35 -0700342 addLocationLabel(tag.label, packagedToolLocation{specs[0]})
Colin Crossba9e4032020-11-24 16:32:22 -0800343 } else {
344 tools = append(tools, path.Path())
Colin Crossd11cf622021-03-23 22:30:35 -0700345 addLocationLabel(tag.label, toolLocation{android.Paths{path.Path()}})
Colin Crossba9e4032020-11-24 16:32:22 -0800346 }
347 case bootstrap.GoBinaryTool:
348 // A GoBinaryTool provides the install path to a tool, which will be copied.
Colin Crossa44551f2021-10-25 15:36:21 -0700349 p := android.PathForGoBinary(ctx, t)
350 tools = append(tools, p)
351 addLocationLabel(tag.label, toolLocation{android.Paths{p}})
Colin Crossba9e4032020-11-24 16:32:22 -0800352 default:
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700353 ctx.ModuleErrorf("%q is not a host tool provider", tool)
Colin Crossba9e4032020-11-24 16:32:22 -0800354 return
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700355 }
356
Colin Crossba9e4032020-11-24 16:32:22 -0800357 seenTools[tag.label] = true
Colin Crossd350ecd2015-04-28 13:25:36 -0700358 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700359 })
Colin Crossba71a3f2019-03-18 12:12:48 -0700360
361 // If AllowMissingDependencies is enabled, the build will not have stopped when
362 // AddFarVariationDependencies was called on a missing tool, which will result in nonsensical
Liz Kammer20ebfb42020-07-28 11:32:07 -0700363 // "cmd: unknown location label ..." errors later. Add a placeholder file to the local label.
364 // The command that uses this placeholder file will never be executed because the rule will be
365 // replaced with an android.Error rule reporting the missing dependencies.
Colin Crossba71a3f2019-03-18 12:12:48 -0700366 if ctx.Config().AllowMissingDependencies() {
367 for _, tool := range g.properties.Tools {
368 if !seenTools[tool] {
Colin Crossd11cf622021-03-23 22:30:35 -0700369 addLocationLabel(tool, errorLocation{"***missing tool " + tool + "***"})
Colin Crossba71a3f2019-03-18 12:12:48 -0700370 }
371 }
372 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700373 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700374
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700375 if ctx.Failed() {
376 return
377 }
378
Colin Cross08f15ab2018-10-04 23:29:14 -0700379 for _, toolFile := range g.properties.Tool_files {
Colin Cross8a497952019-03-05 22:25:09 -0800380 paths := android.PathsForModuleSrc(ctx, []string{toolFile})
Colin Crossba9e4032020-11-24 16:32:22 -0800381 tools = append(tools, paths...)
Colin Crossd11cf622021-03-23 22:30:35 -0700382 addLocationLabel(toolFile, toolLocation{paths})
Colin Cross08f15ab2018-10-04 23:29:14 -0700383 }
384
Liz Kammer619be462022-01-28 15:13:39 -0500385 includeDirInPaths := ctx.DeviceConfig().BuildBrokenInputDir(g.Name())
Colin Cross08f15ab2018-10-04 23:29:14 -0700386 var srcFiles android.Paths
387 for _, in := range g.properties.Srcs {
Liz Kammer619be462022-01-28 15:13:39 -0500388 paths, missingDeps := android.PathsAndMissingDepsRelativeToModuleSourceDir(android.SourceInput{
389 Context: ctx, Paths: []string{in}, ExcludePaths: g.properties.Exclude_srcs, IncludeDirs: includeDirInPaths,
390 })
Colin Crossba71a3f2019-03-18 12:12:48 -0700391 if len(missingDeps) > 0 {
392 if !ctx.Config().AllowMissingDependencies() {
393 panic(fmt.Errorf("should never get here, the missing dependencies %q should have been reported in DepsMutator",
394 missingDeps))
395 }
396
397 // If AllowMissingDependencies is enabled, the build will not have stopped when
398 // the dependency was added on a missing SourceFileProducer module, which will result in nonsensical
Liz Kammer20ebfb42020-07-28 11:32:07 -0700399 // "cmd: label ":..." has no files" errors later. Add a placeholder file to the local label.
400 // The command that uses this placeholder file will never be executed because the rule will be
401 // replaced with an android.Error rule reporting the missing dependencies.
Colin Crossba71a3f2019-03-18 12:12:48 -0700402 ctx.AddMissingDependencies(missingDeps)
Colin Crossd11cf622021-03-23 22:30:35 -0700403 addLocationLabel(in, errorLocation{"***missing srcs " + in + "***"})
Colin Crossba71a3f2019-03-18 12:12:48 -0700404 } else {
405 srcFiles = append(srcFiles, paths...)
Colin Crossd11cf622021-03-23 22:30:35 -0700406 addLocationLabel(in, inputLocation{paths})
Colin Crossba71a3f2019-03-18 12:12:48 -0700407 }
Colin Cross08f15ab2018-10-04 23:29:14 -0700408 }
409
Colin Cross1a527682019-09-23 15:55:30 -0700410 var copyFrom android.Paths
411 var outputFiles android.WritablePaths
412 var zipArgs strings.Builder
Colin Cross08f15ab2018-10-04 23:29:14 -0700413
Colin Crossf3bfd022021-09-27 15:15:06 -0700414 cmd := String(g.properties.Cmd)
415 if g.CmdModifier != nil {
416 cmd = g.CmdModifier(ctx, cmd)
417 }
418
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500419 // Generate tasks, either from genrule or gensrcs.
Colin Crossf3bfd022021-09-27 15:15:06 -0700420 for _, task := range g.taskGenerator(ctx, cmd, srcFiles) {
Colin Cross3d680512020-11-13 16:23:53 -0800421 if len(task.out) == 0 {
422 ctx.ModuleErrorf("must have at least one output file")
423 return
Colin Cross85a2e892018-07-09 09:45:06 -0700424 }
425
Colin Crossf1a035e2020-11-16 17:32:30 -0800426 // Pick a unique path outside the task.genDir for the sbox manifest textproto,
427 // a unique rule name, and the user-visible description.
428 manifestName := "genrule.sbox.textproto"
429 desc := "generate"
430 name := "generator"
431 if task.shards > 0 {
432 manifestName = "genrule_" + strconv.Itoa(task.shard) + ".sbox.textproto"
433 desc += " " + strconv.Itoa(task.shard)
434 name += strconv.Itoa(task.shard)
435 } else if len(task.out) == 1 {
436 desc += " " + task.out[0].Base()
437 }
438
439 manifestPath := android.PathForModuleOut(ctx, manifestName)
440
441 // Use a RuleBuilder to create a rule that runs the command inside an sbox sandbox.
Colin Crossba9e4032020-11-24 16:32:22 -0800442 rule := android.NewRuleBuilder(pctx, ctx).Sbox(task.genDir, manifestPath).SandboxTools()
Colin Crossf1a035e2020-11-16 17:32:30 -0800443 cmd := rule.Command()
444
Colin Cross3d680512020-11-13 16:23:53 -0800445 for _, out := range task.out {
Colin Crossd11cf622021-03-23 22:30:35 -0700446 addLocationLabel(out.Rel(), outputLocation{out})
Colin Cross3d680512020-11-13 16:23:53 -0800447 }
448
Colin Cross1a527682019-09-23 15:55:30 -0700449 referencedDepfile := false
450
Colin Cross3d680512020-11-13 16:23:53 -0800451 rawCommand, err := android.Expand(task.cmd, func(name string) (string, error) {
Colin Cross1a527682019-09-23 15:55:30 -0700452 // report the error directly without returning an error to android.Expand to catch multiple errors in a
453 // single run
Colin Cross3d680512020-11-13 16:23:53 -0800454 reportError := func(fmt string, args ...interface{}) (string, error) {
Colin Cross1a527682019-09-23 15:55:30 -0700455 ctx.PropertyErrorf("cmd", fmt, args...)
Colin Cross3d680512020-11-13 16:23:53 -0800456 return "SOONG_ERROR", nil
Colin Cross6f080df2016-11-04 15:32:58 -0700457 }
Colin Cross1a527682019-09-23 15:55:30 -0700458
459 switch name {
460 case "location":
461 if len(g.properties.Tools) == 0 && len(g.properties.Tool_files) == 0 {
462 return reportError("at least one `tools` or `tool_files` is required if $(location) is used")
Colin Cross6f080df2016-11-04 15:32:58 -0700463 }
Colin Crossd11cf622021-03-23 22:30:35 -0700464 loc := locationLabels[firstLabel]
465 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700466 if len(paths) == 0 {
467 return reportError("default label %q has no files", firstLabel)
468 } else if len(paths) > 1 {
469 return reportError("default label %q has multiple files, use $(locations %s) to reference it",
470 firstLabel, firstLabel)
Colin Cross08f15ab2018-10-04 23:29:14 -0700471 }
Colin Crossd11cf622021-03-23 22:30:35 -0700472 return paths[0], nil
Colin Cross1a527682019-09-23 15:55:30 -0700473 case "in":
Colin Crossd11cf622021-03-23 22:30:35 -0700474 return strings.Join(cmd.PathsForInputs(srcFiles), " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700475 case "out":
Colin Cross3d680512020-11-13 16:23:53 -0800476 var sandboxOuts []string
477 for _, out := range task.out {
Colin Crossf1a035e2020-11-16 17:32:30 -0800478 sandboxOuts = append(sandboxOuts, cmd.PathForOutput(out))
Colin Cross3d680512020-11-13 16:23:53 -0800479 }
480 return strings.Join(sandboxOuts, " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700481 case "depfile":
482 referencedDepfile = true
483 if !Bool(g.properties.Depfile) {
484 return reportError("$(depfile) used without depfile property")
485 }
Colin Cross3d680512020-11-13 16:23:53 -0800486 return "__SBOX_DEPFILE__", nil
Colin Cross1a527682019-09-23 15:55:30 -0700487 case "genDir":
Colin Crossf1a035e2020-11-16 17:32:30 -0800488 return cmd.PathForOutput(task.genDir), nil
Colin Cross1a527682019-09-23 15:55:30 -0700489 default:
490 if strings.HasPrefix(name, "location ") {
491 label := strings.TrimSpace(strings.TrimPrefix(name, "location "))
Colin Crossd11cf622021-03-23 22:30:35 -0700492 if loc, ok := locationLabels[label]; ok {
493 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700494 if len(paths) == 0 {
495 return reportError("label %q has no files", label)
496 } else if len(paths) > 1 {
497 return reportError("label %q has multiple files, use $(locations %s) to reference it",
498 label, label)
499 }
Colin Cross3d680512020-11-13 16:23:53 -0800500 return paths[0], nil
Colin Cross1a527682019-09-23 15:55:30 -0700501 } else {
Anton Hanssonbebf5262022-02-23 11:42:38 +0000502 return reportError("unknown location label %q is not in srcs, out, tools or tool_files.", label)
Colin Cross1a527682019-09-23 15:55:30 -0700503 }
504 } else if strings.HasPrefix(name, "locations ") {
505 label := strings.TrimSpace(strings.TrimPrefix(name, "locations "))
Colin Crossd11cf622021-03-23 22:30:35 -0700506 if loc, ok := locationLabels[label]; ok {
507 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700508 if len(paths) == 0 {
509 return reportError("label %q has no files", label)
510 }
Colin Cross3d680512020-11-13 16:23:53 -0800511 return strings.Join(paths, " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700512 } else {
Anton Hanssonbebf5262022-02-23 11:42:38 +0000513 return reportError("unknown locations label %q is not in srcs, out, tools or tool_files.", label)
Colin Cross1a527682019-09-23 15:55:30 -0700514 }
515 } else {
516 return reportError("unknown variable '$(%s)'", name)
517 }
Colin Cross6f080df2016-11-04 15:32:58 -0700518 }
Colin Cross1a527682019-09-23 15:55:30 -0700519 })
520
521 if err != nil {
522 ctx.PropertyErrorf("cmd", "%s", err.Error())
523 return
Colin Cross6f080df2016-11-04 15:32:58 -0700524 }
Colin Cross6f080df2016-11-04 15:32:58 -0700525
Colin Cross1a527682019-09-23 15:55:30 -0700526 if Bool(g.properties.Depfile) && !referencedDepfile {
527 ctx.PropertyErrorf("cmd", "specified depfile=true but did not include a reference to '${depfile}' in cmd")
528 return
529 }
Colin Cross1a527682019-09-23 15:55:30 -0700530 g.rawCommands = append(g.rawCommands, rawCommand)
Bill Peckhamc087be12020-02-13 15:55:10 -0800531
Colin Cross3d680512020-11-13 16:23:53 -0800532 cmd.Text(rawCommand)
533 cmd.ImplicitOutputs(task.out)
534 cmd.Implicits(task.in)
Colin Crossba9e4032020-11-24 16:32:22 -0800535 cmd.ImplicitTools(tools)
536 cmd.ImplicitTools(task.extraTools)
537 cmd.ImplicitPackagedTools(packagedTools)
Colin Cross3d680512020-11-13 16:23:53 -0800538 if Bool(g.properties.Depfile) {
539 cmd.ImplicitDepFile(task.depFile)
540 }
541
542 // Create the rule to run the genrule command inside sbox.
Colin Crossf1a035e2020-11-16 17:32:30 -0800543 rule.Build(name, desc)
Colin Cross1a527682019-09-23 15:55:30 -0700544
545 if len(task.copyTo) > 0 {
Colin Cross3d680512020-11-13 16:23:53 -0800546 // If copyTo is set, multiple shards need to be copied into a single directory.
547 // task.out contains the per-shard paths, and copyTo contains the corresponding
548 // final path. The files need to be copied into the final directory by a
549 // single rule so it can remove the directory before it starts to ensure no
550 // old files remain. zipsync already does this, so build up zipArgs that
551 // zip all the per-shard directories into a single zip.
Colin Cross1a527682019-09-23 15:55:30 -0700552 outputFiles = append(outputFiles, task.copyTo...)
553 copyFrom = append(copyFrom, task.out.Paths()...)
554 zipArgs.WriteString(" -C " + task.genDir.String())
555 zipArgs.WriteString(android.JoinWithPrefix(task.out.Strings(), " -f "))
556 } else {
557 outputFiles = append(outputFiles, task.out...)
558 }
Colin Cross6f080df2016-11-04 15:32:58 -0700559 }
560
Colin Cross1a527682019-09-23 15:55:30 -0700561 if len(copyFrom) > 0 {
Colin Cross3d680512020-11-13 16:23:53 -0800562 // Create a rule that zips all the per-shard directories into a single zip and then
563 // uses zipsync to unzip it into the final directory.
Colin Cross1a527682019-09-23 15:55:30 -0700564 ctx.Build(pctx, android.BuildParams{
Colin Crossf1885962020-11-20 15:28:30 -0800565 Rule: gensrcsMerge,
566 Implicits: copyFrom,
567 Outputs: outputFiles,
568 Description: "merge shards",
Colin Cross1a527682019-09-23 15:55:30 -0700569 Args: map[string]string{
570 "zipArgs": zipArgs.String(),
571 "tmpZip": android.PathForModuleGen(ctx, g.subDir+".zip").String(),
572 "genDir": android.PathForModuleGen(ctx, g.subDir).String(),
573 },
574 })
Colin Cross85a2e892018-07-09 09:45:06 -0700575 }
576
Colin Cross1a527682019-09-23 15:55:30 -0700577 g.outputFiles = outputFiles.Paths()
Jeff Gastonefc1b412017-03-29 17:29:06 -0700578
Liz Kammerbdc60992021-02-24 16:55:11 -0500579 bazelModuleLabel := g.GetBazelLabel(ctx, g)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400580 bazelActionsUsed := false
Chris Parsonsbab4d7e2021-04-15 17:27:08 -0400581 if g.MixedBuildsEnabled(ctx) {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux0d990452021-08-11 16:46:13 +0000582 bazelActionsUsed = g.GenerateBazelBuildActions(ctx, bazelModuleLabel)
Jeff Gaston02a684b2017-10-27 14:59:27 -0700583 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400584 if !bazelActionsUsed {
585 // For <= 6 outputs, just embed those directly in the users. Right now, that covers >90% of
586 // the genrules on AOSP. That will make things simpler to look at the graph in the common
587 // case. For larger sets of outputs, inject a phony target in between to limit ninja file
588 // growth.
589 if len(g.outputFiles) <= 6 {
590 g.outputDeps = g.outputFiles
591 } else {
592 phonyFile := android.PathForModuleGen(ctx, "genrule-phony")
593 ctx.Build(pctx, android.BuildParams{
594 Rule: blueprint.Phony,
595 Output: phonyFile,
596 Inputs: g.outputFiles,
597 })
598 g.outputDeps = android.Paths{phonyFile}
599 }
600 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700601}
Colin Crossd350ecd2015-04-28 13:25:36 -0700602
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700603// Collect information for opening IDE project files in java/jdeps.go.
604func (g *Module) IDEInfo(dpInfo *android.IdeInfo) {
605 dpInfo.Srcs = append(dpInfo.Srcs, g.Srcs().Strings()...)
606 for _, src := range g.properties.Srcs {
607 if strings.HasPrefix(src, ":") {
608 src = strings.Trim(src, ":")
609 dpInfo.Deps = append(dpInfo.Deps, src)
610 }
611 }
bralee1fbf4402020-05-21 10:11:59 +0800612 dpInfo.Paths = append(dpInfo.Paths, g.modulePaths...)
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700613}
614
Colin Crossa4ad2b02019-03-18 22:15:32 -0700615func (g *Module) AndroidMk() android.AndroidMkData {
616 return android.AndroidMkData{
Anton Hansson72f18492020-10-30 16:34:45 +0000617 Class: "ETC",
Colin Crossa4ad2b02019-03-18 22:15:32 -0700618 OutputFile: android.OptionalPathForPath(g.outputFiles[0]),
619 SubName: g.subName,
620 Extra: []android.AndroidMkExtraFunc{
621 func(w io.Writer, outputFile android.Path) {
Anton Hansson72f18492020-10-30 16:34:45 +0000622 fmt.Fprintln(w, "LOCAL_UNINSTALLABLE_MODULE := true")
Colin Crossa4ad2b02019-03-18 22:15:32 -0700623 },
624 },
625 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
626 android.WriteAndroidMkData(w, data)
627 if data.SubName != "" {
628 fmt.Fprintln(w, ".PHONY:", name)
629 fmt.Fprintln(w, name, ":", name+g.subName)
630 }
631 },
632 }
633}
634
Jiyong Park45bf82e2020-12-15 22:29:02 +0900635var _ android.ApexModule = (*Module)(nil)
636
637// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -0700638func (g *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
639 sdkVersion android.ApiLevel) error {
Jooyung Han749dc692020-04-15 11:03:39 +0900640 // Because generated outputs are checked by client modules(e.g. cc_library, ...)
641 // we can safely ignore the check here.
642 return nil
643}
644
Jeff Gaston437d23c2017-11-08 12:38:00 -0800645func generatorFactory(taskGenerator taskFunc, props ...interface{}) *Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700646 module := &Module{
Jeff Gaston437d23c2017-11-08 12:38:00 -0800647 taskGenerator: taskGenerator,
Colin Crossd350ecd2015-04-28 13:25:36 -0700648 }
649
Colin Cross36242852017-06-23 15:06:31 -0700650 module.AddProperties(props...)
651 module.AddProperties(&module.properties)
Colin Crossd350ecd2015-04-28 13:25:36 -0700652
Colin Cross7228ecd2019-11-18 16:00:16 -0800653 module.ImageInterface = noopImageInterface{}
654
Colin Cross36242852017-06-23 15:06:31 -0700655 return module
Colin Crossd350ecd2015-04-28 13:25:36 -0700656}
657
Colin Cross7228ecd2019-11-18 16:00:16 -0800658type noopImageInterface struct{}
659
660func (x noopImageInterface) ImageMutatorBegin(android.BaseModuleContext) {}
661func (x noopImageInterface) CoreVariantNeeded(android.BaseModuleContext) bool { return false }
Yifan Hong1b3348d2020-01-21 15:53:22 -0800662func (x noopImageInterface) RamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700663func (x noopImageInterface) VendorRamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Inseob Kim08758f02021-04-08 21:13:22 +0900664func (x noopImageInterface) DebugRamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Colin Cross7228ecd2019-11-18 16:00:16 -0800665func (x noopImageInterface) RecoveryVariantNeeded(android.BaseModuleContext) bool { return false }
666func (x noopImageInterface) ExtraImageVariations(ctx android.BaseModuleContext) []string { return nil }
667func (x noopImageInterface) SetImageVariation(ctx android.BaseModuleContext, variation string, module android.Module) {
668}
669
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700670func NewGenSrcs() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700671 properties := &genSrcsProperties{}
672
Colin Crossf1885962020-11-20 15:28:30 -0800673 // finalSubDir is the name of the subdirectory that output files will be generated into.
674 // It is used so that per-shard directories can be placed alongside it an then finally
675 // merged into it.
676 const finalSubDir = "gensrcs"
677
Colin Cross1a527682019-09-23 15:55:30 -0700678 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Colin Cross1a527682019-09-23 15:55:30 -0700679 shardSize := defaultShardSize
680 if s := properties.Shard_size; s != nil {
681 shardSize = int(*s)
682 }
Jeff Gaston437d23c2017-11-08 12:38:00 -0800683
Colin Crossf1885962020-11-20 15:28:30 -0800684 // gensrcs rules can easily hit command line limits by repeating the command for
685 // every input file. Shard the input files into groups.
Colin Cross1a527682019-09-23 15:55:30 -0700686 shards := android.ShardPaths(srcFiles, shardSize)
687 var generateTasks []generateTask
Colin Crossbaccf5b2018-02-21 14:07:48 -0800688
Colin Cross1a527682019-09-23 15:55:30 -0700689 for i, shard := range shards {
690 var commands []string
691 var outFiles android.WritablePaths
Colin Cross3ea4eb82020-11-24 13:07:27 -0800692 var commandDepFiles []string
Colin Cross1a527682019-09-23 15:55:30 -0700693 var copyTo android.WritablePaths
Colin Cross1a527682019-09-23 15:55:30 -0700694
Colin Crossf1885962020-11-20 15:28:30 -0800695 // When sharding is enabled (i.e. len(shards) > 1), the sbox rules for each
696 // shard will be write to their own directories and then be merged together
697 // into finalSubDir. If sharding is not enabled (i.e. len(shards) == 1),
698 // the sbox rule will write directly to finalSubDir.
699 genSubDir := finalSubDir
Colin Cross1a527682019-09-23 15:55:30 -0700700 if len(shards) > 1 {
Colin Crossf1885962020-11-20 15:28:30 -0800701 genSubDir = strconv.Itoa(i)
Jeff Gaston437d23c2017-11-08 12:38:00 -0800702 }
703
Colin Crossf1885962020-11-20 15:28:30 -0800704 genDir := android.PathForModuleGen(ctx, genSubDir)
Colin Crossf1a035e2020-11-16 17:32:30 -0800705 // TODO(ccross): this RuleBuilder is a hack to be able to call
706 // rule.Command().PathForOutput. Replace this with passing the rule into the
707 // generator.
Colin Crossba9e4032020-11-24 16:32:22 -0800708 rule := android.NewRuleBuilder(pctx, ctx).Sbox(genDir, nil).SandboxTools()
Jeff Gaston437d23c2017-11-08 12:38:00 -0800709
Colin Cross3ea4eb82020-11-24 13:07:27 -0800710 for _, in := range shard {
Colin Crossf1885962020-11-20 15:28:30 -0800711 outFile := android.GenPathWithExt(ctx, finalSubDir, in, String(properties.Output_extension))
712
713 // If sharding is enabled, then outFile is the path to the output file in
714 // the shard directory, and copyTo is the path to the output file in the
715 // final directory.
Colin Cross1a527682019-09-23 15:55:30 -0700716 if len(shards) > 1 {
Colin Crossf1885962020-11-20 15:28:30 -0800717 shardFile := android.GenPathWithExt(ctx, genSubDir, in, String(properties.Output_extension))
Colin Cross1a527682019-09-23 15:55:30 -0700718 copyTo = append(copyTo, outFile)
719 outFile = shardFile
720 }
721
722 outFiles = append(outFiles, outFile)
Colin Cross1a527682019-09-23 15:55:30 -0700723
Colin Crossf1885962020-11-20 15:28:30 -0800724 // pre-expand the command line to replace $in and $out with references to
725 // a single input and output file.
Colin Cross1a527682019-09-23 15:55:30 -0700726 command, err := android.Expand(rawCommand, func(name string) (string, error) {
727 switch name {
728 case "in":
729 return in.String(), nil
730 case "out":
Colin Crossf1a035e2020-11-16 17:32:30 -0800731 return rule.Command().PathForOutput(outFile), nil
Colin Cross3ea4eb82020-11-24 13:07:27 -0800732 case "depfile":
733 // Generate a depfile for each output file. Store the list for
734 // later in order to combine them all into a single depfile.
Colin Crossf1a035e2020-11-16 17:32:30 -0800735 depFile := rule.Command().PathForOutput(outFile.ReplaceExtension(ctx, "d"))
Colin Cross3ea4eb82020-11-24 13:07:27 -0800736 commandDepFiles = append(commandDepFiles, depFile)
737 return depFile, nil
Colin Cross1a527682019-09-23 15:55:30 -0700738 default:
739 return "$(" + name + ")", nil
740 }
741 })
742 if err != nil {
743 ctx.PropertyErrorf("cmd", err.Error())
744 }
745
746 // escape the command in case for example it contains '#', an odd number of '"', etc
747 command = fmt.Sprintf("bash -c %v", proptools.ShellEscape(command))
748 commands = append(commands, command)
749 }
750 fullCommand := strings.Join(commands, " && ")
751
Colin Cross3ea4eb82020-11-24 13:07:27 -0800752 var outputDepfile android.WritablePath
753 var extraTools android.Paths
754 if len(commandDepFiles) > 0 {
755 // Each command wrote to a depfile, but ninja can only handle one
756 // depfile per rule. Use the dep_fixer tool at the end of the
757 // command to combine all the depfiles into a single output depfile.
758 outputDepfile = android.PathForModuleGen(ctx, genSubDir, "gensrcs.d")
759 depFixerTool := ctx.Config().HostToolPath(ctx, "dep_fixer")
760 fullCommand += fmt.Sprintf(" && %s -o $(depfile) %s",
Colin Crossd11cf622021-03-23 22:30:35 -0700761 rule.Command().PathForTool(depFixerTool),
Colin Crossba9e4032020-11-24 16:32:22 -0800762 strings.Join(commandDepFiles, " "))
Colin Cross3ea4eb82020-11-24 13:07:27 -0800763 extraTools = append(extraTools, depFixerTool)
764 }
765
Colin Cross1a527682019-09-23 15:55:30 -0700766 generateTasks = append(generateTasks, generateTask{
Colin Cross3ea4eb82020-11-24 13:07:27 -0800767 in: shard,
768 out: outFiles,
769 depFile: outputDepfile,
770 copyTo: copyTo,
771 genDir: genDir,
772 cmd: fullCommand,
773 shard: i,
774 shards: len(shards),
775 extraTools: extraTools,
Colin Cross1a527682019-09-23 15:55:30 -0700776 })
Jeff Gaston437d23c2017-11-08 12:38:00 -0800777 }
Colin Cross1a527682019-09-23 15:55:30 -0700778
779 return generateTasks
Colin Crossd350ecd2015-04-28 13:25:36 -0700780 }
781
Colin Cross1a527682019-09-23 15:55:30 -0700782 g := generatorFactory(taskGenerator, properties)
Colin Crossf1885962020-11-20 15:28:30 -0800783 g.subDir = finalSubDir
Colin Cross1a527682019-09-23 15:55:30 -0700784 return g
Colin Crossd350ecd2015-04-28 13:25:36 -0700785}
786
Colin Cross54190b32017-10-09 15:34:10 -0700787func GenSrcsFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700788 m := NewGenSrcs()
789 android.InitAndroidModule(m)
790 return m
791}
792
Colin Crossd350ecd2015-04-28 13:25:36 -0700793type genSrcsProperties struct {
Colin Cross7d5136f2015-05-11 13:39:40 -0700794 // extension that will be substituted for each output file
Nan Zhanga5e7cb42017-11-09 22:42:32 -0800795 Output_extension *string
Colin Cross1a527682019-09-23 15:55:30 -0700796
797 // maximum number of files that will be passed on a single command line.
798 Shard_size *int64
Colin Cross5049f022015-03-18 13:28:46 -0700799}
800
Evgenii Stepanovf47c90d2020-12-02 18:55:09 -0800801const defaultShardSize = 50
Colin Cross1a527682019-09-23 15:55:30 -0700802
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700803func NewGenRule() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700804 properties := &genRuleProperties{}
Colin Cross5049f022015-03-18 13:28:46 -0700805
Colin Cross1a527682019-09-23 15:55:30 -0700806 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700807 outs := make(android.WritablePaths, len(properties.Out))
Colin Cross3d680512020-11-13 16:23:53 -0800808 var depFile android.WritablePath
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700809 for i, out := range properties.Out {
Colin Cross3d680512020-11-13 16:23:53 -0800810 outPath := android.PathForModuleGen(ctx, out)
811 if i == 0 {
812 depFile = outPath.ReplaceExtension(ctx, "d")
813 }
814 outs[i] = outPath
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700815 }
Colin Cross1a527682019-09-23 15:55:30 -0700816 return []generateTask{{
Colin Cross3d680512020-11-13 16:23:53 -0800817 in: srcFiles,
818 out: outs,
819 depFile: depFile,
820 genDir: android.PathForModuleGen(ctx),
821 cmd: rawCommand,
Colin Cross1a527682019-09-23 15:55:30 -0700822 }}
Colin Cross5049f022015-03-18 13:28:46 -0700823 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700824
Jeff Gaston437d23c2017-11-08 12:38:00 -0800825 return generatorFactory(taskGenerator, properties)
Colin Cross5049f022015-03-18 13:28:46 -0700826}
827
Colin Cross54190b32017-10-09 15:34:10 -0700828func GenRuleFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700829 m := NewGenRule()
830 android.InitAndroidModule(m)
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800831 android.InitDefaultableModule(m)
Liz Kammerea6666f2021-02-17 10:17:28 -0500832 android.InitBazelModule(m)
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700833 return m
834}
835
Colin Crossd350ecd2015-04-28 13:25:36 -0700836type genRuleProperties struct {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700837 // names of the output files that will be generated
Colin Crossef354482018-10-23 11:27:50 -0700838 Out []string `android:"arch_variant"`
Colin Cross5049f022015-03-18 13:28:46 -0700839}
Nan Zhangea568a42017-11-08 21:20:04 -0800840
Jingwen Chen316e07c2020-12-14 09:09:52 -0500841type bazelGenruleAttributes struct {
Jingwen Chen07027912021-03-15 06:02:43 -0400842 Srcs bazel.LabelListAttribute
Jingwen Chen316e07c2020-12-14 09:09:52 -0500843 Outs []string
Jingwen Chen07027912021-03-15 06:02:43 -0400844 Tools bazel.LabelListAttribute
Jingwen Chen316e07c2020-12-14 09:09:52 -0500845 Cmd string
846}
847
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400848// ConvertWithBp2build converts a Soong module -> Bazel target.
849func (m *Module) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
Liz Kammer356f7d42021-01-26 09:18:53 -0500850 // Bazel only has the "tools" attribute.
Jingwen Chen07027912021-03-15 06:02:43 -0400851 tools_prop := android.BazelLabelForModuleDeps(ctx, m.properties.Tools)
852 tool_files_prop := android.BazelLabelForModuleSrc(ctx, m.properties.Tool_files)
853 tools_prop.Append(tool_files_prop)
Liz Kammer356f7d42021-01-26 09:18:53 -0500854
Jingwen Chen07027912021-03-15 06:02:43 -0400855 tools := bazel.MakeLabelListAttribute(tools_prop)
856 srcs := bazel.MakeLabelListAttribute(android.BazelLabelForModuleSrc(ctx, m.properties.Srcs))
Liz Kammer356f7d42021-01-26 09:18:53 -0500857
858 var allReplacements bazel.LabelList
Jingwen Chen07027912021-03-15 06:02:43 -0400859 allReplacements.Append(tools.Value)
860 allReplacements.Append(srcs.Value)
Liz Kammer356f7d42021-01-26 09:18:53 -0500861
862 // Replace in and out variables with $< and $@
863 var cmd string
864 if m.properties.Cmd != nil {
865 cmd = strings.Replace(*m.properties.Cmd, "$(in)", "$(SRCS)", -1)
866 cmd = strings.Replace(cmd, "$(out)", "$(OUTS)", -1)
Wei Libcd39942021-09-16 23:57:28 +0000867 genDir := "$(GENDIR)"
Sam Delmericocd1b80f2022-01-11 21:55:46 +0000868 if t := ctx.ModuleType(); t == "cc_genrule" || t == "java_genrule" || t == "java_genrule_host" {
Wei Libcd39942021-09-16 23:57:28 +0000869 genDir = "$(RULEDIR)"
870 }
871 cmd = strings.Replace(cmd, "$(genDir)", genDir, -1)
Jingwen Chen07027912021-03-15 06:02:43 -0400872 if len(tools.Value.Includes) > 0 {
873 cmd = strings.Replace(cmd, "$(location)", fmt.Sprintf("$(location %s)", tools.Value.Includes[0].Label), -1)
874 cmd = strings.Replace(cmd, "$(locations)", fmt.Sprintf("$(locations %s)", tools.Value.Includes[0].Label), -1)
Liz Kammer356f7d42021-01-26 09:18:53 -0500875 }
876 for _, l := range allReplacements.Includes {
Jingwen Chen38e62642021-04-19 05:00:15 +0000877 bpLoc := fmt.Sprintf("$(location %s)", l.OriginalModuleName)
878 bpLocs := fmt.Sprintf("$(locations %s)", l.OriginalModuleName)
Liz Kammer356f7d42021-01-26 09:18:53 -0500879 bazelLoc := fmt.Sprintf("$(location %s)", l.Label)
880 bazelLocs := fmt.Sprintf("$(locations %s)", l.Label)
881 cmd = strings.Replace(cmd, bpLoc, bazelLoc, -1)
882 cmd = strings.Replace(cmd, bpLocs, bazelLocs, -1)
883 }
884 }
885
886 // The Out prop is not in an immediately accessible field
887 // in the Module struct, so use GetProperties and cast it
888 // to the known struct prop.
889 var outs []string
890 for _, propIntf := range m.GetProperties() {
891 if props, ok := propIntf.(*genRuleProperties); ok {
892 outs = props.Out
893 break
894 }
895 }
896
Jingwen Chen1fd14692021-02-05 03:01:50 -0500897 attrs := &bazelGenruleAttributes{
Liz Kammer356f7d42021-01-26 09:18:53 -0500898 Srcs: srcs,
899 Outs: outs,
900 Cmd: cmd,
901 Tools: tools,
Jingwen Chen1fd14692021-02-05 03:01:50 -0500902 }
903
Liz Kammerfc46bc12021-02-19 11:06:17 -0500904 props := bazel.BazelTargetModuleProperties{
905 Rule_class: "genrule",
906 }
Jingwen Chen1fd14692021-02-05 03:01:50 -0500907
908 // Create the BazelTargetModule.
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +0000909 ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: m.Name()}, attrs)
Jingwen Chen316e07c2020-12-14 09:09:52 -0500910}
911
Nan Zhangea568a42017-11-08 21:20:04 -0800912var Bool = proptools.Bool
913var String = proptools.String
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800914
915//
916// Defaults
917//
918type Defaults struct {
919 android.ModuleBase
920 android.DefaultsModuleBase
921}
922
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800923func defaultsFactory() android.Module {
924 return DefaultsFactory()
925}
926
927func DefaultsFactory(props ...interface{}) android.Module {
928 module := &Defaults{}
929
930 module.AddProperties(props...)
931 module.AddProperties(
932 &generatorProperties{},
933 &genRuleProperties{},
934 )
935
936 android.InitDefaultsModule(module)
937
938 return module
939}