syscall_unix_test.go 14 KB

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