...

Source file src/golang.org/x/sys/unix/syscall_zos_test.go

Documentation: golang.org/x/sys/unix

     1  // Copyright 2020 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  //go:build zos && s390x
     6  
     7  package unix_test
     8  
     9  import (
    10  	"flag"
    11  	"fmt"
    12  	"io"
    13  	"net"
    14  	"os"
    15  	"os/exec"
    16  	"path/filepath"
    17  	"runtime"
    18  	"strconv"
    19  	"syscall"
    20  	"testing"
    21  	"time"
    22  	"unsafe"
    23  
    24  	"golang.org/x/sys/unix"
    25  )
    26  
    27  // Tests that below functions, structures and constants are consistent
    28  // on all Unix-like systems.
    29  func _() {
    30  	// program scheduling priority functions and constants
    31  	var (
    32  		_ func(int, int, int) error   = unix.Setpriority
    33  		_ func(int, int) (int, error) = unix.Getpriority
    34  	)
    35  	const (
    36  		_ int = unix.PRIO_USER
    37  		_ int = unix.PRIO_PROCESS
    38  		_ int = unix.PRIO_PGRP
    39  	)
    40  
    41  	// termios constants
    42  	const (
    43  		_ int = unix.TCIFLUSH
    44  		_ int = unix.TCIOFLUSH
    45  		_ int = unix.TCOFLUSH
    46  	)
    47  
    48  	// fcntl file locking structure and constants
    49  	var (
    50  		_ = unix.Flock_t{
    51  			Type:   int16(0),
    52  			Whence: int16(0),
    53  			Start:  int64(0),
    54  			Len:    int64(0),
    55  			Pid:    int32(0),
    56  		}
    57  	)
    58  	const (
    59  		_ = unix.F_GETLK
    60  		_ = unix.F_SETLK
    61  		_ = unix.F_SETLKW
    62  	)
    63  }
    64  
    65  func TestErrnoSignalName(t *testing.T) {
    66  	testErrors := []struct {
    67  		num  syscall.Errno
    68  		name string
    69  	}{
    70  		{syscall.EPERM, "EDC5139I"},
    71  		{syscall.EINVAL, "EDC5121I"},
    72  		{syscall.ENOENT, "EDC5129I"},
    73  	}
    74  
    75  	for _, te := range testErrors {
    76  		t.Run(fmt.Sprintf("%d/%s", te.num, te.name), func(t *testing.T) {
    77  			e := unix.ErrnoName(te.num)
    78  			if e != te.name {
    79  				t.Errorf("ErrnoName(%d) returned %s, want %s", te.num, e, te.name)
    80  			}
    81  		})
    82  	}
    83  
    84  	testSignals := []struct {
    85  		num  syscall.Signal
    86  		name string
    87  	}{
    88  		{syscall.SIGHUP, "SIGHUP"},
    89  		{syscall.SIGPIPE, "SIGPIPE"},
    90  		{syscall.SIGSEGV, "SIGSEGV"},
    91  	}
    92  
    93  	for _, ts := range testSignals {
    94  		t.Run(fmt.Sprintf("%d/%s", ts.num, ts.name), func(t *testing.T) {
    95  			s := unix.SignalName(ts.num)
    96  			if s != ts.name {
    97  				t.Errorf("SignalName(%d) returned %s, want %s", ts.num, s, ts.name)
    98  			}
    99  		})
   100  	}
   101  }
   102  
   103  func TestSignalNum(t *testing.T) {
   104  	testSignals := []struct {
   105  		name string
   106  		want syscall.Signal
   107  	}{
   108  		{"SIGHUP", syscall.SIGHUP},
   109  		{"SIGPIPE", syscall.SIGPIPE},
   110  		{"SIGSEGV", syscall.SIGSEGV},
   111  		{"NONEXISTS", 0},
   112  	}
   113  	for _, ts := range testSignals {
   114  		t.Run(fmt.Sprintf("%s/%d", ts.name, ts.want), func(t *testing.T) {
   115  			got := unix.SignalNum(ts.name)
   116  			if got != ts.want {
   117  				t.Errorf("SignalNum(%s) returned %d, want %d", ts.name, got, ts.want)
   118  			}
   119  		})
   120  
   121  	}
   122  }
   123  
   124  func TestFcntlInt(t *testing.T) {
   125  	t.Parallel()
   126  	file, err := os.Create(filepath.Join(t.TempDir(), "TestFnctlInt"))
   127  	if err != nil {
   128  		t.Fatal(err)
   129  	}
   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(t.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.Close(fd)
   150  	flock := unix.Flock_t{
   151  		Type:  unix.F_RDLCK,
   152  		Start: 0, Len: 0, Whence: 1,
   153  	}
   154  	if err := unix.FcntlFlock(uintptr(fd), unix.F_GETLK, &flock); err != nil {
   155  		t.Fatalf("FcntlFlock failed: %v", err)
   156  	}
   157  }
   158  
   159  // TestPassFD tests passing a file descriptor over a Unix socket.
   160  //
   161  // This test involved both a parent and child process. The parent
   162  // process is invoked as a normal test, with "go test", which then
   163  // runs the child process by running the current test binary with args
   164  // "-test.run=^TestPassFD$" and an environment variable used to signal
   165  // that the test should become the child process instead.
   166  func TestPassFD(t *testing.T) {
   167  	if runtime.GOOS == "darwin" && runtime.GOARCH == "arm64" {
   168  		t.Skip("cannot exec subprocess on iOS, skipping test")
   169  	}
   170  
   171  	if os.Getenv("GO_WANT_HELPER_PROCESS") == "1" {
   172  		passFDChild()
   173  		return
   174  	}
   175  
   176  	if runtime.GOOS == "aix" {
   177  		// Unix network isn't properly working on AIX
   178  		// 7.2 with Technical Level < 2
   179  		out, err := exec.Command("oslevel", "-s").Output()
   180  		if err != nil {
   181  			t.Skipf("skipping on AIX because oslevel -s failed: %v", err)
   182  		}
   183  
   184  		if len(out) < len("7200-XX-ZZ-YYMM") { // AIX 7.2, Tech Level XX, Service Pack ZZ, date YYMM
   185  			t.Skip("skipping on AIX because oslevel -s hasn't the right length")
   186  		}
   187  		aixVer := string(out[:4])
   188  		tl, err := strconv.Atoi(string(out[5:7]))
   189  		if err != nil {
   190  			t.Skipf("skipping on AIX because oslevel -s output cannot be parsed: %v", err)
   191  		}
   192  		if aixVer < "7200" || (aixVer == "7200" && tl < 2) {
   193  			t.Skip("skipped on AIX versions previous to 7.2 TL 2")
   194  		}
   195  	}
   196  
   197  	fds, err := unix.Socketpair(unix.AF_LOCAL, unix.SOCK_STREAM, 0)
   198  	if err != nil {
   199  		t.Fatalf("Socketpair: %v", err)
   200  	}
   201  	writeFile := os.NewFile(uintptr(fds[0]), "child-writes")
   202  	readFile := os.NewFile(uintptr(fds[1]), "parent-reads")
   203  	defer writeFile.Close()
   204  	defer readFile.Close()
   205  
   206  	cmd := exec.Command(os.Args[0], "-test.run=^TestPassFD$", "--", t.TempDir())
   207  	cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"}
   208  	if lp := os.Getenv("LD_LIBRARY_PATH"); lp != "" {
   209  		cmd.Env = append(cmd.Env, "LD_LIBRARY_PATH="+lp)
   210  	}
   211  	cmd.ExtraFiles = []*os.File{writeFile}
   212  
   213  	out, err := cmd.CombinedOutput()
   214  	if len(out) > 0 || err != nil {
   215  		t.Fatalf("child process: %q, %v", out, err)
   216  	}
   217  
   218  	c, err := net.FileConn(readFile)
   219  	if err != nil {
   220  		t.Fatalf("FileConn: %v", err)
   221  	}
   222  	defer c.Close()
   223  
   224  	uc, ok := c.(*net.UnixConn)
   225  	if !ok {
   226  		t.Fatalf("unexpected FileConn type; expected UnixConn, got %T", c)
   227  	}
   228  
   229  	buf := make([]byte, 32) // expect 1 byte
   230  	oob := make([]byte, 32) // expect 24 bytes
   231  	closeUnix := time.AfterFunc(5*time.Second, func() {
   232  		t.Logf("timeout reading from unix socket")
   233  		uc.Close()
   234  	})
   235  	_, oobn, _, _, err := uc.ReadMsgUnix(buf, oob)
   236  	if err != nil {
   237  		t.Fatalf("ReadMsgUnix: %v", err)
   238  	}
   239  	closeUnix.Stop()
   240  
   241  	scms, err := unix.ParseSocketControlMessage(oob[:oobn])
   242  	if err != nil {
   243  		t.Fatalf("ParseSocketControlMessage: %v", err)
   244  	}
   245  	if len(scms) != 1 {
   246  		t.Fatalf("expected 1 SocketControlMessage; got scms = %#v", scms)
   247  	}
   248  	scm := scms[0]
   249  	gotFds, err := unix.ParseUnixRights(&scm)
   250  	if err != nil {
   251  		t.Fatalf("unix.ParseUnixRights: %v", err)
   252  	}
   253  	if len(gotFds) != 1 {
   254  		t.Fatalf("wanted 1 fd; got %#v", gotFds)
   255  	}
   256  
   257  	f := os.NewFile(uintptr(gotFds[0]), "fd-from-child")
   258  	defer f.Close()
   259  
   260  	got, err := io.ReadAll(f)
   261  	want := "Hello from child process!\n"
   262  	if string(got) != want {
   263  		t.Errorf("child process ReadAll: %q, %v; want %q", got, err, want)
   264  	}
   265  }
   266  
   267  // passFDChild is the child process used by TestPassFD.
   268  func passFDChild() {
   269  	defer os.Exit(0)
   270  
   271  	// Look for our fd. It should be fd 3, but we work around an fd leak
   272  	// bug here (http://golang.org/issue/2603) to let it be elsewhere.
   273  	var uc *net.UnixConn
   274  	for fd := uintptr(3); fd <= 10; fd++ {
   275  		f := os.NewFile(fd, "unix-conn")
   276  		var ok bool
   277  		netc, _ := net.FileConn(f)
   278  		uc, ok = netc.(*net.UnixConn)
   279  		if ok {
   280  			break
   281  		}
   282  	}
   283  	if uc == nil {
   284  		fmt.Println("failed to find unix fd")
   285  		return
   286  	}
   287  
   288  	// Make a file f to send to our parent process on uc.
   289  	// We make it in tempDir, which our parent will clean up.
   290  	flag.Parse()
   291  	tempDir := flag.Arg(0)
   292  	f, err := os.Create(filepath.Join(tempDir, "file"))
   293  	if err != nil {
   294  		fmt.Println(err)
   295  		return
   296  	}
   297  
   298  	f.Write([]byte("Hello from child process!\n"))
   299  	f.Seek(0, 0)
   300  
   301  	rights := unix.UnixRights(int(f.Fd()))
   302  	dummyByte := []byte("x")
   303  	n, oobn, err := uc.WriteMsgUnix(dummyByte, rights, nil)
   304  	if err != nil {
   305  		fmt.Printf("WriteMsgUnix: %v", err)
   306  		return
   307  	}
   308  	if n != 1 || oobn != len(rights) {
   309  		fmt.Printf("WriteMsgUnix = %d, %d; want 1, %d", n, oobn, len(rights))
   310  		return
   311  	}
   312  }
   313  
   314  // TestUnixRightsRoundtrip tests that UnixRights, ParseSocketControlMessage,
   315  // and ParseUnixRights are able to successfully round-trip lists of file descriptors.
   316  func TestUnixRightsRoundtrip(t *testing.T) {
   317  	testCases := [...][][]int{
   318  		{{42}},
   319  		{{1, 2}},
   320  		{{3, 4, 5}},
   321  		{{}},
   322  		{{1, 2}, {3, 4, 5}, {}, {7}},
   323  	}
   324  	for _, testCase := range testCases {
   325  		b := []byte{}
   326  		var n int
   327  		for _, fds := range testCase {
   328  			// Last assignment to n wins
   329  			n = len(b) + unix.CmsgLen(4*len(fds))
   330  			b = append(b, unix.UnixRights(fds...)...)
   331  		}
   332  		// Truncate b
   333  		b = b[:n]
   334  
   335  		scms, err := unix.ParseSocketControlMessage(b)
   336  		if err != nil {
   337  			t.Fatalf("ParseSocketControlMessage: %v", err)
   338  		}
   339  		if len(scms) != len(testCase) {
   340  			t.Fatalf("expected %v SocketControlMessage; got scms = %#v", len(testCase), scms)
   341  		}
   342  		for i, scm := range scms {
   343  			gotFds, err := unix.ParseUnixRights(&scm)
   344  			if err != nil {
   345  				t.Fatalf("ParseUnixRights: %v", err)
   346  			}
   347  			wantFds := testCase[i]
   348  			if len(gotFds) != len(wantFds) {
   349  				t.Fatalf("expected %v fds, got %#v", len(wantFds), gotFds)
   350  			}
   351  			for j, fd := range gotFds {
   352  				if fd != wantFds[j] {
   353  					t.Fatalf("expected fd %v, got %v", wantFds[j], fd)
   354  				}
   355  			}
   356  		}
   357  	}
   358  }
   359  
   360  func TestRlimit(t *testing.T) {
   361  	var rlimit, zero unix.Rlimit
   362  	err := unix.Getrlimit(unix.RLIMIT_NOFILE, &rlimit)
   363  	if err != nil {
   364  		t.Fatalf("Getrlimit: save failed: %v", err)
   365  	}
   366  	if zero == rlimit {
   367  		t.Fatalf("Getrlimit: save failed: got zero value %#v", rlimit)
   368  	}
   369  	set := rlimit
   370  	set.Cur = set.Max - 1
   371  	if runtime.GOOS == "darwin" && set.Cur > 10240 {
   372  		// The max file limit is 10240, even though
   373  		// the max returned by Getrlimit is 1<<63-1.
   374  		// This is OPEN_MAX in sys/syslimits.h.
   375  		set.Cur = 10240
   376  	}
   377  	err = unix.Setrlimit(unix.RLIMIT_NOFILE, &set)
   378  	if err != nil {
   379  		t.Fatalf("Setrlimit: set failed: %#v %v", set, err)
   380  	}
   381  	var get unix.Rlimit
   382  	err = unix.Getrlimit(unix.RLIMIT_NOFILE, &get)
   383  	if err != nil {
   384  		t.Fatalf("Getrlimit: get failed: %v", err)
   385  	}
   386  	set = rlimit
   387  	set.Cur = set.Max - 1
   388  	if set != get {
   389  		// Seems like Darwin requires some privilege to
   390  		// increase the soft limit of rlimit sandbox, though
   391  		// Setrlimit never reports an error.
   392  		switch runtime.GOOS {
   393  		case "darwin":
   394  		default:
   395  			t.Fatalf("Rlimit: change failed: wanted %#v got %#v", set, get)
   396  		}
   397  	}
   398  	err = unix.Setrlimit(unix.RLIMIT_NOFILE, &rlimit)
   399  	if err != nil {
   400  		t.Fatalf("Setrlimit: restore failed: %#v %v", rlimit, err)
   401  	}
   402  }
   403  
   404  func TestSeekFailure(t *testing.T) {
   405  	_, err := unix.Seek(-1, 0, 0)
   406  	if err == nil {
   407  		t.Fatalf("Seek(-1, 0, 0) did not fail")
   408  	}
   409  	str := err.Error() // used to crash on Linux
   410  	t.Logf("Seek: %v", str)
   411  	if str == "" {
   412  		t.Fatalf("Seek(-1, 0, 0) return error with empty message")
   413  	}
   414  }
   415  
   416  func TestSetsockoptString(t *testing.T) {
   417  	// should not panic on empty string, see issue #31277
   418  	err := unix.SetsockoptString(-1, 0, 0, "")
   419  	if err == nil {
   420  		t.Fatalf("SetsockoptString: did not fail")
   421  	}
   422  }
   423  
   424  func TestDup(t *testing.T) {
   425  	file, err := os.Create(filepath.Join(t.TempDir(), "TestDup"))
   426  	if err != nil {
   427  		t.Fatal(err)
   428  	}
   429  	defer file.Close()
   430  	f := int(file.Fd())
   431  
   432  	newFd, err := unix.Dup(f)
   433  	if err != nil {
   434  		t.Fatalf("Dup: %v", err)
   435  	}
   436  
   437  	// Create and reserve a file descriptor.
   438  	// Dup2 automatically closes it before reusing it.
   439  	nullFile, err := os.Open("/dev/null")
   440  	if err != nil {
   441  		t.Fatal(err)
   442  	}
   443  	dupFd := int(file.Fd())
   444  	err = unix.Dup2(newFd, dupFd)
   445  	if err != nil {
   446  		t.Fatalf("Dup2: %v", err)
   447  	}
   448  	// Keep the dummy file open long enough to not be closed in
   449  	// its finalizer.
   450  	runtime.KeepAlive(nullFile)
   451  
   452  	b1 := []byte("Test123")
   453  	b2 := make([]byte, 7)
   454  	_, err = unix.Write(dupFd, b1)
   455  	if err != nil {
   456  		t.Fatalf("Write to dup2 fd failed: %v", err)
   457  	}
   458  	_, err = unix.Seek(f, 0, 0)
   459  	if err != nil {
   460  		t.Fatalf("Seek failed: %v", err)
   461  	}
   462  	_, err = unix.Read(f, b2)
   463  	if err != nil {
   464  		t.Fatalf("Read back failed: %v", err)
   465  	}
   466  	if string(b1) != string(b2) {
   467  		t.Errorf("Dup: stdout write not in file, expected %v, got %v", string(b1), string(b2))
   468  	}
   469  }
   470  
   471  func TestGetwd(t *testing.T) {
   472  	fd, err := os.Open(".")
   473  	if err != nil {
   474  		t.Fatalf("Open .: %s", err)
   475  	}
   476  	defer fd.Close()
   477  	// Directory list for test. Do not worry if any are symlinks or do not
   478  	// exist on some common unix desktop environments. That will be checked.
   479  	dirs := []string{"/", "/usr/bin", "/etc", "/var", "/opt"}
   480  	switch runtime.GOOS {
   481  	case "android":
   482  		dirs = []string{"/", "/system/bin"}
   483  	case "darwin":
   484  		switch runtime.GOARCH {
   485  		case "arm64":
   486  			dirs = []string{t.TempDir(), t.TempDir()}
   487  		}
   488  	}
   489  	oldwd := os.Getenv("PWD")
   490  	for _, d := range dirs {
   491  		// Check whether d exists, is a dir and that d's path does not contain a symlink
   492  		fi, err := os.Stat(d)
   493  		if err != nil || !fi.IsDir() {
   494  			t.Logf("Test dir %s stat error (%v) or not a directory, skipping", d, err)
   495  			continue
   496  		}
   497  		check, err := filepath.EvalSymlinks(d)
   498  		if err != nil || check != d {
   499  			t.Logf("Test dir %s (%s) is symlink or other error (%v), skipping", d, check, err)
   500  			continue
   501  		}
   502  		err = os.Chdir(d)
   503  		if err != nil {
   504  			t.Fatalf("Chdir: %v", err)
   505  		}
   506  		pwd, err := unix.Getwd()
   507  		if err != nil {
   508  			t.Fatalf("Getwd in %s: %s", d, err)
   509  		}
   510  		os.Setenv("PWD", oldwd)
   511  		err = fd.Chdir()
   512  		if err != nil {
   513  			// We changed the current directory and cannot go back.
   514  			// Don't let the tests continue; they'll scribble
   515  			// all over some other directory.
   516  			fmt.Fprintf(os.Stderr, "fchdir back to dot failed: %s\n", err)
   517  			os.Exit(1)
   518  		}
   519  		if pwd != d {
   520  			t.Fatalf("Getwd returned %q want %q", pwd, d)
   521  		}
   522  	}
   523  }
   524  
   525  func TestMkdev(t *testing.T) {
   526  	major := uint32(42)
   527  	minor := uint32(7)
   528  	dev := unix.Mkdev(major, minor)
   529  
   530  	if unix.Major(dev) != major {
   531  		t.Errorf("Major(%#x) == %d, want %d", dev, unix.Major(dev), major)
   532  	}
   533  	if unix.Minor(dev) != minor {
   534  		t.Errorf("Minor(%#x) == %d, want %d", dev, unix.Minor(dev), minor)
   535  	}
   536  }
   537  
   538  func TestMountUnmount(t *testing.T) {
   539  	// use an available fs
   540  	var buffer struct {
   541  		header unix.W_Mnth
   542  		fsinfo [64]unix.W_Mntent
   543  	}
   544  	fsCount, err := unix.W_Getmntent_A((*byte)(unsafe.Pointer(&buffer)), int(unsafe.Sizeof(buffer)))
   545  	if err != nil {
   546  		t.Fatalf("W_Getmntent_A returns with error: %s", err.Error())
   547  	} else if fsCount == 0 {
   548  		t.Fatalf("W_Getmntent_A returns no entries")
   549  	}
   550  	var fs string
   551  	var fstype string
   552  	var mountpoint string
   553  	var available bool = false
   554  	for i := 0; i < fsCount; i++ {
   555  		err = unix.Unmount(unix.ByteSliceToString(buffer.fsinfo[i].Mountpoint[:]), unix.MTM_RDWR)
   556  		if err != nil {
   557  			// Unmount and Mount require elevated privilege
   558  			// If test is run without such permission, skip test
   559  			if err == unix.EPERM {
   560  				t.Logf("Permission denied for Unmount. Skipping test (Errno2:  %X)", unix.Errno2())
   561  				return
   562  			} else if err == unix.EBUSY {
   563  				continue
   564  			} else {
   565  				t.Fatalf("Unmount returns with error: %s", err.Error())
   566  			}
   567  		} else {
   568  			available = true
   569  			fs = unix.ByteSliceToString(buffer.fsinfo[i].Fsname[:])
   570  			fstype = unix.ByteSliceToString(buffer.fsinfo[i].Fstname[:])
   571  			mountpoint = unix.ByteSliceToString(buffer.fsinfo[i].Mountpoint[:])
   572  			t.Logf("using file system = %s; fstype = %s and mountpoint = %s\n", fs, fstype, mountpoint)
   573  			break
   574  		}
   575  	}
   576  	if !available {
   577  		t.Fatalf("No filesystem available")
   578  	}
   579  	// test unmount
   580  	buffer.header = unix.W_Mnth{}
   581  	fsCount, err = unix.W_Getmntent_A((*byte)(unsafe.Pointer(&buffer)), int(unsafe.Sizeof(buffer)))
   582  	if err != nil {
   583  		t.Fatalf("W_Getmntent_A returns with error: %s", err.Error())
   584  	}
   585  	for i := 0; i < fsCount; i++ {
   586  		if unix.ByteSliceToString(buffer.fsinfo[i].Fsname[:]) == fs {
   587  			t.Fatalf("File system found after unmount")
   588  		}
   589  	}
   590  	// test mount
   591  	err = unix.Mount(fs, mountpoint, fstype, unix.MTM_RDWR, "")
   592  	if err != nil {
   593  		t.Fatalf("Mount returns with error: %s", err.Error())
   594  	}
   595  	buffer.header = unix.W_Mnth{}
   596  	fsCount, err = unix.W_Getmntent_A((*byte)(unsafe.Pointer(&buffer)), int(unsafe.Sizeof(buffer)))
   597  	if err != nil {
   598  		t.Fatalf("W_Getmntent_A returns with error: %s", err.Error())
   599  	}
   600  	fsMounted := false
   601  	for i := 0; i < fsCount; i++ {
   602  		if unix.ByteSliceToString(buffer.fsinfo[i].Fsname[:]) == fs &&
   603  			unix.ByteSliceToString(buffer.fsinfo[i].Mountpoint[:]) == mountpoint {
   604  			fsMounted = true
   605  		}
   606  	}
   607  	if !fsMounted {
   608  		t.Fatalf("%s not mounted after Mount()", fs)
   609  	}
   610  }
   611  
   612  func TestChroot(t *testing.T) {
   613  	// create temp dir and tempfile 1
   614  	tempDir := t.TempDir()
   615  	f, err := os.Create(filepath.Join(tempDir, "chroot_test_file"))
   616  	if err != nil {
   617  		t.Fatal(err)
   618  	}
   619  	// chroot temp dir
   620  	err = unix.Chroot(tempDir)
   621  	// Chroot requires elevated privilege
   622  	// If test is run without such permission, skip test
   623  	if err == unix.EPERM {
   624  		t.Logf("Denied permission for Chroot. Skipping test (Errno2:  %X)", unix.Errno2())
   625  		return
   626  	} else if err != nil {
   627  		t.Fatalf("Chroot: %s", err.Error())
   628  	}
   629  	// check if tempDir contains test file
   630  	files, err := os.ReadDir("/")
   631  	if err != nil {
   632  		t.Fatalf("ReadDir: %s", err.Error())
   633  	}
   634  	found := false
   635  	for _, file := range files {
   636  		if file.Name() == filepath.Base(f.Name()) {
   637  			found = true
   638  			break
   639  		}
   640  	}
   641  	if !found {
   642  		t.Fatalf("Temp file not found in temp dir")
   643  	}
   644  }
   645  
   646  func TestFlock(t *testing.T) {
   647  	if os.Getenv("GO_WANT_HELPER_PROCESS") == "1" {
   648  		defer os.Exit(0)
   649  		if len(os.Args) != 3 {
   650  			fmt.Printf("bad argument")
   651  			return
   652  		}
   653  		fn := os.Args[2]
   654  		f, err := os.OpenFile(fn, os.O_RDWR, 0755)
   655  		if err != nil {
   656  			fmt.Printf("%s", err.Error())
   657  			return
   658  		}
   659  		err = unix.Flock(int(f.Fd()), unix.LOCK_EX|unix.LOCK_NB)
   660  		// if the lock we are trying should be locked, ignore EAGAIN error
   661  		// otherwise, report all errors
   662  		if err != nil && err != unix.EAGAIN {
   663  			fmt.Printf("%s", err.Error())
   664  		}
   665  	} else {
   666  		// create temp dir and tempfile 1
   667  		f, err := os.Create(filepath.Join(t.TempDir(), "flock_test_file"))
   668  		if err != nil {
   669  			t.Fatal(err)
   670  		}
   671  		fd := int(f.Fd())
   672  
   673  		/* Test Case 1
   674  		 * Try acquiring an occupied lock from another process
   675  		 */
   676  		err = unix.Flock(fd, unix.LOCK_EX)
   677  		if err != nil {
   678  			t.Fatalf("Flock: %s", err.Error())
   679  		}
   680  		cmd := exec.Command(os.Args[0], "-test.run=^TestFlock$", f.Name())
   681  		cmd.Env = append(os.Environ(), "GO_WANT_HELPER_PROCESS=1")
   682  		out, err := cmd.CombinedOutput()
   683  		if len(out) > 0 || err != nil {
   684  			t.Fatalf("child process: %q, %v", out, err)
   685  		}
   686  		err = unix.Flock(fd, unix.LOCK_UN)
   687  		if err != nil {
   688  			t.Fatalf("Flock: %s", err.Error())
   689  		}
   690  
   691  		/* Test Case 2
   692  		 * Try locking with Flock and FcntlFlock for same file
   693  		 */
   694  		err = unix.Flock(fd, unix.LOCK_EX)
   695  		if err != nil {
   696  			t.Fatalf("Flock: %s", err.Error())
   697  		}
   698  		flock := unix.Flock_t{
   699  			Type:   int16(unix.F_WRLCK),
   700  			Whence: int16(0),
   701  			Start:  int64(0),
   702  			Len:    int64(0),
   703  			Pid:    int32(unix.Getppid()),
   704  		}
   705  		err = unix.FcntlFlock(f.Fd(), unix.F_SETLK, &flock)
   706  		if err != nil {
   707  			t.Fatalf("FcntlFlock: %s", err.Error())
   708  		}
   709  	}
   710  }
   711  
   712  func TestSelect(t *testing.T) {
   713  	for {
   714  		n, err := unix.Select(0, nil, nil, nil, &unix.Timeval{Sec: 0, Usec: 0})
   715  		if err == unix.EINTR {
   716  			t.Logf("Select interrupted")
   717  			continue
   718  		} else if err != nil {
   719  			t.Fatalf("Select: %v", err)
   720  		}
   721  		if n != 0 {
   722  			t.Fatalf("Select: got %v ready file descriptors, expected 0", n)
   723  		}
   724  		break
   725  	}
   726  
   727  	dur := 250 * time.Millisecond
   728  	var took time.Duration
   729  	for {
   730  		// On some platforms (e.g. Linux), the passed-in timeval is
   731  		// updated by select(2). Make sure to reset to the full duration
   732  		// in case of an EINTR.
   733  		tv := unix.NsecToTimeval(int64(dur))
   734  		start := time.Now()
   735  		n, err := unix.Select(0, nil, nil, nil, &tv)
   736  		took = time.Since(start)
   737  		if err == unix.EINTR {
   738  			t.Logf("Select interrupted after %v", took)
   739  			continue
   740  		} else if err != nil {
   741  			t.Fatalf("Select: %v", err)
   742  		}
   743  		if n != 0 {
   744  			t.Fatalf("Select: got %v ready file descriptors, expected 0", n)
   745  		}
   746  		break
   747  	}
   748  
   749  	// On some BSDs the actual timeout might also be slightly less than the requested.
   750  	// Add an acceptable margin to avoid flaky tests.
   751  	if took < dur*2/3 {
   752  		t.Errorf("Select: got %v timeout, expected at least %v", took, dur)
   753  	}
   754  
   755  	rr, ww, err := os.Pipe()
   756  	if err != nil {
   757  		t.Fatal(err)
   758  	}
   759  	defer rr.Close()
   760  	defer ww.Close()
   761  
   762  	if _, err := ww.Write([]byte("HELLO GOPHER")); err != nil {
   763  		t.Fatal(err)
   764  	}
   765  
   766  	rFdSet := &unix.FdSet{}
   767  	fd := int(rr.Fd())
   768  	rFdSet.Set(fd)
   769  
   770  	for {
   771  		n, err := unix.Select(fd+1, rFdSet, nil, nil, nil)
   772  		if err == unix.EINTR {
   773  			t.Log("Select interrupted")
   774  			continue
   775  		} else if err != nil {
   776  			t.Fatalf("Select: %v", err)
   777  		}
   778  		if n != 1 {
   779  			t.Fatalf("Select: got %v ready file descriptors, expected 1", n)
   780  		}
   781  		break
   782  	}
   783  }
   784  

View as plain text