blob: a0008d329edc2d7cf9973a786ecd06da56c9fd61 [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 Cross1a527682019-09-23 15:55:30 -070020 "strconv"
Colin Cross6f080df2016-11-04 15:32:58 -070021 "strings"
Dan Willemsen3f4539b2016-09-28 16:19:10 -070022
Colin Cross70b40592015-03-23 12:57:34 -070023 "github.com/google/blueprint"
Dan Willemsen8eded0a2017-09-13 16:07:44 -070024 "github.com/google/blueprint/bootstrap"
Nan Zhangea568a42017-11-08 21:20:04 -080025 "github.com/google/blueprint/proptools"
Colin Cross5049f022015-03-18 13:28:46 -070026
Colin Cross635c3b02016-05-18 15:37:25 -070027 "android/soong/android"
Jeff Gastonefc1b412017-03-29 17:29:06 -070028 "android/soong/shared"
29 "path/filepath"
Colin Cross5049f022015-03-18 13:28:46 -070030)
31
Colin Cross463a90e2015-06-17 14:20:06 -070032func init() {
Martin Stjernholm710ec3a2020-01-16 15:12:04 +000033 registerGenruleBuildComponents(android.InitRegistrationContext)
34}
Jaewoong Jung98716bd2018-12-10 08:13:18 -080035
Martin Stjernholm710ec3a2020-01-16 15:12:04 +000036func registerGenruleBuildComponents(ctx android.RegistrationContext) {
37 ctx.RegisterModuleType("genrule_defaults", defaultsFactory)
38
39 ctx.RegisterModuleType("gensrcs", GenSrcsFactory)
40 ctx.RegisterModuleType("genrule", GenRuleFactory)
41
42 ctx.FinalDepsMutators(func(ctx android.RegisterMutatorsContext) {
43 ctx.BottomUp("genrule_tool_deps", toolDepsMutator).Parallel()
44 })
Colin Cross463a90e2015-06-17 14:20:06 -070045}
46
Colin Cross5049f022015-03-18 13:28:46 -070047var (
Colin Cross635c3b02016-05-18 15:37:25 -070048 pctx = android.NewPackageContext("android/soong/genrule")
Colin Cross1a527682019-09-23 15:55:30 -070049
50 gensrcsMerge = pctx.AndroidStaticRule("gensrcsMerge", blueprint.RuleParams{
51 Command: "${soongZip} -o ${tmpZip} @${tmpZip}.rsp && ${zipSync} -d ${genDir} ${tmpZip}",
52 CommandDeps: []string{"${soongZip}", "${zipSync}"},
53 Rspfile: "${tmpZip}.rsp",
54 RspfileContent: "${zipArgs}",
55 }, "tmpZip", "genDir", "zipArgs")
Colin Cross5049f022015-03-18 13:28:46 -070056)
57
Jeff Gastonefc1b412017-03-29 17:29:06 -070058func init() {
Dan Willemsenddf504c2019-08-09 16:21:29 -070059 pctx.Import("android/soong/android")
Jeff Gastonefc1b412017-03-29 17:29:06 -070060 pctx.HostBinToolVariable("sboxCmd", "sbox")
Colin Cross1a527682019-09-23 15:55:30 -070061
62 pctx.HostBinToolVariable("soongZip", "soong_zip")
63 pctx.HostBinToolVariable("zipSync", "zipsync")
Jeff Gastonefc1b412017-03-29 17:29:06 -070064}
65
Colin Cross5049f022015-03-18 13:28:46 -070066type SourceFileGenerator interface {
Colin Cross635c3b02016-05-18 15:37:25 -070067 GeneratedSourceFiles() android.Paths
Colin Cross5ed99c62016-11-22 12:55:55 -080068 GeneratedHeaderDirs() android.Paths
Dan Willemsen9da9d492018-02-21 18:28:18 -080069 GeneratedDeps() android.Paths
Colin Cross5049f022015-03-18 13:28:46 -070070}
71
Colin Crossfe17f6f2019-03-28 19:30:56 -070072// Alias for android.HostToolProvider
73// Deprecated: use android.HostToolProvider instead.
Colin Crossd350ecd2015-04-28 13:25:36 -070074type HostToolProvider interface {
Colin Crossfe17f6f2019-03-28 19:30:56 -070075 android.HostToolProvider
Colin Crossd350ecd2015-04-28 13:25:36 -070076}
Colin Cross5049f022015-03-18 13:28:46 -070077
Dan Willemsend6ba0d52017-09-13 15:46:47 -070078type hostToolDependencyTag struct {
79 blueprint.BaseDependencyTag
Colin Cross08f15ab2018-10-04 23:29:14 -070080 label string
Dan Willemsend6ba0d52017-09-13 15:46:47 -070081}
82
Colin Cross7d5136f2015-05-11 13:39:40 -070083type generatorProperties struct {
Jeff Gastonefc1b412017-03-29 17:29:06 -070084 // The command to run on one or more input files. Cmd supports substitution of a few variables
85 // (the actual substitution is implemented in GenerateAndroidBuildActions below)
86 //
87 // Available variables for substitution:
88 //
Colin Cross2296f5b2017-10-17 21:38:14 -070089 // $(location): the path to the first entry in tools or tool_files
Colin Cross08f15ab2018-10-04 23:29:14 -070090 // $(location <label>): the path to the tool, tool_file, input or output with name <label>
Colin Cross2296f5b2017-10-17 21:38:14 -070091 // $(in): one or more input files
92 // $(out): a single output file
93 // $(depfile): a file to which dependencies will be written, if the depfile property is set to true
94 // $(genDir): the sandbox directory for this tool; contains $(out)
95 // $$: a literal $
Colin Cross6f080df2016-11-04 15:32:58 -070096 //
Jeff Gastonefc1b412017-03-29 17:29:06 -070097 // All files used must be declared as inputs (to ensure proper up-to-date checks).
98 // Use "$(in)" directly in Cmd to ensure that all inputs used are declared.
Nan Zhangea568a42017-11-08 21:20:04 -080099 Cmd *string
Colin Cross7d5136f2015-05-11 13:39:40 -0700100
Colin Cross33bfb0a2016-11-21 17:23:08 -0800101 // Enable reading a file containing dependencies in gcc format after the command completes
Nan Zhangea568a42017-11-08 21:20:04 -0800102 Depfile *bool
Colin Cross33bfb0a2016-11-21 17:23:08 -0800103
Colin Cross6f080df2016-11-04 15:32:58 -0700104 // name of the modules (if any) that produces the host executable. Leave empty for
Colin Cross7d5136f2015-05-11 13:39:40 -0700105 // prebuilts or scripts that do not need a module to build them.
Colin Cross6f080df2016-11-04 15:32:58 -0700106 Tools []string
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700107
108 // Local file that is used as the tool
Colin Cross27b922f2019-03-04 22:35:41 -0800109 Tool_files []string `android:"path"`
Colin Cross5ed99c62016-11-22 12:55:55 -0800110
111 // List of directories to export generated headers from
112 Export_include_dirs []string
Colin Cross708c4242017-01-13 18:05:49 -0800113
114 // list of input files
Colin Cross27b922f2019-03-04 22:35:41 -0800115 Srcs []string `android:"path,arch_variant"`
Dan Willemseneefa0262018-11-17 14:01:18 -0800116
117 // input files to exclude
Colin Cross27b922f2019-03-04 22:35:41 -0800118 Exclude_srcs []string `android:"path,arch_variant"`
Colin Cross7d5136f2015-05-11 13:39:40 -0700119}
120
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700121type Module struct {
Colin Cross635c3b02016-05-18 15:37:25 -0700122 android.ModuleBase
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800123 android.DefaultableModuleBase
Jiyong Parkfc752ca2019-06-12 13:27:29 +0900124 android.ApexModuleBase
Colin Crossd350ecd2015-04-28 13:25:36 -0700125
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700126 // For other packages to make their own genrules with extra
127 // properties
128 Extra interface{}
Colin Cross7228ecd2019-11-18 16:00:16 -0800129 android.ImageInterface
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700130
Colin Cross7d5136f2015-05-11 13:39:40 -0700131 properties generatorProperties
Colin Crossd350ecd2015-04-28 13:25:36 -0700132
Jeff Gaston437d23c2017-11-08 12:38:00 -0800133 taskGenerator taskFunc
Colin Crossd350ecd2015-04-28 13:25:36 -0700134
Colin Cross1a527682019-09-23 15:55:30 -0700135 deps android.Paths
136 rule blueprint.Rule
137 rawCommands []string
Colin Crossd350ecd2015-04-28 13:25:36 -0700138
Colin Cross5ed99c62016-11-22 12:55:55 -0800139 exportedIncludeDirs android.Paths
Dan Willemsenb40aab62016-04-20 14:21:14 -0700140
Colin Cross635c3b02016-05-18 15:37:25 -0700141 outputFiles android.Paths
Dan Willemsen9da9d492018-02-21 18:28:18 -0800142 outputDeps android.Paths
Colin Crossa4ad2b02019-03-18 22:15:32 -0700143
144 subName string
Colin Cross1a527682019-09-23 15:55:30 -0700145 subDir string
Colin Crossd350ecd2015-04-28 13:25:36 -0700146}
147
Colin Cross1a527682019-09-23 15:55:30 -0700148type taskFunc func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask
Colin Crossd350ecd2015-04-28 13:25:36 -0700149
150type generateTask struct {
Colin Crossbaccf5b2018-02-21 14:07:48 -0800151 in android.Paths
152 out android.WritablePaths
Colin Cross1a527682019-09-23 15:55:30 -0700153 copyTo android.WritablePaths
154 genDir android.WritablePath
Colin Crossbaccf5b2018-02-21 14:07:48 -0800155 sandboxOuts []string
156 cmd string
Colin Cross1a527682019-09-23 15:55:30 -0700157 shard int
158 shards int
Colin Crossd350ecd2015-04-28 13:25:36 -0700159}
160
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700161func (g *Module) GeneratedSourceFiles() android.Paths {
Colin Crossd350ecd2015-04-28 13:25:36 -0700162 return g.outputFiles
163}
164
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700165func (g *Module) Srcs() android.Paths {
Nan Zhange42777a2018-03-27 16:19:42 -0700166 return append(android.Paths{}, g.outputFiles...)
Colin Cross068e0fe2016-12-13 15:23:47 -0800167}
168
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700169func (g *Module) GeneratedHeaderDirs() android.Paths {
Colin Cross5ed99c62016-11-22 12:55:55 -0800170 return g.exportedIncludeDirs
Dan Willemsenb40aab62016-04-20 14:21:14 -0700171}
172
Dan Willemsen9da9d492018-02-21 18:28:18 -0800173func (g *Module) GeneratedDeps() android.Paths {
174 return g.outputDeps
175}
176
Martin Stjernholm710ec3a2020-01-16 15:12:04 +0000177func toolDepsMutator(ctx android.BottomUpMutatorContext) {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700178 if g, ok := ctx.Module().(*Module); ok {
Colin Cross08f15ab2018-10-04 23:29:14 -0700179 for _, tool := range g.properties.Tools {
180 tag := hostToolDependencyTag{label: tool}
181 if m := android.SrcIsModule(tool); m != "" {
182 tool = m
183 }
Colin Cross0f7d2ef2019-10-16 11:03:10 -0700184 ctx.AddFarVariationDependencies(ctx.Config().BuildOSTarget.Variations(), tag, tool)
Colin Cross6362e272015-10-29 15:25:03 -0700185 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700186 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700187}
188
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700189func (g *Module) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Colin Crossa4ad2b02019-03-18 22:15:32 -0700190 g.subName = ctx.ModuleSubDir()
191
Colin Cross5ed99c62016-11-22 12:55:55 -0800192 if len(g.properties.Export_include_dirs) > 0 {
193 for _, dir := range g.properties.Export_include_dirs {
194 g.exportedIncludeDirs = append(g.exportedIncludeDirs,
Colin Cross1a527682019-09-23 15:55:30 -0700195 android.PathForModuleGen(ctx, g.subDir, ctx.ModuleDir(), dir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800196 }
197 } else {
Colin Cross1a527682019-09-23 15:55:30 -0700198 g.exportedIncludeDirs = append(g.exportedIncludeDirs, android.PathForModuleGen(ctx, g.subDir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800199 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700200
Colin Cross08f15ab2018-10-04 23:29:14 -0700201 locationLabels := map[string][]string{}
202 firstLabel := ""
203
204 addLocationLabel := func(label string, paths []string) {
205 if firstLabel == "" {
206 firstLabel = label
207 }
208 if _, exists := locationLabels[label]; !exists {
209 locationLabels[label] = paths
210 } else {
211 ctx.ModuleErrorf("multiple labels for %q, %q and %q",
212 label, strings.Join(locationLabels[label], " "), strings.Join(paths, " "))
213 }
214 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700215
Colin Cross6f080df2016-11-04 15:32:58 -0700216 if len(g.properties.Tools) > 0 {
Colin Crossba71a3f2019-03-18 12:12:48 -0700217 seenTools := make(map[string]bool)
218
Colin Cross35143d02017-11-16 00:11:20 -0800219 ctx.VisitDirectDepsBlueprint(func(module blueprint.Module) {
Colin Cross08f15ab2018-10-04 23:29:14 -0700220 switch tag := ctx.OtherModuleDependencyTag(module).(type) {
221 case hostToolDependencyTag:
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700222 tool := ctx.OtherModuleName(module)
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700223 var path android.OptionalPath
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700224
Colin Crossfe17f6f2019-03-28 19:30:56 -0700225 if t, ok := module.(android.HostToolProvider); ok {
Colin Cross35143d02017-11-16 00:11:20 -0800226 if !t.(android.Module).Enabled() {
Colin Cross6510f912017-11-29 00:27:14 -0800227 if ctx.Config().AllowMissingDependencies() {
Colin Cross35143d02017-11-16 00:11:20 -0800228 ctx.AddMissingDependencies([]string{tool})
229 } else {
230 ctx.ModuleErrorf("depends on disabled module %q", tool)
231 }
232 break
233 }
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700234 path = t.HostToolPath()
235 } else if t, ok := module.(bootstrap.GoBinaryTool); ok {
236 if s, err := filepath.Rel(android.PathForOutput(ctx).String(), t.InstallPath()); err == nil {
237 path = android.OptionalPathForPath(android.PathForOutput(ctx, s))
Colin Cross6f080df2016-11-04 15:32:58 -0700238 } else {
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700239 ctx.ModuleErrorf("cannot find path for %q: %v", tool, err)
240 break
Colin Cross6f080df2016-11-04 15:32:58 -0700241 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700242 } else {
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700243 ctx.ModuleErrorf("%q is not a host tool provider", tool)
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700244 break
245 }
246
247 if path.Valid() {
248 g.deps = append(g.deps, path.Path())
Colin Cross08f15ab2018-10-04 23:29:14 -0700249 addLocationLabel(tag.label, []string{path.Path().String()})
Colin Crossba71a3f2019-03-18 12:12:48 -0700250 seenTools[tag.label] = true
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700251 } else {
252 ctx.ModuleErrorf("host tool %q missing output file", tool)
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700253 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700254 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700255 })
Colin Crossba71a3f2019-03-18 12:12:48 -0700256
257 // If AllowMissingDependencies is enabled, the build will not have stopped when
258 // AddFarVariationDependencies was called on a missing tool, which will result in nonsensical
259 // "cmd: unknown location label ..." errors later. Add a dummy file to the local label. The
260 // command that uses this dummy file will never be executed because the rule will be replaced with
261 // an android.Error rule reporting the missing dependencies.
262 if ctx.Config().AllowMissingDependencies() {
263 for _, tool := range g.properties.Tools {
264 if !seenTools[tool] {
265 addLocationLabel(tool, []string{"***missing tool " + tool + "***"})
266 }
267 }
268 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700269 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700270
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700271 if ctx.Failed() {
272 return
273 }
274
Colin Cross08f15ab2018-10-04 23:29:14 -0700275 for _, toolFile := range g.properties.Tool_files {
Colin Cross8a497952019-03-05 22:25:09 -0800276 paths := android.PathsForModuleSrc(ctx, []string{toolFile})
Colin Cross08f15ab2018-10-04 23:29:14 -0700277 g.deps = append(g.deps, paths...)
278 addLocationLabel(toolFile, paths.Strings())
279 }
280
281 var srcFiles android.Paths
282 for _, in := range g.properties.Srcs {
Colin Crossba71a3f2019-03-18 12:12:48 -0700283 paths, missingDeps := android.PathsAndMissingDepsForModuleSrcExcludes(ctx, []string{in}, g.properties.Exclude_srcs)
284 if len(missingDeps) > 0 {
285 if !ctx.Config().AllowMissingDependencies() {
286 panic(fmt.Errorf("should never get here, the missing dependencies %q should have been reported in DepsMutator",
287 missingDeps))
288 }
289
290 // If AllowMissingDependencies is enabled, the build will not have stopped when
291 // the dependency was added on a missing SourceFileProducer module, which will result in nonsensical
292 // "cmd: label ":..." has no files" errors later. Add a dummy file to the local label. The
293 // command that uses this dummy file will never be executed because the rule will be replaced with
294 // an android.Error rule reporting the missing dependencies.
295 ctx.AddMissingDependencies(missingDeps)
296 addLocationLabel(in, []string{"***missing srcs " + in + "***"})
297 } else {
298 srcFiles = append(srcFiles, paths...)
299 addLocationLabel(in, paths.Strings())
300 }
Colin Cross08f15ab2018-10-04 23:29:14 -0700301 }
302
Colin Cross1a527682019-09-23 15:55:30 -0700303 var copyFrom android.Paths
304 var outputFiles android.WritablePaths
305 var zipArgs strings.Builder
Colin Cross08f15ab2018-10-04 23:29:14 -0700306
Colin Cross1a527682019-09-23 15:55:30 -0700307 for _, task := range g.taskGenerator(ctx, String(g.properties.Cmd), srcFiles) {
308 for _, out := range task.out {
309 addLocationLabel(out.Rel(), []string{filepath.Join("__SBOX_OUT_DIR__", out.Rel())})
Colin Cross85a2e892018-07-09 09:45:06 -0700310 }
311
Colin Cross1a527682019-09-23 15:55:30 -0700312 referencedDepfile := false
313
314 rawCommand, err := android.ExpandNinjaEscaped(task.cmd, func(name string) (string, bool, error) {
315 // report the error directly without returning an error to android.Expand to catch multiple errors in a
316 // single run
317 reportError := func(fmt string, args ...interface{}) (string, bool, error) {
318 ctx.PropertyErrorf("cmd", fmt, args...)
319 return "SOONG_ERROR", false, nil
Colin Cross6f080df2016-11-04 15:32:58 -0700320 }
Colin Cross1a527682019-09-23 15:55:30 -0700321
322 switch name {
323 case "location":
324 if len(g.properties.Tools) == 0 && len(g.properties.Tool_files) == 0 {
325 return reportError("at least one `tools` or `tool_files` is required if $(location) is used")
Colin Cross6f080df2016-11-04 15:32:58 -0700326 }
Colin Cross1a527682019-09-23 15:55:30 -0700327 paths := locationLabels[firstLabel]
328 if len(paths) == 0 {
329 return reportError("default label %q has no files", firstLabel)
330 } else if len(paths) > 1 {
331 return reportError("default label %q has multiple files, use $(locations %s) to reference it",
332 firstLabel, firstLabel)
Colin Cross08f15ab2018-10-04 23:29:14 -0700333 }
Colin Cross1a527682019-09-23 15:55:30 -0700334 return locationLabels[firstLabel][0], false, nil
335 case "in":
336 return "${in}", true, nil
337 case "out":
338 return "__SBOX_OUT_FILES__", false, nil
339 case "depfile":
340 referencedDepfile = true
341 if !Bool(g.properties.Depfile) {
342 return reportError("$(depfile) used without depfile property")
343 }
344 return "__SBOX_DEPFILE__", false, nil
345 case "genDir":
346 return "__SBOX_OUT_DIR__", false, nil
347 default:
348 if strings.HasPrefix(name, "location ") {
349 label := strings.TrimSpace(strings.TrimPrefix(name, "location "))
350 if paths, ok := locationLabels[label]; ok {
351 if len(paths) == 0 {
352 return reportError("label %q has no files", label)
353 } else if len(paths) > 1 {
354 return reportError("label %q has multiple files, use $(locations %s) to reference it",
355 label, label)
356 }
357 return paths[0], false, nil
358 } else {
359 return reportError("unknown location label %q", label)
360 }
361 } else if strings.HasPrefix(name, "locations ") {
362 label := strings.TrimSpace(strings.TrimPrefix(name, "locations "))
363 if paths, ok := locationLabels[label]; ok {
364 if len(paths) == 0 {
365 return reportError("label %q has no files", label)
366 }
367 return strings.Join(paths, " "), false, nil
368 } else {
369 return reportError("unknown locations label %q", label)
370 }
371 } else {
372 return reportError("unknown variable '$(%s)'", name)
373 }
Colin Cross6f080df2016-11-04 15:32:58 -0700374 }
Colin Cross1a527682019-09-23 15:55:30 -0700375 })
376
377 if err != nil {
378 ctx.PropertyErrorf("cmd", "%s", err.Error())
379 return
Colin Cross6f080df2016-11-04 15:32:58 -0700380 }
Colin Cross6f080df2016-11-04 15:32:58 -0700381
Colin Cross1a527682019-09-23 15:55:30 -0700382 if Bool(g.properties.Depfile) && !referencedDepfile {
383 ctx.PropertyErrorf("cmd", "specified depfile=true but did not include a reference to '${depfile}' in cmd")
384 return
385 }
386
387 // tell the sbox command which directory to use as its sandbox root
388 buildDir := android.PathForOutput(ctx).String()
389 sandboxPath := shared.TempDirForOutDir(buildDir)
390
391 // recall that Sprintf replaces percent sign expressions, whereas dollar signs expressions remain as written,
392 // to be replaced later by ninja_strings.go
393 depfilePlaceholder := ""
394 if Bool(g.properties.Depfile) {
395 depfilePlaceholder = "$depfileArgs"
396 }
397
398 // Escape the command for the shell
399 rawCommand = "'" + strings.Replace(rawCommand, "'", `'\''`, -1) + "'"
400 g.rawCommands = append(g.rawCommands, rawCommand)
401 sandboxCommand := fmt.Sprintf("rm -rf %s && $sboxCmd --sandbox-path %s --output-root %s -c %s %s $allouts",
402 task.genDir, sandboxPath, task.genDir, rawCommand, depfilePlaceholder)
403
404 ruleParams := blueprint.RuleParams{
405 Command: sandboxCommand,
406 CommandDeps: []string{"$sboxCmd"},
407 }
408 args := []string{"allouts"}
409 if Bool(g.properties.Depfile) {
410 ruleParams.Deps = blueprint.DepsGCC
411 args = append(args, "depfileArgs")
412 }
413 name := "generator"
414 if task.shards > 1 {
415 name += strconv.Itoa(task.shard)
416 }
417 rule := ctx.Rule(pctx, name, ruleParams, args...)
418
419 g.generateSourceFile(ctx, task, rule)
420
421 if len(task.copyTo) > 0 {
422 outputFiles = append(outputFiles, task.copyTo...)
423 copyFrom = append(copyFrom, task.out.Paths()...)
424 zipArgs.WriteString(" -C " + task.genDir.String())
425 zipArgs.WriteString(android.JoinWithPrefix(task.out.Strings(), " -f "))
426 } else {
427 outputFiles = append(outputFiles, task.out...)
428 }
Colin Cross6f080df2016-11-04 15:32:58 -0700429 }
430
Colin Cross1a527682019-09-23 15:55:30 -0700431 if len(copyFrom) > 0 {
432 ctx.Build(pctx, android.BuildParams{
433 Rule: gensrcsMerge,
434 Implicits: copyFrom,
435 Outputs: outputFiles,
436 Args: map[string]string{
437 "zipArgs": zipArgs.String(),
438 "tmpZip": android.PathForModuleGen(ctx, g.subDir+".zip").String(),
439 "genDir": android.PathForModuleGen(ctx, g.subDir).String(),
440 },
441 })
Colin Cross85a2e892018-07-09 09:45:06 -0700442 }
443
Colin Cross1a527682019-09-23 15:55:30 -0700444 g.outputFiles = outputFiles.Paths()
Jeff Gastonefc1b412017-03-29 17:29:06 -0700445
Colin Cross1a527682019-09-23 15:55:30 -0700446 // For <= 6 outputs, just embed those directly in the users. Right now, that covers >90% of
447 // the genrules on AOSP. That will make things simpler to look at the graph in the common
448 // case. For larger sets of outputs, inject a phony target in between to limit ninja file
449 // growth.
450 if len(g.outputFiles) <= 6 {
451 g.outputDeps = g.outputFiles
452 } else {
453 phonyFile := android.PathForModuleGen(ctx, "genrule-phony")
454
455 ctx.Build(pctx, android.BuildParams{
456 Rule: blueprint.Phony,
457 Output: phonyFile,
458 Inputs: g.outputFiles,
459 })
460
461 g.outputDeps = android.Paths{phonyFile}
Jeff Gaston02a684b2017-10-27 14:59:27 -0700462 }
Jeff Gaston5acec2b2017-11-06 14:15:16 -0800463
Colin Crossd350ecd2015-04-28 13:25:36 -0700464}
465
Colin Cross1a527682019-09-23 15:55:30 -0700466func (g *Module) generateSourceFile(ctx android.ModuleContext, task generateTask, rule blueprint.Rule) {
Colin Cross67a5c132017-05-09 13:45:28 -0700467 desc := "generate"
Colin Cross15e86d92017-10-20 15:07:08 -0700468 if len(task.out) == 0 {
469 ctx.ModuleErrorf("must have at least one output file")
470 return
471 }
Colin Cross67a5c132017-05-09 13:45:28 -0700472 if len(task.out) == 1 {
473 desc += " " + task.out[0].Base()
474 }
475
Jeff Gaston02a684b2017-10-27 14:59:27 -0700476 var depFile android.ModuleGenPath
Nan Zhangea568a42017-11-08 21:20:04 -0800477 if Bool(g.properties.Depfile) {
Jeff Gaston02a684b2017-10-27 14:59:27 -0700478 depFile = android.PathForModuleGen(ctx, task.out[0].Rel()+".d")
479 }
480
Colin Cross1a527682019-09-23 15:55:30 -0700481 if task.shards > 1 {
482 desc += " " + strconv.Itoa(task.shard)
483 }
484
Colin Crossae887032017-10-23 17:16:14 -0700485 params := android.BuildParams{
Colin Cross1a527682019-09-23 15:55:30 -0700486 Rule: rule,
487 Description: desc,
Colin Cross15e86d92017-10-20 15:07:08 -0700488 Output: task.out[0],
489 ImplicitOutputs: task.out[1:],
490 Inputs: task.in,
491 Implicits: g.deps,
492 Args: map[string]string{
Colin Crossbaccf5b2018-02-21 14:07:48 -0800493 "allouts": strings.Join(task.sandboxOuts, " "),
Colin Cross15e86d92017-10-20 15:07:08 -0700494 },
Colin Cross33bfb0a2016-11-21 17:23:08 -0800495 }
Nan Zhangea568a42017-11-08 21:20:04 -0800496 if Bool(g.properties.Depfile) {
Jeff Gaston02a684b2017-10-27 14:59:27 -0700497 params.Depfile = android.PathForModuleGen(ctx, task.out[0].Rel()+".d")
498 params.Args["depfileArgs"] = "--depfile-out " + depFile.String()
Colin Cross33bfb0a2016-11-21 17:23:08 -0800499 }
Jeff Gaston02a684b2017-10-27 14:59:27 -0700500
Colin Crossae887032017-10-23 17:16:14 -0700501 ctx.Build(pctx, params)
Colin Crossd350ecd2015-04-28 13:25:36 -0700502}
503
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700504// Collect information for opening IDE project files in java/jdeps.go.
505func (g *Module) IDEInfo(dpInfo *android.IdeInfo) {
506 dpInfo.Srcs = append(dpInfo.Srcs, g.Srcs().Strings()...)
507 for _, src := range g.properties.Srcs {
508 if strings.HasPrefix(src, ":") {
509 src = strings.Trim(src, ":")
510 dpInfo.Deps = append(dpInfo.Deps, src)
511 }
512 }
513}
514
Colin Crossa4ad2b02019-03-18 22:15:32 -0700515func (g *Module) AndroidMk() android.AndroidMkData {
516 return android.AndroidMkData{
517 Include: "$(BUILD_PHONY_PACKAGE)",
518 Class: "FAKE",
519 OutputFile: android.OptionalPathForPath(g.outputFiles[0]),
520 SubName: g.subName,
521 Extra: []android.AndroidMkExtraFunc{
522 func(w io.Writer, outputFile android.Path) {
Colin Cross1a527682019-09-23 15:55:30 -0700523 fmt.Fprintln(w, "LOCAL_ADDITIONAL_DEPENDENCIES :=", strings.Join(g.outputDeps.Strings(), " "))
Colin Crossa4ad2b02019-03-18 22:15:32 -0700524 },
525 },
526 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
527 android.WriteAndroidMkData(w, data)
528 if data.SubName != "" {
529 fmt.Fprintln(w, ".PHONY:", name)
530 fmt.Fprintln(w, name, ":", name+g.subName)
531 }
532 },
533 }
534}
535
Jeff Gaston437d23c2017-11-08 12:38:00 -0800536func generatorFactory(taskGenerator taskFunc, props ...interface{}) *Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700537 module := &Module{
Jeff Gaston437d23c2017-11-08 12:38:00 -0800538 taskGenerator: taskGenerator,
Colin Crossd350ecd2015-04-28 13:25:36 -0700539 }
540
Colin Cross36242852017-06-23 15:06:31 -0700541 module.AddProperties(props...)
542 module.AddProperties(&module.properties)
Colin Crossd350ecd2015-04-28 13:25:36 -0700543
Colin Cross7228ecd2019-11-18 16:00:16 -0800544 module.ImageInterface = noopImageInterface{}
545
Colin Cross36242852017-06-23 15:06:31 -0700546 return module
Colin Crossd350ecd2015-04-28 13:25:36 -0700547}
548
Colin Cross7228ecd2019-11-18 16:00:16 -0800549type noopImageInterface struct{}
550
551func (x noopImageInterface) ImageMutatorBegin(android.BaseModuleContext) {}
552func (x noopImageInterface) CoreVariantNeeded(android.BaseModuleContext) bool { return false }
Yifan Hong1b3348d2020-01-21 15:53:22 -0800553func (x noopImageInterface) RamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Colin Cross7228ecd2019-11-18 16:00:16 -0800554func (x noopImageInterface) RecoveryVariantNeeded(android.BaseModuleContext) bool { return false }
555func (x noopImageInterface) ExtraImageVariations(ctx android.BaseModuleContext) []string { return nil }
556func (x noopImageInterface) SetImageVariation(ctx android.BaseModuleContext, variation string, module android.Module) {
557}
558
Colin Crossbaccf5b2018-02-21 14:07:48 -0800559// replace "out" with "__SBOX_OUT_DIR__/<the value of ${out}>"
560func pathToSandboxOut(path android.Path, genDir android.Path) string {
561 relOut, err := filepath.Rel(genDir.String(), path.String())
562 if err != nil {
563 panic(fmt.Sprintf("Could not make ${out} relative: %v", err))
564 }
565 return filepath.Join("__SBOX_OUT_DIR__", relOut)
566
567}
568
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700569func NewGenSrcs() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700570 properties := &genSrcsProperties{}
571
Colin Cross1a527682019-09-23 15:55:30 -0700572 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
573 genDir := android.PathForModuleGen(ctx, "gensrcs")
574 shardSize := defaultShardSize
575 if s := properties.Shard_size; s != nil {
576 shardSize = int(*s)
577 }
Jeff Gaston437d23c2017-11-08 12:38:00 -0800578
Colin Cross1a527682019-09-23 15:55:30 -0700579 shards := android.ShardPaths(srcFiles, shardSize)
580 var generateTasks []generateTask
Colin Crossbaccf5b2018-02-21 14:07:48 -0800581
Colin Cross1a527682019-09-23 15:55:30 -0700582 for i, shard := range shards {
583 var commands []string
584 var outFiles android.WritablePaths
585 var copyTo android.WritablePaths
586 var shardDir android.WritablePath
587 var sandboxOuts []string
588
589 if len(shards) > 1 {
590 shardDir = android.PathForModuleGen(ctx, strconv.Itoa(i))
591 } else {
592 shardDir = genDir
Jeff Gaston437d23c2017-11-08 12:38:00 -0800593 }
594
Colin Cross1a527682019-09-23 15:55:30 -0700595 for _, in := range shard {
596 outFile := android.GenPathWithExt(ctx, "gensrcs", in, String(properties.Output_extension))
597 sandboxOutfile := pathToSandboxOut(outFile, genDir)
Jeff Gaston437d23c2017-11-08 12:38:00 -0800598
Colin Cross1a527682019-09-23 15:55:30 -0700599 if len(shards) > 1 {
600 shardFile := android.GenPathWithExt(ctx, strconv.Itoa(i), in, String(properties.Output_extension))
601 copyTo = append(copyTo, outFile)
602 outFile = shardFile
603 }
604
605 outFiles = append(outFiles, outFile)
606 sandboxOuts = append(sandboxOuts, sandboxOutfile)
607
608 command, err := android.Expand(rawCommand, func(name string) (string, error) {
609 switch name {
610 case "in":
611 return in.String(), nil
612 case "out":
613 return sandboxOutfile, nil
614 default:
615 return "$(" + name + ")", nil
616 }
617 })
618 if err != nil {
619 ctx.PropertyErrorf("cmd", err.Error())
620 }
621
622 // escape the command in case for example it contains '#', an odd number of '"', etc
623 command = fmt.Sprintf("bash -c %v", proptools.ShellEscape(command))
624 commands = append(commands, command)
625 }
626 fullCommand := strings.Join(commands, " && ")
627
628 generateTasks = append(generateTasks, generateTask{
629 in: shard,
630 out: outFiles,
631 copyTo: copyTo,
632 genDir: shardDir,
633 sandboxOuts: sandboxOuts,
634 cmd: fullCommand,
635 shard: i,
636 shards: len(shards),
637 })
Jeff Gaston437d23c2017-11-08 12:38:00 -0800638 }
Colin Cross1a527682019-09-23 15:55:30 -0700639
640 return generateTasks
Colin Crossd350ecd2015-04-28 13:25:36 -0700641 }
642
Colin Cross1a527682019-09-23 15:55:30 -0700643 g := generatorFactory(taskGenerator, properties)
644 g.subDir = "gensrcs"
645 return g
Colin Crossd350ecd2015-04-28 13:25:36 -0700646}
647
Colin Cross54190b32017-10-09 15:34:10 -0700648func GenSrcsFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700649 m := NewGenSrcs()
650 android.InitAndroidModule(m)
651 return m
652}
653
Colin Crossd350ecd2015-04-28 13:25:36 -0700654type genSrcsProperties struct {
Colin Cross7d5136f2015-05-11 13:39:40 -0700655 // extension that will be substituted for each output file
Nan Zhanga5e7cb42017-11-09 22:42:32 -0800656 Output_extension *string
Colin Cross1a527682019-09-23 15:55:30 -0700657
658 // maximum number of files that will be passed on a single command line.
659 Shard_size *int64
Colin Cross5049f022015-03-18 13:28:46 -0700660}
661
Colin Cross1a527682019-09-23 15:55:30 -0700662const defaultShardSize = 100
663
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700664func NewGenRule() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700665 properties := &genRuleProperties{}
Colin Cross5049f022015-03-18 13:28:46 -0700666
Colin Cross1a527682019-09-23 15:55:30 -0700667 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700668 outs := make(android.WritablePaths, len(properties.Out))
Colin Crossbaccf5b2018-02-21 14:07:48 -0800669 sandboxOuts := make([]string, len(properties.Out))
670 genDir := android.PathForModuleGen(ctx)
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700671 for i, out := range properties.Out {
672 outs[i] = android.PathForModuleGen(ctx, out)
Colin Crossbaccf5b2018-02-21 14:07:48 -0800673 sandboxOuts[i] = pathToSandboxOut(outs[i], genDir)
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700674 }
Colin Cross1a527682019-09-23 15:55:30 -0700675 return []generateTask{{
Colin Crossbaccf5b2018-02-21 14:07:48 -0800676 in: srcFiles,
677 out: outs,
Colin Cross1a527682019-09-23 15:55:30 -0700678 genDir: android.PathForModuleGen(ctx),
Colin Crossbaccf5b2018-02-21 14:07:48 -0800679 sandboxOuts: sandboxOuts,
680 cmd: rawCommand,
Colin Cross1a527682019-09-23 15:55:30 -0700681 }}
Colin Cross5049f022015-03-18 13:28:46 -0700682 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700683
Jeff Gaston437d23c2017-11-08 12:38:00 -0800684 return generatorFactory(taskGenerator, properties)
Colin Cross5049f022015-03-18 13:28:46 -0700685}
686
Colin Cross54190b32017-10-09 15:34:10 -0700687func GenRuleFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700688 m := NewGenRule()
689 android.InitAndroidModule(m)
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800690 android.InitDefaultableModule(m)
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700691 return m
692}
693
Colin Crossd350ecd2015-04-28 13:25:36 -0700694type genRuleProperties struct {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700695 // names of the output files that will be generated
Colin Crossef354482018-10-23 11:27:50 -0700696 Out []string `android:"arch_variant"`
Colin Cross5049f022015-03-18 13:28:46 -0700697}
Nan Zhangea568a42017-11-08 21:20:04 -0800698
699var Bool = proptools.Bool
700var String = proptools.String
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800701
702//
703// Defaults
704//
705type Defaults struct {
706 android.ModuleBase
707 android.DefaultsModuleBase
708}
709
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800710func defaultsFactory() android.Module {
711 return DefaultsFactory()
712}
713
714func DefaultsFactory(props ...interface{}) android.Module {
715 module := &Defaults{}
716
717 module.AddProperties(props...)
718 module.AddProperties(
719 &generatorProperties{},
720 &genRuleProperties{},
721 )
722
723 android.InitDefaultsModule(module)
724
725 return module
726}