blob: 89cb9cfe79e8262cdd519cdd2932af7f31e62692 [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
Colin Cross758290d2019-02-01 16:42:32 -0800491// Build adds the built command line to the build graph, with dependencies on Inputs and Tools, and output files for
492// Outputs.
Colin Crossf1a035e2020-11-16 17:32:30 -0800493func (r *RuleBuilder) Build(name string, desc string) {
Cole Faust2f3791f2024-11-25 15:49:57 -0800494 r.build(name, desc)
Sam Delmerico285b66a2023-09-25 12:13:17 +0000495}
496
Cole Faust63ea1f92024-08-27 11:42:26 -0700497var sandboxEnvOnceKey = NewOnceKey("sandbox_environment_variables")
498
Cole Faust2f3791f2024-11-25 15:49:57 -0800499func (r *RuleBuilder) build(name string, desc string) {
Colin Cross1d2cf042019-03-29 15:33:06 -0700500 name = ninjaNameEscape(name)
501
Colin Cross0d2f40a2019-02-05 22:31:15 -0800502 if len(r.missingDeps) > 0 {
Sam Delmerico285b66a2023-09-25 12:13:17 +0000503 r.ctx.Build(r.pctx, BuildParams{
Colin Cross0d2f40a2019-02-05 22:31:15 -0800504 Rule: ErrorRule,
Colin Cross69f59a32019-02-15 10:39:37 -0800505 Outputs: r.Outputs(),
Colin Cross0d2f40a2019-02-05 22:31:15 -0800506 Description: desc,
507 Args: map[string]string{
508 "error": "missing dependencies: " + strings.Join(r.missingDeps, ", "),
509 },
510 })
511 return
512 }
513
Colin Cross1d2cf042019-03-29 15:33:06 -0700514 var depFile WritablePath
515 var depFormat blueprint.Deps
516 if depFiles := r.DepFiles(); len(depFiles) > 0 {
517 depFile = depFiles[0]
518 depFormat = blueprint.DepsGCC
519 if len(depFiles) > 1 {
520 // Add a command locally that merges all depfiles together into the first depfile.
Colin Crossf1a035e2020-11-16 17:32:30 -0800521 r.depFileMergerCmd(depFiles)
Dan Willemsen633c5022019-04-12 11:11:38 -0700522
523 if r.sbox {
Colin Crosse16ce362020-11-12 08:29:30 -0800524 // Check for Rel() errors, as all depfiles should be in the output dir. Errors
525 // will be reported to the ctx.
Dan Willemsen633c5022019-04-12 11:11:38 -0700526 for _, path := range depFiles[1:] {
Colin Crossf1a035e2020-11-16 17:32:30 -0800527 Rel(r.ctx, r.outDir.String(), path.String())
Dan Willemsen633c5022019-04-12 11:11:38 -0700528 }
529 }
Colin Cross1d2cf042019-03-29 15:33:06 -0700530 }
531 }
532
Dan Willemsen633c5022019-04-12 11:11:38 -0700533 tools := r.Tools()
Colin Crossb70a1a92021-03-12 17:51:32 -0800534 commands := r.Commands()
Dan Willemsen633c5022019-04-12 11:11:38 -0700535 outputs := r.Outputs()
Colin Cross3d680512020-11-13 16:23:53 -0800536 inputs := r.Inputs()
Colin Crossce3a51d2021-03-19 16:22:12 -0700537 rspFiles := r.rspFiles()
Dan Willemsen633c5022019-04-12 11:11:38 -0700538
539 if len(commands) == 0 {
540 return
541 }
542 if len(outputs) == 0 {
543 panic("No outputs specified from any Commands")
544 }
545
Colin Cross0cb0d7b2019-07-11 10:59:15 -0700546 commandString := strings.Join(commands, " && ")
Dan Willemsen633c5022019-04-12 11:11:38 -0700547
Inseob Kimf7cd03e2024-09-06 17:25:00 +0900548 if !r.sbox {
549 // If not using sbox the rule will run the command directly, put the hash of the
550 // list of input files in a comment at the end of the command line to ensure ninja
551 // reruns the rule when the list of input files changes.
552 commandString += " # hash of input list: " + hashSrcFiles(inputs)
553 }
554
555 if r.nsjail {
556 var nsjailCmd strings.Builder
557 nsjailPath := r.ctx.Config().PrebuiltBuildTool(r.ctx, "nsjail")
558 nsjailCmd.WriteString("mkdir -p ")
559 nsjailCmd.WriteString(r.nsjailBasePath.String())
560 nsjailCmd.WriteString(" && ")
561 nsjailCmd.WriteString(nsjailPath.String())
562 nsjailCmd.WriteRune(' ')
563 nsjailCmd.WriteString("-B $PWD/")
564 nsjailCmd.WriteString(r.nsjailBasePath.String())
565 nsjailCmd.WriteString(":nsjail_build_sandbox")
566
567 // out is mounted to $(genDir).
568 nsjailCmd.WriteString(" -B $PWD/")
569 nsjailCmd.WriteString(r.outDir.String())
570 nsjailCmd.WriteString(":nsjail_build_sandbox/out")
571
Inseob Kim93036a52024-10-25 17:02:21 +0900572 addBindMount := func(src, dst string) {
Inseob Kimf7cd03e2024-09-06 17:25:00 +0900573 nsjailCmd.WriteString(" -R $PWD/")
Inseob Kim93036a52024-10-25 17:02:21 +0900574 nsjailCmd.WriteString(src)
Inseob Kimf7cd03e2024-09-06 17:25:00 +0900575 nsjailCmd.WriteString(":nsjail_build_sandbox/")
Inseob Kim93036a52024-10-25 17:02:21 +0900576 nsjailCmd.WriteString(dst)
577 }
578
579 for _, input := range inputs {
580 addBindMount(input.String(), r.nsjailPathForInputRel(input))
Inseob Kimf7cd03e2024-09-06 17:25:00 +0900581 }
582 for _, tool := range tools {
Inseob Kim93036a52024-10-25 17:02:21 +0900583 addBindMount(tool.String(), nsjailPathForToolRel(r.ctx, tool))
Inseob Kimf7cd03e2024-09-06 17:25:00 +0900584 }
585 inputs = append(inputs, tools...)
586 for _, c := range r.commands {
Inseob Kim93036a52024-10-25 17:02:21 +0900587 for _, directory := range c.implicitDirectories {
588 addBindMount(directory.String(), directory.String())
589 // TODO(b/375551969): Add implicitDirectories to BuildParams, rather than relying on implicits
590 inputs = append(inputs, SourcePath{basePath: directory.base()})
591 }
Inseob Kimf7cd03e2024-09-06 17:25:00 +0900592 for _, tool := range c.packagedTools {
Inseob Kim93036a52024-10-25 17:02:21 +0900593 addBindMount(tool.srcPath.String(), nsjailPathForPackagedToolRel(tool))
Inseob Kimf7cd03e2024-09-06 17:25:00 +0900594 inputs = append(inputs, tool.srcPath)
595 }
596 }
597
598 // These five directories are necessary to run native host tools like /bin/bash and py3-cmd.
599 nsjailCmd.WriteString(" -R /bin")
600 nsjailCmd.WriteString(" -R /lib")
601 nsjailCmd.WriteString(" -R /lib64")
602 nsjailCmd.WriteString(" -R /dev")
603 nsjailCmd.WriteString(" -R /usr")
604
605 nsjailCmd.WriteString(" -m none:/tmp:tmpfs:size=1073741824") // 1GB, should be enough
606 nsjailCmd.WriteString(" -D nsjail_build_sandbox")
607 nsjailCmd.WriteString(" --disable_rlimits")
Haamed Gheibic128dd72024-11-13 13:27:53 -0800608 nsjailCmd.WriteString(" --skip_setsid") // ABFS relies on process-groups to track file operations
Inseob Kimf7cd03e2024-09-06 17:25:00 +0900609 nsjailCmd.WriteString(" -q")
610 nsjailCmd.WriteString(" -- ")
611 nsjailCmd.WriteString("/bin/bash -c ")
612 nsjailCmd.WriteString(proptools.ShellEscape(commandString))
613
614 commandString = nsjailCmd.String()
615
616 inputs = append(inputs, nsjailPath)
617 inputs = append(inputs, r.nsjailImplicits...)
618 } else if r.sbox {
Colin Crosse16ce362020-11-12 08:29:30 -0800619 // If running the command inside sbox, write the rule data out to an sbox
620 // manifest.textproto.
621 manifest := sbox_proto.Manifest{}
622 command := sbox_proto.Command{}
623 manifest.Commands = append(manifest.Commands, &command)
624 command.Command = proto.String(commandString)
Colin Cross151b9ff2020-11-12 08:29:30 -0800625
Colin Cross619b9ab2020-11-20 18:44:31 +0000626 if depFile != nil {
Colin Crosse16ce362020-11-12 08:29:30 -0800627 manifest.OutputDepfile = proto.String(depFile.String())
Colin Cross619b9ab2020-11-20 18:44:31 +0000628 }
629
Colin Crossba9e4032020-11-24 16:32:22 -0800630 // If sandboxing tools is enabled, add copy rules to the manifest to copy each tool
631 // into the sbox directory.
632 if r.sboxTools {
633 for _, tool := range tools {
634 command.CopyBefore = append(command.CopyBefore, &sbox_proto.Copy{
635 From: proto.String(tool.String()),
636 To: proto.String(sboxPathForToolRel(r.ctx, tool)),
637 })
638 }
639 for _, c := range r.commands {
640 for _, tool := range c.packagedTools {
641 command.CopyBefore = append(command.CopyBefore, &sbox_proto.Copy{
642 From: proto.String(tool.srcPath.String()),
643 To: proto.String(sboxPathForPackagedToolRel(tool)),
644 Executable: proto.Bool(tool.executable),
645 })
646 tools = append(tools, tool.srcPath)
647 }
648 }
649 }
650
Colin Crossab020a72021-03-12 17:52:23 -0800651 // If sandboxing inputs is enabled, add copy rules to the manifest to copy each input
652 // into the sbox directory.
653 if r.sboxInputs {
654 for _, input := range inputs {
655 command.CopyBefore = append(command.CopyBefore, &sbox_proto.Copy{
656 From: proto.String(input.String()),
657 To: proto.String(r.sboxPathForInputRel(input)),
658 })
659 }
Cole Faust78f3c3a2024-08-15 17:19:34 -0700660 for _, input := range r.OrderOnlys() {
661 command.CopyBefore = append(command.CopyBefore, &sbox_proto.Copy{
662 From: proto.String(input.String()),
663 To: proto.String(r.sboxPathForInputRel(input)),
664 })
665 }
Colin Crossab020a72021-03-12 17:52:23 -0800666
Colin Crossce3a51d2021-03-19 16:22:12 -0700667 // If using rsp files copy them and their contents into the sbox directory with
668 // the appropriate path mappings.
669 for _, rspFile := range rspFiles {
Colin Crosse55bd422021-03-23 13:44:30 -0700670 command.RspFiles = append(command.RspFiles, &sbox_proto.RspFile{
Colin Crossce3a51d2021-03-19 16:22:12 -0700671 File: proto.String(rspFile.file.String()),
Colin Crosse55bd422021-03-23 13:44:30 -0700672 // These have to match the logic in sboxPathForInputRel
673 PathMappings: []*sbox_proto.PathMapping{
674 {
675 From: proto.String(r.outDir.String()),
676 To: proto.String(sboxOutSubDir),
677 },
678 {
Cole Fauste8561c62023-11-30 17:26:37 -0800679 From: proto.String(r.ctx.Config().OutDir()),
Colin Crosse55bd422021-03-23 13:44:30 -0700680 To: proto.String(sboxOutSubDir),
681 },
682 },
Colin Crossab020a72021-03-12 17:52:23 -0800683 })
684 }
685
Cole Faust63ea1f92024-08-27 11:42:26 -0700686 // Only allow the build to access certain environment variables
687 command.DontInheritEnv = proto.Bool(true)
688 command.Env = r.ctx.Config().Once(sandboxEnvOnceKey, func() interface{} {
689 // The list of allowed variables was found by running builds of all
690 // genrules and seeing what failed
691 var result []*sbox_proto.EnvironmentVariable
692 inheritedVars := []string{
693 "PATH",
694 "JAVA_HOME",
695 "TMPDIR",
696 // Allow RBE variables because the art tests invoke RBE manually
697 "RBE_log_dir",
698 "RBE_platform",
699 "RBE_server_address",
700 // TODO: RBE_exec_root is set to the absolute path to the root of the source
701 // tree, which we don't want sandboxed actions to find. Remap it to ".".
702 "RBE_exec_root",
703 }
704 for _, v := range inheritedVars {
705 result = append(result, &sbox_proto.EnvironmentVariable{
706 Name: proto.String(v),
707 State: &sbox_proto.EnvironmentVariable_Inherit{
708 Inherit: true,
709 },
710 })
711 }
712 // Set OUT_DIR to the relative path of the sandboxed out directory.
713 // Otherwise, OUT_DIR will be inherited from the rest of the build,
714 // which will allow scripts to escape the sandbox if OUT_DIR is an
715 // absolute path.
716 result = append(result, &sbox_proto.EnvironmentVariable{
717 Name: proto.String("OUT_DIR"),
718 State: &sbox_proto.EnvironmentVariable_Value{
719 Value: sboxOutSubDir,
720 },
721 })
722 return result
723 }).([]*sbox_proto.EnvironmentVariable)
Colin Crossab020a72021-03-12 17:52:23 -0800724 command.Chdir = proto.Bool(true)
725 }
726
Colin Crosse16ce362020-11-12 08:29:30 -0800727 // Add copy rules to the manifest to copy each output file from the sbox directory.
Colin Crossba9e4032020-11-24 16:32:22 -0800728 // to the output directory after running the commands.
Spandan Das33e30972023-07-13 21:19:12 +0000729 for _, output := range outputs {
Colin Crossf1a035e2020-11-16 17:32:30 -0800730 rel := Rel(r.ctx, r.outDir.String(), output.String())
Colin Crosse16ce362020-11-12 08:29:30 -0800731 command.CopyAfter = append(command.CopyAfter, &sbox_proto.Copy{
Spandan Dasaf4ccaa2023-06-29 01:15:51 +0000732 From: proto.String(filepath.Join(r.sboxOutSubDir, rel)),
Colin Crosse16ce362020-11-12 08:29:30 -0800733 To: proto.String(output.String()),
734 })
735 }
Colin Cross619b9ab2020-11-20 18:44:31 +0000736
Colin Cross5334edd2021-03-11 17:18:21 -0800737 // Outputs that were marked Temporary will not be checked that they are in the output
738 // directory by the loop above, check them here.
739 for path := range r.temporariesSet {
740 Rel(r.ctx, r.outDir.String(), path.String())
741 }
742
Colin Crosse16ce362020-11-12 08:29:30 -0800743 // Add a hash of the list of input files to the manifest so that the textproto file
744 // changes when the list of input files changes and causes the sbox rule that
745 // depends on it to rerun.
746 command.InputHash = proto.String(hashSrcFiles(inputs))
Colin Cross619b9ab2020-11-20 18:44:31 +0000747
Colin Crosse16ce362020-11-12 08:29:30 -0800748 // Verify that the manifest textproto is not inside the sbox output directory, otherwise
749 // it will get deleted when the sbox rule clears its output directory.
Colin Crossf1a035e2020-11-16 17:32:30 -0800750 _, manifestInOutDir := MaybeRel(r.ctx, r.outDir.String(), r.sboxManifestPath.String())
Colin Crosse16ce362020-11-12 08:29:30 -0800751 if manifestInOutDir {
Colin Crossf1a035e2020-11-16 17:32:30 -0800752 ReportPathErrorf(r.ctx, "sbox rule %q manifestPath %q must not be in outputDir %q",
753 name, r.sboxManifestPath.String(), r.outDir.String())
Colin Crosse16ce362020-11-12 08:29:30 -0800754 }
755
Paul Duffin4a3a0a52023-10-12 15:01:29 +0100756 // Create a rule to write the manifest as textproto. Pretty print it by indenting and
757 // splitting across multiple lines.
758 pbText, err := prototext.MarshalOptions{Indent: " "}.Marshal(&manifest)
Dan Willemsen4591b642021-05-24 14:24:12 -0700759 if err != nil {
760 ReportPathErrorf(r.ctx, "sbox manifest failed to marshal: %q", err)
761 }
Cole Faust2f3791f2024-11-25 15:49:57 -0800762 WriteFileRule(r.ctx, r.sboxManifestPath, string(pbText))
Colin Crosse16ce362020-11-12 08:29:30 -0800763
764 // Generate a new string to use as the command line of the sbox rule. This uses
765 // a RuleBuilderCommand as a convenience method of building the command line, then
766 // converts it to a string to replace commandString.
Colin Crossf1a035e2020-11-16 17:32:30 -0800767 sboxCmd := &RuleBuilderCommand{
768 rule: &RuleBuilder{
769 ctx: r.ctx,
770 },
771 }
Colin Cross9b698b62021-12-22 09:55:32 -0800772 sboxCmd.builtToolWithoutDeps("sbox").
Colin Crosse52c2ac2022-03-28 17:03:35 -0700773 FlagWithArg("--sandbox-path ", shared.TempDirForOutDir(PathForOutput(r.ctx).String())).
774 FlagWithArg("--output-dir ", r.outDir.String()).
775 FlagWithInput("--manifest ", r.sboxManifestPath)
776
777 if r.restat {
778 sboxCmd.Flag("--write-if-changed")
779 }
Colin Crosse16ce362020-11-12 08:29:30 -0800780
781 // Replace the command string, and add the sbox tool and manifest textproto to the
782 // dependencies of the final sbox rule.
Colin Crosscfec40c2019-07-08 17:07:18 -0700783 commandString = sboxCmd.buf.String()
Dan Willemsen633c5022019-04-12 11:11:38 -0700784 tools = append(tools, sboxCmd.tools...)
Colin Crosse16ce362020-11-12 08:29:30 -0800785 inputs = append(inputs, sboxCmd.inputs...)
Colin Crossef972742021-03-12 17:24:45 -0800786
787 if r.rbeParams != nil {
Colin Crosse55bd422021-03-23 13:44:30 -0700788 // RBE needs a list of input files to copy to the remote builder. For inputs already
789 // listed in an rsp file, pass the rsp file directly to rewrapper. For the rest,
790 // create a new rsp file to pass to rewrapper.
791 var remoteRspFiles Paths
792 var remoteInputs Paths
793
794 remoteInputs = append(remoteInputs, inputs...)
795 remoteInputs = append(remoteInputs, tools...)
796
Colin Crossce3a51d2021-03-19 16:22:12 -0700797 for _, rspFile := range rspFiles {
798 remoteInputs = append(remoteInputs, rspFile.file)
799 remoteRspFiles = append(remoteRspFiles, rspFile.file)
Colin Crossef972742021-03-12 17:24:45 -0800800 }
Colin Crosse55bd422021-03-23 13:44:30 -0700801
802 if len(remoteInputs) > 0 {
803 inputsListFile := r.sboxManifestPath.ReplaceExtension(r.ctx, "rbe_inputs.list")
804 writeRspFileRule(r.ctx, inputsListFile, remoteInputs)
805 remoteRspFiles = append(remoteRspFiles, inputsListFile)
806 // Add the new rsp file as an extra input to the rule.
807 inputs = append(inputs, inputsListFile)
808 }
Colin Crossef972742021-03-12 17:24:45 -0800809
810 r.rbeParams.OutputFiles = outputs.Strings()
Colin Crosse55bd422021-03-23 13:44:30 -0700811 r.rbeParams.RSPFiles = remoteRspFiles.Strings()
Colin Crossef972742021-03-12 17:24:45 -0800812 rewrapperCommand := r.rbeParams.NoVarTemplate(r.ctx.Config().RBEWrapper())
813 commandString = rewrapperCommand + " bash -c '" + strings.ReplaceAll(commandString, `'`, `'\''`) + "'"
814 }
Dan Willemsen633c5022019-04-12 11:11:38 -0700815 }
816
Colin Cross1d2cf042019-03-29 15:33:06 -0700817 // Ninja doesn't like multiple outputs when depfiles are enabled, move all but the first output to
Colin Cross70c47412021-03-12 17:48:14 -0800818 // ImplicitOutputs. RuleBuilder doesn't use "$out", so the distinction between Outputs and
Colin Cross0cb0d7b2019-07-11 10:59:15 -0700819 // ImplicitOutputs doesn't matter.
Dan Willemsen633c5022019-04-12 11:11:38 -0700820 output := outputs[0]
821 implicitOutputs := outputs[1:]
Colin Cross1d2cf042019-03-29 15:33:06 -0700822
Colin Cross0cb0d7b2019-07-11 10:59:15 -0700823 var rspFile, rspFileContent string
Colin Crossce3a51d2021-03-19 16:22:12 -0700824 var rspFileInputs Paths
825 if len(rspFiles) > 0 {
826 // The first rsp files uses Ninja's rsp file support for the rule
827 rspFile = rspFiles[0].file.String()
Colin Crosse55bd422021-03-23 13:44:30 -0700828 // Use "$in" for rspFileContent to avoid duplicating the list of files in the dependency
829 // list and in the contents of the rsp file. Inputs to the rule that are not in the
830 // rsp file will be listed in Implicits instead of Inputs so they don't show up in "$in".
831 rspFileContent = "$in"
Colin Crossce3a51d2021-03-19 16:22:12 -0700832 rspFileInputs = append(rspFileInputs, rspFiles[0].paths...)
833
834 for _, rspFile := range rspFiles[1:] {
835 // Any additional rsp files need an extra rule to write the file.
836 writeRspFileRule(r.ctx, rspFile.file, rspFile.paths)
837 // The main rule needs to depend on the inputs listed in the extra rsp file.
838 inputs = append(inputs, rspFile.paths...)
839 // The main rule needs to depend on the extra rsp file.
840 inputs = append(inputs, rspFile.file)
841 }
Colin Cross0cb0d7b2019-07-11 10:59:15 -0700842 }
843
Colin Cross8b8bec32019-11-15 13:18:43 -0800844 var pool blueprint.Pool
Colin Crossf1a035e2020-11-16 17:32:30 -0800845 if r.ctx.Config().UseGoma() && r.remoteable.Goma {
Colin Cross8b8bec32019-11-15 13:18:43 -0800846 // 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 -0800847 } else if r.ctx.Config().UseRBE() && r.remoteable.RBE {
Ramy Medhat944839a2020-03-31 22:14:52 -0400848 // When USE_RBE=true is set and the rule is supported by RBE, use the remotePool.
849 pool = remotePool
Colin Cross8b8bec32019-11-15 13:18:43 -0800850 } else if r.highmem {
851 pool = highmemPool
Colin Crossf1a035e2020-11-16 17:32:30 -0800852 } else if r.ctx.Config().UseRemoteBuild() {
Colin Cross8b8bec32019-11-15 13:18:43 -0800853 pool = localPool
854 }
855
Cole Faustd7556eb2024-12-02 13:18:58 -0800856 // If the command length is getting close to linux's maximum, dump it to a file, which allows
857 // for longer commands.
858 if len(commandString) > 100000 {
859 hasher := sha256.New()
860 hasher.Write([]byte(output.String()))
861 script := PathForOutput(r.ctx, "rule_builder_scripts", fmt.Sprintf("%x.sh", hasher.Sum(nil)))
862 commandString = "set -eu\n\n" + commandString + "\n"
863 WriteExecutableFileRuleVerbatim(r.ctx, script, commandString)
864 inputs = append(inputs, script)
865 commandString = script.String()
866 }
867
Cole Faust2f3791f2024-11-25 15:49:57 -0800868 commandString = proptools.NinjaEscape(commandString)
Sam Delmericod46f6c82023-09-25 12:13:17 +0000869
Devin Mooreb6cc64f2024-07-15 22:31:24 +0000870 args_vars := make([]string, len(r.args))
871 i := 0
872 for k, _ := range r.args {
873 args_vars[i] = k
874 i++
875 }
Colin Crossf1a035e2020-11-16 17:32:30 -0800876 r.ctx.Build(r.pctx, BuildParams{
Sam Delmerico285b66a2023-09-25 12:13:17 +0000877 Rule: r.ctx.Rule(r.pctx, name, blueprint.RuleParams{
Sam Delmericod46f6c82023-09-25 12:13:17 +0000878 Command: commandString,
Colin Cross45029782021-03-16 16:49:52 -0700879 CommandDeps: proptools.NinjaEscapeList(tools.Strings()),
Colin Cross0cb0d7b2019-07-11 10:59:15 -0700880 Restat: r.restat,
Colin Cross45029782021-03-16 16:49:52 -0700881 Rspfile: proptools.NinjaEscape(rspFile),
Colin Cross0cb0d7b2019-07-11 10:59:15 -0700882 RspfileContent: rspFileContent,
Colin Cross8b8bec32019-11-15 13:18:43 -0800883 Pool: pool,
Devin Mooreb6cc64f2024-07-15 22:31:24 +0000884 }, args_vars...),
Colin Cross0cb0d7b2019-07-11 10:59:15 -0700885 Inputs: rspFileInputs,
Colin Cross3d680512020-11-13 16:23:53 -0800886 Implicits: inputs,
Colin Crossda6401b2021-04-21 11:32:19 -0700887 OrderOnly: r.OrderOnlys(),
Colin Crossae89abe2021-04-21 11:45:23 -0700888 Validations: r.Validations(),
Dan Willemsen633c5022019-04-12 11:11:38 -0700889 Output: output,
890 ImplicitOutputs: implicitOutputs,
891 Depfile: depFile,
892 Deps: depFormat,
893 Description: desc,
Devin Mooreb6cc64f2024-07-15 22:31:24 +0000894 Args: r.args,
Dan Willemsen633c5022019-04-12 11:11:38 -0700895 })
Colin Crossfeec25b2019-01-30 17:32:39 -0800896}
897
Colin Cross758290d2019-02-01 16:42:32 -0800898// RuleBuilderCommand is a builder for a command in a command line. It can be mutated by its methods to add to the
899// command and track dependencies. The methods mutate the RuleBuilderCommand in place, as well as return the
900// RuleBuilderCommand, so they can be used chained or unchained. All methods that add text implicitly add a single
901// space as a separator from the previous method.
Colin Crossfeec25b2019-01-30 17:32:39 -0800902type RuleBuilderCommand struct {
Colin Crossf1a035e2020-11-16 17:32:30 -0800903 rule *RuleBuilder
904
Inseob Kim93036a52024-10-25 17:02:21 +0900905 buf strings.Builder
906 inputs Paths
907 implicits Paths
908 orderOnlys Paths
909 validations Paths
910 outputs WritablePaths
911 depFiles WritablePaths
912 tools Paths
913 packagedTools []PackagingSpec
914 rspFiles []rspFileAndPaths
915 implicitDirectories DirectoryPaths
Colin Crossce3a51d2021-03-19 16:22:12 -0700916}
917
918type rspFileAndPaths struct {
919 file WritablePath
920 paths Paths
Dan Willemsen633c5022019-04-12 11:11:38 -0700921}
922
Paul Duffin3866b892021-10-04 11:24:48 +0100923func checkPathNotNil(path Path) {
924 if path == nil {
925 panic("rule_builder paths cannot be nil")
926 }
927}
928
Dan Willemsen633c5022019-04-12 11:11:38 -0700929func (c *RuleBuilderCommand) addInput(path Path) string {
Paul Duffin3866b892021-10-04 11:24:48 +0100930 checkPathNotNil(path)
Dan Willemsen633c5022019-04-12 11:11:38 -0700931 c.inputs = append(c.inputs, path)
Colin Crossab020a72021-03-12 17:52:23 -0800932 return c.PathForInput(path)
Dan Willemsen633c5022019-04-12 11:11:38 -0700933}
934
Colin Crossab020a72021-03-12 17:52:23 -0800935func (c *RuleBuilderCommand) addImplicit(path Path) {
Paul Duffin3866b892021-10-04 11:24:48 +0100936 checkPathNotNil(path)
Ramy Medhat2f99eec2020-06-13 17:38:27 -0400937 c.implicits = append(c.implicits, path)
Ramy Medhat2f99eec2020-06-13 17:38:27 -0400938}
939
Inseob Kim93036a52024-10-25 17:02:21 +0900940func (c *RuleBuilderCommand) addImplicitDirectory(path DirectoryPath) {
941 c.implicitDirectories = append(c.implicitDirectories, path)
942}
943
Colin Crossda71eda2020-02-21 16:55:19 -0800944func (c *RuleBuilderCommand) addOrderOnly(path Path) {
Paul Duffin3866b892021-10-04 11:24:48 +0100945 checkPathNotNil(path)
Colin Crossda71eda2020-02-21 16:55:19 -0800946 c.orderOnlys = append(c.orderOnlys, path)
947}
948
Colin Crossab020a72021-03-12 17:52:23 -0800949// PathForInput takes an input path and returns the appropriate path to use on the command line. If
950// sbox was enabled via a call to RuleBuilder.Sbox() and the path was an output path it returns a
951// path with the placeholder prefix used for outputs in sbox. If sbox is not enabled it returns the
952// original path.
953func (c *RuleBuilderCommand) PathForInput(path Path) string {
954 if c.rule.sbox {
955 rel, inSandbox := c.rule._sboxPathForInputRel(path)
956 if inSandbox {
957 rel = filepath.Join(sboxSandboxBaseDir, rel)
958 }
959 return rel
Inseob Kimf7cd03e2024-09-06 17:25:00 +0900960 } else if c.rule.nsjail {
961 return c.rule.nsjailPathForInputRel(path)
Colin Crossab020a72021-03-12 17:52:23 -0800962 }
963 return path.String()
964}
965
966// PathsForInputs takes a list of input paths and returns the appropriate paths to use on the
967// command line. If sbox was enabled via a call to RuleBuilder.Sbox() a path was an output path, it
968// returns the path with the placeholder prefix used for outputs in sbox. If sbox is not enabled it
969// returns the original paths.
970func (c *RuleBuilderCommand) PathsForInputs(paths Paths) []string {
971 ret := make([]string, len(paths))
972 for i, path := range paths {
973 ret[i] = c.PathForInput(path)
974 }
975 return ret
976}
977
Colin Crossf1a035e2020-11-16 17:32:30 -0800978// PathForOutput takes an output path and returns the appropriate path to use on the command
979// line. If sbox was enabled via a call to RuleBuilder.Sbox(), it returns a path with the
980// placeholder prefix used for outputs in sbox. If sbox is not enabled it returns the
981// original path.
982func (c *RuleBuilderCommand) PathForOutput(path WritablePath) string {
983 if c.rule.sbox {
984 // Errors will be handled in RuleBuilder.Build where we have a context to report them
985 rel, _, _ := maybeRelErr(c.rule.outDir.String(), path.String())
986 return filepath.Join(sboxOutDir, rel)
Inseob Kimf7cd03e2024-09-06 17:25:00 +0900987 } else if c.rule.nsjail {
988 // Errors will be handled in RuleBuilder.Build where we have a context to report them
989 rel, _, _ := maybeRelErr(c.rule.outDir.String(), path.String())
990 return filepath.Join(nsjailOutDir, rel)
Dan Willemsen633c5022019-04-12 11:11:38 -0700991 }
992 return path.String()
Colin Crossfeec25b2019-01-30 17:32:39 -0800993}
994
Colin Crossba9e4032020-11-24 16:32:22 -0800995func sboxPathForToolRel(ctx BuilderContext, path Path) string {
996 // Errors will be handled in RuleBuilder.Build where we have a context to report them
Cole Faust3b703f32023-10-16 13:30:51 -0700997 toolDir := pathForInstall(ctx, ctx.Config().BuildOS, ctx.Config().BuildArch, "")
Colin Cross790ef352021-10-25 19:15:55 -0700998 relOutSoong, isRelOutSoong, _ := maybeRelErr(toolDir.String(), path.String())
999 if isRelOutSoong {
1000 // The tool is in the Soong output directory, it will be copied to __SBOX_OUT_DIR__/tools/out
1001 return filepath.Join(sboxToolsSubDir, "out", relOutSoong)
Colin Crossba9e4032020-11-24 16:32:22 -08001002 }
1003 // The tool is in the source directory, it will be copied to __SBOX_OUT_DIR__/tools/src
1004 return filepath.Join(sboxToolsSubDir, "src", path.String())
1005}
1006
Colin Crossab020a72021-03-12 17:52:23 -08001007func (r *RuleBuilder) _sboxPathForInputRel(path Path) (rel string, inSandbox bool) {
1008 // Errors will be handled in RuleBuilder.Build where we have a context to report them
1009 rel, isRelSboxOut, _ := maybeRelErr(r.outDir.String(), path.String())
1010 if isRelSboxOut {
1011 return filepath.Join(sboxOutSubDir, rel), true
1012 }
1013 if r.sboxInputs {
1014 // When sandboxing inputs all inputs have to be copied into the sandbox. Input files that
1015 // are outputs of other rules could be an arbitrary absolute path if OUT_DIR is set, so they
1016 // will be copied to relative paths under __SBOX_OUT_DIR__/out.
Cole Fauste8561c62023-11-30 17:26:37 -08001017 rel, isRelOut, _ := maybeRelErr(r.ctx.Config().OutDir(), path.String())
Colin Crossab020a72021-03-12 17:52:23 -08001018 if isRelOut {
1019 return filepath.Join(sboxOutSubDir, rel), true
1020 }
1021 }
1022 return path.String(), false
1023}
1024
1025func (r *RuleBuilder) sboxPathForInputRel(path Path) string {
1026 rel, _ := r._sboxPathForInputRel(path)
1027 return rel
1028}
1029
1030func (r *RuleBuilder) sboxPathsForInputsRel(paths Paths) []string {
1031 ret := make([]string, len(paths))
1032 for i, path := range paths {
1033 ret[i] = r.sboxPathForInputRel(path)
1034 }
1035 return ret
1036}
1037
Colin Crossba9e4032020-11-24 16:32:22 -08001038func sboxPathForPackagedToolRel(spec PackagingSpec) string {
1039 return filepath.Join(sboxToolsSubDir, "out", spec.relPathInPackage)
1040}
1041
Inseob Kimf7cd03e2024-09-06 17:25:00 +09001042func nsjailPathForToolRel(ctx BuilderContext, path Path) string {
1043 // Errors will be handled in RuleBuilder.Build where we have a context to report them
1044 toolDir := pathForInstall(ctx, ctx.Config().BuildOS, ctx.Config().BuildArch, "")
1045 relOutSoong, isRelOutSoong, _ := maybeRelErr(toolDir.String(), path.String())
1046 if isRelOutSoong {
1047 // The tool is in the Soong output directory, it will be copied to __SBOX_OUT_DIR__/tools/out
1048 return filepath.Join(nsjailToolsSubDir, "out", relOutSoong)
1049 }
1050 // The tool is in the source directory, it will be copied to __SBOX_OUT_DIR__/tools/src
1051 return filepath.Join(nsjailToolsSubDir, "src", path.String())
1052}
1053
1054func (r *RuleBuilder) nsjailPathForInputRel(path Path) string {
1055 rel, isRelSboxOut, _ := maybeRelErr(r.outDir.String(), path.String())
1056 if isRelSboxOut {
1057 return filepath.Join(nsjailOutDir, rel)
1058 }
1059 return path.String()
1060}
1061
1062func (r *RuleBuilder) nsjailPathsForInputsRel(paths Paths) []string {
1063 ret := make([]string, len(paths))
1064 for i, path := range paths {
1065 ret[i] = r.nsjailPathForInputRel(path)
1066 }
1067 return ret
1068}
1069
1070func nsjailPathForPackagedToolRel(spec PackagingSpec) string {
1071 return filepath.Join(nsjailToolsSubDir, "out", spec.relPathInPackage)
1072}
1073
Colin Crossd11cf622021-03-23 22:30:35 -07001074// PathForPackagedTool takes a PackageSpec for a tool and returns the corresponding path for the
1075// tool after copying it into the sandbox. This can be used on the RuleBuilder command line to
1076// reference the tool.
1077func (c *RuleBuilderCommand) PathForPackagedTool(spec PackagingSpec) string {
Inseob Kimf7cd03e2024-09-06 17:25:00 +09001078 if c.rule.sboxTools {
1079 return filepath.Join(sboxSandboxBaseDir, sboxPathForPackagedToolRel(spec))
1080 } else if c.rule.nsjail {
1081 return nsjailPathForPackagedToolRel(spec)
1082 } else {
1083 panic("PathForPackagedTool() requires SandboxTools() or Nsjail()")
Colin Crossd11cf622021-03-23 22:30:35 -07001084 }
Colin Crossd11cf622021-03-23 22:30:35 -07001085}
1086
Colin Crossba9e4032020-11-24 16:32:22 -08001087// PathForTool takes a path to a tool, which may be an output file or a source file, and returns
1088// the corresponding path for the tool in the sbox sandbox if sbox is enabled, or the original path
1089// if it is not. This can be used on the RuleBuilder command line to reference the tool.
1090func (c *RuleBuilderCommand) PathForTool(path Path) string {
1091 if c.rule.sbox && c.rule.sboxTools {
1092 return filepath.Join(sboxSandboxBaseDir, sboxPathForToolRel(c.rule.ctx, path))
Inseob Kimf7cd03e2024-09-06 17:25:00 +09001093 } else if c.rule.nsjail {
1094 return nsjailPathForToolRel(c.rule.ctx, path)
Colin Crossba9e4032020-11-24 16:32:22 -08001095 }
1096 return path.String()
1097}
1098
Colin Crossd11cf622021-03-23 22:30:35 -07001099// PathsForTools takes a list of paths to tools, which may be output files or source files, and
1100// returns the corresponding paths for the tools in the sbox sandbox if sbox is enabled, or the
1101// original paths if it is not. This can be used on the RuleBuilder command line to reference the tool.
1102func (c *RuleBuilderCommand) PathsForTools(paths Paths) []string {
1103 if c.rule.sbox && c.rule.sboxTools {
1104 var ret []string
1105 for _, path := range paths {
1106 ret = append(ret, filepath.Join(sboxSandboxBaseDir, sboxPathForToolRel(c.rule.ctx, path)))
1107 }
1108 return ret
Inseob Kimf7cd03e2024-09-06 17:25:00 +09001109 } else if c.rule.nsjail {
1110 var ret []string
1111 for _, path := range paths {
1112 ret = append(ret, nsjailPathForToolRel(c.rule.ctx, path))
1113 }
1114 return ret
Colin Crossd11cf622021-03-23 22:30:35 -07001115 }
1116 return paths.Strings()
1117}
1118
Colin Crossba9e4032020-11-24 16:32:22 -08001119// PackagedTool adds the specified tool path to the command line. It can only be used with tool
1120// sandboxing enabled by SandboxTools(), and will copy the tool into the sandbox.
1121func (c *RuleBuilderCommand) PackagedTool(spec PackagingSpec) *RuleBuilderCommand {
Colin Crossba9e4032020-11-24 16:32:22 -08001122 c.packagedTools = append(c.packagedTools, spec)
Inseob Kimf7cd03e2024-09-06 17:25:00 +09001123 if c.rule.sboxTools {
1124 c.Text(sboxPathForPackagedToolRel(spec))
1125 } else if c.rule.nsjail {
1126 c.Text(nsjailPathForPackagedToolRel(spec))
1127 } else {
1128 panic("PackagedTool() requires SandboxTools() or Nsjail()")
1129 }
Colin Crossba9e4032020-11-24 16:32:22 -08001130 return c
1131}
1132
1133// ImplicitPackagedTool copies the specified tool into the sandbox without modifying the command
1134// line. It can only be used with tool sandboxing enabled by SandboxTools().
1135func (c *RuleBuilderCommand) ImplicitPackagedTool(spec PackagingSpec) *RuleBuilderCommand {
Inseob Kimf7cd03e2024-09-06 17:25:00 +09001136 if !c.rule.sboxTools && !c.rule.nsjail {
1137 panic("ImplicitPackagedTool() requires SandboxTools() or Nsjail()")
Colin Crossba9e4032020-11-24 16:32:22 -08001138 }
1139
1140 c.packagedTools = append(c.packagedTools, spec)
1141 return c
1142}
1143
1144// ImplicitPackagedTools copies the specified tools into the sandbox without modifying the command
1145// line. It can only be used with tool sandboxing enabled by SandboxTools().
1146func (c *RuleBuilderCommand) ImplicitPackagedTools(specs []PackagingSpec) *RuleBuilderCommand {
Inseob Kimf7cd03e2024-09-06 17:25:00 +09001147 if !c.rule.sboxTools && !c.rule.nsjail {
1148 panic("ImplicitPackagedTools() requires SandboxTools() or Nsjail()")
Colin Crossba9e4032020-11-24 16:32:22 -08001149 }
1150
1151 c.packagedTools = append(c.packagedTools, specs...)
1152 return c
1153}
1154
Colin Cross758290d2019-02-01 16:42:32 -08001155// Text adds the specified raw text to the command line. The text should not contain input or output paths or the
1156// rule will not have them listed in its dependencies or outputs.
Colin Crossfeec25b2019-01-30 17:32:39 -08001157func (c *RuleBuilderCommand) Text(text string) *RuleBuilderCommand {
Colin Crosscfec40c2019-07-08 17:07:18 -07001158 if c.buf.Len() > 0 {
1159 c.buf.WriteByte(' ')
Colin Crossfeec25b2019-01-30 17:32:39 -08001160 }
Colin Crosscfec40c2019-07-08 17:07:18 -07001161 c.buf.WriteString(text)
Colin Crossfeec25b2019-01-30 17:32:39 -08001162 return c
1163}
1164
Colin Cross758290d2019-02-01 16:42:32 -08001165// Textf adds the specified formatted text to the command line. The text should not contain input or output paths or
1166// the rule will not have them listed in its dependencies or outputs.
Colin Crossfeec25b2019-01-30 17:32:39 -08001167func (c *RuleBuilderCommand) Textf(format string, a ...interface{}) *RuleBuilderCommand {
1168 return c.Text(fmt.Sprintf(format, a...))
1169}
1170
Colin Cross758290d2019-02-01 16:42:32 -08001171// Flag adds the specified raw text to the command line. The text should not contain input or output paths or the
1172// rule will not have them listed in its dependencies or outputs.
Colin Crossfeec25b2019-01-30 17:32:39 -08001173func (c *RuleBuilderCommand) Flag(flag string) *RuleBuilderCommand {
1174 return c.Text(flag)
1175}
1176
Colin Crossab054432019-07-15 16:13:59 -07001177// OptionalFlag adds the specified raw text to the command line if it is not nil. The text should not contain input or
1178// output paths or the rule will not have them listed in its dependencies or outputs.
1179func (c *RuleBuilderCommand) OptionalFlag(flag *string) *RuleBuilderCommand {
1180 if flag != nil {
1181 c.Text(*flag)
1182 }
1183
1184 return c
1185}
1186
Colin Cross92b7d582019-03-29 15:32:51 -07001187// Flags adds the specified raw text to the command line. The text should not contain input or output paths or the
1188// rule will not have them listed in its dependencies or outputs.
1189func (c *RuleBuilderCommand) Flags(flags []string) *RuleBuilderCommand {
1190 for _, flag := range flags {
1191 c.Text(flag)
1192 }
1193 return c
1194}
1195
Colin Cross758290d2019-02-01 16:42:32 -08001196// FlagWithArg adds the specified flag and argument text to the command line, with no separator between them. The flag
1197// and argument should not contain input or output paths or the rule will not have them listed in its dependencies or
1198// outputs.
Colin Crossfeec25b2019-01-30 17:32:39 -08001199func (c *RuleBuilderCommand) FlagWithArg(flag, arg string) *RuleBuilderCommand {
1200 return c.Text(flag + arg)
1201}
1202
Colin Crossc7ed0042019-02-11 14:11:09 -08001203// FlagForEachArg adds the specified flag joined with each argument to the command line. The result is identical to
1204// calling FlagWithArg for argument.
1205func (c *RuleBuilderCommand) FlagForEachArg(flag string, args []string) *RuleBuilderCommand {
1206 for _, arg := range args {
1207 c.FlagWithArg(flag, arg)
1208 }
1209 return c
1210}
1211
Roland Levillain2da5d9a2019-02-27 16:56:41 +00001212// 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 -08001213// and no separator between the flag and arguments. The flag and arguments should not contain input or output paths or
1214// the rule will not have them listed in its dependencies or outputs.
Colin Crossfeec25b2019-01-30 17:32:39 -08001215func (c *RuleBuilderCommand) FlagWithList(flag string, list []string, sep string) *RuleBuilderCommand {
1216 return c.Text(flag + strings.Join(list, sep))
1217}
1218
Colin Cross758290d2019-02-01 16:42:32 -08001219// Tool adds the specified tool path to the command line. The path will be also added to the dependencies returned by
1220// RuleBuilder.Tools.
Colin Cross69f59a32019-02-15 10:39:37 -08001221func (c *RuleBuilderCommand) Tool(path Path) *RuleBuilderCommand {
Paul Duffin3866b892021-10-04 11:24:48 +01001222 checkPathNotNil(path)
Colin Crossfeec25b2019-01-30 17:32:39 -08001223 c.tools = append(c.tools, path)
Colin Crossba9e4032020-11-24 16:32:22 -08001224 return c.Text(c.PathForTool(path))
1225}
1226
1227// Tool adds the specified tool path to the dependencies returned by RuleBuilder.Tools.
1228func (c *RuleBuilderCommand) ImplicitTool(path Path) *RuleBuilderCommand {
Paul Duffin3866b892021-10-04 11:24:48 +01001229 checkPathNotNil(path)
Colin Crossba9e4032020-11-24 16:32:22 -08001230 c.tools = append(c.tools, path)
1231 return c
1232}
1233
1234// Tool adds the specified tool path to the dependencies returned by RuleBuilder.Tools.
1235func (c *RuleBuilderCommand) ImplicitTools(paths Paths) *RuleBuilderCommand {
Paul Duffin3866b892021-10-04 11:24:48 +01001236 for _, path := range paths {
1237 c.ImplicitTool(path)
1238 }
Colin Crossba9e4032020-11-24 16:32:22 -08001239 return c
Colin Crossfeec25b2019-01-30 17:32:39 -08001240}
1241
Colin Crossee94d6a2019-07-08 17:08:34 -07001242// BuiltTool adds the specified tool path that was built using a host Soong module to the command line. The path will
1243// be also added to the dependencies returned by RuleBuilder.Tools.
1244//
1245// It is equivalent to:
Colin Crossd079e0b2022-08-16 10:27:33 -07001246//
1247// cmd.Tool(ctx.Config().HostToolPath(ctx, tool))
Colin Crossf1a035e2020-11-16 17:32:30 -08001248func (c *RuleBuilderCommand) BuiltTool(tool string) *RuleBuilderCommand {
Colin Cross9b698b62021-12-22 09:55:32 -08001249 if c.rule.ctx.Config().UseHostMusl() {
1250 // If the host is using musl, assume that the tool was built against musl libc and include
1251 // libc_musl.so in the sandbox.
1252 // TODO(ccross): if we supported adding new dependencies during GenerateAndroidBuildActions
1253 // this could be a dependency + TransitivePackagingSpecs.
1254 c.ImplicitTool(c.rule.ctx.Config().HostJNIToolPath(c.rule.ctx, "libc_musl"))
1255 }
1256 return c.builtToolWithoutDeps(tool)
1257}
1258
1259// builtToolWithoutDeps is similar to BuiltTool, but doesn't add any dependencies. It is used
1260// internally by RuleBuilder for helper tools that are known to be compiled statically.
1261func (c *RuleBuilderCommand) builtToolWithoutDeps(tool string) *RuleBuilderCommand {
Colin Crossf1a035e2020-11-16 17:32:30 -08001262 return c.Tool(c.rule.ctx.Config().HostToolPath(c.rule.ctx, tool))
Colin Crossee94d6a2019-07-08 17:08:34 -07001263}
1264
1265// PrebuiltBuildTool adds the specified tool path from prebuils/build-tools. The path will be also added to the
1266// dependencies returned by RuleBuilder.Tools.
1267//
1268// It is equivalent to:
Colin Crossd079e0b2022-08-16 10:27:33 -07001269//
1270// cmd.Tool(ctx.Config().PrebuiltBuildTool(ctx, tool))
Colin Crossee94d6a2019-07-08 17:08:34 -07001271func (c *RuleBuilderCommand) PrebuiltBuildTool(ctx PathContext, tool string) *RuleBuilderCommand {
1272 return c.Tool(ctx.Config().PrebuiltBuildTool(ctx, tool))
1273}
1274
Colin Cross758290d2019-02-01 16:42:32 -08001275// Input adds the specified input path to the command line. The path will also be added to the dependencies returned by
1276// RuleBuilder.Inputs.
Colin Cross69f59a32019-02-15 10:39:37 -08001277func (c *RuleBuilderCommand) Input(path Path) *RuleBuilderCommand {
Dan Willemsen633c5022019-04-12 11:11:38 -07001278 return c.Text(c.addInput(path))
Colin Crossfeec25b2019-01-30 17:32:39 -08001279}
1280
Colin Cross758290d2019-02-01 16:42:32 -08001281// Inputs adds the specified input paths to the command line, separated by spaces. The paths will also be added to the
1282// dependencies returned by RuleBuilder.Inputs.
Colin Cross69f59a32019-02-15 10:39:37 -08001283func (c *RuleBuilderCommand) Inputs(paths Paths) *RuleBuilderCommand {
Colin Cross758290d2019-02-01 16:42:32 -08001284 for _, path := range paths {
1285 c.Input(path)
1286 }
1287 return c
1288}
1289
1290// Implicit adds the specified input path to the dependencies returned by RuleBuilder.Inputs without modifying the
1291// command line.
Colin Cross69f59a32019-02-15 10:39:37 -08001292func (c *RuleBuilderCommand) Implicit(path Path) *RuleBuilderCommand {
Ramy Medhat2f99eec2020-06-13 17:38:27 -04001293 c.addImplicit(path)
Colin Crossfeec25b2019-01-30 17:32:39 -08001294 return c
1295}
1296
Colin Cross758290d2019-02-01 16:42:32 -08001297// Implicits adds the specified input paths to the dependencies returned by RuleBuilder.Inputs without modifying the
1298// command line.
Colin Cross69f59a32019-02-15 10:39:37 -08001299func (c *RuleBuilderCommand) Implicits(paths Paths) *RuleBuilderCommand {
Dan Willemsen633c5022019-04-12 11:11:38 -07001300 for _, path := range paths {
Ramy Medhat2f99eec2020-06-13 17:38:27 -04001301 c.addImplicit(path)
Dan Willemsen633c5022019-04-12 11:11:38 -07001302 }
Colin Crossfeec25b2019-01-30 17:32:39 -08001303 return c
1304}
1305
Inseob Kim93036a52024-10-25 17:02:21 +09001306// ImplicitDirectory adds the specified input directory to the dependencies without modifying the
1307// command line. Added directories will be bind-mounted for the nsjail.
1308func (c *RuleBuilderCommand) ImplicitDirectory(path DirectoryPath) *RuleBuilderCommand {
1309 if !c.rule.nsjail {
1310 panic("ImplicitDirectory() must be called after Nsjail()")
1311 }
1312 c.addImplicitDirectory(path)
1313 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}