github.com/fletavendor/sys@v0.0.0-20181107165924-66b7b1311ac8/unix/syscall_unix_test.go (about)

     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  	"syscall"
    19  	"testing"
    20  	"time"
    21  
    22  	"golang.org/x/sys/unix"
    23  )
    24  
    25  // Tests that below functions, structures and constants are consistent
    26  // on all Unix-like systems.
    27  func _() {
    28  	// program scheduling priority functions and constants
    29  	var (
    30  		_ func(int, int, int) error   = unix.Setpriority
    31  		_ func(int, int) (int, error) = unix.Getpriority
    32  	)
    33  	const (
    34  		_ int = unix.PRIO_USER
    35  		_ int = unix.PRIO_PROCESS
    36  		_ int = unix.PRIO_PGRP
    37  	)
    38  
    39  	// termios constants
    40  	const (
    41  		_ int = unix.TCIFLUSH
    42  		_ int = unix.TCIOFLUSH
    43  		_ int = unix.TCOFLUSH
    44  	)
    45  
    46  	// fcntl file locking structure and constants
    47  	var (
    48  		_ = unix.Flock_t{
    49  			Type:   int16(0),
    50  			Whence: int16(0),
    51  			Start:  int64(0),
    52  			Len:    int64(0),
    53  			Pid:    int32(0),
    54  		}
    55  	)
    56  	const (
    57  		_ = unix.F_GETLK
    58  		_ = unix.F_SETLK
    59  		_ = unix.F_SETLKW
    60  	)
    61  }
    62  
    63  func TestErrnoSignalName(t *testing.T) {
    64  	testErrors := []struct {
    65  		num  syscall.Errno
    66  		name string
    67  	}{
    68  		{syscall.EPERM, "EPERM"},
    69  		{syscall.EINVAL, "EINVAL"},
    70  		{syscall.ENOENT, "ENOENT"},
    71  	}
    72  
    73  	for _, te := range testErrors {
    74  		t.Run(fmt.Sprintf("%d/%s", te.num, te.name), func(t *testing.T) {
    75  			e := unix.ErrnoName(te.num)
    76  			if e != te.name {
    77  				t.Errorf("ErrnoName(%d) returned %s, want %s", te.num, e, te.name)
    78  			}
    79  		})
    80  	}
    81  
    82  	testSignals := []struct {
    83  		num  syscall.Signal
    84  		name string
    85  	}{
    86  		{syscall.SIGHUP, "SIGHUP"},
    87  		{syscall.SIGPIPE, "SIGPIPE"},
    88  		{syscall.SIGSEGV, "SIGSEGV"},
    89  	}
    90  
    91  	for _, ts := range testSignals {
    92  		t.Run(fmt.Sprintf("%d/%s", ts.num, ts.name), func(t *testing.T) {
    93  			s := unix.SignalName(ts.num)
    94  			if s != ts.name {
    95  				t.Errorf("SignalName(%d) returned %s, want %s", ts.num, s, ts.name)
    96  			}
    97  		})
    98  	}
    99  }
   100  
   101  func TestFcntlInt(t *testing.T) {
   102  	t.Parallel()
   103  	file, err := ioutil.TempFile("", "TestFnctlInt")
   104  	if err != nil {
   105  		t.Fatal(err)
   106  	}
   107  	defer os.Remove(file.Name())
   108  	defer file.Close()
   109  	f := file.Fd()
   110  	flags, err := unix.FcntlInt(f, unix.F_GETFD, 0)
   111  	if err != nil {
   112  		t.Fatal(err)
   113  	}
   114  	if flags&unix.FD_CLOEXEC == 0 {
   115  		t.Errorf("flags %#x do not include FD_CLOEXEC", flags)
   116  	}
   117  }
   118  
   119  // TestFcntlFlock tests whether the file locking structure matches
   120  // the calling convention of each kernel.
   121  func TestFcntlFlock(t *testing.T) {
   122  	name := filepath.Join(os.TempDir(), "TestFcntlFlock")
   123  	fd, err := unix.Open(name, unix.O_CREAT|unix.O_RDWR|unix.O_CLOEXEC, 0)
   124  	if err != nil {
   125  		t.Fatalf("Open failed: %v", err)
   126  	}
   127  	defer unix.Unlink(name)
   128  	defer unix.Close(fd)
   129  	flock := unix.Flock_t{
   130  		Type:  unix.F_RDLCK,
   131  		Start: 0, Len: 0, Whence: 1,
   132  	}
   133  	if err := unix.FcntlFlock(uintptr(fd), unix.F_GETLK, &flock); err != nil {
   134  		t.Fatalf("FcntlFlock failed: %v", err)
   135  	}
   136  }
   137  
   138  // TestPassFD tests passing a file descriptor over a Unix socket.
   139  //
   140  // This test involved both a parent and child process. The parent
   141  // process is invoked as a normal test, with "go test", which then
   142  // runs the child process by running the current test binary with args
   143  // "-test.run=^TestPassFD$" and an environment variable used to signal
   144  // that the test should become the child process instead.
   145  func TestPassFD(t *testing.T) {
   146  	if runtime.GOOS == "darwin" && (runtime.GOARCH == "arm" || runtime.GOARCH == "arm64") {
   147  		t.Skip("cannot exec subprocess on iOS, skipping test")
   148  	}
   149  	if runtime.GOOS == "aix" {
   150  		t.Skip("getsockname issue on AIX 7.2 tl1, skipping test")
   151  	}
   152  
   153  	if os.Getenv("GO_WANT_HELPER_PROCESS") == "1" {
   154  		passFDChild()
   155  		return
   156  	}
   157  
   158  	tempDir, err := ioutil.TempDir("", "TestPassFD")
   159  	if err != nil {
   160  		t.Fatal(err)
   161  	}
   162  	defer os.RemoveAll(tempDir)
   163  
   164  	fds, err := unix.Socketpair(unix.AF_LOCAL, unix.SOCK_STREAM, 0)
   165  	if err != nil {
   166  		t.Fatalf("Socketpair: %v", err)
   167  	}
   168  	defer unix.Close(fds[0])
   169  	defer unix.Close(fds[1])
   170  	writeFile := os.NewFile(uintptr(fds[0]), "child-writes")
   171  	readFile := os.NewFile(uintptr(fds[1]), "parent-reads")
   172  	defer writeFile.Close()
   173  	defer readFile.Close()
   174  
   175  	cmd := exec.Command(os.Args[0], "-test.run=^TestPassFD$", "--", tempDir)
   176  	cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"}
   177  	if lp := os.Getenv("LD_LIBRARY_PATH"); lp != "" {
   178  		cmd.Env = append(cmd.Env, "LD_LIBRARY_PATH="+lp)
   179  	}
   180  	cmd.ExtraFiles = []*os.File{writeFile}
   181  
   182  	out, err := cmd.CombinedOutput()
   183  	if len(out) > 0 || err != nil {
   184  		t.Fatalf("child process: %q, %v", out, err)
   185  	}
   186  
   187  	c, err := net.FileConn(readFile)
   188  	if err != nil {
   189  		t.Fatalf("FileConn: %v", err)
   190  	}
   191  	defer c.Close()
   192  
   193  	uc, ok := c.(*net.UnixConn)
   194  	if !ok {
   195  		t.Fatalf("unexpected FileConn type; expected UnixConn, got %T", c)
   196  	}
   197  
   198  	buf := make([]byte, 32) // expect 1 byte
   199  	oob := make([]byte, 32) // expect 24 bytes
   200  	closeUnix := time.AfterFunc(5*time.Second, func() {
   201  		t.Logf("timeout reading from unix socket")
   202  		uc.Close()
   203  	})
   204  	_, oobn, _, _, err := uc.ReadMsgUnix(buf, oob)
   205  	if err != nil {
   206  		t.Fatalf("ReadMsgUnix: %v", err)
   207  	}
   208  	closeUnix.Stop()
   209  
   210  	scms, err := unix.ParseSocketControlMessage(oob[:oobn])
   211  	if err != nil {
   212  		t.Fatalf("ParseSocketControlMessage: %v", err)
   213  	}
   214  	if len(scms) != 1 {
   215  		t.Fatalf("expected 1 SocketControlMessage; got scms = %#v", scms)
   216  	}
   217  	scm := scms[0]
   218  	gotFds, err := unix.ParseUnixRights(&scm)
   219  	if err != nil {
   220  		t.Fatalf("unix.ParseUnixRights: %v", err)
   221  	}
   222  	if len(gotFds) != 1 {
   223  		t.Fatalf("wanted 1 fd; got %#v", gotFds)
   224  	}
   225  
   226  	f := os.NewFile(uintptr(gotFds[0]), "fd-from-child")
   227  	defer f.Close()
   228  
   229  	got, err := ioutil.ReadAll(f)
   230  	want := "Hello from child process!\n"
   231  	if string(got) != want {
   232  		t.Errorf("child process ReadAll: %q, %v; want %q", got, err, want)
   233  	}
   234  }
   235  
   236  // passFDChild is the child process used by TestPassFD.
   237  func passFDChild() {
   238  	defer os.Exit(0)
   239  
   240  	// Look for our fd. It should be fd 3, but we work around an fd leak
   241  	// bug here (http://golang.org/issue/2603) to let it be elsewhere.
   242  	var uc *net.UnixConn
   243  	for fd := uintptr(3); fd <= 10; fd++ {
   244  		f := os.NewFile(fd, "unix-conn")
   245  		var ok bool
   246  		netc, _ := net.FileConn(f)
   247  		uc, ok = netc.(*net.UnixConn)
   248  		if ok {
   249  			break
   250  		}
   251  	}
   252  	if uc == nil {
   253  		fmt.Println("failed to find unix fd")
   254  		return
   255  	}
   256  
   257  	// Make a file f to send to our parent process on uc.
   258  	// We make it in tempDir, which our parent will clean up.
   259  	flag.Parse()
   260  	tempDir := flag.Arg(0)
   261  	f, err := ioutil.TempFile(tempDir, "")
   262  	if err != nil {
   263  		fmt.Printf("TempFile: %v", err)
   264  		return
   265  	}
   266  
   267  	f.Write([]byte("Hello from child process!\n"))
   268  	f.Seek(0, 0)
   269  
   270  	rights := unix.UnixRights(int(f.Fd()))
   271  	dummyByte := []byte("x")
   272  	n, oobn, err := uc.WriteMsgUnix(dummyByte, rights, nil)
   273  	if err != nil {
   274  		fmt.Printf("WriteMsgUnix: %v", err)
   275  		return
   276  	}
   277  	if n != 1 || oobn != len(rights) {
   278  		fmt.Printf("WriteMsgUnix = %d, %d; want 1, %d", n, oobn, len(rights))
   279  		return
   280  	}
   281  }
   282  
   283  // TestUnixRightsRoundtrip tests that UnixRights, ParseSocketControlMessage,
   284  // and ParseUnixRights are able to successfully round-trip lists of file descriptors.
   285  func TestUnixRightsRoundtrip(t *testing.T) {
   286  	testCases := [...][][]int{
   287  		{{42}},
   288  		{{1, 2}},
   289  		{{3, 4, 5}},
   290  		{{}},
   291  		{{1, 2}, {3, 4, 5}, {}, {7}},
   292  	}
   293  	for _, testCase := range testCases {
   294  		b := []byte{}
   295  		var n int
   296  		for _, fds := range testCase {
   297  			// Last assignment to n wins
   298  			n = len(b) + unix.CmsgLen(4*len(fds))
   299  			b = append(b, unix.UnixRights(fds...)...)
   300  		}
   301  		// Truncate b
   302  		b = b[:n]
   303  
   304  		scms, err := unix.ParseSocketControlMessage(b)
   305  		if err != nil {
   306  			t.Fatalf("ParseSocketControlMessage: %v", err)
   307  		}
   308  		if len(scms) != len(testCase) {
   309  			t.Fatalf("expected %v SocketControlMessage; got scms = %#v", len(testCase), scms)
   310  		}
   311  		for i, scm := range scms {
   312  			gotFds, err := unix.ParseUnixRights(&scm)
   313  			if err != nil {
   314  				t.Fatalf("ParseUnixRights: %v", err)
   315  			}
   316  			wantFds := testCase[i]
   317  			if len(gotFds) != len(wantFds) {
   318  				t.Fatalf("expected %v fds, got %#v", len(wantFds), gotFds)
   319  			}
   320  			for j, fd := range gotFds {
   321  				if fd != wantFds[j] {
   322  					t.Fatalf("expected fd %v, got %v", wantFds[j], fd)
   323  				}
   324  			}
   325  		}
   326  	}
   327  }
   328  
   329  func TestRlimit(t *testing.T) {
   330  	var rlimit, zero unix.Rlimit
   331  	err := unix.Getrlimit(unix.RLIMIT_NOFILE, &rlimit)
   332  	if err != nil {
   333  		t.Fatalf("Getrlimit: save failed: %v", err)
   334  	}
   335  	if zero == rlimit {
   336  		t.Fatalf("Getrlimit: save failed: got zero value %#v", rlimit)
   337  	}
   338  	set := rlimit
   339  	set.Cur = set.Max - 1
   340  	err = unix.Setrlimit(unix.RLIMIT_NOFILE, &set)
   341  	if err != nil {
   342  		t.Fatalf("Setrlimit: set failed: %#v %v", set, err)
   343  	}
   344  	var get unix.Rlimit
   345  	err = unix.Getrlimit(unix.RLIMIT_NOFILE, &get)
   346  	if err != nil {
   347  		t.Fatalf("Getrlimit: get failed: %v", err)
   348  	}
   349  	set = rlimit
   350  	set.Cur = set.Max - 1
   351  	if set != get {
   352  		// Seems like Darwin requires some privilege to
   353  		// increase the soft limit of rlimit sandbox, though
   354  		// Setrlimit never reports an error.
   355  		switch runtime.GOOS {
   356  		case "darwin":
   357  		default:
   358  			t.Fatalf("Rlimit: change failed: wanted %#v got %#v", set, get)
   359  		}
   360  	}
   361  	err = unix.Setrlimit(unix.RLIMIT_NOFILE, &rlimit)
   362  	if err != nil {
   363  		t.Fatalf("Setrlimit: restore failed: %#v %v", rlimit, err)
   364  	}
   365  }
   366  
   367  func TestSeekFailure(t *testing.T) {
   368  	_, err := unix.Seek(-1, 0, 0)
   369  	if err == nil {
   370  		t.Fatalf("Seek(-1, 0, 0) did not fail")
   371  	}
   372  	str := err.Error() // used to crash on Linux
   373  	t.Logf("Seek: %v", str)
   374  	if str == "" {
   375  		t.Fatalf("Seek(-1, 0, 0) return error with empty message")
   376  	}
   377  }
   378  
   379  func TestDup(t *testing.T) {
   380  	file, err := ioutil.TempFile("", "TestDup")
   381  	if err != nil {
   382  		t.Fatalf("Tempfile failed: %v", err)
   383  	}
   384  	defer os.Remove(file.Name())
   385  	defer file.Close()
   386  	f := int(file.Fd())
   387  
   388  	newFd, err := unix.Dup(f)
   389  	if err != nil {
   390  		t.Fatalf("Dup: %v", err)
   391  	}
   392  
   393  	err = unix.Dup2(newFd, newFd+1)
   394  	if err != nil {
   395  		t.Fatalf("Dup2: %v", err)
   396  	}
   397  
   398  	b1 := []byte("Test123")
   399  	b2 := make([]byte, 7)
   400  	_, err = unix.Write(newFd+1, b1)
   401  	if err != nil {
   402  		t.Fatalf("Write to dup2 fd failed: %v", err)
   403  	}
   404  	_, err = unix.Seek(f, 0, 0)
   405  	if err != nil {
   406  		t.Fatalf("Seek failed: %v", err)
   407  	}
   408  	_, err = unix.Read(f, b2)
   409  	if err != nil {
   410  		t.Fatalf("Read back failed: %v", err)
   411  	}
   412  	if string(b1) != string(b2) {
   413  		t.Errorf("Dup: stdout write not in file, expected %v, got %v", string(b1), string(b2))
   414  	}
   415  }
   416  
   417  func TestPoll(t *testing.T) {
   418  	if runtime.GOOS == "android" ||
   419  		(runtime.GOOS == "darwin" && (runtime.GOARCH == "arm" || runtime.GOARCH == "arm64")) {
   420  		t.Skip("mkfifo syscall is not available on android and iOS, skipping test")
   421  	}
   422  
   423  	f, cleanup := mktmpfifo(t)
   424  	defer cleanup()
   425  
   426  	const timeout = 100
   427  
   428  	ok := make(chan bool, 1)
   429  	go func() {
   430  		select {
   431  		case <-time.After(10 * timeout * time.Millisecond):
   432  			t.Errorf("Poll: failed to timeout after %d milliseconds", 10*timeout)
   433  		case <-ok:
   434  		}
   435  	}()
   436  
   437  	fds := []unix.PollFd{{Fd: int32(f.Fd()), Events: unix.POLLIN}}
   438  	n, err := unix.Poll(fds, timeout)
   439  	ok <- true
   440  	if err != nil {
   441  		t.Errorf("Poll: unexpected error: %v", err)
   442  		return
   443  	}
   444  	if n != 0 {
   445  		t.Errorf("Poll: wrong number of events: got %v, expected %v", n, 0)
   446  		return
   447  	}
   448  }
   449  
   450  func TestGetwd(t *testing.T) {
   451  	fd, err := os.Open(".")
   452  	if err != nil {
   453  		t.Fatalf("Open .: %s", err)
   454  	}
   455  	defer fd.Close()
   456  	// These are chosen carefully not to be symlinks on a Mac
   457  	// (unlike, say, /var, /etc)
   458  	dirs := []string{"/", "/usr/bin"}
   459  	switch runtime.GOOS {
   460  	case "android":
   461  		dirs = []string{"/", "/system/bin"}
   462  	case "darwin":
   463  		switch runtime.GOARCH {
   464  		case "arm", "arm64":
   465  			d1, err := ioutil.TempDir("", "d1")
   466  			if err != nil {
   467  				t.Fatalf("TempDir: %v", err)
   468  			}
   469  			d2, err := ioutil.TempDir("", "d2")
   470  			if err != nil {
   471  				t.Fatalf("TempDir: %v", err)
   472  			}
   473  			dirs = []string{d1, d2}
   474  		}
   475  	}
   476  	oldwd := os.Getenv("PWD")
   477  	for _, d := range dirs {
   478  		err = os.Chdir(d)
   479  		if err != nil {
   480  			t.Fatalf("Chdir: %v", err)
   481  		}
   482  		pwd, err := unix.Getwd()
   483  		if err != nil {
   484  			t.Fatalf("Getwd in %s: %s", d, err)
   485  		}
   486  		os.Setenv("PWD", oldwd)
   487  		err = fd.Chdir()
   488  		if err != nil {
   489  			// We changed the current directory and cannot go back.
   490  			// Don't let the tests continue; they'll scribble
   491  			// all over some other directory.
   492  			fmt.Fprintf(os.Stderr, "fchdir back to dot failed: %s\n", err)
   493  			os.Exit(1)
   494  		}
   495  		if pwd != d {
   496  			t.Fatalf("Getwd returned %q want %q", pwd, d)
   497  		}
   498  	}
   499  }
   500  
   501  func TestFstatat(t *testing.T) {
   502  	defer chtmpdir(t)()
   503  
   504  	touch(t, "file1")
   505  
   506  	var st1 unix.Stat_t
   507  	err := unix.Stat("file1", &st1)
   508  	if err != nil {
   509  		t.Fatalf("Stat: %v", err)
   510  	}
   511  
   512  	var st2 unix.Stat_t
   513  	err = unix.Fstatat(unix.AT_FDCWD, "file1", &st2, 0)
   514  	if err != nil {
   515  		t.Fatalf("Fstatat: %v", err)
   516  	}
   517  
   518  	if st1 != st2 {
   519  		t.Errorf("Fstatat: returned stat does not match Stat")
   520  	}
   521  
   522  	err = os.Symlink("file1", "symlink1")
   523  	if err != nil {
   524  		t.Fatal(err)
   525  	}
   526  
   527  	err = unix.Lstat("symlink1", &st1)
   528  	if err != nil {
   529  		t.Fatalf("Lstat: %v", err)
   530  	}
   531  
   532  	err = unix.Fstatat(unix.AT_FDCWD, "symlink1", &st2, unix.AT_SYMLINK_NOFOLLOW)
   533  	if err != nil {
   534  		t.Fatalf("Fstatat: %v", err)
   535  	}
   536  
   537  	if st1 != st2 {
   538  		t.Errorf("Fstatat: returned stat does not match Lstat")
   539  	}
   540  }
   541  
   542  func TestFchmodat(t *testing.T) {
   543  	defer chtmpdir(t)()
   544  
   545  	touch(t, "file1")
   546  	err := os.Symlink("file1", "symlink1")
   547  	if err != nil {
   548  		t.Fatal(err)
   549  	}
   550  
   551  	mode := os.FileMode(0444)
   552  	err = unix.Fchmodat(unix.AT_FDCWD, "symlink1", uint32(mode), 0)
   553  	if err != nil {
   554  		t.Fatalf("Fchmodat: unexpected error: %v", err)
   555  	}
   556  
   557  	fi, err := os.Stat("file1")
   558  	if err != nil {
   559  		t.Fatal(err)
   560  	}
   561  
   562  	if fi.Mode() != mode {
   563  		t.Errorf("Fchmodat: failed to change file mode: expected %v, got %v", mode, fi.Mode())
   564  	}
   565  
   566  	mode = os.FileMode(0644)
   567  	didChmodSymlink := true
   568  	err = unix.Fchmodat(unix.AT_FDCWD, "symlink1", uint32(mode), unix.AT_SYMLINK_NOFOLLOW)
   569  	if err != nil {
   570  		if (runtime.GOOS == "android" || runtime.GOOS == "linux" || runtime.GOOS == "solaris") && err == unix.EOPNOTSUPP {
   571  			// Linux and Illumos don't support flags != 0
   572  			didChmodSymlink = false
   573  		} else {
   574  			t.Fatalf("Fchmodat: unexpected error: %v", err)
   575  		}
   576  	}
   577  
   578  	if !didChmodSymlink {
   579  		// Didn't change mode of the symlink. On Linux, the permissions
   580  		// of a symbolic link are always 0777 according to symlink(7)
   581  		mode = os.FileMode(0777)
   582  	}
   583  
   584  	var st unix.Stat_t
   585  	err = unix.Lstat("symlink1", &st)
   586  	if err != nil {
   587  		t.Fatal(err)
   588  	}
   589  
   590  	got := os.FileMode(st.Mode & 0777)
   591  	if got != mode {
   592  		t.Errorf("Fchmodat: failed to change symlink mode: expected %v, got %v", mode, got)
   593  	}
   594  }
   595  
   596  func TestMkdev(t *testing.T) {
   597  	major := uint32(42)
   598  	minor := uint32(7)
   599  	dev := unix.Mkdev(major, minor)
   600  
   601  	if unix.Major(dev) != major {
   602  		t.Errorf("Major(%#x) == %d, want %d", dev, unix.Major(dev), major)
   603  	}
   604  	if unix.Minor(dev) != minor {
   605  		t.Errorf("Minor(%#x) == %d, want %d", dev, unix.Minor(dev), minor)
   606  	}
   607  }
   608  
   609  // mktmpfifo creates a temporary FIFO and provides a cleanup function.
   610  func mktmpfifo(t *testing.T) (*os.File, func()) {
   611  	err := unix.Mkfifo("fifo", 0666)
   612  	if err != nil {
   613  		t.Fatalf("mktmpfifo: failed to create FIFO: %v", err)
   614  	}
   615  
   616  	f, err := os.OpenFile("fifo", os.O_RDWR, 0666)
   617  	if err != nil {
   618  		os.Remove("fifo")
   619  		t.Fatalf("mktmpfifo: failed to open FIFO: %v", err)
   620  	}
   621  
   622  	return f, func() {
   623  		f.Close()
   624  		os.Remove("fifo")
   625  	}
   626  }
   627  
   628  // utilities taken from os/os_test.go
   629  
   630  func touch(t *testing.T, name string) {
   631  	f, err := os.Create(name)
   632  	if err != nil {
   633  		t.Fatal(err)
   634  	}
   635  	if err := f.Close(); err != nil {
   636  		t.Fatal(err)
   637  	}
   638  }
   639  
   640  // chtmpdir changes the working directory to a new temporary directory and
   641  // provides a cleanup function. Used when PWD is read-only.
   642  func chtmpdir(t *testing.T) func() {
   643  	oldwd, err := os.Getwd()
   644  	if err != nil {
   645  		t.Fatalf("chtmpdir: %v", err)
   646  	}
   647  	d, err := ioutil.TempDir("", "test")
   648  	if err != nil {
   649  		t.Fatalf("chtmpdir: %v", err)
   650  	}
   651  	if err := os.Chdir(d); err != nil {
   652  		t.Fatalf("chtmpdir: %v", err)
   653  	}
   654  	return func() {
   655  		if err := os.Chdir(oldwd); err != nil {
   656  			t.Fatalf("chtmpdir: %v", err)
   657  		}
   658  		os.RemoveAll(d)
   659  	}
   660  }