github.com/aloncn/graphics-go@v0.0.1/src/syscall/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 darwin dragonfly freebsd linux netbsd openbsd solaris
     6  
     7  package syscall_test
     8  
     9  import (
    10  	"flag"
    11  	"fmt"
    12  	"internal/testenv"
    13  	"io/ioutil"
    14  	"net"
    15  	"os"
    16  	"os/exec"
    17  	"path/filepath"
    18  	"runtime"
    19  	"syscall"
    20  	"testing"
    21  	"time"
    22  )
    23  
    24  // Tests that below functions, structures and constants are consistent
    25  // on all Unix-like systems.
    26  func _() {
    27  	// program scheduling priority functions and constants
    28  	var (
    29  		_ func(int, int, int) error   = syscall.Setpriority
    30  		_ func(int, int) (int, error) = syscall.Getpriority
    31  	)
    32  	const (
    33  		_ int = syscall.PRIO_USER
    34  		_ int = syscall.PRIO_PROCESS
    35  		_ int = syscall.PRIO_PGRP
    36  	)
    37  
    38  	// termios constants
    39  	const (
    40  		_ int = syscall.TCIFLUSH
    41  		_ int = syscall.TCIOFLUSH
    42  		_ int = syscall.TCOFLUSH
    43  	)
    44  
    45  	// fcntl file locking structure and constants
    46  	var (
    47  		_ = syscall.Flock_t{
    48  			Type:   int16(0),
    49  			Whence: int16(0),
    50  			Start:  int64(0),
    51  			Len:    int64(0),
    52  			Pid:    int32(0),
    53  		}
    54  	)
    55  	const (
    56  		_ = syscall.F_GETLK
    57  		_ = syscall.F_SETLK
    58  		_ = syscall.F_SETLKW
    59  	)
    60  }
    61  
    62  // TestFcntlFlock tests whether the file locking structure matches
    63  // the calling convention of each kernel.
    64  // On some Linux systems, glibc uses another set of values for the
    65  // commands and translates them to the correct value that the kernel
    66  // expects just before the actual fcntl syscall. As Go uses raw
    67  // syscalls directly, it must use the real value, not the glibc value.
    68  // Thus this test also verifies that the Flock_t structure can be
    69  // roundtripped with F_SETLK and F_GETLK.
    70  func TestFcntlFlock(t *testing.T) {
    71  	if runtime.GOOS == "darwin" && (runtime.GOARCH == "arm" || runtime.GOARCH == "arm64") {
    72  		t.Skip("skipping; no child processes allowed on iOS")
    73  	}
    74  	flock := syscall.Flock_t{
    75  		Type:  syscall.F_WRLCK,
    76  		Start: 31415, Len: 271828, Whence: 1,
    77  	}
    78  	if os.Getenv("GO_WANT_HELPER_PROCESS") == "" {
    79  		// parent
    80  		name := filepath.Join(os.TempDir(), "TestFcntlFlock")
    81  		fd, err := syscall.Open(name, syscall.O_CREAT|syscall.O_RDWR|syscall.O_CLOEXEC, 0)
    82  		if err != nil {
    83  			t.Fatalf("Open failed: %v", err)
    84  		}
    85  		defer syscall.Unlink(name)
    86  		defer syscall.Close(fd)
    87  		if err := syscall.Ftruncate(fd, 1<<20); err != nil {
    88  			t.Fatalf("Ftruncate(1<<20) failed: %v", err)
    89  		}
    90  		if err := syscall.FcntlFlock(uintptr(fd), syscall.F_SETLK, &flock); err != nil {
    91  			t.Fatalf("FcntlFlock(F_SETLK) failed: %v", err)
    92  		}
    93  		cmd := exec.Command(os.Args[0], "-test.run=^TestFcntlFlock$")
    94  		cmd.Env = append(os.Environ(), "GO_WANT_HELPER_PROCESS=1")
    95  		cmd.ExtraFiles = []*os.File{os.NewFile(uintptr(fd), name)}
    96  		out, err := cmd.CombinedOutput()
    97  		if len(out) > 0 || err != nil {
    98  			t.Fatalf("child process: %q, %v", out, err)
    99  		}
   100  	} else {
   101  		// child
   102  		got := flock
   103  		// make sure the child lock is conflicting with the parent lock
   104  		got.Start--
   105  		got.Len++
   106  		if err := syscall.FcntlFlock(3, syscall.F_GETLK, &got); err != nil {
   107  			t.Fatalf("FcntlFlock(F_GETLK) failed: %v", err)
   108  		}
   109  		flock.Pid = int32(syscall.Getppid())
   110  		// Linux kernel always set Whence to 0
   111  		flock.Whence = 0
   112  		if got.Type == flock.Type && got.Start == flock.Start && got.Len == flock.Len && got.Pid == flock.Pid && got.Whence == flock.Whence {
   113  			os.Exit(0)
   114  		}
   115  		t.Fatalf("FcntlFlock got %v, want %v", got, flock)
   116  	}
   117  }
   118  
   119  // TestPassFD tests passing a file descriptor over a Unix socket.
   120  //
   121  // This test involved both a parent and child process. The parent
   122  // process is invoked as a normal test, with "go test", which then
   123  // runs the child process by running the current test binary with args
   124  // "-test.run=^TestPassFD$" and an environment variable used to signal
   125  // that the test should become the child process instead.
   126  func TestPassFD(t *testing.T) {
   127  	switch runtime.GOOS {
   128  	case "dragonfly":
   129  		// TODO(jsing): Figure out why sendmsg is returning EINVAL.
   130  		t.Skip("skipping test on dragonfly")
   131  	case "solaris":
   132  		// TODO(aram): Figure out why ReadMsgUnix is returning empty message.
   133  		t.Skip("skipping test on solaris, see issue 7402")
   134  	}
   135  
   136  	testenv.MustHaveExec(t)
   137  
   138  	if os.Getenv("GO_WANT_HELPER_PROCESS") == "1" {
   139  		passFDChild()
   140  		return
   141  	}
   142  
   143  	tempDir, err := ioutil.TempDir("", "TestPassFD")
   144  	if err != nil {
   145  		t.Fatal(err)
   146  	}
   147  	defer os.RemoveAll(tempDir)
   148  
   149  	fds, err := syscall.Socketpair(syscall.AF_LOCAL, syscall.SOCK_STREAM, 0)
   150  	if err != nil {
   151  		t.Fatalf("Socketpair: %v", err)
   152  	}
   153  	defer syscall.Close(fds[0])
   154  	defer syscall.Close(fds[1])
   155  	writeFile := os.NewFile(uintptr(fds[0]), "child-writes")
   156  	readFile := os.NewFile(uintptr(fds[1]), "parent-reads")
   157  	defer writeFile.Close()
   158  	defer readFile.Close()
   159  
   160  	cmd := exec.Command(os.Args[0], "-test.run=^TestPassFD$", "--", tempDir)
   161  	cmd.Env = append(os.Environ(), "GO_WANT_HELPER_PROCESS=1")
   162  	cmd.ExtraFiles = []*os.File{writeFile}
   163  
   164  	out, err := cmd.CombinedOutput()
   165  	if len(out) > 0 || err != nil {
   166  		t.Fatalf("child process: %q, %v", out, err)
   167  	}
   168  
   169  	c, err := net.FileConn(readFile)
   170  	if err != nil {
   171  		t.Fatalf("FileConn: %v", err)
   172  	}
   173  	defer c.Close()
   174  
   175  	uc, ok := c.(*net.UnixConn)
   176  	if !ok {
   177  		t.Fatalf("unexpected FileConn type; expected UnixConn, got %T", c)
   178  	}
   179  
   180  	buf := make([]byte, 32) // expect 1 byte
   181  	oob := make([]byte, 32) // expect 24 bytes
   182  	closeUnix := time.AfterFunc(5*time.Second, func() {
   183  		t.Logf("timeout reading from unix socket")
   184  		uc.Close()
   185  	})
   186  	_, oobn, _, _, err := uc.ReadMsgUnix(buf, oob)
   187  	closeUnix.Stop()
   188  
   189  	scms, err := syscall.ParseSocketControlMessage(oob[:oobn])
   190  	if err != nil {
   191  		t.Fatalf("ParseSocketControlMessage: %v", err)
   192  	}
   193  	if len(scms) != 1 {
   194  		t.Fatalf("expected 1 SocketControlMessage; got scms = %#v", scms)
   195  	}
   196  	scm := scms[0]
   197  	gotFds, err := syscall.ParseUnixRights(&scm)
   198  	if err != nil {
   199  		t.Fatalf("syscall.ParseUnixRights: %v", err)
   200  	}
   201  	if len(gotFds) != 1 {
   202  		t.Fatalf("wanted 1 fd; got %#v", gotFds)
   203  	}
   204  
   205  	f := os.NewFile(uintptr(gotFds[0]), "fd-from-child")
   206  	defer f.Close()
   207  
   208  	got, err := ioutil.ReadAll(f)
   209  	want := "Hello from child process!\n"
   210  	if string(got) != want {
   211  		t.Errorf("child process ReadAll: %q, %v; want %q", got, err, want)
   212  	}
   213  }
   214  
   215  // passFDChild is the child process used by TestPassFD.
   216  func passFDChild() {
   217  	defer os.Exit(0)
   218  
   219  	// Look for our fd. It should be fd 3, but we work around an fd leak
   220  	// bug here (https://golang.org/issue/2603) to let it be elsewhere.
   221  	var uc *net.UnixConn
   222  	for fd := uintptr(3); fd <= 10; fd++ {
   223  		f := os.NewFile(fd, "unix-conn")
   224  		var ok bool
   225  		netc, _ := net.FileConn(f)
   226  		uc, ok = netc.(*net.UnixConn)
   227  		if ok {
   228  			break
   229  		}
   230  	}
   231  	if uc == nil {
   232  		fmt.Println("failed to find unix fd")
   233  		return
   234  	}
   235  
   236  	// Make a file f to send to our parent process on uc.
   237  	// We make it in tempDir, which our parent will clean up.
   238  	flag.Parse()
   239  	tempDir := flag.Arg(0)
   240  	f, err := ioutil.TempFile(tempDir, "")
   241  	if err != nil {
   242  		fmt.Printf("TempFile: %v", err)
   243  		return
   244  	}
   245  
   246  	f.Write([]byte("Hello from child process!\n"))
   247  	f.Seek(0, 0)
   248  
   249  	rights := syscall.UnixRights(int(f.Fd()))
   250  	dummyByte := []byte("x")
   251  	n, oobn, err := uc.WriteMsgUnix(dummyByte, rights, nil)
   252  	if err != nil {
   253  		fmt.Printf("WriteMsgUnix: %v", err)
   254  		return
   255  	}
   256  	if n != 1 || oobn != len(rights) {
   257  		fmt.Printf("WriteMsgUnix = %d, %d; want 1, %d", n, oobn, len(rights))
   258  		return
   259  	}
   260  }
   261  
   262  // TestUnixRightsRoundtrip tests that UnixRights, ParseSocketControlMessage,
   263  // and ParseUnixRights are able to successfully round-trip lists of file descriptors.
   264  func TestUnixRightsRoundtrip(t *testing.T) {
   265  	testCases := [...][][]int{
   266  		{{42}},
   267  		{{1, 2}},
   268  		{{3, 4, 5}},
   269  		{{}},
   270  		{{1, 2}, {3, 4, 5}, {}, {7}},
   271  	}
   272  	for _, testCase := range testCases {
   273  		b := []byte{}
   274  		var n int
   275  		for _, fds := range testCase {
   276  			// Last assignment to n wins
   277  			n = len(b) + syscall.CmsgLen(4*len(fds))
   278  			b = append(b, syscall.UnixRights(fds...)...)
   279  		}
   280  		// Truncate b
   281  		b = b[:n]
   282  
   283  		scms, err := syscall.ParseSocketControlMessage(b)
   284  		if err != nil {
   285  			t.Fatalf("ParseSocketControlMessage: %v", err)
   286  		}
   287  		if len(scms) != len(testCase) {
   288  			t.Fatalf("expected %v SocketControlMessage; got scms = %#v", len(testCase), scms)
   289  		}
   290  		for i, scm := range scms {
   291  			gotFds, err := syscall.ParseUnixRights(&scm)
   292  			if err != nil {
   293  				t.Fatalf("ParseUnixRights: %v", err)
   294  			}
   295  			wantFds := testCase[i]
   296  			if len(gotFds) != len(wantFds) {
   297  				t.Fatalf("expected %v fds, got %#v", len(wantFds), gotFds)
   298  			}
   299  			for j, fd := range gotFds {
   300  				if fd != wantFds[j] {
   301  					t.Fatalf("expected fd %v, got %v", wantFds[j], fd)
   302  				}
   303  			}
   304  		}
   305  	}
   306  }
   307  
   308  func TestRlimit(t *testing.T) {
   309  	var rlimit, zero syscall.Rlimit
   310  	err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rlimit)
   311  	if err != nil {
   312  		t.Fatalf("Getrlimit: save failed: %v", err)
   313  	}
   314  	if zero == rlimit {
   315  		t.Fatalf("Getrlimit: save failed: got zero value %#v", rlimit)
   316  	}
   317  	set := rlimit
   318  	set.Cur = set.Max - 1
   319  	err = syscall.Setrlimit(syscall.RLIMIT_NOFILE, &set)
   320  	if err != nil {
   321  		t.Fatalf("Setrlimit: set failed: %#v %v", set, err)
   322  	}
   323  	var get syscall.Rlimit
   324  	err = syscall.Getrlimit(syscall.RLIMIT_NOFILE, &get)
   325  	if err != nil {
   326  		t.Fatalf("Getrlimit: get failed: %v", err)
   327  	}
   328  	set = rlimit
   329  	set.Cur = set.Max - 1
   330  	if set != get {
   331  		// Seems like Darwin requires some privilege to
   332  		// increase the soft limit of rlimit sandbox, though
   333  		// Setrlimit never reports an error.
   334  		switch runtime.GOOS {
   335  		case "darwin":
   336  		default:
   337  			t.Fatalf("Rlimit: change failed: wanted %#v got %#v", set, get)
   338  		}
   339  	}
   340  	err = syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rlimit)
   341  	if err != nil {
   342  		t.Fatalf("Setrlimit: restore failed: %#v %v", rlimit, err)
   343  	}
   344  }
   345  
   346  func TestSeekFailure(t *testing.T) {
   347  	_, err := syscall.Seek(-1, 0, 0)
   348  	if err == nil {
   349  		t.Fatalf("Seek(-1, 0, 0) did not fail")
   350  	}
   351  	str := err.Error() // used to crash on Linux
   352  	t.Logf("Seek: %v", str)
   353  	if str == "" {
   354  		t.Fatalf("Seek(-1, 0, 0) return error with empty message")
   355  	}
   356  }