blob: 418826c5cfe2a3b74c902cd9a58c35812d5c8c3f [file] [log] [blame]
Jeff Gastonefc1b412017-03-29 17:29:06 -07001// Copyright 2017 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 main
16
17import (
Dan Willemsenc89b6f12019-08-29 14:47:40 -070018 "bytes"
Ulf Adamsb73daa52020-11-25 23:09:09 +010019 "crypto/sha1"
20 "encoding/hex"
Jeff Gaston90cfb092017-09-26 16:46:10 -070021 "errors"
Jeff Gaston93f0f372017-11-01 13:33:02 -070022 "flag"
Jeff Gastonefc1b412017-03-29 17:29:06 -070023 "fmt"
Colin Crosse16ce362020-11-12 08:29:30 -080024 "io"
Jeff Gastonefc1b412017-03-29 17:29:06 -070025 "io/ioutil"
26 "os"
27 "os/exec"
Jeff Gastonefc1b412017-03-29 17:29:06 -070028 "path/filepath"
Colin Crosse16ce362020-11-12 08:29:30 -080029 "strconv"
Jeff Gastonefc1b412017-03-29 17:29:06 -070030 "strings"
Colin Crossd1c1e6f2019-03-29 13:54:39 -070031 "time"
Dan Willemsenc89b6f12019-08-29 14:47:40 -070032
Colin Crosse16ce362020-11-12 08:29:30 -080033 "android/soong/cmd/sbox/sbox_proto"
Dan Willemsenc89b6f12019-08-29 14:47:40 -070034 "android/soong/makedeps"
Colin Crosse55bd422021-03-23 13:44:30 -070035 "android/soong/response"
Colin Crosse16ce362020-11-12 08:29:30 -080036
Dan Willemsen4591b642021-05-24 14:24:12 -070037 "google.golang.org/protobuf/encoding/prototext"
Jeff Gastonefc1b412017-03-29 17:29:06 -070038)
39
Jeff Gaston93f0f372017-11-01 13:33:02 -070040var (
Colin Crosse52c2ac2022-03-28 17:03:35 -070041 sandboxesRoot string
42 outputDir string
43 manifestFile string
44 keepOutDir bool
45 writeIfChanged bool
Colin Crosse16ce362020-11-12 08:29:30 -080046)
47
48const (
49 depFilePlaceholder = "__SBOX_DEPFILE__"
50 sandboxDirPlaceholder = "__SBOX_SANDBOX_DIR__"
Jeff Gaston93f0f372017-11-01 13:33:02 -070051)
52
53func init() {
54 flag.StringVar(&sandboxesRoot, "sandbox-path", "",
55 "root of temp directory to put the sandbox into")
Colin Crosse52c2ac2022-03-28 17:03:35 -070056 flag.StringVar(&outputDir, "output-dir", "",
57 "directory which will contain all output files and only output files")
Colin Crosse16ce362020-11-12 08:29:30 -080058 flag.StringVar(&manifestFile, "manifest", "",
59 "textproto manifest describing the sandboxed command(s)")
Jeff Gaston93f0f372017-11-01 13:33:02 -070060 flag.BoolVar(&keepOutDir, "keep-out-dir", false,
61 "whether to keep the sandbox directory when done")
Colin Crosse52c2ac2022-03-28 17:03:35 -070062 flag.BoolVar(&writeIfChanged, "write-if-changed", false,
63 "only write the output files if they have changed")
Jeff Gaston93f0f372017-11-01 13:33:02 -070064}
65
66func usageViolation(violation string) {
67 if violation != "" {
68 fmt.Fprintf(os.Stderr, "Usage error: %s.\n\n", violation)
69 }
70
71 fmt.Fprintf(os.Stderr,
Colin Crosse16ce362020-11-12 08:29:30 -080072 "Usage: sbox --manifest <manifest> --sandbox-path <sandboxPath>\n")
Jeff Gaston93f0f372017-11-01 13:33:02 -070073
74 flag.PrintDefaults()
75
76 os.Exit(1)
77}
78
Jeff Gastonefc1b412017-03-29 17:29:06 -070079func main() {
Jeff Gaston93f0f372017-11-01 13:33:02 -070080 flag.Usage = func() {
81 usageViolation("")
82 }
83 flag.Parse()
84
Jeff Gastonefc1b412017-03-29 17:29:06 -070085 error := run()
86 if error != nil {
87 fmt.Fprintln(os.Stderr, error)
88 os.Exit(1)
89 }
90}
91
Jeff Gaston90cfb092017-09-26 16:46:10 -070092func findAllFilesUnder(root string) (paths []string) {
93 paths = []string{}
94 filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
95 if !info.IsDir() {
96 relPath, err := filepath.Rel(root, path)
97 if err != nil {
98 // couldn't find relative path from ancestor?
99 panic(err)
100 }
101 paths = append(paths, relPath)
102 }
103 return nil
104 })
105 return paths
106}
107
Jeff Gastonefc1b412017-03-29 17:29:06 -0700108func run() error {
Colin Crosse16ce362020-11-12 08:29:30 -0800109 if manifestFile == "" {
110 usageViolation("--manifest <manifest> is required and must be non-empty")
Jeff Gastonefc1b412017-03-29 17:29:06 -0700111 }
Jeff Gaston02a684b2017-10-27 14:59:27 -0700112 if sandboxesRoot == "" {
Jeff Gastonefc1b412017-03-29 17:29:06 -0700113 // In practice, the value of sandboxesRoot will mostly likely be at a fixed location relative to OUT_DIR,
114 // and the sbox executable will most likely be at a fixed location relative to OUT_DIR too, so
115 // the value of sandboxesRoot will most likely be at a fixed location relative to the sbox executable
116 // However, Soong also needs to be able to separately remove the sandbox directory on startup (if it has anything left in it)
117 // and by passing it as a parameter we don't need to duplicate its value
Jeff Gaston93f0f372017-11-01 13:33:02 -0700118 usageViolation("--sandbox-path <sandboxPath> is required and must be non-empty")
Jeff Gastonefc1b412017-03-29 17:29:06 -0700119 }
Colin Crosse16ce362020-11-12 08:29:30 -0800120
121 manifest, err := readManifest(manifestFile)
122
123 if len(manifest.Commands) == 0 {
124 return fmt.Errorf("at least one commands entry is required in %q", manifestFile)
Jeff Gaston193f2fb2017-06-12 15:00:12 -0700125 }
126
Colin Crosse16ce362020-11-12 08:29:30 -0800127 // setup sandbox directory
128 err = os.MkdirAll(sandboxesRoot, 0777)
Jeff Gaston8a88db52017-11-06 13:33:14 -0800129 if err != nil {
Colin Crosse16ce362020-11-12 08:29:30 -0800130 return fmt.Errorf("failed to create %q: %w", sandboxesRoot, err)
Jeff Gaston8a88db52017-11-06 13:33:14 -0800131 }
Jeff Gastonefc1b412017-03-29 17:29:06 -0700132
Ulf Adamsb73daa52020-11-25 23:09:09 +0100133 // This tool assumes that there are no two concurrent runs with the same
134 // manifestFile. It should therefore be safe to use the hash of the
135 // manifestFile as the temporary directory name. We do this because it
136 // makes the temporary directory name deterministic. There are some
137 // tools that embed the name of the temporary output in the output, and
138 // they otherwise cause non-determinism, which then poisons actions
139 // depending on this one.
140 hash := sha1.New()
141 hash.Write([]byte(manifestFile))
142 tempDir := filepath.Join(sandboxesRoot, "sbox", hex.EncodeToString(hash.Sum(nil)))
143
144 err = os.RemoveAll(tempDir)
145 if err != nil {
146 return err
147 }
148 err = os.MkdirAll(tempDir, 0777)
Jeff Gastonefc1b412017-03-29 17:29:06 -0700149 if err != nil {
Colin Crosse16ce362020-11-12 08:29:30 -0800150 return fmt.Errorf("failed to create temporary dir in %q: %w", sandboxesRoot, err)
Jeff Gastonefc1b412017-03-29 17:29:06 -0700151 }
152
153 // In the common case, the following line of code is what removes the sandbox
154 // If a fatal error occurs (such as if our Go process is killed unexpectedly),
Colin Crosse16ce362020-11-12 08:29:30 -0800155 // then at the beginning of the next build, Soong will wipe the temporary
156 // directory.
Jeff Gastonf49082a2017-06-07 13:22:22 -0700157 defer func() {
158 // in some cases we decline to remove the temp dir, to facilitate debugging
Jeff Gaston93f0f372017-11-01 13:33:02 -0700159 if !keepOutDir {
Jeff Gastonf49082a2017-06-07 13:22:22 -0700160 os.RemoveAll(tempDir)
161 }
162 }()
Jeff Gastonefc1b412017-03-29 17:29:06 -0700163
Colin Crosse16ce362020-11-12 08:29:30 -0800164 // If there is more than one command in the manifest use a separate directory for each one.
165 useSubDir := len(manifest.Commands) > 1
166 var commandDepFiles []string
Jeff Gastonefc1b412017-03-29 17:29:06 -0700167
Colin Crosse16ce362020-11-12 08:29:30 -0800168 for i, command := range manifest.Commands {
169 localTempDir := tempDir
170 if useSubDir {
171 localTempDir = filepath.Join(localTempDir, strconv.Itoa(i))
Jeff Gastonefc1b412017-03-29 17:29:06 -0700172 }
Kevin DuBois0a5da702021-10-05 15:41:02 -0700173 depFile, err := runCommand(command, localTempDir, i)
Jeff Gaston02a684b2017-10-27 14:59:27 -0700174 if err != nil {
Colin Crosse16ce362020-11-12 08:29:30 -0800175 // Running the command failed, keep the temporary output directory around in
176 // case a user wants to inspect it for debugging purposes. Soong will delete
177 // it at the beginning of the next build anyway.
178 keepOutDir = true
Jeff Gaston02a684b2017-10-27 14:59:27 -0700179 return err
180 }
Colin Crosse16ce362020-11-12 08:29:30 -0800181 if depFile != "" {
182 commandDepFiles = append(commandDepFiles, depFile)
183 }
184 }
185
186 outputDepFile := manifest.GetOutputDepfile()
187 if len(commandDepFiles) > 0 && outputDepFile == "" {
188 return fmt.Errorf("Sandboxed commands used %s but output depfile is not set in manifest file",
189 depFilePlaceholder)
190 }
191
192 if outputDepFile != "" {
193 // Merge the depfiles from each command in the manifest to a single output depfile.
194 err = rewriteDepFiles(commandDepFiles, outputDepFile)
195 if err != nil {
196 return fmt.Errorf("failed merging depfiles: %w", err)
197 }
198 }
199
200 return nil
201}
202
Kevin DuBois0a5da702021-10-05 15:41:02 -0700203// createCommandScript will create and return an exec.Cmd that runs rawCommand.
204//
205// rawCommand is executed via a script in the sandbox.
206// tempDir is the temporary where the script is created.
207// toDirInSandBox is the path containing the script in the sbox environment.
208// toDirInSandBox is the path containing the script in the sbox environment.
209// seed is a unique integer used to distinguish different scripts that might be at location.
210//
211// returns an exec.Cmd that can be ran from within sbox context if no error, or nil if error.
212// caller must ensure script is cleaned up if function succeeds.
213//
214func createCommandScript(rawCommand string, tempDir, toDirInSandbox string, seed int) (*exec.Cmd, error) {
215 scriptName := fmt.Sprintf("sbox_command.%d.bash", seed)
216 scriptPathAndName := joinPath(tempDir, scriptName)
217 err := os.WriteFile(scriptPathAndName, []byte(rawCommand), 0644)
218 if err != nil {
219 return nil, fmt.Errorf("failed to write command %s... to %s",
220 rawCommand[0:40], scriptPathAndName)
221 }
222 return exec.Command("bash", joinPath(toDirInSandbox, filepath.Base(scriptName))), nil
223}
224
Colin Crosse16ce362020-11-12 08:29:30 -0800225// readManifest reads an sbox manifest from a textproto file.
226func readManifest(file string) (*sbox_proto.Manifest, error) {
227 manifestData, err := ioutil.ReadFile(file)
228 if err != nil {
229 return nil, fmt.Errorf("error reading manifest %q: %w", file, err)
230 }
231
232 manifest := sbox_proto.Manifest{}
233
Dan Willemsen4591b642021-05-24 14:24:12 -0700234 err = prototext.Unmarshal(manifestData, &manifest)
Colin Crosse16ce362020-11-12 08:29:30 -0800235 if err != nil {
236 return nil, fmt.Errorf("error parsing manifest %q: %w", file, err)
237 }
238
239 return &manifest, nil
240}
241
242// runCommand runs a single command from a manifest. If the command references the
243// __SBOX_DEPFILE__ placeholder it returns the name of the depfile that was used.
Kevin DuBois0a5da702021-10-05 15:41:02 -0700244func runCommand(command *sbox_proto.Command, tempDir string, commandIndex int) (depFile string, err error) {
Colin Crosse16ce362020-11-12 08:29:30 -0800245 rawCommand := command.GetCommand()
246 if rawCommand == "" {
247 return "", fmt.Errorf("command is required")
248 }
249
Colin Crosse52c2ac2022-03-28 17:03:35 -0700250 // Remove files from the output directory
251 err = clearOutputDirectory(command.CopyAfter, outputDir, writeType(writeIfChanged))
252 if err != nil {
253 return "", err
254 }
255
Colin Crosse55bd422021-03-23 13:44:30 -0700256 pathToTempDirInSbox := tempDir
257 if command.GetChdir() {
258 pathToTempDirInSbox = "."
259 }
260
Colin Crosse16ce362020-11-12 08:29:30 -0800261 err = os.MkdirAll(tempDir, 0777)
262 if err != nil {
263 return "", fmt.Errorf("failed to create %q: %w", tempDir, err)
264 }
265
266 // Copy in any files specified by the manifest.
Colin Crosse52c2ac2022-03-28 17:03:35 -0700267 err = copyFiles(command.CopyBefore, "", tempDir, requireFromExists, alwaysWrite)
Colin Crosse16ce362020-11-12 08:29:30 -0800268 if err != nil {
269 return "", err
270 }
Colin Crosse55bd422021-03-23 13:44:30 -0700271 err = copyRspFiles(command.RspFiles, tempDir, pathToTempDirInSbox)
272 if err != nil {
273 return "", err
Colin Crossc590ec42021-03-11 17:20:02 -0800274 }
275
Colin Crosse16ce362020-11-12 08:29:30 -0800276 if strings.Contains(rawCommand, depFilePlaceholder) {
Colin Crossc590ec42021-03-11 17:20:02 -0800277 depFile = filepath.Join(pathToTempDirInSbox, "deps.d")
Colin Crosse16ce362020-11-12 08:29:30 -0800278 rawCommand = strings.Replace(rawCommand, depFilePlaceholder, depFile, -1)
279 }
280
281 if strings.Contains(rawCommand, sandboxDirPlaceholder) {
Colin Crossc590ec42021-03-11 17:20:02 -0800282 rawCommand = strings.Replace(rawCommand, sandboxDirPlaceholder, pathToTempDirInSbox, -1)
Colin Crosse16ce362020-11-12 08:29:30 -0800283 }
284
285 // Emulate ninja's behavior of creating the directories for any output files before
286 // running the command.
287 err = makeOutputDirs(command.CopyAfter, tempDir)
288 if err != nil {
289 return "", err
Jeff Gastonefc1b412017-03-29 17:29:06 -0700290 }
291
Kevin DuBois0a5da702021-10-05 15:41:02 -0700292 cmd, err := createCommandScript(rawCommand, tempDir, pathToTempDirInSbox, commandIndex)
293 if err != nil {
294 return "", err
295 }
296
Colin Cross4258a392021-04-15 18:50:11 -0700297 buf := &bytes.Buffer{}
Jeff Gastonefc1b412017-03-29 17:29:06 -0700298 cmd.Stdin = os.Stdin
Colin Cross4258a392021-04-15 18:50:11 -0700299 cmd.Stdout = buf
300 cmd.Stderr = buf
Colin Crosse16ce362020-11-12 08:29:30 -0800301
302 if command.GetChdir() {
303 cmd.Dir = tempDir
Colin Crossc590ec42021-03-11 17:20:02 -0800304 path := os.Getenv("PATH")
305 absPath, err := makeAbsPathEnv(path)
306 if err != nil {
307 return "", err
308 }
309 err = os.Setenv("PATH", absPath)
310 if err != nil {
311 return "", fmt.Errorf("Failed to update PATH: %w", err)
312 }
Colin Crosse16ce362020-11-12 08:29:30 -0800313 }
Jeff Gastonefc1b412017-03-29 17:29:06 -0700314 err = cmd.Run()
Jeff Gaston193f2fb2017-06-12 15:00:12 -0700315
Colin Crossfc2d8422021-04-15 18:36:42 -0700316 if err != nil {
317 // The command failed, do a best effort copy of output files out of the sandbox. This is
318 // especially useful for linters with baselines that print an error message on failure
319 // with a command to copy the output lint errors to the new baseline. Use a copy instead of
320 // a move to leave the sandbox intact for manual inspection
Colin Crosse52c2ac2022-03-28 17:03:35 -0700321 copyFiles(command.CopyAfter, tempDir, "", allowFromNotExists, writeType(writeIfChanged))
Colin Crossfc2d8422021-04-15 18:36:42 -0700322 }
323
Colin Cross4258a392021-04-15 18:50:11 -0700324 // If the command was executed but failed with an error, print a debugging message before
325 // the command's output so it doesn't scroll the real error message off the screen.
Jeff Gastonefc1b412017-03-29 17:29:06 -0700326 if exit, ok := err.(*exec.ExitError); ok && !exit.Success() {
Colin Cross4258a392021-04-15 18:50:11 -0700327 fmt.Fprintf(os.Stderr,
328 "The failing command was run inside an sbox sandbox in temporary directory\n"+
329 "%s\n"+
330 "The failing command line was:\n"+
331 "%s\n",
332 tempDir, rawCommand)
333 }
334
335 // Write the command's combined stdout/stderr.
336 os.Stdout.Write(buf.Bytes())
337
338 if err != nil {
Colin Crosse16ce362020-11-12 08:29:30 -0800339 return "", err
Jeff Gastonefc1b412017-03-29 17:29:06 -0700340 }
341
Colin Crosse52c2ac2022-03-28 17:03:35 -0700342 err = validateOutputFiles(command.CopyAfter, tempDir, outputDir, rawCommand)
343 if err != nil {
344 return "", err
Jeff Gastonf49082a2017-06-07 13:22:22 -0700345 }
Colin Crosse52c2ac2022-03-28 17:03:35 -0700346
Jeff Gastonf49082a2017-06-07 13:22:22 -0700347 // the created files match the declared files; now move them
Colin Crosse52c2ac2022-03-28 17:03:35 -0700348 err = moveFiles(command.CopyAfter, tempDir, "", writeType(writeIfChanged))
349 if err != nil {
350 return "", err
351 }
Colin Crosse16ce362020-11-12 08:29:30 -0800352
353 return depFile, nil
354}
355
356// makeOutputDirs creates directories in the sandbox dir for every file that has a rule to be copied
357// out of the sandbox. This emulate's Ninja's behavior of creating directories for output files
358// so that the tools don't have to.
359func makeOutputDirs(copies []*sbox_proto.Copy, sandboxDir string) error {
360 for _, copyPair := range copies {
361 dir := joinPath(sandboxDir, filepath.Dir(copyPair.GetFrom()))
362 err := os.MkdirAll(dir, 0777)
363 if err != nil {
364 return err
Jeff Gaston193f2fb2017-06-12 15:00:12 -0700365 }
Colin Crosse16ce362020-11-12 08:29:30 -0800366 }
367 return nil
368}
369
370// validateOutputFiles verifies that all files that have a rule to be copied out of the sandbox
371// were created by the command.
Colin Crosse52c2ac2022-03-28 17:03:35 -0700372func validateOutputFiles(copies []*sbox_proto.Copy, sandboxDir, outputDir, rawCommand string) error {
Colin Crosse16ce362020-11-12 08:29:30 -0800373 var missingOutputErrors []error
Colin Crosse52c2ac2022-03-28 17:03:35 -0700374 var incorrectOutputDirectoryErrors []error
Colin Crosse16ce362020-11-12 08:29:30 -0800375 for _, copyPair := range copies {
376 fromPath := joinPath(sandboxDir, copyPair.GetFrom())
377 fileInfo, err := os.Stat(fromPath)
378 if err != nil {
379 missingOutputErrors = append(missingOutputErrors, fmt.Errorf("%s: does not exist", fromPath))
380 continue
381 }
382 if fileInfo.IsDir() {
383 missingOutputErrors = append(missingOutputErrors, fmt.Errorf("%s: not a file", fromPath))
384 }
Colin Crosse52c2ac2022-03-28 17:03:35 -0700385
386 toPath := copyPair.GetTo()
387 if rel, err := filepath.Rel(outputDir, toPath); err != nil {
388 return err
389 } else if strings.HasPrefix(rel, "../") {
390 incorrectOutputDirectoryErrors = append(incorrectOutputDirectoryErrors,
391 fmt.Errorf("%s is not under %s", toPath, outputDir))
392 }
Colin Crosse16ce362020-11-12 08:29:30 -0800393 }
Colin Crosse52c2ac2022-03-28 17:03:35 -0700394
395 const maxErrors = 10
396
397 if len(incorrectOutputDirectoryErrors) > 0 {
398 errorMessage := ""
399 more := 0
400 if len(incorrectOutputDirectoryErrors) > maxErrors {
401 more = len(incorrectOutputDirectoryErrors) - maxErrors
402 incorrectOutputDirectoryErrors = incorrectOutputDirectoryErrors[:maxErrors]
403 }
404
405 for _, err := range incorrectOutputDirectoryErrors {
406 errorMessage += err.Error() + "\n"
407 }
408 if more > 0 {
409 errorMessage += fmt.Sprintf("...%v more", more)
410 }
411
412 return errors.New(errorMessage)
413 }
414
415 if len(missingOutputErrors) > 0 {
416 // find all created files for making a more informative error message
417 createdFiles := findAllFilesUnder(sandboxDir)
418
419 // build error message
420 errorMessage := "mismatch between declared and actual outputs\n"
421 errorMessage += "in sbox command(" + rawCommand + ")\n\n"
422 errorMessage += "in sandbox " + sandboxDir + ",\n"
423 errorMessage += fmt.Sprintf("failed to create %v files:\n", len(missingOutputErrors))
424 for _, missingOutputError := range missingOutputErrors {
425 errorMessage += " " + missingOutputError.Error() + "\n"
426 }
427 if len(createdFiles) < 1 {
428 errorMessage += "created 0 files."
429 } else {
430 errorMessage += fmt.Sprintf("did create %v files:\n", len(createdFiles))
431 creationMessages := createdFiles
432 if len(creationMessages) > maxErrors {
433 creationMessages = creationMessages[:maxErrors]
434 creationMessages = append(creationMessages, fmt.Sprintf("...%v more", len(createdFiles)-maxErrors))
435 }
436 for _, creationMessage := range creationMessages {
437 errorMessage += " " + creationMessage + "\n"
438 }
439 }
440
441 return errors.New(errorMessage)
442 }
443
444 return nil
Colin Crosse16ce362020-11-12 08:29:30 -0800445}
446
Colin Crosse52c2ac2022-03-28 17:03:35 -0700447type existsType bool
448
449const (
450 requireFromExists existsType = false
451 allowFromNotExists = true
452)
453
454type writeType bool
455
456const (
457 alwaysWrite writeType = false
458 onlyWriteIfChanged = true
459)
460
461// copyFiles copies files in or out of the sandbox. If exists is allowFromNotExists then errors
462// caused by a from path not existing are ignored. If write is onlyWriteIfChanged then the output
463// file is compared to the input file and not written to if it is the same, avoiding updating
464// the timestamp.
465func copyFiles(copies []*sbox_proto.Copy, fromDir, toDir string, exists existsType, write writeType) error {
Colin Crosse16ce362020-11-12 08:29:30 -0800466 for _, copyPair := range copies {
467 fromPath := joinPath(fromDir, copyPair.GetFrom())
468 toPath := joinPath(toDir, copyPair.GetTo())
Colin Crosse52c2ac2022-03-28 17:03:35 -0700469 err := copyOneFile(fromPath, toPath, copyPair.GetExecutable(), exists, write)
Colin Crosse16ce362020-11-12 08:29:30 -0800470 if err != nil {
471 return fmt.Errorf("error copying %q to %q: %w", fromPath, toPath, err)
472 }
473 }
474 return nil
475}
476
Colin Crossfc2d8422021-04-15 18:36:42 -0700477// copyOneFile copies a file and its permissions. If forceExecutable is true it adds u+x to the
Colin Crosse52c2ac2022-03-28 17:03:35 -0700478// permissions. If exists is allowFromNotExists it returns nil if the from path doesn't exist.
479// If write is onlyWriteIfChanged then the output file is compared to the input file and not written to
480// if it is the same, avoiding updating the timestamp.
481func copyOneFile(from string, to string, forceExecutable bool, exists existsType,
482 write writeType) error {
Colin Crosse16ce362020-11-12 08:29:30 -0800483 err := os.MkdirAll(filepath.Dir(to), 0777)
484 if err != nil {
485 return err
486 }
487
Colin Crosse16ce362020-11-12 08:29:30 -0800488 stat, err := os.Stat(from)
489 if err != nil {
Colin Crosse52c2ac2022-03-28 17:03:35 -0700490 if os.IsNotExist(err) && exists == allowFromNotExists {
Colin Crossfc2d8422021-04-15 18:36:42 -0700491 return nil
492 }
Colin Crosse16ce362020-11-12 08:29:30 -0800493 return err
494 }
495
496 perm := stat.Mode()
Colin Crossfc2d8422021-04-15 18:36:42 -0700497 if forceExecutable {
Colin Cross859dfd92020-11-30 20:12:47 -0800498 perm = perm | 0100 // u+x
499 }
Colin Crosse16ce362020-11-12 08:29:30 -0800500
Colin Crosse52c2ac2022-03-28 17:03:35 -0700501 if write == onlyWriteIfChanged && filesHaveSameContents(from, to) {
502 return nil
503 }
504
Colin Crosse16ce362020-11-12 08:29:30 -0800505 in, err := os.Open(from)
506 if err != nil {
507 return err
508 }
509 defer in.Close()
510
Colin Cross607c0b72021-03-31 12:54:06 -0700511 // Remove the target before copying. In most cases the file won't exist, but if there are
512 // duplicate copy rules for a file and the source file was read-only the second copy could
513 // fail.
514 err = os.Remove(to)
515 if err != nil && !os.IsNotExist(err) {
516 return err
517 }
518
Colin Crosse16ce362020-11-12 08:29:30 -0800519 out, err := os.Create(to)
520 if err != nil {
521 return err
522 }
523 defer func() {
524 out.Close()
525 if err != nil {
526 os.Remove(to)
527 }
528 }()
529
530 _, err = io.Copy(out, in)
531 if err != nil {
532 return err
533 }
534
535 if err = out.Close(); err != nil {
536 return err
537 }
538
539 if err = os.Chmod(to, perm); err != nil {
540 return err
541 }
542
543 return nil
544}
545
Colin Crosse55bd422021-03-23 13:44:30 -0700546// copyRspFiles copies rsp files into the sandbox with path mappings, and also copies the files
547// listed into the sandbox.
548func copyRspFiles(rspFiles []*sbox_proto.RspFile, toDir, toDirInSandbox string) error {
549 for _, rspFile := range rspFiles {
550 err := copyOneRspFile(rspFile, toDir, toDirInSandbox)
551 if err != nil {
552 return err
553 }
554 }
555 return nil
556}
557
558// copyOneRspFiles copies an rsp file into the sandbox with path mappings, and also copies the files
559// listed into the sandbox.
560func copyOneRspFile(rspFile *sbox_proto.RspFile, toDir, toDirInSandbox string) error {
561 in, err := os.Open(rspFile.GetFile())
562 if err != nil {
563 return err
564 }
565 defer in.Close()
566
567 files, err := response.ReadRspFile(in)
568 if err != nil {
569 return err
570 }
571
572 for i, from := range files {
573 // Convert the real path of the input file into the path inside the sandbox using the
574 // path mappings.
575 to := applyPathMappings(rspFile.PathMappings, from)
576
577 // Copy the file into the sandbox.
Colin Crosse52c2ac2022-03-28 17:03:35 -0700578 err := copyOneFile(from, joinPath(toDir, to), false, requireFromExists, alwaysWrite)
Colin Crosse55bd422021-03-23 13:44:30 -0700579 if err != nil {
580 return err
581 }
582
583 // Rewrite the name in the list of files to be relative to the sandbox directory.
584 files[i] = joinPath(toDirInSandbox, to)
585 }
586
587 // Convert the real path of the rsp file into the path inside the sandbox using the path
588 // mappings.
589 outRspFile := joinPath(toDir, applyPathMappings(rspFile.PathMappings, rspFile.GetFile()))
590
591 err = os.MkdirAll(filepath.Dir(outRspFile), 0777)
592 if err != nil {
593 return err
594 }
595
596 out, err := os.Create(outRspFile)
597 if err != nil {
598 return err
599 }
600 defer out.Close()
601
602 // Write the rsp file with converted paths into the sandbox.
603 err = response.WriteRspFile(out, files)
604 if err != nil {
605 return err
606 }
607
608 return nil
609}
610
611// applyPathMappings takes a list of path mappings and a path, and returns the path with the first
612// matching path mapping applied. If the path does not match any of the path mappings then it is
613// returned unmodified.
614func applyPathMappings(pathMappings []*sbox_proto.PathMapping, path string) string {
615 for _, mapping := range pathMappings {
616 if strings.HasPrefix(path, mapping.GetFrom()+"/") {
617 return joinPath(mapping.GetTo()+"/", strings.TrimPrefix(path, mapping.GetFrom()+"/"))
618 }
619 }
620 return path
621}
622
Colin Crosse16ce362020-11-12 08:29:30 -0800623// moveFiles moves files specified by a set of copy rules. It uses os.Rename, so it is restricted
624// to moving files where the source and destination are in the same filesystem. This is OK for
Colin Crosse52c2ac2022-03-28 17:03:35 -0700625// sbox because the temporary directory is inside the out directory. If write is onlyWriteIfChanged
626// then the output file is compared to the input file and not written to if it is the same, avoiding
627// updating the timestamp. Otherwise it always updates the timestamp of the new file.
628func moveFiles(copies []*sbox_proto.Copy, fromDir, toDir string, write writeType) error {
Colin Crosse16ce362020-11-12 08:29:30 -0800629 for _, copyPair := range copies {
630 fromPath := joinPath(fromDir, copyPair.GetFrom())
631 toPath := joinPath(toDir, copyPair.GetTo())
632 err := os.MkdirAll(filepath.Dir(toPath), 0777)
633 if err != nil {
634 return err
635 }
636
Colin Crosse52c2ac2022-03-28 17:03:35 -0700637 if write == onlyWriteIfChanged && filesHaveSameContents(fromPath, toPath) {
638 continue
639 }
640
Colin Crosse16ce362020-11-12 08:29:30 -0800641 err = os.Rename(fromPath, toPath)
Jeff Gaston8a88db52017-11-06 13:33:14 -0800642 if err != nil {
643 return err
644 }
Colin Crossd1c1e6f2019-03-29 13:54:39 -0700645
646 // Update the timestamp of the output file in case the tool wrote an old timestamp (for example, tar can extract
647 // files with old timestamps).
648 now := time.Now()
Colin Crosse16ce362020-11-12 08:29:30 -0800649 err = os.Chtimes(toPath, now, now)
Jeff Gastonefc1b412017-03-29 17:29:06 -0700650 if err != nil {
651 return err
652 }
653 }
Jeff Gastonefc1b412017-03-29 17:29:06 -0700654 return nil
655}
Colin Crosse16ce362020-11-12 08:29:30 -0800656
Colin Crosse52c2ac2022-03-28 17:03:35 -0700657// clearOutputDirectory removes all files in the output directory if write is alwaysWrite, or
658// any files not listed in copies if write is onlyWriteIfChanged
659func clearOutputDirectory(copies []*sbox_proto.Copy, outputDir string, write writeType) error {
660 if outputDir == "" {
661 return fmt.Errorf("output directory must be set")
662 }
663
664 if write == alwaysWrite {
665 // When writing all the output files remove the whole output directory
666 return os.RemoveAll(outputDir)
667 }
668
669 outputFiles := make(map[string]bool, len(copies))
670 for _, copyPair := range copies {
671 outputFiles[copyPair.GetTo()] = true
672 }
673
674 existingFiles := findAllFilesUnder(outputDir)
675 for _, existingFile := range existingFiles {
676 fullExistingFile := filepath.Join(outputDir, existingFile)
677 if !outputFiles[fullExistingFile] {
678 err := os.Remove(fullExistingFile)
679 if err != nil {
680 return fmt.Errorf("failed to remove obsolete output file %s: %w", fullExistingFile, err)
681 }
682 }
683 }
684
685 return nil
686}
687
Colin Crosse16ce362020-11-12 08:29:30 -0800688// Rewrite one or more depfiles so that it doesn't include the (randomized) sandbox directory
689// to an output file.
690func rewriteDepFiles(ins []string, out string) error {
691 var mergedDeps []string
692 for _, in := range ins {
693 data, err := ioutil.ReadFile(in)
694 if err != nil {
695 return err
696 }
697
698 deps, err := makedeps.Parse(in, bytes.NewBuffer(data))
699 if err != nil {
700 return err
701 }
702 mergedDeps = append(mergedDeps, deps.Inputs...)
703 }
704
705 deps := makedeps.Deps{
706 // Ninja doesn't care what the output file is, so we can use any string here.
707 Output: "outputfile",
708 Inputs: mergedDeps,
709 }
710
711 // Make the directory for the output depfile in case it is in a different directory
712 // than any of the output files.
713 outDir := filepath.Dir(out)
714 err := os.MkdirAll(outDir, 0777)
715 if err != nil {
716 return fmt.Errorf("failed to create %q: %w", outDir, err)
717 }
718
719 return ioutil.WriteFile(out, deps.Print(), 0666)
720}
721
722// joinPath wraps filepath.Join but returns file without appending to dir if file is
723// absolute.
724func joinPath(dir, file string) string {
725 if filepath.IsAbs(file) {
726 return file
727 }
728 return filepath.Join(dir, file)
729}
Colin Crossc590ec42021-03-11 17:20:02 -0800730
Colin Crosse52c2ac2022-03-28 17:03:35 -0700731// filesHaveSameContents compares the contents if two files, returning true if they are the same
732// and returning false if they are different or any errors occur.
733func filesHaveSameContents(a, b string) bool {
734 // Compare the sizes of the two files
735 statA, err := os.Stat(a)
736 if err != nil {
737 return false
738 }
739 statB, err := os.Stat(b)
740 if err != nil {
741 return false
742 }
743
744 if statA.Size() != statB.Size() {
745 return false
746 }
747
748 // Open the two files
749 fileA, err := os.Open(a)
750 if err != nil {
751 return false
752 }
753 defer fileA.Close()
754 fileB, err := os.Open(a)
755 if err != nil {
756 return false
757 }
758 defer fileB.Close()
759
760 // Compare the files 1MB at a time
761 const bufSize = 1 * 1024 * 1024
762 bufA := make([]byte, bufSize)
763 bufB := make([]byte, bufSize)
764
765 remain := statA.Size()
766 for remain > 0 {
767 toRead := int64(bufSize)
768 if toRead > remain {
769 toRead = remain
770 }
771
772 _, err = io.ReadFull(fileA, bufA[:toRead])
773 if err != nil {
774 return false
775 }
776 _, err = io.ReadFull(fileB, bufB[:toRead])
777 if err != nil {
778 return false
779 }
780
781 if bytes.Compare(bufA[:toRead], bufB[:toRead]) != 0 {
782 return false
783 }
784
785 remain -= toRead
786 }
787
788 return true
789}
790
Colin Crossc590ec42021-03-11 17:20:02 -0800791func makeAbsPathEnv(pathEnv string) (string, error) {
792 pathEnvElements := filepath.SplitList(pathEnv)
793 for i, p := range pathEnvElements {
794 if !filepath.IsAbs(p) {
795 absPath, err := filepath.Abs(p)
796 if err != nil {
797 return "", fmt.Errorf("failed to make PATH entry %q absolute: %w", p, err)
798 }
799 pathEnvElements[i] = absPath
800 }
801 }
802 return strings.Join(pathEnvElements, string(filepath.ListSeparator)), nil
803}