Source file src/syscall/syscall_linux.go

     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 syscall
    13  
    14  import (
    15  	"internal/itoa"
    16  	"unsafe"
    17  )
    18  
    19  func rawSyscallNoError(trap, a1, a2, a3 uintptr) (r1, r2 uintptr)
    20  
    21  /*
    22   * Wrapped
    23   */
    24  
    25  func Access(path string, mode uint32) (err error) {
    26  	return Faccessat(_AT_FDCWD, path, mode, 0)
    27  }
    28  
    29  func Chmod(path string, mode uint32) (err error) {
    30  	return Fchmodat(_AT_FDCWD, path, mode, 0)
    31  }
    32  
    33  func Chown(path string, uid int, gid int) (err error) {
    34  	return Fchownat(_AT_FDCWD, path, uid, gid, 0)
    35  }
    36  
    37  func Creat(path string, mode uint32) (fd int, err error) {
    38  	return Open(path, O_CREAT|O_WRONLY|O_TRUNC, mode)
    39  }
    40  
    41  func isGroupMember(gid int) bool {
    42  	groups, err := Getgroups()
    43  	if err != nil {
    44  		return false
    45  	}
    46  
    47  	for _, g := range groups {
    48  		if g == gid {
    49  			return true
    50  		}
    51  	}
    52  	return false
    53  }
    54  
    55  //sys	faccessat(dirfd int, path string, mode uint32) (err error)
    56  
    57  func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) {
    58  	if flags & ^(_AT_SYMLINK_NOFOLLOW|_AT_EACCESS) != 0 {
    59  		return EINVAL
    60  	}
    61  
    62  	// The Linux kernel faccessat system call does not take any flags.
    63  	// The glibc faccessat implements the flags itself; see
    64  	// https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/unix/sysv/linux/faccessat.c;hb=HEAD
    65  	// Because people naturally expect syscall.Faccessat to act
    66  	// like C faccessat, we do the same.
    67  
    68  	if flags == 0 {
    69  		return faccessat(dirfd, path, mode)
    70  	}
    71  
    72  	var st Stat_t
    73  	if err := fstatat(dirfd, path, &st, flags&_AT_SYMLINK_NOFOLLOW); err != nil {
    74  		return err
    75  	}
    76  
    77  	mode &= 7
    78  	if mode == 0 {
    79  		return nil
    80  	}
    81  
    82  	var uid int
    83  	if flags&_AT_EACCESS != 0 {
    84  		uid = Geteuid()
    85  	} else {
    86  		uid = Getuid()
    87  	}
    88  
    89  	if uid == 0 {
    90  		if mode&1 == 0 {
    91  			// Root can read and write any file.
    92  			return nil
    93  		}
    94  		if st.Mode&0111 != 0 {
    95  			// Root can execute any file that anybody can execute.
    96  			return nil
    97  		}
    98  		return EACCES
    99  	}
   100  
   101  	var fmode uint32
   102  	if uint32(uid) == st.Uid {
   103  		fmode = (st.Mode >> 6) & 7
   104  	} else {
   105  		var gid int
   106  		if flags&_AT_EACCESS != 0 {
   107  			gid = Getegid()
   108  		} else {
   109  			gid = Getgid()
   110  		}
   111  
   112  		if uint32(gid) == st.Gid || isGroupMember(int(st.Gid)) {
   113  			fmode = (st.Mode >> 3) & 7
   114  		} else {
   115  			fmode = st.Mode & 7
   116  		}
   117  	}
   118  
   119  	if fmode&mode == mode {
   120  		return nil
   121  	}
   122  
   123  	return EACCES
   124  }
   125  
   126  //sys	fchmodat(dirfd int, path string, mode uint32) (err error)
   127  
   128  func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) {
   129  	// Linux fchmodat doesn't support the flags parameter. Mimick glibc's behavior
   130  	// and check the flags. Otherwise the mode would be applied to the symlink
   131  	// destination which is not what the user expects.
   132  	if flags&^_AT_SYMLINK_NOFOLLOW != 0 {
   133  		return EINVAL
   134  	} else if flags&_AT_SYMLINK_NOFOLLOW != 0 {
   135  		return EOPNOTSUPP
   136  	}
   137  	return fchmodat(dirfd, path, mode)
   138  }
   139  
   140  //sys	linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error)
   141  
   142  func Link(oldpath string, newpath string) (err error) {
   143  	return linkat(_AT_FDCWD, oldpath, _AT_FDCWD, newpath, 0)
   144  }
   145  
   146  func Mkdir(path string, mode uint32) (err error) {
   147  	return Mkdirat(_AT_FDCWD, path, mode)
   148  }
   149  
   150  func Mknod(path string, mode uint32, dev int) (err error) {
   151  	return Mknodat(_AT_FDCWD, path, mode, dev)
   152  }
   153  
   154  func Open(path string, mode int, perm uint32) (fd int, err error) {
   155  	return openat(_AT_FDCWD, path, mode|O_LARGEFILE, perm)
   156  }
   157  
   158  //sys	openat(dirfd int, path string, flags int, mode uint32) (fd int, err error)
   159  
   160  func Openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) {
   161  	return openat(dirfd, path, flags|O_LARGEFILE, mode)
   162  }
   163  
   164  func Pipe(p []int) error {
   165  	return Pipe2(p, 0)
   166  }
   167  
   168  //sysnb pipe2(p *[2]_C_int, flags int) (err error)
   169  
   170  func Pipe2(p []int, flags int) error {
   171  	if len(p) != 2 {
   172  		return EINVAL
   173  	}
   174  	var pp [2]_C_int
   175  	err := pipe2(&pp, flags)
   176  	if err == nil {
   177  		p[0] = int(pp[0])
   178  		p[1] = int(pp[1])
   179  	}
   180  	return err
   181  }
   182  
   183  //sys	readlinkat(dirfd int, path string, buf []byte) (n int, err error)
   184  
   185  func Readlink(path string, buf []byte) (n int, err error) {
   186  	return readlinkat(_AT_FDCWD, path, buf)
   187  }
   188  
   189  func Rename(oldpath string, newpath string) (err error) {
   190  	return Renameat(_AT_FDCWD, oldpath, _AT_FDCWD, newpath)
   191  }
   192  
   193  func Rmdir(path string) error {
   194  	return unlinkat(_AT_FDCWD, path, _AT_REMOVEDIR)
   195  }
   196  
   197  //sys	symlinkat(oldpath string, newdirfd int, newpath string) (err error)
   198  
   199  func Symlink(oldpath string, newpath string) (err error) {
   200  	return symlinkat(oldpath, _AT_FDCWD, newpath)
   201  }
   202  
   203  func Unlink(path string) error {
   204  	return unlinkat(_AT_FDCWD, path, 0)
   205  }
   206  
   207  //sys	unlinkat(dirfd int, path string, flags int) (err error)
   208  
   209  func Unlinkat(dirfd int, path string) error {
   210  	return unlinkat(dirfd, path, 0)
   211  }
   212  
   213  func Utimes(path string, tv []Timeval) (err error) {
   214  	if len(tv) != 2 {
   215  		return EINVAL
   216  	}
   217  	return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
   218  }
   219  
   220  //sys	utimensat(dirfd int, path string, times *[2]Timespec, flag int) (err error)
   221  
   222  func UtimesNano(path string, ts []Timespec) (err error) {
   223  	if len(ts) != 2 {
   224  		return EINVAL
   225  	}
   226  	return utimensat(_AT_FDCWD, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), 0)
   227  }
   228  
   229  func Futimesat(dirfd int, path string, tv []Timeval) (err error) {
   230  	if len(tv) != 2 {
   231  		return EINVAL
   232  	}
   233  	return futimesat(dirfd, path, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
   234  }
   235  
   236  func Futimes(fd int, tv []Timeval) (err error) {
   237  	// Believe it or not, this is the best we can do on Linux
   238  	// (and is what glibc does).
   239  	return Utimes("/proc/self/fd/"+itoa.Itoa(fd), tv)
   240  }
   241  
   242  const ImplementsGetwd = true
   243  
   244  //sys	Getcwd(buf []byte) (n int, err error)
   245  
   246  func Getwd() (wd string, err error) {
   247  	var buf [PathMax]byte
   248  	n, err := Getcwd(buf[0:])
   249  	if err != nil {
   250  		return "", err
   251  	}
   252  	// Getcwd returns the number of bytes written to buf, including the NUL.
   253  	if n < 1 || n > len(buf) || buf[n-1] != 0 {
   254  		return "", EINVAL
   255  	}
   256  	return string(buf[0 : n-1]), nil
   257  }
   258  
   259  func Getgroups() (gids []int, err error) {
   260  	n, err := getgroups(0, nil)
   261  	if err != nil {
   262  		return nil, err
   263  	}
   264  	if n == 0 {
   265  		return nil, nil
   266  	}
   267  
   268  	// Sanity check group count. Max is 1<<16 on Linux.
   269  	if n < 0 || n > 1<<20 {
   270  		return nil, EINVAL
   271  	}
   272  
   273  	a := make([]_Gid_t, n)
   274  	n, err = getgroups(n, &a[0])
   275  	if err != nil {
   276  		return nil, err
   277  	}
   278  	gids = make([]int, n)
   279  	for i, v := range a[0:n] {
   280  		gids[i] = int(v)
   281  	}
   282  	return
   283  }
   284  
   285  var cgo_libc_setgroups unsafe.Pointer // non-nil if cgo linked.
   286  
   287  func Setgroups(gids []int) (err error) {
   288  	n := uintptr(len(gids))
   289  	if n == 0 {
   290  		if cgo_libc_setgroups == nil {
   291  			if _, _, e1 := AllThreadsSyscall(_SYS_setgroups, 0, 0, 0); e1 != 0 {
   292  				err = errnoErr(e1)
   293  			}
   294  			return
   295  		}
   296  		if ret := cgocaller(cgo_libc_setgroups, 0, 0); ret != 0 {
   297  			err = errnoErr(Errno(ret))
   298  		}
   299  		return
   300  	}
   301  
   302  	a := make([]_Gid_t, len(gids))
   303  	for i, v := range gids {
   304  		a[i] = _Gid_t(v)
   305  	}
   306  	if cgo_libc_setgroups == nil {
   307  		if _, _, e1 := AllThreadsSyscall(_SYS_setgroups, n, uintptr(unsafe.Pointer(&a[0])), 0); e1 != 0 {
   308  			err = errnoErr(e1)
   309  		}
   310  		return
   311  	}
   312  	if ret := cgocaller(cgo_libc_setgroups, n, uintptr(unsafe.Pointer(&a[0]))); ret != 0 {
   313  		err = errnoErr(Errno(ret))
   314  	}
   315  	return
   316  }
   317  
   318  type WaitStatus uint32
   319  
   320  // Wait status is 7 bits at bottom, either 0 (exited),
   321  // 0x7F (stopped), or a signal number that caused an exit.
   322  // The 0x80 bit is whether there was a core dump.
   323  // An extra number (exit code, signal causing a stop)
   324  // is in the high bits. At least that's the idea.
   325  // There are various irregularities. For example, the
   326  // "continued" status is 0xFFFF, distinguishing itself
   327  // from stopped via the core dump bit.
   328  
   329  const (
   330  	mask    = 0x7F
   331  	core    = 0x80
   332  	exited  = 0x00
   333  	stopped = 0x7F
   334  	shift   = 8
   335  )
   336  
   337  func (w WaitStatus) Exited() bool { return w&mask == exited }
   338  
   339  func (w WaitStatus) Signaled() bool { return w&mask != stopped && w&mask != exited }
   340  
   341  func (w WaitStatus) Stopped() bool { return w&0xFF == stopped }
   342  
   343  func (w WaitStatus) Continued() bool { return w == 0xFFFF }
   344  
   345  func (w WaitStatus) CoreDump() bool { return w.Signaled() && w&core != 0 }
   346  
   347  func (w WaitStatus) ExitStatus() int {
   348  	if !w.Exited() {
   349  		return -1
   350  	}
   351  	return int(w>>shift) & 0xFF
   352  }
   353  
   354  func (w WaitStatus) Signal() Signal {
   355  	if !w.Signaled() {
   356  		return -1
   357  	}
   358  	return Signal(w & mask)
   359  }
   360  
   361  func (w WaitStatus) StopSignal() Signal {
   362  	if !w.Stopped() {
   363  		return -1
   364  	}
   365  	return Signal(w>>shift) & 0xFF
   366  }
   367  
   368  func (w WaitStatus) TrapCause() int {
   369  	if w.StopSignal() != SIGTRAP {
   370  		return -1
   371  	}
   372  	return int(w>>shift) >> 8
   373  }
   374  
   375  //sys	wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error)
   376  
   377  func Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, err error) {
   378  	var status _C_int
   379  	wpid, err = wait4(pid, &status, options, rusage)
   380  	if wstatus != nil {
   381  		*wstatus = WaitStatus(status)
   382  	}
   383  	return
   384  }
   385  
   386  func Mkfifo(path string, mode uint32) (err error) {
   387  	return Mknod(path, mode|S_IFIFO, 0)
   388  }
   389  
   390  func (sa *SockaddrInet4) sockaddr() (unsafe.Pointer, _Socklen, error) {
   391  	if sa.Port < 0 || sa.Port > 0xFFFF {
   392  		return nil, 0, EINVAL
   393  	}
   394  	sa.raw.Family = AF_INET
   395  	p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port))
   396  	p[0] = byte(sa.Port >> 8)
   397  	p[1] = byte(sa.Port)
   398  	sa.raw.Addr = sa.Addr
   399  	return unsafe.Pointer(&sa.raw), SizeofSockaddrInet4, nil
   400  }
   401  
   402  func (sa *SockaddrInet6) sockaddr() (unsafe.Pointer, _Socklen, error) {
   403  	if sa.Port < 0 || sa.Port > 0xFFFF {
   404  		return nil, 0, EINVAL
   405  	}
   406  	sa.raw.Family = AF_INET6
   407  	p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port))
   408  	p[0] = byte(sa.Port >> 8)
   409  	p[1] = byte(sa.Port)
   410  	sa.raw.Scope_id = sa.ZoneId
   411  	sa.raw.Addr = sa.Addr
   412  	return unsafe.Pointer(&sa.raw), SizeofSockaddrInet6, nil
   413  }
   414  
   415  func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, _Socklen, error) {
   416  	name := sa.Name
   417  	n := len(name)
   418  	if n > len(sa.raw.Path) {
   419  		return nil, 0, EINVAL
   420  	}
   421  	if n == len(sa.raw.Path) && name[0] != '@' {
   422  		return nil, 0, EINVAL
   423  	}
   424  	sa.raw.Family = AF_UNIX
   425  	for i := 0; i < n; i++ {
   426  		sa.raw.Path[i] = int8(name[i])
   427  	}
   428  	// length is family (uint16), name, NUL.
   429  	sl := _Socklen(2)
   430  	if n > 0 {
   431  		sl += _Socklen(n) + 1
   432  	}
   433  	if sa.raw.Path[0] == '@' {
   434  		sa.raw.Path[0] = 0
   435  		// Don't count trailing NUL for abstract address.
   436  		sl--
   437  	}
   438  
   439  	return unsafe.Pointer(&sa.raw), sl, nil
   440  }
   441  
   442  type SockaddrLinklayer struct {
   443  	Protocol uint16
   444  	Ifindex  int
   445  	Hatype   uint16
   446  	Pkttype  uint8
   447  	Halen    uint8
   448  	Addr     [8]byte
   449  	raw      RawSockaddrLinklayer
   450  }
   451  
   452  func (sa *SockaddrLinklayer) sockaddr() (unsafe.Pointer, _Socklen, error) {
   453  	if sa.Ifindex < 0 || sa.Ifindex > 0x7fffffff {
   454  		return nil, 0, EINVAL
   455  	}
   456  	sa.raw.Family = AF_PACKET
   457  	sa.raw.Protocol = sa.Protocol
   458  	sa.raw.Ifindex = int32(sa.Ifindex)
   459  	sa.raw.Hatype = sa.Hatype
   460  	sa.raw.Pkttype = sa.Pkttype
   461  	sa.raw.Halen = sa.Halen
   462  	sa.raw.Addr = sa.Addr
   463  	return unsafe.Pointer(&sa.raw), SizeofSockaddrLinklayer, nil
   464  }
   465  
   466  type SockaddrNetlink struct {
   467  	Family uint16
   468  	Pad    uint16
   469  	Pid    uint32
   470  	Groups uint32
   471  	raw    RawSockaddrNetlink
   472  }
   473  
   474  func (sa *SockaddrNetlink) sockaddr() (unsafe.Pointer, _Socklen, error) {
   475  	sa.raw.Family = AF_NETLINK
   476  	sa.raw.Pad = sa.Pad
   477  	sa.raw.Pid = sa.Pid
   478  	sa.raw.Groups = sa.Groups
   479  	return unsafe.Pointer(&sa.raw), SizeofSockaddrNetlink, nil
   480  }
   481  
   482  func anyToSockaddr(rsa *RawSockaddrAny) (Sockaddr, error) {
   483  	switch rsa.Addr.Family {
   484  	case AF_NETLINK:
   485  		pp := (*RawSockaddrNetlink)(unsafe.Pointer(rsa))
   486  		sa := new(SockaddrNetlink)
   487  		sa.Family = pp.Family
   488  		sa.Pad = pp.Pad
   489  		sa.Pid = pp.Pid
   490  		sa.Groups = pp.Groups
   491  		return sa, nil
   492  
   493  	case AF_PACKET:
   494  		pp := (*RawSockaddrLinklayer)(unsafe.Pointer(rsa))
   495  		sa := new(SockaddrLinklayer)
   496  		sa.Protocol = pp.Protocol
   497  		sa.Ifindex = int(pp.Ifindex)
   498  		sa.Hatype = pp.Hatype
   499  		sa.Pkttype = pp.Pkttype
   500  		sa.Halen = pp.Halen
   501  		sa.Addr = pp.Addr
   502  		return sa, nil
   503  
   504  	case AF_UNIX:
   505  		pp := (*RawSockaddrUnix)(unsafe.Pointer(rsa))
   506  		sa := new(SockaddrUnix)
   507  		if pp.Path[0] == 0 {
   508  			// "Abstract" Unix domain socket.
   509  			// Rewrite leading NUL as @ for textual display.
   510  			// (This is the standard convention.)
   511  			// Not friendly to overwrite in place,
   512  			// but the callers below don't care.
   513  			pp.Path[0] = '@'
   514  		}
   515  
   516  		// Assume path ends at NUL.
   517  		// This is not technically the Linux semantics for
   518  		// abstract Unix domain sockets--they are supposed
   519  		// to be uninterpreted fixed-size binary blobs--but
   520  		// everyone uses this convention.
   521  		n := 0
   522  		for n < len(pp.Path) && pp.Path[n] != 0 {
   523  			n++
   524  		}
   525  		bytes := (*[len(pp.Path)]byte)(unsafe.Pointer(&pp.Path[0]))[0:n]
   526  		sa.Name = string(bytes)
   527  		return sa, nil
   528  
   529  	case AF_INET:
   530  		pp := (*RawSockaddrInet4)(unsafe.Pointer(rsa))
   531  		sa := new(SockaddrInet4)
   532  		p := (*[2]byte)(unsafe.Pointer(&pp.Port))
   533  		sa.Port = int(p[0])<<8 + int(p[1])
   534  		sa.Addr = pp.Addr
   535  		return sa, nil
   536  
   537  	case AF_INET6:
   538  		pp := (*RawSockaddrInet6)(unsafe.Pointer(rsa))
   539  		sa := new(SockaddrInet6)
   540  		p := (*[2]byte)(unsafe.Pointer(&pp.Port))
   541  		sa.Port = int(p[0])<<8 + int(p[1])
   542  		sa.ZoneId = pp.Scope_id
   543  		sa.Addr = pp.Addr
   544  		return sa, nil
   545  	}
   546  	return nil, EAFNOSUPPORT
   547  }
   548  
   549  func Accept(fd int) (nfd int, sa Sockaddr, err error) {
   550  	var rsa RawSockaddrAny
   551  	var len _Socklen = SizeofSockaddrAny
   552  	nfd, err = accept4(fd, &rsa, &len, 0)
   553  	if err != nil {
   554  		return
   555  	}
   556  	sa, err = anyToSockaddr(&rsa)
   557  	if err != nil {
   558  		Close(nfd)
   559  		nfd = 0
   560  	}
   561  	return
   562  }
   563  
   564  func Accept4(fd int, flags int) (nfd int, sa Sockaddr, err error) {
   565  	var rsa RawSockaddrAny
   566  	var len _Socklen = SizeofSockaddrAny
   567  	nfd, err = accept4(fd, &rsa, &len, flags)
   568  	if err != nil {
   569  		return
   570  	}
   571  	if len > SizeofSockaddrAny {
   572  		panic("RawSockaddrAny too small")
   573  	}
   574  	sa, err = anyToSockaddr(&rsa)
   575  	if err != nil {
   576  		Close(nfd)
   577  		nfd = 0
   578  	}
   579  	return
   580  }
   581  
   582  func Getsockname(fd int) (sa Sockaddr, err error) {
   583  	var rsa RawSockaddrAny
   584  	var len _Socklen = SizeofSockaddrAny
   585  	if err = getsockname(fd, &rsa, &len); err != nil {
   586  		return
   587  	}
   588  	return anyToSockaddr(&rsa)
   589  }
   590  
   591  func GetsockoptInet4Addr(fd, level, opt int) (value [4]byte, err error) {
   592  	vallen := _Socklen(4)
   593  	err = getsockopt(fd, level, opt, unsafe.Pointer(&value[0]), &vallen)
   594  	return value, err
   595  }
   596  
   597  func GetsockoptIPMreq(fd, level, opt int) (*IPMreq, error) {
   598  	var value IPMreq
   599  	vallen := _Socklen(SizeofIPMreq)
   600  	err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
   601  	return &value, err
   602  }
   603  
   604  func GetsockoptIPMreqn(fd, level, opt int) (*IPMreqn, error) {
   605  	var value IPMreqn
   606  	vallen := _Socklen(SizeofIPMreqn)
   607  	err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
   608  	return &value, err
   609  }
   610  
   611  func GetsockoptIPv6Mreq(fd, level, opt int) (*IPv6Mreq, error) {
   612  	var value IPv6Mreq
   613  	vallen := _Socklen(SizeofIPv6Mreq)
   614  	err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
   615  	return &value, err
   616  }
   617  
   618  func GetsockoptIPv6MTUInfo(fd, level, opt int) (*IPv6MTUInfo, error) {
   619  	var value IPv6MTUInfo
   620  	vallen := _Socklen(SizeofIPv6MTUInfo)
   621  	err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
   622  	return &value, err
   623  }
   624  
   625  func GetsockoptICMPv6Filter(fd, level, opt int) (*ICMPv6Filter, error) {
   626  	var value ICMPv6Filter
   627  	vallen := _Socklen(SizeofICMPv6Filter)
   628  	err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
   629  	return &value, err
   630  }
   631  
   632  func GetsockoptUcred(fd, level, opt int) (*Ucred, error) {
   633  	var value Ucred
   634  	vallen := _Socklen(SizeofUcred)
   635  	err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
   636  	return &value, err
   637  }
   638  
   639  func SetsockoptIPMreqn(fd, level, opt int, mreq *IPMreqn) (err error) {
   640  	return setsockopt(fd, level, opt, unsafe.Pointer(mreq), unsafe.Sizeof(*mreq))
   641  }
   642  
   643  func recvmsgRaw(fd int, p, oob []byte, flags int, rsa *RawSockaddrAny) (n, oobn int, recvflags int, err error) {
   644  	var msg Msghdr
   645  	msg.Name = (*byte)(unsafe.Pointer(rsa))
   646  	msg.Namelen = uint32(SizeofSockaddrAny)
   647  	var iov Iovec
   648  	if len(p) > 0 {
   649  		iov.Base = &p[0]
   650  		iov.SetLen(len(p))
   651  	}
   652  	var dummy byte
   653  	if len(oob) > 0 {
   654  		if len(p) == 0 {
   655  			var sockType int
   656  			sockType, err = GetsockoptInt(fd, SOL_SOCKET, SO_TYPE)
   657  			if err != nil {
   658  				return
   659  			}
   660  			// receive at least one normal byte
   661  			if sockType != SOCK_DGRAM {
   662  				iov.Base = &dummy
   663  				iov.SetLen(1)
   664  			}
   665  		}
   666  		msg.Control = &oob[0]
   667  		msg.SetControllen(len(oob))
   668  	}
   669  	msg.Iov = &iov
   670  	msg.Iovlen = 1
   671  	if n, err = recvmsg(fd, &msg, flags); err != nil {
   672  		return
   673  	}
   674  	oobn = int(msg.Controllen)
   675  	recvflags = int(msg.Flags)
   676  	return
   677  }
   678  
   679  func sendmsgN(fd int, p, oob []byte, ptr unsafe.Pointer, salen _Socklen, flags int) (n int, err error) {
   680  	var msg Msghdr
   681  	msg.Name = (*byte)(ptr)
   682  	msg.Namelen = uint32(salen)
   683  	var iov Iovec
   684  	if len(p) > 0 {
   685  		iov.Base = &p[0]
   686  		iov.SetLen(len(p))
   687  	}
   688  	var dummy byte
   689  	if len(oob) > 0 {
   690  		if len(p) == 0 {
   691  			var sockType int
   692  			sockType, err = GetsockoptInt(fd, SOL_SOCKET, SO_TYPE)
   693  			if err != nil {
   694  				return 0, err
   695  			}
   696  			// send at least one normal byte
   697  			if sockType != SOCK_DGRAM {
   698  				iov.Base = &dummy
   699  				iov.SetLen(1)
   700  			}
   701  		}
   702  		msg.Control = &oob[0]
   703  		msg.SetControllen(len(oob))
   704  	}
   705  	msg.Iov = &iov
   706  	msg.Iovlen = 1
   707  	if n, err = sendmsg(fd, &msg, flags); err != nil {
   708  		return 0, err
   709  	}
   710  	if len(oob) > 0 && len(p) == 0 {
   711  		n = 0
   712  	}
   713  	return n, nil
   714  }
   715  
   716  // BindToDevice binds the socket associated with fd to device.
   717  func BindToDevice(fd int, device string) (err error) {
   718  	return SetsockoptString(fd, SOL_SOCKET, SO_BINDTODEVICE, device)
   719  }
   720  
   721  //sys	ptrace(request int, pid int, addr uintptr, data uintptr) (err error)
   722  
   723  func ptracePeek(req int, pid int, addr uintptr, out []byte) (count int, err error) {
   724  	// The peek requests are machine-size oriented, so we wrap it
   725  	// to retrieve arbitrary-length data.
   726  
   727  	// The ptrace syscall differs from glibc's ptrace.
   728  	// Peeks returns the word in *data, not as the return value.
   729  
   730  	var buf [sizeofPtr]byte
   731  
   732  	// Leading edge. PEEKTEXT/PEEKDATA don't require aligned
   733  	// access (PEEKUSER warns that it might), but if we don't
   734  	// align our reads, we might straddle an unmapped page
   735  	// boundary and not get the bytes leading up to the page
   736  	// boundary.
   737  	n := 0
   738  	if addr%sizeofPtr != 0 {
   739  		err = ptrace(req, pid, addr-addr%sizeofPtr, uintptr(unsafe.Pointer(&buf[0])))
   740  		if err != nil {
   741  			return 0, err
   742  		}
   743  		n += copy(out, buf[addr%sizeofPtr:])
   744  		out = out[n:]
   745  	}
   746  
   747  	// Remainder.
   748  	for len(out) > 0 {
   749  		// We use an internal buffer to guarantee alignment.
   750  		// It's not documented if this is necessary, but we're paranoid.
   751  		err = ptrace(req, pid, addr+uintptr(n), uintptr(unsafe.Pointer(&buf[0])))
   752  		if err != nil {
   753  			return n, err
   754  		}
   755  		copied := copy(out, buf[0:])
   756  		n += copied
   757  		out = out[copied:]
   758  	}
   759  
   760  	return n, nil
   761  }
   762  
   763  func PtracePeekText(pid int, addr uintptr, out []byte) (count int, err error) {
   764  	return ptracePeek(PTRACE_PEEKTEXT, pid, addr, out)
   765  }
   766  
   767  func PtracePeekData(pid int, addr uintptr, out []byte) (count int, err error) {
   768  	return ptracePeek(PTRACE_PEEKDATA, pid, addr, out)
   769  }
   770  
   771  func ptracePoke(pokeReq int, peekReq int, pid int, addr uintptr, data []byte) (count int, err error) {
   772  	// As for ptracePeek, we need to align our accesses to deal
   773  	// with the possibility of straddling an invalid page.
   774  
   775  	// Leading edge.
   776  	n := 0
   777  	if addr%sizeofPtr != 0 {
   778  		var buf [sizeofPtr]byte
   779  		err = ptrace(peekReq, pid, addr-addr%sizeofPtr, uintptr(unsafe.Pointer(&buf[0])))
   780  		if err != nil {
   781  			return 0, err
   782  		}
   783  		n += copy(buf[addr%sizeofPtr:], data)
   784  		word := *((*uintptr)(unsafe.Pointer(&buf[0])))
   785  		err = ptrace(pokeReq, pid, addr-addr%sizeofPtr, word)
   786  		if err != nil {
   787  			return 0, err
   788  		}
   789  		data = data[n:]
   790  	}
   791  
   792  	// Interior.
   793  	for len(data) > sizeofPtr {
   794  		word := *((*uintptr)(unsafe.Pointer(&data[0])))
   795  		err = ptrace(pokeReq, pid, addr+uintptr(n), word)
   796  		if err != nil {
   797  			return n, err
   798  		}
   799  		n += sizeofPtr
   800  		data = data[sizeofPtr:]
   801  	}
   802  
   803  	// Trailing edge.
   804  	if len(data) > 0 {
   805  		var buf [sizeofPtr]byte
   806  		err = ptrace(peekReq, pid, addr+uintptr(n), uintptr(unsafe.Pointer(&buf[0])))
   807  		if err != nil {
   808  			return n, err
   809  		}
   810  		copy(buf[0:], data)
   811  		word := *((*uintptr)(unsafe.Pointer(&buf[0])))
   812  		err = ptrace(pokeReq, pid, addr+uintptr(n), word)
   813  		if err != nil {
   814  			return n, err
   815  		}
   816  		n += len(data)
   817  	}
   818  
   819  	return n, nil
   820  }
   821  
   822  func PtracePokeText(pid int, addr uintptr, data []byte) (count int, err error) {
   823  	return ptracePoke(PTRACE_POKETEXT, PTRACE_PEEKTEXT, pid, addr, data)
   824  }
   825  
   826  func PtracePokeData(pid int, addr uintptr, data []byte) (count int, err error) {
   827  	return ptracePoke(PTRACE_POKEDATA, PTRACE_PEEKDATA, pid, addr, data)
   828  }
   829  
   830  func PtraceGetRegs(pid int, regsout *PtraceRegs) (err error) {
   831  	return ptrace(PTRACE_GETREGS, pid, 0, uintptr(unsafe.Pointer(regsout)))
   832  }
   833  
   834  func PtraceSetRegs(pid int, regs *PtraceRegs) (err error) {
   835  	return ptrace(PTRACE_SETREGS, pid, 0, uintptr(unsafe.Pointer(regs)))
   836  }
   837  
   838  func PtraceSetOptions(pid int, options int) (err error) {
   839  	return ptrace(PTRACE_SETOPTIONS, pid, 0, uintptr(options))
   840  }
   841  
   842  func PtraceGetEventMsg(pid int) (msg uint, err error) {
   843  	var data _C_long
   844  	err = ptrace(PTRACE_GETEVENTMSG, pid, 0, uintptr(unsafe.Pointer(&data)))
   845  	msg = uint(data)
   846  	return
   847  }
   848  
   849  func PtraceCont(pid int, signal int) (err error) {
   850  	return ptrace(PTRACE_CONT, pid, 0, uintptr(signal))
   851  }
   852  
   853  func PtraceSyscall(pid int, signal int) (err error) {
   854  	return ptrace(PTRACE_SYSCALL, pid, 0, uintptr(signal))
   855  }
   856  
   857  func PtraceSingleStep(pid int) (err error) { return ptrace(PTRACE_SINGLESTEP, pid, 0, 0) }
   858  
   859  func PtraceAttach(pid int) (err error) { return ptrace(PTRACE_ATTACH, pid, 0, 0) }
   860  
   861  func PtraceDetach(pid int) (err error) { return ptrace(PTRACE_DETACH, pid, 0, 0) }
   862  
   863  //sys	reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error)
   864  
   865  func Reboot(cmd int) (err error) {
   866  	return reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, cmd, "")
   867  }
   868  
   869  func ReadDirent(fd int, buf []byte) (n int, err error) {
   870  	return Getdents(fd, buf)
   871  }
   872  
   873  func direntIno(buf []byte) (uint64, bool) {
   874  	return readInt(buf, unsafe.Offsetof(Dirent{}.Ino), unsafe.Sizeof(Dirent{}.Ino))
   875  }
   876  
   877  func direntReclen(buf []byte) (uint64, bool) {
   878  	return readInt(buf, unsafe.Offsetof(Dirent{}.Reclen), unsafe.Sizeof(Dirent{}.Reclen))
   879  }
   880  
   881  func direntNamlen(buf []byte) (uint64, bool) {
   882  	reclen, ok := direntReclen(buf)
   883  	if !ok {
   884  		return 0, false
   885  	}
   886  	return reclen - uint64(unsafe.Offsetof(Dirent{}.Name)), true
   887  }
   888  
   889  //sys	mount(source string, target string, fstype string, flags uintptr, data *byte) (err error)
   890  
   891  func Mount(source string, target string, fstype string, flags uintptr, data string) (err error) {
   892  	// Certain file systems get rather angry and EINVAL if you give
   893  	// them an empty string of data, rather than NULL.
   894  	if data == "" {
   895  		return mount(source, target, fstype, flags, nil)
   896  	}
   897  	datap, err := BytePtrFromString(data)
   898  	if err != nil {
   899  		return err
   900  	}
   901  	return mount(source, target, fstype, flags, datap)
   902  }
   903  
   904  // Sendto
   905  // Recvfrom
   906  // Socketpair
   907  
   908  /*
   909   * Direct access
   910   */
   911  //sys	Acct(path string) (err error)
   912  //sys	Adjtimex(buf *Timex) (state int, err error)
   913  //sys	Chdir(path string) (err error)
   914  //sys	Chroot(path string) (err error)
   915  //sys	Close(fd int) (err error)
   916  //sys	Dup(oldfd int) (fd int, err error)
   917  //sys	Dup3(oldfd int, newfd int, flags int) (err error)
   918  //sysnb	EpollCreate1(flag int) (fd int, err error)
   919  //sysnb	EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error)
   920  //sys	Fallocate(fd int, mode uint32, off int64, len int64) (err error)
   921  //sys	Fchdir(fd int) (err error)
   922  //sys	Fchmod(fd int, mode uint32) (err error)
   923  //sys	Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error)
   924  //sys	fcntl(fd int, cmd int, arg int) (val int, err error)
   925  //sys	Fdatasync(fd int) (err error)
   926  //sys	Flock(fd int, how int) (err error)
   927  //sys	Fsync(fd int) (err error)
   928  //sys	Getdents(fd int, buf []byte) (n int, err error) = SYS_GETDENTS64
   929  //sysnb	Getpgid(pid int) (pgid int, err error)
   930  
   931  func Getpgrp() (pid int) {
   932  	pid, _ = Getpgid(0)
   933  	return
   934  }
   935  
   936  //sysnb	Getpid() (pid int)
   937  //sysnb	Getppid() (ppid int)
   938  //sys	Getpriority(which int, who int) (prio int, err error)
   939  //sysnb	Getrusage(who int, rusage *Rusage) (err error)
   940  //sysnb	Gettid() (tid int)
   941  //sys	Getxattr(path string, attr string, dest []byte) (sz int, err error)
   942  //sys	InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error)
   943  //sysnb	InotifyInit1(flags int) (fd int, err error)
   944  //sysnb	InotifyRmWatch(fd int, watchdesc uint32) (success int, err error)
   945  //sysnb	Kill(pid int, sig Signal) (err error)
   946  //sys	Klogctl(typ int, buf []byte) (n int, err error) = SYS_SYSLOG
   947  //sys	Listxattr(path string, dest []byte) (sz int, err error)
   948  //sys	Mkdirat(dirfd int, path string, mode uint32) (err error)
   949  //sys	Mknodat(dirfd int, path string, mode uint32, dev int) (err error)
   950  //sys	Nanosleep(time *Timespec, leftover *Timespec) (err error)
   951  //sys	PivotRoot(newroot string, putold string) (err error) = SYS_PIVOT_ROOT
   952  //sysnb prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) = SYS_PRLIMIT64
   953  //sys	read(fd int, p []byte) (n int, err error)
   954  //sys	Removexattr(path string, attr string) (err error)
   955  //sys	Setdomainname(p []byte) (err error)
   956  //sys	Sethostname(p []byte) (err error)
   957  //sysnb	Setpgid(pid int, pgid int) (err error)
   958  //sysnb	Setsid() (pid int, err error)
   959  //sysnb	Settimeofday(tv *Timeval) (err error)
   960  
   961  // Provided by runtime.syscall_runtime_doAllThreadsSyscall which stops the
   962  // world and invokes the syscall on each OS thread. Once this function returns,
   963  // all threads are in sync.
   964  //go:uintptrescapes
   965  func runtime_doAllThreadsSyscall(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2, err uintptr)
   966  
   967  // AllThreadsSyscall performs a syscall on each OS thread of the Go
   968  // runtime. It first invokes the syscall on one thread. Should that
   969  // invocation fail, it returns immediately with the error status.
   970  // Otherwise, it invokes the syscall on all of the remaining threads
   971  // in parallel. It will terminate the program if it observes any
   972  // invoked syscall's return value differs from that of the first
   973  // invocation.
   974  //
   975  // AllThreadsSyscall is intended for emulating simultaneous
   976  // process-wide state changes that require consistently modifying
   977  // per-thread state of the Go runtime.
   978  //
   979  // AllThreadsSyscall is unaware of any threads that are launched
   980  // explicitly by cgo linked code, so the function always returns
   981  // ENOTSUP in binaries that use cgo.
   982  //go:uintptrescapes
   983  func AllThreadsSyscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err Errno) {
   984  	if cgo_libc_setegid != nil {
   985  		return minus1, minus1, ENOTSUP
   986  	}
   987  	r1, r2, errno := runtime_doAllThreadsSyscall(trap, a1, a2, a3, 0, 0, 0)
   988  	return r1, r2, Errno(errno)
   989  }
   990  
   991  // AllThreadsSyscall6 is like AllThreadsSyscall, but extended to six
   992  // arguments.
   993  //go:uintptrescapes
   994  func AllThreadsSyscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err Errno) {
   995  	if cgo_libc_setegid != nil {
   996  		return minus1, minus1, ENOTSUP
   997  	}
   998  	r1, r2, errno := runtime_doAllThreadsSyscall(trap, a1, a2, a3, a4, a5, a6)
   999  	return r1, r2, Errno(errno)
  1000  }
  1001  
  1002  // linked by runtime.cgocall.go
  1003  //go:uintptrescapes
  1004  func cgocaller(unsafe.Pointer, ...uintptr) uintptr
  1005  
  1006  var cgo_libc_setegid unsafe.Pointer // non-nil if cgo linked.
  1007  
  1008  const minus1 = ^uintptr(0)
  1009  
  1010  func Setegid(egid int) (err error) {
  1011  	if cgo_libc_setegid == nil {
  1012  		if _, _, e1 := AllThreadsSyscall(SYS_SETRESGID, minus1, uintptr(egid), minus1); e1 != 0 {
  1013  			err = errnoErr(e1)
  1014  		}
  1015  	} else if ret := cgocaller(cgo_libc_setegid, uintptr(egid)); ret != 0 {
  1016  		err = errnoErr(Errno(ret))
  1017  	}
  1018  	return
  1019  }
  1020  
  1021  var cgo_libc_seteuid unsafe.Pointer // non-nil if cgo linked.
  1022  
  1023  func Seteuid(euid int) (err error) {
  1024  	if cgo_libc_seteuid == nil {
  1025  		if _, _, e1 := AllThreadsSyscall(SYS_SETRESUID, minus1, uintptr(euid), minus1); e1 != 0 {
  1026  			err = errnoErr(e1)
  1027  		}
  1028  	} else if ret := cgocaller(cgo_libc_seteuid, uintptr(euid)); ret != 0 {
  1029  		err = errnoErr(Errno(ret))
  1030  	}
  1031  	return
  1032  }
  1033  
  1034  var cgo_libc_setgid unsafe.Pointer // non-nil if cgo linked.
  1035  
  1036  func Setgid(gid int) (err error) {
  1037  	if cgo_libc_setgid == nil {
  1038  		if _, _, e1 := AllThreadsSyscall(sys_SETGID, uintptr(gid), 0, 0); e1 != 0 {
  1039  			err = errnoErr(e1)
  1040  		}
  1041  	} else if ret := cgocaller(cgo_libc_setgid, uintptr(gid)); ret != 0 {
  1042  		err = errnoErr(Errno(ret))
  1043  	}
  1044  	return
  1045  }
  1046  
  1047  var cgo_libc_setregid unsafe.Pointer // non-nil if cgo linked.
  1048  
  1049  func Setregid(rgid, egid int) (err error) {
  1050  	if cgo_libc_setregid == nil {
  1051  		if _, _, e1 := AllThreadsSyscall(sys_SETREGID, uintptr(rgid), uintptr(egid), 0); e1 != 0 {
  1052  			err = errnoErr(e1)
  1053  		}
  1054  	} else if ret := cgocaller(cgo_libc_setregid, uintptr(rgid), uintptr(egid)); ret != 0 {
  1055  		err = errnoErr(Errno(ret))
  1056  	}
  1057  	return
  1058  }
  1059  
  1060  var cgo_libc_setresgid unsafe.Pointer // non-nil if cgo linked.
  1061  
  1062  func Setresgid(rgid, egid, sgid int) (err error) {
  1063  	if cgo_libc_setresgid == nil {
  1064  		if _, _, e1 := AllThreadsSyscall(sys_SETRESGID, uintptr(rgid), uintptr(egid), uintptr(sgid)); e1 != 0 {
  1065  			err = errnoErr(e1)
  1066  		}
  1067  	} else if ret := cgocaller(cgo_libc_setresgid, uintptr(rgid), uintptr(egid), uintptr(sgid)); ret != 0 {
  1068  		err = errnoErr(Errno(ret))
  1069  	}
  1070  	return
  1071  }
  1072  
  1073  var cgo_libc_setresuid unsafe.Pointer // non-nil if cgo linked.
  1074  
  1075  func Setresuid(ruid, euid, suid int) (err error) {
  1076  	if cgo_libc_setresuid == nil {
  1077  		if _, _, e1 := AllThreadsSyscall(sys_SETRESUID, uintptr(ruid), uintptr(euid), uintptr(suid)); e1 != 0 {
  1078  			err = errnoErr(e1)
  1079  		}
  1080  	} else if ret := cgocaller(cgo_libc_setresuid, uintptr(ruid), uintptr(euid), uintptr(suid)); ret != 0 {
  1081  		err = errnoErr(Errno(ret))
  1082  	}
  1083  	return
  1084  }
  1085  
  1086  var cgo_libc_setreuid unsafe.Pointer // non-nil if cgo linked.
  1087  
  1088  func Setreuid(ruid, euid int) (err error) {
  1089  	if cgo_libc_setreuid == nil {
  1090  		if _, _, e1 := AllThreadsSyscall(sys_SETREUID, uintptr(ruid), uintptr(euid), 0); e1 != 0 {
  1091  			err = errnoErr(e1)
  1092  		}
  1093  	} else if ret := cgocaller(cgo_libc_setreuid, uintptr(ruid), uintptr(euid)); ret != 0 {
  1094  		err = errnoErr(Errno(ret))
  1095  	}
  1096  	return
  1097  }
  1098  
  1099  var cgo_libc_setuid unsafe.Pointer // non-nil if cgo linked.
  1100  
  1101  func Setuid(uid int) (err error) {
  1102  	if cgo_libc_setuid == nil {
  1103  		if _, _, e1 := AllThreadsSyscall(sys_SETUID, uintptr(uid), 0, 0); e1 != 0 {
  1104  			err = errnoErr(e1)
  1105  		}
  1106  	} else if ret := cgocaller(cgo_libc_setuid, uintptr(uid)); ret != 0 {
  1107  		err = errnoErr(Errno(ret))
  1108  	}
  1109  	return
  1110  }
  1111  
  1112  //sys	Setpriority(which int, who int, prio int) (err error)
  1113  //sys	Setxattr(path string, attr string, data []byte, flags int) (err error)
  1114  //sys	Sync()
  1115  //sysnb	Sysinfo(info *Sysinfo_t) (err error)
  1116  //sys	Tee(rfd int, wfd int, len int, flags int) (n int64, err error)
  1117  //sysnb	Tgkill(tgid int, tid int, sig Signal) (err error)
  1118  //sysnb	Times(tms *Tms) (ticks uintptr, err error)
  1119  //sysnb	Umask(mask int) (oldmask int)
  1120  //sysnb	Uname(buf *Utsname) (err error)
  1121  //sys	Unmount(target string, flags int) (err error) = SYS_UMOUNT2
  1122  //sys	Unshare(flags int) (err error)
  1123  //sys	write(fd int, p []byte) (n int, err error)
  1124  //sys	exitThread(code int) (err error) = SYS_EXIT
  1125  //sys	readlen(fd int, p *byte, np int) (n int, err error) = SYS_READ
  1126  //sys	writelen(fd int, p *byte, np int) (n int, err error) = SYS_WRITE
  1127  
  1128  // mmap varies by architecture; see syscall_linux_*.go.
  1129  //sys	munmap(addr uintptr, length uintptr) (err error)
  1130  
  1131  var mapper = &mmapper{
  1132  	active: make(map[*byte][]byte),
  1133  	mmap:   mmap,
  1134  	munmap: munmap,
  1135  }
  1136  
  1137  func Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error) {
  1138  	return mapper.Mmap(fd, offset, length, prot, flags)
  1139  }
  1140  
  1141  func Munmap(b []byte) (err error) {
  1142  	return mapper.Munmap(b)
  1143  }
  1144  
  1145  //sys	Madvise(b []byte, advice int) (err error)
  1146  //sys	Mprotect(b []byte, prot int) (err error)
  1147  //sys	Mlock(b []byte) (err error)
  1148  //sys	Munlock(b []byte) (err error)
  1149  //sys	Mlockall(flags int) (err error)
  1150  //sys	Munlockall() (err error)
  1151  

View as plain text