syscall_unix_test.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  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 aix 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. "strconv"
  16. "syscall"
  17. "testing"
  18. "time"
  19. "golang.org/x/sys/unix"
  20. )
  21. // Tests that below functions, structures and constants are consistent
  22. // on all Unix-like systems.
  23. func _() {
  24. // program scheduling priority functions and constants
  25. var (
  26. _ func(int, int, int) error = unix.Setpriority
  27. _ func(int, int) (int, error) = unix.Getpriority
  28. )
  29. const (
  30. _ int = unix.PRIO_USER
  31. _ int = unix.PRIO_PROCESS
  32. _ int = unix.PRIO_PGRP
  33. )
  34. // termios constants
  35. const (
  36. _ int = unix.TCIFLUSH
  37. _ int = unix.TCIOFLUSH
  38. _ int = unix.TCOFLUSH
  39. )
  40. // fcntl file locking structure and constants
  41. var (
  42. _ = unix.Flock_t{
  43. Type: int16(0),
  44. Whence: int16(0),
  45. Start: int64(0),
  46. Len: int64(0),
  47. Pid: int32(0),
  48. }
  49. )
  50. const (
  51. _ = unix.F_GETLK
  52. _ = unix.F_SETLK
  53. _ = unix.F_SETLKW
  54. )
  55. }
  56. func TestErrnoSignalName(t *testing.T) {
  57. testErrors := []struct {
  58. num syscall.Errno
  59. name string
  60. }{
  61. {syscall.EPERM, "EPERM"},
  62. {syscall.EINVAL, "EINVAL"},
  63. {syscall.ENOENT, "ENOENT"},
  64. }
  65. for _, te := range testErrors {
  66. t.Run(fmt.Sprintf("%d/%s", te.num, te.name), func(t *testing.T) {
  67. e := unix.ErrnoName(te.num)
  68. if e != te.name {
  69. t.Errorf("ErrnoName(%d) returned %s, want %s", te.num, e, te.name)
  70. }
  71. })
  72. }
  73. testSignals := []struct {
  74. num syscall.Signal
  75. name string
  76. }{
  77. {syscall.SIGHUP, "SIGHUP"},
  78. {syscall.SIGPIPE, "SIGPIPE"},
  79. {syscall.SIGSEGV, "SIGSEGV"},
  80. }
  81. for _, ts := range testSignals {
  82. t.Run(fmt.Sprintf("%d/%s", ts.num, ts.name), func(t *testing.T) {
  83. s := unix.SignalName(ts.num)
  84. if s != ts.name {
  85. t.Errorf("SignalName(%d) returned %s, want %s", ts.num, s, ts.name)
  86. }
  87. })
  88. }
  89. }
  90. func TestSignalNum(t *testing.T) {
  91. testSignals := []struct {
  92. name string
  93. want syscall.Signal
  94. }{
  95. {"SIGHUP", syscall.SIGHUP},
  96. {"SIGPIPE", syscall.SIGPIPE},
  97. {"SIGSEGV", syscall.SIGSEGV},
  98. {"NONEXISTS", 0},
  99. }
  100. for _, ts := range testSignals {
  101. t.Run(fmt.Sprintf("%s/%d", ts.name, ts.want), func(t *testing.T) {
  102. got := unix.SignalNum(ts.name)
  103. if got != ts.want {
  104. t.Errorf("SignalNum(%s) returned %d, want %d", ts.name, got, ts.want)
  105. }
  106. })
  107. }
  108. }
  109. func TestFcntlInt(t *testing.T) {
  110. t.Parallel()
  111. file, err := ioutil.TempFile("", "TestFnctlInt")
  112. if err != nil {
  113. t.Fatal(err)
  114. }
  115. defer os.Remove(file.Name())
  116. defer file.Close()
  117. f := file.Fd()
  118. flags, err := unix.FcntlInt(f, unix.F_GETFD, 0)
  119. if err != nil {
  120. t.Fatal(err)
  121. }
  122. if flags&unix.FD_CLOEXEC == 0 {
  123. t.Errorf("flags %#x do not include FD_CLOEXEC", flags)
  124. }
  125. }
  126. // TestFcntlFlock tests whether the file locking structure matches
  127. // the calling convention of each kernel.
  128. func TestFcntlFlock(t *testing.T) {
  129. name := filepath.Join(os.TempDir(), "TestFcntlFlock")
  130. fd, err := unix.Open(name, unix.O_CREAT|unix.O_RDWR|unix.O_CLOEXEC, 0)
  131. if err != nil {
  132. t.Fatalf("Open failed: %v", err)
  133. }
  134. defer unix.Unlink(name)
  135. defer unix.Close(fd)
  136. flock := unix.Flock_t{
  137. Type: unix.F_RDLCK,
  138. Start: 0, Len: 0, Whence: 1,
  139. }
  140. if err := unix.FcntlFlock(uintptr(fd), unix.F_GETLK, &flock); err != nil {
  141. t.Fatalf("FcntlFlock failed: %v", err)
  142. }
  143. }
  144. // TestPassFD tests passing a file descriptor over a Unix socket.
  145. //
  146. // This test involved both a parent and child process. The parent
  147. // process is invoked as a normal test, with "go test", which then
  148. // runs the child process by running the current test binary with args
  149. // "-test.run=^TestPassFD$" and an environment variable used to signal
  150. // that the test should become the child process instead.
  151. func TestPassFD(t *testing.T) {
  152. if runtime.GOOS == "darwin" && (runtime.GOARCH == "arm" || runtime.GOARCH == "arm64") {
  153. t.Skip("cannot exec subprocess on iOS, skipping test")
  154. }
  155. if os.Getenv("GO_WANT_HELPER_PROCESS") == "1" {
  156. passFDChild()
  157. return
  158. }
  159. if runtime.GOOS == "aix" {
  160. // Unix network isn't properly working on AIX
  161. // 7.2 with Technical Level < 2
  162. out, err := exec.Command("oslevel", "-s").Output()
  163. if err != nil {
  164. t.Skipf("skipping on AIX because oslevel -s failed: %v", err)
  165. }
  166. if len(out) < len("7200-XX-ZZ-YYMM") { // AIX 7.2, Tech Level XX, Service Pack ZZ, date YYMM
  167. t.Skip("skipping on AIX because oslevel -s hasn't the right length")
  168. }
  169. aixVer := string(out[:4])
  170. tl, err := strconv.Atoi(string(out[5:7]))
  171. if err != nil {
  172. t.Skipf("skipping on AIX because oslevel -s output cannot be parsed: %v", err)
  173. }
  174. if aixVer < "7200" || (aixVer == "7200" && tl < 2) {
  175. t.Skip("skipped on AIX versions previous to 7.2 TL 2")
  176. }
  177. }
  178. tempDir, err := ioutil.TempDir("", "TestPassFD")
  179. if err != nil {
  180. t.Fatal(err)
  181. }
  182. defer os.RemoveAll(tempDir)
  183. fds, err := unix.Socketpair(unix.AF_LOCAL, unix.SOCK_STREAM, 0)
  184. if err != nil {
  185. t.Fatalf("Socketpair: %v", err)
  186. }
  187. defer unix.Close(fds[0])
  188. defer unix.Close(fds[1])
  189. writeFile := os.NewFile(uintptr(fds[0]), "child-writes")
  190. readFile := os.NewFile(uintptr(fds[1]), "parent-reads")
  191. defer writeFile.Close()
  192. defer readFile.Close()
  193. cmd := exec.Command(os.Args[0], "-test.run=^TestPassFD$", "--", tempDir)
  194. cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"}
  195. if lp := os.Getenv("LD_LIBRARY_PATH"); lp != "" {
  196. cmd.Env = append(cmd.Env, "LD_LIBRARY_PATH="+lp)
  197. }
  198. cmd.ExtraFiles = []*os.File{writeFile}
  199. out, err := cmd.CombinedOutput()
  200. if len(out) > 0 || err != nil {
  201. t.Fatalf("child process: %q, %v", out, err)
  202. }
  203. c, err := net.FileConn(readFile)
  204. if err != nil {
  205. t.Fatalf("FileConn: %v", err)
  206. }
  207. defer c.Close()
  208. uc, ok := c.(*net.UnixConn)
  209. if !ok {
  210. t.Fatalf("unexpected FileConn type; expected UnixConn, got %T", c)
  211. }
  212. buf := make([]byte, 32) // expect 1 byte
  213. oob := make([]byte, 32) // expect 24 bytes
  214. closeUnix := time.AfterFunc(5*time.Second, func() {
  215. t.Logf("timeout reading from unix socket")
  216. uc.Close()
  217. })
  218. _, oobn, _, _, err := uc.ReadMsgUnix(buf, oob)
  219. if err != nil {
  220. t.Fatalf("ReadMsgUnix: %v", err)
  221. }
  222. closeUnix.Stop()
  223. scms, err := unix.ParseSocketControlMessage(oob[:oobn])
  224. if err != nil {
  225. t.Fatalf("ParseSocketControlMessage: %v", err)
  226. }
  227. if len(scms) != 1 {
  228. t.Fatalf("expected 1 SocketControlMessage; got scms = %#v", scms)
  229. }
  230. scm := scms[0]
  231. gotFds, err := unix.ParseUnixRights(&scm)
  232. if err != nil {
  233. t.Fatalf("unix.ParseUnixRights: %v", err)
  234. }
  235. if len(gotFds) != 1 {
  236. t.Fatalf("wanted 1 fd; got %#v", gotFds)
  237. }
  238. f := os.NewFile(uintptr(gotFds[0]), "fd-from-child")
  239. defer f.Close()
  240. got, err := ioutil.ReadAll(f)
  241. want := "Hello from child process!\n"
  242. if string(got) != want {
  243. t.Errorf("child process ReadAll: %q, %v; want %q", got, err, want)
  244. }
  245. }
  246. // passFDChild is the child process used by TestPassFD.
  247. func passFDChild() {
  248. defer os.Exit(0)
  249. // Look for our fd. It should be fd 3, but we work around an fd leak
  250. // bug here (http://golang.org/issue/2603) to let it be elsewhere.
  251. var uc *net.UnixConn
  252. for fd := uintptr(3); fd <= 10; fd++ {
  253. f := os.NewFile(fd, "unix-conn")
  254. var ok bool
  255. netc, _ := net.FileConn(f)
  256. uc, ok = netc.(*net.UnixConn)
  257. if ok {
  258. break
  259. }
  260. }
  261. if uc == nil {
  262. fmt.Println("failed to find unix fd")
  263. return
  264. }
  265. // Make a file f to send to our parent process on uc.
  266. // We make it in tempDir, which our parent will clean up.
  267. flag.Parse()
  268. tempDir := flag.Arg(0)
  269. f, err := ioutil.TempFile(tempDir, "")
  270. if err != nil {
  271. fmt.Printf("TempFile: %v", err)
  272. return
  273. }
  274. f.Write([]byte("Hello from child process!\n"))
  275. f.Seek(0, 0)
  276. rights := unix.UnixRights(int(f.Fd()))
  277. dummyByte := []byte("x")
  278. n, oobn, err := uc.WriteMsgUnix(dummyByte, rights, nil)
  279. if err != nil {
  280. fmt.Printf("WriteMsgUnix: %v", err)
  281. return
  282. }
  283. if n != 1 || oobn != len(rights) {
  284. fmt.Printf("WriteMsgUnix = %d, %d; want 1, %d", n, oobn, len(rights))
  285. return
  286. }
  287. }
  288. // TestUnixRightsRoundtrip tests that UnixRights, ParseSocketControlMessage,
  289. // and ParseUnixRights are able to successfully round-trip lists of file descriptors.
  290. func TestUnixRightsRoundtrip(t *testing.T) {
  291. testCases := [...][][]int{
  292. {{42}},
  293. {{1, 2}},
  294. {{3, 4, 5}},
  295. {{}},
  296. {{1, 2}, {3, 4, 5}, {}, {7}},
  297. }
  298. for _, testCase := range testCases {
  299. b := []byte{}
  300. var n int
  301. for _, fds := range testCase {
  302. // Last assignment to n wins
  303. n = len(b) + unix.CmsgLen(4*len(fds))
  304. b = append(b, unix.UnixRights(fds...)...)
  305. }
  306. // Truncate b
  307. b = b[:n]
  308. scms, err := unix.ParseSocketControlMessage(b)
  309. if err != nil {
  310. t.Fatalf("ParseSocketControlMessage: %v", err)
  311. }
  312. if len(scms) != len(testCase) {
  313. t.Fatalf("expected %v SocketControlMessage; got scms = %#v", len(testCase), scms)
  314. }
  315. for i, scm := range scms {
  316. gotFds, err := unix.ParseUnixRights(&scm)
  317. if err != nil {
  318. t.Fatalf("ParseUnixRights: %v", err)
  319. }
  320. wantFds := testCase[i]
  321. if len(gotFds) != len(wantFds) {
  322. t.Fatalf("expected %v fds, got %#v", len(wantFds), gotFds)
  323. }
  324. for j, fd := range gotFds {
  325. if fd != wantFds[j] {
  326. t.Fatalf("expected fd %v, got %v", wantFds[j], fd)
  327. }
  328. }
  329. }
  330. }
  331. }
  332. func TestRlimit(t *testing.T) {
  333. var rlimit, zero unix.Rlimit
  334. err := unix.Getrlimit(unix.RLIMIT_NOFILE, &rlimit)
  335. if err != nil {
  336. t.Fatalf("Getrlimit: save failed: %v", err)
  337. }
  338. if zero == rlimit {
  339. t.Fatalf("Getrlimit: save failed: got zero value %#v", rlimit)
  340. }
  341. set := rlimit
  342. set.Cur = set.Max - 1
  343. if runtime.GOOS == "darwin" && set.Cur > 10240 {
  344. // The max file limit is 10240, even though
  345. // the max returned by Getrlimit is 1<<63-1.
  346. // This is OPEN_MAX in sys/syslimits.h.
  347. set.Cur = 10240
  348. }
  349. err = unix.Setrlimit(unix.RLIMIT_NOFILE, &set)
  350. if err != nil {
  351. t.Fatalf("Setrlimit: set failed: %#v %v", set, err)
  352. }
  353. var get unix.Rlimit
  354. err = unix.Getrlimit(unix.RLIMIT_NOFILE, &get)
  355. if err != nil {
  356. t.Fatalf("Getrlimit: get failed: %v", err)
  357. }
  358. set = rlimit
  359. set.Cur = set.Max - 1
  360. if set != get {
  361. // Seems like Darwin requires some privilege to
  362. // increase the soft limit of rlimit sandbox, though
  363. // Setrlimit never reports an error.
  364. switch runtime.GOOS {
  365. case "darwin":
  366. default:
  367. t.Fatalf("Rlimit: change failed: wanted %#v got %#v", set, get)
  368. }
  369. }
  370. err = unix.Setrlimit(unix.RLIMIT_NOFILE, &rlimit)
  371. if err != nil {
  372. t.Fatalf("Setrlimit: restore failed: %#v %v", rlimit, err)
  373. }
  374. }
  375. func TestSeekFailure(t *testing.T) {
  376. _, err := unix.Seek(-1, 0, 0)
  377. if err == nil {
  378. t.Fatalf("Seek(-1, 0, 0) did not fail")
  379. }
  380. str := err.Error() // used to crash on Linux
  381. t.Logf("Seek: %v", str)
  382. if str == "" {
  383. t.Fatalf("Seek(-1, 0, 0) return error with empty message")
  384. }
  385. }
  386. func TestSetsockoptString(t *testing.T) {
  387. // should not panic on empty string, see issue #31277
  388. err := unix.SetsockoptString(-1, 0, 0, "")
  389. if err == nil {
  390. t.Fatalf("SetsockoptString: did not fail")
  391. }
  392. }
  393. func TestDup(t *testing.T) {
  394. file, err := ioutil.TempFile("", "TestDup")
  395. if err != nil {
  396. t.Fatalf("Tempfile failed: %v", err)
  397. }
  398. defer os.Remove(file.Name())
  399. defer file.Close()
  400. f := int(file.Fd())
  401. newFd, err := unix.Dup(f)
  402. if err != nil {
  403. t.Fatalf("Dup: %v", err)
  404. }
  405. // Create and reserve a file descriptor.
  406. // Dup2 automatically closes it before reusing it.
  407. nullFile, err := os.Open("/dev/null")
  408. if err != nil {
  409. t.Fatal(err)
  410. }
  411. dupFd := int(file.Fd())
  412. err = unix.Dup2(newFd, dupFd)
  413. if err != nil {
  414. t.Fatalf("Dup2: %v", err)
  415. }
  416. // Keep the dummy file open long enough to not be closed in
  417. // its finalizer.
  418. runtime.KeepAlive(nullFile)
  419. b1 := []byte("Test123")
  420. b2 := make([]byte, 7)
  421. _, err = unix.Write(dupFd, b1)
  422. if err != nil {
  423. t.Fatalf("Write to dup2 fd failed: %v", err)
  424. }
  425. _, err = unix.Seek(f, 0, 0)
  426. if err != nil {
  427. t.Fatalf("Seek failed: %v", err)
  428. }
  429. _, err = unix.Read(f, b2)
  430. if err != nil {
  431. t.Fatalf("Read back failed: %v", err)
  432. }
  433. if string(b1) != string(b2) {
  434. t.Errorf("Dup: stdout write not in file, expected %v, got %v", string(b1), string(b2))
  435. }
  436. }
  437. func TestPoll(t *testing.T) {
  438. if runtime.GOOS == "android" ||
  439. (runtime.GOOS == "darwin" && (runtime.GOARCH == "arm" || runtime.GOARCH == "arm64")) {
  440. t.Skip("mkfifo syscall is not available on android and iOS, skipping test")
  441. }
  442. defer chtmpdir(t)()
  443. f, cleanup := mktmpfifo(t)
  444. defer cleanup()
  445. const timeout = 100
  446. ok := make(chan bool, 1)
  447. go func() {
  448. select {
  449. case <-time.After(10 * timeout * time.Millisecond):
  450. t.Errorf("Poll: failed to timeout after %d milliseconds", 10*timeout)
  451. case <-ok:
  452. }
  453. }()
  454. fds := []unix.PollFd{{Fd: int32(f.Fd()), Events: unix.POLLIN}}
  455. n, err := unix.Poll(fds, timeout)
  456. ok <- true
  457. if err != nil {
  458. t.Errorf("Poll: unexpected error: %v", err)
  459. return
  460. }
  461. if n != 0 {
  462. t.Errorf("Poll: wrong number of events: got %v, expected %v", n, 0)
  463. return
  464. }
  465. }
  466. func TestGetwd(t *testing.T) {
  467. fd, err := os.Open(".")
  468. if err != nil {
  469. t.Fatalf("Open .: %s", err)
  470. }
  471. defer fd.Close()
  472. // Directory list for test. Do not worry if any are symlinks or do not
  473. // exist on some common unix desktop environments. That will be checked.
  474. dirs := []string{"/", "/usr/bin", "/etc", "/var", "/opt"}
  475. switch runtime.GOOS {
  476. case "android":
  477. dirs = []string{"/", "/system/bin"}
  478. case "darwin":
  479. switch runtime.GOARCH {
  480. case "arm", "arm64":
  481. d1, err := ioutil.TempDir("", "d1")
  482. if err != nil {
  483. t.Fatalf("TempDir: %v", err)
  484. }
  485. d2, err := ioutil.TempDir("", "d2")
  486. if err != nil {
  487. t.Fatalf("TempDir: %v", err)
  488. }
  489. dirs = []string{d1, d2}
  490. }
  491. }
  492. oldwd := os.Getenv("PWD")
  493. for _, d := range dirs {
  494. // Check whether d exists, is a dir and that d's path does not contain a symlink
  495. fi, err := os.Stat(d)
  496. if err != nil || !fi.IsDir() {
  497. t.Logf("Test dir %s stat error (%v) or not a directory, skipping", d, err)
  498. continue
  499. }
  500. check, err := filepath.EvalSymlinks(d)
  501. if err != nil || check != d {
  502. t.Logf("Test dir %s (%s) is symlink or other error (%v), skipping", d, check, err)
  503. continue
  504. }
  505. err = os.Chdir(d)
  506. if err != nil {
  507. t.Fatalf("Chdir: %v", err)
  508. }
  509. pwd, err := unix.Getwd()
  510. if err != nil {
  511. t.Fatalf("Getwd in %s: %s", d, err)
  512. }
  513. os.Setenv("PWD", oldwd)
  514. err = fd.Chdir()
  515. if err != nil {
  516. // We changed the current directory and cannot go back.
  517. // Don't let the tests continue; they'll scribble
  518. // all over some other directory.
  519. fmt.Fprintf(os.Stderr, "fchdir back to dot failed: %s\n", err)
  520. os.Exit(1)
  521. }
  522. if pwd != d {
  523. t.Fatalf("Getwd returned %q want %q", pwd, d)
  524. }
  525. }
  526. }
  527. func TestFstatat(t *testing.T) {
  528. defer chtmpdir(t)()
  529. touch(t, "file1")
  530. var st1 unix.Stat_t
  531. err := unix.Stat("file1", &st1)
  532. if err != nil {
  533. t.Fatalf("Stat: %v", err)
  534. }
  535. var st2 unix.Stat_t
  536. err = unix.Fstatat(unix.AT_FDCWD, "file1", &st2, 0)
  537. if err != nil {
  538. t.Fatalf("Fstatat: %v", err)
  539. }
  540. if st1 != st2 {
  541. t.Errorf("Fstatat: returned stat does not match Stat")
  542. }
  543. err = os.Symlink("file1", "symlink1")
  544. if err != nil {
  545. t.Fatal(err)
  546. }
  547. err = unix.Lstat("symlink1", &st1)
  548. if err != nil {
  549. t.Fatalf("Lstat: %v", err)
  550. }
  551. err = unix.Fstatat(unix.AT_FDCWD, "symlink1", &st2, unix.AT_SYMLINK_NOFOLLOW)
  552. if err != nil {
  553. t.Fatalf("Fstatat: %v", err)
  554. }
  555. if st1 != st2 {
  556. t.Errorf("Fstatat: returned stat does not match Lstat")
  557. }
  558. }
  559. func TestFchmodat(t *testing.T) {
  560. defer chtmpdir(t)()
  561. touch(t, "file1")
  562. err := os.Symlink("file1", "symlink1")
  563. if err != nil {
  564. t.Fatal(err)
  565. }
  566. mode := os.FileMode(0444)
  567. err = unix.Fchmodat(unix.AT_FDCWD, "symlink1", uint32(mode), 0)
  568. if err != nil {
  569. t.Fatalf("Fchmodat: unexpected error: %v", err)
  570. }
  571. fi, err := os.Stat("file1")
  572. if err != nil {
  573. t.Fatal(err)
  574. }
  575. if fi.Mode() != mode {
  576. t.Errorf("Fchmodat: failed to change file mode: expected %v, got %v", mode, fi.Mode())
  577. }
  578. mode = os.FileMode(0644)
  579. didChmodSymlink := true
  580. err = unix.Fchmodat(unix.AT_FDCWD, "symlink1", uint32(mode), unix.AT_SYMLINK_NOFOLLOW)
  581. if err != nil {
  582. if (runtime.GOOS == "android" || runtime.GOOS == "linux" ||
  583. runtime.GOOS == "solaris" || runtime.GOOS == "illumos") && err == unix.EOPNOTSUPP {
  584. // Linux and Illumos don't support flags != 0
  585. didChmodSymlink = false
  586. } else {
  587. t.Fatalf("Fchmodat: unexpected error: %v", err)
  588. }
  589. }
  590. if !didChmodSymlink {
  591. // Didn't change mode of the symlink. On Linux, the permissions
  592. // of a symbolic link are always 0777 according to symlink(7)
  593. mode = os.FileMode(0777)
  594. }
  595. var st unix.Stat_t
  596. err = unix.Lstat("symlink1", &st)
  597. if err != nil {
  598. t.Fatal(err)
  599. }
  600. got := os.FileMode(st.Mode & 0777)
  601. if got != mode {
  602. t.Errorf("Fchmodat: failed to change symlink mode: expected %v, got %v", mode, got)
  603. }
  604. }
  605. func TestMkdev(t *testing.T) {
  606. major := uint32(42)
  607. minor := uint32(7)
  608. dev := unix.Mkdev(major, minor)
  609. if unix.Major(dev) != major {
  610. t.Errorf("Major(%#x) == %d, want %d", dev, unix.Major(dev), major)
  611. }
  612. if unix.Minor(dev) != minor {
  613. t.Errorf("Minor(%#x) == %d, want %d", dev, unix.Minor(dev), minor)
  614. }
  615. }
  616. func TestRenameat(t *testing.T) {
  617. defer chtmpdir(t)()
  618. from, to := "renamefrom", "renameto"
  619. touch(t, from)
  620. err := unix.Renameat(unix.AT_FDCWD, from, unix.AT_FDCWD, to)
  621. if err != nil {
  622. t.Fatalf("Renameat: unexpected error: %v", err)
  623. }
  624. _, err = os.Stat(to)
  625. if err != nil {
  626. t.Error(err)
  627. }
  628. _, err = os.Stat(from)
  629. if err == nil {
  630. t.Errorf("Renameat: stat of renamed file %q unexpectedly succeeded", from)
  631. }
  632. }
  633. // mktmpfifo creates a temporary FIFO and provides a cleanup function.
  634. func mktmpfifo(t *testing.T) (*os.File, func()) {
  635. err := unix.Mkfifo("fifo", 0666)
  636. if err != nil {
  637. t.Fatalf("mktmpfifo: failed to create FIFO: %v", err)
  638. }
  639. f, err := os.OpenFile("fifo", os.O_RDWR, 0666)
  640. if err != nil {
  641. os.Remove("fifo")
  642. t.Fatalf("mktmpfifo: failed to open FIFO: %v", err)
  643. }
  644. return f, func() {
  645. f.Close()
  646. os.Remove("fifo")
  647. }
  648. }
  649. // utilities taken from os/os_test.go
  650. func touch(t *testing.T, name string) {
  651. f, err := os.Create(name)
  652. if err != nil {
  653. t.Fatal(err)
  654. }
  655. if err := f.Close(); err != nil {
  656. t.Fatal(err)
  657. }
  658. }
  659. // chtmpdir changes the working directory to a new temporary directory and
  660. // provides a cleanup function. Used when PWD is read-only.
  661. func chtmpdir(t *testing.T) func() {
  662. oldwd, err := os.Getwd()
  663. if err != nil {
  664. t.Fatalf("chtmpdir: %v", err)
  665. }
  666. d, err := ioutil.TempDir("", "test")
  667. if err != nil {
  668. t.Fatalf("chtmpdir: %v", err)
  669. }
  670. if err := os.Chdir(d); err != nil {
  671. t.Fatalf("chtmpdir: %v", err)
  672. }
  673. return func() {
  674. if err := os.Chdir(oldwd); err != nil {
  675. t.Fatalf("chtmpdir: %v", err)
  676. }
  677. os.RemoveAll(d)
  678. }
  679. }