You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1115 lines
28 KiB

  1. // Copyright 2009 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. // Linux system calls.
  5. // This file is compiled as ordinary Go code,
  6. // but it is also input to mksyscall,
  7. // which parses the //sys lines and generates system call stubs.
  8. // Note that sometimes we use a lowercase //sys name and
  9. // wrap it in our own nicer implementation.
  10. package unix
  11. import (
  12. "syscall"
  13. "unsafe"
  14. )
  15. /*
  16. * Wrapped
  17. */
  18. func Access(path string, mode uint32) (err error) {
  19. return Faccessat(AT_FDCWD, path, mode, 0)
  20. }
  21. func Chmod(path string, mode uint32) (err error) {
  22. return Fchmodat(AT_FDCWD, path, mode, 0)
  23. }
  24. func Chown(path string, uid int, gid int) (err error) {
  25. return Fchownat(AT_FDCWD, path, uid, gid, 0)
  26. }
  27. func Creat(path string, mode uint32) (fd int, err error) {
  28. return Open(path, O_CREAT|O_WRONLY|O_TRUNC, mode)
  29. }
  30. //sys Linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error)
  31. func Link(oldpath string, newpath string) (err error) {
  32. return Linkat(AT_FDCWD, oldpath, AT_FDCWD, newpath, 0)
  33. }
  34. func Mkdir(path string, mode uint32) (err error) {
  35. return Mkdirat(AT_FDCWD, path, mode)
  36. }
  37. func Mknod(path string, mode uint32, dev int) (err error) {
  38. return Mknodat(AT_FDCWD, path, mode, dev)
  39. }
  40. func Open(path string, mode int, perm uint32) (fd int, err error) {
  41. return openat(AT_FDCWD, path, mode|O_LARGEFILE, perm)
  42. }
  43. //sys openat(dirfd int, path string, flags int, mode uint32) (fd int, err error)
  44. func Openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) {
  45. return openat(dirfd, path, flags|O_LARGEFILE, mode)
  46. }
  47. //sys ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error)
  48. func Ppoll(fds []PollFd, timeout *Timespec, sigmask *Sigset_t) (n int, err error) {
  49. if len(fds) == 0 {
  50. return ppoll(nil, 0, timeout, sigmask)
  51. }
  52. return ppoll(&fds[0], len(fds), timeout, sigmask)
  53. }
  54. //sys readlinkat(dirfd int, path string, buf []byte) (n int, err error)
  55. func Readlink(path string, buf []byte) (n int, err error) {
  56. return readlinkat(AT_FDCWD, path, buf)
  57. }
  58. func Rename(oldpath string, newpath string) (err error) {
  59. return Renameat(AT_FDCWD, oldpath, AT_FDCWD, newpath)
  60. }
  61. func Rmdir(path string) error {
  62. return unlinkat(AT_FDCWD, path, AT_REMOVEDIR)
  63. }
  64. //sys symlinkat(oldpath string, newdirfd int, newpath string) (err error)
  65. func Symlink(oldpath string, newpath string) (err error) {
  66. return symlinkat(oldpath, AT_FDCWD, newpath)
  67. }
  68. func Unlink(path string) error {
  69. return unlinkat(AT_FDCWD, path, 0)
  70. }
  71. //sys unlinkat(dirfd int, path string, flags int) (err error)
  72. func Unlinkat(dirfd int, path string, flags int) error {
  73. return unlinkat(dirfd, path, flags)
  74. }
  75. //sys utimes(path string, times *[2]Timeval) (err error)
  76. func Utimes(path string, tv []Timeval) error {
  77. if tv == nil {
  78. err := utimensat(AT_FDCWD, path, nil, 0)
  79. if err != ENOSYS {
  80. return err
  81. }
  82. return utimes(path, nil)
  83. }
  84. if len(tv) != 2 {
  85. return EINVAL
  86. }
  87. var ts [2]Timespec
  88. ts[0] = NsecToTimespec(TimevalToNsec(tv[0]))
  89. ts[1] = NsecToTimespec(TimevalToNsec(tv[1]))
  90. err := utimensat(AT_FDCWD, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), 0)
  91. if err != ENOSYS {
  92. return err
  93. }
  94. return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
  95. }
  96. //sys utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error)
  97. func UtimesNano(path string, ts []Timespec) error {
  98. if ts == nil {
  99. err := utimensat(AT_FDCWD, path, nil, 0)
  100. if err != ENOSYS {
  101. return err
  102. }
  103. return utimes(path, nil)
  104. }
  105. if len(ts) != 2 {
  106. return EINVAL
  107. }
  108. err := utimensat(AT_FDCWD, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), 0)
  109. if err != ENOSYS {
  110. return err
  111. }
  112. // If the utimensat syscall isn't available (utimensat was added to Linux
  113. // in 2.6.22, Released, 8 July 2007) then fall back to utimes
  114. var tv [2]Timeval
  115. for i := 0; i < 2; i++ {
  116. tv[i].Sec = ts[i].Sec
  117. tv[i].Usec = ts[i].Nsec / 1000
  118. }
  119. return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
  120. }
  121. func UtimesNanoAt(dirfd int, path string, ts []Timespec, flags int) error {
  122. if ts == nil {
  123. return utimensat(dirfd, path, nil, flags)
  124. }
  125. if len(ts) != 2 {
  126. return EINVAL
  127. }
  128. return utimensat(dirfd, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), flags)
  129. }
  130. //sys futimesat(dirfd int, path *byte, times *[2]Timeval) (err error)
  131. func Futimesat(dirfd int, path string, tv []Timeval) error {
  132. pathp, err := BytePtrFromString(path)
  133. if err != nil {
  134. return err
  135. }
  136. if tv == nil {
  137. return futimesat(dirfd, pathp, nil)
  138. }
  139. if len(tv) != 2 {
  140. return EINVAL
  141. }
  142. return futimesat(dirfd, pathp, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
  143. }
  144. func Futimes(fd int, tv []Timeval) (err error) {
  145. // Believe it or not, this is the best we can do on Linux
  146. // (and is what glibc does).
  147. return Utimes("/proc/self/fd/"+itoa(fd), tv)
  148. }
  149. const ImplementsGetwd = true
  150. //sys Getcwd(buf []byte) (n int, err error)
  151. func Getwd() (wd string, err error) {
  152. var buf [PathMax]byte
  153. n, err := Getcwd(buf[0:])
  154. if err != nil {
  155. return "", err
  156. }
  157. // Getcwd returns the number of bytes written to buf, including the NUL.
  158. if n < 1 || n > len(buf) || buf[n-1] != 0 {
  159. return "", EINVAL
  160. }
  161. return string(buf[0 : n-1]), nil
  162. }
  163. func Getgroups() (gids []int, err error) {
  164. n, err := getgroups(0, nil)
  165. if err != nil {
  166. return nil, err
  167. }
  168. if n == 0 {
  169. return nil, nil
  170. }
  171. // Sanity check group count. Max is 1<<16 on Linux.
  172. if n < 0 || n > 1<<20 {
  173. return nil, EINVAL
  174. }
  175. a := make([]_Gid_t, n)
  176. n, err = getgroups(n, &a[0])
  177. if err != nil {
  178. return nil, err
  179. }
  180. gids = make([]int, n)
  181. for i, v := range a[0:n] {
  182. gids[i] = int(v)
  183. }
  184. return
  185. }
  186. func Setgroups(gids []int) (err error) {
  187. if len(gids) == 0 {
  188. return setgroups(0, nil)
  189. }
  190. a := make([]_Gid_t, len(gids))
  191. for i, v := range gids {
  192. a[i] = _Gid_t(v)
  193. }
  194. return setgroups(len(a), &a[0])
  195. }
  196. type WaitStatus uint32
  197. // Wait status is 7 bits at bottom, either 0 (exited),
  198. // 0x7F (stopped), or a signal number that caused an exit.
  199. // The 0x80 bit is whether there was a core dump.
  200. // An extra number (exit code, signal causing a stop)
  201. // is in the high bits. At least that's the idea.
  202. // There are various irregularities. For example, the
  203. // "continued" status is 0xFFFF, distinguishing itself
  204. // from stopped via the core dump bit.
  205. const (
  206. mask = 0x7F
  207. core = 0x80
  208. exited = 0x00
  209. stopped = 0x7F
  210. shift = 8
  211. )
  212. func (w WaitStatus) Exited() bool { return w&mask == exited }
  213. func (w WaitStatus) Signaled() bool { return w&mask != stopped && w&mask != exited }
  214. func (w WaitStatus) Stopped() bool { return w&0xFF == stopped }
  215. func (w WaitStatus) Continued() bool { return w == 0xFFFF }
  216. func (w WaitStatus) CoreDump() bool { return w.Signaled() && w&core != 0 }
  217. func (w WaitStatus) ExitStatus() int {
  218. if !w.Exited() {
  219. return -1
  220. }
  221. return int(w>>shift) & 0xFF
  222. }
  223. func (w WaitStatus) Signal() syscall.Signal {
  224. if !w.Signaled() {
  225. return -1
  226. }
  227. return syscall.Signal(w & mask)
  228. }
  229. func (w WaitStatus) StopSignal() syscall.Signal {
  230. if !w.Stopped() {
  231. return -1
  232. }
  233. return syscall.Signal(w>>shift) & 0xFF
  234. }
  235. func (w WaitStatus) TrapCause() int {
  236. if w.StopSignal() != SIGTRAP {
  237. return -1
  238. }
  239. return int(w>>shift) >> 8
  240. }
  241. //sys wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error)
  242. func Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, err error) {
  243. var status _C_int
  244. wpid, err = wait4(pid, &status, options, rusage)
  245. if wstatus != nil {
  246. *wstatus = WaitStatus(status)
  247. }
  248. return
  249. }
  250. func Mkfifo(path string, mode uint32) (err error) {
  251. return Mknod(path, mode|S_IFIFO, 0)
  252. }
  253. func (sa *SockaddrInet4) sockaddr() (unsafe.Pointer, _Socklen, error) {
  254. if sa.Port < 0 || sa.Port > 0xFFFF {
  255. return nil, 0, EINVAL
  256. }
  257. sa.raw.Family = AF_INET
  258. p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port))
  259. p[0] = byte(sa.Port >> 8)
  260. p[1] = byte(sa.Port)
  261. for i := 0; i < len(sa.Addr); i++ {
  262. sa.raw.Addr[i] = sa.Addr[i]
  263. }
  264. return unsafe.Pointer(&sa.raw), SizeofSockaddrInet4, nil
  265. }
  266. func (sa *SockaddrInet6) sockaddr() (unsafe.Pointer, _Socklen, error) {
  267. if sa.Port < 0 || sa.Port > 0xFFFF {
  268. return nil, 0, EINVAL
  269. }
  270. sa.raw.Family = AF_INET6
  271. p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port))
  272. p[0] = byte(sa.Port >> 8)
  273. p[1] = byte(sa.Port)
  274. sa.raw.Scope_id = sa.ZoneId
  275. for i := 0; i < len(sa.Addr); i++ {
  276. sa.raw.Addr[i] = sa.Addr[i]
  277. }
  278. return unsafe.Pointer(&sa.raw), SizeofSockaddrInet6, nil
  279. }
  280. func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, _Socklen, error) {
  281. name := sa.Name
  282. n := len(name)
  283. if n >= len(sa.raw.Path) {
  284. return nil, 0, EINVAL
  285. }
  286. sa.raw.Family = AF_UNIX
  287. for i := 0; i < n; i++ {
  288. sa.raw.Path[i] = int8(name[i])
  289. }
  290. // length is family (uint16), name, NUL.
  291. sl := _Socklen(2)
  292. if n > 0 {
  293. sl += _Socklen(n) + 1
  294. }
  295. if sa.raw.Path[0] == '@' {
  296. sa.raw.Path[0] = 0
  297. // Don't count trailing NUL for abstract address.
  298. sl--
  299. }
  300. return unsafe.Pointer(&sa.raw), sl, nil
  301. }
  302. type SockaddrLinklayer struct {
  303. Protocol uint16
  304. Ifindex int
  305. Hatype uint16
  306. Pkttype uint8
  307. Halen uint8
  308. Addr [8]byte
  309. raw RawSockaddrLinklayer
  310. }
  311. func (sa *SockaddrLinklayer) sockaddr() (unsafe.Pointer, _Socklen, error) {
  312. if sa.Ifindex < 0 || sa.Ifindex > 0x7fffffff {
  313. return nil, 0, EINVAL
  314. }
  315. sa.raw.Family = AF_PACKET
  316. sa.raw.Protocol = sa.Protocol
  317. sa.raw.Ifindex = int32(sa.Ifindex)
  318. sa.raw.Hatype = sa.Hatype
  319. sa.raw.Pkttype = sa.Pkttype
  320. sa.raw.Halen = sa.Halen
  321. for i := 0; i < len(sa.Addr); i++ {
  322. sa.raw.Addr[i] = sa.Addr[i]
  323. }
  324. return unsafe.Pointer(&sa.raw), SizeofSockaddrLinklayer, nil
  325. }
  326. type SockaddrNetlink struct {
  327. Family uint16
  328. Pad uint16
  329. Pid uint32
  330. Groups uint32
  331. raw RawSockaddrNetlink
  332. }
  333. func (sa *SockaddrNetlink) sockaddr() (unsafe.Pointer, _Socklen, error) {
  334. sa.raw.Family = AF_NETLINK
  335. sa.raw.Pad = sa.Pad
  336. sa.raw.Pid = sa.Pid
  337. sa.raw.Groups = sa.Groups
  338. return unsafe.Pointer(&sa.raw), SizeofSockaddrNetlink, nil
  339. }
  340. type SockaddrHCI struct {
  341. Dev uint16
  342. Channel uint16
  343. raw RawSockaddrHCI
  344. }
  345. func (sa *SockaddrHCI) sockaddr() (unsafe.Pointer, _Socklen, error) {
  346. sa.raw.Family = AF_BLUETOOTH
  347. sa.raw.Dev = sa.Dev
  348. sa.raw.Channel = sa.Channel
  349. return unsafe.Pointer(&sa.raw), SizeofSockaddrHCI, nil
  350. }
  351. func anyToSockaddr(rsa *RawSockaddrAny) (Sockaddr, error) {
  352. switch rsa.Addr.Family {
  353. case AF_NETLINK:
  354. pp := (*RawSockaddrNetlink)(unsafe.Pointer(rsa))
  355. sa := new(SockaddrNetlink)
  356. sa.Family = pp.Family
  357. sa.Pad = pp.Pad
  358. sa.Pid = pp.Pid
  359. sa.Groups = pp.Groups
  360. return sa, nil
  361. case AF_PACKET:
  362. pp := (*RawSockaddrLinklayer)(unsafe.Pointer(rsa))
  363. sa := new(SockaddrLinklayer)
  364. sa.Protocol = pp.Protocol
  365. sa.Ifindex = int(pp.Ifindex)
  366. sa.Hatype = pp.Hatype
  367. sa.Pkttype = pp.Pkttype
  368. sa.Halen = pp.Halen
  369. for i := 0; i < len(sa.Addr); i++ {
  370. sa.Addr[i] = pp.Addr[i]
  371. }
  372. return sa, nil
  373. case AF_UNIX:
  374. pp := (*RawSockaddrUnix)(unsafe.Pointer(rsa))
  375. sa := new(SockaddrUnix)
  376. if pp.Path[0] == 0 {
  377. // "Abstract" Unix domain socket.
  378. // Rewrite leading NUL as @ for textual display.
  379. // (This is the standard convention.)
  380. // Not friendly to overwrite in place,
  381. // but the callers below don't care.
  382. pp.Path[0] = '@'
  383. }
  384. // Assume path ends at NUL.
  385. // This is not technically the Linux semantics for
  386. // abstract Unix domain sockets--they are supposed
  387. // to be uninterpreted fixed-size binary blobs--but
  388. // everyone uses this convention.
  389. n := 0
  390. for n < len(pp.Path) && pp.Path[n] != 0 {
  391. n++
  392. }
  393. bytes := (*[10000]byte)(unsafe.Pointer(&pp.Path[0]))[0:n]
  394. sa.Name = string(bytes)
  395. return sa, nil
  396. case AF_INET:
  397. pp := (*RawSockaddrInet4)(unsafe.Pointer(rsa))
  398. sa := new(SockaddrInet4)
  399. p := (*[2]byte)(unsafe.Pointer(&pp.Port))
  400. sa.Port = int(p[0])<<8 + int(p[1])
  401. for i := 0; i < len(sa.Addr); i++ {
  402. sa.Addr[i] = pp.Addr[i]
  403. }
  404. return sa, nil
  405. case AF_INET6:
  406. pp := (*RawSockaddrInet6)(unsafe.Pointer(rsa))
  407. sa := new(SockaddrInet6)
  408. p := (*[2]byte)(unsafe.Pointer(&pp.Port))
  409. sa.Port = int(p[0])<<8 + int(p[1])
  410. sa.ZoneId = pp.Scope_id
  411. for i := 0; i < len(sa.Addr); i++ {
  412. sa.Addr[i] = pp.Addr[i]
  413. }
  414. return sa, nil
  415. }
  416. return nil, EAFNOSUPPORT
  417. }
  418. func Accept(fd int) (nfd int, sa Sockaddr, err error) {
  419. var rsa RawSockaddrAny
  420. var len _Socklen = SizeofSockaddrAny
  421. nfd, err = accept(fd, &rsa, &len)
  422. if err != nil {
  423. return
  424. }
  425. sa, err = anyToSockaddr(&rsa)
  426. if err != nil {
  427. Close(nfd)
  428. nfd = 0
  429. }
  430. return
  431. }
  432. func Accept4(fd int, flags int) (nfd int, sa Sockaddr, err error) {
  433. var rsa RawSockaddrAny
  434. var len _Socklen = SizeofSockaddrAny
  435. nfd, err = accept4(fd, &rsa, &len, flags)
  436. if err != nil {
  437. return
  438. }
  439. if len > SizeofSockaddrAny {
  440. panic("RawSockaddrAny too small")
  441. }
  442. sa, err = anyToSockaddr(&rsa)
  443. if err != nil {
  444. Close(nfd)
  445. nfd = 0
  446. }
  447. return
  448. }
  449. func Getsockname(fd int) (sa Sockaddr, err error) {
  450. var rsa RawSockaddrAny
  451. var len _Socklen = SizeofSockaddrAny
  452. if err = getsockname(fd, &rsa, &len); err != nil {
  453. return
  454. }
  455. return anyToSockaddr(&rsa)
  456. }
  457. func GetsockoptInet4Addr(fd, level, opt int) (value [4]byte, err error) {
  458. vallen := _Socklen(4)
  459. err = getsockopt(fd, level, opt, unsafe.Pointer(&value[0]), &vallen)
  460. return value, err
  461. }
  462. func GetsockoptIPMreq(fd, level, opt int) (*IPMreq, error) {
  463. var value IPMreq
  464. vallen := _Socklen(SizeofIPMreq)
  465. err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
  466. return &value, err
  467. }
  468. func GetsockoptIPMreqn(fd, level, opt int) (*IPMreqn, error) {
  469. var value IPMreqn
  470. vallen := _Socklen(SizeofIPMreqn)
  471. err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
  472. return &value, err
  473. }
  474. func GetsockoptIPv6Mreq(fd, level, opt int) (*IPv6Mreq, error) {
  475. var value IPv6Mreq
  476. vallen := _Socklen(SizeofIPv6Mreq)
  477. err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
  478. return &value, err
  479. }
  480. func GetsockoptIPv6MTUInfo(fd, level, opt int) (*IPv6MTUInfo, error) {
  481. var value IPv6MTUInfo
  482. vallen := _Socklen(SizeofIPv6MTUInfo)
  483. err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
  484. return &value, err
  485. }
  486. func GetsockoptICMPv6Filter(fd, level, opt int) (*ICMPv6Filter, error) {
  487. var value ICMPv6Filter
  488. vallen := _Socklen(SizeofICMPv6Filter)
  489. err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
  490. return &value, err
  491. }
  492. func GetsockoptUcred(fd, level, opt int) (*Ucred, error) {
  493. var value Ucred
  494. vallen := _Socklen(SizeofUcred)
  495. err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
  496. return &value, err
  497. }
  498. func SetsockoptIPMreqn(fd, level, opt int, mreq *IPMreqn) (err error) {
  499. return setsockopt(fd, level, opt, unsafe.Pointer(mreq), unsafe.Sizeof(*mreq))
  500. }
  501. func Recvmsg(fd int, p, oob []byte, flags int) (n, oobn int, recvflags int, from Sockaddr, err error) {
  502. var msg Msghdr
  503. var rsa RawSockaddrAny
  504. msg.Name = (*byte)(unsafe.Pointer(&rsa))
  505. msg.Namelen = uint32(SizeofSockaddrAny)
  506. var iov Iovec
  507. if len(p) > 0 {
  508. iov.Base = (*byte)(unsafe.Pointer(&p[0]))
  509. iov.SetLen(len(p))
  510. }
  511. var dummy byte
  512. if len(oob) > 0 {
  513. // receive at least one normal byte
  514. if len(p) == 0 {
  515. iov.Base = &dummy
  516. iov.SetLen(1)
  517. }
  518. msg.Control = (*byte)(unsafe.Pointer(&oob[0]))
  519. msg.SetControllen(len(oob))
  520. }
  521. msg.Iov = &iov
  522. msg.Iovlen = 1
  523. if n, err = recvmsg(fd, &msg, flags); err != nil {
  524. return
  525. }
  526. oobn = int(msg.Controllen)
  527. recvflags = int(msg.Flags)
  528. // source address is only specified if the socket is unconnected
  529. if rsa.Addr.Family != AF_UNSPEC {
  530. from, err = anyToSockaddr(&rsa)
  531. }
  532. return
  533. }
  534. func Sendmsg(fd int, p, oob []byte, to Sockaddr, flags int) (err error) {
  535. _, err = SendmsgN(fd, p, oob, to, flags)
  536. return
  537. }
  538. func SendmsgN(fd int, p, oob []byte, to Sockaddr, flags int) (n int, err error) {
  539. var ptr unsafe.Pointer
  540. var salen _Socklen
  541. if to != nil {
  542. var err error
  543. ptr, salen, err = to.sockaddr()
  544. if err != nil {
  545. return 0, err
  546. }
  547. }
  548. var msg Msghdr
  549. msg.Name = (*byte)(unsafe.Pointer(ptr))
  550. msg.Namelen = uint32(salen)
  551. var iov Iovec
  552. if len(p) > 0 {
  553. iov.Base = (*byte)(unsafe.Pointer(&p[0]))
  554. iov.SetLen(len(p))
  555. }
  556. var dummy byte
  557. if len(oob) > 0 {
  558. // send at least one normal byte
  559. if len(p) == 0 {
  560. iov.Base = &dummy
  561. iov.SetLen(1)
  562. }
  563. msg.Control = (*byte)(unsafe.Pointer(&oob[0]))
  564. msg.SetControllen(len(oob))
  565. }
  566. msg.Iov = &iov
  567. msg.Iovlen = 1
  568. if n, err = sendmsg(fd, &msg, flags); err != nil {
  569. return 0, err
  570. }
  571. if len(oob) > 0 && len(p) == 0 {
  572. n = 0
  573. }
  574. return n, nil
  575. }
  576. // BindToDevice binds the socket associated with fd to device.
  577. func BindToDevice(fd int, device string) (err error) {
  578. return SetsockoptString(fd, SOL_SOCKET, SO_BINDTODEVICE, device)
  579. }
  580. //sys ptrace(request int, pid int, addr uintptr, data uintptr) (err error)
  581. func ptracePeek(req int, pid int, addr uintptr, out []byte) (count int, err error) {
  582. // The peek requests are machine-size oriented, so we wrap it
  583. // to retrieve arbitrary-length data.
  584. // The ptrace syscall differs from glibc's ptrace.
  585. // Peeks returns the word in *data, not as the return value.
  586. var buf [sizeofPtr]byte
  587. // Leading edge. PEEKTEXT/PEEKDATA don't require aligned
  588. // access (PEEKUSER warns that it might), but if we don't
  589. // align our reads, we might straddle an unmapped page
  590. // boundary and not get the bytes leading up to the page
  591. // boundary.
  592. n := 0
  593. if addr%sizeofPtr != 0 {
  594. err = ptrace(req, pid, addr-addr%sizeofPtr, uintptr(unsafe.Pointer(&buf[0])))
  595. if err != nil {
  596. return 0, err
  597. }
  598. n += copy(out, buf[addr%sizeofPtr:])
  599. out = out[n:]
  600. }
  601. // Remainder.
  602. for len(out) > 0 {
  603. // We use an internal buffer to guarantee alignment.
  604. // It's not documented if this is necessary, but we're paranoid.
  605. err = ptrace(req, pid, addr+uintptr(n), uintptr(unsafe.Pointer(&buf[0])))
  606. if err != nil {
  607. return n, err
  608. }
  609. copied := copy(out, buf[0:])
  610. n += copied
  611. out = out[copied:]
  612. }
  613. return n, nil
  614. }
  615. func PtracePeekText(pid int, addr uintptr, out []byte) (count int, err error) {
  616. return ptracePeek(PTRACE_PEEKTEXT, pid, addr, out)
  617. }
  618. func PtracePeekData(pid int, addr uintptr, out []byte) (count int, err error) {
  619. return ptracePeek(PTRACE_PEEKDATA, pid, addr, out)
  620. }
  621. func ptracePoke(pokeReq int, peekReq int, pid int, addr uintptr, data []byte) (count int, err error) {
  622. // As for ptracePeek, we need to align our accesses to deal
  623. // with the possibility of straddling an invalid page.
  624. // Leading edge.
  625. n := 0
  626. if addr%sizeofPtr != 0 {
  627. var buf [sizeofPtr]byte
  628. err = ptrace(peekReq, pid, addr-addr%sizeofPtr, uintptr(unsafe.Pointer(&buf[0])))
  629. if err != nil {
  630. return 0, err
  631. }
  632. n += copy(buf[addr%sizeofPtr:], data)
  633. word := *((*uintptr)(unsafe.Pointer(&buf[0])))
  634. err = ptrace(pokeReq, pid, addr-addr%sizeofPtr, word)
  635. if err != nil {
  636. return 0, err
  637. }
  638. data = data[n:]
  639. }
  640. // Interior.
  641. for len(data) > sizeofPtr {
  642. word := *((*uintptr)(unsafe.Pointer(&data[0])))
  643. err = ptrace(pokeReq, pid, addr+uintptr(n), word)
  644. if err != nil {
  645. return n, err
  646. }
  647. n += sizeofPtr
  648. data = data[sizeofPtr:]
  649. }
  650. // Trailing edge.
  651. if len(data) > 0 {
  652. var buf [sizeofPtr]byte
  653. err = ptrace(peekReq, pid, addr+uintptr(n), uintptr(unsafe.Pointer(&buf[0])))
  654. if err != nil {
  655. return n, err
  656. }
  657. copy(buf[0:], data)
  658. word := *((*uintptr)(unsafe.Pointer(&buf[0])))
  659. err = ptrace(pokeReq, pid, addr+uintptr(n), word)
  660. if err != nil {
  661. return n, err
  662. }
  663. n += len(data)
  664. }
  665. return n, nil
  666. }
  667. func PtracePokeText(pid int, addr uintptr, data []byte) (count int, err error) {
  668. return ptracePoke(PTRACE_POKETEXT, PTRACE_PEEKTEXT, pid, addr, data)
  669. }
  670. func PtracePokeData(pid int, addr uintptr, data []byte) (count int, err error) {
  671. return ptracePoke(PTRACE_POKEDATA, PTRACE_PEEKDATA, pid, addr, data)
  672. }
  673. func PtraceGetRegs(pid int, regsout *PtraceRegs) (err error) {
  674. return ptrace(PTRACE_GETREGS, pid, 0, uintptr(unsafe.Pointer(regsout)))
  675. }
  676. func PtraceSetRegs(pid int, regs *PtraceRegs) (err error) {
  677. return ptrace(PTRACE_SETREGS, pid, 0, uintptr(unsafe.Pointer(regs)))
  678. }
  679. func PtraceSetOptions(pid int, options int) (err error) {
  680. return ptrace(PTRACE_SETOPTIONS, pid, 0, uintptr(options))
  681. }
  682. func PtraceGetEventMsg(pid int) (msg uint, err error) {
  683. var data _C_long
  684. err = ptrace(PTRACE_GETEVENTMSG, pid, 0, uintptr(unsafe.Pointer(&data)))
  685. msg = uint(data)
  686. return
  687. }
  688. func PtraceCont(pid int, signal int) (err error) {
  689. return ptrace(PTRACE_CONT, pid, 0, uintptr(signal))
  690. }
  691. func PtraceSyscall(pid int, signal int) (err error) {
  692. return ptrace(PTRACE_SYSCALL, pid, 0, uintptr(signal))
  693. }
  694. func PtraceSingleStep(pid int) (err error) { return ptrace(PTRACE_SINGLESTEP, pid, 0, 0) }
  695. func PtraceAttach(pid int) (err error) { return ptrace(PTRACE_ATTACH, pid, 0, 0) }
  696. func PtraceDetach(pid int) (err error) { return ptrace(PTRACE_DETACH, pid, 0, 0) }
  697. //sys reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error)
  698. func Reboot(cmd int) (err error) {
  699. return reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, cmd, "")
  700. }
  701. func clen(n []byte) int {
  702. for i := 0; i < len(n); i++ {
  703. if n[i] == 0 {
  704. return i
  705. }
  706. }
  707. return len(n)
  708. }
  709. func ReadDirent(fd int, buf []byte) (n int, err error) {
  710. return Getdents(fd, buf)
  711. }
  712. func ParseDirent(buf []byte, max int, names []string) (consumed int, count int, newnames []string) {
  713. origlen := len(buf)
  714. count = 0
  715. for max != 0 && len(buf) > 0 {
  716. dirent := (*Dirent)(unsafe.Pointer(&buf[0]))
  717. buf = buf[dirent.Reclen:]
  718. if dirent.Ino == 0 { // File absent in directory.
  719. continue
  720. }
  721. bytes := (*[10000]byte)(unsafe.Pointer(&dirent.Name[0]))
  722. var name = string(bytes[0:clen(bytes[:])])
  723. if name == "." || name == ".." { // Useless names
  724. continue
  725. }
  726. max--
  727. count++
  728. names = append(names, name)
  729. }
  730. return origlen - len(buf), count, names
  731. }
  732. //sys mount(source string, target string, fstype string, flags uintptr, data *byte) (err error)
  733. func Mount(source string, target string, fstype string, flags uintptr, data string) (err error) {
  734. // Certain file systems get rather angry and EINVAL if you give
  735. // them an empty string of data, rather than NULL.
  736. if data == "" {
  737. return mount(source, target, fstype, flags, nil)
  738. }
  739. datap, err := BytePtrFromString(data)
  740. if err != nil {
  741. return err
  742. }
  743. return mount(source, target, fstype, flags, datap)
  744. }
  745. // Sendto
  746. // Recvfrom
  747. // Socketpair
  748. /*
  749. * Direct access
  750. */
  751. //sys Acct(path string) (err error)
  752. //sys Adjtimex(buf *Timex) (state int, err error)
  753. //sys Chdir(path string) (err error)
  754. //sys Chroot(path string) (err error)
  755. //sys ClockGettime(clockid int32, time *Timespec) (err error)
  756. //sys Close(fd int) (err error)
  757. //sys Dup(oldfd int) (fd int, err error)
  758. //sys Dup3(oldfd int, newfd int, flags int) (err error)
  759. //sysnb EpollCreate(size int) (fd int, err error)
  760. //sysnb EpollCreate1(flag int) (fd int, err error)
  761. //sysnb EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error)
  762. //sys Exit(code int) = SYS_EXIT_GROUP
  763. //sys Faccessat(dirfd int, path string, mode uint32, flags int) (err error)
  764. //sys Fallocate(fd int, mode uint32, off int64, len int64) (err error)
  765. //sys Fchdir(fd int) (err error)
  766. //sys Fchmod(fd int, mode uint32) (err error)
  767. //sys Fchmodat(dirfd int, path string, mode uint32, flags int) (err error)
  768. //sys Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error)
  769. //sys fcntl(fd int, cmd int, arg int) (val int, err error)
  770. //sys Fdatasync(fd int) (err error)
  771. //sys Flock(fd int, how int) (err error)
  772. //sys Fsync(fd int) (err error)
  773. //sys Getdents(fd int, buf []byte) (n int, err error) = SYS_GETDENTS64
  774. //sysnb Getpgid(pid int) (pgid int, err error)
  775. func Getpgrp() (pid int) {
  776. pid, _ = Getpgid(0)
  777. return
  778. }
  779. //sysnb Getpid() (pid int)
  780. //sysnb Getppid() (ppid int)
  781. //sys Getpriority(which int, who int) (prio int, err error)
  782. //sysnb Getrusage(who int, rusage *Rusage) (err error)
  783. //sysnb Gettid() (tid int)
  784. //sys Getxattr(path string, attr string, dest []byte) (sz int, err error)
  785. //sys InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error)
  786. //sysnb InotifyInit1(flags int) (fd int, err error)
  787. //sysnb InotifyRmWatch(fd int, watchdesc uint32) (success int, err error)
  788. //sysnb Kill(pid int, sig syscall.Signal) (err error)
  789. //sys Klogctl(typ int, buf []byte) (n int, err error) = SYS_SYSLOG
  790. //sys Listxattr(path string, dest []byte) (sz int, err error)
  791. //sys Mkdirat(dirfd int, path string, mode uint32) (err error)
  792. //sys Mknodat(dirfd int, path string, mode uint32, dev int) (err error)
  793. //sys Nanosleep(time *Timespec, leftover *Timespec) (err error)
  794. //sys PivotRoot(newroot string, putold string) (err error) = SYS_PIVOT_ROOT
  795. //sysnb prlimit(pid int, resource int, old *Rlimit, newlimit *Rlimit) (err error) = SYS_PRLIMIT64
  796. //sys Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error)
  797. //sys read(fd int, p []byte) (n int, err error)
  798. //sys Removexattr(path string, attr string) (err error)
  799. //sys Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error)
  800. //sys Setdomainname(p []byte) (err error)
  801. //sys Sethostname(p []byte) (err error)
  802. //sysnb Setpgid(pid int, pgid int) (err error)
  803. //sysnb Setsid() (pid int, err error)
  804. //sysnb Settimeofday(tv *Timeval) (err error)
  805. //sys Setns(fd int, nstype int) (err error)
  806. // issue 1435.
  807. // On linux Setuid and Setgid only affects the current thread, not the process.
  808. // This does not match what most callers expect so we must return an error
  809. // here rather than letting the caller think that the call succeeded.
  810. func Setuid(uid int) (err error) {
  811. return EOPNOTSUPP
  812. }
  813. func Setgid(uid int) (err error) {
  814. return EOPNOTSUPP
  815. }
  816. //sys Setpriority(which int, who int, prio int) (err error)
  817. //sys Setxattr(path string, attr string, data []byte, flags int) (err error)
  818. //sys Sync()
  819. //sysnb Sysinfo(info *Sysinfo_t) (err error)
  820. //sys Tee(rfd int, wfd int, len int, flags int) (n int64, err error)
  821. //sysnb Tgkill(tgid int, tid int, sig syscall.Signal) (err error)
  822. //sysnb Times(tms *Tms) (ticks uintptr, err error)
  823. //sysnb Umask(mask int) (oldmask int)
  824. //sysnb Uname(buf *Utsname) (err error)
  825. //sys Unmount(target string, flags int) (err error) = SYS_UMOUNT2
  826. //sys Unshare(flags int) (err error)
  827. //sys Ustat(dev int, ubuf *Ustat_t) (err error)
  828. //sys write(fd int, p []byte) (n int, err error)
  829. //sys exitThread(code int) (err error) = SYS_EXIT
  830. //sys readlen(fd int, p *byte, np int) (n int, err error) = SYS_READ
  831. //sys writelen(fd int, p *byte, np int) (n int, err error) = SYS_WRITE
  832. // mmap varies by architecture; see syscall_linux_*.go.
  833. //sys munmap(addr uintptr, length uintptr) (err error)
  834. var mapper = &mmapper{
  835. active: make(map[*byte][]byte),
  836. mmap: mmap,
  837. munmap: munmap,
  838. }
  839. func Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error) {
  840. return mapper.Mmap(fd, offset, length, prot, flags)
  841. }
  842. func Munmap(b []byte) (err error) {
  843. return mapper.Munmap(b)
  844. }
  845. //sys Madvise(b []byte, advice int) (err error)
  846. //sys Mprotect(b []byte, prot int) (err error)
  847. //sys Mlock(b []byte) (err error)
  848. //sys Munlock(b []byte) (err error)
  849. //sys Mlockall(flags int) (err error)
  850. //sys Munlockall() (err error)
  851. /*
  852. * Unimplemented
  853. */
  854. // AddKey
  855. // AfsSyscall
  856. // Alarm
  857. // ArchPrctl
  858. // Brk
  859. // Capget
  860. // Capset
  861. // ClockGetres
  862. // ClockNanosleep
  863. // ClockSettime
  864. // Clone
  865. // CreateModule
  866. // DeleteModule
  867. // EpollCtlOld
  868. // EpollPwait
  869. // EpollWaitOld
  870. // Eventfd
  871. // Execve
  872. // Fgetxattr
  873. // Flistxattr
  874. // Fork
  875. // Fremovexattr
  876. // Fsetxattr
  877. // Futex
  878. // GetKernelSyms
  879. // GetMempolicy
  880. // GetRobustList
  881. // GetThreadArea
  882. // Getitimer
  883. // Getpmsg
  884. // IoCancel
  885. // IoDestroy
  886. // IoGetevents
  887. // IoSetup
  888. // IoSubmit
  889. // Ioctl
  890. // IoprioGet
  891. // IoprioSet
  892. // KexecLoad
  893. // Keyctl
  894. // Lgetxattr
  895. // Llistxattr
  896. // LookupDcookie
  897. // Lremovexattr
  898. // Lsetxattr
  899. // Mbind
  900. // MigratePages
  901. // Mincore
  902. // ModifyLdt
  903. // Mount
  904. // MovePages
  905. // Mprotect
  906. // MqGetsetattr
  907. // MqNotify
  908. // MqOpen
  909. // MqTimedreceive
  910. // MqTimedsend
  911. // MqUnlink
  912. // Mremap
  913. // Msgctl
  914. // Msgget
  915. // Msgrcv
  916. // Msgsnd
  917. // Msync
  918. // Newfstatat
  919. // Nfsservctl
  920. // Personality
  921. // Pselect6
  922. // Ptrace
  923. // Putpmsg
  924. // QueryModule
  925. // Quotactl
  926. // Readahead
  927. // Readv
  928. // RemapFilePages
  929. // RequestKey
  930. // RestartSyscall
  931. // RtSigaction
  932. // RtSigpending
  933. // RtSigprocmask
  934. // RtSigqueueinfo
  935. // RtSigreturn
  936. // RtSigsuspend
  937. // RtSigtimedwait
  938. // SchedGetPriorityMax
  939. // SchedGetPriorityMin
  940. // SchedGetaffinity
  941. // SchedGetparam
  942. // SchedGetscheduler
  943. // SchedRrGetInterval
  944. // SchedSetaffinity
  945. // SchedSetparam
  946. // SchedYield
  947. // Security
  948. // Semctl
  949. // Semget
  950. // Semop
  951. // Semtimedop
  952. // SetMempolicy
  953. // SetRobustList
  954. // SetThreadArea
  955. // SetTidAddress
  956. // Shmat
  957. // Shmctl
  958. // Shmdt
  959. // Shmget
  960. // Sigaltstack
  961. // Signalfd
  962. // Swapoff
  963. // Swapon
  964. // Sysfs
  965. // TimerCreate
  966. // TimerDelete
  967. // TimerGetoverrun
  968. // TimerGettime
  969. // TimerSettime
  970. // Timerfd
  971. // Tkill (obsolete)
  972. // Tuxcall
  973. // Umount2
  974. // Uselib
  975. // Utimensat
  976. // Vfork
  977. // Vhangup
  978. // Vmsplice
  979. // Vserver
  980. // Waitid
  981. // _Sysctl