blob: 55c7e628e954f6ce9e81fddc1e572113b6865305 [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 Crossd9c1c8f2019-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 Crossd9c1c8f2019-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() {
51 pctx.HostBinToolVariable("sboxCmd", "sbox")
Colin Crossd9c1c8f2019-09-23 15:55:30 -070052
53 pctx.HostBinToolVariable("soongZip", "soong_zip")
54 pctx.HostBinToolVariable("zipSync", "zipsync")
Jeff Gastonefc1b412017-03-29 17:29:06 -070055}
56
Colin Cross5049f022015-03-18 13:28:46 -070057type SourceFileGenerator interface {
Colin Cross635c3b02016-05-18 15:37:25 -070058 GeneratedSourceFiles() android.Paths
Colin Cross5ed99c62016-11-22 12:55:55 -080059 GeneratedHeaderDirs() android.Paths
Dan Willemsen9da9d492018-02-21 18:28:18 -080060 GeneratedDeps() android.Paths
Colin Cross5049f022015-03-18 13:28:46 -070061}
62
Colin Crossfe17f6f2019-03-28 19:30:56 -070063// Alias for android.HostToolProvider
64// Deprecated: use android.HostToolProvider instead.
Colin Crossd350ecd2015-04-28 13:25:36 -070065type HostToolProvider interface {
Colin Crossfe17f6f2019-03-28 19:30:56 -070066 android.HostToolProvider
Colin Crossd350ecd2015-04-28 13:25:36 -070067}
Colin Cross5049f022015-03-18 13:28:46 -070068
Dan Willemsend6ba0d52017-09-13 15:46:47 -070069type hostToolDependencyTag struct {
70 blueprint.BaseDependencyTag
Colin Cross08f15ab2018-10-04 23:29:14 -070071 label string
Dan Willemsend6ba0d52017-09-13 15:46:47 -070072}
73
Colin Cross7d5136f2015-05-11 13:39:40 -070074type generatorProperties struct {
Jeff Gastonefc1b412017-03-29 17:29:06 -070075 // The command to run on one or more input files. Cmd supports substitution of a few variables
76 // (the actual substitution is implemented in GenerateAndroidBuildActions below)
77 //
78 // Available variables for substitution:
79 //
Colin Cross2296f5b2017-10-17 21:38:14 -070080 // $(location): the path to the first entry in tools or tool_files
Colin Cross08f15ab2018-10-04 23:29:14 -070081 // $(location <label>): the path to the tool, tool_file, input or output with name <label>
Colin Cross2296f5b2017-10-17 21:38:14 -070082 // $(in): one or more input files
83 // $(out): a single output file
84 // $(depfile): a file to which dependencies will be written, if the depfile property is set to true
85 // $(genDir): the sandbox directory for this tool; contains $(out)
86 // $$: a literal $
Colin Cross6f080df2016-11-04 15:32:58 -070087 //
Jeff Gastonefc1b412017-03-29 17:29:06 -070088 // All files used must be declared as inputs (to ensure proper up-to-date checks).
89 // Use "$(in)" directly in Cmd to ensure that all inputs used are declared.
Nan Zhangea568a42017-11-08 21:20:04 -080090 Cmd *string
Colin Cross7d5136f2015-05-11 13:39:40 -070091
Colin Cross33bfb0a2016-11-21 17:23:08 -080092 // Enable reading a file containing dependencies in gcc format after the command completes
Nan Zhangea568a42017-11-08 21:20:04 -080093 Depfile *bool
Colin Cross33bfb0a2016-11-21 17:23:08 -080094
Colin Cross6f080df2016-11-04 15:32:58 -070095 // name of the modules (if any) that produces the host executable. Leave empty for
Colin Cross7d5136f2015-05-11 13:39:40 -070096 // prebuilts or scripts that do not need a module to build them.
Colin Cross6f080df2016-11-04 15:32:58 -070097 Tools []string
Dan Willemsenf7f3d692016-04-20 14:54:32 -070098
99 // Local file that is used as the tool
Colin Cross27b922f2019-03-04 22:35:41 -0800100 Tool_files []string `android:"path"`
Colin Cross5ed99c62016-11-22 12:55:55 -0800101
102 // List of directories to export generated headers from
103 Export_include_dirs []string
Colin Cross708c4242017-01-13 18:05:49 -0800104
105 // list of input files
Colin Cross27b922f2019-03-04 22:35:41 -0800106 Srcs []string `android:"path,arch_variant"`
Dan Willemseneefa0262018-11-17 14:01:18 -0800107
108 // input files to exclude
Colin Cross27b922f2019-03-04 22:35:41 -0800109 Exclude_srcs []string `android:"path,arch_variant"`
Colin Cross7d5136f2015-05-11 13:39:40 -0700110}
111
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700112type Module struct {
Colin Cross635c3b02016-05-18 15:37:25 -0700113 android.ModuleBase
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800114 android.DefaultableModuleBase
Colin Crossd350ecd2015-04-28 13:25:36 -0700115
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700116 // For other packages to make their own genrules with extra
117 // properties
118 Extra interface{}
119
Colin Cross7d5136f2015-05-11 13:39:40 -0700120 properties generatorProperties
Colin Crossd350ecd2015-04-28 13:25:36 -0700121
Jeff Gaston437d23c2017-11-08 12:38:00 -0800122 taskGenerator taskFunc
Colin Crossd350ecd2015-04-28 13:25:36 -0700123
Colin Crossd9c1c8f2019-09-23 15:55:30 -0700124 deps android.Paths
125 rule blueprint.Rule
126 rawCommands []string
Colin Crossd350ecd2015-04-28 13:25:36 -0700127
Colin Cross5ed99c62016-11-22 12:55:55 -0800128 exportedIncludeDirs android.Paths
Dan Willemsenb40aab62016-04-20 14:21:14 -0700129
Colin Cross635c3b02016-05-18 15:37:25 -0700130 outputFiles android.Paths
Dan Willemsen9da9d492018-02-21 18:28:18 -0800131 outputDeps android.Paths
Colin Crossa4ad2b02019-03-18 22:15:32 -0700132
133 subName string
Colin Crossd9c1c8f2019-09-23 15:55:30 -0700134 subDir string
Colin Crossd350ecd2015-04-28 13:25:36 -0700135}
136
Colin Crossd9c1c8f2019-09-23 15:55:30 -0700137type taskFunc func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask
Colin Crossd350ecd2015-04-28 13:25:36 -0700138
139type generateTask struct {
Colin Crossbaccf5b2018-02-21 14:07:48 -0800140 in android.Paths
141 out android.WritablePaths
Colin Crossd9c1c8f2019-09-23 15:55:30 -0700142 copyTo android.WritablePaths
143 genDir android.WritablePath
Colin Crossbaccf5b2018-02-21 14:07:48 -0800144 sandboxOuts []string
145 cmd string
Colin Crossd9c1c8f2019-09-23 15:55:30 -0700146 shard int
147 shards int
Colin Crossd350ecd2015-04-28 13:25:36 -0700148}
149
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700150func (g *Module) GeneratedSourceFiles() android.Paths {
Colin Crossd350ecd2015-04-28 13:25:36 -0700151 return g.outputFiles
152}
153
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700154func (g *Module) Srcs() android.Paths {
Nan Zhange42777a2018-03-27 16:19:42 -0700155 return append(android.Paths{}, g.outputFiles...)
Colin Cross068e0fe2016-12-13 15:23:47 -0800156}
157
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700158func (g *Module) GeneratedHeaderDirs() android.Paths {
Colin Cross5ed99c62016-11-22 12:55:55 -0800159 return g.exportedIncludeDirs
Dan Willemsenb40aab62016-04-20 14:21:14 -0700160}
161
Dan Willemsen9da9d492018-02-21 18:28:18 -0800162func (g *Module) GeneratedDeps() android.Paths {
163 return g.outputDeps
164}
165
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700166func (g *Module) DepsMutator(ctx android.BottomUpMutatorContext) {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700167 if g, ok := ctx.Module().(*Module); ok {
Colin Cross08f15ab2018-10-04 23:29:14 -0700168 for _, tool := range g.properties.Tools {
169 tag := hostToolDependencyTag{label: tool}
170 if m := android.SrcIsModule(tool); m != "" {
171 tool = m
172 }
Dan Willemsen490fd492015-11-24 17:53:15 -0800173 ctx.AddFarVariationDependencies([]blueprint.Variation{
Dan Willemsen59339a22018-07-22 21:18:45 -0700174 {Mutator: "arch", Variation: ctx.Config().BuildOsVariant},
Colin Cross08f15ab2018-10-04 23:29:14 -0700175 }, tag, tool)
Colin Cross6362e272015-10-29 15:25:03 -0700176 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700177 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700178}
179
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700180func (g *Module) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Colin Crossa4ad2b02019-03-18 22:15:32 -0700181 g.subName = ctx.ModuleSubDir()
182
Colin Cross5ed99c62016-11-22 12:55:55 -0800183 if len(g.properties.Export_include_dirs) > 0 {
184 for _, dir := range g.properties.Export_include_dirs {
185 g.exportedIncludeDirs = append(g.exportedIncludeDirs,
Colin Crossd9c1c8f2019-09-23 15:55:30 -0700186 android.PathForModuleGen(ctx, g.subDir, ctx.ModuleDir(), dir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800187 }
188 } else {
Colin Crossd9c1c8f2019-09-23 15:55:30 -0700189 g.exportedIncludeDirs = append(g.exportedIncludeDirs, android.PathForModuleGen(ctx, g.subDir))
Colin Cross5ed99c62016-11-22 12:55:55 -0800190 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700191
Colin Cross08f15ab2018-10-04 23:29:14 -0700192 locationLabels := map[string][]string{}
193 firstLabel := ""
194
195 addLocationLabel := func(label string, paths []string) {
196 if firstLabel == "" {
197 firstLabel = label
198 }
199 if _, exists := locationLabels[label]; !exists {
200 locationLabels[label] = paths
201 } else {
202 ctx.ModuleErrorf("multiple labels for %q, %q and %q",
203 label, strings.Join(locationLabels[label], " "), strings.Join(paths, " "))
204 }
205 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700206
Colin Cross6f080df2016-11-04 15:32:58 -0700207 if len(g.properties.Tools) > 0 {
Colin Crossc6de83c2019-03-18 12:12:48 -0700208 seenTools := make(map[string]bool)
209
Colin Cross35143d02017-11-16 00:11:20 -0800210 ctx.VisitDirectDepsBlueprint(func(module blueprint.Module) {
Colin Cross08f15ab2018-10-04 23:29:14 -0700211 switch tag := ctx.OtherModuleDependencyTag(module).(type) {
212 case hostToolDependencyTag:
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700213 tool := ctx.OtherModuleName(module)
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700214 var path android.OptionalPath
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700215
Colin Crossfe17f6f2019-03-28 19:30:56 -0700216 if t, ok := module.(android.HostToolProvider); ok {
Colin Cross35143d02017-11-16 00:11:20 -0800217 if !t.(android.Module).Enabled() {
Colin Cross6510f912017-11-29 00:27:14 -0800218 if ctx.Config().AllowMissingDependencies() {
Colin Cross35143d02017-11-16 00:11:20 -0800219 ctx.AddMissingDependencies([]string{tool})
220 } else {
221 ctx.ModuleErrorf("depends on disabled module %q", tool)
222 }
223 break
224 }
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700225 path = t.HostToolPath()
226 } else if t, ok := module.(bootstrap.GoBinaryTool); ok {
227 if s, err := filepath.Rel(android.PathForOutput(ctx).String(), t.InstallPath()); err == nil {
228 path = android.OptionalPathForPath(android.PathForOutput(ctx, s))
Colin Cross6f080df2016-11-04 15:32:58 -0700229 } else {
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700230 ctx.ModuleErrorf("cannot find path for %q: %v", tool, err)
231 break
Colin Cross6f080df2016-11-04 15:32:58 -0700232 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700233 } else {
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700234 ctx.ModuleErrorf("%q is not a host tool provider", tool)
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700235 break
236 }
237
238 if path.Valid() {
239 g.deps = append(g.deps, path.Path())
Colin Cross08f15ab2018-10-04 23:29:14 -0700240 addLocationLabel(tag.label, []string{path.Path().String()})
Colin Crossc6de83c2019-03-18 12:12:48 -0700241 seenTools[tag.label] = true
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700242 } else {
243 ctx.ModuleErrorf("host tool %q missing output file", tool)
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700244 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700245 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700246 })
Colin Crossc6de83c2019-03-18 12:12:48 -0700247
248 // If AllowMissingDependencies is enabled, the build will not have stopped when
249 // AddFarVariationDependencies was called on a missing tool, which will result in nonsensical
250 // "cmd: unknown location label ..." errors later. Add a dummy file to the local label. The
251 // command that uses this dummy file will never be executed because the rule will be replaced with
252 // an android.Error rule reporting the missing dependencies.
253 if ctx.Config().AllowMissingDependencies() {
254 for _, tool := range g.properties.Tools {
255 if !seenTools[tool] {
256 addLocationLabel(tool, []string{"***missing tool " + tool + "***"})
257 }
258 }
259 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700260 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700261
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700262 if ctx.Failed() {
263 return
264 }
265
Colin Cross08f15ab2018-10-04 23:29:14 -0700266 for _, toolFile := range g.properties.Tool_files {
Colin Cross8a497952019-03-05 22:25:09 -0800267 paths := android.PathsForModuleSrc(ctx, []string{toolFile})
Colin Cross08f15ab2018-10-04 23:29:14 -0700268 g.deps = append(g.deps, paths...)
269 addLocationLabel(toolFile, paths.Strings())
270 }
271
272 var srcFiles android.Paths
273 for _, in := range g.properties.Srcs {
Colin Crossc6de83c2019-03-18 12:12:48 -0700274 paths, missingDeps := android.PathsAndMissingDepsForModuleSrcExcludes(ctx, []string{in}, g.properties.Exclude_srcs)
275 if len(missingDeps) > 0 {
276 if !ctx.Config().AllowMissingDependencies() {
277 panic(fmt.Errorf("should never get here, the missing dependencies %q should have been reported in DepsMutator",
278 missingDeps))
279 }
280
281 // If AllowMissingDependencies is enabled, the build will not have stopped when
282 // the dependency was added on a missing SourceFileProducer module, which will result in nonsensical
283 // "cmd: label ":..." has no files" errors later. Add a dummy file to the local label. The
284 // command that uses this dummy file will never be executed because the rule will be replaced with
285 // an android.Error rule reporting the missing dependencies.
286 ctx.AddMissingDependencies(missingDeps)
287 addLocationLabel(in, []string{"***missing srcs " + in + "***"})
288 } else {
289 srcFiles = append(srcFiles, paths...)
290 addLocationLabel(in, paths.Strings())
291 }
Colin Cross08f15ab2018-10-04 23:29:14 -0700292 }
293
Colin Crossd9c1c8f2019-09-23 15:55:30 -0700294 var copyFrom android.Paths
295 var outputFiles android.WritablePaths
296 var zipArgs strings.Builder
Colin Cross08f15ab2018-10-04 23:29:14 -0700297
Colin Crossd9c1c8f2019-09-23 15:55:30 -0700298 for _, task := range g.taskGenerator(ctx, String(g.properties.Cmd), srcFiles) {
299 for _, out := range task.out {
300 addLocationLabel(out.Rel(), []string{filepath.Join("__SBOX_OUT_DIR__", out.Rel())})
Colin Cross85a2e892018-07-09 09:45:06 -0700301 }
302
Colin Crossd9c1c8f2019-09-23 15:55:30 -0700303 referencedDepfile := false
304
305 rawCommand, err := android.Expand(task.cmd, func(name string) (string, error) {
306 // report the error directly without returning an error to android.Expand to catch multiple errors in a
307 // single run
308 reportError := func(fmt string, args ...interface{}) (string, error) {
309 ctx.PropertyErrorf("cmd", fmt, args...)
310 return "SOONG_ERROR", nil
Colin Cross6f080df2016-11-04 15:32:58 -0700311 }
Colin Crossd9c1c8f2019-09-23 15:55:30 -0700312
313 switch name {
314 case "location":
315 if len(g.properties.Tools) == 0 && len(g.properties.Tool_files) == 0 {
316 return reportError("at least one `tools` or `tool_files` is required if $(location) is used")
Colin Cross6f080df2016-11-04 15:32:58 -0700317 }
Colin Crossd9c1c8f2019-09-23 15:55:30 -0700318 paths := locationLabels[firstLabel]
319 if len(paths) == 0 {
320 return reportError("default label %q has no files", firstLabel)
321 } else if len(paths) > 1 {
322 return reportError("default label %q has multiple files, use $(locations %s) to reference it",
323 firstLabel, firstLabel)
Colin Cross08f15ab2018-10-04 23:29:14 -0700324 }
Colin Crossd9c1c8f2019-09-23 15:55:30 -0700325 return locationLabels[firstLabel][0], nil
326 case "in":
327 return "${in}", nil
328 case "out":
329 return "__SBOX_OUT_FILES__", nil
330 case "depfile":
331 referencedDepfile = true
332 if !Bool(g.properties.Depfile) {
333 return reportError("$(depfile) used without depfile property")
334 }
335 return "__SBOX_DEPFILE__", nil
336 case "genDir":
337 return "__SBOX_OUT_DIR__", nil
338 default:
339 if strings.HasPrefix(name, "location ") {
340 label := strings.TrimSpace(strings.TrimPrefix(name, "location "))
341 if paths, ok := locationLabels[label]; ok {
342 if len(paths) == 0 {
343 return reportError("label %q has no files", label)
344 } else if len(paths) > 1 {
345 return reportError("label %q has multiple files, use $(locations %s) to reference it",
346 label, label)
347 }
348 return paths[0], nil
349 } else {
350 return reportError("unknown location label %q", label)
351 }
352 } else if strings.HasPrefix(name, "locations ") {
353 label := strings.TrimSpace(strings.TrimPrefix(name, "locations "))
354 if paths, ok := locationLabels[label]; ok {
355 if len(paths) == 0 {
356 return reportError("label %q has no files", label)
357 }
358 return strings.Join(paths, " "), nil
359 } else {
360 return reportError("unknown locations label %q", label)
361 }
362 } else {
363 return reportError("unknown variable '$(%s)'", name)
364 }
Colin Cross6f080df2016-11-04 15:32:58 -0700365 }
Colin Crossd9c1c8f2019-09-23 15:55:30 -0700366 })
367
368 if err != nil {
369 ctx.PropertyErrorf("cmd", "%s", err.Error())
370 return
Colin Cross6f080df2016-11-04 15:32:58 -0700371 }
Colin Cross6f080df2016-11-04 15:32:58 -0700372
Colin Crossd9c1c8f2019-09-23 15:55:30 -0700373 if Bool(g.properties.Depfile) && !referencedDepfile {
374 ctx.PropertyErrorf("cmd", "specified depfile=true but did not include a reference to '${depfile}' in cmd")
375 return
376 }
377
378 // tell the sbox command which directory to use as its sandbox root
379 buildDir := android.PathForOutput(ctx).String()
380 sandboxPath := shared.TempDirForOutDir(buildDir)
381
382 // recall that Sprintf replaces percent sign expressions, whereas dollar signs expressions remain as written,
383 // to be replaced later by ninja_strings.go
384 depfilePlaceholder := ""
385 if Bool(g.properties.Depfile) {
386 depfilePlaceholder = "$depfileArgs"
387 }
388
389 // Escape the command for the shell
390 rawCommand = "'" + strings.Replace(rawCommand, "'", `'\''`, -1) + "'"
391 g.rawCommands = append(g.rawCommands, rawCommand)
392 sandboxCommand := fmt.Sprintf("rm -rf %s && $sboxCmd --sandbox-path %s --output-root %s -c %s %s $allouts",
393 task.genDir, sandboxPath, task.genDir, rawCommand, depfilePlaceholder)
394
395 ruleParams := blueprint.RuleParams{
396 Command: sandboxCommand,
397 CommandDeps: []string{"$sboxCmd"},
398 }
399 args := []string{"allouts"}
400 if Bool(g.properties.Depfile) {
401 ruleParams.Deps = blueprint.DepsGCC
402 args = append(args, "depfileArgs")
403 }
404 name := "generator"
405 if task.shards > 1 {
406 name += strconv.Itoa(task.shard)
407 }
408 rule := ctx.Rule(pctx, name, ruleParams, args...)
409
410 g.generateSourceFile(ctx, task, rule)
411
412 if len(task.copyTo) > 0 {
413 outputFiles = append(outputFiles, task.copyTo...)
414 copyFrom = append(copyFrom, task.out.Paths()...)
415 zipArgs.WriteString(" -C " + task.genDir.String())
416 zipArgs.WriteString(android.JoinWithPrefix(task.out.Strings(), " -f "))
417 } else {
418 outputFiles = append(outputFiles, task.out...)
419 }
Colin Cross6f080df2016-11-04 15:32:58 -0700420 }
421
Colin Crossd9c1c8f2019-09-23 15:55:30 -0700422 if len(copyFrom) > 0 {
423 ctx.Build(pctx, android.BuildParams{
424 Rule: gensrcsMerge,
425 Implicits: copyFrom,
426 Outputs: outputFiles,
427 Args: map[string]string{
428 "zipArgs": zipArgs.String(),
429 "tmpZip": android.PathForModuleGen(ctx, g.subDir+".zip").String(),
430 "genDir": android.PathForModuleGen(ctx, g.subDir).String(),
431 },
432 })
Colin Cross85a2e892018-07-09 09:45:06 -0700433 }
434
Colin Crossd9c1c8f2019-09-23 15:55:30 -0700435 g.outputFiles = outputFiles.Paths()
436 if len(g.outputFiles) > 0 {
437 g.outputDeps = append(g.outputDeps, g.outputFiles[0])
Jeff Gaston02a684b2017-10-27 14:59:27 -0700438 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700439}
440
Colin Crossd9c1c8f2019-09-23 15:55:30 -0700441func (g *Module) generateSourceFile(ctx android.ModuleContext, task generateTask, rule blueprint.Rule) {
Colin Cross67a5c132017-05-09 13:45:28 -0700442 desc := "generate"
Colin Cross15e86d92017-10-20 15:07:08 -0700443 if len(task.out) == 0 {
444 ctx.ModuleErrorf("must have at least one output file")
445 return
446 }
Colin Cross67a5c132017-05-09 13:45:28 -0700447 if len(task.out) == 1 {
448 desc += " " + task.out[0].Base()
449 }
450
Jeff Gaston02a684b2017-10-27 14:59:27 -0700451 var depFile android.ModuleGenPath
Nan Zhangea568a42017-11-08 21:20:04 -0800452 if Bool(g.properties.Depfile) {
Jeff Gaston02a684b2017-10-27 14:59:27 -0700453 depFile = android.PathForModuleGen(ctx, task.out[0].Rel()+".d")
454 }
455
Colin Crossd9c1c8f2019-09-23 15:55:30 -0700456 if task.shards > 1 {
457 desc += " " + strconv.Itoa(task.shard)
458 }
459
Colin Crossae887032017-10-23 17:16:14 -0700460 params := android.BuildParams{
Colin Crossd9c1c8f2019-09-23 15:55:30 -0700461 Rule: rule,
462 Description: desc,
Colin Cross15e86d92017-10-20 15:07:08 -0700463 Output: task.out[0],
464 ImplicitOutputs: task.out[1:],
465 Inputs: task.in,
466 Implicits: g.deps,
467 Args: map[string]string{
Colin Crossbaccf5b2018-02-21 14:07:48 -0800468 "allouts": strings.Join(task.sandboxOuts, " "),
Colin Cross15e86d92017-10-20 15:07:08 -0700469 },
Colin Cross33bfb0a2016-11-21 17:23:08 -0800470 }
Nan Zhangea568a42017-11-08 21:20:04 -0800471 if Bool(g.properties.Depfile) {
Jeff Gaston02a684b2017-10-27 14:59:27 -0700472 params.Depfile = android.PathForModuleGen(ctx, task.out[0].Rel()+".d")
473 params.Args["depfileArgs"] = "--depfile-out " + depFile.String()
Colin Cross33bfb0a2016-11-21 17:23:08 -0800474 }
Jeff Gaston02a684b2017-10-27 14:59:27 -0700475
Colin Crossae887032017-10-23 17:16:14 -0700476 ctx.Build(pctx, params)
Colin Crossd350ecd2015-04-28 13:25:36 -0700477}
478
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700479// Collect information for opening IDE project files in java/jdeps.go.
480func (g *Module) IDEInfo(dpInfo *android.IdeInfo) {
481 dpInfo.Srcs = append(dpInfo.Srcs, g.Srcs().Strings()...)
482 for _, src := range g.properties.Srcs {
483 if strings.HasPrefix(src, ":") {
484 src = strings.Trim(src, ":")
485 dpInfo.Deps = append(dpInfo.Deps, src)
486 }
487 }
488}
489
Colin Crossa4ad2b02019-03-18 22:15:32 -0700490func (g *Module) AndroidMk() android.AndroidMkData {
491 return android.AndroidMkData{
492 Include: "$(BUILD_PHONY_PACKAGE)",
493 Class: "FAKE",
494 OutputFile: android.OptionalPathForPath(g.outputFiles[0]),
495 SubName: g.subName,
496 Extra: []android.AndroidMkExtraFunc{
497 func(w io.Writer, outputFile android.Path) {
Colin Crossd9c1c8f2019-09-23 15:55:30 -0700498 fmt.Fprintln(w, "LOCAL_ADDITIONAL_DEPENDENCIES :=", strings.Join(g.outputDeps.Strings(), " "))
Colin Crossa4ad2b02019-03-18 22:15:32 -0700499 },
500 },
501 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
502 android.WriteAndroidMkData(w, data)
503 if data.SubName != "" {
504 fmt.Fprintln(w, ".PHONY:", name)
505 fmt.Fprintln(w, name, ":", name+g.subName)
506 }
507 },
508 }
509}
510
Jeff Gaston437d23c2017-11-08 12:38:00 -0800511func generatorFactory(taskGenerator taskFunc, props ...interface{}) *Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700512 module := &Module{
Jeff Gaston437d23c2017-11-08 12:38:00 -0800513 taskGenerator: taskGenerator,
Colin Crossd350ecd2015-04-28 13:25:36 -0700514 }
515
Colin Cross36242852017-06-23 15:06:31 -0700516 module.AddProperties(props...)
517 module.AddProperties(&module.properties)
Colin Crossd350ecd2015-04-28 13:25:36 -0700518
Colin Cross36242852017-06-23 15:06:31 -0700519 return module
Colin Crossd350ecd2015-04-28 13:25:36 -0700520}
521
Colin Crossbaccf5b2018-02-21 14:07:48 -0800522// replace "out" with "__SBOX_OUT_DIR__/<the value of ${out}>"
523func pathToSandboxOut(path android.Path, genDir android.Path) string {
524 relOut, err := filepath.Rel(genDir.String(), path.String())
525 if err != nil {
526 panic(fmt.Sprintf("Could not make ${out} relative: %v", err))
527 }
528 return filepath.Join("__SBOX_OUT_DIR__", relOut)
529
530}
531
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700532func NewGenSrcs() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700533 properties := &genSrcsProperties{}
534
Colin Crossd9c1c8f2019-09-23 15:55:30 -0700535 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
536 genDir := android.PathForModuleGen(ctx, "gensrcs")
537 shardSize := defaultShardSize
538 if s := properties.Shard_size; s != nil {
539 shardSize = int(*s)
540 }
Jeff Gaston437d23c2017-11-08 12:38:00 -0800541
Colin Crossd9c1c8f2019-09-23 15:55:30 -0700542 shards := android.ShardPaths(srcFiles, shardSize)
543 var generateTasks []generateTask
Colin Crossbaccf5b2018-02-21 14:07:48 -0800544
Colin Crossd9c1c8f2019-09-23 15:55:30 -0700545 for i, shard := range shards {
546 var commands []string
547 var outFiles android.WritablePaths
548 var copyTo android.WritablePaths
549 var shardDir android.WritablePath
550 var sandboxOuts []string
551
552 if len(shards) > 1 {
553 shardDir = android.PathForModuleGen(ctx, strconv.Itoa(i))
554 } else {
555 shardDir = genDir
Jeff Gaston437d23c2017-11-08 12:38:00 -0800556 }
557
Colin Crossd9c1c8f2019-09-23 15:55:30 -0700558 for _, in := range shard {
559 outFile := android.GenPathWithExt(ctx, "gensrcs", in, String(properties.Output_extension))
560 sandboxOutfile := pathToSandboxOut(outFile, genDir)
Jeff Gaston437d23c2017-11-08 12:38:00 -0800561
Colin Crossd9c1c8f2019-09-23 15:55:30 -0700562 if len(shards) > 1 {
563 shardFile := android.GenPathWithExt(ctx, strconv.Itoa(i), in, String(properties.Output_extension))
564 copyTo = append(copyTo, outFile)
565 outFile = shardFile
566 }
567
568 outFiles = append(outFiles, outFile)
569 sandboxOuts = append(sandboxOuts, sandboxOutfile)
570
571 command, err := android.Expand(rawCommand, func(name string) (string, error) {
572 switch name {
573 case "in":
574 return in.String(), nil
575 case "out":
576 return sandboxOutfile, nil
577 default:
578 return "$(" + name + ")", nil
579 }
580 })
581 if err != nil {
582 ctx.PropertyErrorf("cmd", err.Error())
583 }
584
585 // escape the command in case for example it contains '#', an odd number of '"', etc
586 command = fmt.Sprintf("bash -c %v", proptools.ShellEscape(command))
587 commands = append(commands, command)
588 }
589 fullCommand := strings.Join(commands, " && ")
590
591 generateTasks = append(generateTasks, generateTask{
592 in: shard,
593 out: outFiles,
594 copyTo: copyTo,
595 genDir: shardDir,
596 sandboxOuts: sandboxOuts,
597 cmd: fullCommand,
598 shard: i,
599 shards: len(shards),
600 })
Jeff Gaston437d23c2017-11-08 12:38:00 -0800601 }
Colin Crossd9c1c8f2019-09-23 15:55:30 -0700602
603 return generateTasks
Colin Crossd350ecd2015-04-28 13:25:36 -0700604 }
605
Colin Crossd9c1c8f2019-09-23 15:55:30 -0700606 g := generatorFactory(taskGenerator, properties)
607 g.subDir = "gensrcs"
608 return g
Colin Crossd350ecd2015-04-28 13:25:36 -0700609}
610
Colin Cross54190b32017-10-09 15:34:10 -0700611func GenSrcsFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700612 m := NewGenSrcs()
613 android.InitAndroidModule(m)
614 return m
615}
616
Colin Crossd350ecd2015-04-28 13:25:36 -0700617type genSrcsProperties struct {
Colin Cross7d5136f2015-05-11 13:39:40 -0700618 // extension that will be substituted for each output file
Nan Zhanga5e7cb42017-11-09 22:42:32 -0800619 Output_extension *string
Colin Crossd9c1c8f2019-09-23 15:55:30 -0700620
621 // maximum number of files that will be passed on a single command line.
622 Shard_size *int64
Colin Cross5049f022015-03-18 13:28:46 -0700623}
624
Colin Crossd9c1c8f2019-09-23 15:55:30 -0700625const defaultShardSize = 100
626
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700627func NewGenRule() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700628 properties := &genRuleProperties{}
Colin Cross5049f022015-03-18 13:28:46 -0700629
Colin Crossd9c1c8f2019-09-23 15:55:30 -0700630 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) []generateTask {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700631 outs := make(android.WritablePaths, len(properties.Out))
Colin Crossbaccf5b2018-02-21 14:07:48 -0800632 sandboxOuts := make([]string, len(properties.Out))
633 genDir := android.PathForModuleGen(ctx)
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700634 for i, out := range properties.Out {
635 outs[i] = android.PathForModuleGen(ctx, out)
Colin Crossbaccf5b2018-02-21 14:07:48 -0800636 sandboxOuts[i] = pathToSandboxOut(outs[i], genDir)
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700637 }
Colin Crossd9c1c8f2019-09-23 15:55:30 -0700638 return []generateTask{{
Colin Crossbaccf5b2018-02-21 14:07:48 -0800639 in: srcFiles,
640 out: outs,
Colin Crossd9c1c8f2019-09-23 15:55:30 -0700641 genDir: android.PathForModuleGen(ctx),
Colin Crossbaccf5b2018-02-21 14:07:48 -0800642 sandboxOuts: sandboxOuts,
643 cmd: rawCommand,
Colin Crossd9c1c8f2019-09-23 15:55:30 -0700644 }}
Colin Cross5049f022015-03-18 13:28:46 -0700645 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700646
Jeff Gaston437d23c2017-11-08 12:38:00 -0800647 return generatorFactory(taskGenerator, properties)
Colin Cross5049f022015-03-18 13:28:46 -0700648}
649
Colin Cross54190b32017-10-09 15:34:10 -0700650func GenRuleFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700651 m := NewGenRule()
652 android.InitAndroidModule(m)
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800653 android.InitDefaultableModule(m)
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700654 return m
655}
656
Colin Crossd350ecd2015-04-28 13:25:36 -0700657type genRuleProperties struct {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700658 // names of the output files that will be generated
Colin Crossef354482018-10-23 11:27:50 -0700659 Out []string `android:"arch_variant"`
Colin Cross5049f022015-03-18 13:28:46 -0700660}
Nan Zhangea568a42017-11-08 21:20:04 -0800661
662var Bool = proptools.Bool
663var String = proptools.String
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800664
665//
666// Defaults
667//
668type Defaults struct {
669 android.ModuleBase
670 android.DefaultsModuleBase
671}
672
673func (*Defaults) GenerateAndroidBuildActions(ctx android.ModuleContext) {
674}
675
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800676func defaultsFactory() android.Module {
677 return DefaultsFactory()
678}
679
680func DefaultsFactory(props ...interface{}) android.Module {
681 module := &Defaults{}
682
683 module.AddProperties(props...)
684 module.AddProperties(
685 &generatorProperties{},
686 &genRuleProperties{},
687 )
688
689 android.InitDefaultsModule(module)
690
691 return module
692}