syscall_linux.go 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474
  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 fchmodat(dirfd int, path string, mode uint32) (err error)
  31. func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) {
  32. // Linux fchmodat doesn't support the flags parameter. Mimick glibc's behavior
  33. // and check the flags. Otherwise the mode would be applied to the symlink
  34. // destination which is not what the user expects.
  35. if flags&^AT_SYMLINK_NOFOLLOW != 0 {
  36. return EINVAL
  37. } else if flags&AT_SYMLINK_NOFOLLOW != 0 {
  38. return EOPNOTSUPP
  39. }
  40. return fchmodat(dirfd, path, mode)
  41. }
  42. //sys ioctl(fd int, req uint, arg uintptr) (err error)
  43. // ioctl itself should not be exposed directly, but additional get/set
  44. // functions for specific types are permissible.
  45. // IoctlSetInt performs an ioctl operation which sets an integer value
  46. // on fd, using the specified request number.
  47. func IoctlSetInt(fd int, req uint, value int) error {
  48. return ioctl(fd, req, uintptr(value))
  49. }
  50. func IoctlSetWinsize(fd int, req uint, value *Winsize) error {
  51. return ioctl(fd, req, uintptr(unsafe.Pointer(value)))
  52. }
  53. func IoctlSetTermios(fd int, req uint, value *Termios) error {
  54. return ioctl(fd, req, uintptr(unsafe.Pointer(value)))
  55. }
  56. // IoctlGetInt performs an ioctl operation which gets an integer value
  57. // from fd, using the specified request number.
  58. func IoctlGetInt(fd int, req uint) (int, error) {
  59. var value int
  60. err := ioctl(fd, req, uintptr(unsafe.Pointer(&value)))
  61. return value, err
  62. }
  63. func IoctlGetWinsize(fd int, req uint) (*Winsize, error) {
  64. var value Winsize
  65. err := ioctl(fd, req, uintptr(unsafe.Pointer(&value)))
  66. return &value, err
  67. }
  68. func IoctlGetTermios(fd int, req uint) (*Termios, error) {
  69. var value Termios
  70. err := ioctl(fd, req, uintptr(unsafe.Pointer(&value)))
  71. return &value, err
  72. }
  73. //sys Linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error)
  74. func Link(oldpath string, newpath string) (err error) {
  75. return Linkat(AT_FDCWD, oldpath, AT_FDCWD, newpath, 0)
  76. }
  77. func Mkdir(path string, mode uint32) (err error) {
  78. return Mkdirat(AT_FDCWD, path, mode)
  79. }
  80. func Mknod(path string, mode uint32, dev int) (err error) {
  81. return Mknodat(AT_FDCWD, path, mode, dev)
  82. }
  83. func Open(path string, mode int, perm uint32) (fd int, err error) {
  84. return openat(AT_FDCWD, path, mode|O_LARGEFILE, perm)
  85. }
  86. //sys openat(dirfd int, path string, flags int, mode uint32) (fd int, err error)
  87. func Openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) {
  88. return openat(dirfd, path, flags|O_LARGEFILE, mode)
  89. }
  90. //sys ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error)
  91. func Ppoll(fds []PollFd, timeout *Timespec, sigmask *Sigset_t) (n int, err error) {
  92. if len(fds) == 0 {
  93. return ppoll(nil, 0, timeout, sigmask)
  94. }
  95. return ppoll(&fds[0], len(fds), timeout, sigmask)
  96. }
  97. //sys Readlinkat(dirfd int, path string, buf []byte) (n int, err error)
  98. func Readlink(path string, buf []byte) (n int, err error) {
  99. return Readlinkat(AT_FDCWD, path, buf)
  100. }
  101. func Rename(oldpath string, newpath string) (err error) {
  102. return Renameat(AT_FDCWD, oldpath, AT_FDCWD, newpath)
  103. }
  104. func Rmdir(path string) error {
  105. return Unlinkat(AT_FDCWD, path, AT_REMOVEDIR)
  106. }
  107. //sys Symlinkat(oldpath string, newdirfd int, newpath string) (err error)
  108. func Symlink(oldpath string, newpath string) (err error) {
  109. return Symlinkat(oldpath, AT_FDCWD, newpath)
  110. }
  111. func Unlink(path string) error {
  112. return Unlinkat(AT_FDCWD, path, 0)
  113. }
  114. //sys Unlinkat(dirfd int, path string, flags int) (err error)
  115. func Utimes(path string, tv []Timeval) error {
  116. if tv == nil {
  117. err := utimensat(AT_FDCWD, path, nil, 0)
  118. if err != ENOSYS {
  119. return err
  120. }
  121. return utimes(path, nil)
  122. }
  123. if len(tv) != 2 {
  124. return EINVAL
  125. }
  126. var ts [2]Timespec
  127. ts[0] = NsecToTimespec(TimevalToNsec(tv[0]))
  128. ts[1] = NsecToTimespec(TimevalToNsec(tv[1]))
  129. err := utimensat(AT_FDCWD, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), 0)
  130. if err != ENOSYS {
  131. return err
  132. }
  133. return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
  134. }
  135. //sys utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error)
  136. func UtimesNano(path string, ts []Timespec) error {
  137. if ts == nil {
  138. err := utimensat(AT_FDCWD, path, nil, 0)
  139. if err != ENOSYS {
  140. return err
  141. }
  142. return utimes(path, nil)
  143. }
  144. if len(ts) != 2 {
  145. return EINVAL
  146. }
  147. err := utimensat(AT_FDCWD, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), 0)
  148. if err != ENOSYS {
  149. return err
  150. }
  151. // If the utimensat syscall isn't available (utimensat was added to Linux
  152. // in 2.6.22, Released, 8 July 2007) then fall back to utimes
  153. var tv [2]Timeval
  154. for i := 0; i < 2; i++ {
  155. tv[i] = NsecToTimeval(TimespecToNsec(ts[i]))
  156. }
  157. return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
  158. }
  159. func UtimesNanoAt(dirfd int, path string, ts []Timespec, flags int) error {
  160. if ts == nil {
  161. return utimensat(dirfd, path, nil, flags)
  162. }
  163. if len(ts) != 2 {
  164. return EINVAL
  165. }
  166. return utimensat(dirfd, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), flags)
  167. }
  168. func Futimesat(dirfd int, path string, tv []Timeval) error {
  169. if tv == nil {
  170. return futimesat(dirfd, path, nil)
  171. }
  172. if len(tv) != 2 {
  173. return EINVAL
  174. }
  175. return futimesat(dirfd, path, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
  176. }
  177. func Futimes(fd int, tv []Timeval) (err error) {
  178. // Believe it or not, this is the best we can do on Linux
  179. // (and is what glibc does).
  180. return Utimes("/proc/self/fd/"+itoa(fd), tv)
  181. }
  182. const ImplementsGetwd = true
  183. //sys Getcwd(buf []byte) (n int, err error)
  184. func Getwd() (wd string, err error) {
  185. var buf [PathMax]byte
  186. n, err := Getcwd(buf[0:])
  187. if err != nil {
  188. return "", err
  189. }
  190. // Getcwd returns the number of bytes written to buf, including the NUL.
  191. if n < 1 || n > len(buf) || buf[n-1] != 0 {
  192. return "", EINVAL
  193. }
  194. return string(buf[0 : n-1]), nil
  195. }
  196. func Getgroups() (gids []int, err error) {
  197. n, err := getgroups(0, nil)
  198. if err != nil {
  199. return nil, err
  200. }
  201. if n == 0 {
  202. return nil, nil
  203. }
  204. // Sanity check group count. Max is 1<<16 on Linux.
  205. if n < 0 || n > 1<<20 {
  206. return nil, EINVAL
  207. }
  208. a := make([]_Gid_t, n)
  209. n, err = getgroups(n, &a[0])
  210. if err != nil {
  211. return nil, err
  212. }
  213. gids = make([]int, n)
  214. for i, v := range a[0:n] {
  215. gids[i] = int(v)
  216. }
  217. return
  218. }
  219. func Setgroups(gids []int) (err error) {
  220. if len(gids) == 0 {
  221. return setgroups(0, nil)
  222. }
  223. a := make([]_Gid_t, len(gids))
  224. for i, v := range gids {
  225. a[i] = _Gid_t(v)
  226. }
  227. return setgroups(len(a), &a[0])
  228. }
  229. type WaitStatus uint32
  230. // Wait status is 7 bits at bottom, either 0 (exited),
  231. // 0x7F (stopped), or a signal number that caused an exit.
  232. // The 0x80 bit is whether there was a core dump.
  233. // An extra number (exit code, signal causing a stop)
  234. // is in the high bits. At least that's the idea.
  235. // There are various irregularities. For example, the
  236. // "continued" status is 0xFFFF, distinguishing itself
  237. // from stopped via the core dump bit.
  238. const (
  239. mask = 0x7F
  240. core = 0x80
  241. exited = 0x00
  242. stopped = 0x7F
  243. shift = 8
  244. )
  245. func (w WaitStatus) Exited() bool { return w&mask == exited }
  246. func (w WaitStatus) Signaled() bool { return w&mask != stopped && w&mask != exited }
  247. func (w WaitStatus) Stopped() bool { return w&0xFF == stopped }
  248. func (w WaitStatus) Continued() bool { return w == 0xFFFF }
  249. func (w WaitStatus) CoreDump() bool { return w.Signaled() && w&core != 0 }
  250. func (w WaitStatus) ExitStatus() int {
  251. if !w.Exited() {
  252. return -1
  253. }
  254. return int(w>>shift) & 0xFF
  255. }
  256. func (w WaitStatus) Signal() syscall.Signal {
  257. if !w.Signaled() {
  258. return -1
  259. }
  260. return syscall.Signal(w & mask)
  261. }
  262. func (w WaitStatus) StopSignal() syscall.Signal {
  263. if !w.Stopped() {
  264. return -1
  265. }
  266. return syscall.Signal(w>>shift) & 0xFF
  267. }
  268. func (w WaitStatus) TrapCause() int {
  269. if w.StopSignal() != SIGTRAP {
  270. return -1
  271. }
  272. return int(w>>shift) >> 8
  273. }
  274. //sys wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error)
  275. func Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, err error) {
  276. var status _C_int
  277. wpid, err = wait4(pid, &status, options, rusage)
  278. if wstatus != nil {
  279. *wstatus = WaitStatus(status)
  280. }
  281. return
  282. }
  283. func Mkfifo(path string, mode uint32) error {
  284. return Mknod(path, mode|S_IFIFO, 0)
  285. }
  286. func Mkfifoat(dirfd int, path string, mode uint32) error {
  287. return Mknodat(dirfd, path, mode|S_IFIFO, 0)
  288. }
  289. func (sa *SockaddrInet4) sockaddr() (unsafe.Pointer, _Socklen, error) {
  290. if sa.Port < 0 || sa.Port > 0xFFFF {
  291. return nil, 0, EINVAL
  292. }
  293. sa.raw.Family = AF_INET
  294. p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port))
  295. p[0] = byte(sa.Port >> 8)
  296. p[1] = byte(sa.Port)
  297. for i := 0; i < len(sa.Addr); i++ {
  298. sa.raw.Addr[i] = sa.Addr[i]
  299. }
  300. return unsafe.Pointer(&sa.raw), SizeofSockaddrInet4, nil
  301. }
  302. func (sa *SockaddrInet6) sockaddr() (unsafe.Pointer, _Socklen, error) {
  303. if sa.Port < 0 || sa.Port > 0xFFFF {
  304. return nil, 0, EINVAL
  305. }
  306. sa.raw.Family = AF_INET6
  307. p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port))
  308. p[0] = byte(sa.Port >> 8)
  309. p[1] = byte(sa.Port)
  310. sa.raw.Scope_id = sa.ZoneId
  311. for i := 0; i < len(sa.Addr); i++ {
  312. sa.raw.Addr[i] = sa.Addr[i]
  313. }
  314. return unsafe.Pointer(&sa.raw), SizeofSockaddrInet6, nil
  315. }
  316. func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, _Socklen, error) {
  317. name := sa.Name
  318. n := len(name)
  319. if n >= len(sa.raw.Path) {
  320. return nil, 0, EINVAL
  321. }
  322. sa.raw.Family = AF_UNIX
  323. for i := 0; i < n; i++ {
  324. sa.raw.Path[i] = int8(name[i])
  325. }
  326. // length is family (uint16), name, NUL.
  327. sl := _Socklen(2)
  328. if n > 0 {
  329. sl += _Socklen(n) + 1
  330. }
  331. if sa.raw.Path[0] == '@' {
  332. sa.raw.Path[0] = 0
  333. // Don't count trailing NUL for abstract address.
  334. sl--
  335. }
  336. return unsafe.Pointer(&sa.raw), sl, nil
  337. }
  338. // SockaddrLinklayer implements the Sockaddr interface for AF_PACKET type sockets.
  339. type SockaddrLinklayer struct {
  340. Protocol uint16
  341. Ifindex int
  342. Hatype uint16
  343. Pkttype uint8
  344. Halen uint8
  345. Addr [8]byte
  346. raw RawSockaddrLinklayer
  347. }
  348. func (sa *SockaddrLinklayer) sockaddr() (unsafe.Pointer, _Socklen, error) {
  349. if sa.Ifindex < 0 || sa.Ifindex > 0x7fffffff {
  350. return nil, 0, EINVAL
  351. }
  352. sa.raw.Family = AF_PACKET
  353. sa.raw.Protocol = sa.Protocol
  354. sa.raw.Ifindex = int32(sa.Ifindex)
  355. sa.raw.Hatype = sa.Hatype
  356. sa.raw.Pkttype = sa.Pkttype
  357. sa.raw.Halen = sa.Halen
  358. for i := 0; i < len(sa.Addr); i++ {
  359. sa.raw.Addr[i] = sa.Addr[i]
  360. }
  361. return unsafe.Pointer(&sa.raw), SizeofSockaddrLinklayer, nil
  362. }
  363. // SockaddrNetlink implements the Sockaddr interface for AF_NETLINK type sockets.
  364. type SockaddrNetlink struct {
  365. Family uint16
  366. Pad uint16
  367. Pid uint32
  368. Groups uint32
  369. raw RawSockaddrNetlink
  370. }
  371. func (sa *SockaddrNetlink) sockaddr() (unsafe.Pointer, _Socklen, error) {
  372. sa.raw.Family = AF_NETLINK
  373. sa.raw.Pad = sa.Pad
  374. sa.raw.Pid = sa.Pid
  375. sa.raw.Groups = sa.Groups
  376. return unsafe.Pointer(&sa.raw), SizeofSockaddrNetlink, nil
  377. }
  378. // SockaddrHCI implements the Sockaddr interface for AF_BLUETOOTH type sockets
  379. // using the HCI protocol.
  380. type SockaddrHCI struct {
  381. Dev uint16
  382. Channel uint16
  383. raw RawSockaddrHCI
  384. }
  385. func (sa *SockaddrHCI) sockaddr() (unsafe.Pointer, _Socklen, error) {
  386. sa.raw.Family = AF_BLUETOOTH
  387. sa.raw.Dev = sa.Dev
  388. sa.raw.Channel = sa.Channel
  389. return unsafe.Pointer(&sa.raw), SizeofSockaddrHCI, nil
  390. }
  391. // SockaddrL2 implements the Sockaddr interface for AF_BLUETOOTH type sockets
  392. // using the L2CAP protocol.
  393. type SockaddrL2 struct {
  394. PSM uint16
  395. CID uint16
  396. Addr [6]uint8
  397. AddrType uint8
  398. raw RawSockaddrL2
  399. }
  400. func (sa *SockaddrL2) sockaddr() (unsafe.Pointer, _Socklen, error) {
  401. sa.raw.Family = AF_BLUETOOTH
  402. psm := (*[2]byte)(unsafe.Pointer(&sa.raw.Psm))
  403. psm[0] = byte(sa.PSM)
  404. psm[1] = byte(sa.PSM >> 8)
  405. for i := 0; i < len(sa.Addr); i++ {
  406. sa.raw.Bdaddr[i] = sa.Addr[len(sa.Addr)-1-i]
  407. }
  408. cid := (*[2]byte)(unsafe.Pointer(&sa.raw.Cid))
  409. cid[0] = byte(sa.CID)
  410. cid[1] = byte(sa.CID >> 8)
  411. sa.raw.Bdaddr_type = sa.AddrType
  412. return unsafe.Pointer(&sa.raw), SizeofSockaddrL2, nil
  413. }
  414. // SockaddrCAN implements the Sockaddr interface for AF_CAN type sockets.
  415. // The RxID and TxID fields are used for transport protocol addressing in
  416. // (CAN_TP16, CAN_TP20, CAN_MCNET, and CAN_ISOTP), they can be left with
  417. // zero values for CAN_RAW and CAN_BCM sockets as they have no meaning.
  418. //
  419. // The SockaddrCAN struct must be bound to the socket file descriptor
  420. // using Bind before the CAN socket can be used.
  421. //
  422. // // Read one raw CAN frame
  423. // fd, _ := Socket(AF_CAN, SOCK_RAW, CAN_RAW)
  424. // addr := &SockaddrCAN{Ifindex: index}
  425. // Bind(fd, addr)
  426. // frame := make([]byte, 16)
  427. // Read(fd, frame)
  428. //
  429. // The full SocketCAN documentation can be found in the linux kernel
  430. // archives at: https://www.kernel.org/doc/Documentation/networking/can.txt
  431. type SockaddrCAN struct {
  432. Ifindex int
  433. RxID uint32
  434. TxID uint32
  435. raw RawSockaddrCAN
  436. }
  437. func (sa *SockaddrCAN) sockaddr() (unsafe.Pointer, _Socklen, error) {
  438. if sa.Ifindex < 0 || sa.Ifindex > 0x7fffffff {
  439. return nil, 0, EINVAL
  440. }
  441. sa.raw.Family = AF_CAN
  442. sa.raw.Ifindex = int32(sa.Ifindex)
  443. rx := (*[4]byte)(unsafe.Pointer(&sa.RxID))
  444. for i := 0; i < 4; i++ {
  445. sa.raw.Addr[i] = rx[i]
  446. }
  447. tx := (*[4]byte)(unsafe.Pointer(&sa.TxID))
  448. for i := 0; i < 4; i++ {
  449. sa.raw.Addr[i+4] = tx[i]
  450. }
  451. return unsafe.Pointer(&sa.raw), SizeofSockaddrCAN, nil
  452. }
  453. // SockaddrALG implements the Sockaddr interface for AF_ALG type sockets.
  454. // SockaddrALG enables userspace access to the Linux kernel's cryptography
  455. // subsystem. The Type and Name fields specify which type of hash or cipher
  456. // should be used with a given socket.
  457. //
  458. // To create a file descriptor that provides access to a hash or cipher, both
  459. // Bind and Accept must be used. Once the setup process is complete, input
  460. // data can be written to the socket, processed by the kernel, and then read
  461. // back as hash output or ciphertext.
  462. //
  463. // Here is an example of using an AF_ALG socket with SHA1 hashing.
  464. // The initial socket setup process is as follows:
  465. //
  466. // // Open a socket to perform SHA1 hashing.
  467. // fd, _ := unix.Socket(unix.AF_ALG, unix.SOCK_SEQPACKET, 0)
  468. // addr := &unix.SockaddrALG{Type: "hash", Name: "sha1"}
  469. // unix.Bind(fd, addr)
  470. // // Note: unix.Accept does not work at this time; must invoke accept()
  471. // // manually using unix.Syscall.
  472. // hashfd, _, _ := unix.Syscall(unix.SYS_ACCEPT, uintptr(fd), 0, 0)
  473. //
  474. // Once a file descriptor has been returned from Accept, it may be used to
  475. // perform SHA1 hashing. The descriptor is not safe for concurrent use, but
  476. // may be re-used repeatedly with subsequent Write and Read operations.
  477. //
  478. // When hashing a small byte slice or string, a single Write and Read may
  479. // be used:
  480. //
  481. // // Assume hashfd is already configured using the setup process.
  482. // hash := os.NewFile(hashfd, "sha1")
  483. // // Hash an input string and read the results. Each Write discards
  484. // // previous hash state. Read always reads the current state.
  485. // b := make([]byte, 20)
  486. // for i := 0; i < 2; i++ {
  487. // io.WriteString(hash, "Hello, world.")
  488. // hash.Read(b)
  489. // fmt.Println(hex.EncodeToString(b))
  490. // }
  491. // // Output:
  492. // // 2ae01472317d1935a84797ec1983ae243fc6aa28
  493. // // 2ae01472317d1935a84797ec1983ae243fc6aa28
  494. //
  495. // For hashing larger byte slices, or byte streams such as those read from
  496. // a file or socket, use Sendto with MSG_MORE to instruct the kernel to update
  497. // the hash digest instead of creating a new one for a given chunk and finalizing it.
  498. //
  499. // // Assume hashfd and addr are already configured using the setup process.
  500. // hash := os.NewFile(hashfd, "sha1")
  501. // // Hash the contents of a file.
  502. // f, _ := os.Open("/tmp/linux-4.10-rc7.tar.xz")
  503. // b := make([]byte, 4096)
  504. // for {
  505. // n, err := f.Read(b)
  506. // if err == io.EOF {
  507. // break
  508. // }
  509. // unix.Sendto(hashfd, b[:n], unix.MSG_MORE, addr)
  510. // }
  511. // hash.Read(b)
  512. // fmt.Println(hex.EncodeToString(b))
  513. // // Output: 85cdcad0c06eef66f805ecce353bec9accbeecc5
  514. //
  515. // For more information, see: http://www.chronox.de/crypto-API/crypto/userspace-if.html.
  516. type SockaddrALG struct {
  517. Type string
  518. Name string
  519. Feature uint32
  520. Mask uint32
  521. raw RawSockaddrALG
  522. }
  523. func (sa *SockaddrALG) sockaddr() (unsafe.Pointer, _Socklen, error) {
  524. // Leave room for NUL byte terminator.
  525. if len(sa.Type) > 13 {
  526. return nil, 0, EINVAL
  527. }
  528. if len(sa.Name) > 63 {
  529. return nil, 0, EINVAL
  530. }
  531. sa.raw.Family = AF_ALG
  532. sa.raw.Feat = sa.Feature
  533. sa.raw.Mask = sa.Mask
  534. typ, err := ByteSliceFromString(sa.Type)
  535. if err != nil {
  536. return nil, 0, err
  537. }
  538. name, err := ByteSliceFromString(sa.Name)
  539. if err != nil {
  540. return nil, 0, err
  541. }
  542. copy(sa.raw.Type[:], typ)
  543. copy(sa.raw.Name[:], name)
  544. return unsafe.Pointer(&sa.raw), SizeofSockaddrALG, nil
  545. }
  546. // SockaddrVM implements the Sockaddr interface for AF_VSOCK type sockets.
  547. // SockaddrVM provides access to Linux VM sockets: a mechanism that enables
  548. // bidirectional communication between a hypervisor and its guest virtual
  549. // machines.
  550. type SockaddrVM struct {
  551. // CID and Port specify a context ID and port address for a VM socket.
  552. // Guests have a unique CID, and hosts may have a well-known CID of:
  553. // - VMADDR_CID_HYPERVISOR: refers to the hypervisor process.
  554. // - VMADDR_CID_HOST: refers to other processes on the host.
  555. CID uint32
  556. Port uint32
  557. raw RawSockaddrVM
  558. }
  559. func (sa *SockaddrVM) sockaddr() (unsafe.Pointer, _Socklen, error) {
  560. sa.raw.Family = AF_VSOCK
  561. sa.raw.Port = sa.Port
  562. sa.raw.Cid = sa.CID
  563. return unsafe.Pointer(&sa.raw), SizeofSockaddrVM, nil
  564. }
  565. func anyToSockaddr(rsa *RawSockaddrAny) (Sockaddr, error) {
  566. switch rsa.Addr.Family {
  567. case AF_NETLINK:
  568. pp := (*RawSockaddrNetlink)(unsafe.Pointer(rsa))
  569. sa := new(SockaddrNetlink)
  570. sa.Family = pp.Family
  571. sa.Pad = pp.Pad
  572. sa.Pid = pp.Pid
  573. sa.Groups = pp.Groups
  574. return sa, nil
  575. case AF_PACKET:
  576. pp := (*RawSockaddrLinklayer)(unsafe.Pointer(rsa))
  577. sa := new(SockaddrLinklayer)
  578. sa.Protocol = pp.Protocol
  579. sa.Ifindex = int(pp.Ifindex)
  580. sa.Hatype = pp.Hatype
  581. sa.Pkttype = pp.Pkttype
  582. sa.Halen = pp.Halen
  583. for i := 0; i < len(sa.Addr); i++ {
  584. sa.Addr[i] = pp.Addr[i]
  585. }
  586. return sa, nil
  587. case AF_UNIX:
  588. pp := (*RawSockaddrUnix)(unsafe.Pointer(rsa))
  589. sa := new(SockaddrUnix)
  590. if pp.Path[0] == 0 {
  591. // "Abstract" Unix domain socket.
  592. // Rewrite leading NUL as @ for textual display.
  593. // (This is the standard convention.)
  594. // Not friendly to overwrite in place,
  595. // but the callers below don't care.
  596. pp.Path[0] = '@'
  597. }
  598. // Assume path ends at NUL.
  599. // This is not technically the Linux semantics for
  600. // abstract Unix domain sockets--they are supposed
  601. // to be uninterpreted fixed-size binary blobs--but
  602. // everyone uses this convention.
  603. n := 0
  604. for n < len(pp.Path) && pp.Path[n] != 0 {
  605. n++
  606. }
  607. bytes := (*[10000]byte)(unsafe.Pointer(&pp.Path[0]))[0:n]
  608. sa.Name = string(bytes)
  609. return sa, nil
  610. case AF_INET:
  611. pp := (*RawSockaddrInet4)(unsafe.Pointer(rsa))
  612. sa := new(SockaddrInet4)
  613. p := (*[2]byte)(unsafe.Pointer(&pp.Port))
  614. sa.Port = int(p[0])<<8 + int(p[1])
  615. for i := 0; i < len(sa.Addr); i++ {
  616. sa.Addr[i] = pp.Addr[i]
  617. }
  618. return sa, nil
  619. case AF_INET6:
  620. pp := (*RawSockaddrInet6)(unsafe.Pointer(rsa))
  621. sa := new(SockaddrInet6)
  622. p := (*[2]byte)(unsafe.Pointer(&pp.Port))
  623. sa.Port = int(p[0])<<8 + int(p[1])
  624. sa.ZoneId = pp.Scope_id
  625. for i := 0; i < len(sa.Addr); i++ {
  626. sa.Addr[i] = pp.Addr[i]
  627. }
  628. return sa, nil
  629. case AF_VSOCK:
  630. pp := (*RawSockaddrVM)(unsafe.Pointer(rsa))
  631. sa := &SockaddrVM{
  632. CID: pp.Cid,
  633. Port: pp.Port,
  634. }
  635. return sa, nil
  636. }
  637. return nil, EAFNOSUPPORT
  638. }
  639. func Accept(fd int) (nfd int, sa Sockaddr, err error) {
  640. var rsa RawSockaddrAny
  641. var len _Socklen = SizeofSockaddrAny
  642. nfd, err = accept(fd, &rsa, &len)
  643. if err != nil {
  644. return
  645. }
  646. sa, err = anyToSockaddr(&rsa)
  647. if err != nil {
  648. Close(nfd)
  649. nfd = 0
  650. }
  651. return
  652. }
  653. func Accept4(fd int, flags int) (nfd int, sa Sockaddr, err error) {
  654. var rsa RawSockaddrAny
  655. var len _Socklen = SizeofSockaddrAny
  656. nfd, err = accept4(fd, &rsa, &len, flags)
  657. if err != nil {
  658. return
  659. }
  660. if len > SizeofSockaddrAny {
  661. panic("RawSockaddrAny too small")
  662. }
  663. sa, err = anyToSockaddr(&rsa)
  664. if err != nil {
  665. Close(nfd)
  666. nfd = 0
  667. }
  668. return
  669. }
  670. func Getsockname(fd int) (sa Sockaddr, err error) {
  671. var rsa RawSockaddrAny
  672. var len _Socklen = SizeofSockaddrAny
  673. if err = getsockname(fd, &rsa, &len); err != nil {
  674. return
  675. }
  676. return anyToSockaddr(&rsa)
  677. }
  678. func GetsockoptIPMreqn(fd, level, opt int) (*IPMreqn, error) {
  679. var value IPMreqn
  680. vallen := _Socklen(SizeofIPMreqn)
  681. err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
  682. return &value, err
  683. }
  684. func GetsockoptUcred(fd, level, opt int) (*Ucred, error) {
  685. var value Ucred
  686. vallen := _Socklen(SizeofUcred)
  687. err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
  688. return &value, err
  689. }
  690. func GetsockoptTCPInfo(fd, level, opt int) (*TCPInfo, error) {
  691. var value TCPInfo
  692. vallen := _Socklen(SizeofTCPInfo)
  693. err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
  694. return &value, err
  695. }
  696. // GetsockoptString returns the string value of the socket option opt for the
  697. // socket associated with fd at the given socket level.
  698. func GetsockoptString(fd, level, opt int) (string, error) {
  699. buf := make([]byte, 256)
  700. vallen := _Socklen(len(buf))
  701. err := getsockopt(fd, level, opt, unsafe.Pointer(&buf[0]), &vallen)
  702. if err != nil {
  703. if err == ERANGE {
  704. buf = make([]byte, vallen)
  705. err = getsockopt(fd, level, opt, unsafe.Pointer(&buf[0]), &vallen)
  706. }
  707. if err != nil {
  708. return "", err
  709. }
  710. }
  711. return string(buf[:vallen-1]), nil
  712. }
  713. func SetsockoptIPMreqn(fd, level, opt int, mreq *IPMreqn) (err error) {
  714. return setsockopt(fd, level, opt, unsafe.Pointer(mreq), unsafe.Sizeof(*mreq))
  715. }
  716. // Keyctl Commands (http://man7.org/linux/man-pages/man2/keyctl.2.html)
  717. // KeyctlInt calls keyctl commands in which each argument is an int.
  718. // These commands are KEYCTL_REVOKE, KEYCTL_CHOWN, KEYCTL_CLEAR, KEYCTL_LINK,
  719. // KEYCTL_UNLINK, KEYCTL_NEGATE, KEYCTL_SET_REQKEY_KEYRING, KEYCTL_SET_TIMEOUT,
  720. // KEYCTL_ASSUME_AUTHORITY, KEYCTL_SESSION_TO_PARENT, KEYCTL_REJECT,
  721. // KEYCTL_INVALIDATE, and KEYCTL_GET_PERSISTENT.
  722. //sys KeyctlInt(cmd int, arg2 int, arg3 int, arg4 int, arg5 int) (ret int, err error) = SYS_KEYCTL
  723. // KeyctlBuffer calls keyctl commands in which the third and fourth
  724. // arguments are a buffer and its length, respectively.
  725. // These commands are KEYCTL_UPDATE, KEYCTL_READ, and KEYCTL_INSTANTIATE.
  726. //sys KeyctlBuffer(cmd int, arg2 int, buf []byte, arg5 int) (ret int, err error) = SYS_KEYCTL
  727. // KeyctlString calls keyctl commands which return a string.
  728. // These commands are KEYCTL_DESCRIBE and KEYCTL_GET_SECURITY.
  729. func KeyctlString(cmd int, id int) (string, error) {
  730. // We must loop as the string data may change in between the syscalls.
  731. // We could allocate a large buffer here to reduce the chance that the
  732. // syscall needs to be called twice; however, this is unnecessary as
  733. // the performance loss is negligible.
  734. var buffer []byte
  735. for {
  736. // Try to fill the buffer with data
  737. length, err := KeyctlBuffer(cmd, id, buffer, 0)
  738. if err != nil {
  739. return "", err
  740. }
  741. // Check if the data was written
  742. if length <= len(buffer) {
  743. // Exclude the null terminator
  744. return string(buffer[:length-1]), nil
  745. }
  746. // Make a bigger buffer if needed
  747. buffer = make([]byte, length)
  748. }
  749. }
  750. // Keyctl commands with special signatures.
  751. // KeyctlGetKeyringID implements the KEYCTL_GET_KEYRING_ID command.
  752. // See the full documentation at:
  753. // http://man7.org/linux/man-pages/man3/keyctl_get_keyring_ID.3.html
  754. func KeyctlGetKeyringID(id int, create bool) (ringid int, err error) {
  755. createInt := 0
  756. if create {
  757. createInt = 1
  758. }
  759. return KeyctlInt(KEYCTL_GET_KEYRING_ID, id, createInt, 0, 0)
  760. }
  761. // KeyctlSetperm implements the KEYCTL_SETPERM command. The perm value is the
  762. // key handle permission mask as described in the "keyctl setperm" section of
  763. // http://man7.org/linux/man-pages/man1/keyctl.1.html.
  764. // See the full documentation at:
  765. // http://man7.org/linux/man-pages/man3/keyctl_setperm.3.html
  766. func KeyctlSetperm(id int, perm uint32) error {
  767. _, err := KeyctlInt(KEYCTL_SETPERM, id, int(perm), 0, 0)
  768. return err
  769. }
  770. //sys keyctlJoin(cmd int, arg2 string) (ret int, err error) = SYS_KEYCTL
  771. // KeyctlJoinSessionKeyring implements the KEYCTL_JOIN_SESSION_KEYRING command.
  772. // See the full documentation at:
  773. // http://man7.org/linux/man-pages/man3/keyctl_join_session_keyring.3.html
  774. func KeyctlJoinSessionKeyring(name string) (ringid int, err error) {
  775. return keyctlJoin(KEYCTL_JOIN_SESSION_KEYRING, name)
  776. }
  777. //sys keyctlSearch(cmd int, arg2 int, arg3 string, arg4 string, arg5 int) (ret int, err error) = SYS_KEYCTL
  778. // KeyctlSearch implements the KEYCTL_SEARCH command.
  779. // See the full documentation at:
  780. // http://man7.org/linux/man-pages/man3/keyctl_search.3.html
  781. func KeyctlSearch(ringid int, keyType, description string, destRingid int) (id int, err error) {
  782. return keyctlSearch(KEYCTL_SEARCH, ringid, keyType, description, destRingid)
  783. }
  784. //sys keyctlIOV(cmd int, arg2 int, payload []Iovec, arg5 int) (err error) = SYS_KEYCTL
  785. // KeyctlInstantiateIOV implements the KEYCTL_INSTANTIATE_IOV command. This
  786. // command is similar to KEYCTL_INSTANTIATE, except that the payload is a slice
  787. // of Iovec (each of which represents a buffer) instead of a single buffer.
  788. // See the full documentation at:
  789. // http://man7.org/linux/man-pages/man3/keyctl_instantiate_iov.3.html
  790. func KeyctlInstantiateIOV(id int, payload []Iovec, ringid int) error {
  791. return keyctlIOV(KEYCTL_INSTANTIATE_IOV, id, payload, ringid)
  792. }
  793. //sys keyctlDH(cmd int, arg2 *KeyctlDHParams, buf []byte) (ret int, err error) = SYS_KEYCTL
  794. // KeyctlDHCompute implements the KEYCTL_DH_COMPUTE command. This command
  795. // computes a Diffie-Hellman shared secret based on the provide params. The
  796. // secret is written to the provided buffer and the returned size is the number
  797. // of bytes written (returning an error if there is insufficient space in the
  798. // buffer). If a nil buffer is passed in, this function returns the minimum
  799. // buffer length needed to store the appropriate data. Note that this differs
  800. // from KEYCTL_READ's behavior which always returns the requested payload size.
  801. // See the full documentation at:
  802. // http://man7.org/linux/man-pages/man3/keyctl_dh_compute.3.html
  803. func KeyctlDHCompute(params *KeyctlDHParams, buffer []byte) (size int, err error) {
  804. return keyctlDH(KEYCTL_DH_COMPUTE, params, buffer)
  805. }
  806. func Recvmsg(fd int, p, oob []byte, flags int) (n, oobn int, recvflags int, from Sockaddr, err error) {
  807. var msg Msghdr
  808. var rsa RawSockaddrAny
  809. msg.Name = (*byte)(unsafe.Pointer(&rsa))
  810. msg.Namelen = uint32(SizeofSockaddrAny)
  811. var iov Iovec
  812. if len(p) > 0 {
  813. iov.Base = &p[0]
  814. iov.SetLen(len(p))
  815. }
  816. var dummy byte
  817. if len(oob) > 0 {
  818. if len(p) == 0 {
  819. var sockType int
  820. sockType, err = GetsockoptInt(fd, SOL_SOCKET, SO_TYPE)
  821. if err != nil {
  822. return
  823. }
  824. // receive at least one normal byte
  825. if sockType != SOCK_DGRAM {
  826. iov.Base = &dummy
  827. iov.SetLen(1)
  828. }
  829. }
  830. msg.Control = &oob[0]
  831. msg.SetControllen(len(oob))
  832. }
  833. msg.Iov = &iov
  834. msg.Iovlen = 1
  835. if n, err = recvmsg(fd, &msg, flags); err != nil {
  836. return
  837. }
  838. oobn = int(msg.Controllen)
  839. recvflags = int(msg.Flags)
  840. // source address is only specified if the socket is unconnected
  841. if rsa.Addr.Family != AF_UNSPEC {
  842. from, err = anyToSockaddr(&rsa)
  843. }
  844. return
  845. }
  846. func Sendmsg(fd int, p, oob []byte, to Sockaddr, flags int) (err error) {
  847. _, err = SendmsgN(fd, p, oob, to, flags)
  848. return
  849. }
  850. func SendmsgN(fd int, p, oob []byte, to Sockaddr, flags int) (n int, err error) {
  851. var ptr unsafe.Pointer
  852. var salen _Socklen
  853. if to != nil {
  854. var err error
  855. ptr, salen, err = to.sockaddr()
  856. if err != nil {
  857. return 0, err
  858. }
  859. }
  860. var msg Msghdr
  861. msg.Name = (*byte)(ptr)
  862. msg.Namelen = uint32(salen)
  863. var iov Iovec
  864. if len(p) > 0 {
  865. iov.Base = &p[0]
  866. iov.SetLen(len(p))
  867. }
  868. var dummy byte
  869. if len(oob) > 0 {
  870. if len(p) == 0 {
  871. var sockType int
  872. sockType, err = GetsockoptInt(fd, SOL_SOCKET, SO_TYPE)
  873. if err != nil {
  874. return 0, err
  875. }
  876. // send at least one normal byte
  877. if sockType != SOCK_DGRAM {
  878. iov.Base = &dummy
  879. iov.SetLen(1)
  880. }
  881. }
  882. msg.Control = &oob[0]
  883. msg.SetControllen(len(oob))
  884. }
  885. msg.Iov = &iov
  886. msg.Iovlen = 1
  887. if n, err = sendmsg(fd, &msg, flags); err != nil {
  888. return 0, err
  889. }
  890. if len(oob) > 0 && len(p) == 0 {
  891. n = 0
  892. }
  893. return n, nil
  894. }
  895. // BindToDevice binds the socket associated with fd to device.
  896. func BindToDevice(fd int, device string) (err error) {
  897. return SetsockoptString(fd, SOL_SOCKET, SO_BINDTODEVICE, device)
  898. }
  899. //sys ptrace(request int, pid int, addr uintptr, data uintptr) (err error)
  900. func ptracePeek(req int, pid int, addr uintptr, out []byte) (count int, err error) {
  901. // The peek requests are machine-size oriented, so we wrap it
  902. // to retrieve arbitrary-length data.
  903. // The ptrace syscall differs from glibc's ptrace.
  904. // Peeks returns the word in *data, not as the return value.
  905. var buf [sizeofPtr]byte
  906. // Leading edge. PEEKTEXT/PEEKDATA don't require aligned
  907. // access (PEEKUSER warns that it might), but if we don't
  908. // align our reads, we might straddle an unmapped page
  909. // boundary and not get the bytes leading up to the page
  910. // boundary.
  911. n := 0
  912. if addr%sizeofPtr != 0 {
  913. err = ptrace(req, pid, addr-addr%sizeofPtr, uintptr(unsafe.Pointer(&buf[0])))
  914. if err != nil {
  915. return 0, err
  916. }
  917. n += copy(out, buf[addr%sizeofPtr:])
  918. out = out[n:]
  919. }
  920. // Remainder.
  921. for len(out) > 0 {
  922. // We use an internal buffer to guarantee alignment.
  923. // It's not documented if this is necessary, but we're paranoid.
  924. err = ptrace(req, pid, addr+uintptr(n), uintptr(unsafe.Pointer(&buf[0])))
  925. if err != nil {
  926. return n, err
  927. }
  928. copied := copy(out, buf[0:])
  929. n += copied
  930. out = out[copied:]
  931. }
  932. return n, nil
  933. }
  934. func PtracePeekText(pid int, addr uintptr, out []byte) (count int, err error) {
  935. return ptracePeek(PTRACE_PEEKTEXT, pid, addr, out)
  936. }
  937. func PtracePeekData(pid int, addr uintptr, out []byte) (count int, err error) {
  938. return ptracePeek(PTRACE_PEEKDATA, pid, addr, out)
  939. }
  940. func PtracePeekUser(pid int, addr uintptr, out []byte) (count int, err error) {
  941. return ptracePeek(PTRACE_PEEKUSR, pid, addr, out)
  942. }
  943. func ptracePoke(pokeReq int, peekReq int, pid int, addr uintptr, data []byte) (count int, err error) {
  944. // As for ptracePeek, we need to align our accesses to deal
  945. // with the possibility of straddling an invalid page.
  946. // Leading edge.
  947. n := 0
  948. if addr%sizeofPtr != 0 {
  949. var buf [sizeofPtr]byte
  950. err = ptrace(peekReq, pid, addr-addr%sizeofPtr, uintptr(unsafe.Pointer(&buf[0])))
  951. if err != nil {
  952. return 0, err
  953. }
  954. n += copy(buf[addr%sizeofPtr:], data)
  955. word := *((*uintptr)(unsafe.Pointer(&buf[0])))
  956. err = ptrace(pokeReq, pid, addr-addr%sizeofPtr, word)
  957. if err != nil {
  958. return 0, err
  959. }
  960. data = data[n:]
  961. }
  962. // Interior.
  963. for len(data) > sizeofPtr {
  964. word := *((*uintptr)(unsafe.Pointer(&data[0])))
  965. err = ptrace(pokeReq, pid, addr+uintptr(n), word)
  966. if err != nil {
  967. return n, err
  968. }
  969. n += sizeofPtr
  970. data = data[sizeofPtr:]
  971. }
  972. // Trailing edge.
  973. if len(data) > 0 {
  974. var buf [sizeofPtr]byte
  975. err = ptrace(peekReq, pid, addr+uintptr(n), uintptr(unsafe.Pointer(&buf[0])))
  976. if err != nil {
  977. return n, err
  978. }
  979. copy(buf[0:], data)
  980. word := *((*uintptr)(unsafe.Pointer(&buf[0])))
  981. err = ptrace(pokeReq, pid, addr+uintptr(n), word)
  982. if err != nil {
  983. return n, err
  984. }
  985. n += len(data)
  986. }
  987. return n, nil
  988. }
  989. func PtracePokeText(pid int, addr uintptr, data []byte) (count int, err error) {
  990. return ptracePoke(PTRACE_POKETEXT, PTRACE_PEEKTEXT, pid, addr, data)
  991. }
  992. func PtracePokeData(pid int, addr uintptr, data []byte) (count int, err error) {
  993. return ptracePoke(PTRACE_POKEDATA, PTRACE_PEEKDATA, pid, addr, data)
  994. }
  995. func PtracePokeUser(pid int, addr uintptr, data []byte) (count int, err error) {
  996. return ptracePoke(PTRACE_POKEUSR, PTRACE_PEEKUSR, pid, addr, data)
  997. }
  998. func PtraceGetRegs(pid int, regsout *PtraceRegs) (err error) {
  999. return ptrace(PTRACE_GETREGS, pid, 0, uintptr(unsafe.Pointer(regsout)))
  1000. }
  1001. func PtraceSetRegs(pid int, regs *PtraceRegs) (err error) {
  1002. return ptrace(PTRACE_SETREGS, pid, 0, uintptr(unsafe.Pointer(regs)))
  1003. }
  1004. func PtraceSetOptions(pid int, options int) (err error) {
  1005. return ptrace(PTRACE_SETOPTIONS, pid, 0, uintptr(options))
  1006. }
  1007. func PtraceGetEventMsg(pid int) (msg uint, err error) {
  1008. var data _C_long
  1009. err = ptrace(PTRACE_GETEVENTMSG, pid, 0, uintptr(unsafe.Pointer(&data)))
  1010. msg = uint(data)
  1011. return
  1012. }
  1013. func PtraceCont(pid int, signal int) (err error) {
  1014. return ptrace(PTRACE_CONT, pid, 0, uintptr(signal))
  1015. }
  1016. func PtraceSyscall(pid int, signal int) (err error) {
  1017. return ptrace(PTRACE_SYSCALL, pid, 0, uintptr(signal))
  1018. }
  1019. func PtraceSingleStep(pid int) (err error) { return ptrace(PTRACE_SINGLESTEP, pid, 0, 0) }
  1020. func PtraceAttach(pid int) (err error) { return ptrace(PTRACE_ATTACH, pid, 0, 0) }
  1021. func PtraceDetach(pid int) (err error) { return ptrace(PTRACE_DETACH, pid, 0, 0) }
  1022. //sys reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error)
  1023. func Reboot(cmd int) (err error) {
  1024. return reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, cmd, "")
  1025. }
  1026. func ReadDirent(fd int, buf []byte) (n int, err error) {
  1027. return Getdents(fd, buf)
  1028. }
  1029. //sys mount(source string, target string, fstype string, flags uintptr, data *byte) (err error)
  1030. func Mount(source string, target string, fstype string, flags uintptr, data string) (err error) {
  1031. // Certain file systems get rather angry and EINVAL if you give
  1032. // them an empty string of data, rather than NULL.
  1033. if data == "" {
  1034. return mount(source, target, fstype, flags, nil)
  1035. }
  1036. datap, err := BytePtrFromString(data)
  1037. if err != nil {
  1038. return err
  1039. }
  1040. return mount(source, target, fstype, flags, datap)
  1041. }
  1042. // Sendto
  1043. // Recvfrom
  1044. // Socketpair
  1045. /*
  1046. * Direct access
  1047. */
  1048. //sys Acct(path string) (err error)
  1049. //sys AddKey(keyType string, description string, payload []byte, ringid int) (id int, err error)
  1050. //sys Adjtimex(buf *Timex) (state int, err error)
  1051. //sys Chdir(path string) (err error)
  1052. //sys Chroot(path string) (err error)
  1053. //sys ClockGettime(clockid int32, time *Timespec) (err error)
  1054. //sys Close(fd int) (err error)
  1055. //sys CopyFileRange(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error)
  1056. //sys Dup(oldfd int) (fd int, err error)
  1057. //sys Dup3(oldfd int, newfd int, flags int) (err error)
  1058. //sysnb EpollCreate1(flag int) (fd int, err error)
  1059. //sysnb EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error)
  1060. //sys Eventfd(initval uint, flags int) (fd int, err error) = SYS_EVENTFD2
  1061. //sys Exit(code int) = SYS_EXIT_GROUP
  1062. //sys Fallocate(fd int, mode uint32, off int64, len int64) (err error)
  1063. //sys Fchdir(fd int) (err error)
  1064. //sys Fchmod(fd int, mode uint32) (err error)
  1065. //sys Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error)
  1066. //sys fcntl(fd int, cmd int, arg int) (val int, err error)
  1067. //sys Fdatasync(fd int) (err error)
  1068. //sys Flock(fd int, how int) (err error)
  1069. //sys Fsync(fd int) (err error)
  1070. //sys Getdents(fd int, buf []byte) (n int, err error) = SYS_GETDENTS64
  1071. //sysnb Getpgid(pid int) (pgid int, err error)
  1072. func Getpgrp() (pid int) {
  1073. pid, _ = Getpgid(0)
  1074. return
  1075. }
  1076. //sysnb Getpid() (pid int)
  1077. //sysnb Getppid() (ppid int)
  1078. //sys Getpriority(which int, who int) (prio int, err error)
  1079. //sys Getrandom(buf []byte, flags int) (n int, err error)
  1080. //sysnb Getrusage(who int, rusage *Rusage) (err error)
  1081. //sysnb Getsid(pid int) (sid int, err error)
  1082. //sysnb Gettid() (tid int)
  1083. //sys Getxattr(path string, attr string, dest []byte) (sz int, err error)
  1084. //sys InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error)
  1085. //sysnb InotifyInit1(flags int) (fd int, err error)
  1086. //sysnb InotifyRmWatch(fd int, watchdesc uint32) (success int, err error)
  1087. //sysnb Kill(pid int, sig syscall.Signal) (err error)
  1088. //sys Klogctl(typ int, buf []byte) (n int, err error) = SYS_SYSLOG
  1089. //sys Lgetxattr(path string, attr string, dest []byte) (sz int, err error)
  1090. //sys Listxattr(path string, dest []byte) (sz int, err error)
  1091. //sys Llistxattr(path string, dest []byte) (sz int, err error)
  1092. //sys Lremovexattr(path string, attr string) (err error)
  1093. //sys Lsetxattr(path string, attr string, data []byte, flags int) (err error)
  1094. //sys Mkdirat(dirfd int, path string, mode uint32) (err error)
  1095. //sys Mknodat(dirfd int, path string, mode uint32, dev int) (err error)
  1096. //sys Nanosleep(time *Timespec, leftover *Timespec) (err error)
  1097. //sys PerfEventOpen(attr *PerfEventAttr, pid int, cpu int, groupFd int, flags int) (fd int, err error)
  1098. //sys PivotRoot(newroot string, putold string) (err error) = SYS_PIVOT_ROOT
  1099. //sysnb prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) = SYS_PRLIMIT64
  1100. //sys Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error)
  1101. //sys Pselect(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timespec, sigmask *Sigset_t) (n int, err error) = SYS_PSELECT6
  1102. //sys read(fd int, p []byte) (n int, err error)
  1103. //sys Removexattr(path string, attr string) (err error)
  1104. //sys Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error)
  1105. //sys RequestKey(keyType string, description string, callback string, destRingid int) (id int, err error)
  1106. //sys Setdomainname(p []byte) (err error)
  1107. //sys Sethostname(p []byte) (err error)
  1108. //sysnb Setpgid(pid int, pgid int) (err error)
  1109. //sysnb Setsid() (pid int, err error)
  1110. //sysnb Settimeofday(tv *Timeval) (err error)
  1111. //sys Setns(fd int, nstype int) (err error)
  1112. // issue 1435.
  1113. // On linux Setuid and Setgid only affects the current thread, not the process.
  1114. // This does not match what most callers expect so we must return an error
  1115. // here rather than letting the caller think that the call succeeded.
  1116. func Setuid(uid int) (err error) {
  1117. return EOPNOTSUPP
  1118. }
  1119. func Setgid(uid int) (err error) {
  1120. return EOPNOTSUPP
  1121. }
  1122. //sys Setpriority(which int, who int, prio int) (err error)
  1123. //sys Setxattr(path string, attr string, data []byte, flags int) (err error)
  1124. //sys Statx(dirfd int, path string, flags int, mask int, stat *Statx_t) (err error)
  1125. //sys Sync()
  1126. //sys Syncfs(fd int) (err error)
  1127. //sysnb Sysinfo(info *Sysinfo_t) (err error)
  1128. //sys Tee(rfd int, wfd int, len int, flags int) (n int64, err error)
  1129. //sysnb Tgkill(tgid int, tid int, sig syscall.Signal) (err error)
  1130. //sysnb Times(tms *Tms) (ticks uintptr, err error)
  1131. //sysnb Umask(mask int) (oldmask int)
  1132. //sysnb Uname(buf *Utsname) (err error)
  1133. //sys Unmount(target string, flags int) (err error) = SYS_UMOUNT2
  1134. //sys Unshare(flags int) (err error)
  1135. //sys write(fd int, p []byte) (n int, err error)
  1136. //sys exitThread(code int) (err error) = SYS_EXIT
  1137. //sys readlen(fd int, p *byte, np int) (n int, err error) = SYS_READ
  1138. //sys writelen(fd int, p *byte, np int) (n int, err error) = SYS_WRITE
  1139. // mmap varies by architecture; see syscall_linux_*.go.
  1140. //sys munmap(addr uintptr, length uintptr) (err error)
  1141. var mapper = &mmapper{
  1142. active: make(map[*byte][]byte),
  1143. mmap: mmap,
  1144. munmap: munmap,
  1145. }
  1146. func Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error) {
  1147. return mapper.Mmap(fd, offset, length, prot, flags)
  1148. }
  1149. func Munmap(b []byte) (err error) {
  1150. return mapper.Munmap(b)
  1151. }
  1152. //sys Madvise(b []byte, advice int) (err error)
  1153. //sys Mprotect(b []byte, prot int) (err error)
  1154. //sys Mlock(b []byte) (err error)
  1155. //sys Mlockall(flags int) (err error)
  1156. //sys Msync(b []byte, flags int) (err error)
  1157. //sys Munlock(b []byte) (err error)
  1158. //sys Munlockall() (err error)
  1159. // Vmsplice splices user pages from a slice of Iovecs into a pipe specified by fd,
  1160. // using the specified flags.
  1161. func Vmsplice(fd int, iovs []Iovec, flags int) (int, error) {
  1162. n, _, errno := Syscall6(
  1163. SYS_VMSPLICE,
  1164. uintptr(fd),
  1165. uintptr(unsafe.Pointer(&iovs[0])),
  1166. uintptr(len(iovs)),
  1167. uintptr(flags),
  1168. 0,
  1169. 0,
  1170. )
  1171. if errno != 0 {
  1172. return 0, syscall.Errno(errno)
  1173. }
  1174. return int(n), nil
  1175. }
  1176. //sys faccessat(dirfd int, path string, mode uint32) (err error)
  1177. func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) {
  1178. if flags & ^(AT_SYMLINK_NOFOLLOW|AT_EACCESS) != 0 {
  1179. return EINVAL
  1180. } else if flags&(AT_SYMLINK_NOFOLLOW|AT_EACCESS) != 0 {
  1181. return EOPNOTSUPP
  1182. }
  1183. return faccessat(dirfd, path, mode)
  1184. }
  1185. /*
  1186. * Unimplemented
  1187. */
  1188. // AfsSyscall
  1189. // Alarm
  1190. // ArchPrctl
  1191. // Brk
  1192. // Capget
  1193. // Capset
  1194. // ClockGetres
  1195. // ClockNanosleep
  1196. // ClockSettime
  1197. // Clone
  1198. // CreateModule
  1199. // DeleteModule
  1200. // EpollCtlOld
  1201. // EpollPwait
  1202. // EpollWaitOld
  1203. // Execve
  1204. // Fgetxattr
  1205. // Flistxattr
  1206. // Fork
  1207. // Fremovexattr
  1208. // Fsetxattr
  1209. // Futex
  1210. // GetKernelSyms
  1211. // GetMempolicy
  1212. // GetRobustList
  1213. // GetThreadArea
  1214. // Getitimer
  1215. // Getpmsg
  1216. // IoCancel
  1217. // IoDestroy
  1218. // IoGetevents
  1219. // IoSetup
  1220. // IoSubmit
  1221. // IoprioGet
  1222. // IoprioSet
  1223. // KexecLoad
  1224. // LookupDcookie
  1225. // Mbind
  1226. // MigratePages
  1227. // Mincore
  1228. // ModifyLdt
  1229. // Mount
  1230. // MovePages
  1231. // MqGetsetattr
  1232. // MqNotify
  1233. // MqOpen
  1234. // MqTimedreceive
  1235. // MqTimedsend
  1236. // MqUnlink
  1237. // Mremap
  1238. // Msgctl
  1239. // Msgget
  1240. // Msgrcv
  1241. // Msgsnd
  1242. // Nfsservctl
  1243. // Personality
  1244. // Pselect6
  1245. // Ptrace
  1246. // Putpmsg
  1247. // QueryModule
  1248. // Quotactl
  1249. // Readahead
  1250. // Readv
  1251. // RemapFilePages
  1252. // RestartSyscall
  1253. // RtSigaction
  1254. // RtSigpending
  1255. // RtSigprocmask
  1256. // RtSigqueueinfo
  1257. // RtSigreturn
  1258. // RtSigsuspend
  1259. // RtSigtimedwait
  1260. // SchedGetPriorityMax
  1261. // SchedGetPriorityMin
  1262. // SchedGetparam
  1263. // SchedGetscheduler
  1264. // SchedRrGetInterval
  1265. // SchedSetparam
  1266. // SchedYield
  1267. // Security
  1268. // Semctl
  1269. // Semget
  1270. // Semop
  1271. // Semtimedop
  1272. // SetMempolicy
  1273. // SetRobustList
  1274. // SetThreadArea
  1275. // SetTidAddress
  1276. // Shmat
  1277. // Shmctl
  1278. // Shmdt
  1279. // Shmget
  1280. // Sigaltstack
  1281. // Signalfd
  1282. // Swapoff
  1283. // Swapon
  1284. // Sysfs
  1285. // TimerCreate
  1286. // TimerDelete
  1287. // TimerGetoverrun
  1288. // TimerGettime
  1289. // TimerSettime
  1290. // Timerfd
  1291. // Tkill (obsolete)
  1292. // Tuxcall
  1293. // Umount2
  1294. // Uselib
  1295. // Utimensat
  1296. // Vfork
  1297. // Vhangup
  1298. // Vserver
  1299. // Waitid
  1300. // _Sysctl