1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
|
// Copyright 2015 syzkaller project authors. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
package osutil
import (
"fmt"
"io"
"os"
"path/filepath"
)
// CopyFile atomically copies oldFile to newFile preserving permissions and modification time.
func CopyFile(oldFile, newFile string) error {
oldf, err := os.Open(oldFile)
if err != nil {
return err
}
defer oldf.Close()
stat, err := oldf.Stat()
if err != nil {
return err
}
tmpFile := newFile + ".tmp"
newf, err := os.OpenFile(tmpFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, stat.Mode()&os.ModePerm)
if err != nil {
return err
}
defer newf.Close()
_, err = io.Copy(newf, oldf)
if err != nil {
return err
}
if err := newf.Close(); err != nil {
return err
}
if err := os.Chtimes(tmpFile, stat.ModTime(), stat.ModTime()); err != nil {
return err
}
return os.Rename(tmpFile, newFile)
}
// Rename is similar to os.Rename but handles cross-device renaming (by copying).
func Rename(oldFile, newFile string) error {
err := os.Rename(oldFile, newFile)
if err != nil {
// Can't use syscall.EXDEV because this is used in appengine app.
err = CopyFile(oldFile, newFile)
os.Remove(oldFile)
}
return err
}
// FillDirectory is used to fill in directory structure for tests.
func FillDirectory(dir string, fileContent map[string]string) error {
for path, content := range fileContent {
fullPath := filepath.Join(dir, path)
dirPath := filepath.Dir(fullPath)
if err := MkdirAll(dirPath); err != nil {
return fmt.Errorf("mkdir %q failed: %w", dirPath, err)
}
if err := WriteFile(fullPath, []byte(content)); err != nil {
return fmt.Errorf("write file failed: %w", err)
}
}
return nil
}
// WriteTempFile writes data to a temp file and returns its name.
func WriteTempFile(data []byte) (string, error) {
// Note: pkg/report knows about "syzkaller" prefix as it appears in crashes as process name.
f, err := os.CreateTemp("", "syzkaller")
if err != nil {
return "", fmt.Errorf("failed to create a temp file: %w", err)
}
if _, err := f.Write(data); err != nil {
f.Close()
os.Remove(f.Name())
return "", fmt.Errorf("failed to write a temp file: %w", err)
}
f.Close()
return f.Name(), nil
}
|