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.
6 // This file is compiled as ordinary Go code,
7 // but it is also input to mksyscall,
8 // which parses the //sys lines and generates system call stubs.
9 // Note that sometimes we use a lowercase //sys name and
10 // wrap it in our own nicer implementation.
25 func Access(path string, mode uint32) (err error) {
26 return Faccessat(AT_FDCWD, path, mode, 0)
29 func Chmod(path string, mode uint32) (err error) {
30 return Fchmodat(AT_FDCWD, path, mode, 0)
33 func Chown(path string, uid int, gid int) (err error) {
34 return Fchownat(AT_FDCWD, path, uid, gid, 0)
37 func Creat(path string, mode uint32) (fd int, err error) {
38 return Open(path, O_CREAT|O_WRONLY|O_TRUNC, mode)
41 //sys FanotifyInit(flags uint, event_f_flags uint) (fd int, err error)
42 //sys fanotifyMark(fd int, flags uint, mask uint64, dirFd int, pathname *byte) (err error)
44 func FanotifyMark(fd int, flags uint, mask uint64, dirFd int, pathname string) (err error) {
46 return fanotifyMark(fd, flags, mask, dirFd, nil)
48 p, err := BytePtrFromString(pathname)
52 return fanotifyMark(fd, flags, mask, dirFd, p)
55 //sys fchmodat(dirfd int, path string, mode uint32) (err error)
57 func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) {
58 // Linux fchmodat doesn't support the flags parameter. Mimick glibc's behavior
59 // and check the flags. Otherwise the mode would be applied to the symlink
60 // destination which is not what the user expects.
61 if flags&^AT_SYMLINK_NOFOLLOW != 0 {
63 } else if flags&AT_SYMLINK_NOFOLLOW != 0 {
66 return fchmodat(dirfd, path, mode)
69 //sys ioctl(fd int, req uint, arg uintptr) (err error)
71 // ioctl itself should not be exposed directly, but additional get/set
72 // functions for specific types are permissible.
74 // IoctlRetInt performs an ioctl operation specified by req on a device
75 // associated with opened file descriptor fd, and returns a non-negative
76 // integer that is returned by the ioctl syscall.
77 func IoctlRetInt(fd int, req uint) (int, error) {
78 ret, _, err := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), 0)
85 func IoctlSetRTCTime(fd int, value *RTCTime) error {
86 err := ioctl(fd, RTC_SET_TIME, uintptr(unsafe.Pointer(value)))
87 runtime.KeepAlive(value)
91 func IoctlSetRTCWkAlrm(fd int, value *RTCWkAlrm) error {
92 err := ioctl(fd, RTC_WKALM_SET, uintptr(unsafe.Pointer(value)))
93 runtime.KeepAlive(value)
97 func IoctlGetUint32(fd int, req uint) (uint32, error) {
99 err := ioctl(fd, req, uintptr(unsafe.Pointer(&value)))
103 func IoctlGetRTCTime(fd int) (*RTCTime, error) {
105 err := ioctl(fd, RTC_RD_TIME, uintptr(unsafe.Pointer(&value)))
109 // IoctlGetWatchdogInfo fetches information about a watchdog device from the
110 // Linux watchdog API. For more information, see:
111 // https://www.kernel.org/doc/html/latest/watchdog/watchdog-api.html.
112 func IoctlGetWatchdogInfo(fd int) (*WatchdogInfo, error) {
113 var value WatchdogInfo
114 err := ioctl(fd, WDIOC_GETSUPPORT, uintptr(unsafe.Pointer(&value)))
118 func IoctlGetRTCWkAlrm(fd int) (*RTCWkAlrm, error) {
120 err := ioctl(fd, RTC_WKALM_RD, uintptr(unsafe.Pointer(&value)))
124 // IoctlFileCloneRange performs an FICLONERANGE ioctl operation to clone the
125 // range of data conveyed in value to the file associated with the file
126 // descriptor destFd. See the ioctl_ficlonerange(2) man page for details.
127 func IoctlFileCloneRange(destFd int, value *FileCloneRange) error {
128 err := ioctl(destFd, FICLONERANGE, uintptr(unsafe.Pointer(value)))
129 runtime.KeepAlive(value)
133 // IoctlFileClone performs an FICLONE ioctl operation to clone the entire file
134 // associated with the file description srcFd to the file associated with the
135 // file descriptor destFd. See the ioctl_ficlone(2) man page for details.
136 func IoctlFileClone(destFd, srcFd int) error {
137 return ioctl(destFd, FICLONE, uintptr(srcFd))
140 // IoctlFileDedupeRange performs an FIDEDUPERANGE ioctl operation to share the
141 // range of data conveyed in value with the file associated with the file
142 // descriptor destFd. See the ioctl_fideduperange(2) man page for details.
143 func IoctlFileDedupeRange(destFd int, value *FileDedupeRange) error {
144 err := ioctl(destFd, FIDEDUPERANGE, uintptr(unsafe.Pointer(value)))
145 runtime.KeepAlive(value)
149 // IoctlWatchdogKeepalive issues a keepalive ioctl to a watchdog device. For
150 // more information, see:
151 // https://www.kernel.org/doc/html/latest/watchdog/watchdog-api.html.
152 func IoctlWatchdogKeepalive(fd int) error {
153 return ioctl(fd, WDIOC_KEEPALIVE, 0)
156 //sys Linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error)
158 func Link(oldpath string, newpath string) (err error) {
159 return Linkat(AT_FDCWD, oldpath, AT_FDCWD, newpath, 0)
162 func Mkdir(path string, mode uint32) (err error) {
163 return Mkdirat(AT_FDCWD, path, mode)
166 func Mknod(path string, mode uint32, dev int) (err error) {
167 return Mknodat(AT_FDCWD, path, mode, dev)
170 func Open(path string, mode int, perm uint32) (fd int, err error) {
171 return openat(AT_FDCWD, path, mode|O_LARGEFILE, perm)
174 //sys openat(dirfd int, path string, flags int, mode uint32) (fd int, err error)
176 func Openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) {
177 return openat(dirfd, path, flags|O_LARGEFILE, mode)
180 //sys openat2(dirfd int, path string, open_how *OpenHow, size int) (fd int, err error)
182 func Openat2(dirfd int, path string, how *OpenHow) (fd int, err error) {
183 return openat2(dirfd, path, how, SizeofOpenHow)
186 //sys ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error)
188 func Ppoll(fds []PollFd, timeout *Timespec, sigmask *Sigset_t) (n int, err error) {
190 return ppoll(nil, 0, timeout, sigmask)
192 return ppoll(&fds[0], len(fds), timeout, sigmask)
195 //sys Readlinkat(dirfd int, path string, buf []byte) (n int, err error)
197 func Readlink(path string, buf []byte) (n int, err error) {
198 return Readlinkat(AT_FDCWD, path, buf)
201 func Rename(oldpath string, newpath string) (err error) {
202 return Renameat(AT_FDCWD, oldpath, AT_FDCWD, newpath)
205 func Rmdir(path string) error {
206 return Unlinkat(AT_FDCWD, path, AT_REMOVEDIR)
209 //sys Symlinkat(oldpath string, newdirfd int, newpath string) (err error)
211 func Symlink(oldpath string, newpath string) (err error) {
212 return Symlinkat(oldpath, AT_FDCWD, newpath)
215 func Unlink(path string) error {
216 return Unlinkat(AT_FDCWD, path, 0)
219 //sys Unlinkat(dirfd int, path string, flags int) (err error)
221 func Utimes(path string, tv []Timeval) error {
223 err := utimensat(AT_FDCWD, path, nil, 0)
227 return utimes(path, nil)
233 ts[0] = NsecToTimespec(TimevalToNsec(tv[0]))
234 ts[1] = NsecToTimespec(TimevalToNsec(tv[1]))
235 err := utimensat(AT_FDCWD, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), 0)
239 return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
242 //sys utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error)
244 func UtimesNano(path string, ts []Timespec) error {
246 err := utimensat(AT_FDCWD, path, nil, 0)
250 return utimes(path, nil)
255 err := utimensat(AT_FDCWD, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), 0)
259 // If the utimensat syscall isn't available (utimensat was added to Linux
260 // in 2.6.22, Released, 8 July 2007) then fall back to utimes
262 for i := 0; i < 2; i++ {
263 tv[i] = NsecToTimeval(TimespecToNsec(ts[i]))
265 return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
268 func UtimesNanoAt(dirfd int, path string, ts []Timespec, flags int) error {
270 return utimensat(dirfd, path, nil, flags)
275 return utimensat(dirfd, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), flags)
278 func Futimesat(dirfd int, path string, tv []Timeval) error {
280 return futimesat(dirfd, path, nil)
285 return futimesat(dirfd, path, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
288 func Futimes(fd int, tv []Timeval) (err error) {
289 // Believe it or not, this is the best we can do on Linux
290 // (and is what glibc does).
291 return Utimes("/proc/self/fd/"+itoa(fd), tv)
294 const ImplementsGetwd = true
296 //sys Getcwd(buf []byte) (n int, err error)
298 func Getwd() (wd string, err error) {
299 var buf [PathMax]byte
300 n, err := Getcwd(buf[0:])
304 // Getcwd returns the number of bytes written to buf, including the NUL.
305 if n < 1 || n > len(buf) || buf[n-1] != 0 {
308 return string(buf[0 : n-1]), nil
311 func Getgroups() (gids []int, err error) {
312 n, err := getgroups(0, nil)
320 // Sanity check group count. Max is 1<<16 on Linux.
321 if n < 0 || n > 1<<20 {
325 a := make([]_Gid_t, n)
326 n, err = getgroups(n, &a[0])
330 gids = make([]int, n)
331 for i, v := range a[0:n] {
337 func Setgroups(gids []int) (err error) {
339 return setgroups(0, nil)
342 a := make([]_Gid_t, len(gids))
343 for i, v := range gids {
346 return setgroups(len(a), &a[0])
349 type WaitStatus uint32
351 // Wait status is 7 bits at bottom, either 0 (exited),
352 // 0x7F (stopped), or a signal number that caused an exit.
353 // The 0x80 bit is whether there was a core dump.
354 // An extra number (exit code, signal causing a stop)
355 // is in the high bits. At least that's the idea.
356 // There are various irregularities. For example, the
357 // "continued" status is 0xFFFF, distinguishing itself
358 // from stopped via the core dump bit.
368 func (w WaitStatus) Exited() bool { return w&mask == exited }
370 func (w WaitStatus) Signaled() bool { return w&mask != stopped && w&mask != exited }
372 func (w WaitStatus) Stopped() bool { return w&0xFF == stopped }
374 func (w WaitStatus) Continued() bool { return w == 0xFFFF }
376 func (w WaitStatus) CoreDump() bool { return w.Signaled() && w&core != 0 }
378 func (w WaitStatus) ExitStatus() int {
382 return int(w>>shift) & 0xFF
385 func (w WaitStatus) Signal() syscall.Signal {
389 return syscall.Signal(w & mask)
392 func (w WaitStatus) StopSignal() syscall.Signal {
396 return syscall.Signal(w>>shift) & 0xFF
399 func (w WaitStatus) TrapCause() int {
400 if w.StopSignal() != SIGTRAP {
403 return int(w>>shift) >> 8
406 //sys wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error)
408 func Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, err error) {
410 wpid, err = wait4(pid, &status, options, rusage)
412 *wstatus = WaitStatus(status)
417 func Mkfifo(path string, mode uint32) error {
418 return Mknod(path, mode|S_IFIFO, 0)
421 func Mkfifoat(dirfd int, path string, mode uint32) error {
422 return Mknodat(dirfd, path, mode|S_IFIFO, 0)
425 func (sa *SockaddrInet4) sockaddr() (unsafe.Pointer, _Socklen, error) {
426 if sa.Port < 0 || sa.Port > 0xFFFF {
427 return nil, 0, EINVAL
429 sa.raw.Family = AF_INET
430 p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port))
431 p[0] = byte(sa.Port >> 8)
433 for i := 0; i < len(sa.Addr); i++ {
434 sa.raw.Addr[i] = sa.Addr[i]
436 return unsafe.Pointer(&sa.raw), SizeofSockaddrInet4, nil
439 func (sa *SockaddrInet6) sockaddr() (unsafe.Pointer, _Socklen, error) {
440 if sa.Port < 0 || sa.Port > 0xFFFF {
441 return nil, 0, EINVAL
443 sa.raw.Family = AF_INET6
444 p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port))
445 p[0] = byte(sa.Port >> 8)
447 sa.raw.Scope_id = sa.ZoneId
448 for i := 0; i < len(sa.Addr); i++ {
449 sa.raw.Addr[i] = sa.Addr[i]
451 return unsafe.Pointer(&sa.raw), SizeofSockaddrInet6, nil
454 func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, _Socklen, error) {
457 if n >= len(sa.raw.Path) {
458 return nil, 0, EINVAL
460 sa.raw.Family = AF_UNIX
461 for i := 0; i < n; i++ {
462 sa.raw.Path[i] = int8(name[i])
464 // length is family (uint16), name, NUL.
467 sl += _Socklen(n) + 1
469 if sa.raw.Path[0] == '@' {
471 // Don't count trailing NUL for abstract address.
475 return unsafe.Pointer(&sa.raw), sl, nil
478 // SockaddrLinklayer implements the Sockaddr interface for AF_PACKET type sockets.
479 type SockaddrLinklayer struct {
486 raw RawSockaddrLinklayer
489 func (sa *SockaddrLinklayer) sockaddr() (unsafe.Pointer, _Socklen, error) {
490 if sa.Ifindex < 0 || sa.Ifindex > 0x7fffffff {
491 return nil, 0, EINVAL
493 sa.raw.Family = AF_PACKET
494 sa.raw.Protocol = sa.Protocol
495 sa.raw.Ifindex = int32(sa.Ifindex)
496 sa.raw.Hatype = sa.Hatype
497 sa.raw.Pkttype = sa.Pkttype
498 sa.raw.Halen = sa.Halen
499 for i := 0; i < len(sa.Addr); i++ {
500 sa.raw.Addr[i] = sa.Addr[i]
502 return unsafe.Pointer(&sa.raw), SizeofSockaddrLinklayer, nil
505 // SockaddrNetlink implements the Sockaddr interface for AF_NETLINK type sockets.
506 type SockaddrNetlink struct {
511 raw RawSockaddrNetlink
514 func (sa *SockaddrNetlink) sockaddr() (unsafe.Pointer, _Socklen, error) {
515 sa.raw.Family = AF_NETLINK
518 sa.raw.Groups = sa.Groups
519 return unsafe.Pointer(&sa.raw), SizeofSockaddrNetlink, nil
522 // SockaddrHCI implements the Sockaddr interface for AF_BLUETOOTH type sockets
523 // using the HCI protocol.
524 type SockaddrHCI struct {
530 func (sa *SockaddrHCI) sockaddr() (unsafe.Pointer, _Socklen, error) {
531 sa.raw.Family = AF_BLUETOOTH
533 sa.raw.Channel = sa.Channel
534 return unsafe.Pointer(&sa.raw), SizeofSockaddrHCI, nil
537 // SockaddrL2 implements the Sockaddr interface for AF_BLUETOOTH type sockets
538 // using the L2CAP protocol.
539 type SockaddrL2 struct {
547 func (sa *SockaddrL2) sockaddr() (unsafe.Pointer, _Socklen, error) {
548 sa.raw.Family = AF_BLUETOOTH
549 psm := (*[2]byte)(unsafe.Pointer(&sa.raw.Psm))
550 psm[0] = byte(sa.PSM)
551 psm[1] = byte(sa.PSM >> 8)
552 for i := 0; i < len(sa.Addr); i++ {
553 sa.raw.Bdaddr[i] = sa.Addr[len(sa.Addr)-1-i]
555 cid := (*[2]byte)(unsafe.Pointer(&sa.raw.Cid))
556 cid[0] = byte(sa.CID)
557 cid[1] = byte(sa.CID >> 8)
558 sa.raw.Bdaddr_type = sa.AddrType
559 return unsafe.Pointer(&sa.raw), SizeofSockaddrL2, nil
562 // SockaddrRFCOMM implements the Sockaddr interface for AF_BLUETOOTH type sockets
563 // using the RFCOMM protocol.
567 // fd, _ := Socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM)
568 // _ = unix.Bind(fd, &unix.SockaddrRFCOMM{
570 // Addr: [6]uint8{0, 0, 0, 0, 0, 0}, // BDADDR_ANY or 00:00:00:00:00:00
573 // nfd, sa, _ := Accept(fd)
574 // fmt.Printf("conn addr=%v fd=%d", sa.(*unix.SockaddrRFCOMM).Addr, nfd)
579 // fd, _ := Socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM)
580 // _ = Connect(fd, &SockaddrRFCOMM{
582 // Addr: [6]byte{0x11, 0x22, 0x33, 0xaa, 0xbb, 0xcc}, // CC:BB:AA:33:22:11
584 // Write(fd, []byte(`hello`))
585 type SockaddrRFCOMM struct {
586 // Addr represents a bluetooth address, byte ordering is little-endian.
589 // Channel is a designated bluetooth channel, only 1-30 are available for use.
590 // Since Linux 2.6.7 and further zero value is the first available channel.
593 raw RawSockaddrRFCOMM
596 func (sa *SockaddrRFCOMM) sockaddr() (unsafe.Pointer, _Socklen, error) {
597 sa.raw.Family = AF_BLUETOOTH
598 sa.raw.Channel = sa.Channel
599 sa.raw.Bdaddr = sa.Addr
600 return unsafe.Pointer(&sa.raw), SizeofSockaddrRFCOMM, nil
603 // SockaddrCAN implements the Sockaddr interface for AF_CAN type sockets.
604 // The RxID and TxID fields are used for transport protocol addressing in
605 // (CAN_TP16, CAN_TP20, CAN_MCNET, and CAN_ISOTP), they can be left with
606 // zero values for CAN_RAW and CAN_BCM sockets as they have no meaning.
608 // The SockaddrCAN struct must be bound to the socket file descriptor
609 // using Bind before the CAN socket can be used.
611 // // Read one raw CAN frame
612 // fd, _ := Socket(AF_CAN, SOCK_RAW, CAN_RAW)
613 // addr := &SockaddrCAN{Ifindex: index}
615 // frame := make([]byte, 16)
618 // The full SocketCAN documentation can be found in the linux kernel
619 // archives at: https://www.kernel.org/doc/Documentation/networking/can.txt
620 type SockaddrCAN struct {
627 func (sa *SockaddrCAN) sockaddr() (unsafe.Pointer, _Socklen, error) {
628 if sa.Ifindex < 0 || sa.Ifindex > 0x7fffffff {
629 return nil, 0, EINVAL
631 sa.raw.Family = AF_CAN
632 sa.raw.Ifindex = int32(sa.Ifindex)
633 rx := (*[4]byte)(unsafe.Pointer(&sa.RxID))
634 for i := 0; i < 4; i++ {
635 sa.raw.Addr[i] = rx[i]
637 tx := (*[4]byte)(unsafe.Pointer(&sa.TxID))
638 for i := 0; i < 4; i++ {
639 sa.raw.Addr[i+4] = tx[i]
641 return unsafe.Pointer(&sa.raw), SizeofSockaddrCAN, nil
644 // SockaddrCANJ1939 implements the Sockaddr interface for AF_CAN using J1939
645 // protocol (https://en.wikipedia.org/wiki/SAE_J1939). For more information
646 // on the purposes of the fields, check the official linux kernel documentation
647 // available here: https://www.kernel.org/doc/Documentation/networking/j1939.rst
648 type SockaddrCANJ1939 struct {
656 func (sa *SockaddrCANJ1939) sockaddr() (unsafe.Pointer, _Socklen, error) {
657 if sa.Ifindex < 0 || sa.Ifindex > 0x7fffffff {
658 return nil, 0, EINVAL
660 sa.raw.Family = AF_CAN
661 sa.raw.Ifindex = int32(sa.Ifindex)
662 n := (*[8]byte)(unsafe.Pointer(&sa.Name))
663 for i := 0; i < 8; i++ {
664 sa.raw.Addr[i] = n[i]
666 p := (*[4]byte)(unsafe.Pointer(&sa.PGN))
667 for i := 0; i < 4; i++ {
668 sa.raw.Addr[i+8] = p[i]
670 sa.raw.Addr[12] = sa.Addr
671 return unsafe.Pointer(&sa.raw), SizeofSockaddrCAN, nil
674 // SockaddrALG implements the Sockaddr interface for AF_ALG type sockets.
675 // SockaddrALG enables userspace access to the Linux kernel's cryptography
676 // subsystem. The Type and Name fields specify which type of hash or cipher
677 // should be used with a given socket.
679 // To create a file descriptor that provides access to a hash or cipher, both
680 // Bind and Accept must be used. Once the setup process is complete, input
681 // data can be written to the socket, processed by the kernel, and then read
682 // back as hash output or ciphertext.
684 // Here is an example of using an AF_ALG socket with SHA1 hashing.
685 // The initial socket setup process is as follows:
687 // // Open a socket to perform SHA1 hashing.
688 // fd, _ := unix.Socket(unix.AF_ALG, unix.SOCK_SEQPACKET, 0)
689 // addr := &unix.SockaddrALG{Type: "hash", Name: "sha1"}
690 // unix.Bind(fd, addr)
691 // // Note: unix.Accept does not work at this time; must invoke accept()
692 // // manually using unix.Syscall.
693 // hashfd, _, _ := unix.Syscall(unix.SYS_ACCEPT, uintptr(fd), 0, 0)
695 // Once a file descriptor has been returned from Accept, it may be used to
696 // perform SHA1 hashing. The descriptor is not safe for concurrent use, but
697 // may be re-used repeatedly with subsequent Write and Read operations.
699 // When hashing a small byte slice or string, a single Write and Read may
702 // // Assume hashfd is already configured using the setup process.
703 // hash := os.NewFile(hashfd, "sha1")
704 // // Hash an input string and read the results. Each Write discards
705 // // previous hash state. Read always reads the current state.
706 // b := make([]byte, 20)
707 // for i := 0; i < 2; i++ {
708 // io.WriteString(hash, "Hello, world.")
710 // fmt.Println(hex.EncodeToString(b))
713 // // 2ae01472317d1935a84797ec1983ae243fc6aa28
714 // // 2ae01472317d1935a84797ec1983ae243fc6aa28
716 // For hashing larger byte slices, or byte streams such as those read from
717 // a file or socket, use Sendto with MSG_MORE to instruct the kernel to update
718 // the hash digest instead of creating a new one for a given chunk and finalizing it.
720 // // Assume hashfd and addr are already configured using the setup process.
721 // hash := os.NewFile(hashfd, "sha1")
722 // // Hash the contents of a file.
723 // f, _ := os.Open("/tmp/linux-4.10-rc7.tar.xz")
724 // b := make([]byte, 4096)
726 // n, err := f.Read(b)
727 // if err == io.EOF {
730 // unix.Sendto(hashfd, b[:n], unix.MSG_MORE, addr)
733 // fmt.Println(hex.EncodeToString(b))
734 // // Output: 85cdcad0c06eef66f805ecce353bec9accbeecc5
736 // For more information, see: http://www.chronox.de/crypto-API/crypto/userspace-if.html.
737 type SockaddrALG struct {
745 func (sa *SockaddrALG) sockaddr() (unsafe.Pointer, _Socklen, error) {
746 // Leave room for NUL byte terminator.
747 if len(sa.Type) > 13 {
748 return nil, 0, EINVAL
750 if len(sa.Name) > 63 {
751 return nil, 0, EINVAL
754 sa.raw.Family = AF_ALG
755 sa.raw.Feat = sa.Feature
756 sa.raw.Mask = sa.Mask
758 typ, err := ByteSliceFromString(sa.Type)
762 name, err := ByteSliceFromString(sa.Name)
767 copy(sa.raw.Type[:], typ)
768 copy(sa.raw.Name[:], name)
770 return unsafe.Pointer(&sa.raw), SizeofSockaddrALG, nil
773 // SockaddrVM implements the Sockaddr interface for AF_VSOCK type sockets.
774 // SockaddrVM provides access to Linux VM sockets: a mechanism that enables
775 // bidirectional communication between a hypervisor and its guest virtual
777 type SockaddrVM struct {
778 // CID and Port specify a context ID and port address for a VM socket.
779 // Guests have a unique CID, and hosts may have a well-known CID of:
780 // - VMADDR_CID_HYPERVISOR: refers to the hypervisor process.
781 // - VMADDR_CID_HOST: refers to other processes on the host.
787 func (sa *SockaddrVM) sockaddr() (unsafe.Pointer, _Socklen, error) {
788 sa.raw.Family = AF_VSOCK
789 sa.raw.Port = sa.Port
792 return unsafe.Pointer(&sa.raw), SizeofSockaddrVM, nil
795 type SockaddrXDP struct {
803 func (sa *SockaddrXDP) sockaddr() (unsafe.Pointer, _Socklen, error) {
804 sa.raw.Family = AF_XDP
805 sa.raw.Flags = sa.Flags
806 sa.raw.Ifindex = sa.Ifindex
807 sa.raw.Queue_id = sa.QueueID
808 sa.raw.Shared_umem_fd = sa.SharedUmemFD
810 return unsafe.Pointer(&sa.raw), SizeofSockaddrXDP, nil
813 // This constant mirrors the #define of PX_PROTO_OE in
814 // linux/if_pppox.h. We're defining this by hand here instead of
815 // autogenerating through mkerrors.sh because including
816 // linux/if_pppox.h causes some declaration conflicts with other
817 // includes (linux/if_pppox.h includes linux/in.h, which conflicts
818 // with netinet/in.h). Given that we only need a single zero constant
819 // out of that file, it's cleaner to just define it by hand here.
820 const px_proto_oe = 0
822 type SockaddrPPPoE struct {
829 func (sa *SockaddrPPPoE) sockaddr() (unsafe.Pointer, _Socklen, error) {
830 if len(sa.Remote) != 6 {
831 return nil, 0, EINVAL
833 if len(sa.Dev) > IFNAMSIZ-1 {
834 return nil, 0, EINVAL
837 *(*uint16)(unsafe.Pointer(&sa.raw[0])) = AF_PPPOX
838 // This next field is in host-endian byte order. We can't use the
839 // same unsafe pointer cast as above, because this value is not
840 // 32-bit aligned and some architectures don't allow unaligned
843 // However, the value of px_proto_oe is 0, so we can use
844 // encoding/binary helpers to write the bytes without worrying
845 // about the ordering.
846 binary.BigEndian.PutUint32(sa.raw[2:6], px_proto_oe)
847 // This field is deliberately big-endian, unlike the previous
848 // one. The kernel expects SID to be in network byte order.
849 binary.BigEndian.PutUint16(sa.raw[6:8], sa.SID)
850 copy(sa.raw[8:14], sa.Remote)
851 for i := 14; i < 14+IFNAMSIZ; i++ {
854 copy(sa.raw[14:], sa.Dev)
855 return unsafe.Pointer(&sa.raw), SizeofSockaddrPPPoX, nil
858 // SockaddrTIPC implements the Sockaddr interface for AF_TIPC type sockets.
859 // For more information on TIPC, see: http://tipc.sourceforge.net/.
860 type SockaddrTIPC struct {
861 // Scope is the publication scopes when binding service/service range.
862 // Should be set to TIPC_CLUSTER_SCOPE or TIPC_NODE_SCOPE.
865 // Addr is the type of address used to manipulate a socket. Addr must be
867 // - *TIPCSocketAddr: "id" variant in the C addr union
868 // - *TIPCServiceRange: "nameseq" variant in the C addr union
869 // - *TIPCServiceName: "name" variant in the C addr union
871 // If nil, EINVAL will be returned when the structure is used.
877 // TIPCAddr is implemented by types that can be used as an address for
878 // SockaddrTIPC. It is only implemented by *TIPCSocketAddr, *TIPCServiceRange,
879 // and *TIPCServiceName.
880 type TIPCAddr interface {
885 func (sa *TIPCSocketAddr) tipcAddr() [12]byte {
887 copy(out[:], (*(*[unsafe.Sizeof(TIPCSocketAddr{})]byte)(unsafe.Pointer(sa)))[:])
891 func (sa *TIPCSocketAddr) tipcAddrtype() uint8 { return TIPC_SOCKET_ADDR }
893 func (sa *TIPCServiceRange) tipcAddr() [12]byte {
895 copy(out[:], (*(*[unsafe.Sizeof(TIPCServiceRange{})]byte)(unsafe.Pointer(sa)))[:])
899 func (sa *TIPCServiceRange) tipcAddrtype() uint8 { return TIPC_SERVICE_RANGE }
901 func (sa *TIPCServiceName) tipcAddr() [12]byte {
903 copy(out[:], (*(*[unsafe.Sizeof(TIPCServiceName{})]byte)(unsafe.Pointer(sa)))[:])
907 func (sa *TIPCServiceName) tipcAddrtype() uint8 { return TIPC_SERVICE_ADDR }
909 func (sa *SockaddrTIPC) sockaddr() (unsafe.Pointer, _Socklen, error) {
911 return nil, 0, EINVAL
914 sa.raw.Family = AF_TIPC
915 sa.raw.Scope = int8(sa.Scope)
916 sa.raw.Addrtype = sa.Addr.tipcAddrtype()
917 sa.raw.Addr = sa.Addr.tipcAddr()
919 return unsafe.Pointer(&sa.raw), SizeofSockaddrTIPC, nil
922 // SockaddrL2TPIP implements the Sockaddr interface for IPPROTO_L2TP/AF_INET sockets.
923 type SockaddrL2TPIP struct {
926 raw RawSockaddrL2TPIP
929 func (sa *SockaddrL2TPIP) sockaddr() (unsafe.Pointer, _Socklen, error) {
930 sa.raw.Family = AF_INET
931 sa.raw.Conn_id = sa.ConnId
932 for i := 0; i < len(sa.Addr); i++ {
933 sa.raw.Addr[i] = sa.Addr[i]
935 return unsafe.Pointer(&sa.raw), SizeofSockaddrL2TPIP, nil
938 // SockaddrL2TPIP6 implements the Sockaddr interface for IPPROTO_L2TP/AF_INET6 sockets.
939 type SockaddrL2TPIP6 struct {
943 raw RawSockaddrL2TPIP6
946 func (sa *SockaddrL2TPIP6) sockaddr() (unsafe.Pointer, _Socklen, error) {
947 sa.raw.Family = AF_INET6
948 sa.raw.Conn_id = sa.ConnId
949 sa.raw.Scope_id = sa.ZoneId
950 for i := 0; i < len(sa.Addr); i++ {
951 sa.raw.Addr[i] = sa.Addr[i]
953 return unsafe.Pointer(&sa.raw), SizeofSockaddrL2TPIP6, nil
956 // SockaddrIUCV implements the Sockaddr interface for AF_IUCV sockets.
957 type SockaddrIUCV struct {
963 func (sa *SockaddrIUCV) sockaddr() (unsafe.Pointer, _Socklen, error) {
964 sa.raw.Family = AF_IUCV
965 // These are EBCDIC encoded by the kernel, but we still need to pad them
966 // with blanks. Initializing with blanks allows the caller to feed in either
967 // a padded or an unpadded string.
968 for i := 0; i < 8; i++ {
969 sa.raw.Nodeid[i] = ' '
970 sa.raw.User_id[i] = ' '
973 if len(sa.UserID) > 8 || len(sa.Name) > 8 {
974 return nil, 0, EINVAL
976 for i, b := range []byte(sa.UserID[:]) {
977 sa.raw.User_id[i] = int8(b)
979 for i, b := range []byte(sa.Name[:]) {
980 sa.raw.Name[i] = int8(b)
982 return unsafe.Pointer(&sa.raw), SizeofSockaddrIUCV, nil
985 var socketProtocol = func(fd int) (int, error) {
986 return GetsockoptInt(fd, SOL_SOCKET, SO_PROTOCOL)
989 func anyToSockaddr(fd int, rsa *RawSockaddrAny) (Sockaddr, error) {
990 switch rsa.Addr.Family {
992 pp := (*RawSockaddrNetlink)(unsafe.Pointer(rsa))
993 sa := new(SockaddrNetlink)
994 sa.Family = pp.Family
997 sa.Groups = pp.Groups
1001 pp := (*RawSockaddrLinklayer)(unsafe.Pointer(rsa))
1002 sa := new(SockaddrLinklayer)
1003 sa.Protocol = pp.Protocol
1004 sa.Ifindex = int(pp.Ifindex)
1005 sa.Hatype = pp.Hatype
1006 sa.Pkttype = pp.Pkttype
1008 for i := 0; i < len(sa.Addr); i++ {
1009 sa.Addr[i] = pp.Addr[i]
1014 pp := (*RawSockaddrUnix)(unsafe.Pointer(rsa))
1015 sa := new(SockaddrUnix)
1016 if pp.Path[0] == 0 {
1017 // "Abstract" Unix domain socket.
1018 // Rewrite leading NUL as @ for textual display.
1019 // (This is the standard convention.)
1020 // Not friendly to overwrite in place,
1021 // but the callers below don't care.
1025 // Assume path ends at NUL.
1026 // This is not technically the Linux semantics for
1027 // abstract Unix domain sockets--they are supposed
1028 // to be uninterpreted fixed-size binary blobs--but
1029 // everyone uses this convention.
1031 for n < len(pp.Path) && pp.Path[n] != 0 {
1034 bytes := (*[len(pp.Path)]byte)(unsafe.Pointer(&pp.Path[0]))[0:n]
1035 sa.Name = string(bytes)
1039 proto, err := socketProtocol(fd)
1046 pp := (*RawSockaddrL2TPIP)(unsafe.Pointer(rsa))
1047 sa := new(SockaddrL2TPIP)
1048 sa.ConnId = pp.Conn_id
1049 for i := 0; i < len(sa.Addr); i++ {
1050 sa.Addr[i] = pp.Addr[i]
1054 pp := (*RawSockaddrInet4)(unsafe.Pointer(rsa))
1055 sa := new(SockaddrInet4)
1056 p := (*[2]byte)(unsafe.Pointer(&pp.Port))
1057 sa.Port = int(p[0])<<8 + int(p[1])
1058 for i := 0; i < len(sa.Addr); i++ {
1059 sa.Addr[i] = pp.Addr[i]
1065 proto, err := socketProtocol(fd)
1072 pp := (*RawSockaddrL2TPIP6)(unsafe.Pointer(rsa))
1073 sa := new(SockaddrL2TPIP6)
1074 sa.ConnId = pp.Conn_id
1075 sa.ZoneId = pp.Scope_id
1076 for i := 0; i < len(sa.Addr); i++ {
1077 sa.Addr[i] = pp.Addr[i]
1081 pp := (*RawSockaddrInet6)(unsafe.Pointer(rsa))
1082 sa := new(SockaddrInet6)
1083 p := (*[2]byte)(unsafe.Pointer(&pp.Port))
1084 sa.Port = int(p[0])<<8 + int(p[1])
1085 sa.ZoneId = pp.Scope_id
1086 for i := 0; i < len(sa.Addr); i++ {
1087 sa.Addr[i] = pp.Addr[i]
1093 pp := (*RawSockaddrVM)(unsafe.Pointer(rsa))
1100 proto, err := socketProtocol(fd)
1104 // only BTPROTO_L2CAP and BTPROTO_RFCOMM can accept connections
1107 pp := (*RawSockaddrL2)(unsafe.Pointer(rsa))
1112 AddrType: pp.Bdaddr_type,
1115 case BTPROTO_RFCOMM:
1116 pp := (*RawSockaddrRFCOMM)(unsafe.Pointer(rsa))
1117 sa := &SockaddrRFCOMM{
1118 Channel: pp.Channel,
1124 pp := (*RawSockaddrXDP)(unsafe.Pointer(rsa))
1127 Ifindex: pp.Ifindex,
1128 QueueID: pp.Queue_id,
1129 SharedUmemFD: pp.Shared_umem_fd,
1133 pp := (*RawSockaddrPPPoX)(unsafe.Pointer(rsa))
1134 if binary.BigEndian.Uint32(pp[2:6]) != px_proto_oe {
1137 sa := &SockaddrPPPoE{
1138 SID: binary.BigEndian.Uint16(pp[6:8]),
1141 for i := 14; i < 14+IFNAMSIZ; i++ {
1143 sa.Dev = string(pp[14:i])
1149 pp := (*RawSockaddrTIPC)(unsafe.Pointer(rsa))
1151 sa := &SockaddrTIPC{
1152 Scope: int(pp.Scope),
1155 // Determine which union variant is present in pp.Addr by checking
1157 switch pp.Addrtype {
1158 case TIPC_SERVICE_RANGE:
1159 sa.Addr = (*TIPCServiceRange)(unsafe.Pointer(&pp.Addr))
1160 case TIPC_SERVICE_ADDR:
1161 sa.Addr = (*TIPCServiceName)(unsafe.Pointer(&pp.Addr))
1162 case TIPC_SOCKET_ADDR:
1163 sa.Addr = (*TIPCSocketAddr)(unsafe.Pointer(&pp.Addr))
1170 pp := (*RawSockaddrIUCV)(unsafe.Pointer(rsa))
1175 for i := 0; i < 8; i++ {
1176 user[i] = byte(pp.User_id[i])
1177 name[i] = byte(pp.Name[i])
1180 sa := &SockaddrIUCV{
1181 UserID: string(user[:]),
1182 Name: string(name[:]),
1187 proto, err := socketProtocol(fd)
1192 pp := (*RawSockaddrCAN)(unsafe.Pointer(rsa))
1196 sa := &SockaddrCANJ1939{
1197 Ifindex: int(pp.Ifindex),
1199 name := (*[8]byte)(unsafe.Pointer(&sa.Name))
1200 for i := 0; i < 8; i++ {
1201 name[i] = pp.Addr[i]
1203 pgn := (*[4]byte)(unsafe.Pointer(&sa.PGN))
1204 for i := 0; i < 4; i++ {
1205 pgn[i] = pp.Addr[i+8]
1207 addr := (*[1]byte)(unsafe.Pointer(&sa.Addr))
1208 addr[0] = pp.Addr[12]
1212 Ifindex: int(pp.Ifindex),
1214 rx := (*[4]byte)(unsafe.Pointer(&sa.RxID))
1215 for i := 0; i < 4; i++ {
1218 tx := (*[4]byte)(unsafe.Pointer(&sa.TxID))
1219 for i := 0; i < 4; i++ {
1220 tx[i] = pp.Addr[i+4]
1225 return nil, EAFNOSUPPORT
1228 func Accept(fd int) (nfd int, sa Sockaddr, err error) {
1229 var rsa RawSockaddrAny
1230 var len _Socklen = SizeofSockaddrAny
1231 nfd, err = accept(fd, &rsa, &len)
1235 sa, err = anyToSockaddr(fd, &rsa)
1243 func Accept4(fd int, flags int) (nfd int, sa Sockaddr, err error) {
1244 var rsa RawSockaddrAny
1245 var len _Socklen = SizeofSockaddrAny
1246 nfd, err = accept4(fd, &rsa, &len, flags)
1250 if len > SizeofSockaddrAny {
1251 panic("RawSockaddrAny too small")
1253 sa, err = anyToSockaddr(fd, &rsa)
1261 func Getsockname(fd int) (sa Sockaddr, err error) {
1262 var rsa RawSockaddrAny
1263 var len _Socklen = SizeofSockaddrAny
1264 if err = getsockname(fd, &rsa, &len); err != nil {
1267 return anyToSockaddr(fd, &rsa)
1270 func GetsockoptIPMreqn(fd, level, opt int) (*IPMreqn, error) {
1272 vallen := _Socklen(SizeofIPMreqn)
1273 err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
1277 func GetsockoptUcred(fd, level, opt int) (*Ucred, error) {
1279 vallen := _Socklen(SizeofUcred)
1280 err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
1284 func GetsockoptTCPInfo(fd, level, opt int) (*TCPInfo, error) {
1286 vallen := _Socklen(SizeofTCPInfo)
1287 err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
1291 // GetsockoptString returns the string value of the socket option opt for the
1292 // socket associated with fd at the given socket level.
1293 func GetsockoptString(fd, level, opt int) (string, error) {
1294 buf := make([]byte, 256)
1295 vallen := _Socklen(len(buf))
1296 err := getsockopt(fd, level, opt, unsafe.Pointer(&buf[0]), &vallen)
1299 buf = make([]byte, vallen)
1300 err = getsockopt(fd, level, opt, unsafe.Pointer(&buf[0]), &vallen)
1306 return string(buf[:vallen-1]), nil
1309 func GetsockoptTpacketStats(fd, level, opt int) (*TpacketStats, error) {
1310 var value TpacketStats
1311 vallen := _Socklen(SizeofTpacketStats)
1312 err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
1316 func GetsockoptTpacketStatsV3(fd, level, opt int) (*TpacketStatsV3, error) {
1317 var value TpacketStatsV3
1318 vallen := _Socklen(SizeofTpacketStatsV3)
1319 err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
1323 func SetsockoptIPMreqn(fd, level, opt int, mreq *IPMreqn) (err error) {
1324 return setsockopt(fd, level, opt, unsafe.Pointer(mreq), unsafe.Sizeof(*mreq))
1327 func SetsockoptPacketMreq(fd, level, opt int, mreq *PacketMreq) error {
1328 return setsockopt(fd, level, opt, unsafe.Pointer(mreq), unsafe.Sizeof(*mreq))
1331 // SetsockoptSockFprog attaches a classic BPF or an extended BPF program to a
1332 // socket to filter incoming packets. See 'man 7 socket' for usage information.
1333 func SetsockoptSockFprog(fd, level, opt int, fprog *SockFprog) error {
1334 return setsockopt(fd, level, opt, unsafe.Pointer(fprog), unsafe.Sizeof(*fprog))
1337 func SetsockoptCanRawFilter(fd, level, opt int, filter []CanFilter) error {
1338 var p unsafe.Pointer
1339 if len(filter) > 0 {
1340 p = unsafe.Pointer(&filter[0])
1342 return setsockopt(fd, level, opt, p, uintptr(len(filter)*SizeofCanFilter))
1345 func SetsockoptTpacketReq(fd, level, opt int, tp *TpacketReq) error {
1346 return setsockopt(fd, level, opt, unsafe.Pointer(tp), unsafe.Sizeof(*tp))
1349 func SetsockoptTpacketReq3(fd, level, opt int, tp *TpacketReq3) error {
1350 return setsockopt(fd, level, opt, unsafe.Pointer(tp), unsafe.Sizeof(*tp))
1353 // Keyctl Commands (http://man7.org/linux/man-pages/man2/keyctl.2.html)
1355 // KeyctlInt calls keyctl commands in which each argument is an int.
1356 // These commands are KEYCTL_REVOKE, KEYCTL_CHOWN, KEYCTL_CLEAR, KEYCTL_LINK,
1357 // KEYCTL_UNLINK, KEYCTL_NEGATE, KEYCTL_SET_REQKEY_KEYRING, KEYCTL_SET_TIMEOUT,
1358 // KEYCTL_ASSUME_AUTHORITY, KEYCTL_SESSION_TO_PARENT, KEYCTL_REJECT,
1359 // KEYCTL_INVALIDATE, and KEYCTL_GET_PERSISTENT.
1360 //sys KeyctlInt(cmd int, arg2 int, arg3 int, arg4 int, arg5 int) (ret int, err error) = SYS_KEYCTL
1362 // KeyctlBuffer calls keyctl commands in which the third and fourth
1363 // arguments are a buffer and its length, respectively.
1364 // These commands are KEYCTL_UPDATE, KEYCTL_READ, and KEYCTL_INSTANTIATE.
1365 //sys KeyctlBuffer(cmd int, arg2 int, buf []byte, arg5 int) (ret int, err error) = SYS_KEYCTL
1367 // KeyctlString calls keyctl commands which return a string.
1368 // These commands are KEYCTL_DESCRIBE and KEYCTL_GET_SECURITY.
1369 func KeyctlString(cmd int, id int) (string, error) {
1370 // We must loop as the string data may change in between the syscalls.
1371 // We could allocate a large buffer here to reduce the chance that the
1372 // syscall needs to be called twice; however, this is unnecessary as
1373 // the performance loss is negligible.
1376 // Try to fill the buffer with data
1377 length, err := KeyctlBuffer(cmd, id, buffer, 0)
1382 // Check if the data was written
1383 if length <= len(buffer) {
1384 // Exclude the null terminator
1385 return string(buffer[:length-1]), nil
1388 // Make a bigger buffer if needed
1389 buffer = make([]byte, length)
1393 // Keyctl commands with special signatures.
1395 // KeyctlGetKeyringID implements the KEYCTL_GET_KEYRING_ID command.
1396 // See the full documentation at:
1397 // http://man7.org/linux/man-pages/man3/keyctl_get_keyring_ID.3.html
1398 func KeyctlGetKeyringID(id int, create bool) (ringid int, err error) {
1403 return KeyctlInt(KEYCTL_GET_KEYRING_ID, id, createInt, 0, 0)
1406 // KeyctlSetperm implements the KEYCTL_SETPERM command. The perm value is the
1407 // key handle permission mask as described in the "keyctl setperm" section of
1408 // http://man7.org/linux/man-pages/man1/keyctl.1.html.
1409 // See the full documentation at:
1410 // http://man7.org/linux/man-pages/man3/keyctl_setperm.3.html
1411 func KeyctlSetperm(id int, perm uint32) error {
1412 _, err := KeyctlInt(KEYCTL_SETPERM, id, int(perm), 0, 0)
1416 //sys keyctlJoin(cmd int, arg2 string) (ret int, err error) = SYS_KEYCTL
1418 // KeyctlJoinSessionKeyring implements the KEYCTL_JOIN_SESSION_KEYRING command.
1419 // See the full documentation at:
1420 // http://man7.org/linux/man-pages/man3/keyctl_join_session_keyring.3.html
1421 func KeyctlJoinSessionKeyring(name string) (ringid int, err error) {
1422 return keyctlJoin(KEYCTL_JOIN_SESSION_KEYRING, name)
1425 //sys keyctlSearch(cmd int, arg2 int, arg3 string, arg4 string, arg5 int) (ret int, err error) = SYS_KEYCTL
1427 // KeyctlSearch implements the KEYCTL_SEARCH command.
1428 // See the full documentation at:
1429 // http://man7.org/linux/man-pages/man3/keyctl_search.3.html
1430 func KeyctlSearch(ringid int, keyType, description string, destRingid int) (id int, err error) {
1431 return keyctlSearch(KEYCTL_SEARCH, ringid, keyType, description, destRingid)
1434 //sys keyctlIOV(cmd int, arg2 int, payload []Iovec, arg5 int) (err error) = SYS_KEYCTL
1436 // KeyctlInstantiateIOV implements the KEYCTL_INSTANTIATE_IOV command. This
1437 // command is similar to KEYCTL_INSTANTIATE, except that the payload is a slice
1438 // of Iovec (each of which represents a buffer) instead of a single buffer.
1439 // See the full documentation at:
1440 // http://man7.org/linux/man-pages/man3/keyctl_instantiate_iov.3.html
1441 func KeyctlInstantiateIOV(id int, payload []Iovec, ringid int) error {
1442 return keyctlIOV(KEYCTL_INSTANTIATE_IOV, id, payload, ringid)
1445 //sys keyctlDH(cmd int, arg2 *KeyctlDHParams, buf []byte) (ret int, err error) = SYS_KEYCTL
1447 // KeyctlDHCompute implements the KEYCTL_DH_COMPUTE command. This command
1448 // computes a Diffie-Hellman shared secret based on the provide params. The
1449 // secret is written to the provided buffer and the returned size is the number
1450 // of bytes written (returning an error if there is insufficient space in the
1451 // buffer). If a nil buffer is passed in, this function returns the minimum
1452 // buffer length needed to store the appropriate data. Note that this differs
1453 // from KEYCTL_READ's behavior which always returns the requested payload size.
1454 // See the full documentation at:
1455 // http://man7.org/linux/man-pages/man3/keyctl_dh_compute.3.html
1456 func KeyctlDHCompute(params *KeyctlDHParams, buffer []byte) (size int, err error) {
1457 return keyctlDH(KEYCTL_DH_COMPUTE, params, buffer)
1460 // KeyctlRestrictKeyring implements the KEYCTL_RESTRICT_KEYRING command. This
1461 // command limits the set of keys that can be linked to the keyring, regardless
1462 // of keyring permissions. The command requires the "setattr" permission.
1464 // When called with an empty keyType the command locks the keyring, preventing
1465 // any further keys from being linked to the keyring.
1467 // The "asymmetric" keyType defines restrictions requiring key payloads to be
1468 // DER encoded X.509 certificates signed by keys in another keyring. Restrictions
1469 // for "asymmetric" include "builtin_trusted", "builtin_and_secondary_trusted",
1470 // "key_or_keyring:<key>", and "key_or_keyring:<key>:chain".
1472 // As of Linux 4.12, only the "asymmetric" keyType defines type-specific
1475 // See the full documentation at:
1476 // http://man7.org/linux/man-pages/man3/keyctl_restrict_keyring.3.html
1477 // http://man7.org/linux/man-pages/man2/keyctl.2.html
1478 func KeyctlRestrictKeyring(ringid int, keyType string, restriction string) error {
1480 return keyctlRestrictKeyring(KEYCTL_RESTRICT_KEYRING, ringid)
1482 return keyctlRestrictKeyringByType(KEYCTL_RESTRICT_KEYRING, ringid, keyType, restriction)
1485 //sys keyctlRestrictKeyringByType(cmd int, arg2 int, keyType string, restriction string) (err error) = SYS_KEYCTL
1486 //sys keyctlRestrictKeyring(cmd int, arg2 int) (err error) = SYS_KEYCTL
1488 func Recvmsg(fd int, p, oob []byte, flags int) (n, oobn int, recvflags int, from Sockaddr, err error) {
1490 var rsa RawSockaddrAny
1491 msg.Name = (*byte)(unsafe.Pointer(&rsa))
1492 msg.Namelen = uint32(SizeofSockaddrAny)
1502 sockType, err = GetsockoptInt(fd, SOL_SOCKET, SO_TYPE)
1506 // receive at least one normal byte
1507 if sockType != SOCK_DGRAM {
1512 msg.Control = &oob[0]
1513 msg.SetControllen(len(oob))
1517 if n, err = recvmsg(fd, &msg, flags); err != nil {
1520 oobn = int(msg.Controllen)
1521 recvflags = int(msg.Flags)
1522 // source address is only specified if the socket is unconnected
1523 if rsa.Addr.Family != AF_UNSPEC {
1524 from, err = anyToSockaddr(fd, &rsa)
1529 func Sendmsg(fd int, p, oob []byte, to Sockaddr, flags int) (err error) {
1530 _, err = SendmsgN(fd, p, oob, to, flags)
1534 func SendmsgN(fd int, p, oob []byte, to Sockaddr, flags int) (n int, err error) {
1535 var ptr unsafe.Pointer
1539 ptr, salen, err = to.sockaddr()
1545 msg.Name = (*byte)(ptr)
1546 msg.Namelen = uint32(salen)
1556 sockType, err = GetsockoptInt(fd, SOL_SOCKET, SO_TYPE)
1560 // send at least one normal byte
1561 if sockType != SOCK_DGRAM {
1566 msg.Control = &oob[0]
1567 msg.SetControllen(len(oob))
1571 if n, err = sendmsg(fd, &msg, flags); err != nil {
1574 if len(oob) > 0 && len(p) == 0 {
1580 // BindToDevice binds the socket associated with fd to device.
1581 func BindToDevice(fd int, device string) (err error) {
1582 return SetsockoptString(fd, SOL_SOCKET, SO_BINDTODEVICE, device)
1585 //sys ptrace(request int, pid int, addr uintptr, data uintptr) (err error)
1587 func ptracePeek(req int, pid int, addr uintptr, out []byte) (count int, err error) {
1588 // The peek requests are machine-size oriented, so we wrap it
1589 // to retrieve arbitrary-length data.
1591 // The ptrace syscall differs from glibc's ptrace.
1592 // Peeks returns the word in *data, not as the return value.
1594 var buf [SizeofPtr]byte
1596 // Leading edge. PEEKTEXT/PEEKDATA don't require aligned
1597 // access (PEEKUSER warns that it might), but if we don't
1598 // align our reads, we might straddle an unmapped page
1599 // boundary and not get the bytes leading up to the page
1602 if addr%SizeofPtr != 0 {
1603 err = ptrace(req, pid, addr-addr%SizeofPtr, uintptr(unsafe.Pointer(&buf[0])))
1607 n += copy(out, buf[addr%SizeofPtr:])
1613 // We use an internal buffer to guarantee alignment.
1614 // It's not documented if this is necessary, but we're paranoid.
1615 err = ptrace(req, pid, addr+uintptr(n), uintptr(unsafe.Pointer(&buf[0])))
1619 copied := copy(out, buf[0:])
1627 func PtracePeekText(pid int, addr uintptr, out []byte) (count int, err error) {
1628 return ptracePeek(PTRACE_PEEKTEXT, pid, addr, out)
1631 func PtracePeekData(pid int, addr uintptr, out []byte) (count int, err error) {
1632 return ptracePeek(PTRACE_PEEKDATA, pid, addr, out)
1635 func PtracePeekUser(pid int, addr uintptr, out []byte) (count int, err error) {
1636 return ptracePeek(PTRACE_PEEKUSR, pid, addr, out)
1639 func ptracePoke(pokeReq int, peekReq int, pid int, addr uintptr, data []byte) (count int, err error) {
1640 // As for ptracePeek, we need to align our accesses to deal
1641 // with the possibility of straddling an invalid page.
1645 if addr%SizeofPtr != 0 {
1646 var buf [SizeofPtr]byte
1647 err = ptrace(peekReq, pid, addr-addr%SizeofPtr, uintptr(unsafe.Pointer(&buf[0])))
1651 n += copy(buf[addr%SizeofPtr:], data)
1652 word := *((*uintptr)(unsafe.Pointer(&buf[0])))
1653 err = ptrace(pokeReq, pid, addr-addr%SizeofPtr, word)
1661 for len(data) > SizeofPtr {
1662 word := *((*uintptr)(unsafe.Pointer(&data[0])))
1663 err = ptrace(pokeReq, pid, addr+uintptr(n), word)
1668 data = data[SizeofPtr:]
1673 var buf [SizeofPtr]byte
1674 err = ptrace(peekReq, pid, addr+uintptr(n), uintptr(unsafe.Pointer(&buf[0])))
1679 word := *((*uintptr)(unsafe.Pointer(&buf[0])))
1680 err = ptrace(pokeReq, pid, addr+uintptr(n), word)
1690 func PtracePokeText(pid int, addr uintptr, data []byte) (count int, err error) {
1691 return ptracePoke(PTRACE_POKETEXT, PTRACE_PEEKTEXT, pid, addr, data)
1694 func PtracePokeData(pid int, addr uintptr, data []byte) (count int, err error) {
1695 return ptracePoke(PTRACE_POKEDATA, PTRACE_PEEKDATA, pid, addr, data)
1698 func PtracePokeUser(pid int, addr uintptr, data []byte) (count int, err error) {
1699 return ptracePoke(PTRACE_POKEUSR, PTRACE_PEEKUSR, pid, addr, data)
1702 func PtraceGetRegs(pid int, regsout *PtraceRegs) (err error) {
1703 return ptrace(PTRACE_GETREGS, pid, 0, uintptr(unsafe.Pointer(regsout)))
1706 func PtraceSetRegs(pid int, regs *PtraceRegs) (err error) {
1707 return ptrace(PTRACE_SETREGS, pid, 0, uintptr(unsafe.Pointer(regs)))
1710 func PtraceSetOptions(pid int, options int) (err error) {
1711 return ptrace(PTRACE_SETOPTIONS, pid, 0, uintptr(options))
1714 func PtraceGetEventMsg(pid int) (msg uint, err error) {
1716 err = ptrace(PTRACE_GETEVENTMSG, pid, 0, uintptr(unsafe.Pointer(&data)))
1721 func PtraceCont(pid int, signal int) (err error) {
1722 return ptrace(PTRACE_CONT, pid, 0, uintptr(signal))
1725 func PtraceSyscall(pid int, signal int) (err error) {
1726 return ptrace(PTRACE_SYSCALL, pid, 0, uintptr(signal))
1729 func PtraceSingleStep(pid int) (err error) { return ptrace(PTRACE_SINGLESTEP, pid, 0, 0) }
1731 func PtraceInterrupt(pid int) (err error) { return ptrace(PTRACE_INTERRUPT, pid, 0, 0) }
1733 func PtraceAttach(pid int) (err error) { return ptrace(PTRACE_ATTACH, pid, 0, 0) }
1735 func PtraceSeize(pid int) (err error) { return ptrace(PTRACE_SEIZE, pid, 0, 0) }
1737 func PtraceDetach(pid int) (err error) { return ptrace(PTRACE_DETACH, pid, 0, 0) }
1739 //sys reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error)
1741 func Reboot(cmd int) (err error) {
1742 return reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, cmd, "")
1745 func direntIno(buf []byte) (uint64, bool) {
1746 return readInt(buf, unsafe.Offsetof(Dirent{}.Ino), unsafe.Sizeof(Dirent{}.Ino))
1749 func direntReclen(buf []byte) (uint64, bool) {
1750 return readInt(buf, unsafe.Offsetof(Dirent{}.Reclen), unsafe.Sizeof(Dirent{}.Reclen))
1753 func direntNamlen(buf []byte) (uint64, bool) {
1754 reclen, ok := direntReclen(buf)
1758 return reclen - uint64(unsafe.Offsetof(Dirent{}.Name)), true
1761 //sys mount(source string, target string, fstype string, flags uintptr, data *byte) (err error)
1763 func Mount(source string, target string, fstype string, flags uintptr, data string) (err error) {
1764 // Certain file systems get rather angry and EINVAL if you give
1765 // them an empty string of data, rather than NULL.
1767 return mount(source, target, fstype, flags, nil)
1769 datap, err := BytePtrFromString(data)
1773 return mount(source, target, fstype, flags, datap)
1776 func Sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) {
1778 raceReleaseMerge(unsafe.Pointer(&ioSync))
1780 return sendfile(outfd, infd, offset, count)
1790 //sys Acct(path string) (err error)
1791 //sys AddKey(keyType string, description string, payload []byte, ringid int) (id int, err error)
1792 //sys Adjtimex(buf *Timex) (state int, err error)
1793 //sysnb Capget(hdr *CapUserHeader, data *CapUserData) (err error)
1794 //sysnb Capset(hdr *CapUserHeader, data *CapUserData) (err error)
1795 //sys Chdir(path string) (err error)
1796 //sys Chroot(path string) (err error)
1797 //sys ClockGetres(clockid int32, res *Timespec) (err error)
1798 //sys ClockGettime(clockid int32, time *Timespec) (err error)
1799 //sys ClockNanosleep(clockid int32, flags int, request *Timespec, remain *Timespec) (err error)
1800 //sys Close(fd int) (err error)
1801 //sys CopyFileRange(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error)
1802 //sys DeleteModule(name string, flags int) (err error)
1803 //sys Dup(oldfd int) (fd int, err error)
1805 func Dup2(oldfd, newfd int) error {
1806 // Android O and newer blocks dup2; riscv and arm64 don't implement dup2.
1807 if runtime.GOOS == "android" || runtime.GOARCH == "riscv64" || runtime.GOARCH == "arm64" {
1808 return Dup3(oldfd, newfd, 0)
1810 return dup2(oldfd, newfd)
1813 //sys Dup3(oldfd int, newfd int, flags int) (err error)
1814 //sysnb EpollCreate1(flag int) (fd int, err error)
1815 //sysnb EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error)
1816 //sys Eventfd(initval uint, flags int) (fd int, err error) = SYS_EVENTFD2
1817 //sys Exit(code int) = SYS_EXIT_GROUP
1818 //sys Fallocate(fd int, mode uint32, off int64, len int64) (err error)
1819 //sys Fchdir(fd int) (err error)
1820 //sys Fchmod(fd int, mode uint32) (err error)
1821 //sys Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error)
1822 //sys Fdatasync(fd int) (err error)
1823 //sys Fgetxattr(fd int, attr string, dest []byte) (sz int, err error)
1824 //sys FinitModule(fd int, params string, flags int) (err error)
1825 //sys Flistxattr(fd int, dest []byte) (sz int, err error)
1826 //sys Flock(fd int, how int) (err error)
1827 //sys Fremovexattr(fd int, attr string) (err error)
1828 //sys Fsetxattr(fd int, attr string, dest []byte, flags int) (err error)
1829 //sys Fsync(fd int) (err error)
1830 //sys Getdents(fd int, buf []byte) (n int, err error) = SYS_GETDENTS64
1831 //sysnb Getpgid(pid int) (pgid int, err error)
1833 func Getpgrp() (pid int) {
1838 //sysnb Getpid() (pid int)
1839 //sysnb Getppid() (ppid int)
1840 //sys Getpriority(which int, who int) (prio int, err error)
1841 //sys Getrandom(buf []byte, flags int) (n int, err error)
1842 //sysnb Getrusage(who int, rusage *Rusage) (err error)
1843 //sysnb Getsid(pid int) (sid int, err error)
1844 //sysnb Gettid() (tid int)
1845 //sys Getxattr(path string, attr string, dest []byte) (sz int, err error)
1846 //sys InitModule(moduleImage []byte, params string) (err error)
1847 //sys InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error)
1848 //sysnb InotifyInit1(flags int) (fd int, err error)
1849 //sysnb InotifyRmWatch(fd int, watchdesc uint32) (success int, err error)
1850 //sysnb Kill(pid int, sig syscall.Signal) (err error)
1851 //sys Klogctl(typ int, buf []byte) (n int, err error) = SYS_SYSLOG
1852 //sys Lgetxattr(path string, attr string, dest []byte) (sz int, err error)
1853 //sys Listxattr(path string, dest []byte) (sz int, err error)
1854 //sys Llistxattr(path string, dest []byte) (sz int, err error)
1855 //sys Lremovexattr(path string, attr string) (err error)
1856 //sys Lsetxattr(path string, attr string, data []byte, flags int) (err error)
1857 //sys MemfdCreate(name string, flags int) (fd int, err error)
1858 //sys Mkdirat(dirfd int, path string, mode uint32) (err error)
1859 //sys Mknodat(dirfd int, path string, mode uint32, dev int) (err error)
1860 //sys Nanosleep(time *Timespec, leftover *Timespec) (err error)
1861 //sys PerfEventOpen(attr *PerfEventAttr, pid int, cpu int, groupFd int, flags int) (fd int, err error)
1862 //sys PivotRoot(newroot string, putold string) (err error) = SYS_PIVOT_ROOT
1863 //sysnb prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) = SYS_PRLIMIT64
1864 //sys Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error)
1865 //sys Pselect(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timespec, sigmask *Sigset_t) (n int, err error) = SYS_PSELECT6
1866 //sys read(fd int, p []byte) (n int, err error)
1867 //sys Removexattr(path string, attr string) (err error)
1868 //sys Renameat2(olddirfd int, oldpath string, newdirfd int, newpath string, flags uint) (err error)
1869 //sys RequestKey(keyType string, description string, callback string, destRingid int) (id int, err error)
1870 //sys Setdomainname(p []byte) (err error)
1871 //sys Sethostname(p []byte) (err error)
1872 //sysnb Setpgid(pid int, pgid int) (err error)
1873 //sysnb Setsid() (pid int, err error)
1874 //sysnb Settimeofday(tv *Timeval) (err error)
1875 //sys Setns(fd int, nstype int) (err error)
1877 // PrctlRetInt performs a prctl operation specified by option and further
1878 // optional arguments arg2 through arg5 depending on option. It returns a
1879 // non-negative integer that is returned by the prctl syscall.
1880 func PrctlRetInt(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (int, error) {
1881 ret, _, err := Syscall6(SYS_PRCTL, uintptr(option), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0)
1885 return int(ret), nil
1889 // On linux Setuid and Setgid only affects the current thread, not the process.
1890 // This does not match what most callers expect so we must return an error
1891 // here rather than letting the caller think that the call succeeded.
1893 func Setuid(uid int) (err error) {
1897 func Setgid(uid int) (err error) {
1901 // SetfsgidRetGid sets fsgid for current thread and returns previous fsgid set.
1902 // setfsgid(2) will return a non-nil error only if its caller lacks CAP_SETUID capability.
1903 // If the call fails due to other reasons, current fsgid will be returned.
1904 func SetfsgidRetGid(gid int) (int, error) {
1905 return setfsgid(gid)
1908 // SetfsuidRetUid sets fsuid for current thread and returns previous fsuid set.
1909 // setfsgid(2) will return a non-nil error only if its caller lacks CAP_SETUID capability
1910 // If the call fails due to other reasons, current fsuid will be returned.
1911 func SetfsuidRetUid(uid int) (int, error) {
1912 return setfsuid(uid)
1915 func Setfsgid(gid int) error {
1916 _, err := setfsgid(gid)
1920 func Setfsuid(uid int) error {
1921 _, err := setfsuid(uid)
1925 func Signalfd(fd int, sigmask *Sigset_t, flags int) (newfd int, err error) {
1926 return signalfd(fd, sigmask, _C__NSIG/8, flags)
1929 //sys Setpriority(which int, who int, prio int) (err error)
1930 //sys Setxattr(path string, attr string, data []byte, flags int) (err error)
1931 //sys signalfd(fd int, sigmask *Sigset_t, maskSize uintptr, flags int) (newfd int, err error) = SYS_SIGNALFD4
1932 //sys Statx(dirfd int, path string, flags int, mask int, stat *Statx_t) (err error)
1934 //sys Syncfs(fd int) (err error)
1935 //sysnb Sysinfo(info *Sysinfo_t) (err error)
1936 //sys Tee(rfd int, wfd int, len int, flags int) (n int64, err error)
1937 //sysnb TimerfdCreate(clockid int, flags int) (fd int, err error)
1938 //sysnb TimerfdGettime(fd int, currValue *ItimerSpec) (err error)
1939 //sysnb TimerfdSettime(fd int, flags int, newValue *ItimerSpec, oldValue *ItimerSpec) (err error)
1940 //sysnb Tgkill(tgid int, tid int, sig syscall.Signal) (err error)
1941 //sysnb Times(tms *Tms) (ticks uintptr, err error)
1942 //sysnb Umask(mask int) (oldmask int)
1943 //sysnb Uname(buf *Utsname) (err error)
1944 //sys Unmount(target string, flags int) (err error) = SYS_UMOUNT2
1945 //sys Unshare(flags int) (err error)
1946 //sys write(fd int, p []byte) (n int, err error)
1947 //sys exitThread(code int) (err error) = SYS_EXIT
1948 //sys readlen(fd int, p *byte, np int) (n int, err error) = SYS_READ
1949 //sys writelen(fd int, p *byte, np int) (n int, err error) = SYS_WRITE
1950 //sys readv(fd int, iovs []Iovec) (n int, err error) = SYS_READV
1951 //sys writev(fd int, iovs []Iovec) (n int, err error) = SYS_WRITEV
1952 //sys preadv(fd int, iovs []Iovec, offs_l uintptr, offs_h uintptr) (n int, err error) = SYS_PREADV
1953 //sys pwritev(fd int, iovs []Iovec, offs_l uintptr, offs_h uintptr) (n int, err error) = SYS_PWRITEV
1954 //sys preadv2(fd int, iovs []Iovec, offs_l uintptr, offs_h uintptr, flags int) (n int, err error) = SYS_PREADV2
1955 //sys pwritev2(fd int, iovs []Iovec, offs_l uintptr, offs_h uintptr, flags int) (n int, err error) = SYS_PWRITEV2
1957 func bytes2iovec(bs [][]byte) []Iovec {
1958 iovecs := make([]Iovec, len(bs))
1959 for i, b := range bs {
1960 iovecs[i].SetLen(len(b))
1962 iovecs[i].Base = &b[0]
1964 iovecs[i].Base = (*byte)(unsafe.Pointer(&_zero))
1970 // offs2lohi splits offs into its lower and upper unsigned long. On 64-bit
1971 // systems, hi will always be 0. On 32-bit systems, offs will be split in half.
1972 // preadv/pwritev chose this calling convention so they don't need to add a
1973 // padding-register for alignment on ARM.
1974 func offs2lohi(offs int64) (lo, hi uintptr) {
1975 return uintptr(offs), uintptr(uint64(offs) >> SizeofLong)
1978 func Readv(fd int, iovs [][]byte) (n int, err error) {
1979 iovecs := bytes2iovec(iovs)
1980 n, err = readv(fd, iovecs)
1981 readvRacedetect(iovecs, n, err)
1985 func Preadv(fd int, iovs [][]byte, offset int64) (n int, err error) {
1986 iovecs := bytes2iovec(iovs)
1987 lo, hi := offs2lohi(offset)
1988 n, err = preadv(fd, iovecs, lo, hi)
1989 readvRacedetect(iovecs, n, err)
1993 func Preadv2(fd int, iovs [][]byte, offset int64, flags int) (n int, err error) {
1994 iovecs := bytes2iovec(iovs)
1995 lo, hi := offs2lohi(offset)
1996 n, err = preadv2(fd, iovecs, lo, hi, flags)
1997 readvRacedetect(iovecs, n, err)
2001 func readvRacedetect(iovecs []Iovec, n int, err error) {
2005 for i := 0; n > 0 && i < len(iovecs); i++ {
2006 m := int(iovecs[i].Len)
2012 raceWriteRange(unsafe.Pointer(iovecs[i].Base), m)
2016 raceAcquire(unsafe.Pointer(&ioSync))
2020 func Writev(fd int, iovs [][]byte) (n int, err error) {
2021 iovecs := bytes2iovec(iovs)
2023 raceReleaseMerge(unsafe.Pointer(&ioSync))
2025 n, err = writev(fd, iovecs)
2026 writevRacedetect(iovecs, n)
2030 func Pwritev(fd int, iovs [][]byte, offset int64) (n int, err error) {
2031 iovecs := bytes2iovec(iovs)
2033 raceReleaseMerge(unsafe.Pointer(&ioSync))
2035 lo, hi := offs2lohi(offset)
2036 n, err = pwritev(fd, iovecs, lo, hi)
2037 writevRacedetect(iovecs, n)
2041 func Pwritev2(fd int, iovs [][]byte, offset int64, flags int) (n int, err error) {
2042 iovecs := bytes2iovec(iovs)
2044 raceReleaseMerge(unsafe.Pointer(&ioSync))
2046 lo, hi := offs2lohi(offset)
2047 n, err = pwritev2(fd, iovecs, lo, hi, flags)
2048 writevRacedetect(iovecs, n)
2052 func writevRacedetect(iovecs []Iovec, n int) {
2056 for i := 0; n > 0 && i < len(iovecs); i++ {
2057 m := int(iovecs[i].Len)
2063 raceReadRange(unsafe.Pointer(iovecs[i].Base), m)
2068 // mmap varies by architecture; see syscall_linux_*.go.
2069 //sys munmap(addr uintptr, length uintptr) (err error)
2071 var mapper = &mmapper{
2072 active: make(map[*byte][]byte),
2077 func Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error) {
2078 return mapper.Mmap(fd, offset, length, prot, flags)
2081 func Munmap(b []byte) (err error) {
2082 return mapper.Munmap(b)
2085 //sys Madvise(b []byte, advice int) (err error)
2086 //sys Mprotect(b []byte, prot int) (err error)
2087 //sys Mlock(b []byte) (err error)
2088 //sys Mlockall(flags int) (err error)
2089 //sys Msync(b []byte, flags int) (err error)
2090 //sys Munlock(b []byte) (err error)
2091 //sys Munlockall() (err error)
2093 // Vmsplice splices user pages from a slice of Iovecs into a pipe specified by fd,
2094 // using the specified flags.
2095 func Vmsplice(fd int, iovs []Iovec, flags int) (int, error) {
2096 var p unsafe.Pointer
2098 p = unsafe.Pointer(&iovs[0])
2101 n, _, errno := Syscall6(SYS_VMSPLICE, uintptr(fd), uintptr(p), uintptr(len(iovs)), uintptr(flags), 0, 0)
2103 return 0, syscall.Errno(errno)
2109 func isGroupMember(gid int) bool {
2110 groups, err := Getgroups()
2115 for _, g := range groups {
2123 //sys faccessat(dirfd int, path string, mode uint32) (err error)
2124 //sys Faccessat2(dirfd int, path string, mode uint32, flags int) (err error)
2126 func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) {
2128 return faccessat(dirfd, path, mode)
2131 if err := Faccessat2(dirfd, path, mode, flags); err != ENOSYS && err != EPERM {
2135 // The Linux kernel faccessat system call does not take any flags.
2136 // The glibc faccessat implements the flags itself; see
2137 // https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/unix/sysv/linux/faccessat.c;hb=HEAD
2138 // Because people naturally expect syscall.Faccessat to act
2139 // like C faccessat, we do the same.
2141 if flags & ^(AT_SYMLINK_NOFOLLOW|AT_EACCESS) != 0 {
2146 if err := Fstatat(dirfd, path, &st, flags&AT_SYMLINK_NOFOLLOW); err != nil {
2156 if flags&AT_EACCESS != 0 {
2164 // Root can read and write any file.
2167 if st.Mode&0111 != 0 {
2168 // Root can execute any file that anybody can execute.
2175 if uint32(uid) == st.Uid {
2176 fmode = (st.Mode >> 6) & 7
2179 if flags&AT_EACCESS != 0 {
2185 if uint32(gid) == st.Gid || isGroupMember(gid) {
2186 fmode = (st.Mode >> 3) & 7
2192 if fmode&mode == mode {
2199 //sys nameToHandleAt(dirFD int, pathname string, fh *fileHandle, mountID *_C_int, flags int) (err error) = SYS_NAME_TO_HANDLE_AT
2200 //sys openByHandleAt(mountFD int, fh *fileHandle, flags int) (fd int, err error) = SYS_OPEN_BY_HANDLE_AT
2202 // fileHandle is the argument to nameToHandleAt and openByHandleAt. We
2203 // originally tried to generate it via unix/linux/types.go with "type
2204 // fileHandle C.struct_file_handle" but that generated empty structs
2205 // for mips64 and mips64le. Instead, hard code it for now (it's the
2206 // same everywhere else) until the mips64 generator issue is fixed.
2207 type fileHandle struct {
2212 // FileHandle represents the C struct file_handle used by
2213 // name_to_handle_at (see NameToHandleAt) and open_by_handle_at (see
2215 type FileHandle struct {
2219 // NewFileHandle constructs a FileHandle.
2220 func NewFileHandle(handleType int32, handle []byte) FileHandle {
2221 const hdrSize = unsafe.Sizeof(fileHandle{})
2222 buf := make([]byte, hdrSize+uintptr(len(handle)))
2223 copy(buf[hdrSize:], handle)
2224 fh := (*fileHandle)(unsafe.Pointer(&buf[0]))
2225 fh.Type = handleType
2226 fh.Bytes = uint32(len(handle))
2227 return FileHandle{fh}
2230 func (fh *FileHandle) Size() int { return int(fh.fileHandle.Bytes) }
2231 func (fh *FileHandle) Type() int32 { return fh.fileHandle.Type }
2232 func (fh *FileHandle) Bytes() []byte {
2237 return (*[1 << 30]byte)(unsafe.Pointer(uintptr(unsafe.Pointer(&fh.fileHandle.Type)) + 4))[:n:n]
2240 // NameToHandleAt wraps the name_to_handle_at system call; it obtains
2241 // a handle for a path name.
2242 func NameToHandleAt(dirfd int, path string, flags int) (handle FileHandle, mountID int, err error) {
2244 // Try first with a small buffer, assuming the handle will
2245 // only be 32 bytes.
2246 size := uint32(32 + unsafe.Sizeof(fileHandle{}))
2249 buf := make([]byte, size)
2250 fh := (*fileHandle)(unsafe.Pointer(&buf[0]))
2251 fh.Bytes = size - uint32(unsafe.Sizeof(fileHandle{}))
2252 err = nameToHandleAt(dirfd, path, fh, &mid, flags)
2253 if err == EOVERFLOW {
2255 // We shouldn't need to resize more than once
2259 size = fh.Bytes + uint32(unsafe.Sizeof(fileHandle{}))
2265 return FileHandle{fh}, int(mid), nil
2269 // OpenByHandleAt wraps the open_by_handle_at system call; it opens a
2270 // file via a handle as previously returned by NameToHandleAt.
2271 func OpenByHandleAt(mountFD int, handle FileHandle, flags int) (fd int, err error) {
2272 return openByHandleAt(mountFD, handle.fileHandle, flags)
2275 // Klogset wraps the sys_syslog system call; it sets console_loglevel to
2276 // the value specified by arg and passes a dummy pointer to bufp.
2277 func Klogset(typ int, arg int) (err error) {
2278 var p unsafe.Pointer
2279 _, _, errno := Syscall(SYS_SYSLOG, uintptr(typ), uintptr(p), uintptr(arg))
2281 return errnoErr(errno)
2286 // RemoteIovec is Iovec with the pointer replaced with an integer.
2287 // It is used for ProcessVMReadv and ProcessVMWritev, where the pointer
2288 // refers to a location in a different process' address space, which
2289 // would confuse the Go garbage collector.
2290 type RemoteIovec struct {
2295 //sys ProcessVMReadv(pid int, localIov []Iovec, remoteIov []RemoteIovec, flags uint) (n int, err error) = SYS_PROCESS_VM_READV
2296 //sys ProcessVMWritev(pid int, localIov []Iovec, remoteIov []RemoteIovec, flags uint) (n int, err error) = SYS_PROCESS_VM_WRITEV
2363 // SchedGetPriorityMax
2364 // SchedGetPriorityMin
2366 // SchedGetscheduler
2367 // SchedRrGetInterval