blob: c9a9ddd31966da97a50166546f85674030906f94 [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
Colin Cross758290d2019-02-01 16:42:32 -080041// RuleBuilder provides an alternative to ModuleContext.Rule and ModuleContext.Build to add a command line to the build
42// graph.
Colin Crossfeec25b2019-01-30 17:32:39 -080043type RuleBuilder struct {
Colin Crossf1a035e2020-11-16 17:32:30 -080044 pctx PackageContext
45 ctx BuilderContext
46
Colin Crosse16ce362020-11-12 08:29:30 -080047 commands []*RuleBuilderCommand
48 installs RuleBuilderInstalls
49 temporariesSet map[WritablePath]bool
50 restat bool
51 sbox bool
52 highmem bool
53 remoteable RemoteRuleSupports
Colin Crossef972742021-03-12 17:24:45 -080054 rbeParams *remoteexec.REParams
Colin Crossf1a035e2020-11-16 17:32:30 -080055 outDir WritablePath
Colin Crossba9e4032020-11-24 16:32:22 -080056 sboxTools bool
Colin Crossab020a72021-03-12 17:52:23 -080057 sboxInputs bool
Colin Crosse16ce362020-11-12 08:29:30 -080058 sboxManifestPath WritablePath
59 missingDeps []string
Colin Crossfeec25b2019-01-30 17:32:39 -080060}
61
Colin Cross758290d2019-02-01 16:42:32 -080062// NewRuleBuilder returns a newly created RuleBuilder.
Colin Crossf1a035e2020-11-16 17:32:30 -080063func NewRuleBuilder(pctx PackageContext, ctx BuilderContext) *RuleBuilder {
Colin Cross5cb5b092019-02-02 21:25:18 -080064 return &RuleBuilder{
Colin Crossf1a035e2020-11-16 17:32:30 -080065 pctx: pctx,
66 ctx: ctx,
Colin Cross69f59a32019-02-15 10:39:37 -080067 temporariesSet: make(map[WritablePath]bool),
Colin Cross5cb5b092019-02-02 21:25:18 -080068 }
Colin Cross758290d2019-02-01 16:42:32 -080069}
70
71// RuleBuilderInstall is a tuple of install from and to locations.
72type RuleBuilderInstall struct {
Colin Cross69f59a32019-02-15 10:39:37 -080073 From Path
74 To string
Colin Cross758290d2019-02-01 16:42:32 -080075}
76
Colin Crossdeabb942019-02-11 14:11:09 -080077type RuleBuilderInstalls []RuleBuilderInstall
78
79// String returns the RuleBuilderInstalls in the form used by $(call copy-many-files) in Make, a space separated
80// list of from:to tuples.
81func (installs RuleBuilderInstalls) String() string {
82 sb := strings.Builder{}
83 for i, install := range installs {
84 if i != 0 {
85 sb.WriteRune(' ')
86 }
Colin Cross69f59a32019-02-15 10:39:37 -080087 sb.WriteString(install.From.String())
Colin Crossdeabb942019-02-11 14:11:09 -080088 sb.WriteRune(':')
89 sb.WriteString(install.To)
90 }
91 return sb.String()
92}
93
Colin Cross0d2f40a2019-02-05 22:31:15 -080094// MissingDeps adds modules to the list of missing dependencies. If MissingDeps
95// is called with a non-empty input, any call to Build will result in a rule
96// that will print an error listing the missing dependencies and fail.
97// MissingDeps should only be called if Config.AllowMissingDependencies() is
98// true.
99func (r *RuleBuilder) MissingDeps(missingDeps []string) {
100 r.missingDeps = append(r.missingDeps, missingDeps...)
101}
102
Colin Cross758290d2019-02-01 16:42:32 -0800103// Restat marks the rule as a restat rule, which will be passed to ModuleContext.Rule in BuildParams.Restat.
Dan Willemsen633c5022019-04-12 11:11:38 -0700104//
105// Restat is not compatible with Sbox()
Colin Crossfeec25b2019-01-30 17:32:39 -0800106func (r *RuleBuilder) Restat() *RuleBuilder {
Dan Willemsen633c5022019-04-12 11:11:38 -0700107 if r.sbox {
108 panic("Restat() is not compatible with Sbox()")
109 }
Colin Crossfeec25b2019-01-30 17:32:39 -0800110 r.restat = true
111 return r
112}
113
Colin Cross8b8bec32019-11-15 13:18:43 -0800114// HighMem marks the rule as a high memory rule, which will limit how many run in parallel with other high memory
115// rules.
116func (r *RuleBuilder) HighMem() *RuleBuilder {
117 r.highmem = true
118 return r
119}
120
121// Remoteable marks the rule as supporting remote execution.
122func (r *RuleBuilder) Remoteable(supports RemoteRuleSupports) *RuleBuilder {
123 r.remoteable = supports
124 return r
125}
126
Colin Crossef972742021-03-12 17:24:45 -0800127// Rewrapper marks the rule as running inside rewrapper using the given params in order to support
128// running on RBE. During RuleBuilder.Build the params will be combined with the inputs, outputs
129// and tools known to RuleBuilder to prepend an appropriate rewrapper command line to the rule's
130// command line.
131func (r *RuleBuilder) Rewrapper(params *remoteexec.REParams) *RuleBuilder {
132 if !r.sboxInputs {
133 panic(fmt.Errorf("RuleBuilder.Rewrapper must be called after RuleBuilder.SandboxInputs"))
134 }
135 r.rbeParams = params
136 return r
137}
138
Colin Crosse16ce362020-11-12 08:29:30 -0800139// Sbox marks the rule as needing to be wrapped by sbox. The outputDir should point to the output
140// directory that sbox will wipe. It should not be written to by any other rule. manifestPath should
141// point to a location where sbox's manifest will be written and must be outside outputDir. sbox
142// will ensure that all outputs have been written, and will discard any output files that were not
143// specified.
Dan Willemsen633c5022019-04-12 11:11:38 -0700144//
145// Sbox is not compatible with Restat()
Colin Crosse16ce362020-11-12 08:29:30 -0800146func (r *RuleBuilder) Sbox(outputDir WritablePath, manifestPath WritablePath) *RuleBuilder {
Dan Willemsen633c5022019-04-12 11:11:38 -0700147 if r.sbox {
148 panic("Sbox() may not be called more than once")
149 }
150 if len(r.commands) > 0 {
151 panic("Sbox() may not be called after Command()")
152 }
153 if r.restat {
154 panic("Sbox() is not compatible with Restat()")
155 }
156 r.sbox = true
Colin Crossf1a035e2020-11-16 17:32:30 -0800157 r.outDir = outputDir
Colin Crosse16ce362020-11-12 08:29:30 -0800158 r.sboxManifestPath = manifestPath
Dan Willemsen633c5022019-04-12 11:11:38 -0700159 return r
160}
161
Colin Crossba9e4032020-11-24 16:32:22 -0800162// SandboxTools enables tool sandboxing for the rule by copying any referenced tools into the
163// sandbox.
164func (r *RuleBuilder) SandboxTools() *RuleBuilder {
165 if !r.sbox {
166 panic("SandboxTools() must be called after Sbox()")
167 }
168 if len(r.commands) > 0 {
169 panic("SandboxTools() may not be called after Command()")
170 }
171 r.sboxTools = true
172 return r
173}
174
Colin Crossab020a72021-03-12 17:52:23 -0800175// SandboxInputs enables input sandboxing for the rule by copying any referenced inputs into the
176// sandbox. It also implies SandboxTools().
177//
178// Sandboxing inputs requires RuleBuilder to be aware of all references to input paths. Paths
179// that are passed to RuleBuilder outside of the methods that expect inputs, for example
180// FlagWithArg, must use RuleBuilderCommand.PathForInput to translate the path to one that matches
181// the sandbox layout.
182func (r *RuleBuilder) SandboxInputs() *RuleBuilder {
183 if !r.sbox {
184 panic("SandboxInputs() must be called after Sbox()")
185 }
186 if len(r.commands) > 0 {
187 panic("SandboxInputs() may not be called after Command()")
188 }
189 r.sboxTools = true
190 r.sboxInputs = true
191 return r
192}
193
Colin Cross758290d2019-02-01 16:42:32 -0800194// Install associates an output of the rule with an install location, which can be retrieved later using
195// RuleBuilder.Installs.
Colin Cross69f59a32019-02-15 10:39:37 -0800196func (r *RuleBuilder) Install(from Path, to string) {
Colin Crossfeec25b2019-01-30 17:32:39 -0800197 r.installs = append(r.installs, RuleBuilderInstall{from, to})
198}
199
Colin Cross758290d2019-02-01 16:42:32 -0800200// Command returns a new RuleBuilderCommand for the rule. The commands will be ordered in the rule by when they were
201// created by this method. That can be mutated through their methods in any order, as long as the mutations do not
202// race with any call to Build.
Colin Crossfeec25b2019-01-30 17:32:39 -0800203func (r *RuleBuilder) Command() *RuleBuilderCommand {
Dan Willemsen633c5022019-04-12 11:11:38 -0700204 command := &RuleBuilderCommand{
Colin Crossf1a035e2020-11-16 17:32:30 -0800205 rule: r,
Dan Willemsen633c5022019-04-12 11:11:38 -0700206 }
Colin Crossfeec25b2019-01-30 17:32:39 -0800207 r.commands = append(r.commands, command)
208 return command
209}
210
Colin Cross5cb5b092019-02-02 21:25:18 -0800211// Temporary marks an output of a command as an intermediate file that will be used as an input to another command
212// in the same rule, and should not be listed in Outputs.
Colin Cross69f59a32019-02-15 10:39:37 -0800213func (r *RuleBuilder) Temporary(path WritablePath) {
Colin Cross5cb5b092019-02-02 21:25:18 -0800214 r.temporariesSet[path] = true
215}
216
217// DeleteTemporaryFiles adds a command to the rule that deletes any outputs that have been marked using Temporary
218// when the rule runs. DeleteTemporaryFiles should be called after all calls to Temporary.
219func (r *RuleBuilder) DeleteTemporaryFiles() {
Colin Cross69f59a32019-02-15 10:39:37 -0800220 var temporariesList WritablePaths
Colin Cross5cb5b092019-02-02 21:25:18 -0800221
222 for intermediate := range r.temporariesSet {
223 temporariesList = append(temporariesList, intermediate)
224 }
Colin Cross69f59a32019-02-15 10:39:37 -0800225
226 sort.Slice(temporariesList, func(i, j int) bool {
227 return temporariesList[i].String() < temporariesList[j].String()
228 })
Colin Cross5cb5b092019-02-02 21:25:18 -0800229
230 r.Command().Text("rm").Flag("-f").Outputs(temporariesList)
231}
232
Colin Crossda71eda2020-02-21 16:55:19 -0800233// Inputs returns the list of paths that were passed to the RuleBuilderCommand methods that take
Colin Cross3d680512020-11-13 16:23:53 -0800234// input paths, such as RuleBuilderCommand.Input, RuleBuilderCommand.Implicit, or
Colin Crossda71eda2020-02-21 16:55:19 -0800235// RuleBuilderCommand.FlagWithInput. Inputs to a command that are also outputs of another command
236// in the same RuleBuilder are filtered out. The list is sorted and duplicates removed.
Colin Cross69f59a32019-02-15 10:39:37 -0800237func (r *RuleBuilder) Inputs() Paths {
Colin Crossfeec25b2019-01-30 17:32:39 -0800238 outputs := r.outputSet()
Dan Willemsen633c5022019-04-12 11:11:38 -0700239 depFiles := r.depFileSet()
Colin Crossfeec25b2019-01-30 17:32:39 -0800240
Colin Cross69f59a32019-02-15 10:39:37 -0800241 inputs := make(map[string]Path)
Colin Crossfeec25b2019-01-30 17:32:39 -0800242 for _, c := range r.commands {
Ramy Medhat2f99eec2020-06-13 17:38:27 -0400243 for _, input := range append(c.inputs, c.implicits...) {
Dan Willemsen633c5022019-04-12 11:11:38 -0700244 inputStr := input.String()
245 if _, isOutput := outputs[inputStr]; !isOutput {
246 if _, isDepFile := depFiles[inputStr]; !isDepFile {
247 inputs[input.String()] = input
248 }
Colin Crossfeec25b2019-01-30 17:32:39 -0800249 }
250 }
251 }
252
Colin Cross69f59a32019-02-15 10:39:37 -0800253 var inputList Paths
254 for _, input := range inputs {
Colin Crossfeec25b2019-01-30 17:32:39 -0800255 inputList = append(inputList, input)
256 }
Colin Cross69f59a32019-02-15 10:39:37 -0800257
258 sort.Slice(inputList, func(i, j int) bool {
259 return inputList[i].String() < inputList[j].String()
260 })
Colin Crossfeec25b2019-01-30 17:32:39 -0800261
262 return inputList
263}
264
Colin Crossda71eda2020-02-21 16:55:19 -0800265// OrderOnlys returns the list of paths that were passed to the RuleBuilderCommand.OrderOnly or
266// RuleBuilderCommand.OrderOnlys. The list is sorted and duplicates removed.
267func (r *RuleBuilder) OrderOnlys() Paths {
268 orderOnlys := make(map[string]Path)
269 for _, c := range r.commands {
270 for _, orderOnly := range c.orderOnlys {
271 orderOnlys[orderOnly.String()] = orderOnly
272 }
273 }
274
275 var orderOnlyList Paths
276 for _, orderOnly := range orderOnlys {
277 orderOnlyList = append(orderOnlyList, orderOnly)
278 }
279
280 sort.Slice(orderOnlyList, func(i, j int) bool {
281 return orderOnlyList[i].String() < orderOnlyList[j].String()
282 })
283
284 return orderOnlyList
285}
286
Colin Crossae89abe2021-04-21 11:45:23 -0700287// Validations returns the list of paths that were passed to RuleBuilderCommand.Validation or
288// RuleBuilderCommand.Validations. The list is sorted and duplicates removed.
289func (r *RuleBuilder) Validations() Paths {
290 validations := make(map[string]Path)
291 for _, c := range r.commands {
292 for _, validation := range c.validations {
293 validations[validation.String()] = validation
294 }
295 }
296
297 var validationList Paths
298 for _, validation := range validations {
299 validationList = append(validationList, validation)
300 }
301
302 sort.Slice(validationList, func(i, j int) bool {
303 return validationList[i].String() < validationList[j].String()
304 })
305
306 return validationList
307}
308
Colin Cross69f59a32019-02-15 10:39:37 -0800309func (r *RuleBuilder) outputSet() map[string]WritablePath {
310 outputs := make(map[string]WritablePath)
Colin Crossfeec25b2019-01-30 17:32:39 -0800311 for _, c := range r.commands {
312 for _, output := range c.outputs {
Colin Cross69f59a32019-02-15 10:39:37 -0800313 outputs[output.String()] = output
Colin Crossfeec25b2019-01-30 17:32:39 -0800314 }
315 }
316 return outputs
317}
318
Colin Crossda71eda2020-02-21 16:55:19 -0800319// Outputs returns the list of paths that were passed to the RuleBuilderCommand methods that take
320// output paths, such as RuleBuilderCommand.Output, RuleBuilderCommand.ImplicitOutput, or
321// RuleBuilderCommand.FlagWithInput. The list is sorted and duplicates removed.
Colin Cross69f59a32019-02-15 10:39:37 -0800322func (r *RuleBuilder) Outputs() WritablePaths {
Colin Crossfeec25b2019-01-30 17:32:39 -0800323 outputs := r.outputSet()
324
Colin Cross69f59a32019-02-15 10:39:37 -0800325 var outputList WritablePaths
326 for _, output := range outputs {
Colin Cross5cb5b092019-02-02 21:25:18 -0800327 if !r.temporariesSet[output] {
328 outputList = append(outputList, output)
329 }
Colin Crossfeec25b2019-01-30 17:32:39 -0800330 }
Colin Cross69f59a32019-02-15 10:39:37 -0800331
332 sort.Slice(outputList, func(i, j int) bool {
333 return outputList[i].String() < outputList[j].String()
334 })
335
Colin Crossfeec25b2019-01-30 17:32:39 -0800336 return outputList
337}
338
Jingwen Chence679d22020-09-23 04:30:02 +0000339func (r *RuleBuilder) symlinkOutputSet() map[string]WritablePath {
340 symlinkOutputs := make(map[string]WritablePath)
341 for _, c := range r.commands {
342 for _, symlinkOutput := range c.symlinkOutputs {
343 symlinkOutputs[symlinkOutput.String()] = symlinkOutput
344 }
345 }
346 return symlinkOutputs
347}
348
349// SymlinkOutputs returns the list of paths that the executor (Ninja) would
350// verify, after build edge completion, that:
351//
352// 1) Created output symlinks match the list of paths in this list exactly (no more, no fewer)
353// 2) Created output files are *not* declared in this list.
354//
355// These symlink outputs are expected to be a subset of outputs or implicit
356// outputs, or they would fail validation at build param construction time
357// later, to support other non-rule-builder approaches for constructing
358// statements.
359func (r *RuleBuilder) SymlinkOutputs() WritablePaths {
360 symlinkOutputs := r.symlinkOutputSet()
361
362 var symlinkOutputList WritablePaths
363 for _, symlinkOutput := range symlinkOutputs {
364 symlinkOutputList = append(symlinkOutputList, symlinkOutput)
365 }
366
367 sort.Slice(symlinkOutputList, func(i, j int) bool {
368 return symlinkOutputList[i].String() < symlinkOutputList[j].String()
369 })
370
371 return symlinkOutputList
372}
373
Dan Willemsen633c5022019-04-12 11:11:38 -0700374func (r *RuleBuilder) depFileSet() map[string]WritablePath {
375 depFiles := make(map[string]WritablePath)
376 for _, c := range r.commands {
377 for _, depFile := range c.depFiles {
378 depFiles[depFile.String()] = depFile
379 }
380 }
381 return depFiles
382}
383
Colin Cross1d2cf042019-03-29 15:33:06 -0700384// DepFiles returns the list of paths that were passed to the RuleBuilderCommand methods that take depfile paths, such
385// as RuleBuilderCommand.DepFile or RuleBuilderCommand.FlagWithDepFile.
386func (r *RuleBuilder) DepFiles() WritablePaths {
387 var depFiles WritablePaths
388
389 for _, c := range r.commands {
390 for _, depFile := range c.depFiles {
391 depFiles = append(depFiles, depFile)
392 }
393 }
394
395 return depFiles
396}
397
Colin Cross758290d2019-02-01 16:42:32 -0800398// Installs returns the list of tuples passed to Install.
Colin Crossdeabb942019-02-11 14:11:09 -0800399func (r *RuleBuilder) Installs() RuleBuilderInstalls {
400 return append(RuleBuilderInstalls(nil), r.installs...)
Colin Crossfeec25b2019-01-30 17:32:39 -0800401}
402
Colin Cross69f59a32019-02-15 10:39:37 -0800403func (r *RuleBuilder) toolsSet() map[string]Path {
404 tools := make(map[string]Path)
Colin Cross5cb5b092019-02-02 21:25:18 -0800405 for _, c := range r.commands {
406 for _, tool := range c.tools {
Colin Cross69f59a32019-02-15 10:39:37 -0800407 tools[tool.String()] = tool
Colin Cross5cb5b092019-02-02 21:25:18 -0800408 }
409 }
410
411 return tools
412}
413
Colin Crossda71eda2020-02-21 16:55:19 -0800414// Tools returns the list of paths that were passed to the RuleBuilderCommand.Tool method. The
415// list is sorted and duplicates removed.
Colin Cross69f59a32019-02-15 10:39:37 -0800416func (r *RuleBuilder) Tools() Paths {
Colin Cross5cb5b092019-02-02 21:25:18 -0800417 toolsSet := r.toolsSet()
418
Colin Cross69f59a32019-02-15 10:39:37 -0800419 var toolsList Paths
420 for _, tool := range toolsSet {
Colin Cross5cb5b092019-02-02 21:25:18 -0800421 toolsList = append(toolsList, tool)
Colin Crossfeec25b2019-01-30 17:32:39 -0800422 }
Colin Cross69f59a32019-02-15 10:39:37 -0800423
424 sort.Slice(toolsList, func(i, j int) bool {
425 return toolsList[i].String() < toolsList[j].String()
426 })
427
Colin Cross5cb5b092019-02-02 21:25:18 -0800428 return toolsList
Colin Crossfeec25b2019-01-30 17:32:39 -0800429}
430
Colin Cross0cb0d7b2019-07-11 10:59:15 -0700431// RspFileInputs returns the list of paths that were passed to the RuleBuilderCommand.FlagWithRspFileInputList method.
432func (r *RuleBuilder) RspFileInputs() Paths {
433 var rspFileInputs Paths
434 for _, c := range r.commands {
Colin Crossce3a51d2021-03-19 16:22:12 -0700435 for _, rspFile := range c.rspFiles {
436 rspFileInputs = append(rspFileInputs, rspFile.paths...)
Colin Cross0cb0d7b2019-07-11 10:59:15 -0700437 }
438 }
439
440 return rspFileInputs
441}
442
Colin Crossce3a51d2021-03-19 16:22:12 -0700443func (r *RuleBuilder) rspFiles() []rspFileAndPaths {
444 var rspFiles []rspFileAndPaths
Colin Cross70c47412021-03-12 17:48:14 -0800445 for _, c := range r.commands {
Colin Crossce3a51d2021-03-19 16:22:12 -0700446 rspFiles = append(rspFiles, c.rspFiles...)
Colin Cross70c47412021-03-12 17:48:14 -0800447 }
448
Colin Crossce3a51d2021-03-19 16:22:12 -0700449 return rspFiles
Colin Cross70c47412021-03-12 17:48:14 -0800450}
451
Colin Cross0cb0d7b2019-07-11 10:59:15 -0700452// Commands returns a slice containing the built command line for each call to RuleBuilder.Command.
Colin Crossfeec25b2019-01-30 17:32:39 -0800453func (r *RuleBuilder) Commands() []string {
454 var commands []string
455 for _, c := range r.commands {
Colin Cross0cb0d7b2019-07-11 10:59:15 -0700456 commands = append(commands, c.String())
457 }
458 return commands
459}
460
Colin Cross758290d2019-02-01 16:42:32 -0800461// BuilderContext is a subset of ModuleContext and SingletonContext.
Colin Cross786cd6d2019-02-01 16:41:11 -0800462type BuilderContext interface {
463 PathContext
464 Rule(PackageContext, string, blueprint.RuleParams, ...string) blueprint.Rule
465 Build(PackageContext, BuildParams)
466}
467
Colin Cross758290d2019-02-01 16:42:32 -0800468var _ BuilderContext = ModuleContext(nil)
469var _ BuilderContext = SingletonContext(nil)
470
Colin Crossf1a035e2020-11-16 17:32:30 -0800471func (r *RuleBuilder) depFileMergerCmd(depFiles WritablePaths) *RuleBuilderCommand {
Dan Willemsen633c5022019-04-12 11:11:38 -0700472 return r.Command().
Colin Crossf1a035e2020-11-16 17:32:30 -0800473 BuiltTool("dep_fixer").
Dan Willemsen633c5022019-04-12 11:11:38 -0700474 Inputs(depFiles.Paths())
Colin Cross1d2cf042019-03-29 15:33:06 -0700475}
476
Colin Cross758290d2019-02-01 16:42:32 -0800477// Build adds the built command line to the build graph, with dependencies on Inputs and Tools, and output files for
478// Outputs.
Colin Crossf1a035e2020-11-16 17:32:30 -0800479func (r *RuleBuilder) Build(name string, desc string) {
Colin Cross1d2cf042019-03-29 15:33:06 -0700480 name = ninjaNameEscape(name)
481
Colin Cross0d2f40a2019-02-05 22:31:15 -0800482 if len(r.missingDeps) > 0 {
Colin Crossf1a035e2020-11-16 17:32:30 -0800483 r.ctx.Build(pctx, BuildParams{
Colin Cross0d2f40a2019-02-05 22:31:15 -0800484 Rule: ErrorRule,
Colin Cross69f59a32019-02-15 10:39:37 -0800485 Outputs: r.Outputs(),
Colin Cross0d2f40a2019-02-05 22:31:15 -0800486 Description: desc,
487 Args: map[string]string{
488 "error": "missing dependencies: " + strings.Join(r.missingDeps, ", "),
489 },
490 })
491 return
492 }
493
Colin Cross1d2cf042019-03-29 15:33:06 -0700494 var depFile WritablePath
495 var depFormat blueprint.Deps
496 if depFiles := r.DepFiles(); len(depFiles) > 0 {
497 depFile = depFiles[0]
498 depFormat = blueprint.DepsGCC
499 if len(depFiles) > 1 {
500 // Add a command locally that merges all depfiles together into the first depfile.
Colin Crossf1a035e2020-11-16 17:32:30 -0800501 r.depFileMergerCmd(depFiles)
Dan Willemsen633c5022019-04-12 11:11:38 -0700502
503 if r.sbox {
Colin Crosse16ce362020-11-12 08:29:30 -0800504 // Check for Rel() errors, as all depfiles should be in the output dir. Errors
505 // will be reported to the ctx.
Dan Willemsen633c5022019-04-12 11:11:38 -0700506 for _, path := range depFiles[1:] {
Colin Crossf1a035e2020-11-16 17:32:30 -0800507 Rel(r.ctx, r.outDir.String(), path.String())
Dan Willemsen633c5022019-04-12 11:11:38 -0700508 }
509 }
Colin Cross1d2cf042019-03-29 15:33:06 -0700510 }
511 }
512
Dan Willemsen633c5022019-04-12 11:11:38 -0700513 tools := r.Tools()
Colin Crossb70a1a92021-03-12 17:51:32 -0800514 commands := r.Commands()
Dan Willemsen633c5022019-04-12 11:11:38 -0700515 outputs := r.Outputs()
Colin Cross3d680512020-11-13 16:23:53 -0800516 inputs := r.Inputs()
Colin Crossce3a51d2021-03-19 16:22:12 -0700517 rspFiles := r.rspFiles()
Dan Willemsen633c5022019-04-12 11:11:38 -0700518
519 if len(commands) == 0 {
520 return
521 }
522 if len(outputs) == 0 {
523 panic("No outputs specified from any Commands")
524 }
525
Colin Cross0cb0d7b2019-07-11 10:59:15 -0700526 commandString := strings.Join(commands, " && ")
Dan Willemsen633c5022019-04-12 11:11:38 -0700527
528 if r.sbox {
Colin Crosse16ce362020-11-12 08:29:30 -0800529 // If running the command inside sbox, write the rule data out to an sbox
530 // manifest.textproto.
531 manifest := sbox_proto.Manifest{}
532 command := sbox_proto.Command{}
533 manifest.Commands = append(manifest.Commands, &command)
534 command.Command = proto.String(commandString)
Colin Cross151b9ff2020-11-12 08:29:30 -0800535
Colin Cross619b9ab2020-11-20 18:44:31 +0000536 if depFile != nil {
Colin Crosse16ce362020-11-12 08:29:30 -0800537 manifest.OutputDepfile = proto.String(depFile.String())
Colin Cross619b9ab2020-11-20 18:44:31 +0000538 }
539
Colin Crossba9e4032020-11-24 16:32:22 -0800540 // If sandboxing tools is enabled, add copy rules to the manifest to copy each tool
541 // into the sbox directory.
542 if r.sboxTools {
543 for _, tool := range tools {
544 command.CopyBefore = append(command.CopyBefore, &sbox_proto.Copy{
545 From: proto.String(tool.String()),
546 To: proto.String(sboxPathForToolRel(r.ctx, tool)),
547 })
548 }
549 for _, c := range r.commands {
550 for _, tool := range c.packagedTools {
551 command.CopyBefore = append(command.CopyBefore, &sbox_proto.Copy{
552 From: proto.String(tool.srcPath.String()),
553 To: proto.String(sboxPathForPackagedToolRel(tool)),
554 Executable: proto.Bool(tool.executable),
555 })
556 tools = append(tools, tool.srcPath)
557 }
558 }
559 }
560
Colin Crossab020a72021-03-12 17:52:23 -0800561 // If sandboxing inputs is enabled, add copy rules to the manifest to copy each input
562 // into the sbox directory.
563 if r.sboxInputs {
564 for _, input := range inputs {
565 command.CopyBefore = append(command.CopyBefore, &sbox_proto.Copy{
566 From: proto.String(input.String()),
567 To: proto.String(r.sboxPathForInputRel(input)),
568 })
569 }
570
Colin Crossce3a51d2021-03-19 16:22:12 -0700571 // If using rsp files copy them and their contents into the sbox directory with
572 // the appropriate path mappings.
573 for _, rspFile := range rspFiles {
Colin Crosse55bd422021-03-23 13:44:30 -0700574 command.RspFiles = append(command.RspFiles, &sbox_proto.RspFile{
Colin Crossce3a51d2021-03-19 16:22:12 -0700575 File: proto.String(rspFile.file.String()),
Colin Crosse55bd422021-03-23 13:44:30 -0700576 // These have to match the logic in sboxPathForInputRel
577 PathMappings: []*sbox_proto.PathMapping{
578 {
579 From: proto.String(r.outDir.String()),
580 To: proto.String(sboxOutSubDir),
581 },
582 {
583 From: proto.String(PathForOutput(r.ctx).String()),
584 To: proto.String(sboxOutSubDir),
585 },
586 },
Colin Crossab020a72021-03-12 17:52:23 -0800587 })
588 }
589
590 command.Chdir = proto.Bool(true)
591 }
592
Colin Crosse16ce362020-11-12 08:29:30 -0800593 // Add copy rules to the manifest to copy each output file from the sbox directory.
Colin Crossba9e4032020-11-24 16:32:22 -0800594 // to the output directory after running the commands.
Colin Crosse16ce362020-11-12 08:29:30 -0800595 sboxOutputs := make([]string, len(outputs))
596 for i, output := range outputs {
Colin Crossf1a035e2020-11-16 17:32:30 -0800597 rel := Rel(r.ctx, r.outDir.String(), output.String())
Colin Crosse16ce362020-11-12 08:29:30 -0800598 sboxOutputs[i] = filepath.Join(sboxOutDir, rel)
599 command.CopyAfter = append(command.CopyAfter, &sbox_proto.Copy{
600 From: proto.String(filepath.Join(sboxOutSubDir, rel)),
601 To: proto.String(output.String()),
602 })
603 }
Colin Cross619b9ab2020-11-20 18:44:31 +0000604
Colin Cross5334edd2021-03-11 17:18:21 -0800605 // Outputs that were marked Temporary will not be checked that they are in the output
606 // directory by the loop above, check them here.
607 for path := range r.temporariesSet {
608 Rel(r.ctx, r.outDir.String(), path.String())
609 }
610
Colin Crosse16ce362020-11-12 08:29:30 -0800611 // Add a hash of the list of input files to the manifest so that the textproto file
612 // changes when the list of input files changes and causes the sbox rule that
613 // depends on it to rerun.
614 command.InputHash = proto.String(hashSrcFiles(inputs))
Colin Cross619b9ab2020-11-20 18:44:31 +0000615
Colin Crosse16ce362020-11-12 08:29:30 -0800616 // Verify that the manifest textproto is not inside the sbox output directory, otherwise
617 // it will get deleted when the sbox rule clears its output directory.
Colin Crossf1a035e2020-11-16 17:32:30 -0800618 _, manifestInOutDir := MaybeRel(r.ctx, r.outDir.String(), r.sboxManifestPath.String())
Colin Crosse16ce362020-11-12 08:29:30 -0800619 if manifestInOutDir {
Colin Crossf1a035e2020-11-16 17:32:30 -0800620 ReportPathErrorf(r.ctx, "sbox rule %q manifestPath %q must not be in outputDir %q",
621 name, r.sboxManifestPath.String(), r.outDir.String())
Colin Crosse16ce362020-11-12 08:29:30 -0800622 }
623
624 // Create a rule to write the manifest as a the textproto.
Dan Willemsen4591b642021-05-24 14:24:12 -0700625 pbText, err := prototext.Marshal(&manifest)
626 if err != nil {
627 ReportPathErrorf(r.ctx, "sbox manifest failed to marshal: %q", err)
628 }
629 WriteFileRule(r.ctx, r.sboxManifestPath, string(pbText))
Colin Crosse16ce362020-11-12 08:29:30 -0800630
631 // Generate a new string to use as the command line of the sbox rule. This uses
632 // a RuleBuilderCommand as a convenience method of building the command line, then
633 // converts it to a string to replace commandString.
Colin Crossf1a035e2020-11-16 17:32:30 -0800634 sboxCmd := &RuleBuilderCommand{
635 rule: &RuleBuilder{
636 ctx: r.ctx,
637 },
638 }
639 sboxCmd.Text("rm -rf").Output(r.outDir)
Colin Crosse16ce362020-11-12 08:29:30 -0800640 sboxCmd.Text("&&")
Colin Crossf1a035e2020-11-16 17:32:30 -0800641 sboxCmd.BuiltTool("sbox").
642 Flag("--sandbox-path").Text(shared.TempDirForOutDir(PathForOutput(r.ctx).String())).
Colin Crosse16ce362020-11-12 08:29:30 -0800643 Flag("--manifest").Input(r.sboxManifestPath)
644
645 // Replace the command string, and add the sbox tool and manifest textproto to the
646 // dependencies of the final sbox rule.
Colin Crosscfec40c2019-07-08 17:07:18 -0700647 commandString = sboxCmd.buf.String()
Dan Willemsen633c5022019-04-12 11:11:38 -0700648 tools = append(tools, sboxCmd.tools...)
Colin Crosse16ce362020-11-12 08:29:30 -0800649 inputs = append(inputs, sboxCmd.inputs...)
Colin Crossef972742021-03-12 17:24:45 -0800650
651 if r.rbeParams != nil {
Colin Crosse55bd422021-03-23 13:44:30 -0700652 // RBE needs a list of input files to copy to the remote builder. For inputs already
653 // listed in an rsp file, pass the rsp file directly to rewrapper. For the rest,
654 // create a new rsp file to pass to rewrapper.
655 var remoteRspFiles Paths
656 var remoteInputs Paths
657
658 remoteInputs = append(remoteInputs, inputs...)
659 remoteInputs = append(remoteInputs, tools...)
660
Colin Crossce3a51d2021-03-19 16:22:12 -0700661 for _, rspFile := range rspFiles {
662 remoteInputs = append(remoteInputs, rspFile.file)
663 remoteRspFiles = append(remoteRspFiles, rspFile.file)
Colin Crossef972742021-03-12 17:24:45 -0800664 }
Colin Crosse55bd422021-03-23 13:44:30 -0700665
666 if len(remoteInputs) > 0 {
667 inputsListFile := r.sboxManifestPath.ReplaceExtension(r.ctx, "rbe_inputs.list")
668 writeRspFileRule(r.ctx, inputsListFile, remoteInputs)
669 remoteRspFiles = append(remoteRspFiles, inputsListFile)
670 // Add the new rsp file as an extra input to the rule.
671 inputs = append(inputs, inputsListFile)
672 }
Colin Crossef972742021-03-12 17:24:45 -0800673
674 r.rbeParams.OutputFiles = outputs.Strings()
Colin Crosse55bd422021-03-23 13:44:30 -0700675 r.rbeParams.RSPFiles = remoteRspFiles.Strings()
Colin Crossef972742021-03-12 17:24:45 -0800676 rewrapperCommand := r.rbeParams.NoVarTemplate(r.ctx.Config().RBEWrapper())
677 commandString = rewrapperCommand + " bash -c '" + strings.ReplaceAll(commandString, `'`, `'\''`) + "'"
678 }
Colin Cross3d680512020-11-13 16:23:53 -0800679 } else {
680 // If not using sbox the rule will run the command directly, put the hash of the
681 // list of input files in a comment at the end of the command line to ensure ninja
682 // reruns the rule when the list of input files changes.
683 commandString += " # hash of input list: " + hashSrcFiles(inputs)
Dan Willemsen633c5022019-04-12 11:11:38 -0700684 }
685
Colin Cross1d2cf042019-03-29 15:33:06 -0700686 // Ninja doesn't like multiple outputs when depfiles are enabled, move all but the first output to
Colin Cross70c47412021-03-12 17:48:14 -0800687 // ImplicitOutputs. RuleBuilder doesn't use "$out", so the distinction between Outputs and
Colin Cross0cb0d7b2019-07-11 10:59:15 -0700688 // ImplicitOutputs doesn't matter.
Dan Willemsen633c5022019-04-12 11:11:38 -0700689 output := outputs[0]
690 implicitOutputs := outputs[1:]
Colin Cross1d2cf042019-03-29 15:33:06 -0700691
Colin Cross0cb0d7b2019-07-11 10:59:15 -0700692 var rspFile, rspFileContent string
Colin Crossce3a51d2021-03-19 16:22:12 -0700693 var rspFileInputs Paths
694 if len(rspFiles) > 0 {
695 // The first rsp files uses Ninja's rsp file support for the rule
696 rspFile = rspFiles[0].file.String()
Colin Crosse55bd422021-03-23 13:44:30 -0700697 // Use "$in" for rspFileContent to avoid duplicating the list of files in the dependency
698 // list and in the contents of the rsp file. Inputs to the rule that are not in the
699 // rsp file will be listed in Implicits instead of Inputs so they don't show up in "$in".
700 rspFileContent = "$in"
Colin Crossce3a51d2021-03-19 16:22:12 -0700701 rspFileInputs = append(rspFileInputs, rspFiles[0].paths...)
702
703 for _, rspFile := range rspFiles[1:] {
704 // Any additional rsp files need an extra rule to write the file.
705 writeRspFileRule(r.ctx, rspFile.file, rspFile.paths)
706 // The main rule needs to depend on the inputs listed in the extra rsp file.
707 inputs = append(inputs, rspFile.paths...)
708 // The main rule needs to depend on the extra rsp file.
709 inputs = append(inputs, rspFile.file)
710 }
Colin Cross0cb0d7b2019-07-11 10:59:15 -0700711 }
712
Colin Cross8b8bec32019-11-15 13:18:43 -0800713 var pool blueprint.Pool
Colin Crossf1a035e2020-11-16 17:32:30 -0800714 if r.ctx.Config().UseGoma() && r.remoteable.Goma {
Colin Cross8b8bec32019-11-15 13:18:43 -0800715 // 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 -0800716 } else if r.ctx.Config().UseRBE() && r.remoteable.RBE {
Ramy Medhat944839a2020-03-31 22:14:52 -0400717 // When USE_RBE=true is set and the rule is supported by RBE, use the remotePool.
718 pool = remotePool
Colin Cross8b8bec32019-11-15 13:18:43 -0800719 } else if r.highmem {
720 pool = highmemPool
Colin Crossf1a035e2020-11-16 17:32:30 -0800721 } else if r.ctx.Config().UseRemoteBuild() {
Colin Cross8b8bec32019-11-15 13:18:43 -0800722 pool = localPool
723 }
724
Colin Crossf1a035e2020-11-16 17:32:30 -0800725 r.ctx.Build(r.pctx, BuildParams{
726 Rule: r.ctx.Rule(pctx, name, blueprint.RuleParams{
Colin Crossb70a1a92021-03-12 17:51:32 -0800727 Command: proptools.NinjaEscape(commandString),
Colin Cross45029782021-03-16 16:49:52 -0700728 CommandDeps: proptools.NinjaEscapeList(tools.Strings()),
Colin Cross0cb0d7b2019-07-11 10:59:15 -0700729 Restat: r.restat,
Colin Cross45029782021-03-16 16:49:52 -0700730 Rspfile: proptools.NinjaEscape(rspFile),
Colin Cross0cb0d7b2019-07-11 10:59:15 -0700731 RspfileContent: rspFileContent,
Colin Cross8b8bec32019-11-15 13:18:43 -0800732 Pool: pool,
Dan Willemsen633c5022019-04-12 11:11:38 -0700733 }),
Colin Cross0cb0d7b2019-07-11 10:59:15 -0700734 Inputs: rspFileInputs,
Colin Cross3d680512020-11-13 16:23:53 -0800735 Implicits: inputs,
Colin Crossda6401b2021-04-21 11:32:19 -0700736 OrderOnly: r.OrderOnlys(),
Colin Crossae89abe2021-04-21 11:45:23 -0700737 Validations: r.Validations(),
Dan Willemsen633c5022019-04-12 11:11:38 -0700738 Output: output,
739 ImplicitOutputs: implicitOutputs,
Jingwen Chence679d22020-09-23 04:30:02 +0000740 SymlinkOutputs: r.SymlinkOutputs(),
Dan Willemsen633c5022019-04-12 11:11:38 -0700741 Depfile: depFile,
742 Deps: depFormat,
743 Description: desc,
744 })
Colin Crossfeec25b2019-01-30 17:32:39 -0800745}
746
Colin Cross758290d2019-02-01 16:42:32 -0800747// RuleBuilderCommand is a builder for a command in a command line. It can be mutated by its methods to add to the
748// command and track dependencies. The methods mutate the RuleBuilderCommand in place, as well as return the
749// RuleBuilderCommand, so they can be used chained or unchained. All methods that add text implicitly add a single
750// space as a separator from the previous method.
Colin Crossfeec25b2019-01-30 17:32:39 -0800751type RuleBuilderCommand struct {
Colin Crossf1a035e2020-11-16 17:32:30 -0800752 rule *RuleBuilder
753
Jingwen Chence679d22020-09-23 04:30:02 +0000754 buf strings.Builder
755 inputs Paths
756 implicits Paths
757 orderOnlys Paths
Colin Crossae89abe2021-04-21 11:45:23 -0700758 validations Paths
Jingwen Chence679d22020-09-23 04:30:02 +0000759 outputs WritablePaths
760 symlinkOutputs WritablePaths
761 depFiles WritablePaths
762 tools Paths
Colin Crossba9e4032020-11-24 16:32:22 -0800763 packagedTools []PackagingSpec
Colin Crossce3a51d2021-03-19 16:22:12 -0700764 rspFiles []rspFileAndPaths
765}
766
767type rspFileAndPaths struct {
768 file WritablePath
769 paths Paths
Dan Willemsen633c5022019-04-12 11:11:38 -0700770}
771
Paul Duffin3866b892021-10-04 11:24:48 +0100772func checkPathNotNil(path Path) {
773 if path == nil {
774 panic("rule_builder paths cannot be nil")
775 }
776}
777
Dan Willemsen633c5022019-04-12 11:11:38 -0700778func (c *RuleBuilderCommand) addInput(path Path) string {
Paul Duffin3866b892021-10-04 11:24:48 +0100779 checkPathNotNil(path)
Dan Willemsen633c5022019-04-12 11:11:38 -0700780 c.inputs = append(c.inputs, path)
Colin Crossab020a72021-03-12 17:52:23 -0800781 return c.PathForInput(path)
Dan Willemsen633c5022019-04-12 11:11:38 -0700782}
783
Colin Crossab020a72021-03-12 17:52:23 -0800784func (c *RuleBuilderCommand) addImplicit(path Path) {
Paul Duffin3866b892021-10-04 11:24:48 +0100785 checkPathNotNil(path)
Ramy Medhat2f99eec2020-06-13 17:38:27 -0400786 c.implicits = append(c.implicits, path)
Ramy Medhat2f99eec2020-06-13 17:38:27 -0400787}
788
Colin Crossda71eda2020-02-21 16:55:19 -0800789func (c *RuleBuilderCommand) addOrderOnly(path Path) {
Paul Duffin3866b892021-10-04 11:24:48 +0100790 checkPathNotNil(path)
Colin Crossda71eda2020-02-21 16:55:19 -0800791 c.orderOnlys = append(c.orderOnlys, path)
792}
793
Colin Crossab020a72021-03-12 17:52:23 -0800794// PathForInput takes an input path and returns the appropriate path to use on the command line. If
795// sbox was enabled via a call to RuleBuilder.Sbox() and the path was an output path it returns a
796// path with the placeholder prefix used for outputs in sbox. If sbox is not enabled it returns the
797// original path.
798func (c *RuleBuilderCommand) PathForInput(path Path) string {
799 if c.rule.sbox {
800 rel, inSandbox := c.rule._sboxPathForInputRel(path)
801 if inSandbox {
802 rel = filepath.Join(sboxSandboxBaseDir, rel)
803 }
804 return rel
805 }
806 return path.String()
807}
808
809// PathsForInputs takes a list of input paths and returns the appropriate paths to use on the
810// command line. If sbox was enabled via a call to RuleBuilder.Sbox() a path was an output path, it
811// returns the path with the placeholder prefix used for outputs in sbox. If sbox is not enabled it
812// returns the original paths.
813func (c *RuleBuilderCommand) PathsForInputs(paths Paths) []string {
814 ret := make([]string, len(paths))
815 for i, path := range paths {
816 ret[i] = c.PathForInput(path)
817 }
818 return ret
819}
820
Colin Crossf1a035e2020-11-16 17:32:30 -0800821// PathForOutput takes an output path and returns the appropriate path to use on the command
822// line. If sbox was enabled via a call to RuleBuilder.Sbox(), it returns a path with the
823// placeholder prefix used for outputs in sbox. If sbox is not enabled it returns the
824// original path.
825func (c *RuleBuilderCommand) PathForOutput(path WritablePath) string {
826 if c.rule.sbox {
827 // Errors will be handled in RuleBuilder.Build where we have a context to report them
828 rel, _, _ := maybeRelErr(c.rule.outDir.String(), path.String())
829 return filepath.Join(sboxOutDir, rel)
Dan Willemsen633c5022019-04-12 11:11:38 -0700830 }
831 return path.String()
Colin Crossfeec25b2019-01-30 17:32:39 -0800832}
833
Colin Crossba9e4032020-11-24 16:32:22 -0800834func sboxPathForToolRel(ctx BuilderContext, path Path) string {
835 // Errors will be handled in RuleBuilder.Build where we have a context to report them
836 relOut, isRelOut, _ := maybeRelErr(PathForOutput(ctx, "host", ctx.Config().PrebuiltOS()).String(), path.String())
837 if isRelOut {
838 // The tool is in the output directory, it will be copied to __SBOX_OUT_DIR__/tools/out
839 return filepath.Join(sboxToolsSubDir, "out", relOut)
840 }
841 // The tool is in the source directory, it will be copied to __SBOX_OUT_DIR__/tools/src
842 return filepath.Join(sboxToolsSubDir, "src", path.String())
843}
844
Colin Crossab020a72021-03-12 17:52:23 -0800845func (r *RuleBuilder) _sboxPathForInputRel(path Path) (rel string, inSandbox bool) {
846 // Errors will be handled in RuleBuilder.Build where we have a context to report them
847 rel, isRelSboxOut, _ := maybeRelErr(r.outDir.String(), path.String())
848 if isRelSboxOut {
849 return filepath.Join(sboxOutSubDir, rel), true
850 }
851 if r.sboxInputs {
852 // When sandboxing inputs all inputs have to be copied into the sandbox. Input files that
853 // are outputs of other rules could be an arbitrary absolute path if OUT_DIR is set, so they
854 // will be copied to relative paths under __SBOX_OUT_DIR__/out.
855 rel, isRelOut, _ := maybeRelErr(PathForOutput(r.ctx).String(), path.String())
856 if isRelOut {
857 return filepath.Join(sboxOutSubDir, rel), true
858 }
859 }
860 return path.String(), false
861}
862
863func (r *RuleBuilder) sboxPathForInputRel(path Path) string {
864 rel, _ := r._sboxPathForInputRel(path)
865 return rel
866}
867
868func (r *RuleBuilder) sboxPathsForInputsRel(paths Paths) []string {
869 ret := make([]string, len(paths))
870 for i, path := range paths {
871 ret[i] = r.sboxPathForInputRel(path)
872 }
873 return ret
874}
875
Colin Crossba9e4032020-11-24 16:32:22 -0800876func sboxPathForPackagedToolRel(spec PackagingSpec) string {
877 return filepath.Join(sboxToolsSubDir, "out", spec.relPathInPackage)
878}
879
Colin Crossd11cf622021-03-23 22:30:35 -0700880// PathForPackagedTool takes a PackageSpec for a tool and returns the corresponding path for the
881// tool after copying it into the sandbox. This can be used on the RuleBuilder command line to
882// reference the tool.
883func (c *RuleBuilderCommand) PathForPackagedTool(spec PackagingSpec) string {
884 if !c.rule.sboxTools {
885 panic("PathForPackagedTool() requires SandboxTools()")
886 }
887
888 return filepath.Join(sboxSandboxBaseDir, sboxPathForPackagedToolRel(spec))
889}
890
Colin Crossba9e4032020-11-24 16:32:22 -0800891// PathForTool takes a path to a tool, which may be an output file or a source file, and returns
892// the corresponding path for the tool in the sbox sandbox if sbox is enabled, or the original path
893// if it is not. This can be used on the RuleBuilder command line to reference the tool.
894func (c *RuleBuilderCommand) PathForTool(path Path) string {
895 if c.rule.sbox && c.rule.sboxTools {
896 return filepath.Join(sboxSandboxBaseDir, sboxPathForToolRel(c.rule.ctx, path))
897 }
898 return path.String()
899}
900
Colin Crossd11cf622021-03-23 22:30:35 -0700901// PathsForTools takes a list of paths to tools, which may be output files or source files, and
902// returns the corresponding paths for the tools in the sbox sandbox if sbox is enabled, or the
903// original paths if it is not. This can be used on the RuleBuilder command line to reference the tool.
904func (c *RuleBuilderCommand) PathsForTools(paths Paths) []string {
905 if c.rule.sbox && c.rule.sboxTools {
906 var ret []string
907 for _, path := range paths {
908 ret = append(ret, filepath.Join(sboxSandboxBaseDir, sboxPathForToolRel(c.rule.ctx, path)))
909 }
910 return ret
911 }
912 return paths.Strings()
913}
914
Colin Crossba9e4032020-11-24 16:32:22 -0800915// PackagedTool adds the specified tool path to the command line. It can only be used with tool
916// sandboxing enabled by SandboxTools(), and will copy the tool into the sandbox.
917func (c *RuleBuilderCommand) PackagedTool(spec PackagingSpec) *RuleBuilderCommand {
918 if !c.rule.sboxTools {
919 panic("PackagedTool() requires SandboxTools()")
920 }
921
922 c.packagedTools = append(c.packagedTools, spec)
923 c.Text(sboxPathForPackagedToolRel(spec))
924 return c
925}
926
927// ImplicitPackagedTool copies the specified tool into the sandbox without modifying the command
928// line. It can only be used with tool sandboxing enabled by SandboxTools().
929func (c *RuleBuilderCommand) ImplicitPackagedTool(spec PackagingSpec) *RuleBuilderCommand {
930 if !c.rule.sboxTools {
931 panic("ImplicitPackagedTool() requires SandboxTools()")
932 }
933
934 c.packagedTools = append(c.packagedTools, spec)
935 return c
936}
937
938// ImplicitPackagedTools copies the specified tools into the sandbox without modifying the command
939// line. It can only be used with tool sandboxing enabled by SandboxTools().
940func (c *RuleBuilderCommand) ImplicitPackagedTools(specs []PackagingSpec) *RuleBuilderCommand {
941 if !c.rule.sboxTools {
942 panic("ImplicitPackagedTools() requires SandboxTools()")
943 }
944
945 c.packagedTools = append(c.packagedTools, specs...)
946 return c
947}
948
Colin Cross758290d2019-02-01 16:42:32 -0800949// Text adds the specified raw text to the command line. The text should not contain input or output paths or the
950// rule will not have them listed in its dependencies or outputs.
Colin Crossfeec25b2019-01-30 17:32:39 -0800951func (c *RuleBuilderCommand) Text(text string) *RuleBuilderCommand {
Colin Crosscfec40c2019-07-08 17:07:18 -0700952 if c.buf.Len() > 0 {
953 c.buf.WriteByte(' ')
Colin Crossfeec25b2019-01-30 17:32:39 -0800954 }
Colin Crosscfec40c2019-07-08 17:07:18 -0700955 c.buf.WriteString(text)
Colin Crossfeec25b2019-01-30 17:32:39 -0800956 return c
957}
958
Colin Cross758290d2019-02-01 16:42:32 -0800959// Textf adds the specified formatted text to the command line. The text should not contain input or output paths or
960// the rule will not have them listed in its dependencies or outputs.
Colin Crossfeec25b2019-01-30 17:32:39 -0800961func (c *RuleBuilderCommand) Textf(format string, a ...interface{}) *RuleBuilderCommand {
962 return c.Text(fmt.Sprintf(format, a...))
963}
964
Colin Cross758290d2019-02-01 16:42:32 -0800965// Flag adds the specified raw text to the command line. The text should not contain input or output paths or the
966// rule will not have them listed in its dependencies or outputs.
Colin Crossfeec25b2019-01-30 17:32:39 -0800967func (c *RuleBuilderCommand) Flag(flag string) *RuleBuilderCommand {
968 return c.Text(flag)
969}
970
Colin Crossab054432019-07-15 16:13:59 -0700971// OptionalFlag adds the specified raw text to the command line if it is not nil. The text should not contain input or
972// output paths or the rule will not have them listed in its dependencies or outputs.
973func (c *RuleBuilderCommand) OptionalFlag(flag *string) *RuleBuilderCommand {
974 if flag != nil {
975 c.Text(*flag)
976 }
977
978 return c
979}
980
Colin Cross92b7d582019-03-29 15:32:51 -0700981// Flags adds the specified raw text to the command line. The text should not contain input or output paths or the
982// rule will not have them listed in its dependencies or outputs.
983func (c *RuleBuilderCommand) Flags(flags []string) *RuleBuilderCommand {
984 for _, flag := range flags {
985 c.Text(flag)
986 }
987 return c
988}
989
Colin Cross758290d2019-02-01 16:42:32 -0800990// FlagWithArg adds the specified flag and argument text to the command line, with no separator between them. The flag
991// and argument should not contain input or output paths or the rule will not have them listed in its dependencies or
992// outputs.
Colin Crossfeec25b2019-01-30 17:32:39 -0800993func (c *RuleBuilderCommand) FlagWithArg(flag, arg string) *RuleBuilderCommand {
994 return c.Text(flag + arg)
995}
996
Colin Crossc7ed0042019-02-11 14:11:09 -0800997// FlagForEachArg adds the specified flag joined with each argument to the command line. The result is identical to
998// calling FlagWithArg for argument.
999func (c *RuleBuilderCommand) FlagForEachArg(flag string, args []string) *RuleBuilderCommand {
1000 for _, arg := range args {
1001 c.FlagWithArg(flag, arg)
1002 }
1003 return c
1004}
1005
Roland Levillain2da5d9a2019-02-27 16:56:41 +00001006// 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 -08001007// and no separator between the flag and arguments. The flag and arguments should not contain input or output paths or
1008// the rule will not have them listed in its dependencies or outputs.
Colin Crossfeec25b2019-01-30 17:32:39 -08001009func (c *RuleBuilderCommand) FlagWithList(flag string, list []string, sep string) *RuleBuilderCommand {
1010 return c.Text(flag + strings.Join(list, sep))
1011}
1012
Colin Cross758290d2019-02-01 16:42:32 -08001013// Tool adds the specified tool path to the command line. The path will be also added to the dependencies returned by
1014// RuleBuilder.Tools.
Colin Cross69f59a32019-02-15 10:39:37 -08001015func (c *RuleBuilderCommand) Tool(path Path) *RuleBuilderCommand {
Paul Duffin3866b892021-10-04 11:24:48 +01001016 checkPathNotNil(path)
Colin Crossfeec25b2019-01-30 17:32:39 -08001017 c.tools = append(c.tools, path)
Colin Crossba9e4032020-11-24 16:32:22 -08001018 return c.Text(c.PathForTool(path))
1019}
1020
1021// Tool adds the specified tool path to the dependencies returned by RuleBuilder.Tools.
1022func (c *RuleBuilderCommand) ImplicitTool(path Path) *RuleBuilderCommand {
Paul Duffin3866b892021-10-04 11:24:48 +01001023 checkPathNotNil(path)
Colin Crossba9e4032020-11-24 16:32:22 -08001024 c.tools = append(c.tools, path)
1025 return c
1026}
1027
1028// Tool adds the specified tool path to the dependencies returned by RuleBuilder.Tools.
1029func (c *RuleBuilderCommand) ImplicitTools(paths Paths) *RuleBuilderCommand {
Paul Duffin3866b892021-10-04 11:24:48 +01001030 for _, path := range paths {
1031 c.ImplicitTool(path)
1032 }
Colin Crossba9e4032020-11-24 16:32:22 -08001033 return c
Colin Crossfeec25b2019-01-30 17:32:39 -08001034}
1035
Colin Crossee94d6a2019-07-08 17:08:34 -07001036// BuiltTool adds the specified tool path that was built using a host Soong module to the command line. The path will
1037// be also added to the dependencies returned by RuleBuilder.Tools.
1038//
1039// It is equivalent to:
1040// cmd.Tool(ctx.Config().HostToolPath(ctx, tool))
Colin Crossf1a035e2020-11-16 17:32:30 -08001041func (c *RuleBuilderCommand) BuiltTool(tool string) *RuleBuilderCommand {
1042 return c.Tool(c.rule.ctx.Config().HostToolPath(c.rule.ctx, tool))
Colin Crossee94d6a2019-07-08 17:08:34 -07001043}
1044
1045// PrebuiltBuildTool adds the specified tool path from prebuils/build-tools. The path will be also added to the
1046// dependencies returned by RuleBuilder.Tools.
1047//
1048// It is equivalent to:
1049// cmd.Tool(ctx.Config().PrebuiltBuildTool(ctx, tool))
1050func (c *RuleBuilderCommand) PrebuiltBuildTool(ctx PathContext, tool string) *RuleBuilderCommand {
1051 return c.Tool(ctx.Config().PrebuiltBuildTool(ctx, tool))
1052}
1053
Colin Cross758290d2019-02-01 16:42:32 -08001054// Input adds the specified input path to the command line. The path will also be added to the dependencies returned by
1055// RuleBuilder.Inputs.
Colin Cross69f59a32019-02-15 10:39:37 -08001056func (c *RuleBuilderCommand) Input(path Path) *RuleBuilderCommand {
Dan Willemsen633c5022019-04-12 11:11:38 -07001057 return c.Text(c.addInput(path))
Colin Crossfeec25b2019-01-30 17:32:39 -08001058}
1059
Colin Cross758290d2019-02-01 16:42:32 -08001060// Inputs adds the specified input paths to the command line, separated by spaces. The paths will also be added to the
1061// dependencies returned by RuleBuilder.Inputs.
Colin Cross69f59a32019-02-15 10:39:37 -08001062func (c *RuleBuilderCommand) Inputs(paths Paths) *RuleBuilderCommand {
Colin Cross758290d2019-02-01 16:42:32 -08001063 for _, path := range paths {
1064 c.Input(path)
1065 }
1066 return c
1067}
1068
1069// Implicit adds the specified input path to the dependencies returned by RuleBuilder.Inputs without modifying the
1070// command line.
Colin Cross69f59a32019-02-15 10:39:37 -08001071func (c *RuleBuilderCommand) Implicit(path Path) *RuleBuilderCommand {
Ramy Medhat2f99eec2020-06-13 17:38:27 -04001072 c.addImplicit(path)
Colin Crossfeec25b2019-01-30 17:32:39 -08001073 return c
1074}
1075
Colin Cross758290d2019-02-01 16:42:32 -08001076// Implicits adds the specified input paths to the dependencies returned by RuleBuilder.Inputs without modifying the
1077// command line.
Colin Cross69f59a32019-02-15 10:39:37 -08001078func (c *RuleBuilderCommand) Implicits(paths Paths) *RuleBuilderCommand {
Dan Willemsen633c5022019-04-12 11:11:38 -07001079 for _, path := range paths {
Ramy Medhat2f99eec2020-06-13 17:38:27 -04001080 c.addImplicit(path)
Dan Willemsen633c5022019-04-12 11:11:38 -07001081 }
Colin Crossfeec25b2019-01-30 17:32:39 -08001082 return c
1083}
1084
Ramy Medhat2f99eec2020-06-13 17:38:27 -04001085// GetImplicits returns the command's implicit inputs.
1086func (c *RuleBuilderCommand) GetImplicits() Paths {
1087 return c.implicits
1088}
1089
Colin Crossda71eda2020-02-21 16:55:19 -08001090// OrderOnly adds the specified input path to the dependencies returned by RuleBuilder.OrderOnlys
1091// without modifying the command line.
1092func (c *RuleBuilderCommand) OrderOnly(path Path) *RuleBuilderCommand {
1093 c.addOrderOnly(path)
1094 return c
1095}
1096
1097// OrderOnlys adds the specified input paths to the dependencies returned by RuleBuilder.OrderOnlys
1098// without modifying the command line.
1099func (c *RuleBuilderCommand) OrderOnlys(paths Paths) *RuleBuilderCommand {
1100 for _, path := range paths {
1101 c.addOrderOnly(path)
1102 }
1103 return c
1104}
1105
Colin Crossae89abe2021-04-21 11:45:23 -07001106// Validation adds the specified input path to the validation dependencies by
1107// RuleBuilder.Validations without modifying the command line.
1108func (c *RuleBuilderCommand) Validation(path Path) *RuleBuilderCommand {
Paul Duffin3866b892021-10-04 11:24:48 +01001109 checkPathNotNil(path)
Colin Crossae89abe2021-04-21 11:45:23 -07001110 c.validations = append(c.validations, path)
1111 return c
1112}
1113
1114// Validations adds the specified input paths to the validation dependencies by
1115// RuleBuilder.Validations without modifying the command line.
1116func (c *RuleBuilderCommand) Validations(paths Paths) *RuleBuilderCommand {
Paul Duffin3866b892021-10-04 11:24:48 +01001117 for _, path := range paths {
1118 c.Validation(path)
1119 }
Colin Crossae89abe2021-04-21 11:45:23 -07001120 return c
1121}
1122
Colin Cross758290d2019-02-01 16:42:32 -08001123// Output adds the specified output path to the command line. The path will also be added to the outputs returned by
1124// RuleBuilder.Outputs.
Colin Cross69f59a32019-02-15 10:39:37 -08001125func (c *RuleBuilderCommand) Output(path WritablePath) *RuleBuilderCommand {
Paul Duffin3866b892021-10-04 11:24:48 +01001126 checkPathNotNil(path)
Colin Crossfeec25b2019-01-30 17:32:39 -08001127 c.outputs = append(c.outputs, path)
Colin Crossf1a035e2020-11-16 17:32:30 -08001128 return c.Text(c.PathForOutput(path))
Colin Crossfeec25b2019-01-30 17:32:39 -08001129}
1130
Colin Cross758290d2019-02-01 16:42:32 -08001131// Outputs adds the specified output paths to the command line, separated by spaces. The paths will also be added to
1132// the outputs returned by RuleBuilder.Outputs.
Colin Cross69f59a32019-02-15 10:39:37 -08001133func (c *RuleBuilderCommand) Outputs(paths WritablePaths) *RuleBuilderCommand {
Colin Cross758290d2019-02-01 16:42:32 -08001134 for _, path := range paths {
1135 c.Output(path)
1136 }
1137 return c
1138}
1139
Dan Willemsen1945a4b2019-06-04 17:10:41 -07001140// OutputDir adds the output directory to the command line. This is only available when used with RuleBuilder.Sbox,
1141// and will be the temporary output directory managed by sbox, not the final one.
1142func (c *RuleBuilderCommand) OutputDir() *RuleBuilderCommand {
Colin Crossf1a035e2020-11-16 17:32:30 -08001143 if !c.rule.sbox {
Dan Willemsen1945a4b2019-06-04 17:10:41 -07001144 panic("OutputDir only valid with Sbox")
1145 }
Colin Cross3d680512020-11-13 16:23:53 -08001146 return c.Text(sboxOutDir)
Dan Willemsen1945a4b2019-06-04 17:10:41 -07001147}
1148
Colin Cross1d2cf042019-03-29 15:33:06 -07001149// DepFile adds the specified depfile path to the paths returned by RuleBuilder.DepFiles and adds it to the command
1150// line, and causes RuleBuilder.Build file to set the depfile flag for ninja. If multiple depfiles are added to
1151// commands in a single RuleBuilder then RuleBuilder.Build will add an extra command to merge the depfiles together.
1152func (c *RuleBuilderCommand) DepFile(path WritablePath) *RuleBuilderCommand {
Paul Duffin3866b892021-10-04 11:24:48 +01001153 checkPathNotNil(path)
Colin Cross1d2cf042019-03-29 15:33:06 -07001154 c.depFiles = append(c.depFiles, path)
Colin Crossf1a035e2020-11-16 17:32:30 -08001155 return c.Text(c.PathForOutput(path))
Colin Cross1d2cf042019-03-29 15:33:06 -07001156}
1157
Colin Cross758290d2019-02-01 16:42:32 -08001158// ImplicitOutput adds the specified output path to the dependencies returned by RuleBuilder.Outputs without modifying
1159// the command line.
Colin Cross69f59a32019-02-15 10:39:37 -08001160func (c *RuleBuilderCommand) ImplicitOutput(path WritablePath) *RuleBuilderCommand {
Colin Crossfeec25b2019-01-30 17:32:39 -08001161 c.outputs = append(c.outputs, path)
1162 return c
1163}
1164
Colin Cross758290d2019-02-01 16:42:32 -08001165// ImplicitOutputs adds the specified output paths to the dependencies returned by RuleBuilder.Outputs without modifying
1166// the command line.
Colin Cross69f59a32019-02-15 10:39:37 -08001167func (c *RuleBuilderCommand) ImplicitOutputs(paths WritablePaths) *RuleBuilderCommand {
Colin Cross758290d2019-02-01 16:42:32 -08001168 c.outputs = append(c.outputs, paths...)
1169 return c
1170}
1171
Jingwen Chence679d22020-09-23 04:30:02 +00001172// ImplicitSymlinkOutput declares the specified path as an implicit output that
1173// will be a symlink instead of a regular file. Does not modify the command
1174// line.
1175func (c *RuleBuilderCommand) ImplicitSymlinkOutput(path WritablePath) *RuleBuilderCommand {
Paul Duffin3866b892021-10-04 11:24:48 +01001176 checkPathNotNil(path)
Jingwen Chence679d22020-09-23 04:30:02 +00001177 c.symlinkOutputs = append(c.symlinkOutputs, path)
1178 return c.ImplicitOutput(path)
1179}
1180
1181// ImplicitSymlinkOutputs declares the specified paths as implicit outputs that
1182// will be a symlinks instead of regular files. Does not modify the command
1183// line.
1184func (c *RuleBuilderCommand) ImplicitSymlinkOutputs(paths WritablePaths) *RuleBuilderCommand {
1185 for _, path := range paths {
1186 c.ImplicitSymlinkOutput(path)
1187 }
1188 return c
1189}
1190
1191// SymlinkOutput declares the specified path as an output that will be a symlink
1192// instead of a regular file. Modifies the command line.
1193func (c *RuleBuilderCommand) SymlinkOutput(path WritablePath) *RuleBuilderCommand {
Paul Duffin3866b892021-10-04 11:24:48 +01001194 checkPathNotNil(path)
Jingwen Chence679d22020-09-23 04:30:02 +00001195 c.symlinkOutputs = append(c.symlinkOutputs, path)
1196 return c.Output(path)
1197}
1198
1199// SymlinkOutputsl declares the specified paths as outputs that will be symlinks
1200// instead of regular files. Modifies the command line.
1201func (c *RuleBuilderCommand) SymlinkOutputs(paths WritablePaths) *RuleBuilderCommand {
1202 for _, path := range paths {
1203 c.SymlinkOutput(path)
1204 }
1205 return c
1206}
1207
Colin Cross1d2cf042019-03-29 15:33:06 -07001208// ImplicitDepFile adds the specified depfile path to the paths returned by RuleBuilder.DepFiles without modifying
1209// the command line, and causes RuleBuilder.Build file to set the depfile flag for ninja. If multiple depfiles
1210// are added to commands in a single RuleBuilder then RuleBuilder.Build will add an extra command to merge the
1211// depfiles together.
1212func (c *RuleBuilderCommand) ImplicitDepFile(path WritablePath) *RuleBuilderCommand {
1213 c.depFiles = append(c.depFiles, path)
1214 return c
1215}
1216
Colin Cross758290d2019-02-01 16:42:32 -08001217// FlagWithInput adds the specified flag and input path to the command line, with no separator between them. The path
1218// will also be added to the dependencies returned by RuleBuilder.Inputs.
Colin Cross69f59a32019-02-15 10:39:37 -08001219func (c *RuleBuilderCommand) FlagWithInput(flag string, path Path) *RuleBuilderCommand {
Dan Willemsen633c5022019-04-12 11:11:38 -07001220 return c.Text(flag + c.addInput(path))
Colin Crossfeec25b2019-01-30 17:32:39 -08001221}
1222
Colin Cross758290d2019-02-01 16:42:32 -08001223// FlagWithInputList adds the specified flag and input paths to the command line, with the inputs joined by sep
1224// and no separator between the flag and inputs. The input paths will also be added to the dependencies returned by
1225// RuleBuilder.Inputs.
Colin Cross69f59a32019-02-15 10:39:37 -08001226func (c *RuleBuilderCommand) FlagWithInputList(flag string, paths Paths, sep string) *RuleBuilderCommand {
Dan Willemsen633c5022019-04-12 11:11:38 -07001227 strs := make([]string, len(paths))
1228 for i, path := range paths {
1229 strs[i] = c.addInput(path)
1230 }
1231 return c.FlagWithList(flag, strs, sep)
Colin Crossfeec25b2019-01-30 17:32:39 -08001232}
1233
Colin Cross758290d2019-02-01 16:42:32 -08001234// FlagForEachInput adds the specified flag joined with each input path to the command line. The input paths will also
1235// be added to the dependencies returned by RuleBuilder.Inputs. The result is identical to calling FlagWithInput for
1236// each input path.
Colin Cross69f59a32019-02-15 10:39:37 -08001237func (c *RuleBuilderCommand) FlagForEachInput(flag string, paths Paths) *RuleBuilderCommand {
Colin Cross758290d2019-02-01 16:42:32 -08001238 for _, path := range paths {
1239 c.FlagWithInput(flag, path)
1240 }
1241 return c
1242}
1243
1244// FlagWithOutput adds the specified flag and output path to the command line, with no separator between them. The path
1245// will also be added to the outputs returned by RuleBuilder.Outputs.
Colin Cross69f59a32019-02-15 10:39:37 -08001246func (c *RuleBuilderCommand) FlagWithOutput(flag string, path WritablePath) *RuleBuilderCommand {
Colin Crossfeec25b2019-01-30 17:32:39 -08001247 c.outputs = append(c.outputs, path)
Colin Crossf1a035e2020-11-16 17:32:30 -08001248 return c.Text(flag + c.PathForOutput(path))
Colin Crossfeec25b2019-01-30 17:32:39 -08001249}
1250
Colin Cross1d2cf042019-03-29 15:33:06 -07001251// FlagWithDepFile adds the specified flag and depfile path to the command line, with no separator between them. The path
1252// will also be added to the outputs returned by RuleBuilder.Outputs.
1253func (c *RuleBuilderCommand) FlagWithDepFile(flag string, path WritablePath) *RuleBuilderCommand {
1254 c.depFiles = append(c.depFiles, path)
Colin Crossf1a035e2020-11-16 17:32:30 -08001255 return c.Text(flag + c.PathForOutput(path))
Colin Cross1d2cf042019-03-29 15:33:06 -07001256}
1257
Colin Crossce3a51d2021-03-19 16:22:12 -07001258// FlagWithRspFileInputList adds the specified flag and path to an rspfile to the command line, with
1259// no separator between them. The paths will be written to the rspfile. If sbox is enabled, the
1260// rspfile must be outside the sbox directory. The first use of FlagWithRspFileInputList in any
1261// RuleBuilderCommand of a RuleBuilder will use Ninja's rsp file support for the rule, additional
1262// uses will result in an auxiliary rules to write the rspFile contents.
Colin Cross70c47412021-03-12 17:48:14 -08001263func (c *RuleBuilderCommand) FlagWithRspFileInputList(flag string, rspFile WritablePath, paths Paths) *RuleBuilderCommand {
Colin Cross0cb0d7b2019-07-11 10:59:15 -07001264 // Use an empty slice if paths is nil, the non-nil slice is used as an indicator that the rsp file must be
1265 // generated.
1266 if paths == nil {
1267 paths = Paths{}
1268 }
1269
Colin Crossce3a51d2021-03-19 16:22:12 -07001270 c.rspFiles = append(c.rspFiles, rspFileAndPaths{rspFile, paths})
Colin Cross0cb0d7b2019-07-11 10:59:15 -07001271
Colin Cross70c47412021-03-12 17:48:14 -08001272 if c.rule.sbox {
1273 if _, isRel, _ := maybeRelErr(c.rule.outDir.String(), rspFile.String()); isRel {
1274 panic(fmt.Errorf("FlagWithRspFileInputList rspfile %q must not be inside out dir %q",
1275 rspFile.String(), c.rule.outDir.String()))
1276 }
1277 }
1278
Colin Crossab020a72021-03-12 17:52:23 -08001279 c.FlagWithArg(flag, c.PathForInput(rspFile))
Colin Cross0cb0d7b2019-07-11 10:59:15 -07001280 return c
1281}
1282
Colin Cross758290d2019-02-01 16:42:32 -08001283// String returns the command line.
1284func (c *RuleBuilderCommand) String() string {
Colin Crosscfec40c2019-07-08 17:07:18 -07001285 return c.buf.String()
Colin Cross758290d2019-02-01 16:42:32 -08001286}
Colin Cross1d2cf042019-03-29 15:33:06 -07001287
Colin Crosse16ce362020-11-12 08:29:30 -08001288// RuleBuilderSboxProtoForTests takes the BuildParams for the manifest passed to RuleBuilder.Sbox()
1289// and returns sbox testproto generated by the RuleBuilder.
1290func RuleBuilderSboxProtoForTests(t *testing.T, params TestingBuildParams) *sbox_proto.Manifest {
1291 t.Helper()
1292 content := ContentFromFileRuleForTests(t, params)
1293 manifest := sbox_proto.Manifest{}
Dan Willemsen4591b642021-05-24 14:24:12 -07001294 err := prototext.Unmarshal([]byte(content), &manifest)
Colin Crosse16ce362020-11-12 08:29:30 -08001295 if err != nil {
1296 t.Fatalf("failed to unmarshal manifest: %s", err.Error())
1297 }
1298 return &manifest
1299}
1300
Colin Cross1d2cf042019-03-29 15:33:06 -07001301func ninjaNameEscape(s string) string {
1302 b := []byte(s)
1303 escaped := false
1304 for i, c := range b {
1305 valid := (c >= 'a' && c <= 'z') ||
1306 (c >= 'A' && c <= 'Z') ||
1307 (c >= '0' && c <= '9') ||
1308 (c == '_') ||
1309 (c == '-') ||
1310 (c == '.')
1311 if !valid {
1312 b[i] = '_'
1313 escaped = true
1314 }
1315 }
1316 if escaped {
1317 s = string(b)
1318 }
1319 return s
1320}
Colin Cross3d680512020-11-13 16:23:53 -08001321
1322// hashSrcFiles returns a hash of the list of source files. It is used to ensure the command line
1323// or the sbox textproto manifest change even if the input files are not listed on the command line.
1324func hashSrcFiles(srcFiles Paths) string {
1325 h := sha256.New()
1326 srcFileList := strings.Join(srcFiles.Strings(), "\n")
1327 h.Write([]byte(srcFileList))
1328 return fmt.Sprintf("%x", h.Sum(nil))
1329}
Colin Crossf1a035e2020-11-16 17:32:30 -08001330
1331// BuilderContextForTesting returns a BuilderContext for the given config that can be used for tests
1332// that need to call methods that take a BuilderContext.
1333func BuilderContextForTesting(config Config) BuilderContext {
1334 pathCtx := PathContextForTesting(config)
1335 return builderContextForTests{
1336 PathContext: pathCtx,
1337 }
1338}
1339
1340type builderContextForTests struct {
1341 PathContext
1342}
1343
1344func (builderContextForTests) Rule(PackageContext, string, blueprint.RuleParams, ...string) blueprint.Rule {
1345 return nil
1346}
1347func (builderContextForTests) Build(PackageContext, BuildParams) {}
Colin Crossef972742021-03-12 17:24:45 -08001348
Colin Crosse55bd422021-03-23 13:44:30 -07001349func writeRspFileRule(ctx BuilderContext, rspFile WritablePath, paths Paths) {
1350 buf := &strings.Builder{}
1351 err := response.WriteRspFile(buf, paths.Strings())
1352 if err != nil {
1353 // There should never be I/O errors writing to a bytes.Buffer.
1354 panic(err)
Colin Crossef972742021-03-12 17:24:45 -08001355 }
Colin Crosse55bd422021-03-23 13:44:30 -07001356 WriteFileRule(ctx, rspFile, buf.String())
Colin Crossef972742021-03-12 17:24:45 -08001357}