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
12package unix
13
14import (
15	"syscall"
16	"unsafe"
17)
18
19/*
20 * Wrapped
21 */
22
23func Access(path string, mode uint32) (err error) {
24	return Faccessat(AT_FDCWD, path, mode, 0)
25}
26
27func Chmod(path string, mode uint32) (err error) {
28	return Fchmodat(AT_FDCWD, path, mode, 0)
29}
30
31func Chown(path string, uid int, gid int) (err error) {
32	return Fchownat(AT_FDCWD, path, uid, gid, 0)
33}
34
35func Creat(path string, mode uint32) (fd int, err error) {
36	return Open(path, O_CREAT|O_WRONLY|O_TRUNC, mode)
37}
38
39//sys	fchmodat(dirfd int, path string, mode uint32) (err error)
40
41func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) {
42	// Linux fchmodat doesn't support the flags parameter. Mimick glibc's behavior
43	// and check the flags. Otherwise the mode would be applied to the symlink
44	// destination which is not what the user expects.
45	if flags&^AT_SYMLINK_NOFOLLOW != 0 {
46		return EINVAL
47	} else if flags&AT_SYMLINK_NOFOLLOW != 0 {
48		return EOPNOTSUPP
49	}
50	return fchmodat(dirfd, path, mode)
51}
52
53//sys	ioctl(fd int, req uint, arg uintptr) (err error)
54
55// ioctl itself should not be exposed directly, but additional get/set
56// functions for specific types are permissible.
57
58// IoctlSetInt performs an ioctl operation which sets an integer value
59// on fd, using the specified request number.
60func IoctlSetInt(fd int, req uint, value int) error {
61	return ioctl(fd, req, uintptr(value))
62}
63
64func IoctlSetWinsize(fd int, req uint, value *Winsize) error {
65	return ioctl(fd, req, uintptr(unsafe.Pointer(value)))
66}
67
68func IoctlSetTermios(fd int, req uint, value *Termios) error {
69	return ioctl(fd, req, uintptr(unsafe.Pointer(value)))
70}
71
72// IoctlGetInt performs an ioctl operation which gets an integer value
73// from fd, using the specified request number.
74func IoctlGetInt(fd int, req uint) (int, error) {
75	var value int
76	err := ioctl(fd, req, uintptr(unsafe.Pointer(&value)))
77	return value, err
78}
79
80func IoctlGetWinsize(fd int, req uint) (*Winsize, error) {
81	var value Winsize
82	err := ioctl(fd, req, uintptr(unsafe.Pointer(&value)))
83	return &value, err
84}
85
86func IoctlGetTermios(fd int, req uint) (*Termios, error) {
87	var value Termios
88	err := ioctl(fd, req, uintptr(unsafe.Pointer(&value)))
89	return &value, err
90}
91
92//sys	Linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error)
93
94func Link(oldpath string, newpath string) (err error) {
95	return Linkat(AT_FDCWD, oldpath, AT_FDCWD, newpath, 0)
96}
97
98func Mkdir(path string, mode uint32) (err error) {
99	return Mkdirat(AT_FDCWD, path, mode)
100}
101
102func Mknod(path string, mode uint32, dev int) (err error) {
103	return Mknodat(AT_FDCWD, path, mode, dev)
104}
105
106func 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
112func 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	ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error)
117
118func Ppoll(fds []PollFd, timeout *Timespec, sigmask *Sigset_t) (n int, err error) {
119	if len(fds) == 0 {
120		return ppoll(nil, 0, timeout, sigmask)
121	}
122	return ppoll(&fds[0], len(fds), timeout, sigmask)
123}
124
125//sys	Readlinkat(dirfd int, path string, buf []byte) (n int, err error)
126
127func Readlink(path string, buf []byte) (n int, err error) {
128	return Readlinkat(AT_FDCWD, path, buf)
129}
130
131func Rename(oldpath string, newpath string) (err error) {
132	return Renameat(AT_FDCWD, oldpath, AT_FDCWD, newpath)
133}
134
135func Rmdir(path string) error {
136	return Unlinkat(AT_FDCWD, path, AT_REMOVEDIR)
137}
138
139//sys	Symlinkat(oldpath string, newdirfd int, newpath string) (err error)
140
141func Symlink(oldpath string, newpath string) (err error) {
142	return Symlinkat(oldpath, AT_FDCWD, newpath)
143}
144
145func Unlink(path string) error {
146	return Unlinkat(AT_FDCWD, path, 0)
147}
148
149//sys	Unlinkat(dirfd int, path string, flags int) (err error)
150
151func Utimes(path string, tv []Timeval) error {
152	if tv == nil {
153		err := utimensat(AT_FDCWD, path, nil, 0)
154		if err != ENOSYS {
155			return err
156		}
157		return utimes(path, nil)
158	}
159	if len(tv) != 2 {
160		return EINVAL
161	}
162	var ts [2]Timespec
163	ts[0] = NsecToTimespec(TimevalToNsec(tv[0]))
164	ts[1] = NsecToTimespec(TimevalToNsec(tv[1]))
165	err := utimensat(AT_FDCWD, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), 0)
166	if err != ENOSYS {
167		return err
168	}
169	return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
170}
171
172//sys	utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error)
173
174func UtimesNano(path string, ts []Timespec) error {
175	if ts == nil {
176		err := utimensat(AT_FDCWD, path, nil, 0)
177		if err != ENOSYS {
178			return err
179		}
180		return utimes(path, nil)
181	}
182	if len(ts) != 2 {
183		return EINVAL
184	}
185	err := utimensat(AT_FDCWD, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), 0)
186	if err != ENOSYS {
187		return err
188	}
189	// If the utimensat syscall isn't available (utimensat was added to Linux
190	// in 2.6.22, Released, 8 July 2007) then fall back to utimes
191	var tv [2]Timeval
192	for i := 0; i < 2; i++ {
193		tv[i] = NsecToTimeval(TimespecToNsec(ts[i]))
194	}
195	return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
196}
197
198func UtimesNanoAt(dirfd int, path string, ts []Timespec, flags int) error {
199	if ts == nil {
200		return utimensat(dirfd, path, nil, flags)
201	}
202	if len(ts) != 2 {
203		return EINVAL
204	}
205	return utimensat(dirfd, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), flags)
206}
207
208func Futimesat(dirfd int, path string, tv []Timeval) error {
209	if tv == nil {
210		return futimesat(dirfd, path, nil)
211	}
212	if len(tv) != 2 {
213		return EINVAL
214	}
215	return futimesat(dirfd, path, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
216}
217
218func Futimes(fd int, tv []Timeval) (err error) {
219	// Believe it or not, this is the best we can do on Linux
220	// (and is what glibc does).
221	return Utimes("/proc/self/fd/"+itoa(fd), tv)
222}
223
224const ImplementsGetwd = true
225
226//sys	Getcwd(buf []byte) (n int, err error)
227
228func Getwd() (wd string, err error) {
229	var buf [PathMax]byte
230	n, err := Getcwd(buf[0:])
231	if err != nil {
232		return "", err
233	}
234	// Getcwd returns the number of bytes written to buf, including the NUL.
235	if n < 1 || n > len(buf) || buf[n-1] != 0 {
236		return "", EINVAL
237	}
238	return string(buf[0 : n-1]), nil
239}
240
241func Getgroups() (gids []int, err error) {
242	n, err := getgroups(0, nil)
243	if err != nil {
244		return nil, err
245	}
246	if n == 0 {
247		return nil, nil
248	}
249
250	// Sanity check group count. Max is 1<<16 on Linux.
251	if n < 0 || n > 1<<20 {
252		return nil, EINVAL
253	}
254
255	a := make([]_Gid_t, n)
256	n, err = getgroups(n, &a[0])
257	if err != nil {
258		return nil, err
259	}
260	gids = make([]int, n)
261	for i, v := range a[0:n] {
262		gids[i] = int(v)
263	}
264	return
265}
266
267func Setgroups(gids []int) (err error) {
268	if len(gids) == 0 {
269		return setgroups(0, nil)
270	}
271
272	a := make([]_Gid_t, len(gids))
273	for i, v := range gids {
274		a[i] = _Gid_t(v)
275	}
276	return setgroups(len(a), &a[0])
277}
278
279type WaitStatus uint32
280
281// Wait status is 7 bits at bottom, either 0 (exited),
282// 0x7F (stopped), or a signal number that caused an exit.
283// The 0x80 bit is whether there was a core dump.
284// An extra number (exit code, signal causing a stop)
285// is in the high bits. At least that's the idea.
286// There are various irregularities. For example, the
287// "continued" status is 0xFFFF, distinguishing itself
288// from stopped via the core dump bit.
289
290const (
291	mask    = 0x7F
292	core    = 0x80
293	exited  = 0x00
294	stopped = 0x7F
295	shift   = 8
296)
297
298func (w WaitStatus) Exited() bool { return w&mask == exited }
299
300func (w WaitStatus) Signaled() bool { return w&mask != stopped && w&mask != exited }
301
302func (w WaitStatus) Stopped() bool { return w&0xFF == stopped }
303
304func (w WaitStatus) Continued() bool { return w == 0xFFFF }
305
306func (w WaitStatus) CoreDump() bool { return w.Signaled() && w&core != 0 }
307
308func (w WaitStatus) ExitStatus() int {
309	if !w.Exited() {
310		return -1
311	}
312	return int(w>>shift) & 0xFF
313}
314
315func (w WaitStatus) Signal() syscall.Signal {
316	if !w.Signaled() {
317		return -1
318	}
319	return syscall.Signal(w & mask)
320}
321
322func (w WaitStatus) StopSignal() syscall.Signal {
323	if !w.Stopped() {
324		return -1
325	}
326	return syscall.Signal(w>>shift) & 0xFF
327}
328
329func (w WaitStatus) TrapCause() int {
330	if w.StopSignal() != SIGTRAP {
331		return -1
332	}
333	return int(w>>shift) >> 8
334}
335
336//sys	wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error)
337
338func Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, err error) {
339	var status _C_int
340	wpid, err = wait4(pid, &status, options, rusage)
341	if wstatus != nil {
342		*wstatus = WaitStatus(status)
343	}
344	return
345}
346
347func Mkfifo(path string, mode uint32) error {
348	return Mknod(path, mode|S_IFIFO, 0)
349}
350
351func Mkfifoat(dirfd int, path string, mode uint32) error {
352	return Mknodat(dirfd, path, mode|S_IFIFO, 0)
353}
354
355func (sa *SockaddrInet4) sockaddr() (unsafe.Pointer, _Socklen, error) {
356	if sa.Port < 0 || sa.Port > 0xFFFF {
357		return nil, 0, EINVAL
358	}
359	sa.raw.Family = AF_INET
360	p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port))
361	p[0] = byte(sa.Port >> 8)
362	p[1] = byte(sa.Port)
363	for i := 0; i < len(sa.Addr); i++ {
364		sa.raw.Addr[i] = sa.Addr[i]
365	}
366	return unsafe.Pointer(&sa.raw), SizeofSockaddrInet4, nil
367}
368
369func (sa *SockaddrInet6) sockaddr() (unsafe.Pointer, _Socklen, error) {
370	if sa.Port < 0 || sa.Port > 0xFFFF {
371		return nil, 0, EINVAL
372	}
373	sa.raw.Family = AF_INET6
374	p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port))
375	p[0] = byte(sa.Port >> 8)
376	p[1] = byte(sa.Port)
377	sa.raw.Scope_id = sa.ZoneId
378	for i := 0; i < len(sa.Addr); i++ {
379		sa.raw.Addr[i] = sa.Addr[i]
380	}
381	return unsafe.Pointer(&sa.raw), SizeofSockaddrInet6, nil
382}
383
384func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, _Socklen, error) {
385	name := sa.Name
386	n := len(name)
387	if n >= len(sa.raw.Path) {
388		return nil, 0, EINVAL
389	}
390	sa.raw.Family = AF_UNIX
391	for i := 0; i < n; i++ {
392		sa.raw.Path[i] = int8(name[i])
393	}
394	// length is family (uint16), name, NUL.
395	sl := _Socklen(2)
396	if n > 0 {
397		sl += _Socklen(n) + 1
398	}
399	if sa.raw.Path[0] == '@' {
400		sa.raw.Path[0] = 0
401		// Don't count trailing NUL for abstract address.
402		sl--
403	}
404
405	return unsafe.Pointer(&sa.raw), sl, nil
406}
407
408// SockaddrLinklayer implements the Sockaddr interface for AF_PACKET type sockets.
409type SockaddrLinklayer struct {
410	Protocol uint16
411	Ifindex  int
412	Hatype   uint16
413	Pkttype  uint8
414	Halen    uint8
415	Addr     [8]byte
416	raw      RawSockaddrLinklayer
417}
418
419func (sa *SockaddrLinklayer) sockaddr() (unsafe.Pointer, _Socklen, error) {
420	if sa.Ifindex < 0 || sa.Ifindex > 0x7fffffff {
421		return nil, 0, EINVAL
422	}
423	sa.raw.Family = AF_PACKET
424	sa.raw.Protocol = sa.Protocol
425	sa.raw.Ifindex = int32(sa.Ifindex)
426	sa.raw.Hatype = sa.Hatype
427	sa.raw.Pkttype = sa.Pkttype
428	sa.raw.Halen = sa.Halen
429	for i := 0; i < len(sa.Addr); i++ {
430		sa.raw.Addr[i] = sa.Addr[i]
431	}
432	return unsafe.Pointer(&sa.raw), SizeofSockaddrLinklayer, nil
433}
434
435// SockaddrNetlink implements the Sockaddr interface for AF_NETLINK type sockets.
436type SockaddrNetlink struct {
437	Family uint16
438	Pad    uint16
439	Pid    uint32
440	Groups uint32
441	raw    RawSockaddrNetlink
442}
443
444func (sa *SockaddrNetlink) sockaddr() (unsafe.Pointer, _Socklen, error) {
445	sa.raw.Family = AF_NETLINK
446	sa.raw.Pad = sa.Pad
447	sa.raw.Pid = sa.Pid
448	sa.raw.Groups = sa.Groups
449	return unsafe.Pointer(&sa.raw), SizeofSockaddrNetlink, nil
450}
451
452// SockaddrHCI implements the Sockaddr interface for AF_BLUETOOTH type sockets
453// using the HCI protocol.
454type SockaddrHCI struct {
455	Dev     uint16
456	Channel uint16
457	raw     RawSockaddrHCI
458}
459
460func (sa *SockaddrHCI) sockaddr() (unsafe.Pointer, _Socklen, error) {
461	sa.raw.Family = AF_BLUETOOTH
462	sa.raw.Dev = sa.Dev
463	sa.raw.Channel = sa.Channel
464	return unsafe.Pointer(&sa.raw), SizeofSockaddrHCI, nil
465}
466
467// SockaddrL2 implements the Sockaddr interface for AF_BLUETOOTH type sockets
468// using the L2CAP protocol.
469type SockaddrL2 struct {
470	PSM      uint16
471	CID      uint16
472	Addr     [6]uint8
473	AddrType uint8
474	raw      RawSockaddrL2
475}
476
477func (sa *SockaddrL2) sockaddr() (unsafe.Pointer, _Socklen, error) {
478	sa.raw.Family = AF_BLUETOOTH
479	psm := (*[2]byte)(unsafe.Pointer(&sa.raw.Psm))
480	psm[0] = byte(sa.PSM)
481	psm[1] = byte(sa.PSM >> 8)
482	for i := 0; i < len(sa.Addr); i++ {
483		sa.raw.Bdaddr[i] = sa.Addr[len(sa.Addr)-1-i]
484	}
485	cid := (*[2]byte)(unsafe.Pointer(&sa.raw.Cid))
486	cid[0] = byte(sa.CID)
487	cid[1] = byte(sa.CID >> 8)
488	sa.raw.Bdaddr_type = sa.AddrType
489	return unsafe.Pointer(&sa.raw), SizeofSockaddrL2, nil
490}
491
492// SockaddrCAN implements the Sockaddr interface for AF_CAN type sockets.
493// The RxID and TxID fields are used for transport protocol addressing in
494// (CAN_TP16, CAN_TP20, CAN_MCNET, and CAN_ISOTP), they can be left with
495// zero values for CAN_RAW and CAN_BCM sockets as they have no meaning.
496//
497// The SockaddrCAN struct must be bound to the socket file descriptor
498// using Bind before the CAN socket can be used.
499//
500//      // Read one raw CAN frame
501//      fd, _ := Socket(AF_CAN, SOCK_RAW, CAN_RAW)
502//      addr := &SockaddrCAN{Ifindex: index}
503//      Bind(fd, addr)
504//      frame := make([]byte, 16)
505//      Read(fd, frame)
506//
507// The full SocketCAN documentation can be found in the linux kernel
508// archives at: https://www.kernel.org/doc/Documentation/networking/can.txt
509type SockaddrCAN struct {
510	Ifindex int
511	RxID    uint32
512	TxID    uint32
513	raw     RawSockaddrCAN
514}
515
516func (sa *SockaddrCAN) sockaddr() (unsafe.Pointer, _Socklen, error) {
517	if sa.Ifindex < 0 || sa.Ifindex > 0x7fffffff {
518		return nil, 0, EINVAL
519	}
520	sa.raw.Family = AF_CAN
521	sa.raw.Ifindex = int32(sa.Ifindex)
522	rx := (*[4]byte)(unsafe.Pointer(&sa.RxID))
523	for i := 0; i < 4; i++ {
524		sa.raw.Addr[i] = rx[i]
525	}
526	tx := (*[4]byte)(unsafe.Pointer(&sa.TxID))
527	for i := 0; i < 4; i++ {
528		sa.raw.Addr[i+4] = tx[i]
529	}
530	return unsafe.Pointer(&sa.raw), SizeofSockaddrCAN, nil
531}
532
533// SockaddrALG implements the Sockaddr interface for AF_ALG type sockets.
534// SockaddrALG enables userspace access to the Linux kernel's cryptography
535// subsystem. The Type and Name fields specify which type of hash or cipher
536// should be used with a given socket.
537//
538// To create a file descriptor that provides access to a hash or cipher, both
539// Bind and Accept must be used. Once the setup process is complete, input
540// data can be written to the socket, processed by the kernel, and then read
541// back as hash output or ciphertext.
542//
543// Here is an example of using an AF_ALG socket with SHA1 hashing.
544// The initial socket setup process is as follows:
545//
546//      // Open a socket to perform SHA1 hashing.
547//      fd, _ := unix.Socket(unix.AF_ALG, unix.SOCK_SEQPACKET, 0)
548//      addr := &unix.SockaddrALG{Type: "hash", Name: "sha1"}
549//      unix.Bind(fd, addr)
550//      // Note: unix.Accept does not work at this time; must invoke accept()
551//      // manually using unix.Syscall.
552//      hashfd, _, _ := unix.Syscall(unix.SYS_ACCEPT, uintptr(fd), 0, 0)
553//
554// Once a file descriptor has been returned from Accept, it may be used to
555// perform SHA1 hashing. The descriptor is not safe for concurrent use, but
556// may be re-used repeatedly with subsequent Write and Read operations.
557//
558// When hashing a small byte slice or string, a single Write and Read may
559// be used:
560//
561//      // Assume hashfd is already configured using the setup process.
562//      hash := os.NewFile(hashfd, "sha1")
563//      // Hash an input string and read the results. Each Write discards
564//      // previous hash state. Read always reads the current state.
565//      b := make([]byte, 20)
566//      for i := 0; i < 2; i++ {
567//          io.WriteString(hash, "Hello, world.")
568//          hash.Read(b)
569//          fmt.Println(hex.EncodeToString(b))
570//      }
571//      // Output:
572//      // 2ae01472317d1935a84797ec1983ae243fc6aa28
573//      // 2ae01472317d1935a84797ec1983ae243fc6aa28
574//
575// For hashing larger byte slices, or byte streams such as those read from
576// a file or socket, use Sendto with MSG_MORE to instruct the kernel to update
577// the hash digest instead of creating a new one for a given chunk and finalizing it.
578//
579//      // Assume hashfd and addr are already configured using the setup process.
580//      hash := os.NewFile(hashfd, "sha1")
581//      // Hash the contents of a file.
582//      f, _ := os.Open("/tmp/linux-4.10-rc7.tar.xz")
583//      b := make([]byte, 4096)
584//      for {
585//          n, err := f.Read(b)
586//          if err == io.EOF {
587//              break
588//          }
589//          unix.Sendto(hashfd, b[:n], unix.MSG_MORE, addr)
590//      }
591//      hash.Read(b)
592//      fmt.Println(hex.EncodeToString(b))
593//      // Output: 85cdcad0c06eef66f805ecce353bec9accbeecc5
594//
595// For more information, see: http://www.chronox.de/crypto-API/crypto/userspace-if.html.
596type SockaddrALG struct {
597	Type    string
598	Name    string
599	Feature uint32
600	Mask    uint32
601	raw     RawSockaddrALG
602}
603
604func (sa *SockaddrALG) sockaddr() (unsafe.Pointer, _Socklen, error) {
605	// Leave room for NUL byte terminator.
606	if len(sa.Type) > 13 {
607		return nil, 0, EINVAL
608	}
609	if len(sa.Name) > 63 {
610		return nil, 0, EINVAL
611	}
612
613	sa.raw.Family = AF_ALG
614	sa.raw.Feat = sa.Feature
615	sa.raw.Mask = sa.Mask
616
617	typ, err := ByteSliceFromString(sa.Type)
618	if err != nil {
619		return nil, 0, err
620	}
621	name, err := ByteSliceFromString(sa.Name)
622	if err != nil {
623		return nil, 0, err
624	}
625
626	copy(sa.raw.Type[:], typ)
627	copy(sa.raw.Name[:], name)
628
629	return unsafe.Pointer(&sa.raw), SizeofSockaddrALG, nil
630}
631
632// SockaddrVM implements the Sockaddr interface for AF_VSOCK type sockets.
633// SockaddrVM provides access to Linux VM sockets: a mechanism that enables
634// bidirectional communication between a hypervisor and its guest virtual
635// machines.
636type SockaddrVM struct {
637	// CID and Port specify a context ID and port address for a VM socket.
638	// Guests have a unique CID, and hosts may have a well-known CID of:
639	//  - VMADDR_CID_HYPERVISOR: refers to the hypervisor process.
640	//  - VMADDR_CID_HOST: refers to other processes on the host.
641	CID  uint32
642	Port uint32
643	raw  RawSockaddrVM
644}
645
646func (sa *SockaddrVM) sockaddr() (unsafe.Pointer, _Socklen, error) {
647	sa.raw.Family = AF_VSOCK
648	sa.raw.Port = sa.Port
649	sa.raw.Cid = sa.CID
650
651	return unsafe.Pointer(&sa.raw), SizeofSockaddrVM, nil
652}
653
654func anyToSockaddr(rsa *RawSockaddrAny) (Sockaddr, error) {
655	switch rsa.Addr.Family {
656	case AF_NETLINK:
657		pp := (*RawSockaddrNetlink)(unsafe.Pointer(rsa))
658		sa := new(SockaddrNetlink)
659		sa.Family = pp.Family
660		sa.Pad = pp.Pad
661		sa.Pid = pp.Pid
662		sa.Groups = pp.Groups
663		return sa, nil
664
665	case AF_PACKET:
666		pp := (*RawSockaddrLinklayer)(unsafe.Pointer(rsa))
667		sa := new(SockaddrLinklayer)
668		sa.Protocol = pp.Protocol
669		sa.Ifindex = int(pp.Ifindex)
670		sa.Hatype = pp.Hatype
671		sa.Pkttype = pp.Pkttype
672		sa.Halen = pp.Halen
673		for i := 0; i < len(sa.Addr); i++ {
674			sa.Addr[i] = pp.Addr[i]
675		}
676		return sa, nil
677
678	case AF_UNIX:
679		pp := (*RawSockaddrUnix)(unsafe.Pointer(rsa))
680		sa := new(SockaddrUnix)
681		if pp.Path[0] == 0 {
682			// "Abstract" Unix domain socket.
683			// Rewrite leading NUL as @ for textual display.
684			// (This is the standard convention.)
685			// Not friendly to overwrite in place,
686			// but the callers below don't care.
687			pp.Path[0] = '@'
688		}
689
690		// Assume path ends at NUL.
691		// This is not technically the Linux semantics for
692		// abstract Unix domain sockets--they are supposed
693		// to be uninterpreted fixed-size binary blobs--but
694		// everyone uses this convention.
695		n := 0
696		for n < len(pp.Path) && pp.Path[n] != 0 {
697			n++
698		}
699		bytes := (*[10000]byte)(unsafe.Pointer(&pp.Path[0]))[0:n]
700		sa.Name = string(bytes)
701		return sa, nil
702
703	case AF_INET:
704		pp := (*RawSockaddrInet4)(unsafe.Pointer(rsa))
705		sa := new(SockaddrInet4)
706		p := (*[2]byte)(unsafe.Pointer(&pp.Port))
707		sa.Port = int(p[0])<<8 + int(p[1])
708		for i := 0; i < len(sa.Addr); i++ {
709			sa.Addr[i] = pp.Addr[i]
710		}
711		return sa, nil
712
713	case AF_INET6:
714		pp := (*RawSockaddrInet6)(unsafe.Pointer(rsa))
715		sa := new(SockaddrInet6)
716		p := (*[2]byte)(unsafe.Pointer(&pp.Port))
717		sa.Port = int(p[0])<<8 + int(p[1])
718		sa.ZoneId = pp.Scope_id
719		for i := 0; i < len(sa.Addr); i++ {
720			sa.Addr[i] = pp.Addr[i]
721		}
722		return sa, nil
723
724	case AF_VSOCK:
725		pp := (*RawSockaddrVM)(unsafe.Pointer(rsa))
726		sa := &SockaddrVM{
727			CID:  pp.Cid,
728			Port: pp.Port,
729		}
730		return sa, nil
731	}
732	return nil, EAFNOSUPPORT
733}
734
735func Accept(fd int) (nfd int, sa Sockaddr, err error) {
736	var rsa RawSockaddrAny
737	var len _Socklen = SizeofSockaddrAny
738	nfd, err = accept(fd, &rsa, &len)
739	if err != nil {
740		return
741	}
742	sa, err = anyToSockaddr(&rsa)
743	if err != nil {
744		Close(nfd)
745		nfd = 0
746	}
747	return
748}
749
750func Accept4(fd int, flags int) (nfd int, sa Sockaddr, err error) {
751	var rsa RawSockaddrAny
752	var len _Socklen = SizeofSockaddrAny
753	nfd, err = accept4(fd, &rsa, &len, flags)
754	if err != nil {
755		return
756	}
757	if len > SizeofSockaddrAny {
758		panic("RawSockaddrAny too small")
759	}
760	sa, err = anyToSockaddr(&rsa)
761	if err != nil {
762		Close(nfd)
763		nfd = 0
764	}
765	return
766}
767
768func Getsockname(fd int) (sa Sockaddr, err error) {
769	var rsa RawSockaddrAny
770	var len _Socklen = SizeofSockaddrAny
771	if err = getsockname(fd, &rsa, &len); err != nil {
772		return
773	}
774	return anyToSockaddr(&rsa)
775}
776
777func GetsockoptIPMreqn(fd, level, opt int) (*IPMreqn, error) {
778	var value IPMreqn
779	vallen := _Socklen(SizeofIPMreqn)
780	err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
781	return &value, err
782}
783
784func GetsockoptUcred(fd, level, opt int) (*Ucred, error) {
785	var value Ucred
786	vallen := _Socklen(SizeofUcred)
787	err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
788	return &value, err
789}
790
791func GetsockoptTCPInfo(fd, level, opt int) (*TCPInfo, error) {
792	var value TCPInfo
793	vallen := _Socklen(SizeofTCPInfo)
794	err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
795	return &value, err
796}
797
798// GetsockoptString returns the string value of the socket option opt for the
799// socket associated with fd at the given socket level.
800func GetsockoptString(fd, level, opt int) (string, error) {
801	buf := make([]byte, 256)
802	vallen := _Socklen(len(buf))
803	err := getsockopt(fd, level, opt, unsafe.Pointer(&buf[0]), &vallen)
804	if err != nil {
805		if err == ERANGE {
806			buf = make([]byte, vallen)
807			err = getsockopt(fd, level, opt, unsafe.Pointer(&buf[0]), &vallen)
808		}
809		if err != nil {
810			return "", err
811		}
812	}
813	return string(buf[:vallen-1]), nil
814}
815
816func SetsockoptIPMreqn(fd, level, opt int, mreq *IPMreqn) (err error) {
817	return setsockopt(fd, level, opt, unsafe.Pointer(mreq), unsafe.Sizeof(*mreq))
818}
819
820// Keyctl Commands (http://man7.org/linux/man-pages/man2/keyctl.2.html)
821
822// KeyctlInt calls keyctl commands in which each argument is an int.
823// These commands are KEYCTL_REVOKE, KEYCTL_CHOWN, KEYCTL_CLEAR, KEYCTL_LINK,
824// KEYCTL_UNLINK, KEYCTL_NEGATE, KEYCTL_SET_REQKEY_KEYRING, KEYCTL_SET_TIMEOUT,
825// KEYCTL_ASSUME_AUTHORITY, KEYCTL_SESSION_TO_PARENT, KEYCTL_REJECT,
826// KEYCTL_INVALIDATE, and KEYCTL_GET_PERSISTENT.
827//sys	KeyctlInt(cmd int, arg2 int, arg3 int, arg4 int, arg5 int) (ret int, err error) = SYS_KEYCTL
828
829// KeyctlBuffer calls keyctl commands in which the third and fourth
830// arguments are a buffer and its length, respectively.
831// These commands are KEYCTL_UPDATE, KEYCTL_READ, and KEYCTL_INSTANTIATE.
832//sys	KeyctlBuffer(cmd int, arg2 int, buf []byte, arg5 int) (ret int, err error) = SYS_KEYCTL
833
834// KeyctlString calls keyctl commands which return a string.
835// These commands are KEYCTL_DESCRIBE and KEYCTL_GET_SECURITY.
836func KeyctlString(cmd int, id int) (string, error) {
837	// We must loop as the string data may change in between the syscalls.
838	// We could allocate a large buffer here to reduce the chance that the
839	// syscall needs to be called twice; however, this is unnecessary as
840	// the performance loss is negligible.
841	var buffer []byte
842	for {
843		// Try to fill the buffer with data
844		length, err := KeyctlBuffer(cmd, id, buffer, 0)
845		if err != nil {
846			return "", err
847		}
848
849		// Check if the data was written
850		if length <= len(buffer) {
851			// Exclude the null terminator
852			return string(buffer[:length-1]), nil
853		}
854
855		// Make a bigger buffer if needed
856		buffer = make([]byte, length)
857	}
858}
859
860// Keyctl commands with special signatures.
861
862// KeyctlGetKeyringID implements the KEYCTL_GET_KEYRING_ID command.
863// See the full documentation at:
864// http://man7.org/linux/man-pages/man3/keyctl_get_keyring_ID.3.html
865func KeyctlGetKeyringID(id int, create bool) (ringid int, err error) {
866	createInt := 0
867	if create {
868		createInt = 1
869	}
870	return KeyctlInt(KEYCTL_GET_KEYRING_ID, id, createInt, 0, 0)
871}
872
873// KeyctlSetperm implements the KEYCTL_SETPERM command. The perm value is the
874// key handle permission mask as described in the "keyctl setperm" section of
875// http://man7.org/linux/man-pages/man1/keyctl.1.html.
876// See the full documentation at:
877// http://man7.org/linux/man-pages/man3/keyctl_setperm.3.html
878func KeyctlSetperm(id int, perm uint32) error {
879	_, err := KeyctlInt(KEYCTL_SETPERM, id, int(perm), 0, 0)
880	return err
881}
882
883//sys	keyctlJoin(cmd int, arg2 string) (ret int, err error) = SYS_KEYCTL
884
885// KeyctlJoinSessionKeyring implements the KEYCTL_JOIN_SESSION_KEYRING command.
886// See the full documentation at:
887// http://man7.org/linux/man-pages/man3/keyctl_join_session_keyring.3.html
888func KeyctlJoinSessionKeyring(name string) (ringid int, err error) {
889	return keyctlJoin(KEYCTL_JOIN_SESSION_KEYRING, name)
890}
891
892//sys	keyctlSearch(cmd int, arg2 int, arg3 string, arg4 string, arg5 int) (ret int, err error) = SYS_KEYCTL
893
894// KeyctlSearch implements the KEYCTL_SEARCH command.
895// See the full documentation at:
896// http://man7.org/linux/man-pages/man3/keyctl_search.3.html
897func KeyctlSearch(ringid int, keyType, description string, destRingid int) (id int, err error) {
898	return keyctlSearch(KEYCTL_SEARCH, ringid, keyType, description, destRingid)
899}
900
901//sys	keyctlIOV(cmd int, arg2 int, payload []Iovec, arg5 int) (err error) = SYS_KEYCTL
902
903// KeyctlInstantiateIOV implements the KEYCTL_INSTANTIATE_IOV command. This
904// command is similar to KEYCTL_INSTANTIATE, except that the payload is a slice
905// of Iovec (each of which represents a buffer) instead of a single buffer.
906// See the full documentation at:
907// http://man7.org/linux/man-pages/man3/keyctl_instantiate_iov.3.html
908func KeyctlInstantiateIOV(id int, payload []Iovec, ringid int) error {
909	return keyctlIOV(KEYCTL_INSTANTIATE_IOV, id, payload, ringid)
910}
911
912//sys	keyctlDH(cmd int, arg2 *KeyctlDHParams, buf []byte) (ret int, err error) = SYS_KEYCTL
913
914// KeyctlDHCompute implements the KEYCTL_DH_COMPUTE command. This command
915// computes a Diffie-Hellman shared secret based on the provide params. The
916// secret is written to the provided buffer and the returned size is the number
917// of bytes written (returning an error if there is insufficient space in the
918// buffer). If a nil buffer is passed in, this function returns the minimum
919// buffer length needed to store the appropriate data. Note that this differs
920// from KEYCTL_READ's behavior which always returns the requested payload size.
921// See the full documentation at:
922// http://man7.org/linux/man-pages/man3/keyctl_dh_compute.3.html
923func KeyctlDHCompute(params *KeyctlDHParams, buffer []byte) (size int, err error) {
924	return keyctlDH(KEYCTL_DH_COMPUTE, params, buffer)
925}
926
927func Recvmsg(fd int, p, oob []byte, flags int) (n, oobn int, recvflags int, from Sockaddr, err error) {
928	var msg Msghdr
929	var rsa RawSockaddrAny
930	msg.Name = (*byte)(unsafe.Pointer(&rsa))
931	msg.Namelen = uint32(SizeofSockaddrAny)
932	var iov Iovec
933	if len(p) > 0 {
934		iov.Base = &p[0]
935		iov.SetLen(len(p))
936	}
937	var dummy byte
938	if len(oob) > 0 {
939		if len(p) == 0 {
940			var sockType int
941			sockType, err = GetsockoptInt(fd, SOL_SOCKET, SO_TYPE)
942			if err != nil {
943				return
944			}
945			// receive at least one normal byte
946			if sockType != SOCK_DGRAM {
947				iov.Base = &dummy
948				iov.SetLen(1)
949			}
950		}
951		msg.Control = &oob[0]
952		msg.SetControllen(len(oob))
953	}
954	msg.Iov = &iov
955	msg.Iovlen = 1
956	if n, err = recvmsg(fd, &msg, flags); err != nil {
957		return
958	}
959	oobn = int(msg.Controllen)
960	recvflags = int(msg.Flags)
961	// source address is only specified if the socket is unconnected
962	if rsa.Addr.Family != AF_UNSPEC {
963		from, err = anyToSockaddr(&rsa)
964	}
965	return
966}
967
968func Sendmsg(fd int, p, oob []byte, to Sockaddr, flags int) (err error) {
969	_, err = SendmsgN(fd, p, oob, to, flags)
970	return
971}
972
973func SendmsgN(fd int, p, oob []byte, to Sockaddr, flags int) (n int, err error) {
974	var ptr unsafe.Pointer
975	var salen _Socklen
976	if to != nil {
977		var err error
978		ptr, salen, err = to.sockaddr()
979		if err != nil {
980			return 0, err
981		}
982	}
983	var msg Msghdr
984	msg.Name = (*byte)(ptr)
985	msg.Namelen = uint32(salen)
986	var iov Iovec
987	if len(p) > 0 {
988		iov.Base = &p[0]
989		iov.SetLen(len(p))
990	}
991	var dummy byte
992	if len(oob) > 0 {
993		if len(p) == 0 {
994			var sockType int
995			sockType, err = GetsockoptInt(fd, SOL_SOCKET, SO_TYPE)
996			if err != nil {
997				return 0, err
998			}
999			// send at least one normal byte
1000			if sockType != SOCK_DGRAM {
1001				iov.Base = &dummy
1002				iov.SetLen(1)
1003			}
1004		}
1005		msg.Control = &oob[0]
1006		msg.SetControllen(len(oob))
1007	}
1008	msg.Iov = &iov
1009	msg.Iovlen = 1
1010	if n, err = sendmsg(fd, &msg, flags); err != nil {
1011		return 0, err
1012	}
1013	if len(oob) > 0 && len(p) == 0 {
1014		n = 0
1015	}
1016	return n, nil
1017}
1018
1019// BindToDevice binds the socket associated with fd to device.
1020func BindToDevice(fd int, device string) (err error) {
1021	return SetsockoptString(fd, SOL_SOCKET, SO_BINDTODEVICE, device)
1022}
1023
1024//sys	ptrace(request int, pid int, addr uintptr, data uintptr) (err error)
1025
1026func ptracePeek(req int, pid int, addr uintptr, out []byte) (count int, err error) {
1027	// The peek requests are machine-size oriented, so we wrap it
1028	// to retrieve arbitrary-length data.
1029
1030	// The ptrace syscall differs from glibc's ptrace.
1031	// Peeks returns the word in *data, not as the return value.
1032
1033	var buf [sizeofPtr]byte
1034
1035	// Leading edge. PEEKTEXT/PEEKDATA don't require aligned
1036	// access (PEEKUSER warns that it might), but if we don't
1037	// align our reads, we might straddle an unmapped page
1038	// boundary and not get the bytes leading up to the page
1039	// boundary.
1040	n := 0
1041	if addr%sizeofPtr != 0 {
1042		err = ptrace(req, pid, addr-addr%sizeofPtr, uintptr(unsafe.Pointer(&buf[0])))
1043		if err != nil {
1044			return 0, err
1045		}
1046		n += copy(out, buf[addr%sizeofPtr:])
1047		out = out[n:]
1048	}
1049
1050	// Remainder.
1051	for len(out) > 0 {
1052		// We use an internal buffer to guarantee alignment.
1053		// It's not documented if this is necessary, but we're paranoid.
1054		err = ptrace(req, pid, addr+uintptr(n), uintptr(unsafe.Pointer(&buf[0])))
1055		if err != nil {
1056			return n, err
1057		}
1058		copied := copy(out, buf[0:])
1059		n += copied
1060		out = out[copied:]
1061	}
1062
1063	return n, nil
1064}
1065
1066func PtracePeekText(pid int, addr uintptr, out []byte) (count int, err error) {
1067	return ptracePeek(PTRACE_PEEKTEXT, pid, addr, out)
1068}
1069
1070func PtracePeekData(pid int, addr uintptr, out []byte) (count int, err error) {
1071	return ptracePeek(PTRACE_PEEKDATA, pid, addr, out)
1072}
1073
1074func PtracePeekUser(pid int, addr uintptr, out []byte) (count int, err error) {
1075	return ptracePeek(PTRACE_PEEKUSR, pid, addr, out)
1076}
1077
1078func ptracePoke(pokeReq int, peekReq int, pid int, addr uintptr, data []byte) (count int, err error) {
1079	// As for ptracePeek, we need to align our accesses to deal
1080	// with the possibility of straddling an invalid page.
1081
1082	// Leading edge.
1083	n := 0
1084	if addr%sizeofPtr != 0 {
1085		var buf [sizeofPtr]byte
1086		err = ptrace(peekReq, pid, addr-addr%sizeofPtr, uintptr(unsafe.Pointer(&buf[0])))
1087		if err != nil {
1088			return 0, err
1089		}
1090		n += copy(buf[addr%sizeofPtr:], data)
1091		word := *((*uintptr)(unsafe.Pointer(&buf[0])))
1092		err = ptrace(pokeReq, pid, addr-addr%sizeofPtr, word)
1093		if err != nil {
1094			return 0, err
1095		}
1096		data = data[n:]
1097	}
1098
1099	// Interior.
1100	for len(data) > sizeofPtr {
1101		word := *((*uintptr)(unsafe.Pointer(&data[0])))
1102		err = ptrace(pokeReq, pid, addr+uintptr(n), word)
1103		if err != nil {
1104			return n, err
1105		}
1106		n += sizeofPtr
1107		data = data[sizeofPtr:]
1108	}
1109
1110	// Trailing edge.
1111	if len(data) > 0 {
1112		var buf [sizeofPtr]byte
1113		err = ptrace(peekReq, pid, addr+uintptr(n), uintptr(unsafe.Pointer(&buf[0])))
1114		if err != nil {
1115			return n, err
1116		}
1117		copy(buf[0:], data)
1118		word := *((*uintptr)(unsafe.Pointer(&buf[0])))
1119		err = ptrace(pokeReq, pid, addr+uintptr(n), word)
1120		if err != nil {
1121			return n, err
1122		}
1123		n += len(data)
1124	}
1125
1126	return n, nil
1127}
1128
1129func PtracePokeText(pid int, addr uintptr, data []byte) (count int, err error) {
1130	return ptracePoke(PTRACE_POKETEXT, PTRACE_PEEKTEXT, pid, addr, data)
1131}
1132
1133func PtracePokeData(pid int, addr uintptr, data []byte) (count int, err error) {
1134	return ptracePoke(PTRACE_POKEDATA, PTRACE_PEEKDATA, pid, addr, data)
1135}
1136
1137func PtracePokeUser(pid int, addr uintptr, data []byte) (count int, err error) {
1138	return ptracePoke(PTRACE_POKEUSR, PTRACE_PEEKUSR, pid, addr, data)
1139}
1140
1141func PtraceGetRegs(pid int, regsout *PtraceRegs) (err error) {
1142	return ptrace(PTRACE_GETREGS, pid, 0, uintptr(unsafe.Pointer(regsout)))
1143}
1144
1145func PtraceSetRegs(pid int, regs *PtraceRegs) (err error) {
1146	return ptrace(PTRACE_SETREGS, pid, 0, uintptr(unsafe.Pointer(regs)))
1147}
1148
1149func PtraceSetOptions(pid int, options int) (err error) {
1150	return ptrace(PTRACE_SETOPTIONS, pid, 0, uintptr(options))
1151}
1152
1153func PtraceGetEventMsg(pid int) (msg uint, err error) {
1154	var data _C_long
1155	err = ptrace(PTRACE_GETEVENTMSG, pid, 0, uintptr(unsafe.Pointer(&data)))
1156	msg = uint(data)
1157	return
1158}
1159
1160func PtraceCont(pid int, signal int) (err error) {
1161	return ptrace(PTRACE_CONT, pid, 0, uintptr(signal))
1162}
1163
1164func PtraceSyscall(pid int, signal int) (err error) {
1165	return ptrace(PTRACE_SYSCALL, pid, 0, uintptr(signal))
1166}
1167
1168func PtraceSingleStep(pid int) (err error) { return ptrace(PTRACE_SINGLESTEP, pid, 0, 0) }
1169
1170func PtraceAttach(pid int) (err error) { return ptrace(PTRACE_ATTACH, pid, 0, 0) }
1171
1172func PtraceDetach(pid int) (err error) { return ptrace(PTRACE_DETACH, pid, 0, 0) }
1173
1174//sys	reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error)
1175
1176func Reboot(cmd int) (err error) {
1177	return reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, cmd, "")
1178}
1179
1180func ReadDirent(fd int, buf []byte) (n int, err error) {
1181	return Getdents(fd, buf)
1182}
1183
1184//sys	mount(source string, target string, fstype string, flags uintptr, data *byte) (err error)
1185
1186func Mount(source string, target string, fstype string, flags uintptr, data string) (err error) {
1187	// Certain file systems get rather angry and EINVAL if you give
1188	// them an empty string of data, rather than NULL.
1189	if data == "" {
1190		return mount(source, target, fstype, flags, nil)
1191	}
1192	datap, err := BytePtrFromString(data)
1193	if err != nil {
1194		return err
1195	}
1196	return mount(source, target, fstype, flags, datap)
1197}
1198
1199// Sendto
1200// Recvfrom
1201// Socketpair
1202
1203/*
1204 * Direct access
1205 */
1206//sys	Acct(path string) (err error)
1207//sys	AddKey(keyType string, description string, payload []byte, ringid int) (id int, err error)
1208//sys	Adjtimex(buf *Timex) (state int, err error)
1209//sys	Chdir(path string) (err error)
1210//sys	Chroot(path string) (err error)
1211//sys	ClockGettime(clockid int32, time *Timespec) (err error)
1212//sys	Close(fd int) (err error)
1213//sys	CopyFileRange(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error)
1214//sys	Dup(oldfd int) (fd int, err error)
1215//sys	Dup3(oldfd int, newfd int, flags int) (err error)
1216//sysnb	EpollCreate1(flag int) (fd int, err error)
1217//sysnb	EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error)
1218//sys	Eventfd(initval uint, flags int) (fd int, err error) = SYS_EVENTFD2
1219//sys	Exit(code int) = SYS_EXIT_GROUP
1220//sys	Fallocate(fd int, mode uint32, off int64, len int64) (err error)
1221//sys	Fchdir(fd int) (err error)
1222//sys	Fchmod(fd int, mode uint32) (err error)
1223//sys	Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error)
1224//sys	fcntl(fd int, cmd int, arg int) (val int, err error)
1225//sys	Fdatasync(fd int) (err error)
1226//sys	Flock(fd int, how int) (err error)
1227//sys	Fsync(fd int) (err error)
1228//sys	Getdents(fd int, buf []byte) (n int, err error) = SYS_GETDENTS64
1229//sysnb	Getpgid(pid int) (pgid int, err error)
1230
1231func Getpgrp() (pid int) {
1232	pid, _ = Getpgid(0)
1233	return
1234}
1235
1236//sysnb	Getpid() (pid int)
1237//sysnb	Getppid() (ppid int)
1238//sys	Getpriority(which int, who int) (prio int, err error)
1239//sys	Getrandom(buf []byte, flags int) (n int, err error)
1240//sysnb	Getrusage(who int, rusage *Rusage) (err error)
1241//sysnb	Getsid(pid int) (sid int, err error)
1242//sysnb	Gettid() (tid int)
1243//sys	Getxattr(path string, attr string, dest []byte) (sz int, err error)
1244//sys	InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error)
1245//sysnb	InotifyInit1(flags int) (fd int, err error)
1246//sysnb	InotifyRmWatch(fd int, watchdesc uint32) (success int, err error)
1247//sysnb	Kill(pid int, sig syscall.Signal) (err error)
1248//sys	Klogctl(typ int, buf []byte) (n int, err error) = SYS_SYSLOG
1249//sys	Lgetxattr(path string, attr string, dest []byte) (sz int, err error)
1250//sys	Listxattr(path string, dest []byte) (sz int, err error)
1251//sys	Llistxattr(path string, dest []byte) (sz int, err error)
1252//sys	Lremovexattr(path string, attr string) (err error)
1253//sys	Lsetxattr(path string, attr string, data []byte, flags int) (err error)
1254//sys	Mkdirat(dirfd int, path string, mode uint32) (err error)
1255//sys	Mknodat(dirfd int, path string, mode uint32, dev int) (err error)
1256//sys	Nanosleep(time *Timespec, leftover *Timespec) (err error)
1257//sys	PerfEventOpen(attr *PerfEventAttr, pid int, cpu int, groupFd int, flags int) (fd int, err error)
1258//sys	PivotRoot(newroot string, putold string) (err error) = SYS_PIVOT_ROOT
1259//sysnb prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) = SYS_PRLIMIT64
1260//sys   Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error)
1261//sys	Pselect(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timespec, sigmask *Sigset_t) (n int, err error) = SYS_PSELECT6
1262//sys	read(fd int, p []byte) (n int, err error)
1263//sys	Removexattr(path string, attr string) (err error)
1264//sys	Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error)
1265//sys	RequestKey(keyType string, description string, callback string, destRingid int) (id int, err error)
1266//sys	Setdomainname(p []byte) (err error)
1267//sys	Sethostname(p []byte) (err error)
1268//sysnb	Setpgid(pid int, pgid int) (err error)
1269//sysnb	Setsid() (pid int, err error)
1270//sysnb	Settimeofday(tv *Timeval) (err error)
1271//sys	Setns(fd int, nstype int) (err error)
1272
1273// issue 1435.
1274// On linux Setuid and Setgid only affects the current thread, not the process.
1275// This does not match what most callers expect so we must return an error
1276// here rather than letting the caller think that the call succeeded.
1277
1278func Setuid(uid int) (err error) {
1279	return EOPNOTSUPP
1280}
1281
1282func Setgid(uid int) (err error) {
1283	return EOPNOTSUPP
1284}
1285
1286//sys	Setpriority(which int, who int, prio int) (err error)
1287//sys	Setxattr(path string, attr string, data []byte, flags int) (err error)
1288//sys	Statx(dirfd int, path string, flags int, mask int, stat *Statx_t) (err error)
1289//sys	Sync()
1290//sys	Syncfs(fd int) (err error)
1291//sysnb	Sysinfo(info *Sysinfo_t) (err error)
1292//sys	Tee(rfd int, wfd int, len int, flags int) (n int64, err error)
1293//sysnb	Tgkill(tgid int, tid int, sig syscall.Signal) (err error)
1294//sysnb	Times(tms *Tms) (ticks uintptr, err error)
1295//sysnb	Umask(mask int) (oldmask int)
1296//sysnb	Uname(buf *Utsname) (err error)
1297//sys	Unmount(target string, flags int) (err error) = SYS_UMOUNT2
1298//sys	Unshare(flags int) (err error)
1299//sys	write(fd int, p []byte) (n int, err error)
1300//sys	exitThread(code int) (err error) = SYS_EXIT
1301//sys	readlen(fd int, p *byte, np int) (n int, err error) = SYS_READ
1302//sys	writelen(fd int, p *byte, np int) (n int, err error) = SYS_WRITE
1303
1304// mmap varies by architecture; see syscall_linux_*.go.
1305//sys	munmap(addr uintptr, length uintptr) (err error)
1306
1307var mapper = &mmapper{
1308	active: make(map[*byte][]byte),
1309	mmap:   mmap,
1310	munmap: munmap,
1311}
1312
1313func Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error) {
1314	return mapper.Mmap(fd, offset, length, prot, flags)
1315}
1316
1317func Munmap(b []byte) (err error) {
1318	return mapper.Munmap(b)
1319}
1320
1321//sys	Madvise(b []byte, advice int) (err error)
1322//sys	Mprotect(b []byte, prot int) (err error)
1323//sys	Mlock(b []byte) (err error)
1324//sys	Mlockall(flags int) (err error)
1325//sys	Msync(b []byte, flags int) (err error)
1326//sys	Munlock(b []byte) (err error)
1327//sys	Munlockall() (err error)
1328
1329// Vmsplice splices user pages from a slice of Iovecs into a pipe specified by fd,
1330// using the specified flags.
1331func Vmsplice(fd int, iovs []Iovec, flags int) (int, error) {
1332	n, _, errno := Syscall6(
1333		SYS_VMSPLICE,
1334		uintptr(fd),
1335		uintptr(unsafe.Pointer(&iovs[0])),
1336		uintptr(len(iovs)),
1337		uintptr(flags),
1338		0,
1339		0,
1340	)
1341	if errno != 0 {
1342		return 0, syscall.Errno(errno)
1343	}
1344
1345	return int(n), nil
1346}
1347
1348//sys	faccessat(dirfd int, path string, mode uint32) (err error)
1349
1350func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) {
1351	if flags & ^(AT_SYMLINK_NOFOLLOW|AT_EACCESS) != 0 {
1352		return EINVAL
1353	} else if flags&(AT_SYMLINK_NOFOLLOW|AT_EACCESS) != 0 {
1354		return EOPNOTSUPP
1355	}
1356	return faccessat(dirfd, path, mode)
1357}
1358
1359/*
1360 * Unimplemented
1361 */
1362// AfsSyscall
1363// Alarm
1364// ArchPrctl
1365// Brk
1366// Capget
1367// Capset
1368// ClockGetres
1369// ClockNanosleep
1370// ClockSettime
1371// Clone
1372// CreateModule
1373// DeleteModule
1374// EpollCtlOld
1375// EpollPwait
1376// EpollWaitOld
1377// Execve
1378// Fgetxattr
1379// Flistxattr
1380// Fork
1381// Fremovexattr
1382// Fsetxattr
1383// Futex
1384// GetKernelSyms
1385// GetMempolicy
1386// GetRobustList
1387// GetThreadArea
1388// Getitimer
1389// Getpmsg
1390// IoCancel
1391// IoDestroy
1392// IoGetevents
1393// IoSetup
1394// IoSubmit
1395// IoprioGet
1396// IoprioSet
1397// KexecLoad
1398// LookupDcookie
1399// Mbind
1400// MigratePages
1401// Mincore
1402// ModifyLdt
1403// Mount
1404// MovePages
1405// MqGetsetattr
1406// MqNotify
1407// MqOpen
1408// MqTimedreceive
1409// MqTimedsend
1410// MqUnlink
1411// Mremap
1412// Msgctl
1413// Msgget
1414// Msgrcv
1415// Msgsnd
1416// Nfsservctl
1417// Personality
1418// Pselect6
1419// Ptrace
1420// Putpmsg
1421// QueryModule
1422// Quotactl
1423// Readahead
1424// Readv
1425// RemapFilePages
1426// RestartSyscall
1427// RtSigaction
1428// RtSigpending
1429// RtSigprocmask
1430// RtSigqueueinfo
1431// RtSigreturn
1432// RtSigsuspend
1433// RtSigtimedwait
1434// SchedGetPriorityMax
1435// SchedGetPriorityMin
1436// SchedGetparam
1437// SchedGetscheduler
1438// SchedRrGetInterval
1439// SchedSetparam
1440// SchedYield
1441// Security
1442// Semctl
1443// Semget
1444// Semop
1445// Semtimedop
1446// SetMempolicy
1447// SetRobustList
1448// SetThreadArea
1449// SetTidAddress
1450// Shmat
1451// Shmctl
1452// Shmdt
1453// Shmget
1454// Sigaltstack
1455// Signalfd
1456// Swapoff
1457// Swapon
1458// Sysfs
1459// TimerCreate
1460// TimerDelete
1461// TimerGetoverrun
1462// TimerGettime
1463// TimerSettime
1464// Timerfd
1465// Tkill (obsolete)
1466// Tuxcall
1467// Umount2
1468// Uselib
1469// Utimensat
1470// Vfork
1471// Vhangup
1472// Vserver
1473// Waitid
1474// _Sysctl
1475