blob: 6686c8717261af79e2d89c12b5bf292648fbab50 [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
Chris Parsonsf874e462022-05-10 13:50:12 -040028 "android/soong/bazel/cquery"
Colin Cross70b40592015-03-23 12:57:34 -070029 "github.com/google/blueprint"
Dan Willemsen8eded0a2017-09-13 16:07:44 -070030 "github.com/google/blueprint/bootstrap"
Nan Zhangea568a42017-11-08 21:20:04 -080031 "github.com/google/blueprint/proptools"
Colin Cross5049f022015-03-18 13:28:46 -070032
Colin Cross635c3b02016-05-18 15:37:25 -070033 "android/soong/android"
Jingwen Chen30f5aaa2020-11-19 05:38:02 -050034 "android/soong/bazel"
Colin Cross5049f022015-03-18 13:28:46 -070035)
36
Colin Cross463a90e2015-06-17 14:20:06 -070037func init() {
Colin Crosse9fe2942020-11-10 18:12:15 -080038 RegisterGenruleBuildComponents(android.InitRegistrationContext)
Martin Stjernholm710ec3a2020-01-16 15:12:04 +000039}
Jaewoong Jung98716bd2018-12-10 08:13:18 -080040
Paul Duffin672cb9f2021-03-03 02:30:37 +000041// Test fixture preparer that will register most genrule build components.
42//
43// Singletons and mutators should only be added here if they are needed for a majority of genrule
44// module types, otherwise they should be added under a separate preparer to allow them to be
45// selected only when needed to reduce test execution time.
46//
47// Module types do not have much of an overhead unless they are used so this should include as many
48// module types as possible. The exceptions are those module types that require mutators and/or
49// singletons in order to function in which case they should be kept together in a separate
50// preparer.
51var PrepareForTestWithGenRuleBuildComponents = android.GroupFixturePreparers(
52 android.FixtureRegisterWithContext(RegisterGenruleBuildComponents),
53)
54
55// Prepare a fixture to use all genrule module types, mutators and singletons fully.
56//
57// This should only be used by tests that want to run with as much of the build enabled as possible.
58var PrepareForIntegrationTestWithGenrule = android.GroupFixturePreparers(
59 PrepareForTestWithGenRuleBuildComponents,
60)
61
Colin Crosse9fe2942020-11-10 18:12:15 -080062func RegisterGenruleBuildComponents(ctx android.RegistrationContext) {
Martin Stjernholm710ec3a2020-01-16 15:12:04 +000063 ctx.RegisterModuleType("genrule_defaults", defaultsFactory)
64
65 ctx.RegisterModuleType("gensrcs", GenSrcsFactory)
66 ctx.RegisterModuleType("genrule", GenRuleFactory)
67
68 ctx.FinalDepsMutators(func(ctx android.RegisterMutatorsContext) {
69 ctx.BottomUp("genrule_tool_deps", toolDepsMutator).Parallel()
70 })
Liz Kammer356f7d42021-01-26 09:18:53 -050071}
72
Colin Cross5049f022015-03-18 13:28:46 -070073var (
Colin Cross635c3b02016-05-18 15:37:25 -070074 pctx = android.NewPackageContext("android/soong/genrule")
Colin Cross1a527682019-09-23 15:55:30 -070075
Alex Humesky29e3bbe2020-11-20 21:30:13 -050076 // Used by gensrcs when there is more than 1 shard to merge the outputs
77 // of each shard into a zip file.
Colin Cross1a527682019-09-23 15:55:30 -070078 gensrcsMerge = pctx.AndroidStaticRule("gensrcsMerge", blueprint.RuleParams{
79 Command: "${soongZip} -o ${tmpZip} @${tmpZip}.rsp && ${zipSync} -d ${genDir} ${tmpZip}",
80 CommandDeps: []string{"${soongZip}", "${zipSync}"},
81 Rspfile: "${tmpZip}.rsp",
82 RspfileContent: "${zipArgs}",
83 }, "tmpZip", "genDir", "zipArgs")
Colin Cross5049f022015-03-18 13:28:46 -070084)
85
Jeff Gastonefc1b412017-03-29 17:29:06 -070086func init() {
Dan Willemsenddf504c2019-08-09 16:21:29 -070087 pctx.Import("android/soong/android")
Colin Cross1a527682019-09-23 15:55:30 -070088
89 pctx.HostBinToolVariable("soongZip", "soong_zip")
90 pctx.HostBinToolVariable("zipSync", "zipsync")
Jeff Gastonefc1b412017-03-29 17:29:06 -070091}
92
Colin Cross5049f022015-03-18 13:28:46 -070093type SourceFileGenerator interface {
Colin Cross635c3b02016-05-18 15:37:25 -070094 GeneratedSourceFiles() android.Paths
Colin Cross5ed99c62016-11-22 12:55:55 -080095 GeneratedHeaderDirs() android.Paths
Dan Willemsen9da9d492018-02-21 18:28:18 -080096 GeneratedDeps() android.Paths
Colin Cross5049f022015-03-18 13:28:46 -070097}
98
Colin Crossfe17f6f2019-03-28 19:30:56 -070099// Alias for android.HostToolProvider
100// Deprecated: use android.HostToolProvider instead.
Colin Crossd350ecd2015-04-28 13:25:36 -0700101type HostToolProvider interface {
Colin Crossfe17f6f2019-03-28 19:30:56 -0700102 android.HostToolProvider
Colin Crossd350ecd2015-04-28 13:25:36 -0700103}
Colin Cross5049f022015-03-18 13:28:46 -0700104
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700105type hostToolDependencyTag struct {
106 blueprint.BaseDependencyTag
Colin Cross65cb3142021-12-10 23:05:02 +0000107 android.LicenseAnnotationToolchainDependencyTag
Colin Cross08f15ab2018-10-04 23:29:14 -0700108 label string
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700109}
Martin Stjernholmdbd814d2022-01-12 23:18:30 +0000110
111func (t hostToolDependencyTag) AllowDisabledModuleDependency(target android.Module) bool {
112 // Allow depending on a disabled module if it's replaced by a prebuilt
113 // counterpart. We get the prebuilt through android.PrebuiltGetPreferred in
114 // GenerateAndroidBuildActions.
115 return target.IsReplacedByPrebuilt()
116}
117
118var _ android.AllowDisabledModuleDependency = (*hostToolDependencyTag)(nil)
119
Colin Cross7d5136f2015-05-11 13:39:40 -0700120type generatorProperties struct {
Spandan Das93e95992021-07-29 18:26:39 +0000121 // The command to run on one or more input files. Cmd supports substitution of a few variables.
Jeff Gastonefc1b412017-03-29 17:29:06 -0700122 //
123 // Available variables for substitution:
124 //
Spandan Das93e95992021-07-29 18:26:39 +0000125 // $(location): the path to the first entry in tools or tool_files.
126 // $(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.
127 // $(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.
128 // $(in): one or more input files.
129 // $(out): a single output file.
130 // $(depfile): a file to which dependencies will be written, if the depfile property is set to true.
131 // $(genDir): the sandbox directory for this tool; contains $(out).
Colin Cross2296f5b2017-10-17 21:38:14 -0700132 // $$: a literal $
Nan Zhangea568a42017-11-08 21:20:04 -0800133 Cmd *string
Colin Cross7d5136f2015-05-11 13:39:40 -0700134
Colin Cross33bfb0a2016-11-21 17:23:08 -0800135 // Enable reading a file containing dependencies in gcc format after the command completes
Nan Zhangea568a42017-11-08 21:20:04 -0800136 Depfile *bool
Colin Cross33bfb0a2016-11-21 17:23:08 -0800137
Colin Cross6f080df2016-11-04 15:32:58 -0700138 // name of the modules (if any) that produces the host executable. Leave empty for
Colin Cross7d5136f2015-05-11 13:39:40 -0700139 // prebuilts or scripts that do not need a module to build them.
Colin Cross6f080df2016-11-04 15:32:58 -0700140 Tools []string
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700141
142 // Local file that is used as the tool
Colin Cross27b922f2019-03-04 22:35:41 -0800143 Tool_files []string `android:"path"`
Colin Cross5ed99c62016-11-22 12:55:55 -0800144
145 // List of directories to export generated headers from
146 Export_include_dirs []string
Colin Cross708c4242017-01-13 18:05:49 -0800147
148 // list of input files
Colin Cross27b922f2019-03-04 22:35:41 -0800149 Srcs []string `android:"path,arch_variant"`
Dan Willemseneefa0262018-11-17 14:01:18 -0800150
151 // input files to exclude
Colin Cross27b922f2019-03-04 22:35:41 -0800152 Exclude_srcs []string `android:"path,arch_variant"`
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400153}
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500154
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700155type Module struct {
Colin Cross635c3b02016-05-18 15:37:25 -0700156 android.ModuleBase
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800157 android.DefaultableModuleBase
Liz Kammerea6666f2021-02-17 10:17:28 -0500158 android.BazelModuleBase
Jiyong Parkfc752ca2019-06-12 13:27:29 +0900159 android.ApexModuleBase
Colin Crossd350ecd2015-04-28 13:25:36 -0700160
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700161 // For other packages to make their own genrules with extra
162 // properties
163 Extra interface{}
Colin Crossf3bfd022021-09-27 15:15:06 -0700164
165 // CmdModifier can be set by wrappers around genrule to modify the command, for example to
166 // prefix environment variables to it.
167 CmdModifier func(ctx android.ModuleContext, cmd string) string
168
Colin Cross7228ecd2019-11-18 16:00:16 -0800169 android.ImageInterface
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700170
Colin Cross7d5136f2015-05-11 13:39:40 -0700171 properties generatorProperties
Colin Crossd350ecd2015-04-28 13:25:36 -0700172
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500173 // For the different tasks that genrule and gensrc generate. genrule will
174 // generate 1 task, and gensrc will generate 1 or more tasks based on the
175 // number of shards the input files are sharded into.
Jeff Gaston437d23c2017-11-08 12:38:00 -0800176 taskGenerator taskFunc
Colin Crossd350ecd2015-04-28 13:25:36 -0700177
Colin Cross1a527682019-09-23 15:55:30 -0700178 rule blueprint.Rule
179 rawCommands []string
Colin Crossd350ecd2015-04-28 13:25:36 -0700180
Colin Cross5ed99c62016-11-22 12:55:55 -0800181 exportedIncludeDirs android.Paths
Dan Willemsenb40aab62016-04-20 14:21:14 -0700182
Colin Cross635c3b02016-05-18 15:37:25 -0700183 outputFiles android.Paths
Dan Willemsen9da9d492018-02-21 18:28:18 -0800184 outputDeps android.Paths
Colin Crossa4ad2b02019-03-18 22:15:32 -0700185
186 subName string
Colin Cross1a527682019-09-23 15:55:30 -0700187 subDir string
bralee1fbf4402020-05-21 10:11:59 +0800188
189 // Collect the module directory for IDE info in java/jdeps.go.
190 modulePaths []string
Colin Crossd350ecd2015-04-28 13:25:36 -0700191}
192
Chris Parsonsf874e462022-05-10 13:50:12 -0400193var _ android.MixedBuildBuildable = (*Module)(nil)
194
Colin Cross1a527682019-09-23 15:55:30 -0700195type taskFunc func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask
Colin Crossd350ecd2015-04-28 13:25:36 -0700196
197type generateTask struct {
Colin Cross3ea4eb82020-11-24 13:07:27 -0800198 in android.Paths
199 out android.WritablePaths
200 depFile android.WritablePath
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500201 copyTo android.WritablePaths // For gensrcs to set on gensrcsMerge rule.
Colin Cross3ea4eb82020-11-24 13:07:27 -0800202 genDir android.WritablePath
203 extraTools android.Paths // dependencies on tools used by the generator
204
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500205 cmd string
206 // For gensrsc sharding.
Colin Cross3ea4eb82020-11-24 13:07:27 -0800207 shard int
208 shards int
Colin Crossd350ecd2015-04-28 13:25:36 -0700209}
210
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700211func (g *Module) GeneratedSourceFiles() android.Paths {
Colin Crossd350ecd2015-04-28 13:25:36 -0700212 return g.outputFiles
213}
214
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700215func (g *Module) Srcs() android.Paths {
Nan Zhange42777a2018-03-27 16:19:42 -0700216 return append(android.Paths{}, g.outputFiles...)
Colin Cross068e0fe2016-12-13 15:23:47 -0800217}
218
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700219func (g *Module) GeneratedHeaderDirs() android.Paths {
Colin Cross5ed99c62016-11-22 12:55:55 -0800220 return g.exportedIncludeDirs
Dan Willemsenb40aab62016-04-20 14:21:14 -0700221}
222
Dan Willemsen9da9d492018-02-21 18:28:18 -0800223func (g *Module) GeneratedDeps() android.Paths {
224 return g.outputDeps
225}
226
Jooyung Han8c7e3ed2021-06-28 17:35:58 +0900227func (g *Module) OutputFiles(tag string) (android.Paths, error) {
228 if tag == "" {
229 return append(android.Paths{}, g.outputFiles...), nil
230 }
231 // otherwise, tag should match one of outputs
232 for _, outputFile := range g.outputFiles {
233 if outputFile.Rel() == tag {
234 return android.Paths{outputFile}, nil
235 }
236 }
237 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
238}
239
240var _ android.SourceFileProducer = (*Module)(nil)
241var _ android.OutputFileProducer = (*Module)(nil)
242
Martin Stjernholm710ec3a2020-01-16 15:12:04 +0000243func toolDepsMutator(ctx android.BottomUpMutatorContext) {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700244 if g, ok := ctx.Module().(*Module); ok {
Colin Cross08f15ab2018-10-04 23:29:14 -0700245 for _, tool := range g.properties.Tools {
246 tag := hostToolDependencyTag{label: tool}
247 if m := android.SrcIsModule(tool); m != "" {
248 tool = m
249 }
Colin Cross0f7d2ef2019-10-16 11:03:10 -0700250 ctx.AddFarVariationDependencies(ctx.Config().BuildOSTarget.Variations(), tag, tool)
Colin Cross6362e272015-10-29 15:25:03 -0700251 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700252 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700253}
254
Chris Parsonsf874e462022-05-10 13:50:12 -0400255func (g *Module) ProcessBazelQueryResponse(ctx android.ModuleContext) {
256 g.generateCommonBuildActions(ctx)
257
258 label := g.GetBazelLabel(ctx, g)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400259 bazelCtx := ctx.Config().BazelContext
Chris Parsonsf874e462022-05-10 13:50:12 -0400260 filePaths, err := bazelCtx.GetOutputFiles(label, android.GetConfigKey(ctx))
261 if err != nil {
262 ctx.ModuleErrorf(err.Error())
263 return
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400264 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400265
266 var bazelOutputFiles android.Paths
267 exportIncludeDirs := map[string]bool{}
268 for _, bazelOutputFile := range filePaths {
Cole Faust01243362022-06-02 12:11:12 -0700269 bazelOutputFiles = append(bazelOutputFiles, android.PathForBazelOutRelative(ctx, ctx.ModuleDir(), bazelOutputFile))
Chris Parsonsf874e462022-05-10 13:50:12 -0400270 exportIncludeDirs[filepath.Dir(bazelOutputFile)] = true
271 }
272 g.outputFiles = bazelOutputFiles
273 g.outputDeps = bazelOutputFiles
274 for includePath, _ := range exportIncludeDirs {
275 g.exportedIncludeDirs = append(g.exportedIncludeDirs, android.PathForBazelOut(ctx, includePath))
276 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400277}
Colin Crossf1885962020-11-20 15:28:30 -0800278
Chris Parsonsf874e462022-05-10 13:50:12 -0400279// generateCommonBuildActions contains build action generation logic
280// common to both the mixed build case and the legacy case of genrule processing.
281// To fully support genrule in mixed builds, the contents of this function should
282// approach zero; there should be no genrule action registration done directly
283// by Soong logic in the mixed-build case.
284func (g *Module) generateCommonBuildActions(ctx android.ModuleContext) {
Colin Crossa4ad2b02019-03-18 22:15:32 -0700285 g.subName = ctx.ModuleSubDir()
286
bralee1fbf4402020-05-21 10:11:59 +0800287 // Collect the module directory for IDE info in java/jdeps.go.
288 g.modulePaths = append(g.modulePaths, ctx.ModuleDir())
289
Colin Cross5ed99c62016-11-22 12:55:55 -0800290 if len(g.properties.Export_include_dirs) > 0 {
291 for _, dir := range g.properties.Export_include_dirs {
292 g.exportedIncludeDirs = append(g.exportedIncludeDirs,
Colin Cross1a527682019-09-23 15:55:30 -0700293 android.PathForModuleGen(ctx, g.subDir, ctx.ModuleDir(), dir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800294 }
295 } else {
Colin Cross1a527682019-09-23 15:55:30 -0700296 g.exportedIncludeDirs = append(g.exportedIncludeDirs, android.PathForModuleGen(ctx, g.subDir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800297 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700298
Colin Crossd11cf622021-03-23 22:30:35 -0700299 locationLabels := map[string]location{}
Colin Cross08f15ab2018-10-04 23:29:14 -0700300 firstLabel := ""
301
Colin Crossd11cf622021-03-23 22:30:35 -0700302 addLocationLabel := func(label string, loc location) {
Colin Cross08f15ab2018-10-04 23:29:14 -0700303 if firstLabel == "" {
304 firstLabel = label
305 }
306 if _, exists := locationLabels[label]; !exists {
Colin Crossd11cf622021-03-23 22:30:35 -0700307 locationLabels[label] = loc
Colin Cross08f15ab2018-10-04 23:29:14 -0700308 } else {
Anton Hansson7cd41e52021-10-08 16:13:10 +0100309 ctx.ModuleErrorf("multiple locations for label %q: %q and %q (do you have duplicate srcs entries?)",
Colin Crossd11cf622021-03-23 22:30:35 -0700310 label, locationLabels[label], loc)
Colin Cross08f15ab2018-10-04 23:29:14 -0700311 }
312 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700313
Colin Crossba9e4032020-11-24 16:32:22 -0800314 var tools android.Paths
315 var packagedTools []android.PackagingSpec
Colin Cross6f080df2016-11-04 15:32:58 -0700316 if len(g.properties.Tools) > 0 {
Colin Crossba71a3f2019-03-18 12:12:48 -0700317 seenTools := make(map[string]bool)
318
Colin Cross35143d02017-11-16 00:11:20 -0800319 ctx.VisitDirectDepsBlueprint(func(module blueprint.Module) {
Colin Cross08f15ab2018-10-04 23:29:14 -0700320 switch tag := ctx.OtherModuleDependencyTag(module).(type) {
321 case hostToolDependencyTag:
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700322 tool := ctx.OtherModuleName(module)
Martin Stjernholmdbd814d2022-01-12 23:18:30 +0000323 if m, ok := module.(android.Module); ok {
324 // Necessary to retrieve any prebuilt replacement for the tool, since
325 // toolDepsMutator runs too late for the prebuilt mutators to have
326 // replaced the dependency.
327 module = android.PrebuiltGetPreferred(ctx, m)
328 }
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700329
Colin Crossba9e4032020-11-24 16:32:22 -0800330 switch t := module.(type) {
331 case android.HostToolProvider:
332 // A HostToolProvider provides the path to a tool, which will be copied
333 // into the sandbox.
Colin Cross35143d02017-11-16 00:11:20 -0800334 if !t.(android.Module).Enabled() {
Colin Cross6510f912017-11-29 00:27:14 -0800335 if ctx.Config().AllowMissingDependencies() {
Colin Cross35143d02017-11-16 00:11:20 -0800336 ctx.AddMissingDependencies([]string{tool})
337 } else {
338 ctx.ModuleErrorf("depends on disabled module %q", tool)
339 }
Colin Crossba9e4032020-11-24 16:32:22 -0800340 return
Colin Cross35143d02017-11-16 00:11:20 -0800341 }
Colin Crossba9e4032020-11-24 16:32:22 -0800342 path := t.HostToolPath()
343 if !path.Valid() {
344 ctx.ModuleErrorf("host tool %q missing output file", tool)
345 return
346 }
347 if specs := t.TransitivePackagingSpecs(); specs != nil {
348 // If the HostToolProvider has PackgingSpecs, which are definitions of the
349 // required relative locations of the tool and its dependencies, use those
350 // instead. They will be copied to those relative locations in the sbox
351 // sandbox.
352 packagedTools = append(packagedTools, specs...)
353 // Assume that the first PackagingSpec of the module is the tool.
Colin Crossd11cf622021-03-23 22:30:35 -0700354 addLocationLabel(tag.label, packagedToolLocation{specs[0]})
Colin Crossba9e4032020-11-24 16:32:22 -0800355 } else {
356 tools = append(tools, path.Path())
Colin Crossd11cf622021-03-23 22:30:35 -0700357 addLocationLabel(tag.label, toolLocation{android.Paths{path.Path()}})
Colin Crossba9e4032020-11-24 16:32:22 -0800358 }
359 case bootstrap.GoBinaryTool:
360 // A GoBinaryTool provides the install path to a tool, which will be copied.
Colin Crossa44551f2021-10-25 15:36:21 -0700361 p := android.PathForGoBinary(ctx, t)
362 tools = append(tools, p)
363 addLocationLabel(tag.label, toolLocation{android.Paths{p}})
Colin Crossba9e4032020-11-24 16:32:22 -0800364 default:
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700365 ctx.ModuleErrorf("%q is not a host tool provider", tool)
Colin Crossba9e4032020-11-24 16:32:22 -0800366 return
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700367 }
368
Colin Crossba9e4032020-11-24 16:32:22 -0800369 seenTools[tag.label] = true
Colin Crossd350ecd2015-04-28 13:25:36 -0700370 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700371 })
Colin Crossba71a3f2019-03-18 12:12:48 -0700372
373 // If AllowMissingDependencies is enabled, the build will not have stopped when
374 // AddFarVariationDependencies was called on a missing tool, which will result in nonsensical
Liz Kammer20ebfb42020-07-28 11:32:07 -0700375 // "cmd: unknown location label ..." errors later. Add a placeholder file to the local label.
376 // The command that uses this placeholder file will never be executed because the rule will be
377 // replaced with an android.Error rule reporting the missing dependencies.
Colin Crossba71a3f2019-03-18 12:12:48 -0700378 if ctx.Config().AllowMissingDependencies() {
379 for _, tool := range g.properties.Tools {
380 if !seenTools[tool] {
Colin Crossd11cf622021-03-23 22:30:35 -0700381 addLocationLabel(tool, errorLocation{"***missing tool " + tool + "***"})
Colin Crossba71a3f2019-03-18 12:12:48 -0700382 }
383 }
384 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700385 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700386
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700387 if ctx.Failed() {
388 return
389 }
390
Colin Cross08f15ab2018-10-04 23:29:14 -0700391 for _, toolFile := range g.properties.Tool_files {
Colin Cross8a497952019-03-05 22:25:09 -0800392 paths := android.PathsForModuleSrc(ctx, []string{toolFile})
Colin Crossba9e4032020-11-24 16:32:22 -0800393 tools = append(tools, paths...)
Colin Crossd11cf622021-03-23 22:30:35 -0700394 addLocationLabel(toolFile, toolLocation{paths})
Colin Cross08f15ab2018-10-04 23:29:14 -0700395 }
396
Liz Kammer619be462022-01-28 15:13:39 -0500397 includeDirInPaths := ctx.DeviceConfig().BuildBrokenInputDir(g.Name())
Colin Cross08f15ab2018-10-04 23:29:14 -0700398 var srcFiles android.Paths
399 for _, in := range g.properties.Srcs {
Liz Kammer619be462022-01-28 15:13:39 -0500400 paths, missingDeps := android.PathsAndMissingDepsRelativeToModuleSourceDir(android.SourceInput{
401 Context: ctx, Paths: []string{in}, ExcludePaths: g.properties.Exclude_srcs, IncludeDirs: includeDirInPaths,
402 })
Colin Crossba71a3f2019-03-18 12:12:48 -0700403 if len(missingDeps) > 0 {
404 if !ctx.Config().AllowMissingDependencies() {
405 panic(fmt.Errorf("should never get here, the missing dependencies %q should have been reported in DepsMutator",
406 missingDeps))
407 }
408
409 // If AllowMissingDependencies is enabled, the build will not have stopped when
410 // the dependency was added on a missing SourceFileProducer module, which will result in nonsensical
Liz Kammer20ebfb42020-07-28 11:32:07 -0700411 // "cmd: label ":..." has no files" errors later. Add a placeholder file to the local label.
412 // The command that uses this placeholder file will never be executed because the rule will be
413 // replaced with an android.Error rule reporting the missing dependencies.
Colin Crossba71a3f2019-03-18 12:12:48 -0700414 ctx.AddMissingDependencies(missingDeps)
Colin Crossd11cf622021-03-23 22:30:35 -0700415 addLocationLabel(in, errorLocation{"***missing srcs " + in + "***"})
Colin Crossba71a3f2019-03-18 12:12:48 -0700416 } else {
417 srcFiles = append(srcFiles, paths...)
Colin Crossd11cf622021-03-23 22:30:35 -0700418 addLocationLabel(in, inputLocation{paths})
Colin Crossba71a3f2019-03-18 12:12:48 -0700419 }
Colin Cross08f15ab2018-10-04 23:29:14 -0700420 }
421
Colin Cross1a527682019-09-23 15:55:30 -0700422 var copyFrom android.Paths
423 var outputFiles android.WritablePaths
424 var zipArgs strings.Builder
Colin Cross08f15ab2018-10-04 23:29:14 -0700425
Colin Crossf3bfd022021-09-27 15:15:06 -0700426 cmd := String(g.properties.Cmd)
427 if g.CmdModifier != nil {
428 cmd = g.CmdModifier(ctx, cmd)
429 }
430
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500431 // Generate tasks, either from genrule or gensrcs.
Colin Crossf3bfd022021-09-27 15:15:06 -0700432 for _, task := range g.taskGenerator(ctx, cmd, srcFiles) {
Colin Cross3d680512020-11-13 16:23:53 -0800433 if len(task.out) == 0 {
434 ctx.ModuleErrorf("must have at least one output file")
435 return
Colin Cross85a2e892018-07-09 09:45:06 -0700436 }
437
Colin Crossf1a035e2020-11-16 17:32:30 -0800438 // Pick a unique path outside the task.genDir for the sbox manifest textproto,
439 // a unique rule name, and the user-visible description.
440 manifestName := "genrule.sbox.textproto"
441 desc := "generate"
442 name := "generator"
443 if task.shards > 0 {
444 manifestName = "genrule_" + strconv.Itoa(task.shard) + ".sbox.textproto"
445 desc += " " + strconv.Itoa(task.shard)
446 name += strconv.Itoa(task.shard)
447 } else if len(task.out) == 1 {
448 desc += " " + task.out[0].Base()
449 }
450
451 manifestPath := android.PathForModuleOut(ctx, manifestName)
452
453 // Use a RuleBuilder to create a rule that runs the command inside an sbox sandbox.
Colin Crossba9e4032020-11-24 16:32:22 -0800454 rule := android.NewRuleBuilder(pctx, ctx).Sbox(task.genDir, manifestPath).SandboxTools()
Colin Crossf1a035e2020-11-16 17:32:30 -0800455 cmd := rule.Command()
456
Colin Cross3d680512020-11-13 16:23:53 -0800457 for _, out := range task.out {
Colin Crossd11cf622021-03-23 22:30:35 -0700458 addLocationLabel(out.Rel(), outputLocation{out})
Colin Cross3d680512020-11-13 16:23:53 -0800459 }
460
Colin Cross1a527682019-09-23 15:55:30 -0700461 referencedDepfile := false
462
Colin Cross3d680512020-11-13 16:23:53 -0800463 rawCommand, err := android.Expand(task.cmd, func(name string) (string, error) {
Colin Cross1a527682019-09-23 15:55:30 -0700464 // report the error directly without returning an error to android.Expand to catch multiple errors in a
465 // single run
Colin Cross3d680512020-11-13 16:23:53 -0800466 reportError := func(fmt string, args ...interface{}) (string, error) {
Colin Cross1a527682019-09-23 15:55:30 -0700467 ctx.PropertyErrorf("cmd", fmt, args...)
Colin Cross3d680512020-11-13 16:23:53 -0800468 return "SOONG_ERROR", nil
Colin Cross6f080df2016-11-04 15:32:58 -0700469 }
Colin Cross1a527682019-09-23 15:55:30 -0700470
471 switch name {
472 case "location":
473 if len(g.properties.Tools) == 0 && len(g.properties.Tool_files) == 0 {
474 return reportError("at least one `tools` or `tool_files` is required if $(location) is used")
Colin Cross6f080df2016-11-04 15:32:58 -0700475 }
Colin Crossd11cf622021-03-23 22:30:35 -0700476 loc := locationLabels[firstLabel]
477 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700478 if len(paths) == 0 {
479 return reportError("default label %q has no files", firstLabel)
480 } else if len(paths) > 1 {
481 return reportError("default label %q has multiple files, use $(locations %s) to reference it",
482 firstLabel, firstLabel)
Colin Cross08f15ab2018-10-04 23:29:14 -0700483 }
Colin Crossd11cf622021-03-23 22:30:35 -0700484 return paths[0], nil
Colin Cross1a527682019-09-23 15:55:30 -0700485 case "in":
Colin Crossd11cf622021-03-23 22:30:35 -0700486 return strings.Join(cmd.PathsForInputs(srcFiles), " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700487 case "out":
Colin Cross3d680512020-11-13 16:23:53 -0800488 var sandboxOuts []string
489 for _, out := range task.out {
Colin Crossf1a035e2020-11-16 17:32:30 -0800490 sandboxOuts = append(sandboxOuts, cmd.PathForOutput(out))
Colin Cross3d680512020-11-13 16:23:53 -0800491 }
492 return strings.Join(sandboxOuts, " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700493 case "depfile":
494 referencedDepfile = true
495 if !Bool(g.properties.Depfile) {
496 return reportError("$(depfile) used without depfile property")
497 }
Colin Cross3d680512020-11-13 16:23:53 -0800498 return "__SBOX_DEPFILE__", nil
Colin Cross1a527682019-09-23 15:55:30 -0700499 case "genDir":
Colin Crossf1a035e2020-11-16 17:32:30 -0800500 return cmd.PathForOutput(task.genDir), nil
Colin Cross1a527682019-09-23 15:55:30 -0700501 default:
502 if strings.HasPrefix(name, "location ") {
503 label := strings.TrimSpace(strings.TrimPrefix(name, "location "))
Colin Crossd11cf622021-03-23 22:30:35 -0700504 if loc, ok := locationLabels[label]; ok {
505 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700506 if len(paths) == 0 {
507 return reportError("label %q has no files", label)
508 } else if len(paths) > 1 {
509 return reportError("label %q has multiple files, use $(locations %s) to reference it",
510 label, label)
511 }
Colin Cross3d680512020-11-13 16:23:53 -0800512 return paths[0], nil
Colin Cross1a527682019-09-23 15:55:30 -0700513 } else {
Anton Hanssonbebf5262022-02-23 11:42:38 +0000514 return reportError("unknown location label %q is not in srcs, out, tools or tool_files.", label)
Colin Cross1a527682019-09-23 15:55:30 -0700515 }
516 } else if strings.HasPrefix(name, "locations ") {
517 label := strings.TrimSpace(strings.TrimPrefix(name, "locations "))
Colin Crossd11cf622021-03-23 22:30:35 -0700518 if loc, ok := locationLabels[label]; ok {
519 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700520 if len(paths) == 0 {
521 return reportError("label %q has no files", label)
522 }
Colin Cross3d680512020-11-13 16:23:53 -0800523 return strings.Join(paths, " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700524 } else {
Anton Hanssonbebf5262022-02-23 11:42:38 +0000525 return reportError("unknown locations label %q is not in srcs, out, tools or tool_files.", label)
Colin Cross1a527682019-09-23 15:55:30 -0700526 }
527 } else {
528 return reportError("unknown variable '$(%s)'", name)
529 }
Colin Cross6f080df2016-11-04 15:32:58 -0700530 }
Colin Cross1a527682019-09-23 15:55:30 -0700531 })
532
533 if err != nil {
534 ctx.PropertyErrorf("cmd", "%s", err.Error())
535 return
Colin Cross6f080df2016-11-04 15:32:58 -0700536 }
Colin Cross6f080df2016-11-04 15:32:58 -0700537
Colin Cross1a527682019-09-23 15:55:30 -0700538 if Bool(g.properties.Depfile) && !referencedDepfile {
539 ctx.PropertyErrorf("cmd", "specified depfile=true but did not include a reference to '${depfile}' in cmd")
540 return
541 }
Colin Cross1a527682019-09-23 15:55:30 -0700542 g.rawCommands = append(g.rawCommands, rawCommand)
Bill Peckhamc087be12020-02-13 15:55:10 -0800543
Colin Cross3d680512020-11-13 16:23:53 -0800544 cmd.Text(rawCommand)
545 cmd.ImplicitOutputs(task.out)
546 cmd.Implicits(task.in)
Colin Crossba9e4032020-11-24 16:32:22 -0800547 cmd.ImplicitTools(tools)
548 cmd.ImplicitTools(task.extraTools)
549 cmd.ImplicitPackagedTools(packagedTools)
Colin Cross3d680512020-11-13 16:23:53 -0800550 if Bool(g.properties.Depfile) {
551 cmd.ImplicitDepFile(task.depFile)
552 }
553
554 // Create the rule to run the genrule command inside sbox.
Colin Crossf1a035e2020-11-16 17:32:30 -0800555 rule.Build(name, desc)
Colin Cross1a527682019-09-23 15:55:30 -0700556
557 if len(task.copyTo) > 0 {
Colin Cross3d680512020-11-13 16:23:53 -0800558 // If copyTo is set, multiple shards need to be copied into a single directory.
559 // task.out contains the per-shard paths, and copyTo contains the corresponding
560 // final path. The files need to be copied into the final directory by a
561 // single rule so it can remove the directory before it starts to ensure no
562 // old files remain. zipsync already does this, so build up zipArgs that
563 // zip all the per-shard directories into a single zip.
Colin Cross1a527682019-09-23 15:55:30 -0700564 outputFiles = append(outputFiles, task.copyTo...)
565 copyFrom = append(copyFrom, task.out.Paths()...)
566 zipArgs.WriteString(" -C " + task.genDir.String())
567 zipArgs.WriteString(android.JoinWithPrefix(task.out.Strings(), " -f "))
568 } else {
569 outputFiles = append(outputFiles, task.out...)
570 }
Colin Cross6f080df2016-11-04 15:32:58 -0700571 }
572
Colin Cross1a527682019-09-23 15:55:30 -0700573 if len(copyFrom) > 0 {
Colin Cross3d680512020-11-13 16:23:53 -0800574 // Create a rule that zips all the per-shard directories into a single zip and then
575 // uses zipsync to unzip it into the final directory.
Colin Cross1a527682019-09-23 15:55:30 -0700576 ctx.Build(pctx, android.BuildParams{
Colin Crossf1885962020-11-20 15:28:30 -0800577 Rule: gensrcsMerge,
578 Implicits: copyFrom,
579 Outputs: outputFiles,
580 Description: "merge shards",
Colin Cross1a527682019-09-23 15:55:30 -0700581 Args: map[string]string{
582 "zipArgs": zipArgs.String(),
583 "tmpZip": android.PathForModuleGen(ctx, g.subDir+".zip").String(),
584 "genDir": android.PathForModuleGen(ctx, g.subDir).String(),
585 },
586 })
Colin Cross85a2e892018-07-09 09:45:06 -0700587 }
588
Colin Cross1a527682019-09-23 15:55:30 -0700589 g.outputFiles = outputFiles.Paths()
Chris Parsonsf874e462022-05-10 13:50:12 -0400590}
Jeff Gastonefc1b412017-03-29 17:29:06 -0700591
Chris Parsonsf874e462022-05-10 13:50:12 -0400592func (g *Module) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Vinh Tran140d5882022-06-10 14:23:27 -0400593 // Allowlist genrule to use depfile until we have a solution to remove it.
594 // TODO(b/235582219): Remove allowlist for genrule
595 if ctx.ModuleType() == "gensrcs" &&
596 !ctx.DeviceConfig().BuildBrokenDepfile() &&
597 Bool(g.properties.Depfile) {
598 ctx.PropertyErrorf(
599 "depfile",
600 "Deprecated to ensure the module type is convertible to Bazel. "+
601 "Try specifying the dependencies explicitly so that there is no need to use depfile. "+
602 "If not possible, the escape hatch is to use BUILD_BROKEN_DEPFILE to bypass the error.")
603 }
604
Chris Parsonsf874e462022-05-10 13:50:12 -0400605 g.generateCommonBuildActions(ctx)
606
607 // For <= 6 outputs, just embed those directly in the users. Right now, that covers >90% of
608 // the genrules on AOSP. That will make things simpler to look at the graph in the common
609 // case. For larger sets of outputs, inject a phony target in between to limit ninja file
610 // growth.
611 if len(g.outputFiles) <= 6 {
612 g.outputDeps = g.outputFiles
613 } else {
614 phonyFile := android.PathForModuleGen(ctx, "genrule-phony")
615 ctx.Build(pctx, android.BuildParams{
616 Rule: blueprint.Phony,
617 Output: phonyFile,
618 Inputs: g.outputFiles,
619 })
620 g.outputDeps = android.Paths{phonyFile}
Jeff Gaston02a684b2017-10-27 14:59:27 -0700621 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400622}
623
624func (g *Module) QueueBazelCall(ctx android.BaseModuleContext) {
625 bazelCtx := ctx.Config().BazelContext
626 bazelCtx.QueueBazelRequest(g.GetBazelLabel(ctx, g), cquery.GetOutputFiles, android.GetConfigKey(ctx))
627}
628
629func (g *Module) IsMixedBuildSupported(ctx android.BaseModuleContext) bool {
630 return true
Colin Crossd350ecd2015-04-28 13:25:36 -0700631}
Colin Crossd350ecd2015-04-28 13:25:36 -0700632
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700633// Collect information for opening IDE project files in java/jdeps.go.
634func (g *Module) IDEInfo(dpInfo *android.IdeInfo) {
635 dpInfo.Srcs = append(dpInfo.Srcs, g.Srcs().Strings()...)
636 for _, src := range g.properties.Srcs {
637 if strings.HasPrefix(src, ":") {
638 src = strings.Trim(src, ":")
639 dpInfo.Deps = append(dpInfo.Deps, src)
640 }
641 }
bralee1fbf4402020-05-21 10:11:59 +0800642 dpInfo.Paths = append(dpInfo.Paths, g.modulePaths...)
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700643}
644
Colin Crossa4ad2b02019-03-18 22:15:32 -0700645func (g *Module) AndroidMk() android.AndroidMkData {
646 return android.AndroidMkData{
Anton Hansson72f18492020-10-30 16:34:45 +0000647 Class: "ETC",
Colin Crossa4ad2b02019-03-18 22:15:32 -0700648 OutputFile: android.OptionalPathForPath(g.outputFiles[0]),
649 SubName: g.subName,
650 Extra: []android.AndroidMkExtraFunc{
651 func(w io.Writer, outputFile android.Path) {
Anton Hansson72f18492020-10-30 16:34:45 +0000652 fmt.Fprintln(w, "LOCAL_UNINSTALLABLE_MODULE := true")
Colin Crossa4ad2b02019-03-18 22:15:32 -0700653 },
654 },
655 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
656 android.WriteAndroidMkData(w, data)
657 if data.SubName != "" {
658 fmt.Fprintln(w, ".PHONY:", name)
659 fmt.Fprintln(w, name, ":", name+g.subName)
660 }
661 },
662 }
663}
664
Jiyong Park45bf82e2020-12-15 22:29:02 +0900665var _ android.ApexModule = (*Module)(nil)
666
667// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -0700668func (g *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
669 sdkVersion android.ApiLevel) error {
Jooyung Han749dc692020-04-15 11:03:39 +0900670 // Because generated outputs are checked by client modules(e.g. cc_library, ...)
671 // we can safely ignore the check here.
672 return nil
673}
674
Jeff Gaston437d23c2017-11-08 12:38:00 -0800675func generatorFactory(taskGenerator taskFunc, props ...interface{}) *Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700676 module := &Module{
Jeff Gaston437d23c2017-11-08 12:38:00 -0800677 taskGenerator: taskGenerator,
Colin Crossd350ecd2015-04-28 13:25:36 -0700678 }
679
Colin Cross36242852017-06-23 15:06:31 -0700680 module.AddProperties(props...)
681 module.AddProperties(&module.properties)
Colin Crossd350ecd2015-04-28 13:25:36 -0700682
Colin Cross7228ecd2019-11-18 16:00:16 -0800683 module.ImageInterface = noopImageInterface{}
684
Colin Cross36242852017-06-23 15:06:31 -0700685 return module
Colin Crossd350ecd2015-04-28 13:25:36 -0700686}
687
Colin Cross7228ecd2019-11-18 16:00:16 -0800688type noopImageInterface struct{}
689
690func (x noopImageInterface) ImageMutatorBegin(android.BaseModuleContext) {}
691func (x noopImageInterface) CoreVariantNeeded(android.BaseModuleContext) bool { return false }
Yifan Hong1b3348d2020-01-21 15:53:22 -0800692func (x noopImageInterface) RamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700693func (x noopImageInterface) VendorRamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Inseob Kim08758f02021-04-08 21:13:22 +0900694func (x noopImageInterface) DebugRamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Colin Cross7228ecd2019-11-18 16:00:16 -0800695func (x noopImageInterface) RecoveryVariantNeeded(android.BaseModuleContext) bool { return false }
696func (x noopImageInterface) ExtraImageVariations(ctx android.BaseModuleContext) []string { return nil }
697func (x noopImageInterface) SetImageVariation(ctx android.BaseModuleContext, variation string, module android.Module) {
698}
699
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700700func NewGenSrcs() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700701 properties := &genSrcsProperties{}
702
Colin Crossf1885962020-11-20 15:28:30 -0800703 // finalSubDir is the name of the subdirectory that output files will be generated into.
704 // It is used so that per-shard directories can be placed alongside it an then finally
705 // merged into it.
706 const finalSubDir = "gensrcs"
707
Colin Cross1a527682019-09-23 15:55:30 -0700708 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Colin Cross1a527682019-09-23 15:55:30 -0700709 shardSize := defaultShardSize
710 if s := properties.Shard_size; s != nil {
711 shardSize = int(*s)
712 }
Jeff Gaston437d23c2017-11-08 12:38:00 -0800713
Colin Crossf1885962020-11-20 15:28:30 -0800714 // gensrcs rules can easily hit command line limits by repeating the command for
715 // every input file. Shard the input files into groups.
Colin Cross1a527682019-09-23 15:55:30 -0700716 shards := android.ShardPaths(srcFiles, shardSize)
717 var generateTasks []generateTask
Colin Crossbaccf5b2018-02-21 14:07:48 -0800718
Colin Cross1a527682019-09-23 15:55:30 -0700719 for i, shard := range shards {
720 var commands []string
721 var outFiles android.WritablePaths
Colin Cross3ea4eb82020-11-24 13:07:27 -0800722 var commandDepFiles []string
Colin Cross1a527682019-09-23 15:55:30 -0700723 var copyTo android.WritablePaths
Colin Cross1a527682019-09-23 15:55:30 -0700724
Colin Crossf1885962020-11-20 15:28:30 -0800725 // When sharding is enabled (i.e. len(shards) > 1), the sbox rules for each
726 // shard will be write to their own directories and then be merged together
727 // into finalSubDir. If sharding is not enabled (i.e. len(shards) == 1),
728 // the sbox rule will write directly to finalSubDir.
729 genSubDir := finalSubDir
Colin Cross1a527682019-09-23 15:55:30 -0700730 if len(shards) > 1 {
Colin Crossf1885962020-11-20 15:28:30 -0800731 genSubDir = strconv.Itoa(i)
Jeff Gaston437d23c2017-11-08 12:38:00 -0800732 }
733
Colin Crossf1885962020-11-20 15:28:30 -0800734 genDir := android.PathForModuleGen(ctx, genSubDir)
Colin Crossf1a035e2020-11-16 17:32:30 -0800735 // TODO(ccross): this RuleBuilder is a hack to be able to call
736 // rule.Command().PathForOutput. Replace this with passing the rule into the
737 // generator.
Colin Crossba9e4032020-11-24 16:32:22 -0800738 rule := android.NewRuleBuilder(pctx, ctx).Sbox(genDir, nil).SandboxTools()
Jeff Gaston437d23c2017-11-08 12:38:00 -0800739
Colin Cross3ea4eb82020-11-24 13:07:27 -0800740 for _, in := range shard {
Colin Crossf1885962020-11-20 15:28:30 -0800741 outFile := android.GenPathWithExt(ctx, finalSubDir, in, String(properties.Output_extension))
742
743 // If sharding is enabled, then outFile is the path to the output file in
744 // the shard directory, and copyTo is the path to the output file in the
745 // final directory.
Colin Cross1a527682019-09-23 15:55:30 -0700746 if len(shards) > 1 {
Colin Crossf1885962020-11-20 15:28:30 -0800747 shardFile := android.GenPathWithExt(ctx, genSubDir, in, String(properties.Output_extension))
Colin Cross1a527682019-09-23 15:55:30 -0700748 copyTo = append(copyTo, outFile)
749 outFile = shardFile
750 }
751
752 outFiles = append(outFiles, outFile)
Colin Cross1a527682019-09-23 15:55:30 -0700753
Colin Crossf1885962020-11-20 15:28:30 -0800754 // pre-expand the command line to replace $in and $out with references to
755 // a single input and output file.
Colin Cross1a527682019-09-23 15:55:30 -0700756 command, err := android.Expand(rawCommand, func(name string) (string, error) {
757 switch name {
758 case "in":
759 return in.String(), nil
760 case "out":
Colin Crossf1a035e2020-11-16 17:32:30 -0800761 return rule.Command().PathForOutput(outFile), nil
Colin Cross3ea4eb82020-11-24 13:07:27 -0800762 case "depfile":
763 // Generate a depfile for each output file. Store the list for
764 // later in order to combine them all into a single depfile.
Colin Crossf1a035e2020-11-16 17:32:30 -0800765 depFile := rule.Command().PathForOutput(outFile.ReplaceExtension(ctx, "d"))
Colin Cross3ea4eb82020-11-24 13:07:27 -0800766 commandDepFiles = append(commandDepFiles, depFile)
767 return depFile, nil
Colin Cross1a527682019-09-23 15:55:30 -0700768 default:
769 return "$(" + name + ")", nil
770 }
771 })
772 if err != nil {
773 ctx.PropertyErrorf("cmd", err.Error())
774 }
775
776 // escape the command in case for example it contains '#', an odd number of '"', etc
777 command = fmt.Sprintf("bash -c %v", proptools.ShellEscape(command))
778 commands = append(commands, command)
779 }
780 fullCommand := strings.Join(commands, " && ")
781
Colin Cross3ea4eb82020-11-24 13:07:27 -0800782 var outputDepfile android.WritablePath
783 var extraTools android.Paths
784 if len(commandDepFiles) > 0 {
785 // Each command wrote to a depfile, but ninja can only handle one
786 // depfile per rule. Use the dep_fixer tool at the end of the
787 // command to combine all the depfiles into a single output depfile.
788 outputDepfile = android.PathForModuleGen(ctx, genSubDir, "gensrcs.d")
789 depFixerTool := ctx.Config().HostToolPath(ctx, "dep_fixer")
790 fullCommand += fmt.Sprintf(" && %s -o $(depfile) %s",
Colin Crossd11cf622021-03-23 22:30:35 -0700791 rule.Command().PathForTool(depFixerTool),
Colin Crossba9e4032020-11-24 16:32:22 -0800792 strings.Join(commandDepFiles, " "))
Colin Cross3ea4eb82020-11-24 13:07:27 -0800793 extraTools = append(extraTools, depFixerTool)
794 }
795
Colin Cross1a527682019-09-23 15:55:30 -0700796 generateTasks = append(generateTasks, generateTask{
Colin Cross3ea4eb82020-11-24 13:07:27 -0800797 in: shard,
798 out: outFiles,
799 depFile: outputDepfile,
800 copyTo: copyTo,
801 genDir: genDir,
802 cmd: fullCommand,
803 shard: i,
804 shards: len(shards),
805 extraTools: extraTools,
Colin Cross1a527682019-09-23 15:55:30 -0700806 })
Jeff Gaston437d23c2017-11-08 12:38:00 -0800807 }
Colin Cross1a527682019-09-23 15:55:30 -0700808
809 return generateTasks
Colin Crossd350ecd2015-04-28 13:25:36 -0700810 }
811
Colin Cross1a527682019-09-23 15:55:30 -0700812 g := generatorFactory(taskGenerator, properties)
Colin Crossf1885962020-11-20 15:28:30 -0800813 g.subDir = finalSubDir
Colin Cross1a527682019-09-23 15:55:30 -0700814 return g
Colin Crossd350ecd2015-04-28 13:25:36 -0700815}
816
Colin Cross54190b32017-10-09 15:34:10 -0700817func GenSrcsFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700818 m := NewGenSrcs()
819 android.InitAndroidModule(m)
Vinh Tranb69e1ae2022-05-20 18:54:09 -0400820 android.InitBazelModule(m)
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700821 return m
822}
823
Colin Crossd350ecd2015-04-28 13:25:36 -0700824type genSrcsProperties struct {
Colin Cross7d5136f2015-05-11 13:39:40 -0700825 // extension that will be substituted for each output file
Nan Zhanga5e7cb42017-11-09 22:42:32 -0800826 Output_extension *string
Colin Cross1a527682019-09-23 15:55:30 -0700827
828 // maximum number of files that will be passed on a single command line.
829 Shard_size *int64
Colin Cross5049f022015-03-18 13:28:46 -0700830}
831
Vinh Tranb69e1ae2022-05-20 18:54:09 -0400832type bazelGensrcsAttributes struct {
833 Srcs bazel.LabelListAttribute
834 Output_extension *string
835 Tools bazel.LabelListAttribute
836 Cmd string
837}
838
Evgenii Stepanovf47c90d2020-12-02 18:55:09 -0800839const defaultShardSize = 50
Colin Cross1a527682019-09-23 15:55:30 -0700840
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700841func NewGenRule() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700842 properties := &genRuleProperties{}
Colin Cross5049f022015-03-18 13:28:46 -0700843
Colin Cross1a527682019-09-23 15:55:30 -0700844 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700845 outs := make(android.WritablePaths, len(properties.Out))
Colin Cross3d680512020-11-13 16:23:53 -0800846 var depFile android.WritablePath
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700847 for i, out := range properties.Out {
Colin Cross3d680512020-11-13 16:23:53 -0800848 outPath := android.PathForModuleGen(ctx, out)
849 if i == 0 {
850 depFile = outPath.ReplaceExtension(ctx, "d")
851 }
852 outs[i] = outPath
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700853 }
Colin Cross1a527682019-09-23 15:55:30 -0700854 return []generateTask{{
Colin Cross3d680512020-11-13 16:23:53 -0800855 in: srcFiles,
856 out: outs,
857 depFile: depFile,
858 genDir: android.PathForModuleGen(ctx),
859 cmd: rawCommand,
Colin Cross1a527682019-09-23 15:55:30 -0700860 }}
Colin Cross5049f022015-03-18 13:28:46 -0700861 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700862
Jeff Gaston437d23c2017-11-08 12:38:00 -0800863 return generatorFactory(taskGenerator, properties)
Colin Cross5049f022015-03-18 13:28:46 -0700864}
865
Colin Cross54190b32017-10-09 15:34:10 -0700866func GenRuleFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700867 m := NewGenRule()
868 android.InitAndroidModule(m)
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800869 android.InitDefaultableModule(m)
Liz Kammerea6666f2021-02-17 10:17:28 -0500870 android.InitBazelModule(m)
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700871 return m
872}
873
Colin Crossd350ecd2015-04-28 13:25:36 -0700874type genRuleProperties struct {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700875 // names of the output files that will be generated
Colin Crossef354482018-10-23 11:27:50 -0700876 Out []string `android:"arch_variant"`
Colin Cross5049f022015-03-18 13:28:46 -0700877}
Nan Zhangea568a42017-11-08 21:20:04 -0800878
Jingwen Chen316e07c2020-12-14 09:09:52 -0500879type bazelGenruleAttributes struct {
Jingwen Chen07027912021-03-15 06:02:43 -0400880 Srcs bazel.LabelListAttribute
Jingwen Chen316e07c2020-12-14 09:09:52 -0500881 Outs []string
Jingwen Chen07027912021-03-15 06:02:43 -0400882 Tools bazel.LabelListAttribute
Jingwen Chen316e07c2020-12-14 09:09:52 -0500883 Cmd string
884}
885
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400886// ConvertWithBp2build converts a Soong module -> Bazel target.
887func (m *Module) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
Liz Kammer356f7d42021-01-26 09:18:53 -0500888 // Bazel only has the "tools" attribute.
Jingwen Chen07027912021-03-15 06:02:43 -0400889 tools_prop := android.BazelLabelForModuleDeps(ctx, m.properties.Tools)
890 tool_files_prop := android.BazelLabelForModuleSrc(ctx, m.properties.Tool_files)
891 tools_prop.Append(tool_files_prop)
Liz Kammer356f7d42021-01-26 09:18:53 -0500892
Jingwen Chen07027912021-03-15 06:02:43 -0400893 tools := bazel.MakeLabelListAttribute(tools_prop)
894 srcs := bazel.MakeLabelListAttribute(android.BazelLabelForModuleSrc(ctx, m.properties.Srcs))
Liz Kammer356f7d42021-01-26 09:18:53 -0500895
896 var allReplacements bazel.LabelList
Jingwen Chen07027912021-03-15 06:02:43 -0400897 allReplacements.Append(tools.Value)
898 allReplacements.Append(srcs.Value)
Liz Kammer356f7d42021-01-26 09:18:53 -0500899
900 // Replace in and out variables with $< and $@
901 var cmd string
902 if m.properties.Cmd != nil {
Vinh Tranb69e1ae2022-05-20 18:54:09 -0400903 if ctx.ModuleType() == "gensrcs" {
904 cmd = strings.ReplaceAll(*m.properties.Cmd, "$(in)", "$(SRC)")
905 cmd = strings.ReplaceAll(cmd, "$(out)", "$(OUT)")
906 } else {
907 cmd = strings.Replace(*m.properties.Cmd, "$(in)", "$(SRCS)", -1)
908 cmd = strings.Replace(cmd, "$(out)", "$(OUTS)", -1)
909 }
910
Wei Libcd39942021-09-16 23:57:28 +0000911 genDir := "$(GENDIR)"
Sam Delmericocd1b80f2022-01-11 21:55:46 +0000912 if t := ctx.ModuleType(); t == "cc_genrule" || t == "java_genrule" || t == "java_genrule_host" {
Wei Libcd39942021-09-16 23:57:28 +0000913 genDir = "$(RULEDIR)"
914 }
915 cmd = strings.Replace(cmd, "$(genDir)", genDir, -1)
Jingwen Chen07027912021-03-15 06:02:43 -0400916 if len(tools.Value.Includes) > 0 {
917 cmd = strings.Replace(cmd, "$(location)", fmt.Sprintf("$(location %s)", tools.Value.Includes[0].Label), -1)
918 cmd = strings.Replace(cmd, "$(locations)", fmt.Sprintf("$(locations %s)", tools.Value.Includes[0].Label), -1)
Liz Kammer356f7d42021-01-26 09:18:53 -0500919 }
920 for _, l := range allReplacements.Includes {
Jingwen Chen38e62642021-04-19 05:00:15 +0000921 bpLoc := fmt.Sprintf("$(location %s)", l.OriginalModuleName)
922 bpLocs := fmt.Sprintf("$(locations %s)", l.OriginalModuleName)
Liz Kammer356f7d42021-01-26 09:18:53 -0500923 bazelLoc := fmt.Sprintf("$(location %s)", l.Label)
924 bazelLocs := fmt.Sprintf("$(locations %s)", l.Label)
925 cmd = strings.Replace(cmd, bpLoc, bazelLoc, -1)
926 cmd = strings.Replace(cmd, bpLocs, bazelLocs, -1)
927 }
928 }
929
Vinh Tranb69e1ae2022-05-20 18:54:09 -0400930 if ctx.ModuleType() == "gensrcs" {
931 // The Output_extension prop is not in an immediately accessible field
932 // in the Module struct, so use GetProperties and cast it
933 // to the known struct prop.
934 var outputExtension *string
935 for _, propIntf := range m.GetProperties() {
936 if props, ok := propIntf.(*genSrcsProperties); ok {
937 outputExtension = props.Output_extension
938 break
939 }
Liz Kammer356f7d42021-01-26 09:18:53 -0500940 }
Vinh Tranb69e1ae2022-05-20 18:54:09 -0400941 props := bazel.BazelTargetModuleProperties{
942 Rule_class: "gensrcs",
943 Bzl_load_location: "//build/bazel/rules:gensrcs.bzl",
944 }
945 attrs := &bazelGensrcsAttributes{
946 Srcs: srcs,
947 Output_extension: outputExtension,
948 Cmd: cmd,
949 Tools: tools,
950 }
951 ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: m.Name()}, attrs)
952 } else {
953 // The Out prop is not in an immediately accessible field
954 // in the Module struct, so use GetProperties and cast it
955 // to the known struct prop.
956 var outs []string
957 for _, propIntf := range m.GetProperties() {
958 if props, ok := propIntf.(*genRuleProperties); ok {
959 outs = props.Out
960 break
961 }
962 }
963 attrs := &bazelGenruleAttributes{
964 Srcs: srcs,
965 Outs: outs,
966 Cmd: cmd,
967 Tools: tools,
968 }
969 props := bazel.BazelTargetModuleProperties{
970 Rule_class: "genrule",
971 }
972 ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: m.Name()}, attrs)
Liz Kammer356f7d42021-01-26 09:18:53 -0500973 }
Jingwen Chen316e07c2020-12-14 09:09:52 -0500974}
975
Nan Zhangea568a42017-11-08 21:20:04 -0800976var Bool = proptools.Bool
977var String = proptools.String
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800978
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800979// Defaults
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800980type Defaults struct {
981 android.ModuleBase
982 android.DefaultsModuleBase
983}
984
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800985func defaultsFactory() android.Module {
986 return DefaultsFactory()
987}
988
989func DefaultsFactory(props ...interface{}) android.Module {
990 module := &Defaults{}
991
992 module.AddProperties(props...)
993 module.AddProperties(
994 &generatorProperties{},
995 &genRuleProperties{},
996 )
997
998 android.InitDefaultsModule(module)
999
1000 return module
1001}