blob: e50596422b88753d5543dd3aea58bce074e344cc [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
Spandan Dasaf4ccaa2023-06-29 01:15:51 +000056 sboxOutSubDir string
Colin Crossba9e4032020-11-24 16:32:22 -080057 sboxTools bool
Colin Crossab020a72021-03-12 17:52:23 -080058 sboxInputs bool
Colin Crosse16ce362020-11-12 08:29:30 -080059 sboxManifestPath WritablePath
60 missingDeps []string
Colin Crossfeec25b2019-01-30 17:32:39 -080061}
62
Colin Cross758290d2019-02-01 16:42:32 -080063// NewRuleBuilder returns a newly created RuleBuilder.
Colin Crossf1a035e2020-11-16 17:32:30 -080064func NewRuleBuilder(pctx PackageContext, ctx BuilderContext) *RuleBuilder {
Colin Cross5cb5b092019-02-02 21:25:18 -080065 return &RuleBuilder{
Colin Crossf1a035e2020-11-16 17:32:30 -080066 pctx: pctx,
67 ctx: ctx,
Colin Cross69f59a32019-02-15 10:39:37 -080068 temporariesSet: make(map[WritablePath]bool),
Spandan Dasaf4ccaa2023-06-29 01:15:51 +000069 sboxOutSubDir: sboxOutSubDir,
Colin Cross5cb5b092019-02-02 21:25:18 -080070 }
Colin Cross758290d2019-02-01 16:42:32 -080071}
72
Spandan Dasaf4ccaa2023-06-29 01:15:51 +000073// SetSboxOutDirDirAsEmpty sets the out subdirectory to an empty string
74// This is useful for sandboxing actions that change the execution root to a path in out/ (e.g mixed builds)
75// For such actions, SetSboxOutDirDirAsEmpty ensures that the path does not become $SBOX_SANDBOX_DIR/out/out/bazel/output/execroot/__main__/...
76func (rb *RuleBuilder) SetSboxOutDirDirAsEmpty() *RuleBuilder {
77 rb.sboxOutSubDir = ""
78 return rb
79}
80
Colin Cross758290d2019-02-01 16:42:32 -080081// RuleBuilderInstall is a tuple of install from and to locations.
82type RuleBuilderInstall struct {
Colin Cross69f59a32019-02-15 10:39:37 -080083 From Path
84 To string
Colin Cross758290d2019-02-01 16:42:32 -080085}
86
Colin Crossdeabb942019-02-11 14:11:09 -080087type RuleBuilderInstalls []RuleBuilderInstall
88
89// String returns the RuleBuilderInstalls in the form used by $(call copy-many-files) in Make, a space separated
90// list of from:to tuples.
91func (installs RuleBuilderInstalls) String() string {
92 sb := strings.Builder{}
93 for i, install := range installs {
94 if i != 0 {
95 sb.WriteRune(' ')
96 }
Colin Cross69f59a32019-02-15 10:39:37 -080097 sb.WriteString(install.From.String())
Colin Crossdeabb942019-02-11 14:11:09 -080098 sb.WriteRune(':')
99 sb.WriteString(install.To)
100 }
101 return sb.String()
102}
103
Colin Cross0d2f40a2019-02-05 22:31:15 -0800104// MissingDeps adds modules to the list of missing dependencies. If MissingDeps
105// is called with a non-empty input, any call to Build will result in a rule
106// that will print an error listing the missing dependencies and fail.
107// MissingDeps should only be called if Config.AllowMissingDependencies() is
108// true.
109func (r *RuleBuilder) MissingDeps(missingDeps []string) {
110 r.missingDeps = append(r.missingDeps, missingDeps...)
111}
112
Colin Cross758290d2019-02-01 16:42:32 -0800113// 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 -0800114func (r *RuleBuilder) Restat() *RuleBuilder {
115 r.restat = true
116 return r
117}
118
Colin Cross8b8bec32019-11-15 13:18:43 -0800119// HighMem marks the rule as a high memory rule, which will limit how many run in parallel with other high memory
120// rules.
121func (r *RuleBuilder) HighMem() *RuleBuilder {
122 r.highmem = true
123 return r
124}
125
126// Remoteable marks the rule as supporting remote execution.
127func (r *RuleBuilder) Remoteable(supports RemoteRuleSupports) *RuleBuilder {
128 r.remoteable = supports
129 return r
130}
131
Colin Crossef972742021-03-12 17:24:45 -0800132// Rewrapper marks the rule as running inside rewrapper using the given params in order to support
133// running on RBE. During RuleBuilder.Build the params will be combined with the inputs, outputs
134// and tools known to RuleBuilder to prepend an appropriate rewrapper command line to the rule's
135// command line.
136func (r *RuleBuilder) Rewrapper(params *remoteexec.REParams) *RuleBuilder {
137 if !r.sboxInputs {
138 panic(fmt.Errorf("RuleBuilder.Rewrapper must be called after RuleBuilder.SandboxInputs"))
139 }
140 r.rbeParams = params
141 return r
142}
143
Colin Crosse16ce362020-11-12 08:29:30 -0800144// Sbox marks the rule as needing to be wrapped by sbox. The outputDir should point to the output
145// directory that sbox will wipe. It should not be written to by any other rule. manifestPath should
146// point to a location where sbox's manifest will be written and must be outside outputDir. sbox
147// will ensure that all outputs have been written, and will discard any output files that were not
148// specified.
Colin Crosse16ce362020-11-12 08:29:30 -0800149func (r *RuleBuilder) Sbox(outputDir WritablePath, manifestPath WritablePath) *RuleBuilder {
Dan Willemsen633c5022019-04-12 11:11:38 -0700150 if r.sbox {
151 panic("Sbox() may not be called more than once")
152 }
153 if len(r.commands) > 0 {
154 panic("Sbox() may not be called after Command()")
155 }
Dan Willemsen633c5022019-04-12 11:11:38 -0700156 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
Dan Willemsen633c5022019-04-12 11:11:38 -0700339func (r *RuleBuilder) depFileSet() map[string]WritablePath {
340 depFiles := make(map[string]WritablePath)
341 for _, c := range r.commands {
342 for _, depFile := range c.depFiles {
343 depFiles[depFile.String()] = depFile
344 }
345 }
346 return depFiles
347}
348
Colin Cross1d2cf042019-03-29 15:33:06 -0700349// DepFiles returns the list of paths that were passed to the RuleBuilderCommand methods that take depfile paths, such
350// as RuleBuilderCommand.DepFile or RuleBuilderCommand.FlagWithDepFile.
351func (r *RuleBuilder) DepFiles() WritablePaths {
352 var depFiles WritablePaths
353
354 for _, c := range r.commands {
355 for _, depFile := range c.depFiles {
356 depFiles = append(depFiles, depFile)
357 }
358 }
359
360 return depFiles
361}
362
Colin Cross758290d2019-02-01 16:42:32 -0800363// Installs returns the list of tuples passed to Install.
Colin Crossdeabb942019-02-11 14:11:09 -0800364func (r *RuleBuilder) Installs() RuleBuilderInstalls {
365 return append(RuleBuilderInstalls(nil), r.installs...)
Colin Crossfeec25b2019-01-30 17:32:39 -0800366}
367
Colin Cross69f59a32019-02-15 10:39:37 -0800368func (r *RuleBuilder) toolsSet() map[string]Path {
369 tools := make(map[string]Path)
Colin Cross5cb5b092019-02-02 21:25:18 -0800370 for _, c := range r.commands {
371 for _, tool := range c.tools {
Colin Cross69f59a32019-02-15 10:39:37 -0800372 tools[tool.String()] = tool
Colin Cross5cb5b092019-02-02 21:25:18 -0800373 }
374 }
375
376 return tools
377}
378
Colin Crossda71eda2020-02-21 16:55:19 -0800379// Tools returns the list of paths that were passed to the RuleBuilderCommand.Tool method. The
380// list is sorted and duplicates removed.
Colin Cross69f59a32019-02-15 10:39:37 -0800381func (r *RuleBuilder) Tools() Paths {
Colin Cross5cb5b092019-02-02 21:25:18 -0800382 toolsSet := r.toolsSet()
383
Colin Cross69f59a32019-02-15 10:39:37 -0800384 var toolsList Paths
385 for _, tool := range toolsSet {
Colin Cross5cb5b092019-02-02 21:25:18 -0800386 toolsList = append(toolsList, tool)
Colin Crossfeec25b2019-01-30 17:32:39 -0800387 }
Colin Cross69f59a32019-02-15 10:39:37 -0800388
389 sort.Slice(toolsList, func(i, j int) bool {
390 return toolsList[i].String() < toolsList[j].String()
391 })
392
Colin Cross5cb5b092019-02-02 21:25:18 -0800393 return toolsList
Colin Crossfeec25b2019-01-30 17:32:39 -0800394}
395
Colin Cross0cb0d7b2019-07-11 10:59:15 -0700396// RspFileInputs returns the list of paths that were passed to the RuleBuilderCommand.FlagWithRspFileInputList method.
397func (r *RuleBuilder) RspFileInputs() Paths {
398 var rspFileInputs Paths
399 for _, c := range r.commands {
Colin Crossce3a51d2021-03-19 16:22:12 -0700400 for _, rspFile := range c.rspFiles {
401 rspFileInputs = append(rspFileInputs, rspFile.paths...)
Colin Cross0cb0d7b2019-07-11 10:59:15 -0700402 }
403 }
404
405 return rspFileInputs
406}
407
Colin Crossce3a51d2021-03-19 16:22:12 -0700408func (r *RuleBuilder) rspFiles() []rspFileAndPaths {
409 var rspFiles []rspFileAndPaths
Colin Cross70c47412021-03-12 17:48:14 -0800410 for _, c := range r.commands {
Colin Crossce3a51d2021-03-19 16:22:12 -0700411 rspFiles = append(rspFiles, c.rspFiles...)
Colin Cross70c47412021-03-12 17:48:14 -0800412 }
413
Colin Crossce3a51d2021-03-19 16:22:12 -0700414 return rspFiles
Colin Cross70c47412021-03-12 17:48:14 -0800415}
416
Colin Cross0cb0d7b2019-07-11 10:59:15 -0700417// Commands returns a slice containing the built command line for each call to RuleBuilder.Command.
Colin Crossfeec25b2019-01-30 17:32:39 -0800418func (r *RuleBuilder) Commands() []string {
419 var commands []string
420 for _, c := range r.commands {
Colin Cross0cb0d7b2019-07-11 10:59:15 -0700421 commands = append(commands, c.String())
422 }
423 return commands
424}
425
Colin Cross758290d2019-02-01 16:42:32 -0800426// BuilderContext is a subset of ModuleContext and SingletonContext.
Colin Cross786cd6d2019-02-01 16:41:11 -0800427type BuilderContext interface {
428 PathContext
429 Rule(PackageContext, string, blueprint.RuleParams, ...string) blueprint.Rule
430 Build(PackageContext, BuildParams)
431}
432
Colin Cross758290d2019-02-01 16:42:32 -0800433var _ BuilderContext = ModuleContext(nil)
434var _ BuilderContext = SingletonContext(nil)
435
Colin Crossf1a035e2020-11-16 17:32:30 -0800436func (r *RuleBuilder) depFileMergerCmd(depFiles WritablePaths) *RuleBuilderCommand {
Dan Willemsen633c5022019-04-12 11:11:38 -0700437 return r.Command().
Colin Cross9b698b62021-12-22 09:55:32 -0800438 builtToolWithoutDeps("dep_fixer").
Dan Willemsen633c5022019-04-12 11:11:38 -0700439 Inputs(depFiles.Paths())
Colin Cross1d2cf042019-03-29 15:33:06 -0700440}
441
Sam Delmerico285b66a2023-09-25 12:13:17 +0000442// BuildWithNinjaVars adds the built command line to the build graph, with dependencies on Inputs and Tools, and output files for
443// Outputs. This function will not escape Ninja variables, so it may be used to write sandbox manifests using Ninja variables.
444func (r *RuleBuilder) BuildWithUnescapedNinjaVars(name string, desc string) {
445 r.build(name, desc, false)
446}
447
Colin Cross758290d2019-02-01 16:42:32 -0800448// Build adds the built command line to the build graph, with dependencies on Inputs and Tools, and output files for
449// Outputs.
Colin Crossf1a035e2020-11-16 17:32:30 -0800450func (r *RuleBuilder) Build(name string, desc string) {
Sam Delmerico285b66a2023-09-25 12:13:17 +0000451 r.build(name, desc, true)
452}
453
454func (r *RuleBuilder) build(name string, desc string, ninjaEscapeCommandString bool) {
Colin Cross1d2cf042019-03-29 15:33:06 -0700455 name = ninjaNameEscape(name)
456
Colin Cross0d2f40a2019-02-05 22:31:15 -0800457 if len(r.missingDeps) > 0 {
Sam Delmerico285b66a2023-09-25 12:13:17 +0000458 r.ctx.Build(r.pctx, BuildParams{
Colin Cross0d2f40a2019-02-05 22:31:15 -0800459 Rule: ErrorRule,
Colin Cross69f59a32019-02-15 10:39:37 -0800460 Outputs: r.Outputs(),
Colin Cross0d2f40a2019-02-05 22:31:15 -0800461 Description: desc,
462 Args: map[string]string{
463 "error": "missing dependencies: " + strings.Join(r.missingDeps, ", "),
464 },
465 })
466 return
467 }
468
Colin Cross1d2cf042019-03-29 15:33:06 -0700469 var depFile WritablePath
470 var depFormat blueprint.Deps
471 if depFiles := r.DepFiles(); len(depFiles) > 0 {
472 depFile = depFiles[0]
473 depFormat = blueprint.DepsGCC
474 if len(depFiles) > 1 {
475 // Add a command locally that merges all depfiles together into the first depfile.
Colin Crossf1a035e2020-11-16 17:32:30 -0800476 r.depFileMergerCmd(depFiles)
Dan Willemsen633c5022019-04-12 11:11:38 -0700477
478 if r.sbox {
Colin Crosse16ce362020-11-12 08:29:30 -0800479 // Check for Rel() errors, as all depfiles should be in the output dir. Errors
480 // will be reported to the ctx.
Dan Willemsen633c5022019-04-12 11:11:38 -0700481 for _, path := range depFiles[1:] {
Colin Crossf1a035e2020-11-16 17:32:30 -0800482 Rel(r.ctx, r.outDir.String(), path.String())
Dan Willemsen633c5022019-04-12 11:11:38 -0700483 }
484 }
Colin Cross1d2cf042019-03-29 15:33:06 -0700485 }
486 }
487
Dan Willemsen633c5022019-04-12 11:11:38 -0700488 tools := r.Tools()
Colin Crossb70a1a92021-03-12 17:51:32 -0800489 commands := r.Commands()
Dan Willemsen633c5022019-04-12 11:11:38 -0700490 outputs := r.Outputs()
Colin Cross3d680512020-11-13 16:23:53 -0800491 inputs := r.Inputs()
Colin Crossce3a51d2021-03-19 16:22:12 -0700492 rspFiles := r.rspFiles()
Dan Willemsen633c5022019-04-12 11:11:38 -0700493
494 if len(commands) == 0 {
495 return
496 }
497 if len(outputs) == 0 {
498 panic("No outputs specified from any Commands")
499 }
500
Colin Cross0cb0d7b2019-07-11 10:59:15 -0700501 commandString := strings.Join(commands, " && ")
Dan Willemsen633c5022019-04-12 11:11:38 -0700502
503 if r.sbox {
Colin Crosse16ce362020-11-12 08:29:30 -0800504 // If running the command inside sbox, write the rule data out to an sbox
505 // manifest.textproto.
506 manifest := sbox_proto.Manifest{}
507 command := sbox_proto.Command{}
508 manifest.Commands = append(manifest.Commands, &command)
509 command.Command = proto.String(commandString)
Colin Cross151b9ff2020-11-12 08:29:30 -0800510
Colin Cross619b9ab2020-11-20 18:44:31 +0000511 if depFile != nil {
Colin Crosse16ce362020-11-12 08:29:30 -0800512 manifest.OutputDepfile = proto.String(depFile.String())
Colin Cross619b9ab2020-11-20 18:44:31 +0000513 }
514
Colin Crossba9e4032020-11-24 16:32:22 -0800515 // If sandboxing tools is enabled, add copy rules to the manifest to copy each tool
516 // into the sbox directory.
517 if r.sboxTools {
518 for _, tool := range tools {
519 command.CopyBefore = append(command.CopyBefore, &sbox_proto.Copy{
520 From: proto.String(tool.String()),
521 To: proto.String(sboxPathForToolRel(r.ctx, tool)),
522 })
523 }
524 for _, c := range r.commands {
525 for _, tool := range c.packagedTools {
526 command.CopyBefore = append(command.CopyBefore, &sbox_proto.Copy{
527 From: proto.String(tool.srcPath.String()),
528 To: proto.String(sboxPathForPackagedToolRel(tool)),
529 Executable: proto.Bool(tool.executable),
530 })
531 tools = append(tools, tool.srcPath)
532 }
533 }
534 }
535
Colin Crossab020a72021-03-12 17:52:23 -0800536 // If sandboxing inputs is enabled, add copy rules to the manifest to copy each input
537 // into the sbox directory.
538 if r.sboxInputs {
539 for _, input := range inputs {
540 command.CopyBefore = append(command.CopyBefore, &sbox_proto.Copy{
541 From: proto.String(input.String()),
542 To: proto.String(r.sboxPathForInputRel(input)),
543 })
544 }
545
Colin Crossce3a51d2021-03-19 16:22:12 -0700546 // If using rsp files copy them and their contents into the sbox directory with
547 // the appropriate path mappings.
548 for _, rspFile := range rspFiles {
Colin Crosse55bd422021-03-23 13:44:30 -0700549 command.RspFiles = append(command.RspFiles, &sbox_proto.RspFile{
Colin Crossce3a51d2021-03-19 16:22:12 -0700550 File: proto.String(rspFile.file.String()),
Colin Crosse55bd422021-03-23 13:44:30 -0700551 // These have to match the logic in sboxPathForInputRel
552 PathMappings: []*sbox_proto.PathMapping{
553 {
554 From: proto.String(r.outDir.String()),
555 To: proto.String(sboxOutSubDir),
556 },
557 {
Cole Fauste8561c62023-11-30 17:26:37 -0800558 From: proto.String(r.ctx.Config().OutDir()),
Colin Crosse55bd422021-03-23 13:44:30 -0700559 To: proto.String(sboxOutSubDir),
560 },
561 },
Colin Crossab020a72021-03-12 17:52:23 -0800562 })
563 }
564
565 command.Chdir = proto.Bool(true)
566 }
567
Colin Crosse16ce362020-11-12 08:29:30 -0800568 // Add copy rules to the manifest to copy each output file from the sbox directory.
Colin Crossba9e4032020-11-24 16:32:22 -0800569 // to the output directory after running the commands.
Spandan Das33e30972023-07-13 21:19:12 +0000570 for _, output := range outputs {
Colin Crossf1a035e2020-11-16 17:32:30 -0800571 rel := Rel(r.ctx, r.outDir.String(), output.String())
Colin Crosse16ce362020-11-12 08:29:30 -0800572 command.CopyAfter = append(command.CopyAfter, &sbox_proto.Copy{
Spandan Dasaf4ccaa2023-06-29 01:15:51 +0000573 From: proto.String(filepath.Join(r.sboxOutSubDir, rel)),
Colin Crosse16ce362020-11-12 08:29:30 -0800574 To: proto.String(output.String()),
575 })
576 }
Colin Cross619b9ab2020-11-20 18:44:31 +0000577
Colin Cross5334edd2021-03-11 17:18:21 -0800578 // Outputs that were marked Temporary will not be checked that they are in the output
579 // directory by the loop above, check them here.
580 for path := range r.temporariesSet {
581 Rel(r.ctx, r.outDir.String(), path.String())
582 }
583
Colin Crosse16ce362020-11-12 08:29:30 -0800584 // Add a hash of the list of input files to the manifest so that the textproto file
585 // changes when the list of input files changes and causes the sbox rule that
586 // depends on it to rerun.
587 command.InputHash = proto.String(hashSrcFiles(inputs))
Colin Cross619b9ab2020-11-20 18:44:31 +0000588
Colin Crosse16ce362020-11-12 08:29:30 -0800589 // Verify that the manifest textproto is not inside the sbox output directory, otherwise
590 // it will get deleted when the sbox rule clears its output directory.
Colin Crossf1a035e2020-11-16 17:32:30 -0800591 _, manifestInOutDir := MaybeRel(r.ctx, r.outDir.String(), r.sboxManifestPath.String())
Colin Crosse16ce362020-11-12 08:29:30 -0800592 if manifestInOutDir {
Colin Crossf1a035e2020-11-16 17:32:30 -0800593 ReportPathErrorf(r.ctx, "sbox rule %q manifestPath %q must not be in outputDir %q",
594 name, r.sboxManifestPath.String(), r.outDir.String())
Colin Crosse16ce362020-11-12 08:29:30 -0800595 }
596
Sam Delmerico285b66a2023-09-25 12:13:17 +0000597 // Create a rule to write the manifest as textproto.
Dan Willemsen4591b642021-05-24 14:24:12 -0700598 pbText, err := prototext.Marshal(&manifest)
599 if err != nil {
600 ReportPathErrorf(r.ctx, "sbox manifest failed to marshal: %q", err)
601 }
Sam Delmerico285b66a2023-09-25 12:13:17 +0000602 if ninjaEscapeCommandString {
603 WriteFileRule(r.ctx, r.sboxManifestPath, string(pbText))
604 } else {
605 // We need to have a rule to write files that is
606 // defined on the RuleBuilder's pctx in order to
607 // write Ninja variables in the string.
608 // The WriteFileRule function above rule can only write
609 // raw strings because it is defined on the android
610 // package's pctx, and it can't access variables defined
611 // in another context.
612 r.ctx.Build(r.pctx, BuildParams{
613 Rule: r.ctx.Rule(r.pctx, "unescapedWriteFile", blueprint.RuleParams{
614 Command: `rm -rf ${out} && cat ${out}.rsp > ${out}`,
615 Rspfile: "${out}.rsp",
616 RspfileContent: "${content}",
617 Description: "write file",
618 }, "content"),
619 Output: r.sboxManifestPath,
620 Description: "write sbox manifest " + r.sboxManifestPath.Base(),
621 Args: map[string]string{
622 "content": string(pbText),
623 },
624 })
625 }
Colin Crosse16ce362020-11-12 08:29:30 -0800626
627 // Generate a new string to use as the command line of the sbox rule. This uses
628 // a RuleBuilderCommand as a convenience method of building the command line, then
629 // converts it to a string to replace commandString.
Colin Crossf1a035e2020-11-16 17:32:30 -0800630 sboxCmd := &RuleBuilderCommand{
631 rule: &RuleBuilder{
632 ctx: r.ctx,
633 },
634 }
Colin Cross9b698b62021-12-22 09:55:32 -0800635 sboxCmd.builtToolWithoutDeps("sbox").
Colin Crosse52c2ac2022-03-28 17:03:35 -0700636 FlagWithArg("--sandbox-path ", shared.TempDirForOutDir(PathForOutput(r.ctx).String())).
637 FlagWithArg("--output-dir ", r.outDir.String()).
638 FlagWithInput("--manifest ", r.sboxManifestPath)
639
640 if r.restat {
641 sboxCmd.Flag("--write-if-changed")
642 }
Colin Crosse16ce362020-11-12 08:29:30 -0800643
644 // Replace the command string, and add the sbox tool and manifest textproto to the
645 // dependencies of the final sbox rule.
Colin Crosscfec40c2019-07-08 17:07:18 -0700646 commandString = sboxCmd.buf.String()
Dan Willemsen633c5022019-04-12 11:11:38 -0700647 tools = append(tools, sboxCmd.tools...)
Colin Crosse16ce362020-11-12 08:29:30 -0800648 inputs = append(inputs, sboxCmd.inputs...)
Colin Crossef972742021-03-12 17:24:45 -0800649
650 if r.rbeParams != nil {
Colin Crosse55bd422021-03-23 13:44:30 -0700651 // RBE needs a list of input files to copy to the remote builder. For inputs already
652 // listed in an rsp file, pass the rsp file directly to rewrapper. For the rest,
653 // create a new rsp file to pass to rewrapper.
654 var remoteRspFiles Paths
655 var remoteInputs Paths
656
657 remoteInputs = append(remoteInputs, inputs...)
658 remoteInputs = append(remoteInputs, tools...)
659
Colin Crossce3a51d2021-03-19 16:22:12 -0700660 for _, rspFile := range rspFiles {
661 remoteInputs = append(remoteInputs, rspFile.file)
662 remoteRspFiles = append(remoteRspFiles, rspFile.file)
Colin Crossef972742021-03-12 17:24:45 -0800663 }
Colin Crosse55bd422021-03-23 13:44:30 -0700664
665 if len(remoteInputs) > 0 {
666 inputsListFile := r.sboxManifestPath.ReplaceExtension(r.ctx, "rbe_inputs.list")
667 writeRspFileRule(r.ctx, inputsListFile, remoteInputs)
668 remoteRspFiles = append(remoteRspFiles, inputsListFile)
669 // Add the new rsp file as an extra input to the rule.
670 inputs = append(inputs, inputsListFile)
671 }
Colin Crossef972742021-03-12 17:24:45 -0800672
673 r.rbeParams.OutputFiles = outputs.Strings()
Colin Crosse55bd422021-03-23 13:44:30 -0700674 r.rbeParams.RSPFiles = remoteRspFiles.Strings()
Colin Crossef972742021-03-12 17:24:45 -0800675 rewrapperCommand := r.rbeParams.NoVarTemplate(r.ctx.Config().RBEWrapper())
676 commandString = rewrapperCommand + " bash -c '" + strings.ReplaceAll(commandString, `'`, `'\''`) + "'"
677 }
Colin Cross3d680512020-11-13 16:23:53 -0800678 } else {
679 // If not using sbox the rule will run the command directly, put the hash of the
680 // list of input files in a comment at the end of the command line to ensure ninja
681 // reruns the rule when the list of input files changes.
682 commandString += " # hash of input list: " + hashSrcFiles(inputs)
Dan Willemsen633c5022019-04-12 11:11:38 -0700683 }
684
Colin Cross1d2cf042019-03-29 15:33:06 -0700685 // Ninja doesn't like multiple outputs when depfiles are enabled, move all but the first output to
Colin Cross70c47412021-03-12 17:48:14 -0800686 // ImplicitOutputs. RuleBuilder doesn't use "$out", so the distinction between Outputs and
Colin Cross0cb0d7b2019-07-11 10:59:15 -0700687 // ImplicitOutputs doesn't matter.
Dan Willemsen633c5022019-04-12 11:11:38 -0700688 output := outputs[0]
689 implicitOutputs := outputs[1:]
Colin Cross1d2cf042019-03-29 15:33:06 -0700690
Colin Cross0cb0d7b2019-07-11 10:59:15 -0700691 var rspFile, rspFileContent string
Colin Crossce3a51d2021-03-19 16:22:12 -0700692 var rspFileInputs Paths
693 if len(rspFiles) > 0 {
694 // The first rsp files uses Ninja's rsp file support for the rule
695 rspFile = rspFiles[0].file.String()
Colin Crosse55bd422021-03-23 13:44:30 -0700696 // Use "$in" for rspFileContent to avoid duplicating the list of files in the dependency
697 // list and in the contents of the rsp file. Inputs to the rule that are not in the
698 // rsp file will be listed in Implicits instead of Inputs so they don't show up in "$in".
699 rspFileContent = "$in"
Colin Crossce3a51d2021-03-19 16:22:12 -0700700 rspFileInputs = append(rspFileInputs, rspFiles[0].paths...)
701
702 for _, rspFile := range rspFiles[1:] {
703 // Any additional rsp files need an extra rule to write the file.
704 writeRspFileRule(r.ctx, rspFile.file, rspFile.paths)
705 // The main rule needs to depend on the inputs listed in the extra rsp file.
706 inputs = append(inputs, rspFile.paths...)
707 // The main rule needs to depend on the extra rsp file.
708 inputs = append(inputs, rspFile.file)
709 }
Colin Cross0cb0d7b2019-07-11 10:59:15 -0700710 }
711
Colin Cross8b8bec32019-11-15 13:18:43 -0800712 var pool blueprint.Pool
Colin Crossf1a035e2020-11-16 17:32:30 -0800713 if r.ctx.Config().UseGoma() && r.remoteable.Goma {
Colin Cross8b8bec32019-11-15 13:18:43 -0800714 // 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 -0800715 } else if r.ctx.Config().UseRBE() && r.remoteable.RBE {
Ramy Medhat944839a2020-03-31 22:14:52 -0400716 // When USE_RBE=true is set and the rule is supported by RBE, use the remotePool.
717 pool = remotePool
Colin Cross8b8bec32019-11-15 13:18:43 -0800718 } else if r.highmem {
719 pool = highmemPool
Colin Crossf1a035e2020-11-16 17:32:30 -0800720 } else if r.ctx.Config().UseRemoteBuild() {
Colin Cross8b8bec32019-11-15 13:18:43 -0800721 pool = localPool
722 }
723
Sam Delmericod46f6c82023-09-25 12:13:17 +0000724 if ninjaEscapeCommandString {
725 commandString = proptools.NinjaEscape(commandString)
726 }
727
Colin Crossf1a035e2020-11-16 17:32:30 -0800728 r.ctx.Build(r.pctx, BuildParams{
Sam Delmerico285b66a2023-09-25 12:13:17 +0000729 Rule: r.ctx.Rule(r.pctx, name, blueprint.RuleParams{
Sam Delmericod46f6c82023-09-25 12:13:17 +0000730 Command: commandString,
Colin Cross45029782021-03-16 16:49:52 -0700731 CommandDeps: proptools.NinjaEscapeList(tools.Strings()),
Colin Cross0cb0d7b2019-07-11 10:59:15 -0700732 Restat: r.restat,
Colin Cross45029782021-03-16 16:49:52 -0700733 Rspfile: proptools.NinjaEscape(rspFile),
Colin Cross0cb0d7b2019-07-11 10:59:15 -0700734 RspfileContent: rspFileContent,
Colin Cross8b8bec32019-11-15 13:18:43 -0800735 Pool: pool,
Dan Willemsen633c5022019-04-12 11:11:38 -0700736 }),
Colin Cross0cb0d7b2019-07-11 10:59:15 -0700737 Inputs: rspFileInputs,
Colin Cross3d680512020-11-13 16:23:53 -0800738 Implicits: inputs,
Colin Crossda6401b2021-04-21 11:32:19 -0700739 OrderOnly: r.OrderOnlys(),
Colin Crossae89abe2021-04-21 11:45:23 -0700740 Validations: r.Validations(),
Dan Willemsen633c5022019-04-12 11:11:38 -0700741 Output: output,
742 ImplicitOutputs: implicitOutputs,
743 Depfile: depFile,
744 Deps: depFormat,
745 Description: desc,
746 })
Colin Crossfeec25b2019-01-30 17:32:39 -0800747}
748
Colin Cross758290d2019-02-01 16:42:32 -0800749// RuleBuilderCommand is a builder for a command in a command line. It can be mutated by its methods to add to the
750// command and track dependencies. The methods mutate the RuleBuilderCommand in place, as well as return the
751// RuleBuilderCommand, so they can be used chained or unchained. All methods that add text implicitly add a single
752// space as a separator from the previous method.
Colin Crossfeec25b2019-01-30 17:32:39 -0800753type RuleBuilderCommand struct {
Colin Crossf1a035e2020-11-16 17:32:30 -0800754 rule *RuleBuilder
755
Cole Faust9a346f62024-01-18 20:12:02 +0000756 buf strings.Builder
757 inputs Paths
758 implicits Paths
759 orderOnlys Paths
760 validations Paths
761 outputs WritablePaths
762 depFiles WritablePaths
763 tools Paths
764 packagedTools []PackagingSpec
765 rspFiles []rspFileAndPaths
Colin Crossce3a51d2021-03-19 16:22:12 -0700766}
767
768type rspFileAndPaths struct {
769 file WritablePath
770 paths Paths
Dan Willemsen633c5022019-04-12 11:11:38 -0700771}
772
Paul Duffin3866b892021-10-04 11:24:48 +0100773func checkPathNotNil(path Path) {
774 if path == nil {
775 panic("rule_builder paths cannot be nil")
776 }
777}
778
Dan Willemsen633c5022019-04-12 11:11:38 -0700779func (c *RuleBuilderCommand) addInput(path Path) string {
Paul Duffin3866b892021-10-04 11:24:48 +0100780 checkPathNotNil(path)
Dan Willemsen633c5022019-04-12 11:11:38 -0700781 c.inputs = append(c.inputs, path)
Colin Crossab020a72021-03-12 17:52:23 -0800782 return c.PathForInput(path)
Dan Willemsen633c5022019-04-12 11:11:38 -0700783}
784
Colin Crossab020a72021-03-12 17:52:23 -0800785func (c *RuleBuilderCommand) addImplicit(path Path) {
Paul Duffin3866b892021-10-04 11:24:48 +0100786 checkPathNotNil(path)
Ramy Medhat2f99eec2020-06-13 17:38:27 -0400787 c.implicits = append(c.implicits, path)
Ramy Medhat2f99eec2020-06-13 17:38:27 -0400788}
789
Colin Crossda71eda2020-02-21 16:55:19 -0800790func (c *RuleBuilderCommand) addOrderOnly(path Path) {
Paul Duffin3866b892021-10-04 11:24:48 +0100791 checkPathNotNil(path)
Colin Crossda71eda2020-02-21 16:55:19 -0800792 c.orderOnlys = append(c.orderOnlys, path)
793}
794
Colin Crossab020a72021-03-12 17:52:23 -0800795// PathForInput takes an input path and returns the appropriate path to use on the command line. If
796// sbox was enabled via a call to RuleBuilder.Sbox() and the path was an output path it returns a
797// path with the placeholder prefix used for outputs in sbox. If sbox is not enabled it returns the
798// original path.
799func (c *RuleBuilderCommand) PathForInput(path Path) string {
800 if c.rule.sbox {
801 rel, inSandbox := c.rule._sboxPathForInputRel(path)
802 if inSandbox {
803 rel = filepath.Join(sboxSandboxBaseDir, rel)
804 }
805 return rel
806 }
807 return path.String()
808}
809
810// PathsForInputs takes a list of input paths and returns the appropriate paths to use on the
811// command line. If sbox was enabled via a call to RuleBuilder.Sbox() a path was an output path, it
812// returns the path with the placeholder prefix used for outputs in sbox. If sbox is not enabled it
813// returns the original paths.
814func (c *RuleBuilderCommand) PathsForInputs(paths Paths) []string {
815 ret := make([]string, len(paths))
816 for i, path := range paths {
817 ret[i] = c.PathForInput(path)
818 }
819 return ret
820}
821
Colin Crossf1a035e2020-11-16 17:32:30 -0800822// PathForOutput takes an output path and returns the appropriate path to use on the command
823// line. If sbox was enabled via a call to RuleBuilder.Sbox(), it returns a path with the
824// placeholder prefix used for outputs in sbox. If sbox is not enabled it returns the
825// original path.
826func (c *RuleBuilderCommand) PathForOutput(path WritablePath) string {
827 if c.rule.sbox {
828 // Errors will be handled in RuleBuilder.Build where we have a context to report them
829 rel, _, _ := maybeRelErr(c.rule.outDir.String(), path.String())
830 return filepath.Join(sboxOutDir, rel)
Dan Willemsen633c5022019-04-12 11:11:38 -0700831 }
832 return path.String()
Colin Crossfeec25b2019-01-30 17:32:39 -0800833}
834
Colin Crossba9e4032020-11-24 16:32:22 -0800835func sboxPathForToolRel(ctx BuilderContext, path Path) string {
836 // Errors will be handled in RuleBuilder.Build where we have a context to report them
Cole Faust3b703f32023-10-16 13:30:51 -0700837 toolDir := pathForInstall(ctx, ctx.Config().BuildOS, ctx.Config().BuildArch, "")
Colin Cross790ef352021-10-25 19:15:55 -0700838 relOutSoong, isRelOutSoong, _ := maybeRelErr(toolDir.String(), path.String())
839 if isRelOutSoong {
840 // The tool is in the Soong output directory, it will be copied to __SBOX_OUT_DIR__/tools/out
841 return filepath.Join(sboxToolsSubDir, "out", relOutSoong)
Colin Crossba9e4032020-11-24 16:32:22 -0800842 }
843 // The tool is in the source directory, it will be copied to __SBOX_OUT_DIR__/tools/src
844 return filepath.Join(sboxToolsSubDir, "src", path.String())
845}
846
Colin Crossab020a72021-03-12 17:52:23 -0800847func (r *RuleBuilder) _sboxPathForInputRel(path Path) (rel string, inSandbox bool) {
848 // Errors will be handled in RuleBuilder.Build where we have a context to report them
849 rel, isRelSboxOut, _ := maybeRelErr(r.outDir.String(), path.String())
850 if isRelSboxOut {
851 return filepath.Join(sboxOutSubDir, rel), true
852 }
853 if r.sboxInputs {
854 // When sandboxing inputs all inputs have to be copied into the sandbox. Input files that
855 // are outputs of other rules could be an arbitrary absolute path if OUT_DIR is set, so they
856 // will be copied to relative paths under __SBOX_OUT_DIR__/out.
Cole Fauste8561c62023-11-30 17:26:37 -0800857 rel, isRelOut, _ := maybeRelErr(r.ctx.Config().OutDir(), path.String())
Colin Crossab020a72021-03-12 17:52:23 -0800858 if isRelOut {
859 return filepath.Join(sboxOutSubDir, rel), true
860 }
861 }
862 return path.String(), false
863}
864
865func (r *RuleBuilder) sboxPathForInputRel(path Path) string {
866 rel, _ := r._sboxPathForInputRel(path)
867 return rel
868}
869
870func (r *RuleBuilder) sboxPathsForInputsRel(paths Paths) []string {
871 ret := make([]string, len(paths))
872 for i, path := range paths {
873 ret[i] = r.sboxPathForInputRel(path)
874 }
875 return ret
876}
877
Colin Crossba9e4032020-11-24 16:32:22 -0800878func sboxPathForPackagedToolRel(spec PackagingSpec) string {
879 return filepath.Join(sboxToolsSubDir, "out", spec.relPathInPackage)
880}
881
Colin Crossd11cf622021-03-23 22:30:35 -0700882// PathForPackagedTool takes a PackageSpec for a tool and returns the corresponding path for the
883// tool after copying it into the sandbox. This can be used on the RuleBuilder command line to
884// reference the tool.
885func (c *RuleBuilderCommand) PathForPackagedTool(spec PackagingSpec) string {
886 if !c.rule.sboxTools {
887 panic("PathForPackagedTool() requires SandboxTools()")
888 }
889
890 return filepath.Join(sboxSandboxBaseDir, sboxPathForPackagedToolRel(spec))
891}
892
Colin Crossba9e4032020-11-24 16:32:22 -0800893// PathForTool takes a path to a tool, which may be an output file or a source file, and returns
894// the corresponding path for the tool in the sbox sandbox if sbox is enabled, or the original path
895// if it is not. This can be used on the RuleBuilder command line to reference the tool.
896func (c *RuleBuilderCommand) PathForTool(path Path) string {
897 if c.rule.sbox && c.rule.sboxTools {
898 return filepath.Join(sboxSandboxBaseDir, sboxPathForToolRel(c.rule.ctx, path))
899 }
900 return path.String()
901}
902
Colin Crossd11cf622021-03-23 22:30:35 -0700903// PathsForTools takes a list of paths to tools, which may be output files or source files, and
904// returns the corresponding paths for the tools in the sbox sandbox if sbox is enabled, or the
905// original paths if it is not. This can be used on the RuleBuilder command line to reference the tool.
906func (c *RuleBuilderCommand) PathsForTools(paths Paths) []string {
907 if c.rule.sbox && c.rule.sboxTools {
908 var ret []string
909 for _, path := range paths {
910 ret = append(ret, filepath.Join(sboxSandboxBaseDir, sboxPathForToolRel(c.rule.ctx, path)))
911 }
912 return ret
913 }
914 return paths.Strings()
915}
916
Colin Crossba9e4032020-11-24 16:32:22 -0800917// PackagedTool adds the specified tool path to the command line. It can only be used with tool
918// sandboxing enabled by SandboxTools(), and will copy the tool into the sandbox.
919func (c *RuleBuilderCommand) PackagedTool(spec PackagingSpec) *RuleBuilderCommand {
920 if !c.rule.sboxTools {
921 panic("PackagedTool() requires SandboxTools()")
922 }
923
924 c.packagedTools = append(c.packagedTools, spec)
925 c.Text(sboxPathForPackagedToolRel(spec))
926 return c
927}
928
929// ImplicitPackagedTool copies the specified tool into the sandbox without modifying the command
930// line. It can only be used with tool sandboxing enabled by SandboxTools().
931func (c *RuleBuilderCommand) ImplicitPackagedTool(spec PackagingSpec) *RuleBuilderCommand {
932 if !c.rule.sboxTools {
933 panic("ImplicitPackagedTool() requires SandboxTools()")
934 }
935
936 c.packagedTools = append(c.packagedTools, spec)
937 return c
938}
939
940// ImplicitPackagedTools copies the specified tools into the sandbox without modifying the command
941// line. It can only be used with tool sandboxing enabled by SandboxTools().
942func (c *RuleBuilderCommand) ImplicitPackagedTools(specs []PackagingSpec) *RuleBuilderCommand {
943 if !c.rule.sboxTools {
944 panic("ImplicitPackagedTools() requires SandboxTools()")
945 }
946
947 c.packagedTools = append(c.packagedTools, specs...)
948 return c
949}
950
Colin Cross758290d2019-02-01 16:42:32 -0800951// Text adds the specified raw text to the command line. The text should not contain input or output paths or the
952// rule will not have them listed in its dependencies or outputs.
Colin Crossfeec25b2019-01-30 17:32:39 -0800953func (c *RuleBuilderCommand) Text(text string) *RuleBuilderCommand {
Colin Crosscfec40c2019-07-08 17:07:18 -0700954 if c.buf.Len() > 0 {
955 c.buf.WriteByte(' ')
Colin Crossfeec25b2019-01-30 17:32:39 -0800956 }
Colin Crosscfec40c2019-07-08 17:07:18 -0700957 c.buf.WriteString(text)
Colin Crossfeec25b2019-01-30 17:32:39 -0800958 return c
959}
960
Colin Cross758290d2019-02-01 16:42:32 -0800961// Textf adds the specified formatted text to the command line. The text should not contain input or output paths or
962// the rule will not have them listed in its dependencies or outputs.
Colin Crossfeec25b2019-01-30 17:32:39 -0800963func (c *RuleBuilderCommand) Textf(format string, a ...interface{}) *RuleBuilderCommand {
964 return c.Text(fmt.Sprintf(format, a...))
965}
966
Colin Cross758290d2019-02-01 16:42:32 -0800967// Flag adds the specified raw text to the command line. The text should not contain input or output paths or the
968// rule will not have them listed in its dependencies or outputs.
Colin Crossfeec25b2019-01-30 17:32:39 -0800969func (c *RuleBuilderCommand) Flag(flag string) *RuleBuilderCommand {
970 return c.Text(flag)
971}
972
Colin Crossab054432019-07-15 16:13:59 -0700973// OptionalFlag adds the specified raw text to the command line if it is not nil. The text should not contain input or
974// output paths or the rule will not have them listed in its dependencies or outputs.
975func (c *RuleBuilderCommand) OptionalFlag(flag *string) *RuleBuilderCommand {
976 if flag != nil {
977 c.Text(*flag)
978 }
979
980 return c
981}
982
Colin Cross92b7d582019-03-29 15:32:51 -0700983// Flags adds the specified raw text to the command line. The text should not contain input or output paths or the
984// rule will not have them listed in its dependencies or outputs.
985func (c *RuleBuilderCommand) Flags(flags []string) *RuleBuilderCommand {
986 for _, flag := range flags {
987 c.Text(flag)
988 }
989 return c
990}
991
Colin Cross758290d2019-02-01 16:42:32 -0800992// FlagWithArg adds the specified flag and argument text to the command line, with no separator between them. The flag
993// and argument should not contain input or output paths or the rule will not have them listed in its dependencies or
994// outputs.
Colin Crossfeec25b2019-01-30 17:32:39 -0800995func (c *RuleBuilderCommand) FlagWithArg(flag, arg string) *RuleBuilderCommand {
996 return c.Text(flag + arg)
997}
998
Colin Crossc7ed0042019-02-11 14:11:09 -0800999// FlagForEachArg adds the specified flag joined with each argument to the command line. The result is identical to
1000// calling FlagWithArg for argument.
1001func (c *RuleBuilderCommand) FlagForEachArg(flag string, args []string) *RuleBuilderCommand {
1002 for _, arg := range args {
1003 c.FlagWithArg(flag, arg)
1004 }
1005 return c
1006}
1007
Roland Levillain2da5d9a2019-02-27 16:56:41 +00001008// 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 -08001009// and no separator between the flag and arguments. The flag and arguments should not contain input or output paths or
1010// the rule will not have them listed in its dependencies or outputs.
Colin Crossfeec25b2019-01-30 17:32:39 -08001011func (c *RuleBuilderCommand) FlagWithList(flag string, list []string, sep string) *RuleBuilderCommand {
1012 return c.Text(flag + strings.Join(list, sep))
1013}
1014
Colin Cross758290d2019-02-01 16:42:32 -08001015// Tool adds the specified tool path to the command line. The path will be also added to the dependencies returned by
1016// RuleBuilder.Tools.
Colin Cross69f59a32019-02-15 10:39:37 -08001017func (c *RuleBuilderCommand) Tool(path Path) *RuleBuilderCommand {
Paul Duffin3866b892021-10-04 11:24:48 +01001018 checkPathNotNil(path)
Colin Crossfeec25b2019-01-30 17:32:39 -08001019 c.tools = append(c.tools, path)
Colin Crossba9e4032020-11-24 16:32:22 -08001020 return c.Text(c.PathForTool(path))
1021}
1022
1023// Tool adds the specified tool path to the dependencies returned by RuleBuilder.Tools.
1024func (c *RuleBuilderCommand) ImplicitTool(path Path) *RuleBuilderCommand {
Paul Duffin3866b892021-10-04 11:24:48 +01001025 checkPathNotNil(path)
Colin Crossba9e4032020-11-24 16:32:22 -08001026 c.tools = append(c.tools, path)
1027 return c
1028}
1029
1030// Tool adds the specified tool path to the dependencies returned by RuleBuilder.Tools.
1031func (c *RuleBuilderCommand) ImplicitTools(paths Paths) *RuleBuilderCommand {
Paul Duffin3866b892021-10-04 11:24:48 +01001032 for _, path := range paths {
1033 c.ImplicitTool(path)
1034 }
Colin Crossba9e4032020-11-24 16:32:22 -08001035 return c
Colin Crossfeec25b2019-01-30 17:32:39 -08001036}
1037
Colin Crossee94d6a2019-07-08 17:08:34 -07001038// BuiltTool adds the specified tool path that was built using a host Soong module to the command line. The path will
1039// be also added to the dependencies returned by RuleBuilder.Tools.
1040//
1041// It is equivalent to:
Colin Crossd079e0b2022-08-16 10:27:33 -07001042//
1043// cmd.Tool(ctx.Config().HostToolPath(ctx, tool))
Colin Crossf1a035e2020-11-16 17:32:30 -08001044func (c *RuleBuilderCommand) BuiltTool(tool string) *RuleBuilderCommand {
Colin Cross9b698b62021-12-22 09:55:32 -08001045 if c.rule.ctx.Config().UseHostMusl() {
1046 // If the host is using musl, assume that the tool was built against musl libc and include
1047 // libc_musl.so in the sandbox.
1048 // TODO(ccross): if we supported adding new dependencies during GenerateAndroidBuildActions
1049 // this could be a dependency + TransitivePackagingSpecs.
1050 c.ImplicitTool(c.rule.ctx.Config().HostJNIToolPath(c.rule.ctx, "libc_musl"))
1051 }
1052 return c.builtToolWithoutDeps(tool)
1053}
1054
1055// builtToolWithoutDeps is similar to BuiltTool, but doesn't add any dependencies. It is used
1056// internally by RuleBuilder for helper tools that are known to be compiled statically.
1057func (c *RuleBuilderCommand) builtToolWithoutDeps(tool string) *RuleBuilderCommand {
Colin Crossf1a035e2020-11-16 17:32:30 -08001058 return c.Tool(c.rule.ctx.Config().HostToolPath(c.rule.ctx, tool))
Colin Crossee94d6a2019-07-08 17:08:34 -07001059}
1060
1061// PrebuiltBuildTool adds the specified tool path from prebuils/build-tools. The path will be also added to the
1062// dependencies returned by RuleBuilder.Tools.
1063//
1064// It is equivalent to:
Colin Crossd079e0b2022-08-16 10:27:33 -07001065//
1066// cmd.Tool(ctx.Config().PrebuiltBuildTool(ctx, tool))
Colin Crossee94d6a2019-07-08 17:08:34 -07001067func (c *RuleBuilderCommand) PrebuiltBuildTool(ctx PathContext, tool string) *RuleBuilderCommand {
1068 return c.Tool(ctx.Config().PrebuiltBuildTool(ctx, tool))
1069}
1070
Colin Cross758290d2019-02-01 16:42:32 -08001071// Input adds the specified input path to the command line. The path will also be added to the dependencies returned by
1072// RuleBuilder.Inputs.
Colin Cross69f59a32019-02-15 10:39:37 -08001073func (c *RuleBuilderCommand) Input(path Path) *RuleBuilderCommand {
Dan Willemsen633c5022019-04-12 11:11:38 -07001074 return c.Text(c.addInput(path))
Colin Crossfeec25b2019-01-30 17:32:39 -08001075}
1076
Colin Cross758290d2019-02-01 16:42:32 -08001077// Inputs adds the specified input paths to the command line, separated by spaces. The paths will also be added to the
1078// dependencies returned by RuleBuilder.Inputs.
Colin Cross69f59a32019-02-15 10:39:37 -08001079func (c *RuleBuilderCommand) Inputs(paths Paths) *RuleBuilderCommand {
Colin Cross758290d2019-02-01 16:42:32 -08001080 for _, path := range paths {
1081 c.Input(path)
1082 }
1083 return c
1084}
1085
1086// Implicit adds the specified input path to the dependencies returned by RuleBuilder.Inputs without modifying the
1087// command line.
Colin Cross69f59a32019-02-15 10:39:37 -08001088func (c *RuleBuilderCommand) Implicit(path Path) *RuleBuilderCommand {
Ramy Medhat2f99eec2020-06-13 17:38:27 -04001089 c.addImplicit(path)
Colin Crossfeec25b2019-01-30 17:32:39 -08001090 return c
1091}
1092
Colin Cross758290d2019-02-01 16:42:32 -08001093// Implicits adds the specified input paths to the dependencies returned by RuleBuilder.Inputs without modifying the
1094// command line.
Colin Cross69f59a32019-02-15 10:39:37 -08001095func (c *RuleBuilderCommand) Implicits(paths Paths) *RuleBuilderCommand {
Dan Willemsen633c5022019-04-12 11:11:38 -07001096 for _, path := range paths {
Ramy Medhat2f99eec2020-06-13 17:38:27 -04001097 c.addImplicit(path)
Dan Willemsen633c5022019-04-12 11:11:38 -07001098 }
Colin Crossfeec25b2019-01-30 17:32:39 -08001099 return c
1100}
1101
Ramy Medhat2f99eec2020-06-13 17:38:27 -04001102// GetImplicits returns the command's implicit inputs.
1103func (c *RuleBuilderCommand) GetImplicits() Paths {
1104 return c.implicits
1105}
1106
Colin Crossda71eda2020-02-21 16:55:19 -08001107// OrderOnly adds the specified input path to the dependencies returned by RuleBuilder.OrderOnlys
1108// without modifying the command line.
1109func (c *RuleBuilderCommand) OrderOnly(path Path) *RuleBuilderCommand {
1110 c.addOrderOnly(path)
1111 return c
1112}
1113
1114// OrderOnlys adds the specified input paths to the dependencies returned by RuleBuilder.OrderOnlys
1115// without modifying the command line.
1116func (c *RuleBuilderCommand) OrderOnlys(paths Paths) *RuleBuilderCommand {
1117 for _, path := range paths {
1118 c.addOrderOnly(path)
1119 }
1120 return c
1121}
1122
Colin Crossae89abe2021-04-21 11:45:23 -07001123// Validation adds the specified input path to the validation dependencies by
1124// RuleBuilder.Validations without modifying the command line.
1125func (c *RuleBuilderCommand) Validation(path Path) *RuleBuilderCommand {
Paul Duffin3866b892021-10-04 11:24:48 +01001126 checkPathNotNil(path)
Colin Crossae89abe2021-04-21 11:45:23 -07001127 c.validations = append(c.validations, path)
1128 return c
1129}
1130
1131// Validations adds the specified input paths to the validation dependencies by
1132// RuleBuilder.Validations without modifying the command line.
1133func (c *RuleBuilderCommand) Validations(paths Paths) *RuleBuilderCommand {
Paul Duffin3866b892021-10-04 11:24:48 +01001134 for _, path := range paths {
1135 c.Validation(path)
1136 }
Colin Crossae89abe2021-04-21 11:45:23 -07001137 return c
1138}
1139
Colin Cross758290d2019-02-01 16:42:32 -08001140// Output adds the specified output path to the command line. The path will also be added to the outputs returned by
1141// RuleBuilder.Outputs.
Colin Cross69f59a32019-02-15 10:39:37 -08001142func (c *RuleBuilderCommand) Output(path WritablePath) *RuleBuilderCommand {
Paul Duffin3866b892021-10-04 11:24:48 +01001143 checkPathNotNil(path)
Colin Crossfeec25b2019-01-30 17:32:39 -08001144 c.outputs = append(c.outputs, path)
Colin Crossf1a035e2020-11-16 17:32:30 -08001145 return c.Text(c.PathForOutput(path))
Colin Crossfeec25b2019-01-30 17:32:39 -08001146}
1147
Colin Cross758290d2019-02-01 16:42:32 -08001148// Outputs adds the specified output paths to the command line, separated by spaces. The paths will also be added to
1149// the outputs returned by RuleBuilder.Outputs.
Colin Cross69f59a32019-02-15 10:39:37 -08001150func (c *RuleBuilderCommand) Outputs(paths WritablePaths) *RuleBuilderCommand {
Colin Cross758290d2019-02-01 16:42:32 -08001151 for _, path := range paths {
1152 c.Output(path)
1153 }
1154 return c
1155}
1156
Dan Willemsen1945a4b2019-06-04 17:10:41 -07001157// OutputDir adds the output directory to the command line. This is only available when used with RuleBuilder.Sbox,
1158// and will be the temporary output directory managed by sbox, not the final one.
1159func (c *RuleBuilderCommand) OutputDir() *RuleBuilderCommand {
Colin Crossf1a035e2020-11-16 17:32:30 -08001160 if !c.rule.sbox {
Dan Willemsen1945a4b2019-06-04 17:10:41 -07001161 panic("OutputDir only valid with Sbox")
1162 }
Colin Cross3d680512020-11-13 16:23:53 -08001163 return c.Text(sboxOutDir)
Dan Willemsen1945a4b2019-06-04 17:10:41 -07001164}
1165
Colin Cross1d2cf042019-03-29 15:33:06 -07001166// DepFile adds the specified depfile path to the paths returned by RuleBuilder.DepFiles and adds it to the command
1167// line, and causes RuleBuilder.Build file to set the depfile flag for ninja. If multiple depfiles are added to
1168// commands in a single RuleBuilder then RuleBuilder.Build will add an extra command to merge the depfiles together.
1169func (c *RuleBuilderCommand) DepFile(path WritablePath) *RuleBuilderCommand {
Paul Duffin3866b892021-10-04 11:24:48 +01001170 checkPathNotNil(path)
Colin Cross1d2cf042019-03-29 15:33:06 -07001171 c.depFiles = append(c.depFiles, path)
Colin Crossf1a035e2020-11-16 17:32:30 -08001172 return c.Text(c.PathForOutput(path))
Colin Cross1d2cf042019-03-29 15:33:06 -07001173}
1174
Colin Cross758290d2019-02-01 16:42:32 -08001175// ImplicitOutput adds the specified output path to the dependencies returned by RuleBuilder.Outputs without modifying
1176// the command line.
Colin Cross69f59a32019-02-15 10:39:37 -08001177func (c *RuleBuilderCommand) ImplicitOutput(path WritablePath) *RuleBuilderCommand {
Colin Crossfeec25b2019-01-30 17:32:39 -08001178 c.outputs = append(c.outputs, path)
1179 return c
1180}
1181
Colin Cross758290d2019-02-01 16:42:32 -08001182// ImplicitOutputs adds the specified output paths to the dependencies returned by RuleBuilder.Outputs without modifying
1183// the command line.
Colin Cross69f59a32019-02-15 10:39:37 -08001184func (c *RuleBuilderCommand) ImplicitOutputs(paths WritablePaths) *RuleBuilderCommand {
Colin Cross758290d2019-02-01 16:42:32 -08001185 c.outputs = append(c.outputs, paths...)
1186 return c
1187}
1188
Colin Cross1d2cf042019-03-29 15:33:06 -07001189// ImplicitDepFile adds the specified depfile path to the paths returned by RuleBuilder.DepFiles without modifying
1190// the command line, and causes RuleBuilder.Build file to set the depfile flag for ninja. If multiple depfiles
1191// are added to commands in a single RuleBuilder then RuleBuilder.Build will add an extra command to merge the
1192// depfiles together.
1193func (c *RuleBuilderCommand) ImplicitDepFile(path WritablePath) *RuleBuilderCommand {
1194 c.depFiles = append(c.depFiles, path)
1195 return c
1196}
1197
Colin Cross758290d2019-02-01 16:42:32 -08001198// FlagWithInput adds the specified flag and input path to the command line, with no separator between them. The path
1199// will also be added to the dependencies returned by RuleBuilder.Inputs.
Colin Cross69f59a32019-02-15 10:39:37 -08001200func (c *RuleBuilderCommand) FlagWithInput(flag string, path Path) *RuleBuilderCommand {
Dan Willemsen633c5022019-04-12 11:11:38 -07001201 return c.Text(flag + c.addInput(path))
Colin Crossfeec25b2019-01-30 17:32:39 -08001202}
1203
Colin Cross758290d2019-02-01 16:42:32 -08001204// FlagWithInputList adds the specified flag and input paths to the command line, with the inputs joined by sep
1205// and no separator between the flag and inputs. The input paths will also be added to the dependencies returned by
1206// RuleBuilder.Inputs.
Colin Cross69f59a32019-02-15 10:39:37 -08001207func (c *RuleBuilderCommand) FlagWithInputList(flag string, paths Paths, sep string) *RuleBuilderCommand {
Dan Willemsen633c5022019-04-12 11:11:38 -07001208 strs := make([]string, len(paths))
1209 for i, path := range paths {
1210 strs[i] = c.addInput(path)
1211 }
1212 return c.FlagWithList(flag, strs, sep)
Colin Crossfeec25b2019-01-30 17:32:39 -08001213}
1214
Colin Cross758290d2019-02-01 16:42:32 -08001215// FlagForEachInput adds the specified flag joined with each input path to the command line. The input paths will also
1216// be added to the dependencies returned by RuleBuilder.Inputs. The result is identical to calling FlagWithInput for
1217// each input path.
Colin Cross69f59a32019-02-15 10:39:37 -08001218func (c *RuleBuilderCommand) FlagForEachInput(flag string, paths Paths) *RuleBuilderCommand {
Colin Cross758290d2019-02-01 16:42:32 -08001219 for _, path := range paths {
1220 c.FlagWithInput(flag, path)
1221 }
1222 return c
1223}
1224
1225// FlagWithOutput adds the specified flag and output path to the command line, with no separator between them. The path
1226// will also be added to the outputs returned by RuleBuilder.Outputs.
Colin Cross69f59a32019-02-15 10:39:37 -08001227func (c *RuleBuilderCommand) FlagWithOutput(flag string, path WritablePath) *RuleBuilderCommand {
Colin Crossfeec25b2019-01-30 17:32:39 -08001228 c.outputs = append(c.outputs, path)
Colin Crossf1a035e2020-11-16 17:32:30 -08001229 return c.Text(flag + c.PathForOutput(path))
Colin Crossfeec25b2019-01-30 17:32:39 -08001230}
1231
Colin Cross1d2cf042019-03-29 15:33:06 -07001232// FlagWithDepFile adds the specified flag and depfile path to the command line, with no separator between them. The path
1233// will also be added to the outputs returned by RuleBuilder.Outputs.
1234func (c *RuleBuilderCommand) FlagWithDepFile(flag string, path WritablePath) *RuleBuilderCommand {
1235 c.depFiles = append(c.depFiles, path)
Colin Crossf1a035e2020-11-16 17:32:30 -08001236 return c.Text(flag + c.PathForOutput(path))
Colin Cross1d2cf042019-03-29 15:33:06 -07001237}
1238
Colin Crossce3a51d2021-03-19 16:22:12 -07001239// FlagWithRspFileInputList adds the specified flag and path to an rspfile to the command line, with
1240// no separator between them. The paths will be written to the rspfile. If sbox is enabled, the
1241// rspfile must be outside the sbox directory. The first use of FlagWithRspFileInputList in any
1242// RuleBuilderCommand of a RuleBuilder will use Ninja's rsp file support for the rule, additional
1243// uses will result in an auxiliary rules to write the rspFile contents.
Colin Cross70c47412021-03-12 17:48:14 -08001244func (c *RuleBuilderCommand) FlagWithRspFileInputList(flag string, rspFile WritablePath, paths Paths) *RuleBuilderCommand {
Colin Cross0cb0d7b2019-07-11 10:59:15 -07001245 // Use an empty slice if paths is nil, the non-nil slice is used as an indicator that the rsp file must be
1246 // generated.
1247 if paths == nil {
1248 paths = Paths{}
1249 }
1250
Colin Crossce3a51d2021-03-19 16:22:12 -07001251 c.rspFiles = append(c.rspFiles, rspFileAndPaths{rspFile, paths})
Colin Cross0cb0d7b2019-07-11 10:59:15 -07001252
Colin Cross70c47412021-03-12 17:48:14 -08001253 if c.rule.sbox {
1254 if _, isRel, _ := maybeRelErr(c.rule.outDir.String(), rspFile.String()); isRel {
1255 panic(fmt.Errorf("FlagWithRspFileInputList rspfile %q must not be inside out dir %q",
1256 rspFile.String(), c.rule.outDir.String()))
1257 }
1258 }
1259
Colin Crossab020a72021-03-12 17:52:23 -08001260 c.FlagWithArg(flag, c.PathForInput(rspFile))
Colin Cross0cb0d7b2019-07-11 10:59:15 -07001261 return c
1262}
1263
Colin Cross758290d2019-02-01 16:42:32 -08001264// String returns the command line.
1265func (c *RuleBuilderCommand) String() string {
Colin Crosscfec40c2019-07-08 17:07:18 -07001266 return c.buf.String()
Colin Cross758290d2019-02-01 16:42:32 -08001267}
Colin Cross1d2cf042019-03-29 15:33:06 -07001268
Colin Crosse16ce362020-11-12 08:29:30 -08001269// RuleBuilderSboxProtoForTests takes the BuildParams for the manifest passed to RuleBuilder.Sbox()
1270// and returns sbox testproto generated by the RuleBuilder.
Colin Crossf61d03d2023-11-02 16:56:39 -07001271func RuleBuilderSboxProtoForTests(t *testing.T, ctx *TestContext, params TestingBuildParams) *sbox_proto.Manifest {
Colin Crosse16ce362020-11-12 08:29:30 -08001272 t.Helper()
Colin Crossf61d03d2023-11-02 16:56:39 -07001273 content := ContentFromFileRuleForTests(t, ctx, params)
Colin Crosse16ce362020-11-12 08:29:30 -08001274 manifest := sbox_proto.Manifest{}
Dan Willemsen4591b642021-05-24 14:24:12 -07001275 err := prototext.Unmarshal([]byte(content), &manifest)
Colin Crosse16ce362020-11-12 08:29:30 -08001276 if err != nil {
1277 t.Fatalf("failed to unmarshal manifest: %s", err.Error())
1278 }
1279 return &manifest
1280}
1281
Colin Cross1d2cf042019-03-29 15:33:06 -07001282func ninjaNameEscape(s string) string {
1283 b := []byte(s)
1284 escaped := false
1285 for i, c := range b {
1286 valid := (c >= 'a' && c <= 'z') ||
1287 (c >= 'A' && c <= 'Z') ||
1288 (c >= '0' && c <= '9') ||
1289 (c == '_') ||
1290 (c == '-') ||
1291 (c == '.')
1292 if !valid {
1293 b[i] = '_'
1294 escaped = true
1295 }
1296 }
1297 if escaped {
1298 s = string(b)
1299 }
1300 return s
1301}
Colin Cross3d680512020-11-13 16:23:53 -08001302
1303// hashSrcFiles returns a hash of the list of source files. It is used to ensure the command line
1304// or the sbox textproto manifest change even if the input files are not listed on the command line.
1305func hashSrcFiles(srcFiles Paths) string {
1306 h := sha256.New()
1307 srcFileList := strings.Join(srcFiles.Strings(), "\n")
1308 h.Write([]byte(srcFileList))
1309 return fmt.Sprintf("%x", h.Sum(nil))
1310}
Colin Crossf1a035e2020-11-16 17:32:30 -08001311
1312// BuilderContextForTesting returns a BuilderContext for the given config that can be used for tests
1313// that need to call methods that take a BuilderContext.
1314func BuilderContextForTesting(config Config) BuilderContext {
1315 pathCtx := PathContextForTesting(config)
1316 return builderContextForTests{
1317 PathContext: pathCtx,
1318 }
1319}
1320
1321type builderContextForTests struct {
1322 PathContext
1323}
1324
1325func (builderContextForTests) Rule(PackageContext, string, blueprint.RuleParams, ...string) blueprint.Rule {
1326 return nil
1327}
1328func (builderContextForTests) Build(PackageContext, BuildParams) {}
Colin Crossef972742021-03-12 17:24:45 -08001329
Colin Crosse55bd422021-03-23 13:44:30 -07001330func writeRspFileRule(ctx BuilderContext, rspFile WritablePath, paths Paths) {
1331 buf := &strings.Builder{}
1332 err := response.WriteRspFile(buf, paths.Strings())
1333 if err != nil {
1334 // There should never be I/O errors writing to a bytes.Buffer.
1335 panic(err)
Colin Crossef972742021-03-12 17:24:45 -08001336 }
Colin Crosse55bd422021-03-23 13:44:30 -07001337 WriteFileRule(ctx, rspFile, buf.String())
Colin Crossef972742021-03-12 17:24:45 -08001338}