blob: 7bd086882ecf423f0444f1ad61bf26e7968e7ac4 [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
37 "github.com/golang/protobuf/proto"
Jeff Gastonefc1b412017-03-29 17:29:06 -070038)
39
Jeff Gaston93f0f372017-11-01 13:33:02 -070040var (
41 sandboxesRoot string
Colin Crosse16ce362020-11-12 08:29:30 -080042 manifestFile string
Jeff Gaston93f0f372017-11-01 13:33:02 -070043 keepOutDir bool
Colin Crosse16ce362020-11-12 08:29:30 -080044)
45
46const (
47 depFilePlaceholder = "__SBOX_DEPFILE__"
48 sandboxDirPlaceholder = "__SBOX_SANDBOX_DIR__"
Jeff Gaston93f0f372017-11-01 13:33:02 -070049)
50
51func init() {
52 flag.StringVar(&sandboxesRoot, "sandbox-path", "",
53 "root of temp directory to put the sandbox into")
Colin Crosse16ce362020-11-12 08:29:30 -080054 flag.StringVar(&manifestFile, "manifest", "",
55 "textproto manifest describing the sandboxed command(s)")
Jeff Gaston93f0f372017-11-01 13:33:02 -070056 flag.BoolVar(&keepOutDir, "keep-out-dir", false,
57 "whether to keep the sandbox directory when done")
Jeff Gaston93f0f372017-11-01 13:33:02 -070058}
59
60func usageViolation(violation string) {
61 if violation != "" {
62 fmt.Fprintf(os.Stderr, "Usage error: %s.\n\n", violation)
63 }
64
65 fmt.Fprintf(os.Stderr,
Colin Crosse16ce362020-11-12 08:29:30 -080066 "Usage: sbox --manifest <manifest> --sandbox-path <sandboxPath>\n")
Jeff Gaston93f0f372017-11-01 13:33:02 -070067
68 flag.PrintDefaults()
69
70 os.Exit(1)
71}
72
Jeff Gastonefc1b412017-03-29 17:29:06 -070073func main() {
Jeff Gaston93f0f372017-11-01 13:33:02 -070074 flag.Usage = func() {
75 usageViolation("")
76 }
77 flag.Parse()
78
Jeff Gastonefc1b412017-03-29 17:29:06 -070079 error := run()
80 if error != nil {
81 fmt.Fprintln(os.Stderr, error)
82 os.Exit(1)
83 }
84}
85
Jeff Gaston90cfb092017-09-26 16:46:10 -070086func findAllFilesUnder(root string) (paths []string) {
87 paths = []string{}
88 filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
89 if !info.IsDir() {
90 relPath, err := filepath.Rel(root, path)
91 if err != nil {
92 // couldn't find relative path from ancestor?
93 panic(err)
94 }
95 paths = append(paths, relPath)
96 }
97 return nil
98 })
99 return paths
100}
101
Jeff Gastonefc1b412017-03-29 17:29:06 -0700102func run() error {
Colin Crosse16ce362020-11-12 08:29:30 -0800103 if manifestFile == "" {
104 usageViolation("--manifest <manifest> is required and must be non-empty")
Jeff Gastonefc1b412017-03-29 17:29:06 -0700105 }
Jeff Gaston02a684b2017-10-27 14:59:27 -0700106 if sandboxesRoot == "" {
Jeff Gastonefc1b412017-03-29 17:29:06 -0700107 // In practice, the value of sandboxesRoot will mostly likely be at a fixed location relative to OUT_DIR,
108 // and the sbox executable will most likely be at a fixed location relative to OUT_DIR too, so
109 // the value of sandboxesRoot will most likely be at a fixed location relative to the sbox executable
110 // However, Soong also needs to be able to separately remove the sandbox directory on startup (if it has anything left in it)
111 // and by passing it as a parameter we don't need to duplicate its value
Jeff Gaston93f0f372017-11-01 13:33:02 -0700112 usageViolation("--sandbox-path <sandboxPath> is required and must be non-empty")
Jeff Gastonefc1b412017-03-29 17:29:06 -0700113 }
Colin Crosse16ce362020-11-12 08:29:30 -0800114
115 manifest, err := readManifest(manifestFile)
116
117 if len(manifest.Commands) == 0 {
118 return fmt.Errorf("at least one commands entry is required in %q", manifestFile)
Jeff Gaston193f2fb2017-06-12 15:00:12 -0700119 }
120
Colin Crosse16ce362020-11-12 08:29:30 -0800121 // setup sandbox directory
122 err = os.MkdirAll(sandboxesRoot, 0777)
Jeff Gaston8a88db52017-11-06 13:33:14 -0800123 if err != nil {
Colin Crosse16ce362020-11-12 08:29:30 -0800124 return fmt.Errorf("failed to create %q: %w", sandboxesRoot, err)
Jeff Gaston8a88db52017-11-06 13:33:14 -0800125 }
Jeff Gastonefc1b412017-03-29 17:29:06 -0700126
Ulf Adamsb73daa52020-11-25 23:09:09 +0100127 // This tool assumes that there are no two concurrent runs with the same
128 // manifestFile. It should therefore be safe to use the hash of the
129 // manifestFile as the temporary directory name. We do this because it
130 // makes the temporary directory name deterministic. There are some
131 // tools that embed the name of the temporary output in the output, and
132 // they otherwise cause non-determinism, which then poisons actions
133 // depending on this one.
134 hash := sha1.New()
135 hash.Write([]byte(manifestFile))
136 tempDir := filepath.Join(sandboxesRoot, "sbox", hex.EncodeToString(hash.Sum(nil)))
137
138 err = os.RemoveAll(tempDir)
139 if err != nil {
140 return err
141 }
142 err = os.MkdirAll(tempDir, 0777)
Jeff Gastonefc1b412017-03-29 17:29:06 -0700143 if err != nil {
Colin Crosse16ce362020-11-12 08:29:30 -0800144 return fmt.Errorf("failed to create temporary dir in %q: %w", sandboxesRoot, err)
Jeff Gastonefc1b412017-03-29 17:29:06 -0700145 }
146
147 // In the common case, the following line of code is what removes the sandbox
148 // If a fatal error occurs (such as if our Go process is killed unexpectedly),
Colin Crosse16ce362020-11-12 08:29:30 -0800149 // then at the beginning of the next build, Soong will wipe the temporary
150 // directory.
Jeff Gastonf49082a2017-06-07 13:22:22 -0700151 defer func() {
152 // in some cases we decline to remove the temp dir, to facilitate debugging
Jeff Gaston93f0f372017-11-01 13:33:02 -0700153 if !keepOutDir {
Jeff Gastonf49082a2017-06-07 13:22:22 -0700154 os.RemoveAll(tempDir)
155 }
156 }()
Jeff Gastonefc1b412017-03-29 17:29:06 -0700157
Colin Crosse16ce362020-11-12 08:29:30 -0800158 // If there is more than one command in the manifest use a separate directory for each one.
159 useSubDir := len(manifest.Commands) > 1
160 var commandDepFiles []string
Jeff Gastonefc1b412017-03-29 17:29:06 -0700161
Colin Crosse16ce362020-11-12 08:29:30 -0800162 for i, command := range manifest.Commands {
163 localTempDir := tempDir
164 if useSubDir {
165 localTempDir = filepath.Join(localTempDir, strconv.Itoa(i))
Jeff Gastonefc1b412017-03-29 17:29:06 -0700166 }
Colin Crosse16ce362020-11-12 08:29:30 -0800167 depFile, err := runCommand(command, localTempDir)
Jeff Gaston02a684b2017-10-27 14:59:27 -0700168 if err != nil {
Colin Crosse16ce362020-11-12 08:29:30 -0800169 // Running the command failed, keep the temporary output directory around in
170 // case a user wants to inspect it for debugging purposes. Soong will delete
171 // it at the beginning of the next build anyway.
172 keepOutDir = true
Jeff Gaston02a684b2017-10-27 14:59:27 -0700173 return err
174 }
Colin Crosse16ce362020-11-12 08:29:30 -0800175 if depFile != "" {
176 commandDepFiles = append(commandDepFiles, depFile)
177 }
178 }
179
180 outputDepFile := manifest.GetOutputDepfile()
181 if len(commandDepFiles) > 0 && outputDepFile == "" {
182 return fmt.Errorf("Sandboxed commands used %s but output depfile is not set in manifest file",
183 depFilePlaceholder)
184 }
185
186 if outputDepFile != "" {
187 // Merge the depfiles from each command in the manifest to a single output depfile.
188 err = rewriteDepFiles(commandDepFiles, outputDepFile)
189 if err != nil {
190 return fmt.Errorf("failed merging depfiles: %w", err)
191 }
192 }
193
194 return nil
195}
196
197// readManifest reads an sbox manifest from a textproto file.
198func readManifest(file string) (*sbox_proto.Manifest, error) {
199 manifestData, err := ioutil.ReadFile(file)
200 if err != nil {
201 return nil, fmt.Errorf("error reading manifest %q: %w", file, err)
202 }
203
204 manifest := sbox_proto.Manifest{}
205
206 err = proto.UnmarshalText(string(manifestData), &manifest)
207 if err != nil {
208 return nil, fmt.Errorf("error parsing manifest %q: %w", file, err)
209 }
210
211 return &manifest, nil
212}
213
214// runCommand runs a single command from a manifest. If the command references the
215// __SBOX_DEPFILE__ placeholder it returns the name of the depfile that was used.
216func runCommand(command *sbox_proto.Command, tempDir string) (depFile string, err error) {
217 rawCommand := command.GetCommand()
218 if rawCommand == "" {
219 return "", fmt.Errorf("command is required")
220 }
221
Colin Crosse55bd422021-03-23 13:44:30 -0700222 pathToTempDirInSbox := tempDir
223 if command.GetChdir() {
224 pathToTempDirInSbox = "."
225 }
226
Colin Crosse16ce362020-11-12 08:29:30 -0800227 err = os.MkdirAll(tempDir, 0777)
228 if err != nil {
229 return "", fmt.Errorf("failed to create %q: %w", tempDir, err)
230 }
231
232 // Copy in any files specified by the manifest.
Colin Crossd03797e2020-11-25 10:24:51 -0800233 err = copyFiles(command.CopyBefore, "", tempDir)
Colin Crosse16ce362020-11-12 08:29:30 -0800234 if err != nil {
235 return "", err
236 }
Colin Crosse55bd422021-03-23 13:44:30 -0700237 err = copyRspFiles(command.RspFiles, tempDir, pathToTempDirInSbox)
238 if err != nil {
239 return "", err
Colin Crossc590ec42021-03-11 17:20:02 -0800240 }
241
Colin Crosse16ce362020-11-12 08:29:30 -0800242 if strings.Contains(rawCommand, depFilePlaceholder) {
Colin Crossc590ec42021-03-11 17:20:02 -0800243 depFile = filepath.Join(pathToTempDirInSbox, "deps.d")
Colin Crosse16ce362020-11-12 08:29:30 -0800244 rawCommand = strings.Replace(rawCommand, depFilePlaceholder, depFile, -1)
245 }
246
247 if strings.Contains(rawCommand, sandboxDirPlaceholder) {
Colin Crossc590ec42021-03-11 17:20:02 -0800248 rawCommand = strings.Replace(rawCommand, sandboxDirPlaceholder, pathToTempDirInSbox, -1)
Colin Crosse16ce362020-11-12 08:29:30 -0800249 }
250
251 // Emulate ninja's behavior of creating the directories for any output files before
252 // running the command.
253 err = makeOutputDirs(command.CopyAfter, tempDir)
254 if err != nil {
255 return "", err
Jeff Gastonefc1b412017-03-29 17:29:06 -0700256 }
257
Jeff Gaston193f2fb2017-06-12 15:00:12 -0700258 commandDescription := rawCommand
259
Jeff Gastonefc1b412017-03-29 17:29:06 -0700260 cmd := exec.Command("bash", "-c", rawCommand)
261 cmd.Stdin = os.Stdin
262 cmd.Stdout = os.Stdout
263 cmd.Stderr = os.Stderr
Colin Crosse16ce362020-11-12 08:29:30 -0800264
265 if command.GetChdir() {
266 cmd.Dir = tempDir
Colin Crossc590ec42021-03-11 17:20:02 -0800267 path := os.Getenv("PATH")
268 absPath, err := makeAbsPathEnv(path)
269 if err != nil {
270 return "", err
271 }
272 err = os.Setenv("PATH", absPath)
273 if err != nil {
274 return "", fmt.Errorf("Failed to update PATH: %w", err)
275 }
Colin Crosse16ce362020-11-12 08:29:30 -0800276 }
Jeff Gastonefc1b412017-03-29 17:29:06 -0700277 err = cmd.Run()
Jeff Gaston193f2fb2017-06-12 15:00:12 -0700278
Jeff Gastonefc1b412017-03-29 17:29:06 -0700279 if exit, ok := err.(*exec.ExitError); ok && !exit.Success() {
Colin Crosse16ce362020-11-12 08:29:30 -0800280 return "", fmt.Errorf("sbox command failed with err:\n%s\n%w\n", commandDescription, err)
Jeff Gastonefc1b412017-03-29 17:29:06 -0700281 } else if err != nil {
Colin Crosse16ce362020-11-12 08:29:30 -0800282 return "", err
Jeff Gastonefc1b412017-03-29 17:29:06 -0700283 }
284
Colin Crosse16ce362020-11-12 08:29:30 -0800285 missingOutputErrors := validateOutputFiles(command.CopyAfter, tempDir)
286
Jeff Gaston90cfb092017-09-26 16:46:10 -0700287 if len(missingOutputErrors) > 0 {
288 // find all created files for making a more informative error message
289 createdFiles := findAllFilesUnder(tempDir)
290
291 // build error message
292 errorMessage := "mismatch between declared and actual outputs\n"
293 errorMessage += "in sbox command(" + commandDescription + ")\n\n"
294 errorMessage += "in sandbox " + tempDir + ",\n"
295 errorMessage += fmt.Sprintf("failed to create %v files:\n", len(missingOutputErrors))
296 for _, missingOutputError := range missingOutputErrors {
Colin Crosse16ce362020-11-12 08:29:30 -0800297 errorMessage += " " + missingOutputError.Error() + "\n"
Jeff Gaston90cfb092017-09-26 16:46:10 -0700298 }
299 if len(createdFiles) < 1 {
300 errorMessage += "created 0 files."
301 } else {
302 errorMessage += fmt.Sprintf("did create %v files:\n", len(createdFiles))
303 creationMessages := createdFiles
304 maxNumCreationLines := 10
305 if len(creationMessages) > maxNumCreationLines {
306 creationMessages = creationMessages[:maxNumCreationLines]
307 creationMessages = append(creationMessages, fmt.Sprintf("...%v more", len(createdFiles)-maxNumCreationLines))
308 }
309 for _, creationMessage := range creationMessages {
310 errorMessage += " " + creationMessage + "\n"
311 }
312 }
313
Colin Crosse16ce362020-11-12 08:29:30 -0800314 return "", errors.New(errorMessage)
Jeff Gastonf49082a2017-06-07 13:22:22 -0700315 }
316 // the created files match the declared files; now move them
Colin Crosse16ce362020-11-12 08:29:30 -0800317 err = moveFiles(command.CopyAfter, tempDir, "")
318
319 return depFile, nil
320}
321
322// makeOutputDirs creates directories in the sandbox dir for every file that has a rule to be copied
323// out of the sandbox. This emulate's Ninja's behavior of creating directories for output files
324// so that the tools don't have to.
325func makeOutputDirs(copies []*sbox_proto.Copy, sandboxDir string) error {
326 for _, copyPair := range copies {
327 dir := joinPath(sandboxDir, filepath.Dir(copyPair.GetFrom()))
328 err := os.MkdirAll(dir, 0777)
329 if err != nil {
330 return err
Jeff Gaston193f2fb2017-06-12 15:00:12 -0700331 }
Colin Crosse16ce362020-11-12 08:29:30 -0800332 }
333 return nil
334}
335
336// validateOutputFiles verifies that all files that have a rule to be copied out of the sandbox
337// were created by the command.
338func validateOutputFiles(copies []*sbox_proto.Copy, sandboxDir string) []error {
339 var missingOutputErrors []error
340 for _, copyPair := range copies {
341 fromPath := joinPath(sandboxDir, copyPair.GetFrom())
342 fileInfo, err := os.Stat(fromPath)
343 if err != nil {
344 missingOutputErrors = append(missingOutputErrors, fmt.Errorf("%s: does not exist", fromPath))
345 continue
346 }
347 if fileInfo.IsDir() {
348 missingOutputErrors = append(missingOutputErrors, fmt.Errorf("%s: not a file", fromPath))
349 }
350 }
351 return missingOutputErrors
352}
353
Colin Crossd03797e2020-11-25 10:24:51 -0800354// copyFiles copies files in or out of the sandbox.
355func copyFiles(copies []*sbox_proto.Copy, fromDir, toDir string) error {
Colin Crosse16ce362020-11-12 08:29:30 -0800356 for _, copyPair := range copies {
357 fromPath := joinPath(fromDir, copyPair.GetFrom())
358 toPath := joinPath(toDir, copyPair.GetTo())
Colin Cross859dfd92020-11-30 20:12:47 -0800359 err := copyOneFile(fromPath, toPath, copyPair.GetExecutable())
Colin Crosse16ce362020-11-12 08:29:30 -0800360 if err != nil {
361 return fmt.Errorf("error copying %q to %q: %w", fromPath, toPath, err)
362 }
363 }
364 return nil
365}
366
Colin Crossd03797e2020-11-25 10:24:51 -0800367// copyOneFile copies a file.
Colin Cross859dfd92020-11-30 20:12:47 -0800368func copyOneFile(from string, to string, executable bool) error {
Colin Crosse16ce362020-11-12 08:29:30 -0800369 err := os.MkdirAll(filepath.Dir(to), 0777)
370 if err != nil {
371 return err
372 }
373
Colin Crosse16ce362020-11-12 08:29:30 -0800374 stat, err := os.Stat(from)
375 if err != nil {
376 return err
377 }
378
379 perm := stat.Mode()
Colin Cross859dfd92020-11-30 20:12:47 -0800380 if executable {
381 perm = perm | 0100 // u+x
382 }
Colin Crosse16ce362020-11-12 08:29:30 -0800383
384 in, err := os.Open(from)
385 if err != nil {
386 return err
387 }
388 defer in.Close()
389
Colin Cross607c0b72021-03-31 12:54:06 -0700390 // Remove the target before copying. In most cases the file won't exist, but if there are
391 // duplicate copy rules for a file and the source file was read-only the second copy could
392 // fail.
393 err = os.Remove(to)
394 if err != nil && !os.IsNotExist(err) {
395 return err
396 }
397
Colin Crosse16ce362020-11-12 08:29:30 -0800398 out, err := os.Create(to)
399 if err != nil {
400 return err
401 }
402 defer func() {
403 out.Close()
404 if err != nil {
405 os.Remove(to)
406 }
407 }()
408
409 _, err = io.Copy(out, in)
410 if err != nil {
411 return err
412 }
413
414 if err = out.Close(); err != nil {
415 return err
416 }
417
418 if err = os.Chmod(to, perm); err != nil {
419 return err
420 }
421
422 return nil
423}
424
Colin Crosse55bd422021-03-23 13:44:30 -0700425// copyRspFiles copies rsp files into the sandbox with path mappings, and also copies the files
426// listed into the sandbox.
427func copyRspFiles(rspFiles []*sbox_proto.RspFile, toDir, toDirInSandbox string) error {
428 for _, rspFile := range rspFiles {
429 err := copyOneRspFile(rspFile, toDir, toDirInSandbox)
430 if err != nil {
431 return err
432 }
433 }
434 return nil
435}
436
437// copyOneRspFiles copies an rsp file into the sandbox with path mappings, and also copies the files
438// listed into the sandbox.
439func copyOneRspFile(rspFile *sbox_proto.RspFile, toDir, toDirInSandbox string) error {
440 in, err := os.Open(rspFile.GetFile())
441 if err != nil {
442 return err
443 }
444 defer in.Close()
445
446 files, err := response.ReadRspFile(in)
447 if err != nil {
448 return err
449 }
450
451 for i, from := range files {
452 // Convert the real path of the input file into the path inside the sandbox using the
453 // path mappings.
454 to := applyPathMappings(rspFile.PathMappings, from)
455
456 // Copy the file into the sandbox.
457 err := copyOneFile(from, joinPath(toDir, to), false)
458 if err != nil {
459 return err
460 }
461
462 // Rewrite the name in the list of files to be relative to the sandbox directory.
463 files[i] = joinPath(toDirInSandbox, to)
464 }
465
466 // Convert the real path of the rsp file into the path inside the sandbox using the path
467 // mappings.
468 outRspFile := joinPath(toDir, applyPathMappings(rspFile.PathMappings, rspFile.GetFile()))
469
470 err = os.MkdirAll(filepath.Dir(outRspFile), 0777)
471 if err != nil {
472 return err
473 }
474
475 out, err := os.Create(outRspFile)
476 if err != nil {
477 return err
478 }
479 defer out.Close()
480
481 // Write the rsp file with converted paths into the sandbox.
482 err = response.WriteRspFile(out, files)
483 if err != nil {
484 return err
485 }
486
487 return nil
488}
489
490// applyPathMappings takes a list of path mappings and a path, and returns the path with the first
491// matching path mapping applied. If the path does not match any of the path mappings then it is
492// returned unmodified.
493func applyPathMappings(pathMappings []*sbox_proto.PathMapping, path string) string {
494 for _, mapping := range pathMappings {
495 if strings.HasPrefix(path, mapping.GetFrom()+"/") {
496 return joinPath(mapping.GetTo()+"/", strings.TrimPrefix(path, mapping.GetFrom()+"/"))
497 }
498 }
499 return path
500}
501
Colin Crosse16ce362020-11-12 08:29:30 -0800502// moveFiles moves files specified by a set of copy rules. It uses os.Rename, so it is restricted
503// to moving files where the source and destination are in the same filesystem. This is OK for
504// sbox because the temporary directory is inside the out directory. It updates the timestamp
505// of the new file.
506func moveFiles(copies []*sbox_proto.Copy, fromDir, toDir string) error {
507 for _, copyPair := range copies {
508 fromPath := joinPath(fromDir, copyPair.GetFrom())
509 toPath := joinPath(toDir, copyPair.GetTo())
510 err := os.MkdirAll(filepath.Dir(toPath), 0777)
511 if err != nil {
512 return err
513 }
514
515 err = os.Rename(fromPath, toPath)
Jeff Gaston8a88db52017-11-06 13:33:14 -0800516 if err != nil {
517 return err
518 }
Colin Crossd1c1e6f2019-03-29 13:54:39 -0700519
520 // Update the timestamp of the output file in case the tool wrote an old timestamp (for example, tar can extract
521 // files with old timestamps).
522 now := time.Now()
Colin Crosse16ce362020-11-12 08:29:30 -0800523 err = os.Chtimes(toPath, now, now)
Jeff Gastonefc1b412017-03-29 17:29:06 -0700524 if err != nil {
525 return err
526 }
527 }
Jeff Gastonefc1b412017-03-29 17:29:06 -0700528 return nil
529}
Colin Crosse16ce362020-11-12 08:29:30 -0800530
531// Rewrite one or more depfiles so that it doesn't include the (randomized) sandbox directory
532// to an output file.
533func rewriteDepFiles(ins []string, out string) error {
534 var mergedDeps []string
535 for _, in := range ins {
536 data, err := ioutil.ReadFile(in)
537 if err != nil {
538 return err
539 }
540
541 deps, err := makedeps.Parse(in, bytes.NewBuffer(data))
542 if err != nil {
543 return err
544 }
545 mergedDeps = append(mergedDeps, deps.Inputs...)
546 }
547
548 deps := makedeps.Deps{
549 // Ninja doesn't care what the output file is, so we can use any string here.
550 Output: "outputfile",
551 Inputs: mergedDeps,
552 }
553
554 // Make the directory for the output depfile in case it is in a different directory
555 // than any of the output files.
556 outDir := filepath.Dir(out)
557 err := os.MkdirAll(outDir, 0777)
558 if err != nil {
559 return fmt.Errorf("failed to create %q: %w", outDir, err)
560 }
561
562 return ioutil.WriteFile(out, deps.Print(), 0666)
563}
564
565// joinPath wraps filepath.Join but returns file without appending to dir if file is
566// absolute.
567func joinPath(dir, file string) string {
568 if filepath.IsAbs(file) {
569 return file
570 }
571 return filepath.Join(dir, file)
572}
Colin Crossc590ec42021-03-11 17:20:02 -0800573
574func makeAbsPathEnv(pathEnv string) (string, error) {
575 pathEnvElements := filepath.SplitList(pathEnv)
576 for i, p := range pathEnvElements {
577 if !filepath.IsAbs(p) {
578 absPath, err := filepath.Abs(p)
579 if err != nil {
580 return "", fmt.Errorf("failed to make PATH entry %q absolute: %w", p, err)
581 }
582 pathEnvElements[i] = absPath
583 }
584 }
585 return strings.Join(pathEnvElements, string(filepath.ListSeparator)), nil
586}