1 // Copyright 2016 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.
25 "golang.org/x/sys/unix"
28 func TestIoctlGetInt(t *testing.T) {
29 f, err := os.Open("/dev/random")
31 t.Fatalf("failed to open device: %v", err)
35 v, err := unix.IoctlGetInt(int(f.Fd()), unix.RNDGETENTCNT)
37 t.Fatalf("failed to perform ioctl: %v", err)
40 t.Logf("%d bits of entropy available", v)
43 func TestIoctlRetInt(t *testing.T) {
44 f, err := os.Open("/proc/self/ns/mnt")
46 t.Skipf("skipping test, %v", err)
50 v, err := unix.IoctlRetInt(int(f.Fd()), unix.NS_GET_NSTYPE)
52 if err == unix.ENOTTY {
53 t.Skipf("old kernel? (need Linux >= 4.11)")
55 t.Fatalf("failed to perform ioctl: %v", err)
57 if v != unix.CLONE_NEWNS {
58 t.Fatalf("unexpected return from ioctl; expected %v, got %v", v, unix.CLONE_NEWNS)
62 func TestIoctlGetRTCTime(t *testing.T) {
63 f, err := os.Open("/dev/rtc0")
65 t.Skipf("skipping test, %v", err)
69 v, err := unix.IoctlGetRTCTime(int(f.Fd()))
71 t.Fatalf("failed to perform ioctl: %v", err)
74 t.Logf("RTC time: %04d-%02d-%02d %02d:%02d:%02d", v.Year+1900, v.Mon+1, v.Mday, v.Hour, v.Min, v.Sec)
77 func TestIoctlGetRTCWkAlrm(t *testing.T) {
78 f, err := os.Open("/dev/rtc0")
80 t.Skipf("skipping test, %v", err)
84 v, err := unix.IoctlGetRTCWkAlrm(int(f.Fd()))
86 t.Fatalf("failed to perform ioctl: %v", err)
89 t.Logf("RTC wake alarm enabled '%d'; time: %04d-%02d-%02d %02d:%02d:%02d",
90 v.Enabled, v.Time.Year+1900, v.Time.Mon+1, v.Time.Mday, v.Time.Hour, v.Time.Min, v.Time.Sec)
93 func TestPpoll(t *testing.T) {
94 if runtime.GOOS == "android" {
95 t.Skip("mkfifo syscall is not available on android, skipping test")
99 f, cleanup := mktmpfifo(t)
102 const timeout = 100 * time.Millisecond
104 ok := make(chan bool, 1)
107 case <-time.After(10 * timeout):
108 t.Errorf("Ppoll: failed to timeout after %d", 10*timeout)
113 fds := []unix.PollFd{{Fd: int32(f.Fd()), Events: unix.POLLIN}}
114 timeoutTs := unix.NsecToTimespec(int64(timeout))
115 n, err := unix.Ppoll(fds, &timeoutTs, nil)
118 t.Errorf("Ppoll: unexpected error: %v", err)
122 t.Errorf("Ppoll: wrong number of events: got %v, expected %v", n, 0)
127 func TestTime(t *testing.T) {
129 ut2, err := unix.Time(&ut)
131 t.Fatalf("Time: %v", err)
134 t.Errorf("Time: return value %v should be equal to argument %v", ut2, ut)
139 for i := 0; i < 10; i++ {
140 ut, err = unix.Time(nil)
142 t.Fatalf("Time: %v", err)
146 diff := int64(ut) - now.Unix()
147 if -1 <= diff && diff <= 1 {
152 t.Errorf("Time: return value %v should be nearly equal to time.Now().Unix() %v±1", ut, now.Unix())
155 func TestUtime(t *testing.T) {
160 buf := &unix.Utimbuf{
164 err := unix.Utime("file1", buf)
166 t.Fatalf("Utime: %v", err)
169 fi, err := os.Stat("file1")
174 if fi.ModTime().Unix() != 12345 {
175 t.Errorf("Utime: failed to change modtime: expected %v, got %v", 12345, fi.ModTime().Unix())
179 func TestRlimitAs(t *testing.T) {
180 // disable GC during to avoid flaky test
181 defer debug.SetGCPercent(debug.SetGCPercent(-1))
184 err := unix.Getrlimit(unix.RLIMIT_AS, &rlim)
186 t.Fatalf("Getrlimit: %v", err)
190 t.Fatalf("Getrlimit: got zero value %#v", rlim)
193 set.Cur = uint64(unix.Getpagesize())
194 err = unix.Setrlimit(unix.RLIMIT_AS, &set)
196 t.Fatalf("Setrlimit: set failed: %#v %v", set, err)
199 // RLIMIT_AS was set to the page size, so mmap()'ing twice the page size
200 // should fail. See 'man 2 getrlimit'.
201 _, err = unix.Mmap(-1, 0, 2*unix.Getpagesize(), unix.PROT_NONE, unix.MAP_ANON|unix.MAP_PRIVATE)
203 t.Fatal("Mmap: unexpectedly succeeded after setting RLIMIT_AS")
206 err = unix.Setrlimit(unix.RLIMIT_AS, &rlim)
208 t.Fatalf("Setrlimit: restore failed: %#v %v", rlim, err)
211 b, err := unix.Mmap(-1, 0, 2*unix.Getpagesize(), unix.PROT_NONE, unix.MAP_ANON|unix.MAP_PRIVATE)
213 t.Fatalf("Mmap: %v", err)
217 t.Fatalf("Munmap: %v", err)
221 func TestPselect(t *testing.T) {
223 n, err := unix.Pselect(0, nil, nil, nil, &unix.Timespec{Sec: 0, Nsec: 0}, nil)
224 if err == unix.EINTR {
225 t.Logf("Pselect interrupted")
227 } else if err != nil {
228 t.Fatalf("Pselect: %v", err)
231 t.Fatalf("Pselect: got %v ready file descriptors, expected 0", n)
236 dur := 2500 * time.Microsecond
237 var took time.Duration
239 // On some platforms (e.g. Linux), the passed-in timespec is
240 // updated by pselect(2). Make sure to reset to the full
241 // duration in case of an EINTR.
242 ts := unix.NsecToTimespec(int64(dur))
244 n, err := unix.Pselect(0, nil, nil, nil, &ts, nil)
245 took = time.Since(start)
246 if err == unix.EINTR {
247 t.Logf("Pselect interrupted after %v", took)
249 } else if err != nil {
250 t.Fatalf("Pselect: %v", err)
253 t.Fatalf("Pselect: got %v ready file descriptors, expected 0", n)
258 // On some builder the actual timeout might also be slightly less than the requested.
259 // Add an acceptable margin to avoid flaky tests.
261 t.Errorf("Pselect: got %v timeout, expected at least %v", took, dur)
265 func TestSchedSetaffinity(t *testing.T) {
266 var newMask unix.CPUSet
268 if newMask.Count() != 0 {
269 t.Errorf("CpuZero: didn't zero CPU set: %v", newMask)
273 if newMask.Count() != 1 || !newMask.IsSet(cpu) {
274 t.Errorf("CpuSet: didn't set CPU %d in set: %v", cpu, newMask)
278 if newMask.Count() != 2 || !newMask.IsSet(cpu) {
279 t.Errorf("CpuSet: didn't set CPU %d in set: %v", cpu, newMask)
282 if newMask.Count() != 1 || newMask.IsSet(cpu) {
283 t.Errorf("CpuClr: didn't clear CPU %d in set: %v", cpu, newMask)
286 runtime.LockOSThread()
287 defer runtime.UnlockOSThread()
289 var oldMask unix.CPUSet
290 err := unix.SchedGetaffinity(0, &oldMask)
292 t.Fatalf("SchedGetaffinity: %v", err)
295 if runtime.NumCPU() < 2 {
296 t.Skip("skipping setaffinity tests on single CPU system")
298 if runtime.GOOS == "android" {
299 t.Skip("skipping setaffinity tests on android")
302 // On a system like ppc64x where some cores can be disabled using ppc64_cpu,
303 // setaffinity should only be called with enabled cores. The valid cores
304 // are found from the oldMask, but if none are found then the setaffinity
305 // tests are skipped. Issue #27875.
307 if !oldMask.IsSet(cpu) {
309 for i := 0; i < len(oldMask); i++ {
310 if oldMask.IsSet(i) {
315 if newMask.Count() == 0 {
316 t.Skip("skipping setaffinity tests if CPU not available")
320 err = unix.SchedSetaffinity(0, &newMask)
322 t.Fatalf("SchedSetaffinity: %v", err)
325 var gotMask unix.CPUSet
326 err = unix.SchedGetaffinity(0, &gotMask)
328 t.Fatalf("SchedGetaffinity: %v", err)
331 if gotMask != newMask {
332 t.Errorf("SchedSetaffinity: returned affinity mask does not match set affinity mask")
335 // Restore old mask so it doesn't affect successive tests
336 err = unix.SchedSetaffinity(0, &oldMask)
338 t.Fatalf("SchedSetaffinity: %v", err)
342 func TestStatx(t *testing.T) {
344 err := unix.Statx(unix.AT_FDCWD, ".", 0, 0, &stx)
345 if err == unix.ENOSYS || err == unix.EPERM {
346 t.Skip("statx syscall is not available, skipping test")
347 } else if err != nil {
348 t.Fatalf("Statx: %v", err)
355 err = unix.Stat("file1", &st)
357 t.Fatalf("Stat: %v", err)
360 flags := unix.AT_STATX_SYNC_AS_STAT
361 err = unix.Statx(unix.AT_FDCWD, "file1", flags, unix.STATX_ALL, &stx)
363 t.Fatalf("Statx: %v", err)
366 if uint32(stx.Mode) != st.Mode {
367 t.Errorf("Statx: returned stat mode does not match Stat")
370 ctime := unix.StatxTimestamp{Sec: int64(st.Ctim.Sec), Nsec: uint32(st.Ctim.Nsec)}
371 mtime := unix.StatxTimestamp{Sec: int64(st.Mtim.Sec), Nsec: uint32(st.Mtim.Nsec)}
373 if stx.Ctime != ctime {
374 t.Errorf("Statx: returned stat ctime does not match Stat")
376 if stx.Mtime != mtime {
377 t.Errorf("Statx: returned stat mtime does not match Stat")
380 err = os.Symlink("file1", "symlink1")
385 err = unix.Lstat("symlink1", &st)
387 t.Fatalf("Lstat: %v", err)
390 err = unix.Statx(unix.AT_FDCWD, "symlink1", flags, unix.STATX_BASIC_STATS, &stx)
392 t.Fatalf("Statx: %v", err)
395 // follow symlink, expect a regulat file
396 if stx.Mode&unix.S_IFREG == 0 {
397 t.Errorf("Statx: didn't follow symlink")
400 err = unix.Statx(unix.AT_FDCWD, "symlink1", flags|unix.AT_SYMLINK_NOFOLLOW, unix.STATX_ALL, &stx)
402 t.Fatalf("Statx: %v", err)
405 // follow symlink, expect a symlink
406 if stx.Mode&unix.S_IFLNK == 0 {
407 t.Errorf("Statx: unexpectedly followed symlink")
409 if uint32(stx.Mode) != st.Mode {
410 t.Errorf("Statx: returned stat mode does not match Lstat")
413 ctime = unix.StatxTimestamp{Sec: int64(st.Ctim.Sec), Nsec: uint32(st.Ctim.Nsec)}
414 mtime = unix.StatxTimestamp{Sec: int64(st.Mtim.Sec), Nsec: uint32(st.Mtim.Nsec)}
416 if stx.Ctime != ctime {
417 t.Errorf("Statx: returned stat ctime does not match Lstat")
419 if stx.Mtime != mtime {
420 t.Errorf("Statx: returned stat mtime does not match Lstat")
424 // stringsFromByteSlice converts a sequence of attributes to a []string.
425 // On Linux, each entry is a NULL-terminated string.
426 func stringsFromByteSlice(buf []byte) []string {
429 for i, b := range buf {
431 result = append(result, string(buf[off:i]))
438 func TestFaccessat(t *testing.T) {
442 err := unix.Faccessat(unix.AT_FDCWD, "file1", unix.R_OK, 0)
444 t.Errorf("Faccessat: unexpected error: %v", err)
447 err = unix.Faccessat(unix.AT_FDCWD, "file1", unix.R_OK, 2)
448 if err != unix.EINVAL {
449 t.Errorf("Faccessat: unexpected error: %v, want EINVAL", err)
452 err = unix.Faccessat(unix.AT_FDCWD, "file1", unix.R_OK, unix.AT_EACCESS)
454 t.Errorf("Faccessat: unexpected error: %v", err)
457 err = os.Symlink("file1", "symlink1")
462 err = unix.Faccessat(unix.AT_FDCWD, "symlink1", unix.R_OK, unix.AT_SYMLINK_NOFOLLOW)
464 t.Errorf("Faccessat SYMLINK_NOFOLLOW: unexpected error %v", err)
467 // We can't really test AT_SYMLINK_NOFOLLOW, because there
468 // doesn't seem to be any way to change the mode of a symlink.
469 // We don't test AT_EACCESS because such tests are only
470 // meaningful if run as root.
472 err = unix.Fchmodat(unix.AT_FDCWD, "file1", 0, 0)
474 t.Errorf("Fchmodat: unexpected error %v", err)
477 err = unix.Faccessat(unix.AT_FDCWD, "file1", unix.F_OK, unix.AT_SYMLINK_NOFOLLOW)
479 t.Errorf("Faccessat: unexpected error: %v", err)
482 err = unix.Faccessat(unix.AT_FDCWD, "file1", unix.R_OK, unix.AT_SYMLINK_NOFOLLOW)
483 if err != unix.EACCES {
484 if unix.Getuid() != 0 {
485 t.Errorf("Faccessat: unexpected error: %v, want EACCES", err)
490 func TestSyncFileRange(t *testing.T) {
491 file, err := ioutil.TempFile("", "TestSyncFileRange")
495 defer os.Remove(file.Name())
498 err = unix.SyncFileRange(int(file.Fd()), 0, 0, 0)
499 if err == unix.ENOSYS || err == unix.EPERM {
500 t.Skip("sync_file_range syscall is not available, skipping test")
501 } else if err != nil {
502 t.Fatalf("SyncFileRange: %v", err)
507 err = unix.SyncFileRange(int(file.Fd()), 0, 0, flags)
508 if err != unix.EINVAL {
509 t.Fatalf("SyncFileRange: unexpected error: %v, want EINVAL", err)
513 func TestClockNanosleep(t *testing.T) {
514 delay := 50 * time.Millisecond
516 // Relative timespec.
518 rel := unix.NsecToTimespec(delay.Nanoseconds())
519 remain := unix.Timespec{}
521 err := unix.ClockNanosleep(unix.CLOCK_MONOTONIC, 0, &rel, &remain)
522 if err == unix.ENOSYS || err == unix.EPERM {
523 t.Skip("clock_nanosleep syscall is not available, skipping test")
524 } else if err == unix.EINTR {
525 t.Logf("ClockNanosleep interrupted after %v", time.Since(start))
528 } else if err != nil {
529 t.Errorf("ClockNanosleep(CLOCK_MONOTONIC, 0, %#v, nil) = %v", &rel, err)
530 } else if slept := time.Since(start); slept < delay {
531 t.Errorf("ClockNanosleep(CLOCK_MONOTONIC, 0, %#v, nil) slept only %v", &rel, slept)
536 // Absolute timespec.
539 until := start.Add(delay)
540 abs := unix.NsecToTimespec(until.UnixNano())
541 err := unix.ClockNanosleep(unix.CLOCK_REALTIME, unix.TIMER_ABSTIME, &abs, nil)
542 if err == unix.EINTR {
543 t.Logf("ClockNanosleep interrupted after %v", time.Since(start))
545 } else if err != nil {
546 t.Errorf("ClockNanosleep(CLOCK_REALTIME, TIMER_ABSTIME, %#v (=%v), nil) = %v", &abs, until, err)
547 } else if slept := time.Since(start); slept < delay {
548 t.Errorf("ClockNanosleep(CLOCK_REALTIME, TIMER_ABSTIME, %#v (=%v), nil) slept only %v", &abs, until, slept)
553 // Invalid clock. clock_nanosleep(2) says EINVAL, but it’s actually EOPNOTSUPP.
554 err := unix.ClockNanosleep(unix.CLOCK_THREAD_CPUTIME_ID, 0, &rel, nil)
555 if err != unix.EINVAL && err != unix.EOPNOTSUPP {
556 t.Errorf("ClockNanosleep(CLOCK_THREAD_CPUTIME_ID, 0, %#v, nil) = %v, want EINVAL or EOPNOTSUPP", &rel, err)
560 func TestOpenByHandleAt(t *testing.T) {
561 skipIfNotSupported := func(t *testing.T, name string, err error) {
562 if err == unix.EPERM {
563 t.Skipf("skipping %s test without CAP_DAC_READ_SEARCH", name)
565 if err == unix.ENOSYS {
566 t.Skipf("%s system call not available", name)
568 if err == unix.EOPNOTSUPP {
569 t.Skipf("%s not supported on this filesystem", name)
573 h, mountID, err := unix.NameToHandleAt(unix.AT_FDCWD, "syscall_linux_test.go", 0)
575 skipIfNotSupported(t, "name_to_handle_at", err)
576 t.Fatalf("NameToHandleAt: %v", err)
578 t.Logf("mountID: %v, handle: size=%d, type=%d, bytes=%q", mountID,
579 h.Size(), h.Type(), h.Bytes())
580 mount, err := openMountByID(mountID)
582 t.Fatalf("openMountByID: %v", err)
586 for _, clone := range []bool{false, true} {
587 t.Run("clone="+strconv.FormatBool(clone), func(t *testing.T) {
589 h = unix.NewFileHandle(h.Type(), h.Bytes())
591 fd, err := unix.OpenByHandleAt(int(mount.Fd()), h, unix.O_RDONLY)
592 skipIfNotSupported(t, "open_by_handle_at", err)
594 t.Fatalf("OpenByHandleAt: %v", err)
598 t.Logf("opened fd %v", fd)
599 f := os.NewFile(uintptr(fd), "")
600 slurp, err := ioutil.ReadAll(f)
604 const substr = "Some substring for a test."
605 if !strings.Contains(string(slurp), substr) {
606 t.Errorf("didn't find substring %q in opened file; read %d bytes", substr, len(slurp))
612 func openMountByID(mountID int) (f *os.File, err error) {
613 mi, err := os.Open("/proc/self/mountinfo")
618 bs := bufio.NewScanner(mi)
619 wantPrefix := []byte(fmt.Sprintf("%v ", mountID))
621 if !bytes.HasPrefix(bs.Bytes(), wantPrefix) {
624 fields := strings.Fields(bs.Text())
628 if err := bs.Err(); err != nil {
631 return nil, errors.New("mountID not found")
634 func TestEpoll(t *testing.T) {
635 efd, err := unix.EpollCreate1(unix.EPOLL_CLOEXEC)
637 t.Fatalf("EpollCreate1: %v", err)
639 defer unix.Close(efd)
641 r, w, err := os.Pipe()
649 ev := unix.EpollEvent{Events: unix.EPOLLIN, Fd: int32(fd)}
651 err = unix.EpollCtl(efd, unix.EPOLL_CTL_ADD, fd, &ev)
653 t.Fatalf("EpollCtl: %v", err)
656 if _, err := w.Write([]byte("HELLO GOPHER")); err != nil {
660 events := make([]unix.EpollEvent, 128)
661 n, err := unix.EpollWait(efd, events, 1)
663 t.Fatalf("EpollWait: %v", err)
667 t.Errorf("EpollWait: wrong number of events: got %v, expected 1", n)
670 got := int(events[0].Fd)
672 t.Errorf("EpollWait: wrong Fd in event: got %v, expected %v", got, fd)
676 func TestPrctlRetInt(t *testing.T) {
677 err := unix.Prctl(unix.PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)
679 t.Skipf("Prctl: %v, skipping test", err)
681 v, err := unix.PrctlRetInt(unix.PR_GET_NO_NEW_PRIVS, 0, 0, 0, 0)
683 t.Fatalf("failed to perform prctl: %v", err)
686 t.Fatalf("unexpected return from prctl; got %v, expected %v", v, 1)
690 func TestTimerfd(t *testing.T) {
691 var now unix.Timespec
692 if err := unix.ClockGettime(unix.CLOCK_REALTIME, &now); err != nil {
693 t.Fatalf("ClockGettime: %v", err)
696 tfd, err := unix.TimerfdCreate(unix.CLOCK_REALTIME, 0)
697 if err == unix.ENOSYS {
698 t.Skip("timerfd_create system call not implemented")
699 } else if err != nil {
700 t.Fatalf("TimerfdCreate: %v", err)
702 defer unix.Close(tfd)
704 var timeSpec unix.ItimerSpec
705 if err := unix.TimerfdGettime(tfd, &timeSpec); err != nil {
706 t.Fatalf("TimerfdGettime: %v", err)
709 if timeSpec.Value.Nsec != 0 || timeSpec.Value.Sec != 0 {
710 t.Fatalf("TimerfdGettime: timer is already set, but shouldn't be")
713 timeSpec = unix.ItimerSpec{
714 Interval: unix.NsecToTimespec(int64(time.Millisecond)),
718 if err := unix.TimerfdSettime(tfd, unix.TFD_TIMER_ABSTIME, &timeSpec, nil); err != nil {
719 t.Fatalf("TimerfdSettime: %v", err)
722 const totalTicks = 10
723 const bufferLength = 8
725 buffer := make([]byte, bufferLength)
728 for count < totalTicks {
729 n, err := unix.Read(tfd, buffer)
731 t.Fatalf("Timerfd: %v", err)
732 } else if n != bufferLength {
733 t.Fatalf("Timerfd: got %d bytes from timerfd, expected %d bytes", n, bufferLength)
736 count += *(*uint64)(unsafe.Pointer(&buffer))
740 func TestOpenat2(t *testing.T) {
741 how := &unix.OpenHow{
742 Flags: unix.O_RDONLY,
744 fd, err := unix.Openat2(unix.AT_FDCWD, ".", how)
746 if err == unix.ENOSYS || err == unix.EPERM {
747 t.Skipf("openat2: %v (old kernel? need Linux >= 5.6)", err)
749 t.Fatalf("openat2: %v", err)
751 if err := unix.Close(fd); err != nil {
752 t.Fatalf("close: %v", err)
756 tempDir, err := ioutil.TempDir("", t.Name())
760 defer os.RemoveAll(tempDir)
762 subdir := filepath.Join(tempDir, "dir")
763 if err := os.Mkdir(subdir, 0755); err != nil {
766 symlink := filepath.Join(subdir, "symlink")
767 if err := os.Symlink("../", symlink); err != nil {
771 dirfd, err := unix.Open(subdir, unix.O_RDONLY, 0)
773 t.Fatalf("open(%q): %v", subdir, err)
775 defer unix.Close(dirfd)
777 // openat2 with no extra flags -- should succeed
778 fd, err = unix.Openat2(dirfd, "symlink", how)
780 t.Errorf("Openat2 should succeed, got %v", err)
782 if err := unix.Close(fd); err != nil {
783 t.Fatalf("close: %v", err)
786 // open with RESOLVE_BENEATH, should result in EXDEV
787 how.Resolve = unix.RESOLVE_BENEATH
788 fd, err = unix.Openat2(dirfd, "symlink", how)
790 if err := unix.Close(fd); err != nil {
791 t.Fatalf("close: %v", err)
794 if err != unix.EXDEV {
795 t.Errorf("Openat2 should fail with EXDEV, got %v", err)