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