syscall_unix_test.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  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 runtime.GOOS == "darwin" && (runtime.GOARCH == "arm" || runtime.GOARCH == "arm64") {
  116. t.Skip("cannot exec subprocess on iOS, skipping test")
  117. }
  118. if os.Getenv("GO_WANT_HELPER_PROCESS") == "1" {
  119. passFDChild()
  120. return
  121. }
  122. tempDir, err := ioutil.TempDir("", "TestPassFD")
  123. if err != nil {
  124. t.Fatal(err)
  125. }
  126. defer os.RemoveAll(tempDir)
  127. fds, err := unix.Socketpair(unix.AF_LOCAL, unix.SOCK_STREAM, 0)
  128. if err != nil {
  129. t.Fatalf("Socketpair: %v", err)
  130. }
  131. defer unix.Close(fds[0])
  132. defer unix.Close(fds[1])
  133. writeFile := os.NewFile(uintptr(fds[0]), "child-writes")
  134. readFile := os.NewFile(uintptr(fds[1]), "parent-reads")
  135. defer writeFile.Close()
  136. defer readFile.Close()
  137. cmd := exec.Command(os.Args[0], "-test.run=^TestPassFD$", "--", tempDir)
  138. cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"}
  139. if lp := os.Getenv("LD_LIBRARY_PATH"); lp != "" {
  140. cmd.Env = append(cmd.Env, "LD_LIBRARY_PATH="+lp)
  141. }
  142. cmd.ExtraFiles = []*os.File{writeFile}
  143. out, err := cmd.CombinedOutput()
  144. if len(out) > 0 || err != nil {
  145. t.Fatalf("child process: %q, %v", out, err)
  146. }
  147. c, err := net.FileConn(readFile)
  148. if err != nil {
  149. t.Fatalf("FileConn: %v", err)
  150. }
  151. defer c.Close()
  152. uc, ok := c.(*net.UnixConn)
  153. if !ok {
  154. t.Fatalf("unexpected FileConn type; expected UnixConn, got %T", c)
  155. }
  156. buf := make([]byte, 32) // expect 1 byte
  157. oob := make([]byte, 32) // expect 24 bytes
  158. closeUnix := time.AfterFunc(5*time.Second, func() {
  159. t.Logf("timeout reading from unix socket")
  160. uc.Close()
  161. })
  162. _, oobn, _, _, err := uc.ReadMsgUnix(buf, oob)
  163. if err != nil {
  164. t.Fatalf("ReadMsgUnix: %v", err)
  165. }
  166. closeUnix.Stop()
  167. scms, err := unix.ParseSocketControlMessage(oob[:oobn])
  168. if err != nil {
  169. t.Fatalf("ParseSocketControlMessage: %v", err)
  170. }
  171. if len(scms) != 1 {
  172. t.Fatalf("expected 1 SocketControlMessage; got scms = %#v", scms)
  173. }
  174. scm := scms[0]
  175. gotFds, err := unix.ParseUnixRights(&scm)
  176. if err != nil {
  177. t.Fatalf("unix.ParseUnixRights: %v", err)
  178. }
  179. if len(gotFds) != 1 {
  180. t.Fatalf("wanted 1 fd; got %#v", gotFds)
  181. }
  182. f := os.NewFile(uintptr(gotFds[0]), "fd-from-child")
  183. defer f.Close()
  184. got, err := ioutil.ReadAll(f)
  185. want := "Hello from child process!\n"
  186. if string(got) != want {
  187. t.Errorf("child process ReadAll: %q, %v; want %q", got, err, want)
  188. }
  189. }
  190. // passFDChild is the child process used by TestPassFD.
  191. func passFDChild() {
  192. defer os.Exit(0)
  193. // Look for our fd. It should be fd 3, but we work around an fd leak
  194. // bug here (http://golang.org/issue/2603) to let it be elsewhere.
  195. var uc *net.UnixConn
  196. for fd := uintptr(3); fd <= 10; fd++ {
  197. f := os.NewFile(fd, "unix-conn")
  198. var ok bool
  199. netc, _ := net.FileConn(f)
  200. uc, ok = netc.(*net.UnixConn)
  201. if ok {
  202. break
  203. }
  204. }
  205. if uc == nil {
  206. fmt.Println("failed to find unix fd")
  207. return
  208. }
  209. // Make a file f to send to our parent process on uc.
  210. // We make it in tempDir, which our parent will clean up.
  211. flag.Parse()
  212. tempDir := flag.Arg(0)
  213. f, err := ioutil.TempFile(tempDir, "")
  214. if err != nil {
  215. fmt.Printf("TempFile: %v", err)
  216. return
  217. }
  218. f.Write([]byte("Hello from child process!\n"))
  219. f.Seek(0, 0)
  220. rights := unix.UnixRights(int(f.Fd()))
  221. dummyByte := []byte("x")
  222. n, oobn, err := uc.WriteMsgUnix(dummyByte, rights, nil)
  223. if err != nil {
  224. fmt.Printf("WriteMsgUnix: %v", err)
  225. return
  226. }
  227. if n != 1 || oobn != len(rights) {
  228. fmt.Printf("WriteMsgUnix = %d, %d; want 1, %d", n, oobn, len(rights))
  229. return
  230. }
  231. }
  232. // TestUnixRightsRoundtrip tests that UnixRights, ParseSocketControlMessage,
  233. // and ParseUnixRights are able to successfully round-trip lists of file descriptors.
  234. func TestUnixRightsRoundtrip(t *testing.T) {
  235. testCases := [...][][]int{
  236. {{42}},
  237. {{1, 2}},
  238. {{3, 4, 5}},
  239. {{}},
  240. {{1, 2}, {3, 4, 5}, {}, {7}},
  241. }
  242. for _, testCase := range testCases {
  243. b := []byte{}
  244. var n int
  245. for _, fds := range testCase {
  246. // Last assignment to n wins
  247. n = len(b) + unix.CmsgLen(4*len(fds))
  248. b = append(b, unix.UnixRights(fds...)...)
  249. }
  250. // Truncate b
  251. b = b[:n]
  252. scms, err := unix.ParseSocketControlMessage(b)
  253. if err != nil {
  254. t.Fatalf("ParseSocketControlMessage: %v", err)
  255. }
  256. if len(scms) != len(testCase) {
  257. t.Fatalf("expected %v SocketControlMessage; got scms = %#v", len(testCase), scms)
  258. }
  259. for i, scm := range scms {
  260. gotFds, err := unix.ParseUnixRights(&scm)
  261. if err != nil {
  262. t.Fatalf("ParseUnixRights: %v", err)
  263. }
  264. wantFds := testCase[i]
  265. if len(gotFds) != len(wantFds) {
  266. t.Fatalf("expected %v fds, got %#v", len(wantFds), gotFds)
  267. }
  268. for j, fd := range gotFds {
  269. if fd != wantFds[j] {
  270. t.Fatalf("expected fd %v, got %v", wantFds[j], fd)
  271. }
  272. }
  273. }
  274. }
  275. }
  276. func TestRlimit(t *testing.T) {
  277. var rlimit, zero unix.Rlimit
  278. err := unix.Getrlimit(unix.RLIMIT_NOFILE, &rlimit)
  279. if err != nil {
  280. t.Fatalf("Getrlimit: save failed: %v", err)
  281. }
  282. if zero == rlimit {
  283. t.Fatalf("Getrlimit: save failed: got zero value %#v", rlimit)
  284. }
  285. set := rlimit
  286. set.Cur = set.Max - 1
  287. err = unix.Setrlimit(unix.RLIMIT_NOFILE, &set)
  288. if err != nil {
  289. t.Fatalf("Setrlimit: set failed: %#v %v", set, err)
  290. }
  291. var get unix.Rlimit
  292. err = unix.Getrlimit(unix.RLIMIT_NOFILE, &get)
  293. if err != nil {
  294. t.Fatalf("Getrlimit: get failed: %v", err)
  295. }
  296. set = rlimit
  297. set.Cur = set.Max - 1
  298. if set != get {
  299. // Seems like Darwin requires some privilege to
  300. // increase the soft limit of rlimit sandbox, though
  301. // Setrlimit never reports an error.
  302. switch runtime.GOOS {
  303. case "darwin":
  304. default:
  305. t.Fatalf("Rlimit: change failed: wanted %#v got %#v", set, get)
  306. }
  307. }
  308. err = unix.Setrlimit(unix.RLIMIT_NOFILE, &rlimit)
  309. if err != nil {
  310. t.Fatalf("Setrlimit: restore failed: %#v %v", rlimit, err)
  311. }
  312. }
  313. func TestSeekFailure(t *testing.T) {
  314. _, err := unix.Seek(-1, 0, 0)
  315. if err == nil {
  316. t.Fatalf("Seek(-1, 0, 0) did not fail")
  317. }
  318. str := err.Error() // used to crash on Linux
  319. t.Logf("Seek: %v", str)
  320. if str == "" {
  321. t.Fatalf("Seek(-1, 0, 0) return error with empty message")
  322. }
  323. }
  324. func TestDup(t *testing.T) {
  325. file, err := ioutil.TempFile("", "TestDup")
  326. if err != nil {
  327. t.Fatalf("Tempfile failed: %v", err)
  328. }
  329. defer os.Remove(file.Name())
  330. defer file.Close()
  331. f := int(file.Fd())
  332. newFd, err := unix.Dup(f)
  333. if err != nil {
  334. t.Fatalf("Dup: %v", err)
  335. }
  336. err = unix.Dup2(newFd, newFd+1)
  337. if err != nil {
  338. t.Fatalf("Dup2: %v", err)
  339. }
  340. b1 := []byte("Test123")
  341. b2 := make([]byte, 7)
  342. _, err = unix.Write(newFd+1, b1)
  343. if err != nil {
  344. t.Fatalf("Write to dup2 fd failed: %v", err)
  345. }
  346. _, err = unix.Seek(f, 0, 0)
  347. if err != nil {
  348. t.Fatalf("Seek failed: %v", err)
  349. }
  350. _, err = unix.Read(f, b2)
  351. if err != nil {
  352. t.Fatalf("Read back failed: %v", err)
  353. }
  354. if string(b1) != string(b2) {
  355. t.Errorf("Dup: stdout write not in file, expected %v, got %v", string(b1), string(b2))
  356. }
  357. }
  358. func TestPoll(t *testing.T) {
  359. if runtime.GOOS == "android" ||
  360. (runtime.GOOS == "darwin" && (runtime.GOARCH == "arm" || runtime.GOARCH == "arm64")) {
  361. t.Skip("mkfifo syscall is not available on android and iOS, skipping test")
  362. }
  363. f, cleanup := mktmpfifo(t)
  364. defer cleanup()
  365. const timeout = 100
  366. ok := make(chan bool, 1)
  367. go func() {
  368. select {
  369. case <-time.After(10 * timeout * time.Millisecond):
  370. t.Errorf("Poll: failed to timeout after %d milliseconds", 10*timeout)
  371. case <-ok:
  372. }
  373. }()
  374. fds := []unix.PollFd{{Fd: int32(f.Fd()), Events: unix.POLLIN}}
  375. n, err := unix.Poll(fds, timeout)
  376. ok <- true
  377. if err != nil {
  378. t.Errorf("Poll: unexpected error: %v", err)
  379. return
  380. }
  381. if n != 0 {
  382. t.Errorf("Poll: wrong number of events: got %v, expected %v", n, 0)
  383. return
  384. }
  385. }
  386. func TestGetwd(t *testing.T) {
  387. fd, err := os.Open(".")
  388. if err != nil {
  389. t.Fatalf("Open .: %s", err)
  390. }
  391. defer fd.Close()
  392. // These are chosen carefully not to be symlinks on a Mac
  393. // (unlike, say, /var, /etc)
  394. dirs := []string{"/", "/usr/bin"}
  395. switch runtime.GOOS {
  396. case "android":
  397. dirs = []string{"/", "/system/bin"}
  398. case "darwin":
  399. switch runtime.GOARCH {
  400. case "arm", "arm64":
  401. d1, err := ioutil.TempDir("", "d1")
  402. if err != nil {
  403. t.Fatalf("TempDir: %v", err)
  404. }
  405. d2, err := ioutil.TempDir("", "d2")
  406. if err != nil {
  407. t.Fatalf("TempDir: %v", err)
  408. }
  409. dirs = []string{d1, d2}
  410. }
  411. }
  412. oldwd := os.Getenv("PWD")
  413. for _, d := range dirs {
  414. err = os.Chdir(d)
  415. if err != nil {
  416. t.Fatalf("Chdir: %v", err)
  417. }
  418. pwd, err := unix.Getwd()
  419. if err != nil {
  420. t.Fatalf("Getwd in %s: %s", d, err)
  421. }
  422. os.Setenv("PWD", oldwd)
  423. err = fd.Chdir()
  424. if err != nil {
  425. // We changed the current directory and cannot go back.
  426. // Don't let the tests continue; they'll scribble
  427. // all over some other directory.
  428. fmt.Fprintf(os.Stderr, "fchdir back to dot failed: %s\n", err)
  429. os.Exit(1)
  430. }
  431. if pwd != d {
  432. t.Fatalf("Getwd returned %q want %q", pwd, d)
  433. }
  434. }
  435. }
  436. func TestFstatat(t *testing.T) {
  437. defer chtmpdir(t)()
  438. touch(t, "file1")
  439. var st1 unix.Stat_t
  440. err := unix.Stat("file1", &st1)
  441. if err != nil {
  442. t.Fatalf("Stat: %v", err)
  443. }
  444. var st2 unix.Stat_t
  445. err = unix.Fstatat(unix.AT_FDCWD, "file1", &st2, 0)
  446. if err != nil {
  447. t.Fatalf("Fstatat: %v", err)
  448. }
  449. if st1 != st2 {
  450. t.Errorf("Fstatat: returned stat does not match Stat")
  451. }
  452. err = os.Symlink("file1", "symlink1")
  453. if err != nil {
  454. t.Fatal(err)
  455. }
  456. err = unix.Lstat("symlink1", &st1)
  457. if err != nil {
  458. t.Fatalf("Lstat: %v", err)
  459. }
  460. err = unix.Fstatat(unix.AT_FDCWD, "symlink1", &st2, unix.AT_SYMLINK_NOFOLLOW)
  461. if err != nil {
  462. t.Fatalf("Fstatat: %v", err)
  463. }
  464. if st1 != st2 {
  465. t.Errorf("Fstatat: returned stat does not match Lstat")
  466. }
  467. }
  468. func TestFchmodat(t *testing.T) {
  469. defer chtmpdir(t)()
  470. touch(t, "file1")
  471. err := os.Symlink("file1", "symlink1")
  472. if err != nil {
  473. t.Fatal(err)
  474. }
  475. mode := os.FileMode(0444)
  476. err = unix.Fchmodat(unix.AT_FDCWD, "symlink1", uint32(mode), 0)
  477. if err != nil {
  478. t.Fatalf("Fchmodat: unexpected error: %v", err)
  479. }
  480. fi, err := os.Stat("file1")
  481. if err != nil {
  482. t.Fatal(err)
  483. }
  484. if fi.Mode() != mode {
  485. t.Errorf("Fchmodat: failed to change file mode: expected %v, got %v", mode, fi.Mode())
  486. }
  487. mode = os.FileMode(0644)
  488. didChmodSymlink := true
  489. err = unix.Fchmodat(unix.AT_FDCWD, "symlink1", uint32(mode), unix.AT_SYMLINK_NOFOLLOW)
  490. if err != nil {
  491. if (runtime.GOOS == "android" || runtime.GOOS == "linux" || runtime.GOOS == "solaris") && err == unix.EOPNOTSUPP {
  492. // Linux and Illumos don't support flags != 0
  493. didChmodSymlink = false
  494. } else {
  495. t.Fatalf("Fchmodat: unexpected error: %v", err)
  496. }
  497. }
  498. if !didChmodSymlink {
  499. // Didn't change mode of the symlink. On Linux, the permissions
  500. // of a symbolic link are always 0777 according to symlink(7)
  501. mode = os.FileMode(0777)
  502. }
  503. var st unix.Stat_t
  504. err = unix.Lstat("symlink1", &st)
  505. if err != nil {
  506. t.Fatal(err)
  507. }
  508. got := os.FileMode(st.Mode & 0777)
  509. if got != mode {
  510. t.Errorf("Fchmodat: failed to change symlink mode: expected %v, got %v", mode, got)
  511. }
  512. }
  513. func TestMkdev(t *testing.T) {
  514. major := uint32(42)
  515. minor := uint32(7)
  516. dev := unix.Mkdev(major, minor)
  517. if unix.Major(dev) != major {
  518. t.Errorf("Major(%#x) == %d, want %d", dev, unix.Major(dev), major)
  519. }
  520. if unix.Minor(dev) != minor {
  521. t.Errorf("Minor(%#x) == %d, want %d", dev, unix.Minor(dev), minor)
  522. }
  523. }
  524. // mktmpfifo creates a temporary FIFO and provides a cleanup function.
  525. func mktmpfifo(t *testing.T) (*os.File, func()) {
  526. err := unix.Mkfifo("fifo", 0666)
  527. if err != nil {
  528. t.Fatalf("mktmpfifo: failed to create FIFO: %v", err)
  529. }
  530. f, err := os.OpenFile("fifo", os.O_RDWR, 0666)
  531. if err != nil {
  532. os.Remove("fifo")
  533. t.Fatalf("mktmpfifo: failed to open FIFO: %v", err)
  534. }
  535. return f, func() {
  536. f.Close()
  537. os.Remove("fifo")
  538. }
  539. }
  540. // utilities taken from os/os_test.go
  541. func touch(t *testing.T, name string) {
  542. f, err := os.Create(name)
  543. if err != nil {
  544. t.Fatal(err)
  545. }
  546. if err := f.Close(); err != nil {
  547. t.Fatal(err)
  548. }
  549. }
  550. // chtmpdir changes the working directory to a new temporary directory and
  551. // provides a cleanup function. Used when PWD is read-only.
  552. func chtmpdir(t *testing.T) func() {
  553. oldwd, err := os.Getwd()
  554. if err != nil {
  555. t.Fatalf("chtmpdir: %v", err)
  556. }
  557. d, err := ioutil.TempDir("", "test")
  558. if err != nil {
  559. t.Fatalf("chtmpdir: %v", err)
  560. }
  561. if err := os.Chdir(d); err != nil {
  562. t.Fatalf("chtmpdir: %v", err)
  563. }
  564. return func() {
  565. if err := os.Chdir(oldwd); err != nil {
  566. t.Fatalf("chtmpdir: %v", err)
  567. }
  568. os.RemoveAll(d)
  569. }
  570. }