syscall_linux_test.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  1. // Copyright 2016 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 linux
  5. package unix_test
  6. import (
  7. "bufio"
  8. "bytes"
  9. "errors"
  10. "fmt"
  11. "io/ioutil"
  12. "os"
  13. "runtime"
  14. "runtime/debug"
  15. "strconv"
  16. "strings"
  17. "testing"
  18. "time"
  19. "golang.org/x/sys/unix"
  20. )
  21. func TestIoctlGetInt(t *testing.T) {
  22. f, err := os.Open("/dev/random")
  23. if err != nil {
  24. t.Fatalf("failed to open device: %v", err)
  25. }
  26. defer f.Close()
  27. v, err := unix.IoctlGetInt(int(f.Fd()), unix.RNDGETENTCNT)
  28. if err != nil {
  29. t.Fatalf("failed to perform ioctl: %v", err)
  30. }
  31. t.Logf("%d bits of entropy available", v)
  32. }
  33. func TestIoctlRetInt(t *testing.T) {
  34. f, err := os.Open("/proc/self/ns/mnt")
  35. if err != nil {
  36. t.Skipf("skipping test, %v", err)
  37. }
  38. defer f.Close()
  39. v, err := unix.IoctlRetInt(int(f.Fd()), unix.NS_GET_NSTYPE)
  40. if err != nil {
  41. if err == unix.ENOTTY {
  42. t.Skipf("old kernel? (need Linux >= 4.11)")
  43. }
  44. t.Fatalf("failed to perform ioctl: %v", err)
  45. }
  46. if v != unix.CLONE_NEWNS {
  47. t.Fatalf("unexpected return from ioctl; expected %v, got %v", v, unix.CLONE_NEWNS)
  48. }
  49. }
  50. func TestIoctlGetRTCTime(t *testing.T) {
  51. f, err := os.Open("/dev/rtc0")
  52. if err != nil {
  53. t.Skipf("skipping test, %v", err)
  54. }
  55. defer f.Close()
  56. v, err := unix.IoctlGetRTCTime(int(f.Fd()))
  57. if err != nil {
  58. t.Fatalf("failed to perform ioctl: %v", err)
  59. }
  60. t.Logf("RTC time: %04d-%02d-%02d %02d:%02d:%02d", v.Year+1900, v.Mon+1, v.Mday, v.Hour, v.Min, v.Sec)
  61. }
  62. func TestPpoll(t *testing.T) {
  63. if runtime.GOOS == "android" {
  64. t.Skip("mkfifo syscall is not available on android, skipping test")
  65. }
  66. defer chtmpdir(t)()
  67. f, cleanup := mktmpfifo(t)
  68. defer cleanup()
  69. const timeout = 100 * time.Millisecond
  70. ok := make(chan bool, 1)
  71. go func() {
  72. select {
  73. case <-time.After(10 * timeout):
  74. t.Errorf("Ppoll: failed to timeout after %d", 10*timeout)
  75. case <-ok:
  76. }
  77. }()
  78. fds := []unix.PollFd{{Fd: int32(f.Fd()), Events: unix.POLLIN}}
  79. timeoutTs := unix.NsecToTimespec(int64(timeout))
  80. n, err := unix.Ppoll(fds, &timeoutTs, nil)
  81. ok <- true
  82. if err != nil {
  83. t.Errorf("Ppoll: unexpected error: %v", err)
  84. return
  85. }
  86. if n != 0 {
  87. t.Errorf("Ppoll: wrong number of events: got %v, expected %v", n, 0)
  88. return
  89. }
  90. }
  91. func TestTime(t *testing.T) {
  92. var ut unix.Time_t
  93. ut2, err := unix.Time(&ut)
  94. if err != nil {
  95. t.Fatalf("Time: %v", err)
  96. }
  97. if ut != ut2 {
  98. t.Errorf("Time: return value %v should be equal to argument %v", ut2, ut)
  99. }
  100. var now time.Time
  101. for i := 0; i < 10; i++ {
  102. ut, err = unix.Time(nil)
  103. if err != nil {
  104. t.Fatalf("Time: %v", err)
  105. }
  106. now = time.Now()
  107. if int64(ut) == now.Unix() {
  108. return
  109. }
  110. }
  111. t.Errorf("Time: return value %v should be nearly equal to time.Now().Unix() %v", ut, now.Unix())
  112. }
  113. func TestUtime(t *testing.T) {
  114. defer chtmpdir(t)()
  115. touch(t, "file1")
  116. buf := &unix.Utimbuf{
  117. Modtime: 12345,
  118. }
  119. err := unix.Utime("file1", buf)
  120. if err != nil {
  121. t.Fatalf("Utime: %v", err)
  122. }
  123. fi, err := os.Stat("file1")
  124. if err != nil {
  125. t.Fatal(err)
  126. }
  127. if fi.ModTime().Unix() != 12345 {
  128. t.Errorf("Utime: failed to change modtime: expected %v, got %v", 12345, fi.ModTime().Unix())
  129. }
  130. }
  131. func TestUtimesNanoAt(t *testing.T) {
  132. defer chtmpdir(t)()
  133. symlink := "symlink1"
  134. os.Remove(symlink)
  135. err := os.Symlink("nonexisting", symlink)
  136. if err != nil {
  137. t.Fatal(err)
  138. }
  139. ts := []unix.Timespec{
  140. {Sec: 1111, Nsec: 2222},
  141. {Sec: 3333, Nsec: 4444},
  142. }
  143. err = unix.UtimesNanoAt(unix.AT_FDCWD, symlink, ts, unix.AT_SYMLINK_NOFOLLOW)
  144. if err != nil {
  145. t.Fatalf("UtimesNanoAt: %v", err)
  146. }
  147. var st unix.Stat_t
  148. err = unix.Lstat(symlink, &st)
  149. if err != nil {
  150. t.Fatalf("Lstat: %v", err)
  151. }
  152. // Only check Mtim, Atim might not be supported by the underlying filesystem
  153. expected := ts[1]
  154. if st.Mtim.Nsec == 0 {
  155. // Some filesystems only support 1-second time stamp resolution
  156. // and will always set Nsec to 0.
  157. expected.Nsec = 0
  158. }
  159. if st.Mtim != expected {
  160. t.Errorf("UtimesNanoAt: wrong mtime: expected %v, got %v", expected, st.Mtim)
  161. }
  162. }
  163. func TestRlimitAs(t *testing.T) {
  164. // disable GC during to avoid flaky test
  165. defer debug.SetGCPercent(debug.SetGCPercent(-1))
  166. var rlim unix.Rlimit
  167. err := unix.Getrlimit(unix.RLIMIT_AS, &rlim)
  168. if err != nil {
  169. t.Fatalf("Getrlimit: %v", err)
  170. }
  171. var zero unix.Rlimit
  172. if zero == rlim {
  173. t.Fatalf("Getrlimit: got zero value %#v", rlim)
  174. }
  175. set := rlim
  176. set.Cur = uint64(unix.Getpagesize())
  177. err = unix.Setrlimit(unix.RLIMIT_AS, &set)
  178. if err != nil {
  179. t.Fatalf("Setrlimit: set failed: %#v %v", set, err)
  180. }
  181. // RLIMIT_AS was set to the page size, so mmap()'ing twice the page size
  182. // should fail. See 'man 2 getrlimit'.
  183. _, err = unix.Mmap(-1, 0, 2*unix.Getpagesize(), unix.PROT_NONE, unix.MAP_ANON|unix.MAP_PRIVATE)
  184. if err == nil {
  185. t.Fatal("Mmap: unexpectedly succeeded after setting RLIMIT_AS")
  186. }
  187. err = unix.Setrlimit(unix.RLIMIT_AS, &rlim)
  188. if err != nil {
  189. t.Fatalf("Setrlimit: restore failed: %#v %v", rlim, err)
  190. }
  191. b, err := unix.Mmap(-1, 0, 2*unix.Getpagesize(), unix.PROT_NONE, unix.MAP_ANON|unix.MAP_PRIVATE)
  192. if err != nil {
  193. t.Fatalf("Mmap: %v", err)
  194. }
  195. err = unix.Munmap(b)
  196. if err != nil {
  197. t.Fatalf("Munmap: %v", err)
  198. }
  199. }
  200. func TestSelect(t *testing.T) {
  201. n, err := unix.Select(0, nil, nil, nil, &unix.Timeval{Sec: 0, Usec: 0})
  202. if err != nil {
  203. t.Fatalf("Select: %v", err)
  204. }
  205. if n != 0 {
  206. t.Fatalf("Select: expected 0 ready file descriptors, got %v", n)
  207. }
  208. dur := 150 * time.Millisecond
  209. tv := unix.NsecToTimeval(int64(dur))
  210. start := time.Now()
  211. n, err = unix.Select(0, nil, nil, nil, &tv)
  212. took := time.Since(start)
  213. if err != nil {
  214. t.Fatalf("Select: %v", err)
  215. }
  216. if n != 0 {
  217. t.Fatalf("Select: expected 0 ready file descriptors, got %v", n)
  218. }
  219. if took < dur {
  220. t.Errorf("Select: timeout should have been at least %v, got %v", dur, took)
  221. }
  222. rr, ww, err := os.Pipe()
  223. if err != nil {
  224. t.Fatal(err)
  225. }
  226. defer rr.Close()
  227. defer ww.Close()
  228. if _, err := ww.Write([]byte("HELLO GOPHER")); err != nil {
  229. t.Fatal(err)
  230. }
  231. rFdSet := &unix.FdSet{}
  232. fd := rr.Fd()
  233. // FD_SET(fd, rFdSet)
  234. rFdSet.Bits[fd/unix.NFDBITS] |= (1 << (fd % unix.NFDBITS))
  235. n, err = unix.Select(int(fd+1), rFdSet, nil, nil, nil)
  236. if err != nil {
  237. t.Fatalf("Select: %v", err)
  238. }
  239. if n != 1 {
  240. t.Fatalf("Select: expected 1 ready file descriptors, got %v", n)
  241. }
  242. }
  243. func TestPselect(t *testing.T) {
  244. _, err := unix.Pselect(0, nil, nil, nil, &unix.Timespec{Sec: 0, Nsec: 0}, nil)
  245. if err != nil {
  246. t.Fatalf("Pselect: %v", err)
  247. }
  248. dur := 2500 * time.Microsecond
  249. ts := unix.NsecToTimespec(int64(dur))
  250. start := time.Now()
  251. _, err = unix.Pselect(0, nil, nil, nil, &ts, nil)
  252. took := time.Since(start)
  253. if err != nil {
  254. t.Fatalf("Pselect: %v", err)
  255. }
  256. if took < dur {
  257. t.Errorf("Pselect: timeout should have been at least %v, got %v", dur, took)
  258. }
  259. }
  260. func TestSchedSetaffinity(t *testing.T) {
  261. runtime.LockOSThread()
  262. defer runtime.UnlockOSThread()
  263. var oldMask unix.CPUSet
  264. err := unix.SchedGetaffinity(0, &oldMask)
  265. if err != nil {
  266. t.Fatalf("SchedGetaffinity: %v", err)
  267. }
  268. var newMask unix.CPUSet
  269. newMask.Zero()
  270. if newMask.Count() != 0 {
  271. t.Errorf("CpuZero: didn't zero CPU set: %v", newMask)
  272. }
  273. cpu := 1
  274. newMask.Set(cpu)
  275. if newMask.Count() != 1 || !newMask.IsSet(cpu) {
  276. t.Errorf("CpuSet: didn't set CPU %d in set: %v", cpu, newMask)
  277. }
  278. cpu = 5
  279. newMask.Set(cpu)
  280. if newMask.Count() != 2 || !newMask.IsSet(cpu) {
  281. t.Errorf("CpuSet: didn't set CPU %d in set: %v", cpu, newMask)
  282. }
  283. newMask.Clear(cpu)
  284. if newMask.Count() != 1 || newMask.IsSet(cpu) {
  285. t.Errorf("CpuClr: didn't clear CPU %d in set: %v", cpu, newMask)
  286. }
  287. if runtime.NumCPU() < 2 {
  288. t.Skip("skipping setaffinity tests on single CPU system")
  289. }
  290. if runtime.GOOS == "android" {
  291. t.Skip("skipping setaffinity tests on android")
  292. }
  293. // On a system like ppc64x where some cores can be disabled using ppc64_cpu,
  294. // setaffinity should only be called with enabled cores. The valid cores
  295. // are found from the oldMask, but if none are found then the setaffinity
  296. // tests are skipped. Issue #27875.
  297. if !oldMask.IsSet(cpu) {
  298. newMask.Zero()
  299. for i := 0; i < len(oldMask); i++ {
  300. if oldMask.IsSet(i) {
  301. newMask.Set(i)
  302. break
  303. }
  304. }
  305. if newMask.Count() == 0 {
  306. t.Skip("skipping setaffinity tests if CPU not available")
  307. }
  308. }
  309. err = unix.SchedSetaffinity(0, &newMask)
  310. if err != nil {
  311. t.Fatalf("SchedSetaffinity: %v", err)
  312. }
  313. var gotMask unix.CPUSet
  314. err = unix.SchedGetaffinity(0, &gotMask)
  315. if err != nil {
  316. t.Fatalf("SchedGetaffinity: %v", err)
  317. }
  318. if gotMask != newMask {
  319. t.Errorf("SchedSetaffinity: returned affinity mask does not match set affinity mask")
  320. }
  321. // Restore old mask so it doesn't affect successive tests
  322. err = unix.SchedSetaffinity(0, &oldMask)
  323. if err != nil {
  324. t.Fatalf("SchedSetaffinity: %v", err)
  325. }
  326. }
  327. func TestStatx(t *testing.T) {
  328. var stx unix.Statx_t
  329. err := unix.Statx(unix.AT_FDCWD, ".", 0, 0, &stx)
  330. if err == unix.ENOSYS || err == unix.EPERM {
  331. t.Skip("statx syscall is not available, skipping test")
  332. } else if err != nil {
  333. t.Fatalf("Statx: %v", err)
  334. }
  335. defer chtmpdir(t)()
  336. touch(t, "file1")
  337. var st unix.Stat_t
  338. err = unix.Stat("file1", &st)
  339. if err != nil {
  340. t.Fatalf("Stat: %v", err)
  341. }
  342. flags := unix.AT_STATX_SYNC_AS_STAT
  343. err = unix.Statx(unix.AT_FDCWD, "file1", flags, unix.STATX_ALL, &stx)
  344. if err != nil {
  345. t.Fatalf("Statx: %v", err)
  346. }
  347. if uint32(stx.Mode) != st.Mode {
  348. t.Errorf("Statx: returned stat mode does not match Stat")
  349. }
  350. ctime := unix.StatxTimestamp{Sec: int64(st.Ctim.Sec), Nsec: uint32(st.Ctim.Nsec)}
  351. mtime := unix.StatxTimestamp{Sec: int64(st.Mtim.Sec), Nsec: uint32(st.Mtim.Nsec)}
  352. if stx.Ctime != ctime {
  353. t.Errorf("Statx: returned stat ctime does not match Stat")
  354. }
  355. if stx.Mtime != mtime {
  356. t.Errorf("Statx: returned stat mtime does not match Stat")
  357. }
  358. err = os.Symlink("file1", "symlink1")
  359. if err != nil {
  360. t.Fatal(err)
  361. }
  362. err = unix.Lstat("symlink1", &st)
  363. if err != nil {
  364. t.Fatalf("Lstat: %v", err)
  365. }
  366. err = unix.Statx(unix.AT_FDCWD, "symlink1", flags, unix.STATX_BASIC_STATS, &stx)
  367. if err != nil {
  368. t.Fatalf("Statx: %v", err)
  369. }
  370. // follow symlink, expect a regulat file
  371. if stx.Mode&unix.S_IFREG == 0 {
  372. t.Errorf("Statx: didn't follow symlink")
  373. }
  374. err = unix.Statx(unix.AT_FDCWD, "symlink1", flags|unix.AT_SYMLINK_NOFOLLOW, unix.STATX_ALL, &stx)
  375. if err != nil {
  376. t.Fatalf("Statx: %v", err)
  377. }
  378. // follow symlink, expect a symlink
  379. if stx.Mode&unix.S_IFLNK == 0 {
  380. t.Errorf("Statx: unexpectedly followed symlink")
  381. }
  382. if uint32(stx.Mode) != st.Mode {
  383. t.Errorf("Statx: returned stat mode does not match Lstat")
  384. }
  385. ctime = unix.StatxTimestamp{Sec: int64(st.Ctim.Sec), Nsec: uint32(st.Ctim.Nsec)}
  386. mtime = unix.StatxTimestamp{Sec: int64(st.Mtim.Sec), Nsec: uint32(st.Mtim.Nsec)}
  387. if stx.Ctime != ctime {
  388. t.Errorf("Statx: returned stat ctime does not match Lstat")
  389. }
  390. if stx.Mtime != mtime {
  391. t.Errorf("Statx: returned stat mtime does not match Lstat")
  392. }
  393. }
  394. // stringsFromByteSlice converts a sequence of attributes to a []string.
  395. // On Linux, each entry is a NULL-terminated string.
  396. func stringsFromByteSlice(buf []byte) []string {
  397. var result []string
  398. off := 0
  399. for i, b := range buf {
  400. if b == 0 {
  401. result = append(result, string(buf[off:i]))
  402. off = i + 1
  403. }
  404. }
  405. return result
  406. }
  407. func TestFaccessat(t *testing.T) {
  408. defer chtmpdir(t)()
  409. touch(t, "file1")
  410. err := unix.Faccessat(unix.AT_FDCWD, "file1", unix.R_OK, 0)
  411. if err != nil {
  412. t.Errorf("Faccessat: unexpected error: %v", err)
  413. }
  414. err = unix.Faccessat(unix.AT_FDCWD, "file1", unix.R_OK, 2)
  415. if err != unix.EINVAL {
  416. t.Errorf("Faccessat: unexpected error: %v, want EINVAL", err)
  417. }
  418. err = unix.Faccessat(unix.AT_FDCWD, "file1", unix.R_OK, unix.AT_EACCESS)
  419. if err != nil {
  420. t.Errorf("Faccessat: unexpected error: %v", err)
  421. }
  422. err = os.Symlink("file1", "symlink1")
  423. if err != nil {
  424. t.Fatal(err)
  425. }
  426. err = unix.Faccessat(unix.AT_FDCWD, "symlink1", unix.R_OK, unix.AT_SYMLINK_NOFOLLOW)
  427. if err != nil {
  428. t.Errorf("Faccessat SYMLINK_NOFOLLOW: unexpected error %v", err)
  429. }
  430. // We can't really test AT_SYMLINK_NOFOLLOW, because there
  431. // doesn't seem to be any way to change the mode of a symlink.
  432. // We don't test AT_EACCESS because such tests are only
  433. // meaningful if run as root.
  434. err = unix.Fchmodat(unix.AT_FDCWD, "file1", 0, 0)
  435. if err != nil {
  436. t.Errorf("Fchmodat: unexpected error %v", err)
  437. }
  438. err = unix.Faccessat(unix.AT_FDCWD, "file1", unix.F_OK, unix.AT_SYMLINK_NOFOLLOW)
  439. if err != nil {
  440. t.Errorf("Faccessat: unexpected error: %v", err)
  441. }
  442. err = unix.Faccessat(unix.AT_FDCWD, "file1", unix.R_OK, unix.AT_SYMLINK_NOFOLLOW)
  443. if err != unix.EACCES {
  444. if unix.Getuid() != 0 {
  445. t.Errorf("Faccessat: unexpected error: %v, want EACCES", err)
  446. }
  447. }
  448. }
  449. func TestSyncFileRange(t *testing.T) {
  450. file, err := ioutil.TempFile("", "TestSyncFileRange")
  451. if err != nil {
  452. t.Fatal(err)
  453. }
  454. defer os.Remove(file.Name())
  455. defer file.Close()
  456. err = unix.SyncFileRange(int(file.Fd()), 0, 0, 0)
  457. if err == unix.ENOSYS || err == unix.EPERM {
  458. t.Skip("sync_file_range syscall is not available, skipping test")
  459. } else if err != nil {
  460. t.Fatalf("SyncFileRange: %v", err)
  461. }
  462. // invalid flags
  463. flags := 0xf00
  464. err = unix.SyncFileRange(int(file.Fd()), 0, 0, flags)
  465. if err != unix.EINVAL {
  466. t.Fatalf("SyncFileRange: unexpected error: %v, want EINVAL", err)
  467. }
  468. }
  469. func TestClockNanosleep(t *testing.T) {
  470. delay := 100 * time.Millisecond
  471. // Relative timespec.
  472. start := time.Now()
  473. rel := unix.NsecToTimespec(delay.Nanoseconds())
  474. err := unix.ClockNanosleep(unix.CLOCK_MONOTONIC, 0, &rel, nil)
  475. if err == unix.ENOSYS || err == unix.EPERM {
  476. t.Skip("clock_nanosleep syscall is not available, skipping test")
  477. } else if err != nil {
  478. t.Errorf("ClockNanosleep(CLOCK_MONOTONIC, 0, %#v, nil) = %v", &rel, err)
  479. } else if slept := time.Since(start); slept < delay {
  480. t.Errorf("ClockNanosleep(CLOCK_MONOTONIC, 0, %#v, nil) slept only %v", &rel, slept)
  481. }
  482. // Absolute timespec.
  483. start = time.Now()
  484. until := start.Add(delay)
  485. abs := unix.NsecToTimespec(until.UnixNano())
  486. err = unix.ClockNanosleep(unix.CLOCK_REALTIME, unix.TIMER_ABSTIME, &abs, nil)
  487. if err != nil {
  488. t.Errorf("ClockNanosleep(CLOCK_REALTIME, TIMER_ABSTIME, %#v (=%v), nil) = %v", &abs, until, err)
  489. } else if slept := time.Since(start); slept < delay {
  490. t.Errorf("ClockNanosleep(CLOCK_REALTIME, TIMER_ABSTIME, %#v (=%v), nil) slept only %v", &abs, until, slept)
  491. }
  492. // Invalid clock. clock_nanosleep(2) says EINVAL, but it’s actually EOPNOTSUPP.
  493. err = unix.ClockNanosleep(unix.CLOCK_THREAD_CPUTIME_ID, 0, &rel, nil)
  494. if err != unix.EINVAL && err != unix.EOPNOTSUPP {
  495. t.Errorf("ClockNanosleep(CLOCK_THREAD_CPUTIME_ID, 0, %#v, nil) = %v, want EINVAL or EOPNOTSUPP", &rel, err)
  496. }
  497. }
  498. func TestOpenByHandleAt(t *testing.T) {
  499. skipIfNotSupported := func(t *testing.T, name string, err error) {
  500. if err == unix.EPERM {
  501. t.Skipf("skipping %s test without CAP_DAC_READ_SEARCH", name)
  502. }
  503. if err == unix.ENOSYS {
  504. t.Skipf("%s system call not available", name)
  505. }
  506. if err == unix.EOPNOTSUPP {
  507. t.Skipf("%s not supported on this filesystem", name)
  508. }
  509. }
  510. h, mountID, err := unix.NameToHandleAt(unix.AT_FDCWD, "syscall_linux_test.go", 0)
  511. if err != nil {
  512. skipIfNotSupported(t, "name_to_handle_at", err)
  513. t.Fatalf("NameToHandleAt: %v", err)
  514. }
  515. t.Logf("mountID: %v, handle: size=%d, type=%d, bytes=%q", mountID,
  516. h.Size(), h.Type(), h.Bytes())
  517. mount, err := openMountByID(mountID)
  518. if err != nil {
  519. t.Fatalf("openMountByID: %v", err)
  520. }
  521. defer mount.Close()
  522. for _, clone := range []bool{false, true} {
  523. t.Run("clone="+strconv.FormatBool(clone), func(t *testing.T) {
  524. if clone {
  525. h = unix.NewFileHandle(h.Type(), h.Bytes())
  526. }
  527. fd, err := unix.OpenByHandleAt(int(mount.Fd()), h, unix.O_RDONLY)
  528. skipIfNotSupported(t, "open_by_handle_at", err)
  529. if err != nil {
  530. t.Fatalf("OpenByHandleAt: %v", err)
  531. }
  532. defer unix.Close(fd)
  533. t.Logf("opened fd %v", fd)
  534. f := os.NewFile(uintptr(fd), "")
  535. slurp, err := ioutil.ReadAll(f)
  536. if err != nil {
  537. t.Fatal(err)
  538. }
  539. const substr = "Some substring for a test."
  540. if !strings.Contains(string(slurp), substr) {
  541. t.Errorf("didn't find substring %q in opened file; read %d bytes", substr, len(slurp))
  542. }
  543. })
  544. }
  545. }
  546. func openMountByID(mountID int) (f *os.File, err error) {
  547. mi, err := os.Open("/proc/self/mountinfo")
  548. if err != nil {
  549. return nil, err
  550. }
  551. defer mi.Close()
  552. bs := bufio.NewScanner(mi)
  553. wantPrefix := []byte(fmt.Sprintf("%v ", mountID))
  554. for bs.Scan() {
  555. if !bytes.HasPrefix(bs.Bytes(), wantPrefix) {
  556. continue
  557. }
  558. fields := strings.Fields(bs.Text())
  559. dev := fields[4]
  560. return os.Open(dev)
  561. }
  562. if err := bs.Err(); err != nil {
  563. return nil, err
  564. }
  565. return nil, errors.New("mountID not found")
  566. }