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