.gitignore added
[dotfiles/.git] / .config / coc / extensions / coc-go-data / tools / pkg / mod / golang.org / x / sys@v0.0.0-20210124154548-22da62e12c0c / unix / syscall_unix_test.go
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.
4
5 // +build aix darwin dragonfly freebsd linux netbsd openbsd solaris
6
7 package unix_test
8
9 import (
10         "flag"
11         "fmt"
12         "io/ioutil"
13         "net"
14         "os"
15         "os/exec"
16         "path/filepath"
17         "runtime"
18         "strconv"
19         "syscall"
20         "testing"
21         "time"
22
23         "golang.org/x/sys/unix"
24 )
25
26 // Tests that below functions, structures and constants are consistent
27 // on all Unix-like systems.
28 func _() {
29         // program scheduling priority functions and constants
30         var (
31                 _ func(int, int, int) error   = unix.Setpriority
32                 _ func(int, int) (int, error) = unix.Getpriority
33         )
34         const (
35                 _ int = unix.PRIO_USER
36                 _ int = unix.PRIO_PROCESS
37                 _ int = unix.PRIO_PGRP
38         )
39
40         // termios constants
41         const (
42                 _ int = unix.TCIFLUSH
43                 _ int = unix.TCIOFLUSH
44                 _ int = unix.TCOFLUSH
45         )
46
47         // fcntl file locking structure and constants
48         var (
49                 _ = unix.Flock_t{
50                         Type:   int16(0),
51                         Whence: int16(0),
52                         Start:  int64(0),
53                         Len:    int64(0),
54                         Pid:    int32(0),
55                 }
56         )
57         const (
58                 _ = unix.F_GETLK
59                 _ = unix.F_SETLK
60                 _ = unix.F_SETLKW
61         )
62 }
63
64 func TestErrnoSignalName(t *testing.T) {
65         testErrors := []struct {
66                 num  syscall.Errno
67                 name string
68         }{
69                 {syscall.EPERM, "EPERM"},
70                 {syscall.EINVAL, "EINVAL"},
71                 {syscall.ENOENT, "ENOENT"},
72         }
73
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)
77                         if e != te.name {
78                                 t.Errorf("ErrnoName(%d) returned %s, want %s", te.num, e, te.name)
79                         }
80                 })
81         }
82
83         testSignals := []struct {
84                 num  syscall.Signal
85                 name string
86         }{
87                 {syscall.SIGHUP, "SIGHUP"},
88                 {syscall.SIGPIPE, "SIGPIPE"},
89                 {syscall.SIGSEGV, "SIGSEGV"},
90         }
91
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)
95                         if s != ts.name {
96                                 t.Errorf("SignalName(%d) returned %s, want %s", ts.num, s, ts.name)
97                         }
98                 })
99         }
100 }
101
102 func TestSignalNum(t *testing.T) {
103         testSignals := []struct {
104                 name string
105                 want syscall.Signal
106         }{
107                 {"SIGHUP", syscall.SIGHUP},
108                 {"SIGPIPE", syscall.SIGPIPE},
109                 {"SIGSEGV", syscall.SIGSEGV},
110                 {"NONEXISTS", 0},
111         }
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)
115                         if got != ts.want {
116                                 t.Errorf("SignalNum(%s) returned %d, want %d", ts.name, got, ts.want)
117                         }
118                 })
119
120         }
121 }
122
123 func TestFcntlInt(t *testing.T) {
124         t.Parallel()
125         file, err := ioutil.TempFile("", "TestFnctlInt")
126         if err != nil {
127                 t.Fatal(err)
128         }
129         defer os.Remove(file.Name())
130         defer file.Close()
131         f := file.Fd()
132         flags, err := unix.FcntlInt(f, unix.F_GETFD, 0)
133         if err != nil {
134                 t.Fatal(err)
135         }
136         if flags&unix.FD_CLOEXEC == 0 {
137                 t.Errorf("flags %#x do not include FD_CLOEXEC", flags)
138         }
139 }
140
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)
146         if err != nil {
147                 t.Fatalf("Open failed: %v", err)
148         }
149         defer unix.Unlink(name)
150         defer unix.Close(fd)
151         flock := unix.Flock_t{
152                 Type:  unix.F_RDLCK,
153                 Start: 0, Len: 0, Whence: 1,
154         }
155         if err := unix.FcntlFlock(uintptr(fd), unix.F_GETLK, &flock); err != nil {
156                 t.Fatalf("FcntlFlock failed: %v", err)
157         }
158 }
159
160 // TestPassFD tests passing a file descriptor over a Unix socket.
161 //
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")
170         }
171
172         if os.Getenv("GO_WANT_HELPER_PROCESS") == "1" {
173                 passFDChild()
174                 return
175         }
176
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()
181                 if err != nil {
182                         t.Skipf("skipping on AIX because oslevel -s failed: %v", err)
183                 }
184
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")
187                 }
188                 aixVer := string(out[:4])
189                 tl, err := strconv.Atoi(string(out[5:7]))
190                 if err != nil {
191                         t.Skipf("skipping on AIX because oslevel -s output cannot be parsed: %v", err)
192                 }
193                 if aixVer < "7200" || (aixVer == "7200" && tl < 2) {
194                         t.Skip("skipped on AIX versions previous to 7.2 TL 2")
195                 }
196         }
197
198         tempDir, err := ioutil.TempDir("", "TestPassFD")
199         if err != nil {
200                 t.Fatal(err)
201         }
202         defer os.RemoveAll(tempDir)
203
204         fds, err := unix.Socketpair(unix.AF_LOCAL, unix.SOCK_STREAM, 0)
205         if err != nil {
206                 t.Fatalf("Socketpair: %v", err)
207         }
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()
214
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)
219         }
220         cmd.ExtraFiles = []*os.File{writeFile}
221
222         out, err := cmd.CombinedOutput()
223         if len(out) > 0 || err != nil {
224                 t.Fatalf("child process: %q, %v", out, err)
225         }
226
227         c, err := net.FileConn(readFile)
228         if err != nil {
229                 t.Fatalf("FileConn: %v", err)
230         }
231         defer c.Close()
232
233         uc, ok := c.(*net.UnixConn)
234         if !ok {
235                 t.Fatalf("unexpected FileConn type; expected UnixConn, got %T", c)
236         }
237
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")
242                 uc.Close()
243         })
244         _, oobn, _, _, err := uc.ReadMsgUnix(buf, oob)
245         if err != nil {
246                 t.Fatalf("ReadMsgUnix: %v", err)
247         }
248         closeUnix.Stop()
249
250         scms, err := unix.ParseSocketControlMessage(oob[:oobn])
251         if err != nil {
252                 t.Fatalf("ParseSocketControlMessage: %v", err)
253         }
254         if len(scms) != 1 {
255                 t.Fatalf("expected 1 SocketControlMessage; got scms = %#v", scms)
256         }
257         scm := scms[0]
258         gotFds, err := unix.ParseUnixRights(&scm)
259         if err != nil {
260                 t.Fatalf("unix.ParseUnixRights: %v", err)
261         }
262         if len(gotFds) != 1 {
263                 t.Fatalf("wanted 1 fd; got %#v", gotFds)
264         }
265
266         f := os.NewFile(uintptr(gotFds[0]), "fd-from-child")
267         defer f.Close()
268
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)
273         }
274 }
275
276 // passFDChild is the child process used by TestPassFD.
277 func passFDChild() {
278         defer os.Exit(0)
279
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.
282         var uc *net.UnixConn
283         for fd := uintptr(3); fd <= 10; fd++ {
284                 f := os.NewFile(fd, "unix-conn")
285                 var ok bool
286                 netc, _ := net.FileConn(f)
287                 uc, ok = netc.(*net.UnixConn)
288                 if ok {
289                         break
290                 }
291         }
292         if uc == nil {
293                 fmt.Println("failed to find unix fd")
294                 return
295         }
296
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.
299         flag.Parse()
300         tempDir := flag.Arg(0)
301         f, err := ioutil.TempFile(tempDir, "")
302         if err != nil {
303                 fmt.Printf("TempFile: %v", err)
304                 return
305         }
306
307         f.Write([]byte("Hello from child process!\n"))
308         f.Seek(0, 0)
309
310         rights := unix.UnixRights(int(f.Fd()))
311         dummyByte := []byte("x")
312         n, oobn, err := uc.WriteMsgUnix(dummyByte, rights, nil)
313         if err != nil {
314                 fmt.Printf("WriteMsgUnix: %v", err)
315                 return
316         }
317         if n != 1 || oobn != len(rights) {
318                 fmt.Printf("WriteMsgUnix = %d, %d; want 1, %d", n, oobn, len(rights))
319                 return
320         }
321 }
322
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{
327                 {{42}},
328                 {{1, 2}},
329                 {{3, 4, 5}},
330                 {{}},
331                 {{1, 2}, {3, 4, 5}, {}, {7}},
332         }
333         for _, testCase := range testCases {
334                 b := []byte{}
335                 var n int
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...)...)
340                 }
341                 // Truncate b
342                 b = b[:n]
343
344                 scms, err := unix.ParseSocketControlMessage(b)
345                 if err != nil {
346                         t.Fatalf("ParseSocketControlMessage: %v", err)
347                 }
348                 if len(scms) != len(testCase) {
349                         t.Fatalf("expected %v SocketControlMessage; got scms = %#v", len(testCase), scms)
350                 }
351                 for i, scm := range scms {
352                         gotFds, err := unix.ParseUnixRights(&scm)
353                         if err != nil {
354                                 t.Fatalf("ParseUnixRights: %v", err)
355                         }
356                         wantFds := testCase[i]
357                         if len(gotFds) != len(wantFds) {
358                                 t.Fatalf("expected %v fds, got %#v", len(wantFds), gotFds)
359                         }
360                         for j, fd := range gotFds {
361                                 if fd != wantFds[j] {
362                                         t.Fatalf("expected fd %v, got %v", wantFds[j], fd)
363                                 }
364                         }
365                 }
366         }
367 }
368
369 func TestRlimit(t *testing.T) {
370         var rlimit, zero unix.Rlimit
371         err := unix.Getrlimit(unix.RLIMIT_NOFILE, &rlimit)
372         if err != nil {
373                 t.Fatalf("Getrlimit: save failed: %v", err)
374         }
375         if zero == rlimit {
376                 t.Fatalf("Getrlimit: save failed: got zero value %#v", rlimit)
377         }
378         set := 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.
384                 set.Cur = 4096
385         }
386         err = unix.Setrlimit(unix.RLIMIT_NOFILE, &set)
387         if err != nil {
388                 t.Fatalf("Setrlimit: set failed: %#v %v", set, err)
389         }
390         var get unix.Rlimit
391         err = unix.Getrlimit(unix.RLIMIT_NOFILE, &get)
392         if err != nil {
393                 t.Fatalf("Getrlimit: get failed: %v", err)
394         }
395         set = rlimit
396         set.Cur = set.Max - 1
397         if (runtime.GOOS == "darwin" || runtime.GOOS == "ios") && set.Cur > 4096 {
398                 set.Cur = 4096
399         }
400         if set != get {
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":
406                 default:
407                         t.Fatalf("Rlimit: change failed: wanted %#v got %#v", set, get)
408                 }
409         }
410         err = unix.Setrlimit(unix.RLIMIT_NOFILE, &rlimit)
411         if err != nil {
412                 t.Fatalf("Setrlimit: restore failed: %#v %v", rlimit, err)
413         }
414
415         // make sure RLIM_INFINITY can be assigned to Rlimit members
416         _ = unix.Rlimit{
417                 Cur: unix.RLIM_INFINITY,
418                 Max: unix.RLIM_INFINITY,
419         }
420 }
421
422 func TestSeekFailure(t *testing.T) {
423         _, err := unix.Seek(-1, 0, 0)
424         if err == nil {
425                 t.Fatalf("Seek(-1, 0, 0) did not fail")
426         }
427         str := err.Error() // used to crash on Linux
428         t.Logf("Seek: %v", str)
429         if str == "" {
430                 t.Fatalf("Seek(-1, 0, 0) return error with empty message")
431         }
432 }
433
434 func TestSetsockoptString(t *testing.T) {
435         // should not panic on empty string, see issue #31277
436         err := unix.SetsockoptString(-1, 0, 0, "")
437         if err == nil {
438                 t.Fatalf("SetsockoptString: did not fail")
439         }
440 }
441
442 func TestDup(t *testing.T) {
443         file, err := ioutil.TempFile("", "TestDup")
444         if err != nil {
445                 t.Fatalf("Tempfile failed: %v", err)
446         }
447         defer os.Remove(file.Name())
448         defer file.Close()
449         f := int(file.Fd())
450
451         newFd, err := unix.Dup(f)
452         if err != nil {
453                 t.Fatalf("Dup: %v", err)
454         }
455
456         // Create and reserve a file descriptor.
457         // Dup2 automatically closes it before reusing it.
458         nullFile, err := os.Open("/dev/null")
459         if err != nil {
460                 t.Fatal(err)
461         }
462         dupFd := int(file.Fd())
463         err = unix.Dup2(newFd, dupFd)
464         if err != nil {
465                 t.Fatalf("Dup2: %v", err)
466         }
467         // Keep the dummy file open long enough to not be closed in
468         // its finalizer.
469         runtime.KeepAlive(nullFile)
470
471         b1 := []byte("Test123")
472         b2 := make([]byte, 7)
473         _, err = unix.Write(dupFd, b1)
474         if err != nil {
475                 t.Fatalf("Write to dup2 fd failed: %v", err)
476         }
477         _, err = unix.Seek(f, 0, 0)
478         if err != nil {
479                 t.Fatalf("Seek failed: %v", err)
480         }
481         _, err = unix.Read(f, b2)
482         if err != nil {
483                 t.Fatalf("Read back failed: %v", err)
484         }
485         if string(b1) != string(b2) {
486                 t.Errorf("Dup: stdout write not in file, expected %v, got %v", string(b1), string(b2))
487         }
488 }
489
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")
494         }
495
496         defer chtmpdir(t)()
497         f, cleanup := mktmpfifo(t)
498         defer cleanup()
499
500         const timeout = 100
501
502         ok := make(chan bool, 1)
503         go func() {
504                 select {
505                 case <-time.After(10 * timeout * time.Millisecond):
506                         t.Errorf("Poll: failed to timeout after %d milliseconds", 10*timeout)
507                 case <-ok:
508                 }
509         }()
510
511         fds := []unix.PollFd{{Fd: int32(f.Fd()), Events: unix.POLLIN}}
512         n, err := unix.Poll(fds, timeout)
513         ok <- true
514         if err != nil {
515                 t.Errorf("Poll: unexpected error: %v", err)
516                 return
517         }
518         if n != 0 {
519                 t.Errorf("Poll: wrong number of events: got %v, expected %v", n, 0)
520                 return
521         }
522 }
523
524 func TestSelect(t *testing.T) {
525         for {
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")
529                         continue
530                 } else if err != nil {
531                         t.Fatalf("Select: %v", err)
532                 }
533                 if n != 0 {
534                         t.Fatalf("Select: got %v ready file descriptors, expected 0", n)
535                 }
536                 break
537         }
538
539         dur := 250 * time.Millisecond
540         var took time.Duration
541         for {
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))
546                 start := time.Now()
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)
551                         continue
552                 } else if err != nil {
553                         t.Fatalf("Select: %v", err)
554                 }
555                 if n != 0 {
556                         t.Fatalf("Select: got %v ready file descriptors, expected 0", n)
557                 }
558                 break
559         }
560
561         // On some BSDs the actual timeout might also be slightly less than the requested.
562         // Add an acceptable margin to avoid flaky tests.
563         if took < dur*2/3 {
564                 t.Errorf("Select: got %v timeout, expected at least %v", took, dur)
565         }
566
567         rr, ww, err := os.Pipe()
568         if err != nil {
569                 t.Fatal(err)
570         }
571         defer rr.Close()
572         defer ww.Close()
573
574         if _, err := ww.Write([]byte("HELLO GOPHER")); err != nil {
575                 t.Fatal(err)
576         }
577
578         rFdSet := &unix.FdSet{}
579         fd := int(rr.Fd())
580         rFdSet.Set(fd)
581
582         for {
583                 n, err := unix.Select(fd+1, rFdSet, nil, nil, nil)
584                 if err == unix.EINTR {
585                         t.Log("Select interrupted")
586                         continue
587                 } else if err != nil {
588                         t.Fatalf("Select: %v", err)
589                 }
590                 if n != 1 {
591                         t.Fatalf("Select: got %v ready file descriptors, expected 1", n)
592                 }
593                 break
594         }
595 }
596
597 func TestGetwd(t *testing.T) {
598         fd, err := os.Open(".")
599         if err != nil {
600                 t.Fatalf("Open .: %s", err)
601         }
602         defer fd.Close()
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 {
607         case "android":
608                 dirs = []string{"/", "/system/bin"}
609         case "darwin", "ios":
610                 switch runtime.GOARCH {
611                 case "arm", "arm64":
612                         d1, err := ioutil.TempDir("", "d1")
613                         if err != nil {
614                                 t.Fatalf("TempDir: %v", err)
615                         }
616                         d2, err := ioutil.TempDir("", "d2")
617                         if err != nil {
618                                 t.Fatalf("TempDir: %v", err)
619                         }
620                         dirs = []string{d1, d2}
621                 }
622         }
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)
629                         continue
630                 }
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)
634                         continue
635                 }
636                 err = os.Chdir(d)
637                 if err != nil {
638                         t.Fatalf("Chdir: %v", err)
639                 }
640                 pwd, err := unix.Getwd()
641                 if err != nil {
642                         t.Fatalf("Getwd in %s: %s", d, err)
643                 }
644                 os.Setenv("PWD", oldwd)
645                 err = fd.Chdir()
646                 if err != nil {
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)
651                         os.Exit(1)
652                 }
653                 if pwd != d {
654                         t.Fatalf("Getwd returned %q want %q", pwd, d)
655                 }
656         }
657 }
658
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)
662         }
663         if st2.Ino != st1.Ino {
664                 t.Errorf("%s/Fstatat: got ino %v, expected %v", otherStat, st2.Ino, st1.Ino)
665         }
666         if st2.Mode != st1.Mode {
667                 t.Errorf("%s/Fstatat: got mode %v, expected %v", otherStat, st2.Mode, st1.Mode)
668         }
669         if st2.Uid != st1.Uid {
670                 t.Errorf("%s/Fstatat: got uid %v, expected %v", otherStat, st2.Uid, st1.Uid)
671         }
672         if st2.Gid != st1.Gid {
673                 t.Errorf("%s/Fstatat: got gid %v, expected %v", otherStat, st2.Gid, st1.Gid)
674         }
675         if st2.Size != st1.Size {
676                 t.Errorf("%s/Fstatat: got size %v, expected %v", otherStat, st2.Size, st1.Size)
677         }
678 }
679
680 func TestFstatat(t *testing.T) {
681         defer chtmpdir(t)()
682
683         touch(t, "file1")
684
685         var st1 unix.Stat_t
686         err := unix.Stat("file1", &st1)
687         if err != nil {
688                 t.Fatalf("Stat: %v", err)
689         }
690
691         var st2 unix.Stat_t
692         err = unix.Fstatat(unix.AT_FDCWD, "file1", &st2, 0)
693         if err != nil {
694                 t.Fatalf("Fstatat: %v", err)
695         }
696
697         compareStat_t(t, "Stat", &st1, &st2)
698
699         err = os.Symlink("file1", "symlink1")
700         if err != nil {
701                 t.Fatal(err)
702         }
703
704         err = unix.Lstat("symlink1", &st1)
705         if err != nil {
706                 t.Fatalf("Lstat: %v", err)
707         }
708
709         err = unix.Fstatat(unix.AT_FDCWD, "symlink1", &st2, unix.AT_SYMLINK_NOFOLLOW)
710         if err != nil {
711                 t.Fatalf("Fstatat: %v", err)
712         }
713
714         compareStat_t(t, "Lstat", &st1, &st2)
715 }
716
717 func TestFchmodat(t *testing.T) {
718         defer chtmpdir(t)()
719
720         touch(t, "file1")
721         err := os.Symlink("file1", "symlink1")
722         if err != nil {
723                 t.Fatal(err)
724         }
725
726         mode := os.FileMode(0444)
727         err = unix.Fchmodat(unix.AT_FDCWD, "symlink1", uint32(mode), 0)
728         if err != nil {
729                 t.Fatalf("Fchmodat: unexpected error: %v", err)
730         }
731
732         fi, err := os.Stat("file1")
733         if err != nil {
734                 t.Fatal(err)
735         }
736
737         if fi.Mode() != mode {
738                 t.Errorf("Fchmodat: failed to change file mode: expected %v, got %v", mode, fi.Mode())
739         }
740
741         mode = os.FileMode(0644)
742         didChmodSymlink := true
743         err = unix.Fchmodat(unix.AT_FDCWD, "symlink1", uint32(mode), unix.AT_SYMLINK_NOFOLLOW)
744         if err != nil {
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
749                 } else {
750                         t.Fatalf("Fchmodat: unexpected error: %v", err)
751                 }
752         }
753
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)
758         }
759
760         var st unix.Stat_t
761         err = unix.Lstat("symlink1", &st)
762         if err != nil {
763                 t.Fatal(err)
764         }
765
766         got := os.FileMode(st.Mode & 0777)
767         if got != mode {
768                 t.Errorf("Fchmodat: failed to change symlink mode: expected %v, got %v", mode, got)
769         }
770 }
771
772 func TestMkdev(t *testing.T) {
773         major := uint32(42)
774         minor := uint32(7)
775         dev := unix.Mkdev(major, minor)
776
777         if unix.Major(dev) != major {
778                 t.Errorf("Major(%#x) == %d, want %d", dev, unix.Major(dev), major)
779         }
780         if unix.Minor(dev) != minor {
781                 t.Errorf("Minor(%#x) == %d, want %d", dev, unix.Minor(dev), minor)
782         }
783 }
784
785 func TestRenameat(t *testing.T) {
786         defer chtmpdir(t)()
787
788         from, to := "renamefrom", "renameto"
789
790         touch(t, from)
791
792         err := unix.Renameat(unix.AT_FDCWD, from, unix.AT_FDCWD, to)
793         if err != nil {
794                 t.Fatalf("Renameat: unexpected error: %v", err)
795         }
796
797         _, err = os.Stat(to)
798         if err != nil {
799                 t.Error(err)
800         }
801
802         _, err = os.Stat(from)
803         if err == nil {
804                 t.Errorf("Renameat: stat of renamed file %q unexpectedly succeeded", from)
805         }
806 }
807
808 func TestUtimesNanoAt(t *testing.T) {
809         defer chtmpdir(t)()
810
811         symlink := "symlink1"
812         os.Remove(symlink)
813         err := os.Symlink("nonexisting", symlink)
814         if err != nil {
815                 t.Fatal(err)
816         }
817
818         // Some filesystems only support microsecond resolution. Account for
819         // that in Nsec.
820         ts := []unix.Timespec{
821                 {Sec: 1111, Nsec: 2000},
822                 {Sec: 3333, Nsec: 4000},
823         }
824         err = unix.UtimesNanoAt(unix.AT_FDCWD, symlink, ts, unix.AT_SYMLINK_NOFOLLOW)
825         if err != nil {
826                 t.Fatalf("UtimesNanoAt: %v", err)
827         }
828
829         var st unix.Stat_t
830         err = unix.Lstat(symlink, &st)
831         if err != nil {
832                 t.Fatalf("Lstat: %v", err)
833         }
834
835         // Only check Mtim, Atim might not be supported by the underlying filesystem
836         expected := ts[1]
837         if st.Mtim.Nsec == 0 {
838                 // Some filesystems only support 1-second time stamp resolution
839                 // and will always set Nsec to 0.
840                 expected.Nsec = 0
841         }
842         if st.Mtim != expected {
843                 t.Errorf("UtimesNanoAt: wrong mtime: got %v, expected %v", st.Mtim, expected)
844         }
845 }
846
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)
850         if err != nil {
851                 t.Fatalf("mktmpfifo: failed to create FIFO: %v", err)
852         }
853
854         f, err := os.OpenFile("fifo", os.O_RDWR, 0666)
855         if err != nil {
856                 os.Remove("fifo")
857                 t.Fatalf("mktmpfifo: failed to open FIFO: %v", err)
858         }
859
860         return f, func() {
861                 f.Close()
862                 os.Remove("fifo")
863         }
864 }
865
866 // utilities taken from os/os_test.go
867
868 func touch(t *testing.T, name string) {
869         f, err := os.Create(name)
870         if err != nil {
871                 t.Fatal(err)
872         }
873         if err := f.Close(); err != nil {
874                 t.Fatal(err)
875         }
876 }
877
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()
882         if err != nil {
883                 t.Fatalf("chtmpdir: %v", err)
884         }
885         d, err := ioutil.TempDir("", "test")
886         if err != nil {
887                 t.Fatalf("chtmpdir: %v", err)
888         }
889         if err := os.Chdir(d); err != nil {
890                 t.Fatalf("chtmpdir: %v", err)
891         }
892         return func() {
893                 if err := os.Chdir(oldwd); err != nil {
894                         t.Fatalf("chtmpdir: %v", err)
895                 }
896                 os.RemoveAll(d)
897         }
898 }
899
900 func TestPipe(t *testing.T) {
901         const s = "hello"
902         var pipes [2]int
903         unix.Pipe(pipes[:])
904         r := pipes[0]
905         w := pipes[1]
906         go func() {
907                 n, err := unix.Write(w, []byte(s))
908                 if err != nil {
909                         t.Errorf("bad write: %s\n", err)
910                         return
911                 }
912                 if n != len(s) {
913                         t.Errorf("bad write count: %d\n", n)
914                         return
915                 }
916                 err = unix.Close(w)
917                 if err != nil {
918                         t.Errorf("bad close: %s\n", err)
919                         return
920                 }
921         }()
922         var buf [10 + len(s)]byte
923         n, err := unix.Read(r, buf[:])
924         if err != nil {
925                 t.Fatalf("bad read: %s\n", err)
926         }
927         if n != len(s) {
928                 t.Fatalf("bad read count: %d\n", n)
929         }
930         if string(buf[:n]) != s {
931                 t.Fatalf("bad contents: %s\n", string(buf[:n]))
932         }
933         err = unix.Close(r)
934         if err != nil {
935                 t.Fatalf("bad close: %s\n", err)
936         }
937 }