1 // Copyright 2013 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // +build darwin dragonfly freebsd linux netbsd openbsd solaris
21 "golang.org/x/sys/unix"
24 // Tests that below functions, structures and constants are consistent
25 // on all Unix-like systems.
27 // program scheduling priority functions and constants
29 _ func(int, int, int) error = unix.Setpriority
30 _ func(int, int) (int, error) = unix.Getpriority
33 _ int = unix.PRIO_USER
34 _ int = unix.PRIO_PROCESS
35 _ int = unix.PRIO_PGRP
41 _ int = unix.TCIOFLUSH
45 // fcntl file locking structure and constants
62 // TestFcntlFlock tests whether the file locking structure matches
63 // the calling convention of each kernel.
64 func TestFcntlFlock(t *testing.T) {
65 name := filepath.Join(os.TempDir(), "TestFcntlFlock")
66 fd, err := unix.Open(name, unix.O_CREAT|unix.O_RDWR|unix.O_CLOEXEC, 0)
68 t.Fatalf("Open failed: %v", err)
70 defer unix.Unlink(name)
72 flock := unix.Flock_t{
74 Start: 0, Len: 0, Whence: 1,
76 if err := unix.FcntlFlock(uintptr(fd), unix.F_GETLK, &flock); err != nil {
77 t.Fatalf("FcntlFlock failed: %v", err)
81 // TestPassFD tests passing a file descriptor over a Unix socket.
83 // This test involved both a parent and child process. The parent
84 // process is invoked as a normal test, with "go test", which then
85 // runs the child process by running the current test binary with args
86 // "-test.run=^TestPassFD$" and an environment variable used to signal
87 // that the test should become the child process instead.
88 func TestPassFD(t *testing.T) {
89 if os.Getenv("GO_WANT_HELPER_PROCESS") == "1" {
94 tempDir, err := ioutil.TempDir("", "TestPassFD")
98 defer os.RemoveAll(tempDir)
100 fds, err := unix.Socketpair(unix.AF_LOCAL, unix.SOCK_STREAM, 0)
102 t.Fatalf("Socketpair: %v", err)
104 defer unix.Close(fds[0])
105 defer unix.Close(fds[1])
106 writeFile := os.NewFile(uintptr(fds[0]), "child-writes")
107 readFile := os.NewFile(uintptr(fds[1]), "parent-reads")
108 defer writeFile.Close()
109 defer readFile.Close()
111 cmd := exec.Command(os.Args[0], "-test.run=^TestPassFD$", "--", tempDir)
112 cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"}
113 if lp := os.Getenv("LD_LIBRARY_PATH"); lp != "" {
114 cmd.Env = append(cmd.Env, "LD_LIBRARY_PATH="+lp)
116 cmd.ExtraFiles = []*os.File{writeFile}
118 out, err := cmd.CombinedOutput()
119 if len(out) > 0 || err != nil {
120 t.Fatalf("child process: %q, %v", out, err)
123 c, err := net.FileConn(readFile)
125 t.Fatalf("FileConn: %v", err)
129 uc, ok := c.(*net.UnixConn)
131 t.Fatalf("unexpected FileConn type; expected UnixConn, got %T", c)
134 buf := make([]byte, 32) // expect 1 byte
135 oob := make([]byte, 32) // expect 24 bytes
136 closeUnix := time.AfterFunc(5*time.Second, func() {
137 t.Logf("timeout reading from unix socket")
140 _, oobn, _, _, err := uc.ReadMsgUnix(buf, oob)
143 scms, err := unix.ParseSocketControlMessage(oob[:oobn])
145 t.Fatalf("ParseSocketControlMessage: %v", err)
148 t.Fatalf("expected 1 SocketControlMessage; got scms = %#v", scms)
151 gotFds, err := unix.ParseUnixRights(&scm)
153 t.Fatalf("unix.ParseUnixRights: %v", err)
155 if len(gotFds) != 1 {
156 t.Fatalf("wanted 1 fd; got %#v", gotFds)
159 f := os.NewFile(uintptr(gotFds[0]), "fd-from-child")
162 got, err := ioutil.ReadAll(f)
163 want := "Hello from child process!\n"
164 if string(got) != want {
165 t.Errorf("child process ReadAll: %q, %v; want %q", got, err, want)
169 // passFDChild is the child process used by TestPassFD.
173 // Look for our fd. It should be fd 3, but we work around an fd leak
174 // bug here (http://golang.org/issue/2603) to let it be elsewhere.
176 for fd := uintptr(3); fd <= 10; fd++ {
177 f := os.NewFile(fd, "unix-conn")
179 netc, _ := net.FileConn(f)
180 uc, ok = netc.(*net.UnixConn)
186 fmt.Println("failed to find unix fd")
190 // Make a file f to send to our parent process on uc.
191 // We make it in tempDir, which our parent will clean up.
193 tempDir := flag.Arg(0)
194 f, err := ioutil.TempFile(tempDir, "")
196 fmt.Printf("TempFile: %v", err)
200 f.Write([]byte("Hello from child process!\n"))
203 rights := unix.UnixRights(int(f.Fd()))
204 dummyByte := []byte("x")
205 n, oobn, err := uc.WriteMsgUnix(dummyByte, rights, nil)
207 fmt.Printf("WriteMsgUnix: %v", err)
210 if n != 1 || oobn != len(rights) {
211 fmt.Printf("WriteMsgUnix = %d, %d; want 1, %d", n, oobn, len(rights))
216 // TestUnixRightsRoundtrip tests that UnixRights, ParseSocketControlMessage,
217 // and ParseUnixRights are able to successfully round-trip lists of file descriptors.
218 func TestUnixRightsRoundtrip(t *testing.T) {
219 testCases := [...][][]int{
224 {{1, 2}, {3, 4, 5}, {}, {7}},
226 for _, testCase := range testCases {
229 for _, fds := range testCase {
230 // Last assignment to n wins
231 n = len(b) + unix.CmsgLen(4*len(fds))
232 b = append(b, unix.UnixRights(fds...)...)
237 scms, err := unix.ParseSocketControlMessage(b)
239 t.Fatalf("ParseSocketControlMessage: %v", err)
241 if len(scms) != len(testCase) {
242 t.Fatalf("expected %v SocketControlMessage; got scms = %#v", len(testCase), scms)
244 for i, scm := range scms {
245 gotFds, err := unix.ParseUnixRights(&scm)
247 t.Fatalf("ParseUnixRights: %v", err)
249 wantFds := testCase[i]
250 if len(gotFds) != len(wantFds) {
251 t.Fatalf("expected %v fds, got %#v", len(wantFds), gotFds)
253 for j, fd := range gotFds {
254 if fd != wantFds[j] {
255 t.Fatalf("expected fd %v, got %v", wantFds[j], fd)
262 func TestRlimit(t *testing.T) {
263 var rlimit, zero unix.Rlimit
264 err := unix.Getrlimit(unix.RLIMIT_NOFILE, &rlimit)
266 t.Fatalf("Getrlimit: save failed: %v", err)
269 t.Fatalf("Getrlimit: save failed: got zero value %#v", rlimit)
272 set.Cur = set.Max - 1
273 err = unix.Setrlimit(unix.RLIMIT_NOFILE, &set)
275 t.Fatalf("Setrlimit: set failed: %#v %v", set, err)
278 err = unix.Getrlimit(unix.RLIMIT_NOFILE, &get)
280 t.Fatalf("Getrlimit: get failed: %v", err)
283 set.Cur = set.Max - 1
285 // Seems like Darwin requires some privilege to
286 // increase the soft limit of rlimit sandbox, though
287 // Setrlimit never reports an error.
288 switch runtime.GOOS {
291 t.Fatalf("Rlimit: change failed: wanted %#v got %#v", set, get)
294 err = unix.Setrlimit(unix.RLIMIT_NOFILE, &rlimit)
296 t.Fatalf("Setrlimit: restore failed: %#v %v", rlimit, err)
300 func TestSeekFailure(t *testing.T) {
301 _, err := unix.Seek(-1, 0, 0)
303 t.Fatalf("Seek(-1, 0, 0) did not fail")
305 str := err.Error() // used to crash on Linux
306 t.Logf("Seek: %v", str)
308 t.Fatalf("Seek(-1, 0, 0) return error with empty message")
312 func TestDup(t *testing.T) {
313 file, err := ioutil.TempFile("", "TestDup")
315 t.Fatalf("Tempfile failed: %v", err)
317 defer os.Remove(file.Name())
321 newFd, err := unix.Dup(f)
323 t.Fatalf("Dup: %v", err)
326 err = unix.Dup2(newFd, newFd+1)
328 t.Fatalf("Dup2: %v", err)
331 b1 := []byte("Test123")
332 b2 := make([]byte, 7)
333 _, err = unix.Write(newFd+1, b1)
335 t.Fatalf("Write to dup2 fd failed: %v", err)
337 _, err = unix.Seek(f, 0, 0)
338 _, err = unix.Read(f, b2)
340 t.Fatalf("Read back failed: %v", err)
342 if string(b1) != string(b2) {
343 t.Errorf("Dup: stdout write not in file, expected %v, got %v", string(b1), string(b2))