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