// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

//go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris
// +build aix darwin dragonfly freebsd linux netbsd openbsd solaris

package unix

import (
	
	
	
	
	
)

var (
	Stdin  = 0
	Stdout = 1
	Stderr = 2
)

// Do the interface allocations only once for common
// Errno values.
var (
	errEAGAIN error = syscall.EAGAIN
	errEINVAL error = syscall.EINVAL
	errENOENT error = syscall.ENOENT
)

var (
	signalNameMapOnce sync.Once
	signalNameMap     map[string]syscall.Signal
)

// errnoErr returns common boxed Errno values, to prevent
// allocations at runtime.
func errnoErr( syscall.Errno) error {
	switch  {
	case 0:
		return nil
	case EAGAIN:
		return errEAGAIN
	case EINVAL:
		return errEINVAL
	case ENOENT:
		return errENOENT
	}
	return 
}

// ErrnoName returns the error name for error number e.
func ( syscall.Errno) string {
	 := sort.Search(len(errorList), func( int) bool {
		return errorList[].num >= 
	})
	if  < len(errorList) && errorList[].num ==  {
		return errorList[].name
	}
	return ""
}

// SignalName returns the signal name for signal number s.
func ( syscall.Signal) string {
	 := sort.Search(len(signalList), func( int) bool {
		return signalList[].num >= 
	})
	if  < len(signalList) && signalList[].num ==  {
		return signalList[].name
	}
	return ""
}

// SignalNum returns the syscall.Signal for signal named s,
// or 0 if a signal with such name is not found.
// The signal name should start with "SIG".
func ( string) syscall.Signal {
	signalNameMapOnce.Do(func() {
		signalNameMap = make(map[string]syscall.Signal, len(signalList))
		for ,  := range signalList {
			signalNameMap[.name] = .num
		}
	})
	return signalNameMap[]
}

// clen returns the index of the first NULL byte in n or len(n) if n contains no NULL byte.
func clen( []byte) int {
	 := bytes.IndexByte(, 0)
	if  == -1 {
		 = len()
	}
	return 
}

// Mmap manager, for use by operating system-specific implementations.

type mmapper struct {
	sync.Mutex
	active map[*byte][]byte // active mappings; key is last byte in mapping
	mmap   func(addr, length uintptr, prot, flags, fd int, offset int64) (uintptr, error)
	munmap func(addr uintptr, length uintptr) error
}

func ( *mmapper) ( int,  int64,  int,  int,  int) ( []byte,  error) {
	if  <= 0 {
		return nil, EINVAL
	}

	// Map the requested memory.
	,  := .mmap(0, uintptr(), , , , )
	if  != nil {
		return nil, 
	}

	// Use unsafe to convert addr into a []byte.
	 := unsafe.Slice((*byte)(unsafe.Pointer()), )

	// Register mapping in m and return it.
	 := &[cap()-1]
	.Lock()
	defer .Unlock()
	.active[] = 
	return , nil
}

func ( *mmapper) ( []byte) ( error) {
	if len() == 0 || len() != cap() {
		return EINVAL
	}

	// Find the base of the mapping.
	 := &[cap()-1]
	.Lock()
	defer .Unlock()
	 := .active[]
	if  == nil || &[0] != &[0] {
		return EINVAL
	}

	// Unmap the memory and update m.
	if  := .munmap(uintptr(unsafe.Pointer(&[0])), uintptr(len()));  != nil {
		return 
	}
	delete(.active, )
	return nil
}

func ( int,  int64,  int,  int,  int) ( []byte,  error) {
	return mapper.Mmap(, , , , )
}

func ( []byte) ( error) {
	return mapper.Munmap()
}

func ( int,  []byte) ( int,  error) {
	,  = read(, )
	if raceenabled {
		if  > 0 {
			raceWriteRange(unsafe.Pointer(&[0]), )
		}
		if  == nil {
			raceAcquire(unsafe.Pointer(&ioSync))
		}
	}
	return
}

func ( int,  []byte) ( int,  error) {
	if raceenabled {
		raceReleaseMerge(unsafe.Pointer(&ioSync))
	}
	,  = write(, )
	if raceenabled &&  > 0 {
		raceReadRange(unsafe.Pointer(&[0]), )
	}
	return
}

func ( int,  []byte,  int64) ( int,  error) {
	,  = pread(, , )
	if raceenabled {
		if  > 0 {
			raceWriteRange(unsafe.Pointer(&[0]), )
		}
		if  == nil {
			raceAcquire(unsafe.Pointer(&ioSync))
		}
	}
	return
}

func ( int,  []byte,  int64) ( int,  error) {
	if raceenabled {
		raceReleaseMerge(unsafe.Pointer(&ioSync))
	}
	,  = pwrite(, , )
	if raceenabled &&  > 0 {
		raceReadRange(unsafe.Pointer(&[0]), )
	}
	return
}

// For testing: clients can set this flag to force
// creation of IPv6 sockets to return EAFNOSUPPORT.
var SocketDisableIPv6 bool

// Sockaddr represents a socket address.
type Sockaddr interface {
	sockaddr() (ptr unsafe.Pointer, len _Socklen, err error) // lowercase; only we can define Sockaddrs
}

// SockaddrInet4 implements the Sockaddr interface for AF_INET type sockets.
type SockaddrInet4 struct {
	Port int
	Addr [4]byte
	raw  RawSockaddrInet4
}

// SockaddrInet6 implements the Sockaddr interface for AF_INET6 type sockets.
type SockaddrInet6 struct {
	Port   int
	ZoneId uint32
	Addr   [16]byte
	raw    RawSockaddrInet6
}

// SockaddrUnix implements the Sockaddr interface for AF_UNIX type sockets.
type SockaddrUnix struct {
	Name string
	raw  RawSockaddrUnix
}

func ( int,  Sockaddr) ( error) {
	, ,  := .sockaddr()
	if  != nil {
		return 
	}
	return bind(, , )
}

func ( int,  Sockaddr) ( error) {
	, ,  := .sockaddr()
	if  != nil {
		return 
	}
	return connect(, , )
}

func ( int) ( Sockaddr,  error) {
	var  RawSockaddrAny
	var  _Socklen = SizeofSockaddrAny
	if  = getpeername(, &, &);  != nil {
		return
	}
	return anyToSockaddr(, &)
}

func (, ,  int) ( byte,  error) {
	var  byte
	 := _Socklen(1)
	 = getsockopt(, , , unsafe.Pointer(&), &)
	return , 
}

func (, ,  int) ( int,  error) {
	var  int32
	 := _Socklen(4)
	 = getsockopt(, , , unsafe.Pointer(&), &)
	return int(), 
}

func (, ,  int) ( [4]byte,  error) {
	 := _Socklen(4)
	 = getsockopt(, , , unsafe.Pointer(&[0]), &)
	return , 
}

func (, ,  int) (*IPMreq, error) {
	var  IPMreq
	 := _Socklen(SizeofIPMreq)
	 := getsockopt(, , , unsafe.Pointer(&), &)
	return &, 
}

func (, ,  int) (*IPv6Mreq, error) {
	var  IPv6Mreq
	 := _Socklen(SizeofIPv6Mreq)
	 := getsockopt(, , , unsafe.Pointer(&), &)
	return &, 
}

func (, ,  int) (*IPv6MTUInfo, error) {
	var  IPv6MTUInfo
	 := _Socklen(SizeofIPv6MTUInfo)
	 := getsockopt(, , , unsafe.Pointer(&), &)
	return &, 
}

func (, ,  int) (*ICMPv6Filter, error) {
	var  ICMPv6Filter
	 := _Socklen(SizeofICMPv6Filter)
	 := getsockopt(, , , unsafe.Pointer(&), &)
	return &, 
}

func (, ,  int) (*Linger, error) {
	var  Linger
	 := _Socklen(SizeofLinger)
	 := getsockopt(, , , unsafe.Pointer(&), &)
	return &, 
}

func (, ,  int) (*Timeval, error) {
	var  Timeval
	 := _Socklen(unsafe.Sizeof())
	 := getsockopt(, , , unsafe.Pointer(&), &)
	return &, 
}

func (, ,  int) ( uint64,  error) {
	var  uint64
	 := _Socklen(8)
	 = getsockopt(, , , unsafe.Pointer(&), &)
	return , 
}

func ( int,  []byte,  int) ( int,  Sockaddr,  error) {
	var  RawSockaddrAny
	var  _Socklen = SizeofSockaddrAny
	if ,  = recvfrom(, , , &, &);  != nil {
		return
	}
	if .Addr.Family != AF_UNSPEC {
		,  = anyToSockaddr(, &)
	}
	return
}

// Recvmsg receives a message from a socket using the recvmsg system call. The
// received non-control data will be written to p, and any "out of band"
// control data will be written to oob. The flags are passed to recvmsg.
//
// The results are:
//   - n is the number of non-control data bytes read into p
//   - oobn is the number of control data bytes read into oob; this may be interpreted using [ParseSocketControlMessage]
//   - recvflags is flags returned by recvmsg
//   - from is the address of the sender
//
// If the underlying socket type is not SOCK_DGRAM, a received message
// containing oob data and a single '\0' of non-control data is treated as if
// the message contained only control data, i.e. n will be zero on return.
func ( int, ,  []byte,  int) (,  int,  int,  Sockaddr,  error) {
	var  [1]Iovec
	if len() > 0 {
		[0].Base = &[0]
		[0].SetLen(len())
	}
	var  RawSockaddrAny
	, , ,  = recvmsgRaw(, [:], , , &)
	// source address is only specified if the socket is unconnected
	if .Addr.Family != AF_UNSPEC {
		,  = anyToSockaddr(, &)
	}
	return
}

// RecvmsgBuffers receives a message from a socket using the recvmsg system
// call. This function is equivalent to Recvmsg, but non-control data read is
// scattered into the buffers slices.
func ( int,  [][]byte,  []byte,  int) (,  int,  int,  Sockaddr,  error) {
	 := make([]Iovec, len())
	for  := range  {
		if len([]) > 0 {
			[].Base = &[][0]
			[].SetLen(len([]))
		} else {
			[].Base = (*byte)(unsafe.Pointer(&_zero))
		}
	}
	var  RawSockaddrAny
	, , ,  = recvmsgRaw(, , , , &)
	if  == nil && .Addr.Family != AF_UNSPEC {
		,  = anyToSockaddr(, &)
	}
	return
}

// Sendmsg sends a message on a socket to an address using the sendmsg system
// call. This function is equivalent to SendmsgN, but does not return the
// number of bytes actually sent.
func ( int, ,  []byte,  Sockaddr,  int) ( error) {
	_,  = SendmsgN(, , , , )
	return
}

// SendmsgN sends a message on a socket to an address using the sendmsg system
// call. p contains the non-control data to send, and oob contains the "out of
// band" control data. The flags are passed to sendmsg. The number of
// non-control bytes actually written to the socket is returned.
//
// Some socket types do not support sending control data without accompanying
// non-control data. If p is empty, and oob contains control data, and the
// underlying socket type is not SOCK_DGRAM, p will be treated as containing a
// single '\0' and the return value will indicate zero bytes sent.
//
// The Go function Recvmsg, if called with an empty p and a non-empty oob,
// will read and ignore this additional '\0'.  If the message is received by
// code that does not use Recvmsg, or that does not use Go at all, that code
// will need to be written to expect and ignore the additional '\0'.
//
// If you need to send non-empty oob with p actually empty, and if the
// underlying socket type supports it, you can do so via a raw system call as
// follows:
//
//	msg := &unix.Msghdr{
//	    Control: &oob[0],
//	}
//	msg.SetControllen(len(oob))
//	n, _, errno := unix.Syscall(unix.SYS_SENDMSG, uintptr(fd), uintptr(unsafe.Pointer(msg)), flags)
func ( int, ,  []byte,  Sockaddr,  int) ( int,  error) {
	var  [1]Iovec
	if len() > 0 {
		[0].Base = &[0]
		[0].SetLen(len())
	}
	var  unsafe.Pointer
	var  _Socklen
	if  != nil {
		, ,  = .sockaddr()
		if  != nil {
			return 0, 
		}
	}
	return sendmsgN(, [:], , , , )
}

// SendmsgBuffers sends a message on a socket to an address using the sendmsg
// system call. This function is equivalent to SendmsgN, but the non-control
// data is gathered from buffers.
func ( int,  [][]byte,  []byte,  Sockaddr,  int) ( int,  error) {
	 := make([]Iovec, len())
	for  := range  {
		if len([]) > 0 {
			[].Base = &[][0]
			[].SetLen(len([]))
		} else {
			[].Base = (*byte)(unsafe.Pointer(&_zero))
		}
	}
	var  unsafe.Pointer
	var  _Socklen
	if  != nil {
		, ,  = .sockaddr()
		if  != nil {
			return 0, 
		}
	}
	return sendmsgN(, , , , , )
}

func ( int,  []byte,  int) ( error) {
	return sendto(, , , nil, 0)
}

func ( int,  []byte,  int,  Sockaddr) ( error) {
	var  unsafe.Pointer
	var  _Socklen
	if  != nil {
		, ,  = .sockaddr()
		if  != nil {
			return 
		}
	}
	return sendto(, , , , )
}

func (, ,  int,  byte) ( error) {
	return setsockopt(, , , unsafe.Pointer(&), 1)
}

func (, ,  int,  int) ( error) {
	var  = int32()
	return setsockopt(, , , unsafe.Pointer(&), 4)
}

func (, ,  int,  [4]byte) ( error) {
	return setsockopt(, , , unsafe.Pointer(&[0]), 4)
}

func (, ,  int,  *IPMreq) ( error) {
	return setsockopt(, , , unsafe.Pointer(), SizeofIPMreq)
}

func (, ,  int,  *IPv6Mreq) ( error) {
	return setsockopt(, , , unsafe.Pointer(), SizeofIPv6Mreq)
}

func (, ,  int,  *ICMPv6Filter) error {
	return setsockopt(, , , unsafe.Pointer(), SizeofICMPv6Filter)
}

func (, ,  int,  *Linger) ( error) {
	return setsockopt(, , , unsafe.Pointer(), SizeofLinger)
}

func (, ,  int,  string) ( error) {
	var  unsafe.Pointer
	if len() > 0 {
		 = unsafe.Pointer(&[]byte()[0])
	}
	return setsockopt(, , , , uintptr(len()))
}

func (, ,  int,  *Timeval) ( error) {
	return setsockopt(, , , unsafe.Pointer(), unsafe.Sizeof(*))
}

func (, ,  int,  uint64) ( error) {
	return setsockopt(, , , unsafe.Pointer(&), 8)
}

func (, ,  int) ( int,  error) {
	if  == AF_INET6 && SocketDisableIPv6 {
		return -1, EAFNOSUPPORT
	}
	,  = socket(, , )
	return
}

func (, ,  int) ( [2]int,  error) {
	var  [2]int32
	 = socketpair(, , , &)
	if  == nil {
		[0] = int([0])
		[1] = int([1])
	}
	return
}

var ioSync int64

func ( int) { fcntl(, F_SETFD, FD_CLOEXEC) }

func ( int,  bool) ( error) {
	,  := fcntl(, F_GETFL, 0)
	if  != nil {
		return 
	}
	if (&O_NONBLOCK != 0) ==  {
		return nil
	}
	if  {
		 |= O_NONBLOCK
	} else {
		 &= ^O_NONBLOCK
	}
	_,  = fcntl(, F_SETFL, )
	return 
}

// Exec calls execve(2), which replaces the calling executable in the process
// tree. argv0 should be the full path to an executable ("/bin/ls") and the
// executable name should also be the first argument in argv (["ls", "-l"]).
// envv are the environment variables that should be passed to the new
// process (["USER=go", "PWD=/tmp"]).
func ( string,  []string,  []string) error {
	return syscall.Exec(, , )
}

// Lutimes sets the access and modification times tv on path. If path refers to
// a symlink, it is not dereferenced and the timestamps are set on the symlink.
// If tv is nil, the access and modification times are set to the current time.
// Otherwise tv must contain exactly 2 elements, with access time as the first
// element and modification time as the second element.
func ( string,  []Timeval) error {
	if  == nil {
		return UtimesNanoAt(AT_FDCWD, , nil, AT_SYMLINK_NOFOLLOW)
	}
	if len() != 2 {
		return EINVAL
	}
	 := []Timespec{
		NsecToTimespec(TimevalToNsec([0])),
		NsecToTimespec(TimevalToNsec([1])),
	}
	return UtimesNanoAt(AT_FDCWD, , , AT_SYMLINK_NOFOLLOW)
}

// emptyIovecs reports whether there are no bytes in the slice of Iovec.
func emptyIovecs( []Iovec) bool {
	for  := range  {
		if [].Len > 0 {
			return false
		}
	}
	return true
}

// Setrlimit sets a resource limit.
func ( int,  *Rlimit) error {
	// Just call the syscall version, because as of Go 1.21
	// it will affect starting a new process.
	return syscall.Setrlimit(, (*syscall.Rlimit)())
}