blob: 86408cde74aa29a30df63cebb04eee00c2bf7faa [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
15package genrule
16
17import (
Colin Cross6f080df2016-11-04 15:32:58 -070018 "fmt"
Colin Crossa4ad2b02019-03-18 22:15:32 -070019 "io"
Colin Cross3d680512020-11-13 16:23:53 -080020 "path/filepath"
Colin Cross1a527682019-09-23 15:55:30 -070021 "strconv"
Colin Cross6f080df2016-11-04 15:32:58 -070022 "strings"
Dan Willemsen3f4539b2016-09-28 16:19:10 -070023
Colin Cross70b40592015-03-23 12:57:34 -070024 "github.com/google/blueprint"
Dan Willemsen8eded0a2017-09-13 16:07:44 -070025 "github.com/google/blueprint/bootstrap"
Nan Zhangea568a42017-11-08 21:20:04 -080026 "github.com/google/blueprint/proptools"
Colin Cross5049f022015-03-18 13:28:46 -070027
Colin Cross635c3b02016-05-18 15:37:25 -070028 "android/soong/android"
Colin Cross5049f022015-03-18 13:28:46 -070029)
30
Colin Cross463a90e2015-06-17 14:20:06 -070031func init() {
Colin Crossb5ae1932020-11-17 06:32:06 +000032 registerGenruleBuildComponents(android.InitRegistrationContext)
Martin Stjernholm710ec3a2020-01-16 15:12:04 +000033}
Jaewoong Jung98716bd2018-12-10 08:13:18 -080034
Colin Crossb5ae1932020-11-17 06:32:06 +000035func registerGenruleBuildComponents(ctx android.RegistrationContext) {
Martin Stjernholm710ec3a2020-01-16 15:12:04 +000036 ctx.RegisterModuleType("genrule_defaults", defaultsFactory)
37
38 ctx.RegisterModuleType("gensrcs", GenSrcsFactory)
39 ctx.RegisterModuleType("genrule", GenRuleFactory)
40
41 ctx.FinalDepsMutators(func(ctx android.RegisterMutatorsContext) {
42 ctx.BottomUp("genrule_tool_deps", toolDepsMutator).Parallel()
43 })
Colin Cross463a90e2015-06-17 14:20:06 -070044}
45
Colin Cross5049f022015-03-18 13:28:46 -070046var (
Colin Cross635c3b02016-05-18 15:37:25 -070047 pctx = android.NewPackageContext("android/soong/genrule")
Colin Cross1a527682019-09-23 15:55:30 -070048
49 gensrcsMerge = pctx.AndroidStaticRule("gensrcsMerge", blueprint.RuleParams{
50 Command: "${soongZip} -o ${tmpZip} @${tmpZip}.rsp && ${zipSync} -d ${genDir} ${tmpZip}",
51 CommandDeps: []string{"${soongZip}", "${zipSync}"},
52 Rspfile: "${tmpZip}.rsp",
53 RspfileContent: "${zipArgs}",
54 }, "tmpZip", "genDir", "zipArgs")
Colin Cross5049f022015-03-18 13:28:46 -070055)
56
Jeff Gastonefc1b412017-03-29 17:29:06 -070057func init() {
Dan Willemsenddf504c2019-08-09 16:21:29 -070058 pctx.Import("android/soong/android")
Jeff Gastonefc1b412017-03-29 17:29:06 -070059 pctx.HostBinToolVariable("sboxCmd", "sbox")
Colin Cross1a527682019-09-23 15:55:30 -070060
61 pctx.HostBinToolVariable("soongZip", "soong_zip")
62 pctx.HostBinToolVariable("zipSync", "zipsync")
Jeff Gastonefc1b412017-03-29 17:29:06 -070063}
64
Colin Cross5049f022015-03-18 13:28:46 -070065type SourceFileGenerator interface {
Colin Cross635c3b02016-05-18 15:37:25 -070066 GeneratedSourceFiles() android.Paths
Colin Cross5ed99c62016-11-22 12:55:55 -080067 GeneratedHeaderDirs() android.Paths
Dan Willemsen9da9d492018-02-21 18:28:18 -080068 GeneratedDeps() android.Paths
Colin Cross5049f022015-03-18 13:28:46 -070069}
70
Colin Crossfe17f6f2019-03-28 19:30:56 -070071// Alias for android.HostToolProvider
72// Deprecated: use android.HostToolProvider instead.
Colin Crossd350ecd2015-04-28 13:25:36 -070073type HostToolProvider interface {
Colin Crossfe17f6f2019-03-28 19:30:56 -070074 android.HostToolProvider
Colin Crossd350ecd2015-04-28 13:25:36 -070075}
Colin Cross5049f022015-03-18 13:28:46 -070076
Dan Willemsend6ba0d52017-09-13 15:46:47 -070077type hostToolDependencyTag struct {
78 blueprint.BaseDependencyTag
Colin Cross08f15ab2018-10-04 23:29:14 -070079 label string
Dan Willemsend6ba0d52017-09-13 15:46:47 -070080}
81
Chris Parsonsaa8be052020-10-14 16:22:37 -040082// TODO(cparsons): Move to a common location when there is more than just
83// genrule with a bazel_module property.
84type bazelModuleProperties struct {
85 Label string
86}
87
Colin Cross7d5136f2015-05-11 13:39:40 -070088type generatorProperties struct {
Jeff Gastonefc1b412017-03-29 17:29:06 -070089 // The command to run on one or more input files. Cmd supports substitution of a few variables
Jeff Gastonefc1b412017-03-29 17:29:06 -070090 //
91 // Available variables for substitution:
92 //
Colin Cross2296f5b2017-10-17 21:38:14 -070093 // $(location): the path to the first entry in tools or tool_files
Colin Cross08f15ab2018-10-04 23:29:14 -070094 // $(location <label>): the path to the tool, tool_file, input or output with name <label>
Colin Cross2296f5b2017-10-17 21:38:14 -070095 // $(in): one or more input files
96 // $(out): a single output file
97 // $(depfile): a file to which dependencies will be written, if the depfile property is set to true
98 // $(genDir): the sandbox directory for this tool; contains $(out)
99 // $$: a literal $
Nan Zhangea568a42017-11-08 21:20:04 -0800100 Cmd *string
Colin Cross7d5136f2015-05-11 13:39:40 -0700101
Colin Cross33bfb0a2016-11-21 17:23:08 -0800102 // Enable reading a file containing dependencies in gcc format after the command completes
Nan Zhangea568a42017-11-08 21:20:04 -0800103 Depfile *bool
Colin Cross33bfb0a2016-11-21 17:23:08 -0800104
Colin Cross6f080df2016-11-04 15:32:58 -0700105 // name of the modules (if any) that produces the host executable. Leave empty for
Colin Cross7d5136f2015-05-11 13:39:40 -0700106 // prebuilts or scripts that do not need a module to build them.
Colin Cross6f080df2016-11-04 15:32:58 -0700107 Tools []string
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700108
109 // Local file that is used as the tool
Colin Cross27b922f2019-03-04 22:35:41 -0800110 Tool_files []string `android:"path"`
Colin Cross5ed99c62016-11-22 12:55:55 -0800111
112 // List of directories to export generated headers from
113 Export_include_dirs []string
Colin Cross708c4242017-01-13 18:05:49 -0800114
115 // list of input files
Colin Cross27b922f2019-03-04 22:35:41 -0800116 Srcs []string `android:"path,arch_variant"`
Dan Willemseneefa0262018-11-17 14:01:18 -0800117
118 // input files to exclude
Colin Cross27b922f2019-03-04 22:35:41 -0800119 Exclude_srcs []string `android:"path,arch_variant"`
Colin Cross7d5136f2015-05-11 13:39:40 -0700120
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400121 // in bazel-enabled mode, the bazel label to evaluate instead of this module
Chris Parsonsaa8be052020-10-14 16:22:37 -0400122 Bazel_module bazelModuleProperties
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400123}
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700124type Module struct {
Colin Cross635c3b02016-05-18 15:37:25 -0700125 android.ModuleBase
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800126 android.DefaultableModuleBase
Jiyong Parkfc752ca2019-06-12 13:27:29 +0900127 android.ApexModuleBase
Colin Crossd350ecd2015-04-28 13:25:36 -0700128
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700129 // For other packages to make their own genrules with extra
130 // properties
131 Extra interface{}
Colin Cross7228ecd2019-11-18 16:00:16 -0800132 android.ImageInterface
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700133
Colin Cross7d5136f2015-05-11 13:39:40 -0700134 properties generatorProperties
Colin Crossd350ecd2015-04-28 13:25:36 -0700135
Jeff Gaston437d23c2017-11-08 12:38:00 -0800136 taskGenerator taskFunc
Colin Crossd350ecd2015-04-28 13:25:36 -0700137
Colin Cross1a527682019-09-23 15:55:30 -0700138 deps android.Paths
139 rule blueprint.Rule
140 rawCommands []string
Colin Crossd350ecd2015-04-28 13:25:36 -0700141
Colin Cross5ed99c62016-11-22 12:55:55 -0800142 exportedIncludeDirs android.Paths
Dan Willemsenb40aab62016-04-20 14:21:14 -0700143
Colin Cross635c3b02016-05-18 15:37:25 -0700144 outputFiles android.Paths
Dan Willemsen9da9d492018-02-21 18:28:18 -0800145 outputDeps android.Paths
Colin Crossa4ad2b02019-03-18 22:15:32 -0700146
147 subName string
Colin Cross1a527682019-09-23 15:55:30 -0700148 subDir string
bralee1fbf4402020-05-21 10:11:59 +0800149
150 // Collect the module directory for IDE info in java/jdeps.go.
151 modulePaths []string
Colin Crossd350ecd2015-04-28 13:25:36 -0700152}
153
Colin Cross1a527682019-09-23 15:55:30 -0700154type taskFunc func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask
Colin Crossd350ecd2015-04-28 13:25:36 -0700155
156type generateTask struct {
Colin Cross3d680512020-11-13 16:23:53 -0800157 in android.Paths
158 out android.WritablePaths
159 depFile android.WritablePath
160 copyTo android.WritablePaths
161 genDir android.WritablePath
162 cmd string
163 shard int
164 shards int
Colin Crossd350ecd2015-04-28 13:25:36 -0700165}
166
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700167func (g *Module) GeneratedSourceFiles() android.Paths {
Colin Crossd350ecd2015-04-28 13:25:36 -0700168 return g.outputFiles
169}
170
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700171func (g *Module) Srcs() android.Paths {
Nan Zhange42777a2018-03-27 16:19:42 -0700172 return append(android.Paths{}, g.outputFiles...)
Colin Cross068e0fe2016-12-13 15:23:47 -0800173}
174
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700175func (g *Module) GeneratedHeaderDirs() android.Paths {
Colin Cross5ed99c62016-11-22 12:55:55 -0800176 return g.exportedIncludeDirs
Dan Willemsenb40aab62016-04-20 14:21:14 -0700177}
178
Dan Willemsen9da9d492018-02-21 18:28:18 -0800179func (g *Module) GeneratedDeps() android.Paths {
180 return g.outputDeps
181}
182
Martin Stjernholm710ec3a2020-01-16 15:12:04 +0000183func toolDepsMutator(ctx android.BottomUpMutatorContext) {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700184 if g, ok := ctx.Module().(*Module); ok {
Colin Cross08f15ab2018-10-04 23:29:14 -0700185 for _, tool := range g.properties.Tools {
186 tag := hostToolDependencyTag{label: tool}
187 if m := android.SrcIsModule(tool); m != "" {
188 tool = m
189 }
Colin Cross0f7d2ef2019-10-16 11:03:10 -0700190 ctx.AddFarVariationDependencies(ctx.Config().BuildOSTarget.Variations(), tag, tool)
Colin Cross6362e272015-10-29 15:25:03 -0700191 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700192 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700193}
194
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400195// Returns true if information was available from Bazel, false if bazel invocation still needs to occur.
196func (c *Module) generateBazelBuildActions(ctx android.ModuleContext, label string) bool {
197 bazelCtx := ctx.Config().BazelContext
198 filePaths, ok := bazelCtx.GetAllFiles(label)
199 if ok {
200 var bazelOutputFiles android.Paths
201 for _, bazelOutputFile := range filePaths {
202 bazelOutputFiles = append(bazelOutputFiles, android.PathForSource(ctx, bazelOutputFile))
203 }
204 c.outputFiles = bazelOutputFiles
205 c.outputDeps = bazelOutputFiles
206 }
207 return ok
208}
Colin Crossf1885962020-11-20 15:28:30 -0800209
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700210func (g *Module) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Colin Crossa4ad2b02019-03-18 22:15:32 -0700211 g.subName = ctx.ModuleSubDir()
212
bralee1fbf4402020-05-21 10:11:59 +0800213 // Collect the module directory for IDE info in java/jdeps.go.
214 g.modulePaths = append(g.modulePaths, ctx.ModuleDir())
215
Colin Cross5ed99c62016-11-22 12:55:55 -0800216 if len(g.properties.Export_include_dirs) > 0 {
217 for _, dir := range g.properties.Export_include_dirs {
218 g.exportedIncludeDirs = append(g.exportedIncludeDirs,
Colin Cross1a527682019-09-23 15:55:30 -0700219 android.PathForModuleGen(ctx, g.subDir, ctx.ModuleDir(), dir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800220 }
221 } else {
Colin Cross1a527682019-09-23 15:55:30 -0700222 g.exportedIncludeDirs = append(g.exportedIncludeDirs, android.PathForModuleGen(ctx, g.subDir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800223 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700224
Colin Cross08f15ab2018-10-04 23:29:14 -0700225 locationLabels := map[string][]string{}
226 firstLabel := ""
227
228 addLocationLabel := func(label string, paths []string) {
229 if firstLabel == "" {
230 firstLabel = label
231 }
232 if _, exists := locationLabels[label]; !exists {
233 locationLabels[label] = paths
234 } else {
235 ctx.ModuleErrorf("multiple labels for %q, %q and %q",
236 label, strings.Join(locationLabels[label], " "), strings.Join(paths, " "))
237 }
238 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700239
Colin Cross6f080df2016-11-04 15:32:58 -0700240 if len(g.properties.Tools) > 0 {
Colin Crossba71a3f2019-03-18 12:12:48 -0700241 seenTools := make(map[string]bool)
242
Colin Cross35143d02017-11-16 00:11:20 -0800243 ctx.VisitDirectDepsBlueprint(func(module blueprint.Module) {
Colin Cross08f15ab2018-10-04 23:29:14 -0700244 switch tag := ctx.OtherModuleDependencyTag(module).(type) {
245 case hostToolDependencyTag:
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700246 tool := ctx.OtherModuleName(module)
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700247 var path android.OptionalPath
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700248
Colin Crossfe17f6f2019-03-28 19:30:56 -0700249 if t, ok := module.(android.HostToolProvider); ok {
Colin Cross35143d02017-11-16 00:11:20 -0800250 if !t.(android.Module).Enabled() {
Colin Cross6510f912017-11-29 00:27:14 -0800251 if ctx.Config().AllowMissingDependencies() {
Colin Cross35143d02017-11-16 00:11:20 -0800252 ctx.AddMissingDependencies([]string{tool})
253 } else {
254 ctx.ModuleErrorf("depends on disabled module %q", tool)
255 }
256 break
257 }
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700258 path = t.HostToolPath()
259 } else if t, ok := module.(bootstrap.GoBinaryTool); ok {
260 if s, err := filepath.Rel(android.PathForOutput(ctx).String(), t.InstallPath()); err == nil {
261 path = android.OptionalPathForPath(android.PathForOutput(ctx, s))
Colin Cross6f080df2016-11-04 15:32:58 -0700262 } else {
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700263 ctx.ModuleErrorf("cannot find path for %q: %v", tool, err)
264 break
Colin Cross6f080df2016-11-04 15:32:58 -0700265 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700266 } else {
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700267 ctx.ModuleErrorf("%q is not a host tool provider", tool)
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700268 break
269 }
270
271 if path.Valid() {
272 g.deps = append(g.deps, path.Path())
Colin Cross08f15ab2018-10-04 23:29:14 -0700273 addLocationLabel(tag.label, []string{path.Path().String()})
Colin Crossba71a3f2019-03-18 12:12:48 -0700274 seenTools[tag.label] = true
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700275 } else {
276 ctx.ModuleErrorf("host tool %q missing output file", tool)
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700277 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700278 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700279 })
Colin Crossba71a3f2019-03-18 12:12:48 -0700280
281 // If AllowMissingDependencies is enabled, the build will not have stopped when
282 // AddFarVariationDependencies was called on a missing tool, which will result in nonsensical
Liz Kammer20ebfb42020-07-28 11:32:07 -0700283 // "cmd: unknown location label ..." errors later. Add a placeholder file to the local label.
284 // The command that uses this placeholder file will never be executed because the rule will be
285 // replaced with an android.Error rule reporting the missing dependencies.
Colin Crossba71a3f2019-03-18 12:12:48 -0700286 if ctx.Config().AllowMissingDependencies() {
287 for _, tool := range g.properties.Tools {
288 if !seenTools[tool] {
289 addLocationLabel(tool, []string{"***missing tool " + tool + "***"})
290 }
291 }
292 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700293 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700294
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700295 if ctx.Failed() {
296 return
297 }
298
Colin Cross08f15ab2018-10-04 23:29:14 -0700299 for _, toolFile := range g.properties.Tool_files {
Colin Cross8a497952019-03-05 22:25:09 -0800300 paths := android.PathsForModuleSrc(ctx, []string{toolFile})
Colin Cross08f15ab2018-10-04 23:29:14 -0700301 g.deps = append(g.deps, paths...)
302 addLocationLabel(toolFile, paths.Strings())
303 }
304
305 var srcFiles android.Paths
306 for _, in := range g.properties.Srcs {
Colin Crossba71a3f2019-03-18 12:12:48 -0700307 paths, missingDeps := android.PathsAndMissingDepsForModuleSrcExcludes(ctx, []string{in}, g.properties.Exclude_srcs)
308 if len(missingDeps) > 0 {
309 if !ctx.Config().AllowMissingDependencies() {
310 panic(fmt.Errorf("should never get here, the missing dependencies %q should have been reported in DepsMutator",
311 missingDeps))
312 }
313
314 // If AllowMissingDependencies is enabled, the build will not have stopped when
315 // the dependency was added on a missing SourceFileProducer module, which will result in nonsensical
Liz Kammer20ebfb42020-07-28 11:32:07 -0700316 // "cmd: label ":..." has no files" errors later. Add a placeholder file to the local label.
317 // The command that uses this placeholder file will never be executed because the rule will be
318 // replaced with an android.Error rule reporting the missing dependencies.
Colin Crossba71a3f2019-03-18 12:12:48 -0700319 ctx.AddMissingDependencies(missingDeps)
320 addLocationLabel(in, []string{"***missing srcs " + in + "***"})
321 } else {
322 srcFiles = append(srcFiles, paths...)
323 addLocationLabel(in, paths.Strings())
324 }
Colin Cross08f15ab2018-10-04 23:29:14 -0700325 }
326
Colin Cross1a527682019-09-23 15:55:30 -0700327 var copyFrom android.Paths
328 var outputFiles android.WritablePaths
329 var zipArgs strings.Builder
Colin Cross08f15ab2018-10-04 23:29:14 -0700330
Colin Cross1a527682019-09-23 15:55:30 -0700331 for _, task := range g.taskGenerator(ctx, String(g.properties.Cmd), srcFiles) {
Colin Cross3d680512020-11-13 16:23:53 -0800332 if len(task.out) == 0 {
333 ctx.ModuleErrorf("must have at least one output file")
334 return
Colin Cross85a2e892018-07-09 09:45:06 -0700335 }
336
Colin Cross3d680512020-11-13 16:23:53 -0800337 for _, out := range task.out {
338 addLocationLabel(out.Rel(), []string{android.SboxPathForOutput(out, task.genDir)})
339 }
340
Colin Cross1a527682019-09-23 15:55:30 -0700341 referencedDepfile := false
342
Colin Cross3d680512020-11-13 16:23:53 -0800343 rawCommand, err := android.Expand(task.cmd, func(name string) (string, error) {
Colin Cross1a527682019-09-23 15:55:30 -0700344 // report the error directly without returning an error to android.Expand to catch multiple errors in a
345 // single run
Colin Cross3d680512020-11-13 16:23:53 -0800346 reportError := func(fmt string, args ...interface{}) (string, error) {
Colin Cross1a527682019-09-23 15:55:30 -0700347 ctx.PropertyErrorf("cmd", fmt, args...)
Colin Cross3d680512020-11-13 16:23:53 -0800348 return "SOONG_ERROR", nil
Colin Cross6f080df2016-11-04 15:32:58 -0700349 }
Colin Cross1a527682019-09-23 15:55:30 -0700350
351 switch name {
352 case "location":
353 if len(g.properties.Tools) == 0 && len(g.properties.Tool_files) == 0 {
354 return reportError("at least one `tools` or `tool_files` is required if $(location) is used")
Colin Cross6f080df2016-11-04 15:32:58 -0700355 }
Colin Cross1a527682019-09-23 15:55:30 -0700356 paths := locationLabels[firstLabel]
357 if len(paths) == 0 {
358 return reportError("default label %q has no files", firstLabel)
359 } else if len(paths) > 1 {
360 return reportError("default label %q has multiple files, use $(locations %s) to reference it",
361 firstLabel, firstLabel)
Colin Cross08f15ab2018-10-04 23:29:14 -0700362 }
Colin Cross3d680512020-11-13 16:23:53 -0800363 return locationLabels[firstLabel][0], nil
Colin Cross1a527682019-09-23 15:55:30 -0700364 case "in":
Colin Cross3d680512020-11-13 16:23:53 -0800365 return strings.Join(srcFiles.Strings(), " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700366 case "out":
Colin Cross3d680512020-11-13 16:23:53 -0800367 var sandboxOuts []string
368 for _, out := range task.out {
369 sandboxOuts = append(sandboxOuts, android.SboxPathForOutput(out, task.genDir))
370 }
371 return strings.Join(sandboxOuts, " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700372 case "depfile":
373 referencedDepfile = true
374 if !Bool(g.properties.Depfile) {
375 return reportError("$(depfile) used without depfile property")
376 }
Colin Cross3d680512020-11-13 16:23:53 -0800377 return "__SBOX_DEPFILE__", nil
Colin Cross1a527682019-09-23 15:55:30 -0700378 case "genDir":
Colin Cross3d680512020-11-13 16:23:53 -0800379 return android.SboxPathForOutput(task.genDir, task.genDir), nil
Colin Cross1a527682019-09-23 15:55:30 -0700380 default:
381 if strings.HasPrefix(name, "location ") {
382 label := strings.TrimSpace(strings.TrimPrefix(name, "location "))
383 if paths, ok := locationLabels[label]; ok {
384 if len(paths) == 0 {
385 return reportError("label %q has no files", label)
386 } else if len(paths) > 1 {
387 return reportError("label %q has multiple files, use $(locations %s) to reference it",
388 label, label)
389 }
Colin Cross3d680512020-11-13 16:23:53 -0800390 return paths[0], nil
Colin Cross1a527682019-09-23 15:55:30 -0700391 } else {
392 return reportError("unknown location label %q", label)
393 }
394 } else if strings.HasPrefix(name, "locations ") {
395 label := strings.TrimSpace(strings.TrimPrefix(name, "locations "))
396 if paths, ok := locationLabels[label]; ok {
397 if len(paths) == 0 {
398 return reportError("label %q has no files", label)
399 }
Colin Cross3d680512020-11-13 16:23:53 -0800400 return strings.Join(paths, " "), nil
Colin Cross1a527682019-09-23 15:55:30 -0700401 } else {
402 return reportError("unknown locations label %q", label)
403 }
404 } else {
405 return reportError("unknown variable '$(%s)'", name)
406 }
Colin Cross6f080df2016-11-04 15:32:58 -0700407 }
Colin Cross1a527682019-09-23 15:55:30 -0700408 })
409
410 if err != nil {
411 ctx.PropertyErrorf("cmd", "%s", err.Error())
412 return
Colin Cross6f080df2016-11-04 15:32:58 -0700413 }
Colin Cross6f080df2016-11-04 15:32:58 -0700414
Colin Cross1a527682019-09-23 15:55:30 -0700415 if Bool(g.properties.Depfile) && !referencedDepfile {
416 ctx.PropertyErrorf("cmd", "specified depfile=true but did not include a reference to '${depfile}' in cmd")
417 return
418 }
Colin Cross1a527682019-09-23 15:55:30 -0700419 g.rawCommands = append(g.rawCommands, rawCommand)
Bill Peckhamc087be12020-02-13 15:55:10 -0800420
Colin Crosse16ce362020-11-12 08:29:30 -0800421 // Pick a unique path outside the task.genDir for the sbox manifest textproto,
422 // a unique rule name, and the user-visible description.
423 manifestName := "genrule.sbox.textproto"
Colin Cross3d680512020-11-13 16:23:53 -0800424 desc := "generate"
Colin Cross1a527682019-09-23 15:55:30 -0700425 name := "generator"
Colin Cross3d680512020-11-13 16:23:53 -0800426 if task.shards > 0 {
Colin Crosse16ce362020-11-12 08:29:30 -0800427 manifestName = "genrule_" + strconv.Itoa(task.shard) + ".sbox.textproto"
Colin Cross3d680512020-11-13 16:23:53 -0800428 desc += " " + strconv.Itoa(task.shard)
Colin Cross1a527682019-09-23 15:55:30 -0700429 name += strconv.Itoa(task.shard)
Colin Cross3d680512020-11-13 16:23:53 -0800430 } else if len(task.out) == 1 {
431 desc += " " + task.out[0].Base()
Colin Cross1a527682019-09-23 15:55:30 -0700432 }
Colin Cross1a527682019-09-23 15:55:30 -0700433
Colin Crosse16ce362020-11-12 08:29:30 -0800434 manifestPath := android.PathForModuleOut(ctx, manifestName)
435
Colin Cross3d680512020-11-13 16:23:53 -0800436 // Use a RuleBuilder to create a rule that runs the command inside an sbox sandbox.
Colin Crosse16ce362020-11-12 08:29:30 -0800437 rule := android.NewRuleBuilder().Sbox(task.genDir, manifestPath)
Colin Cross3d680512020-11-13 16:23:53 -0800438 cmd := rule.Command()
439 cmd.Text(rawCommand)
440 cmd.ImplicitOutputs(task.out)
441 cmd.Implicits(task.in)
442 cmd.Implicits(g.deps)
443 if Bool(g.properties.Depfile) {
444 cmd.ImplicitDepFile(task.depFile)
445 }
446
447 // Create the rule to run the genrule command inside sbox.
448 rule.Build(pctx, ctx, name, desc)
Colin Cross1a527682019-09-23 15:55:30 -0700449
450 if len(task.copyTo) > 0 {
Colin Cross3d680512020-11-13 16:23:53 -0800451 // If copyTo is set, multiple shards need to be copied into a single directory.
452 // task.out contains the per-shard paths, and copyTo contains the corresponding
453 // final path. The files need to be copied into the final directory by a
454 // single rule so it can remove the directory before it starts to ensure no
455 // old files remain. zipsync already does this, so build up zipArgs that
456 // zip all the per-shard directories into a single zip.
Colin Cross1a527682019-09-23 15:55:30 -0700457 outputFiles = append(outputFiles, task.copyTo...)
458 copyFrom = append(copyFrom, task.out.Paths()...)
459 zipArgs.WriteString(" -C " + task.genDir.String())
460 zipArgs.WriteString(android.JoinWithPrefix(task.out.Strings(), " -f "))
461 } else {
462 outputFiles = append(outputFiles, task.out...)
463 }
Colin Cross6f080df2016-11-04 15:32:58 -0700464 }
465
Colin Cross1a527682019-09-23 15:55:30 -0700466 if len(copyFrom) > 0 {
Colin Cross3d680512020-11-13 16:23:53 -0800467 // Create a rule that zips all the per-shard directories into a single zip and then
468 // uses zipsync to unzip it into the final directory.
Colin Cross1a527682019-09-23 15:55:30 -0700469 ctx.Build(pctx, android.BuildParams{
Colin Crossf1885962020-11-20 15:28:30 -0800470 Rule: gensrcsMerge,
471 Implicits: copyFrom,
472 Outputs: outputFiles,
473 Description: "merge shards",
Colin Cross1a527682019-09-23 15:55:30 -0700474 Args: map[string]string{
475 "zipArgs": zipArgs.String(),
476 "tmpZip": android.PathForModuleGen(ctx, g.subDir+".zip").String(),
477 "genDir": android.PathForModuleGen(ctx, g.subDir).String(),
478 },
479 })
Colin Cross85a2e892018-07-09 09:45:06 -0700480 }
481
Colin Cross1a527682019-09-23 15:55:30 -0700482 g.outputFiles = outputFiles.Paths()
Jeff Gastonefc1b412017-03-29 17:29:06 -0700483
Chris Parsonsaa8be052020-10-14 16:22:37 -0400484 bazelModuleLabel := g.properties.Bazel_module.Label
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400485 bazelActionsUsed := false
486 if ctx.Config().BazelContext.BazelEnabled() && len(bazelModuleLabel) > 0 {
487 bazelActionsUsed = g.generateBazelBuildActions(ctx, bazelModuleLabel)
Jeff Gaston02a684b2017-10-27 14:59:27 -0700488 }
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400489 if !bazelActionsUsed {
490 // For <= 6 outputs, just embed those directly in the users. Right now, that covers >90% of
491 // the genrules on AOSP. That will make things simpler to look at the graph in the common
492 // case. For larger sets of outputs, inject a phony target in between to limit ninja file
493 // growth.
494 if len(g.outputFiles) <= 6 {
495 g.outputDeps = g.outputFiles
496 } else {
497 phonyFile := android.PathForModuleGen(ctx, "genrule-phony")
498 ctx.Build(pctx, android.BuildParams{
499 Rule: blueprint.Phony,
500 Output: phonyFile,
501 Inputs: g.outputFiles,
502 })
503 g.outputDeps = android.Paths{phonyFile}
504 }
505 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700506}
Colin Crossd350ecd2015-04-28 13:25:36 -0700507
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700508// Collect information for opening IDE project files in java/jdeps.go.
509func (g *Module) IDEInfo(dpInfo *android.IdeInfo) {
510 dpInfo.Srcs = append(dpInfo.Srcs, g.Srcs().Strings()...)
511 for _, src := range g.properties.Srcs {
512 if strings.HasPrefix(src, ":") {
513 src = strings.Trim(src, ":")
514 dpInfo.Deps = append(dpInfo.Deps, src)
515 }
516 }
bralee1fbf4402020-05-21 10:11:59 +0800517 dpInfo.Paths = append(dpInfo.Paths, g.modulePaths...)
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700518}
519
Colin Crossa4ad2b02019-03-18 22:15:32 -0700520func (g *Module) AndroidMk() android.AndroidMkData {
521 return android.AndroidMkData{
Anton Hansson72f18492020-10-30 16:34:45 +0000522 Class: "ETC",
Colin Crossa4ad2b02019-03-18 22:15:32 -0700523 OutputFile: android.OptionalPathForPath(g.outputFiles[0]),
524 SubName: g.subName,
525 Extra: []android.AndroidMkExtraFunc{
526 func(w io.Writer, outputFile android.Path) {
Anton Hansson72f18492020-10-30 16:34:45 +0000527 fmt.Fprintln(w, "LOCAL_UNINSTALLABLE_MODULE := true")
Colin Crossa4ad2b02019-03-18 22:15:32 -0700528 },
529 },
530 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
531 android.WriteAndroidMkData(w, data)
532 if data.SubName != "" {
533 fmt.Fprintln(w, ".PHONY:", name)
534 fmt.Fprintln(w, name, ":", name+g.subName)
535 }
536 },
537 }
538}
539
Dan Albertc8060532020-07-22 22:32:17 -0700540func (g *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
541 sdkVersion android.ApiLevel) error {
Jooyung Han749dc692020-04-15 11:03:39 +0900542 // Because generated outputs are checked by client modules(e.g. cc_library, ...)
543 // we can safely ignore the check here.
544 return nil
545}
546
Jeff Gaston437d23c2017-11-08 12:38:00 -0800547func generatorFactory(taskGenerator taskFunc, props ...interface{}) *Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700548 module := &Module{
Jeff Gaston437d23c2017-11-08 12:38:00 -0800549 taskGenerator: taskGenerator,
Colin Crossd350ecd2015-04-28 13:25:36 -0700550 }
551
Colin Cross36242852017-06-23 15:06:31 -0700552 module.AddProperties(props...)
553 module.AddProperties(&module.properties)
Colin Crossd350ecd2015-04-28 13:25:36 -0700554
Colin Cross7228ecd2019-11-18 16:00:16 -0800555 module.ImageInterface = noopImageInterface{}
556
Colin Cross36242852017-06-23 15:06:31 -0700557 return module
Colin Crossd350ecd2015-04-28 13:25:36 -0700558}
559
Colin Cross7228ecd2019-11-18 16:00:16 -0800560type noopImageInterface struct{}
561
562func (x noopImageInterface) ImageMutatorBegin(android.BaseModuleContext) {}
563func (x noopImageInterface) CoreVariantNeeded(android.BaseModuleContext) bool { return false }
Yifan Hong1b3348d2020-01-21 15:53:22 -0800564func (x noopImageInterface) RamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700565func (x noopImageInterface) VendorRamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Colin Cross7228ecd2019-11-18 16:00:16 -0800566func (x noopImageInterface) RecoveryVariantNeeded(android.BaseModuleContext) bool { return false }
567func (x noopImageInterface) ExtraImageVariations(ctx android.BaseModuleContext) []string { return nil }
568func (x noopImageInterface) SetImageVariation(ctx android.BaseModuleContext, variation string, module android.Module) {
569}
570
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700571func NewGenSrcs() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700572 properties := &genSrcsProperties{}
573
Colin Crossf1885962020-11-20 15:28:30 -0800574 // finalSubDir is the name of the subdirectory that output files will be generated into.
575 // It is used so that per-shard directories can be placed alongside it an then finally
576 // merged into it.
577 const finalSubDir = "gensrcs"
578
Colin Cross1a527682019-09-23 15:55:30 -0700579 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Colin Cross1a527682019-09-23 15:55:30 -0700580 shardSize := defaultShardSize
581 if s := properties.Shard_size; s != nil {
582 shardSize = int(*s)
583 }
Jeff Gaston437d23c2017-11-08 12:38:00 -0800584
Colin Crossf1885962020-11-20 15:28:30 -0800585 // gensrcs rules can easily hit command line limits by repeating the command for
586 // every input file. Shard the input files into groups.
Colin Cross1a527682019-09-23 15:55:30 -0700587 shards := android.ShardPaths(srcFiles, shardSize)
588 var generateTasks []generateTask
Colin Crossbaccf5b2018-02-21 14:07:48 -0800589
Colin Cross1a527682019-09-23 15:55:30 -0700590 for i, shard := range shards {
591 var commands []string
592 var outFiles android.WritablePaths
593 var copyTo android.WritablePaths
Colin Cross3d680512020-11-13 16:23:53 -0800594 var depFile android.WritablePath
Colin Cross1a527682019-09-23 15:55:30 -0700595
Colin Crossf1885962020-11-20 15:28:30 -0800596 // When sharding is enabled (i.e. len(shards) > 1), the sbox rules for each
597 // shard will be write to their own directories and then be merged together
598 // into finalSubDir. If sharding is not enabled (i.e. len(shards) == 1),
599 // the sbox rule will write directly to finalSubDir.
600 genSubDir := finalSubDir
Colin Cross1a527682019-09-23 15:55:30 -0700601 if len(shards) > 1 {
Colin Crossf1885962020-11-20 15:28:30 -0800602 genSubDir = strconv.Itoa(i)
Jeff Gaston437d23c2017-11-08 12:38:00 -0800603 }
604
Colin Crossf1885962020-11-20 15:28:30 -0800605 genDir := android.PathForModuleGen(ctx, genSubDir)
Jeff Gaston437d23c2017-11-08 12:38:00 -0800606
Colin Crossf1885962020-11-20 15:28:30 -0800607 for j, in := range shard {
608 outFile := android.GenPathWithExt(ctx, finalSubDir, in, String(properties.Output_extension))
609
610 // If sharding is enabled, then outFile is the path to the output file in
611 // the shard directory, and copyTo is the path to the output file in the
612 // final directory.
Colin Cross1a527682019-09-23 15:55:30 -0700613 if len(shards) > 1 {
Colin Crossf1885962020-11-20 15:28:30 -0800614 shardFile := android.GenPathWithExt(ctx, genSubDir, in, String(properties.Output_extension))
Colin Cross1a527682019-09-23 15:55:30 -0700615 copyTo = append(copyTo, outFile)
616 outFile = shardFile
617 }
618
Colin Crossf1885962020-11-20 15:28:30 -0800619 if j == 0 {
620 depFile = outFile.ReplaceExtension(ctx, "d")
621 }
622
Colin Cross1a527682019-09-23 15:55:30 -0700623 outFiles = append(outFiles, outFile)
Colin Cross1a527682019-09-23 15:55:30 -0700624
Colin Crossf1885962020-11-20 15:28:30 -0800625 // pre-expand the command line to replace $in and $out with references to
626 // a single input and output file.
Colin Cross1a527682019-09-23 15:55:30 -0700627 command, err := android.Expand(rawCommand, func(name string) (string, error) {
628 switch name {
629 case "in":
630 return in.String(), nil
631 case "out":
Colin Crossf1885962020-11-20 15:28:30 -0800632 return android.SboxPathForOutput(outFile, genDir), nil
Colin Cross1a527682019-09-23 15:55:30 -0700633 default:
634 return "$(" + name + ")", nil
635 }
636 })
637 if err != nil {
638 ctx.PropertyErrorf("cmd", err.Error())
639 }
640
641 // escape the command in case for example it contains '#', an odd number of '"', etc
642 command = fmt.Sprintf("bash -c %v", proptools.ShellEscape(command))
643 commands = append(commands, command)
644 }
645 fullCommand := strings.Join(commands, " && ")
646
647 generateTasks = append(generateTasks, generateTask{
Colin Cross3d680512020-11-13 16:23:53 -0800648 in: shard,
649 out: outFiles,
650 depFile: depFile,
651 copyTo: copyTo,
Colin Crossf1885962020-11-20 15:28:30 -0800652 genDir: genDir,
Colin Cross3d680512020-11-13 16:23:53 -0800653 cmd: fullCommand,
654 shard: i,
655 shards: len(shards),
Colin Cross1a527682019-09-23 15:55:30 -0700656 })
Jeff Gaston437d23c2017-11-08 12:38:00 -0800657 }
Colin Cross1a527682019-09-23 15:55:30 -0700658
659 return generateTasks
Colin Crossd350ecd2015-04-28 13:25:36 -0700660 }
661
Colin Cross1a527682019-09-23 15:55:30 -0700662 g := generatorFactory(taskGenerator, properties)
Colin Crossf1885962020-11-20 15:28:30 -0800663 g.subDir = finalSubDir
Colin Cross1a527682019-09-23 15:55:30 -0700664 return g
Colin Crossd350ecd2015-04-28 13:25:36 -0700665}
666
Colin Cross54190b32017-10-09 15:34:10 -0700667func GenSrcsFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700668 m := NewGenSrcs()
669 android.InitAndroidModule(m)
670 return m
671}
672
Colin Crossd350ecd2015-04-28 13:25:36 -0700673type genSrcsProperties struct {
Colin Cross7d5136f2015-05-11 13:39:40 -0700674 // extension that will be substituted for each output file
Nan Zhanga5e7cb42017-11-09 22:42:32 -0800675 Output_extension *string
Colin Cross1a527682019-09-23 15:55:30 -0700676
677 // maximum number of files that will be passed on a single command line.
678 Shard_size *int64
Colin Cross5049f022015-03-18 13:28:46 -0700679}
680
Colin Cross1a527682019-09-23 15:55:30 -0700681const defaultShardSize = 100
682
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700683func NewGenRule() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700684 properties := &genRuleProperties{}
Colin Cross5049f022015-03-18 13:28:46 -0700685
Colin Cross1a527682019-09-23 15:55:30 -0700686 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700687 outs := make(android.WritablePaths, len(properties.Out))
Colin Cross3d680512020-11-13 16:23:53 -0800688 var depFile android.WritablePath
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700689 for i, out := range properties.Out {
Colin Cross3d680512020-11-13 16:23:53 -0800690 outPath := android.PathForModuleGen(ctx, out)
691 if i == 0 {
692 depFile = outPath.ReplaceExtension(ctx, "d")
693 }
694 outs[i] = outPath
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700695 }
Colin Cross1a527682019-09-23 15:55:30 -0700696 return []generateTask{{
Colin Cross3d680512020-11-13 16:23:53 -0800697 in: srcFiles,
698 out: outs,
699 depFile: depFile,
700 genDir: android.PathForModuleGen(ctx),
701 cmd: rawCommand,
Colin Cross1a527682019-09-23 15:55:30 -0700702 }}
Colin Cross5049f022015-03-18 13:28:46 -0700703 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700704
Jeff Gaston437d23c2017-11-08 12:38:00 -0800705 return generatorFactory(taskGenerator, properties)
Colin Cross5049f022015-03-18 13:28:46 -0700706}
707
Colin Cross54190b32017-10-09 15:34:10 -0700708func GenRuleFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700709 m := NewGenRule()
710 android.InitAndroidModule(m)
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800711 android.InitDefaultableModule(m)
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700712 return m
713}
714
Colin Crossd350ecd2015-04-28 13:25:36 -0700715type genRuleProperties struct {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700716 // names of the output files that will be generated
Colin Crossef354482018-10-23 11:27:50 -0700717 Out []string `android:"arch_variant"`
Colin Cross5049f022015-03-18 13:28:46 -0700718}
Nan Zhangea568a42017-11-08 21:20:04 -0800719
720var Bool = proptools.Bool
721var String = proptools.String
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800722
723//
724// Defaults
725//
726type Defaults struct {
727 android.ModuleBase
728 android.DefaultsModuleBase
729}
730
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800731func defaultsFactory() android.Module {
732 return DefaultsFactory()
733}
734
735func DefaultsFactory(props ...interface{}) android.Module {
736 module := &Defaults{}
737
738 module.AddProperties(props...)
739 module.AddProperties(
740 &generatorProperties{},
741 &genRuleProperties{},
742 )
743
744 android.InitDefaultsModule(module)
745
746 return module
747}