blob: 57ca9bc6fda226812c4ed84ee9c75f836537d788 [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() {
Jaewoong Jung98716bd2018-12-10 08:13:18 -080033 android.RegisterModuleType("genrule_defaults", defaultsFactory)
34
Colin Cross54190b32017-10-09 15:34:10 -070035 android.RegisterModuleType("gensrcs", GenSrcsFactory)
36 android.RegisterModuleType("genrule", GenRuleFactory)
Colin Cross463a90e2015-06-17 14:20:06 -070037}
38
Colin Cross5049f022015-03-18 13:28:46 -070039var (
Colin Cross635c3b02016-05-18 15:37:25 -070040 pctx = android.NewPackageContext("android/soong/genrule")
Colin Cross1a527682019-09-23 15:55:30 -070041
42 gensrcsMerge = pctx.AndroidStaticRule("gensrcsMerge", blueprint.RuleParams{
43 Command: "${soongZip} -o ${tmpZip} @${tmpZip}.rsp && ${zipSync} -d ${genDir} ${tmpZip}",
44 CommandDeps: []string{"${soongZip}", "${zipSync}"},
45 Rspfile: "${tmpZip}.rsp",
46 RspfileContent: "${zipArgs}",
47 }, "tmpZip", "genDir", "zipArgs")
Colin Cross5049f022015-03-18 13:28:46 -070048)
49
Jeff Gastonefc1b412017-03-29 17:29:06 -070050func init() {
Dan Willemsenddf504c2019-08-09 16:21:29 -070051 pctx.Import("android/soong/android")
Jeff Gastonefc1b412017-03-29 17:29:06 -070052 pctx.HostBinToolVariable("sboxCmd", "sbox")
Colin Cross1a527682019-09-23 15:55:30 -070053
54 pctx.HostBinToolVariable("soongZip", "soong_zip")
55 pctx.HostBinToolVariable("zipSync", "zipsync")
Jeff Gastonefc1b412017-03-29 17:29:06 -070056}
57
Colin Cross5049f022015-03-18 13:28:46 -070058type SourceFileGenerator interface {
Colin Cross635c3b02016-05-18 15:37:25 -070059 GeneratedSourceFiles() android.Paths
Colin Cross5ed99c62016-11-22 12:55:55 -080060 GeneratedHeaderDirs() android.Paths
Dan Willemsen9da9d492018-02-21 18:28:18 -080061 GeneratedDeps() android.Paths
Colin Cross5049f022015-03-18 13:28:46 -070062}
63
Colin Crossfe17f6f2019-03-28 19:30:56 -070064// Alias for android.HostToolProvider
65// Deprecated: use android.HostToolProvider instead.
Colin Crossd350ecd2015-04-28 13:25:36 -070066type HostToolProvider interface {
Colin Crossfe17f6f2019-03-28 19:30:56 -070067 android.HostToolProvider
Colin Crossd350ecd2015-04-28 13:25:36 -070068}
Colin Cross5049f022015-03-18 13:28:46 -070069
Dan Willemsend6ba0d52017-09-13 15:46:47 -070070type hostToolDependencyTag struct {
71 blueprint.BaseDependencyTag
Colin Cross08f15ab2018-10-04 23:29:14 -070072 label string
Dan Willemsend6ba0d52017-09-13 15:46:47 -070073}
74
Colin Cross7d5136f2015-05-11 13:39:40 -070075type generatorProperties struct {
Jeff Gastonefc1b412017-03-29 17:29:06 -070076 // The command to run on one or more input files. Cmd supports substitution of a few variables
77 // (the actual substitution is implemented in GenerateAndroidBuildActions below)
78 //
79 // Available variables for substitution:
80 //
Colin Cross2296f5b2017-10-17 21:38:14 -070081 // $(location): the path to the first entry in tools or tool_files
Colin Cross08f15ab2018-10-04 23:29:14 -070082 // $(location <label>): the path to the tool, tool_file, input or output with name <label>
Colin Cross2296f5b2017-10-17 21:38:14 -070083 // $(in): one or more input files
84 // $(out): a single output file
85 // $(depfile): a file to which dependencies will be written, if the depfile property is set to true
86 // $(genDir): the sandbox directory for this tool; contains $(out)
87 // $$: a literal $
Colin Cross6f080df2016-11-04 15:32:58 -070088 //
Jeff Gastonefc1b412017-03-29 17:29:06 -070089 // All files used must be declared as inputs (to ensure proper up-to-date checks).
90 // Use "$(in)" directly in Cmd to ensure that all inputs used are declared.
Nan Zhangea568a42017-11-08 21:20:04 -080091 Cmd *string
Colin Cross7d5136f2015-05-11 13:39:40 -070092
Colin Cross33bfb0a2016-11-21 17:23:08 -080093 // Enable reading a file containing dependencies in gcc format after the command completes
Nan Zhangea568a42017-11-08 21:20:04 -080094 Depfile *bool
Colin Cross33bfb0a2016-11-21 17:23:08 -080095
Colin Cross6f080df2016-11-04 15:32:58 -070096 // name of the modules (if any) that produces the host executable. Leave empty for
Colin Cross7d5136f2015-05-11 13:39:40 -070097 // prebuilts or scripts that do not need a module to build them.
Colin Cross6f080df2016-11-04 15:32:58 -070098 Tools []string
Dan Willemsenf7f3d692016-04-20 14:54:32 -070099
100 // Local file that is used as the tool
Colin Cross27b922f2019-03-04 22:35:41 -0800101 Tool_files []string `android:"path"`
Colin Cross5ed99c62016-11-22 12:55:55 -0800102
103 // List of directories to export generated headers from
104 Export_include_dirs []string
Colin Cross708c4242017-01-13 18:05:49 -0800105
106 // list of input files
Colin Cross27b922f2019-03-04 22:35:41 -0800107 Srcs []string `android:"path,arch_variant"`
Dan Willemseneefa0262018-11-17 14:01:18 -0800108
109 // input files to exclude
Colin Cross27b922f2019-03-04 22:35:41 -0800110 Exclude_srcs []string `android:"path,arch_variant"`
Colin Cross7d5136f2015-05-11 13:39:40 -0700111}
112
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700113type Module struct {
Colin Cross635c3b02016-05-18 15:37:25 -0700114 android.ModuleBase
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800115 android.DefaultableModuleBase
Jiyong Parkfc752ca2019-06-12 13:27:29 +0900116 android.ApexModuleBase
Colin Crossd350ecd2015-04-28 13:25:36 -0700117
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700118 // For other packages to make their own genrules with extra
119 // properties
120 Extra interface{}
Colin Cross7228ecd2019-11-18 16:00:16 -0800121 android.ImageInterface
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700122
Colin Cross7d5136f2015-05-11 13:39:40 -0700123 properties generatorProperties
Colin Crossd350ecd2015-04-28 13:25:36 -0700124
Jeff Gaston437d23c2017-11-08 12:38:00 -0800125 taskGenerator taskFunc
Colin Crossd350ecd2015-04-28 13:25:36 -0700126
Colin Cross1a527682019-09-23 15:55:30 -0700127 deps android.Paths
128 rule blueprint.Rule
129 rawCommands []string
Colin Crossd350ecd2015-04-28 13:25:36 -0700130
Colin Cross5ed99c62016-11-22 12:55:55 -0800131 exportedIncludeDirs android.Paths
Dan Willemsenb40aab62016-04-20 14:21:14 -0700132
Colin Cross635c3b02016-05-18 15:37:25 -0700133 outputFiles android.Paths
Dan Willemsen9da9d492018-02-21 18:28:18 -0800134 outputDeps android.Paths
Colin Crossa4ad2b02019-03-18 22:15:32 -0700135
136 subName string
Colin Cross1a527682019-09-23 15:55:30 -0700137 subDir string
Colin Crossd350ecd2015-04-28 13:25:36 -0700138}
139
Colin Cross1a527682019-09-23 15:55:30 -0700140type taskFunc func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask
Colin Crossd350ecd2015-04-28 13:25:36 -0700141
142type generateTask struct {
Colin Crossbaccf5b2018-02-21 14:07:48 -0800143 in android.Paths
144 out android.WritablePaths
Colin Cross1a527682019-09-23 15:55:30 -0700145 copyTo android.WritablePaths
146 genDir android.WritablePath
Colin Crossbaccf5b2018-02-21 14:07:48 -0800147 sandboxOuts []string
148 cmd string
Colin Cross1a527682019-09-23 15:55:30 -0700149 shard int
150 shards int
Colin Crossd350ecd2015-04-28 13:25:36 -0700151}
152
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700153func (g *Module) GeneratedSourceFiles() android.Paths {
Colin Crossd350ecd2015-04-28 13:25:36 -0700154 return g.outputFiles
155}
156
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700157func (g *Module) Srcs() android.Paths {
Nan Zhange42777a2018-03-27 16:19:42 -0700158 return append(android.Paths{}, g.outputFiles...)
Colin Cross068e0fe2016-12-13 15:23:47 -0800159}
160
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700161func (g *Module) GeneratedHeaderDirs() android.Paths {
Colin Cross5ed99c62016-11-22 12:55:55 -0800162 return g.exportedIncludeDirs
Dan Willemsenb40aab62016-04-20 14:21:14 -0700163}
164
Dan Willemsen9da9d492018-02-21 18:28:18 -0800165func (g *Module) GeneratedDeps() android.Paths {
166 return g.outputDeps
167}
168
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700169func (g *Module) DepsMutator(ctx android.BottomUpMutatorContext) {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700170 if g, ok := ctx.Module().(*Module); ok {
Colin Cross08f15ab2018-10-04 23:29:14 -0700171 for _, tool := range g.properties.Tools {
172 tag := hostToolDependencyTag{label: tool}
173 if m := android.SrcIsModule(tool); m != "" {
174 tool = m
175 }
Colin Cross0f7d2ef2019-10-16 11:03:10 -0700176 ctx.AddFarVariationDependencies(ctx.Config().BuildOSTarget.Variations(), tag, tool)
Colin Cross6362e272015-10-29 15:25:03 -0700177 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700178 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700179}
180
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700181func (g *Module) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Colin Crossa4ad2b02019-03-18 22:15:32 -0700182 g.subName = ctx.ModuleSubDir()
183
Colin Cross5ed99c62016-11-22 12:55:55 -0800184 if len(g.properties.Export_include_dirs) > 0 {
185 for _, dir := range g.properties.Export_include_dirs {
186 g.exportedIncludeDirs = append(g.exportedIncludeDirs,
Colin Cross1a527682019-09-23 15:55:30 -0700187 android.PathForModuleGen(ctx, g.subDir, ctx.ModuleDir(), dir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800188 }
189 } else {
Colin Cross1a527682019-09-23 15:55:30 -0700190 g.exportedIncludeDirs = append(g.exportedIncludeDirs, android.PathForModuleGen(ctx, g.subDir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800191 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700192
Colin Cross08f15ab2018-10-04 23:29:14 -0700193 locationLabels := map[string][]string{}
194 firstLabel := ""
195
196 addLocationLabel := func(label string, paths []string) {
197 if firstLabel == "" {
198 firstLabel = label
199 }
200 if _, exists := locationLabels[label]; !exists {
201 locationLabels[label] = paths
202 } else {
203 ctx.ModuleErrorf("multiple labels for %q, %q and %q",
204 label, strings.Join(locationLabels[label], " "), strings.Join(paths, " "))
205 }
206 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700207
Colin Cross6f080df2016-11-04 15:32:58 -0700208 if len(g.properties.Tools) > 0 {
Colin Crossba71a3f2019-03-18 12:12:48 -0700209 seenTools := make(map[string]bool)
210
Colin Cross35143d02017-11-16 00:11:20 -0800211 ctx.VisitDirectDepsBlueprint(func(module blueprint.Module) {
Colin Cross08f15ab2018-10-04 23:29:14 -0700212 switch tag := ctx.OtherModuleDependencyTag(module).(type) {
213 case hostToolDependencyTag:
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700214 tool := ctx.OtherModuleName(module)
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700215 var path android.OptionalPath
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700216
Colin Crossfe17f6f2019-03-28 19:30:56 -0700217 if t, ok := module.(android.HostToolProvider); ok {
Colin Cross35143d02017-11-16 00:11:20 -0800218 if !t.(android.Module).Enabled() {
Colin Cross6510f912017-11-29 00:27:14 -0800219 if ctx.Config().AllowMissingDependencies() {
Colin Cross35143d02017-11-16 00:11:20 -0800220 ctx.AddMissingDependencies([]string{tool})
221 } else {
222 ctx.ModuleErrorf("depends on disabled module %q", tool)
223 }
224 break
225 }
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700226 path = t.HostToolPath()
227 } else if t, ok := module.(bootstrap.GoBinaryTool); ok {
228 if s, err := filepath.Rel(android.PathForOutput(ctx).String(), t.InstallPath()); err == nil {
229 path = android.OptionalPathForPath(android.PathForOutput(ctx, s))
Colin Cross6f080df2016-11-04 15:32:58 -0700230 } else {
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700231 ctx.ModuleErrorf("cannot find path for %q: %v", tool, err)
232 break
Colin Cross6f080df2016-11-04 15:32:58 -0700233 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700234 } else {
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700235 ctx.ModuleErrorf("%q is not a host tool provider", tool)
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700236 break
237 }
238
239 if path.Valid() {
240 g.deps = append(g.deps, path.Path())
Colin Cross08f15ab2018-10-04 23:29:14 -0700241 addLocationLabel(tag.label, []string{path.Path().String()})
Colin Crossba71a3f2019-03-18 12:12:48 -0700242 seenTools[tag.label] = true
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700243 } else {
244 ctx.ModuleErrorf("host tool %q missing output file", tool)
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700245 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700246 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700247 })
Colin Crossba71a3f2019-03-18 12:12:48 -0700248
249 // If AllowMissingDependencies is enabled, the build will not have stopped when
250 // AddFarVariationDependencies was called on a missing tool, which will result in nonsensical
251 // "cmd: unknown location label ..." errors later. Add a dummy file to the local label. The
252 // command that uses this dummy file will never be executed because the rule will be replaced with
253 // an android.Error rule reporting the missing dependencies.
254 if ctx.Config().AllowMissingDependencies() {
255 for _, tool := range g.properties.Tools {
256 if !seenTools[tool] {
257 addLocationLabel(tool, []string{"***missing tool " + tool + "***"})
258 }
259 }
260 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700261 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700262
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700263 if ctx.Failed() {
264 return
265 }
266
Colin Cross08f15ab2018-10-04 23:29:14 -0700267 for _, toolFile := range g.properties.Tool_files {
Colin Cross8a497952019-03-05 22:25:09 -0800268 paths := android.PathsForModuleSrc(ctx, []string{toolFile})
Colin Cross08f15ab2018-10-04 23:29:14 -0700269 g.deps = append(g.deps, paths...)
270 addLocationLabel(toolFile, paths.Strings())
271 }
272
273 var srcFiles android.Paths
274 for _, in := range g.properties.Srcs {
Colin Crossba71a3f2019-03-18 12:12:48 -0700275 paths, missingDeps := android.PathsAndMissingDepsForModuleSrcExcludes(ctx, []string{in}, g.properties.Exclude_srcs)
276 if len(missingDeps) > 0 {
277 if !ctx.Config().AllowMissingDependencies() {
278 panic(fmt.Errorf("should never get here, the missing dependencies %q should have been reported in DepsMutator",
279 missingDeps))
280 }
281
282 // If AllowMissingDependencies is enabled, the build will not have stopped when
283 // the dependency was added on a missing SourceFileProducer module, which will result in nonsensical
284 // "cmd: label ":..." has no files" errors later. Add a dummy file to the local label. The
285 // command that uses this dummy file will never be executed because the rule will be replaced with
286 // an android.Error rule reporting the missing dependencies.
287 ctx.AddMissingDependencies(missingDeps)
288 addLocationLabel(in, []string{"***missing srcs " + in + "***"})
289 } else {
290 srcFiles = append(srcFiles, paths...)
291 addLocationLabel(in, paths.Strings())
292 }
Colin Cross08f15ab2018-10-04 23:29:14 -0700293 }
294
Colin Cross1a527682019-09-23 15:55:30 -0700295 var copyFrom android.Paths
296 var outputFiles android.WritablePaths
297 var zipArgs strings.Builder
Colin Cross08f15ab2018-10-04 23:29:14 -0700298
Colin Cross1a527682019-09-23 15:55:30 -0700299 for _, task := range g.taskGenerator(ctx, String(g.properties.Cmd), srcFiles) {
300 for _, out := range task.out {
301 addLocationLabel(out.Rel(), []string{filepath.Join("__SBOX_OUT_DIR__", out.Rel())})
Colin Cross85a2e892018-07-09 09:45:06 -0700302 }
303
Colin Cross1a527682019-09-23 15:55:30 -0700304 referencedDepfile := false
305
306 rawCommand, err := android.ExpandNinjaEscaped(task.cmd, func(name string) (string, bool, error) {
307 // report the error directly without returning an error to android.Expand to catch multiple errors in a
308 // single run
309 reportError := func(fmt string, args ...interface{}) (string, bool, error) {
310 ctx.PropertyErrorf("cmd", fmt, args...)
311 return "SOONG_ERROR", false, nil
Colin Cross6f080df2016-11-04 15:32:58 -0700312 }
Colin Cross1a527682019-09-23 15:55:30 -0700313
314 switch name {
315 case "location":
316 if len(g.properties.Tools) == 0 && len(g.properties.Tool_files) == 0 {
317 return reportError("at least one `tools` or `tool_files` is required if $(location) is used")
Colin Cross6f080df2016-11-04 15:32:58 -0700318 }
Colin Cross1a527682019-09-23 15:55:30 -0700319 paths := locationLabels[firstLabel]
320 if len(paths) == 0 {
321 return reportError("default label %q has no files", firstLabel)
322 } else if len(paths) > 1 {
323 return reportError("default label %q has multiple files, use $(locations %s) to reference it",
324 firstLabel, firstLabel)
Colin Cross08f15ab2018-10-04 23:29:14 -0700325 }
Colin Cross1a527682019-09-23 15:55:30 -0700326 return locationLabels[firstLabel][0], false, nil
327 case "in":
328 return "${in}", true, nil
329 case "out":
330 return "__SBOX_OUT_FILES__", false, nil
331 case "depfile":
332 referencedDepfile = true
333 if !Bool(g.properties.Depfile) {
334 return reportError("$(depfile) used without depfile property")
335 }
336 return "__SBOX_DEPFILE__", false, nil
337 case "genDir":
338 return "__SBOX_OUT_DIR__", false, nil
339 default:
340 if strings.HasPrefix(name, "location ") {
341 label := strings.TrimSpace(strings.TrimPrefix(name, "location "))
342 if paths, ok := locationLabels[label]; ok {
343 if len(paths) == 0 {
344 return reportError("label %q has no files", label)
345 } else if len(paths) > 1 {
346 return reportError("label %q has multiple files, use $(locations %s) to reference it",
347 label, label)
348 }
349 return paths[0], false, nil
350 } else {
351 return reportError("unknown location label %q", label)
352 }
353 } else if strings.HasPrefix(name, "locations ") {
354 label := strings.TrimSpace(strings.TrimPrefix(name, "locations "))
355 if paths, ok := locationLabels[label]; ok {
356 if len(paths) == 0 {
357 return reportError("label %q has no files", label)
358 }
359 return strings.Join(paths, " "), false, nil
360 } else {
361 return reportError("unknown locations label %q", label)
362 }
363 } else {
364 return reportError("unknown variable '$(%s)'", name)
365 }
Colin Cross6f080df2016-11-04 15:32:58 -0700366 }
Colin Cross1a527682019-09-23 15:55:30 -0700367 })
368
369 if err != nil {
370 ctx.PropertyErrorf("cmd", "%s", err.Error())
371 return
Colin Cross6f080df2016-11-04 15:32:58 -0700372 }
Colin Cross6f080df2016-11-04 15:32:58 -0700373
Colin Cross1a527682019-09-23 15:55:30 -0700374 if Bool(g.properties.Depfile) && !referencedDepfile {
375 ctx.PropertyErrorf("cmd", "specified depfile=true but did not include a reference to '${depfile}' in cmd")
376 return
377 }
378
379 // tell the sbox command which directory to use as its sandbox root
380 buildDir := android.PathForOutput(ctx).String()
381 sandboxPath := shared.TempDirForOutDir(buildDir)
382
383 // recall that Sprintf replaces percent sign expressions, whereas dollar signs expressions remain as written,
384 // to be replaced later by ninja_strings.go
385 depfilePlaceholder := ""
386 if Bool(g.properties.Depfile) {
387 depfilePlaceholder = "$depfileArgs"
388 }
389
390 // Escape the command for the shell
391 rawCommand = "'" + strings.Replace(rawCommand, "'", `'\''`, -1) + "'"
392 g.rawCommands = append(g.rawCommands, rawCommand)
393 sandboxCommand := fmt.Sprintf("rm -rf %s && $sboxCmd --sandbox-path %s --output-root %s -c %s %s $allouts",
394 task.genDir, sandboxPath, task.genDir, rawCommand, depfilePlaceholder)
395
396 ruleParams := blueprint.RuleParams{
397 Command: sandboxCommand,
398 CommandDeps: []string{"$sboxCmd"},
399 }
400 args := []string{"allouts"}
401 if Bool(g.properties.Depfile) {
402 ruleParams.Deps = blueprint.DepsGCC
403 args = append(args, "depfileArgs")
404 }
405 name := "generator"
406 if task.shards > 1 {
407 name += strconv.Itoa(task.shard)
408 }
409 rule := ctx.Rule(pctx, name, ruleParams, args...)
410
411 g.generateSourceFile(ctx, task, rule)
412
413 if len(task.copyTo) > 0 {
414 outputFiles = append(outputFiles, task.copyTo...)
415 copyFrom = append(copyFrom, task.out.Paths()...)
416 zipArgs.WriteString(" -C " + task.genDir.String())
417 zipArgs.WriteString(android.JoinWithPrefix(task.out.Strings(), " -f "))
418 } else {
419 outputFiles = append(outputFiles, task.out...)
420 }
Colin Cross6f080df2016-11-04 15:32:58 -0700421 }
422
Colin Cross1a527682019-09-23 15:55:30 -0700423 if len(copyFrom) > 0 {
424 ctx.Build(pctx, android.BuildParams{
425 Rule: gensrcsMerge,
426 Implicits: copyFrom,
427 Outputs: outputFiles,
428 Args: map[string]string{
429 "zipArgs": zipArgs.String(),
430 "tmpZip": android.PathForModuleGen(ctx, g.subDir+".zip").String(),
431 "genDir": android.PathForModuleGen(ctx, g.subDir).String(),
432 },
433 })
Colin Cross85a2e892018-07-09 09:45:06 -0700434 }
435
Colin Cross1a527682019-09-23 15:55:30 -0700436 g.outputFiles = outputFiles.Paths()
Jeff Gastonefc1b412017-03-29 17:29:06 -0700437
Colin Cross1a527682019-09-23 15:55:30 -0700438 // For <= 6 outputs, just embed those directly in the users. Right now, that covers >90% of
439 // the genrules on AOSP. That will make things simpler to look at the graph in the common
440 // case. For larger sets of outputs, inject a phony target in between to limit ninja file
441 // growth.
442 if len(g.outputFiles) <= 6 {
443 g.outputDeps = g.outputFiles
444 } else {
445 phonyFile := android.PathForModuleGen(ctx, "genrule-phony")
446
447 ctx.Build(pctx, android.BuildParams{
448 Rule: blueprint.Phony,
449 Output: phonyFile,
450 Inputs: g.outputFiles,
451 })
452
453 g.outputDeps = android.Paths{phonyFile}
Jeff Gaston02a684b2017-10-27 14:59:27 -0700454 }
Jeff Gaston5acec2b2017-11-06 14:15:16 -0800455
Colin Crossd350ecd2015-04-28 13:25:36 -0700456}
457
Colin Cross1a527682019-09-23 15:55:30 -0700458func (g *Module) generateSourceFile(ctx android.ModuleContext, task generateTask, rule blueprint.Rule) {
Colin Cross67a5c132017-05-09 13:45:28 -0700459 desc := "generate"
Colin Cross15e86d92017-10-20 15:07:08 -0700460 if len(task.out) == 0 {
461 ctx.ModuleErrorf("must have at least one output file")
462 return
463 }
Colin Cross67a5c132017-05-09 13:45:28 -0700464 if len(task.out) == 1 {
465 desc += " " + task.out[0].Base()
466 }
467
Jeff Gaston02a684b2017-10-27 14:59:27 -0700468 var depFile android.ModuleGenPath
Nan Zhangea568a42017-11-08 21:20:04 -0800469 if Bool(g.properties.Depfile) {
Jeff Gaston02a684b2017-10-27 14:59:27 -0700470 depFile = android.PathForModuleGen(ctx, task.out[0].Rel()+".d")
471 }
472
Colin Cross1a527682019-09-23 15:55:30 -0700473 if task.shards > 1 {
474 desc += " " + strconv.Itoa(task.shard)
475 }
476
Colin Crossae887032017-10-23 17:16:14 -0700477 params := android.BuildParams{
Colin Cross1a527682019-09-23 15:55:30 -0700478 Rule: rule,
479 Description: desc,
Colin Cross15e86d92017-10-20 15:07:08 -0700480 Output: task.out[0],
481 ImplicitOutputs: task.out[1:],
482 Inputs: task.in,
483 Implicits: g.deps,
484 Args: map[string]string{
Colin Crossbaccf5b2018-02-21 14:07:48 -0800485 "allouts": strings.Join(task.sandboxOuts, " "),
Colin Cross15e86d92017-10-20 15:07:08 -0700486 },
Colin Cross33bfb0a2016-11-21 17:23:08 -0800487 }
Nan Zhangea568a42017-11-08 21:20:04 -0800488 if Bool(g.properties.Depfile) {
Jeff Gaston02a684b2017-10-27 14:59:27 -0700489 params.Depfile = android.PathForModuleGen(ctx, task.out[0].Rel()+".d")
490 params.Args["depfileArgs"] = "--depfile-out " + depFile.String()
Colin Cross33bfb0a2016-11-21 17:23:08 -0800491 }
Jeff Gaston02a684b2017-10-27 14:59:27 -0700492
Colin Crossae887032017-10-23 17:16:14 -0700493 ctx.Build(pctx, params)
Colin Crossd350ecd2015-04-28 13:25:36 -0700494}
495
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700496// Collect information for opening IDE project files in java/jdeps.go.
497func (g *Module) IDEInfo(dpInfo *android.IdeInfo) {
498 dpInfo.Srcs = append(dpInfo.Srcs, g.Srcs().Strings()...)
499 for _, src := range g.properties.Srcs {
500 if strings.HasPrefix(src, ":") {
501 src = strings.Trim(src, ":")
502 dpInfo.Deps = append(dpInfo.Deps, src)
503 }
504 }
505}
506
Colin Crossa4ad2b02019-03-18 22:15:32 -0700507func (g *Module) AndroidMk() android.AndroidMkData {
508 return android.AndroidMkData{
509 Include: "$(BUILD_PHONY_PACKAGE)",
510 Class: "FAKE",
511 OutputFile: android.OptionalPathForPath(g.outputFiles[0]),
512 SubName: g.subName,
513 Extra: []android.AndroidMkExtraFunc{
514 func(w io.Writer, outputFile android.Path) {
Colin Cross1a527682019-09-23 15:55:30 -0700515 fmt.Fprintln(w, "LOCAL_ADDITIONAL_DEPENDENCIES :=", strings.Join(g.outputDeps.Strings(), " "))
Colin Crossa4ad2b02019-03-18 22:15:32 -0700516 },
517 },
518 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
519 android.WriteAndroidMkData(w, data)
520 if data.SubName != "" {
521 fmt.Fprintln(w, ".PHONY:", name)
522 fmt.Fprintln(w, name, ":", name+g.subName)
523 }
524 },
525 }
526}
527
Jeff Gaston437d23c2017-11-08 12:38:00 -0800528func generatorFactory(taskGenerator taskFunc, props ...interface{}) *Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700529 module := &Module{
Jeff Gaston437d23c2017-11-08 12:38:00 -0800530 taskGenerator: taskGenerator,
Colin Crossd350ecd2015-04-28 13:25:36 -0700531 }
532
Colin Cross36242852017-06-23 15:06:31 -0700533 module.AddProperties(props...)
534 module.AddProperties(&module.properties)
Colin Crossd350ecd2015-04-28 13:25:36 -0700535
Colin Cross7228ecd2019-11-18 16:00:16 -0800536 module.ImageInterface = noopImageInterface{}
537
Colin Cross36242852017-06-23 15:06:31 -0700538 return module
Colin Crossd350ecd2015-04-28 13:25:36 -0700539}
540
Colin Cross7228ecd2019-11-18 16:00:16 -0800541type noopImageInterface struct{}
542
543func (x noopImageInterface) ImageMutatorBegin(android.BaseModuleContext) {}
544func (x noopImageInterface) CoreVariantNeeded(android.BaseModuleContext) bool { return false }
545func (x noopImageInterface) RecoveryVariantNeeded(android.BaseModuleContext) bool { return false }
546func (x noopImageInterface) ExtraImageVariations(ctx android.BaseModuleContext) []string { return nil }
547func (x noopImageInterface) SetImageVariation(ctx android.BaseModuleContext, variation string, module android.Module) {
548}
549
Colin Crossbaccf5b2018-02-21 14:07:48 -0800550// replace "out" with "__SBOX_OUT_DIR__/<the value of ${out}>"
551func pathToSandboxOut(path android.Path, genDir android.Path) string {
552 relOut, err := filepath.Rel(genDir.String(), path.String())
553 if err != nil {
554 panic(fmt.Sprintf("Could not make ${out} relative: %v", err))
555 }
556 return filepath.Join("__SBOX_OUT_DIR__", relOut)
557
558}
559
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700560func NewGenSrcs() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700561 properties := &genSrcsProperties{}
562
Colin Cross1a527682019-09-23 15:55:30 -0700563 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
564 genDir := android.PathForModuleGen(ctx, "gensrcs")
565 shardSize := defaultShardSize
566 if s := properties.Shard_size; s != nil {
567 shardSize = int(*s)
568 }
Jeff Gaston437d23c2017-11-08 12:38:00 -0800569
Colin Cross1a527682019-09-23 15:55:30 -0700570 shards := android.ShardPaths(srcFiles, shardSize)
571 var generateTasks []generateTask
Colin Crossbaccf5b2018-02-21 14:07:48 -0800572
Colin Cross1a527682019-09-23 15:55:30 -0700573 for i, shard := range shards {
574 var commands []string
575 var outFiles android.WritablePaths
576 var copyTo android.WritablePaths
577 var shardDir android.WritablePath
578 var sandboxOuts []string
579
580 if len(shards) > 1 {
581 shardDir = android.PathForModuleGen(ctx, strconv.Itoa(i))
582 } else {
583 shardDir = genDir
Jeff Gaston437d23c2017-11-08 12:38:00 -0800584 }
585
Colin Cross1a527682019-09-23 15:55:30 -0700586 for _, in := range shard {
587 outFile := android.GenPathWithExt(ctx, "gensrcs", in, String(properties.Output_extension))
588 sandboxOutfile := pathToSandboxOut(outFile, genDir)
Jeff Gaston437d23c2017-11-08 12:38:00 -0800589
Colin Cross1a527682019-09-23 15:55:30 -0700590 if len(shards) > 1 {
591 shardFile := android.GenPathWithExt(ctx, strconv.Itoa(i), in, String(properties.Output_extension))
592 copyTo = append(copyTo, outFile)
593 outFile = shardFile
594 }
595
596 outFiles = append(outFiles, outFile)
597 sandboxOuts = append(sandboxOuts, sandboxOutfile)
598
599 command, err := android.Expand(rawCommand, func(name string) (string, error) {
600 switch name {
601 case "in":
602 return in.String(), nil
603 case "out":
604 return sandboxOutfile, nil
605 default:
606 return "$(" + name + ")", nil
607 }
608 })
609 if err != nil {
610 ctx.PropertyErrorf("cmd", err.Error())
611 }
612
613 // escape the command in case for example it contains '#', an odd number of '"', etc
614 command = fmt.Sprintf("bash -c %v", proptools.ShellEscape(command))
615 commands = append(commands, command)
616 }
617 fullCommand := strings.Join(commands, " && ")
618
619 generateTasks = append(generateTasks, generateTask{
620 in: shard,
621 out: outFiles,
622 copyTo: copyTo,
623 genDir: shardDir,
624 sandboxOuts: sandboxOuts,
625 cmd: fullCommand,
626 shard: i,
627 shards: len(shards),
628 })
Jeff Gaston437d23c2017-11-08 12:38:00 -0800629 }
Colin Cross1a527682019-09-23 15:55:30 -0700630
631 return generateTasks
Colin Crossd350ecd2015-04-28 13:25:36 -0700632 }
633
Colin Cross1a527682019-09-23 15:55:30 -0700634 g := generatorFactory(taskGenerator, properties)
635 g.subDir = "gensrcs"
636 return g
Colin Crossd350ecd2015-04-28 13:25:36 -0700637}
638
Colin Cross54190b32017-10-09 15:34:10 -0700639func GenSrcsFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700640 m := NewGenSrcs()
641 android.InitAndroidModule(m)
642 return m
643}
644
Colin Crossd350ecd2015-04-28 13:25:36 -0700645type genSrcsProperties struct {
Colin Cross7d5136f2015-05-11 13:39:40 -0700646 // extension that will be substituted for each output file
Nan Zhanga5e7cb42017-11-09 22:42:32 -0800647 Output_extension *string
Colin Cross1a527682019-09-23 15:55:30 -0700648
649 // maximum number of files that will be passed on a single command line.
650 Shard_size *int64
Colin Cross5049f022015-03-18 13:28:46 -0700651}
652
Colin Cross1a527682019-09-23 15:55:30 -0700653const defaultShardSize = 100
654
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700655func NewGenRule() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700656 properties := &genRuleProperties{}
Colin Cross5049f022015-03-18 13:28:46 -0700657
Colin Cross1a527682019-09-23 15:55:30 -0700658 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700659 outs := make(android.WritablePaths, len(properties.Out))
Colin Crossbaccf5b2018-02-21 14:07:48 -0800660 sandboxOuts := make([]string, len(properties.Out))
661 genDir := android.PathForModuleGen(ctx)
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700662 for i, out := range properties.Out {
663 outs[i] = android.PathForModuleGen(ctx, out)
Colin Crossbaccf5b2018-02-21 14:07:48 -0800664 sandboxOuts[i] = pathToSandboxOut(outs[i], genDir)
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700665 }
Colin Cross1a527682019-09-23 15:55:30 -0700666 return []generateTask{{
Colin Crossbaccf5b2018-02-21 14:07:48 -0800667 in: srcFiles,
668 out: outs,
Colin Cross1a527682019-09-23 15:55:30 -0700669 genDir: android.PathForModuleGen(ctx),
Colin Crossbaccf5b2018-02-21 14:07:48 -0800670 sandboxOuts: sandboxOuts,
671 cmd: rawCommand,
Colin Cross1a527682019-09-23 15:55:30 -0700672 }}
Colin Cross5049f022015-03-18 13:28:46 -0700673 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700674
Jeff Gaston437d23c2017-11-08 12:38:00 -0800675 return generatorFactory(taskGenerator, properties)
Colin Cross5049f022015-03-18 13:28:46 -0700676}
677
Colin Cross54190b32017-10-09 15:34:10 -0700678func GenRuleFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700679 m := NewGenRule()
680 android.InitAndroidModule(m)
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800681 android.InitDefaultableModule(m)
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700682 return m
683}
684
Colin Crossd350ecd2015-04-28 13:25:36 -0700685type genRuleProperties struct {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700686 // names of the output files that will be generated
Colin Crossef354482018-10-23 11:27:50 -0700687 Out []string `android:"arch_variant"`
Colin Cross5049f022015-03-18 13:28:46 -0700688}
Nan Zhangea568a42017-11-08 21:20:04 -0800689
690var Bool = proptools.Bool
691var String = proptools.String
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800692
693//
694// Defaults
695//
696type Defaults struct {
697 android.ModuleBase
698 android.DefaultsModuleBase
699}
700
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800701func defaultsFactory() android.Module {
702 return DefaultsFactory()
703}
704
705func DefaultsFactory(props ...interface{}) android.Module {
706 module := &Defaults{}
707
708 module.AddProperties(props...)
709 module.AddProperties(
710 &generatorProperties{},
711 &genRuleProperties{},
712 )
713
714 android.InitDefaultsModule(module)
715
716 return module
717}