blob: cf0b484e19f5558275f2678871be2ca08fa4a3af [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 Cross6f080df2016-11-04 15:32:58 -070020 "strings"
Dan Willemsen3f4539b2016-09-28 16:19:10 -070021
Colin Cross70b40592015-03-23 12:57:34 -070022 "github.com/google/blueprint"
Dan Willemsen8eded0a2017-09-13 16:07:44 -070023 "github.com/google/blueprint/bootstrap"
Nan Zhangea568a42017-11-08 21:20:04 -080024 "github.com/google/blueprint/proptools"
Colin Cross5049f022015-03-18 13:28:46 -070025
Colin Cross635c3b02016-05-18 15:37:25 -070026 "android/soong/android"
Jeff Gastonefc1b412017-03-29 17:29:06 -070027 "android/soong/shared"
28 "path/filepath"
Colin Cross5049f022015-03-18 13:28:46 -070029)
30
Colin Cross463a90e2015-06-17 14:20:06 -070031func init() {
Jaewoong Jung98716bd2018-12-10 08:13:18 -080032 android.RegisterModuleType("genrule_defaults", defaultsFactory)
33
Colin Cross54190b32017-10-09 15:34:10 -070034 android.RegisterModuleType("gensrcs", GenSrcsFactory)
35 android.RegisterModuleType("genrule", GenRuleFactory)
Colin Cross463a90e2015-06-17 14:20:06 -070036}
37
Colin Cross5049f022015-03-18 13:28:46 -070038var (
Colin Cross635c3b02016-05-18 15:37:25 -070039 pctx = android.NewPackageContext("android/soong/genrule")
Colin Cross5049f022015-03-18 13:28:46 -070040)
41
Jeff Gastonefc1b412017-03-29 17:29:06 -070042func init() {
Dan Willemsenddf504c2019-08-09 16:21:29 -070043 pctx.Import("android/soong/android")
Jeff Gastonefc1b412017-03-29 17:29:06 -070044 pctx.HostBinToolVariable("sboxCmd", "sbox")
45}
46
Colin Cross5049f022015-03-18 13:28:46 -070047type SourceFileGenerator interface {
Colin Cross635c3b02016-05-18 15:37:25 -070048 GeneratedSourceFiles() android.Paths
Colin Cross5ed99c62016-11-22 12:55:55 -080049 GeneratedHeaderDirs() android.Paths
Dan Willemsen9da9d492018-02-21 18:28:18 -080050 GeneratedDeps() android.Paths
Colin Cross5049f022015-03-18 13:28:46 -070051}
52
Colin Crossfe17f6f2019-03-28 19:30:56 -070053// Alias for android.HostToolProvider
54// Deprecated: use android.HostToolProvider instead.
Colin Crossd350ecd2015-04-28 13:25:36 -070055type HostToolProvider interface {
Colin Crossfe17f6f2019-03-28 19:30:56 -070056 android.HostToolProvider
Colin Crossd350ecd2015-04-28 13:25:36 -070057}
Colin Cross5049f022015-03-18 13:28:46 -070058
Dan Willemsend6ba0d52017-09-13 15:46:47 -070059type hostToolDependencyTag struct {
60 blueprint.BaseDependencyTag
Colin Cross08f15ab2018-10-04 23:29:14 -070061 label string
Dan Willemsend6ba0d52017-09-13 15:46:47 -070062}
63
Colin Cross7d5136f2015-05-11 13:39:40 -070064type generatorProperties struct {
Jeff Gastonefc1b412017-03-29 17:29:06 -070065 // The command to run on one or more input files. Cmd supports substitution of a few variables
66 // (the actual substitution is implemented in GenerateAndroidBuildActions below)
67 //
68 // Available variables for substitution:
69 //
Colin Cross2296f5b2017-10-17 21:38:14 -070070 // $(location): the path to the first entry in tools or tool_files
Colin Cross08f15ab2018-10-04 23:29:14 -070071 // $(location <label>): the path to the tool, tool_file, input or output with name <label>
Colin Cross2296f5b2017-10-17 21:38:14 -070072 // $(in): one or more input files
73 // $(out): a single output file
74 // $(depfile): a file to which dependencies will be written, if the depfile property is set to true
75 // $(genDir): the sandbox directory for this tool; contains $(out)
76 // $$: a literal $
Colin Cross6f080df2016-11-04 15:32:58 -070077 //
Jeff Gastonefc1b412017-03-29 17:29:06 -070078 // All files used must be declared as inputs (to ensure proper up-to-date checks).
79 // Use "$(in)" directly in Cmd to ensure that all inputs used are declared.
Nan Zhangea568a42017-11-08 21:20:04 -080080 Cmd *string
Colin Cross7d5136f2015-05-11 13:39:40 -070081
Colin Cross33bfb0a2016-11-21 17:23:08 -080082 // Enable reading a file containing dependencies in gcc format after the command completes
Nan Zhangea568a42017-11-08 21:20:04 -080083 Depfile *bool
Colin Cross33bfb0a2016-11-21 17:23:08 -080084
Colin Cross6f080df2016-11-04 15:32:58 -070085 // name of the modules (if any) that produces the host executable. Leave empty for
Colin Cross7d5136f2015-05-11 13:39:40 -070086 // prebuilts or scripts that do not need a module to build them.
Colin Cross6f080df2016-11-04 15:32:58 -070087 Tools []string
Dan Willemsenf7f3d692016-04-20 14:54:32 -070088
89 // Local file that is used as the tool
Colin Cross27b922f2019-03-04 22:35:41 -080090 Tool_files []string `android:"path"`
Colin Cross5ed99c62016-11-22 12:55:55 -080091
92 // List of directories to export generated headers from
93 Export_include_dirs []string
Colin Cross708c4242017-01-13 18:05:49 -080094
95 // list of input files
Colin Cross27b922f2019-03-04 22:35:41 -080096 Srcs []string `android:"path,arch_variant"`
Dan Willemseneefa0262018-11-17 14:01:18 -080097
98 // input files to exclude
Colin Cross27b922f2019-03-04 22:35:41 -080099 Exclude_srcs []string `android:"path,arch_variant"`
Colin Cross7d5136f2015-05-11 13:39:40 -0700100}
101
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700102type Module struct {
Colin Cross635c3b02016-05-18 15:37:25 -0700103 android.ModuleBase
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800104 android.DefaultableModuleBase
Jiyong Parkfc752ca2019-06-12 13:27:29 +0900105 android.ApexModuleBase
Colin Crossd350ecd2015-04-28 13:25:36 -0700106
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700107 // For other packages to make their own genrules with extra
108 // properties
109 Extra interface{}
110
Colin Cross7d5136f2015-05-11 13:39:40 -0700111 properties generatorProperties
Colin Crossd350ecd2015-04-28 13:25:36 -0700112
Jeff Gaston437d23c2017-11-08 12:38:00 -0800113 taskGenerator taskFunc
Colin Crossd350ecd2015-04-28 13:25:36 -0700114
Colin Cross2a076922018-10-04 23:28:25 -0700115 deps android.Paths
116 rule blueprint.Rule
117 rawCommand string
Colin Crossd350ecd2015-04-28 13:25:36 -0700118
Colin Cross5ed99c62016-11-22 12:55:55 -0800119 exportedIncludeDirs android.Paths
Dan Willemsenb40aab62016-04-20 14:21:14 -0700120
Colin Cross635c3b02016-05-18 15:37:25 -0700121 outputFiles android.Paths
Dan Willemsen9da9d492018-02-21 18:28:18 -0800122 outputDeps android.Paths
Colin Crossa4ad2b02019-03-18 22:15:32 -0700123
124 subName string
Colin Crossd350ecd2015-04-28 13:25:36 -0700125}
126
Jeff Gaston437d23c2017-11-08 12:38:00 -0800127type taskFunc func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) generateTask
Colin Crossd350ecd2015-04-28 13:25:36 -0700128
129type generateTask struct {
Colin Crossbaccf5b2018-02-21 14:07:48 -0800130 in android.Paths
131 out android.WritablePaths
132 sandboxOuts []string
133 cmd string
Colin Crossd350ecd2015-04-28 13:25:36 -0700134}
135
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700136func (g *Module) GeneratedSourceFiles() android.Paths {
Colin Crossd350ecd2015-04-28 13:25:36 -0700137 return g.outputFiles
138}
139
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700140func (g *Module) Srcs() android.Paths {
Nan Zhange42777a2018-03-27 16:19:42 -0700141 return append(android.Paths{}, g.outputFiles...)
Colin Cross068e0fe2016-12-13 15:23:47 -0800142}
143
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700144func (g *Module) GeneratedHeaderDirs() android.Paths {
Colin Cross5ed99c62016-11-22 12:55:55 -0800145 return g.exportedIncludeDirs
Dan Willemsenb40aab62016-04-20 14:21:14 -0700146}
147
Dan Willemsen9da9d492018-02-21 18:28:18 -0800148func (g *Module) GeneratedDeps() android.Paths {
149 return g.outputDeps
150}
151
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700152func (g *Module) DepsMutator(ctx android.BottomUpMutatorContext) {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700153 if g, ok := ctx.Module().(*Module); ok {
Colin Cross08f15ab2018-10-04 23:29:14 -0700154 for _, tool := range g.properties.Tools {
155 tag := hostToolDependencyTag{label: tool}
156 if m := android.SrcIsModule(tool); m != "" {
157 tool = m
158 }
Dan Willemsen490fd492015-11-24 17:53:15 -0800159 ctx.AddFarVariationDependencies([]blueprint.Variation{
Dan Willemsen59339a22018-07-22 21:18:45 -0700160 {Mutator: "arch", Variation: ctx.Config().BuildOsVariant},
Colin Cross08f15ab2018-10-04 23:29:14 -0700161 }, tag, tool)
Colin Cross6362e272015-10-29 15:25:03 -0700162 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700163 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700164}
165
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700166func (g *Module) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Colin Crossa4ad2b02019-03-18 22:15:32 -0700167 g.subName = ctx.ModuleSubDir()
168
Colin Cross5ed99c62016-11-22 12:55:55 -0800169 if len(g.properties.Export_include_dirs) > 0 {
170 for _, dir := range g.properties.Export_include_dirs {
171 g.exportedIncludeDirs = append(g.exportedIncludeDirs,
172 android.PathForModuleGen(ctx, ctx.ModuleDir(), dir))
173 }
174 } else {
175 g.exportedIncludeDirs = append(g.exportedIncludeDirs, android.PathForModuleGen(ctx, ""))
176 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700177
Colin Cross08f15ab2018-10-04 23:29:14 -0700178 locationLabels := map[string][]string{}
179 firstLabel := ""
180
181 addLocationLabel := func(label string, paths []string) {
182 if firstLabel == "" {
183 firstLabel = label
184 }
185 if _, exists := locationLabels[label]; !exists {
186 locationLabels[label] = paths
187 } else {
188 ctx.ModuleErrorf("multiple labels for %q, %q and %q",
189 label, strings.Join(locationLabels[label], " "), strings.Join(paths, " "))
190 }
191 }
Dan Willemsen3f4539b2016-09-28 16:19:10 -0700192
Colin Cross6f080df2016-11-04 15:32:58 -0700193 if len(g.properties.Tools) > 0 {
Colin Crossba71a3f2019-03-18 12:12:48 -0700194 seenTools := make(map[string]bool)
195
Colin Cross35143d02017-11-16 00:11:20 -0800196 ctx.VisitDirectDepsBlueprint(func(module blueprint.Module) {
Colin Cross08f15ab2018-10-04 23:29:14 -0700197 switch tag := ctx.OtherModuleDependencyTag(module).(type) {
198 case hostToolDependencyTag:
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700199 tool := ctx.OtherModuleName(module)
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700200 var path android.OptionalPath
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700201
Colin Crossfe17f6f2019-03-28 19:30:56 -0700202 if t, ok := module.(android.HostToolProvider); ok {
Colin Cross35143d02017-11-16 00:11:20 -0800203 if !t.(android.Module).Enabled() {
Colin Cross6510f912017-11-29 00:27:14 -0800204 if ctx.Config().AllowMissingDependencies() {
Colin Cross35143d02017-11-16 00:11:20 -0800205 ctx.AddMissingDependencies([]string{tool})
206 } else {
207 ctx.ModuleErrorf("depends on disabled module %q", tool)
208 }
209 break
210 }
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700211 path = t.HostToolPath()
212 } else if t, ok := module.(bootstrap.GoBinaryTool); ok {
213 if s, err := filepath.Rel(android.PathForOutput(ctx).String(), t.InstallPath()); err == nil {
214 path = android.OptionalPathForPath(android.PathForOutput(ctx, s))
Colin Cross6f080df2016-11-04 15:32:58 -0700215 } else {
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700216 ctx.ModuleErrorf("cannot find path for %q: %v", tool, err)
217 break
Colin Cross6f080df2016-11-04 15:32:58 -0700218 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700219 } else {
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700220 ctx.ModuleErrorf("%q is not a host tool provider", tool)
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700221 break
222 }
223
224 if path.Valid() {
225 g.deps = append(g.deps, path.Path())
Colin Cross08f15ab2018-10-04 23:29:14 -0700226 addLocationLabel(tag.label, []string{path.Path().String()})
Colin Crossba71a3f2019-03-18 12:12:48 -0700227 seenTools[tag.label] = true
Dan Willemsen8eded0a2017-09-13 16:07:44 -0700228 } else {
229 ctx.ModuleErrorf("host tool %q missing output file", tool)
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700230 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700231 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700232 })
Colin Crossba71a3f2019-03-18 12:12:48 -0700233
234 // If AllowMissingDependencies is enabled, the build will not have stopped when
235 // AddFarVariationDependencies was called on a missing tool, which will result in nonsensical
236 // "cmd: unknown location label ..." errors later. Add a dummy file to the local label. The
237 // command that uses this dummy file will never be executed because the rule will be replaced with
238 // an android.Error rule reporting the missing dependencies.
239 if ctx.Config().AllowMissingDependencies() {
240 for _, tool := range g.properties.Tools {
241 if !seenTools[tool] {
242 addLocationLabel(tool, []string{"***missing tool " + tool + "***"})
243 }
244 }
245 }
Dan Willemsenf7f3d692016-04-20 14:54:32 -0700246 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700247
Dan Willemsend6ba0d52017-09-13 15:46:47 -0700248 if ctx.Failed() {
249 return
250 }
251
Colin Cross08f15ab2018-10-04 23:29:14 -0700252 for _, toolFile := range g.properties.Tool_files {
Colin Cross8a497952019-03-05 22:25:09 -0800253 paths := android.PathsForModuleSrc(ctx, []string{toolFile})
Colin Cross08f15ab2018-10-04 23:29:14 -0700254 g.deps = append(g.deps, paths...)
255 addLocationLabel(toolFile, paths.Strings())
256 }
257
258 var srcFiles android.Paths
259 for _, in := range g.properties.Srcs {
Colin Crossba71a3f2019-03-18 12:12:48 -0700260 paths, missingDeps := android.PathsAndMissingDepsForModuleSrcExcludes(ctx, []string{in}, g.properties.Exclude_srcs)
261 if len(missingDeps) > 0 {
262 if !ctx.Config().AllowMissingDependencies() {
263 panic(fmt.Errorf("should never get here, the missing dependencies %q should have been reported in DepsMutator",
264 missingDeps))
265 }
266
267 // If AllowMissingDependencies is enabled, the build will not have stopped when
268 // the dependency was added on a missing SourceFileProducer module, which will result in nonsensical
269 // "cmd: label ":..." has no files" errors later. Add a dummy file to the local label. The
270 // command that uses this dummy file will never be executed because the rule will be replaced with
271 // an android.Error rule reporting the missing dependencies.
272 ctx.AddMissingDependencies(missingDeps)
273 addLocationLabel(in, []string{"***missing srcs " + in + "***"})
274 } else {
275 srcFiles = append(srcFiles, paths...)
276 addLocationLabel(in, paths.Strings())
277 }
Colin Cross08f15ab2018-10-04 23:29:14 -0700278 }
279
280 task := g.taskGenerator(ctx, String(g.properties.Cmd), srcFiles)
281
282 for _, out := range task.out {
283 addLocationLabel(out.Rel(), []string{filepath.Join("__SBOX_OUT_DIR__", out.Rel())})
Colin Cross6f080df2016-11-04 15:32:58 -0700284 }
285
Jeff Gaston02a684b2017-10-27 14:59:27 -0700286 referencedDepfile := false
287
Colin Cross2647ced2019-07-11 10:58:17 -0700288 rawCommand, err := android.ExpandNinjaEscaped(task.cmd, func(name string) (string, bool, error) {
Colin Cross85a2e892018-07-09 09:45:06 -0700289 // report the error directly without returning an error to android.Expand to catch multiple errors in a
290 // single run
Colin Cross2647ced2019-07-11 10:58:17 -0700291 reportError := func(fmt string, args ...interface{}) (string, bool, error) {
Colin Cross85a2e892018-07-09 09:45:06 -0700292 ctx.PropertyErrorf("cmd", fmt, args...)
Colin Cross2647ced2019-07-11 10:58:17 -0700293 return "SOONG_ERROR", false, nil
Colin Cross85a2e892018-07-09 09:45:06 -0700294 }
295
Colin Cross6f080df2016-11-04 15:32:58 -0700296 switch name {
297 case "location":
Colin Cross08f15ab2018-10-04 23:29:14 -0700298 if len(g.properties.Tools) == 0 && len(g.properties.Tool_files) == 0 {
Colin Cross85a2e892018-07-09 09:45:06 -0700299 return reportError("at least one `tools` or `tool_files` is required if $(location) is used")
Colin Cross6f080df2016-11-04 15:32:58 -0700300 }
Colin Cross08f15ab2018-10-04 23:29:14 -0700301 paths := locationLabels[firstLabel]
302 if len(paths) == 0 {
303 return reportError("default label %q has no files", firstLabel)
304 } else if len(paths) > 1 {
305 return reportError("default label %q has multiple files, use $(locations %s) to reference it",
306 firstLabel, firstLabel)
307 }
Colin Cross2647ced2019-07-11 10:58:17 -0700308 return locationLabels[firstLabel][0], false, nil
Colin Cross6f080df2016-11-04 15:32:58 -0700309 case "in":
Colin Cross2647ced2019-07-11 10:58:17 -0700310 return "${in}", true, nil
Colin Cross6f080df2016-11-04 15:32:58 -0700311 case "out":
Colin Cross2647ced2019-07-11 10:58:17 -0700312 return "__SBOX_OUT_FILES__", false, nil
Colin Cross33bfb0a2016-11-21 17:23:08 -0800313 case "depfile":
Jeff Gaston02a684b2017-10-27 14:59:27 -0700314 referencedDepfile = true
Nan Zhangea568a42017-11-08 21:20:04 -0800315 if !Bool(g.properties.Depfile) {
Colin Cross85a2e892018-07-09 09:45:06 -0700316 return reportError("$(depfile) used without depfile property")
Colin Cross33bfb0a2016-11-21 17:23:08 -0800317 }
Colin Cross2647ced2019-07-11 10:58:17 -0700318 return "__SBOX_DEPFILE__", false, nil
Colin Cross6f080df2016-11-04 15:32:58 -0700319 case "genDir":
Colin Cross2647ced2019-07-11 10:58:17 -0700320 return "__SBOX_OUT_DIR__", false, nil
Colin Cross6f080df2016-11-04 15:32:58 -0700321 default:
322 if strings.HasPrefix(name, "location ") {
323 label := strings.TrimSpace(strings.TrimPrefix(name, "location "))
Colin Cross08f15ab2018-10-04 23:29:14 -0700324 if paths, ok := locationLabels[label]; ok {
325 if len(paths) == 0 {
326 return reportError("label %q has no files", label)
327 } else if len(paths) > 1 {
328 return reportError("label %q has multiple files, use $(locations %s) to reference it",
329 label, label)
330 }
Colin Cross2647ced2019-07-11 10:58:17 -0700331 return paths[0], false, nil
Colin Cross6f080df2016-11-04 15:32:58 -0700332 } else {
Colin Cross85a2e892018-07-09 09:45:06 -0700333 return reportError("unknown location label %q", label)
Colin Cross6f080df2016-11-04 15:32:58 -0700334 }
Colin Cross08f15ab2018-10-04 23:29:14 -0700335 } else if strings.HasPrefix(name, "locations ") {
336 label := strings.TrimSpace(strings.TrimPrefix(name, "locations "))
337 if paths, ok := locationLabels[label]; ok {
338 if len(paths) == 0 {
339 return reportError("label %q has no files", label)
340 }
Colin Cross2647ced2019-07-11 10:58:17 -0700341 return strings.Join(paths, " "), false, nil
Colin Cross08f15ab2018-10-04 23:29:14 -0700342 } else {
343 return reportError("unknown locations label %q", label)
344 }
345 } else {
346 return reportError("unknown variable '$(%s)'", name)
Colin Cross6f080df2016-11-04 15:32:58 -0700347 }
Colin Cross6f080df2016-11-04 15:32:58 -0700348 }
349 })
350
351 if err != nil {
352 ctx.PropertyErrorf("cmd", "%s", err.Error())
Colin Cross54c5dd52017-04-19 14:23:26 -0700353 return
Colin Cross6f080df2016-11-04 15:32:58 -0700354 }
355
Colin Cross85a2e892018-07-09 09:45:06 -0700356 if Bool(g.properties.Depfile) && !referencedDepfile {
357 ctx.PropertyErrorf("cmd", "specified depfile=true but did not include a reference to '${depfile}' in cmd")
358 }
359
Jeff Gastonefc1b412017-03-29 17:29:06 -0700360 // tell the sbox command which directory to use as its sandbox root
Jeff Gaston193f2fb2017-06-12 15:00:12 -0700361 buildDir := android.PathForOutput(ctx).String()
362 sandboxPath := shared.TempDirForOutDir(buildDir)
Jeff Gastonefc1b412017-03-29 17:29:06 -0700363
364 // recall that Sprintf replaces percent sign expressions, whereas dollar signs expressions remain as written,
365 // to be replaced later by ninja_strings.go
Jeff Gaston02a684b2017-10-27 14:59:27 -0700366 depfilePlaceholder := ""
Nan Zhangea568a42017-11-08 21:20:04 -0800367 if Bool(g.properties.Depfile) {
Jeff Gaston02a684b2017-10-27 14:59:27 -0700368 depfilePlaceholder = "$depfileArgs"
369 }
Jeff Gaston5acec2b2017-11-06 14:15:16 -0800370
Jeff Gaston437d23c2017-11-08 12:38:00 -0800371 genDir := android.PathForModuleGen(ctx)
Jeff Gaston31603062017-12-08 12:45:35 -0800372 // Escape the command for the shell
373 rawCommand = "'" + strings.Replace(rawCommand, "'", `'\''`, -1) + "'"
Colin Cross2a076922018-10-04 23:28:25 -0700374 g.rawCommand = rawCommand
Jeff Gaston31603062017-12-08 12:45:35 -0800375 sandboxCommand := fmt.Sprintf("$sboxCmd --sandbox-path %s --output-root %s -c %s %s $allouts",
376 sandboxPath, genDir, rawCommand, depfilePlaceholder)
Jeff Gastonefc1b412017-03-29 17:29:06 -0700377
Colin Cross33bfb0a2016-11-21 17:23:08 -0800378 ruleParams := blueprint.RuleParams{
Jeff Gastonefc1b412017-03-29 17:29:06 -0700379 Command: sandboxCommand,
380 CommandDeps: []string{"$sboxCmd"},
Colin Cross33bfb0a2016-11-21 17:23:08 -0800381 }
Colin Cross15e86d92017-10-20 15:07:08 -0700382 args := []string{"allouts"}
Nan Zhangea568a42017-11-08 21:20:04 -0800383 if Bool(g.properties.Depfile) {
Colin Cross33bfb0a2016-11-21 17:23:08 -0800384 ruleParams.Deps = blueprint.DepsGCC
Jeff Gaston02a684b2017-10-27 14:59:27 -0700385 args = append(args, "depfileArgs")
Colin Cross33bfb0a2016-11-21 17:23:08 -0800386 }
387 g.rule = ctx.Rule(pctx, "generator", ruleParams, args...)
Colin Cross6f080df2016-11-04 15:32:58 -0700388
Jeff Gaston437d23c2017-11-08 12:38:00 -0800389 g.generateSourceFile(ctx, task)
390
Colin Crossd350ecd2015-04-28 13:25:36 -0700391}
392
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700393func (g *Module) generateSourceFile(ctx android.ModuleContext, task generateTask) {
Colin Cross67a5c132017-05-09 13:45:28 -0700394 desc := "generate"
Colin Cross15e86d92017-10-20 15:07:08 -0700395 if len(task.out) == 0 {
396 ctx.ModuleErrorf("must have at least one output file")
397 return
398 }
Colin Cross67a5c132017-05-09 13:45:28 -0700399 if len(task.out) == 1 {
400 desc += " " + task.out[0].Base()
401 }
402
Jeff Gaston02a684b2017-10-27 14:59:27 -0700403 var depFile android.ModuleGenPath
Nan Zhangea568a42017-11-08 21:20:04 -0800404 if Bool(g.properties.Depfile) {
Jeff Gaston02a684b2017-10-27 14:59:27 -0700405 depFile = android.PathForModuleGen(ctx, task.out[0].Rel()+".d")
406 }
407
Colin Crossae887032017-10-23 17:16:14 -0700408 params := android.BuildParams{
Colin Cross15e86d92017-10-20 15:07:08 -0700409 Rule: g.rule,
410 Description: "generate",
411 Output: task.out[0],
412 ImplicitOutputs: task.out[1:],
413 Inputs: task.in,
414 Implicits: g.deps,
415 Args: map[string]string{
Colin Crossbaccf5b2018-02-21 14:07:48 -0800416 "allouts": strings.Join(task.sandboxOuts, " "),
Colin Cross15e86d92017-10-20 15:07:08 -0700417 },
Colin Cross33bfb0a2016-11-21 17:23:08 -0800418 }
Nan Zhangea568a42017-11-08 21:20:04 -0800419 if Bool(g.properties.Depfile) {
Jeff Gaston02a684b2017-10-27 14:59:27 -0700420 params.Depfile = android.PathForModuleGen(ctx, task.out[0].Rel()+".d")
421 params.Args["depfileArgs"] = "--depfile-out " + depFile.String()
Colin Cross33bfb0a2016-11-21 17:23:08 -0800422 }
Jeff Gaston02a684b2017-10-27 14:59:27 -0700423
Colin Crossae887032017-10-23 17:16:14 -0700424 ctx.Build(pctx, params)
Colin Crossd350ecd2015-04-28 13:25:36 -0700425
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700426 for _, outputFile := range task.out {
427 g.outputFiles = append(g.outputFiles, outputFile)
428 }
Dan Willemsenddf504c2019-08-09 16:21:29 -0700429
430 // For <= 6 outputs, just embed those directly in the users. Right now, that covers >90% of
431 // the genrules on AOSP. That will make things simpler to look at the graph in the common
432 // case. For larger sets of outputs, inject a phony target in between to limit ninja file
433 // growth.
434 if len(task.out) <= 6 {
435 g.outputDeps = g.outputFiles
436 } else {
437 phonyFile := android.PathForModuleGen(ctx, "genrule-phony")
438
439 ctx.Build(pctx, android.BuildParams{
440 Rule: android.Phony,
441 Output: phonyFile,
442 Inputs: g.outputFiles,
443 })
444
445 g.outputDeps = android.Paths{phonyFile}
446 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700447}
448
Brandon Lee5d45c6f2018-08-15 15:35:38 -0700449// Collect information for opening IDE project files in java/jdeps.go.
450func (g *Module) IDEInfo(dpInfo *android.IdeInfo) {
451 dpInfo.Srcs = append(dpInfo.Srcs, g.Srcs().Strings()...)
452 for _, src := range g.properties.Srcs {
453 if strings.HasPrefix(src, ":") {
454 src = strings.Trim(src, ":")
455 dpInfo.Deps = append(dpInfo.Deps, src)
456 }
457 }
458}
459
Colin Crossa4ad2b02019-03-18 22:15:32 -0700460func (g *Module) AndroidMk() android.AndroidMkData {
461 return android.AndroidMkData{
462 Include: "$(BUILD_PHONY_PACKAGE)",
463 Class: "FAKE",
464 OutputFile: android.OptionalPathForPath(g.outputFiles[0]),
465 SubName: g.subName,
466 Extra: []android.AndroidMkExtraFunc{
467 func(w io.Writer, outputFile android.Path) {
468 fmt.Fprintln(w, "LOCAL_ADDITIONAL_DEPENDENCIES :=", strings.Join(g.outputFiles.Strings(), " "))
469 },
470 },
471 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
472 android.WriteAndroidMkData(w, data)
473 if data.SubName != "" {
474 fmt.Fprintln(w, ".PHONY:", name)
475 fmt.Fprintln(w, name, ":", name+g.subName)
476 }
477 },
478 }
479}
480
Jeff Gaston437d23c2017-11-08 12:38:00 -0800481func generatorFactory(taskGenerator taskFunc, props ...interface{}) *Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700482 module := &Module{
Jeff Gaston437d23c2017-11-08 12:38:00 -0800483 taskGenerator: taskGenerator,
Colin Crossd350ecd2015-04-28 13:25:36 -0700484 }
485
Colin Cross36242852017-06-23 15:06:31 -0700486 module.AddProperties(props...)
487 module.AddProperties(&module.properties)
Colin Crossd350ecd2015-04-28 13:25:36 -0700488
Colin Cross36242852017-06-23 15:06:31 -0700489 return module
Colin Crossd350ecd2015-04-28 13:25:36 -0700490}
491
Colin Crossbaccf5b2018-02-21 14:07:48 -0800492// replace "out" with "__SBOX_OUT_DIR__/<the value of ${out}>"
493func pathToSandboxOut(path android.Path, genDir android.Path) string {
494 relOut, err := filepath.Rel(genDir.String(), path.String())
495 if err != nil {
496 panic(fmt.Sprintf("Could not make ${out} relative: %v", err))
497 }
498 return filepath.Join("__SBOX_OUT_DIR__", relOut)
499
500}
501
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700502func NewGenSrcs() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700503 properties := &genSrcsProperties{}
504
Jeff Gaston437d23c2017-11-08 12:38:00 -0800505 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) generateTask {
506 commands := []string{}
507 outFiles := android.WritablePaths{}
Colin Crossbaccf5b2018-02-21 14:07:48 -0800508 genDir := android.PathForModuleGen(ctx)
509 sandboxOuts := []string{}
Colin Crossd350ecd2015-04-28 13:25:36 -0700510 for _, in := range srcFiles {
Nan Zhanga5e7cb42017-11-09 22:42:32 -0800511 outFile := android.GenPathWithExt(ctx, "", in, String(properties.Output_extension))
Jeff Gaston437d23c2017-11-08 12:38:00 -0800512 outFiles = append(outFiles, outFile)
513
Colin Crossbaccf5b2018-02-21 14:07:48 -0800514 sandboxOutfile := pathToSandboxOut(outFile, genDir)
515 sandboxOuts = append(sandboxOuts, sandboxOutfile)
516
Jeff Gaston437d23c2017-11-08 12:38:00 -0800517 command, err := android.Expand(rawCommand, func(name string) (string, error) {
518 switch name {
519 case "in":
520 return in.String(), nil
521 case "out":
522 return sandboxOutfile, nil
523 default:
524 return "$(" + name + ")", nil
525 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700526 })
Jeff Gaston437d23c2017-11-08 12:38:00 -0800527 if err != nil {
528 ctx.PropertyErrorf("cmd", err.Error())
529 }
530
531 // escape the command in case for example it contains '#', an odd number of '"', etc
Colin Cross0b9f31f2019-02-28 11:00:01 -0800532 command = fmt.Sprintf("bash -c %v", proptools.ShellEscape(command))
Jeff Gaston437d23c2017-11-08 12:38:00 -0800533 commands = append(commands, command)
Colin Crossd350ecd2015-04-28 13:25:36 -0700534 }
Jeff Gaston437d23c2017-11-08 12:38:00 -0800535 fullCommand := strings.Join(commands, " && ")
536
537 return generateTask{
Colin Crossbaccf5b2018-02-21 14:07:48 -0800538 in: srcFiles,
539 out: outFiles,
540 sandboxOuts: sandboxOuts,
541 cmd: fullCommand,
Jeff Gaston437d23c2017-11-08 12:38:00 -0800542 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700543 }
544
Jeff Gaston437d23c2017-11-08 12:38:00 -0800545 return generatorFactory(taskGenerator, properties)
Colin Crossd350ecd2015-04-28 13:25:36 -0700546}
547
Colin Cross54190b32017-10-09 15:34:10 -0700548func GenSrcsFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700549 m := NewGenSrcs()
550 android.InitAndroidModule(m)
551 return m
552}
553
Colin Crossd350ecd2015-04-28 13:25:36 -0700554type genSrcsProperties struct {
Colin Cross7d5136f2015-05-11 13:39:40 -0700555 // extension that will be substituted for each output file
Nan Zhanga5e7cb42017-11-09 22:42:32 -0800556 Output_extension *string
Colin Cross5049f022015-03-18 13:28:46 -0700557}
558
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700559func NewGenRule() *Module {
Colin Crossd350ecd2015-04-28 13:25:36 -0700560 properties := &genRuleProperties{}
Colin Cross5049f022015-03-18 13:28:46 -0700561
Jeff Gaston437d23c2017-11-08 12:38:00 -0800562 taskGenerator := func(ctx android.ModuleContext, rawCommand string, srcFiles android.Paths) generateTask {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700563 outs := make(android.WritablePaths, len(properties.Out))
Colin Crossbaccf5b2018-02-21 14:07:48 -0800564 sandboxOuts := make([]string, len(properties.Out))
565 genDir := android.PathForModuleGen(ctx)
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700566 for i, out := range properties.Out {
567 outs[i] = android.PathForModuleGen(ctx, out)
Colin Crossbaccf5b2018-02-21 14:07:48 -0800568 sandboxOuts[i] = pathToSandboxOut(outs[i], genDir)
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700569 }
Jeff Gaston437d23c2017-11-08 12:38:00 -0800570 return generateTask{
Colin Crossbaccf5b2018-02-21 14:07:48 -0800571 in: srcFiles,
572 out: outs,
573 sandboxOuts: sandboxOuts,
574 cmd: rawCommand,
Colin Crossd350ecd2015-04-28 13:25:36 -0700575 }
Colin Cross5049f022015-03-18 13:28:46 -0700576 }
Colin Crossd350ecd2015-04-28 13:25:36 -0700577
Jeff Gaston437d23c2017-11-08 12:38:00 -0800578 return generatorFactory(taskGenerator, properties)
Colin Cross5049f022015-03-18 13:28:46 -0700579}
580
Colin Cross54190b32017-10-09 15:34:10 -0700581func GenRuleFactory() android.Module {
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700582 m := NewGenRule()
583 android.InitAndroidModule(m)
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800584 android.InitDefaultableModule(m)
Dan Willemsen3e5bdf22017-09-13 18:37:08 -0700585 return m
586}
587
Colin Crossd350ecd2015-04-28 13:25:36 -0700588type genRuleProperties struct {
Dan Willemsen9c8681f2016-09-28 16:21:00 -0700589 // names of the output files that will be generated
Colin Crossef354482018-10-23 11:27:50 -0700590 Out []string `android:"arch_variant"`
Colin Cross5049f022015-03-18 13:28:46 -0700591}
Nan Zhangea568a42017-11-08 21:20:04 -0800592
593var Bool = proptools.Bool
594var String = proptools.String
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800595
596//
597// Defaults
598//
599type Defaults struct {
600 android.ModuleBase
601 android.DefaultsModuleBase
602}
603
Jaewoong Jung98716bd2018-12-10 08:13:18 -0800604func defaultsFactory() android.Module {
605 return DefaultsFactory()
606}
607
608func DefaultsFactory(props ...interface{}) android.Module {
609 module := &Defaults{}
610
611 module.AddProperties(props...)
612 module.AddProperties(
613 &generatorProperties{},
614 &genRuleProperties{},
615 )
616
617 android.InitDefaultsModule(module)
618
619 return module
620}