blob: c21df4c5a54ff59e55eb84dfff591840f5bc36fa [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{}
121
Colin Cross7d5136f2015-05-11 13:39:40 -0700122 properties generatorProperties
Colin Crossd350ecd2015-04-28 13:25:36 -0700123
Jeff Gaston437d23c2017-11-08 12:38:00 -0800124 taskGenerator taskFunc
Colin Crossd350ecd2015-04-28 13:25:36 -0700125
Colin Cross1a527682019-09-23 15:55:30 -0700126 deps android.Paths
127 rule blueprint.Rule
128 rawCommands []string
Colin Crossd350ecd2015-04-28 13:25:36 -0700129
Colin Cross5ed99c62016-11-22 12:55:55 -0800130 exportedIncludeDirs android.Paths
Dan Willemsenb40aab62016-04-20 14:21:14 -0700131
Colin Cross635c3b02016-05-18 15:37:25 -0700132 outputFiles android.Paths
Dan Willemsen9da9d492018-02-21 18:28:18 -0800133 outputDeps android.Paths
Colin Crossa4ad2b02019-03-18 22:15:32 -0700134
135 subName string
Colin Cross1a527682019-09-23 15:55:30 -0700136 subDir string
Colin Crossd350ecd2015-04-28 13:25:36 -0700137}
138
Colin Cross1a527682019-09-23 15:55:30 -0700139type taskFunc func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask
Colin Crossd350ecd2015-04-28 13:25:36 -0700140
141type generateTask struct {
Colin Crossbaccf5b2018-02-21 14:07:48 -0800142 in android.Paths
143 out android.WritablePaths
Colin Cross1a527682019-09-23 15:55:30 -0700144 copyTo android.WritablePaths
145 genDir android.WritablePath
Colin Crossbaccf5b2018-02-21 14:07:48 -0800146 sandboxOuts []string
147 cmd string
Colin Cross1a527682019-09-23 15:55:30 -0700148 shard int
149 shards int
Colin Crossd350ecd2015-04-28 13:25:36 -0700150}
151
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700152func (g *Module) GeneratedSourceFiles() android.Paths {
Colin Crossd350ecd2015-04-28 13:25:36 -0700153 return g.outputFiles
154}
155
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700156func (g *Module) Srcs() android.Paths {
Nan Zhange42777a2018-03-27 16:19:42 -0700157 return append(android.Paths{}, g.outputFiles...)
Colin Cross068e0fe2016-12-13 15:23:47 -0800158}
159
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700160func (g *Module) GeneratedHeaderDirs() android.Paths {
Colin Cross5ed99c62016-11-22 12:55:55 -0800161 return g.exportedIncludeDirs
Dan Willemsenb40aab62016-04-20 14:21:14 -0700162}
163
Dan Willemsen9da9d492018-02-21 18:28:18 -0800164func (g *Module) GeneratedDeps() android.Paths {
165 return g.outputDeps
166}
167
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700168func (g *Module) DepsMutator(ctx android.BottomUpMutatorContext) {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700169 if g, ok := ctx.Module().(*Module); ok {
Colin Cross08f15ab2018-10-04 23:29:14 -0700170 for _, tool := range g.properties.Tools {
171 tag := hostToolDependencyTag{label: tool}
172 if m := android.SrcIsModule(tool); m != "" {
173 tool = m
174 }
Dan Willemsen490fd492015-11-24 17:53:15 -0800175 ctx.AddFarVariationDependencies([]blueprint.Variation{
Dan Willemsen59339a22018-07-22 21:18:45 -0700176 {Mutator: "arch", Variation: ctx.Config().BuildOsVariant},
Colin Cross08f15ab2018-10-04 23:29:14 -0700177 }, tag, tool)
Colin Cross6362e272015-10-29 15:25:03 -0700178 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700179 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700180}
181
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700182func (g *Module) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Colin Crossa4ad2b02019-03-18 22:15:32 -0700183 g.subName = ctx.ModuleSubDir()
184
Colin Cross5ed99c62016-11-22 12:55:55 -0800185 if len(g.properties.Export_include_dirs) > 0 {
186 for _, dir := range g.properties.Export_include_dirs {
187 g.exportedIncludeDirs = append(g.exportedIncludeDirs,
Colin Cross1a527682019-09-23 15:55:30 -0700188 android.PathForModuleGen(ctx, g.subDir, ctx.ModuleDir(), dir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800189 }
190 } else {
Colin Cross1a527682019-09-23 15:55:30 -0700191 g.exportedIncludeDirs = append(g.exportedIncludeDirs, android.PathForModuleGen(ctx, g.subDir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800192 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700193
Colin Cross08f15ab2018-10-04 23:29:14 -0700194 locationLabels := map[string][]string{}
195 firstLabel := ""
196
197 addLocationLabel := func(label string, paths []string) {
198 if firstLabel == "" {
199 firstLabel = label
200 }
201 if _, exists := locationLabels[label]; !exists {
202 locationLabels[label] = paths
203 } else {
204 ctx.ModuleErrorf("multiple labels for %q, %q and %q",
205 label, strings.Join(locationLabels[label], " "), strings.Join(paths, " "))
206 }
207 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700208
Colin Cross6f080df2016-11-04 15:32:58 -0700209 if len(g.properties.Tools) > 0 {
Colin Crossba71a3f2019-03-18 12:12:48 -0700210 seenTools := make(map[string]bool)
211
Colin Cross35143d02017-11-16 00:11:20 -0800212 ctx.VisitDirectDepsBlueprint(func(module blueprint.Module) {
Colin Cross08f15ab2018-10-04 23:29:14 -0700213 switch tag := ctx.OtherModuleDependencyTag(module).(type) {
214 case hostToolDependencyTag:
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700215 tool := ctx.OtherModuleName(module)
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700216 var path android.OptionalPath
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700217
Colin Crossfe17f6f2019-03-28 19:30:56 -0700218 if t, ok := module.(android.HostToolProvider); ok {
Colin Cross35143d02017-11-16 00:11:20 -0800219 if !t.(android.Module).Enabled() {
Colin Cross6510f912017-11-29 00:27:14 -0800220 if ctx.Config().AllowMissingDependencies() {
Colin Cross35143d02017-11-16 00:11:20 -0800221 ctx.AddMissingDependencies([]string{tool})
222 } else {
223 ctx.ModuleErrorf("depends on disabled module %q", tool)
224 }
225 break
226 }
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700227 path = t.HostToolPath()
228 } else if t, ok := module.(bootstrap.GoBinaryTool); ok {
229 if s, err := filepath.Rel(android.PathForOutput(ctx).String(), t.InstallPath()); err == nil {
230 path = android.OptionalPathForPath(android.PathForOutput(ctx, s))
Colin Cross6f080df2016-11-04 15:32:58 -0700231 } else {
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700232 ctx.ModuleErrorf("cannot find path for %q: %v", tool, err)
233 break
Colin Cross6f080df2016-11-04 15:32:58 -0700234 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700235 } else {
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700236 ctx.ModuleErrorf("%q is not a host tool provider", tool)
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700237 break
238 }
239
240 if path.Valid() {
241 g.deps = append(g.deps, path.Path())
Colin Cross08f15ab2018-10-04 23:29:14 -0700242 addLocationLabel(tag.label, []string{path.Path().String()})
Colin Crossba71a3f2019-03-18 12:12:48 -0700243 seenTools[tag.label] = true
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700244 } else {
245 ctx.ModuleErrorf("host tool %q missing output file", tool)
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700246 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700247 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700248 })
Colin Crossba71a3f2019-03-18 12:12:48 -0700249
250 // If AllowMissingDependencies is enabled, the build will not have stopped when
251 // AddFarVariationDependencies was called on a missing tool, which will result in nonsensical
252 // "cmd: unknown location label ..." errors later. Add a dummy file to the local label. The
253 // command that uses this dummy file will never be executed because the rule will be replaced with
254 // an android.Error rule reporting the missing dependencies.
255 if ctx.Config().AllowMissingDependencies() {
256 for _, tool := range g.properties.Tools {
257 if !seenTools[tool] {
258 addLocationLabel(tool, []string{"***missing tool " + tool + "***"})
259 }
260 }
261 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700262 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700263
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700264 if ctx.Failed() {
265 return
266 }
267
Colin Cross08f15ab2018-10-04 23:29:14 -0700268 for _, toolFile := range g.properties.Tool_files {
Colin Cross8a497952019-03-05 22:25:09 -0800269 paths := android.PathsForModuleSrc(ctx, []string{toolFile})
Colin Cross08f15ab2018-10-04 23:29:14 -0700270 g.deps = append(g.deps, paths...)
271 addLocationLabel(toolFile, paths.Strings())
272 }
273
274 var srcFiles android.Paths
275 for _, in := range g.properties.Srcs {
Colin Crossba71a3f2019-03-18 12:12:48 -0700276 paths, missingDeps := android.PathsAndMissingDepsForModuleSrcExcludes(ctx, []string{in}, g.properties.Exclude_srcs)
277 if len(missingDeps) > 0 {
278 if !ctx.Config().AllowMissingDependencies() {
279 panic(fmt.Errorf("should never get here, the missing dependencies %q should have been reported in DepsMutator",
280 missingDeps))
281 }
282
283 // If AllowMissingDependencies is enabled, the build will not have stopped when
284 // the dependency was added on a missing SourceFileProducer module, which will result in nonsensical
285 // "cmd: label ":..." has no files" errors later. Add a dummy file to the local label. The
286 // command that uses this dummy file will never be executed because the rule will be replaced with
287 // an android.Error rule reporting the missing dependencies.
288 ctx.AddMissingDependencies(missingDeps)
289 addLocationLabel(in, []string{"***missing srcs " + in + "***"})
290 } else {
291 srcFiles = append(srcFiles, paths...)
292 addLocationLabel(in, paths.Strings())
293 }
Colin Cross08f15ab2018-10-04 23:29:14 -0700294 }
295
Colin Cross1a527682019-09-23 15:55:30 -0700296 var copyFrom android.Paths
297 var outputFiles android.WritablePaths
298 var zipArgs strings.Builder
Colin Cross08f15ab2018-10-04 23:29:14 -0700299
Colin Cross1a527682019-09-23 15:55:30 -0700300 for _, task := range g.taskGenerator(ctx, String(g.properties.Cmd), srcFiles) {
301 for _, out := range task.out {
302 addLocationLabel(out.Rel(), []string{filepath.Join("__SBOX_OUT_DIR__", out.Rel())})
Colin Cross85a2e892018-07-09 09:45:06 -0700303 }
304
Colin Cross1a527682019-09-23 15:55:30 -0700305 referencedDepfile := false
306
307 rawCommand, err := android.ExpandNinjaEscaped(task.cmd, func(name string) (string, bool, error) {
308 // report the error directly without returning an error to android.Expand to catch multiple errors in a
309 // single run
310 reportError := func(fmt string, args ...interface{}) (string, bool, error) {
311 ctx.PropertyErrorf("cmd", fmt, args...)
312 return "SOONG_ERROR", false, nil
Colin Cross6f080df2016-11-04 15:32:58 -0700313 }
Colin Cross1a527682019-09-23 15:55:30 -0700314
315 switch name {
316 case "location":
317 if len(g.properties.Tools) == 0 && len(g.properties.Tool_files) == 0 {
318 return reportError("at least one `tools` or `tool_files` is required if $(location) is used")
Colin Cross6f080df2016-11-04 15:32:58 -0700319 }
Colin Cross1a527682019-09-23 15:55:30 -0700320 paths := locationLabels[firstLabel]
321 if len(paths) == 0 {
322 return reportError("default label %q has no files", firstLabel)
323 } else if len(paths) > 1 {
324 return reportError("default label %q has multiple files, use $(locations %s) to reference it",
325 firstLabel, firstLabel)
Colin Cross08f15ab2018-10-04 23:29:14 -0700326 }
Colin Cross1a527682019-09-23 15:55:30 -0700327 return locationLabels[firstLabel][0], false, nil
328 case "in":
329 return "${in}", true, nil
330 case "out":
331 return "__SBOX_OUT_FILES__", false, nil
332 case "depfile":
333 referencedDepfile = true
334 if !Bool(g.properties.Depfile) {
335 return reportError("$(depfile) used without depfile property")
336 }
337 return "__SBOX_DEPFILE__", false, nil
338 case "genDir":
339 return "__SBOX_OUT_DIR__", false, nil
340 default:
341 if strings.HasPrefix(name, "location ") {
342 label := strings.TrimSpace(strings.TrimPrefix(name, "location "))
343 if paths, ok := locationLabels[label]; ok {
344 if len(paths) == 0 {
345 return reportError("label %q has no files", label)
346 } else if len(paths) > 1 {
347 return reportError("label %q has multiple files, use $(locations %s) to reference it",
348 label, label)
349 }
350 return paths[0], false, nil
351 } else {
352 return reportError("unknown location label %q", label)
353 }
354 } else if strings.HasPrefix(name, "locations ") {
355 label := strings.TrimSpace(strings.TrimPrefix(name, "locations "))
356 if paths, ok := locationLabels[label]; ok {
357 if len(paths) == 0 {
358 return reportError("label %q has no files", label)
359 }
360 return strings.Join(paths, " "), false, nil
361 } else {
362 return reportError("unknown locations label %q", label)
363 }
364 } else {
365 return reportError("unknown variable '$(%s)'", name)
366 }
Colin Cross6f080df2016-11-04 15:32:58 -0700367 }
Colin Cross1a527682019-09-23 15:55:30 -0700368 })
369
370 if err != nil {
371 ctx.PropertyErrorf("cmd", "%s", err.Error())
372 return
Colin Cross6f080df2016-11-04 15:32:58 -0700373 }
Colin Cross6f080df2016-11-04 15:32:58 -0700374
Colin Cross1a527682019-09-23 15:55:30 -0700375 if Bool(g.properties.Depfile) && !referencedDepfile {
376 ctx.PropertyErrorf("cmd", "specified depfile=true but did not include a reference to '${depfile}' in cmd")
377 return
378 }
379
380 // tell the sbox command which directory to use as its sandbox root
381 buildDir := android.PathForOutput(ctx).String()
382 sandboxPath := shared.TempDirForOutDir(buildDir)
383
384 // recall that Sprintf replaces percent sign expressions, whereas dollar signs expressions remain as written,
385 // to be replaced later by ninja_strings.go
386 depfilePlaceholder := ""
387 if Bool(g.properties.Depfile) {
388 depfilePlaceholder = "$depfileArgs"
389 }
390
391 // Escape the command for the shell
392 rawCommand = "'" + strings.Replace(rawCommand, "'", `'\''`, -1) + "'"
393 g.rawCommands = append(g.rawCommands, rawCommand)
394 sandboxCommand := fmt.Sprintf("rm -rf %s && $sboxCmd --sandbox-path %s --output-root %s -c %s %s $allouts",
395 task.genDir, sandboxPath, task.genDir, rawCommand, depfilePlaceholder)
396
397 ruleParams := blueprint.RuleParams{
398 Command: sandboxCommand,
399 CommandDeps: []string{"$sboxCmd"},
400 }
401 args := []string{"allouts"}
402 if Bool(g.properties.Depfile) {
403 ruleParams.Deps = blueprint.DepsGCC
404 args = append(args, "depfileArgs")
405 }
406 name := "generator"
407 if task.shards > 1 {
408 name += strconv.Itoa(task.shard)
409 }
410 rule := ctx.Rule(pctx, name, ruleParams, args...)
411
412 g.generateSourceFile(ctx, task, rule)
413
414 if len(task.copyTo) > 0 {
415 outputFiles = append(outputFiles, task.copyTo...)
416 copyFrom = append(copyFrom, task.out.Paths()...)
417 zipArgs.WriteString(" -C " + task.genDir.String())
418 zipArgs.WriteString(android.JoinWithPrefix(task.out.Strings(), " -f "))
419 } else {
420 outputFiles = append(outputFiles, task.out...)
421 }
Colin Cross6f080df2016-11-04 15:32:58 -0700422 }
423
Colin Cross1a527682019-09-23 15:55:30 -0700424 if len(copyFrom) > 0 {
425 ctx.Build(pctx, android.BuildParams{
426 Rule: gensrcsMerge,
427 Implicits: copyFrom,
428 Outputs: outputFiles,
429 Args: map[string]string{
430 "zipArgs": zipArgs.String(),
431 "tmpZip": android.PathForModuleGen(ctx, g.subDir+".zip").String(),
432 "genDir": android.PathForModuleGen(ctx, g.subDir).String(),
433 },
434 })
Colin Cross85a2e892018-07-09 09:45:06 -0700435 }
436
Colin Cross1a527682019-09-23 15:55:30 -0700437 g.outputFiles = outputFiles.Paths()
Jeff Gastonefc1b412017-03-29 17:29:06 -0700438
Colin Cross1a527682019-09-23 15:55:30 -0700439 // For <= 6 outputs, just embed those directly in the users. Right now, that covers >90% of
440 // the genrules on AOSP. That will make things simpler to look at the graph in the common
441 // case. For larger sets of outputs, inject a phony target in between to limit ninja file
442 // growth.
443 if len(g.outputFiles) <= 6 {
444 g.outputDeps = g.outputFiles
445 } else {
446 phonyFile := android.PathForModuleGen(ctx, "genrule-phony")
447
448 ctx.Build(pctx, android.BuildParams{
449 Rule: blueprint.Phony,
450 Output: phonyFile,
451 Inputs: g.outputFiles,
452 })
453
454 g.outputDeps = android.Paths{phonyFile}
Jeff Gaston02a684b2017-10-27 14:59:27 -0700455 }
Jeff Gaston5acec2b2017-11-06 14:15:16 -0800456
Colin Crossd350ecd2015-04-28 13:25:36 -0700457}
458
Colin Cross1a527682019-09-23 15:55:30 -0700459func (g *Module) generateSourceFile(ctx android.ModuleContext, task generateTask, rule blueprint.Rule) {
Colin Cross67a5c132017-05-09 13:45:28 -0700460 desc := "generate"
Colin Cross15e86d92017-10-20 15:07:08 -0700461 if len(task.out) == 0 {
462 ctx.ModuleErrorf("must have at least one output file")
463 return
464 }
Colin Cross67a5c132017-05-09 13:45:28 -0700465 if len(task.out) == 1 {
466 desc += " " + task.out[0].Base()
467 }
468
Jeff Gaston02a684b2017-10-27 14:59:27 -0700469 var depFile android.ModuleGenPath
Nan Zhangea568a42017-11-08 21:20:04 -0800470 if Bool(g.properties.Depfile) {
Jeff Gaston02a684b2017-10-27 14:59:27 -0700471 depFile = android.PathForModuleGen(ctx, task.out[0].Rel()+".d")
472 }
473
Colin Cross1a527682019-09-23 15:55:30 -0700474 if task.shards > 1 {
475 desc += " " + strconv.Itoa(task.shard)
476 }
477
Colin Crossae887032017-10-23 17:16:14 -0700478 params := android.BuildParams{
Colin Cross1a527682019-09-23 15:55:30 -0700479 Rule: rule,
480 Description: desc,
Colin Cross15e86d92017-10-20 15:07:08 -0700481 Output: task.out[0],
482 ImplicitOutputs: task.out[1:],
483 Inputs: task.in,
484 Implicits: g.deps,
485 Args: map[string]string{
Colin Crossbaccf5b2018-02-21 14:07:48 -0800486 "allouts": strings.Join(task.sandboxOuts, " "),
Colin Cross15e86d92017-10-20 15:07:08 -0700487 },
Colin Cross33bfb0a2016-11-21 17:23:08 -0800488 }
Nan Zhangea568a42017-11-08 21:20:04 -0800489 if Bool(g.properties.Depfile) {
Jeff Gaston02a684b2017-10-27 14:59:27 -0700490 params.Depfile = android.PathForModuleGen(ctx, task.out[0].Rel()+".d")
491 params.Args["depfileArgs"] = "--depfile-out " + depFile.String()
Colin Cross33bfb0a2016-11-21 17:23:08 -0800492 }
Jeff Gaston02a684b2017-10-27 14:59:27 -0700493
Colin Crossae887032017-10-23 17:16:14 -0700494 ctx.Build(pctx, params)
Colin Crossd350ecd2015-04-28 13:25:36 -0700495}
496
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700497// Collect information for opening IDE project files in java/jdeps.go.
498func (g *Module) IDEInfo(dpInfo *android.IdeInfo) {
499 dpInfo.Srcs = append(dpInfo.Srcs, g.Srcs().Strings()...)
500 for _, src := range g.properties.Srcs {
501 if strings.HasPrefix(src, ":") {
502 src = strings.Trim(src, ":")
503 dpInfo.Deps = append(dpInfo.Deps, src)
504 }
505 }
506}
507
Colin Crossa4ad2b02019-03-18 22:15:32 -0700508func (g *Module) AndroidMk() android.AndroidMkData {
509 return android.AndroidMkData{
510 Include: "$(BUILD_PHONY_PACKAGE)",
511 Class: "FAKE",
512 OutputFile: android.OptionalPathForPath(g.outputFiles[0]),
513 SubName: g.subName,
514 Extra: []android.AndroidMkExtraFunc{
515 func(w io.Writer, outputFile android.Path) {
Colin Cross1a527682019-09-23 15:55:30 -0700516 fmt.Fprintln(w, "LOCAL_ADDITIONAL_DEPENDENCIES :=", strings.Join(g.outputDeps.Strings(), " "))
Colin Crossa4ad2b02019-03-18 22:15:32 -0700517 },
518 },
519 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
520 android.WriteAndroidMkData(w, data)
521 if data.SubName != "" {
522 fmt.Fprintln(w, ".PHONY:", name)
523 fmt.Fprintln(w, name, ":", name+g.subName)
524 }
525 },
526 }
527}
528
Jeff Gaston437d23c2017-11-08 12:38:00 -0800529func generatorFactory(taskGenerator taskFunc, props ...interface{}) *Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700530 module := &Module{
Jeff Gaston437d23c2017-11-08 12:38:00 -0800531 taskGenerator: taskGenerator,
Colin Crossd350ecd2015-04-28 13:25:36 -0700532 }
533
Colin Cross36242852017-06-23 15:06:31 -0700534 module.AddProperties(props...)
535 module.AddProperties(&module.properties)
Colin Crossd350ecd2015-04-28 13:25:36 -0700536
Colin Cross36242852017-06-23 15:06:31 -0700537 return module
Colin Crossd350ecd2015-04-28 13:25:36 -0700538}
539
Colin Crossbaccf5b2018-02-21 14:07:48 -0800540// replace "out" with "__SBOX_OUT_DIR__/<the value of ${out}>"
541func pathToSandboxOut(path android.Path, genDir android.Path) string {
542 relOut, err := filepath.Rel(genDir.String(), path.String())
543 if err != nil {
544 panic(fmt.Sprintf("Could not make ${out} relative: %v", err))
545 }
546 return filepath.Join("__SBOX_OUT_DIR__", relOut)
547
548}
549
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700550func NewGenSrcs() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700551 properties := &genSrcsProperties{}
552
Colin Cross1a527682019-09-23 15:55:30 -0700553 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
554 genDir := android.PathForModuleGen(ctx, "gensrcs")
555 shardSize := defaultShardSize
556 if s := properties.Shard_size; s != nil {
557 shardSize = int(*s)
558 }
Jeff Gaston437d23c2017-11-08 12:38:00 -0800559
Colin Cross1a527682019-09-23 15:55:30 -0700560 shards := android.ShardPaths(srcFiles, shardSize)
561 var generateTasks []generateTask
Colin Crossbaccf5b2018-02-21 14:07:48 -0800562
Colin Cross1a527682019-09-23 15:55:30 -0700563 for i, shard := range shards {
564 var commands []string
565 var outFiles android.WritablePaths
566 var copyTo android.WritablePaths
567 var shardDir android.WritablePath
568 var sandboxOuts []string
569
570 if len(shards) > 1 {
571 shardDir = android.PathForModuleGen(ctx, strconv.Itoa(i))
572 } else {
573 shardDir = genDir
Jeff Gaston437d23c2017-11-08 12:38:00 -0800574 }
575
Colin Cross1a527682019-09-23 15:55:30 -0700576 for _, in := range shard {
577 outFile := android.GenPathWithExt(ctx, "gensrcs", in, String(properties.Output_extension))
578 sandboxOutfile := pathToSandboxOut(outFile, genDir)
Jeff Gaston437d23c2017-11-08 12:38:00 -0800579
Colin Cross1a527682019-09-23 15:55:30 -0700580 if len(shards) > 1 {
581 shardFile := android.GenPathWithExt(ctx, strconv.Itoa(i), in, String(properties.Output_extension))
582 copyTo = append(copyTo, outFile)
583 outFile = shardFile
584 }
585
586 outFiles = append(outFiles, outFile)
587 sandboxOuts = append(sandboxOuts, sandboxOutfile)
588
589 command, err := android.Expand(rawCommand, func(name string) (string, error) {
590 switch name {
591 case "in":
592 return in.String(), nil
593 case "out":
594 return sandboxOutfile, nil
595 default:
596 return "$(" + name + ")", nil
597 }
598 })
599 if err != nil {
600 ctx.PropertyErrorf("cmd", err.Error())
601 }
602
603 // escape the command in case for example it contains '#', an odd number of '"', etc
604 command = fmt.Sprintf("bash -c %v", proptools.ShellEscape(command))
605 commands = append(commands, command)
606 }
607 fullCommand := strings.Join(commands, " && ")
608
609 generateTasks = append(generateTasks, generateTask{
610 in: shard,
611 out: outFiles,
612 copyTo: copyTo,
613 genDir: shardDir,
614 sandboxOuts: sandboxOuts,
615 cmd: fullCommand,
616 shard: i,
617 shards: len(shards),
618 })
Jeff Gaston437d23c2017-11-08 12:38:00 -0800619 }
Colin Cross1a527682019-09-23 15:55:30 -0700620
621 return generateTasks
Colin Crossd350ecd2015-04-28 13:25:36 -0700622 }
623
Colin Cross1a527682019-09-23 15:55:30 -0700624 g := generatorFactory(taskGenerator, properties)
625 g.subDir = "gensrcs"
626 return g
Colin Crossd350ecd2015-04-28 13:25:36 -0700627}
628
Colin Cross54190b32017-10-09 15:34:10 -0700629func GenSrcsFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700630 m := NewGenSrcs()
631 android.InitAndroidModule(m)
632 return m
633}
634
Colin Crossd350ecd2015-04-28 13:25:36 -0700635type genSrcsProperties struct {
Colin Cross7d5136f2015-05-11 13:39:40 -0700636 // extension that will be substituted for each output file
Nan Zhanga5e7cb42017-11-09 22:42:32 -0800637 Output_extension *string
Colin Cross1a527682019-09-23 15:55:30 -0700638
639 // maximum number of files that will be passed on a single command line.
640 Shard_size *int64
Colin Cross5049f022015-03-18 13:28:46 -0700641}
642
Colin Cross1a527682019-09-23 15:55:30 -0700643const defaultShardSize = 100
644
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700645func NewGenRule() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700646 properties := &genRuleProperties{}
Colin Cross5049f022015-03-18 13:28:46 -0700647
Colin Cross1a527682019-09-23 15:55:30 -0700648 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700649 outs := make(android.WritablePaths, len(properties.Out))
Colin Crossbaccf5b2018-02-21 14:07:48 -0800650 sandboxOuts := make([]string, len(properties.Out))
651 genDir := android.PathForModuleGen(ctx)
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700652 for i, out := range properties.Out {
653 outs[i] = android.PathForModuleGen(ctx, out)
Colin Crossbaccf5b2018-02-21 14:07:48 -0800654 sandboxOuts[i] = pathToSandboxOut(outs[i], genDir)
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700655 }
Colin Cross1a527682019-09-23 15:55:30 -0700656 return []generateTask{{
Colin Crossbaccf5b2018-02-21 14:07:48 -0800657 in: srcFiles,
658 out: outs,
Colin Cross1a527682019-09-23 15:55:30 -0700659 genDir: android.PathForModuleGen(ctx),
Colin Crossbaccf5b2018-02-21 14:07:48 -0800660 sandboxOuts: sandboxOuts,
661 cmd: rawCommand,
Colin Cross1a527682019-09-23 15:55:30 -0700662 }}
Colin Cross5049f022015-03-18 13:28:46 -0700663 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700664
Jeff Gaston437d23c2017-11-08 12:38:00 -0800665 return generatorFactory(taskGenerator, properties)
Colin Cross5049f022015-03-18 13:28:46 -0700666}
667
Colin Cross54190b32017-10-09 15:34:10 -0700668func GenRuleFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700669 m := NewGenRule()
670 android.InitAndroidModule(m)
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800671 android.InitDefaultableModule(m)
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700672 return m
673}
674
Colin Crossd350ecd2015-04-28 13:25:36 -0700675type genRuleProperties struct {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700676 // names of the output files that will be generated
Colin Crossef354482018-10-23 11:27:50 -0700677 Out []string `android:"arch_variant"`
Colin Cross5049f022015-03-18 13:28:46 -0700678}
Nan Zhangea568a42017-11-08 21:20:04 -0800679
680var Bool = proptools.Bool
681var String = proptools.String
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800682
683//
684// Defaults
685//
686type Defaults struct {
687 android.ModuleBase
688 android.DefaultsModuleBase
689}
690
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800691func defaultsFactory() android.Module {
692 return DefaultsFactory()
693}
694
695func DefaultsFactory(props ...interface{}) android.Module {
696 module := &Defaults{}
697
698 module.AddProperties(props...)
699 module.AddProperties(
700 &generatorProperties{},
701 &genRuleProperties{},
702 )
703
704 android.InitDefaultsModule(module)
705
706 return module
707}