syscall_unix.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  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. //go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris
  5. package unix
  6. import (
  7. "bytes"
  8. "sort"
  9. "sync"
  10. "syscall"
  11. "unsafe"
  12. )
  13. var (
  14. Stdin = 0
  15. Stdout = 1
  16. Stderr = 2
  17. )
  18. // Do the interface allocations only once for common
  19. // Errno values.
  20. var (
  21. errEAGAIN error = syscall.EAGAIN
  22. errEINVAL error = syscall.EINVAL
  23. errENOENT error = syscall.ENOENT
  24. )
  25. var (
  26. signalNameMapOnce sync.Once
  27. signalNameMap map[string]syscall.Signal
  28. )
  29. // errnoErr returns common boxed Errno values, to prevent
  30. // allocations at runtime.
  31. func errnoErr(e syscall.Errno) error {
  32. switch e {
  33. case 0:
  34. return nil
  35. case EAGAIN:
  36. return errEAGAIN
  37. case EINVAL:
  38. return errEINVAL
  39. case ENOENT:
  40. return errENOENT
  41. }
  42. return e
  43. }
  44. // ErrnoName returns the error name for error number e.
  45. func ErrnoName(e syscall.Errno) string {
  46. i := sort.Search(len(errorList), func(i int) bool {
  47. return errorList[i].num >= e
  48. })
  49. if i < len(errorList) && errorList[i].num == e {
  50. return errorList[i].name
  51. }
  52. return ""
  53. }
  54. // SignalName returns the signal name for signal number s.
  55. func SignalName(s syscall.Signal) string {
  56. i := sort.Search(len(signalList), func(i int) bool {
  57. return signalList[i].num >= s
  58. })
  59. if i < len(signalList) && signalList[i].num == s {
  60. return signalList[i].name
  61. }
  62. return ""
  63. }
  64. // SignalNum returns the syscall.Signal for signal named s,
  65. // or 0 if a signal with such name is not found.
  66. // The signal name should start with "SIG".
  67. func SignalNum(s string) syscall.Signal {
  68. signalNameMapOnce.Do(func() {
  69. signalNameMap = make(map[string]syscall.Signal, len(signalList))
  70. for _, signal := range signalList {
  71. signalNameMap[signal.name] = signal.num
  72. }
  73. })
  74. return signalNameMap[s]
  75. }
  76. // clen returns the index of the first NULL byte in n or len(n) if n contains no NULL byte.
  77. func clen(n []byte) int {
  78. i := bytes.IndexByte(n, 0)
  79. if i == -1 {
  80. i = len(n)
  81. }
  82. return i
  83. }
  84. // Mmap manager, for use by operating system-specific implementations.
  85. type mmapper struct {
  86. sync.Mutex
  87. active map[*byte][]byte // active mappings; key is last byte in mapping
  88. mmap func(addr, length uintptr, prot, flags, fd int, offset int64) (uintptr, error)
  89. munmap func(addr uintptr, length uintptr) error
  90. }
  91. func (m *mmapper) Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error) {
  92. if length <= 0 {
  93. return nil, EINVAL
  94. }
  95. // Map the requested memory.
  96. addr, errno := m.mmap(0, uintptr(length), prot, flags, fd, offset)
  97. if errno != nil {
  98. return nil, errno
  99. }
  100. // Use unsafe to convert addr into a []byte.
  101. b := unsafe.Slice((*byte)(unsafe.Pointer(addr)), length)
  102. // Register mapping in m and return it.
  103. p := &b[cap(b)-1]
  104. m.Lock()
  105. defer m.Unlock()
  106. m.active[p] = b
  107. return b, nil
  108. }
  109. func (m *mmapper) Munmap(data []byte) (err error) {
  110. if len(data) == 0 || len(data) != cap(data) {
  111. return EINVAL
  112. }
  113. // Find the base of the mapping.
  114. p := &data[cap(data)-1]
  115. m.Lock()
  116. defer m.Unlock()
  117. b := m.active[p]
  118. if b == nil || &b[0] != &data[0] {
  119. return EINVAL
  120. }
  121. // Unmap the memory and update m.
  122. if errno := m.munmap(uintptr(unsafe.Pointer(&b[0])), uintptr(len(b))); errno != nil {
  123. return errno
  124. }
  125. delete(m.active, p)
  126. return nil
  127. }
  128. func Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error) {
  129. return mapper.Mmap(fd, offset, length, prot, flags)
  130. }
  131. func Munmap(b []byte) (err error) {
  132. return mapper.Munmap(b)
  133. }
  134. func Read(fd int, p []byte) (n int, err error) {
  135. n, err = read(fd, p)
  136. if raceenabled {
  137. if n > 0 {
  138. raceWriteRange(unsafe.Pointer(&p[0]), n)
  139. }
  140. if err == nil {
  141. raceAcquire(unsafe.Pointer(&ioSync))
  142. }
  143. }
  144. return
  145. }
  146. func Write(fd int, p []byte) (n int, err error) {
  147. if raceenabled {
  148. raceReleaseMerge(unsafe.Pointer(&ioSync))
  149. }
  150. n, err = write(fd, p)
  151. if raceenabled && n > 0 {
  152. raceReadRange(unsafe.Pointer(&p[0]), n)
  153. }
  154. return
  155. }
  156. func Pread(fd int, p []byte, offset int64) (n int, err error) {
  157. n, err = pread(fd, p, offset)
  158. if raceenabled {
  159. if n > 0 {
  160. raceWriteRange(unsafe.Pointer(&p[0]), n)
  161. }
  162. if err == nil {
  163. raceAcquire(unsafe.Pointer(&ioSync))
  164. }
  165. }
  166. return
  167. }
  168. func Pwrite(fd int, p []byte, offset int64) (n int, err error) {
  169. if raceenabled {
  170. raceReleaseMerge(unsafe.Pointer(&ioSync))
  171. }
  172. n, err = pwrite(fd, p, offset)
  173. if raceenabled && n > 0 {
  174. raceReadRange(unsafe.Pointer(&p[0]), n)
  175. }
  176. return
  177. }
  178. // For testing: clients can set this flag to force
  179. // creation of IPv6 sockets to return EAFNOSUPPORT.
  180. var SocketDisableIPv6 bool
  181. // Sockaddr represents a socket address.
  182. type Sockaddr interface {
  183. sockaddr() (ptr unsafe.Pointer, len _Socklen, err error) // lowercase; only we can define Sockaddrs
  184. }
  185. // SockaddrInet4 implements the Sockaddr interface for AF_INET type sockets.
  186. type SockaddrInet4 struct {
  187. Port int
  188. Addr [4]byte
  189. raw RawSockaddrInet4
  190. }
  191. // SockaddrInet6 implements the Sockaddr interface for AF_INET6 type sockets.
  192. type SockaddrInet6 struct {
  193. Port int
  194. ZoneId uint32
  195. Addr [16]byte
  196. raw RawSockaddrInet6
  197. }
  198. // SockaddrUnix implements the Sockaddr interface for AF_UNIX type sockets.
  199. type SockaddrUnix struct {
  200. Name string
  201. raw RawSockaddrUnix
  202. }
  203. func Bind(fd int, sa Sockaddr) (err error) {
  204. ptr, n, err := sa.sockaddr()
  205. if err != nil {
  206. return err
  207. }
  208. return bind(fd, ptr, n)
  209. }
  210. func Connect(fd int, sa Sockaddr) (err error) {
  211. ptr, n, err := sa.sockaddr()
  212. if err != nil {
  213. return err
  214. }
  215. return connect(fd, ptr, n)
  216. }
  217. func Getpeername(fd int) (sa Sockaddr, err error) {
  218. var rsa RawSockaddrAny
  219. var len _Socklen = SizeofSockaddrAny
  220. if err = getpeername(fd, &rsa, &len); err != nil {
  221. return
  222. }
  223. return anyToSockaddr(fd, &rsa)
  224. }
  225. func GetsockoptByte(fd, level, opt int) (value byte, err error) {
  226. var n byte
  227. vallen := _Socklen(1)
  228. err = getsockopt(fd, level, opt, unsafe.Pointer(&n), &vallen)
  229. return n, err
  230. }
  231. func GetsockoptInt(fd, level, opt int) (value int, err error) {
  232. var n int32
  233. vallen := _Socklen(4)
  234. err = getsockopt(fd, level, opt, unsafe.Pointer(&n), &vallen)
  235. return int(n), err
  236. }
  237. func GetsockoptInet4Addr(fd, level, opt int) (value [4]byte, err error) {
  238. vallen := _Socklen(4)
  239. err = getsockopt(fd, level, opt, unsafe.Pointer(&value[0]), &vallen)
  240. return value, err
  241. }
  242. func GetsockoptIPMreq(fd, level, opt int) (*IPMreq, error) {
  243. var value IPMreq
  244. vallen := _Socklen(SizeofIPMreq)
  245. err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
  246. return &value, err
  247. }
  248. func GetsockoptIPv6Mreq(fd, level, opt int) (*IPv6Mreq, error) {
  249. var value IPv6Mreq
  250. vallen := _Socklen(SizeofIPv6Mreq)
  251. err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
  252. return &value, err
  253. }
  254. func GetsockoptIPv6MTUInfo(fd, level, opt int) (*IPv6MTUInfo, error) {
  255. var value IPv6MTUInfo
  256. vallen := _Socklen(SizeofIPv6MTUInfo)
  257. err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
  258. return &value, err
  259. }
  260. func GetsockoptICMPv6Filter(fd, level, opt int) (*ICMPv6Filter, error) {
  261. var value ICMPv6Filter
  262. vallen := _Socklen(SizeofICMPv6Filter)
  263. err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
  264. return &value, err
  265. }
  266. func GetsockoptLinger(fd, level, opt int) (*Linger, error) {
  267. var linger Linger
  268. vallen := _Socklen(SizeofLinger)
  269. err := getsockopt(fd, level, opt, unsafe.Pointer(&linger), &vallen)
  270. return &linger, err
  271. }
  272. func GetsockoptTimeval(fd, level, opt int) (*Timeval, error) {
  273. var tv Timeval
  274. vallen := _Socklen(unsafe.Sizeof(tv))
  275. err := getsockopt(fd, level, opt, unsafe.Pointer(&tv), &vallen)
  276. return &tv, err
  277. }
  278. func GetsockoptUint64(fd, level, opt int) (value uint64, err error) {
  279. var n uint64
  280. vallen := _Socklen(8)
  281. err = getsockopt(fd, level, opt, unsafe.Pointer(&n), &vallen)
  282. return n, err
  283. }
  284. func Recvfrom(fd int, p []byte, flags int) (n int, from Sockaddr, err error) {
  285. var rsa RawSockaddrAny
  286. var len _Socklen = SizeofSockaddrAny
  287. if n, err = recvfrom(fd, p, flags, &rsa, &len); err != nil {
  288. return
  289. }
  290. if rsa.Addr.Family != AF_UNSPEC {
  291. from, err = anyToSockaddr(fd, &rsa)
  292. }
  293. return
  294. }
  295. // Recvmsg receives a message from a socket using the recvmsg system call. The
  296. // received non-control data will be written to p, and any "out of band"
  297. // control data will be written to oob. The flags are passed to recvmsg.
  298. //
  299. // The results are:
  300. // - n is the number of non-control data bytes read into p
  301. // - oobn is the number of control data bytes read into oob; this may be interpreted using [ParseSocketControlMessage]
  302. // - recvflags is flags returned by recvmsg
  303. // - from is the address of the sender
  304. //
  305. // If the underlying socket type is not SOCK_DGRAM, a received message
  306. // containing oob data and a single '\0' of non-control data is treated as if
  307. // the message contained only control data, i.e. n will be zero on return.
  308. func Recvmsg(fd int, p, oob []byte, flags int) (n, oobn int, recvflags int, from Sockaddr, err error) {
  309. var iov [1]Iovec
  310. if len(p) > 0 {
  311. iov[0].Base = &p[0]
  312. iov[0].SetLen(len(p))
  313. }
  314. var rsa RawSockaddrAny
  315. n, oobn, recvflags, err = recvmsgRaw(fd, iov[:], oob, flags, &rsa)
  316. // source address is only specified if the socket is unconnected
  317. if rsa.Addr.Family != AF_UNSPEC {
  318. from, err = anyToSockaddr(fd, &rsa)
  319. }
  320. return
  321. }
  322. // RecvmsgBuffers receives a message from a socket using the recvmsg system
  323. // call. This function is equivalent to Recvmsg, but non-control data read is
  324. // scattered into the buffers slices.
  325. func RecvmsgBuffers(fd int, buffers [][]byte, oob []byte, flags int) (n, oobn int, recvflags int, from Sockaddr, err error) {
  326. iov := make([]Iovec, len(buffers))
  327. for i := range buffers {
  328. if len(buffers[i]) > 0 {
  329. iov[i].Base = &buffers[i][0]
  330. iov[i].SetLen(len(buffers[i]))
  331. } else {
  332. iov[i].Base = (*byte)(unsafe.Pointer(&_zero))
  333. }
  334. }
  335. var rsa RawSockaddrAny
  336. n, oobn, recvflags, err = recvmsgRaw(fd, iov, oob, flags, &rsa)
  337. if err == nil && rsa.Addr.Family != AF_UNSPEC {
  338. from, err = anyToSockaddr(fd, &rsa)
  339. }
  340. return
  341. }
  342. // Sendmsg sends a message on a socket to an address using the sendmsg system
  343. // call. This function is equivalent to SendmsgN, but does not return the
  344. // number of bytes actually sent.
  345. func Sendmsg(fd int, p, oob []byte, to Sockaddr, flags int) (err error) {
  346. _, err = SendmsgN(fd, p, oob, to, flags)
  347. return
  348. }
  349. // SendmsgN sends a message on a socket to an address using the sendmsg system
  350. // call. p contains the non-control data to send, and oob contains the "out of
  351. // band" control data. The flags are passed to sendmsg. The number of
  352. // non-control bytes actually written to the socket is returned.
  353. //
  354. // Some socket types do not support sending control data without accompanying
  355. // non-control data. If p is empty, and oob contains control data, and the
  356. // underlying socket type is not SOCK_DGRAM, p will be treated as containing a
  357. // single '\0' and the return value will indicate zero bytes sent.
  358. //
  359. // The Go function Recvmsg, if called with an empty p and a non-empty oob,
  360. // will read and ignore this additional '\0'. If the message is received by
  361. // code that does not use Recvmsg, or that does not use Go at all, that code
  362. // will need to be written to expect and ignore the additional '\0'.
  363. //
  364. // If you need to send non-empty oob with p actually empty, and if the
  365. // underlying socket type supports it, you can do so via a raw system call as
  366. // follows:
  367. //
  368. // msg := &unix.Msghdr{
  369. // Control: &oob[0],
  370. // }
  371. // msg.SetControllen(len(oob))
  372. // n, _, errno := unix.Syscall(unix.SYS_SENDMSG, uintptr(fd), uintptr(unsafe.Pointer(msg)), flags)
  373. func SendmsgN(fd int, p, oob []byte, to Sockaddr, flags int) (n int, err error) {
  374. var iov [1]Iovec
  375. if len(p) > 0 {
  376. iov[0].Base = &p[0]
  377. iov[0].SetLen(len(p))
  378. }
  379. var ptr unsafe.Pointer
  380. var salen _Socklen
  381. if to != nil {
  382. ptr, salen, err = to.sockaddr()
  383. if err != nil {
  384. return 0, err
  385. }
  386. }
  387. return sendmsgN(fd, iov[:], oob, ptr, salen, flags)
  388. }
  389. // SendmsgBuffers sends a message on a socket to an address using the sendmsg
  390. // system call. This function is equivalent to SendmsgN, but the non-control
  391. // data is gathered from buffers.
  392. func SendmsgBuffers(fd int, buffers [][]byte, oob []byte, to Sockaddr, flags int) (n int, err error) {
  393. iov := make([]Iovec, len(buffers))
  394. for i := range buffers {
  395. if len(buffers[i]) > 0 {
  396. iov[i].Base = &buffers[i][0]
  397. iov[i].SetLen(len(buffers[i]))
  398. } else {
  399. iov[i].Base = (*byte)(unsafe.Pointer(&_zero))
  400. }
  401. }
  402. var ptr unsafe.Pointer
  403. var salen _Socklen
  404. if to != nil {
  405. ptr, salen, err = to.sockaddr()
  406. if err != nil {
  407. return 0, err
  408. }
  409. }
  410. return sendmsgN(fd, iov, oob, ptr, salen, flags)
  411. }
  412. func Send(s int, buf []byte, flags int) (err error) {
  413. return sendto(s, buf, flags, nil, 0)
  414. }
  415. func Sendto(fd int, p []byte, flags int, to Sockaddr) (err error) {
  416. var ptr unsafe.Pointer
  417. var salen _Socklen
  418. if to != nil {
  419. ptr, salen, err = to.sockaddr()
  420. if err != nil {
  421. return err
  422. }
  423. }
  424. return sendto(fd, p, flags, ptr, salen)
  425. }
  426. func SetsockoptByte(fd, level, opt int, value byte) (err error) {
  427. return setsockopt(fd, level, opt, unsafe.Pointer(&value), 1)
  428. }
  429. func SetsockoptInt(fd, level, opt int, value int) (err error) {
  430. var n = int32(value)
  431. return setsockopt(fd, level, opt, unsafe.Pointer(&n), 4)
  432. }
  433. func SetsockoptInet4Addr(fd, level, opt int, value [4]byte) (err error) {
  434. return setsockopt(fd, level, opt, unsafe.Pointer(&value[0]), 4)
  435. }
  436. func SetsockoptIPMreq(fd, level, opt int, mreq *IPMreq) (err error) {
  437. return setsockopt(fd, level, opt, unsafe.Pointer(mreq), SizeofIPMreq)
  438. }
  439. func SetsockoptIPv6Mreq(fd, level, opt int, mreq *IPv6Mreq) (err error) {
  440. return setsockopt(fd, level, opt, unsafe.Pointer(mreq), SizeofIPv6Mreq)
  441. }
  442. func SetsockoptICMPv6Filter(fd, level, opt int, filter *ICMPv6Filter) error {
  443. return setsockopt(fd, level, opt, unsafe.Pointer(filter), SizeofICMPv6Filter)
  444. }
  445. func SetsockoptLinger(fd, level, opt int, l *Linger) (err error) {
  446. return setsockopt(fd, level, opt, unsafe.Pointer(l), SizeofLinger)
  447. }
  448. func SetsockoptString(fd, level, opt int, s string) (err error) {
  449. var p unsafe.Pointer
  450. if len(s) > 0 {
  451. p = unsafe.Pointer(&[]byte(s)[0])
  452. }
  453. return setsockopt(fd, level, opt, p, uintptr(len(s)))
  454. }
  455. func SetsockoptTimeval(fd, level, opt int, tv *Timeval) (err error) {
  456. return setsockopt(fd, level, opt, unsafe.Pointer(tv), unsafe.Sizeof(*tv))
  457. }
  458. func SetsockoptUint64(fd, level, opt int, value uint64) (err error) {
  459. return setsockopt(fd, level, opt, unsafe.Pointer(&value), 8)
  460. }
  461. func Socket(domain, typ, proto int) (fd int, err error) {
  462. if domain == AF_INET6 && SocketDisableIPv6 {
  463. return -1, EAFNOSUPPORT
  464. }
  465. fd, err = socket(domain, typ, proto)
  466. return
  467. }
  468. func Socketpair(domain, typ, proto int) (fd [2]int, err error) {
  469. var fdx [2]int32
  470. err = socketpair(domain, typ, proto, &fdx)
  471. if err == nil {
  472. fd[0] = int(fdx[0])
  473. fd[1] = int(fdx[1])
  474. }
  475. return
  476. }
  477. var ioSync int64
  478. func CloseOnExec(fd int) { fcntl(fd, F_SETFD, FD_CLOEXEC) }
  479. func SetNonblock(fd int, nonblocking bool) (err error) {
  480. flag, err := fcntl(fd, F_GETFL, 0)
  481. if err != nil {
  482. return err
  483. }
  484. if (flag&O_NONBLOCK != 0) == nonblocking {
  485. return nil
  486. }
  487. if nonblocking {
  488. flag |= O_NONBLOCK
  489. } else {
  490. flag &= ^O_NONBLOCK
  491. }
  492. _, err = fcntl(fd, F_SETFL, flag)
  493. return err
  494. }
  495. // Exec calls execve(2), which replaces the calling executable in the process
  496. // tree. argv0 should be the full path to an executable ("/bin/ls") and the
  497. // executable name should also be the first argument in argv (["ls", "-l"]).
  498. // envv are the environment variables that should be passed to the new
  499. // process (["USER=go", "PWD=/tmp"]).
  500. func Exec(argv0 string, argv []string, envv []string) error {
  501. return syscall.Exec(argv0, argv, envv)
  502. }
  503. // Lutimes sets the access and modification times tv on path. If path refers to
  504. // a symlink, it is not dereferenced and the timestamps are set on the symlink.
  505. // If tv is nil, the access and modification times are set to the current time.
  506. // Otherwise tv must contain exactly 2 elements, with access time as the first
  507. // element and modification time as the second element.
  508. func Lutimes(path string, tv []Timeval) error {
  509. if tv == nil {
  510. return UtimesNanoAt(AT_FDCWD, path, nil, AT_SYMLINK_NOFOLLOW)
  511. }
  512. if len(tv) != 2 {
  513. return EINVAL
  514. }
  515. ts := []Timespec{
  516. NsecToTimespec(TimevalToNsec(tv[0])),
  517. NsecToTimespec(TimevalToNsec(tv[1])),
  518. }
  519. return UtimesNanoAt(AT_FDCWD, path, ts, AT_SYMLINK_NOFOLLOW)
  520. }
  521. // emptyIovecs reports whether there are no bytes in the slice of Iovec.
  522. func emptyIovecs(iov []Iovec) bool {
  523. for i := range iov {
  524. if iov[i].Len > 0 {
  525. return false
  526. }
  527. }
  528. return true
  529. }
  530. // Setrlimit sets a resource limit.
  531. func Setrlimit(resource int, rlim *Rlimit) error {
  532. // Just call the syscall version, because as of Go 1.21
  533. // it will affect starting a new process.
  534. return syscall.Setrlimit(resource, (*syscall.Rlimit)(rlim))
  535. }