blob: fe877fe8df2a5befdc125ab2a58bc32a7db279ce [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"
Bill Peckhamc087be12020-02-13 15:55:10 -080029 "crypto/sha256"
Jeff Gastonefc1b412017-03-29 17:29:06 -070030 "path/filepath"
Colin Cross5049f022015-03-18 13:28:46 -070031)
32
Colin Cross463a90e2015-06-17 14:20:06 -070033func init() {
Martin Stjernholm710ec3a2020-01-16 15:12:04 +000034 registerGenruleBuildComponents(android.InitRegistrationContext)
35}
Jaewoong Jung98716bd2018-12-10 08:13:18 -080036
Martin Stjernholm710ec3a2020-01-16 15:12:04 +000037func registerGenruleBuildComponents(ctx android.RegistrationContext) {
38 ctx.RegisterModuleType("genrule_defaults", defaultsFactory)
39
40 ctx.RegisterModuleType("gensrcs", GenSrcsFactory)
41 ctx.RegisterModuleType("genrule", GenRuleFactory)
42
43 ctx.FinalDepsMutators(func(ctx android.RegisterMutatorsContext) {
44 ctx.BottomUp("genrule_tool_deps", toolDepsMutator).Parallel()
45 })
Colin Cross463a90e2015-06-17 14:20:06 -070046}
47
Colin Cross5049f022015-03-18 13:28:46 -070048var (
Colin Cross635c3b02016-05-18 15:37:25 -070049 pctx = android.NewPackageContext("android/soong/genrule")
Colin Cross1a527682019-09-23 15:55:30 -070050
51 gensrcsMerge = pctx.AndroidStaticRule("gensrcsMerge", blueprint.RuleParams{
52 Command: "${soongZip} -o ${tmpZip} @${tmpZip}.rsp && ${zipSync} -d ${genDir} ${tmpZip}",
53 CommandDeps: []string{"${soongZip}", "${zipSync}"},
54 Rspfile: "${tmpZip}.rsp",
55 RspfileContent: "${zipArgs}",
56 }, "tmpZip", "genDir", "zipArgs")
Colin Cross5049f022015-03-18 13:28:46 -070057)
58
Jeff Gastonefc1b412017-03-29 17:29:06 -070059func init() {
Dan Willemsenddf504c2019-08-09 16:21:29 -070060 pctx.Import("android/soong/android")
Jeff Gastonefc1b412017-03-29 17:29:06 -070061 pctx.HostBinToolVariable("sboxCmd", "sbox")
Colin Cross1a527682019-09-23 15:55:30 -070062
63 pctx.HostBinToolVariable("soongZip", "soong_zip")
64 pctx.HostBinToolVariable("zipSync", "zipsync")
Jeff Gastonefc1b412017-03-29 17:29:06 -070065}
66
Colin Cross5049f022015-03-18 13:28:46 -070067type SourceFileGenerator interface {
Colin Cross635c3b02016-05-18 15:37:25 -070068 GeneratedSourceFiles() android.Paths
Colin Cross5ed99c62016-11-22 12:55:55 -080069 GeneratedHeaderDirs() android.Paths
Dan Willemsen9da9d492018-02-21 18:28:18 -080070 GeneratedDeps() android.Paths
Colin Cross5049f022015-03-18 13:28:46 -070071}
72
Colin Crossfe17f6f2019-03-28 19:30:56 -070073// Alias for android.HostToolProvider
74// Deprecated: use android.HostToolProvider instead.
Colin Crossd350ecd2015-04-28 13:25:36 -070075type HostToolProvider interface {
Colin Crossfe17f6f2019-03-28 19:30:56 -070076 android.HostToolProvider
Colin Crossd350ecd2015-04-28 13:25:36 -070077}
Colin Cross5049f022015-03-18 13:28:46 -070078
Dan Willemsend6ba0d52017-09-13 15:46:47 -070079type hostToolDependencyTag struct {
80 blueprint.BaseDependencyTag
Colin Cross08f15ab2018-10-04 23:29:14 -070081 label string
Dan Willemsend6ba0d52017-09-13 15:46:47 -070082}
83
Colin Cross7d5136f2015-05-11 13:39:40 -070084type generatorProperties struct {
Jeff Gastonefc1b412017-03-29 17:29:06 -070085 // The command to run on one or more input files. Cmd supports substitution of a few variables
86 // (the actual substitution is implemented in GenerateAndroidBuildActions below)
87 //
88 // Available variables for substitution:
89 //
Colin Cross2296f5b2017-10-17 21:38:14 -070090 // $(location): the path to the first entry in tools or tool_files
Colin Cross08f15ab2018-10-04 23:29:14 -070091 // $(location <label>): the path to the tool, tool_file, input or output with name <label>
Colin Cross2296f5b2017-10-17 21:38:14 -070092 // $(in): one or more input files
93 // $(out): a single output file
94 // $(depfile): a file to which dependencies will be written, if the depfile property is set to true
95 // $(genDir): the sandbox directory for this tool; contains $(out)
96 // $$: a literal $
Colin Cross6f080df2016-11-04 15:32:58 -070097 //
Jeff Gastonefc1b412017-03-29 17:29:06 -070098 // All files used must be declared as inputs (to ensure proper up-to-date checks).
99 // Use "$(in)" directly in Cmd to ensure that all inputs used are declared.
Nan Zhangea568a42017-11-08 21:20:04 -0800100 Cmd *string
Colin Cross7d5136f2015-05-11 13:39:40 -0700101
Colin Cross33bfb0a2016-11-21 17:23:08 -0800102 // Enable reading a file containing dependencies in gcc format after the command completes
Nan Zhangea568a42017-11-08 21:20:04 -0800103 Depfile *bool
Colin Cross33bfb0a2016-11-21 17:23:08 -0800104
Colin Cross6f080df2016-11-04 15:32:58 -0700105 // name of the modules (if any) that produces the host executable. Leave empty for
Colin Cross7d5136f2015-05-11 13:39:40 -0700106 // prebuilts or scripts that do not need a module to build them.
Colin Cross6f080df2016-11-04 15:32:58 -0700107 Tools []string
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700108
109 // Local file that is used as the tool
Colin Cross27b922f2019-03-04 22:35:41 -0800110 Tool_files []string `android:"path"`
Colin Cross5ed99c62016-11-22 12:55:55 -0800111
112 // List of directories to export generated headers from
113 Export_include_dirs []string
Colin Cross708c4242017-01-13 18:05:49 -0800114
115 // list of input files
Colin Cross27b922f2019-03-04 22:35:41 -0800116 Srcs []string `android:"path,arch_variant"`
Dan Willemseneefa0262018-11-17 14:01:18 -0800117
118 // input files to exclude
Colin Cross27b922f2019-03-04 22:35:41 -0800119 Exclude_srcs []string `android:"path,arch_variant"`
Colin Cross7d5136f2015-05-11 13:39:40 -0700120}
121
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700122type Module struct {
Colin Cross635c3b02016-05-18 15:37:25 -0700123 android.ModuleBase
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800124 android.DefaultableModuleBase
Jiyong Parkfc752ca2019-06-12 13:27:29 +0900125 android.ApexModuleBase
Colin Crossd350ecd2015-04-28 13:25:36 -0700126
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700127 // For other packages to make their own genrules with extra
128 // properties
129 Extra interface{}
Colin Cross7228ecd2019-11-18 16:00:16 -0800130 android.ImageInterface
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700131
Colin Cross7d5136f2015-05-11 13:39:40 -0700132 properties generatorProperties
Colin Crossd350ecd2015-04-28 13:25:36 -0700133
Jeff Gaston437d23c2017-11-08 12:38:00 -0800134 taskGenerator taskFunc
Colin Crossd350ecd2015-04-28 13:25:36 -0700135
Colin Cross1a527682019-09-23 15:55:30 -0700136 deps android.Paths
137 rule blueprint.Rule
138 rawCommands []string
Colin Crossd350ecd2015-04-28 13:25:36 -0700139
Colin Cross5ed99c62016-11-22 12:55:55 -0800140 exportedIncludeDirs android.Paths
Dan Willemsenb40aab62016-04-20 14:21:14 -0700141
Colin Cross635c3b02016-05-18 15:37:25 -0700142 outputFiles android.Paths
Dan Willemsen9da9d492018-02-21 18:28:18 -0800143 outputDeps android.Paths
Colin Crossa4ad2b02019-03-18 22:15:32 -0700144
145 subName string
Colin Cross1a527682019-09-23 15:55:30 -0700146 subDir string
Colin Crossd350ecd2015-04-28 13:25:36 -0700147}
148
Colin Cross1a527682019-09-23 15:55:30 -0700149type taskFunc func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask
Colin Crossd350ecd2015-04-28 13:25:36 -0700150
151type generateTask struct {
Colin Crossbaccf5b2018-02-21 14:07:48 -0800152 in android.Paths
153 out android.WritablePaths
Colin Cross1a527682019-09-23 15:55:30 -0700154 copyTo android.WritablePaths
155 genDir android.WritablePath
Colin Crossbaccf5b2018-02-21 14:07:48 -0800156 sandboxOuts []string
157 cmd string
Colin Cross1a527682019-09-23 15:55:30 -0700158 shard int
159 shards int
Colin Crossd350ecd2015-04-28 13:25:36 -0700160}
161
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700162func (g *Module) GeneratedSourceFiles() android.Paths {
Colin Crossd350ecd2015-04-28 13:25:36 -0700163 return g.outputFiles
164}
165
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700166func (g *Module) Srcs() android.Paths {
Nan Zhange42777a2018-03-27 16:19:42 -0700167 return append(android.Paths{}, g.outputFiles...)
Colin Cross068e0fe2016-12-13 15:23:47 -0800168}
169
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700170func (g *Module) GeneratedHeaderDirs() android.Paths {
Colin Cross5ed99c62016-11-22 12:55:55 -0800171 return g.exportedIncludeDirs
Dan Willemsenb40aab62016-04-20 14:21:14 -0700172}
173
Dan Willemsen9da9d492018-02-21 18:28:18 -0800174func (g *Module) GeneratedDeps() android.Paths {
175 return g.outputDeps
176}
177
Martin Stjernholm710ec3a2020-01-16 15:12:04 +0000178func toolDepsMutator(ctx android.BottomUpMutatorContext) {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700179 if g, ok := ctx.Module().(*Module); ok {
Colin Cross08f15ab2018-10-04 23:29:14 -0700180 for _, tool := range g.properties.Tools {
181 tag := hostToolDependencyTag{label: tool}
182 if m := android.SrcIsModule(tool); m != "" {
183 tool = m
184 }
Colin Cross0f7d2ef2019-10-16 11:03:10 -0700185 ctx.AddFarVariationDependencies(ctx.Config().BuildOSTarget.Variations(), tag, tool)
Colin Cross6362e272015-10-29 15:25:03 -0700186 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700187 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700188}
189
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700190func (g *Module) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Colin Crossa4ad2b02019-03-18 22:15:32 -0700191 g.subName = ctx.ModuleSubDir()
192
Colin Cross5ed99c62016-11-22 12:55:55 -0800193 if len(g.properties.Export_include_dirs) > 0 {
194 for _, dir := range g.properties.Export_include_dirs {
195 g.exportedIncludeDirs = append(g.exportedIncludeDirs,
Colin Cross1a527682019-09-23 15:55:30 -0700196 android.PathForModuleGen(ctx, g.subDir, ctx.ModuleDir(), dir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800197 }
198 } else {
Colin Cross1a527682019-09-23 15:55:30 -0700199 g.exportedIncludeDirs = append(g.exportedIncludeDirs, android.PathForModuleGen(ctx, g.subDir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800200 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700201
Colin Cross08f15ab2018-10-04 23:29:14 -0700202 locationLabels := map[string][]string{}
203 firstLabel := ""
204
205 addLocationLabel := func(label string, paths []string) {
206 if firstLabel == "" {
207 firstLabel = label
208 }
209 if _, exists := locationLabels[label]; !exists {
210 locationLabels[label] = paths
211 } else {
212 ctx.ModuleErrorf("multiple labels for %q, %q and %q",
213 label, strings.Join(locationLabels[label], " "), strings.Join(paths, " "))
214 }
215 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700216
Colin Cross6f080df2016-11-04 15:32:58 -0700217 if len(g.properties.Tools) > 0 {
Colin Crossba71a3f2019-03-18 12:12:48 -0700218 seenTools := make(map[string]bool)
219
Colin Cross35143d02017-11-16 00:11:20 -0800220 ctx.VisitDirectDepsBlueprint(func(module blueprint.Module) {
Colin Cross08f15ab2018-10-04 23:29:14 -0700221 switch tag := ctx.OtherModuleDependencyTag(module).(type) {
222 case hostToolDependencyTag:
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700223 tool := ctx.OtherModuleName(module)
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700224 var path android.OptionalPath
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700225
Colin Crossfe17f6f2019-03-28 19:30:56 -0700226 if t, ok := module.(android.HostToolProvider); ok {
Colin Cross35143d02017-11-16 00:11:20 -0800227 if !t.(android.Module).Enabled() {
Colin Cross6510f912017-11-29 00:27:14 -0800228 if ctx.Config().AllowMissingDependencies() {
Colin Cross35143d02017-11-16 00:11:20 -0800229 ctx.AddMissingDependencies([]string{tool})
230 } else {
231 ctx.ModuleErrorf("depends on disabled module %q", tool)
232 }
233 break
234 }
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700235 path = t.HostToolPath()
236 } else if t, ok := module.(bootstrap.GoBinaryTool); ok {
237 if s, err := filepath.Rel(android.PathForOutput(ctx).String(), t.InstallPath()); err == nil {
238 path = android.OptionalPathForPath(android.PathForOutput(ctx, s))
Colin Cross6f080df2016-11-04 15:32:58 -0700239 } else {
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700240 ctx.ModuleErrorf("cannot find path for %q: %v", tool, err)
241 break
Colin Cross6f080df2016-11-04 15:32:58 -0700242 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700243 } else {
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700244 ctx.ModuleErrorf("%q is not a host tool provider", tool)
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700245 break
246 }
247
248 if path.Valid() {
249 g.deps = append(g.deps, path.Path())
Colin Cross08f15ab2018-10-04 23:29:14 -0700250 addLocationLabel(tag.label, []string{path.Path().String()})
Colin Crossba71a3f2019-03-18 12:12:48 -0700251 seenTools[tag.label] = true
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700252 } else {
253 ctx.ModuleErrorf("host tool %q missing output file", tool)
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700254 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700255 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700256 })
Colin Crossba71a3f2019-03-18 12:12:48 -0700257
258 // If AllowMissingDependencies is enabled, the build will not have stopped when
259 // AddFarVariationDependencies was called on a missing tool, which will result in nonsensical
260 // "cmd: unknown location label ..." errors later. Add a dummy file to the local label. The
261 // command that uses this dummy file will never be executed because the rule will be replaced with
262 // an android.Error rule reporting the missing dependencies.
263 if ctx.Config().AllowMissingDependencies() {
264 for _, tool := range g.properties.Tools {
265 if !seenTools[tool] {
266 addLocationLabel(tool, []string{"***missing tool " + tool + "***"})
267 }
268 }
269 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700270 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700271
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700272 if ctx.Failed() {
273 return
274 }
275
Colin Cross08f15ab2018-10-04 23:29:14 -0700276 for _, toolFile := range g.properties.Tool_files {
Colin Cross8a497952019-03-05 22:25:09 -0800277 paths := android.PathsForModuleSrc(ctx, []string{toolFile})
Colin Cross08f15ab2018-10-04 23:29:14 -0700278 g.deps = append(g.deps, paths...)
279 addLocationLabel(toolFile, paths.Strings())
280 }
281
282 var srcFiles android.Paths
283 for _, in := range g.properties.Srcs {
Colin Crossba71a3f2019-03-18 12:12:48 -0700284 paths, missingDeps := android.PathsAndMissingDepsForModuleSrcExcludes(ctx, []string{in}, g.properties.Exclude_srcs)
285 if len(missingDeps) > 0 {
286 if !ctx.Config().AllowMissingDependencies() {
287 panic(fmt.Errorf("should never get here, the missing dependencies %q should have been reported in DepsMutator",
288 missingDeps))
289 }
290
291 // If AllowMissingDependencies is enabled, the build will not have stopped when
292 // the dependency was added on a missing SourceFileProducer module, which will result in nonsensical
293 // "cmd: label ":..." has no files" errors later. Add a dummy file to the local label. The
294 // command that uses this dummy file will never be executed because the rule will be replaced with
295 // an android.Error rule reporting the missing dependencies.
296 ctx.AddMissingDependencies(missingDeps)
297 addLocationLabel(in, []string{"***missing srcs " + in + "***"})
298 } else {
299 srcFiles = append(srcFiles, paths...)
300 addLocationLabel(in, paths.Strings())
301 }
Colin Cross08f15ab2018-10-04 23:29:14 -0700302 }
303
Colin Cross1a527682019-09-23 15:55:30 -0700304 var copyFrom android.Paths
305 var outputFiles android.WritablePaths
306 var zipArgs strings.Builder
Colin Cross08f15ab2018-10-04 23:29:14 -0700307
Colin Cross1a527682019-09-23 15:55:30 -0700308 for _, task := range g.taskGenerator(ctx, String(g.properties.Cmd), srcFiles) {
309 for _, out := range task.out {
310 addLocationLabel(out.Rel(), []string{filepath.Join("__SBOX_OUT_DIR__", out.Rel())})
Colin Cross85a2e892018-07-09 09:45:06 -0700311 }
312
Bill Peckhamc087be12020-02-13 15:55:10 -0800313 referencedIn := false
Colin Cross1a527682019-09-23 15:55:30 -0700314 referencedDepfile := false
315
316 rawCommand, err := android.ExpandNinjaEscaped(task.cmd, func(name string) (string, bool, error) {
317 // report the error directly without returning an error to android.Expand to catch multiple errors in a
318 // single run
319 reportError := func(fmt string, args ...interface{}) (string, bool, error) {
320 ctx.PropertyErrorf("cmd", fmt, args...)
321 return "SOONG_ERROR", false, nil
Colin Cross6f080df2016-11-04 15:32:58 -0700322 }
Colin Cross1a527682019-09-23 15:55:30 -0700323
324 switch name {
325 case "location":
326 if len(g.properties.Tools) == 0 && len(g.properties.Tool_files) == 0 {
327 return reportError("at least one `tools` or `tool_files` is required if $(location) is used")
Colin Cross6f080df2016-11-04 15:32:58 -0700328 }
Colin Cross1a527682019-09-23 15:55:30 -0700329 paths := locationLabels[firstLabel]
330 if len(paths) == 0 {
331 return reportError("default label %q has no files", firstLabel)
332 } else if len(paths) > 1 {
333 return reportError("default label %q has multiple files, use $(locations %s) to reference it",
334 firstLabel, firstLabel)
Colin Cross08f15ab2018-10-04 23:29:14 -0700335 }
Colin Cross1a527682019-09-23 15:55:30 -0700336 return locationLabels[firstLabel][0], false, nil
337 case "in":
Bill Peckhamc087be12020-02-13 15:55:10 -0800338 referencedIn = true
Colin Cross1a527682019-09-23 15:55:30 -0700339 return "${in}", true, nil
340 case "out":
341 return "__SBOX_OUT_FILES__", false, nil
342 case "depfile":
343 referencedDepfile = true
344 if !Bool(g.properties.Depfile) {
345 return reportError("$(depfile) used without depfile property")
346 }
347 return "__SBOX_DEPFILE__", false, nil
348 case "genDir":
349 return "__SBOX_OUT_DIR__", false, nil
350 default:
351 if strings.HasPrefix(name, "location ") {
352 label := strings.TrimSpace(strings.TrimPrefix(name, "location "))
353 if paths, ok := locationLabels[label]; ok {
354 if len(paths) == 0 {
355 return reportError("label %q has no files", label)
356 } else if len(paths) > 1 {
357 return reportError("label %q has multiple files, use $(locations %s) to reference it",
358 label, label)
359 }
360 return paths[0], false, nil
361 } else {
362 return reportError("unknown location label %q", label)
363 }
364 } else if strings.HasPrefix(name, "locations ") {
365 label := strings.TrimSpace(strings.TrimPrefix(name, "locations "))
366 if paths, ok := locationLabels[label]; ok {
367 if len(paths) == 0 {
368 return reportError("label %q has no files", label)
369 }
370 return strings.Join(paths, " "), false, nil
371 } else {
372 return reportError("unknown locations label %q", label)
373 }
374 } else {
375 return reportError("unknown variable '$(%s)'", name)
376 }
Colin Cross6f080df2016-11-04 15:32:58 -0700377 }
Colin Cross1a527682019-09-23 15:55:30 -0700378 })
379
380 if err != nil {
381 ctx.PropertyErrorf("cmd", "%s", err.Error())
382 return
Colin Cross6f080df2016-11-04 15:32:58 -0700383 }
Colin Cross6f080df2016-11-04 15:32:58 -0700384
Colin Cross1a527682019-09-23 15:55:30 -0700385 if Bool(g.properties.Depfile) && !referencedDepfile {
386 ctx.PropertyErrorf("cmd", "specified depfile=true but did not include a reference to '${depfile}' in cmd")
387 return
388 }
389
390 // tell the sbox command which directory to use as its sandbox root
391 buildDir := android.PathForOutput(ctx).String()
392 sandboxPath := shared.TempDirForOutDir(buildDir)
393
394 // recall that Sprintf replaces percent sign expressions, whereas dollar signs expressions remain as written,
395 // to be replaced later by ninja_strings.go
396 depfilePlaceholder := ""
397 if Bool(g.properties.Depfile) {
398 depfilePlaceholder = "$depfileArgs"
399 }
400
401 // Escape the command for the shell
402 rawCommand = "'" + strings.Replace(rawCommand, "'", `'\''`, -1) + "'"
403 g.rawCommands = append(g.rawCommands, rawCommand)
Bill Peckhamc087be12020-02-13 15:55:10 -0800404
405 sandboxCommand := fmt.Sprintf("rm -rf %s && $sboxCmd --sandbox-path %s --output-root %s",
406 task.genDir, sandboxPath, task.genDir)
407
408 if !referencedIn {
409 sandboxCommand = sandboxCommand + hashSrcFiles(srcFiles)
410 }
411
412 sandboxCommand = sandboxCommand + fmt.Sprintf(" -c %s %s $allouts",
413 rawCommand, depfilePlaceholder)
Colin Cross1a527682019-09-23 15:55:30 -0700414
415 ruleParams := blueprint.RuleParams{
416 Command: sandboxCommand,
417 CommandDeps: []string{"$sboxCmd"},
418 }
419 args := []string{"allouts"}
420 if Bool(g.properties.Depfile) {
421 ruleParams.Deps = blueprint.DepsGCC
422 args = append(args, "depfileArgs")
423 }
424 name := "generator"
425 if task.shards > 1 {
426 name += strconv.Itoa(task.shard)
427 }
428 rule := ctx.Rule(pctx, name, ruleParams, args...)
429
430 g.generateSourceFile(ctx, task, rule)
431
432 if len(task.copyTo) > 0 {
433 outputFiles = append(outputFiles, task.copyTo...)
434 copyFrom = append(copyFrom, task.out.Paths()...)
435 zipArgs.WriteString(" -C " + task.genDir.String())
436 zipArgs.WriteString(android.JoinWithPrefix(task.out.Strings(), " -f "))
437 } else {
438 outputFiles = append(outputFiles, task.out...)
439 }
Colin Cross6f080df2016-11-04 15:32:58 -0700440 }
441
Colin Cross1a527682019-09-23 15:55:30 -0700442 if len(copyFrom) > 0 {
443 ctx.Build(pctx, android.BuildParams{
444 Rule: gensrcsMerge,
445 Implicits: copyFrom,
446 Outputs: outputFiles,
447 Args: map[string]string{
448 "zipArgs": zipArgs.String(),
449 "tmpZip": android.PathForModuleGen(ctx, g.subDir+".zip").String(),
450 "genDir": android.PathForModuleGen(ctx, g.subDir).String(),
451 },
452 })
Colin Cross85a2e892018-07-09 09:45:06 -0700453 }
454
Colin Cross1a527682019-09-23 15:55:30 -0700455 g.outputFiles = outputFiles.Paths()
Jeff Gastonefc1b412017-03-29 17:29:06 -0700456
Colin Cross1a527682019-09-23 15:55:30 -0700457 // For <= 6 outputs, just embed those directly in the users. Right now, that covers >90% of
458 // the genrules on AOSP. That will make things simpler to look at the graph in the common
459 // case. For larger sets of outputs, inject a phony target in between to limit ninja file
460 // growth.
461 if len(g.outputFiles) <= 6 {
462 g.outputDeps = g.outputFiles
463 } else {
464 phonyFile := android.PathForModuleGen(ctx, "genrule-phony")
465
466 ctx.Build(pctx, android.BuildParams{
467 Rule: blueprint.Phony,
468 Output: phonyFile,
469 Inputs: g.outputFiles,
470 })
471
472 g.outputDeps = android.Paths{phonyFile}
Jeff Gaston02a684b2017-10-27 14:59:27 -0700473 }
Jeff Gaston5acec2b2017-11-06 14:15:16 -0800474
Colin Crossd350ecd2015-04-28 13:25:36 -0700475}
476
Bill Peckhamc087be12020-02-13 15:55:10 -0800477func hashSrcFiles(srcFiles android.Paths) string {
478 h := sha256.New()
479 for _, src := range srcFiles {
480 h.Write([]byte(src.String()))
481 }
482 return fmt.Sprintf(" --input-hash %x", h.Sum(nil))
483}
484
Colin Cross1a527682019-09-23 15:55:30 -0700485func (g *Module) generateSourceFile(ctx android.ModuleContext, task generateTask, rule blueprint.Rule) {
Colin Cross67a5c132017-05-09 13:45:28 -0700486 desc := "generate"
Colin Cross15e86d92017-10-20 15:07:08 -0700487 if len(task.out) == 0 {
488 ctx.ModuleErrorf("must have at least one output file")
489 return
490 }
Colin Cross67a5c132017-05-09 13:45:28 -0700491 if len(task.out) == 1 {
492 desc += " " + task.out[0].Base()
493 }
494
Jeff Gaston02a684b2017-10-27 14:59:27 -0700495 var depFile android.ModuleGenPath
Nan Zhangea568a42017-11-08 21:20:04 -0800496 if Bool(g.properties.Depfile) {
Jeff Gaston02a684b2017-10-27 14:59:27 -0700497 depFile = android.PathForModuleGen(ctx, task.out[0].Rel()+".d")
498 }
499
Colin Cross1a527682019-09-23 15:55:30 -0700500 if task.shards > 1 {
501 desc += " " + strconv.Itoa(task.shard)
502 }
503
Colin Crossae887032017-10-23 17:16:14 -0700504 params := android.BuildParams{
Colin Cross1a527682019-09-23 15:55:30 -0700505 Rule: rule,
506 Description: desc,
Colin Cross15e86d92017-10-20 15:07:08 -0700507 Output: task.out[0],
508 ImplicitOutputs: task.out[1:],
509 Inputs: task.in,
510 Implicits: g.deps,
511 Args: map[string]string{
Colin Crossbaccf5b2018-02-21 14:07:48 -0800512 "allouts": strings.Join(task.sandboxOuts, " "),
Colin Cross15e86d92017-10-20 15:07:08 -0700513 },
Colin Cross33bfb0a2016-11-21 17:23:08 -0800514 }
Nan Zhangea568a42017-11-08 21:20:04 -0800515 if Bool(g.properties.Depfile) {
Jeff Gaston02a684b2017-10-27 14:59:27 -0700516 params.Depfile = android.PathForModuleGen(ctx, task.out[0].Rel()+".d")
517 params.Args["depfileArgs"] = "--depfile-out " + depFile.String()
Colin Cross33bfb0a2016-11-21 17:23:08 -0800518 }
Jeff Gaston02a684b2017-10-27 14:59:27 -0700519
Colin Crossae887032017-10-23 17:16:14 -0700520 ctx.Build(pctx, params)
Colin Crossd350ecd2015-04-28 13:25:36 -0700521}
522
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700523// Collect information for opening IDE project files in java/jdeps.go.
524func (g *Module) IDEInfo(dpInfo *android.IdeInfo) {
525 dpInfo.Srcs = append(dpInfo.Srcs, g.Srcs().Strings()...)
526 for _, src := range g.properties.Srcs {
527 if strings.HasPrefix(src, ":") {
528 src = strings.Trim(src, ":")
529 dpInfo.Deps = append(dpInfo.Deps, src)
530 }
531 }
532}
533
Colin Crossa4ad2b02019-03-18 22:15:32 -0700534func (g *Module) AndroidMk() android.AndroidMkData {
535 return android.AndroidMkData{
536 Include: "$(BUILD_PHONY_PACKAGE)",
537 Class: "FAKE",
538 OutputFile: android.OptionalPathForPath(g.outputFiles[0]),
539 SubName: g.subName,
540 Extra: []android.AndroidMkExtraFunc{
541 func(w io.Writer, outputFile android.Path) {
Colin Cross1a527682019-09-23 15:55:30 -0700542 fmt.Fprintln(w, "LOCAL_ADDITIONAL_DEPENDENCIES :=", strings.Join(g.outputDeps.Strings(), " "))
Colin Crossa4ad2b02019-03-18 22:15:32 -0700543 },
544 },
545 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
546 android.WriteAndroidMkData(w, data)
547 if data.SubName != "" {
548 fmt.Fprintln(w, ".PHONY:", name)
549 fmt.Fprintln(w, name, ":", name+g.subName)
550 }
551 },
552 }
553}
554
Jeff Gaston437d23c2017-11-08 12:38:00 -0800555func generatorFactory(taskGenerator taskFunc, props ...interface{}) *Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700556 module := &Module{
Jeff Gaston437d23c2017-11-08 12:38:00 -0800557 taskGenerator: taskGenerator,
Colin Crossd350ecd2015-04-28 13:25:36 -0700558 }
559
Colin Cross36242852017-06-23 15:06:31 -0700560 module.AddProperties(props...)
561 module.AddProperties(&module.properties)
Colin Crossd350ecd2015-04-28 13:25:36 -0700562
Colin Cross7228ecd2019-11-18 16:00:16 -0800563 module.ImageInterface = noopImageInterface{}
564
Colin Cross36242852017-06-23 15:06:31 -0700565 return module
Colin Crossd350ecd2015-04-28 13:25:36 -0700566}
567
Colin Cross7228ecd2019-11-18 16:00:16 -0800568type noopImageInterface struct{}
569
570func (x noopImageInterface) ImageMutatorBegin(android.BaseModuleContext) {}
571func (x noopImageInterface) CoreVariantNeeded(android.BaseModuleContext) bool { return false }
Yifan Hong1b3348d2020-01-21 15:53:22 -0800572func (x noopImageInterface) RamdiskVariantNeeded(android.BaseModuleContext) bool { return false }
Colin Cross7228ecd2019-11-18 16:00:16 -0800573func (x noopImageInterface) RecoveryVariantNeeded(android.BaseModuleContext) bool { return false }
574func (x noopImageInterface) ExtraImageVariations(ctx android.BaseModuleContext) []string { return nil }
575func (x noopImageInterface) SetImageVariation(ctx android.BaseModuleContext, variation string, module android.Module) {
576}
577
Colin Crossbaccf5b2018-02-21 14:07:48 -0800578// replace "out" with "__SBOX_OUT_DIR__/<the value of ${out}>"
579func pathToSandboxOut(path android.Path, genDir android.Path) string {
580 relOut, err := filepath.Rel(genDir.String(), path.String())
581 if err != nil {
582 panic(fmt.Sprintf("Could not make ${out} relative: %v", err))
583 }
584 return filepath.Join("__SBOX_OUT_DIR__", relOut)
585
586}
587
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700588func NewGenSrcs() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700589 properties := &genSrcsProperties{}
590
Colin Cross1a527682019-09-23 15:55:30 -0700591 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
592 genDir := android.PathForModuleGen(ctx, "gensrcs")
593 shardSize := defaultShardSize
594 if s := properties.Shard_size; s != nil {
595 shardSize = int(*s)
596 }
Jeff Gaston437d23c2017-11-08 12:38:00 -0800597
Colin Cross1a527682019-09-23 15:55:30 -0700598 shards := android.ShardPaths(srcFiles, shardSize)
599 var generateTasks []generateTask
Colin Crossbaccf5b2018-02-21 14:07:48 -0800600
Colin Cross1a527682019-09-23 15:55:30 -0700601 for i, shard := range shards {
602 var commands []string
603 var outFiles android.WritablePaths
604 var copyTo android.WritablePaths
605 var shardDir android.WritablePath
606 var sandboxOuts []string
607
608 if len(shards) > 1 {
609 shardDir = android.PathForModuleGen(ctx, strconv.Itoa(i))
610 } else {
611 shardDir = genDir
Jeff Gaston437d23c2017-11-08 12:38:00 -0800612 }
613
Colin Cross1a527682019-09-23 15:55:30 -0700614 for _, in := range shard {
615 outFile := android.GenPathWithExt(ctx, "gensrcs", in, String(properties.Output_extension))
616 sandboxOutfile := pathToSandboxOut(outFile, genDir)
Jeff Gaston437d23c2017-11-08 12:38:00 -0800617
Colin Cross1a527682019-09-23 15:55:30 -0700618 if len(shards) > 1 {
619 shardFile := android.GenPathWithExt(ctx, strconv.Itoa(i), in, String(properties.Output_extension))
620 copyTo = append(copyTo, outFile)
621 outFile = shardFile
622 }
623
624 outFiles = append(outFiles, outFile)
625 sandboxOuts = append(sandboxOuts, sandboxOutfile)
626
627 command, err := android.Expand(rawCommand, func(name string) (string, error) {
628 switch name {
629 case "in":
630 return in.String(), nil
631 case "out":
632 return sandboxOutfile, nil
633 default:
634 return "$(" + name + ")", nil
635 }
636 })
637 if err != nil {
638 ctx.PropertyErrorf("cmd", err.Error())
639 }
640
641 // escape the command in case for example it contains '#', an odd number of '"', etc
642 command = fmt.Sprintf("bash -c %v", proptools.ShellEscape(command))
643 commands = append(commands, command)
644 }
645 fullCommand := strings.Join(commands, " && ")
646
647 generateTasks = append(generateTasks, generateTask{
648 in: shard,
649 out: outFiles,
650 copyTo: copyTo,
651 genDir: shardDir,
652 sandboxOuts: sandboxOuts,
653 cmd: fullCommand,
654 shard: i,
655 shards: len(shards),
656 })
Jeff Gaston437d23c2017-11-08 12:38:00 -0800657 }
Colin Cross1a527682019-09-23 15:55:30 -0700658
659 return generateTasks
Colin Crossd350ecd2015-04-28 13:25:36 -0700660 }
661
Colin Cross1a527682019-09-23 15:55:30 -0700662 g := generatorFactory(taskGenerator, properties)
663 g.subDir = "gensrcs"
664 return g
Colin Crossd350ecd2015-04-28 13:25:36 -0700665}
666
Colin Cross54190b32017-10-09 15:34:10 -0700667func GenSrcsFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700668 m := NewGenSrcs()
669 android.InitAndroidModule(m)
670 return m
671}
672
Colin Crossd350ecd2015-04-28 13:25:36 -0700673type genSrcsProperties struct {
Colin Cross7d5136f2015-05-11 13:39:40 -0700674 // extension that will be substituted for each output file
Nan Zhanga5e7cb42017-11-09 22:42:32 -0800675 Output_extension *string
Colin Cross1a527682019-09-23 15:55:30 -0700676
677 // maximum number of files that will be passed on a single command line.
678 Shard_size *int64
Colin Cross5049f022015-03-18 13:28:46 -0700679}
680
Colin Cross1a527682019-09-23 15:55:30 -0700681const defaultShardSize = 100
682
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700683func NewGenRule() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700684 properties := &genRuleProperties{}
Colin Cross5049f022015-03-18 13:28:46 -0700685
Colin Cross1a527682019-09-23 15:55:30 -0700686 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700687 outs := make(android.WritablePaths, len(properties.Out))
Colin Crossbaccf5b2018-02-21 14:07:48 -0800688 sandboxOuts := make([]string, len(properties.Out))
689 genDir := android.PathForModuleGen(ctx)
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700690 for i, out := range properties.Out {
691 outs[i] = android.PathForModuleGen(ctx, out)
Colin Crossbaccf5b2018-02-21 14:07:48 -0800692 sandboxOuts[i] = pathToSandboxOut(outs[i], genDir)
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700693 }
Colin Cross1a527682019-09-23 15:55:30 -0700694 return []generateTask{{
Colin Crossbaccf5b2018-02-21 14:07:48 -0800695 in: srcFiles,
696 out: outs,
Colin Cross1a527682019-09-23 15:55:30 -0700697 genDir: android.PathForModuleGen(ctx),
Colin Crossbaccf5b2018-02-21 14:07:48 -0800698 sandboxOuts: sandboxOuts,
699 cmd: rawCommand,
Colin Cross1a527682019-09-23 15:55:30 -0700700 }}
Colin Cross5049f022015-03-18 13:28:46 -0700701 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700702
Jeff Gaston437d23c2017-11-08 12:38:00 -0800703 return generatorFactory(taskGenerator, properties)
Colin Cross5049f022015-03-18 13:28:46 -0700704}
705
Colin Cross54190b32017-10-09 15:34:10 -0700706func GenRuleFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700707 m := NewGenRule()
708 android.InitAndroidModule(m)
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800709 android.InitDefaultableModule(m)
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700710 return m
711}
712
Colin Crossd350ecd2015-04-28 13:25:36 -0700713type genRuleProperties struct {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700714 // names of the output files that will be generated
Colin Crossef354482018-10-23 11:27:50 -0700715 Out []string `android:"arch_variant"`
Colin Cross5049f022015-03-18 13:28:46 -0700716}
Nan Zhangea568a42017-11-08 21:20:04 -0800717
718var Bool = proptools.Bool
719var String = proptools.String
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800720
721//
722// Defaults
723//
724type Defaults struct {
725 android.ModuleBase
726 android.DefaultsModuleBase
727}
728
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800729func defaultsFactory() android.Module {
730 return DefaultsFactory()
731}
732
733func DefaultsFactory(props ...interface{}) android.Module {
734 module := &Defaults{}
735
736 module.AddProperties(props...)
737 module.AddProperties(
738 &generatorProperties{},
739 &genRuleProperties{},
740 )
741
742 android.InitDefaultsModule(module)
743
744 return module
745}