blob: 0aecc452ce7751d34d3efdb1f42646b51588ed7d [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"
Inseob Kimf7cd03e2024-09-06 17:25:00 +090024 "path/filepath"
Colin Cross1a527682019-09-23 15:55:30 -070025 "strconv"
Colin Cross6f080df2016-11-04 15:32:58 -070026 "strings"
Dan Willemsen3f4539b2016-09-28 16:19:10 -070027
Colin Cross70b40592015-03-23 12:57:34 -070028 "github.com/google/blueprint"
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 $
Aleks Todorov1eb06c42024-06-03 15:23:56 +0100129 Cmd proptools.Configurable[string] `android:"replace_instead_of_append"`
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
Inseob Kim2f730622024-07-23 14:03:40 +0900142 Srcs proptools.Configurable[[]string] `android:"path,arch_variant"`
143 ResolvedSrcs []string `blueprint:"mutated"`
Dan Willemseneefa0262018-11-17 14:01:18 -0800144
145 // input files to exclude
Colin Cross27b922f2019-03-04 22:35:41 -0800146 Exclude_srcs []string `android:"path,arch_variant"`
Justin Yun4da4ccc2023-07-06 10:56:29 +0900147
148 // Enable restat to update the output only if the output is changed
149 Write_if_changed *bool
Cole Faust78f3c3a2024-08-15 17:19:34 -0700150
151 // When set to true, an additional $(build_number_file) label will be available
152 // to use in the cmd. This will be the location of a text file containing the
153 // build number. The dependency on this file will be "order-only", meaning that
154 // the genrule will not rerun when only this file changes, to avoid rerunning
155 // the genrule every build, because the build number changes every build.
156 // This also means that you should not attempt to consume the build number from
157 // the result of this genrule in another build rule. If you do, the build number
158 // in the second build rule will be stale when the second build rule rebuilds
159 // but this genrule does not. Only certain allowlisted modules are allowed to
160 // use this property, usages of the build number should be kept to the absolute
161 // minimum. Particularly no modules on the system image may include the build
162 // number. Prefer using libbuildversion via the use_version_lib property on
163 // cc modules.
164 Uses_order_only_build_number_file *bool
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400165}
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500166
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700167type Module struct {
Colin Cross635c3b02016-05-18 15:37:25 -0700168 android.ModuleBase
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800169 android.DefaultableModuleBase
Jiyong Parkfc752ca2019-06-12 13:27:29 +0900170 android.ApexModuleBase
Colin Crossd350ecd2015-04-28 13:25:36 -0700171
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700172 // For other packages to make their own genrules with extra
173 // properties
174 Extra interface{}
Colin Crossf3bfd022021-09-27 15:15:06 -0700175
176 // CmdModifier can be set by wrappers around genrule to modify the command, for example to
177 // prefix environment variables to it.
178 CmdModifier func(ctx android.ModuleContext, cmd string) string
179
Colin Cross7228ecd2019-11-18 16:00:16 -0800180 android.ImageInterface
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700181
Colin Cross7d5136f2015-05-11 13:39:40 -0700182 properties generatorProperties
Colin Crossd350ecd2015-04-28 13:25:36 -0700183
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500184 // For the different tasks that genrule and gensrc generate. genrule will
185 // generate 1 task, and gensrc will generate 1 or more tasks based on the
186 // number of shards the input files are sharded into.
Jeff Gaston437d23c2017-11-08 12:38:00 -0800187 taskGenerator taskFunc
Colin Crossd350ecd2015-04-28 13:25:36 -0700188
Colin Cross1a527682019-09-23 15:55:30 -0700189 rule blueprint.Rule
190 rawCommands []string
Colin Crossd350ecd2015-04-28 13:25:36 -0700191
Colin Cross5ed99c62016-11-22 12:55:55 -0800192 exportedIncludeDirs android.Paths
Dan Willemsenb40aab62016-04-20 14:21:14 -0700193
Colin Cross635c3b02016-05-18 15:37:25 -0700194 outputFiles android.Paths
Dan Willemsen9da9d492018-02-21 18:28:18 -0800195 outputDeps android.Paths
Colin Crossa4ad2b02019-03-18 22:15:32 -0700196
197 subName string
Colin Cross1a527682019-09-23 15:55:30 -0700198 subDir string
Colin Crossd350ecd2015-04-28 13:25:36 -0700199}
200
Colin Cross1a527682019-09-23 15:55:30 -0700201type taskFunc func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask
Colin Crossd350ecd2015-04-28 13:25:36 -0700202
203type generateTask struct {
Liz Kammer81fec182023-06-09 13:33:45 -0400204 in android.Paths
205 out android.WritablePaths
Liz Kammer81fec182023-06-09 13:33:45 -0400206 copyTo android.WritablePaths // For gensrcs to set on gensrcsMerge rule.
207 genDir android.WritablePath
Liz Kammer81fec182023-06-09 13:33:45 -0400208 extraInputs map[string][]string
Colin Cross3ea4eb82020-11-24 13:07:27 -0800209
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500210 cmd string
211 // For gensrsc sharding.
Colin Cross3ea4eb82020-11-24 13:07:27 -0800212 shard int
213 shards int
Inseob Kimf7cd03e2024-09-06 17:25:00 +0900214
215 // For nsjail tasks
216 useNsjail bool
Colin Crossd350ecd2015-04-28 13:25:36 -0700217}
218
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700219func (g *Module) GeneratedSourceFiles() android.Paths {
Colin Crossd350ecd2015-04-28 13:25:36 -0700220 return g.outputFiles
221}
222
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700223func (g *Module) Srcs() android.Paths {
Nan Zhange42777a2018-03-27 16:19:42 -0700224 return append(android.Paths{}, g.outputFiles...)
Colin Cross068e0fe2016-12-13 15:23:47 -0800225}
226
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700227func (g *Module) GeneratedHeaderDirs() android.Paths {
Colin Cross5ed99c62016-11-22 12:55:55 -0800228 return g.exportedIncludeDirs
Dan Willemsenb40aab62016-04-20 14:21:14 -0700229}
230
Dan Willemsen9da9d492018-02-21 18:28:18 -0800231func (g *Module) GeneratedDeps() android.Paths {
232 return g.outputDeps
233}
234
Jooyung Han8c7e3ed2021-06-28 17:35:58 +0900235var _ android.SourceFileProducer = (*Module)(nil)
Jooyung Han8c7e3ed2021-06-28 17:35:58 +0900236
Martin Stjernholm710ec3a2020-01-16 15:12:04 +0000237func toolDepsMutator(ctx android.BottomUpMutatorContext) {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700238 if g, ok := ctx.Module().(*Module); ok {
Colin Cross08f15ab2018-10-04 23:29:14 -0700239 for _, tool := range g.properties.Tools {
240 tag := hostToolDependencyTag{label: tool}
241 if m := android.SrcIsModule(tool); m != "" {
242 tool = m
243 }
Colin Cross0f7d2ef2019-10-16 11:03:10 -0700244 ctx.AddFarVariationDependencies(ctx.Config().BuildOSTarget.Variations(), tag, tool)
Colin Cross6362e272015-10-29 15:25:03 -0700245 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700246 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700247}
248
Cole Faustf23fdc02024-08-23 15:21:13 -0700249var buildNumberAllowlistKey = android.NewOnceKey("genruleBuildNumberAllowlistKey")
250
Cole Faust78f3c3a2024-08-15 17:19:34 -0700251// This allowlist should be kept to the bare minimum, it's
252// intended for things that existed before the build number
253// was tightly controlled. Prefer using libbuildversion
254// via the use_version_lib property of cc modules.
Cole Faustf23fdc02024-08-23 15:21:13 -0700255// This is a function instead of a global map so that
256// soong plugins cannot add entries to the allowlist
257func isModuleInBuildNumberAllowlist(ctx android.ModuleContext) bool {
258 allowlist := ctx.Config().Once(buildNumberAllowlistKey, func() interface{} {
Cole Faustdc018782024-08-28 11:08:06 -0700259 // Define the allowlist as a list and then copy it into a map so that
260 // gofmt doesn't change unnecessary lines trying to align the values of the map.
261 allowlist := []string{
Cole Faustf23fdc02024-08-23 15:21:13 -0700262 // go/keep-sorted start
Cole Faustdc018782024-08-28 11:08:06 -0700263 "build/soong/tests:gen",
264 "hardware/google/camera/common/hal/aidl_service:aidl_camera_build_version",
265 "tools/tradefederation/core:tradefed_zip",
266 "vendor/google/services/LyricCameraHAL/src/apex:com.google.pixel.camera.hal.manifest",
Cole Faustf23fdc02024-08-23 15:21:13 -0700267 // go/keep-sorted end
268 }
Cole Faustdc018782024-08-28 11:08:06 -0700269 allowlistMap := make(map[string]bool, len(allowlist))
270 for _, a := range allowlist {
271 allowlistMap[a] = true
272 }
273 return allowlistMap
Cole Faustf23fdc02024-08-23 15:21:13 -0700274 }).(map[string]bool)
275
276 _, ok := allowlist[ctx.ModuleDir()+":"+ctx.ModuleName()]
277 return ok
Cole Faust78f3c3a2024-08-15 17:19:34 -0700278}
279
Chris Parsonsf874e462022-05-10 13:50:12 -0400280// generateCommonBuildActions contains build action generation logic
281// common to both the mixed build case and the legacy case of genrule processing.
282// To fully support genrule in mixed builds, the contents of this function should
283// approach zero; there should be no genrule action registration done directly
284// by Soong logic in the mixed-build case.
285func (g *Module) generateCommonBuildActions(ctx android.ModuleContext) {
Colin Crossa4ad2b02019-03-18 22:15:32 -0700286 g.subName = ctx.ModuleSubDir()
287
Colin Cross5ed99c62016-11-22 12:55:55 -0800288 if len(g.properties.Export_include_dirs) > 0 {
289 for _, dir := range g.properties.Export_include_dirs {
290 g.exportedIncludeDirs = append(g.exportedIncludeDirs,
Colin Cross1a527682019-09-23 15:55:30 -0700291 android.PathForModuleGen(ctx, g.subDir, ctx.ModuleDir(), dir))
Liz Kammerd38c87c2023-07-17 09:58:50 -0400292 // Also export without ModuleDir for consistency with Export_include_dirs not being set
293 g.exportedIncludeDirs = append(g.exportedIncludeDirs,
294 android.PathForModuleGen(ctx, g.subDir, dir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800295 }
296 } else {
Colin Cross1a527682019-09-23 15:55:30 -0700297 g.exportedIncludeDirs = append(g.exportedIncludeDirs, android.PathForModuleGen(ctx, g.subDir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800298 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700299
Colin Crossd11cf622021-03-23 22:30:35 -0700300 locationLabels := map[string]location{}
Colin Cross08f15ab2018-10-04 23:29:14 -0700301 firstLabel := ""
302
Colin Crossd11cf622021-03-23 22:30:35 -0700303 addLocationLabel := func(label string, loc location) {
Colin Cross08f15ab2018-10-04 23:29:14 -0700304 if firstLabel == "" {
305 firstLabel = label
306 }
307 if _, exists := locationLabels[label]; !exists {
Colin Crossd11cf622021-03-23 22:30:35 -0700308 locationLabels[label] = loc
Colin Cross08f15ab2018-10-04 23:29:14 -0700309 } else {
Anton Hansson7cd41e52021-10-08 16:13:10 +0100310 ctx.ModuleErrorf("multiple locations for label %q: %q and %q (do you have duplicate srcs entries?)",
Colin Crossd11cf622021-03-23 22:30:35 -0700311 label, locationLabels[label], loc)
Colin Cross08f15ab2018-10-04 23:29:14 -0700312 }
313 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700314
Colin Crossba9e4032020-11-24 16:32:22 -0800315 var tools android.Paths
316 var packagedTools []android.PackagingSpec
Colin Cross6f080df2016-11-04 15:32:58 -0700317 if len(g.properties.Tools) > 0 {
Colin Crossba71a3f2019-03-18 12:12:48 -0700318 seenTools := make(map[string]bool)
319
Colin Cross35143d02017-11-16 00:11:20 -0800320 ctx.VisitDirectDepsBlueprint(func(module blueprint.Module) {
Colin Cross08f15ab2018-10-04 23:29:14 -0700321 switch tag := ctx.OtherModuleDependencyTag(module).(type) {
322 case hostToolDependencyTag:
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700323 tool := ctx.OtherModuleName(module)
Martin Stjernholmdbd814d2022-01-12 23:18:30 +0000324 if m, ok := module.(android.Module); ok {
325 // Necessary to retrieve any prebuilt replacement for the tool, since
326 // toolDepsMutator runs too late for the prebuilt mutators to have
327 // replaced the dependency.
328 module = android.PrebuiltGetPreferred(ctx, m)
329 }
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700330
Colin Crossba9e4032020-11-24 16:32:22 -0800331 switch t := module.(type) {
332 case android.HostToolProvider:
333 // A HostToolProvider provides the path to a tool, which will be copied
334 // into the sandbox.
Cole Fausta963b942024-04-11 17:43:00 -0700335 if !t.(android.Module).Enabled(ctx) {
Colin Cross6510f912017-11-29 00:27:14 -0800336 if ctx.Config().AllowMissingDependencies() {
Colin Cross35143d02017-11-16 00:11:20 -0800337 ctx.AddMissingDependencies([]string{tool})
338 } else {
339 ctx.ModuleErrorf("depends on disabled module %q", tool)
340 }
Colin Crossba9e4032020-11-24 16:32:22 -0800341 return
Colin Cross35143d02017-11-16 00:11:20 -0800342 }
Colin Crossba9e4032020-11-24 16:32:22 -0800343 path := t.HostToolPath()
344 if !path.Valid() {
345 ctx.ModuleErrorf("host tool %q missing output file", tool)
346 return
347 }
Yu Liubad1eef2024-08-21 22:37:35 +0000348 if specs := android.OtherModuleProviderOrDefault(
349 ctx, t, android.InstallFilesProvider).TransitivePackagingSpecs.ToList(); specs != nil {
Colin Crossba9e4032020-11-24 16:32:22 -0800350 // If the HostToolProvider has PackgingSpecs, which are definitions of the
351 // required relative locations of the tool and its dependencies, use those
352 // instead. They will be copied to those relative locations in the sbox
353 // sandbox.
Jiyong Park8fb0e972024-03-18 18:29:37 +0900354 // Care must be taken since TransitivePackagingSpec may return device-side
355 // paths via the required property. Filter them out.
356 for i, ps := range specs {
357 if ps.Partition() != "" {
358 if i == 0 {
359 panic("first PackagingSpec is assumed to be the host-side tool")
360 }
361 continue
362 }
363 packagedTools = append(packagedTools, ps)
364 }
Colin Crossba9e4032020-11-24 16:32:22 -0800365 // Assume that the first PackagingSpec of the module is the tool.
Colin Crossd11cf622021-03-23 22:30:35 -0700366 addLocationLabel(tag.label, packagedToolLocation{specs[0]})
Colin Crossba9e4032020-11-24 16:32:22 -0800367 } else {
368 tools = append(tools, path.Path())
Colin Crossd11cf622021-03-23 22:30:35 -0700369 addLocationLabel(tag.label, toolLocation{android.Paths{path.Path()}})
Colin Crossba9e4032020-11-24 16:32:22 -0800370 }
Colin Crossba9e4032020-11-24 16:32:22 -0800371 default:
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700372 ctx.ModuleErrorf("%q is not a host tool provider", tool)
Colin Crossba9e4032020-11-24 16:32:22 -0800373 return
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700374 }
375
Colin Crossba9e4032020-11-24 16:32:22 -0800376 seenTools[tag.label] = true
Colin Crossd350ecd2015-04-28 13:25:36 -0700377 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700378 })
Colin Crossba71a3f2019-03-18 12:12:48 -0700379
380 // If AllowMissingDependencies is enabled, the build will not have stopped when
381 // AddFarVariationDependencies was called on a missing tool, which will result in nonsensical
Liz Kammer20ebfb42020-07-28 11:32:07 -0700382 // "cmd: unknown location label ..." errors later. Add a placeholder file to the local label.
383 // The command that uses this placeholder file will never be executed because the rule will be
384 // replaced with an android.Error rule reporting the missing dependencies.
Colin Crossba71a3f2019-03-18 12:12:48 -0700385 if ctx.Config().AllowMissingDependencies() {
386 for _, tool := range g.properties.Tools {
387 if !seenTools[tool] {
Colin Crossd11cf622021-03-23 22:30:35 -0700388 addLocationLabel(tool, errorLocation{"***missing tool " + tool + "***"})
Colin Crossba71a3f2019-03-18 12:12:48 -0700389 }
390 }
391 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700392 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700393
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700394 if ctx.Failed() {
395 return
396 }
397
Colin Cross08f15ab2018-10-04 23:29:14 -0700398 for _, toolFile := range g.properties.Tool_files {
Colin Cross8a497952019-03-05 22:25:09 -0800399 paths := android.PathsForModuleSrc(ctx, []string{toolFile})
Colin Crossba9e4032020-11-24 16:32:22 -0800400 tools = append(tools, paths...)
Colin Crossd11cf622021-03-23 22:30:35 -0700401 addLocationLabel(toolFile, toolLocation{paths})
Colin Cross08f15ab2018-10-04 23:29:14 -0700402 }
403
Liz Kammer81fec182023-06-09 13:33:45 -0400404 addLabelsForInputs := func(propName string, include, exclude []string) android.Paths {
Liz Kammer81fec182023-06-09 13:33:45 -0400405 includeDirInPaths := ctx.DeviceConfig().BuildBrokenInputDir(g.Name())
406 var srcFiles android.Paths
407 for _, in := range include {
408 paths, missingDeps := android.PathsAndMissingDepsRelativeToModuleSourceDir(android.SourceInput{
409 Context: ctx, Paths: []string{in}, ExcludePaths: exclude, IncludeDirs: includeDirInPaths,
410 })
411 if len(missingDeps) > 0 {
412 if !ctx.Config().AllowMissingDependencies() {
413 panic(fmt.Errorf("should never get here, the missing dependencies %q should have been reported in DepsMutator",
414 missingDeps))
415 }
416
417 // If AllowMissingDependencies is enabled, the build will not have stopped when
418 // the dependency was added on a missing SourceFileProducer module, which will result in nonsensical
419 // "cmd: label ":..." has no files" errors later. Add a placeholder file to the local label.
420 // The command that uses this placeholder file will never be executed because the rule will be
421 // replaced with an android.Error rule reporting the missing dependencies.
422 ctx.AddMissingDependencies(missingDeps)
423 addLocationLabel(in, errorLocation{"***missing " + propName + " " + in + "***"})
424 } else {
425 srcFiles = append(srcFiles, paths...)
426 addLocationLabel(in, inputLocation{paths})
427 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700428 }
Liz Kammer81fec182023-06-09 13:33:45 -0400429 return srcFiles
Colin Cross08f15ab2018-10-04 23:29:14 -0700430 }
Cole Faustbf1d92a2024-07-29 12:24:25 -0700431 g.properties.ResolvedSrcs = g.properties.Srcs.GetOrDefault(ctx, nil)
Inseob Kim2f730622024-07-23 14:03:40 +0900432 srcFiles := addLabelsForInputs("srcs", g.properties.ResolvedSrcs, g.properties.Exclude_srcs)
Colin Cross40213022023-12-13 15:19:49 -0800433 android.SetProvider(ctx, blueprint.SrcsFileProviderKey, blueprint.SrcsFileProviderData{SrcPaths: srcFiles.Strings()})
Colin Cross08f15ab2018-10-04 23:29:14 -0700434
Colin Cross1a527682019-09-23 15:55:30 -0700435 var copyFrom android.Paths
436 var outputFiles android.WritablePaths
437 var zipArgs strings.Builder
Colin Cross08f15ab2018-10-04 23:29:14 -0700438
Aleks Todorov1eb06c42024-06-03 15:23:56 +0100439 cmd := g.properties.Cmd.GetOrDefault(ctx, "")
Colin Crossf3bfd022021-09-27 15:15:06 -0700440 if g.CmdModifier != nil {
441 cmd = g.CmdModifier(ctx, cmd)
442 }
443
Liz Kammer796921d2023-07-11 08:21:41 -0400444 var extraInputs android.Paths
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500445 // Generate tasks, either from genrule or gensrcs.
Liz Kammer81fec182023-06-09 13:33:45 -0400446 for i, task := range g.taskGenerator(ctx, cmd, srcFiles) {
Colin Cross3d680512020-11-13 16:23:53 -0800447 if len(task.out) == 0 {
448 ctx.ModuleErrorf("must have at least one output file")
449 return
Colin Cross85a2e892018-07-09 09:45:06 -0700450 }
451
Liz Kammer81fec182023-06-09 13:33:45 -0400452 // Only handle extra inputs once as these currently are the same across all tasks
453 if i == 0 {
454 for name, values := range task.extraInputs {
455 extraInputs = append(extraInputs, addLabelsForInputs(name, values, []string{})...)
456 }
457 }
458
Colin Crossf1a035e2020-11-16 17:32:30 -0800459 // Pick a unique path outside the task.genDir for the sbox manifest textproto,
460 // a unique rule name, and the user-visible description.
Inseob Kimf7cd03e2024-09-06 17:25:00 +0900461 var rule *android.RuleBuilder
Colin Crossf1a035e2020-11-16 17:32:30 -0800462 desc := "generate"
463 name := "generator"
Inseob Kimf7cd03e2024-09-06 17:25:00 +0900464 if task.useNsjail {
465 rule = android.NewRuleBuilder(pctx, ctx).Nsjail(task.genDir, android.PathForModuleOut(ctx, "nsjail_build_sandbox"))
466 } else {
467 manifestName := "genrule.sbox.textproto"
468 if task.shards > 0 {
469 manifestName = "genrule_" + strconv.Itoa(task.shard) + ".sbox.textproto"
470 desc += " " + strconv.Itoa(task.shard)
471 name += strconv.Itoa(task.shard)
472 } else if len(task.out) == 1 {
473 desc += " " + task.out[0].Base()
474 }
475
476 manifestPath := android.PathForModuleOut(ctx, manifestName)
477
478 // Use a RuleBuilder to create a rule that runs the command inside an sbox sandbox.
479 rule = getSandboxedRuleBuilder(ctx, android.NewRuleBuilder(pctx, ctx).Sbox(task.genDir, manifestPath))
Colin Crossf1a035e2020-11-16 17:32:30 -0800480 }
Justin Yun4da4ccc2023-07-06 10:56:29 +0900481 if Bool(g.properties.Write_if_changed) {
482 rule.Restat()
483 }
Colin Crossf1a035e2020-11-16 17:32:30 -0800484 cmd := rule.Command()
485
Colin Cross3d680512020-11-13 16:23:53 -0800486 for _, out := range task.out {
Colin Crossd11cf622021-03-23 22:30:35 -0700487 addLocationLabel(out.Rel(), outputLocation{out})
Colin Cross3d680512020-11-13 16:23:53 -0800488 }
489
Colin Cross3d680512020-11-13 16:23:53 -0800490 rawCommand, err := android.Expand(task.cmd, func(name string) (string, error) {
Colin Cross1a527682019-09-23 15:55:30 -0700491 // report the error directly without returning an error to android.Expand to catch multiple errors in a
492 // single run
Colin Cross3d680512020-11-13 16:23:53 -0800493 reportError := func(fmt string, args ...interface{}) (string, error) {
Colin Cross1a527682019-09-23 15:55:30 -0700494 ctx.PropertyErrorf("cmd", fmt, args...)
Colin Cross3d680512020-11-13 16:23:53 -0800495 return "SOONG_ERROR", nil
Colin Cross6f080df2016-11-04 15:32:58 -0700496 }
Colin Cross1a527682019-09-23 15:55:30 -0700497
Jihoon Kangc170af42022-08-20 05:26:38 +0000498 // Apply shell escape to each cases to prevent source file paths containing $ from being evaluated in shell
Colin Cross1a527682019-09-23 15:55:30 -0700499 switch name {
500 case "location":
501 if len(g.properties.Tools) == 0 && len(g.properties.Tool_files) == 0 {
502 return reportError("at least one `tools` or `tool_files` is required if $(location) is used")
Colin Cross6f080df2016-11-04 15:32:58 -0700503 }
Colin Crossd11cf622021-03-23 22:30:35 -0700504 loc := locationLabels[firstLabel]
505 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700506 if len(paths) == 0 {
507 return reportError("default label %q has no files", firstLabel)
508 } else if len(paths) > 1 {
509 return reportError("default label %q has multiple files, use $(locations %s) to reference it",
510 firstLabel, firstLabel)
Colin Cross08f15ab2018-10-04 23:29:14 -0700511 }
Jihoon Kangc170af42022-08-20 05:26:38 +0000512 return proptools.ShellEscape(paths[0]), nil
Colin Cross1a527682019-09-23 15:55:30 -0700513 case "in":
Jihoon Kangc170af42022-08-20 05:26:38 +0000514 return strings.Join(proptools.ShellEscapeList(cmd.PathsForInputs(srcFiles)), " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700515 case "out":
Colin Cross3d680512020-11-13 16:23:53 -0800516 var sandboxOuts []string
517 for _, out := range task.out {
Colin Crossf1a035e2020-11-16 17:32:30 -0800518 sandboxOuts = append(sandboxOuts, cmd.PathForOutput(out))
Colin Cross3d680512020-11-13 16:23:53 -0800519 }
Jihoon Kangc170af42022-08-20 05:26:38 +0000520 return strings.Join(proptools.ShellEscapeList(sandboxOuts), " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700521 case "genDir":
Jihoon Kangc170af42022-08-20 05:26:38 +0000522 return proptools.ShellEscape(cmd.PathForOutput(task.genDir)), nil
Cole Faust78f3c3a2024-08-15 17:19:34 -0700523 case "build_number_file":
524 if !proptools.Bool(g.properties.Uses_order_only_build_number_file) {
525 return reportError("to use the $(build_number_file) label, you must set uses_order_only_build_number_file: true")
526 }
527 return proptools.ShellEscape(cmd.PathForInput(ctx.Config().BuildNumberFile(ctx))), nil
Colin Cross1a527682019-09-23 15:55:30 -0700528 default:
529 if strings.HasPrefix(name, "location ") {
530 label := strings.TrimSpace(strings.TrimPrefix(name, "location "))
Colin Crossd11cf622021-03-23 22:30:35 -0700531 if loc, ok := locationLabels[label]; ok {
532 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700533 if len(paths) == 0 {
534 return reportError("label %q has no files", label)
535 } else if len(paths) > 1 {
536 return reportError("label %q has multiple files, use $(locations %s) to reference it",
537 label, label)
538 }
Jihoon Kangc170af42022-08-20 05:26:38 +0000539 return proptools.ShellEscape(paths[0]), nil
Colin Cross1a527682019-09-23 15:55:30 -0700540 } else {
Anton Hanssonbebf5262022-02-23 11:42:38 +0000541 return reportError("unknown location label %q is not in srcs, out, tools or tool_files.", label)
Colin Cross1a527682019-09-23 15:55:30 -0700542 }
543 } else if strings.HasPrefix(name, "locations ") {
544 label := strings.TrimSpace(strings.TrimPrefix(name, "locations "))
Colin Crossd11cf622021-03-23 22:30:35 -0700545 if loc, ok := locationLabels[label]; ok {
546 paths := loc.Paths(cmd)
Colin Cross1a527682019-09-23 15:55:30 -0700547 if len(paths) == 0 {
548 return reportError("label %q has no files", label)
549 }
Cole Faustce74a592023-12-07 14:58:45 -0800550 return strings.Join(proptools.ShellEscapeList(paths), " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700551 } else {
Anton Hanssonbebf5262022-02-23 11:42:38 +0000552 return reportError("unknown locations label %q is not in srcs, out, tools or tool_files.", label)
Colin Cross1a527682019-09-23 15:55:30 -0700553 }
554 } else {
555 return reportError("unknown variable '$(%s)'", name)
556 }
Colin Cross6f080df2016-11-04 15:32:58 -0700557 }
Colin Cross1a527682019-09-23 15:55:30 -0700558 })
559
560 if err != nil {
561 ctx.PropertyErrorf("cmd", "%s", err.Error())
562 return
Colin Cross6f080df2016-11-04 15:32:58 -0700563 }
Colin Cross6f080df2016-11-04 15:32:58 -0700564
Colin Cross1a527682019-09-23 15:55:30 -0700565 g.rawCommands = append(g.rawCommands, rawCommand)
Bill Peckhamc087be12020-02-13 15:55:10 -0800566
Colin Cross3d680512020-11-13 16:23:53 -0800567 cmd.Text(rawCommand)
Liz Kammer81fec182023-06-09 13:33:45 -0400568 cmd.Implicits(srcFiles) // need to be able to reference other srcs
569 cmd.Implicits(extraInputs)
Colin Cross3d680512020-11-13 16:23:53 -0800570 cmd.ImplicitOutputs(task.out)
571 cmd.Implicits(task.in)
Colin Crossba9e4032020-11-24 16:32:22 -0800572 cmd.ImplicitTools(tools)
Colin Crossba9e4032020-11-24 16:32:22 -0800573 cmd.ImplicitPackagedTools(packagedTools)
Cole Faust78f3c3a2024-08-15 17:19:34 -0700574 if proptools.Bool(g.properties.Uses_order_only_build_number_file) {
Cole Faustf23fdc02024-08-23 15:21:13 -0700575 if !isModuleInBuildNumberAllowlist(ctx) {
Cole Faust78f3c3a2024-08-15 17:19:34 -0700576 ctx.ModuleErrorf("Only allowlisted modules may use uses_order_only_build_number_file: true")
577 }
578 cmd.OrderOnly(ctx.Config().BuildNumberFile(ctx))
579 }
Colin Cross3d680512020-11-13 16:23:53 -0800580
Inseob Kimf7cd03e2024-09-06 17:25:00 +0900581 if task.useNsjail {
582 for _, input := range task.in {
583 // can fail if input is a file.
584 if paths, err := ctx.GlobWithDeps(filepath.Join(input.String(), "**/*"), nil); err == nil {
585 rule.NsjailImplicits(android.PathsForSource(ctx, paths))
586 }
587 }
588 }
589
Colin Cross3d680512020-11-13 16:23:53 -0800590 // Create the rule to run the genrule command inside sbox.
Colin Crossf1a035e2020-11-16 17:32:30 -0800591 rule.Build(name, desc)
Colin Cross1a527682019-09-23 15:55:30 -0700592
593 if len(task.copyTo) > 0 {
Colin Cross3d680512020-11-13 16:23:53 -0800594 // If copyTo is set, multiple shards need to be copied into a single directory.
595 // task.out contains the per-shard paths, and copyTo contains the corresponding
596 // final path. The files need to be copied into the final directory by a
597 // single rule so it can remove the directory before it starts to ensure no
598 // old files remain. zipsync already does this, so build up zipArgs that
599 // zip all the per-shard directories into a single zip.
Colin Cross1a527682019-09-23 15:55:30 -0700600 outputFiles = append(outputFiles, task.copyTo...)
601 copyFrom = append(copyFrom, task.out.Paths()...)
602 zipArgs.WriteString(" -C " + task.genDir.String())
603 zipArgs.WriteString(android.JoinWithPrefix(task.out.Strings(), " -f "))
604 } else {
605 outputFiles = append(outputFiles, task.out...)
606 }
Colin Cross6f080df2016-11-04 15:32:58 -0700607 }
608
Colin Cross1a527682019-09-23 15:55:30 -0700609 if len(copyFrom) > 0 {
Colin Cross3d680512020-11-13 16:23:53 -0800610 // Create a rule that zips all the per-shard directories into a single zip and then
611 // uses zipsync to unzip it into the final directory.
Colin Cross1a527682019-09-23 15:55:30 -0700612 ctx.Build(pctx, android.BuildParams{
Colin Crossf1885962020-11-20 15:28:30 -0800613 Rule: gensrcsMerge,
614 Implicits: copyFrom,
615 Outputs: outputFiles,
616 Description: "merge shards",
Colin Cross1a527682019-09-23 15:55:30 -0700617 Args: map[string]string{
618 "zipArgs": zipArgs.String(),
619 "tmpZip": android.PathForModuleGen(ctx, g.subDir+".zip").String(),
620 "genDir": android.PathForModuleGen(ctx, g.subDir).String(),
621 },
622 })
Colin Cross85a2e892018-07-09 09:45:06 -0700623 }
624
Colin Cross1a527682019-09-23 15:55:30 -0700625 g.outputFiles = outputFiles.Paths()
Chris Parsonsf874e462022-05-10 13:50:12 -0400626}
Jeff Gastonefc1b412017-03-29 17:29:06 -0700627
Chris Parsonsf874e462022-05-10 13:50:12 -0400628func (g *Module) GenerateAndroidBuildActions(ctx android.ModuleContext) {
629 g.generateCommonBuildActions(ctx)
630
631 // For <= 6 outputs, just embed those directly in the users. Right now, that covers >90% of
632 // the genrules on AOSP. That will make things simpler to look at the graph in the common
633 // case. For larger sets of outputs, inject a phony target in between to limit ninja file
634 // growth.
635 if len(g.outputFiles) <= 6 {
636 g.outputDeps = g.outputFiles
637 } else {
638 phonyFile := android.PathForModuleGen(ctx, "genrule-phony")
639 ctx.Build(pctx, android.BuildParams{
640 Rule: blueprint.Phony,
641 Output: phonyFile,
642 Inputs: g.outputFiles,
643 })
644 g.outputDeps = android.Paths{phonyFile}
Jeff Gaston02a684b2017-10-27 14:59:27 -0700645 }
mrziwang4514ef22024-06-07 13:31:48 -0700646
647 g.setOutputFiles(ctx)
648}
649
650func (g *Module) setOutputFiles(ctx android.ModuleContext) {
651 if len(g.outputFiles) == 0 {
652 return
653 }
654 ctx.SetOutputFiles(g.outputFiles, "")
655 // non-empty-string-tag should match one of the outputs
656 for _, files := range g.outputFiles {
657 ctx.SetOutputFiles(android.Paths{files}, files.Rel())
658 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400659}
660
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700661// Collect information for opening IDE project files in java/jdeps.go.
Cole Faustb36d31d2024-08-27 16:04:28 -0700662func (g *Module) IDEInfo(ctx android.BaseModuleContext, dpInfo *android.IdeInfo) {
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700663 dpInfo.Srcs = append(dpInfo.Srcs, g.Srcs().Strings()...)
Inseob Kim2f730622024-07-23 14:03:40 +0900664 for _, src := range g.properties.ResolvedSrcs {
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700665 if strings.HasPrefix(src, ":") {
666 src = strings.Trim(src, ":")
667 dpInfo.Deps = append(dpInfo.Deps, src)
668 }
669 }
670}
671
Colin Crossa4ad2b02019-03-18 22:15:32 -0700672func (g *Module) AndroidMk() android.AndroidMkData {
673 return android.AndroidMkData{
Anton Hansson72f18492020-10-30 16:34:45 +0000674 Class: "ETC",
Colin Crossa4ad2b02019-03-18 22:15:32 -0700675 OutputFile: android.OptionalPathForPath(g.outputFiles[0]),
676 SubName: g.subName,
677 Extra: []android.AndroidMkExtraFunc{
678 func(w io.Writer, outputFile android.Path) {
Anton Hansson72f18492020-10-30 16:34:45 +0000679 fmt.Fprintln(w, "LOCAL_UNINSTALLABLE_MODULE := true")
Colin Crossa4ad2b02019-03-18 22:15:32 -0700680 },
681 },
682 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
683 android.WriteAndroidMkData(w, data)
684 if data.SubName != "" {
685 fmt.Fprintln(w, ".PHONY:", name)
686 fmt.Fprintln(w, name, ":", name+g.subName)
687 }
688 },
689 }
690}
691
Jiyong Park45bf82e2020-12-15 22:29:02 +0900692var _ android.ApexModule = (*Module)(nil)
693
694// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -0700695func (g *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
696 sdkVersion android.ApiLevel) error {
Jooyung Han749dc692020-04-15 11:03:39 +0900697 // Because generated outputs are checked by client modules(e.g. cc_library, ...)
698 // we can safely ignore the check here.
699 return nil
700}
701
Jeff Gaston437d23c2017-11-08 12:38:00 -0800702func generatorFactory(taskGenerator taskFunc, props ...interface{}) *Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700703 module := &Module{
Jeff Gaston437d23c2017-11-08 12:38:00 -0800704 taskGenerator: taskGenerator,
Colin Crossd350ecd2015-04-28 13:25:36 -0700705 }
706
Colin Cross36242852017-06-23 15:06:31 -0700707 module.AddProperties(props...)
708 module.AddProperties(&module.properties)
Colin Crossd350ecd2015-04-28 13:25:36 -0700709
Colin Cross7228ecd2019-11-18 16:00:16 -0800710 module.ImageInterface = noopImageInterface{}
711
Colin Cross36242852017-06-23 15:06:31 -0700712 return module
Colin Crossd350ecd2015-04-28 13:25:36 -0700713}
714
Colin Cross7228ecd2019-11-18 16:00:16 -0800715type noopImageInterface struct{}
716
717func (x noopImageInterface) ImageMutatorBegin(android.BaseModuleContext) {}
Jihoon Kang47e91842024-06-19 00:51:16 +0000718func (x noopImageInterface) VendorVariantNeeded(android.BaseModuleContext) bool { return false }
719func (x noopImageInterface) ProductVariantNeeded(android.BaseModuleContext) bool { return false }
Colin Cross7228ecd2019-11-18 16:00:16 -0800720func (x noopImageInterface) CoreVariantNeeded(android.BaseModuleContext) bool { return false }
Yifan Hong1b3348d2020-01-21 15:53:22 -0800721func (x noopImageInterface) RamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700722func (x noopImageInterface) VendorRamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Inseob Kim08758f02021-04-08 21:13:22 +0900723func (x noopImageInterface) DebugRamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Colin Cross7228ecd2019-11-18 16:00:16 -0800724func (x noopImageInterface) RecoveryVariantNeeded(android.BaseModuleContext) bool { return false }
725func (x noopImageInterface) ExtraImageVariations(ctx android.BaseModuleContext) []string { return nil }
Jihoon Kang7583e832024-06-13 21:25:45 +0000726func (x noopImageInterface) SetImageVariation(ctx android.BaseModuleContext, variation string) {
Colin Cross7228ecd2019-11-18 16:00:16 -0800727}
728
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700729func NewGenSrcs() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700730 properties := &genSrcsProperties{}
731
Colin Crossf1885962020-11-20 15:28:30 -0800732 // finalSubDir is the name of the subdirectory that output files will be generated into.
733 // It is used so that per-shard directories can be placed alongside it an then finally
734 // merged into it.
735 const finalSubDir = "gensrcs"
736
Colin Cross1a527682019-09-23 15:55:30 -0700737 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Colin Cross1a527682019-09-23 15:55:30 -0700738 shardSize := defaultShardSize
739 if s := properties.Shard_size; s != nil {
740 shardSize = int(*s)
741 }
Jeff Gaston437d23c2017-11-08 12:38:00 -0800742
Colin Crossf1885962020-11-20 15:28:30 -0800743 // gensrcs rules can easily hit command line limits by repeating the command for
744 // every input file. Shard the input files into groups.
Colin Cross1a527682019-09-23 15:55:30 -0700745 shards := android.ShardPaths(srcFiles, shardSize)
746 var generateTasks []generateTask
Colin Crossbaccf5b2018-02-21 14:07:48 -0800747
Colin Cross1a527682019-09-23 15:55:30 -0700748 for i, shard := range shards {
749 var commands []string
750 var outFiles android.WritablePaths
751 var copyTo android.WritablePaths
Colin Cross1a527682019-09-23 15:55:30 -0700752
Colin Crossf1885962020-11-20 15:28:30 -0800753 // When sharding is enabled (i.e. len(shards) > 1), the sbox rules for each
754 // shard will be write to their own directories and then be merged together
755 // into finalSubDir. If sharding is not enabled (i.e. len(shards) == 1),
756 // the sbox rule will write directly to finalSubDir.
757 genSubDir := finalSubDir
Colin Cross1a527682019-09-23 15:55:30 -0700758 if len(shards) > 1 {
Colin Crossf1885962020-11-20 15:28:30 -0800759 genSubDir = strconv.Itoa(i)
Jeff Gaston437d23c2017-11-08 12:38:00 -0800760 }
761
Colin Crossf1885962020-11-20 15:28:30 -0800762 genDir := android.PathForModuleGen(ctx, genSubDir)
Colin Crossf1a035e2020-11-16 17:32:30 -0800763 // TODO(ccross): this RuleBuilder is a hack to be able to call
764 // rule.Command().PathForOutput. Replace this with passing the rule into the
765 // generator.
Yu Liu6a7940c2023-05-09 17:12:22 -0700766 rule := getSandboxedRuleBuilder(ctx, android.NewRuleBuilder(pctx, ctx).Sbox(genDir, nil))
Jeff Gaston437d23c2017-11-08 12:38:00 -0800767
Colin Cross3ea4eb82020-11-24 13:07:27 -0800768 for _, in := range shard {
yangbill6d032dd2024-04-18 03:05:49 +0000769 outFile := android.GenPathWithExtAndTrimExt(ctx, finalSubDir, in, String(properties.Output_extension), String(properties.Trim_extension))
Colin Crossf1885962020-11-20 15:28:30 -0800770
771 // If sharding is enabled, then outFile is the path to the output file in
772 // the shard directory, and copyTo is the path to the output file in the
773 // final directory.
Colin Cross1a527682019-09-23 15:55:30 -0700774 if len(shards) > 1 {
yangbill6d032dd2024-04-18 03:05:49 +0000775 shardFile := android.GenPathWithExtAndTrimExt(ctx, genSubDir, in, String(properties.Output_extension), String(properties.Trim_extension))
Colin Cross1a527682019-09-23 15:55:30 -0700776 copyTo = append(copyTo, outFile)
777 outFile = shardFile
778 }
779
780 outFiles = append(outFiles, outFile)
Colin Cross1a527682019-09-23 15:55:30 -0700781
Colin Crossf1885962020-11-20 15:28:30 -0800782 // pre-expand the command line to replace $in and $out with references to
783 // a single input and output file.
Colin Cross1a527682019-09-23 15:55:30 -0700784 command, err := android.Expand(rawCommand, func(name string) (string, error) {
785 switch name {
786 case "in":
787 return in.String(), nil
788 case "out":
Colin Crossf1a035e2020-11-16 17:32:30 -0800789 return rule.Command().PathForOutput(outFile), nil
Colin Cross1a527682019-09-23 15:55:30 -0700790 default:
791 return "$(" + name + ")", nil
792 }
793 })
794 if err != nil {
795 ctx.PropertyErrorf("cmd", err.Error())
796 }
797
798 // escape the command in case for example it contains '#', an odd number of '"', etc
799 command = fmt.Sprintf("bash -c %v", proptools.ShellEscape(command))
800 commands = append(commands, command)
801 }
802 fullCommand := strings.Join(commands, " && ")
803
804 generateTasks = append(generateTasks, generateTask{
Cole Faust55492572024-01-25 18:00:33 -0800805 in: shard,
806 out: outFiles,
807 copyTo: copyTo,
808 genDir: genDir,
809 cmd: fullCommand,
810 shard: i,
811 shards: len(shards),
Liz Kammer81fec182023-06-09 13:33:45 -0400812 extraInputs: map[string][]string{
813 "data": properties.Data,
814 },
Colin Cross1a527682019-09-23 15:55:30 -0700815 })
Jeff Gaston437d23c2017-11-08 12:38:00 -0800816 }
Colin Cross1a527682019-09-23 15:55:30 -0700817
818 return generateTasks
Colin Crossd350ecd2015-04-28 13:25:36 -0700819 }
820
Colin Cross1a527682019-09-23 15:55:30 -0700821 g := generatorFactory(taskGenerator, properties)
Colin Crossf1885962020-11-20 15:28:30 -0800822 g.subDir = finalSubDir
Colin Cross1a527682019-09-23 15:55:30 -0700823 return g
Colin Crossd350ecd2015-04-28 13:25:36 -0700824}
825
Colin Cross54190b32017-10-09 15:34:10 -0700826func GenSrcsFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700827 m := NewGenSrcs()
828 android.InitAndroidModule(m)
Colin Cross483b4c42024-05-09 13:08:02 -0700829 android.InitDefaultableModule(m)
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700830 return m
831}
832
Colin Crossd350ecd2015-04-28 13:25:36 -0700833type genSrcsProperties struct {
Colin Cross7d5136f2015-05-11 13:39:40 -0700834 // extension that will be substituted for each output file
Nan Zhanga5e7cb42017-11-09 22:42:32 -0800835 Output_extension *string
Colin Cross1a527682019-09-23 15:55:30 -0700836
837 // maximum number of files that will be passed on a single command line.
838 Shard_size *int64
Liz Kammer81fec182023-06-09 13:33:45 -0400839
840 // Additional files needed for build that are not tooling related.
841 Data []string `android:"path"`
yangbill6d032dd2024-04-18 03:05:49 +0000842
843 // Trim the matched extension for each input file, and it should start with ".".
844 Trim_extension *string
Colin Cross5049f022015-03-18 13:28:46 -0700845}
846
Evgenii Stepanovf47c90d2020-12-02 18:55:09 -0800847const defaultShardSize = 50
Colin Cross1a527682019-09-23 15:55:30 -0700848
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700849func NewGenRule() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700850 properties := &genRuleProperties{}
Colin Cross5049f022015-03-18 13:28:46 -0700851
Colin Cross1a527682019-09-23 15:55:30 -0700852 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Inseob Kimf7cd03e2024-09-06 17:25:00 +0900853 useNsjail := Bool(properties.Use_nsjail)
854
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700855 outs := make(android.WritablePaths, len(properties.Out))
856 for i, out := range properties.Out {
Cole Faust55492572024-01-25 18:00:33 -0800857 outs[i] = android.PathForModuleGen(ctx, out)
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700858 }
Colin Cross1a527682019-09-23 15:55:30 -0700859 return []generateTask{{
Inseob Kimf7cd03e2024-09-06 17:25:00 +0900860 in: srcFiles,
861 out: outs,
862 genDir: android.PathForModuleGen(ctx),
863 cmd: rawCommand,
864 useNsjail: useNsjail,
Colin Cross1a527682019-09-23 15:55:30 -0700865 }}
Colin Cross5049f022015-03-18 13:28:46 -0700866 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700867
Jeff Gaston437d23c2017-11-08 12:38:00 -0800868 return generatorFactory(taskGenerator, properties)
Colin Cross5049f022015-03-18 13:28:46 -0700869}
870
Colin Cross54190b32017-10-09 15:34:10 -0700871func GenRuleFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700872 m := NewGenRule()
873 android.InitAndroidModule(m)
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800874 android.InitDefaultableModule(m)
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700875 return m
876}
877
Colin Crossd350ecd2015-04-28 13:25:36 -0700878type genRuleProperties struct {
Inseob Kimf7cd03e2024-09-06 17:25:00 +0900879 Use_nsjail *bool
880
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700881 // names of the output files that will be generated
kellyhung750334a2024-03-14 01:03:49 +0800882 Out []string `android:"arch_variant"`
Colin Cross5049f022015-03-18 13:28:46 -0700883}
Nan Zhangea568a42017-11-08 21:20:04 -0800884
885var Bool = proptools.Bool
886var String = proptools.String
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800887
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800888// Defaults
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800889type Defaults struct {
890 android.ModuleBase
891 android.DefaultsModuleBase
892}
893
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800894func defaultsFactory() android.Module {
895 return DefaultsFactory()
896}
897
898func DefaultsFactory(props ...interface{}) android.Module {
899 module := &Defaults{}
900
901 module.AddProperties(props...)
902 module.AddProperties(
903 &generatorProperties{},
904 &genRuleProperties{},
905 )
906
907 android.InitDefaultsModule(module)
908
909 return module
910}
Yu Liu6a7940c2023-05-09 17:12:22 -0700911
Yu Liue7f7cbf2023-06-13 18:50:03 +0000912var sandboxingAllowlistKey = android.NewOnceKey("genruleSandboxingAllowlistKey")
913
914type sandboxingAllowlistSets struct {
915 sandboxingDenyModuleSet map[string]bool
Yu Liue7f7cbf2023-06-13 18:50:03 +0000916}
917
918func getSandboxingAllowlistSets(ctx android.PathContext) *sandboxingAllowlistSets {
919 return ctx.Config().Once(sandboxingAllowlistKey, func() interface{} {
920 sandboxingDenyModuleSet := map[string]bool{}
Yu Liue7f7cbf2023-06-13 18:50:03 +0000921
Cole Faust55492572024-01-25 18:00:33 -0800922 android.AddToStringSet(sandboxingDenyModuleSet, SandboxingDenyModuleList)
Yu Liue7f7cbf2023-06-13 18:50:03 +0000923 return &sandboxingAllowlistSets{
924 sandboxingDenyModuleSet: sandboxingDenyModuleSet,
Yu Liue7f7cbf2023-06-13 18:50:03 +0000925 }
926 }).(*sandboxingAllowlistSets)
927}
Liz Kammer0db0e342023-07-18 11:39:30 -0400928
Yu Liu6a7940c2023-05-09 17:12:22 -0700929func getSandboxedRuleBuilder(ctx android.ModuleContext, r *android.RuleBuilder) *android.RuleBuilder {
Yu Liu45d6af52023-05-24 23:10:18 +0000930 if !ctx.DeviceConfig().GenruleSandboxing() {
931 return r.SandboxTools()
932 }
Yu Liue7f7cbf2023-06-13 18:50:03 +0000933 sandboxingAllowlistSets := getSandboxingAllowlistSets(ctx)
Cole Fauste762b942024-03-15 12:46:14 -0700934 if sandboxingAllowlistSets.sandboxingDenyModuleSet[ctx.ModuleName()] {
Yu Liu6a7940c2023-05-09 17:12:22 -0700935 return r.SandboxTools()
936 }
937 return r.SandboxInputs()
938}