github.com/giovannyortegon/go@v0.0.0-20220115155912-8890063f5bdd/src/pkg/mod/golang.org/x/sys@v0.0.0-20210927094055-39ccf1dd6fa6/unix/syscall_linux.go (about)

     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  
     5  // Linux system calls.
     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.
    11  
    12  package unix
    13  
    14  import (
    15  	"encoding/binary"
    16  	"syscall"
    17  	"unsafe"
    18  )
    19  
    20  /*
    21   * Wrapped
    22   */
    23  
    24  func Access(path string, mode uint32) (err error) {
    25  	return Faccessat(AT_FDCWD, path, mode, 0)
    26  }
    27  
    28  func Chmod(path string, mode uint32) (err error) {
    29  	return Fchmodat(AT_FDCWD, path, mode, 0)
    30  }
    31  
    32  func Chown(path string, uid int, gid int) (err error) {
    33  	return Fchownat(AT_FDCWD, path, uid, gid, 0)
    34  }
    35  
    36  func Creat(path string, mode uint32) (fd int, err error) {
    37  	return Open(path, O_CREAT|O_WRONLY|O_TRUNC, mode)
    38  }
    39  
    40  func EpollCreate(size int) (fd int, err error) {
    41  	if size <= 0 {
    42  		return -1, EINVAL
    43  	}
    44  	return EpollCreate1(0)
    45  }
    46  
    47  //sys	FanotifyInit(flags uint, event_f_flags uint) (fd int, err error)
    48  //sys	fanotifyMark(fd int, flags uint, mask uint64, dirFd int, pathname *byte) (err error)
    49  
    50  func FanotifyMark(fd int, flags uint, mask uint64, dirFd int, pathname string) (err error) {
    51  	if pathname == "" {
    52  		return fanotifyMark(fd, flags, mask, dirFd, nil)
    53  	}
    54  	p, err := BytePtrFromString(pathname)
    55  	if err != nil {
    56  		return err
    57  	}
    58  	return fanotifyMark(fd, flags, mask, dirFd, p)
    59  }
    60  
    61  //sys	fchmodat(dirfd int, path string, mode uint32) (err error)
    62  
    63  func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) {
    64  	// Linux fchmodat doesn't support the flags parameter. Mimick glibc's behavior
    65  	// and check the flags. Otherwise the mode would be applied to the symlink
    66  	// destination which is not what the user expects.
    67  	if flags&^AT_SYMLINK_NOFOLLOW != 0 {
    68  		return EINVAL
    69  	} else if flags&AT_SYMLINK_NOFOLLOW != 0 {
    70  		return EOPNOTSUPP
    71  	}
    72  	return fchmodat(dirfd, path, mode)
    73  }
    74  
    75  func InotifyInit() (fd int, err error) {
    76  	return InotifyInit1(0)
    77  }
    78  
    79  //sys	ioctl(fd int, req uint, arg uintptr) (err error) = SYS_IOCTL
    80  //sys	ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) = SYS_IOCTL
    81  
    82  // ioctl itself should not be exposed directly, but additional get/set functions
    83  // for specific types are permissible. These are defined in ioctl.go and
    84  // ioctl_linux.go.
    85  //
    86  // The third argument to ioctl is often a pointer but sometimes an integer.
    87  // Callers should use ioctlPtr when the third argument is a pointer and ioctl
    88  // when the third argument is an integer.
    89  //
    90  // TODO: some existing code incorrectly uses ioctl when it should use ioctlPtr.
    91  
    92  //sys	Linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error)
    93  
    94  func Link(oldpath string, newpath string) (err error) {
    95  	return Linkat(AT_FDCWD, oldpath, AT_FDCWD, newpath, 0)
    96  }
    97  
    98  func Mkdir(path string, mode uint32) (err error) {
    99  	return Mkdirat(AT_FDCWD, path, mode)
   100  }
   101  
   102  func Mknod(path string, mode uint32, dev int) (err error) {
   103  	return Mknodat(AT_FDCWD, path, mode, dev)
   104  }
   105  
   106  func Open(path string, mode int, perm uint32) (fd int, err error) {
   107  	return openat(AT_FDCWD, path, mode|O_LARGEFILE, perm)
   108  }
   109  
   110  //sys	openat(dirfd int, path string, flags int, mode uint32) (fd int, err error)
   111  
   112  func Openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) {
   113  	return openat(dirfd, path, flags|O_LARGEFILE, mode)
   114  }
   115  
   116  //sys	openat2(dirfd int, path string, open_how *OpenHow, size int) (fd int, err error)
   117  
   118  func Openat2(dirfd int, path string, how *OpenHow) (fd int, err error) {
   119  	return openat2(dirfd, path, how, SizeofOpenHow)
   120  }
   121  
   122  func Pipe(p []int) error {
   123  	return Pipe2(p, 0)
   124  }
   125  
   126  //sysnb	pipe2(p *[2]_C_int, flags int) (err error)
   127  
   128  func Pipe2(p []int, flags int) error {
   129  	if len(p) != 2 {
   130  		return EINVAL
   131  	}
   132  	var pp [2]_C_int
   133  	err := pipe2(&pp, flags)
   134  	p[0] = int(pp[0])
   135  	p[1] = int(pp[1])
   136  	return err
   137  }
   138  
   139  //sys	ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error)
   140  
   141  func Ppoll(fds []PollFd, timeout *Timespec, sigmask *Sigset_t) (n int, err error) {
   142  	if len(fds) == 0 {
   143  		return ppoll(nil, 0, timeout, sigmask)
   144  	}
   145  	return ppoll(&fds[0], len(fds), timeout, sigmask)
   146  }
   147  
   148  func Poll(fds []PollFd, timeout int) (n int, err error) {
   149  	var ts *Timespec
   150  	if timeout >= 0 {
   151  		ts = new(Timespec)
   152  		*ts = NsecToTimespec(int64(timeout) * 1e6)
   153  	}
   154  	return Ppoll(fds, ts, nil)
   155  }
   156  
   157  //sys	Readlinkat(dirfd int, path string, buf []byte) (n int, err error)
   158  
   159  func Readlink(path string, buf []byte) (n int, err error) {
   160  	return Readlinkat(AT_FDCWD, path, buf)
   161  }
   162  
   163  func Rename(oldpath string, newpath string) (err error) {
   164  	return Renameat(AT_FDCWD, oldpath, AT_FDCWD, newpath)
   165  }
   166  
   167  func Rmdir(path string) error {
   168  	return Unlinkat(AT_FDCWD, path, AT_REMOVEDIR)
   169  }
   170  
   171  //sys	Symlinkat(oldpath string, newdirfd int, newpath string) (err error)
   172  
   173  func Symlink(oldpath string, newpath string) (err error) {
   174  	return Symlinkat(oldpath, AT_FDCWD, newpath)
   175  }
   176  
   177  func Unlink(path string) error {
   178  	return Unlinkat(AT_FDCWD, path, 0)
   179  }
   180  
   181  //sys	Unlinkat(dirfd int, path string, flags int) (err error)
   182  
   183  func Utimes(path string, tv []Timeval) error {
   184  	if tv == nil {
   185  		err := utimensat(AT_FDCWD, path, nil, 0)
   186  		if err != ENOSYS {
   187  			return err
   188  		}
   189  		return utimes(path, nil)
   190  	}
   191  	if len(tv) != 2 {
   192  		return EINVAL
   193  	}
   194  	var ts [2]Timespec
   195  	ts[0] = NsecToTimespec(TimevalToNsec(tv[0]))
   196  	ts[1] = NsecToTimespec(TimevalToNsec(tv[1]))
   197  	err := utimensat(AT_FDCWD, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), 0)
   198  	if err != ENOSYS {
   199  		return err
   200  	}
   201  	return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
   202  }
   203  
   204  //sys	utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error)
   205  
   206  func UtimesNano(path string, ts []Timespec) error {
   207  	return UtimesNanoAt(AT_FDCWD, path, ts, 0)
   208  }
   209  
   210  func UtimesNanoAt(dirfd int, path string, ts []Timespec, flags int) error {
   211  	if ts == nil {
   212  		return utimensat(dirfd, path, nil, flags)
   213  	}
   214  	if len(ts) != 2 {
   215  		return EINVAL
   216  	}
   217  	return utimensat(dirfd, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), flags)
   218  }
   219  
   220  func Futimesat(dirfd int, path string, tv []Timeval) error {
   221  	if tv == nil {
   222  		return futimesat(dirfd, path, nil)
   223  	}
   224  	if len(tv) != 2 {
   225  		return EINVAL
   226  	}
   227  	return futimesat(dirfd, path, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
   228  }
   229  
   230  func Futimes(fd int, tv []Timeval) (err error) {
   231  	// Believe it or not, this is the best we can do on Linux
   232  	// (and is what glibc does).
   233  	return Utimes("/proc/self/fd/"+itoa(fd), tv)
   234  }
   235  
   236  const ImplementsGetwd = true
   237  
   238  //sys	Getcwd(buf []byte) (n int, err error)
   239  
   240  func Getwd() (wd string, err error) {
   241  	var buf [PathMax]byte
   242  	n, err := Getcwd(buf[0:])
   243  	if err != nil {
   244  		return "", err
   245  	}
   246  	// Getcwd returns the number of bytes written to buf, including the NUL.
   247  	if n < 1 || n > len(buf) || buf[n-1] != 0 {
   248  		return "", EINVAL
   249  	}
   250  	return string(buf[0 : n-1]), nil
   251  }
   252  
   253  func Getgroups() (gids []int, err error) {
   254  	n, err := getgroups(0, nil)
   255  	if err != nil {
   256  		return nil, err
   257  	}
   258  	if n == 0 {
   259  		return nil, nil
   260  	}
   261  
   262  	// Sanity check group count. Max is 1<<16 on Linux.
   263  	if n < 0 || n > 1<<20 {
   264  		return nil, EINVAL
   265  	}
   266  
   267  	a := make([]_Gid_t, n)
   268  	n, err = getgroups(n, &a[0])
   269  	if err != nil {
   270  		return nil, err
   271  	}
   272  	gids = make([]int, n)
   273  	for i, v := range a[0:n] {
   274  		gids[i] = int(v)
   275  	}
   276  	return
   277  }
   278  
   279  func Setgroups(gids []int) (err error) {
   280  	if len(gids) == 0 {
   281  		return setgroups(0, nil)
   282  	}
   283  
   284  	a := make([]_Gid_t, len(gids))
   285  	for i, v := range gids {
   286  		a[i] = _Gid_t(v)
   287  	}
   288  	return setgroups(len(a), &a[0])
   289  }
   290  
   291  type WaitStatus uint32
   292  
   293  // Wait status is 7 bits at bottom, either 0 (exited),
   294  // 0x7F (stopped), or a signal number that caused an exit.
   295  // The 0x80 bit is whether there was a core dump.
   296  // An extra number (exit code, signal causing a stop)
   297  // is in the high bits. At least that's the idea.
   298  // There are various irregularities. For example, the
   299  // "continued" status is 0xFFFF, distinguishing itself
   300  // from stopped via the core dump bit.
   301  
   302  const (
   303  	mask    = 0x7F
   304  	core    = 0x80
   305  	exited  = 0x00
   306  	stopped = 0x7F
   307  	shift   = 8
   308  )
   309  
   310  func (w WaitStatus) Exited() bool { return w&mask == exited }
   311  
   312  func (w WaitStatus) Signaled() bool { return w&mask != stopped && w&mask != exited }
   313  
   314  func (w WaitStatus) Stopped() bool { return w&0xFF == stopped }
   315  
   316  func (w WaitStatus) Continued() bool { return w == 0xFFFF }
   317  
   318  func (w WaitStatus) CoreDump() bool { return w.Signaled() && w&core != 0 }
   319  
   320  func (w WaitStatus) ExitStatus() int {
   321  	if !w.Exited() {
   322  		return -1
   323  	}
   324  	return int(w>>shift) & 0xFF
   325  }
   326  
   327  func (w WaitStatus) Signal() syscall.Signal {
   328  	if !w.Signaled() {
   329  		return -1
   330  	}
   331  	return syscall.Signal(w & mask)
   332  }
   333  
   334  func (w WaitStatus) StopSignal() syscall.Signal {
   335  	if !w.Stopped() {
   336  		return -1
   337  	}
   338  	return syscall.Signal(w>>shift) & 0xFF
   339  }
   340  
   341  func (w WaitStatus) TrapCause() int {
   342  	if w.StopSignal() != SIGTRAP {
   343  		return -1
   344  	}
   345  	return int(w>>shift) >> 8
   346  }
   347  
   348  //sys	wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error)
   349  
   350  func Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, err error) {
   351  	var status _C_int
   352  	wpid, err = wait4(pid, &status, options, rusage)
   353  	if wstatus != nil {
   354  		*wstatus = WaitStatus(status)
   355  	}
   356  	return
   357  }
   358  
   359  func Mkfifo(path string, mode uint32) error {
   360  	return Mknod(path, mode|S_IFIFO, 0)
   361  }
   362  
   363  func Mkfifoat(dirfd int, path string, mode uint32) error {
   364  	return Mknodat(dirfd, path, mode|S_IFIFO, 0)
   365  }
   366  
   367  func (sa *SockaddrInet4) sockaddr() (unsafe.Pointer, _Socklen, error) {
   368  	if sa.Port < 0 || sa.Port > 0xFFFF {
   369  		return nil, 0, EINVAL
   370  	}
   371  	sa.raw.Family = AF_INET
   372  	p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port))
   373  	p[0] = byte(sa.Port >> 8)
   374  	p[1] = byte(sa.Port)
   375  	for i := 0; i < len(sa.Addr); i++ {
   376  		sa.raw.Addr[i] = sa.Addr[i]
   377  	}
   378  	return unsafe.Pointer(&sa.raw), SizeofSockaddrInet4, nil
   379  }
   380  
   381  func (sa *SockaddrInet6) sockaddr() (unsafe.Pointer, _Socklen, error) {
   382  	if sa.Port < 0 || sa.Port > 0xFFFF {
   383  		return nil, 0, EINVAL
   384  	}
   385  	sa.raw.Family = AF_INET6
   386  	p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port))
   387  	p[0] = byte(sa.Port >> 8)
   388  	p[1] = byte(sa.Port)
   389  	sa.raw.Scope_id = sa.ZoneId
   390  	for i := 0; i < len(sa.Addr); i++ {
   391  		sa.raw.Addr[i] = sa.Addr[i]
   392  	}
   393  	return unsafe.Pointer(&sa.raw), SizeofSockaddrInet6, nil
   394  }
   395  
   396  func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, _Socklen, error) {
   397  	name := sa.Name
   398  	n := len(name)
   399  	if n >= len(sa.raw.Path) {
   400  		return nil, 0, EINVAL
   401  	}
   402  	sa.raw.Family = AF_UNIX
   403  	for i := 0; i < n; i++ {
   404  		sa.raw.Path[i] = int8(name[i])
   405  	}
   406  	// length is family (uint16), name, NUL.
   407  	sl := _Socklen(2)
   408  	if n > 0 {
   409  		sl += _Socklen(n) + 1
   410  	}
   411  	if sa.raw.Path[0] == '@' {
   412  		sa.raw.Path[0] = 0
   413  		// Don't count trailing NUL for abstract address.
   414  		sl--
   415  	}
   416  
   417  	return unsafe.Pointer(&sa.raw), sl, nil
   418  }
   419  
   420  // SockaddrLinklayer implements the Sockaddr interface for AF_PACKET type sockets.
   421  type SockaddrLinklayer struct {
   422  	Protocol uint16
   423  	Ifindex  int
   424  	Hatype   uint16
   425  	Pkttype  uint8
   426  	Halen    uint8
   427  	Addr     [8]byte
   428  	raw      RawSockaddrLinklayer
   429  }
   430  
   431  func (sa *SockaddrLinklayer) sockaddr() (unsafe.Pointer, _Socklen, error) {
   432  	if sa.Ifindex < 0 || sa.Ifindex > 0x7fffffff {
   433  		return nil, 0, EINVAL
   434  	}
   435  	sa.raw.Family = AF_PACKET
   436  	sa.raw.Protocol = sa.Protocol
   437  	sa.raw.Ifindex = int32(sa.Ifindex)
   438  	sa.raw.Hatype = sa.Hatype
   439  	sa.raw.Pkttype = sa.Pkttype
   440  	sa.raw.Halen = sa.Halen
   441  	for i := 0; i < len(sa.Addr); i++ {
   442  		sa.raw.Addr[i] = sa.Addr[i]
   443  	}
   444  	return unsafe.Pointer(&sa.raw), SizeofSockaddrLinklayer, nil
   445  }
   446  
   447  // SockaddrNetlink implements the Sockaddr interface for AF_NETLINK type sockets.
   448  type SockaddrNetlink struct {
   449  	Family uint16
   450  	Pad    uint16
   451  	Pid    uint32
   452  	Groups uint32
   453  	raw    RawSockaddrNetlink
   454  }
   455  
   456  func (sa *SockaddrNetlink) sockaddr() (unsafe.Pointer, _Socklen, error) {
   457  	sa.raw.Family = AF_NETLINK
   458  	sa.raw.Pad = sa.Pad
   459  	sa.raw.Pid = sa.Pid
   460  	sa.raw.Groups = sa.Groups
   461  	return unsafe.Pointer(&sa.raw), SizeofSockaddrNetlink, nil
   462  }
   463  
   464  // SockaddrHCI implements the Sockaddr interface for AF_BLUETOOTH type sockets
   465  // using the HCI protocol.
   466  type SockaddrHCI struct {
   467  	Dev     uint16
   468  	Channel uint16
   469  	raw     RawSockaddrHCI
   470  }
   471  
   472  func (sa *SockaddrHCI) sockaddr() (unsafe.Pointer, _Socklen, error) {
   473  	sa.raw.Family = AF_BLUETOOTH
   474  	sa.raw.Dev = sa.Dev
   475  	sa.raw.Channel = sa.Channel
   476  	return unsafe.Pointer(&sa.raw), SizeofSockaddrHCI, nil
   477  }
   478  
   479  // SockaddrL2 implements the Sockaddr interface for AF_BLUETOOTH type sockets
   480  // using the L2CAP protocol.
   481  type SockaddrL2 struct {
   482  	PSM      uint16
   483  	CID      uint16
   484  	Addr     [6]uint8
   485  	AddrType uint8
   486  	raw      RawSockaddrL2
   487  }
   488  
   489  func (sa *SockaddrL2) sockaddr() (unsafe.Pointer, _Socklen, error) {
   490  	sa.raw.Family = AF_BLUETOOTH
   491  	psm := (*[2]byte)(unsafe.Pointer(&sa.raw.Psm))
   492  	psm[0] = byte(sa.PSM)
   493  	psm[1] = byte(sa.PSM >> 8)
   494  	for i := 0; i < len(sa.Addr); i++ {
   495  		sa.raw.Bdaddr[i] = sa.Addr[len(sa.Addr)-1-i]
   496  	}
   497  	cid := (*[2]byte)(unsafe.Pointer(&sa.raw.Cid))
   498  	cid[0] = byte(sa.CID)
   499  	cid[1] = byte(sa.CID >> 8)
   500  	sa.raw.Bdaddr_type = sa.AddrType
   501  	return unsafe.Pointer(&sa.raw), SizeofSockaddrL2, nil
   502  }
   503  
   504  // SockaddrRFCOMM implements the Sockaddr interface for AF_BLUETOOTH type sockets
   505  // using the RFCOMM protocol.
   506  //
   507  // Server example:
   508  //
   509  //      fd, _ := Socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM)
   510  //      _ = unix.Bind(fd, &unix.SockaddrRFCOMM{
   511  //      	Channel: 1,
   512  //      	Addr:    [6]uint8{0, 0, 0, 0, 0, 0}, // BDADDR_ANY or 00:00:00:00:00:00
   513  //      })
   514  //      _ = Listen(fd, 1)
   515  //      nfd, sa, _ := Accept(fd)
   516  //      fmt.Printf("conn addr=%v fd=%d", sa.(*unix.SockaddrRFCOMM).Addr, nfd)
   517  //      Read(nfd, buf)
   518  //
   519  // Client example:
   520  //
   521  //      fd, _ := Socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM)
   522  //      _ = Connect(fd, &SockaddrRFCOMM{
   523  //      	Channel: 1,
   524  //      	Addr:    [6]byte{0x11, 0x22, 0x33, 0xaa, 0xbb, 0xcc}, // CC:BB:AA:33:22:11
   525  //      })
   526  //      Write(fd, []byte(`hello`))
   527  type SockaddrRFCOMM struct {
   528  	// Addr represents a bluetooth address, byte ordering is little-endian.
   529  	Addr [6]uint8
   530  
   531  	// Channel is a designated bluetooth channel, only 1-30 are available for use.
   532  	// Since Linux 2.6.7 and further zero value is the first available channel.
   533  	Channel uint8
   534  
   535  	raw RawSockaddrRFCOMM
   536  }
   537  
   538  func (sa *SockaddrRFCOMM) sockaddr() (unsafe.Pointer, _Socklen, error) {
   539  	sa.raw.Family = AF_BLUETOOTH
   540  	sa.raw.Channel = sa.Channel
   541  	sa.raw.Bdaddr = sa.Addr
   542  	return unsafe.Pointer(&sa.raw), SizeofSockaddrRFCOMM, nil
   543  }
   544  
   545  // SockaddrCAN implements the Sockaddr interface for AF_CAN type sockets.
   546  // The RxID and TxID fields are used for transport protocol addressing in
   547  // (CAN_TP16, CAN_TP20, CAN_MCNET, and CAN_ISOTP), they can be left with
   548  // zero values for CAN_RAW and CAN_BCM sockets as they have no meaning.
   549  //
   550  // The SockaddrCAN struct must be bound to the socket file descriptor
   551  // using Bind before the CAN socket can be used.
   552  //
   553  //      // Read one raw CAN frame
   554  //      fd, _ := Socket(AF_CAN, SOCK_RAW, CAN_RAW)
   555  //      addr := &SockaddrCAN{Ifindex: index}
   556  //      Bind(fd, addr)
   557  //      frame := make([]byte, 16)
   558  //      Read(fd, frame)
   559  //
   560  // The full SocketCAN documentation can be found in the linux kernel
   561  // archives at: https://www.kernel.org/doc/Documentation/networking/can.txt
   562  type SockaddrCAN struct {
   563  	Ifindex int
   564  	RxID    uint32
   565  	TxID    uint32
   566  	raw     RawSockaddrCAN
   567  }
   568  
   569  func (sa *SockaddrCAN) sockaddr() (unsafe.Pointer, _Socklen, error) {
   570  	if sa.Ifindex < 0 || sa.Ifindex > 0x7fffffff {
   571  		return nil, 0, EINVAL
   572  	}
   573  	sa.raw.Family = AF_CAN
   574  	sa.raw.Ifindex = int32(sa.Ifindex)
   575  	rx := (*[4]byte)(unsafe.Pointer(&sa.RxID))
   576  	for i := 0; i < 4; i++ {
   577  		sa.raw.Addr[i] = rx[i]
   578  	}
   579  	tx := (*[4]byte)(unsafe.Pointer(&sa.TxID))
   580  	for i := 0; i < 4; i++ {
   581  		sa.raw.Addr[i+4] = tx[i]
   582  	}
   583  	return unsafe.Pointer(&sa.raw), SizeofSockaddrCAN, nil
   584  }
   585  
   586  // SockaddrCANJ1939 implements the Sockaddr interface for AF_CAN using J1939
   587  // protocol (https://en.wikipedia.org/wiki/SAE_J1939). For more information
   588  // on the purposes of the fields, check the official linux kernel documentation
   589  // available here: https://www.kernel.org/doc/Documentation/networking/j1939.rst
   590  type SockaddrCANJ1939 struct {
   591  	Ifindex int
   592  	Name    uint64
   593  	PGN     uint32
   594  	Addr    uint8
   595  	raw     RawSockaddrCAN
   596  }
   597  
   598  func (sa *SockaddrCANJ1939) sockaddr() (unsafe.Pointer, _Socklen, error) {
   599  	if sa.Ifindex < 0 || sa.Ifindex > 0x7fffffff {
   600  		return nil, 0, EINVAL
   601  	}
   602  	sa.raw.Family = AF_CAN
   603  	sa.raw.Ifindex = int32(sa.Ifindex)
   604  	n := (*[8]byte)(unsafe.Pointer(&sa.Name))
   605  	for i := 0; i < 8; i++ {
   606  		sa.raw.Addr[i] = n[i]
   607  	}
   608  	p := (*[4]byte)(unsafe.Pointer(&sa.PGN))
   609  	for i := 0; i < 4; i++ {
   610  		sa.raw.Addr[i+8] = p[i]
   611  	}
   612  	sa.raw.Addr[12] = sa.Addr
   613  	return unsafe.Pointer(&sa.raw), SizeofSockaddrCAN, nil
   614  }
   615  
   616  // SockaddrALG implements the Sockaddr interface for AF_ALG type sockets.
   617  // SockaddrALG enables userspace access to the Linux kernel's cryptography
   618  // subsystem. The Type and Name fields specify which type of hash or cipher
   619  // should be used with a given socket.
   620  //
   621  // To create a file descriptor that provides access to a hash or cipher, both
   622  // Bind and Accept must be used. Once the setup process is complete, input
   623  // data can be written to the socket, processed by the kernel, and then read
   624  // back as hash output or ciphertext.
   625  //
   626  // Here is an example of using an AF_ALG socket with SHA1 hashing.
   627  // The initial socket setup process is as follows:
   628  //
   629  //      // Open a socket to perform SHA1 hashing.
   630  //      fd, _ := unix.Socket(unix.AF_ALG, unix.SOCK_SEQPACKET, 0)
   631  //      addr := &unix.SockaddrALG{Type: "hash", Name: "sha1"}
   632  //      unix.Bind(fd, addr)
   633  //      // Note: unix.Accept does not work at this time; must invoke accept()
   634  //      // manually using unix.Syscall.
   635  //      hashfd, _, _ := unix.Syscall(unix.SYS_ACCEPT, uintptr(fd), 0, 0)
   636  //
   637  // Once a file descriptor has been returned from Accept, it may be used to
   638  // perform SHA1 hashing. The descriptor is not safe for concurrent use, but
   639  // may be re-used repeatedly with subsequent Write and Read operations.
   640  //
   641  // When hashing a small byte slice or string, a single Write and Read may
   642  // be used:
   643  //
   644  //      // Assume hashfd is already configured using the setup process.
   645  //      hash := os.NewFile(hashfd, "sha1")
   646  //      // Hash an input string and read the results. Each Write discards
   647  //      // previous hash state. Read always reads the current state.
   648  //      b := make([]byte, 20)
   649  //      for i := 0; i < 2; i++ {
   650  //          io.WriteString(hash, "Hello, world.")
   651  //          hash.Read(b)
   652  //          fmt.Println(hex.EncodeToString(b))
   653  //      }
   654  //      // Output:
   655  //      // 2ae01472317d1935a84797ec1983ae243fc6aa28
   656  //      // 2ae01472317d1935a84797ec1983ae243fc6aa28
   657  //
   658  // For hashing larger byte slices, or byte streams such as those read from
   659  // a file or socket, use Sendto with MSG_MORE to instruct the kernel to update
   660  // the hash digest instead of creating a new one for a given chunk and finalizing it.
   661  //
   662  //      // Assume hashfd and addr are already configured using the setup process.
   663  //      hash := os.NewFile(hashfd, "sha1")
   664  //      // Hash the contents of a file.
   665  //      f, _ := os.Open("/tmp/linux-4.10-rc7.tar.xz")
   666  //      b := make([]byte, 4096)
   667  //      for {
   668  //          n, err := f.Read(b)
   669  //          if err == io.EOF {
   670  //              break
   671  //          }
   672  //          unix.Sendto(hashfd, b[:n], unix.MSG_MORE, addr)
   673  //      }
   674  //      hash.Read(b)
   675  //      fmt.Println(hex.EncodeToString(b))
   676  //      // Output: 85cdcad0c06eef66f805ecce353bec9accbeecc5
   677  //
   678  // For more information, see: http://www.chronox.de/crypto-API/crypto/userspace-if.html.
   679  type SockaddrALG struct {
   680  	Type    string
   681  	Name    string
   682  	Feature uint32
   683  	Mask    uint32
   684  	raw     RawSockaddrALG
   685  }
   686  
   687  func (sa *SockaddrALG) sockaddr() (unsafe.Pointer, _Socklen, error) {
   688  	// Leave room for NUL byte terminator.
   689  	if len(sa.Type) > 13 {
   690  		return nil, 0, EINVAL
   691  	}
   692  	if len(sa.Name) > 63 {
   693  		return nil, 0, EINVAL
   694  	}
   695  
   696  	sa.raw.Family = AF_ALG
   697  	sa.raw.Feat = sa.Feature
   698  	sa.raw.Mask = sa.Mask
   699  
   700  	typ, err := ByteSliceFromString(sa.Type)
   701  	if err != nil {
   702  		return nil, 0, err
   703  	}
   704  	name, err := ByteSliceFromString(sa.Name)
   705  	if err != nil {
   706  		return nil, 0, err
   707  	}
   708  
   709  	copy(sa.raw.Type[:], typ)
   710  	copy(sa.raw.Name[:], name)
   711  
   712  	return unsafe.Pointer(&sa.raw), SizeofSockaddrALG, nil
   713  }
   714  
   715  // SockaddrVM implements the Sockaddr interface for AF_VSOCK type sockets.
   716  // SockaddrVM provides access to Linux VM sockets: a mechanism that enables
   717  // bidirectional communication between a hypervisor and its guest virtual
   718  // machines.
   719  type SockaddrVM struct {
   720  	// CID and Port specify a context ID and port address for a VM socket.
   721  	// Guests have a unique CID, and hosts may have a well-known CID of:
   722  	//  - VMADDR_CID_HYPERVISOR: refers to the hypervisor process.
   723  	//  - VMADDR_CID_LOCAL: refers to local communication (loopback).
   724  	//  - VMADDR_CID_HOST: refers to other processes on the host.
   725  	CID   uint32
   726  	Port  uint32
   727  	Flags uint8
   728  	raw   RawSockaddrVM
   729  }
   730  
   731  func (sa *SockaddrVM) sockaddr() (unsafe.Pointer, _Socklen, error) {
   732  	sa.raw.Family = AF_VSOCK
   733  	sa.raw.Port = sa.Port
   734  	sa.raw.Cid = sa.CID
   735  	sa.raw.Flags = sa.Flags
   736  
   737  	return unsafe.Pointer(&sa.raw), SizeofSockaddrVM, nil
   738  }
   739  
   740  type SockaddrXDP struct {
   741  	Flags        uint16
   742  	Ifindex      uint32
   743  	QueueID      uint32
   744  	SharedUmemFD uint32
   745  	raw          RawSockaddrXDP
   746  }
   747  
   748  func (sa *SockaddrXDP) sockaddr() (unsafe.Pointer, _Socklen, error) {
   749  	sa.raw.Family = AF_XDP
   750  	sa.raw.Flags = sa.Flags
   751  	sa.raw.Ifindex = sa.Ifindex
   752  	sa.raw.Queue_id = sa.QueueID
   753  	sa.raw.Shared_umem_fd = sa.SharedUmemFD
   754  
   755  	return unsafe.Pointer(&sa.raw), SizeofSockaddrXDP, nil
   756  }
   757  
   758  // This constant mirrors the #define of PX_PROTO_OE in
   759  // linux/if_pppox.h. We're defining this by hand here instead of
   760  // autogenerating through mkerrors.sh because including
   761  // linux/if_pppox.h causes some declaration conflicts with other
   762  // includes (linux/if_pppox.h includes linux/in.h, which conflicts
   763  // with netinet/in.h). Given that we only need a single zero constant
   764  // out of that file, it's cleaner to just define it by hand here.
   765  const px_proto_oe = 0
   766  
   767  type SockaddrPPPoE struct {
   768  	SID    uint16
   769  	Remote []byte
   770  	Dev    string
   771  	raw    RawSockaddrPPPoX
   772  }
   773  
   774  func (sa *SockaddrPPPoE) sockaddr() (unsafe.Pointer, _Socklen, error) {
   775  	if len(sa.Remote) != 6 {
   776  		return nil, 0, EINVAL
   777  	}
   778  	if len(sa.Dev) > IFNAMSIZ-1 {
   779  		return nil, 0, EINVAL
   780  	}
   781  
   782  	*(*uint16)(unsafe.Pointer(&sa.raw[0])) = AF_PPPOX
   783  	// This next field is in host-endian byte order. We can't use the
   784  	// same unsafe pointer cast as above, because this value is not
   785  	// 32-bit aligned and some architectures don't allow unaligned
   786  	// access.
   787  	//
   788  	// However, the value of px_proto_oe is 0, so we can use
   789  	// encoding/binary helpers to write the bytes without worrying
   790  	// about the ordering.
   791  	binary.BigEndian.PutUint32(sa.raw[2:6], px_proto_oe)
   792  	// This field is deliberately big-endian, unlike the previous
   793  	// one. The kernel expects SID to be in network byte order.
   794  	binary.BigEndian.PutUint16(sa.raw[6:8], sa.SID)
   795  	copy(sa.raw[8:14], sa.Remote)
   796  	for i := 14; i < 14+IFNAMSIZ; i++ {
   797  		sa.raw[i] = 0
   798  	}
   799  	copy(sa.raw[14:], sa.Dev)
   800  	return unsafe.Pointer(&sa.raw), SizeofSockaddrPPPoX, nil
   801  }
   802  
   803  // SockaddrTIPC implements the Sockaddr interface for AF_TIPC type sockets.
   804  // For more information on TIPC, see: http://tipc.sourceforge.net/.
   805  type SockaddrTIPC struct {
   806  	// Scope is the publication scopes when binding service/service range.
   807  	// Should be set to TIPC_CLUSTER_SCOPE or TIPC_NODE_SCOPE.
   808  	Scope int
   809  
   810  	// Addr is the type of address used to manipulate a socket. Addr must be
   811  	// one of:
   812  	//  - *TIPCSocketAddr: "id" variant in the C addr union
   813  	//  - *TIPCServiceRange: "nameseq" variant in the C addr union
   814  	//  - *TIPCServiceName: "name" variant in the C addr union
   815  	//
   816  	// If nil, EINVAL will be returned when the structure is used.
   817  	Addr TIPCAddr
   818  
   819  	raw RawSockaddrTIPC
   820  }
   821  
   822  // TIPCAddr is implemented by types that can be used as an address for
   823  // SockaddrTIPC. It is only implemented by *TIPCSocketAddr, *TIPCServiceRange,
   824  // and *TIPCServiceName.
   825  type TIPCAddr interface {
   826  	tipcAddrtype() uint8
   827  	tipcAddr() [12]byte
   828  }
   829  
   830  func (sa *TIPCSocketAddr) tipcAddr() [12]byte {
   831  	var out [12]byte
   832  	copy(out[:], (*(*[unsafe.Sizeof(TIPCSocketAddr{})]byte)(unsafe.Pointer(sa)))[:])
   833  	return out
   834  }
   835  
   836  func (sa *TIPCSocketAddr) tipcAddrtype() uint8 { return TIPC_SOCKET_ADDR }
   837  
   838  func (sa *TIPCServiceRange) tipcAddr() [12]byte {
   839  	var out [12]byte
   840  	copy(out[:], (*(*[unsafe.Sizeof(TIPCServiceRange{})]byte)(unsafe.Pointer(sa)))[:])
   841  	return out
   842  }
   843  
   844  func (sa *TIPCServiceRange) tipcAddrtype() uint8 { return TIPC_SERVICE_RANGE }
   845  
   846  func (sa *TIPCServiceName) tipcAddr() [12]byte {
   847  	var out [12]byte
   848  	copy(out[:], (*(*[unsafe.Sizeof(TIPCServiceName{})]byte)(unsafe.Pointer(sa)))[:])
   849  	return out
   850  }
   851  
   852  func (sa *TIPCServiceName) tipcAddrtype() uint8 { return TIPC_SERVICE_ADDR }
   853  
   854  func (sa *SockaddrTIPC) sockaddr() (unsafe.Pointer, _Socklen, error) {
   855  	if sa.Addr == nil {
   856  		return nil, 0, EINVAL
   857  	}
   858  
   859  	sa.raw.Family = AF_TIPC
   860  	sa.raw.Scope = int8(sa.Scope)
   861  	sa.raw.Addrtype = sa.Addr.tipcAddrtype()
   862  	sa.raw.Addr = sa.Addr.tipcAddr()
   863  
   864  	return unsafe.Pointer(&sa.raw), SizeofSockaddrTIPC, nil
   865  }
   866  
   867  // SockaddrL2TPIP implements the Sockaddr interface for IPPROTO_L2TP/AF_INET sockets.
   868  type SockaddrL2TPIP struct {
   869  	Addr   [4]byte
   870  	ConnId uint32
   871  	raw    RawSockaddrL2TPIP
   872  }
   873  
   874  func (sa *SockaddrL2TPIP) sockaddr() (unsafe.Pointer, _Socklen, error) {
   875  	sa.raw.Family = AF_INET
   876  	sa.raw.Conn_id = sa.ConnId
   877  	for i := 0; i < len(sa.Addr); i++ {
   878  		sa.raw.Addr[i] = sa.Addr[i]
   879  	}
   880  	return unsafe.Pointer(&sa.raw), SizeofSockaddrL2TPIP, nil
   881  }
   882  
   883  // SockaddrL2TPIP6 implements the Sockaddr interface for IPPROTO_L2TP/AF_INET6 sockets.
   884  type SockaddrL2TPIP6 struct {
   885  	Addr   [16]byte
   886  	ZoneId uint32
   887  	ConnId uint32
   888  	raw    RawSockaddrL2TPIP6
   889  }
   890  
   891  func (sa *SockaddrL2TPIP6) sockaddr() (unsafe.Pointer, _Socklen, error) {
   892  	sa.raw.Family = AF_INET6
   893  	sa.raw.Conn_id = sa.ConnId
   894  	sa.raw.Scope_id = sa.ZoneId
   895  	for i := 0; i < len(sa.Addr); i++ {
   896  		sa.raw.Addr[i] = sa.Addr[i]
   897  	}
   898  	return unsafe.Pointer(&sa.raw), SizeofSockaddrL2TPIP6, nil
   899  }
   900  
   901  // SockaddrIUCV implements the Sockaddr interface for AF_IUCV sockets.
   902  type SockaddrIUCV struct {
   903  	UserID string
   904  	Name   string
   905  	raw    RawSockaddrIUCV
   906  }
   907  
   908  func (sa *SockaddrIUCV) sockaddr() (unsafe.Pointer, _Socklen, error) {
   909  	sa.raw.Family = AF_IUCV
   910  	// These are EBCDIC encoded by the kernel, but we still need to pad them
   911  	// with blanks. Initializing with blanks allows the caller to feed in either
   912  	// a padded or an unpadded string.
   913  	for i := 0; i < 8; i++ {
   914  		sa.raw.Nodeid[i] = ' '
   915  		sa.raw.User_id[i] = ' '
   916  		sa.raw.Name[i] = ' '
   917  	}
   918  	if len(sa.UserID) > 8 || len(sa.Name) > 8 {
   919  		return nil, 0, EINVAL
   920  	}
   921  	for i, b := range []byte(sa.UserID[:]) {
   922  		sa.raw.User_id[i] = int8(b)
   923  	}
   924  	for i, b := range []byte(sa.Name[:]) {
   925  		sa.raw.Name[i] = int8(b)
   926  	}
   927  	return unsafe.Pointer(&sa.raw), SizeofSockaddrIUCV, nil
   928  }
   929  
   930  type SockaddrNFC struct {
   931  	DeviceIdx   uint32
   932  	TargetIdx   uint32
   933  	NFCProtocol uint32
   934  	raw         RawSockaddrNFC
   935  }
   936  
   937  func (sa *SockaddrNFC) sockaddr() (unsafe.Pointer, _Socklen, error) {
   938  	sa.raw.Sa_family = AF_NFC
   939  	sa.raw.Dev_idx = sa.DeviceIdx
   940  	sa.raw.Target_idx = sa.TargetIdx
   941  	sa.raw.Nfc_protocol = sa.NFCProtocol
   942  	return unsafe.Pointer(&sa.raw), SizeofSockaddrNFC, nil
   943  }
   944  
   945  type SockaddrNFCLLCP struct {
   946  	DeviceIdx      uint32
   947  	TargetIdx      uint32
   948  	NFCProtocol    uint32
   949  	DestinationSAP uint8
   950  	SourceSAP      uint8
   951  	ServiceName    string
   952  	raw            RawSockaddrNFCLLCP
   953  }
   954  
   955  func (sa *SockaddrNFCLLCP) sockaddr() (unsafe.Pointer, _Socklen, error) {
   956  	sa.raw.Sa_family = AF_NFC
   957  	sa.raw.Dev_idx = sa.DeviceIdx
   958  	sa.raw.Target_idx = sa.TargetIdx
   959  	sa.raw.Nfc_protocol = sa.NFCProtocol
   960  	sa.raw.Dsap = sa.DestinationSAP
   961  	sa.raw.Ssap = sa.SourceSAP
   962  	if len(sa.ServiceName) > len(sa.raw.Service_name) {
   963  		return nil, 0, EINVAL
   964  	}
   965  	copy(sa.raw.Service_name[:], sa.ServiceName)
   966  	sa.raw.SetServiceNameLen(len(sa.ServiceName))
   967  	return unsafe.Pointer(&sa.raw), SizeofSockaddrNFCLLCP, nil
   968  }
   969  
   970  var socketProtocol = func(fd int) (int, error) {
   971  	return GetsockoptInt(fd, SOL_SOCKET, SO_PROTOCOL)
   972  }
   973  
   974  func anyToSockaddr(fd int, rsa *RawSockaddrAny) (Sockaddr, error) {
   975  	switch rsa.Addr.Family {
   976  	case AF_NETLINK:
   977  		pp := (*RawSockaddrNetlink)(unsafe.Pointer(rsa))
   978  		sa := new(SockaddrNetlink)
   979  		sa.Family = pp.Family
   980  		sa.Pad = pp.Pad
   981  		sa.Pid = pp.Pid
   982  		sa.Groups = pp.Groups
   983  		return sa, nil
   984  
   985  	case AF_PACKET:
   986  		pp := (*RawSockaddrLinklayer)(unsafe.Pointer(rsa))
   987  		sa := new(SockaddrLinklayer)
   988  		sa.Protocol = pp.Protocol
   989  		sa.Ifindex = int(pp.Ifindex)
   990  		sa.Hatype = pp.Hatype
   991  		sa.Pkttype = pp.Pkttype
   992  		sa.Halen = pp.Halen
   993  		for i := 0; i < len(sa.Addr); i++ {
   994  			sa.Addr[i] = pp.Addr[i]
   995  		}
   996  		return sa, nil
   997  
   998  	case AF_UNIX:
   999  		pp := (*RawSockaddrUnix)(unsafe.Pointer(rsa))
  1000  		sa := new(SockaddrUnix)
  1001  		if pp.Path[0] == 0 {
  1002  			// "Abstract" Unix domain socket.
  1003  			// Rewrite leading NUL as @ for textual display.
  1004  			// (This is the standard convention.)
  1005  			// Not friendly to overwrite in place,
  1006  			// but the callers below don't care.
  1007  			pp.Path[0] = '@'
  1008  		}
  1009  
  1010  		// Assume path ends at NUL.
  1011  		// This is not technically the Linux semantics for
  1012  		// abstract Unix domain sockets--they are supposed
  1013  		// to be uninterpreted fixed-size binary blobs--but
  1014  		// everyone uses this convention.
  1015  		n := 0
  1016  		for n < len(pp.Path) && pp.Path[n] != 0 {
  1017  			n++
  1018  		}
  1019  		bytes := (*[len(pp.Path)]byte)(unsafe.Pointer(&pp.Path[0]))[0:n]
  1020  		sa.Name = string(bytes)
  1021  		return sa, nil
  1022  
  1023  	case AF_INET:
  1024  		proto, err := socketProtocol(fd)
  1025  		if err != nil {
  1026  			return nil, err
  1027  		}
  1028  
  1029  		switch proto {
  1030  		case IPPROTO_L2TP:
  1031  			pp := (*RawSockaddrL2TPIP)(unsafe.Pointer(rsa))
  1032  			sa := new(SockaddrL2TPIP)
  1033  			sa.ConnId = pp.Conn_id
  1034  			for i := 0; i < len(sa.Addr); i++ {
  1035  				sa.Addr[i] = pp.Addr[i]
  1036  			}
  1037  			return sa, nil
  1038  		default:
  1039  			pp := (*RawSockaddrInet4)(unsafe.Pointer(rsa))
  1040  			sa := new(SockaddrInet4)
  1041  			p := (*[2]byte)(unsafe.Pointer(&pp.Port))
  1042  			sa.Port = int(p[0])<<8 + int(p[1])
  1043  			for i := 0; i < len(sa.Addr); i++ {
  1044  				sa.Addr[i] = pp.Addr[i]
  1045  			}
  1046  			return sa, nil
  1047  		}
  1048  
  1049  	case AF_INET6:
  1050  		proto, err := socketProtocol(fd)
  1051  		if err != nil {
  1052  			return nil, err
  1053  		}
  1054  
  1055  		switch proto {
  1056  		case IPPROTO_L2TP:
  1057  			pp := (*RawSockaddrL2TPIP6)(unsafe.Pointer(rsa))
  1058  			sa := new(SockaddrL2TPIP6)
  1059  			sa.ConnId = pp.Conn_id
  1060  			sa.ZoneId = pp.Scope_id
  1061  			for i := 0; i < len(sa.Addr); i++ {
  1062  				sa.Addr[i] = pp.Addr[i]
  1063  			}
  1064  			return sa, nil
  1065  		default:
  1066  			pp := (*RawSockaddrInet6)(unsafe.Pointer(rsa))
  1067  			sa := new(SockaddrInet6)
  1068  			p := (*[2]byte)(unsafe.Pointer(&pp.Port))
  1069  			sa.Port = int(p[0])<<8 + int(p[1])
  1070  			sa.ZoneId = pp.Scope_id
  1071  			for i := 0; i < len(sa.Addr); i++ {
  1072  				sa.Addr[i] = pp.Addr[i]
  1073  			}
  1074  			return sa, nil
  1075  		}
  1076  
  1077  	case AF_VSOCK:
  1078  		pp := (*RawSockaddrVM)(unsafe.Pointer(rsa))
  1079  		sa := &SockaddrVM{
  1080  			CID:   pp.Cid,
  1081  			Port:  pp.Port,
  1082  			Flags: pp.Flags,
  1083  		}
  1084  		return sa, nil
  1085  	case AF_BLUETOOTH:
  1086  		proto, err := socketProtocol(fd)
  1087  		if err != nil {
  1088  			return nil, err
  1089  		}
  1090  		// only BTPROTO_L2CAP and BTPROTO_RFCOMM can accept connections
  1091  		switch proto {
  1092  		case BTPROTO_L2CAP:
  1093  			pp := (*RawSockaddrL2)(unsafe.Pointer(rsa))
  1094  			sa := &SockaddrL2{
  1095  				PSM:      pp.Psm,
  1096  				CID:      pp.Cid,
  1097  				Addr:     pp.Bdaddr,
  1098  				AddrType: pp.Bdaddr_type,
  1099  			}
  1100  			return sa, nil
  1101  		case BTPROTO_RFCOMM:
  1102  			pp := (*RawSockaddrRFCOMM)(unsafe.Pointer(rsa))
  1103  			sa := &SockaddrRFCOMM{
  1104  				Channel: pp.Channel,
  1105  				Addr:    pp.Bdaddr,
  1106  			}
  1107  			return sa, nil
  1108  		}
  1109  	case AF_XDP:
  1110  		pp := (*RawSockaddrXDP)(unsafe.Pointer(rsa))
  1111  		sa := &SockaddrXDP{
  1112  			Flags:        pp.Flags,
  1113  			Ifindex:      pp.Ifindex,
  1114  			QueueID:      pp.Queue_id,
  1115  			SharedUmemFD: pp.Shared_umem_fd,
  1116  		}
  1117  		return sa, nil
  1118  	case AF_PPPOX:
  1119  		pp := (*RawSockaddrPPPoX)(unsafe.Pointer(rsa))
  1120  		if binary.BigEndian.Uint32(pp[2:6]) != px_proto_oe {
  1121  			return nil, EINVAL
  1122  		}
  1123  		sa := &SockaddrPPPoE{
  1124  			SID:    binary.BigEndian.Uint16(pp[6:8]),
  1125  			Remote: pp[8:14],
  1126  		}
  1127  		for i := 14; i < 14+IFNAMSIZ; i++ {
  1128  			if pp[i] == 0 {
  1129  				sa.Dev = string(pp[14:i])
  1130  				break
  1131  			}
  1132  		}
  1133  		return sa, nil
  1134  	case AF_TIPC:
  1135  		pp := (*RawSockaddrTIPC)(unsafe.Pointer(rsa))
  1136  
  1137  		sa := &SockaddrTIPC{
  1138  			Scope: int(pp.Scope),
  1139  		}
  1140  
  1141  		// Determine which union variant is present in pp.Addr by checking
  1142  		// pp.Addrtype.
  1143  		switch pp.Addrtype {
  1144  		case TIPC_SERVICE_RANGE:
  1145  			sa.Addr = (*TIPCServiceRange)(unsafe.Pointer(&pp.Addr))
  1146  		case TIPC_SERVICE_ADDR:
  1147  			sa.Addr = (*TIPCServiceName)(unsafe.Pointer(&pp.Addr))
  1148  		case TIPC_SOCKET_ADDR:
  1149  			sa.Addr = (*TIPCSocketAddr)(unsafe.Pointer(&pp.Addr))
  1150  		default:
  1151  			return nil, EINVAL
  1152  		}
  1153  
  1154  		return sa, nil
  1155  	case AF_IUCV:
  1156  		pp := (*RawSockaddrIUCV)(unsafe.Pointer(rsa))
  1157  
  1158  		var user [8]byte
  1159  		var name [8]byte
  1160  
  1161  		for i := 0; i < 8; i++ {
  1162  			user[i] = byte(pp.User_id[i])
  1163  			name[i] = byte(pp.Name[i])
  1164  		}
  1165  
  1166  		sa := &SockaddrIUCV{
  1167  			UserID: string(user[:]),
  1168  			Name:   string(name[:]),
  1169  		}
  1170  		return sa, nil
  1171  
  1172  	case AF_CAN:
  1173  		proto, err := socketProtocol(fd)
  1174  		if err != nil {
  1175  			return nil, err
  1176  		}
  1177  
  1178  		pp := (*RawSockaddrCAN)(unsafe.Pointer(rsa))
  1179  
  1180  		switch proto {
  1181  		case CAN_J1939:
  1182  			sa := &SockaddrCANJ1939{
  1183  				Ifindex: int(pp.Ifindex),
  1184  			}
  1185  			name := (*[8]byte)(unsafe.Pointer(&sa.Name))
  1186  			for i := 0; i < 8; i++ {
  1187  				name[i] = pp.Addr[i]
  1188  			}
  1189  			pgn := (*[4]byte)(unsafe.Pointer(&sa.PGN))
  1190  			for i := 0; i < 4; i++ {
  1191  				pgn[i] = pp.Addr[i+8]
  1192  			}
  1193  			addr := (*[1]byte)(unsafe.Pointer(&sa.Addr))
  1194  			addr[0] = pp.Addr[12]
  1195  			return sa, nil
  1196  		default:
  1197  			sa := &SockaddrCAN{
  1198  				Ifindex: int(pp.Ifindex),
  1199  			}
  1200  			rx := (*[4]byte)(unsafe.Pointer(&sa.RxID))
  1201  			for i := 0; i < 4; i++ {
  1202  				rx[i] = pp.Addr[i]
  1203  			}
  1204  			tx := (*[4]byte)(unsafe.Pointer(&sa.TxID))
  1205  			for i := 0; i < 4; i++ {
  1206  				tx[i] = pp.Addr[i+4]
  1207  			}
  1208  			return sa, nil
  1209  		}
  1210  	case AF_NFC:
  1211  		proto, err := socketProtocol(fd)
  1212  		if err != nil {
  1213  			return nil, err
  1214  		}
  1215  		switch proto {
  1216  		case NFC_SOCKPROTO_RAW:
  1217  			pp := (*RawSockaddrNFC)(unsafe.Pointer(rsa))
  1218  			sa := &SockaddrNFC{
  1219  				DeviceIdx:   pp.Dev_idx,
  1220  				TargetIdx:   pp.Target_idx,
  1221  				NFCProtocol: pp.Nfc_protocol,
  1222  			}
  1223  			return sa, nil
  1224  		case NFC_SOCKPROTO_LLCP:
  1225  			pp := (*RawSockaddrNFCLLCP)(unsafe.Pointer(rsa))
  1226  			if uint64(pp.Service_name_len) > uint64(len(pp.Service_name)) {
  1227  				return nil, EINVAL
  1228  			}
  1229  			sa := &SockaddrNFCLLCP{
  1230  				DeviceIdx:      pp.Dev_idx,
  1231  				TargetIdx:      pp.Target_idx,
  1232  				NFCProtocol:    pp.Nfc_protocol,
  1233  				DestinationSAP: pp.Dsap,
  1234  				SourceSAP:      pp.Ssap,
  1235  				ServiceName:    string(pp.Service_name[:pp.Service_name_len]),
  1236  			}
  1237  			return sa, nil
  1238  		default:
  1239  			return nil, EINVAL
  1240  		}
  1241  	}
  1242  	return nil, EAFNOSUPPORT
  1243  }
  1244  
  1245  func Accept(fd int) (nfd int, sa Sockaddr, err error) {
  1246  	var rsa RawSockaddrAny
  1247  	var len _Socklen = SizeofSockaddrAny
  1248  	nfd, err = accept4(fd, &rsa, &len, 0)
  1249  	if err != nil {
  1250  		return
  1251  	}
  1252  	sa, err = anyToSockaddr(fd, &rsa)
  1253  	if err != nil {
  1254  		Close(nfd)
  1255  		nfd = 0
  1256  	}
  1257  	return
  1258  }
  1259  
  1260  func Accept4(fd int, flags int) (nfd int, sa Sockaddr, err error) {
  1261  	var rsa RawSockaddrAny
  1262  	var len _Socklen = SizeofSockaddrAny
  1263  	nfd, err = accept4(fd, &rsa, &len, flags)
  1264  	if err != nil {
  1265  		return
  1266  	}
  1267  	if len > SizeofSockaddrAny {
  1268  		panic("RawSockaddrAny too small")
  1269  	}
  1270  	sa, err = anyToSockaddr(fd, &rsa)
  1271  	if err != nil {
  1272  		Close(nfd)
  1273  		nfd = 0
  1274  	}
  1275  	return
  1276  }
  1277  
  1278  func Getsockname(fd int) (sa Sockaddr, err error) {
  1279  	var rsa RawSockaddrAny
  1280  	var len _Socklen = SizeofSockaddrAny
  1281  	if err = getsockname(fd, &rsa, &len); err != nil {
  1282  		return
  1283  	}
  1284  	return anyToSockaddr(fd, &rsa)
  1285  }
  1286  
  1287  func GetsockoptIPMreqn(fd, level, opt int) (*IPMreqn, error) {
  1288  	var value IPMreqn
  1289  	vallen := _Socklen(SizeofIPMreqn)
  1290  	err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
  1291  	return &value, err
  1292  }
  1293  
  1294  func GetsockoptUcred(fd, level, opt int) (*Ucred, error) {
  1295  	var value Ucred
  1296  	vallen := _Socklen(SizeofUcred)
  1297  	err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
  1298  	return &value, err
  1299  }
  1300  
  1301  func GetsockoptTCPInfo(fd, level, opt int) (*TCPInfo, error) {
  1302  	var value TCPInfo
  1303  	vallen := _Socklen(SizeofTCPInfo)
  1304  	err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
  1305  	return &value, err
  1306  }
  1307  
  1308  // GetsockoptString returns the string value of the socket option opt for the
  1309  // socket associated with fd at the given socket level.
  1310  func GetsockoptString(fd, level, opt int) (string, error) {
  1311  	buf := make([]byte, 256)
  1312  	vallen := _Socklen(len(buf))
  1313  	err := getsockopt(fd, level, opt, unsafe.Pointer(&buf[0]), &vallen)
  1314  	if err != nil {
  1315  		if err == ERANGE {
  1316  			buf = make([]byte, vallen)
  1317  			err = getsockopt(fd, level, opt, unsafe.Pointer(&buf[0]), &vallen)
  1318  		}
  1319  		if err != nil {
  1320  			return "", err
  1321  		}
  1322  	}
  1323  	return string(buf[:vallen-1]), nil
  1324  }
  1325  
  1326  func GetsockoptTpacketStats(fd, level, opt int) (*TpacketStats, error) {
  1327  	var value TpacketStats
  1328  	vallen := _Socklen(SizeofTpacketStats)
  1329  	err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
  1330  	return &value, err
  1331  }
  1332  
  1333  func GetsockoptTpacketStatsV3(fd, level, opt int) (*TpacketStatsV3, error) {
  1334  	var value TpacketStatsV3
  1335  	vallen := _Socklen(SizeofTpacketStatsV3)
  1336  	err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
  1337  	return &value, err
  1338  }
  1339  
  1340  func SetsockoptIPMreqn(fd, level, opt int, mreq *IPMreqn) (err error) {
  1341  	return setsockopt(fd, level, opt, unsafe.Pointer(mreq), unsafe.Sizeof(*mreq))
  1342  }
  1343  
  1344  func SetsockoptPacketMreq(fd, level, opt int, mreq *PacketMreq) error {
  1345  	return setsockopt(fd, level, opt, unsafe.Pointer(mreq), unsafe.Sizeof(*mreq))
  1346  }
  1347  
  1348  // SetsockoptSockFprog attaches a classic BPF or an extended BPF program to a
  1349  // socket to filter incoming packets.  See 'man 7 socket' for usage information.
  1350  func SetsockoptSockFprog(fd, level, opt int, fprog *SockFprog) error {
  1351  	return setsockopt(fd, level, opt, unsafe.Pointer(fprog), unsafe.Sizeof(*fprog))
  1352  }
  1353  
  1354  func SetsockoptCanRawFilter(fd, level, opt int, filter []CanFilter) error {
  1355  	var p unsafe.Pointer
  1356  	if len(filter) > 0 {
  1357  		p = unsafe.Pointer(&filter[0])
  1358  	}
  1359  	return setsockopt(fd, level, opt, p, uintptr(len(filter)*SizeofCanFilter))
  1360  }
  1361  
  1362  func SetsockoptTpacketReq(fd, level, opt int, tp *TpacketReq) error {
  1363  	return setsockopt(fd, level, opt, unsafe.Pointer(tp), unsafe.Sizeof(*tp))
  1364  }
  1365  
  1366  func SetsockoptTpacketReq3(fd, level, opt int, tp *TpacketReq3) error {
  1367  	return setsockopt(fd, level, opt, unsafe.Pointer(tp), unsafe.Sizeof(*tp))
  1368  }
  1369  
  1370  func SetsockoptTCPRepairOpt(fd, level, opt int, o []TCPRepairOpt) (err error) {
  1371  	if len(o) == 0 {
  1372  		return EINVAL
  1373  	}
  1374  	return setsockopt(fd, level, opt, unsafe.Pointer(&o[0]), uintptr(SizeofTCPRepairOpt*len(o)))
  1375  }
  1376  
  1377  // Keyctl Commands (http://man7.org/linux/man-pages/man2/keyctl.2.html)
  1378  
  1379  // KeyctlInt calls keyctl commands in which each argument is an int.
  1380  // These commands are KEYCTL_REVOKE, KEYCTL_CHOWN, KEYCTL_CLEAR, KEYCTL_LINK,
  1381  // KEYCTL_UNLINK, KEYCTL_NEGATE, KEYCTL_SET_REQKEY_KEYRING, KEYCTL_SET_TIMEOUT,
  1382  // KEYCTL_ASSUME_AUTHORITY, KEYCTL_SESSION_TO_PARENT, KEYCTL_REJECT,
  1383  // KEYCTL_INVALIDATE, and KEYCTL_GET_PERSISTENT.
  1384  //sys	KeyctlInt(cmd int, arg2 int, arg3 int, arg4 int, arg5 int) (ret int, err error) = SYS_KEYCTL
  1385  
  1386  // KeyctlBuffer calls keyctl commands in which the third and fourth
  1387  // arguments are a buffer and its length, respectively.
  1388  // These commands are KEYCTL_UPDATE, KEYCTL_READ, and KEYCTL_INSTANTIATE.
  1389  //sys	KeyctlBuffer(cmd int, arg2 int, buf []byte, arg5 int) (ret int, err error) = SYS_KEYCTL
  1390  
  1391  // KeyctlString calls keyctl commands which return a string.
  1392  // These commands are KEYCTL_DESCRIBE and KEYCTL_GET_SECURITY.
  1393  func KeyctlString(cmd int, id int) (string, error) {
  1394  	// We must loop as the string data may change in between the syscalls.
  1395  	// We could allocate a large buffer here to reduce the chance that the
  1396  	// syscall needs to be called twice; however, this is unnecessary as
  1397  	// the performance loss is negligible.
  1398  	var buffer []byte
  1399  	for {
  1400  		// Try to fill the buffer with data
  1401  		length, err := KeyctlBuffer(cmd, id, buffer, 0)
  1402  		if err != nil {
  1403  			return "", err
  1404  		}
  1405  
  1406  		// Check if the data was written
  1407  		if length <= len(buffer) {
  1408  			// Exclude the null terminator
  1409  			return string(buffer[:length-1]), nil
  1410  		}
  1411  
  1412  		// Make a bigger buffer if needed
  1413  		buffer = make([]byte, length)
  1414  	}
  1415  }
  1416  
  1417  // Keyctl commands with special signatures.
  1418  
  1419  // KeyctlGetKeyringID implements the KEYCTL_GET_KEYRING_ID command.
  1420  // See the full documentation at:
  1421  // http://man7.org/linux/man-pages/man3/keyctl_get_keyring_ID.3.html
  1422  func KeyctlGetKeyringID(id int, create bool) (ringid int, err error) {
  1423  	createInt := 0
  1424  	if create {
  1425  		createInt = 1
  1426  	}
  1427  	return KeyctlInt(KEYCTL_GET_KEYRING_ID, id, createInt, 0, 0)
  1428  }
  1429  
  1430  // KeyctlSetperm implements the KEYCTL_SETPERM command. The perm value is the
  1431  // key handle permission mask as described in the "keyctl setperm" section of
  1432  // http://man7.org/linux/man-pages/man1/keyctl.1.html.
  1433  // See the full documentation at:
  1434  // http://man7.org/linux/man-pages/man3/keyctl_setperm.3.html
  1435  func KeyctlSetperm(id int, perm uint32) error {
  1436  	_, err := KeyctlInt(KEYCTL_SETPERM, id, int(perm), 0, 0)
  1437  	return err
  1438  }
  1439  
  1440  //sys	keyctlJoin(cmd int, arg2 string) (ret int, err error) = SYS_KEYCTL
  1441  
  1442  // KeyctlJoinSessionKeyring implements the KEYCTL_JOIN_SESSION_KEYRING command.
  1443  // See the full documentation at:
  1444  // http://man7.org/linux/man-pages/man3/keyctl_join_session_keyring.3.html
  1445  func KeyctlJoinSessionKeyring(name string) (ringid int, err error) {
  1446  	return keyctlJoin(KEYCTL_JOIN_SESSION_KEYRING, name)
  1447  }
  1448  
  1449  //sys	keyctlSearch(cmd int, arg2 int, arg3 string, arg4 string, arg5 int) (ret int, err error) = SYS_KEYCTL
  1450  
  1451  // KeyctlSearch implements the KEYCTL_SEARCH command.
  1452  // See the full documentation at:
  1453  // http://man7.org/linux/man-pages/man3/keyctl_search.3.html
  1454  func KeyctlSearch(ringid int, keyType, description string, destRingid int) (id int, err error) {
  1455  	return keyctlSearch(KEYCTL_SEARCH, ringid, keyType, description, destRingid)
  1456  }
  1457  
  1458  //sys	keyctlIOV(cmd int, arg2 int, payload []Iovec, arg5 int) (err error) = SYS_KEYCTL
  1459  
  1460  // KeyctlInstantiateIOV implements the KEYCTL_INSTANTIATE_IOV command. This
  1461  // command is similar to KEYCTL_INSTANTIATE, except that the payload is a slice
  1462  // of Iovec (each of which represents a buffer) instead of a single buffer.
  1463  // See the full documentation at:
  1464  // http://man7.org/linux/man-pages/man3/keyctl_instantiate_iov.3.html
  1465  func KeyctlInstantiateIOV(id int, payload []Iovec, ringid int) error {
  1466  	return keyctlIOV(KEYCTL_INSTANTIATE_IOV, id, payload, ringid)
  1467  }
  1468  
  1469  //sys	keyctlDH(cmd int, arg2 *KeyctlDHParams, buf []byte) (ret int, err error) = SYS_KEYCTL
  1470  
  1471  // KeyctlDHCompute implements the KEYCTL_DH_COMPUTE command. This command
  1472  // computes a Diffie-Hellman shared secret based on the provide params. The
  1473  // secret is written to the provided buffer and the returned size is the number
  1474  // of bytes written (returning an error if there is insufficient space in the
  1475  // buffer). If a nil buffer is passed in, this function returns the minimum
  1476  // buffer length needed to store the appropriate data. Note that this differs
  1477  // from KEYCTL_READ's behavior which always returns the requested payload size.
  1478  // See the full documentation at:
  1479  // http://man7.org/linux/man-pages/man3/keyctl_dh_compute.3.html
  1480  func KeyctlDHCompute(params *KeyctlDHParams, buffer []byte) (size int, err error) {
  1481  	return keyctlDH(KEYCTL_DH_COMPUTE, params, buffer)
  1482  }
  1483  
  1484  // KeyctlRestrictKeyring implements the KEYCTL_RESTRICT_KEYRING command. This
  1485  // command limits the set of keys that can be linked to the keyring, regardless
  1486  // of keyring permissions. The command requires the "setattr" permission.
  1487  //
  1488  // When called with an empty keyType the command locks the keyring, preventing
  1489  // any further keys from being linked to the keyring.
  1490  //
  1491  // The "asymmetric" keyType defines restrictions requiring key payloads to be
  1492  // DER encoded X.509 certificates signed by keys in another keyring. Restrictions
  1493  // for "asymmetric" include "builtin_trusted", "builtin_and_secondary_trusted",
  1494  // "key_or_keyring:<key>", and "key_or_keyring:<key>:chain".
  1495  //
  1496  // As of Linux 4.12, only the "asymmetric" keyType defines type-specific
  1497  // restrictions.
  1498  //
  1499  // See the full documentation at:
  1500  // http://man7.org/linux/man-pages/man3/keyctl_restrict_keyring.3.html
  1501  // http://man7.org/linux/man-pages/man2/keyctl.2.html
  1502  func KeyctlRestrictKeyring(ringid int, keyType string, restriction string) error {
  1503  	if keyType == "" {
  1504  		return keyctlRestrictKeyring(KEYCTL_RESTRICT_KEYRING, ringid)
  1505  	}
  1506  	return keyctlRestrictKeyringByType(KEYCTL_RESTRICT_KEYRING, ringid, keyType, restriction)
  1507  }
  1508  
  1509  //sys	keyctlRestrictKeyringByType(cmd int, arg2 int, keyType string, restriction string) (err error) = SYS_KEYCTL
  1510  //sys	keyctlRestrictKeyring(cmd int, arg2 int) (err error) = SYS_KEYCTL
  1511  
  1512  func Recvmsg(fd int, p, oob []byte, flags int) (n, oobn int, recvflags int, from Sockaddr, err error) {
  1513  	var msg Msghdr
  1514  	var rsa RawSockaddrAny
  1515  	msg.Name = (*byte)(unsafe.Pointer(&rsa))
  1516  	msg.Namelen = uint32(SizeofSockaddrAny)
  1517  	var iov Iovec
  1518  	if len(p) > 0 {
  1519  		iov.Base = &p[0]
  1520  		iov.SetLen(len(p))
  1521  	}
  1522  	var dummy byte
  1523  	if len(oob) > 0 {
  1524  		if len(p) == 0 {
  1525  			var sockType int
  1526  			sockType, err = GetsockoptInt(fd, SOL_SOCKET, SO_TYPE)
  1527  			if err != nil {
  1528  				return
  1529  			}
  1530  			// receive at least one normal byte
  1531  			if sockType != SOCK_DGRAM {
  1532  				iov.Base = &dummy
  1533  				iov.SetLen(1)
  1534  			}
  1535  		}
  1536  		msg.Control = &oob[0]
  1537  		msg.SetControllen(len(oob))
  1538  	}
  1539  	msg.Iov = &iov
  1540  	msg.Iovlen = 1
  1541  	if n, err = recvmsg(fd, &msg, flags); err != nil {
  1542  		return
  1543  	}
  1544  	oobn = int(msg.Controllen)
  1545  	recvflags = int(msg.Flags)
  1546  	// source address is only specified if the socket is unconnected
  1547  	if rsa.Addr.Family != AF_UNSPEC {
  1548  		from, err = anyToSockaddr(fd, &rsa)
  1549  	}
  1550  	return
  1551  }
  1552  
  1553  func Sendmsg(fd int, p, oob []byte, to Sockaddr, flags int) (err error) {
  1554  	_, err = SendmsgN(fd, p, oob, to, flags)
  1555  	return
  1556  }
  1557  
  1558  func SendmsgN(fd int, p, oob []byte, to Sockaddr, flags int) (n int, err error) {
  1559  	var ptr unsafe.Pointer
  1560  	var salen _Socklen
  1561  	if to != nil {
  1562  		var err error
  1563  		ptr, salen, err = to.sockaddr()
  1564  		if err != nil {
  1565  			return 0, err
  1566  		}
  1567  	}
  1568  	var msg Msghdr
  1569  	msg.Name = (*byte)(ptr)
  1570  	msg.Namelen = uint32(salen)
  1571  	var iov Iovec
  1572  	if len(p) > 0 {
  1573  		iov.Base = &p[0]
  1574  		iov.SetLen(len(p))
  1575  	}
  1576  	var dummy byte
  1577  	if len(oob) > 0 {
  1578  		if len(p) == 0 {
  1579  			var sockType int
  1580  			sockType, err = GetsockoptInt(fd, SOL_SOCKET, SO_TYPE)
  1581  			if err != nil {
  1582  				return 0, err
  1583  			}
  1584  			// send at least one normal byte
  1585  			if sockType != SOCK_DGRAM {
  1586  				iov.Base = &dummy
  1587  				iov.SetLen(1)
  1588  			}
  1589  		}
  1590  		msg.Control = &oob[0]
  1591  		msg.SetControllen(len(oob))
  1592  	}
  1593  	msg.Iov = &iov
  1594  	msg.Iovlen = 1
  1595  	if n, err = sendmsg(fd, &msg, flags); err != nil {
  1596  		return 0, err
  1597  	}
  1598  	if len(oob) > 0 && len(p) == 0 {
  1599  		n = 0
  1600  	}
  1601  	return n, nil
  1602  }
  1603  
  1604  // BindToDevice binds the socket associated with fd to device.
  1605  func BindToDevice(fd int, device string) (err error) {
  1606  	return SetsockoptString(fd, SOL_SOCKET, SO_BINDTODEVICE, device)
  1607  }
  1608  
  1609  //sys	ptrace(request int, pid int, addr uintptr, data uintptr) (err error)
  1610  
  1611  func ptracePeek(req int, pid int, addr uintptr, out []byte) (count int, err error) {
  1612  	// The peek requests are machine-size oriented, so we wrap it
  1613  	// to retrieve arbitrary-length data.
  1614  
  1615  	// The ptrace syscall differs from glibc's ptrace.
  1616  	// Peeks returns the word in *data, not as the return value.
  1617  
  1618  	var buf [SizeofPtr]byte
  1619  
  1620  	// Leading edge. PEEKTEXT/PEEKDATA don't require aligned
  1621  	// access (PEEKUSER warns that it might), but if we don't
  1622  	// align our reads, we might straddle an unmapped page
  1623  	// boundary and not get the bytes leading up to the page
  1624  	// boundary.
  1625  	n := 0
  1626  	if addr%SizeofPtr != 0 {
  1627  		err = ptrace(req, pid, addr-addr%SizeofPtr, uintptr(unsafe.Pointer(&buf[0])))
  1628  		if err != nil {
  1629  			return 0, err
  1630  		}
  1631  		n += copy(out, buf[addr%SizeofPtr:])
  1632  		out = out[n:]
  1633  	}
  1634  
  1635  	// Remainder.
  1636  	for len(out) > 0 {
  1637  		// We use an internal buffer to guarantee alignment.
  1638  		// It's not documented if this is necessary, but we're paranoid.
  1639  		err = ptrace(req, pid, addr+uintptr(n), uintptr(unsafe.Pointer(&buf[0])))
  1640  		if err != nil {
  1641  			return n, err
  1642  		}
  1643  		copied := copy(out, buf[0:])
  1644  		n += copied
  1645  		out = out[copied:]
  1646  	}
  1647  
  1648  	return n, nil
  1649  }
  1650  
  1651  func PtracePeekText(pid int, addr uintptr, out []byte) (count int, err error) {
  1652  	return ptracePeek(PTRACE_PEEKTEXT, pid, addr, out)
  1653  }
  1654  
  1655  func PtracePeekData(pid int, addr uintptr, out []byte) (count int, err error) {
  1656  	return ptracePeek(PTRACE_PEEKDATA, pid, addr, out)
  1657  }
  1658  
  1659  func PtracePeekUser(pid int, addr uintptr, out []byte) (count int, err error) {
  1660  	return ptracePeek(PTRACE_PEEKUSR, pid, addr, out)
  1661  }
  1662  
  1663  func ptracePoke(pokeReq int, peekReq int, pid int, addr uintptr, data []byte) (count int, err error) {
  1664  	// As for ptracePeek, we need to align our accesses to deal
  1665  	// with the possibility of straddling an invalid page.
  1666  
  1667  	// Leading edge.
  1668  	n := 0
  1669  	if addr%SizeofPtr != 0 {
  1670  		var buf [SizeofPtr]byte
  1671  		err = ptrace(peekReq, pid, addr-addr%SizeofPtr, uintptr(unsafe.Pointer(&buf[0])))
  1672  		if err != nil {
  1673  			return 0, err
  1674  		}
  1675  		n += copy(buf[addr%SizeofPtr:], data)
  1676  		word := *((*uintptr)(unsafe.Pointer(&buf[0])))
  1677  		err = ptrace(pokeReq, pid, addr-addr%SizeofPtr, word)
  1678  		if err != nil {
  1679  			return 0, err
  1680  		}
  1681  		data = data[n:]
  1682  	}
  1683  
  1684  	// Interior.
  1685  	for len(data) > SizeofPtr {
  1686  		word := *((*uintptr)(unsafe.Pointer(&data[0])))
  1687  		err = ptrace(pokeReq, pid, addr+uintptr(n), word)
  1688  		if err != nil {
  1689  			return n, err
  1690  		}
  1691  		n += SizeofPtr
  1692  		data = data[SizeofPtr:]
  1693  	}
  1694  
  1695  	// Trailing edge.
  1696  	if len(data) > 0 {
  1697  		var buf [SizeofPtr]byte
  1698  		err = ptrace(peekReq, pid, addr+uintptr(n), uintptr(unsafe.Pointer(&buf[0])))
  1699  		if err != nil {
  1700  			return n, err
  1701  		}
  1702  		copy(buf[0:], data)
  1703  		word := *((*uintptr)(unsafe.Pointer(&buf[0])))
  1704  		err = ptrace(pokeReq, pid, addr+uintptr(n), word)
  1705  		if err != nil {
  1706  			return n, err
  1707  		}
  1708  		n += len(data)
  1709  	}
  1710  
  1711  	return n, nil
  1712  }
  1713  
  1714  func PtracePokeText(pid int, addr uintptr, data []byte) (count int, err error) {
  1715  	return ptracePoke(PTRACE_POKETEXT, PTRACE_PEEKTEXT, pid, addr, data)
  1716  }
  1717  
  1718  func PtracePokeData(pid int, addr uintptr, data []byte) (count int, err error) {
  1719  	return ptracePoke(PTRACE_POKEDATA, PTRACE_PEEKDATA, pid, addr, data)
  1720  }
  1721  
  1722  func PtracePokeUser(pid int, addr uintptr, data []byte) (count int, err error) {
  1723  	return ptracePoke(PTRACE_POKEUSR, PTRACE_PEEKUSR, pid, addr, data)
  1724  }
  1725  
  1726  func PtraceGetRegs(pid int, regsout *PtraceRegs) (err error) {
  1727  	return ptrace(PTRACE_GETREGS, pid, 0, uintptr(unsafe.Pointer(regsout)))
  1728  }
  1729  
  1730  func PtraceSetRegs(pid int, regs *PtraceRegs) (err error) {
  1731  	return ptrace(PTRACE_SETREGS, pid, 0, uintptr(unsafe.Pointer(regs)))
  1732  }
  1733  
  1734  func PtraceSetOptions(pid int, options int) (err error) {
  1735  	return ptrace(PTRACE_SETOPTIONS, pid, 0, uintptr(options))
  1736  }
  1737  
  1738  func PtraceGetEventMsg(pid int) (msg uint, err error) {
  1739  	var data _C_long
  1740  	err = ptrace(PTRACE_GETEVENTMSG, pid, 0, uintptr(unsafe.Pointer(&data)))
  1741  	msg = uint(data)
  1742  	return
  1743  }
  1744  
  1745  func PtraceCont(pid int, signal int) (err error) {
  1746  	return ptrace(PTRACE_CONT, pid, 0, uintptr(signal))
  1747  }
  1748  
  1749  func PtraceSyscall(pid int, signal int) (err error) {
  1750  	return ptrace(PTRACE_SYSCALL, pid, 0, uintptr(signal))
  1751  }
  1752  
  1753  func PtraceSingleStep(pid int) (err error) { return ptrace(PTRACE_SINGLESTEP, pid, 0, 0) }
  1754  
  1755  func PtraceInterrupt(pid int) (err error) { return ptrace(PTRACE_INTERRUPT, pid, 0, 0) }
  1756  
  1757  func PtraceAttach(pid int) (err error) { return ptrace(PTRACE_ATTACH, pid, 0, 0) }
  1758  
  1759  func PtraceSeize(pid int) (err error) { return ptrace(PTRACE_SEIZE, pid, 0, 0) }
  1760  
  1761  func PtraceDetach(pid int) (err error) { return ptrace(PTRACE_DETACH, pid, 0, 0) }
  1762  
  1763  //sys	reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error)
  1764  
  1765  func Reboot(cmd int) (err error) {
  1766  	return reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, cmd, "")
  1767  }
  1768  
  1769  func direntIno(buf []byte) (uint64, bool) {
  1770  	return readInt(buf, unsafe.Offsetof(Dirent{}.Ino), unsafe.Sizeof(Dirent{}.Ino))
  1771  }
  1772  
  1773  func direntReclen(buf []byte) (uint64, bool) {
  1774  	return readInt(buf, unsafe.Offsetof(Dirent{}.Reclen), unsafe.Sizeof(Dirent{}.Reclen))
  1775  }
  1776  
  1777  func direntNamlen(buf []byte) (uint64, bool) {
  1778  	reclen, ok := direntReclen(buf)
  1779  	if !ok {
  1780  		return 0, false
  1781  	}
  1782  	return reclen - uint64(unsafe.Offsetof(Dirent{}.Name)), true
  1783  }
  1784  
  1785  //sys	mount(source string, target string, fstype string, flags uintptr, data *byte) (err error)
  1786  
  1787  func Mount(source string, target string, fstype string, flags uintptr, data string) (err error) {
  1788  	// Certain file systems get rather angry and EINVAL if you give
  1789  	// them an empty string of data, rather than NULL.
  1790  	if data == "" {
  1791  		return mount(source, target, fstype, flags, nil)
  1792  	}
  1793  	datap, err := BytePtrFromString(data)
  1794  	if err != nil {
  1795  		return err
  1796  	}
  1797  	return mount(source, target, fstype, flags, datap)
  1798  }
  1799  
  1800  func Sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) {
  1801  	if raceenabled {
  1802  		raceReleaseMerge(unsafe.Pointer(&ioSync))
  1803  	}
  1804  	return sendfile(outfd, infd, offset, count)
  1805  }
  1806  
  1807  // Sendto
  1808  // Recvfrom
  1809  // Socketpair
  1810  
  1811  /*
  1812   * Direct access
  1813   */
  1814  //sys	Acct(path string) (err error)
  1815  //sys	AddKey(keyType string, description string, payload []byte, ringid int) (id int, err error)
  1816  //sys	Adjtimex(buf *Timex) (state int, err error)
  1817  //sysnb	Capget(hdr *CapUserHeader, data *CapUserData) (err error)
  1818  //sysnb	Capset(hdr *CapUserHeader, data *CapUserData) (err error)
  1819  //sys	Chdir(path string) (err error)
  1820  //sys	Chroot(path string) (err error)
  1821  //sys	ClockGetres(clockid int32, res *Timespec) (err error)
  1822  //sys	ClockGettime(clockid int32, time *Timespec) (err error)
  1823  //sys	ClockNanosleep(clockid int32, flags int, request *Timespec, remain *Timespec) (err error)
  1824  //sys	Close(fd int) (err error)
  1825  //sys	CloseRange(first uint, last uint, flags uint) (err error)
  1826  //sys	CopyFileRange(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error)
  1827  //sys	DeleteModule(name string, flags int) (err error)
  1828  //sys	Dup(oldfd int) (fd int, err error)
  1829  
  1830  func Dup2(oldfd, newfd int) error {
  1831  	return Dup3(oldfd, newfd, 0)
  1832  }
  1833  
  1834  //sys	Dup3(oldfd int, newfd int, flags int) (err error)
  1835  //sysnb	EpollCreate1(flag int) (fd int, err error)
  1836  //sysnb	EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error)
  1837  //sys	Eventfd(initval uint, flags int) (fd int, err error) = SYS_EVENTFD2
  1838  //sys	Exit(code int) = SYS_EXIT_GROUP
  1839  //sys	Fallocate(fd int, mode uint32, off int64, len int64) (err error)
  1840  //sys	Fchdir(fd int) (err error)
  1841  //sys	Fchmod(fd int, mode uint32) (err error)
  1842  //sys	Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error)
  1843  //sys	Fdatasync(fd int) (err error)
  1844  //sys	Fgetxattr(fd int, attr string, dest []byte) (sz int, err error)
  1845  //sys	FinitModule(fd int, params string, flags int) (err error)
  1846  //sys	Flistxattr(fd int, dest []byte) (sz int, err error)
  1847  //sys	Flock(fd int, how int) (err error)
  1848  //sys	Fremovexattr(fd int, attr string) (err error)
  1849  //sys	Fsetxattr(fd int, attr string, dest []byte, flags int) (err error)
  1850  //sys	Fsync(fd int) (err error)
  1851  //sys	Getdents(fd int, buf []byte) (n int, err error) = SYS_GETDENTS64
  1852  //sysnb	Getpgid(pid int) (pgid int, err error)
  1853  
  1854  func Getpgrp() (pid int) {
  1855  	pid, _ = Getpgid(0)
  1856  	return
  1857  }
  1858  
  1859  //sysnb	Getpid() (pid int)
  1860  //sysnb	Getppid() (ppid int)
  1861  //sys	Getpriority(which int, who int) (prio int, err error)
  1862  //sys	Getrandom(buf []byte, flags int) (n int, err error)
  1863  //sysnb	Getrusage(who int, rusage *Rusage) (err error)
  1864  //sysnb	Getsid(pid int) (sid int, err error)
  1865  //sysnb	Gettid() (tid int)
  1866  //sys	Getxattr(path string, attr string, dest []byte) (sz int, err error)
  1867  //sys	InitModule(moduleImage []byte, params string) (err error)
  1868  //sys	InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error)
  1869  //sysnb	InotifyInit1(flags int) (fd int, err error)
  1870  //sysnb	InotifyRmWatch(fd int, watchdesc uint32) (success int, err error)
  1871  //sysnb	Kill(pid int, sig syscall.Signal) (err error)
  1872  //sys	Klogctl(typ int, buf []byte) (n int, err error) = SYS_SYSLOG
  1873  //sys	Lgetxattr(path string, attr string, dest []byte) (sz int, err error)
  1874  //sys	Listxattr(path string, dest []byte) (sz int, err error)
  1875  //sys	Llistxattr(path string, dest []byte) (sz int, err error)
  1876  //sys	Lremovexattr(path string, attr string) (err error)
  1877  //sys	Lsetxattr(path string, attr string, data []byte, flags int) (err error)
  1878  //sys	MemfdCreate(name string, flags int) (fd int, err error)
  1879  //sys	Mkdirat(dirfd int, path string, mode uint32) (err error)
  1880  //sys	Mknodat(dirfd int, path string, mode uint32, dev int) (err error)
  1881  //sys	Nanosleep(time *Timespec, leftover *Timespec) (err error)
  1882  //sys	PerfEventOpen(attr *PerfEventAttr, pid int, cpu int, groupFd int, flags int) (fd int, err error)
  1883  //sys	PivotRoot(newroot string, putold string) (err error) = SYS_PIVOT_ROOT
  1884  //sysnb	Prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) = SYS_PRLIMIT64
  1885  //sys	Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error)
  1886  //sys	Pselect(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timespec, sigmask *Sigset_t) (n int, err error) = SYS_PSELECT6
  1887  //sys	read(fd int, p []byte) (n int, err error)
  1888  //sys	Removexattr(path string, attr string) (err error)
  1889  //sys	Renameat2(olddirfd int, oldpath string, newdirfd int, newpath string, flags uint) (err error)
  1890  //sys	RequestKey(keyType string, description string, callback string, destRingid int) (id int, err error)
  1891  //sys	Setdomainname(p []byte) (err error)
  1892  //sys	Sethostname(p []byte) (err error)
  1893  //sysnb	Setpgid(pid int, pgid int) (err error)
  1894  //sysnb	Setsid() (pid int, err error)
  1895  //sysnb	Settimeofday(tv *Timeval) (err error)
  1896  //sys	Setns(fd int, nstype int) (err error)
  1897  
  1898  // PrctlRetInt performs a prctl operation specified by option and further
  1899  // optional arguments arg2 through arg5 depending on option. It returns a
  1900  // non-negative integer that is returned by the prctl syscall.
  1901  func PrctlRetInt(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (int, error) {
  1902  	ret, _, err := Syscall6(SYS_PRCTL, uintptr(option), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0)
  1903  	if err != 0 {
  1904  		return 0, err
  1905  	}
  1906  	return int(ret), nil
  1907  }
  1908  
  1909  // issue 1435.
  1910  // On linux Setuid and Setgid only affects the current thread, not the process.
  1911  // This does not match what most callers expect so we must return an error
  1912  // here rather than letting the caller think that the call succeeded.
  1913  
  1914  func Setuid(uid int) (err error) {
  1915  	return EOPNOTSUPP
  1916  }
  1917  
  1918  func Setgid(uid int) (err error) {
  1919  	return EOPNOTSUPP
  1920  }
  1921  
  1922  // SetfsgidRetGid sets fsgid for current thread and returns previous fsgid set.
  1923  // setfsgid(2) will return a non-nil error only if its caller lacks CAP_SETUID capability.
  1924  // If the call fails due to other reasons, current fsgid will be returned.
  1925  func SetfsgidRetGid(gid int) (int, error) {
  1926  	return setfsgid(gid)
  1927  }
  1928  
  1929  // SetfsuidRetUid sets fsuid for current thread and returns previous fsuid set.
  1930  // setfsgid(2) will return a non-nil error only if its caller lacks CAP_SETUID capability
  1931  // If the call fails due to other reasons, current fsuid will be returned.
  1932  func SetfsuidRetUid(uid int) (int, error) {
  1933  	return setfsuid(uid)
  1934  }
  1935  
  1936  func Setfsgid(gid int) error {
  1937  	_, err := setfsgid(gid)
  1938  	return err
  1939  }
  1940  
  1941  func Setfsuid(uid int) error {
  1942  	_, err := setfsuid(uid)
  1943  	return err
  1944  }
  1945  
  1946  func Signalfd(fd int, sigmask *Sigset_t, flags int) (newfd int, err error) {
  1947  	return signalfd(fd, sigmask, _C__NSIG/8, flags)
  1948  }
  1949  
  1950  //sys	Setpriority(which int, who int, prio int) (err error)
  1951  //sys	Setxattr(path string, attr string, data []byte, flags int) (err error)
  1952  //sys	signalfd(fd int, sigmask *Sigset_t, maskSize uintptr, flags int) (newfd int, err error) = SYS_SIGNALFD4
  1953  //sys	Statx(dirfd int, path string, flags int, mask int, stat *Statx_t) (err error)
  1954  //sys	Sync()
  1955  //sys	Syncfs(fd int) (err error)
  1956  //sysnb	Sysinfo(info *Sysinfo_t) (err error)
  1957  //sys	Tee(rfd int, wfd int, len int, flags int) (n int64, err error)
  1958  //sysnb	TimerfdCreate(clockid int, flags int) (fd int, err error)
  1959  //sysnb	TimerfdGettime(fd int, currValue *ItimerSpec) (err error)
  1960  //sysnb	TimerfdSettime(fd int, flags int, newValue *ItimerSpec, oldValue *ItimerSpec) (err error)
  1961  //sysnb	Tgkill(tgid int, tid int, sig syscall.Signal) (err error)
  1962  //sysnb	Times(tms *Tms) (ticks uintptr, err error)
  1963  //sysnb	Umask(mask int) (oldmask int)
  1964  //sysnb	Uname(buf *Utsname) (err error)
  1965  //sys	Unmount(target string, flags int) (err error) = SYS_UMOUNT2
  1966  //sys	Unshare(flags int) (err error)
  1967  //sys	write(fd int, p []byte) (n int, err error)
  1968  //sys	exitThread(code int) (err error) = SYS_EXIT
  1969  //sys	readlen(fd int, p *byte, np int) (n int, err error) = SYS_READ
  1970  //sys	writelen(fd int, p *byte, np int) (n int, err error) = SYS_WRITE
  1971  //sys	readv(fd int, iovs []Iovec) (n int, err error) = SYS_READV
  1972  //sys	writev(fd int, iovs []Iovec) (n int, err error) = SYS_WRITEV
  1973  //sys	preadv(fd int, iovs []Iovec, offs_l uintptr, offs_h uintptr) (n int, err error) = SYS_PREADV
  1974  //sys	pwritev(fd int, iovs []Iovec, offs_l uintptr, offs_h uintptr) (n int, err error) = SYS_PWRITEV
  1975  //sys	preadv2(fd int, iovs []Iovec, offs_l uintptr, offs_h uintptr, flags int) (n int, err error) = SYS_PREADV2
  1976  //sys	pwritev2(fd int, iovs []Iovec, offs_l uintptr, offs_h uintptr, flags int) (n int, err error) = SYS_PWRITEV2
  1977  
  1978  func bytes2iovec(bs [][]byte) []Iovec {
  1979  	iovecs := make([]Iovec, len(bs))
  1980  	for i, b := range bs {
  1981  		iovecs[i].SetLen(len(b))
  1982  		if len(b) > 0 {
  1983  			iovecs[i].Base = &b[0]
  1984  		} else {
  1985  			iovecs[i].Base = (*byte)(unsafe.Pointer(&_zero))
  1986  		}
  1987  	}
  1988  	return iovecs
  1989  }
  1990  
  1991  // offs2lohi splits offs into its lower and upper unsigned long. On 64-bit
  1992  // systems, hi will always be 0. On 32-bit systems, offs will be split in half.
  1993  // preadv/pwritev chose this calling convention so they don't need to add a
  1994  // padding-register for alignment on ARM.
  1995  func offs2lohi(offs int64) (lo, hi uintptr) {
  1996  	return uintptr(offs), uintptr(uint64(offs) >> SizeofLong)
  1997  }
  1998  
  1999  func Readv(fd int, iovs [][]byte) (n int, err error) {
  2000  	iovecs := bytes2iovec(iovs)
  2001  	n, err = readv(fd, iovecs)
  2002  	readvRacedetect(iovecs, n, err)
  2003  	return n, err
  2004  }
  2005  
  2006  func Preadv(fd int, iovs [][]byte, offset int64) (n int, err error) {
  2007  	iovecs := bytes2iovec(iovs)
  2008  	lo, hi := offs2lohi(offset)
  2009  	n, err = preadv(fd, iovecs, lo, hi)
  2010  	readvRacedetect(iovecs, n, err)
  2011  	return n, err
  2012  }
  2013  
  2014  func Preadv2(fd int, iovs [][]byte, offset int64, flags int) (n int, err error) {
  2015  	iovecs := bytes2iovec(iovs)
  2016  	lo, hi := offs2lohi(offset)
  2017  	n, err = preadv2(fd, iovecs, lo, hi, flags)
  2018  	readvRacedetect(iovecs, n, err)
  2019  	return n, err
  2020  }
  2021  
  2022  func readvRacedetect(iovecs []Iovec, n int, err error) {
  2023  	if !raceenabled {
  2024  		return
  2025  	}
  2026  	for i := 0; n > 0 && i < len(iovecs); i++ {
  2027  		m := int(iovecs[i].Len)
  2028  		if m > n {
  2029  			m = n
  2030  		}
  2031  		n -= m
  2032  		if m > 0 {
  2033  			raceWriteRange(unsafe.Pointer(iovecs[i].Base), m)
  2034  		}
  2035  	}
  2036  	if err == nil {
  2037  		raceAcquire(unsafe.Pointer(&ioSync))
  2038  	}
  2039  }
  2040  
  2041  func Writev(fd int, iovs [][]byte) (n int, err error) {
  2042  	iovecs := bytes2iovec(iovs)
  2043  	if raceenabled {
  2044  		raceReleaseMerge(unsafe.Pointer(&ioSync))
  2045  	}
  2046  	n, err = writev(fd, iovecs)
  2047  	writevRacedetect(iovecs, n)
  2048  	return n, err
  2049  }
  2050  
  2051  func Pwritev(fd int, iovs [][]byte, offset int64) (n int, err error) {
  2052  	iovecs := bytes2iovec(iovs)
  2053  	if raceenabled {
  2054  		raceReleaseMerge(unsafe.Pointer(&ioSync))
  2055  	}
  2056  	lo, hi := offs2lohi(offset)
  2057  	n, err = pwritev(fd, iovecs, lo, hi)
  2058  	writevRacedetect(iovecs, n)
  2059  	return n, err
  2060  }
  2061  
  2062  func Pwritev2(fd int, iovs [][]byte, offset int64, flags int) (n int, err error) {
  2063  	iovecs := bytes2iovec(iovs)
  2064  	if raceenabled {
  2065  		raceReleaseMerge(unsafe.Pointer(&ioSync))
  2066  	}
  2067  	lo, hi := offs2lohi(offset)
  2068  	n, err = pwritev2(fd, iovecs, lo, hi, flags)
  2069  	writevRacedetect(iovecs, n)
  2070  	return n, err
  2071  }
  2072  
  2073  func writevRacedetect(iovecs []Iovec, n int) {
  2074  	if !raceenabled {
  2075  		return
  2076  	}
  2077  	for i := 0; n > 0 && i < len(iovecs); i++ {
  2078  		m := int(iovecs[i].Len)
  2079  		if m > n {
  2080  			m = n
  2081  		}
  2082  		n -= m
  2083  		if m > 0 {
  2084  			raceReadRange(unsafe.Pointer(iovecs[i].Base), m)
  2085  		}
  2086  	}
  2087  }
  2088  
  2089  // mmap varies by architecture; see syscall_linux_*.go.
  2090  //sys	munmap(addr uintptr, length uintptr) (err error)
  2091  
  2092  var mapper = &mmapper{
  2093  	active: make(map[*byte][]byte),
  2094  	mmap:   mmap,
  2095  	munmap: munmap,
  2096  }
  2097  
  2098  func Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error) {
  2099  	return mapper.Mmap(fd, offset, length, prot, flags)
  2100  }
  2101  
  2102  func Munmap(b []byte) (err error) {
  2103  	return mapper.Munmap(b)
  2104  }
  2105  
  2106  //sys	Madvise(b []byte, advice int) (err error)
  2107  //sys	Mprotect(b []byte, prot int) (err error)
  2108  //sys	Mlock(b []byte) (err error)
  2109  //sys	Mlockall(flags int) (err error)
  2110  //sys	Msync(b []byte, flags int) (err error)
  2111  //sys	Munlock(b []byte) (err error)
  2112  //sys	Munlockall() (err error)
  2113  
  2114  // Vmsplice splices user pages from a slice of Iovecs into a pipe specified by fd,
  2115  // using the specified flags.
  2116  func Vmsplice(fd int, iovs []Iovec, flags int) (int, error) {
  2117  	var p unsafe.Pointer
  2118  	if len(iovs) > 0 {
  2119  		p = unsafe.Pointer(&iovs[0])
  2120  	}
  2121  
  2122  	n, _, errno := Syscall6(SYS_VMSPLICE, uintptr(fd), uintptr(p), uintptr(len(iovs)), uintptr(flags), 0, 0)
  2123  	if errno != 0 {
  2124  		return 0, syscall.Errno(errno)
  2125  	}
  2126  
  2127  	return int(n), nil
  2128  }
  2129  
  2130  func isGroupMember(gid int) bool {
  2131  	groups, err := Getgroups()
  2132  	if err != nil {
  2133  		return false
  2134  	}
  2135  
  2136  	for _, g := range groups {
  2137  		if g == gid {
  2138  			return true
  2139  		}
  2140  	}
  2141  	return false
  2142  }
  2143  
  2144  //sys	faccessat(dirfd int, path string, mode uint32) (err error)
  2145  //sys	Faccessat2(dirfd int, path string, mode uint32, flags int) (err error)
  2146  
  2147  func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) {
  2148  	if flags == 0 {
  2149  		return faccessat(dirfd, path, mode)
  2150  	}
  2151  
  2152  	if err := Faccessat2(dirfd, path, mode, flags); err != ENOSYS && err != EPERM {
  2153  		return err
  2154  	}
  2155  
  2156  	// The Linux kernel faccessat system call does not take any flags.
  2157  	// The glibc faccessat implements the flags itself; see
  2158  	// https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/unix/sysv/linux/faccessat.c;hb=HEAD
  2159  	// Because people naturally expect syscall.Faccessat to act
  2160  	// like C faccessat, we do the same.
  2161  
  2162  	if flags & ^(AT_SYMLINK_NOFOLLOW|AT_EACCESS) != 0 {
  2163  		return EINVAL
  2164  	}
  2165  
  2166  	var st Stat_t
  2167  	if err := Fstatat(dirfd, path, &st, flags&AT_SYMLINK_NOFOLLOW); err != nil {
  2168  		return err
  2169  	}
  2170  
  2171  	mode &= 7
  2172  	if mode == 0 {
  2173  		return nil
  2174  	}
  2175  
  2176  	var uid int
  2177  	if flags&AT_EACCESS != 0 {
  2178  		uid = Geteuid()
  2179  	} else {
  2180  		uid = Getuid()
  2181  	}
  2182  
  2183  	if uid == 0 {
  2184  		if mode&1 == 0 {
  2185  			// Root can read and write any file.
  2186  			return nil
  2187  		}
  2188  		if st.Mode&0111 != 0 {
  2189  			// Root can execute any file that anybody can execute.
  2190  			return nil
  2191  		}
  2192  		return EACCES
  2193  	}
  2194  
  2195  	var fmode uint32
  2196  	if uint32(uid) == st.Uid {
  2197  		fmode = (st.Mode >> 6) & 7
  2198  	} else {
  2199  		var gid int
  2200  		if flags&AT_EACCESS != 0 {
  2201  			gid = Getegid()
  2202  		} else {
  2203  			gid = Getgid()
  2204  		}
  2205  
  2206  		if uint32(gid) == st.Gid || isGroupMember(gid) {
  2207  			fmode = (st.Mode >> 3) & 7
  2208  		} else {
  2209  			fmode = st.Mode & 7
  2210  		}
  2211  	}
  2212  
  2213  	if fmode&mode == mode {
  2214  		return nil
  2215  	}
  2216  
  2217  	return EACCES
  2218  }
  2219  
  2220  //sys	nameToHandleAt(dirFD int, pathname string, fh *fileHandle, mountID *_C_int, flags int) (err error) = SYS_NAME_TO_HANDLE_AT
  2221  //sys	openByHandleAt(mountFD int, fh *fileHandle, flags int) (fd int, err error) = SYS_OPEN_BY_HANDLE_AT
  2222  
  2223  // fileHandle is the argument to nameToHandleAt and openByHandleAt. We
  2224  // originally tried to generate it via unix/linux/types.go with "type
  2225  // fileHandle C.struct_file_handle" but that generated empty structs
  2226  // for mips64 and mips64le. Instead, hard code it for now (it's the
  2227  // same everywhere else) until the mips64 generator issue is fixed.
  2228  type fileHandle struct {
  2229  	Bytes uint32
  2230  	Type  int32
  2231  }
  2232  
  2233  // FileHandle represents the C struct file_handle used by
  2234  // name_to_handle_at (see NameToHandleAt) and open_by_handle_at (see
  2235  // OpenByHandleAt).
  2236  type FileHandle struct {
  2237  	*fileHandle
  2238  }
  2239  
  2240  // NewFileHandle constructs a FileHandle.
  2241  func NewFileHandle(handleType int32, handle []byte) FileHandle {
  2242  	const hdrSize = unsafe.Sizeof(fileHandle{})
  2243  	buf := make([]byte, hdrSize+uintptr(len(handle)))
  2244  	copy(buf[hdrSize:], handle)
  2245  	fh := (*fileHandle)(unsafe.Pointer(&buf[0]))
  2246  	fh.Type = handleType
  2247  	fh.Bytes = uint32(len(handle))
  2248  	return FileHandle{fh}
  2249  }
  2250  
  2251  func (fh *FileHandle) Size() int   { return int(fh.fileHandle.Bytes) }
  2252  func (fh *FileHandle) Type() int32 { return fh.fileHandle.Type }
  2253  func (fh *FileHandle) Bytes() []byte {
  2254  	n := fh.Size()
  2255  	if n == 0 {
  2256  		return nil
  2257  	}
  2258  	return (*[1 << 30]byte)(unsafe.Pointer(uintptr(unsafe.Pointer(&fh.fileHandle.Type)) + 4))[:n:n]
  2259  }
  2260  
  2261  // NameToHandleAt wraps the name_to_handle_at system call; it obtains
  2262  // a handle for a path name.
  2263  func NameToHandleAt(dirfd int, path string, flags int) (handle FileHandle, mountID int, err error) {
  2264  	var mid _C_int
  2265  	// Try first with a small buffer, assuming the handle will
  2266  	// only be 32 bytes.
  2267  	size := uint32(32 + unsafe.Sizeof(fileHandle{}))
  2268  	didResize := false
  2269  	for {
  2270  		buf := make([]byte, size)
  2271  		fh := (*fileHandle)(unsafe.Pointer(&buf[0]))
  2272  		fh.Bytes = size - uint32(unsafe.Sizeof(fileHandle{}))
  2273  		err = nameToHandleAt(dirfd, path, fh, &mid, flags)
  2274  		if err == EOVERFLOW {
  2275  			if didResize {
  2276  				// We shouldn't need to resize more than once
  2277  				return
  2278  			}
  2279  			didResize = true
  2280  			size = fh.Bytes + uint32(unsafe.Sizeof(fileHandle{}))
  2281  			continue
  2282  		}
  2283  		if err != nil {
  2284  			return
  2285  		}
  2286  		return FileHandle{fh}, int(mid), nil
  2287  	}
  2288  }
  2289  
  2290  // OpenByHandleAt wraps the open_by_handle_at system call; it opens a
  2291  // file via a handle as previously returned by NameToHandleAt.
  2292  func OpenByHandleAt(mountFD int, handle FileHandle, flags int) (fd int, err error) {
  2293  	return openByHandleAt(mountFD, handle.fileHandle, flags)
  2294  }
  2295  
  2296  // Klogset wraps the sys_syslog system call; it sets console_loglevel to
  2297  // the value specified by arg and passes a dummy pointer to bufp.
  2298  func Klogset(typ int, arg int) (err error) {
  2299  	var p unsafe.Pointer
  2300  	_, _, errno := Syscall(SYS_SYSLOG, uintptr(typ), uintptr(p), uintptr(arg))
  2301  	if errno != 0 {
  2302  		return errnoErr(errno)
  2303  	}
  2304  	return nil
  2305  }
  2306  
  2307  // RemoteIovec is Iovec with the pointer replaced with an integer.
  2308  // It is used for ProcessVMReadv and ProcessVMWritev, where the pointer
  2309  // refers to a location in a different process' address space, which
  2310  // would confuse the Go garbage collector.
  2311  type RemoteIovec struct {
  2312  	Base uintptr
  2313  	Len  int
  2314  }
  2315  
  2316  //sys	ProcessVMReadv(pid int, localIov []Iovec, remoteIov []RemoteIovec, flags uint) (n int, err error) = SYS_PROCESS_VM_READV
  2317  //sys	ProcessVMWritev(pid int, localIov []Iovec, remoteIov []RemoteIovec, flags uint) (n int, err error) = SYS_PROCESS_VM_WRITEV
  2318  
  2319  //sys	PidfdOpen(pid int, flags int) (fd int, err error) = SYS_PIDFD_OPEN
  2320  //sys	PidfdGetfd(pidfd int, targetfd int, flags int) (fd int, err error) = SYS_PIDFD_GETFD
  2321  
  2322  /*
  2323   * Unimplemented
  2324   */
  2325  // AfsSyscall
  2326  // Alarm
  2327  // ArchPrctl
  2328  // Brk
  2329  // ClockNanosleep
  2330  // ClockSettime
  2331  // Clone
  2332  // EpollCtlOld
  2333  // EpollPwait
  2334  // EpollWaitOld
  2335  // Execve
  2336  // Fork
  2337  // Futex
  2338  // GetKernelSyms
  2339  // GetMempolicy
  2340  // GetRobustList
  2341  // GetThreadArea
  2342  // Getitimer
  2343  // Getpmsg
  2344  // IoCancel
  2345  // IoDestroy
  2346  // IoGetevents
  2347  // IoSetup
  2348  // IoSubmit
  2349  // IoprioGet
  2350  // IoprioSet
  2351  // KexecLoad
  2352  // LookupDcookie
  2353  // Mbind
  2354  // MigratePages
  2355  // Mincore
  2356  // ModifyLdt
  2357  // Mount
  2358  // MovePages
  2359  // MqGetsetattr
  2360  // MqNotify
  2361  // MqOpen
  2362  // MqTimedreceive
  2363  // MqTimedsend
  2364  // MqUnlink
  2365  // Mremap
  2366  // Msgctl
  2367  // Msgget
  2368  // Msgrcv
  2369  // Msgsnd
  2370  // Nfsservctl
  2371  // Personality
  2372  // Pselect6
  2373  // Ptrace
  2374  // Putpmsg
  2375  // Quotactl
  2376  // Readahead
  2377  // Readv
  2378  // RemapFilePages
  2379  // RestartSyscall
  2380  // RtSigaction
  2381  // RtSigpending
  2382  // RtSigprocmask
  2383  // RtSigqueueinfo
  2384  // RtSigreturn
  2385  // RtSigsuspend
  2386  // RtSigtimedwait
  2387  // SchedGetPriorityMax
  2388  // SchedGetPriorityMin
  2389  // SchedGetparam
  2390  // SchedGetscheduler
  2391  // SchedRrGetInterval
  2392  // SchedSetparam
  2393  // SchedYield
  2394  // Security
  2395  // Semctl
  2396  // Semget
  2397  // Semop
  2398  // Semtimedop
  2399  // SetMempolicy
  2400  // SetRobustList
  2401  // SetThreadArea
  2402  // SetTidAddress
  2403  // Shmat
  2404  // Shmctl
  2405  // Shmdt
  2406  // Shmget
  2407  // Sigaltstack
  2408  // Swapoff
  2409  // Swapon
  2410  // Sysfs
  2411  // TimerCreate
  2412  // TimerDelete
  2413  // TimerGetoverrun
  2414  // TimerGettime
  2415  // TimerSettime
  2416  // Tkill (obsolete)
  2417  // Tuxcall
  2418  // Umount2
  2419  // Uselib
  2420  // Utimensat
  2421  // Vfork
  2422  // Vhangup
  2423  // Vserver
  2424  // Waitid
  2425  // _Sysctl