syscall_solaris.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104
  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. // Solaris 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 wrap
  9. // it in our own nicer implementation, either here or in
  10. // syscall_solaris.go or syscall_unix.go.
  11. package unix
  12. import (
  13. "fmt"
  14. "os"
  15. "runtime"
  16. "sync"
  17. "syscall"
  18. "unsafe"
  19. )
  20. // Implemented in runtime/syscall_solaris.go.
  21. type syscallFunc uintptr
  22. func rawSysvicall6(trap, nargs, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno)
  23. func sysvicall6(trap, nargs, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno)
  24. // SockaddrDatalink implements the Sockaddr interface for AF_LINK type sockets.
  25. type SockaddrDatalink struct {
  26. Family uint16
  27. Index uint16
  28. Type uint8
  29. Nlen uint8
  30. Alen uint8
  31. Slen uint8
  32. Data [244]int8
  33. raw RawSockaddrDatalink
  34. }
  35. func direntIno(buf []byte) (uint64, bool) {
  36. return readInt(buf, unsafe.Offsetof(Dirent{}.Ino), unsafe.Sizeof(Dirent{}.Ino))
  37. }
  38. func direntReclen(buf []byte) (uint64, bool) {
  39. return readInt(buf, unsafe.Offsetof(Dirent{}.Reclen), unsafe.Sizeof(Dirent{}.Reclen))
  40. }
  41. func direntNamlen(buf []byte) (uint64, bool) {
  42. reclen, ok := direntReclen(buf)
  43. if !ok {
  44. return 0, false
  45. }
  46. return reclen - uint64(unsafe.Offsetof(Dirent{}.Name)), true
  47. }
  48. //sysnb pipe(p *[2]_C_int) (n int, err error)
  49. func Pipe(p []int) (err error) {
  50. if len(p) != 2 {
  51. return EINVAL
  52. }
  53. var pp [2]_C_int
  54. n, err := pipe(&pp)
  55. if n != 0 {
  56. return err
  57. }
  58. if err == nil {
  59. p[0] = int(pp[0])
  60. p[1] = int(pp[1])
  61. }
  62. return nil
  63. }
  64. //sysnb pipe2(p *[2]_C_int, flags int) (err error)
  65. func Pipe2(p []int, flags int) error {
  66. if len(p) != 2 {
  67. return EINVAL
  68. }
  69. var pp [2]_C_int
  70. err := pipe2(&pp, flags)
  71. if err == nil {
  72. p[0] = int(pp[0])
  73. p[1] = int(pp[1])
  74. }
  75. return err
  76. }
  77. func (sa *SockaddrInet4) sockaddr() (unsafe.Pointer, _Socklen, error) {
  78. if sa.Port < 0 || sa.Port > 0xFFFF {
  79. return nil, 0, EINVAL
  80. }
  81. sa.raw.Family = AF_INET
  82. p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port))
  83. p[0] = byte(sa.Port >> 8)
  84. p[1] = byte(sa.Port)
  85. sa.raw.Addr = sa.Addr
  86. return unsafe.Pointer(&sa.raw), SizeofSockaddrInet4, nil
  87. }
  88. func (sa *SockaddrInet6) sockaddr() (unsafe.Pointer, _Socklen, error) {
  89. if sa.Port < 0 || sa.Port > 0xFFFF {
  90. return nil, 0, EINVAL
  91. }
  92. sa.raw.Family = AF_INET6
  93. p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port))
  94. p[0] = byte(sa.Port >> 8)
  95. p[1] = byte(sa.Port)
  96. sa.raw.Scope_id = sa.ZoneId
  97. sa.raw.Addr = sa.Addr
  98. return unsafe.Pointer(&sa.raw), SizeofSockaddrInet6, nil
  99. }
  100. func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, _Socklen, error) {
  101. name := sa.Name
  102. n := len(name)
  103. if n >= len(sa.raw.Path) {
  104. return nil, 0, EINVAL
  105. }
  106. sa.raw.Family = AF_UNIX
  107. for i := 0; i < n; i++ {
  108. sa.raw.Path[i] = int8(name[i])
  109. }
  110. // length is family (uint16), name, NUL.
  111. sl := _Socklen(2)
  112. if n > 0 {
  113. sl += _Socklen(n) + 1
  114. }
  115. if sa.raw.Path[0] == '@' || (sa.raw.Path[0] == 0 && sl > 3) {
  116. // Check sl > 3 so we don't change unnamed socket behavior.
  117. sa.raw.Path[0] = 0
  118. // Don't count trailing NUL for abstract address.
  119. sl--
  120. }
  121. return unsafe.Pointer(&sa.raw), sl, nil
  122. }
  123. //sys getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) = libsocket.getsockname
  124. func Getsockname(fd int) (sa Sockaddr, err error) {
  125. var rsa RawSockaddrAny
  126. var len _Socklen = SizeofSockaddrAny
  127. if err = getsockname(fd, &rsa, &len); err != nil {
  128. return
  129. }
  130. return anyToSockaddr(fd, &rsa)
  131. }
  132. // GetsockoptString returns the string value of the socket option opt for the
  133. // socket associated with fd at the given socket level.
  134. func GetsockoptString(fd, level, opt int) (string, error) {
  135. buf := make([]byte, 256)
  136. vallen := _Socklen(len(buf))
  137. err := getsockopt(fd, level, opt, unsafe.Pointer(&buf[0]), &vallen)
  138. if err != nil {
  139. return "", err
  140. }
  141. return ByteSliceToString(buf[:vallen]), nil
  142. }
  143. const ImplementsGetwd = true
  144. //sys Getcwd(buf []byte) (n int, err error)
  145. func Getwd() (wd string, err error) {
  146. var buf [PathMax]byte
  147. // Getcwd will return an error if it failed for any reason.
  148. _, err = Getcwd(buf[0:])
  149. if err != nil {
  150. return "", err
  151. }
  152. n := clen(buf[:])
  153. if n < 1 {
  154. return "", EINVAL
  155. }
  156. return string(buf[:n]), nil
  157. }
  158. /*
  159. * Wrapped
  160. */
  161. //sysnb getgroups(ngid int, gid *_Gid_t) (n int, err error)
  162. //sysnb setgroups(ngid int, gid *_Gid_t) (err error)
  163. func Getgroups() (gids []int, err error) {
  164. n, err := getgroups(0, nil)
  165. // Check for error and sanity check group count. Newer versions of
  166. // Solaris allow up to 1024 (NGROUPS_MAX).
  167. if n < 0 || n > 1024 {
  168. if err != nil {
  169. return nil, err
  170. }
  171. return nil, EINVAL
  172. } else if n == 0 {
  173. return nil, nil
  174. }
  175. a := make([]_Gid_t, n)
  176. n, err = getgroups(n, &a[0])
  177. if n == -1 {
  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. // ReadDirent reads directory entries from fd and writes them into buf.
  197. func ReadDirent(fd int, buf []byte) (n int, err error) {
  198. // Final argument is (basep *uintptr) and the syscall doesn't take nil.
  199. // TODO(rsc): Can we use a single global basep for all calls?
  200. return Getdents(fd, buf, new(uintptr))
  201. }
  202. // Wait status is 7 bits at bottom, either 0 (exited),
  203. // 0x7F (stopped), or a signal number that caused an exit.
  204. // The 0x80 bit is whether there was a core dump.
  205. // An extra number (exit code, signal causing a stop)
  206. // is in the high bits.
  207. type WaitStatus uint32
  208. const (
  209. mask = 0x7F
  210. core = 0x80
  211. shift = 8
  212. exited = 0
  213. stopped = 0x7F
  214. )
  215. func (w WaitStatus) Exited() bool { return w&mask == exited }
  216. func (w WaitStatus) ExitStatus() int {
  217. if w&mask != exited {
  218. return -1
  219. }
  220. return int(w >> shift)
  221. }
  222. func (w WaitStatus) Signaled() bool { return w&mask != stopped && w&mask != 0 }
  223. func (w WaitStatus) Signal() syscall.Signal {
  224. sig := syscall.Signal(w & mask)
  225. if sig == stopped || sig == 0 {
  226. return -1
  227. }
  228. return sig
  229. }
  230. func (w WaitStatus) CoreDump() bool { return w.Signaled() && w&core != 0 }
  231. func (w WaitStatus) Stopped() bool { return w&mask == stopped && syscall.Signal(w>>shift) != SIGSTOP }
  232. func (w WaitStatus) Continued() bool { return w&mask == stopped && syscall.Signal(w>>shift) == SIGSTOP }
  233. func (w WaitStatus) StopSignal() syscall.Signal {
  234. if !w.Stopped() {
  235. return -1
  236. }
  237. return syscall.Signal(w>>shift) & 0xFF
  238. }
  239. func (w WaitStatus) TrapCause() int { return -1 }
  240. //sys wait4(pid int32, statusp *_C_int, options int, rusage *Rusage) (wpid int32, err error)
  241. func Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (int, error) {
  242. var status _C_int
  243. rpid, err := wait4(int32(pid), &status, options, rusage)
  244. wpid := int(rpid)
  245. if wpid == -1 {
  246. return wpid, err
  247. }
  248. if wstatus != nil {
  249. *wstatus = WaitStatus(status)
  250. }
  251. return wpid, nil
  252. }
  253. //sys gethostname(buf []byte) (n int, err error)
  254. func Gethostname() (name string, err error) {
  255. var buf [MaxHostNameLen]byte
  256. n, err := gethostname(buf[:])
  257. if n != 0 {
  258. return "", err
  259. }
  260. n = clen(buf[:])
  261. if n < 1 {
  262. return "", EFAULT
  263. }
  264. return string(buf[:n]), nil
  265. }
  266. //sys utimes(path string, times *[2]Timeval) (err error)
  267. func Utimes(path string, tv []Timeval) (err error) {
  268. if tv == nil {
  269. return utimes(path, nil)
  270. }
  271. if len(tv) != 2 {
  272. return EINVAL
  273. }
  274. return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
  275. }
  276. //sys utimensat(fd int, path string, times *[2]Timespec, flag int) (err error)
  277. func UtimesNano(path string, ts []Timespec) error {
  278. if ts == nil {
  279. return utimensat(AT_FDCWD, path, nil, 0)
  280. }
  281. if len(ts) != 2 {
  282. return EINVAL
  283. }
  284. return utimensat(AT_FDCWD, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), 0)
  285. }
  286. func UtimesNanoAt(dirfd int, path string, ts []Timespec, flags int) error {
  287. if ts == nil {
  288. return utimensat(dirfd, path, nil, flags)
  289. }
  290. if len(ts) != 2 {
  291. return EINVAL
  292. }
  293. return utimensat(dirfd, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), flags)
  294. }
  295. //sys fcntl(fd int, cmd int, arg int) (val int, err error)
  296. // FcntlInt performs a fcntl syscall on fd with the provided command and argument.
  297. func FcntlInt(fd uintptr, cmd, arg int) (int, error) {
  298. valptr, _, errno := sysvicall6(uintptr(unsafe.Pointer(&procfcntl)), 3, uintptr(fd), uintptr(cmd), uintptr(arg), 0, 0, 0)
  299. var err error
  300. if errno != 0 {
  301. err = errno
  302. }
  303. return int(valptr), err
  304. }
  305. // FcntlFlock performs a fcntl syscall for the F_GETLK, F_SETLK or F_SETLKW command.
  306. func FcntlFlock(fd uintptr, cmd int, lk *Flock_t) error {
  307. _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procfcntl)), 3, uintptr(fd), uintptr(cmd), uintptr(unsafe.Pointer(lk)), 0, 0, 0)
  308. if e1 != 0 {
  309. return e1
  310. }
  311. return nil
  312. }
  313. //sys futimesat(fildes int, path *byte, times *[2]Timeval) (err error)
  314. func Futimesat(dirfd int, path string, tv []Timeval) error {
  315. pathp, err := BytePtrFromString(path)
  316. if err != nil {
  317. return err
  318. }
  319. if tv == nil {
  320. return futimesat(dirfd, pathp, nil)
  321. }
  322. if len(tv) != 2 {
  323. return EINVAL
  324. }
  325. return futimesat(dirfd, pathp, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
  326. }
  327. // Solaris doesn't have an futimes function because it allows NULL to be
  328. // specified as the path for futimesat. However, Go doesn't like
  329. // NULL-style string interfaces, so this simple wrapper is provided.
  330. func Futimes(fd int, tv []Timeval) error {
  331. if tv == nil {
  332. return futimesat(fd, nil, nil)
  333. }
  334. if len(tv) != 2 {
  335. return EINVAL
  336. }
  337. return futimesat(fd, nil, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
  338. }
  339. func anyToSockaddr(fd int, rsa *RawSockaddrAny) (Sockaddr, error) {
  340. switch rsa.Addr.Family {
  341. case AF_UNIX:
  342. pp := (*RawSockaddrUnix)(unsafe.Pointer(rsa))
  343. sa := new(SockaddrUnix)
  344. // Assume path ends at NUL.
  345. // This is not technically the Solaris semantics for
  346. // abstract Unix domain sockets -- they are supposed
  347. // to be uninterpreted fixed-size binary blobs -- but
  348. // everyone uses this convention.
  349. n := 0
  350. for n < len(pp.Path) && pp.Path[n] != 0 {
  351. n++
  352. }
  353. sa.Name = string(unsafe.Slice((*byte)(unsafe.Pointer(&pp.Path[0])), n))
  354. return sa, nil
  355. case AF_INET:
  356. pp := (*RawSockaddrInet4)(unsafe.Pointer(rsa))
  357. sa := new(SockaddrInet4)
  358. p := (*[2]byte)(unsafe.Pointer(&pp.Port))
  359. sa.Port = int(p[0])<<8 + int(p[1])
  360. sa.Addr = pp.Addr
  361. return sa, nil
  362. case AF_INET6:
  363. pp := (*RawSockaddrInet6)(unsafe.Pointer(rsa))
  364. sa := new(SockaddrInet6)
  365. p := (*[2]byte)(unsafe.Pointer(&pp.Port))
  366. sa.Port = int(p[0])<<8 + int(p[1])
  367. sa.ZoneId = pp.Scope_id
  368. sa.Addr = pp.Addr
  369. return sa, nil
  370. }
  371. return nil, EAFNOSUPPORT
  372. }
  373. //sys accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) = libsocket.accept
  374. func Accept(fd int) (nfd int, sa Sockaddr, err error) {
  375. var rsa RawSockaddrAny
  376. var len _Socklen = SizeofSockaddrAny
  377. nfd, err = accept(fd, &rsa, &len)
  378. if nfd == -1 {
  379. return
  380. }
  381. sa, err = anyToSockaddr(fd, &rsa)
  382. if err != nil {
  383. Close(nfd)
  384. nfd = 0
  385. }
  386. return
  387. }
  388. //sys recvmsg(s int, msg *Msghdr, flags int) (n int, err error) = libsocket.__xnet_recvmsg
  389. func recvmsgRaw(fd int, iov []Iovec, oob []byte, flags int, rsa *RawSockaddrAny) (n, oobn int, recvflags int, err error) {
  390. var msg Msghdr
  391. msg.Name = (*byte)(unsafe.Pointer(rsa))
  392. msg.Namelen = uint32(SizeofSockaddrAny)
  393. var dummy byte
  394. if len(oob) > 0 {
  395. // receive at least one normal byte
  396. if emptyIovecs(iov) {
  397. var iova [1]Iovec
  398. iova[0].Base = &dummy
  399. iova[0].SetLen(1)
  400. iov = iova[:]
  401. }
  402. msg.Accrightslen = int32(len(oob))
  403. }
  404. if len(iov) > 0 {
  405. msg.Iov = &iov[0]
  406. msg.SetIovlen(len(iov))
  407. }
  408. if n, err = recvmsg(fd, &msg, flags); n == -1 {
  409. return
  410. }
  411. oobn = int(msg.Accrightslen)
  412. return
  413. }
  414. //sys sendmsg(s int, msg *Msghdr, flags int) (n int, err error) = libsocket.__xnet_sendmsg
  415. func sendmsgN(fd int, iov []Iovec, oob []byte, ptr unsafe.Pointer, salen _Socklen, flags int) (n int, err error) {
  416. var msg Msghdr
  417. msg.Name = (*byte)(unsafe.Pointer(ptr))
  418. msg.Namelen = uint32(salen)
  419. var dummy byte
  420. var empty bool
  421. if len(oob) > 0 {
  422. // send at least one normal byte
  423. empty = emptyIovecs(iov)
  424. if empty {
  425. var iova [1]Iovec
  426. iova[0].Base = &dummy
  427. iova[0].SetLen(1)
  428. iov = iova[:]
  429. }
  430. msg.Accrightslen = int32(len(oob))
  431. }
  432. if len(iov) > 0 {
  433. msg.Iov = &iov[0]
  434. msg.SetIovlen(len(iov))
  435. }
  436. if n, err = sendmsg(fd, &msg, flags); err != nil {
  437. return 0, err
  438. }
  439. if len(oob) > 0 && empty {
  440. n = 0
  441. }
  442. return n, nil
  443. }
  444. //sys acct(path *byte) (err error)
  445. func Acct(path string) (err error) {
  446. if len(path) == 0 {
  447. // Assume caller wants to disable accounting.
  448. return acct(nil)
  449. }
  450. pathp, err := BytePtrFromString(path)
  451. if err != nil {
  452. return err
  453. }
  454. return acct(pathp)
  455. }
  456. //sys __makedev(version int, major uint, minor uint) (val uint64)
  457. func Mkdev(major, minor uint32) uint64 {
  458. return __makedev(NEWDEV, uint(major), uint(minor))
  459. }
  460. //sys __major(version int, dev uint64) (val uint)
  461. func Major(dev uint64) uint32 {
  462. return uint32(__major(NEWDEV, dev))
  463. }
  464. //sys __minor(version int, dev uint64) (val uint)
  465. func Minor(dev uint64) uint32 {
  466. return uint32(__minor(NEWDEV, dev))
  467. }
  468. /*
  469. * Expose the ioctl function
  470. */
  471. //sys ioctlRet(fd int, req int, arg uintptr) (ret int, err error) = libc.ioctl
  472. //sys ioctlPtrRet(fd int, req int, arg unsafe.Pointer) (ret int, err error) = libc.ioctl
  473. func ioctl(fd int, req int, arg uintptr) (err error) {
  474. _, err = ioctlRet(fd, req, arg)
  475. return err
  476. }
  477. func ioctlPtr(fd int, req int, arg unsafe.Pointer) (err error) {
  478. _, err = ioctlPtrRet(fd, req, arg)
  479. return err
  480. }
  481. func IoctlSetTermio(fd int, req int, value *Termio) error {
  482. return ioctlPtr(fd, req, unsafe.Pointer(value))
  483. }
  484. func IoctlGetTermio(fd int, req int) (*Termio, error) {
  485. var value Termio
  486. err := ioctlPtr(fd, req, unsafe.Pointer(&value))
  487. return &value, err
  488. }
  489. //sys poll(fds *PollFd, nfds int, timeout int) (n int, err error)
  490. func Poll(fds []PollFd, timeout int) (n int, err error) {
  491. if len(fds) == 0 {
  492. return poll(nil, 0, timeout)
  493. }
  494. return poll(&fds[0], len(fds), timeout)
  495. }
  496. func Sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) {
  497. if raceenabled {
  498. raceReleaseMerge(unsafe.Pointer(&ioSync))
  499. }
  500. return sendfile(outfd, infd, offset, count)
  501. }
  502. /*
  503. * Exposed directly
  504. */
  505. //sys Access(path string, mode uint32) (err error)
  506. //sys Adjtime(delta *Timeval, olddelta *Timeval) (err error)
  507. //sys Chdir(path string) (err error)
  508. //sys Chmod(path string, mode uint32) (err error)
  509. //sys Chown(path string, uid int, gid int) (err error)
  510. //sys Chroot(path string) (err error)
  511. //sys ClockGettime(clockid int32, time *Timespec) (err error)
  512. //sys Close(fd int) (err error)
  513. //sys Creat(path string, mode uint32) (fd int, err error)
  514. //sys Dup(fd int) (nfd int, err error)
  515. //sys Dup2(oldfd int, newfd int) (err error)
  516. //sys Exit(code int)
  517. //sys Faccessat(dirfd int, path string, mode uint32, flags int) (err error)
  518. //sys Fchdir(fd int) (err error)
  519. //sys Fchmod(fd int, mode uint32) (err error)
  520. //sys Fchmodat(dirfd int, path string, mode uint32, flags int) (err error)
  521. //sys Fchown(fd int, uid int, gid int) (err error)
  522. //sys Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error)
  523. //sys Fdatasync(fd int) (err error)
  524. //sys Flock(fd int, how int) (err error)
  525. //sys Fpathconf(fd int, name int) (val int, err error)
  526. //sys Fstat(fd int, stat *Stat_t) (err error)
  527. //sys Fstatat(fd int, path string, stat *Stat_t, flags int) (err error)
  528. //sys Fstatvfs(fd int, vfsstat *Statvfs_t) (err error)
  529. //sys Getdents(fd int, buf []byte, basep *uintptr) (n int, err error)
  530. //sysnb Getgid() (gid int)
  531. //sysnb Getpid() (pid int)
  532. //sysnb Getpgid(pid int) (pgid int, err error)
  533. //sysnb Getpgrp() (pgid int, err error)
  534. //sys Geteuid() (euid int)
  535. //sys Getegid() (egid int)
  536. //sys Getppid() (ppid int)
  537. //sys Getpriority(which int, who int) (n int, err error)
  538. //sysnb Getrlimit(which int, lim *Rlimit) (err error)
  539. //sysnb Getrusage(who int, rusage *Rusage) (err error)
  540. //sysnb Getsid(pid int) (sid int, err error)
  541. //sysnb Gettimeofday(tv *Timeval) (err error)
  542. //sysnb Getuid() (uid int)
  543. //sys Kill(pid int, signum syscall.Signal) (err error)
  544. //sys Lchown(path string, uid int, gid int) (err error)
  545. //sys Link(path string, link string) (err error)
  546. //sys Listen(s int, backlog int) (err error) = libsocket.__xnet_llisten
  547. //sys Lstat(path string, stat *Stat_t) (err error)
  548. //sys Madvise(b []byte, advice int) (err error)
  549. //sys Mkdir(path string, mode uint32) (err error)
  550. //sys Mkdirat(dirfd int, path string, mode uint32) (err error)
  551. //sys Mkfifo(path string, mode uint32) (err error)
  552. //sys Mkfifoat(dirfd int, path string, mode uint32) (err error)
  553. //sys Mknod(path string, mode uint32, dev int) (err error)
  554. //sys Mknodat(dirfd int, path string, mode uint32, dev int) (err error)
  555. //sys Mlock(b []byte) (err error)
  556. //sys Mlockall(flags int) (err error)
  557. //sys Mprotect(b []byte, prot int) (err error)
  558. //sys Msync(b []byte, flags int) (err error)
  559. //sys Munlock(b []byte) (err error)
  560. //sys Munlockall() (err error)
  561. //sys Nanosleep(time *Timespec, leftover *Timespec) (err error)
  562. //sys Open(path string, mode int, perm uint32) (fd int, err error)
  563. //sys Openat(dirfd int, path string, flags int, mode uint32) (fd int, err error)
  564. //sys Pathconf(path string, name int) (val int, err error)
  565. //sys Pause() (err error)
  566. //sys pread(fd int, p []byte, offset int64) (n int, err error)
  567. //sys pwrite(fd int, p []byte, offset int64) (n int, err error)
  568. //sys read(fd int, p []byte) (n int, err error)
  569. //sys Readlink(path string, buf []byte) (n int, err error)
  570. //sys Rename(from string, to string) (err error)
  571. //sys Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error)
  572. //sys Rmdir(path string) (err error)
  573. //sys Seek(fd int, offset int64, whence int) (newoffset int64, err error) = lseek
  574. //sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error)
  575. //sysnb Setegid(egid int) (err error)
  576. //sysnb Seteuid(euid int) (err error)
  577. //sysnb Setgid(gid int) (err error)
  578. //sys Sethostname(p []byte) (err error)
  579. //sysnb Setpgid(pid int, pgid int) (err error)
  580. //sys Setpriority(which int, who int, prio int) (err error)
  581. //sysnb Setregid(rgid int, egid int) (err error)
  582. //sysnb Setreuid(ruid int, euid int) (err error)
  583. //sysnb Setsid() (pid int, err error)
  584. //sysnb Setuid(uid int) (err error)
  585. //sys Shutdown(s int, how int) (err error) = libsocket.shutdown
  586. //sys Stat(path string, stat *Stat_t) (err error)
  587. //sys Statvfs(path string, vfsstat *Statvfs_t) (err error)
  588. //sys Symlink(path string, link string) (err error)
  589. //sys Sync() (err error)
  590. //sys Sysconf(which int) (n int64, err error)
  591. //sysnb Times(tms *Tms) (ticks uintptr, err error)
  592. //sys Truncate(path string, length int64) (err error)
  593. //sys Fsync(fd int) (err error)
  594. //sys Ftruncate(fd int, length int64) (err error)
  595. //sys Umask(mask int) (oldmask int)
  596. //sysnb Uname(buf *Utsname) (err error)
  597. //sys Unmount(target string, flags int) (err error) = libc.umount
  598. //sys Unlink(path string) (err error)
  599. //sys Unlinkat(dirfd int, path string, flags int) (err error)
  600. //sys Ustat(dev int, ubuf *Ustat_t) (err error)
  601. //sys Utime(path string, buf *Utimbuf) (err error)
  602. //sys bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) = libsocket.__xnet_bind
  603. //sys connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) = libsocket.__xnet_connect
  604. //sys mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error)
  605. //sys munmap(addr uintptr, length uintptr) (err error)
  606. //sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) = libsendfile.sendfile
  607. //sys sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) = libsocket.__xnet_sendto
  608. //sys socket(domain int, typ int, proto int) (fd int, err error) = libsocket.__xnet_socket
  609. //sysnb socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) = libsocket.__xnet_socketpair
  610. //sys write(fd int, p []byte) (n int, err error)
  611. //sys getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) = libsocket.__xnet_getsockopt
  612. //sysnb getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) = libsocket.getpeername
  613. //sys setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) = libsocket.setsockopt
  614. //sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) = libsocket.recvfrom
  615. // Event Ports
  616. type fileObjCookie struct {
  617. fobj *fileObj
  618. cookie interface{}
  619. }
  620. // EventPort provides a safe abstraction on top of Solaris/illumos Event Ports.
  621. type EventPort struct {
  622. port int
  623. mu sync.Mutex
  624. fds map[uintptr]*fileObjCookie
  625. paths map[string]*fileObjCookie
  626. // The user cookie presents an interesting challenge from a memory management perspective.
  627. // There are two paths by which we can discover that it is no longer in use:
  628. // 1. The user calls port_dissociate before any events fire
  629. // 2. An event fires and we return it to the user
  630. // The tricky situation is if the event has fired in the kernel but
  631. // the user hasn't requested/received it yet.
  632. // If the user wants to port_dissociate before the event has been processed,
  633. // we should handle things gracefully. To do so, we need to keep an extra
  634. // reference to the cookie around until the event is processed
  635. // thus the otherwise seemingly extraneous "cookies" map
  636. // The key of this map is a pointer to the corresponding fCookie
  637. cookies map[*fileObjCookie]struct{}
  638. }
  639. // PortEvent is an abstraction of the port_event C struct.
  640. // Compare Source against PORT_SOURCE_FILE or PORT_SOURCE_FD
  641. // to see if Path or Fd was the event source. The other will be
  642. // uninitialized.
  643. type PortEvent struct {
  644. Cookie interface{}
  645. Events int32
  646. Fd uintptr
  647. Path string
  648. Source uint16
  649. fobj *fileObj
  650. }
  651. // NewEventPort creates a new EventPort including the
  652. // underlying call to port_create(3c).
  653. func NewEventPort() (*EventPort, error) {
  654. port, err := port_create()
  655. if err != nil {
  656. return nil, err
  657. }
  658. e := &EventPort{
  659. port: port,
  660. fds: make(map[uintptr]*fileObjCookie),
  661. paths: make(map[string]*fileObjCookie),
  662. cookies: make(map[*fileObjCookie]struct{}),
  663. }
  664. return e, nil
  665. }
  666. //sys port_create() (n int, err error)
  667. //sys port_associate(port int, source int, object uintptr, events int, user *byte) (n int, err error)
  668. //sys port_dissociate(port int, source int, object uintptr) (n int, err error)
  669. //sys port_get(port int, pe *portEvent, timeout *Timespec) (n int, err error)
  670. //sys port_getn(port int, pe *portEvent, max uint32, nget *uint32, timeout *Timespec) (n int, err error)
  671. // Close closes the event port.
  672. func (e *EventPort) Close() error {
  673. e.mu.Lock()
  674. defer e.mu.Unlock()
  675. err := Close(e.port)
  676. if err != nil {
  677. return err
  678. }
  679. e.fds = nil
  680. e.paths = nil
  681. e.cookies = nil
  682. return nil
  683. }
  684. // PathIsWatched checks to see if path is associated with this EventPort.
  685. func (e *EventPort) PathIsWatched(path string) bool {
  686. e.mu.Lock()
  687. defer e.mu.Unlock()
  688. _, found := e.paths[path]
  689. return found
  690. }
  691. // FdIsWatched checks to see if fd is associated with this EventPort.
  692. func (e *EventPort) FdIsWatched(fd uintptr) bool {
  693. e.mu.Lock()
  694. defer e.mu.Unlock()
  695. _, found := e.fds[fd]
  696. return found
  697. }
  698. // AssociatePath wraps port_associate(3c) for a filesystem path including
  699. // creating the necessary file_obj from the provided stat information.
  700. func (e *EventPort) AssociatePath(path string, stat os.FileInfo, events int, cookie interface{}) error {
  701. e.mu.Lock()
  702. defer e.mu.Unlock()
  703. if _, found := e.paths[path]; found {
  704. return fmt.Errorf("%v is already associated with this Event Port", path)
  705. }
  706. fCookie, err := createFileObjCookie(path, stat, cookie)
  707. if err != nil {
  708. return err
  709. }
  710. _, err = port_associate(e.port, PORT_SOURCE_FILE, uintptr(unsafe.Pointer(fCookie.fobj)), events, (*byte)(unsafe.Pointer(fCookie)))
  711. if err != nil {
  712. return err
  713. }
  714. e.paths[path] = fCookie
  715. e.cookies[fCookie] = struct{}{}
  716. return nil
  717. }
  718. // DissociatePath wraps port_dissociate(3c) for a filesystem path.
  719. func (e *EventPort) DissociatePath(path string) error {
  720. e.mu.Lock()
  721. defer e.mu.Unlock()
  722. f, ok := e.paths[path]
  723. if !ok {
  724. return fmt.Errorf("%v is not associated with this Event Port", path)
  725. }
  726. _, err := port_dissociate(e.port, PORT_SOURCE_FILE, uintptr(unsafe.Pointer(f.fobj)))
  727. // If the path is no longer associated with this event port (ENOENT)
  728. // we should delete it from our map. We can still return ENOENT to the caller.
  729. // But we need to save the cookie
  730. if err != nil && err != ENOENT {
  731. return err
  732. }
  733. if err == nil {
  734. // dissociate was successful, safe to delete the cookie
  735. fCookie := e.paths[path]
  736. delete(e.cookies, fCookie)
  737. }
  738. delete(e.paths, path)
  739. return err
  740. }
  741. // AssociateFd wraps calls to port_associate(3c) on file descriptors.
  742. func (e *EventPort) AssociateFd(fd uintptr, events int, cookie interface{}) error {
  743. e.mu.Lock()
  744. defer e.mu.Unlock()
  745. if _, found := e.fds[fd]; found {
  746. return fmt.Errorf("%v is already associated with this Event Port", fd)
  747. }
  748. fCookie, err := createFileObjCookie("", nil, cookie)
  749. if err != nil {
  750. return err
  751. }
  752. _, err = port_associate(e.port, PORT_SOURCE_FD, fd, events, (*byte)(unsafe.Pointer(fCookie)))
  753. if err != nil {
  754. return err
  755. }
  756. e.fds[fd] = fCookie
  757. e.cookies[fCookie] = struct{}{}
  758. return nil
  759. }
  760. // DissociateFd wraps calls to port_dissociate(3c) on file descriptors.
  761. func (e *EventPort) DissociateFd(fd uintptr) error {
  762. e.mu.Lock()
  763. defer e.mu.Unlock()
  764. _, ok := e.fds[fd]
  765. if !ok {
  766. return fmt.Errorf("%v is not associated with this Event Port", fd)
  767. }
  768. _, err := port_dissociate(e.port, PORT_SOURCE_FD, fd)
  769. if err != nil && err != ENOENT {
  770. return err
  771. }
  772. if err == nil {
  773. // dissociate was successful, safe to delete the cookie
  774. fCookie := e.fds[fd]
  775. delete(e.cookies, fCookie)
  776. }
  777. delete(e.fds, fd)
  778. return err
  779. }
  780. func createFileObjCookie(name string, stat os.FileInfo, cookie interface{}) (*fileObjCookie, error) {
  781. fCookie := new(fileObjCookie)
  782. fCookie.cookie = cookie
  783. if name != "" && stat != nil {
  784. fCookie.fobj = new(fileObj)
  785. bs, err := ByteSliceFromString(name)
  786. if err != nil {
  787. return nil, err
  788. }
  789. fCookie.fobj.Name = (*int8)(unsafe.Pointer(&bs[0]))
  790. s := stat.Sys().(*syscall.Stat_t)
  791. fCookie.fobj.Atim.Sec = s.Atim.Sec
  792. fCookie.fobj.Atim.Nsec = s.Atim.Nsec
  793. fCookie.fobj.Mtim.Sec = s.Mtim.Sec
  794. fCookie.fobj.Mtim.Nsec = s.Mtim.Nsec
  795. fCookie.fobj.Ctim.Sec = s.Ctim.Sec
  796. fCookie.fobj.Ctim.Nsec = s.Ctim.Nsec
  797. }
  798. return fCookie, nil
  799. }
  800. // GetOne wraps port_get(3c) and returns a single PortEvent.
  801. func (e *EventPort) GetOne(t *Timespec) (*PortEvent, error) {
  802. pe := new(portEvent)
  803. _, err := port_get(e.port, pe, t)
  804. if err != nil {
  805. return nil, err
  806. }
  807. p := new(PortEvent)
  808. e.mu.Lock()
  809. defer e.mu.Unlock()
  810. err = e.peIntToExt(pe, p)
  811. if err != nil {
  812. return nil, err
  813. }
  814. return p, nil
  815. }
  816. // peIntToExt converts a cgo portEvent struct into the friendlier PortEvent
  817. // NOTE: Always call this function while holding the e.mu mutex
  818. func (e *EventPort) peIntToExt(peInt *portEvent, peExt *PortEvent) error {
  819. if e.cookies == nil {
  820. return fmt.Errorf("this EventPort is already closed")
  821. }
  822. peExt.Events = peInt.Events
  823. peExt.Source = peInt.Source
  824. fCookie := (*fileObjCookie)(unsafe.Pointer(peInt.User))
  825. _, found := e.cookies[fCookie]
  826. if !found {
  827. panic("unexpected event port address; may be due to kernel bug; see https://go.dev/issue/54254")
  828. }
  829. peExt.Cookie = fCookie.cookie
  830. delete(e.cookies, fCookie)
  831. switch peInt.Source {
  832. case PORT_SOURCE_FD:
  833. peExt.Fd = uintptr(peInt.Object)
  834. // Only remove the fds entry if it exists and this cookie matches
  835. if fobj, ok := e.fds[peExt.Fd]; ok {
  836. if fobj == fCookie {
  837. delete(e.fds, peExt.Fd)
  838. }
  839. }
  840. case PORT_SOURCE_FILE:
  841. peExt.fobj = fCookie.fobj
  842. peExt.Path = BytePtrToString((*byte)(unsafe.Pointer(peExt.fobj.Name)))
  843. // Only remove the paths entry if it exists and this cookie matches
  844. if fobj, ok := e.paths[peExt.Path]; ok {
  845. if fobj == fCookie {
  846. delete(e.paths, peExt.Path)
  847. }
  848. }
  849. }
  850. return nil
  851. }
  852. // Pending wraps port_getn(3c) and returns how many events are pending.
  853. func (e *EventPort) Pending() (int, error) {
  854. var n uint32 = 0
  855. _, err := port_getn(e.port, nil, 0, &n, nil)
  856. return int(n), err
  857. }
  858. // Get wraps port_getn(3c) and fills a slice of PortEvent.
  859. // It will block until either min events have been received
  860. // or the timeout has been exceeded. It will return how many
  861. // events were actually received along with any error information.
  862. func (e *EventPort) Get(s []PortEvent, min int, timeout *Timespec) (int, error) {
  863. if min == 0 {
  864. return 0, fmt.Errorf("need to request at least one event or use Pending() instead")
  865. }
  866. if len(s) < min {
  867. return 0, fmt.Errorf("len(s) (%d) is less than min events requested (%d)", len(s), min)
  868. }
  869. got := uint32(min)
  870. max := uint32(len(s))
  871. var err error
  872. ps := make([]portEvent, max)
  873. _, err = port_getn(e.port, &ps[0], max, &got, timeout)
  874. // got will be trustworthy with ETIME, but not any other error.
  875. if err != nil && err != ETIME {
  876. return 0, err
  877. }
  878. e.mu.Lock()
  879. defer e.mu.Unlock()
  880. valid := 0
  881. for i := 0; i < int(got); i++ {
  882. err2 := e.peIntToExt(&ps[i], &s[i])
  883. if err2 != nil {
  884. if valid == 0 && err == nil {
  885. // If err2 is the only error and there are no valid events
  886. // to return, return it to the caller.
  887. err = err2
  888. }
  889. break
  890. }
  891. valid = i + 1
  892. }
  893. return valid, err
  894. }
  895. //sys putmsg(fd int, clptr *strbuf, dataptr *strbuf, flags int) (err error)
  896. func Putmsg(fd int, cl []byte, data []byte, flags int) (err error) {
  897. var clp, datap *strbuf
  898. if len(cl) > 0 {
  899. clp = &strbuf{
  900. Len: int32(len(cl)),
  901. Buf: (*int8)(unsafe.Pointer(&cl[0])),
  902. }
  903. }
  904. if len(data) > 0 {
  905. datap = &strbuf{
  906. Len: int32(len(data)),
  907. Buf: (*int8)(unsafe.Pointer(&data[0])),
  908. }
  909. }
  910. return putmsg(fd, clp, datap, flags)
  911. }
  912. //sys getmsg(fd int, clptr *strbuf, dataptr *strbuf, flags *int) (err error)
  913. func Getmsg(fd int, cl []byte, data []byte) (retCl []byte, retData []byte, flags int, err error) {
  914. var clp, datap *strbuf
  915. if len(cl) > 0 {
  916. clp = &strbuf{
  917. Maxlen: int32(len(cl)),
  918. Buf: (*int8)(unsafe.Pointer(&cl[0])),
  919. }
  920. }
  921. if len(data) > 0 {
  922. datap = &strbuf{
  923. Maxlen: int32(len(data)),
  924. Buf: (*int8)(unsafe.Pointer(&data[0])),
  925. }
  926. }
  927. if err = getmsg(fd, clp, datap, &flags); err != nil {
  928. return nil, nil, 0, err
  929. }
  930. if len(cl) > 0 {
  931. retCl = cl[:clp.Len]
  932. }
  933. if len(data) > 0 {
  934. retData = data[:datap.Len]
  935. }
  936. return retCl, retData, flags, nil
  937. }
  938. func IoctlSetIntRetInt(fd int, req int, arg int) (int, error) {
  939. return ioctlRet(fd, req, uintptr(arg))
  940. }
  941. func IoctlSetString(fd int, req int, val string) error {
  942. bs := make([]byte, len(val)+1)
  943. copy(bs[:len(bs)-1], val)
  944. err := ioctlPtr(fd, req, unsafe.Pointer(&bs[0]))
  945. runtime.KeepAlive(&bs[0])
  946. return err
  947. }
  948. // Lifreq Helpers
  949. func (l *Lifreq) SetName(name string) error {
  950. if len(name) >= len(l.Name) {
  951. return fmt.Errorf("name cannot be more than %d characters", len(l.Name)-1)
  952. }
  953. for i := range name {
  954. l.Name[i] = int8(name[i])
  955. }
  956. return nil
  957. }
  958. func (l *Lifreq) SetLifruInt(d int) {
  959. *(*int)(unsafe.Pointer(&l.Lifru[0])) = d
  960. }
  961. func (l *Lifreq) GetLifruInt() int {
  962. return *(*int)(unsafe.Pointer(&l.Lifru[0]))
  963. }
  964. func (l *Lifreq) SetLifruUint(d uint) {
  965. *(*uint)(unsafe.Pointer(&l.Lifru[0])) = d
  966. }
  967. func (l *Lifreq) GetLifruUint() uint {
  968. return *(*uint)(unsafe.Pointer(&l.Lifru[0]))
  969. }
  970. func IoctlLifreq(fd int, req int, l *Lifreq) error {
  971. return ioctlPtr(fd, req, unsafe.Pointer(l))
  972. }
  973. // Strioctl Helpers
  974. func (s *Strioctl) SetInt(i int) {
  975. s.Len = int32(unsafe.Sizeof(i))
  976. s.Dp = (*int8)(unsafe.Pointer(&i))
  977. }
  978. func IoctlSetStrioctlRetInt(fd int, req int, s *Strioctl) (int, error) {
  979. return ioctlPtrRet(fd, req, unsafe.Pointer(s))
  980. }