blob: 67b96ca92ec59631462f9914f7867bfb74e4bc41 [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.
Spandan Das93e95992021-07-29 18:26:39 +0000127 // $(genDir): the sandbox directory for this tool; contains $(out).
Colin Cross2296f5b2017-10-17 21:38:14 -0700128 // $$: a literal $
Nan Zhangea568a42017-11-08 21:20:04 -0800129 Cmd *string
Colin Cross7d5136f2015-05-11 13:39:40 -0700130
Colin Cross6f080df2016-11-04 15:32:58 -0700131 // name of the modules (if any) that produces the host executable. Leave empty for
Colin Cross7d5136f2015-05-11 13:39:40 -0700132 // prebuilts or scripts that do not need a module to build them.
Colin Cross6f080df2016-11-04 15:32:58 -0700133 Tools []string
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700134
Sam Delmericof8775632023-08-14 23:45:41 +0000135 // Local files that are used by the tool
Colin Cross27b922f2019-03-04 22:35:41 -0800136 Tool_files []string `android:"path"`
Colin Cross5ed99c62016-11-22 12:55:55 -0800137
138 // List of directories to export generated headers from
139 Export_include_dirs []string
Colin Cross708c4242017-01-13 18:05:49 -0800140
141 // list of input files
Colin Cross27b922f2019-03-04 22:35:41 -0800142 Srcs []string `android:"path,arch_variant"`
Dan Willemseneefa0262018-11-17 14:01:18 -0800143
144 // input files to exclude
Colin Cross27b922f2019-03-04 22:35:41 -0800145 Exclude_srcs []string `android:"path,arch_variant"`
Justin Yun4da4ccc2023-07-06 10:56:29 +0900146
147 // Enable restat to update the output only if the output is changed
148 Write_if_changed *bool
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400149}
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500150
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700151type Module struct {
Colin Cross635c3b02016-05-18 15:37:25 -0700152 android.ModuleBase
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800153 android.DefaultableModuleBase
Jiyong Parkfc752ca2019-06-12 13:27:29 +0900154 android.ApexModuleBase
Colin Crossd350ecd2015-04-28 13:25:36 -0700155
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700156 // For other packages to make their own genrules with extra
157 // properties
158 Extra interface{}
Colin Crossf3bfd022021-09-27 15:15:06 -0700159
160 // CmdModifier can be set by wrappers around genrule to modify the command, for example to
161 // prefix environment variables to it.
162 CmdModifier func(ctx android.ModuleContext, cmd string) string
163
Colin Cross7228ecd2019-11-18 16:00:16 -0800164 android.ImageInterface
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700165
Colin Cross7d5136f2015-05-11 13:39:40 -0700166 properties generatorProperties
Colin Crossd350ecd2015-04-28 13:25:36 -0700167
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500168 // For the different tasks that genrule and gensrc generate. genrule will
169 // generate 1 task, and gensrc will generate 1 or more tasks based on the
170 // number of shards the input files are sharded into.
Jeff Gaston437d23c2017-11-08 12:38:00 -0800171 taskGenerator taskFunc
Colin Crossd350ecd2015-04-28 13:25:36 -0700172
Colin Cross1a527682019-09-23 15:55:30 -0700173 rule blueprint.Rule
174 rawCommands []string
Colin Crossd350ecd2015-04-28 13:25:36 -0700175
Colin Cross5ed99c62016-11-22 12:55:55 -0800176 exportedIncludeDirs android.Paths
Dan Willemsenb40aab62016-04-20 14:21:14 -0700177
Colin Cross635c3b02016-05-18 15:37:25 -0700178 outputFiles android.Paths
Dan Willemsen9da9d492018-02-21 18:28:18 -0800179 outputDeps android.Paths
Colin Crossa4ad2b02019-03-18 22:15:32 -0700180
181 subName string
Colin Cross1a527682019-09-23 15:55:30 -0700182 subDir string
LaMont Jonesafe7baf2024-01-09 22:47:39 +0000183
184 // Aconfig files for all transitive deps. Also exposed via TransitiveDeclarationsInfo
185 mergedAconfigFiles map[string]android.Paths
Colin Crossd350ecd2015-04-28 13:25:36 -0700186}
187
Colin Cross1a527682019-09-23 15:55:30 -0700188type taskFunc func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask
Colin Crossd350ecd2015-04-28 13:25:36 -0700189
190type generateTask struct {
Liz Kammer81fec182023-06-09 13:33:45 -0400191 in android.Paths
192 out android.WritablePaths
Liz Kammer81fec182023-06-09 13:33:45 -0400193 copyTo android.WritablePaths // For gensrcs to set on gensrcsMerge rule.
194 genDir android.WritablePath
Liz Kammer81fec182023-06-09 13:33:45 -0400195 extraInputs map[string][]string
Colin Cross3ea4eb82020-11-24 13:07:27 -0800196
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500197 cmd string
198 // For gensrsc sharding.
Colin Cross3ea4eb82020-11-24 13:07:27 -0800199 shard int
200 shards int
Colin Crossd350ecd2015-04-28 13:25:36 -0700201}
202
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700203func (g *Module) GeneratedSourceFiles() android.Paths {
Colin Crossd350ecd2015-04-28 13:25:36 -0700204 return g.outputFiles
205}
206
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700207func (g *Module) Srcs() android.Paths {
Nan Zhange42777a2018-03-27 16:19:42 -0700208 return append(android.Paths{}, g.outputFiles...)
Colin Cross068e0fe2016-12-13 15:23:47 -0800209}
210
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700211func (g *Module) GeneratedHeaderDirs() android.Paths {
Colin Cross5ed99c62016-11-22 12:55:55 -0800212 return g.exportedIncludeDirs
Dan Willemsenb40aab62016-04-20 14:21:14 -0700213}
214
Dan Willemsen9da9d492018-02-21 18:28:18 -0800215func (g *Module) GeneratedDeps() android.Paths {
216 return g.outputDeps
217}
218
Jooyung Han8c7e3ed2021-06-28 17:35:58 +0900219func (g *Module) OutputFiles(tag string) (android.Paths, error) {
220 if tag == "" {
221 return append(android.Paths{}, g.outputFiles...), nil
222 }
223 // otherwise, tag should match one of outputs
224 for _, outputFile := range g.outputFiles {
225 if outputFile.Rel() == tag {
226 return android.Paths{outputFile}, nil
227 }
228 }
229 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
230}
231
232var _ android.SourceFileProducer = (*Module)(nil)
233var _ android.OutputFileProducer = (*Module)(nil)
234
Martin Stjernholm710ec3a2020-01-16 15:12:04 +0000235func toolDepsMutator(ctx android.BottomUpMutatorContext) {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700236 if g, ok := ctx.Module().(*Module); ok {
Colin Cross08f15ab2018-10-04 23:29:14 -0700237 for _, tool := range g.properties.Tools {
238 tag := hostToolDependencyTag{label: tool}
239 if m := android.SrcIsModule(tool); m != "" {
240 tool = m
241 }
Colin Cross0f7d2ef2019-10-16 11:03:10 -0700242 ctx.AddFarVariationDependencies(ctx.Config().BuildOSTarget.Variations(), tag, tool)
Colin Cross6362e272015-10-29 15:25:03 -0700243 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700244 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700245}
246
Chris Parsonsf874e462022-05-10 13:50:12 -0400247// generateCommonBuildActions contains build action generation logic
248// common to both the mixed build case and the legacy case of genrule processing.
249// To fully support genrule in mixed builds, the contents of this function should
250// approach zero; there should be no genrule action registration done directly
251// by Soong logic in the mixed-build case.
252func (g *Module) generateCommonBuildActions(ctx android.ModuleContext) {
Colin Crossa4ad2b02019-03-18 22:15:32 -0700253 g.subName = ctx.ModuleSubDir()
254
Colin Cross5ed99c62016-11-22 12:55:55 -0800255 if len(g.properties.Export_include_dirs) > 0 {
256 for _, dir := range g.properties.Export_include_dirs {
257 g.exportedIncludeDirs = append(g.exportedIncludeDirs,
Colin Cross1a527682019-09-23 15:55:30 -0700258 android.PathForModuleGen(ctx, g.subDir, ctx.ModuleDir(), dir))
Liz Kammerd38c87c2023-07-17 09:58:50 -0400259 // Also export without ModuleDir for consistency with Export_include_dirs not being set
260 g.exportedIncludeDirs = append(g.exportedIncludeDirs,
261 android.PathForModuleGen(ctx, g.subDir, dir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800262 }
263 } else {
Colin Cross1a527682019-09-23 15:55:30 -0700264 g.exportedIncludeDirs = append(g.exportedIncludeDirs, android.PathForModuleGen(ctx, g.subDir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800265 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700266
Colin Crossd11cf622021-03-23 22:30:35 -0700267 locationLabels := map[string]location{}
Colin Cross08f15ab2018-10-04 23:29:14 -0700268 firstLabel := ""
269
Colin Crossd11cf622021-03-23 22:30:35 -0700270 addLocationLabel := func(label string, loc location) {
Colin Cross08f15ab2018-10-04 23:29:14 -0700271 if firstLabel == "" {
272 firstLabel = label
273 }
274 if _, exists := locationLabels[label]; !exists {
Colin Crossd11cf622021-03-23 22:30:35 -0700275 locationLabels[label] = loc
Colin Cross08f15ab2018-10-04 23:29:14 -0700276 } else {
Anton Hansson7cd41e52021-10-08 16:13:10 +0100277 ctx.ModuleErrorf("multiple locations for label %q: %q and %q (do you have duplicate srcs entries?)",
Colin Crossd11cf622021-03-23 22:30:35 -0700278 label, locationLabels[label], loc)
Colin Cross08f15ab2018-10-04 23:29:14 -0700279 }
280 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700281
Colin Crossba9e4032020-11-24 16:32:22 -0800282 var tools android.Paths
283 var packagedTools []android.PackagingSpec
Colin Cross6f080df2016-11-04 15:32:58 -0700284 if len(g.properties.Tools) > 0 {
Colin Crossba71a3f2019-03-18 12:12:48 -0700285 seenTools := make(map[string]bool)
286
Colin Cross35143d02017-11-16 00:11:20 -0800287 ctx.VisitDirectDepsBlueprint(func(module blueprint.Module) {
Colin Cross08f15ab2018-10-04 23:29:14 -0700288 switch tag := ctx.OtherModuleDependencyTag(module).(type) {
289 case hostToolDependencyTag:
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700290 tool := ctx.OtherModuleName(module)
Martin Stjernholmdbd814d2022-01-12 23:18:30 +0000291 if m, ok := module.(android.Module); ok {
292 // Necessary to retrieve any prebuilt replacement for the tool, since
293 // toolDepsMutator runs too late for the prebuilt mutators to have
294 // replaced the dependency.
295 module = android.PrebuiltGetPreferred(ctx, m)
296 }
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700297
Colin Crossba9e4032020-11-24 16:32:22 -0800298 switch t := module.(type) {
299 case android.HostToolProvider:
300 // A HostToolProvider provides the path to a tool, which will be copied
301 // into the sandbox.
Cole Fausta963b942024-04-11 17:43:00 -0700302 if !t.(android.Module).Enabled(ctx) {
Colin Cross6510f912017-11-29 00:27:14 -0800303 if ctx.Config().AllowMissingDependencies() {
Colin Cross35143d02017-11-16 00:11:20 -0800304 ctx.AddMissingDependencies([]string{tool})
305 } else {
306 ctx.ModuleErrorf("depends on disabled module %q", tool)
307 }
Colin Crossba9e4032020-11-24 16:32:22 -0800308 return
Colin Cross35143d02017-11-16 00:11:20 -0800309 }
Colin Crossba9e4032020-11-24 16:32:22 -0800310 path := t.HostToolPath()
311 if !path.Valid() {
312 ctx.ModuleErrorf("host tool %q missing output file", tool)
313 return
314 }
315 if specs := t.TransitivePackagingSpecs(); specs != nil {
316 // If the HostToolProvider has PackgingSpecs, which are definitions of the
317 // required relative locations of the tool and its dependencies, use those
318 // instead. They will be copied to those relative locations in the sbox
319 // sandbox.
Jiyong Park8fb0e972024-03-18 18:29:37 +0900320 // Care must be taken since TransitivePackagingSpec may return device-side
321 // paths via the required property. Filter them out.
322 for i, ps := range specs {
323 if ps.Partition() != "" {
324 if i == 0 {
325 panic("first PackagingSpec is assumed to be the host-side tool")
326 }
327 continue
328 }
329 packagedTools = append(packagedTools, ps)
330 }
Colin Crossba9e4032020-11-24 16:32:22 -0800331 // Assume that the first PackagingSpec of the module is the tool.
Colin Crossd11cf622021-03-23 22:30:35 -0700332 addLocationLabel(tag.label, packagedToolLocation{specs[0]})
Colin Crossba9e4032020-11-24 16:32:22 -0800333 } else {
334 tools = append(tools, path.Path())
Colin Crossd11cf622021-03-23 22:30:35 -0700335 addLocationLabel(tag.label, toolLocation{android.Paths{path.Path()}})
Colin Crossba9e4032020-11-24 16:32:22 -0800336 }
337 case bootstrap.GoBinaryTool:
338 // A GoBinaryTool provides the install path to a tool, which will be copied.
Colin Crossa44551f2021-10-25 15:36:21 -0700339 p := android.PathForGoBinary(ctx, t)
340 tools = append(tools, p)
341 addLocationLabel(tag.label, toolLocation{android.Paths{p}})
Colin Crossba9e4032020-11-24 16:32:22 -0800342 default:
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700343 ctx.ModuleErrorf("%q is not a host tool provider", tool)
Colin Crossba9e4032020-11-24 16:32:22 -0800344 return
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700345 }
346
Colin Crossba9e4032020-11-24 16:32:22 -0800347 seenTools[tag.label] = true
Colin Crossd350ecd2015-04-28 13:25:36 -0700348 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700349 })
Colin Crossba71a3f2019-03-18 12:12:48 -0700350
351 // If AllowMissingDependencies is enabled, the build will not have stopped when
352 // AddFarVariationDependencies was called on a missing tool, which will result in nonsensical
Liz Kammer20ebfb42020-07-28 11:32:07 -0700353 // "cmd: unknown location label ..." errors later. Add a placeholder file to the local label.
354 // The command that uses this placeholder file will never be executed because the rule will be
355 // replaced with an android.Error rule reporting the missing dependencies.
Colin Crossba71a3f2019-03-18 12:12:48 -0700356 if ctx.Config().AllowMissingDependencies() {
357 for _, tool := range g.properties.Tools {
358 if !seenTools[tool] {
Colin Crossd11cf622021-03-23 22:30:35 -0700359 addLocationLabel(tool, errorLocation{"***missing tool " + tool + "***"})
Colin Crossba71a3f2019-03-18 12:12:48 -0700360 }
361 }
362 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700363 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700364
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700365 if ctx.Failed() {
366 return
367 }
368
Colin Cross08f15ab2018-10-04 23:29:14 -0700369 for _, toolFile := range g.properties.Tool_files {
Colin Cross8a497952019-03-05 22:25:09 -0800370 paths := android.PathsForModuleSrc(ctx, []string{toolFile})
Colin Crossba9e4032020-11-24 16:32:22 -0800371 tools = append(tools, paths...)
Colin Crossd11cf622021-03-23 22:30:35 -0700372 addLocationLabel(toolFile, toolLocation{paths})
Colin Cross08f15ab2018-10-04 23:29:14 -0700373 }
374
Liz Kammer81fec182023-06-09 13:33:45 -0400375 addLabelsForInputs := func(propName string, include, exclude []string) android.Paths {
Liz Kammer81fec182023-06-09 13:33:45 -0400376 includeDirInPaths := ctx.DeviceConfig().BuildBrokenInputDir(g.Name())
377 var srcFiles android.Paths
378 for _, in := range include {
379 paths, missingDeps := android.PathsAndMissingDepsRelativeToModuleSourceDir(android.SourceInput{
380 Context: ctx, Paths: []string{in}, ExcludePaths: exclude, IncludeDirs: includeDirInPaths,
381 })
382 if len(missingDeps) > 0 {
383 if !ctx.Config().AllowMissingDependencies() {
384 panic(fmt.Errorf("should never get here, the missing dependencies %q should have been reported in DepsMutator",
385 missingDeps))
386 }
387
388 // If AllowMissingDependencies is enabled, the build will not have stopped when
389 // the dependency was added on a missing SourceFileProducer module, which will result in nonsensical
390 // "cmd: label ":..." has no files" errors later. Add a placeholder file to the local label.
391 // The command that uses this placeholder file will never be executed because the rule will be
392 // replaced with an android.Error rule reporting the missing dependencies.
393 ctx.AddMissingDependencies(missingDeps)
394 addLocationLabel(in, errorLocation{"***missing " + propName + " " + in + "***"})
395 } else {
396 srcFiles = append(srcFiles, paths...)
397 addLocationLabel(in, inputLocation{paths})
398 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700399 }
Liz Kammer81fec182023-06-09 13:33:45 -0400400 return srcFiles
Colin Cross08f15ab2018-10-04 23:29:14 -0700401 }
Liz Kammer81fec182023-06-09 13:33:45 -0400402 srcFiles := addLabelsForInputs("srcs", g.properties.Srcs, g.properties.Exclude_srcs)
Colin Cross40213022023-12-13 15:19:49 -0800403 android.SetProvider(ctx, blueprint.SrcsFileProviderKey, blueprint.SrcsFileProviderData{SrcPaths: srcFiles.Strings()})
Colin Cross08f15ab2018-10-04 23:29:14 -0700404
Colin Cross1a527682019-09-23 15:55:30 -0700405 var copyFrom android.Paths
406 var outputFiles android.WritablePaths
407 var zipArgs strings.Builder
Colin Cross08f15ab2018-10-04 23:29:14 -0700408
Colin Crossf3bfd022021-09-27 15:15:06 -0700409 cmd := String(g.properties.Cmd)
410 if g.CmdModifier != nil {
411 cmd = g.CmdModifier(ctx, cmd)
412 }
413
Liz Kammer796921d2023-07-11 08:21:41 -0400414 var extraInputs android.Paths
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500415 // Generate tasks, either from genrule or gensrcs.
Liz Kammer81fec182023-06-09 13:33:45 -0400416 for i, task := range g.taskGenerator(ctx, cmd, srcFiles) {
Colin Cross3d680512020-11-13 16:23:53 -0800417 if len(task.out) == 0 {
418 ctx.ModuleErrorf("must have at least one output file")
419 return
Colin Cross85a2e892018-07-09 09:45:06 -0700420 }
421
Liz Kammer81fec182023-06-09 13:33:45 -0400422 // Only handle extra inputs once as these currently are the same across all tasks
423 if i == 0 {
424 for name, values := range task.extraInputs {
425 extraInputs = append(extraInputs, addLabelsForInputs(name, values, []string{})...)
426 }
427 }
428
Colin Crossf1a035e2020-11-16 17:32:30 -0800429 // Pick a unique path outside the task.genDir for the sbox manifest textproto,
430 // a unique rule name, and the user-visible description.
431 manifestName := "genrule.sbox.textproto"
432 desc := "generate"
433 name := "generator"
434 if task.shards > 0 {
435 manifestName = "genrule_" + strconv.Itoa(task.shard) + ".sbox.textproto"
436 desc += " " + strconv.Itoa(task.shard)
437 name += strconv.Itoa(task.shard)
438 } else if len(task.out) == 1 {
439 desc += " " + task.out[0].Base()
440 }
441
442 manifestPath := android.PathForModuleOut(ctx, manifestName)
443
444 // Use a RuleBuilder to create a rule that runs the command inside an sbox sandbox.
Yu Liu6a7940c2023-05-09 17:12:22 -0700445 rule := getSandboxedRuleBuilder(ctx, android.NewRuleBuilder(pctx, ctx).Sbox(task.genDir, manifestPath))
Justin Yun4da4ccc2023-07-06 10:56:29 +0900446 if Bool(g.properties.Write_if_changed) {
447 rule.Restat()
448 }
Colin Crossf1a035e2020-11-16 17:32:30 -0800449 cmd := rule.Command()
450
Colin Cross3d680512020-11-13 16:23:53 -0800451 for _, out := range task.out {
Colin Crossd11cf622021-03-23 22:30:35 -0700452 addLocationLabel(out.Rel(), outputLocation{out})
Colin Cross3d680512020-11-13 16:23:53 -0800453 }
454
Colin Cross3d680512020-11-13 16:23:53 -0800455 rawCommand, err := android.Expand(task.cmd, func(name string) (string, error) {
Colin Cross1a527682019-09-23 15:55:30 -0700456 // report the error directly without returning an error to android.Expand to catch multiple errors in a
457 // single run
Colin Cross3d680512020-11-13 16:23:53 -0800458 reportError := func(fmt string, args ...interface{}) (string, error) {
Colin Cross1a527682019-09-23 15:55:30 -0700459 ctx.PropertyErrorf("cmd", fmt, args...)
Colin Cross3d680512020-11-13 16:23:53 -0800460 return "SOONG_ERROR", nil
Colin Cross6f080df2016-11-04 15:32:58 -0700461 }
Colin Cross1a527682019-09-23 15:55:30 -0700462
Jihoon Kangc170af42022-08-20 05:26:38 +0000463 // Apply shell escape to each cases to prevent source file paths containing $ from being evaluated in shell
Colin Cross1a527682019-09-23 15:55:30 -0700464 switch name {
465 case "location":
466 if len(g.properties.Tools) == 0 && len(g.properties.Tool_files) == 0 {
467 return reportError("at least one `tools` or `tool_files` is required if $(location) is used")
Colin Cross6f080df2016-11-04 15:32:58 -0700468 }
Colin Crossd11cf622021-03-23 22:30:35 -0700469 loc := locationLabels[firstLabel]
470 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700471 if len(paths) == 0 {
472 return reportError("default label %q has no files", firstLabel)
473 } else if len(paths) > 1 {
474 return reportError("default label %q has multiple files, use $(locations %s) to reference it",
475 firstLabel, firstLabel)
Colin Cross08f15ab2018-10-04 23:29:14 -0700476 }
Jihoon Kangc170af42022-08-20 05:26:38 +0000477 return proptools.ShellEscape(paths[0]), nil
Colin Cross1a527682019-09-23 15:55:30 -0700478 case "in":
Jihoon Kangc170af42022-08-20 05:26:38 +0000479 return strings.Join(proptools.ShellEscapeList(cmd.PathsForInputs(srcFiles)), " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700480 case "out":
Colin Cross3d680512020-11-13 16:23:53 -0800481 var sandboxOuts []string
482 for _, out := range task.out {
Colin Crossf1a035e2020-11-16 17:32:30 -0800483 sandboxOuts = append(sandboxOuts, cmd.PathForOutput(out))
Colin Cross3d680512020-11-13 16:23:53 -0800484 }
Jihoon Kangc170af42022-08-20 05:26:38 +0000485 return strings.Join(proptools.ShellEscapeList(sandboxOuts), " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700486 case "genDir":
Jihoon Kangc170af42022-08-20 05:26:38 +0000487 return proptools.ShellEscape(cmd.PathForOutput(task.genDir)), nil
Colin Cross1a527682019-09-23 15:55:30 -0700488 default:
489 if strings.HasPrefix(name, "location ") {
490 label := strings.TrimSpace(strings.TrimPrefix(name, "location "))
Colin Crossd11cf622021-03-23 22:30:35 -0700491 if loc, ok := locationLabels[label]; ok {
492 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700493 if len(paths) == 0 {
494 return reportError("label %q has no files", label)
495 } else if len(paths) > 1 {
496 return reportError("label %q has multiple files, use $(locations %s) to reference it",
497 label, label)
498 }
Jihoon Kangc170af42022-08-20 05:26:38 +0000499 return proptools.ShellEscape(paths[0]), nil
Colin Cross1a527682019-09-23 15:55:30 -0700500 } else {
Anton Hanssonbebf5262022-02-23 11:42:38 +0000501 return reportError("unknown location label %q is not in srcs, out, tools or tool_files.", label)
Colin Cross1a527682019-09-23 15:55:30 -0700502 }
503 } else if strings.HasPrefix(name, "locations ") {
504 label := strings.TrimSpace(strings.TrimPrefix(name, "locations "))
Colin Crossd11cf622021-03-23 22:30:35 -0700505 if loc, ok := locationLabels[label]; ok {
506 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700507 if len(paths) == 0 {
508 return reportError("label %q has no files", label)
509 }
Cole Faustce74a592023-12-07 14:58:45 -0800510 return strings.Join(proptools.ShellEscapeList(paths), " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700511 } else {
Anton Hanssonbebf5262022-02-23 11:42:38 +0000512 return reportError("unknown locations label %q is not in srcs, out, tools or tool_files.", label)
Colin Cross1a527682019-09-23 15:55:30 -0700513 }
514 } else {
515 return reportError("unknown variable '$(%s)'", name)
516 }
Colin Cross6f080df2016-11-04 15:32:58 -0700517 }
Colin Cross1a527682019-09-23 15:55:30 -0700518 })
519
520 if err != nil {
521 ctx.PropertyErrorf("cmd", "%s", err.Error())
522 return
Colin Cross6f080df2016-11-04 15:32:58 -0700523 }
Colin Cross6f080df2016-11-04 15:32:58 -0700524
Colin Cross1a527682019-09-23 15:55:30 -0700525 g.rawCommands = append(g.rawCommands, rawCommand)
Bill Peckhamc087be12020-02-13 15:55:10 -0800526
Colin Cross3d680512020-11-13 16:23:53 -0800527 cmd.Text(rawCommand)
Liz Kammer81fec182023-06-09 13:33:45 -0400528 cmd.Implicits(srcFiles) // need to be able to reference other srcs
529 cmd.Implicits(extraInputs)
Colin Cross3d680512020-11-13 16:23:53 -0800530 cmd.ImplicitOutputs(task.out)
531 cmd.Implicits(task.in)
Colin Crossba9e4032020-11-24 16:32:22 -0800532 cmd.ImplicitTools(tools)
Colin Crossba9e4032020-11-24 16:32:22 -0800533 cmd.ImplicitPackagedTools(packagedTools)
Colin Cross3d680512020-11-13 16:23:53 -0800534
535 // Create the rule to run the genrule command inside sbox.
Colin Crossf1a035e2020-11-16 17:32:30 -0800536 rule.Build(name, desc)
Colin Cross1a527682019-09-23 15:55:30 -0700537
538 if len(task.copyTo) > 0 {
Colin Cross3d680512020-11-13 16:23:53 -0800539 // If copyTo is set, multiple shards need to be copied into a single directory.
540 // task.out contains the per-shard paths, and copyTo contains the corresponding
541 // final path. The files need to be copied into the final directory by a
542 // single rule so it can remove the directory before it starts to ensure no
543 // old files remain. zipsync already does this, so build up zipArgs that
544 // zip all the per-shard directories into a single zip.
Colin Cross1a527682019-09-23 15:55:30 -0700545 outputFiles = append(outputFiles, task.copyTo...)
546 copyFrom = append(copyFrom, task.out.Paths()...)
547 zipArgs.WriteString(" -C " + task.genDir.String())
548 zipArgs.WriteString(android.JoinWithPrefix(task.out.Strings(), " -f "))
549 } else {
550 outputFiles = append(outputFiles, task.out...)
551 }
Colin Cross6f080df2016-11-04 15:32:58 -0700552 }
553
Colin Cross1a527682019-09-23 15:55:30 -0700554 if len(copyFrom) > 0 {
Colin Cross3d680512020-11-13 16:23:53 -0800555 // Create a rule that zips all the per-shard directories into a single zip and then
556 // uses zipsync to unzip it into the final directory.
Colin Cross1a527682019-09-23 15:55:30 -0700557 ctx.Build(pctx, android.BuildParams{
Colin Crossf1885962020-11-20 15:28:30 -0800558 Rule: gensrcsMerge,
559 Implicits: copyFrom,
560 Outputs: outputFiles,
561 Description: "merge shards",
Colin Cross1a527682019-09-23 15:55:30 -0700562 Args: map[string]string{
563 "zipArgs": zipArgs.String(),
564 "tmpZip": android.PathForModuleGen(ctx, g.subDir+".zip").String(),
565 "genDir": android.PathForModuleGen(ctx, g.subDir).String(),
566 },
567 })
Colin Cross85a2e892018-07-09 09:45:06 -0700568 }
569
Colin Cross1a527682019-09-23 15:55:30 -0700570 g.outputFiles = outputFiles.Paths()
Chris Parsonsf874e462022-05-10 13:50:12 -0400571}
Jeff Gastonefc1b412017-03-29 17:29:06 -0700572
Chris Parsonsf874e462022-05-10 13:50:12 -0400573func (g *Module) GenerateAndroidBuildActions(ctx android.ModuleContext) {
574 g.generateCommonBuildActions(ctx)
575
576 // For <= 6 outputs, just embed those directly in the users. Right now, that covers >90% of
577 // the genrules on AOSP. That will make things simpler to look at the graph in the common
578 // case. For larger sets of outputs, inject a phony target in between to limit ninja file
579 // growth.
580 if len(g.outputFiles) <= 6 {
581 g.outputDeps = g.outputFiles
582 } else {
583 phonyFile := android.PathForModuleGen(ctx, "genrule-phony")
584 ctx.Build(pctx, android.BuildParams{
585 Rule: blueprint.Phony,
586 Output: phonyFile,
587 Inputs: g.outputFiles,
588 })
589 g.outputDeps = android.Paths{phonyFile}
Jeff Gaston02a684b2017-10-27 14:59:27 -0700590 }
LaMont Jonesafe7baf2024-01-09 22:47:39 +0000591 android.CollectDependencyAconfigFiles(ctx, &g.mergedAconfigFiles)
592}
593
594func (g *Module) AndroidMkEntries() []android.AndroidMkEntries {
595 ret := android.AndroidMkEntries{
596 OutputFile: android.OptionalPathForPath(g.outputFiles[0]),
597 ExtraEntries: []android.AndroidMkExtraEntriesFunc{
598 func(ctx android.AndroidMkExtraEntriesContext, entries *android.AndroidMkEntries) {
599 android.SetAconfigFileMkEntries(g.AndroidModuleBase(), entries, g.mergedAconfigFiles)
600 },
601 },
602 }
603
604 return []android.AndroidMkEntries{ret}
605}
606
607func (g *Module) AndroidModuleBase() *android.ModuleBase {
608 return &g.ModuleBase
Chris Parsonsf874e462022-05-10 13:50:12 -0400609}
610
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700611// Collect information for opening IDE project files in java/jdeps.go.
612func (g *Module) IDEInfo(dpInfo *android.IdeInfo) {
613 dpInfo.Srcs = append(dpInfo.Srcs, g.Srcs().Strings()...)
614 for _, src := range g.properties.Srcs {
615 if strings.HasPrefix(src, ":") {
616 src = strings.Trim(src, ":")
617 dpInfo.Deps = append(dpInfo.Deps, src)
618 }
619 }
620}
621
Colin Crossa4ad2b02019-03-18 22:15:32 -0700622func (g *Module) AndroidMk() android.AndroidMkData {
623 return android.AndroidMkData{
Anton Hansson72f18492020-10-30 16:34:45 +0000624 Class: "ETC",
Colin Crossa4ad2b02019-03-18 22:15:32 -0700625 OutputFile: android.OptionalPathForPath(g.outputFiles[0]),
626 SubName: g.subName,
627 Extra: []android.AndroidMkExtraFunc{
628 func(w io.Writer, outputFile android.Path) {
Anton Hansson72f18492020-10-30 16:34:45 +0000629 fmt.Fprintln(w, "LOCAL_UNINSTALLABLE_MODULE := true")
Colin Crossa4ad2b02019-03-18 22:15:32 -0700630 },
631 },
632 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
633 android.WriteAndroidMkData(w, data)
634 if data.SubName != "" {
635 fmt.Fprintln(w, ".PHONY:", name)
636 fmt.Fprintln(w, name, ":", name+g.subName)
637 }
638 },
639 }
640}
641
Jiyong Park45bf82e2020-12-15 22:29:02 +0900642var _ android.ApexModule = (*Module)(nil)
643
644// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -0700645func (g *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
646 sdkVersion android.ApiLevel) error {
Jooyung Han749dc692020-04-15 11:03:39 +0900647 // Because generated outputs are checked by client modules(e.g. cc_library, ...)
648 // we can safely ignore the check here.
649 return nil
650}
651
Jeff Gaston437d23c2017-11-08 12:38:00 -0800652func generatorFactory(taskGenerator taskFunc, props ...interface{}) *Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700653 module := &Module{
Jeff Gaston437d23c2017-11-08 12:38:00 -0800654 taskGenerator: taskGenerator,
Colin Crossd350ecd2015-04-28 13:25:36 -0700655 }
656
Colin Cross36242852017-06-23 15:06:31 -0700657 module.AddProperties(props...)
658 module.AddProperties(&module.properties)
Colin Crossd350ecd2015-04-28 13:25:36 -0700659
Colin Cross7228ecd2019-11-18 16:00:16 -0800660 module.ImageInterface = noopImageInterface{}
661
Colin Cross36242852017-06-23 15:06:31 -0700662 return module
Colin Crossd350ecd2015-04-28 13:25:36 -0700663}
664
Colin Cross7228ecd2019-11-18 16:00:16 -0800665type noopImageInterface struct{}
666
667func (x noopImageInterface) ImageMutatorBegin(android.BaseModuleContext) {}
668func (x noopImageInterface) CoreVariantNeeded(android.BaseModuleContext) bool { return false }
Yifan Hong1b3348d2020-01-21 15:53:22 -0800669func (x noopImageInterface) RamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700670func (x noopImageInterface) VendorRamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Inseob Kim08758f02021-04-08 21:13:22 +0900671func (x noopImageInterface) DebugRamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Colin Cross7228ecd2019-11-18 16:00:16 -0800672func (x noopImageInterface) RecoveryVariantNeeded(android.BaseModuleContext) bool { return false }
673func (x noopImageInterface) ExtraImageVariations(ctx android.BaseModuleContext) []string { return nil }
674func (x noopImageInterface) SetImageVariation(ctx android.BaseModuleContext, variation string, module android.Module) {
675}
676
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700677func NewGenSrcs() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700678 properties := &genSrcsProperties{}
679
Colin Crossf1885962020-11-20 15:28:30 -0800680 // finalSubDir is the name of the subdirectory that output files will be generated into.
681 // It is used so that per-shard directories can be placed alongside it an then finally
682 // merged into it.
683 const finalSubDir = "gensrcs"
684
Colin Cross1a527682019-09-23 15:55:30 -0700685 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Colin Cross1a527682019-09-23 15:55:30 -0700686 shardSize := defaultShardSize
687 if s := properties.Shard_size; s != nil {
688 shardSize = int(*s)
689 }
Jeff Gaston437d23c2017-11-08 12:38:00 -0800690
Colin Crossf1885962020-11-20 15:28:30 -0800691 // gensrcs rules can easily hit command line limits by repeating the command for
692 // every input file. Shard the input files into groups.
Colin Cross1a527682019-09-23 15:55:30 -0700693 shards := android.ShardPaths(srcFiles, shardSize)
694 var generateTasks []generateTask
Colin Crossbaccf5b2018-02-21 14:07:48 -0800695
Colin Cross1a527682019-09-23 15:55:30 -0700696 for i, shard := range shards {
697 var commands []string
698 var outFiles android.WritablePaths
699 var copyTo android.WritablePaths
Colin Cross1a527682019-09-23 15:55:30 -0700700
Colin Crossf1885962020-11-20 15:28:30 -0800701 // When sharding is enabled (i.e. len(shards) > 1), the sbox rules for each
702 // shard will be write to their own directories and then be merged together
703 // into finalSubDir. If sharding is not enabled (i.e. len(shards) == 1),
704 // the sbox rule will write directly to finalSubDir.
705 genSubDir := finalSubDir
Colin Cross1a527682019-09-23 15:55:30 -0700706 if len(shards) > 1 {
Colin Crossf1885962020-11-20 15:28:30 -0800707 genSubDir = strconv.Itoa(i)
Jeff Gaston437d23c2017-11-08 12:38:00 -0800708 }
709
Colin Crossf1885962020-11-20 15:28:30 -0800710 genDir := android.PathForModuleGen(ctx, genSubDir)
Colin Crossf1a035e2020-11-16 17:32:30 -0800711 // TODO(ccross): this RuleBuilder is a hack to be able to call
712 // rule.Command().PathForOutput. Replace this with passing the rule into the
713 // generator.
Yu Liu6a7940c2023-05-09 17:12:22 -0700714 rule := getSandboxedRuleBuilder(ctx, android.NewRuleBuilder(pctx, ctx).Sbox(genDir, nil))
Jeff Gaston437d23c2017-11-08 12:38:00 -0800715
Colin Cross3ea4eb82020-11-24 13:07:27 -0800716 for _, in := range shard {
yangbill6d032dd2024-04-18 03:05:49 +0000717 outFile := android.GenPathWithExtAndTrimExt(ctx, finalSubDir, in, String(properties.Output_extension), String(properties.Trim_extension))
Colin Crossf1885962020-11-20 15:28:30 -0800718
719 // If sharding is enabled, then outFile is the path to the output file in
720 // the shard directory, and copyTo is the path to the output file in the
721 // final directory.
Colin Cross1a527682019-09-23 15:55:30 -0700722 if len(shards) > 1 {
yangbill6d032dd2024-04-18 03:05:49 +0000723 shardFile := android.GenPathWithExtAndTrimExt(ctx, genSubDir, in, String(properties.Output_extension), String(properties.Trim_extension))
Colin Cross1a527682019-09-23 15:55:30 -0700724 copyTo = append(copyTo, outFile)
725 outFile = shardFile
726 }
727
728 outFiles = append(outFiles, outFile)
Colin Cross1a527682019-09-23 15:55:30 -0700729
Colin Crossf1885962020-11-20 15:28:30 -0800730 // pre-expand the command line to replace $in and $out with references to
731 // a single input and output file.
Colin Cross1a527682019-09-23 15:55:30 -0700732 command, err := android.Expand(rawCommand, func(name string) (string, error) {
733 switch name {
734 case "in":
735 return in.String(), nil
736 case "out":
Colin Crossf1a035e2020-11-16 17:32:30 -0800737 return rule.Command().PathForOutput(outFile), nil
Colin Cross1a527682019-09-23 15:55:30 -0700738 default:
739 return "$(" + name + ")", nil
740 }
741 })
742 if err != nil {
743 ctx.PropertyErrorf("cmd", err.Error())
744 }
745
746 // escape the command in case for example it contains '#', an odd number of '"', etc
747 command = fmt.Sprintf("bash -c %v", proptools.ShellEscape(command))
748 commands = append(commands, command)
749 }
750 fullCommand := strings.Join(commands, " && ")
751
752 generateTasks = append(generateTasks, generateTask{
Cole Faust55492572024-01-25 18:00:33 -0800753 in: shard,
754 out: outFiles,
755 copyTo: copyTo,
756 genDir: genDir,
757 cmd: fullCommand,
758 shard: i,
759 shards: len(shards),
Liz Kammer81fec182023-06-09 13:33:45 -0400760 extraInputs: map[string][]string{
761 "data": properties.Data,
762 },
Colin Cross1a527682019-09-23 15:55:30 -0700763 })
Jeff Gaston437d23c2017-11-08 12:38:00 -0800764 }
Colin Cross1a527682019-09-23 15:55:30 -0700765
766 return generateTasks
Colin Crossd350ecd2015-04-28 13:25:36 -0700767 }
768
Colin Cross1a527682019-09-23 15:55:30 -0700769 g := generatorFactory(taskGenerator, properties)
Colin Crossf1885962020-11-20 15:28:30 -0800770 g.subDir = finalSubDir
Colin Cross1a527682019-09-23 15:55:30 -0700771 return g
Colin Crossd350ecd2015-04-28 13:25:36 -0700772}
773
Colin Cross54190b32017-10-09 15:34:10 -0700774func GenSrcsFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700775 m := NewGenSrcs()
776 android.InitAndroidModule(m)
777 return m
778}
779
Colin Crossd350ecd2015-04-28 13:25:36 -0700780type genSrcsProperties struct {
Colin Cross7d5136f2015-05-11 13:39:40 -0700781 // extension that will be substituted for each output file
Nan Zhanga5e7cb42017-11-09 22:42:32 -0800782 Output_extension *string
Colin Cross1a527682019-09-23 15:55:30 -0700783
784 // maximum number of files that will be passed on a single command line.
785 Shard_size *int64
Liz Kammer81fec182023-06-09 13:33:45 -0400786
787 // Additional files needed for build that are not tooling related.
788 Data []string `android:"path"`
yangbill6d032dd2024-04-18 03:05:49 +0000789
790 // Trim the matched extension for each input file, and it should start with ".".
791 Trim_extension *string
Colin Cross5049f022015-03-18 13:28:46 -0700792}
793
Evgenii Stepanovf47c90d2020-12-02 18:55:09 -0800794const defaultShardSize = 50
Colin Cross1a527682019-09-23 15:55:30 -0700795
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700796func NewGenRule() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700797 properties := &genRuleProperties{}
Colin Cross5049f022015-03-18 13:28:46 -0700798
Colin Cross1a527682019-09-23 15:55:30 -0700799 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700800 outs := make(android.WritablePaths, len(properties.Out))
801 for i, out := range properties.Out {
Cole Faust55492572024-01-25 18:00:33 -0800802 outs[i] = android.PathForModuleGen(ctx, out)
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700803 }
Colin Cross1a527682019-09-23 15:55:30 -0700804 return []generateTask{{
Cole Faust55492572024-01-25 18:00:33 -0800805 in: srcFiles,
806 out: outs,
807 genDir: android.PathForModuleGen(ctx),
808 cmd: rawCommand,
Colin Cross1a527682019-09-23 15:55:30 -0700809 }}
Colin Cross5049f022015-03-18 13:28:46 -0700810 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700811
Jeff Gaston437d23c2017-11-08 12:38:00 -0800812 return generatorFactory(taskGenerator, properties)
Colin Cross5049f022015-03-18 13:28:46 -0700813}
814
Colin Cross54190b32017-10-09 15:34:10 -0700815func GenRuleFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700816 m := NewGenRule()
817 android.InitAndroidModule(m)
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800818 android.InitDefaultableModule(m)
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700819 return m
820}
821
Colin Crossd350ecd2015-04-28 13:25:36 -0700822type genRuleProperties struct {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700823 // names of the output files that will be generated
kellyhung750334a2024-03-14 01:03:49 +0800824 Out []string `android:"arch_variant"`
Colin Cross5049f022015-03-18 13:28:46 -0700825}
Nan Zhangea568a42017-11-08 21:20:04 -0800826
827var Bool = proptools.Bool
828var String = proptools.String
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800829
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800830// Defaults
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800831type Defaults struct {
832 android.ModuleBase
833 android.DefaultsModuleBase
834}
835
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800836func defaultsFactory() android.Module {
837 return DefaultsFactory()
838}
839
840func DefaultsFactory(props ...interface{}) android.Module {
841 module := &Defaults{}
842
843 module.AddProperties(props...)
844 module.AddProperties(
845 &generatorProperties{},
846 &genRuleProperties{},
847 )
848
849 android.InitDefaultsModule(module)
850
851 return module
852}
Yu Liu6a7940c2023-05-09 17:12:22 -0700853
Yu Liue7f7cbf2023-06-13 18:50:03 +0000854var sandboxingAllowlistKey = android.NewOnceKey("genruleSandboxingAllowlistKey")
855
856type sandboxingAllowlistSets struct {
857 sandboxingDenyModuleSet map[string]bool
Yu Liue7f7cbf2023-06-13 18:50:03 +0000858}
859
860func getSandboxingAllowlistSets(ctx android.PathContext) *sandboxingAllowlistSets {
861 return ctx.Config().Once(sandboxingAllowlistKey, func() interface{} {
862 sandboxingDenyModuleSet := map[string]bool{}
Yu Liue7f7cbf2023-06-13 18:50:03 +0000863
Cole Faust55492572024-01-25 18:00:33 -0800864 android.AddToStringSet(sandboxingDenyModuleSet, SandboxingDenyModuleList)
Yu Liue7f7cbf2023-06-13 18:50:03 +0000865 return &sandboxingAllowlistSets{
866 sandboxingDenyModuleSet: sandboxingDenyModuleSet,
Yu Liue7f7cbf2023-06-13 18:50:03 +0000867 }
868 }).(*sandboxingAllowlistSets)
869}
Liz Kammer0db0e342023-07-18 11:39:30 -0400870
Yu Liu6a7940c2023-05-09 17:12:22 -0700871func getSandboxedRuleBuilder(ctx android.ModuleContext, r *android.RuleBuilder) *android.RuleBuilder {
Yu Liu45d6af52023-05-24 23:10:18 +0000872 if !ctx.DeviceConfig().GenruleSandboxing() {
873 return r.SandboxTools()
874 }
Yu Liue7f7cbf2023-06-13 18:50:03 +0000875 sandboxingAllowlistSets := getSandboxingAllowlistSets(ctx)
Cole Fauste762b942024-03-15 12:46:14 -0700876 if sandboxingAllowlistSets.sandboxingDenyModuleSet[ctx.ModuleName()] {
Yu Liu6a7940c2023-05-09 17:12:22 -0700877 return r.SandboxTools()
878 }
879 return r.SandboxInputs()
880}