blob: 56de9cd0062ee78aaabaf39569bed7c09aebf93c [file] [log] [blame]
Colin Crossfeec25b2019-01-30 17:32:39 -08001// Copyright 2018 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 android
16
17import (
Colin Cross3d680512020-11-13 16:23:53 -080018 "crypto/sha256"
Colin Crossfeec25b2019-01-30 17:32:39 -080019 "fmt"
Colin Cross3d680512020-11-13 16:23:53 -080020 "path/filepath"
Colin Crossfeec25b2019-01-30 17:32:39 -080021 "sort"
22 "strings"
Colin Crosse16ce362020-11-12 08:29:30 -080023 "testing"
Colin Crossfeec25b2019-01-30 17:32:39 -080024
25 "github.com/google/blueprint"
26 "github.com/google/blueprint/proptools"
Dan Willemsen4591b642021-05-24 14:24:12 -070027 "google.golang.org/protobuf/encoding/prototext"
28 "google.golang.org/protobuf/proto"
Dan Willemsen633c5022019-04-12 11:11:38 -070029
Colin Crosse16ce362020-11-12 08:29:30 -080030 "android/soong/cmd/sbox/sbox_proto"
Colin Crossef972742021-03-12 17:24:45 -080031 "android/soong/remoteexec"
Colin Crosse55bd422021-03-23 13:44:30 -070032 "android/soong/response"
Dan Willemsen633c5022019-04-12 11:11:38 -070033 "android/soong/shared"
Colin Crossfeec25b2019-01-30 17:32:39 -080034)
35
Colin Crosse16ce362020-11-12 08:29:30 -080036const sboxSandboxBaseDir = "__SBOX_SANDBOX_DIR__"
37const sboxOutSubDir = "out"
Colin Crossba9e4032020-11-24 16:32:22 -080038const sboxToolsSubDir = "tools"
Colin Crosse16ce362020-11-12 08:29:30 -080039const sboxOutDir = sboxSandboxBaseDir + "/" + sboxOutSubDir
Colin Cross3d680512020-11-13 16:23:53 -080040
Inseob Kimf7cd03e2024-09-06 17:25:00 +090041const nsjailToolsSubDir = "tools"
42const nsjailOutDir = "out"
43
Colin Cross758290d2019-02-01 16:42:32 -080044// RuleBuilder provides an alternative to ModuleContext.Rule and ModuleContext.Build to add a command line to the build
45// graph.
Colin Crossfeec25b2019-01-30 17:32:39 -080046type RuleBuilder struct {
Colin Crossf1a035e2020-11-16 17:32:30 -080047 pctx PackageContext
48 ctx BuilderContext
49
Colin Crosse16ce362020-11-12 08:29:30 -080050 commands []*RuleBuilderCommand
51 installs RuleBuilderInstalls
52 temporariesSet map[WritablePath]bool
53 restat bool
54 sbox bool
55 highmem bool
56 remoteable RemoteRuleSupports
Colin Crossef972742021-03-12 17:24:45 -080057 rbeParams *remoteexec.REParams
Colin Crossf1a035e2020-11-16 17:32:30 -080058 outDir WritablePath
Spandan Dasaf4ccaa2023-06-29 01:15:51 +000059 sboxOutSubDir string
Colin Crossba9e4032020-11-24 16:32:22 -080060 sboxTools bool
Colin Crossab020a72021-03-12 17:52:23 -080061 sboxInputs bool
Colin Crosse16ce362020-11-12 08:29:30 -080062 sboxManifestPath WritablePath
63 missingDeps []string
Devin Mooreb6cc64f2024-07-15 22:31:24 +000064 args map[string]string
Inseob Kimf7cd03e2024-09-06 17:25:00 +090065 nsjail bool
66 nsjailBasePath WritablePath
67 nsjailImplicits Paths
Colin Crossfeec25b2019-01-30 17:32:39 -080068}
69
Colin Cross758290d2019-02-01 16:42:32 -080070// NewRuleBuilder returns a newly created RuleBuilder.
Colin Crossf1a035e2020-11-16 17:32:30 -080071func NewRuleBuilder(pctx PackageContext, ctx BuilderContext) *RuleBuilder {
Colin Cross5cb5b092019-02-02 21:25:18 -080072 return &RuleBuilder{
Colin Crossf1a035e2020-11-16 17:32:30 -080073 pctx: pctx,
74 ctx: ctx,
Colin Cross69f59a32019-02-15 10:39:37 -080075 temporariesSet: make(map[WritablePath]bool),
Spandan Dasaf4ccaa2023-06-29 01:15:51 +000076 sboxOutSubDir: sboxOutSubDir,
Colin Cross5cb5b092019-02-02 21:25:18 -080077 }
Colin Cross758290d2019-02-01 16:42:32 -080078}
79
Spandan Dasaf4ccaa2023-06-29 01:15:51 +000080// SetSboxOutDirDirAsEmpty sets the out subdirectory to an empty string
81// This is useful for sandboxing actions that change the execution root to a path in out/ (e.g mixed builds)
82// For such actions, SetSboxOutDirDirAsEmpty ensures that the path does not become $SBOX_SANDBOX_DIR/out/out/bazel/output/execroot/__main__/...
83func (rb *RuleBuilder) SetSboxOutDirDirAsEmpty() *RuleBuilder {
84 rb.sboxOutSubDir = ""
85 return rb
86}
87
Devin Mooreb6cc64f2024-07-15 22:31:24 +000088// Set the phony_output argument.
89// This causes the output files to be ignored.
90// If the output isn't created, it's not treated as an error.
91// The build rule is run every time whether or not the output is created.
92func (rb *RuleBuilder) SetPhonyOutput() {
93 if rb.args == nil {
94 rb.args = make(map[string]string)
95 }
96 rb.args["phony_output"] = "true"
97}
98
Colin Cross758290d2019-02-01 16:42:32 -080099// RuleBuilderInstall is a tuple of install from and to locations.
100type RuleBuilderInstall struct {
Colin Cross69f59a32019-02-15 10:39:37 -0800101 From Path
102 To string
Colin Cross758290d2019-02-01 16:42:32 -0800103}
104
Colin Crossdeabb942019-02-11 14:11:09 -0800105type RuleBuilderInstalls []RuleBuilderInstall
106
107// String returns the RuleBuilderInstalls in the form used by $(call copy-many-files) in Make, a space separated
108// list of from:to tuples.
109func (installs RuleBuilderInstalls) String() string {
110 sb := strings.Builder{}
111 for i, install := range installs {
112 if i != 0 {
113 sb.WriteRune(' ')
114 }
Colin Cross69f59a32019-02-15 10:39:37 -0800115 sb.WriteString(install.From.String())
Colin Crossdeabb942019-02-11 14:11:09 -0800116 sb.WriteRune(':')
117 sb.WriteString(install.To)
118 }
119 return sb.String()
120}
121
Colin Cross0d2f40a2019-02-05 22:31:15 -0800122// MissingDeps adds modules to the list of missing dependencies. If MissingDeps
123// is called with a non-empty input, any call to Build will result in a rule
124// that will print an error listing the missing dependencies and fail.
125// MissingDeps should only be called if Config.AllowMissingDependencies() is
126// true.
127func (r *RuleBuilder) MissingDeps(missingDeps []string) {
128 r.missingDeps = append(r.missingDeps, missingDeps...)
129}
130
Colin Cross758290d2019-02-01 16:42:32 -0800131// Restat marks the rule as a restat rule, which will be passed to ModuleContext.Rule in BuildParams.Restat.
Colin Crossfeec25b2019-01-30 17:32:39 -0800132func (r *RuleBuilder) Restat() *RuleBuilder {
133 r.restat = true
134 return r
135}
136
Colin Cross8b8bec32019-11-15 13:18:43 -0800137// HighMem marks the rule as a high memory rule, which will limit how many run in parallel with other high memory
138// rules.
139func (r *RuleBuilder) HighMem() *RuleBuilder {
140 r.highmem = true
141 return r
142}
143
144// Remoteable marks the rule as supporting remote execution.
145func (r *RuleBuilder) Remoteable(supports RemoteRuleSupports) *RuleBuilder {
146 r.remoteable = supports
147 return r
148}
149
Colin Crossef972742021-03-12 17:24:45 -0800150// Rewrapper marks the rule as running inside rewrapper using the given params in order to support
151// running on RBE. During RuleBuilder.Build the params will be combined with the inputs, outputs
152// and tools known to RuleBuilder to prepend an appropriate rewrapper command line to the rule's
153// command line.
154func (r *RuleBuilder) Rewrapper(params *remoteexec.REParams) *RuleBuilder {
155 if !r.sboxInputs {
156 panic(fmt.Errorf("RuleBuilder.Rewrapper must be called after RuleBuilder.SandboxInputs"))
157 }
158 r.rbeParams = params
159 return r
160}
161
Colin Crosse16ce362020-11-12 08:29:30 -0800162// Sbox marks the rule as needing to be wrapped by sbox. The outputDir should point to the output
163// directory that sbox will wipe. It should not be written to by any other rule. manifestPath should
164// point to a location where sbox's manifest will be written and must be outside outputDir. sbox
165// will ensure that all outputs have been written, and will discard any output files that were not
166// specified.
Colin Crosse16ce362020-11-12 08:29:30 -0800167func (r *RuleBuilder) Sbox(outputDir WritablePath, manifestPath WritablePath) *RuleBuilder {
Dan Willemsen633c5022019-04-12 11:11:38 -0700168 if r.sbox {
169 panic("Sbox() may not be called more than once")
170 }
171 if len(r.commands) > 0 {
172 panic("Sbox() may not be called after Command()")
173 }
Inseob Kimf7cd03e2024-09-06 17:25:00 +0900174 if r.nsjail {
175 panic("Sbox() may not be called after Nsjail()")
176 }
Dan Willemsen633c5022019-04-12 11:11:38 -0700177 r.sbox = true
Colin Crossf1a035e2020-11-16 17:32:30 -0800178 r.outDir = outputDir
Colin Crosse16ce362020-11-12 08:29:30 -0800179 r.sboxManifestPath = manifestPath
Dan Willemsen633c5022019-04-12 11:11:38 -0700180 return r
181}
182
Inseob Kimf7cd03e2024-09-06 17:25:00 +0900183// Nsjail marks the rule as needing to be wrapped by nsjail. The outputDir should point to the
184// output directory that nsjail will mount to out/. It should not be written to by any other rule.
185// baseDir should point to a location where nsjail will mount to /nsjail_build_sandbox, which will
186// be the working directory of the command.
187func (r *RuleBuilder) Nsjail(outputDir WritablePath, baseDir WritablePath) *RuleBuilder {
188 if len(r.commands) > 0 {
189 panic("Nsjail() may not be called after Command()")
190 }
191 if r.sbox {
192 panic("Nsjail() may not be called after Sbox()")
193 }
194 r.nsjail = true
195 r.outDir = outputDir
196 r.nsjailBasePath = baseDir
197 return r
198}
199
200// NsjailImplicits adds implicit inputs that are not directly mounted. This is useful when
201// the rule mounts directories, as files within those directories can be globbed and
202// tracked as dependencies with NsjailImplicits().
203func (r *RuleBuilder) NsjailImplicits(inputs Paths) *RuleBuilder {
204 if !r.nsjail {
205 panic("NsjailImplicits() must be called after Nsjail()")
206 }
207 r.nsjailImplicits = append(r.nsjailImplicits, inputs...)
208 return r
209}
210
Colin Crossba9e4032020-11-24 16:32:22 -0800211// SandboxTools enables tool sandboxing for the rule by copying any referenced tools into the
212// sandbox.
213func (r *RuleBuilder) SandboxTools() *RuleBuilder {
214 if !r.sbox {
215 panic("SandboxTools() must be called after Sbox()")
216 }
217 if len(r.commands) > 0 {
218 panic("SandboxTools() may not be called after Command()")
219 }
220 r.sboxTools = true
221 return r
222}
223
Colin Crossab020a72021-03-12 17:52:23 -0800224// SandboxInputs enables input sandboxing for the rule by copying any referenced inputs into the
225// sandbox. It also implies SandboxTools().
226//
227// Sandboxing inputs requires RuleBuilder to be aware of all references to input paths. Paths
228// that are passed to RuleBuilder outside of the methods that expect inputs, for example
229// FlagWithArg, must use RuleBuilderCommand.PathForInput to translate the path to one that matches
230// the sandbox layout.
231func (r *RuleBuilder) SandboxInputs() *RuleBuilder {
232 if !r.sbox {
233 panic("SandboxInputs() must be called after Sbox()")
234 }
235 if len(r.commands) > 0 {
236 panic("SandboxInputs() may not be called after Command()")
237 }
238 r.sboxTools = true
239 r.sboxInputs = true
240 return r
241}
242
Colin Cross758290d2019-02-01 16:42:32 -0800243// Install associates an output of the rule with an install location, which can be retrieved later using
244// RuleBuilder.Installs.
Colin Cross69f59a32019-02-15 10:39:37 -0800245func (r *RuleBuilder) Install(from Path, to string) {
Colin Crossfeec25b2019-01-30 17:32:39 -0800246 r.installs = append(r.installs, RuleBuilderInstall{from, to})
247}
248
Colin Cross758290d2019-02-01 16:42:32 -0800249// Command returns a new RuleBuilderCommand for the rule. The commands will be ordered in the rule by when they were
250// created by this method. That can be mutated through their methods in any order, as long as the mutations do not
251// race with any call to Build.
Colin Crossfeec25b2019-01-30 17:32:39 -0800252func (r *RuleBuilder) Command() *RuleBuilderCommand {
Dan Willemsen633c5022019-04-12 11:11:38 -0700253 command := &RuleBuilderCommand{
Colin Crossf1a035e2020-11-16 17:32:30 -0800254 rule: r,
Dan Willemsen633c5022019-04-12 11:11:38 -0700255 }
Colin Crossfeec25b2019-01-30 17:32:39 -0800256 r.commands = append(r.commands, command)
257 return command
258}
259
Colin Cross5cb5b092019-02-02 21:25:18 -0800260// Temporary marks an output of a command as an intermediate file that will be used as an input to another command
261// in the same rule, and should not be listed in Outputs.
Colin Cross69f59a32019-02-15 10:39:37 -0800262func (r *RuleBuilder) Temporary(path WritablePath) {
Colin Cross5cb5b092019-02-02 21:25:18 -0800263 r.temporariesSet[path] = true
264}
265
266// DeleteTemporaryFiles adds a command to the rule that deletes any outputs that have been marked using Temporary
267// when the rule runs. DeleteTemporaryFiles should be called after all calls to Temporary.
268func (r *RuleBuilder) DeleteTemporaryFiles() {
Colin Cross69f59a32019-02-15 10:39:37 -0800269 var temporariesList WritablePaths
Colin Cross5cb5b092019-02-02 21:25:18 -0800270
271 for intermediate := range r.temporariesSet {
272 temporariesList = append(temporariesList, intermediate)
273 }
Colin Cross69f59a32019-02-15 10:39:37 -0800274
275 sort.Slice(temporariesList, func(i, j int) bool {
276 return temporariesList[i].String() < temporariesList[j].String()
277 })
Colin Cross5cb5b092019-02-02 21:25:18 -0800278
279 r.Command().Text("rm").Flag("-f").Outputs(temporariesList)
280}
281
Colin Crossda71eda2020-02-21 16:55:19 -0800282// Inputs returns the list of paths that were passed to the RuleBuilderCommand methods that take
Colin Cross3d680512020-11-13 16:23:53 -0800283// input paths, such as RuleBuilderCommand.Input, RuleBuilderCommand.Implicit, or
Colin Crossda71eda2020-02-21 16:55:19 -0800284// RuleBuilderCommand.FlagWithInput. Inputs to a command that are also outputs of another command
285// in the same RuleBuilder are filtered out. The list is sorted and duplicates removed.
Colin Cross69f59a32019-02-15 10:39:37 -0800286func (r *RuleBuilder) Inputs() Paths {
Colin Crossfeec25b2019-01-30 17:32:39 -0800287 outputs := r.outputSet()
Dan Willemsen633c5022019-04-12 11:11:38 -0700288 depFiles := r.depFileSet()
Colin Crossfeec25b2019-01-30 17:32:39 -0800289
Colin Cross69f59a32019-02-15 10:39:37 -0800290 inputs := make(map[string]Path)
Colin Crossfeec25b2019-01-30 17:32:39 -0800291 for _, c := range r.commands {
Ramy Medhat2f99eec2020-06-13 17:38:27 -0400292 for _, input := range append(c.inputs, c.implicits...) {
Dan Willemsen633c5022019-04-12 11:11:38 -0700293 inputStr := input.String()
294 if _, isOutput := outputs[inputStr]; !isOutput {
295 if _, isDepFile := depFiles[inputStr]; !isDepFile {
296 inputs[input.String()] = input
297 }
Colin Crossfeec25b2019-01-30 17:32:39 -0800298 }
299 }
300 }
301
Colin Cross69f59a32019-02-15 10:39:37 -0800302 var inputList Paths
303 for _, input := range inputs {
Colin Crossfeec25b2019-01-30 17:32:39 -0800304 inputList = append(inputList, input)
305 }
Colin Cross69f59a32019-02-15 10:39:37 -0800306
307 sort.Slice(inputList, func(i, j int) bool {
308 return inputList[i].String() < inputList[j].String()
309 })
Colin Crossfeec25b2019-01-30 17:32:39 -0800310
311 return inputList
312}
313
Colin Crossda71eda2020-02-21 16:55:19 -0800314// OrderOnlys returns the list of paths that were passed to the RuleBuilderCommand.OrderOnly or
315// RuleBuilderCommand.OrderOnlys. The list is sorted and duplicates removed.
316func (r *RuleBuilder) OrderOnlys() Paths {
317 orderOnlys := make(map[string]Path)
318 for _, c := range r.commands {
319 for _, orderOnly := range c.orderOnlys {
320 orderOnlys[orderOnly.String()] = orderOnly
321 }
322 }
323
324 var orderOnlyList Paths
325 for _, orderOnly := range orderOnlys {
326 orderOnlyList = append(orderOnlyList, orderOnly)
327 }
328
329 sort.Slice(orderOnlyList, func(i, j int) bool {
330 return orderOnlyList[i].String() < orderOnlyList[j].String()
331 })
332
333 return orderOnlyList
334}
335
Colin Crossae89abe2021-04-21 11:45:23 -0700336// Validations returns the list of paths that were passed to RuleBuilderCommand.Validation or
337// RuleBuilderCommand.Validations. The list is sorted and duplicates removed.
338func (r *RuleBuilder) Validations() Paths {
339 validations := make(map[string]Path)
340 for _, c := range r.commands {
341 for _, validation := range c.validations {
342 validations[validation.String()] = validation
343 }
344 }
345
346 var validationList Paths
347 for _, validation := range validations {
348 validationList = append(validationList, validation)
349 }
350
351 sort.Slice(validationList, func(i, j int) bool {
352 return validationList[i].String() < validationList[j].String()
353 })
354
355 return validationList
356}
357
Colin Cross69f59a32019-02-15 10:39:37 -0800358func (r *RuleBuilder) outputSet() map[string]WritablePath {
359 outputs := make(map[string]WritablePath)
Colin Crossfeec25b2019-01-30 17:32:39 -0800360 for _, c := range r.commands {
361 for _, output := range c.outputs {
Colin Cross69f59a32019-02-15 10:39:37 -0800362 outputs[output.String()] = output
Colin Crossfeec25b2019-01-30 17:32:39 -0800363 }
364 }
365 return outputs
366}
367
Colin Crossda71eda2020-02-21 16:55:19 -0800368// Outputs returns the list of paths that were passed to the RuleBuilderCommand methods that take
369// output paths, such as RuleBuilderCommand.Output, RuleBuilderCommand.ImplicitOutput, or
370// RuleBuilderCommand.FlagWithInput. The list is sorted and duplicates removed.
Colin Cross69f59a32019-02-15 10:39:37 -0800371func (r *RuleBuilder) Outputs() WritablePaths {
Colin Crossfeec25b2019-01-30 17:32:39 -0800372 outputs := r.outputSet()
373
Colin Cross69f59a32019-02-15 10:39:37 -0800374 var outputList WritablePaths
375 for _, output := range outputs {
Colin Cross5cb5b092019-02-02 21:25:18 -0800376 if !r.temporariesSet[output] {
377 outputList = append(outputList, output)
378 }
Colin Crossfeec25b2019-01-30 17:32:39 -0800379 }
Colin Cross69f59a32019-02-15 10:39:37 -0800380
381 sort.Slice(outputList, func(i, j int) bool {
382 return outputList[i].String() < outputList[j].String()
383 })
384
Colin Crossfeec25b2019-01-30 17:32:39 -0800385 return outputList
386}
387
Dan Willemsen633c5022019-04-12 11:11:38 -0700388func (r *RuleBuilder) depFileSet() map[string]WritablePath {
389 depFiles := make(map[string]WritablePath)
390 for _, c := range r.commands {
391 for _, depFile := range c.depFiles {
392 depFiles[depFile.String()] = depFile
393 }
394 }
395 return depFiles
396}
397
Colin Cross1d2cf042019-03-29 15:33:06 -0700398// DepFiles returns the list of paths that were passed to the RuleBuilderCommand methods that take depfile paths, such
399// as RuleBuilderCommand.DepFile or RuleBuilderCommand.FlagWithDepFile.
400func (r *RuleBuilder) DepFiles() WritablePaths {
401 var depFiles WritablePaths
402
403 for _, c := range r.commands {
404 for _, depFile := range c.depFiles {
405 depFiles = append(depFiles, depFile)
406 }
407 }
408
409 return depFiles
410}
411
Colin Cross758290d2019-02-01 16:42:32 -0800412// Installs returns the list of tuples passed to Install.
Colin Crossdeabb942019-02-11 14:11:09 -0800413func (r *RuleBuilder) Installs() RuleBuilderInstalls {
414 return append(RuleBuilderInstalls(nil), r.installs...)
Colin Crossfeec25b2019-01-30 17:32:39 -0800415}
416
Colin Cross69f59a32019-02-15 10:39:37 -0800417func (r *RuleBuilder) toolsSet() map[string]Path {
418 tools := make(map[string]Path)
Colin Cross5cb5b092019-02-02 21:25:18 -0800419 for _, c := range r.commands {
420 for _, tool := range c.tools {
Colin Cross69f59a32019-02-15 10:39:37 -0800421 tools[tool.String()] = tool
Colin Cross5cb5b092019-02-02 21:25:18 -0800422 }
423 }
424
425 return tools
426}
427
Colin Crossda71eda2020-02-21 16:55:19 -0800428// Tools returns the list of paths that were passed to the RuleBuilderCommand.Tool method. The
429// list is sorted and duplicates removed.
Colin Cross69f59a32019-02-15 10:39:37 -0800430func (r *RuleBuilder) Tools() Paths {
Colin Cross5cb5b092019-02-02 21:25:18 -0800431 toolsSet := r.toolsSet()
432
Colin Cross69f59a32019-02-15 10:39:37 -0800433 var toolsList Paths
434 for _, tool := range toolsSet {
Colin Cross5cb5b092019-02-02 21:25:18 -0800435 toolsList = append(toolsList, tool)
Colin Crossfeec25b2019-01-30 17:32:39 -0800436 }
Colin Cross69f59a32019-02-15 10:39:37 -0800437
438 sort.Slice(toolsList, func(i, j int) bool {
439 return toolsList[i].String() < toolsList[j].String()
440 })
441
Colin Cross5cb5b092019-02-02 21:25:18 -0800442 return toolsList
Colin Crossfeec25b2019-01-30 17:32:39 -0800443}
444
Colin Cross0cb0d7b2019-07-11 10:59:15 -0700445// RspFileInputs returns the list of paths that were passed to the RuleBuilderCommand.FlagWithRspFileInputList method.
446func (r *RuleBuilder) RspFileInputs() Paths {
447 var rspFileInputs Paths
448 for _, c := range r.commands {
Colin Crossce3a51d2021-03-19 16:22:12 -0700449 for _, rspFile := range c.rspFiles {
450 rspFileInputs = append(rspFileInputs, rspFile.paths...)
Colin Cross0cb0d7b2019-07-11 10:59:15 -0700451 }
452 }
453
454 return rspFileInputs
455}
456
Colin Crossce3a51d2021-03-19 16:22:12 -0700457func (r *RuleBuilder) rspFiles() []rspFileAndPaths {
458 var rspFiles []rspFileAndPaths
Colin Cross70c47412021-03-12 17:48:14 -0800459 for _, c := range r.commands {
Colin Crossce3a51d2021-03-19 16:22:12 -0700460 rspFiles = append(rspFiles, c.rspFiles...)
Colin Cross70c47412021-03-12 17:48:14 -0800461 }
462
Colin Crossce3a51d2021-03-19 16:22:12 -0700463 return rspFiles
Colin Cross70c47412021-03-12 17:48:14 -0800464}
465
Colin Cross0cb0d7b2019-07-11 10:59:15 -0700466// Commands returns a slice containing the built command line for each call to RuleBuilder.Command.
Colin Crossfeec25b2019-01-30 17:32:39 -0800467func (r *RuleBuilder) Commands() []string {
468 var commands []string
469 for _, c := range r.commands {
Colin Cross0cb0d7b2019-07-11 10:59:15 -0700470 commands = append(commands, c.String())
471 }
472 return commands
473}
474
Colin Cross758290d2019-02-01 16:42:32 -0800475// BuilderContext is a subset of ModuleContext and SingletonContext.
Colin Cross786cd6d2019-02-01 16:41:11 -0800476type BuilderContext interface {
477 PathContext
478 Rule(PackageContext, string, blueprint.RuleParams, ...string) blueprint.Rule
479 Build(PackageContext, BuildParams)
480}
481
Colin Cross758290d2019-02-01 16:42:32 -0800482var _ BuilderContext = ModuleContext(nil)
483var _ BuilderContext = SingletonContext(nil)
484
Colin Crossf1a035e2020-11-16 17:32:30 -0800485func (r *RuleBuilder) depFileMergerCmd(depFiles WritablePaths) *RuleBuilderCommand {
Dan Willemsen633c5022019-04-12 11:11:38 -0700486 return r.Command().
Colin Cross9b698b62021-12-22 09:55:32 -0800487 builtToolWithoutDeps("dep_fixer").
Dan Willemsen633c5022019-04-12 11:11:38 -0700488 Inputs(depFiles.Paths())
Colin Cross1d2cf042019-03-29 15:33:06 -0700489}
490
Sam Delmerico285b66a2023-09-25 12:13:17 +0000491// BuildWithNinjaVars adds the built command line to the build graph, with dependencies on Inputs and Tools, and output files for
492// Outputs. This function will not escape Ninja variables, so it may be used to write sandbox manifests using Ninja variables.
493func (r *RuleBuilder) BuildWithUnescapedNinjaVars(name string, desc string) {
494 r.build(name, desc, false)
495}
496
Colin Cross758290d2019-02-01 16:42:32 -0800497// Build adds the built command line to the build graph, with dependencies on Inputs and Tools, and output files for
498// Outputs.
Colin Crossf1a035e2020-11-16 17:32:30 -0800499func (r *RuleBuilder) Build(name string, desc string) {
Sam Delmerico285b66a2023-09-25 12:13:17 +0000500 r.build(name, desc, true)
501}
502
Cole Faust63ea1f92024-08-27 11:42:26 -0700503var sandboxEnvOnceKey = NewOnceKey("sandbox_environment_variables")
504
Sam Delmerico285b66a2023-09-25 12:13:17 +0000505func (r *RuleBuilder) build(name string, desc string, ninjaEscapeCommandString bool) {
Colin Cross1d2cf042019-03-29 15:33:06 -0700506 name = ninjaNameEscape(name)
507
Colin Cross0d2f40a2019-02-05 22:31:15 -0800508 if len(r.missingDeps) > 0 {
Sam Delmerico285b66a2023-09-25 12:13:17 +0000509 r.ctx.Build(r.pctx, BuildParams{
Colin Cross0d2f40a2019-02-05 22:31:15 -0800510 Rule: ErrorRule,
Colin Cross69f59a32019-02-15 10:39:37 -0800511 Outputs: r.Outputs(),
Colin Cross0d2f40a2019-02-05 22:31:15 -0800512 Description: desc,
513 Args: map[string]string{
514 "error": "missing dependencies: " + strings.Join(r.missingDeps, ", "),
515 },
516 })
517 return
518 }
519
Colin Cross1d2cf042019-03-29 15:33:06 -0700520 var depFile WritablePath
521 var depFormat blueprint.Deps
522 if depFiles := r.DepFiles(); len(depFiles) > 0 {
523 depFile = depFiles[0]
524 depFormat = blueprint.DepsGCC
525 if len(depFiles) > 1 {
526 // Add a command locally that merges all depfiles together into the first depfile.
Colin Crossf1a035e2020-11-16 17:32:30 -0800527 r.depFileMergerCmd(depFiles)
Dan Willemsen633c5022019-04-12 11:11:38 -0700528
529 if r.sbox {
Colin Crosse16ce362020-11-12 08:29:30 -0800530 // Check for Rel() errors, as all depfiles should be in the output dir. Errors
531 // will be reported to the ctx.
Dan Willemsen633c5022019-04-12 11:11:38 -0700532 for _, path := range depFiles[1:] {
Colin Crossf1a035e2020-11-16 17:32:30 -0800533 Rel(r.ctx, r.outDir.String(), path.String())
Dan Willemsen633c5022019-04-12 11:11:38 -0700534 }
535 }
Colin Cross1d2cf042019-03-29 15:33:06 -0700536 }
537 }
538
Dan Willemsen633c5022019-04-12 11:11:38 -0700539 tools := r.Tools()
Colin Crossb70a1a92021-03-12 17:51:32 -0800540 commands := r.Commands()
Dan Willemsen633c5022019-04-12 11:11:38 -0700541 outputs := r.Outputs()
Colin Cross3d680512020-11-13 16:23:53 -0800542 inputs := r.Inputs()
Colin Crossce3a51d2021-03-19 16:22:12 -0700543 rspFiles := r.rspFiles()
Dan Willemsen633c5022019-04-12 11:11:38 -0700544
545 if len(commands) == 0 {
546 return
547 }
548 if len(outputs) == 0 {
549 panic("No outputs specified from any Commands")
550 }
551
Colin Cross0cb0d7b2019-07-11 10:59:15 -0700552 commandString := strings.Join(commands, " && ")
Dan Willemsen633c5022019-04-12 11:11:38 -0700553
Inseob Kimf7cd03e2024-09-06 17:25:00 +0900554 if !r.sbox {
555 // If not using sbox the rule will run the command directly, put the hash of the
556 // list of input files in a comment at the end of the command line to ensure ninja
557 // reruns the rule when the list of input files changes.
558 commandString += " # hash of input list: " + hashSrcFiles(inputs)
559 }
560
561 if r.nsjail {
562 var nsjailCmd strings.Builder
563 nsjailPath := r.ctx.Config().PrebuiltBuildTool(r.ctx, "nsjail")
564 nsjailCmd.WriteString("mkdir -p ")
565 nsjailCmd.WriteString(r.nsjailBasePath.String())
566 nsjailCmd.WriteString(" && ")
567 nsjailCmd.WriteString(nsjailPath.String())
568 nsjailCmd.WriteRune(' ')
569 nsjailCmd.WriteString("-B $PWD/")
570 nsjailCmd.WriteString(r.nsjailBasePath.String())
571 nsjailCmd.WriteString(":nsjail_build_sandbox")
572
573 // out is mounted to $(genDir).
574 nsjailCmd.WriteString(" -B $PWD/")
575 nsjailCmd.WriteString(r.outDir.String())
576 nsjailCmd.WriteString(":nsjail_build_sandbox/out")
577
578 for _, input := range inputs {
579 nsjailCmd.WriteString(" -R $PWD/")
580 nsjailCmd.WriteString(input.String())
581 nsjailCmd.WriteString(":nsjail_build_sandbox/")
582 nsjailCmd.WriteString(r.nsjailPathForInputRel(input))
583 }
584 for _, tool := range tools {
585 nsjailCmd.WriteString(" -R $PWD/")
586 nsjailCmd.WriteString(tool.String())
587 nsjailCmd.WriteString(":nsjail_build_sandbox/")
588 nsjailCmd.WriteString(nsjailPathForToolRel(r.ctx, tool))
589 }
590 inputs = append(inputs, tools...)
591 for _, c := range r.commands {
592 for _, tool := range c.packagedTools {
593 nsjailCmd.WriteString(" -R $PWD/")
594 nsjailCmd.WriteString(tool.srcPath.String())
595 nsjailCmd.WriteString(":nsjail_build_sandbox/")
596 nsjailCmd.WriteString(nsjailPathForPackagedToolRel(tool))
597 inputs = append(inputs, tool.srcPath)
598 }
599 }
600
601 // These five directories are necessary to run native host tools like /bin/bash and py3-cmd.
602 nsjailCmd.WriteString(" -R /bin")
603 nsjailCmd.WriteString(" -R /lib")
604 nsjailCmd.WriteString(" -R /lib64")
605 nsjailCmd.WriteString(" -R /dev")
606 nsjailCmd.WriteString(" -R /usr")
607
608 nsjailCmd.WriteString(" -m none:/tmp:tmpfs:size=1073741824") // 1GB, should be enough
609 nsjailCmd.WriteString(" -D nsjail_build_sandbox")
610 nsjailCmd.WriteString(" --disable_rlimits")
611 nsjailCmd.WriteString(" -q")
612 nsjailCmd.WriteString(" -- ")
613 nsjailCmd.WriteString("/bin/bash -c ")
614 nsjailCmd.WriteString(proptools.ShellEscape(commandString))
615
616 commandString = nsjailCmd.String()
617
618 inputs = append(inputs, nsjailPath)
619 inputs = append(inputs, r.nsjailImplicits...)
620 } else if r.sbox {
Colin Crosse16ce362020-11-12 08:29:30 -0800621 // If running the command inside sbox, write the rule data out to an sbox
622 // manifest.textproto.
623 manifest := sbox_proto.Manifest{}
624 command := sbox_proto.Command{}
625 manifest.Commands = append(manifest.Commands, &command)
626 command.Command = proto.String(commandString)
Colin Cross151b9ff2020-11-12 08:29:30 -0800627
Colin Cross619b9ab2020-11-20 18:44:31 +0000628 if depFile != nil {
Colin Crosse16ce362020-11-12 08:29:30 -0800629 manifest.OutputDepfile = proto.String(depFile.String())
Colin Cross619b9ab2020-11-20 18:44:31 +0000630 }
631
Colin Crossba9e4032020-11-24 16:32:22 -0800632 // If sandboxing tools is enabled, add copy rules to the manifest to copy each tool
633 // into the sbox directory.
634 if r.sboxTools {
635 for _, tool := range tools {
636 command.CopyBefore = append(command.CopyBefore, &sbox_proto.Copy{
637 From: proto.String(tool.String()),
638 To: proto.String(sboxPathForToolRel(r.ctx, tool)),
639 })
640 }
641 for _, c := range r.commands {
642 for _, tool := range c.packagedTools {
643 command.CopyBefore = append(command.CopyBefore, &sbox_proto.Copy{
644 From: proto.String(tool.srcPath.String()),
645 To: proto.String(sboxPathForPackagedToolRel(tool)),
646 Executable: proto.Bool(tool.executable),
647 })
648 tools = append(tools, tool.srcPath)
649 }
650 }
651 }
652
Colin Crossab020a72021-03-12 17:52:23 -0800653 // If sandboxing inputs is enabled, add copy rules to the manifest to copy each input
654 // into the sbox directory.
655 if r.sboxInputs {
656 for _, input := range inputs {
657 command.CopyBefore = append(command.CopyBefore, &sbox_proto.Copy{
658 From: proto.String(input.String()),
659 To: proto.String(r.sboxPathForInputRel(input)),
660 })
661 }
Cole Faust78f3c3a2024-08-15 17:19:34 -0700662 for _, input := range r.OrderOnlys() {
663 command.CopyBefore = append(command.CopyBefore, &sbox_proto.Copy{
664 From: proto.String(input.String()),
665 To: proto.String(r.sboxPathForInputRel(input)),
666 })
667 }
Colin Crossab020a72021-03-12 17:52:23 -0800668
Colin Crossce3a51d2021-03-19 16:22:12 -0700669 // If using rsp files copy them and their contents into the sbox directory with
670 // the appropriate path mappings.
671 for _, rspFile := range rspFiles {
Colin Crosse55bd422021-03-23 13:44:30 -0700672 command.RspFiles = append(command.RspFiles, &sbox_proto.RspFile{
Colin Crossce3a51d2021-03-19 16:22:12 -0700673 File: proto.String(rspFile.file.String()),
Colin Crosse55bd422021-03-23 13:44:30 -0700674 // These have to match the logic in sboxPathForInputRel
675 PathMappings: []*sbox_proto.PathMapping{
676 {
677 From: proto.String(r.outDir.String()),
678 To: proto.String(sboxOutSubDir),
679 },
680 {
Cole Fauste8561c62023-11-30 17:26:37 -0800681 From: proto.String(r.ctx.Config().OutDir()),
Colin Crosse55bd422021-03-23 13:44:30 -0700682 To: proto.String(sboxOutSubDir),
683 },
684 },
Colin Crossab020a72021-03-12 17:52:23 -0800685 })
686 }
687
Cole Faust63ea1f92024-08-27 11:42:26 -0700688 // Only allow the build to access certain environment variables
689 command.DontInheritEnv = proto.Bool(true)
690 command.Env = r.ctx.Config().Once(sandboxEnvOnceKey, func() interface{} {
691 // The list of allowed variables was found by running builds of all
692 // genrules and seeing what failed
693 var result []*sbox_proto.EnvironmentVariable
694 inheritedVars := []string{
695 "PATH",
696 "JAVA_HOME",
697 "TMPDIR",
698 // Allow RBE variables because the art tests invoke RBE manually
699 "RBE_log_dir",
700 "RBE_platform",
701 "RBE_server_address",
702 // TODO: RBE_exec_root is set to the absolute path to the root of the source
703 // tree, which we don't want sandboxed actions to find. Remap it to ".".
704 "RBE_exec_root",
705 }
706 for _, v := range inheritedVars {
707 result = append(result, &sbox_proto.EnvironmentVariable{
708 Name: proto.String(v),
709 State: &sbox_proto.EnvironmentVariable_Inherit{
710 Inherit: true,
711 },
712 })
713 }
714 // Set OUT_DIR to the relative path of the sandboxed out directory.
715 // Otherwise, OUT_DIR will be inherited from the rest of the build,
716 // which will allow scripts to escape the sandbox if OUT_DIR is an
717 // absolute path.
718 result = append(result, &sbox_proto.EnvironmentVariable{
719 Name: proto.String("OUT_DIR"),
720 State: &sbox_proto.EnvironmentVariable_Value{
721 Value: sboxOutSubDir,
722 },
723 })
724 return result
725 }).([]*sbox_proto.EnvironmentVariable)
Colin Crossab020a72021-03-12 17:52:23 -0800726 command.Chdir = proto.Bool(true)
727 }
728
Colin Crosse16ce362020-11-12 08:29:30 -0800729 // Add copy rules to the manifest to copy each output file from the sbox directory.
Colin Crossba9e4032020-11-24 16:32:22 -0800730 // to the output directory after running the commands.
Spandan Das33e30972023-07-13 21:19:12 +0000731 for _, output := range outputs {
Colin Crossf1a035e2020-11-16 17:32:30 -0800732 rel := Rel(r.ctx, r.outDir.String(), output.String())
Colin Crosse16ce362020-11-12 08:29:30 -0800733 command.CopyAfter = append(command.CopyAfter, &sbox_proto.Copy{
Spandan Dasaf4ccaa2023-06-29 01:15:51 +0000734 From: proto.String(filepath.Join(r.sboxOutSubDir, rel)),
Colin Crosse16ce362020-11-12 08:29:30 -0800735 To: proto.String(output.String()),
736 })
737 }
Colin Cross619b9ab2020-11-20 18:44:31 +0000738
Colin Cross5334edd2021-03-11 17:18:21 -0800739 // Outputs that were marked Temporary will not be checked that they are in the output
740 // directory by the loop above, check them here.
741 for path := range r.temporariesSet {
742 Rel(r.ctx, r.outDir.String(), path.String())
743 }
744
Colin Crosse16ce362020-11-12 08:29:30 -0800745 // Add a hash of the list of input files to the manifest so that the textproto file
746 // changes when the list of input files changes and causes the sbox rule that
747 // depends on it to rerun.
748 command.InputHash = proto.String(hashSrcFiles(inputs))
Colin Cross619b9ab2020-11-20 18:44:31 +0000749
Colin Crosse16ce362020-11-12 08:29:30 -0800750 // Verify that the manifest textproto is not inside the sbox output directory, otherwise
751 // it will get deleted when the sbox rule clears its output directory.
Colin Crossf1a035e2020-11-16 17:32:30 -0800752 _, manifestInOutDir := MaybeRel(r.ctx, r.outDir.String(), r.sboxManifestPath.String())
Colin Crosse16ce362020-11-12 08:29:30 -0800753 if manifestInOutDir {
Colin Crossf1a035e2020-11-16 17:32:30 -0800754 ReportPathErrorf(r.ctx, "sbox rule %q manifestPath %q must not be in outputDir %q",
755 name, r.sboxManifestPath.String(), r.outDir.String())
Colin Crosse16ce362020-11-12 08:29:30 -0800756 }
757
Paul Duffin4a3a0a52023-10-12 15:01:29 +0100758 // Create a rule to write the manifest as textproto. Pretty print it by indenting and
759 // splitting across multiple lines.
760 pbText, err := prototext.MarshalOptions{Indent: " "}.Marshal(&manifest)
Dan Willemsen4591b642021-05-24 14:24:12 -0700761 if err != nil {
762 ReportPathErrorf(r.ctx, "sbox manifest failed to marshal: %q", err)
763 }
Sam Delmerico285b66a2023-09-25 12:13:17 +0000764 if ninjaEscapeCommandString {
765 WriteFileRule(r.ctx, r.sboxManifestPath, string(pbText))
766 } else {
767 // We need to have a rule to write files that is
768 // defined on the RuleBuilder's pctx in order to
769 // write Ninja variables in the string.
770 // The WriteFileRule function above rule can only write
771 // raw strings because it is defined on the android
772 // package's pctx, and it can't access variables defined
773 // in another context.
774 r.ctx.Build(r.pctx, BuildParams{
775 Rule: r.ctx.Rule(r.pctx, "unescapedWriteFile", blueprint.RuleParams{
776 Command: `rm -rf ${out} && cat ${out}.rsp > ${out}`,
777 Rspfile: "${out}.rsp",
778 RspfileContent: "${content}",
779 Description: "write file",
780 }, "content"),
781 Output: r.sboxManifestPath,
782 Description: "write sbox manifest " + r.sboxManifestPath.Base(),
783 Args: map[string]string{
784 "content": string(pbText),
785 },
786 })
787 }
Colin Crosse16ce362020-11-12 08:29:30 -0800788
789 // Generate a new string to use as the command line of the sbox rule. This uses
790 // a RuleBuilderCommand as a convenience method of building the command line, then
791 // converts it to a string to replace commandString.
Colin Crossf1a035e2020-11-16 17:32:30 -0800792 sboxCmd := &RuleBuilderCommand{
793 rule: &RuleBuilder{
794 ctx: r.ctx,
795 },
796 }
Colin Cross9b698b62021-12-22 09:55:32 -0800797 sboxCmd.builtToolWithoutDeps("sbox").
Colin Crosse52c2ac2022-03-28 17:03:35 -0700798 FlagWithArg("--sandbox-path ", shared.TempDirForOutDir(PathForOutput(r.ctx).String())).
799 FlagWithArg("--output-dir ", r.outDir.String()).
800 FlagWithInput("--manifest ", r.sboxManifestPath)
801
802 if r.restat {
803 sboxCmd.Flag("--write-if-changed")
804 }
Colin Crosse16ce362020-11-12 08:29:30 -0800805
806 // Replace the command string, and add the sbox tool and manifest textproto to the
807 // dependencies of the final sbox rule.
Colin Crosscfec40c2019-07-08 17:07:18 -0700808 commandString = sboxCmd.buf.String()
Dan Willemsen633c5022019-04-12 11:11:38 -0700809 tools = append(tools, sboxCmd.tools...)
Colin Crosse16ce362020-11-12 08:29:30 -0800810 inputs = append(inputs, sboxCmd.inputs...)
Colin Crossef972742021-03-12 17:24:45 -0800811
812 if r.rbeParams != nil {
Colin Crosse55bd422021-03-23 13:44:30 -0700813 // RBE needs a list of input files to copy to the remote builder. For inputs already
814 // listed in an rsp file, pass the rsp file directly to rewrapper. For the rest,
815 // create a new rsp file to pass to rewrapper.
816 var remoteRspFiles Paths
817 var remoteInputs Paths
818
819 remoteInputs = append(remoteInputs, inputs...)
820 remoteInputs = append(remoteInputs, tools...)
821
Colin Crossce3a51d2021-03-19 16:22:12 -0700822 for _, rspFile := range rspFiles {
823 remoteInputs = append(remoteInputs, rspFile.file)
824 remoteRspFiles = append(remoteRspFiles, rspFile.file)
Colin Crossef972742021-03-12 17:24:45 -0800825 }
Colin Crosse55bd422021-03-23 13:44:30 -0700826
827 if len(remoteInputs) > 0 {
828 inputsListFile := r.sboxManifestPath.ReplaceExtension(r.ctx, "rbe_inputs.list")
829 writeRspFileRule(r.ctx, inputsListFile, remoteInputs)
830 remoteRspFiles = append(remoteRspFiles, inputsListFile)
831 // Add the new rsp file as an extra input to the rule.
832 inputs = append(inputs, inputsListFile)
833 }
Colin Crossef972742021-03-12 17:24:45 -0800834
835 r.rbeParams.OutputFiles = outputs.Strings()
Colin Crosse55bd422021-03-23 13:44:30 -0700836 r.rbeParams.RSPFiles = remoteRspFiles.Strings()
Colin Crossef972742021-03-12 17:24:45 -0800837 rewrapperCommand := r.rbeParams.NoVarTemplate(r.ctx.Config().RBEWrapper())
838 commandString = rewrapperCommand + " bash -c '" + strings.ReplaceAll(commandString, `'`, `'\''`) + "'"
839 }
Dan Willemsen633c5022019-04-12 11:11:38 -0700840 }
841
Colin Cross1d2cf042019-03-29 15:33:06 -0700842 // Ninja doesn't like multiple outputs when depfiles are enabled, move all but the first output to
Colin Cross70c47412021-03-12 17:48:14 -0800843 // ImplicitOutputs. RuleBuilder doesn't use "$out", so the distinction between Outputs and
Colin Cross0cb0d7b2019-07-11 10:59:15 -0700844 // ImplicitOutputs doesn't matter.
Dan Willemsen633c5022019-04-12 11:11:38 -0700845 output := outputs[0]
846 implicitOutputs := outputs[1:]
Colin Cross1d2cf042019-03-29 15:33:06 -0700847
Colin Cross0cb0d7b2019-07-11 10:59:15 -0700848 var rspFile, rspFileContent string
Colin Crossce3a51d2021-03-19 16:22:12 -0700849 var rspFileInputs Paths
850 if len(rspFiles) > 0 {
851 // The first rsp files uses Ninja's rsp file support for the rule
852 rspFile = rspFiles[0].file.String()
Colin Crosse55bd422021-03-23 13:44:30 -0700853 // Use "$in" for rspFileContent to avoid duplicating the list of files in the dependency
854 // list and in the contents of the rsp file. Inputs to the rule that are not in the
855 // rsp file will be listed in Implicits instead of Inputs so they don't show up in "$in".
856 rspFileContent = "$in"
Colin Crossce3a51d2021-03-19 16:22:12 -0700857 rspFileInputs = append(rspFileInputs, rspFiles[0].paths...)
858
859 for _, rspFile := range rspFiles[1:] {
860 // Any additional rsp files need an extra rule to write the file.
861 writeRspFileRule(r.ctx, rspFile.file, rspFile.paths)
862 // The main rule needs to depend on the inputs listed in the extra rsp file.
863 inputs = append(inputs, rspFile.paths...)
864 // The main rule needs to depend on the extra rsp file.
865 inputs = append(inputs, rspFile.file)
866 }
Colin Cross0cb0d7b2019-07-11 10:59:15 -0700867 }
868
Colin Cross8b8bec32019-11-15 13:18:43 -0800869 var pool blueprint.Pool
Colin Crossf1a035e2020-11-16 17:32:30 -0800870 if r.ctx.Config().UseGoma() && r.remoteable.Goma {
Colin Cross8b8bec32019-11-15 13:18:43 -0800871 // When USE_GOMA=true is set and the rule is supported by goma, allow jobs to run outside the local pool.
Colin Crossf1a035e2020-11-16 17:32:30 -0800872 } else if r.ctx.Config().UseRBE() && r.remoteable.RBE {
Ramy Medhat944839a2020-03-31 22:14:52 -0400873 // When USE_RBE=true is set and the rule is supported by RBE, use the remotePool.
874 pool = remotePool
Colin Cross8b8bec32019-11-15 13:18:43 -0800875 } else if r.highmem {
876 pool = highmemPool
Colin Crossf1a035e2020-11-16 17:32:30 -0800877 } else if r.ctx.Config().UseRemoteBuild() {
Colin Cross8b8bec32019-11-15 13:18:43 -0800878 pool = localPool
879 }
880
Sam Delmericod46f6c82023-09-25 12:13:17 +0000881 if ninjaEscapeCommandString {
882 commandString = proptools.NinjaEscape(commandString)
883 }
884
Devin Mooreb6cc64f2024-07-15 22:31:24 +0000885 args_vars := make([]string, len(r.args))
886 i := 0
887 for k, _ := range r.args {
888 args_vars[i] = k
889 i++
890 }
Colin Crossf1a035e2020-11-16 17:32:30 -0800891 r.ctx.Build(r.pctx, BuildParams{
Sam Delmerico285b66a2023-09-25 12:13:17 +0000892 Rule: r.ctx.Rule(r.pctx, name, blueprint.RuleParams{
Sam Delmericod46f6c82023-09-25 12:13:17 +0000893 Command: commandString,
Colin Cross45029782021-03-16 16:49:52 -0700894 CommandDeps: proptools.NinjaEscapeList(tools.Strings()),
Colin Cross0cb0d7b2019-07-11 10:59:15 -0700895 Restat: r.restat,
Colin Cross45029782021-03-16 16:49:52 -0700896 Rspfile: proptools.NinjaEscape(rspFile),
Colin Cross0cb0d7b2019-07-11 10:59:15 -0700897 RspfileContent: rspFileContent,
Colin Cross8b8bec32019-11-15 13:18:43 -0800898 Pool: pool,
Devin Mooreb6cc64f2024-07-15 22:31:24 +0000899 }, args_vars...),
Colin Cross0cb0d7b2019-07-11 10:59:15 -0700900 Inputs: rspFileInputs,
Colin Cross3d680512020-11-13 16:23:53 -0800901 Implicits: inputs,
Colin Crossda6401b2021-04-21 11:32:19 -0700902 OrderOnly: r.OrderOnlys(),
Colin Crossae89abe2021-04-21 11:45:23 -0700903 Validations: r.Validations(),
Dan Willemsen633c5022019-04-12 11:11:38 -0700904 Output: output,
905 ImplicitOutputs: implicitOutputs,
906 Depfile: depFile,
907 Deps: depFormat,
908 Description: desc,
Devin Mooreb6cc64f2024-07-15 22:31:24 +0000909 Args: r.args,
Dan Willemsen633c5022019-04-12 11:11:38 -0700910 })
Colin Crossfeec25b2019-01-30 17:32:39 -0800911}
912
Colin Cross758290d2019-02-01 16:42:32 -0800913// RuleBuilderCommand is a builder for a command in a command line. It can be mutated by its methods to add to the
914// command and track dependencies. The methods mutate the RuleBuilderCommand in place, as well as return the
915// RuleBuilderCommand, so they can be used chained or unchained. All methods that add text implicitly add a single
916// space as a separator from the previous method.
Colin Crossfeec25b2019-01-30 17:32:39 -0800917type RuleBuilderCommand struct {
Colin Crossf1a035e2020-11-16 17:32:30 -0800918 rule *RuleBuilder
919
Cole Faust9a346f62024-01-18 20:12:02 +0000920 buf strings.Builder
921 inputs Paths
922 implicits Paths
923 orderOnlys Paths
924 validations Paths
925 outputs WritablePaths
926 depFiles WritablePaths
927 tools Paths
928 packagedTools []PackagingSpec
929 rspFiles []rspFileAndPaths
Colin Crossce3a51d2021-03-19 16:22:12 -0700930}
931
932type rspFileAndPaths struct {
933 file WritablePath
934 paths Paths
Dan Willemsen633c5022019-04-12 11:11:38 -0700935}
936
Paul Duffin3866b892021-10-04 11:24:48 +0100937func checkPathNotNil(path Path) {
938 if path == nil {
939 panic("rule_builder paths cannot be nil")
940 }
941}
942
Dan Willemsen633c5022019-04-12 11:11:38 -0700943func (c *RuleBuilderCommand) addInput(path Path) string {
Paul Duffin3866b892021-10-04 11:24:48 +0100944 checkPathNotNil(path)
Dan Willemsen633c5022019-04-12 11:11:38 -0700945 c.inputs = append(c.inputs, path)
Colin Crossab020a72021-03-12 17:52:23 -0800946 return c.PathForInput(path)
Dan Willemsen633c5022019-04-12 11:11:38 -0700947}
948
Colin Crossab020a72021-03-12 17:52:23 -0800949func (c *RuleBuilderCommand) addImplicit(path Path) {
Paul Duffin3866b892021-10-04 11:24:48 +0100950 checkPathNotNil(path)
Ramy Medhat2f99eec2020-06-13 17:38:27 -0400951 c.implicits = append(c.implicits, path)
Ramy Medhat2f99eec2020-06-13 17:38:27 -0400952}
953
Colin Crossda71eda2020-02-21 16:55:19 -0800954func (c *RuleBuilderCommand) addOrderOnly(path Path) {
Paul Duffin3866b892021-10-04 11:24:48 +0100955 checkPathNotNil(path)
Colin Crossda71eda2020-02-21 16:55:19 -0800956 c.orderOnlys = append(c.orderOnlys, path)
957}
958
Colin Crossab020a72021-03-12 17:52:23 -0800959// PathForInput takes an input path and returns the appropriate path to use on the command line. If
960// sbox was enabled via a call to RuleBuilder.Sbox() and the path was an output path it returns a
961// path with the placeholder prefix used for outputs in sbox. If sbox is not enabled it returns the
962// original path.
963func (c *RuleBuilderCommand) PathForInput(path Path) string {
964 if c.rule.sbox {
965 rel, inSandbox := c.rule._sboxPathForInputRel(path)
966 if inSandbox {
967 rel = filepath.Join(sboxSandboxBaseDir, rel)
968 }
969 return rel
Inseob Kimf7cd03e2024-09-06 17:25:00 +0900970 } else if c.rule.nsjail {
971 return c.rule.nsjailPathForInputRel(path)
Colin Crossab020a72021-03-12 17:52:23 -0800972 }
973 return path.String()
974}
975
976// PathsForInputs takes a list of input paths and returns the appropriate paths to use on the
977// command line. If sbox was enabled via a call to RuleBuilder.Sbox() a path was an output path, it
978// returns the path with the placeholder prefix used for outputs in sbox. If sbox is not enabled it
979// returns the original paths.
980func (c *RuleBuilderCommand) PathsForInputs(paths Paths) []string {
981 ret := make([]string, len(paths))
982 for i, path := range paths {
983 ret[i] = c.PathForInput(path)
984 }
985 return ret
986}
987
Colin Crossf1a035e2020-11-16 17:32:30 -0800988// PathForOutput takes an output path and returns the appropriate path to use on the command
989// line. If sbox was enabled via a call to RuleBuilder.Sbox(), it returns a path with the
990// placeholder prefix used for outputs in sbox. If sbox is not enabled it returns the
991// original path.
992func (c *RuleBuilderCommand) PathForOutput(path WritablePath) string {
993 if c.rule.sbox {
994 // Errors will be handled in RuleBuilder.Build where we have a context to report them
995 rel, _, _ := maybeRelErr(c.rule.outDir.String(), path.String())
996 return filepath.Join(sboxOutDir, rel)
Inseob Kimf7cd03e2024-09-06 17:25:00 +0900997 } else if c.rule.nsjail {
998 // Errors will be handled in RuleBuilder.Build where we have a context to report them
999 rel, _, _ := maybeRelErr(c.rule.outDir.String(), path.String())
1000 return filepath.Join(nsjailOutDir, rel)
Dan Willemsen633c5022019-04-12 11:11:38 -07001001 }
1002 return path.String()
Colin Crossfeec25b2019-01-30 17:32:39 -08001003}
1004
Colin Crossba9e4032020-11-24 16:32:22 -08001005func sboxPathForToolRel(ctx BuilderContext, path Path) string {
1006 // Errors will be handled in RuleBuilder.Build where we have a context to report them
Cole Faust3b703f32023-10-16 13:30:51 -07001007 toolDir := pathForInstall(ctx, ctx.Config().BuildOS, ctx.Config().BuildArch, "")
Colin Cross790ef352021-10-25 19:15:55 -07001008 relOutSoong, isRelOutSoong, _ := maybeRelErr(toolDir.String(), path.String())
1009 if isRelOutSoong {
1010 // The tool is in the Soong output directory, it will be copied to __SBOX_OUT_DIR__/tools/out
1011 return filepath.Join(sboxToolsSubDir, "out", relOutSoong)
Colin Crossba9e4032020-11-24 16:32:22 -08001012 }
1013 // The tool is in the source directory, it will be copied to __SBOX_OUT_DIR__/tools/src
1014 return filepath.Join(sboxToolsSubDir, "src", path.String())
1015}
1016
Colin Crossab020a72021-03-12 17:52:23 -08001017func (r *RuleBuilder) _sboxPathForInputRel(path Path) (rel string, inSandbox bool) {
1018 // Errors will be handled in RuleBuilder.Build where we have a context to report them
1019 rel, isRelSboxOut, _ := maybeRelErr(r.outDir.String(), path.String())
1020 if isRelSboxOut {
1021 return filepath.Join(sboxOutSubDir, rel), true
1022 }
1023 if r.sboxInputs {
1024 // When sandboxing inputs all inputs have to be copied into the sandbox. Input files that
1025 // are outputs of other rules could be an arbitrary absolute path if OUT_DIR is set, so they
1026 // will be copied to relative paths under __SBOX_OUT_DIR__/out.
Cole Fauste8561c62023-11-30 17:26:37 -08001027 rel, isRelOut, _ := maybeRelErr(r.ctx.Config().OutDir(), path.String())
Colin Crossab020a72021-03-12 17:52:23 -08001028 if isRelOut {
1029 return filepath.Join(sboxOutSubDir, rel), true
1030 }
1031 }
1032 return path.String(), false
1033}
1034
1035func (r *RuleBuilder) sboxPathForInputRel(path Path) string {
1036 rel, _ := r._sboxPathForInputRel(path)
1037 return rel
1038}
1039
1040func (r *RuleBuilder) sboxPathsForInputsRel(paths Paths) []string {
1041 ret := make([]string, len(paths))
1042 for i, path := range paths {
1043 ret[i] = r.sboxPathForInputRel(path)
1044 }
1045 return ret
1046}
1047
Colin Crossba9e4032020-11-24 16:32:22 -08001048func sboxPathForPackagedToolRel(spec PackagingSpec) string {
1049 return filepath.Join(sboxToolsSubDir, "out", spec.relPathInPackage)
1050}
1051
Inseob Kimf7cd03e2024-09-06 17:25:00 +09001052func nsjailPathForToolRel(ctx BuilderContext, path Path) string {
1053 // Errors will be handled in RuleBuilder.Build where we have a context to report them
1054 toolDir := pathForInstall(ctx, ctx.Config().BuildOS, ctx.Config().BuildArch, "")
1055 relOutSoong, isRelOutSoong, _ := maybeRelErr(toolDir.String(), path.String())
1056 if isRelOutSoong {
1057 // The tool is in the Soong output directory, it will be copied to __SBOX_OUT_DIR__/tools/out
1058 return filepath.Join(nsjailToolsSubDir, "out", relOutSoong)
1059 }
1060 // The tool is in the source directory, it will be copied to __SBOX_OUT_DIR__/tools/src
1061 return filepath.Join(nsjailToolsSubDir, "src", path.String())
1062}
1063
1064func (r *RuleBuilder) nsjailPathForInputRel(path Path) string {
1065 rel, isRelSboxOut, _ := maybeRelErr(r.outDir.String(), path.String())
1066 if isRelSboxOut {
1067 return filepath.Join(nsjailOutDir, rel)
1068 }
1069 return path.String()
1070}
1071
1072func (r *RuleBuilder) nsjailPathsForInputsRel(paths Paths) []string {
1073 ret := make([]string, len(paths))
1074 for i, path := range paths {
1075 ret[i] = r.nsjailPathForInputRel(path)
1076 }
1077 return ret
1078}
1079
1080func nsjailPathForPackagedToolRel(spec PackagingSpec) string {
1081 return filepath.Join(nsjailToolsSubDir, "out", spec.relPathInPackage)
1082}
1083
Colin Crossd11cf622021-03-23 22:30:35 -07001084// PathForPackagedTool takes a PackageSpec for a tool and returns the corresponding path for the
1085// tool after copying it into the sandbox. This can be used on the RuleBuilder command line to
1086// reference the tool.
1087func (c *RuleBuilderCommand) PathForPackagedTool(spec PackagingSpec) string {
Inseob Kimf7cd03e2024-09-06 17:25:00 +09001088 if c.rule.sboxTools {
1089 return filepath.Join(sboxSandboxBaseDir, sboxPathForPackagedToolRel(spec))
1090 } else if c.rule.nsjail {
1091 return nsjailPathForPackagedToolRel(spec)
1092 } else {
1093 panic("PathForPackagedTool() requires SandboxTools() or Nsjail()")
Colin Crossd11cf622021-03-23 22:30:35 -07001094 }
Colin Crossd11cf622021-03-23 22:30:35 -07001095}
1096
Colin Crossba9e4032020-11-24 16:32:22 -08001097// PathForTool takes a path to a tool, which may be an output file or a source file, and returns
1098// the corresponding path for the tool in the sbox sandbox if sbox is enabled, or the original path
1099// if it is not. This can be used on the RuleBuilder command line to reference the tool.
1100func (c *RuleBuilderCommand) PathForTool(path Path) string {
1101 if c.rule.sbox && c.rule.sboxTools {
1102 return filepath.Join(sboxSandboxBaseDir, sboxPathForToolRel(c.rule.ctx, path))
Inseob Kimf7cd03e2024-09-06 17:25:00 +09001103 } else if c.rule.nsjail {
1104 return nsjailPathForToolRel(c.rule.ctx, path)
Colin Crossba9e4032020-11-24 16:32:22 -08001105 }
1106 return path.String()
1107}
1108
Colin Crossd11cf622021-03-23 22:30:35 -07001109// PathsForTools takes a list of paths to tools, which may be output files or source files, and
1110// returns the corresponding paths for the tools in the sbox sandbox if sbox is enabled, or the
1111// original paths if it is not. This can be used on the RuleBuilder command line to reference the tool.
1112func (c *RuleBuilderCommand) PathsForTools(paths Paths) []string {
1113 if c.rule.sbox && c.rule.sboxTools {
1114 var ret []string
1115 for _, path := range paths {
1116 ret = append(ret, filepath.Join(sboxSandboxBaseDir, sboxPathForToolRel(c.rule.ctx, path)))
1117 }
1118 return ret
Inseob Kimf7cd03e2024-09-06 17:25:00 +09001119 } else if c.rule.nsjail {
1120 var ret []string
1121 for _, path := range paths {
1122 ret = append(ret, nsjailPathForToolRel(c.rule.ctx, path))
1123 }
1124 return ret
Colin Crossd11cf622021-03-23 22:30:35 -07001125 }
1126 return paths.Strings()
1127}
1128
Colin Crossba9e4032020-11-24 16:32:22 -08001129// PackagedTool adds the specified tool path to the command line. It can only be used with tool
1130// sandboxing enabled by SandboxTools(), and will copy the tool into the sandbox.
1131func (c *RuleBuilderCommand) PackagedTool(spec PackagingSpec) *RuleBuilderCommand {
Colin Crossba9e4032020-11-24 16:32:22 -08001132 c.packagedTools = append(c.packagedTools, spec)
Inseob Kimf7cd03e2024-09-06 17:25:00 +09001133 if c.rule.sboxTools {
1134 c.Text(sboxPathForPackagedToolRel(spec))
1135 } else if c.rule.nsjail {
1136 c.Text(nsjailPathForPackagedToolRel(spec))
1137 } else {
1138 panic("PackagedTool() requires SandboxTools() or Nsjail()")
1139 }
Colin Crossba9e4032020-11-24 16:32:22 -08001140 return c
1141}
1142
1143// ImplicitPackagedTool copies the specified tool into the sandbox without modifying the command
1144// line. It can only be used with tool sandboxing enabled by SandboxTools().
1145func (c *RuleBuilderCommand) ImplicitPackagedTool(spec PackagingSpec) *RuleBuilderCommand {
Inseob Kimf7cd03e2024-09-06 17:25:00 +09001146 if !c.rule.sboxTools && !c.rule.nsjail {
1147 panic("ImplicitPackagedTool() requires SandboxTools() or Nsjail()")
Colin Crossba9e4032020-11-24 16:32:22 -08001148 }
1149
1150 c.packagedTools = append(c.packagedTools, spec)
1151 return c
1152}
1153
1154// ImplicitPackagedTools copies the specified tools into the sandbox without modifying the command
1155// line. It can only be used with tool sandboxing enabled by SandboxTools().
1156func (c *RuleBuilderCommand) ImplicitPackagedTools(specs []PackagingSpec) *RuleBuilderCommand {
Inseob Kimf7cd03e2024-09-06 17:25:00 +09001157 if !c.rule.sboxTools && !c.rule.nsjail {
1158 panic("ImplicitPackagedTools() requires SandboxTools() or Nsjail()")
Colin Crossba9e4032020-11-24 16:32:22 -08001159 }
1160
1161 c.packagedTools = append(c.packagedTools, specs...)
1162 return c
1163}
1164
Colin Cross758290d2019-02-01 16:42:32 -08001165// Text adds the specified raw text to the command line. The text should not contain input or output paths or the
1166// rule will not have them listed in its dependencies or outputs.
Colin Crossfeec25b2019-01-30 17:32:39 -08001167func (c *RuleBuilderCommand) Text(text string) *RuleBuilderCommand {
Colin Crosscfec40c2019-07-08 17:07:18 -07001168 if c.buf.Len() > 0 {
1169 c.buf.WriteByte(' ')
Colin Crossfeec25b2019-01-30 17:32:39 -08001170 }
Colin Crosscfec40c2019-07-08 17:07:18 -07001171 c.buf.WriteString(text)
Colin Crossfeec25b2019-01-30 17:32:39 -08001172 return c
1173}
1174
Colin Cross758290d2019-02-01 16:42:32 -08001175// Textf adds the specified formatted text to the command line. The text should not contain input or output paths or
1176// the rule will not have them listed in its dependencies or outputs.
Colin Crossfeec25b2019-01-30 17:32:39 -08001177func (c *RuleBuilderCommand) Textf(format string, a ...interface{}) *RuleBuilderCommand {
1178 return c.Text(fmt.Sprintf(format, a...))
1179}
1180
Colin Cross758290d2019-02-01 16:42:32 -08001181// Flag adds the specified raw text to the command line. The text should not contain input or output paths or the
1182// rule will not have them listed in its dependencies or outputs.
Colin Crossfeec25b2019-01-30 17:32:39 -08001183func (c *RuleBuilderCommand) Flag(flag string) *RuleBuilderCommand {
1184 return c.Text(flag)
1185}
1186
Colin Crossab054432019-07-15 16:13:59 -07001187// OptionalFlag adds the specified raw text to the command line if it is not nil. The text should not contain input or
1188// output paths or the rule will not have them listed in its dependencies or outputs.
1189func (c *RuleBuilderCommand) OptionalFlag(flag *string) *RuleBuilderCommand {
1190 if flag != nil {
1191 c.Text(*flag)
1192 }
1193
1194 return c
1195}
1196
Colin Cross92b7d582019-03-29 15:32:51 -07001197// Flags adds the specified raw text to the command line. The text should not contain input or output paths or the
1198// rule will not have them listed in its dependencies or outputs.
1199func (c *RuleBuilderCommand) Flags(flags []string) *RuleBuilderCommand {
1200 for _, flag := range flags {
1201 c.Text(flag)
1202 }
1203 return c
1204}
1205
Colin Cross758290d2019-02-01 16:42:32 -08001206// FlagWithArg adds the specified flag and argument text to the command line, with no separator between them. The flag
1207// and argument should not contain input or output paths or the rule will not have them listed in its dependencies or
1208// outputs.
Colin Crossfeec25b2019-01-30 17:32:39 -08001209func (c *RuleBuilderCommand) FlagWithArg(flag, arg string) *RuleBuilderCommand {
1210 return c.Text(flag + arg)
1211}
1212
Colin Crossc7ed0042019-02-11 14:11:09 -08001213// FlagForEachArg adds the specified flag joined with each argument to the command line. The result is identical to
1214// calling FlagWithArg for argument.
1215func (c *RuleBuilderCommand) FlagForEachArg(flag string, args []string) *RuleBuilderCommand {
1216 for _, arg := range args {
1217 c.FlagWithArg(flag, arg)
1218 }
1219 return c
1220}
1221
Roland Levillain2da5d9a2019-02-27 16:56:41 +00001222// FlagWithList adds the specified flag and list of arguments to the command line, with the arguments joined by sep
Colin Cross758290d2019-02-01 16:42:32 -08001223// and no separator between the flag and arguments. The flag and arguments should not contain input or output paths or
1224// the rule will not have them listed in its dependencies or outputs.
Colin Crossfeec25b2019-01-30 17:32:39 -08001225func (c *RuleBuilderCommand) FlagWithList(flag string, list []string, sep string) *RuleBuilderCommand {
1226 return c.Text(flag + strings.Join(list, sep))
1227}
1228
Colin Cross758290d2019-02-01 16:42:32 -08001229// Tool adds the specified tool path to the command line. The path will be also added to the dependencies returned by
1230// RuleBuilder.Tools.
Colin Cross69f59a32019-02-15 10:39:37 -08001231func (c *RuleBuilderCommand) Tool(path Path) *RuleBuilderCommand {
Paul Duffin3866b892021-10-04 11:24:48 +01001232 checkPathNotNil(path)
Colin Crossfeec25b2019-01-30 17:32:39 -08001233 c.tools = append(c.tools, path)
Colin Crossba9e4032020-11-24 16:32:22 -08001234 return c.Text(c.PathForTool(path))
1235}
1236
1237// Tool adds the specified tool path to the dependencies returned by RuleBuilder.Tools.
1238func (c *RuleBuilderCommand) ImplicitTool(path Path) *RuleBuilderCommand {
Paul Duffin3866b892021-10-04 11:24:48 +01001239 checkPathNotNil(path)
Colin Crossba9e4032020-11-24 16:32:22 -08001240 c.tools = append(c.tools, path)
1241 return c
1242}
1243
1244// Tool adds the specified tool path to the dependencies returned by RuleBuilder.Tools.
1245func (c *RuleBuilderCommand) ImplicitTools(paths Paths) *RuleBuilderCommand {
Paul Duffin3866b892021-10-04 11:24:48 +01001246 for _, path := range paths {
1247 c.ImplicitTool(path)
1248 }
Colin Crossba9e4032020-11-24 16:32:22 -08001249 return c
Colin Crossfeec25b2019-01-30 17:32:39 -08001250}
1251
Colin Crossee94d6a2019-07-08 17:08:34 -07001252// BuiltTool adds the specified tool path that was built using a host Soong module to the command line. The path will
1253// be also added to the dependencies returned by RuleBuilder.Tools.
1254//
1255// It is equivalent to:
Colin Crossd079e0b2022-08-16 10:27:33 -07001256//
1257// cmd.Tool(ctx.Config().HostToolPath(ctx, tool))
Colin Crossf1a035e2020-11-16 17:32:30 -08001258func (c *RuleBuilderCommand) BuiltTool(tool string) *RuleBuilderCommand {
Colin Cross9b698b62021-12-22 09:55:32 -08001259 if c.rule.ctx.Config().UseHostMusl() {
1260 // If the host is using musl, assume that the tool was built against musl libc and include
1261 // libc_musl.so in the sandbox.
1262 // TODO(ccross): if we supported adding new dependencies during GenerateAndroidBuildActions
1263 // this could be a dependency + TransitivePackagingSpecs.
1264 c.ImplicitTool(c.rule.ctx.Config().HostJNIToolPath(c.rule.ctx, "libc_musl"))
1265 }
1266 return c.builtToolWithoutDeps(tool)
1267}
1268
1269// builtToolWithoutDeps is similar to BuiltTool, but doesn't add any dependencies. It is used
1270// internally by RuleBuilder for helper tools that are known to be compiled statically.
1271func (c *RuleBuilderCommand) builtToolWithoutDeps(tool string) *RuleBuilderCommand {
Colin Crossf1a035e2020-11-16 17:32:30 -08001272 return c.Tool(c.rule.ctx.Config().HostToolPath(c.rule.ctx, tool))
Colin Crossee94d6a2019-07-08 17:08:34 -07001273}
1274
1275// PrebuiltBuildTool adds the specified tool path from prebuils/build-tools. The path will be also added to the
1276// dependencies returned by RuleBuilder.Tools.
1277//
1278// It is equivalent to:
Colin Crossd079e0b2022-08-16 10:27:33 -07001279//
1280// cmd.Tool(ctx.Config().PrebuiltBuildTool(ctx, tool))
Colin Crossee94d6a2019-07-08 17:08:34 -07001281func (c *RuleBuilderCommand) PrebuiltBuildTool(ctx PathContext, tool string) *RuleBuilderCommand {
1282 return c.Tool(ctx.Config().PrebuiltBuildTool(ctx, tool))
1283}
1284
Colin Cross758290d2019-02-01 16:42:32 -08001285// Input adds the specified input path to the command line. The path will also be added to the dependencies returned by
1286// RuleBuilder.Inputs.
Colin Cross69f59a32019-02-15 10:39:37 -08001287func (c *RuleBuilderCommand) Input(path Path) *RuleBuilderCommand {
Dan Willemsen633c5022019-04-12 11:11:38 -07001288 return c.Text(c.addInput(path))
Colin Crossfeec25b2019-01-30 17:32:39 -08001289}
1290
Colin Cross758290d2019-02-01 16:42:32 -08001291// Inputs adds the specified input paths to the command line, separated by spaces. The paths will also be added to the
1292// dependencies returned by RuleBuilder.Inputs.
Colin Cross69f59a32019-02-15 10:39:37 -08001293func (c *RuleBuilderCommand) Inputs(paths Paths) *RuleBuilderCommand {
Colin Cross758290d2019-02-01 16:42:32 -08001294 for _, path := range paths {
1295 c.Input(path)
1296 }
1297 return c
1298}
1299
1300// Implicit adds the specified input path to the dependencies returned by RuleBuilder.Inputs without modifying the
1301// command line.
Colin Cross69f59a32019-02-15 10:39:37 -08001302func (c *RuleBuilderCommand) Implicit(path Path) *RuleBuilderCommand {
Ramy Medhat2f99eec2020-06-13 17:38:27 -04001303 c.addImplicit(path)
Colin Crossfeec25b2019-01-30 17:32:39 -08001304 return c
1305}
1306
Colin Cross758290d2019-02-01 16:42:32 -08001307// Implicits adds the specified input paths to the dependencies returned by RuleBuilder.Inputs without modifying the
1308// command line.
Colin Cross69f59a32019-02-15 10:39:37 -08001309func (c *RuleBuilderCommand) Implicits(paths Paths) *RuleBuilderCommand {
Dan Willemsen633c5022019-04-12 11:11:38 -07001310 for _, path := range paths {
Ramy Medhat2f99eec2020-06-13 17:38:27 -04001311 c.addImplicit(path)
Dan Willemsen633c5022019-04-12 11:11:38 -07001312 }
Colin Crossfeec25b2019-01-30 17:32:39 -08001313 return c
1314}
1315
Ramy Medhat2f99eec2020-06-13 17:38:27 -04001316// GetImplicits returns the command's implicit inputs.
1317func (c *RuleBuilderCommand) GetImplicits() Paths {
1318 return c.implicits
1319}
1320
Colin Crossda71eda2020-02-21 16:55:19 -08001321// OrderOnly adds the specified input path to the dependencies returned by RuleBuilder.OrderOnlys
1322// without modifying the command line.
1323func (c *RuleBuilderCommand) OrderOnly(path Path) *RuleBuilderCommand {
1324 c.addOrderOnly(path)
1325 return c
1326}
1327
1328// OrderOnlys adds the specified input paths to the dependencies returned by RuleBuilder.OrderOnlys
1329// without modifying the command line.
1330func (c *RuleBuilderCommand) OrderOnlys(paths Paths) *RuleBuilderCommand {
1331 for _, path := range paths {
1332 c.addOrderOnly(path)
1333 }
1334 return c
1335}
1336
Colin Crossae89abe2021-04-21 11:45:23 -07001337// Validation adds the specified input path to the validation dependencies by
1338// RuleBuilder.Validations without modifying the command line.
1339func (c *RuleBuilderCommand) Validation(path Path) *RuleBuilderCommand {
Paul Duffin3866b892021-10-04 11:24:48 +01001340 checkPathNotNil(path)
Colin Crossae89abe2021-04-21 11:45:23 -07001341 c.validations = append(c.validations, path)
1342 return c
1343}
1344
1345// Validations adds the specified input paths to the validation dependencies by
1346// RuleBuilder.Validations without modifying the command line.
1347func (c *RuleBuilderCommand) Validations(paths Paths) *RuleBuilderCommand {
Paul Duffin3866b892021-10-04 11:24:48 +01001348 for _, path := range paths {
1349 c.Validation(path)
1350 }
Colin Crossae89abe2021-04-21 11:45:23 -07001351 return c
1352}
1353
Colin Cross758290d2019-02-01 16:42:32 -08001354// Output adds the specified output path to the command line. The path will also be added to the outputs returned by
1355// RuleBuilder.Outputs.
Colin Cross69f59a32019-02-15 10:39:37 -08001356func (c *RuleBuilderCommand) Output(path WritablePath) *RuleBuilderCommand {
Paul Duffin3866b892021-10-04 11:24:48 +01001357 checkPathNotNil(path)
Colin Crossfeec25b2019-01-30 17:32:39 -08001358 c.outputs = append(c.outputs, path)
Colin Crossf1a035e2020-11-16 17:32:30 -08001359 return c.Text(c.PathForOutput(path))
Colin Crossfeec25b2019-01-30 17:32:39 -08001360}
1361
Colin Cross758290d2019-02-01 16:42:32 -08001362// Outputs adds the specified output paths to the command line, separated by spaces. The paths will also be added to
1363// the outputs returned by RuleBuilder.Outputs.
Colin Cross69f59a32019-02-15 10:39:37 -08001364func (c *RuleBuilderCommand) Outputs(paths WritablePaths) *RuleBuilderCommand {
Colin Cross758290d2019-02-01 16:42:32 -08001365 for _, path := range paths {
1366 c.Output(path)
1367 }
1368 return c
1369}
1370
Dan Willemsen1945a4b2019-06-04 17:10:41 -07001371// OutputDir adds the output directory to the command line. This is only available when used with RuleBuilder.Sbox,
1372// and will be the temporary output directory managed by sbox, not the final one.
Anas Sulaimanb4dff132024-02-07 21:58:46 +00001373func (c *RuleBuilderCommand) OutputDir(subPathComponents ...string) *RuleBuilderCommand {
Colin Crossf1a035e2020-11-16 17:32:30 -08001374 if !c.rule.sbox {
Dan Willemsen1945a4b2019-06-04 17:10:41 -07001375 panic("OutputDir only valid with Sbox")
1376 }
Anas Sulaimanb4dff132024-02-07 21:58:46 +00001377 path := sboxOutDir
1378 if len(subPathComponents) > 0 {
1379 path = filepath.Join(append([]string{sboxOutDir}, subPathComponents...)...)
1380 }
1381 return c.Text(path)
Dan Willemsen1945a4b2019-06-04 17:10:41 -07001382}
1383
Colin Cross1d2cf042019-03-29 15:33:06 -07001384// DepFile adds the specified depfile path to the paths returned by RuleBuilder.DepFiles and adds it to the command
1385// line, and causes RuleBuilder.Build file to set the depfile flag for ninja. If multiple depfiles are added to
1386// commands in a single RuleBuilder then RuleBuilder.Build will add an extra command to merge the depfiles together.
1387func (c *RuleBuilderCommand) DepFile(path WritablePath) *RuleBuilderCommand {
Paul Duffin3866b892021-10-04 11:24:48 +01001388 checkPathNotNil(path)
Colin Cross1d2cf042019-03-29 15:33:06 -07001389 c.depFiles = append(c.depFiles, path)
Colin Crossf1a035e2020-11-16 17:32:30 -08001390 return c.Text(c.PathForOutput(path))
Colin Cross1d2cf042019-03-29 15:33:06 -07001391}
1392
Colin Cross758290d2019-02-01 16:42:32 -08001393// ImplicitOutput adds the specified output path to the dependencies returned by RuleBuilder.Outputs without modifying
1394// the command line.
Colin Cross69f59a32019-02-15 10:39:37 -08001395func (c *RuleBuilderCommand) ImplicitOutput(path WritablePath) *RuleBuilderCommand {
Colin Crossfeec25b2019-01-30 17:32:39 -08001396 c.outputs = append(c.outputs, path)
1397 return c
1398}
1399
Colin Cross758290d2019-02-01 16:42:32 -08001400// ImplicitOutputs adds the specified output paths to the dependencies returned by RuleBuilder.Outputs without modifying
1401// the command line.
Colin Cross69f59a32019-02-15 10:39:37 -08001402func (c *RuleBuilderCommand) ImplicitOutputs(paths WritablePaths) *RuleBuilderCommand {
Colin Cross758290d2019-02-01 16:42:32 -08001403 c.outputs = append(c.outputs, paths...)
1404 return c
1405}
1406
Colin Cross1d2cf042019-03-29 15:33:06 -07001407// ImplicitDepFile adds the specified depfile path to the paths returned by RuleBuilder.DepFiles without modifying
1408// the command line, and causes RuleBuilder.Build file to set the depfile flag for ninja. If multiple depfiles
1409// are added to commands in a single RuleBuilder then RuleBuilder.Build will add an extra command to merge the
1410// depfiles together.
1411func (c *RuleBuilderCommand) ImplicitDepFile(path WritablePath) *RuleBuilderCommand {
1412 c.depFiles = append(c.depFiles, path)
1413 return c
1414}
1415
Colin Cross758290d2019-02-01 16:42:32 -08001416// FlagWithInput adds the specified flag and input path to the command line, with no separator between them. The path
1417// will also be added to the dependencies returned by RuleBuilder.Inputs.
Colin Cross69f59a32019-02-15 10:39:37 -08001418func (c *RuleBuilderCommand) FlagWithInput(flag string, path Path) *RuleBuilderCommand {
Dan Willemsen633c5022019-04-12 11:11:38 -07001419 return c.Text(flag + c.addInput(path))
Colin Crossfeec25b2019-01-30 17:32:39 -08001420}
1421
Colin Cross758290d2019-02-01 16:42:32 -08001422// FlagWithInputList adds the specified flag and input paths to the command line, with the inputs joined by sep
1423// and no separator between the flag and inputs. The input paths will also be added to the dependencies returned by
1424// RuleBuilder.Inputs.
Colin Cross69f59a32019-02-15 10:39:37 -08001425func (c *RuleBuilderCommand) FlagWithInputList(flag string, paths Paths, sep string) *RuleBuilderCommand {
Dan Willemsen633c5022019-04-12 11:11:38 -07001426 strs := make([]string, len(paths))
1427 for i, path := range paths {
1428 strs[i] = c.addInput(path)
1429 }
1430 return c.FlagWithList(flag, strs, sep)
Colin Crossfeec25b2019-01-30 17:32:39 -08001431}
1432
Colin Cross758290d2019-02-01 16:42:32 -08001433// FlagForEachInput adds the specified flag joined with each input path to the command line. The input paths will also
1434// be added to the dependencies returned by RuleBuilder.Inputs. The result is identical to calling FlagWithInput for
1435// each input path.
Colin Cross69f59a32019-02-15 10:39:37 -08001436func (c *RuleBuilderCommand) FlagForEachInput(flag string, paths Paths) *RuleBuilderCommand {
Colin Cross758290d2019-02-01 16:42:32 -08001437 for _, path := range paths {
1438 c.FlagWithInput(flag, path)
1439 }
1440 return c
1441}
1442
1443// FlagWithOutput adds the specified flag and output path to the command line, with no separator between them. The path
1444// will also be added to the outputs returned by RuleBuilder.Outputs.
Colin Cross69f59a32019-02-15 10:39:37 -08001445func (c *RuleBuilderCommand) FlagWithOutput(flag string, path WritablePath) *RuleBuilderCommand {
Colin Crossfeec25b2019-01-30 17:32:39 -08001446 c.outputs = append(c.outputs, path)
Colin Crossf1a035e2020-11-16 17:32:30 -08001447 return c.Text(flag + c.PathForOutput(path))
Colin Crossfeec25b2019-01-30 17:32:39 -08001448}
1449
Colin Cross1d2cf042019-03-29 15:33:06 -07001450// FlagWithDepFile adds the specified flag and depfile path to the command line, with no separator between them. The path
1451// will also be added to the outputs returned by RuleBuilder.Outputs.
1452func (c *RuleBuilderCommand) FlagWithDepFile(flag string, path WritablePath) *RuleBuilderCommand {
1453 c.depFiles = append(c.depFiles, path)
Colin Crossf1a035e2020-11-16 17:32:30 -08001454 return c.Text(flag + c.PathForOutput(path))
Colin Cross1d2cf042019-03-29 15:33:06 -07001455}
1456
Colin Crossce3a51d2021-03-19 16:22:12 -07001457// FlagWithRspFileInputList adds the specified flag and path to an rspfile to the command line, with
1458// no separator between them. The paths will be written to the rspfile. If sbox is enabled, the
1459// rspfile must be outside the sbox directory. The first use of FlagWithRspFileInputList in any
1460// RuleBuilderCommand of a RuleBuilder will use Ninja's rsp file support for the rule, additional
1461// uses will result in an auxiliary rules to write the rspFile contents.
Colin Cross70c47412021-03-12 17:48:14 -08001462func (c *RuleBuilderCommand) FlagWithRspFileInputList(flag string, rspFile WritablePath, paths Paths) *RuleBuilderCommand {
Colin Cross0cb0d7b2019-07-11 10:59:15 -07001463 // Use an empty slice if paths is nil, the non-nil slice is used as an indicator that the rsp file must be
1464 // generated.
1465 if paths == nil {
1466 paths = Paths{}
1467 }
1468
Colin Crossce3a51d2021-03-19 16:22:12 -07001469 c.rspFiles = append(c.rspFiles, rspFileAndPaths{rspFile, paths})
Colin Cross0cb0d7b2019-07-11 10:59:15 -07001470
Colin Cross70c47412021-03-12 17:48:14 -08001471 if c.rule.sbox {
1472 if _, isRel, _ := maybeRelErr(c.rule.outDir.String(), rspFile.String()); isRel {
1473 panic(fmt.Errorf("FlagWithRspFileInputList rspfile %q must not be inside out dir %q",
1474 rspFile.String(), c.rule.outDir.String()))
1475 }
1476 }
1477
Colin Crossab020a72021-03-12 17:52:23 -08001478 c.FlagWithArg(flag, c.PathForInput(rspFile))
Colin Cross0cb0d7b2019-07-11 10:59:15 -07001479 return c
1480}
1481
Colin Cross758290d2019-02-01 16:42:32 -08001482// String returns the command line.
1483func (c *RuleBuilderCommand) String() string {
Colin Crosscfec40c2019-07-08 17:07:18 -07001484 return c.buf.String()
Colin Cross758290d2019-02-01 16:42:32 -08001485}
Colin Cross1d2cf042019-03-29 15:33:06 -07001486
Colin Crosse16ce362020-11-12 08:29:30 -08001487// RuleBuilderSboxProtoForTests takes the BuildParams for the manifest passed to RuleBuilder.Sbox()
1488// and returns sbox testproto generated by the RuleBuilder.
Colin Crossf61d03d2023-11-02 16:56:39 -07001489func RuleBuilderSboxProtoForTests(t *testing.T, ctx *TestContext, params TestingBuildParams) *sbox_proto.Manifest {
Colin Crosse16ce362020-11-12 08:29:30 -08001490 t.Helper()
Colin Crossf61d03d2023-11-02 16:56:39 -07001491 content := ContentFromFileRuleForTests(t, ctx, params)
Colin Crosse16ce362020-11-12 08:29:30 -08001492 manifest := sbox_proto.Manifest{}
Dan Willemsen4591b642021-05-24 14:24:12 -07001493 err := prototext.Unmarshal([]byte(content), &manifest)
Colin Crosse16ce362020-11-12 08:29:30 -08001494 if err != nil {
1495 t.Fatalf("failed to unmarshal manifest: %s", err.Error())
1496 }
1497 return &manifest
1498}
1499
Colin Cross1d2cf042019-03-29 15:33:06 -07001500func ninjaNameEscape(s string) string {
1501 b := []byte(s)
1502 escaped := false
1503 for i, c := range b {
1504 valid := (c >= 'a' && c <= 'z') ||
1505 (c >= 'A' && c <= 'Z') ||
1506 (c >= '0' && c <= '9') ||
1507 (c == '_') ||
1508 (c == '-') ||
1509 (c == '.')
1510 if !valid {
1511 b[i] = '_'
1512 escaped = true
1513 }
1514 }
1515 if escaped {
1516 s = string(b)
1517 }
1518 return s
1519}
Colin Cross3d680512020-11-13 16:23:53 -08001520
1521// hashSrcFiles returns a hash of the list of source files. It is used to ensure the command line
1522// or the sbox textproto manifest change even if the input files are not listed on the command line.
1523func hashSrcFiles(srcFiles Paths) string {
1524 h := sha256.New()
1525 srcFileList := strings.Join(srcFiles.Strings(), "\n")
1526 h.Write([]byte(srcFileList))
1527 return fmt.Sprintf("%x", h.Sum(nil))
1528}
Colin Crossf1a035e2020-11-16 17:32:30 -08001529
1530// BuilderContextForTesting returns a BuilderContext for the given config that can be used for tests
1531// that need to call methods that take a BuilderContext.
1532func BuilderContextForTesting(config Config) BuilderContext {
1533 pathCtx := PathContextForTesting(config)
1534 return builderContextForTests{
1535 PathContext: pathCtx,
1536 }
1537}
1538
1539type builderContextForTests struct {
1540 PathContext
1541}
1542
1543func (builderContextForTests) Rule(PackageContext, string, blueprint.RuleParams, ...string) blueprint.Rule {
1544 return nil
1545}
1546func (builderContextForTests) Build(PackageContext, BuildParams) {}
Colin Crossef972742021-03-12 17:24:45 -08001547
Colin Crosse55bd422021-03-23 13:44:30 -07001548func writeRspFileRule(ctx BuilderContext, rspFile WritablePath, paths Paths) {
1549 buf := &strings.Builder{}
1550 err := response.WriteRspFile(buf, paths.Strings())
1551 if err != nil {
1552 // There should never be I/O errors writing to a bytes.Buffer.
1553 panic(err)
Colin Crossef972742021-03-12 17:24:45 -08001554 }
Colin Crosse55bd422021-03-23 13:44:30 -07001555 WriteFileRule(ctx, rspFile, buf.String())
Colin Crossef972742021-03-12 17:24:45 -08001556}