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 aix darwin dragonfly freebsd linux netbsd openbsd solaris
23 "golang.org/x/sys/unix"
26 // Tests that below functions, structures and constants are consistent
27 // on all Unix-like systems.
29 // program scheduling priority functions and constants
31 _ func(int, int, int) error = unix.Setpriority
32 _ func(int, int) (int, error) = unix.Getpriority
35 _ int = unix.PRIO_USER
36 _ int = unix.PRIO_PROCESS
37 _ int = unix.PRIO_PGRP
43 _ int = unix.TCIOFLUSH
47 // fcntl file locking structure and constants
64 func TestErrnoSignalName(t *testing.T) {
65 testErrors := []struct {
69 {syscall.EPERM, "EPERM"},
70 {syscall.EINVAL, "EINVAL"},
71 {syscall.ENOENT, "ENOENT"},
74 for _, te := range testErrors {
75 t.Run(fmt.Sprintf("%d/%s", te.num, te.name), func(t *testing.T) {
76 e := unix.ErrnoName(te.num)
78 t.Errorf("ErrnoName(%d) returned %s, want %s", te.num, e, te.name)
83 testSignals := []struct {
87 {syscall.SIGHUP, "SIGHUP"},
88 {syscall.SIGPIPE, "SIGPIPE"},
89 {syscall.SIGSEGV, "SIGSEGV"},
92 for _, ts := range testSignals {
93 t.Run(fmt.Sprintf("%d/%s", ts.num, ts.name), func(t *testing.T) {
94 s := unix.SignalName(ts.num)
96 t.Errorf("SignalName(%d) returned %s, want %s", ts.num, s, ts.name)
102 func TestSignalNum(t *testing.T) {
103 testSignals := []struct {
107 {"SIGHUP", syscall.SIGHUP},
108 {"SIGPIPE", syscall.SIGPIPE},
109 {"SIGSEGV", syscall.SIGSEGV},
112 for _, ts := range testSignals {
113 t.Run(fmt.Sprintf("%s/%d", ts.name, ts.want), func(t *testing.T) {
114 got := unix.SignalNum(ts.name)
116 t.Errorf("SignalNum(%s) returned %d, want %d", ts.name, got, ts.want)
123 func TestFcntlInt(t *testing.T) {
125 file, err := ioutil.TempFile("", "TestFnctlInt")
129 defer os.Remove(file.Name())
132 flags, err := unix.FcntlInt(f, unix.F_GETFD, 0)
136 if flags&unix.FD_CLOEXEC == 0 {
137 t.Errorf("flags %#x do not include FD_CLOEXEC", flags)
141 // TestFcntlFlock tests whether the file locking structure matches
142 // the calling convention of each kernel.
143 func TestFcntlFlock(t *testing.T) {
144 name := filepath.Join(os.TempDir(), "TestFcntlFlock")
145 fd, err := unix.Open(name, unix.O_CREAT|unix.O_RDWR|unix.O_CLOEXEC, 0)
147 t.Fatalf("Open failed: %v", err)
149 defer unix.Unlink(name)
151 flock := unix.Flock_t{
153 Start: 0, Len: 0, Whence: 1,
155 if err := unix.FcntlFlock(uintptr(fd), unix.F_GETLK, &flock); err != nil {
156 t.Fatalf("FcntlFlock failed: %v", err)
160 // TestPassFD tests passing a file descriptor over a Unix socket.
162 // This test involved both a parent and child process. The parent
163 // process is invoked as a normal test, with "go test", which then
164 // runs the child process by running the current test binary with args
165 // "-test.run=^TestPassFD$" and an environment variable used to signal
166 // that the test should become the child process instead.
167 func TestPassFD(t *testing.T) {
168 if (runtime.GOOS == "darwin" || runtime.GOOS == "ios") && (runtime.GOARCH == "arm" || runtime.GOARCH == "arm64") {
169 t.Skip("cannot exec subprocess on iOS, skipping test")
172 if os.Getenv("GO_WANT_HELPER_PROCESS") == "1" {
177 if runtime.GOOS == "aix" {
178 // Unix network isn't properly working on AIX
179 // 7.2 with Technical Level < 2
180 out, err := exec.Command("oslevel", "-s").Output()
182 t.Skipf("skipping on AIX because oslevel -s failed: %v", err)
185 if len(out) < len("7200-XX-ZZ-YYMM") { // AIX 7.2, Tech Level XX, Service Pack ZZ, date YYMM
186 t.Skip("skipping on AIX because oslevel -s hasn't the right length")
188 aixVer := string(out[:4])
189 tl, err := strconv.Atoi(string(out[5:7]))
191 t.Skipf("skipping on AIX because oslevel -s output cannot be parsed: %v", err)
193 if aixVer < "7200" || (aixVer == "7200" && tl < 2) {
194 t.Skip("skipped on AIX versions previous to 7.2 TL 2")
198 tempDir, err := ioutil.TempDir("", "TestPassFD")
202 defer os.RemoveAll(tempDir)
204 fds, err := unix.Socketpair(unix.AF_LOCAL, unix.SOCK_STREAM, 0)
206 t.Fatalf("Socketpair: %v", err)
208 defer unix.Close(fds[0])
209 defer unix.Close(fds[1])
210 writeFile := os.NewFile(uintptr(fds[0]), "child-writes")
211 readFile := os.NewFile(uintptr(fds[1]), "parent-reads")
212 defer writeFile.Close()
213 defer readFile.Close()
215 cmd := exec.Command(os.Args[0], "-test.run=^TestPassFD$", "--", tempDir)
216 cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"}
217 if lp := os.Getenv("LD_LIBRARY_PATH"); lp != "" {
218 cmd.Env = append(cmd.Env, "LD_LIBRARY_PATH="+lp)
220 cmd.ExtraFiles = []*os.File{writeFile}
222 out, err := cmd.CombinedOutput()
223 if len(out) > 0 || err != nil {
224 t.Fatalf("child process: %q, %v", out, err)
227 c, err := net.FileConn(readFile)
229 t.Fatalf("FileConn: %v", err)
233 uc, ok := c.(*net.UnixConn)
235 t.Fatalf("unexpected FileConn type; expected UnixConn, got %T", c)
238 buf := make([]byte, 32) // expect 1 byte
239 oob := make([]byte, 32) // expect 24 bytes
240 closeUnix := time.AfterFunc(5*time.Second, func() {
241 t.Logf("timeout reading from unix socket")
244 _, oobn, _, _, err := uc.ReadMsgUnix(buf, oob)
246 t.Fatalf("ReadMsgUnix: %v", err)
250 scms, err := unix.ParseSocketControlMessage(oob[:oobn])
252 t.Fatalf("ParseSocketControlMessage: %v", err)
255 t.Fatalf("expected 1 SocketControlMessage; got scms = %#v", scms)
258 gotFds, err := unix.ParseUnixRights(&scm)
260 t.Fatalf("unix.ParseUnixRights: %v", err)
262 if len(gotFds) != 1 {
263 t.Fatalf("wanted 1 fd; got %#v", gotFds)
266 f := os.NewFile(uintptr(gotFds[0]), "fd-from-child")
269 got, err := ioutil.ReadAll(f)
270 want := "Hello from child process!\n"
271 if string(got) != want {
272 t.Errorf("child process ReadAll: %q, %v; want %q", got, err, want)
276 // passFDChild is the child process used by TestPassFD.
280 // Look for our fd. It should be fd 3, but we work around an fd leak
281 // bug here (http://golang.org/issue/2603) to let it be elsewhere.
283 for fd := uintptr(3); fd <= 10; fd++ {
284 f := os.NewFile(fd, "unix-conn")
286 netc, _ := net.FileConn(f)
287 uc, ok = netc.(*net.UnixConn)
293 fmt.Println("failed to find unix fd")
297 // Make a file f to send to our parent process on uc.
298 // We make it in tempDir, which our parent will clean up.
300 tempDir := flag.Arg(0)
301 f, err := ioutil.TempFile(tempDir, "")
303 fmt.Printf("TempFile: %v", err)
307 f.Write([]byte("Hello from child process!\n"))
310 rights := unix.UnixRights(int(f.Fd()))
311 dummyByte := []byte("x")
312 n, oobn, err := uc.WriteMsgUnix(dummyByte, rights, nil)
314 fmt.Printf("WriteMsgUnix: %v", err)
317 if n != 1 || oobn != len(rights) {
318 fmt.Printf("WriteMsgUnix = %d, %d; want 1, %d", n, oobn, len(rights))
323 // TestUnixRightsRoundtrip tests that UnixRights, ParseSocketControlMessage,
324 // and ParseUnixRights are able to successfully round-trip lists of file descriptors.
325 func TestUnixRightsRoundtrip(t *testing.T) {
326 testCases := [...][][]int{
331 {{1, 2}, {3, 4, 5}, {}, {7}},
333 for _, testCase := range testCases {
336 for _, fds := range testCase {
337 // Last assignment to n wins
338 n = len(b) + unix.CmsgLen(4*len(fds))
339 b = append(b, unix.UnixRights(fds...)...)
344 scms, err := unix.ParseSocketControlMessage(b)
346 t.Fatalf("ParseSocketControlMessage: %v", err)
348 if len(scms) != len(testCase) {
349 t.Fatalf("expected %v SocketControlMessage; got scms = %#v", len(testCase), scms)
351 for i, scm := range scms {
352 gotFds, err := unix.ParseUnixRights(&scm)
354 t.Fatalf("ParseUnixRights: %v", err)
356 wantFds := testCase[i]
357 if len(gotFds) != len(wantFds) {
358 t.Fatalf("expected %v fds, got %#v", len(wantFds), gotFds)
360 for j, fd := range gotFds {
361 if fd != wantFds[j] {
362 t.Fatalf("expected fd %v, got %v", wantFds[j], fd)
369 func TestRlimit(t *testing.T) {
370 var rlimit, zero unix.Rlimit
371 err := unix.Getrlimit(unix.RLIMIT_NOFILE, &rlimit)
373 t.Fatalf("Getrlimit: save failed: %v", err)
376 t.Fatalf("Getrlimit: save failed: got zero value %#v", rlimit)
379 set.Cur = set.Max - 1
380 if (runtime.GOOS == "darwin" || runtime.GOOS == "ios") && set.Cur > 4096 {
381 // rlim_min for RLIMIT_NOFILE should be equal to
382 // or lower than kern.maxfilesperproc, which on
383 // some machines are 4096. See #40564.
386 err = unix.Setrlimit(unix.RLIMIT_NOFILE, &set)
388 t.Fatalf("Setrlimit: set failed: %#v %v", set, err)
391 err = unix.Getrlimit(unix.RLIMIT_NOFILE, &get)
393 t.Fatalf("Getrlimit: get failed: %v", err)
396 set.Cur = set.Max - 1
397 if (runtime.GOOS == "darwin" || runtime.GOOS == "ios") && set.Cur > 4096 {
401 // Seems like Darwin requires some privilege to
402 // increase the soft limit of rlimit sandbox, though
403 // Setrlimit never reports an error.
404 switch runtime.GOOS {
405 case "darwin", "ios":
407 t.Fatalf("Rlimit: change failed: wanted %#v got %#v", set, get)
410 err = unix.Setrlimit(unix.RLIMIT_NOFILE, &rlimit)
412 t.Fatalf("Setrlimit: restore failed: %#v %v", rlimit, err)
415 // make sure RLIM_INFINITY can be assigned to Rlimit members
417 Cur: unix.RLIM_INFINITY,
418 Max: unix.RLIM_INFINITY,
422 func TestSeekFailure(t *testing.T) {
423 _, err := unix.Seek(-1, 0, 0)
425 t.Fatalf("Seek(-1, 0, 0) did not fail")
427 str := err.Error() // used to crash on Linux
428 t.Logf("Seek: %v", str)
430 t.Fatalf("Seek(-1, 0, 0) return error with empty message")
434 func TestSetsockoptString(t *testing.T) {
435 // should not panic on empty string, see issue #31277
436 err := unix.SetsockoptString(-1, 0, 0, "")
438 t.Fatalf("SetsockoptString: did not fail")
442 func TestDup(t *testing.T) {
443 file, err := ioutil.TempFile("", "TestDup")
445 t.Fatalf("Tempfile failed: %v", err)
447 defer os.Remove(file.Name())
451 newFd, err := unix.Dup(f)
453 t.Fatalf("Dup: %v", err)
456 // Create and reserve a file descriptor.
457 // Dup2 automatically closes it before reusing it.
458 nullFile, err := os.Open("/dev/null")
462 dupFd := int(file.Fd())
463 err = unix.Dup2(newFd, dupFd)
465 t.Fatalf("Dup2: %v", err)
467 // Keep the dummy file open long enough to not be closed in
469 runtime.KeepAlive(nullFile)
471 b1 := []byte("Test123")
472 b2 := make([]byte, 7)
473 _, err = unix.Write(dupFd, b1)
475 t.Fatalf("Write to dup2 fd failed: %v", err)
477 _, err = unix.Seek(f, 0, 0)
479 t.Fatalf("Seek failed: %v", err)
481 _, err = unix.Read(f, b2)
483 t.Fatalf("Read back failed: %v", err)
485 if string(b1) != string(b2) {
486 t.Errorf("Dup: stdout write not in file, expected %v, got %v", string(b1), string(b2))
490 func TestPoll(t *testing.T) {
491 if runtime.GOOS == "android" ||
492 ((runtime.GOOS == "darwin" || runtime.GOOS == "ios") && (runtime.GOARCH == "arm" || runtime.GOARCH == "arm64")) {
493 t.Skip("mkfifo syscall is not available on android and iOS, skipping test")
497 f, cleanup := mktmpfifo(t)
502 ok := make(chan bool, 1)
505 case <-time.After(10 * timeout * time.Millisecond):
506 t.Errorf("Poll: failed to timeout after %d milliseconds", 10*timeout)
511 fds := []unix.PollFd{{Fd: int32(f.Fd()), Events: unix.POLLIN}}
512 n, err := unix.Poll(fds, timeout)
515 t.Errorf("Poll: unexpected error: %v", err)
519 t.Errorf("Poll: wrong number of events: got %v, expected %v", n, 0)
524 func TestSelect(t *testing.T) {
526 n, err := unix.Select(0, nil, nil, nil, &unix.Timeval{Sec: 0, Usec: 0})
527 if err == unix.EINTR {
528 t.Logf("Select interrupted")
530 } else if err != nil {
531 t.Fatalf("Select: %v", err)
534 t.Fatalf("Select: got %v ready file descriptors, expected 0", n)
539 dur := 250 * time.Millisecond
540 var took time.Duration
542 // On some platforms (e.g. Linux), the passed-in timeval is
543 // updated by select(2). Make sure to reset to the full duration
544 // in case of an EINTR.
545 tv := unix.NsecToTimeval(int64(dur))
547 n, err := unix.Select(0, nil, nil, nil, &tv)
548 took = time.Since(start)
549 if err == unix.EINTR {
550 t.Logf("Select interrupted after %v", took)
552 } else if err != nil {
553 t.Fatalf("Select: %v", err)
556 t.Fatalf("Select: got %v ready file descriptors, expected 0", n)
561 // On some BSDs the actual timeout might also be slightly less than the requested.
562 // Add an acceptable margin to avoid flaky tests.
564 t.Errorf("Select: got %v timeout, expected at least %v", took, dur)
567 rr, ww, err := os.Pipe()
574 if _, err := ww.Write([]byte("HELLO GOPHER")); err != nil {
578 rFdSet := &unix.FdSet{}
583 n, err := unix.Select(fd+1, rFdSet, nil, nil, nil)
584 if err == unix.EINTR {
585 t.Log("Select interrupted")
587 } else if err != nil {
588 t.Fatalf("Select: %v", err)
591 t.Fatalf("Select: got %v ready file descriptors, expected 1", n)
597 func TestGetwd(t *testing.T) {
598 fd, err := os.Open(".")
600 t.Fatalf("Open .: %s", err)
603 // Directory list for test. Do not worry if any are symlinks or do not
604 // exist on some common unix desktop environments. That will be checked.
605 dirs := []string{"/", "/usr/bin", "/etc", "/var", "/opt"}
606 switch runtime.GOOS {
608 dirs = []string{"/", "/system/bin"}
609 case "darwin", "ios":
610 switch runtime.GOARCH {
612 d1, err := ioutil.TempDir("", "d1")
614 t.Fatalf("TempDir: %v", err)
616 d2, err := ioutil.TempDir("", "d2")
618 t.Fatalf("TempDir: %v", err)
620 dirs = []string{d1, d2}
623 oldwd := os.Getenv("PWD")
624 for _, d := range dirs {
625 // Check whether d exists, is a dir and that d's path does not contain a symlink
626 fi, err := os.Stat(d)
627 if err != nil || !fi.IsDir() {
628 t.Logf("Test dir %s stat error (%v) or not a directory, skipping", d, err)
631 check, err := filepath.EvalSymlinks(d)
632 if err != nil || check != d {
633 t.Logf("Test dir %s (%s) is symlink or other error (%v), skipping", d, check, err)
638 t.Fatalf("Chdir: %v", err)
640 pwd, err := unix.Getwd()
642 t.Fatalf("Getwd in %s: %s", d, err)
644 os.Setenv("PWD", oldwd)
647 // We changed the current directory and cannot go back.
648 // Don't let the tests continue; they'll scribble
649 // all over some other directory.
650 fmt.Fprintf(os.Stderr, "fchdir back to dot failed: %s\n", err)
654 t.Fatalf("Getwd returned %q want %q", pwd, d)
659 func compareStat_t(t *testing.T, otherStat string, st1, st2 *unix.Stat_t) {
660 if st2.Dev != st1.Dev {
661 t.Errorf("%s/Fstatat: got dev %v, expected %v", otherStat, st2.Dev, st1.Dev)
663 if st2.Ino != st1.Ino {
664 t.Errorf("%s/Fstatat: got ino %v, expected %v", otherStat, st2.Ino, st1.Ino)
666 if st2.Mode != st1.Mode {
667 t.Errorf("%s/Fstatat: got mode %v, expected %v", otherStat, st2.Mode, st1.Mode)
669 if st2.Uid != st1.Uid {
670 t.Errorf("%s/Fstatat: got uid %v, expected %v", otherStat, st2.Uid, st1.Uid)
672 if st2.Gid != st1.Gid {
673 t.Errorf("%s/Fstatat: got gid %v, expected %v", otherStat, st2.Gid, st1.Gid)
675 if st2.Size != st1.Size {
676 t.Errorf("%s/Fstatat: got size %v, expected %v", otherStat, st2.Size, st1.Size)
680 func TestFstatat(t *testing.T) {
686 err := unix.Stat("file1", &st1)
688 t.Fatalf("Stat: %v", err)
692 err = unix.Fstatat(unix.AT_FDCWD, "file1", &st2, 0)
694 t.Fatalf("Fstatat: %v", err)
697 compareStat_t(t, "Stat", &st1, &st2)
699 err = os.Symlink("file1", "symlink1")
704 err = unix.Lstat("symlink1", &st1)
706 t.Fatalf("Lstat: %v", err)
709 err = unix.Fstatat(unix.AT_FDCWD, "symlink1", &st2, unix.AT_SYMLINK_NOFOLLOW)
711 t.Fatalf("Fstatat: %v", err)
714 compareStat_t(t, "Lstat", &st1, &st2)
717 func TestFchmodat(t *testing.T) {
721 err := os.Symlink("file1", "symlink1")
726 mode := os.FileMode(0444)
727 err = unix.Fchmodat(unix.AT_FDCWD, "symlink1", uint32(mode), 0)
729 t.Fatalf("Fchmodat: unexpected error: %v", err)
732 fi, err := os.Stat("file1")
737 if fi.Mode() != mode {
738 t.Errorf("Fchmodat: failed to change file mode: expected %v, got %v", mode, fi.Mode())
741 mode = os.FileMode(0644)
742 didChmodSymlink := true
743 err = unix.Fchmodat(unix.AT_FDCWD, "symlink1", uint32(mode), unix.AT_SYMLINK_NOFOLLOW)
745 if (runtime.GOOS == "android" || runtime.GOOS == "linux" ||
746 runtime.GOOS == "solaris" || runtime.GOOS == "illumos") && err == unix.EOPNOTSUPP {
747 // Linux and Illumos don't support flags != 0
748 didChmodSymlink = false
750 t.Fatalf("Fchmodat: unexpected error: %v", err)
754 if !didChmodSymlink {
755 // Didn't change mode of the symlink. On Linux, the permissions
756 // of a symbolic link are always 0777 according to symlink(7)
757 mode = os.FileMode(0777)
761 err = unix.Lstat("symlink1", &st)
766 got := os.FileMode(st.Mode & 0777)
768 t.Errorf("Fchmodat: failed to change symlink mode: expected %v, got %v", mode, got)
772 func TestMkdev(t *testing.T) {
775 dev := unix.Mkdev(major, minor)
777 if unix.Major(dev) != major {
778 t.Errorf("Major(%#x) == %d, want %d", dev, unix.Major(dev), major)
780 if unix.Minor(dev) != minor {
781 t.Errorf("Minor(%#x) == %d, want %d", dev, unix.Minor(dev), minor)
785 func TestRenameat(t *testing.T) {
788 from, to := "renamefrom", "renameto"
792 err := unix.Renameat(unix.AT_FDCWD, from, unix.AT_FDCWD, to)
794 t.Fatalf("Renameat: unexpected error: %v", err)
802 _, err = os.Stat(from)
804 t.Errorf("Renameat: stat of renamed file %q unexpectedly succeeded", from)
808 func TestUtimesNanoAt(t *testing.T) {
811 symlink := "symlink1"
813 err := os.Symlink("nonexisting", symlink)
818 // Some filesystems only support microsecond resolution. Account for
820 ts := []unix.Timespec{
821 {Sec: 1111, Nsec: 2000},
822 {Sec: 3333, Nsec: 4000},
824 err = unix.UtimesNanoAt(unix.AT_FDCWD, symlink, ts, unix.AT_SYMLINK_NOFOLLOW)
826 t.Fatalf("UtimesNanoAt: %v", err)
830 err = unix.Lstat(symlink, &st)
832 t.Fatalf("Lstat: %v", err)
835 // Only check Mtim, Atim might not be supported by the underlying filesystem
837 if st.Mtim.Nsec == 0 {
838 // Some filesystems only support 1-second time stamp resolution
839 // and will always set Nsec to 0.
842 if st.Mtim != expected {
843 t.Errorf("UtimesNanoAt: wrong mtime: got %v, expected %v", st.Mtim, expected)
847 // mktmpfifo creates a temporary FIFO and provides a cleanup function.
848 func mktmpfifo(t *testing.T) (*os.File, func()) {
849 err := unix.Mkfifo("fifo", 0666)
851 t.Fatalf("mktmpfifo: failed to create FIFO: %v", err)
854 f, err := os.OpenFile("fifo", os.O_RDWR, 0666)
857 t.Fatalf("mktmpfifo: failed to open FIFO: %v", err)
866 // utilities taken from os/os_test.go
868 func touch(t *testing.T, name string) {
869 f, err := os.Create(name)
873 if err := f.Close(); err != nil {
878 // chtmpdir changes the working directory to a new temporary directory and
879 // provides a cleanup function. Used when PWD is read-only.
880 func chtmpdir(t *testing.T) func() {
881 oldwd, err := os.Getwd()
883 t.Fatalf("chtmpdir: %v", err)
885 d, err := ioutil.TempDir("", "test")
887 t.Fatalf("chtmpdir: %v", err)
889 if err := os.Chdir(d); err != nil {
890 t.Fatalf("chtmpdir: %v", err)
893 if err := os.Chdir(oldwd); err != nil {
894 t.Fatalf("chtmpdir: %v", err)
900 func TestPipe(t *testing.T) {
907 n, err := unix.Write(w, []byte(s))
909 t.Errorf("bad write: %s\n", err)
913 t.Errorf("bad write count: %d\n", n)
918 t.Errorf("bad close: %s\n", err)
922 var buf [10 + len(s)]byte
923 n, err := unix.Read(r, buf[:])
925 t.Fatalf("bad read: %s\n", err)
928 t.Fatalf("bad read count: %d\n", n)
930 if string(buf[:n]) != s {
931 t.Fatalf("bad contents: %s\n", string(buf[:n]))
935 t.Fatalf("bad close: %s\n", err)