summaryrefslogtreecommitdiff
path: root/internal/syscallcompat/sys_common_test.go
blob: 455774face3d2064c20cab951478c22fc84bc2c0 (plain)
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
84
85
86
87
88
package syscallcompat

import (
	"bytes"
	"os"
	"syscall"
	"testing"
)

func TestReadlinkat(t *testing.T) {
	for _, targetLen := range []int{100, 500, 4000} {
		target := string(bytes.Repeat([]byte("x"), targetLen))
		err := syscall.Symlink(target, tmpDir+"/readlinkat")
		if err != nil {
			if targetLen > 1000 {
				// Symlinks longer than 1024 (?) bytes are not supported on
				// MacOS and XFS
				t.Logf("skipping targetLen=%d: %v", targetLen, err)
				continue
			}
			t.Fatalf("targetLen=%d: %v", targetLen, err)
		}
		target2, err := Readlinkat(tmpDirFd, "readlinkat")
		if err != nil {
			t.Fatal(err)
		}
		if target != target2 {
			t.Errorf("target=%q != target2=%q", target, target2)
		}
		err = syscall.Unlink(tmpDir + "/readlinkat")
		if err != nil {
			t.Fatal(err)
		}
	}
}

func TestFchmodat(t *testing.T) {
	regular := "TestFchmodat_Regular"
	f, err := os.OpenFile(tmpDir+"/"+regular, os.O_CREATE|os.O_WRONLY, 0000)
	if err != nil {
		t.Fatal(err)
	}
	f.Close()
	symlink := "TestFchmodat_Symlink"
	err = syscall.Symlink(regular, tmpDir+"/"+symlink)
	if err != nil {
		t.Fatal(err)
	}
	dirfd, err := syscall.Open(tmpDir, syscall.O_RDONLY, 0)
	if err != nil {
		t.Fatal(err)
	}
	defer syscall.Close(dirfd)

	// Check that chmod on a regular file works ok
	err = Fchmodat(dirfd, regular, 0111, 0)
	if err != nil {
		t.Fatal(err)
	}
	var st syscall.Stat_t
	syscall.Lstat(tmpDir+"/"+regular, &st)
	st.Mode &= 0777
	if st.Mode != 0111 {
		t.Errorf("wrong mode: %#0o", st.Mode)
	}
	err = Fchmodat(dirfd, regular, 0000, 0)
	if err != nil {
		t.Error(err)
	}
	syscall.Lstat(tmpDir+"/"+regular, &st)
	st.Mode &= 0777
	if st.Mode != 0000 {
		t.Errorf("wrong mode: %#0o", st.Mode)
	}

	// Check what happens on a symlink
	err = Fchmodat(dirfd, symlink, 0333, 0)
	if err == nil {
		syscall.Lstat(tmpDir+"/"+symlink, &st)
		st.Mode &= 0777
		t.Errorf("chmod on symlink should have failed, but did not. New mode=%#0o", st.Mode)
	}
	syscall.Lstat(tmpDir+"/"+regular, &st)
	st.Mode &= 0777
	if st.Mode != 0000 {
		t.Errorf("chmod on symlink affected symlink target: New mode=%#0o", st.Mode)
	}
}