blob: fbda074838b21ccba738a8e3dd753c02308fb2b1 [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 Cross1a527682019-09-23 15:55:30 -070024 "strconv"
Colin Cross6f080df2016-11-04 15:32:58 -070025 "strings"
Dan Willemsen3f4539b2016-09-28 16:19:10 -070026
Colin Cross70b40592015-03-23 12:57:34 -070027 "github.com/google/blueprint"
Dan Willemsen8eded0a2017-09-13 16:07:44 -070028 "github.com/google/blueprint/bootstrap"
Nan Zhangea568a42017-11-08 21:20:04 -080029 "github.com/google/blueprint/proptools"
Colin Cross5049f022015-03-18 13:28:46 -070030
Colin Cross635c3b02016-05-18 15:37:25 -070031 "android/soong/android"
Colin Cross5049f022015-03-18 13:28:46 -070032)
33
Colin Cross463a90e2015-06-17 14:20:06 -070034func init() {
Colin Crosse9fe2942020-11-10 18:12:15 -080035 RegisterGenruleBuildComponents(android.InitRegistrationContext)
Martin Stjernholm710ec3a2020-01-16 15:12:04 +000036}
Jaewoong Jung98716bd2018-12-10 08:13:18 -080037
Paul Duffin672cb9f2021-03-03 02:30:37 +000038// Test fixture preparer that will register most genrule build components.
39//
40// Singletons and mutators should only be added here if they are needed for a majority of genrule
41// module types, otherwise they should be added under a separate preparer to allow them to be
42// selected only when needed to reduce test execution time.
43//
44// Module types do not have much of an overhead unless they are used so this should include as many
45// module types as possible. The exceptions are those module types that require mutators and/or
46// singletons in order to function in which case they should be kept together in a separate
47// preparer.
48var PrepareForTestWithGenRuleBuildComponents = android.GroupFixturePreparers(
49 android.FixtureRegisterWithContext(RegisterGenruleBuildComponents),
50)
51
52// Prepare a fixture to use all genrule module types, mutators and singletons fully.
53//
54// This should only be used by tests that want to run with as much of the build enabled as possible.
55var PrepareForIntegrationTestWithGenrule = android.GroupFixturePreparers(
56 PrepareForTestWithGenRuleBuildComponents,
57)
58
Colin Crosse9fe2942020-11-10 18:12:15 -080059func RegisterGenruleBuildComponents(ctx android.RegistrationContext) {
Martin Stjernholm710ec3a2020-01-16 15:12:04 +000060 ctx.RegisterModuleType("genrule_defaults", defaultsFactory)
61
62 ctx.RegisterModuleType("gensrcs", GenSrcsFactory)
63 ctx.RegisterModuleType("genrule", GenRuleFactory)
64
65 ctx.FinalDepsMutators(func(ctx android.RegisterMutatorsContext) {
66 ctx.BottomUp("genrule_tool_deps", toolDepsMutator).Parallel()
67 })
Liz Kammer356f7d42021-01-26 09:18:53 -050068}
69
Colin Cross5049f022015-03-18 13:28:46 -070070var (
Colin Cross635c3b02016-05-18 15:37:25 -070071 pctx = android.NewPackageContext("android/soong/genrule")
Colin Cross1a527682019-09-23 15:55:30 -070072
Alex Humesky29e3bbe2020-11-20 21:30:13 -050073 // Used by gensrcs when there is more than 1 shard to merge the outputs
74 // of each shard into a zip file.
Colin Cross1a527682019-09-23 15:55:30 -070075 gensrcsMerge = pctx.AndroidStaticRule("gensrcsMerge", blueprint.RuleParams{
76 Command: "${soongZip} -o ${tmpZip} @${tmpZip}.rsp && ${zipSync} -d ${genDir} ${tmpZip}",
77 CommandDeps: []string{"${soongZip}", "${zipSync}"},
78 Rspfile: "${tmpZip}.rsp",
79 RspfileContent: "${zipArgs}",
80 }, "tmpZip", "genDir", "zipArgs")
Colin Cross5049f022015-03-18 13:28:46 -070081)
82
Jeff Gastonefc1b412017-03-29 17:29:06 -070083func init() {
Dan Willemsenddf504c2019-08-09 16:21:29 -070084 pctx.Import("android/soong/android")
Colin Cross1a527682019-09-23 15:55:30 -070085
86 pctx.HostBinToolVariable("soongZip", "soong_zip")
87 pctx.HostBinToolVariable("zipSync", "zipsync")
Jeff Gastonefc1b412017-03-29 17:29:06 -070088}
89
Colin Cross5049f022015-03-18 13:28:46 -070090type SourceFileGenerator interface {
Colin Cross635c3b02016-05-18 15:37:25 -070091 GeneratedSourceFiles() android.Paths
Colin Cross5ed99c62016-11-22 12:55:55 -080092 GeneratedHeaderDirs() android.Paths
Dan Willemsen9da9d492018-02-21 18:28:18 -080093 GeneratedDeps() android.Paths
Colin Cross5049f022015-03-18 13:28:46 -070094}
95
Colin Crossfe17f6f2019-03-28 19:30:56 -070096// Alias for android.HostToolProvider
97// Deprecated: use android.HostToolProvider instead.
Colin Crossd350ecd2015-04-28 13:25:36 -070098type HostToolProvider interface {
Colin Crossfe17f6f2019-03-28 19:30:56 -070099 android.HostToolProvider
Colin Crossd350ecd2015-04-28 13:25:36 -0700100}
Colin Cross5049f022015-03-18 13:28:46 -0700101
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700102type hostToolDependencyTag struct {
103 blueprint.BaseDependencyTag
Colin Cross65cb3142021-12-10 23:05:02 +0000104 android.LicenseAnnotationToolchainDependencyTag
Colin Cross08f15ab2018-10-04 23:29:14 -0700105 label string
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700106}
Martin Stjernholmdbd814d2022-01-12 23:18:30 +0000107
108func (t hostToolDependencyTag) AllowDisabledModuleDependency(target android.Module) bool {
109 // Allow depending on a disabled module if it's replaced by a prebuilt
110 // counterpart. We get the prebuilt through android.PrebuiltGetPreferred in
111 // GenerateAndroidBuildActions.
112 return target.IsReplacedByPrebuilt()
113}
114
115var _ android.AllowDisabledModuleDependency = (*hostToolDependencyTag)(nil)
116
Colin Cross7d5136f2015-05-11 13:39:40 -0700117type generatorProperties struct {
Spandan Das93e95992021-07-29 18:26:39 +0000118 // The command to run on one or more input files. Cmd supports substitution of a few variables.
Jeff Gastonefc1b412017-03-29 17:29:06 -0700119 //
120 // Available variables for substitution:
121 //
Spandan Das93e95992021-07-29 18:26:39 +0000122 // $(location): the path to the first entry in tools or tool_files.
123 // $(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.
124 // $(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.
125 // $(in): one or more input files.
126 // $(out): a single output file.
127 // $(depfile): a file to which dependencies will be written, if the depfile property is set to true.
128 // $(genDir): the sandbox directory for this tool; contains $(out).
Colin Cross2296f5b2017-10-17 21:38:14 -0700129 // $$: a literal $
Nan Zhangea568a42017-11-08 21:20:04 -0800130 Cmd *string
Colin Cross7d5136f2015-05-11 13:39:40 -0700131
Colin Cross33bfb0a2016-11-21 17:23:08 -0800132 // Enable reading a file containing dependencies in gcc format after the command completes
Nan Zhangea568a42017-11-08 21:20:04 -0800133 Depfile *bool
Colin Cross33bfb0a2016-11-21 17:23:08 -0800134
Colin Cross6f080df2016-11-04 15:32:58 -0700135 // name of the modules (if any) that produces the host executable. Leave empty for
Colin Cross7d5136f2015-05-11 13:39:40 -0700136 // prebuilts or scripts that do not need a module to build them.
Colin Cross6f080df2016-11-04 15:32:58 -0700137 Tools []string
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700138
Sam Delmericof8775632023-08-14 23:45:41 +0000139 // Local files that are used by the tool
Colin Cross27b922f2019-03-04 22:35:41 -0800140 Tool_files []string `android:"path"`
Colin Cross5ed99c62016-11-22 12:55:55 -0800141
142 // List of directories to export generated headers from
143 Export_include_dirs []string
Colin Cross708c4242017-01-13 18:05:49 -0800144
145 // list of input files
Colin Cross27b922f2019-03-04 22:35:41 -0800146 Srcs []string `android:"path,arch_variant"`
Dan Willemseneefa0262018-11-17 14:01:18 -0800147
148 // input files to exclude
Colin Cross27b922f2019-03-04 22:35:41 -0800149 Exclude_srcs []string `android:"path,arch_variant"`
Justin Yun4da4ccc2023-07-06 10:56:29 +0900150
151 // Enable restat to update the output only if the output is changed
152 Write_if_changed *bool
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
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
LaMont Jonesafe7baf2024-01-09 22:47:39 +0000187
188 // Aconfig files for all transitive deps. Also exposed via TransitiveDeclarationsInfo
189 mergedAconfigFiles map[string]android.Paths
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 {
Liz Kammer81fec182023-06-09 13:33:45 -0400195 in android.Paths
196 out android.WritablePaths
197 depFile android.WritablePath
198 copyTo android.WritablePaths // For gensrcs to set on gensrcsMerge rule.
199 genDir android.WritablePath
200 extraTools android.Paths // dependencies on tools used by the generator
201 extraInputs map[string][]string
Colin Cross3ea4eb82020-11-24 13:07:27 -0800202
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500203 cmd string
204 // For gensrsc sharding.
Colin Cross3ea4eb82020-11-24 13:07:27 -0800205 shard int
206 shards int
Colin Crossd350ecd2015-04-28 13:25:36 -0700207}
208
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700209func (g *Module) GeneratedSourceFiles() android.Paths {
Colin Crossd350ecd2015-04-28 13:25:36 -0700210 return g.outputFiles
211}
212
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700213func (g *Module) Srcs() android.Paths {
Nan Zhange42777a2018-03-27 16:19:42 -0700214 return append(android.Paths{}, g.outputFiles...)
Colin Cross068e0fe2016-12-13 15:23:47 -0800215}
216
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700217func (g *Module) GeneratedHeaderDirs() android.Paths {
Colin Cross5ed99c62016-11-22 12:55:55 -0800218 return g.exportedIncludeDirs
Dan Willemsenb40aab62016-04-20 14:21:14 -0700219}
220
Dan Willemsen9da9d492018-02-21 18:28:18 -0800221func (g *Module) GeneratedDeps() android.Paths {
222 return g.outputDeps
223}
224
Jooyung Han8c7e3ed2021-06-28 17:35:58 +0900225func (g *Module) OutputFiles(tag string) (android.Paths, error) {
226 if tag == "" {
227 return append(android.Paths{}, g.outputFiles...), nil
228 }
229 // otherwise, tag should match one of outputs
230 for _, outputFile := range g.outputFiles {
231 if outputFile.Rel() == tag {
232 return android.Paths{outputFile}, nil
233 }
234 }
235 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
236}
237
238var _ android.SourceFileProducer = (*Module)(nil)
239var _ android.OutputFileProducer = (*Module)(nil)
240
Martin Stjernholm710ec3a2020-01-16 15:12:04 +0000241func toolDepsMutator(ctx android.BottomUpMutatorContext) {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700242 if g, ok := ctx.Module().(*Module); ok {
Colin Cross08f15ab2018-10-04 23:29:14 -0700243 for _, tool := range g.properties.Tools {
244 tag := hostToolDependencyTag{label: tool}
245 if m := android.SrcIsModule(tool); m != "" {
246 tool = m
247 }
Colin Cross0f7d2ef2019-10-16 11:03:10 -0700248 ctx.AddFarVariationDependencies(ctx.Config().BuildOSTarget.Variations(), tag, tool)
Colin Cross6362e272015-10-29 15:25:03 -0700249 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700250 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700251}
252
Chris Parsonsf874e462022-05-10 13:50:12 -0400253// generateCommonBuildActions contains build action generation logic
254// common to both the mixed build case and the legacy case of genrule processing.
255// To fully support genrule in mixed builds, the contents of this function should
256// approach zero; there should be no genrule action registration done directly
257// by Soong logic in the mixed-build case.
258func (g *Module) generateCommonBuildActions(ctx android.ModuleContext) {
Colin Crossa4ad2b02019-03-18 22:15:32 -0700259 g.subName = ctx.ModuleSubDir()
260
Colin Cross5ed99c62016-11-22 12:55:55 -0800261 if len(g.properties.Export_include_dirs) > 0 {
262 for _, dir := range g.properties.Export_include_dirs {
263 g.exportedIncludeDirs = append(g.exportedIncludeDirs,
Colin Cross1a527682019-09-23 15:55:30 -0700264 android.PathForModuleGen(ctx, g.subDir, ctx.ModuleDir(), dir))
Liz Kammerd38c87c2023-07-17 09:58:50 -0400265 // Also export without ModuleDir for consistency with Export_include_dirs not being set
266 g.exportedIncludeDirs = append(g.exportedIncludeDirs,
267 android.PathForModuleGen(ctx, g.subDir, dir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800268 }
269 } else {
Colin Cross1a527682019-09-23 15:55:30 -0700270 g.exportedIncludeDirs = append(g.exportedIncludeDirs, android.PathForModuleGen(ctx, g.subDir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800271 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700272
Colin Crossd11cf622021-03-23 22:30:35 -0700273 locationLabels := map[string]location{}
Colin Cross08f15ab2018-10-04 23:29:14 -0700274 firstLabel := ""
275
Colin Crossd11cf622021-03-23 22:30:35 -0700276 addLocationLabel := func(label string, loc location) {
Colin Cross08f15ab2018-10-04 23:29:14 -0700277 if firstLabel == "" {
278 firstLabel = label
279 }
280 if _, exists := locationLabels[label]; !exists {
Colin Crossd11cf622021-03-23 22:30:35 -0700281 locationLabels[label] = loc
Colin Cross08f15ab2018-10-04 23:29:14 -0700282 } else {
Anton Hansson7cd41e52021-10-08 16:13:10 +0100283 ctx.ModuleErrorf("multiple locations for label %q: %q and %q (do you have duplicate srcs entries?)",
Colin Crossd11cf622021-03-23 22:30:35 -0700284 label, locationLabels[label], loc)
Colin Cross08f15ab2018-10-04 23:29:14 -0700285 }
286 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700287
Colin Crossba9e4032020-11-24 16:32:22 -0800288 var tools android.Paths
289 var packagedTools []android.PackagingSpec
Colin Cross6f080df2016-11-04 15:32:58 -0700290 if len(g.properties.Tools) > 0 {
Colin Crossba71a3f2019-03-18 12:12:48 -0700291 seenTools := make(map[string]bool)
292
Colin Cross35143d02017-11-16 00:11:20 -0800293 ctx.VisitDirectDepsBlueprint(func(module blueprint.Module) {
Colin Cross08f15ab2018-10-04 23:29:14 -0700294 switch tag := ctx.OtherModuleDependencyTag(module).(type) {
295 case hostToolDependencyTag:
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700296 tool := ctx.OtherModuleName(module)
Martin Stjernholmdbd814d2022-01-12 23:18:30 +0000297 if m, ok := module.(android.Module); ok {
298 // Necessary to retrieve any prebuilt replacement for the tool, since
299 // toolDepsMutator runs too late for the prebuilt mutators to have
300 // replaced the dependency.
301 module = android.PrebuiltGetPreferred(ctx, m)
302 }
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700303
Colin Crossba9e4032020-11-24 16:32:22 -0800304 switch t := module.(type) {
305 case android.HostToolProvider:
306 // A HostToolProvider provides the path to a tool, which will be copied
307 // into the sandbox.
Colin Cross35143d02017-11-16 00:11:20 -0800308 if !t.(android.Module).Enabled() {
Colin Cross6510f912017-11-29 00:27:14 -0800309 if ctx.Config().AllowMissingDependencies() {
Colin Cross35143d02017-11-16 00:11:20 -0800310 ctx.AddMissingDependencies([]string{tool})
311 } else {
312 ctx.ModuleErrorf("depends on disabled module %q", tool)
313 }
Colin Crossba9e4032020-11-24 16:32:22 -0800314 return
Colin Cross35143d02017-11-16 00:11:20 -0800315 }
Colin Crossba9e4032020-11-24 16:32:22 -0800316 path := t.HostToolPath()
317 if !path.Valid() {
318 ctx.ModuleErrorf("host tool %q missing output file", tool)
319 return
320 }
321 if specs := t.TransitivePackagingSpecs(); specs != nil {
322 // If the HostToolProvider has PackgingSpecs, which are definitions of the
323 // required relative locations of the tool and its dependencies, use those
324 // instead. They will be copied to those relative locations in the sbox
325 // sandbox.
326 packagedTools = append(packagedTools, specs...)
327 // Assume that the first PackagingSpec of the module is the tool.
Colin Crossd11cf622021-03-23 22:30:35 -0700328 addLocationLabel(tag.label, packagedToolLocation{specs[0]})
Colin Crossba9e4032020-11-24 16:32:22 -0800329 } else {
330 tools = append(tools, path.Path())
Colin Crossd11cf622021-03-23 22:30:35 -0700331 addLocationLabel(tag.label, toolLocation{android.Paths{path.Path()}})
Colin Crossba9e4032020-11-24 16:32:22 -0800332 }
333 case bootstrap.GoBinaryTool:
334 // A GoBinaryTool provides the install path to a tool, which will be copied.
Colin Crossa44551f2021-10-25 15:36:21 -0700335 p := android.PathForGoBinary(ctx, t)
336 tools = append(tools, p)
337 addLocationLabel(tag.label, toolLocation{android.Paths{p}})
Colin Crossba9e4032020-11-24 16:32:22 -0800338 default:
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700339 ctx.ModuleErrorf("%q is not a host tool provider", tool)
Colin Crossba9e4032020-11-24 16:32:22 -0800340 return
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700341 }
342
Colin Crossba9e4032020-11-24 16:32:22 -0800343 seenTools[tag.label] = true
Colin Crossd350ecd2015-04-28 13:25:36 -0700344 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700345 })
Colin Crossba71a3f2019-03-18 12:12:48 -0700346
347 // If AllowMissingDependencies is enabled, the build will not have stopped when
348 // AddFarVariationDependencies was called on a missing tool, which will result in nonsensical
Liz Kammer20ebfb42020-07-28 11:32:07 -0700349 // "cmd: unknown location label ..." errors later. Add a placeholder file to the local label.
350 // The command that uses this placeholder file will never be executed because the rule will be
351 // replaced with an android.Error rule reporting the missing dependencies.
Colin Crossba71a3f2019-03-18 12:12:48 -0700352 if ctx.Config().AllowMissingDependencies() {
353 for _, tool := range g.properties.Tools {
354 if !seenTools[tool] {
Colin Crossd11cf622021-03-23 22:30:35 -0700355 addLocationLabel(tool, errorLocation{"***missing tool " + tool + "***"})
Colin Crossba71a3f2019-03-18 12:12:48 -0700356 }
357 }
358 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700359 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700360
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700361 if ctx.Failed() {
362 return
363 }
364
Colin Cross08f15ab2018-10-04 23:29:14 -0700365 for _, toolFile := range g.properties.Tool_files {
Colin Cross8a497952019-03-05 22:25:09 -0800366 paths := android.PathsForModuleSrc(ctx, []string{toolFile})
Colin Crossba9e4032020-11-24 16:32:22 -0800367 tools = append(tools, paths...)
Colin Crossd11cf622021-03-23 22:30:35 -0700368 addLocationLabel(toolFile, toolLocation{paths})
Colin Cross08f15ab2018-10-04 23:29:14 -0700369 }
370
Liz Kammer81fec182023-06-09 13:33:45 -0400371 addLabelsForInputs := func(propName string, include, exclude []string) android.Paths {
Liz Kammer81fec182023-06-09 13:33:45 -0400372 includeDirInPaths := ctx.DeviceConfig().BuildBrokenInputDir(g.Name())
373 var srcFiles android.Paths
374 for _, in := range include {
375 paths, missingDeps := android.PathsAndMissingDepsRelativeToModuleSourceDir(android.SourceInput{
376 Context: ctx, Paths: []string{in}, ExcludePaths: exclude, IncludeDirs: includeDirInPaths,
377 })
378 if len(missingDeps) > 0 {
379 if !ctx.Config().AllowMissingDependencies() {
380 panic(fmt.Errorf("should never get here, the missing dependencies %q should have been reported in DepsMutator",
381 missingDeps))
382 }
383
384 // If AllowMissingDependencies is enabled, the build will not have stopped when
385 // the dependency was added on a missing SourceFileProducer module, which will result in nonsensical
386 // "cmd: label ":..." has no files" errors later. Add a placeholder file to the local label.
387 // The command that uses this placeholder file will never be executed because the rule will be
388 // replaced with an android.Error rule reporting the missing dependencies.
389 ctx.AddMissingDependencies(missingDeps)
390 addLocationLabel(in, errorLocation{"***missing " + propName + " " + in + "***"})
391 } else {
392 srcFiles = append(srcFiles, paths...)
393 addLocationLabel(in, inputLocation{paths})
394 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700395 }
Liz Kammer81fec182023-06-09 13:33:45 -0400396 return srcFiles
Colin Cross08f15ab2018-10-04 23:29:14 -0700397 }
Liz Kammer81fec182023-06-09 13:33:45 -0400398 srcFiles := addLabelsForInputs("srcs", g.properties.Srcs, g.properties.Exclude_srcs)
Colin Cross40213022023-12-13 15:19:49 -0800399 android.SetProvider(ctx, blueprint.SrcsFileProviderKey, blueprint.SrcsFileProviderData{SrcPaths: srcFiles.Strings()})
Colin Cross08f15ab2018-10-04 23:29:14 -0700400
Colin Cross1a527682019-09-23 15:55:30 -0700401 var copyFrom android.Paths
402 var outputFiles android.WritablePaths
403 var zipArgs strings.Builder
Colin Cross08f15ab2018-10-04 23:29:14 -0700404
Colin Crossf3bfd022021-09-27 15:15:06 -0700405 cmd := String(g.properties.Cmd)
406 if g.CmdModifier != nil {
407 cmd = g.CmdModifier(ctx, cmd)
408 }
409
Liz Kammer796921d2023-07-11 08:21:41 -0400410 var extraInputs android.Paths
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500411 // Generate tasks, either from genrule or gensrcs.
Liz Kammer81fec182023-06-09 13:33:45 -0400412 for i, task := range g.taskGenerator(ctx, cmd, srcFiles) {
Colin Cross3d680512020-11-13 16:23:53 -0800413 if len(task.out) == 0 {
414 ctx.ModuleErrorf("must have at least one output file")
415 return
Colin Cross85a2e892018-07-09 09:45:06 -0700416 }
417
Liz Kammer81fec182023-06-09 13:33:45 -0400418 // Only handle extra inputs once as these currently are the same across all tasks
419 if i == 0 {
420 for name, values := range task.extraInputs {
421 extraInputs = append(extraInputs, addLabelsForInputs(name, values, []string{})...)
422 }
423 }
424
Colin Crossf1a035e2020-11-16 17:32:30 -0800425 // Pick a unique path outside the task.genDir for the sbox manifest textproto,
426 // a unique rule name, and the user-visible description.
427 manifestName := "genrule.sbox.textproto"
428 desc := "generate"
429 name := "generator"
430 if task.shards > 0 {
431 manifestName = "genrule_" + strconv.Itoa(task.shard) + ".sbox.textproto"
432 desc += " " + strconv.Itoa(task.shard)
433 name += strconv.Itoa(task.shard)
434 } else if len(task.out) == 1 {
435 desc += " " + task.out[0].Base()
436 }
437
438 manifestPath := android.PathForModuleOut(ctx, manifestName)
439
440 // Use a RuleBuilder to create a rule that runs the command inside an sbox sandbox.
Yu Liu6a7940c2023-05-09 17:12:22 -0700441 rule := getSandboxedRuleBuilder(ctx, android.NewRuleBuilder(pctx, ctx).Sbox(task.genDir, manifestPath))
Justin Yun4da4ccc2023-07-06 10:56:29 +0900442 if Bool(g.properties.Write_if_changed) {
443 rule.Restat()
444 }
Colin Crossf1a035e2020-11-16 17:32:30 -0800445 cmd := rule.Command()
446
Colin Cross3d680512020-11-13 16:23:53 -0800447 for _, out := range task.out {
Colin Crossd11cf622021-03-23 22:30:35 -0700448 addLocationLabel(out.Rel(), outputLocation{out})
Colin Cross3d680512020-11-13 16:23:53 -0800449 }
450
Colin Cross1a527682019-09-23 15:55:30 -0700451 referencedDepfile := false
452
Colin Cross3d680512020-11-13 16:23:53 -0800453 rawCommand, err := android.Expand(task.cmd, func(name string) (string, error) {
Colin Cross1a527682019-09-23 15:55:30 -0700454 // report the error directly without returning an error to android.Expand to catch multiple errors in a
455 // single run
Colin Cross3d680512020-11-13 16:23:53 -0800456 reportError := func(fmt string, args ...interface{}) (string, error) {
Colin Cross1a527682019-09-23 15:55:30 -0700457 ctx.PropertyErrorf("cmd", fmt, args...)
Colin Cross3d680512020-11-13 16:23:53 -0800458 return "SOONG_ERROR", nil
Colin Cross6f080df2016-11-04 15:32:58 -0700459 }
Colin Cross1a527682019-09-23 15:55:30 -0700460
Jihoon Kangc170af42022-08-20 05:26:38 +0000461 // Apply shell escape to each cases to prevent source file paths containing $ from being evaluated in shell
Colin Cross1a527682019-09-23 15:55:30 -0700462 switch name {
463 case "location":
464 if len(g.properties.Tools) == 0 && len(g.properties.Tool_files) == 0 {
465 return reportError("at least one `tools` or `tool_files` is required if $(location) is used")
Colin Cross6f080df2016-11-04 15:32:58 -0700466 }
Colin Crossd11cf622021-03-23 22:30:35 -0700467 loc := locationLabels[firstLabel]
468 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700469 if len(paths) == 0 {
470 return reportError("default label %q has no files", firstLabel)
471 } else if len(paths) > 1 {
472 return reportError("default label %q has multiple files, use $(locations %s) to reference it",
473 firstLabel, firstLabel)
Colin Cross08f15ab2018-10-04 23:29:14 -0700474 }
Jihoon Kangc170af42022-08-20 05:26:38 +0000475 return proptools.ShellEscape(paths[0]), nil
Colin Cross1a527682019-09-23 15:55:30 -0700476 case "in":
Jihoon Kangc170af42022-08-20 05:26:38 +0000477 return strings.Join(proptools.ShellEscapeList(cmd.PathsForInputs(srcFiles)), " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700478 case "out":
Colin Cross3d680512020-11-13 16:23:53 -0800479 var sandboxOuts []string
480 for _, out := range task.out {
Colin Crossf1a035e2020-11-16 17:32:30 -0800481 sandboxOuts = append(sandboxOuts, cmd.PathForOutput(out))
Colin Cross3d680512020-11-13 16:23:53 -0800482 }
Jihoon Kangc170af42022-08-20 05:26:38 +0000483 return strings.Join(proptools.ShellEscapeList(sandboxOuts), " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700484 case "depfile":
485 referencedDepfile = true
486 if !Bool(g.properties.Depfile) {
487 return reportError("$(depfile) used without depfile property")
488 }
Colin Cross3d680512020-11-13 16:23:53 -0800489 return "__SBOX_DEPFILE__", nil
Colin Cross1a527682019-09-23 15:55:30 -0700490 case "genDir":
Jihoon Kangc170af42022-08-20 05:26:38 +0000491 return proptools.ShellEscape(cmd.PathForOutput(task.genDir)), nil
Colin Cross1a527682019-09-23 15:55:30 -0700492 default:
493 if strings.HasPrefix(name, "location ") {
494 label := strings.TrimSpace(strings.TrimPrefix(name, "location "))
Colin Crossd11cf622021-03-23 22:30:35 -0700495 if loc, ok := locationLabels[label]; ok {
496 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700497 if len(paths) == 0 {
498 return reportError("label %q has no files", label)
499 } else if len(paths) > 1 {
500 return reportError("label %q has multiple files, use $(locations %s) to reference it",
501 label, label)
502 }
Jihoon Kangc170af42022-08-20 05:26:38 +0000503 return proptools.ShellEscape(paths[0]), nil
Colin Cross1a527682019-09-23 15:55:30 -0700504 } else {
Anton Hanssonbebf5262022-02-23 11:42:38 +0000505 return reportError("unknown location label %q is not in srcs, out, tools or tool_files.", label)
Colin Cross1a527682019-09-23 15:55:30 -0700506 }
507 } else if strings.HasPrefix(name, "locations ") {
508 label := strings.TrimSpace(strings.TrimPrefix(name, "locations "))
Colin Crossd11cf622021-03-23 22:30:35 -0700509 if loc, ok := locationLabels[label]; ok {
510 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700511 if len(paths) == 0 {
512 return reportError("label %q has no files", label)
513 }
Cole Faustce74a592023-12-07 14:58:45 -0800514 return strings.Join(proptools.ShellEscapeList(paths), " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700515 } else {
Anton Hanssonbebf5262022-02-23 11:42:38 +0000516 return reportError("unknown locations label %q is not in srcs, out, tools or tool_files.", label)
Colin Cross1a527682019-09-23 15:55:30 -0700517 }
518 } else {
519 return reportError("unknown variable '$(%s)'", name)
520 }
Colin Cross6f080df2016-11-04 15:32:58 -0700521 }
Colin Cross1a527682019-09-23 15:55:30 -0700522 })
523
524 if err != nil {
525 ctx.PropertyErrorf("cmd", "%s", err.Error())
526 return
Colin Cross6f080df2016-11-04 15:32:58 -0700527 }
Colin Cross6f080df2016-11-04 15:32:58 -0700528
Colin Cross1a527682019-09-23 15:55:30 -0700529 if Bool(g.properties.Depfile) && !referencedDepfile {
530 ctx.PropertyErrorf("cmd", "specified depfile=true but did not include a reference to '${depfile}' in cmd")
531 return
532 }
Colin Cross1a527682019-09-23 15:55:30 -0700533 g.rawCommands = append(g.rawCommands, rawCommand)
Bill Peckhamc087be12020-02-13 15:55:10 -0800534
Colin Cross3d680512020-11-13 16:23:53 -0800535 cmd.Text(rawCommand)
Liz Kammer81fec182023-06-09 13:33:45 -0400536 cmd.Implicits(srcFiles) // need to be able to reference other srcs
537 cmd.Implicits(extraInputs)
Colin Cross3d680512020-11-13 16:23:53 -0800538 cmd.ImplicitOutputs(task.out)
539 cmd.Implicits(task.in)
Colin Crossba9e4032020-11-24 16:32:22 -0800540 cmd.ImplicitTools(tools)
541 cmd.ImplicitTools(task.extraTools)
542 cmd.ImplicitPackagedTools(packagedTools)
Colin Cross3d680512020-11-13 16:23:53 -0800543 if Bool(g.properties.Depfile) {
544 cmd.ImplicitDepFile(task.depFile)
545 }
546
547 // Create the rule to run the genrule command inside sbox.
Colin Crossf1a035e2020-11-16 17:32:30 -0800548 rule.Build(name, desc)
Colin Cross1a527682019-09-23 15:55:30 -0700549
550 if len(task.copyTo) > 0 {
Colin Cross3d680512020-11-13 16:23:53 -0800551 // If copyTo is set, multiple shards need to be copied into a single directory.
552 // task.out contains the per-shard paths, and copyTo contains the corresponding
553 // final path. The files need to be copied into the final directory by a
554 // single rule so it can remove the directory before it starts to ensure no
555 // old files remain. zipsync already does this, so build up zipArgs that
556 // zip all the per-shard directories into a single zip.
Colin Cross1a527682019-09-23 15:55:30 -0700557 outputFiles = append(outputFiles, task.copyTo...)
558 copyFrom = append(copyFrom, task.out.Paths()...)
559 zipArgs.WriteString(" -C " + task.genDir.String())
560 zipArgs.WriteString(android.JoinWithPrefix(task.out.Strings(), " -f "))
561 } else {
562 outputFiles = append(outputFiles, task.out...)
563 }
Colin Cross6f080df2016-11-04 15:32:58 -0700564 }
565
Colin Cross1a527682019-09-23 15:55:30 -0700566 if len(copyFrom) > 0 {
Colin Cross3d680512020-11-13 16:23:53 -0800567 // Create a rule that zips all the per-shard directories into a single zip and then
568 // uses zipsync to unzip it into the final directory.
Colin Cross1a527682019-09-23 15:55:30 -0700569 ctx.Build(pctx, android.BuildParams{
Colin Crossf1885962020-11-20 15:28:30 -0800570 Rule: gensrcsMerge,
571 Implicits: copyFrom,
572 Outputs: outputFiles,
573 Description: "merge shards",
Colin Cross1a527682019-09-23 15:55:30 -0700574 Args: map[string]string{
575 "zipArgs": zipArgs.String(),
576 "tmpZip": android.PathForModuleGen(ctx, g.subDir+".zip").String(),
577 "genDir": android.PathForModuleGen(ctx, g.subDir).String(),
578 },
579 })
Colin Cross85a2e892018-07-09 09:45:06 -0700580 }
581
Colin Cross1a527682019-09-23 15:55:30 -0700582 g.outputFiles = outputFiles.Paths()
Chris Parsonsf874e462022-05-10 13:50:12 -0400583}
Jeff Gastonefc1b412017-03-29 17:29:06 -0700584
Chris Parsonsf874e462022-05-10 13:50:12 -0400585func (g *Module) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Vinh Tran140d5882022-06-10 14:23:27 -0400586 // Allowlist genrule to use depfile until we have a solution to remove it.
Cole Faust27609f12023-12-12 10:15:59 -0800587 // TODO(b/307824623): Remove depfile property
Yu Liu6a7940c2023-05-09 17:12:22 -0700588 if Bool(g.properties.Depfile) {
Yu Liue7f7cbf2023-06-13 18:50:03 +0000589 sandboxingAllowlistSets := getSandboxingAllowlistSets(ctx)
Yu Liue7f7cbf2023-06-13 18:50:03 +0000590 if ctx.DeviceConfig().GenruleSandboxing() && !sandboxingAllowlistSets.depfileAllowSet[g.Name()] {
Yu Liu6a7940c2023-05-09 17:12:22 -0700591 ctx.PropertyErrorf(
592 "depfile",
Cole Faust27609f12023-12-12 10:15:59 -0800593 "Deprecated because with genrule sandboxing, dependencies must be known before the action is run "+
594 "in order to add them to the sandbox. "+
595 "Please specify the dependencies explicitly so that there is no need to use depfile.")
Yu Liu6a7940c2023-05-09 17:12:22 -0700596 }
Vinh Tran140d5882022-06-10 14:23:27 -0400597 }
598
Chris Parsonsf874e462022-05-10 13:50:12 -0400599 g.generateCommonBuildActions(ctx)
600
601 // For <= 6 outputs, just embed those directly in the users. Right now, that covers >90% of
602 // the genrules on AOSP. That will make things simpler to look at the graph in the common
603 // case. For larger sets of outputs, inject a phony target in between to limit ninja file
604 // growth.
605 if len(g.outputFiles) <= 6 {
606 g.outputDeps = g.outputFiles
607 } else {
608 phonyFile := android.PathForModuleGen(ctx, "genrule-phony")
609 ctx.Build(pctx, android.BuildParams{
610 Rule: blueprint.Phony,
611 Output: phonyFile,
612 Inputs: g.outputFiles,
613 })
614 g.outputDeps = android.Paths{phonyFile}
Jeff Gaston02a684b2017-10-27 14:59:27 -0700615 }
LaMont Jonesafe7baf2024-01-09 22:47:39 +0000616 android.CollectDependencyAconfigFiles(ctx, &g.mergedAconfigFiles)
617}
618
619func (g *Module) AndroidMkEntries() []android.AndroidMkEntries {
620 ret := android.AndroidMkEntries{
621 OutputFile: android.OptionalPathForPath(g.outputFiles[0]),
622 ExtraEntries: []android.AndroidMkExtraEntriesFunc{
623 func(ctx android.AndroidMkExtraEntriesContext, entries *android.AndroidMkEntries) {
624 android.SetAconfigFileMkEntries(g.AndroidModuleBase(), entries, g.mergedAconfigFiles)
625 },
626 },
627 }
628
629 return []android.AndroidMkEntries{ret}
630}
631
632func (g *Module) AndroidModuleBase() *android.ModuleBase {
633 return &g.ModuleBase
Chris Parsonsf874e462022-05-10 13:50:12 -0400634}
635
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700636// Collect information for opening IDE project files in java/jdeps.go.
637func (g *Module) IDEInfo(dpInfo *android.IdeInfo) {
638 dpInfo.Srcs = append(dpInfo.Srcs, g.Srcs().Strings()...)
639 for _, src := range g.properties.Srcs {
640 if strings.HasPrefix(src, ":") {
641 src = strings.Trim(src, ":")
642 dpInfo.Deps = append(dpInfo.Deps, src)
643 }
644 }
645}
646
Colin Crossa4ad2b02019-03-18 22:15:32 -0700647func (g *Module) AndroidMk() android.AndroidMkData {
648 return android.AndroidMkData{
Anton Hansson72f18492020-10-30 16:34:45 +0000649 Class: "ETC",
Colin Crossa4ad2b02019-03-18 22:15:32 -0700650 OutputFile: android.OptionalPathForPath(g.outputFiles[0]),
651 SubName: g.subName,
652 Extra: []android.AndroidMkExtraFunc{
653 func(w io.Writer, outputFile android.Path) {
Anton Hansson72f18492020-10-30 16:34:45 +0000654 fmt.Fprintln(w, "LOCAL_UNINSTALLABLE_MODULE := true")
Colin Crossa4ad2b02019-03-18 22:15:32 -0700655 },
656 },
657 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
658 android.WriteAndroidMkData(w, data)
659 if data.SubName != "" {
660 fmt.Fprintln(w, ".PHONY:", name)
661 fmt.Fprintln(w, name, ":", name+g.subName)
662 }
663 },
664 }
665}
666
Jiyong Park45bf82e2020-12-15 22:29:02 +0900667var _ android.ApexModule = (*Module)(nil)
668
669// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -0700670func (g *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
671 sdkVersion android.ApiLevel) error {
Jooyung Han749dc692020-04-15 11:03:39 +0900672 // Because generated outputs are checked by client modules(e.g. cc_library, ...)
673 // we can safely ignore the check here.
674 return nil
675}
676
Jeff Gaston437d23c2017-11-08 12:38:00 -0800677func generatorFactory(taskGenerator taskFunc, props ...interface{}) *Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700678 module := &Module{
Jeff Gaston437d23c2017-11-08 12:38:00 -0800679 taskGenerator: taskGenerator,
Colin Crossd350ecd2015-04-28 13:25:36 -0700680 }
681
Colin Cross36242852017-06-23 15:06:31 -0700682 module.AddProperties(props...)
683 module.AddProperties(&module.properties)
Colin Crossd350ecd2015-04-28 13:25:36 -0700684
Colin Cross7228ecd2019-11-18 16:00:16 -0800685 module.ImageInterface = noopImageInterface{}
686
Colin Cross36242852017-06-23 15:06:31 -0700687 return module
Colin Crossd350ecd2015-04-28 13:25:36 -0700688}
689
Colin Cross7228ecd2019-11-18 16:00:16 -0800690type noopImageInterface struct{}
691
692func (x noopImageInterface) ImageMutatorBegin(android.BaseModuleContext) {}
693func (x noopImageInterface) CoreVariantNeeded(android.BaseModuleContext) bool { return false }
Yifan Hong1b3348d2020-01-21 15:53:22 -0800694func (x noopImageInterface) RamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700695func (x noopImageInterface) VendorRamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Inseob Kim08758f02021-04-08 21:13:22 +0900696func (x noopImageInterface) DebugRamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Colin Cross7228ecd2019-11-18 16:00:16 -0800697func (x noopImageInterface) RecoveryVariantNeeded(android.BaseModuleContext) bool { return false }
698func (x noopImageInterface) ExtraImageVariations(ctx android.BaseModuleContext) []string { return nil }
699func (x noopImageInterface) SetImageVariation(ctx android.BaseModuleContext, variation string, module android.Module) {
700}
701
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700702func NewGenSrcs() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700703 properties := &genSrcsProperties{}
704
Colin Crossf1885962020-11-20 15:28:30 -0800705 // finalSubDir is the name of the subdirectory that output files will be generated into.
706 // It is used so that per-shard directories can be placed alongside it an then finally
707 // merged into it.
708 const finalSubDir = "gensrcs"
709
Colin Cross1a527682019-09-23 15:55:30 -0700710 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Colin Cross1a527682019-09-23 15:55:30 -0700711 shardSize := defaultShardSize
712 if s := properties.Shard_size; s != nil {
713 shardSize = int(*s)
714 }
Jeff Gaston437d23c2017-11-08 12:38:00 -0800715
Colin Crossf1885962020-11-20 15:28:30 -0800716 // gensrcs rules can easily hit command line limits by repeating the command for
717 // every input file. Shard the input files into groups.
Colin Cross1a527682019-09-23 15:55:30 -0700718 shards := android.ShardPaths(srcFiles, shardSize)
719 var generateTasks []generateTask
Colin Crossbaccf5b2018-02-21 14:07:48 -0800720
Colin Cross1a527682019-09-23 15:55:30 -0700721 for i, shard := range shards {
722 var commands []string
723 var outFiles android.WritablePaths
Colin Cross3ea4eb82020-11-24 13:07:27 -0800724 var commandDepFiles []string
Colin Cross1a527682019-09-23 15:55:30 -0700725 var copyTo android.WritablePaths
Colin Cross1a527682019-09-23 15:55:30 -0700726
Colin Crossf1885962020-11-20 15:28:30 -0800727 // When sharding is enabled (i.e. len(shards) > 1), the sbox rules for each
728 // shard will be write to their own directories and then be merged together
729 // into finalSubDir. If sharding is not enabled (i.e. len(shards) == 1),
730 // the sbox rule will write directly to finalSubDir.
731 genSubDir := finalSubDir
Colin Cross1a527682019-09-23 15:55:30 -0700732 if len(shards) > 1 {
Colin Crossf1885962020-11-20 15:28:30 -0800733 genSubDir = strconv.Itoa(i)
Jeff Gaston437d23c2017-11-08 12:38:00 -0800734 }
735
Colin Crossf1885962020-11-20 15:28:30 -0800736 genDir := android.PathForModuleGen(ctx, genSubDir)
Colin Crossf1a035e2020-11-16 17:32:30 -0800737 // TODO(ccross): this RuleBuilder is a hack to be able to call
738 // rule.Command().PathForOutput. Replace this with passing the rule into the
739 // generator.
Yu Liu6a7940c2023-05-09 17:12:22 -0700740 rule := getSandboxedRuleBuilder(ctx, android.NewRuleBuilder(pctx, ctx).Sbox(genDir, nil))
Jeff Gaston437d23c2017-11-08 12:38:00 -0800741
Colin Cross3ea4eb82020-11-24 13:07:27 -0800742 for _, in := range shard {
Colin Crossf1885962020-11-20 15:28:30 -0800743 outFile := android.GenPathWithExt(ctx, finalSubDir, in, String(properties.Output_extension))
744
745 // If sharding is enabled, then outFile is the path to the output file in
746 // the shard directory, and copyTo is the path to the output file in the
747 // final directory.
Colin Cross1a527682019-09-23 15:55:30 -0700748 if len(shards) > 1 {
Colin Crossf1885962020-11-20 15:28:30 -0800749 shardFile := android.GenPathWithExt(ctx, genSubDir, in, String(properties.Output_extension))
Colin Cross1a527682019-09-23 15:55:30 -0700750 copyTo = append(copyTo, outFile)
751 outFile = shardFile
752 }
753
754 outFiles = append(outFiles, outFile)
Colin Cross1a527682019-09-23 15:55:30 -0700755
Colin Crossf1885962020-11-20 15:28:30 -0800756 // pre-expand the command line to replace $in and $out with references to
757 // a single input and output file.
Colin Cross1a527682019-09-23 15:55:30 -0700758 command, err := android.Expand(rawCommand, func(name string) (string, error) {
759 switch name {
760 case "in":
761 return in.String(), nil
762 case "out":
Colin Crossf1a035e2020-11-16 17:32:30 -0800763 return rule.Command().PathForOutput(outFile), nil
Colin Cross3ea4eb82020-11-24 13:07:27 -0800764 case "depfile":
765 // Generate a depfile for each output file. Store the list for
766 // later in order to combine them all into a single depfile.
Colin Crossf1a035e2020-11-16 17:32:30 -0800767 depFile := rule.Command().PathForOutput(outFile.ReplaceExtension(ctx, "d"))
Colin Cross3ea4eb82020-11-24 13:07:27 -0800768 commandDepFiles = append(commandDepFiles, depFile)
769 return depFile, nil
Colin Cross1a527682019-09-23 15:55:30 -0700770 default:
771 return "$(" + name + ")", nil
772 }
773 })
774 if err != nil {
775 ctx.PropertyErrorf("cmd", err.Error())
776 }
777
778 // escape the command in case for example it contains '#', an odd number of '"', etc
779 command = fmt.Sprintf("bash -c %v", proptools.ShellEscape(command))
780 commands = append(commands, command)
781 }
782 fullCommand := strings.Join(commands, " && ")
783
Colin Cross3ea4eb82020-11-24 13:07:27 -0800784 var outputDepfile android.WritablePath
785 var extraTools android.Paths
786 if len(commandDepFiles) > 0 {
787 // Each command wrote to a depfile, but ninja can only handle one
788 // depfile per rule. Use the dep_fixer tool at the end of the
789 // command to combine all the depfiles into a single output depfile.
790 outputDepfile = android.PathForModuleGen(ctx, genSubDir, "gensrcs.d")
791 depFixerTool := ctx.Config().HostToolPath(ctx, "dep_fixer")
792 fullCommand += fmt.Sprintf(" && %s -o $(depfile) %s",
Colin Crossd11cf622021-03-23 22:30:35 -0700793 rule.Command().PathForTool(depFixerTool),
Colin Crossba9e4032020-11-24 16:32:22 -0800794 strings.Join(commandDepFiles, " "))
Colin Cross3ea4eb82020-11-24 13:07:27 -0800795 extraTools = append(extraTools, depFixerTool)
796 }
797
Colin Cross1a527682019-09-23 15:55:30 -0700798 generateTasks = append(generateTasks, generateTask{
Colin Cross3ea4eb82020-11-24 13:07:27 -0800799 in: shard,
800 out: outFiles,
801 depFile: outputDepfile,
802 copyTo: copyTo,
803 genDir: genDir,
804 cmd: fullCommand,
805 shard: i,
806 shards: len(shards),
807 extraTools: extraTools,
Liz Kammer81fec182023-06-09 13:33:45 -0400808 extraInputs: map[string][]string{
809 "data": properties.Data,
810 },
Colin Cross1a527682019-09-23 15:55:30 -0700811 })
Jeff Gaston437d23c2017-11-08 12:38:00 -0800812 }
Colin Cross1a527682019-09-23 15:55:30 -0700813
814 return generateTasks
Colin Crossd350ecd2015-04-28 13:25:36 -0700815 }
816
Colin Cross1a527682019-09-23 15:55:30 -0700817 g := generatorFactory(taskGenerator, properties)
Colin Crossf1885962020-11-20 15:28:30 -0800818 g.subDir = finalSubDir
Colin Cross1a527682019-09-23 15:55:30 -0700819 return g
Colin Crossd350ecd2015-04-28 13:25:36 -0700820}
821
Colin Cross54190b32017-10-09 15:34:10 -0700822func GenSrcsFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700823 m := NewGenSrcs()
824 android.InitAndroidModule(m)
825 return m
826}
827
Colin Crossd350ecd2015-04-28 13:25:36 -0700828type genSrcsProperties struct {
Colin Cross7d5136f2015-05-11 13:39:40 -0700829 // extension that will be substituted for each output file
Nan Zhanga5e7cb42017-11-09 22:42:32 -0800830 Output_extension *string
Colin Cross1a527682019-09-23 15:55:30 -0700831
832 // maximum number of files that will be passed on a single command line.
833 Shard_size *int64
Liz Kammer81fec182023-06-09 13:33:45 -0400834
835 // Additional files needed for build that are not tooling related.
836 Data []string `android:"path"`
Colin Cross5049f022015-03-18 13:28:46 -0700837}
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)
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700870 return m
871}
872
Colin Crossd350ecd2015-04-28 13:25:36 -0700873type genRuleProperties struct {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700874 // names of the output files that will be generated
Yu Liud6201012022-10-17 12:29:15 -0700875 Out []string
Colin Cross5049f022015-03-18 13:28:46 -0700876}
Nan Zhangea568a42017-11-08 21:20:04 -0800877
878var Bool = proptools.Bool
879var String = proptools.String
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800880
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800881// Defaults
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800882type Defaults struct {
883 android.ModuleBase
884 android.DefaultsModuleBase
885}
886
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800887func defaultsFactory() android.Module {
888 return DefaultsFactory()
889}
890
891func DefaultsFactory(props ...interface{}) android.Module {
892 module := &Defaults{}
893
894 module.AddProperties(props...)
895 module.AddProperties(
896 &generatorProperties{},
897 &genRuleProperties{},
898 )
899
900 android.InitDefaultsModule(module)
901
902 return module
903}
Yu Liu6a7940c2023-05-09 17:12:22 -0700904
Yu Liue7f7cbf2023-06-13 18:50:03 +0000905var sandboxingAllowlistKey = android.NewOnceKey("genruleSandboxingAllowlistKey")
906
907type sandboxingAllowlistSets struct {
908 sandboxingDenyModuleSet map[string]bool
909 sandboxingDenyPathSet map[string]bool
910 depfileAllowSet map[string]bool
911}
912
913func getSandboxingAllowlistSets(ctx android.PathContext) *sandboxingAllowlistSets {
914 return ctx.Config().Once(sandboxingAllowlistKey, func() interface{} {
915 sandboxingDenyModuleSet := map[string]bool{}
916 sandboxingDenyPathSet := map[string]bool{}
917 depfileAllowSet := map[string]bool{}
918
919 android.AddToStringSet(sandboxingDenyModuleSet, append(DepfileAllowList, SandboxingDenyModuleList...))
920 android.AddToStringSet(sandboxingDenyPathSet, SandboxingDenyPathList)
921 android.AddToStringSet(depfileAllowSet, DepfileAllowList)
922 return &sandboxingAllowlistSets{
923 sandboxingDenyModuleSet: sandboxingDenyModuleSet,
924 sandboxingDenyPathSet: sandboxingDenyPathSet,
925 depfileAllowSet: depfileAllowSet,
926 }
927 }).(*sandboxingAllowlistSets)
928}
Liz Kammer0db0e342023-07-18 11:39:30 -0400929
Yu Liu6a7940c2023-05-09 17:12:22 -0700930func getSandboxedRuleBuilder(ctx android.ModuleContext, r *android.RuleBuilder) *android.RuleBuilder {
Yu Liu45d6af52023-05-24 23:10:18 +0000931 if !ctx.DeviceConfig().GenruleSandboxing() {
932 return r.SandboxTools()
933 }
Yu Liue7f7cbf2023-06-13 18:50:03 +0000934 sandboxingAllowlistSets := getSandboxingAllowlistSets(ctx)
935 if sandboxingAllowlistSets.sandboxingDenyPathSet[ctx.ModuleDir()] ||
936 sandboxingAllowlistSets.sandboxingDenyModuleSet[ctx.ModuleName()] {
Yu Liu6a7940c2023-05-09 17:12:22 -0700937 return r.SandboxTools()
938 }
939 return r.SandboxInputs()
940}