blob: a48038bac7ff4b0d2313f4ca1afa2d67f38f9672 [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"
Nan Zhangea568a42017-11-08 21:20:04 -080028 "github.com/google/blueprint/proptools"
Colin Cross5049f022015-03-18 13:28:46 -070029
Colin Cross635c3b02016-05-18 15:37:25 -070030 "android/soong/android"
Colin Cross5049f022015-03-18 13:28:46 -070031)
32
Colin Cross463a90e2015-06-17 14:20:06 -070033func init() {
Colin Crosse9fe2942020-11-10 18:12:15 -080034 RegisterGenruleBuildComponents(android.InitRegistrationContext)
Martin Stjernholm710ec3a2020-01-16 15:12:04 +000035}
Jaewoong Jung98716bd2018-12-10 08:13:18 -080036
Paul Duffin672cb9f2021-03-03 02:30:37 +000037// Test fixture preparer that will register most genrule build components.
38//
39// Singletons and mutators should only be added here if they are needed for a majority of genrule
40// module types, otherwise they should be added under a separate preparer to allow them to be
41// selected only when needed to reduce test execution time.
42//
43// Module types do not have much of an overhead unless they are used so this should include as many
44// module types as possible. The exceptions are those module types that require mutators and/or
45// singletons in order to function in which case they should be kept together in a separate
46// preparer.
47var PrepareForTestWithGenRuleBuildComponents = android.GroupFixturePreparers(
48 android.FixtureRegisterWithContext(RegisterGenruleBuildComponents),
49)
50
51// Prepare a fixture to use all genrule module types, mutators and singletons fully.
52//
53// This should only be used by tests that want to run with as much of the build enabled as possible.
54var PrepareForIntegrationTestWithGenrule = android.GroupFixturePreparers(
55 PrepareForTestWithGenRuleBuildComponents,
56)
57
Colin Crosse9fe2942020-11-10 18:12:15 -080058func RegisterGenruleBuildComponents(ctx android.RegistrationContext) {
Martin Stjernholm710ec3a2020-01-16 15:12:04 +000059 ctx.RegisterModuleType("genrule_defaults", defaultsFactory)
60
61 ctx.RegisterModuleType("gensrcs", GenSrcsFactory)
62 ctx.RegisterModuleType("genrule", GenRuleFactory)
63
64 ctx.FinalDepsMutators(func(ctx android.RegisterMutatorsContext) {
65 ctx.BottomUp("genrule_tool_deps", toolDepsMutator).Parallel()
66 })
Liz Kammer356f7d42021-01-26 09:18:53 -050067}
68
Colin Cross5049f022015-03-18 13:28:46 -070069var (
Colin Cross635c3b02016-05-18 15:37:25 -070070 pctx = android.NewPackageContext("android/soong/genrule")
Colin Cross1a527682019-09-23 15:55:30 -070071
Alex Humesky29e3bbe2020-11-20 21:30:13 -050072 // Used by gensrcs when there is more than 1 shard to merge the outputs
73 // of each shard into a zip file.
Colin Cross1a527682019-09-23 15:55:30 -070074 gensrcsMerge = pctx.AndroidStaticRule("gensrcsMerge", blueprint.RuleParams{
75 Command: "${soongZip} -o ${tmpZip} @${tmpZip}.rsp && ${zipSync} -d ${genDir} ${tmpZip}",
76 CommandDeps: []string{"${soongZip}", "${zipSync}"},
77 Rspfile: "${tmpZip}.rsp",
78 RspfileContent: "${zipArgs}",
79 }, "tmpZip", "genDir", "zipArgs")
Colin Cross5049f022015-03-18 13:28:46 -070080)
81
Jeff Gastonefc1b412017-03-29 17:29:06 -070082func init() {
Dan Willemsenddf504c2019-08-09 16:21:29 -070083 pctx.Import("android/soong/android")
Colin Cross1a527682019-09-23 15:55:30 -070084
85 pctx.HostBinToolVariable("soongZip", "soong_zip")
86 pctx.HostBinToolVariable("zipSync", "zipsync")
Jeff Gastonefc1b412017-03-29 17:29:06 -070087}
88
Colin Cross5049f022015-03-18 13:28:46 -070089type SourceFileGenerator interface {
Colin Cross635c3b02016-05-18 15:37:25 -070090 GeneratedSourceFiles() android.Paths
Colin Cross5ed99c62016-11-22 12:55:55 -080091 GeneratedHeaderDirs() android.Paths
Dan Willemsen9da9d492018-02-21 18:28:18 -080092 GeneratedDeps() android.Paths
Colin Cross5049f022015-03-18 13:28:46 -070093}
94
Colin Crossfe17f6f2019-03-28 19:30:56 -070095// Alias for android.HostToolProvider
96// Deprecated: use android.HostToolProvider instead.
Colin Crossd350ecd2015-04-28 13:25:36 -070097type HostToolProvider interface {
Colin Crossfe17f6f2019-03-28 19:30:56 -070098 android.HostToolProvider
Colin Crossd350ecd2015-04-28 13:25:36 -070099}
Colin Cross5049f022015-03-18 13:28:46 -0700100
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700101type hostToolDependencyTag struct {
102 blueprint.BaseDependencyTag
Colin Cross65cb3142021-12-10 23:05:02 +0000103 android.LicenseAnnotationToolchainDependencyTag
Colin Cross08f15ab2018-10-04 23:29:14 -0700104 label string
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700105}
Martin Stjernholmdbd814d2022-01-12 23:18:30 +0000106
107func (t hostToolDependencyTag) AllowDisabledModuleDependency(target android.Module) bool {
108 // Allow depending on a disabled module if it's replaced by a prebuilt
109 // counterpart. We get the prebuilt through android.PrebuiltGetPreferred in
110 // GenerateAndroidBuildActions.
111 return target.IsReplacedByPrebuilt()
112}
113
114var _ android.AllowDisabledModuleDependency = (*hostToolDependencyTag)(nil)
115
Colin Cross7d5136f2015-05-11 13:39:40 -0700116type generatorProperties struct {
Spandan Das93e95992021-07-29 18:26:39 +0000117 // The command to run on one or more input files. Cmd supports substitution of a few variables.
Jeff Gastonefc1b412017-03-29 17:29:06 -0700118 //
119 // Available variables for substitution:
120 //
Spandan Das93e95992021-07-29 18:26:39 +0000121 // $(location): the path to the first entry in tools or tool_files.
122 // $(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.
123 // $(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.
124 // $(in): one or more input files.
125 // $(out): a single output file.
Spandan Das93e95992021-07-29 18:26:39 +0000126 // $(genDir): the sandbox directory for this tool; contains $(out).
Colin Cross2296f5b2017-10-17 21:38:14 -0700127 // $$: a literal $
Aleks Todorov1eb06c42024-06-03 15:23:56 +0100128 Cmd proptools.Configurable[string] `android:"replace_instead_of_append"`
Colin Cross7d5136f2015-05-11 13:39:40 -0700129
Colin Cross6f080df2016-11-04 15:32:58 -0700130 // name of the modules (if any) that produces the host executable. Leave empty for
Colin Cross7d5136f2015-05-11 13:39:40 -0700131 // prebuilts or scripts that do not need a module to build them.
Colin Cross6f080df2016-11-04 15:32:58 -0700132 Tools []string
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700133
Sam Delmericof8775632023-08-14 23:45:41 +0000134 // Local files that are used by the tool
Colin Cross27b922f2019-03-04 22:35:41 -0800135 Tool_files []string `android:"path"`
Colin Cross5ed99c62016-11-22 12:55:55 -0800136
137 // List of directories to export generated headers from
138 Export_include_dirs []string
Colin Cross708c4242017-01-13 18:05:49 -0800139
140 // list of input files
Inseob Kim2f730622024-07-23 14:03:40 +0900141 Srcs proptools.Configurable[[]string] `android:"path,arch_variant"`
142 ResolvedSrcs []string `blueprint:"mutated"`
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
Cole Faust78f3c3a2024-08-15 17:19:34 -0700149
150 // When set to true, an additional $(build_number_file) label will be available
151 // to use in the cmd. This will be the location of a text file containing the
152 // build number. The dependency on this file will be "order-only", meaning that
153 // the genrule will not rerun when only this file changes, to avoid rerunning
154 // the genrule every build, because the build number changes every build.
155 // This also means that you should not attempt to consume the build number from
156 // the result of this genrule in another build rule. If you do, the build number
157 // in the second build rule will be stale when the second build rule rebuilds
158 // but this genrule does not. Only certain allowlisted modules are allowed to
159 // use this property, usages of the build number should be kept to the absolute
160 // minimum. Particularly no modules on the system image may include the build
161 // number. Prefer using libbuildversion via the use_version_lib property on
162 // cc modules.
163 Uses_order_only_build_number_file *bool
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400164}
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500165
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700166type Module struct {
Colin Cross635c3b02016-05-18 15:37:25 -0700167 android.ModuleBase
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800168 android.DefaultableModuleBase
Jiyong Parkfc752ca2019-06-12 13:27:29 +0900169 android.ApexModuleBase
Colin Crossd350ecd2015-04-28 13:25:36 -0700170
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700171 // For other packages to make their own genrules with extra
172 // properties
173 Extra interface{}
Colin Crossf3bfd022021-09-27 15:15:06 -0700174
175 // CmdModifier can be set by wrappers around genrule to modify the command, for example to
176 // prefix environment variables to it.
177 CmdModifier func(ctx android.ModuleContext, cmd string) string
178
Colin Cross7228ecd2019-11-18 16:00:16 -0800179 android.ImageInterface
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700180
Colin Cross7d5136f2015-05-11 13:39:40 -0700181 properties generatorProperties
Colin Crossd350ecd2015-04-28 13:25:36 -0700182
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500183 // For the different tasks that genrule and gensrc generate. genrule will
184 // generate 1 task, and gensrc will generate 1 or more tasks based on the
185 // number of shards the input files are sharded into.
Jeff Gaston437d23c2017-11-08 12:38:00 -0800186 taskGenerator taskFunc
Colin Crossd350ecd2015-04-28 13:25:36 -0700187
Colin Cross1a527682019-09-23 15:55:30 -0700188 rule blueprint.Rule
189 rawCommands []string
Colin Crossd350ecd2015-04-28 13:25:36 -0700190
Colin Cross5ed99c62016-11-22 12:55:55 -0800191 exportedIncludeDirs android.Paths
Dan Willemsenb40aab62016-04-20 14:21:14 -0700192
Colin Cross635c3b02016-05-18 15:37:25 -0700193 outputFiles android.Paths
Dan Willemsen9da9d492018-02-21 18:28:18 -0800194 outputDeps android.Paths
Colin Crossa4ad2b02019-03-18 22:15:32 -0700195
196 subName string
Colin Cross1a527682019-09-23 15:55:30 -0700197 subDir string
Colin Crossd350ecd2015-04-28 13:25:36 -0700198}
199
Colin Cross1a527682019-09-23 15:55:30 -0700200type taskFunc func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask
Colin Crossd350ecd2015-04-28 13:25:36 -0700201
202type generateTask struct {
Liz Kammer81fec182023-06-09 13:33:45 -0400203 in android.Paths
204 out android.WritablePaths
Liz Kammer81fec182023-06-09 13:33:45 -0400205 copyTo android.WritablePaths // For gensrcs to set on gensrcsMerge rule.
206 genDir android.WritablePath
Liz Kammer81fec182023-06-09 13:33:45 -0400207 extraInputs map[string][]string
Colin Cross3ea4eb82020-11-24 13:07:27 -0800208
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500209 cmd string
210 // For gensrsc sharding.
Colin Cross3ea4eb82020-11-24 13:07:27 -0800211 shard int
212 shards int
Colin Crossd350ecd2015-04-28 13:25:36 -0700213}
214
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700215func (g *Module) GeneratedSourceFiles() android.Paths {
Colin Crossd350ecd2015-04-28 13:25:36 -0700216 return g.outputFiles
217}
218
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700219func (g *Module) Srcs() android.Paths {
Nan Zhange42777a2018-03-27 16:19:42 -0700220 return append(android.Paths{}, g.outputFiles...)
Colin Cross068e0fe2016-12-13 15:23:47 -0800221}
222
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700223func (g *Module) GeneratedHeaderDirs() android.Paths {
Colin Cross5ed99c62016-11-22 12:55:55 -0800224 return g.exportedIncludeDirs
Dan Willemsenb40aab62016-04-20 14:21:14 -0700225}
226
Dan Willemsen9da9d492018-02-21 18:28:18 -0800227func (g *Module) GeneratedDeps() android.Paths {
228 return g.outputDeps
229}
230
Jooyung Han8c7e3ed2021-06-28 17:35:58 +0900231var _ android.SourceFileProducer = (*Module)(nil)
Jooyung Han8c7e3ed2021-06-28 17:35:58 +0900232
Martin Stjernholm710ec3a2020-01-16 15:12:04 +0000233func toolDepsMutator(ctx android.BottomUpMutatorContext) {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700234 if g, ok := ctx.Module().(*Module); ok {
Colin Cross08f15ab2018-10-04 23:29:14 -0700235 for _, tool := range g.properties.Tools {
236 tag := hostToolDependencyTag{label: tool}
237 if m := android.SrcIsModule(tool); m != "" {
238 tool = m
239 }
Colin Cross0f7d2ef2019-10-16 11:03:10 -0700240 ctx.AddFarVariationDependencies(ctx.Config().BuildOSTarget.Variations(), tag, tool)
Colin Cross6362e272015-10-29 15:25:03 -0700241 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700242 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700243}
244
Cole Faustf23fdc02024-08-23 15:21:13 -0700245var buildNumberAllowlistKey = android.NewOnceKey("genruleBuildNumberAllowlistKey")
246
Cole Faust78f3c3a2024-08-15 17:19:34 -0700247// This allowlist should be kept to the bare minimum, it's
248// intended for things that existed before the build number
249// was tightly controlled. Prefer using libbuildversion
250// via the use_version_lib property of cc modules.
Cole Faustf23fdc02024-08-23 15:21:13 -0700251// This is a function instead of a global map so that
252// soong plugins cannot add entries to the allowlist
253func isModuleInBuildNumberAllowlist(ctx android.ModuleContext) bool {
254 allowlist := ctx.Config().Once(buildNumberAllowlistKey, func() interface{} {
Cole Faustdc018782024-08-28 11:08:06 -0700255 // Define the allowlist as a list and then copy it into a map so that
256 // gofmt doesn't change unnecessary lines trying to align the values of the map.
257 allowlist := []string{
Cole Faustf23fdc02024-08-23 15:21:13 -0700258 // go/keep-sorted start
Cole Faustdc018782024-08-28 11:08:06 -0700259 "build/soong/tests:gen",
260 "hardware/google/camera/common/hal/aidl_service:aidl_camera_build_version",
261 "tools/tradefederation/core:tradefed_zip",
262 "vendor/google/services/LyricCameraHAL/src/apex:com.google.pixel.camera.hal.manifest",
Cole Faustf23fdc02024-08-23 15:21:13 -0700263 // go/keep-sorted end
264 }
Cole Faustdc018782024-08-28 11:08:06 -0700265 allowlistMap := make(map[string]bool, len(allowlist))
266 for _, a := range allowlist {
267 allowlistMap[a] = true
268 }
269 return allowlistMap
Cole Faustf23fdc02024-08-23 15:21:13 -0700270 }).(map[string]bool)
271
272 _, ok := allowlist[ctx.ModuleDir()+":"+ctx.ModuleName()]
273 return ok
Cole Faust78f3c3a2024-08-15 17:19:34 -0700274}
275
Chris Parsonsf874e462022-05-10 13:50:12 -0400276// generateCommonBuildActions contains build action generation logic
277// common to both the mixed build case and the legacy case of genrule processing.
278// To fully support genrule in mixed builds, the contents of this function should
279// approach zero; there should be no genrule action registration done directly
280// by Soong logic in the mixed-build case.
281func (g *Module) generateCommonBuildActions(ctx android.ModuleContext) {
Colin Crossa4ad2b02019-03-18 22:15:32 -0700282 g.subName = ctx.ModuleSubDir()
283
Colin Cross5ed99c62016-11-22 12:55:55 -0800284 if len(g.properties.Export_include_dirs) > 0 {
285 for _, dir := range g.properties.Export_include_dirs {
286 g.exportedIncludeDirs = append(g.exportedIncludeDirs,
Colin Cross1a527682019-09-23 15:55:30 -0700287 android.PathForModuleGen(ctx, g.subDir, ctx.ModuleDir(), dir))
Liz Kammerd38c87c2023-07-17 09:58:50 -0400288 // Also export without ModuleDir for consistency with Export_include_dirs not being set
289 g.exportedIncludeDirs = append(g.exportedIncludeDirs,
290 android.PathForModuleGen(ctx, g.subDir, dir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800291 }
292 } else {
Colin Cross1a527682019-09-23 15:55:30 -0700293 g.exportedIncludeDirs = append(g.exportedIncludeDirs, android.PathForModuleGen(ctx, g.subDir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800294 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700295
Colin Crossd11cf622021-03-23 22:30:35 -0700296 locationLabels := map[string]location{}
Colin Cross08f15ab2018-10-04 23:29:14 -0700297 firstLabel := ""
298
Colin Crossd11cf622021-03-23 22:30:35 -0700299 addLocationLabel := func(label string, loc location) {
Colin Cross08f15ab2018-10-04 23:29:14 -0700300 if firstLabel == "" {
301 firstLabel = label
302 }
303 if _, exists := locationLabels[label]; !exists {
Colin Crossd11cf622021-03-23 22:30:35 -0700304 locationLabels[label] = loc
Colin Cross08f15ab2018-10-04 23:29:14 -0700305 } else {
Anton Hansson7cd41e52021-10-08 16:13:10 +0100306 ctx.ModuleErrorf("multiple locations for label %q: %q and %q (do you have duplicate srcs entries?)",
Colin Crossd11cf622021-03-23 22:30:35 -0700307 label, locationLabels[label], loc)
Colin Cross08f15ab2018-10-04 23:29:14 -0700308 }
309 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700310
Colin Crossba9e4032020-11-24 16:32:22 -0800311 var tools android.Paths
312 var packagedTools []android.PackagingSpec
Colin Cross6f080df2016-11-04 15:32:58 -0700313 if len(g.properties.Tools) > 0 {
Colin Crossba71a3f2019-03-18 12:12:48 -0700314 seenTools := make(map[string]bool)
315
Colin Cross35143d02017-11-16 00:11:20 -0800316 ctx.VisitDirectDepsBlueprint(func(module blueprint.Module) {
Colin Cross08f15ab2018-10-04 23:29:14 -0700317 switch tag := ctx.OtherModuleDependencyTag(module).(type) {
318 case hostToolDependencyTag:
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700319 tool := ctx.OtherModuleName(module)
Martin Stjernholmdbd814d2022-01-12 23:18:30 +0000320 if m, ok := module.(android.Module); ok {
321 // Necessary to retrieve any prebuilt replacement for the tool, since
322 // toolDepsMutator runs too late for the prebuilt mutators to have
323 // replaced the dependency.
324 module = android.PrebuiltGetPreferred(ctx, m)
325 }
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700326
Colin Crossba9e4032020-11-24 16:32:22 -0800327 switch t := module.(type) {
328 case android.HostToolProvider:
329 // A HostToolProvider provides the path to a tool, which will be copied
330 // into the sandbox.
Cole Fausta963b942024-04-11 17:43:00 -0700331 if !t.(android.Module).Enabled(ctx) {
Colin Cross6510f912017-11-29 00:27:14 -0800332 if ctx.Config().AllowMissingDependencies() {
Colin Cross35143d02017-11-16 00:11:20 -0800333 ctx.AddMissingDependencies([]string{tool})
334 } else {
335 ctx.ModuleErrorf("depends on disabled module %q", tool)
336 }
Colin Crossba9e4032020-11-24 16:32:22 -0800337 return
Colin Cross35143d02017-11-16 00:11:20 -0800338 }
Colin Crossba9e4032020-11-24 16:32:22 -0800339 path := t.HostToolPath()
340 if !path.Valid() {
341 ctx.ModuleErrorf("host tool %q missing output file", tool)
342 return
343 }
Yu Liubad1eef2024-08-21 22:37:35 +0000344 if specs := android.OtherModuleProviderOrDefault(
345 ctx, t, android.InstallFilesProvider).TransitivePackagingSpecs.ToList(); specs != nil {
Colin Crossba9e4032020-11-24 16:32:22 -0800346 // If the HostToolProvider has PackgingSpecs, which are definitions of the
347 // required relative locations of the tool and its dependencies, use those
348 // instead. They will be copied to those relative locations in the sbox
349 // sandbox.
Jiyong Park8fb0e972024-03-18 18:29:37 +0900350 // Care must be taken since TransitivePackagingSpec may return device-side
351 // paths via the required property. Filter them out.
352 for i, ps := range specs {
353 if ps.Partition() != "" {
354 if i == 0 {
355 panic("first PackagingSpec is assumed to be the host-side tool")
356 }
357 continue
358 }
359 packagedTools = append(packagedTools, ps)
360 }
Colin Crossba9e4032020-11-24 16:32:22 -0800361 // Assume that the first PackagingSpec of the module is the tool.
Colin Crossd11cf622021-03-23 22:30:35 -0700362 addLocationLabel(tag.label, packagedToolLocation{specs[0]})
Colin Crossba9e4032020-11-24 16:32:22 -0800363 } else {
364 tools = append(tools, path.Path())
Colin Crossd11cf622021-03-23 22:30:35 -0700365 addLocationLabel(tag.label, toolLocation{android.Paths{path.Path()}})
Colin Crossba9e4032020-11-24 16:32:22 -0800366 }
Colin Crossba9e4032020-11-24 16:32:22 -0800367 default:
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700368 ctx.ModuleErrorf("%q is not a host tool provider", tool)
Colin Crossba9e4032020-11-24 16:32:22 -0800369 return
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700370 }
371
Colin Crossba9e4032020-11-24 16:32:22 -0800372 seenTools[tag.label] = true
Colin Crossd350ecd2015-04-28 13:25:36 -0700373 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700374 })
Colin Crossba71a3f2019-03-18 12:12:48 -0700375
376 // If AllowMissingDependencies is enabled, the build will not have stopped when
377 // AddFarVariationDependencies was called on a missing tool, which will result in nonsensical
Liz Kammer20ebfb42020-07-28 11:32:07 -0700378 // "cmd: unknown location label ..." errors later. Add a placeholder file to the local label.
379 // The command that uses this placeholder file will never be executed because the rule will be
380 // replaced with an android.Error rule reporting the missing dependencies.
Colin Crossba71a3f2019-03-18 12:12:48 -0700381 if ctx.Config().AllowMissingDependencies() {
382 for _, tool := range g.properties.Tools {
383 if !seenTools[tool] {
Colin Crossd11cf622021-03-23 22:30:35 -0700384 addLocationLabel(tool, errorLocation{"***missing tool " + tool + "***"})
Colin Crossba71a3f2019-03-18 12:12:48 -0700385 }
386 }
387 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700388 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700389
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700390 if ctx.Failed() {
391 return
392 }
393
Colin Cross08f15ab2018-10-04 23:29:14 -0700394 for _, toolFile := range g.properties.Tool_files {
Colin Cross8a497952019-03-05 22:25:09 -0800395 paths := android.PathsForModuleSrc(ctx, []string{toolFile})
Colin Crossba9e4032020-11-24 16:32:22 -0800396 tools = append(tools, paths...)
Colin Crossd11cf622021-03-23 22:30:35 -0700397 addLocationLabel(toolFile, toolLocation{paths})
Colin Cross08f15ab2018-10-04 23:29:14 -0700398 }
399
Liz Kammer81fec182023-06-09 13:33:45 -0400400 addLabelsForInputs := func(propName string, include, exclude []string) android.Paths {
Liz Kammer81fec182023-06-09 13:33:45 -0400401 includeDirInPaths := ctx.DeviceConfig().BuildBrokenInputDir(g.Name())
402 var srcFiles android.Paths
403 for _, in := range include {
404 paths, missingDeps := android.PathsAndMissingDepsRelativeToModuleSourceDir(android.SourceInput{
405 Context: ctx, Paths: []string{in}, ExcludePaths: exclude, IncludeDirs: includeDirInPaths,
406 })
407 if len(missingDeps) > 0 {
408 if !ctx.Config().AllowMissingDependencies() {
409 panic(fmt.Errorf("should never get here, the missing dependencies %q should have been reported in DepsMutator",
410 missingDeps))
411 }
412
413 // If AllowMissingDependencies is enabled, the build will not have stopped when
414 // the dependency was added on a missing SourceFileProducer module, which will result in nonsensical
415 // "cmd: label ":..." has no files" errors later. Add a placeholder file to the local label.
416 // The command that uses this placeholder file will never be executed because the rule will be
417 // replaced with an android.Error rule reporting the missing dependencies.
418 ctx.AddMissingDependencies(missingDeps)
419 addLocationLabel(in, errorLocation{"***missing " + propName + " " + in + "***"})
420 } else {
421 srcFiles = append(srcFiles, paths...)
422 addLocationLabel(in, inputLocation{paths})
423 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700424 }
Liz Kammer81fec182023-06-09 13:33:45 -0400425 return srcFiles
Colin Cross08f15ab2018-10-04 23:29:14 -0700426 }
Cole Faustbf1d92a2024-07-29 12:24:25 -0700427 g.properties.ResolvedSrcs = g.properties.Srcs.GetOrDefault(ctx, nil)
Inseob Kim2f730622024-07-23 14:03:40 +0900428 srcFiles := addLabelsForInputs("srcs", g.properties.ResolvedSrcs, g.properties.Exclude_srcs)
Colin Cross40213022023-12-13 15:19:49 -0800429 android.SetProvider(ctx, blueprint.SrcsFileProviderKey, blueprint.SrcsFileProviderData{SrcPaths: srcFiles.Strings()})
Colin Cross08f15ab2018-10-04 23:29:14 -0700430
Colin Cross1a527682019-09-23 15:55:30 -0700431 var copyFrom android.Paths
432 var outputFiles android.WritablePaths
433 var zipArgs strings.Builder
Colin Cross08f15ab2018-10-04 23:29:14 -0700434
Aleks Todorov1eb06c42024-06-03 15:23:56 +0100435 cmd := g.properties.Cmd.GetOrDefault(ctx, "")
Colin Crossf3bfd022021-09-27 15:15:06 -0700436 if g.CmdModifier != nil {
437 cmd = g.CmdModifier(ctx, cmd)
438 }
439
Liz Kammer796921d2023-07-11 08:21:41 -0400440 var extraInputs android.Paths
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500441 // Generate tasks, either from genrule or gensrcs.
Liz Kammer81fec182023-06-09 13:33:45 -0400442 for i, task := range g.taskGenerator(ctx, cmd, srcFiles) {
Colin Cross3d680512020-11-13 16:23:53 -0800443 if len(task.out) == 0 {
444 ctx.ModuleErrorf("must have at least one output file")
445 return
Colin Cross85a2e892018-07-09 09:45:06 -0700446 }
447
Liz Kammer81fec182023-06-09 13:33:45 -0400448 // Only handle extra inputs once as these currently are the same across all tasks
449 if i == 0 {
450 for name, values := range task.extraInputs {
451 extraInputs = append(extraInputs, addLabelsForInputs(name, values, []string{})...)
452 }
453 }
454
Colin Crossf1a035e2020-11-16 17:32:30 -0800455 // Pick a unique path outside the task.genDir for the sbox manifest textproto,
456 // a unique rule name, and the user-visible description.
457 manifestName := "genrule.sbox.textproto"
458 desc := "generate"
459 name := "generator"
460 if task.shards > 0 {
461 manifestName = "genrule_" + strconv.Itoa(task.shard) + ".sbox.textproto"
462 desc += " " + strconv.Itoa(task.shard)
463 name += strconv.Itoa(task.shard)
464 } else if len(task.out) == 1 {
465 desc += " " + task.out[0].Base()
466 }
467
468 manifestPath := android.PathForModuleOut(ctx, manifestName)
469
470 // Use a RuleBuilder to create a rule that runs the command inside an sbox sandbox.
Yu Liu6a7940c2023-05-09 17:12:22 -0700471 rule := getSandboxedRuleBuilder(ctx, android.NewRuleBuilder(pctx, ctx).Sbox(task.genDir, manifestPath))
Justin Yun4da4ccc2023-07-06 10:56:29 +0900472 if Bool(g.properties.Write_if_changed) {
473 rule.Restat()
474 }
Colin Crossf1a035e2020-11-16 17:32:30 -0800475 cmd := rule.Command()
476
Colin Cross3d680512020-11-13 16:23:53 -0800477 for _, out := range task.out {
Colin Crossd11cf622021-03-23 22:30:35 -0700478 addLocationLabel(out.Rel(), outputLocation{out})
Colin Cross3d680512020-11-13 16:23:53 -0800479 }
480
Colin Cross3d680512020-11-13 16:23:53 -0800481 rawCommand, err := android.Expand(task.cmd, func(name string) (string, error) {
Colin Cross1a527682019-09-23 15:55:30 -0700482 // report the error directly without returning an error to android.Expand to catch multiple errors in a
483 // single run
Colin Cross3d680512020-11-13 16:23:53 -0800484 reportError := func(fmt string, args ...interface{}) (string, error) {
Colin Cross1a527682019-09-23 15:55:30 -0700485 ctx.PropertyErrorf("cmd", fmt, args...)
Colin Cross3d680512020-11-13 16:23:53 -0800486 return "SOONG_ERROR", nil
Colin Cross6f080df2016-11-04 15:32:58 -0700487 }
Colin Cross1a527682019-09-23 15:55:30 -0700488
Jihoon Kangc170af42022-08-20 05:26:38 +0000489 // Apply shell escape to each cases to prevent source file paths containing $ from being evaluated in shell
Colin Cross1a527682019-09-23 15:55:30 -0700490 switch name {
491 case "location":
492 if len(g.properties.Tools) == 0 && len(g.properties.Tool_files) == 0 {
493 return reportError("at least one `tools` or `tool_files` is required if $(location) is used")
Colin Cross6f080df2016-11-04 15:32:58 -0700494 }
Colin Crossd11cf622021-03-23 22:30:35 -0700495 loc := locationLabels[firstLabel]
496 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700497 if len(paths) == 0 {
498 return reportError("default label %q has no files", firstLabel)
499 } else if len(paths) > 1 {
500 return reportError("default label %q has multiple files, use $(locations %s) to reference it",
501 firstLabel, firstLabel)
Colin Cross08f15ab2018-10-04 23:29:14 -0700502 }
Jihoon Kangc170af42022-08-20 05:26:38 +0000503 return proptools.ShellEscape(paths[0]), nil
Colin Cross1a527682019-09-23 15:55:30 -0700504 case "in":
Jihoon Kangc170af42022-08-20 05:26:38 +0000505 return strings.Join(proptools.ShellEscapeList(cmd.PathsForInputs(srcFiles)), " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700506 case "out":
Colin Cross3d680512020-11-13 16:23:53 -0800507 var sandboxOuts []string
508 for _, out := range task.out {
Colin Crossf1a035e2020-11-16 17:32:30 -0800509 sandboxOuts = append(sandboxOuts, cmd.PathForOutput(out))
Colin Cross3d680512020-11-13 16:23:53 -0800510 }
Jihoon Kangc170af42022-08-20 05:26:38 +0000511 return strings.Join(proptools.ShellEscapeList(sandboxOuts), " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700512 case "genDir":
Jihoon Kangc170af42022-08-20 05:26:38 +0000513 return proptools.ShellEscape(cmd.PathForOutput(task.genDir)), nil
Cole Faust78f3c3a2024-08-15 17:19:34 -0700514 case "build_number_file":
515 if !proptools.Bool(g.properties.Uses_order_only_build_number_file) {
516 return reportError("to use the $(build_number_file) label, you must set uses_order_only_build_number_file: true")
517 }
518 return proptools.ShellEscape(cmd.PathForInput(ctx.Config().BuildNumberFile(ctx))), nil
Colin Cross1a527682019-09-23 15:55:30 -0700519 default:
520 if strings.HasPrefix(name, "location ") {
521 label := strings.TrimSpace(strings.TrimPrefix(name, "location "))
Colin Crossd11cf622021-03-23 22:30:35 -0700522 if loc, ok := locationLabels[label]; ok {
523 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700524 if len(paths) == 0 {
525 return reportError("label %q has no files", label)
526 } else if len(paths) > 1 {
527 return reportError("label %q has multiple files, use $(locations %s) to reference it",
528 label, label)
529 }
Jihoon Kangc170af42022-08-20 05:26:38 +0000530 return proptools.ShellEscape(paths[0]), nil
Colin Cross1a527682019-09-23 15:55:30 -0700531 } else {
Anton Hanssonbebf5262022-02-23 11:42:38 +0000532 return reportError("unknown location label %q is not in srcs, out, tools or tool_files.", label)
Colin Cross1a527682019-09-23 15:55:30 -0700533 }
534 } else if strings.HasPrefix(name, "locations ") {
535 label := strings.TrimSpace(strings.TrimPrefix(name, "locations "))
Colin Crossd11cf622021-03-23 22:30:35 -0700536 if loc, ok := locationLabels[label]; ok {
537 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700538 if len(paths) == 0 {
539 return reportError("label %q has no files", label)
540 }
Cole Faustce74a592023-12-07 14:58:45 -0800541 return strings.Join(proptools.ShellEscapeList(paths), " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700542 } else {
Anton Hanssonbebf5262022-02-23 11:42:38 +0000543 return reportError("unknown locations label %q is not in srcs, out, tools or tool_files.", label)
Colin Cross1a527682019-09-23 15:55:30 -0700544 }
545 } else {
546 return reportError("unknown variable '$(%s)'", name)
547 }
Colin Cross6f080df2016-11-04 15:32:58 -0700548 }
Colin Cross1a527682019-09-23 15:55:30 -0700549 })
550
551 if err != nil {
552 ctx.PropertyErrorf("cmd", "%s", err.Error())
553 return
Colin Cross6f080df2016-11-04 15:32:58 -0700554 }
Colin Cross6f080df2016-11-04 15:32:58 -0700555
Colin Cross1a527682019-09-23 15:55:30 -0700556 g.rawCommands = append(g.rawCommands, rawCommand)
Bill Peckhamc087be12020-02-13 15:55:10 -0800557
Colin Cross3d680512020-11-13 16:23:53 -0800558 cmd.Text(rawCommand)
Liz Kammer81fec182023-06-09 13:33:45 -0400559 cmd.Implicits(srcFiles) // need to be able to reference other srcs
560 cmd.Implicits(extraInputs)
Colin Cross3d680512020-11-13 16:23:53 -0800561 cmd.ImplicitOutputs(task.out)
562 cmd.Implicits(task.in)
Colin Crossba9e4032020-11-24 16:32:22 -0800563 cmd.ImplicitTools(tools)
Colin Crossba9e4032020-11-24 16:32:22 -0800564 cmd.ImplicitPackagedTools(packagedTools)
Cole Faust78f3c3a2024-08-15 17:19:34 -0700565 if proptools.Bool(g.properties.Uses_order_only_build_number_file) {
Cole Faustf23fdc02024-08-23 15:21:13 -0700566 if !isModuleInBuildNumberAllowlist(ctx) {
Cole Faust78f3c3a2024-08-15 17:19:34 -0700567 ctx.ModuleErrorf("Only allowlisted modules may use uses_order_only_build_number_file: true")
568 }
569 cmd.OrderOnly(ctx.Config().BuildNumberFile(ctx))
570 }
Colin Cross3d680512020-11-13 16:23:53 -0800571
572 // Create the rule to run the genrule command inside sbox.
Colin Crossf1a035e2020-11-16 17:32:30 -0800573 rule.Build(name, desc)
Colin Cross1a527682019-09-23 15:55:30 -0700574
575 if len(task.copyTo) > 0 {
Colin Cross3d680512020-11-13 16:23:53 -0800576 // If copyTo is set, multiple shards need to be copied into a single directory.
577 // task.out contains the per-shard paths, and copyTo contains the corresponding
578 // final path. The files need to be copied into the final directory by a
579 // single rule so it can remove the directory before it starts to ensure no
580 // old files remain. zipsync already does this, so build up zipArgs that
581 // zip all the per-shard directories into a single zip.
Colin Cross1a527682019-09-23 15:55:30 -0700582 outputFiles = append(outputFiles, task.copyTo...)
583 copyFrom = append(copyFrom, task.out.Paths()...)
584 zipArgs.WriteString(" -C " + task.genDir.String())
585 zipArgs.WriteString(android.JoinWithPrefix(task.out.Strings(), " -f "))
586 } else {
587 outputFiles = append(outputFiles, task.out...)
588 }
Colin Cross6f080df2016-11-04 15:32:58 -0700589 }
590
Colin Cross1a527682019-09-23 15:55:30 -0700591 if len(copyFrom) > 0 {
Colin Cross3d680512020-11-13 16:23:53 -0800592 // Create a rule that zips all the per-shard directories into a single zip and then
593 // uses zipsync to unzip it into the final directory.
Colin Cross1a527682019-09-23 15:55:30 -0700594 ctx.Build(pctx, android.BuildParams{
Colin Crossf1885962020-11-20 15:28:30 -0800595 Rule: gensrcsMerge,
596 Implicits: copyFrom,
597 Outputs: outputFiles,
598 Description: "merge shards",
Colin Cross1a527682019-09-23 15:55:30 -0700599 Args: map[string]string{
600 "zipArgs": zipArgs.String(),
601 "tmpZip": android.PathForModuleGen(ctx, g.subDir+".zip").String(),
602 "genDir": android.PathForModuleGen(ctx, g.subDir).String(),
603 },
604 })
Colin Cross85a2e892018-07-09 09:45:06 -0700605 }
606
Colin Cross1a527682019-09-23 15:55:30 -0700607 g.outputFiles = outputFiles.Paths()
Chris Parsonsf874e462022-05-10 13:50:12 -0400608}
Jeff Gastonefc1b412017-03-29 17:29:06 -0700609
Chris Parsonsf874e462022-05-10 13:50:12 -0400610func (g *Module) GenerateAndroidBuildActions(ctx android.ModuleContext) {
611 g.generateCommonBuildActions(ctx)
612
613 // For <= 6 outputs, just embed those directly in the users. Right now, that covers >90% of
614 // the genrules on AOSP. That will make things simpler to look at the graph in the common
615 // case. For larger sets of outputs, inject a phony target in between to limit ninja file
616 // growth.
617 if len(g.outputFiles) <= 6 {
618 g.outputDeps = g.outputFiles
619 } else {
620 phonyFile := android.PathForModuleGen(ctx, "genrule-phony")
621 ctx.Build(pctx, android.BuildParams{
622 Rule: blueprint.Phony,
623 Output: phonyFile,
624 Inputs: g.outputFiles,
625 })
626 g.outputDeps = android.Paths{phonyFile}
Jeff Gaston02a684b2017-10-27 14:59:27 -0700627 }
mrziwang4514ef22024-06-07 13:31:48 -0700628
629 g.setOutputFiles(ctx)
630}
631
632func (g *Module) setOutputFiles(ctx android.ModuleContext) {
633 if len(g.outputFiles) == 0 {
634 return
635 }
636 ctx.SetOutputFiles(g.outputFiles, "")
637 // non-empty-string-tag should match one of the outputs
638 for _, files := range g.outputFiles {
639 ctx.SetOutputFiles(android.Paths{files}, files.Rel())
640 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400641}
642
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700643// Collect information for opening IDE project files in java/jdeps.go.
Cole Faustb36d31d2024-08-27 16:04:28 -0700644func (g *Module) IDEInfo(ctx android.BaseModuleContext, dpInfo *android.IdeInfo) {
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700645 dpInfo.Srcs = append(dpInfo.Srcs, g.Srcs().Strings()...)
Inseob Kim2f730622024-07-23 14:03:40 +0900646 for _, src := range g.properties.ResolvedSrcs {
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700647 if strings.HasPrefix(src, ":") {
648 src = strings.Trim(src, ":")
649 dpInfo.Deps = append(dpInfo.Deps, src)
650 }
651 }
652}
653
Colin Crossa4ad2b02019-03-18 22:15:32 -0700654func (g *Module) AndroidMk() android.AndroidMkData {
655 return android.AndroidMkData{
Anton Hansson72f18492020-10-30 16:34:45 +0000656 Class: "ETC",
Colin Crossa4ad2b02019-03-18 22:15:32 -0700657 OutputFile: android.OptionalPathForPath(g.outputFiles[0]),
658 SubName: g.subName,
659 Extra: []android.AndroidMkExtraFunc{
660 func(w io.Writer, outputFile android.Path) {
Anton Hansson72f18492020-10-30 16:34:45 +0000661 fmt.Fprintln(w, "LOCAL_UNINSTALLABLE_MODULE := true")
Colin Crossa4ad2b02019-03-18 22:15:32 -0700662 },
663 },
664 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
665 android.WriteAndroidMkData(w, data)
666 if data.SubName != "" {
667 fmt.Fprintln(w, ".PHONY:", name)
668 fmt.Fprintln(w, name, ":", name+g.subName)
669 }
670 },
671 }
672}
673
Jiyong Park45bf82e2020-12-15 22:29:02 +0900674var _ android.ApexModule = (*Module)(nil)
675
676// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -0700677func (g *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
678 sdkVersion android.ApiLevel) error {
Jooyung Han749dc692020-04-15 11:03:39 +0900679 // Because generated outputs are checked by client modules(e.g. cc_library, ...)
680 // we can safely ignore the check here.
681 return nil
682}
683
Jeff Gaston437d23c2017-11-08 12:38:00 -0800684func generatorFactory(taskGenerator taskFunc, props ...interface{}) *Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700685 module := &Module{
Jeff Gaston437d23c2017-11-08 12:38:00 -0800686 taskGenerator: taskGenerator,
Colin Crossd350ecd2015-04-28 13:25:36 -0700687 }
688
Colin Cross36242852017-06-23 15:06:31 -0700689 module.AddProperties(props...)
690 module.AddProperties(&module.properties)
Colin Crossd350ecd2015-04-28 13:25:36 -0700691
Colin Cross7228ecd2019-11-18 16:00:16 -0800692 module.ImageInterface = noopImageInterface{}
693
Colin Cross36242852017-06-23 15:06:31 -0700694 return module
Colin Crossd350ecd2015-04-28 13:25:36 -0700695}
696
Colin Cross7228ecd2019-11-18 16:00:16 -0800697type noopImageInterface struct{}
698
699func (x noopImageInterface) ImageMutatorBegin(android.BaseModuleContext) {}
Jihoon Kang47e91842024-06-19 00:51:16 +0000700func (x noopImageInterface) VendorVariantNeeded(android.BaseModuleContext) bool { return false }
701func (x noopImageInterface) ProductVariantNeeded(android.BaseModuleContext) bool { return false }
Colin Cross7228ecd2019-11-18 16:00:16 -0800702func (x noopImageInterface) CoreVariantNeeded(android.BaseModuleContext) bool { return false }
Yifan Hong1b3348d2020-01-21 15:53:22 -0800703func (x noopImageInterface) RamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700704func (x noopImageInterface) VendorRamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Inseob Kim08758f02021-04-08 21:13:22 +0900705func (x noopImageInterface) DebugRamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Colin Cross7228ecd2019-11-18 16:00:16 -0800706func (x noopImageInterface) RecoveryVariantNeeded(android.BaseModuleContext) bool { return false }
707func (x noopImageInterface) ExtraImageVariations(ctx android.BaseModuleContext) []string { return nil }
Jihoon Kang7583e832024-06-13 21:25:45 +0000708func (x noopImageInterface) SetImageVariation(ctx android.BaseModuleContext, variation string) {
Colin Cross7228ecd2019-11-18 16:00:16 -0800709}
710
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700711func NewGenSrcs() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700712 properties := &genSrcsProperties{}
713
Colin Crossf1885962020-11-20 15:28:30 -0800714 // finalSubDir is the name of the subdirectory that output files will be generated into.
715 // It is used so that per-shard directories can be placed alongside it an then finally
716 // merged into it.
717 const finalSubDir = "gensrcs"
718
Colin Cross1a527682019-09-23 15:55:30 -0700719 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Colin Cross1a527682019-09-23 15:55:30 -0700720 shardSize := defaultShardSize
721 if s := properties.Shard_size; s != nil {
722 shardSize = int(*s)
723 }
Jeff Gaston437d23c2017-11-08 12:38:00 -0800724
Colin Crossf1885962020-11-20 15:28:30 -0800725 // gensrcs rules can easily hit command line limits by repeating the command for
726 // every input file. Shard the input files into groups.
Colin Cross1a527682019-09-23 15:55:30 -0700727 shards := android.ShardPaths(srcFiles, shardSize)
728 var generateTasks []generateTask
Colin Crossbaccf5b2018-02-21 14:07:48 -0800729
Colin Cross1a527682019-09-23 15:55:30 -0700730 for i, shard := range shards {
731 var commands []string
732 var outFiles android.WritablePaths
733 var copyTo android.WritablePaths
Colin Cross1a527682019-09-23 15:55:30 -0700734
Colin Crossf1885962020-11-20 15:28:30 -0800735 // When sharding is enabled (i.e. len(shards) > 1), the sbox rules for each
736 // shard will be write to their own directories and then be merged together
737 // into finalSubDir. If sharding is not enabled (i.e. len(shards) == 1),
738 // the sbox rule will write directly to finalSubDir.
739 genSubDir := finalSubDir
Colin Cross1a527682019-09-23 15:55:30 -0700740 if len(shards) > 1 {
Colin Crossf1885962020-11-20 15:28:30 -0800741 genSubDir = strconv.Itoa(i)
Jeff Gaston437d23c2017-11-08 12:38:00 -0800742 }
743
Colin Crossf1885962020-11-20 15:28:30 -0800744 genDir := android.PathForModuleGen(ctx, genSubDir)
Colin Crossf1a035e2020-11-16 17:32:30 -0800745 // TODO(ccross): this RuleBuilder is a hack to be able to call
746 // rule.Command().PathForOutput. Replace this with passing the rule into the
747 // generator.
Yu Liu6a7940c2023-05-09 17:12:22 -0700748 rule := getSandboxedRuleBuilder(ctx, android.NewRuleBuilder(pctx, ctx).Sbox(genDir, nil))
Jeff Gaston437d23c2017-11-08 12:38:00 -0800749
Colin Cross3ea4eb82020-11-24 13:07:27 -0800750 for _, in := range shard {
yangbill6d032dd2024-04-18 03:05:49 +0000751 outFile := android.GenPathWithExtAndTrimExt(ctx, finalSubDir, in, String(properties.Output_extension), String(properties.Trim_extension))
Colin Crossf1885962020-11-20 15:28:30 -0800752
753 // If sharding is enabled, then outFile is the path to the output file in
754 // the shard directory, and copyTo is the path to the output file in the
755 // final directory.
Colin Cross1a527682019-09-23 15:55:30 -0700756 if len(shards) > 1 {
yangbill6d032dd2024-04-18 03:05:49 +0000757 shardFile := android.GenPathWithExtAndTrimExt(ctx, genSubDir, in, String(properties.Output_extension), String(properties.Trim_extension))
Colin Cross1a527682019-09-23 15:55:30 -0700758 copyTo = append(copyTo, outFile)
759 outFile = shardFile
760 }
761
762 outFiles = append(outFiles, outFile)
Colin Cross1a527682019-09-23 15:55:30 -0700763
Colin Crossf1885962020-11-20 15:28:30 -0800764 // pre-expand the command line to replace $in and $out with references to
765 // a single input and output file.
Colin Cross1a527682019-09-23 15:55:30 -0700766 command, err := android.Expand(rawCommand, func(name string) (string, error) {
767 switch name {
768 case "in":
769 return in.String(), nil
770 case "out":
Colin Crossf1a035e2020-11-16 17:32:30 -0800771 return rule.Command().PathForOutput(outFile), nil
Colin Cross1a527682019-09-23 15:55:30 -0700772 default:
773 return "$(" + name + ")", nil
774 }
775 })
776 if err != nil {
777 ctx.PropertyErrorf("cmd", err.Error())
778 }
779
780 // escape the command in case for example it contains '#', an odd number of '"', etc
781 command = fmt.Sprintf("bash -c %v", proptools.ShellEscape(command))
782 commands = append(commands, command)
783 }
784 fullCommand := strings.Join(commands, " && ")
785
786 generateTasks = append(generateTasks, generateTask{
Cole Faust55492572024-01-25 18:00:33 -0800787 in: shard,
788 out: outFiles,
789 copyTo: copyTo,
790 genDir: genDir,
791 cmd: fullCommand,
792 shard: i,
793 shards: len(shards),
Liz Kammer81fec182023-06-09 13:33:45 -0400794 extraInputs: map[string][]string{
795 "data": properties.Data,
796 },
Colin Cross1a527682019-09-23 15:55:30 -0700797 })
Jeff Gaston437d23c2017-11-08 12:38:00 -0800798 }
Colin Cross1a527682019-09-23 15:55:30 -0700799
800 return generateTasks
Colin Crossd350ecd2015-04-28 13:25:36 -0700801 }
802
Colin Cross1a527682019-09-23 15:55:30 -0700803 g := generatorFactory(taskGenerator, properties)
Colin Crossf1885962020-11-20 15:28:30 -0800804 g.subDir = finalSubDir
Colin Cross1a527682019-09-23 15:55:30 -0700805 return g
Colin Crossd350ecd2015-04-28 13:25:36 -0700806}
807
Colin Cross54190b32017-10-09 15:34:10 -0700808func GenSrcsFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700809 m := NewGenSrcs()
810 android.InitAndroidModule(m)
Colin Cross483b4c42024-05-09 13:08:02 -0700811 android.InitDefaultableModule(m)
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700812 return m
813}
814
Colin Crossd350ecd2015-04-28 13:25:36 -0700815type genSrcsProperties struct {
Colin Cross7d5136f2015-05-11 13:39:40 -0700816 // extension that will be substituted for each output file
Nan Zhanga5e7cb42017-11-09 22:42:32 -0800817 Output_extension *string
Colin Cross1a527682019-09-23 15:55:30 -0700818
819 // maximum number of files that will be passed on a single command line.
820 Shard_size *int64
Liz Kammer81fec182023-06-09 13:33:45 -0400821
822 // Additional files needed for build that are not tooling related.
823 Data []string `android:"path"`
yangbill6d032dd2024-04-18 03:05:49 +0000824
825 // Trim the matched extension for each input file, and it should start with ".".
826 Trim_extension *string
Colin Cross5049f022015-03-18 13:28:46 -0700827}
828
Evgenii Stepanovf47c90d2020-12-02 18:55:09 -0800829const defaultShardSize = 50
Colin Cross1a527682019-09-23 15:55:30 -0700830
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700831func NewGenRule() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700832 properties := &genRuleProperties{}
Colin Cross5049f022015-03-18 13:28:46 -0700833
Colin Cross1a527682019-09-23 15:55:30 -0700834 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700835 outs := make(android.WritablePaths, len(properties.Out))
836 for i, out := range properties.Out {
Cole Faust55492572024-01-25 18:00:33 -0800837 outs[i] = android.PathForModuleGen(ctx, out)
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700838 }
Colin Cross1a527682019-09-23 15:55:30 -0700839 return []generateTask{{
Cole Faust55492572024-01-25 18:00:33 -0800840 in: srcFiles,
841 out: outs,
842 genDir: android.PathForModuleGen(ctx),
843 cmd: rawCommand,
Colin Cross1a527682019-09-23 15:55:30 -0700844 }}
Colin Cross5049f022015-03-18 13:28:46 -0700845 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700846
Jeff Gaston437d23c2017-11-08 12:38:00 -0800847 return generatorFactory(taskGenerator, properties)
Colin Cross5049f022015-03-18 13:28:46 -0700848}
849
Colin Cross54190b32017-10-09 15:34:10 -0700850func GenRuleFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700851 m := NewGenRule()
852 android.InitAndroidModule(m)
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800853 android.InitDefaultableModule(m)
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700854 return m
855}
856
Colin Crossd350ecd2015-04-28 13:25:36 -0700857type genRuleProperties struct {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700858 // names of the output files that will be generated
kellyhung750334a2024-03-14 01:03:49 +0800859 Out []string `android:"arch_variant"`
Colin Cross5049f022015-03-18 13:28:46 -0700860}
Nan Zhangea568a42017-11-08 21:20:04 -0800861
862var Bool = proptools.Bool
863var String = proptools.String
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800864
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800865// Defaults
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800866type Defaults struct {
867 android.ModuleBase
868 android.DefaultsModuleBase
869}
870
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800871func defaultsFactory() android.Module {
872 return DefaultsFactory()
873}
874
875func DefaultsFactory(props ...interface{}) android.Module {
876 module := &Defaults{}
877
878 module.AddProperties(props...)
879 module.AddProperties(
880 &generatorProperties{},
881 &genRuleProperties{},
882 )
883
884 android.InitDefaultsModule(module)
885
886 return module
887}
Yu Liu6a7940c2023-05-09 17:12:22 -0700888
Yu Liue7f7cbf2023-06-13 18:50:03 +0000889var sandboxingAllowlistKey = android.NewOnceKey("genruleSandboxingAllowlistKey")
890
891type sandboxingAllowlistSets struct {
892 sandboxingDenyModuleSet map[string]bool
Yu Liue7f7cbf2023-06-13 18:50:03 +0000893}
894
895func getSandboxingAllowlistSets(ctx android.PathContext) *sandboxingAllowlistSets {
896 return ctx.Config().Once(sandboxingAllowlistKey, func() interface{} {
897 sandboxingDenyModuleSet := map[string]bool{}
Yu Liue7f7cbf2023-06-13 18:50:03 +0000898
Cole Faust55492572024-01-25 18:00:33 -0800899 android.AddToStringSet(sandboxingDenyModuleSet, SandboxingDenyModuleList)
Yu Liue7f7cbf2023-06-13 18:50:03 +0000900 return &sandboxingAllowlistSets{
901 sandboxingDenyModuleSet: sandboxingDenyModuleSet,
Yu Liue7f7cbf2023-06-13 18:50:03 +0000902 }
903 }).(*sandboxingAllowlistSets)
904}
Liz Kammer0db0e342023-07-18 11:39:30 -0400905
Yu Liu6a7940c2023-05-09 17:12:22 -0700906func getSandboxedRuleBuilder(ctx android.ModuleContext, r *android.RuleBuilder) *android.RuleBuilder {
Yu Liu45d6af52023-05-24 23:10:18 +0000907 if !ctx.DeviceConfig().GenruleSandboxing() {
908 return r.SandboxTools()
909 }
Yu Liue7f7cbf2023-06-13 18:50:03 +0000910 sandboxingAllowlistSets := getSandboxingAllowlistSets(ctx)
Cole Fauste762b942024-03-15 12:46:14 -0700911 if sandboxingAllowlistSets.sandboxingDenyModuleSet[ctx.ModuleName()] {
Yu Liu6a7940c2023-05-09 17:12:22 -0700912 return r.SandboxTools()
913 }
914 return r.SandboxInputs()
915}