Source file src/syscall/syscall_windows.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  // Windows system calls.
     6  
     7  package syscall
     8  
     9  import (
    10  	errorspkg "errors"
    11  	"internal/bytealg"
    12  	"internal/itoa"
    13  	"internal/oserror"
    14  	"internal/race"
    15  	"internal/unsafeheader"
    16  	"runtime"
    17  	"sync"
    18  	"unicode/utf16"
    19  	"unsafe"
    20  )
    21  
    22  type Handle uintptr
    23  
    24  const InvalidHandle = ^Handle(0)
    25  
    26  // StringToUTF16 returns the UTF-16 encoding of the UTF-8 string s,
    27  // with a terminating NUL added. If s contains a NUL byte this
    28  // function panics instead of returning an error.
    29  //
    30  // Deprecated: Use UTF16FromString instead.
    31  func StringToUTF16(s string) []uint16 {
    32  	a, err := UTF16FromString(s)
    33  	if err != nil {
    34  		panic("syscall: string with NUL passed to StringToUTF16")
    35  	}
    36  	return a
    37  }
    38  
    39  // UTF16FromString returns the UTF-16 encoding of the UTF-8 string
    40  // s, with a terminating NUL added. If s contains a NUL byte at any
    41  // location, it returns (nil, EINVAL).
    42  func UTF16FromString(s string) ([]uint16, error) {
    43  	if bytealg.IndexByteString(s, 0) != -1 {
    44  		return nil, EINVAL
    45  	}
    46  	return utf16.Encode([]rune(s + "\x00")), nil
    47  }
    48  
    49  // UTF16ToString returns the UTF-8 encoding of the UTF-16 sequence s,
    50  // with a terminating NUL removed.
    51  func UTF16ToString(s []uint16) string {
    52  	for i, v := range s {
    53  		if v == 0 {
    54  			s = s[0:i]
    55  			break
    56  		}
    57  	}
    58  	return string(utf16.Decode(s))
    59  }
    60  
    61  // utf16PtrToString is like UTF16ToString, but takes *uint16
    62  // as a parameter instead of []uint16.
    63  func utf16PtrToString(p *uint16) string {
    64  	if p == nil {
    65  		return ""
    66  	}
    67  	// Find NUL terminator.
    68  	end := unsafe.Pointer(p)
    69  	n := 0
    70  	for *(*uint16)(end) != 0 {
    71  		end = unsafe.Pointer(uintptr(end) + unsafe.Sizeof(*p))
    72  		n++
    73  	}
    74  	// Turn *uint16 into []uint16.
    75  	var s []uint16
    76  	hdr := (*unsafeheader.Slice)(unsafe.Pointer(&s))
    77  	hdr.Data = unsafe.Pointer(p)
    78  	hdr.Cap = n
    79  	hdr.Len = n
    80  	// Decode []uint16 into string.
    81  	return string(utf16.Decode(s))
    82  }
    83  
    84  // StringToUTF16Ptr returns pointer to the UTF-16 encoding of
    85  // the UTF-8 string s, with a terminating NUL added. If s
    86  // contains a NUL byte this function panics instead of
    87  // returning an error.
    88  //
    89  // Deprecated: Use UTF16PtrFromString instead.
    90  func StringToUTF16Ptr(s string) *uint16 { return &StringToUTF16(s)[0] }
    91  
    92  // UTF16PtrFromString returns pointer to the UTF-16 encoding of
    93  // the UTF-8 string s, with a terminating NUL added. If s
    94  // contains a NUL byte at any location, it returns (nil, EINVAL).
    95  func UTF16PtrFromString(s string) (*uint16, error) {
    96  	a, err := UTF16FromString(s)
    97  	if err != nil {
    98  		return nil, err
    99  	}
   100  	return &a[0], nil
   101  }
   102  
   103  // Errno is the Windows error number.
   104  //
   105  // Errno values can be tested against error values from the os package
   106  // using errors.Is. For example:
   107  //
   108  //	_, _, err := syscall.Syscall(...)
   109  //	if errors.Is(err, fs.ErrNotExist) ...
   110  type Errno uintptr
   111  
   112  func langid(pri, sub uint16) uint32 { return uint32(sub)<<10 | uint32(pri) }
   113  
   114  // FormatMessage is deprecated (msgsrc should be uintptr, not uint32, but can
   115  // not be changed due to the Go 1 compatibility guarantee).
   116  //
   117  // Deprecated: Use FormatMessage from golang.org/x/sys/windows instead.
   118  func FormatMessage(flags uint32, msgsrc uint32, msgid uint32, langid uint32, buf []uint16, args *byte) (n uint32, err error) {
   119  	return formatMessage(flags, uintptr(msgsrc), msgid, langid, buf, args)
   120  }
   121  
   122  func (e Errno) Error() string {
   123  	// deal with special go errors
   124  	idx := int(e - APPLICATION_ERROR)
   125  	if 0 <= idx && idx < len(errors) {
   126  		return errors[idx]
   127  	}
   128  	// ask windows for the remaining errors
   129  	var flags uint32 = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY | FORMAT_MESSAGE_IGNORE_INSERTS
   130  	b := make([]uint16, 300)
   131  	n, err := formatMessage(flags, 0, uint32(e), langid(LANG_ENGLISH, SUBLANG_ENGLISH_US), b, nil)
   132  	if err != nil {
   133  		n, err = formatMessage(flags, 0, uint32(e), 0, b, nil)
   134  		if err != nil {
   135  			return "winapi error #" + itoa.Itoa(int(e))
   136  		}
   137  	}
   138  	// trim terminating \r and \n
   139  	for ; n > 0 && (b[n-1] == '\n' || b[n-1] == '\r'); n-- {
   140  	}
   141  	return string(utf16.Decode(b[:n]))
   142  }
   143  
   144  const _ERROR_BAD_NETPATH = Errno(53)
   145  
   146  func (e Errno) Is(target error) bool {
   147  	switch target {
   148  	case oserror.ErrPermission:
   149  		return e == ERROR_ACCESS_DENIED
   150  	case oserror.ErrExist:
   151  		return e == ERROR_ALREADY_EXISTS ||
   152  			e == ERROR_DIR_NOT_EMPTY ||
   153  			e == ERROR_FILE_EXISTS
   154  	case oserror.ErrNotExist:
   155  		return e == ERROR_FILE_NOT_FOUND ||
   156  			e == _ERROR_BAD_NETPATH ||
   157  			e == ERROR_PATH_NOT_FOUND
   158  	}
   159  	return false
   160  }
   161  
   162  func (e Errno) Temporary() bool {
   163  	return e == EINTR || e == EMFILE || e.Timeout()
   164  }
   165  
   166  func (e Errno) Timeout() bool {
   167  	return e == EAGAIN || e == EWOULDBLOCK || e == ETIMEDOUT
   168  }
   169  
   170  // Implemented in runtime/syscall_windows.go.
   171  func compileCallback(fn any, cleanstack bool) uintptr
   172  
   173  // NewCallback converts a Go function to a function pointer conforming to the stdcall calling convention.
   174  // This is useful when interoperating with Windows code requiring callbacks.
   175  // The argument is expected to be a function with one uintptr-sized result. The function must not have arguments with size larger than the size of uintptr.
   176  // Only a limited number of callbacks may be created in a single Go process, and any memory allocated
   177  // for these callbacks is never released.
   178  // Between NewCallback and NewCallbackCDecl, at least 1024 callbacks can always be created.
   179  func NewCallback(fn any) uintptr {
   180  	return compileCallback(fn, true)
   181  }
   182  
   183  // NewCallbackCDecl converts a Go function to a function pointer conforming to the cdecl calling convention.
   184  // This is useful when interoperating with Windows code requiring callbacks.
   185  // The argument is expected to be a function with one uintptr-sized result. The function must not have arguments with size larger than the size of uintptr.
   186  // Only a limited number of callbacks may be created in a single Go process, and any memory allocated
   187  // for these callbacks is never released.
   188  // Between NewCallback and NewCallbackCDecl, at least 1024 callbacks can always be created.
   189  func NewCallbackCDecl(fn any) uintptr {
   190  	return compileCallback(fn, false)
   191  }
   192  
   193  // windows api calls
   194  
   195  //sys	GetLastError() (lasterr error)
   196  //sys	LoadLibrary(libname string) (handle Handle, err error) = LoadLibraryW
   197  //sys	FreeLibrary(handle Handle) (err error)
   198  //sys	GetProcAddress(module Handle, procname string) (proc uintptr, err error)
   199  //sys	GetVersion() (ver uint32, err error)
   200  //sys	rtlGetNtVersionNumbers(majorVersion *uint32, minorVersion *uint32, buildNumber *uint32) = ntdll.RtlGetNtVersionNumbers
   201  //sys	formatMessage(flags uint32, msgsrc uintptr, msgid uint32, langid uint32, buf []uint16, args *byte) (n uint32, err error) = FormatMessageW
   202  //sys	ExitProcess(exitcode uint32)
   203  //sys	CreateFile(name *uint16, access uint32, mode uint32, sa *SecurityAttributes, createmode uint32, attrs uint32, templatefile int32) (handle Handle, err error) [failretval==InvalidHandle] = CreateFileW
   204  //sys	readFile(handle Handle, buf []byte, done *uint32, overlapped *Overlapped) (err error) = ReadFile
   205  //sys	writeFile(handle Handle, buf []byte, done *uint32, overlapped *Overlapped) (err error) = WriteFile
   206  //sys	SetFilePointer(handle Handle, lowoffset int32, highoffsetptr *int32, whence uint32) (newlowoffset uint32, err error) [failretval==0xffffffff]
   207  //sys	CloseHandle(handle Handle) (err error)
   208  //sys	GetStdHandle(stdhandle int) (handle Handle, err error) [failretval==InvalidHandle]
   209  //sys	findFirstFile1(name *uint16, data *win32finddata1) (handle Handle, err error) [failretval==InvalidHandle] = FindFirstFileW
   210  //sys	findNextFile1(handle Handle, data *win32finddata1) (err error) = FindNextFileW
   211  //sys	FindClose(handle Handle) (err error)
   212  //sys	GetFileInformationByHandle(handle Handle, data *ByHandleFileInformation) (err error)
   213  //sys	GetCurrentDirectory(buflen uint32, buf *uint16) (n uint32, err error) = GetCurrentDirectoryW
   214  //sys	SetCurrentDirectory(path *uint16) (err error) = SetCurrentDirectoryW
   215  //sys	CreateDirectory(path *uint16, sa *SecurityAttributes) (err error) = CreateDirectoryW
   216  //sys	RemoveDirectory(path *uint16) (err error) = RemoveDirectoryW
   217  //sys	DeleteFile(path *uint16) (err error) = DeleteFileW
   218  //sys	MoveFile(from *uint16, to *uint16) (err error) = MoveFileW
   219  //sys	GetComputerName(buf *uint16, n *uint32) (err error) = GetComputerNameW
   220  //sys	SetEndOfFile(handle Handle) (err error)
   221  //sys	GetSystemTimeAsFileTime(time *Filetime)
   222  //sys	GetTimeZoneInformation(tzi *Timezoneinformation) (rc uint32, err error) [failretval==0xffffffff]
   223  //sys	createIoCompletionPort(filehandle Handle, cphandle Handle, key uintptr, threadcnt uint32) (handle Handle, err error) = CreateIoCompletionPort
   224  //sys	getQueuedCompletionStatus(cphandle Handle, qty *uint32, key *uintptr, overlapped **Overlapped, timeout uint32) (err error) = GetQueuedCompletionStatus
   225  //sys	postQueuedCompletionStatus(cphandle Handle, qty uint32, key uintptr, overlapped *Overlapped) (err error) = PostQueuedCompletionStatus
   226  //sys	CancelIo(s Handle) (err error)
   227  //sys	CancelIoEx(s Handle, o *Overlapped) (err error)
   228  //sys	CreateProcess(appName *uint16, commandLine *uint16, procSecurity *SecurityAttributes, threadSecurity *SecurityAttributes, inheritHandles bool, creationFlags uint32, env *uint16, currentDir *uint16, startupInfo *StartupInfo, outProcInfo *ProcessInformation) (err error) = CreateProcessW
   229  //sys	CreateProcessAsUser(token Token, appName *uint16, commandLine *uint16, procSecurity *SecurityAttributes, threadSecurity *SecurityAttributes, inheritHandles bool, creationFlags uint32, env *uint16, currentDir *uint16, startupInfo *StartupInfo, outProcInfo *ProcessInformation) (err error) = advapi32.CreateProcessAsUserW
   230  //sys	OpenProcess(da uint32, inheritHandle bool, pid uint32) (handle Handle, err error)
   231  //sys	TerminateProcess(handle Handle, exitcode uint32) (err error)
   232  //sys	GetExitCodeProcess(handle Handle, exitcode *uint32) (err error)
   233  //sys	GetStartupInfo(startupInfo *StartupInfo) (err error) = GetStartupInfoW
   234  //sys	GetCurrentProcess() (pseudoHandle Handle, err error)
   235  //sys	GetProcessTimes(handle Handle, creationTime *Filetime, exitTime *Filetime, kernelTime *Filetime, userTime *Filetime) (err error)
   236  //sys	DuplicateHandle(hSourceProcessHandle Handle, hSourceHandle Handle, hTargetProcessHandle Handle, lpTargetHandle *Handle, dwDesiredAccess uint32, bInheritHandle bool, dwOptions uint32) (err error)
   237  //sys	WaitForSingleObject(handle Handle, waitMilliseconds uint32) (event uint32, err error) [failretval==0xffffffff]
   238  //sys	GetTempPath(buflen uint32, buf *uint16) (n uint32, err error) = GetTempPathW
   239  //sys	CreatePipe(readhandle *Handle, writehandle *Handle, sa *SecurityAttributes, size uint32) (err error)
   240  //sys	GetFileType(filehandle Handle) (n uint32, err error)
   241  //sys	CryptAcquireContext(provhandle *Handle, container *uint16, provider *uint16, provtype uint32, flags uint32) (err error) = advapi32.CryptAcquireContextW
   242  //sys	CryptReleaseContext(provhandle Handle, flags uint32) (err error) = advapi32.CryptReleaseContext
   243  //sys	CryptGenRandom(provhandle Handle, buflen uint32, buf *byte) (err error) = advapi32.CryptGenRandom
   244  //sys	GetEnvironmentStrings() (envs *uint16, err error) [failretval==nil] = kernel32.GetEnvironmentStringsW
   245  //sys	FreeEnvironmentStrings(envs *uint16) (err error) = kernel32.FreeEnvironmentStringsW
   246  //sys	GetEnvironmentVariable(name *uint16, buffer *uint16, size uint32) (n uint32, err error) = kernel32.GetEnvironmentVariableW
   247  //sys	SetEnvironmentVariable(name *uint16, value *uint16) (err error) = kernel32.SetEnvironmentVariableW
   248  //sys	SetFileTime(handle Handle, ctime *Filetime, atime *Filetime, wtime *Filetime) (err error)
   249  //sys	GetFileAttributes(name *uint16) (attrs uint32, err error) [failretval==INVALID_FILE_ATTRIBUTES] = kernel32.GetFileAttributesW
   250  //sys	SetFileAttributes(name *uint16, attrs uint32) (err error) = kernel32.SetFileAttributesW
   251  //sys	GetFileAttributesEx(name *uint16, level uint32, info *byte) (err error) = kernel32.GetFileAttributesExW
   252  //sys	GetCommandLine() (cmd *uint16) = kernel32.GetCommandLineW
   253  //sys	CommandLineToArgv(cmd *uint16, argc *int32) (argv *[8192]*[8192]uint16, err error) [failretval==nil] = shell32.CommandLineToArgvW
   254  //sys	LocalFree(hmem Handle) (handle Handle, err error) [failretval!=0]
   255  //sys	SetHandleInformation(handle Handle, mask uint32, flags uint32) (err error)
   256  //sys	FlushFileBuffers(handle Handle) (err error)
   257  //sys	GetFullPathName(path *uint16, buflen uint32, buf *uint16, fname **uint16) (n uint32, err error) = kernel32.GetFullPathNameW
   258  //sys	GetLongPathName(path *uint16, buf *uint16, buflen uint32) (n uint32, err error) = kernel32.GetLongPathNameW
   259  //sys	GetShortPathName(longpath *uint16, shortpath *uint16, buflen uint32) (n uint32, err error) = kernel32.GetShortPathNameW
   260  //sys	CreateFileMapping(fhandle Handle, sa *SecurityAttributes, prot uint32, maxSizeHigh uint32, maxSizeLow uint32, name *uint16) (handle Handle, err error) = kernel32.CreateFileMappingW
   261  //sys	MapViewOfFile(handle Handle, access uint32, offsetHigh uint32, offsetLow uint32, length uintptr) (addr uintptr, err error)
   262  //sys	UnmapViewOfFile(addr uintptr) (err error)
   263  //sys	FlushViewOfFile(addr uintptr, length uintptr) (err error)
   264  //sys	VirtualLock(addr uintptr, length uintptr) (err error)
   265  //sys	VirtualUnlock(addr uintptr, length uintptr) (err error)
   266  //sys	TransmitFile(s Handle, handle Handle, bytesToWrite uint32, bytsPerSend uint32, overlapped *Overlapped, transmitFileBuf *TransmitFileBuffers, flags uint32) (err error) = mswsock.TransmitFile
   267  //sys	ReadDirectoryChanges(handle Handle, buf *byte, buflen uint32, watchSubTree bool, mask uint32, retlen *uint32, overlapped *Overlapped, completionRoutine uintptr) (err error) = kernel32.ReadDirectoryChangesW
   268  //sys	CertOpenSystemStore(hprov Handle, name *uint16) (store Handle, err error) = crypt32.CertOpenSystemStoreW
   269  //sys   CertOpenStore(storeProvider uintptr, msgAndCertEncodingType uint32, cryptProv uintptr, flags uint32, para uintptr) (handle Handle, err error) = crypt32.CertOpenStore
   270  //sys	CertEnumCertificatesInStore(store Handle, prevContext *CertContext) (context *CertContext, err error) [failretval==nil] = crypt32.CertEnumCertificatesInStore
   271  //sys   CertAddCertificateContextToStore(store Handle, certContext *CertContext, addDisposition uint32, storeContext **CertContext) (err error) = crypt32.CertAddCertificateContextToStore
   272  //sys	CertCloseStore(store Handle, flags uint32) (err error) = crypt32.CertCloseStore
   273  //sys   CertGetCertificateChain(engine Handle, leaf *CertContext, time *Filetime, additionalStore Handle, para *CertChainPara, flags uint32, reserved uintptr, chainCtx **CertChainContext) (err error) = crypt32.CertGetCertificateChain
   274  //sys   CertFreeCertificateChain(ctx *CertChainContext) = crypt32.CertFreeCertificateChain
   275  //sys   CertCreateCertificateContext(certEncodingType uint32, certEncoded *byte, encodedLen uint32) (context *CertContext, err error) [failretval==nil] = crypt32.CertCreateCertificateContext
   276  //sys   CertFreeCertificateContext(ctx *CertContext) (err error) = crypt32.CertFreeCertificateContext
   277  //sys   CertVerifyCertificateChainPolicy(policyOID uintptr, chain *CertChainContext, para *CertChainPolicyPara, status *CertChainPolicyStatus) (err error) = crypt32.CertVerifyCertificateChainPolicy
   278  //sys	RegOpenKeyEx(key Handle, subkey *uint16, options uint32, desiredAccess uint32, result *Handle) (regerrno error) = advapi32.RegOpenKeyExW
   279  //sys	RegCloseKey(key Handle) (regerrno error) = advapi32.RegCloseKey
   280  //sys	RegQueryInfoKey(key Handle, class *uint16, classLen *uint32, reserved *uint32, subkeysLen *uint32, maxSubkeyLen *uint32, maxClassLen *uint32, valuesLen *uint32, maxValueNameLen *uint32, maxValueLen *uint32, saLen *uint32, lastWriteTime *Filetime) (regerrno error) = advapi32.RegQueryInfoKeyW
   281  //sys	regEnumKeyEx(key Handle, index uint32, name *uint16, nameLen *uint32, reserved *uint32, class *uint16, classLen *uint32, lastWriteTime *Filetime) (regerrno error) = advapi32.RegEnumKeyExW
   282  //sys	RegQueryValueEx(key Handle, name *uint16, reserved *uint32, valtype *uint32, buf *byte, buflen *uint32) (regerrno error) = advapi32.RegQueryValueExW
   283  //sys	getCurrentProcessId() (pid uint32) = kernel32.GetCurrentProcessId
   284  //sys	GetConsoleMode(console Handle, mode *uint32) (err error) = kernel32.GetConsoleMode
   285  //sys	WriteConsole(console Handle, buf *uint16, towrite uint32, written *uint32, reserved *byte) (err error) = kernel32.WriteConsoleW
   286  //sys	ReadConsole(console Handle, buf *uint16, toread uint32, read *uint32, inputControl *byte) (err error) = kernel32.ReadConsoleW
   287  //sys	CreateToolhelp32Snapshot(flags uint32, processId uint32) (handle Handle, err error) [failretval==InvalidHandle] = kernel32.CreateToolhelp32Snapshot
   288  //sys	Process32First(snapshot Handle, procEntry *ProcessEntry32) (err error) = kernel32.Process32FirstW
   289  //sys	Process32Next(snapshot Handle, procEntry *ProcessEntry32) (err error) = kernel32.Process32NextW
   290  //sys	DeviceIoControl(handle Handle, ioControlCode uint32, inBuffer *byte, inBufferSize uint32, outBuffer *byte, outBufferSize uint32, bytesReturned *uint32, overlapped *Overlapped) (err error)
   291  // This function returns 1 byte BOOLEAN rather than the 4 byte BOOL.
   292  //sys	CreateSymbolicLink(symlinkfilename *uint16, targetfilename *uint16, flags uint32) (err error) [failretval&0xff==0] = CreateSymbolicLinkW
   293  //sys	CreateHardLink(filename *uint16, existingfilename *uint16, reserved uintptr) (err error) [failretval&0xff==0] = CreateHardLinkW
   294  //sys	initializeProcThreadAttributeList(attrlist *_PROC_THREAD_ATTRIBUTE_LIST, attrcount uint32, flags uint32, size *uintptr) (err error) = InitializeProcThreadAttributeList
   295  //sys	deleteProcThreadAttributeList(attrlist *_PROC_THREAD_ATTRIBUTE_LIST) = DeleteProcThreadAttributeList
   296  //sys	updateProcThreadAttribute(attrlist *_PROC_THREAD_ATTRIBUTE_LIST, flags uint32, attr uintptr, value unsafe.Pointer, size uintptr, prevvalue unsafe.Pointer, returnedsize *uintptr) (err error) = UpdateProcThreadAttribute
   297  
   298  // syscall interface implementation for other packages
   299  
   300  func makeInheritSa() *SecurityAttributes {
   301  	var sa SecurityAttributes
   302  	sa.Length = uint32(unsafe.Sizeof(sa))
   303  	sa.InheritHandle = 1
   304  	return &sa
   305  }
   306  
   307  func Open(path string, mode int, perm uint32) (fd Handle, err error) {
   308  	if len(path) == 0 {
   309  		return InvalidHandle, ERROR_FILE_NOT_FOUND
   310  	}
   311  	pathp, err := UTF16PtrFromString(path)
   312  	if err != nil {
   313  		return InvalidHandle, err
   314  	}
   315  	var access uint32
   316  	switch mode & (O_RDONLY | O_WRONLY | O_RDWR) {
   317  	case O_RDONLY:
   318  		access = GENERIC_READ
   319  	case O_WRONLY:
   320  		access = GENERIC_WRITE
   321  	case O_RDWR:
   322  		access = GENERIC_READ | GENERIC_WRITE
   323  	}
   324  	if mode&O_CREAT != 0 {
   325  		access |= GENERIC_WRITE
   326  	}
   327  	if mode&O_APPEND != 0 {
   328  		access &^= GENERIC_WRITE
   329  		access |= FILE_APPEND_DATA
   330  	}
   331  	sharemode := uint32(FILE_SHARE_READ | FILE_SHARE_WRITE)
   332  	var sa *SecurityAttributes
   333  	if mode&O_CLOEXEC == 0 {
   334  		sa = makeInheritSa()
   335  	}
   336  	var createmode uint32
   337  	switch {
   338  	case mode&(O_CREAT|O_EXCL) == (O_CREAT | O_EXCL):
   339  		createmode = CREATE_NEW
   340  	case mode&(O_CREAT|O_TRUNC) == (O_CREAT | O_TRUNC):
   341  		createmode = CREATE_ALWAYS
   342  	case mode&O_CREAT == O_CREAT:
   343  		createmode = OPEN_ALWAYS
   344  	case mode&O_TRUNC == O_TRUNC:
   345  		createmode = TRUNCATE_EXISTING
   346  	default:
   347  		createmode = OPEN_EXISTING
   348  	}
   349  	var attrs uint32 = FILE_ATTRIBUTE_NORMAL
   350  	if perm&S_IWRITE == 0 {
   351  		attrs = FILE_ATTRIBUTE_READONLY
   352  		if createmode == CREATE_ALWAYS {
   353  			// We have been asked to create a read-only file.
   354  			// If the file already exists, the semantics of
   355  			// the Unix open system call is to preserve the
   356  			// existing permissions. If we pass CREATE_ALWAYS
   357  			// and FILE_ATTRIBUTE_READONLY to CreateFile,
   358  			// and the file already exists, CreateFile will
   359  			// change the file permissions.
   360  			// Avoid that to preserve the Unix semantics.
   361  			h, e := CreateFile(pathp, access, sharemode, sa, TRUNCATE_EXISTING, FILE_ATTRIBUTE_NORMAL, 0)
   362  			switch e {
   363  			case ERROR_FILE_NOT_FOUND, _ERROR_BAD_NETPATH, ERROR_PATH_NOT_FOUND:
   364  				// File does not exist. These are the same
   365  				// errors as Errno.Is checks for ErrNotExist.
   366  				// Carry on to create the file.
   367  			default:
   368  				// Success or some different error.
   369  				return h, e
   370  			}
   371  		}
   372  	}
   373  	h, e := CreateFile(pathp, access, sharemode, sa, createmode, attrs, 0)
   374  	return h, e
   375  }
   376  
   377  func Read(fd Handle, p []byte) (n int, err error) {
   378  	var done uint32
   379  	e := ReadFile(fd, p, &done, nil)
   380  	if e != nil {
   381  		if e == ERROR_BROKEN_PIPE {
   382  			// NOTE(brainman): work around ERROR_BROKEN_PIPE is returned on reading EOF from stdin
   383  			return 0, nil
   384  		}
   385  		return 0, e
   386  	}
   387  	return int(done), nil
   388  }
   389  
   390  func Write(fd Handle, p []byte) (n int, err error) {
   391  	var done uint32
   392  	e := WriteFile(fd, p, &done, nil)
   393  	if e != nil {
   394  		return 0, e
   395  	}
   396  	return int(done), nil
   397  }
   398  
   399  func ReadFile(fd Handle, p []byte, done *uint32, overlapped *Overlapped) error {
   400  	err := readFile(fd, p, done, overlapped)
   401  	if race.Enabled {
   402  		if *done > 0 {
   403  			race.WriteRange(unsafe.Pointer(&p[0]), int(*done))
   404  		}
   405  		race.Acquire(unsafe.Pointer(&ioSync))
   406  	}
   407  	if msanenabled && *done > 0 {
   408  		msanWrite(unsafe.Pointer(&p[0]), int(*done))
   409  	}
   410  	if asanenabled && *done > 0 {
   411  		asanWrite(unsafe.Pointer(&p[0]), int(*done))
   412  	}
   413  	return err
   414  }
   415  
   416  func WriteFile(fd Handle, p []byte, done *uint32, overlapped *Overlapped) error {
   417  	if race.Enabled {
   418  		race.ReleaseMerge(unsafe.Pointer(&ioSync))
   419  	}
   420  	err := writeFile(fd, p, done, overlapped)
   421  	if race.Enabled && *done > 0 {
   422  		race.ReadRange(unsafe.Pointer(&p[0]), int(*done))
   423  	}
   424  	if msanenabled && *done > 0 {
   425  		msanRead(unsafe.Pointer(&p[0]), int(*done))
   426  	}
   427  	if asanenabled && *done > 0 {
   428  		asanRead(unsafe.Pointer(&p[0]), int(*done))
   429  	}
   430  	return err
   431  }
   432  
   433  var ioSync int64
   434  
   435  var procSetFilePointerEx = modkernel32.NewProc("SetFilePointerEx")
   436  
   437  const ptrSize = unsafe.Sizeof(uintptr(0))
   438  
   439  // setFilePointerEx calls SetFilePointerEx.
   440  // See https://msdn.microsoft.com/en-us/library/windows/desktop/aa365542(v=vs.85).aspx
   441  func setFilePointerEx(handle Handle, distToMove int64, newFilePointer *int64, whence uint32) error {
   442  	var e1 Errno
   443  	if unsafe.Sizeof(uintptr(0)) == 8 {
   444  		_, _, e1 = Syscall6(procSetFilePointerEx.Addr(), 4, uintptr(handle), uintptr(distToMove), uintptr(unsafe.Pointer(newFilePointer)), uintptr(whence), 0, 0)
   445  	} else {
   446  		// Different 32-bit systems disgaree about whether distToMove starts 8-byte aligned.
   447  		switch runtime.GOARCH {
   448  		default:
   449  			panic("unsupported 32-bit architecture")
   450  		case "386":
   451  			// distToMove is a LARGE_INTEGER, which is 64 bits.
   452  			_, _, e1 = Syscall6(procSetFilePointerEx.Addr(), 5, uintptr(handle), uintptr(distToMove), uintptr(distToMove>>32), uintptr(unsafe.Pointer(newFilePointer)), uintptr(whence), 0)
   453  		case "arm":
   454  			// distToMove must be 8-byte aligned per ARM calling convention
   455  			// https://docs.microsoft.com/en-us/cpp/build/overview-of-arm-abi-conventions#stage-c-assignment-of-arguments-to-registers-and-stack
   456  			_, _, e1 = Syscall6(procSetFilePointerEx.Addr(), 6, uintptr(handle), 0, uintptr(distToMove), uintptr(distToMove>>32), uintptr(unsafe.Pointer(newFilePointer)), uintptr(whence))
   457  		}
   458  	}
   459  	if e1 != 0 {
   460  		return errnoErr(e1)
   461  	}
   462  	return nil
   463  }
   464  
   465  func Seek(fd Handle, offset int64, whence int) (newoffset int64, err error) {
   466  	var w uint32
   467  	switch whence {
   468  	case 0:
   469  		w = FILE_BEGIN
   470  	case 1:
   471  		w = FILE_CURRENT
   472  	case 2:
   473  		w = FILE_END
   474  	}
   475  	// use GetFileType to check pipe, pipe can't do seek
   476  	ft, _ := GetFileType(fd)
   477  	if ft == FILE_TYPE_PIPE {
   478  		return 0, ESPIPE
   479  	}
   480  	err = setFilePointerEx(fd, offset, &newoffset, w)
   481  	return
   482  }
   483  
   484  func Close(fd Handle) (err error) {
   485  	return CloseHandle(fd)
   486  }
   487  
   488  var (
   489  	Stdin  = getStdHandle(STD_INPUT_HANDLE)
   490  	Stdout = getStdHandle(STD_OUTPUT_HANDLE)
   491  	Stderr = getStdHandle(STD_ERROR_HANDLE)
   492  )
   493  
   494  func getStdHandle(h int) (fd Handle) {
   495  	r, _ := GetStdHandle(h)
   496  	return r
   497  }
   498  
   499  const ImplementsGetwd = true
   500  
   501  func Getwd() (wd string, err error) {
   502  	b := make([]uint16, 300)
   503  	n, e := GetCurrentDirectory(uint32(len(b)), &b[0])
   504  	if e != nil {
   505  		return "", e
   506  	}
   507  	return string(utf16.Decode(b[0:n])), nil
   508  }
   509  
   510  func Chdir(path string) (err error) {
   511  	pathp, err := UTF16PtrFromString(path)
   512  	if err != nil {
   513  		return err
   514  	}
   515  	return SetCurrentDirectory(pathp)
   516  }
   517  
   518  func Mkdir(path string, mode uint32) (err error) {
   519  	pathp, err := UTF16PtrFromString(path)
   520  	if err != nil {
   521  		return err
   522  	}
   523  	return CreateDirectory(pathp, nil)
   524  }
   525  
   526  func Rmdir(path string) (err error) {
   527  	pathp, err := UTF16PtrFromString(path)
   528  	if err != nil {
   529  		return err
   530  	}
   531  	return RemoveDirectory(pathp)
   532  }
   533  
   534  func Unlink(path string) (err error) {
   535  	pathp, err := UTF16PtrFromString(path)
   536  	if err != nil {
   537  		return err
   538  	}
   539  	return DeleteFile(pathp)
   540  }
   541  
   542  func Rename(oldpath, newpath string) (err error) {
   543  	from, err := UTF16PtrFromString(oldpath)
   544  	if err != nil {
   545  		return err
   546  	}
   547  	to, err := UTF16PtrFromString(newpath)
   548  	if err != nil {
   549  		return err
   550  	}
   551  	return MoveFile(from, to)
   552  }
   553  
   554  func ComputerName() (name string, err error) {
   555  	var n uint32 = MAX_COMPUTERNAME_LENGTH + 1
   556  	b := make([]uint16, n)
   557  	e := GetComputerName(&b[0], &n)
   558  	if e != nil {
   559  		return "", e
   560  	}
   561  	return string(utf16.Decode(b[0:n])), nil
   562  }
   563  
   564  func Ftruncate(fd Handle, length int64) (err error) {
   565  	curoffset, e := Seek(fd, 0, 1)
   566  	if e != nil {
   567  		return e
   568  	}
   569  	defer Seek(fd, curoffset, 0)
   570  	_, e = Seek(fd, length, 0)
   571  	if e != nil {
   572  		return e
   573  	}
   574  	e = SetEndOfFile(fd)
   575  	if e != nil {
   576  		return e
   577  	}
   578  	return nil
   579  }
   580  
   581  func Gettimeofday(tv *Timeval) (err error) {
   582  	var ft Filetime
   583  	GetSystemTimeAsFileTime(&ft)
   584  	*tv = NsecToTimeval(ft.Nanoseconds())
   585  	return nil
   586  }
   587  
   588  func Pipe(p []Handle) (err error) {
   589  	if len(p) != 2 {
   590  		return EINVAL
   591  	}
   592  	var r, w Handle
   593  	e := CreatePipe(&r, &w, makeInheritSa(), 0)
   594  	if e != nil {
   595  		return e
   596  	}
   597  	p[0] = r
   598  	p[1] = w
   599  	return nil
   600  }
   601  
   602  func Utimes(path string, tv []Timeval) (err error) {
   603  	if len(tv) != 2 {
   604  		return EINVAL
   605  	}
   606  	pathp, e := UTF16PtrFromString(path)
   607  	if e != nil {
   608  		return e
   609  	}
   610  	h, e := CreateFile(pathp,
   611  		FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, nil,
   612  		OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0)
   613  	if e != nil {
   614  		return e
   615  	}
   616  	defer Close(h)
   617  	a := NsecToFiletime(tv[0].Nanoseconds())
   618  	w := NsecToFiletime(tv[1].Nanoseconds())
   619  	return SetFileTime(h, nil, &a, &w)
   620  }
   621  
   622  func UtimesNano(path string, ts []Timespec) (err error) {
   623  	if len(ts) != 2 {
   624  		return EINVAL
   625  	}
   626  	pathp, e := UTF16PtrFromString(path)
   627  	if e != nil {
   628  		return e
   629  	}
   630  	h, e := CreateFile(pathp,
   631  		FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, nil,
   632  		OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0)
   633  	if e != nil {
   634  		return e
   635  	}
   636  	defer Close(h)
   637  	a := NsecToFiletime(TimespecToNsec(ts[0]))
   638  	w := NsecToFiletime(TimespecToNsec(ts[1]))
   639  	return SetFileTime(h, nil, &a, &w)
   640  }
   641  
   642  func Fsync(fd Handle) (err error) {
   643  	return FlushFileBuffers(fd)
   644  }
   645  
   646  func Chmod(path string, mode uint32) (err error) {
   647  	p, e := UTF16PtrFromString(path)
   648  	if e != nil {
   649  		return e
   650  	}
   651  	attrs, e := GetFileAttributes(p)
   652  	if e != nil {
   653  		return e
   654  	}
   655  	if mode&S_IWRITE != 0 {
   656  		attrs &^= FILE_ATTRIBUTE_READONLY
   657  	} else {
   658  		attrs |= FILE_ATTRIBUTE_READONLY
   659  	}
   660  	return SetFileAttributes(p, attrs)
   661  }
   662  
   663  func LoadCancelIoEx() error {
   664  	return procCancelIoEx.Find()
   665  }
   666  
   667  func LoadSetFileCompletionNotificationModes() error {
   668  	return procSetFileCompletionNotificationModes.Find()
   669  }
   670  
   671  // net api calls
   672  
   673  const socket_error = uintptr(^uint32(0))
   674  
   675  //sys	WSAStartup(verreq uint32, data *WSAData) (sockerr error) = ws2_32.WSAStartup
   676  //sys	WSACleanup() (err error) [failretval==socket_error] = ws2_32.WSACleanup
   677  //sys	WSAIoctl(s Handle, iocc uint32, inbuf *byte, cbif uint32, outbuf *byte, cbob uint32, cbbr *uint32, overlapped *Overlapped, completionRoutine uintptr) (err error) [failretval==socket_error] = ws2_32.WSAIoctl
   678  //sys	socket(af int32, typ int32, protocol int32) (handle Handle, err error) [failretval==InvalidHandle] = ws2_32.socket
   679  //sys	Setsockopt(s Handle, level int32, optname int32, optval *byte, optlen int32) (err error) [failretval==socket_error] = ws2_32.setsockopt
   680  //sys	Getsockopt(s Handle, level int32, optname int32, optval *byte, optlen *int32) (err error) [failretval==socket_error] = ws2_32.getsockopt
   681  //sys	bind(s Handle, name unsafe.Pointer, namelen int32) (err error) [failretval==socket_error] = ws2_32.bind
   682  //sys	connect(s Handle, name unsafe.Pointer, namelen int32) (err error) [failretval==socket_error] = ws2_32.connect
   683  //sys	getsockname(s Handle, rsa *RawSockaddrAny, addrlen *int32) (err error) [failretval==socket_error] = ws2_32.getsockname
   684  //sys	getpeername(s Handle, rsa *RawSockaddrAny, addrlen *int32) (err error) [failretval==socket_error] = ws2_32.getpeername
   685  //sys	listen(s Handle, backlog int32) (err error) [failretval==socket_error] = ws2_32.listen
   686  //sys	shutdown(s Handle, how int32) (err error) [failretval==socket_error] = ws2_32.shutdown
   687  //sys	Closesocket(s Handle) (err error) [failretval==socket_error] = ws2_32.closesocket
   688  //sys	AcceptEx(ls Handle, as Handle, buf *byte, rxdatalen uint32, laddrlen uint32, raddrlen uint32, recvd *uint32, overlapped *Overlapped) (err error) = mswsock.AcceptEx
   689  //sys	GetAcceptExSockaddrs(buf *byte, rxdatalen uint32, laddrlen uint32, raddrlen uint32, lrsa **RawSockaddrAny, lrsalen *int32, rrsa **RawSockaddrAny, rrsalen *int32) = mswsock.GetAcceptExSockaddrs
   690  //sys	WSARecv(s Handle, bufs *WSABuf, bufcnt uint32, recvd *uint32, flags *uint32, overlapped *Overlapped, croutine *byte) (err error) [failretval==socket_error] = ws2_32.WSARecv
   691  //sys	WSASend(s Handle, bufs *WSABuf, bufcnt uint32, sent *uint32, flags uint32, overlapped *Overlapped, croutine *byte) (err error) [failretval==socket_error] = ws2_32.WSASend
   692  //sys	WSARecvFrom(s Handle, bufs *WSABuf, bufcnt uint32, recvd *uint32, flags *uint32,  from *RawSockaddrAny, fromlen *int32, overlapped *Overlapped, croutine *byte) (err error) [failretval==socket_error] = ws2_32.WSARecvFrom
   693  //sys	WSASendTo(s Handle, bufs *WSABuf, bufcnt uint32, sent *uint32, flags uint32, to *RawSockaddrAny, tolen int32,  overlapped *Overlapped, croutine *byte) (err error) [failretval==socket_error] = ws2_32.WSASendTo
   694  //sys	GetHostByName(name string) (h *Hostent, err error) [failretval==nil] = ws2_32.gethostbyname
   695  //sys	GetServByName(name string, proto string) (s *Servent, err error) [failretval==nil] = ws2_32.getservbyname
   696  //sys	Ntohs(netshort uint16) (u uint16) = ws2_32.ntohs
   697  //sys	GetProtoByName(name string) (p *Protoent, err error) [failretval==nil] = ws2_32.getprotobyname
   698  //sys	DnsQuery(name string, qtype uint16, options uint32, extra *byte, qrs **DNSRecord, pr *byte) (status error) = dnsapi.DnsQuery_W
   699  //sys	DnsRecordListFree(rl *DNSRecord, freetype uint32) = dnsapi.DnsRecordListFree
   700  //sys	DnsNameCompare(name1 *uint16, name2 *uint16) (same bool) = dnsapi.DnsNameCompare_W
   701  //sys	GetAddrInfoW(nodename *uint16, servicename *uint16, hints *AddrinfoW, result **AddrinfoW) (sockerr error) = ws2_32.GetAddrInfoW
   702  //sys	FreeAddrInfoW(addrinfo *AddrinfoW) = ws2_32.FreeAddrInfoW
   703  //sys	GetIfEntry(pIfRow *MibIfRow) (errcode error) = iphlpapi.GetIfEntry
   704  //sys	GetAdaptersInfo(ai *IpAdapterInfo, ol *uint32) (errcode error) = iphlpapi.GetAdaptersInfo
   705  //sys	SetFileCompletionNotificationModes(handle Handle, flags uint8) (err error) = kernel32.SetFileCompletionNotificationModes
   706  //sys	WSAEnumProtocols(protocols *int32, protocolBuffer *WSAProtocolInfo, bufferLength *uint32) (n int32, err error) [failretval==-1] = ws2_32.WSAEnumProtocolsW
   707  
   708  // For testing: clients can set this flag to force
   709  // creation of IPv6 sockets to return EAFNOSUPPORT.
   710  var SocketDisableIPv6 bool
   711  
   712  type RawSockaddrInet4 struct {
   713  	Family uint16
   714  	Port   uint16
   715  	Addr   [4]byte /* in_addr */
   716  	Zero   [8]uint8
   717  }
   718  
   719  type RawSockaddrInet6 struct {
   720  	Family   uint16
   721  	Port     uint16
   722  	Flowinfo uint32
   723  	Addr     [16]byte /* in6_addr */
   724  	Scope_id uint32
   725  }
   726  
   727  type RawSockaddr struct {
   728  	Family uint16
   729  	Data   [14]int8
   730  }
   731  
   732  type RawSockaddrAny struct {
   733  	Addr RawSockaddr
   734  	Pad  [100]int8
   735  }
   736  
   737  type Sockaddr interface {
   738  	sockaddr() (ptr unsafe.Pointer, len int32, err error) // lowercase; only we can define Sockaddrs
   739  }
   740  
   741  type SockaddrInet4 struct {
   742  	Port int
   743  	Addr [4]byte
   744  	raw  RawSockaddrInet4
   745  }
   746  
   747  func (sa *SockaddrInet4) sockaddr() (unsafe.Pointer, int32, error) {
   748  	if sa.Port < 0 || sa.Port > 0xFFFF {
   749  		return nil, 0, EINVAL
   750  	}
   751  	sa.raw.Family = AF_INET
   752  	p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port))
   753  	p[0] = byte(sa.Port >> 8)
   754  	p[1] = byte(sa.Port)
   755  	sa.raw.Addr = sa.Addr
   756  	return unsafe.Pointer(&sa.raw), int32(unsafe.Sizeof(sa.raw)), nil
   757  }
   758  
   759  type SockaddrInet6 struct {
   760  	Port   int
   761  	ZoneId uint32
   762  	Addr   [16]byte
   763  	raw    RawSockaddrInet6
   764  }
   765  
   766  func (sa *SockaddrInet6) sockaddr() (unsafe.Pointer, int32, error) {
   767  	if sa.Port < 0 || sa.Port > 0xFFFF {
   768  		return nil, 0, EINVAL
   769  	}
   770  	sa.raw.Family = AF_INET6
   771  	p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port))
   772  	p[0] = byte(sa.Port >> 8)
   773  	p[1] = byte(sa.Port)
   774  	sa.raw.Scope_id = sa.ZoneId
   775  	sa.raw.Addr = sa.Addr
   776  	return unsafe.Pointer(&sa.raw), int32(unsafe.Sizeof(sa.raw)), nil
   777  }
   778  
   779  type RawSockaddrUnix struct {
   780  	Family uint16
   781  	Path   [UNIX_PATH_MAX]int8
   782  }
   783  
   784  type SockaddrUnix struct {
   785  	Name string
   786  	raw  RawSockaddrUnix
   787  }
   788  
   789  func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, int32, error) {
   790  	name := sa.Name
   791  	n := len(name)
   792  	if n > len(sa.raw.Path) {
   793  		return nil, 0, EINVAL
   794  	}
   795  	if n == len(sa.raw.Path) && name[0] != '@' {
   796  		return nil, 0, EINVAL
   797  	}
   798  	sa.raw.Family = AF_UNIX
   799  	for i := 0; i < n; i++ {
   800  		sa.raw.Path[i] = int8(name[i])
   801  	}
   802  	// length is family (uint16), name, NUL.
   803  	sl := int32(2)
   804  	if n > 0 {
   805  		sl += int32(n) + 1
   806  	}
   807  	if sa.raw.Path[0] == '@' {
   808  		sa.raw.Path[0] = 0
   809  		// Don't count trailing NUL for abstract address.
   810  		sl--
   811  	}
   812  
   813  	return unsafe.Pointer(&sa.raw), sl, nil
   814  }
   815  
   816  func (rsa *RawSockaddrAny) Sockaddr() (Sockaddr, error) {
   817  	switch rsa.Addr.Family {
   818  	case AF_UNIX:
   819  		pp := (*RawSockaddrUnix)(unsafe.Pointer(rsa))
   820  		sa := new(SockaddrUnix)
   821  		if pp.Path[0] == 0 {
   822  			// "Abstract" Unix domain socket.
   823  			// Rewrite leading NUL as @ for textual display.
   824  			// (This is the standard convention.)
   825  			// Not friendly to overwrite in place,
   826  			// but the callers below don't care.
   827  			pp.Path[0] = '@'
   828  		}
   829  
   830  		// Assume path ends at NUL.
   831  		// This is not technically the Linux semantics for
   832  		// abstract Unix domain sockets--they are supposed
   833  		// to be uninterpreted fixed-size binary blobs--but
   834  		// everyone uses this convention.
   835  		n := 0
   836  		for n < len(pp.Path) && pp.Path[n] != 0 {
   837  			n++
   838  		}
   839  		bytes := (*[len(pp.Path)]byte)(unsafe.Pointer(&pp.Path[0]))[0:n:n]
   840  		sa.Name = string(bytes)
   841  		return sa, nil
   842  
   843  	case AF_INET:
   844  		pp := (*RawSockaddrInet4)(unsafe.Pointer(rsa))
   845  		sa := new(SockaddrInet4)
   846  		p := (*[2]byte)(unsafe.Pointer(&pp.Port))
   847  		sa.Port = int(p[0])<<8 + int(p[1])
   848  		sa.Addr = pp.Addr
   849  		return sa, nil
   850  
   851  	case AF_INET6:
   852  		pp := (*RawSockaddrInet6)(unsafe.Pointer(rsa))
   853  		sa := new(SockaddrInet6)
   854  		p := (*[2]byte)(unsafe.Pointer(&pp.Port))
   855  		sa.Port = int(p[0])<<8 + int(p[1])
   856  		sa.ZoneId = pp.Scope_id
   857  		sa.Addr = pp.Addr
   858  		return sa, nil
   859  	}
   860  	return nil, EAFNOSUPPORT
   861  }
   862  
   863  func Socket(domain, typ, proto int) (fd Handle, err error) {
   864  	if domain == AF_INET6 && SocketDisableIPv6 {
   865  		return InvalidHandle, EAFNOSUPPORT
   866  	}
   867  	return socket(int32(domain), int32(typ), int32(proto))
   868  }
   869  
   870  func SetsockoptInt(fd Handle, level, opt int, value int) (err error) {
   871  	v := int32(value)
   872  	return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(&v)), int32(unsafe.Sizeof(v)))
   873  }
   874  
   875  func Bind(fd Handle, sa Sockaddr) (err error) {
   876  	ptr, n, err := sa.sockaddr()
   877  	if err != nil {
   878  		return err
   879  	}
   880  	return bind(fd, ptr, n)
   881  }
   882  
   883  func Connect(fd Handle, sa Sockaddr) (err error) {
   884  	ptr, n, err := sa.sockaddr()
   885  	if err != nil {
   886  		return err
   887  	}
   888  	return connect(fd, ptr, n)
   889  }
   890  
   891  func Getsockname(fd Handle) (sa Sockaddr, err error) {
   892  	var rsa RawSockaddrAny
   893  	l := int32(unsafe.Sizeof(rsa))
   894  	if err = getsockname(fd, &rsa, &l); err != nil {
   895  		return
   896  	}
   897  	return rsa.Sockaddr()
   898  }
   899  
   900  func Getpeername(fd Handle) (sa Sockaddr, err error) {
   901  	var rsa RawSockaddrAny
   902  	l := int32(unsafe.Sizeof(rsa))
   903  	if err = getpeername(fd, &rsa, &l); err != nil {
   904  		return
   905  	}
   906  	return rsa.Sockaddr()
   907  }
   908  
   909  func Listen(s Handle, n int) (err error) {
   910  	return listen(s, int32(n))
   911  }
   912  
   913  func Shutdown(fd Handle, how int) (err error) {
   914  	return shutdown(fd, int32(how))
   915  }
   916  
   917  func WSASendto(s Handle, bufs *WSABuf, bufcnt uint32, sent *uint32, flags uint32, to Sockaddr, overlapped *Overlapped, croutine *byte) (err error) {
   918  	rsa, len, err := to.sockaddr()
   919  	if err != nil {
   920  		return err
   921  	}
   922  	r1, _, e1 := Syscall9(procWSASendTo.Addr(), 9, uintptr(s), uintptr(unsafe.Pointer(bufs)), uintptr(bufcnt), uintptr(unsafe.Pointer(sent)), uintptr(flags), uintptr(unsafe.Pointer(rsa)), uintptr(len), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(croutine)))
   923  	if r1 == socket_error {
   924  		if e1 != 0 {
   925  			err = errnoErr(e1)
   926  		} else {
   927  			err = EINVAL
   928  		}
   929  	}
   930  	return err
   931  }
   932  
   933  func wsaSendtoInet4(s Handle, bufs *WSABuf, bufcnt uint32, sent *uint32, flags uint32, to *SockaddrInet4, overlapped *Overlapped, croutine *byte) (err error) {
   934  	rsa, len, err := to.sockaddr()
   935  	if err != nil {
   936  		return err
   937  	}
   938  	r1, _, e1 := Syscall9(procWSASendTo.Addr(), 9, uintptr(s), uintptr(unsafe.Pointer(bufs)), uintptr(bufcnt), uintptr(unsafe.Pointer(sent)), uintptr(flags), uintptr(unsafe.Pointer(rsa)), uintptr(len), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(croutine)))
   939  	if r1 == socket_error {
   940  		if e1 != 0 {
   941  			err = errnoErr(e1)
   942  		} else {
   943  			err = EINVAL
   944  		}
   945  	}
   946  	return err
   947  }
   948  
   949  func wsaSendtoInet6(s Handle, bufs *WSABuf, bufcnt uint32, sent *uint32, flags uint32, to *SockaddrInet6, overlapped *Overlapped, croutine *byte) (err error) {
   950  	rsa, len, err := to.sockaddr()
   951  	if err != nil {
   952  		return err
   953  	}
   954  	r1, _, e1 := Syscall9(procWSASendTo.Addr(), 9, uintptr(s), uintptr(unsafe.Pointer(bufs)), uintptr(bufcnt), uintptr(unsafe.Pointer(sent)), uintptr(flags), uintptr(unsafe.Pointer(rsa)), uintptr(len), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(croutine)))
   955  	if r1 == socket_error {
   956  		if e1 != 0 {
   957  			err = errnoErr(e1)
   958  		} else {
   959  			err = EINVAL
   960  		}
   961  	}
   962  	return err
   963  }
   964  
   965  func LoadGetAddrInfo() error {
   966  	return procGetAddrInfoW.Find()
   967  }
   968  
   969  var connectExFunc struct {
   970  	once sync.Once
   971  	addr uintptr
   972  	err  error
   973  }
   974  
   975  func LoadConnectEx() error {
   976  	connectExFunc.once.Do(func() {
   977  		var s Handle
   978  		s, connectExFunc.err = Socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)
   979  		if connectExFunc.err != nil {
   980  			return
   981  		}
   982  		defer CloseHandle(s)
   983  		var n uint32
   984  		connectExFunc.err = WSAIoctl(s,
   985  			SIO_GET_EXTENSION_FUNCTION_POINTER,
   986  			(*byte)(unsafe.Pointer(&WSAID_CONNECTEX)),
   987  			uint32(unsafe.Sizeof(WSAID_CONNECTEX)),
   988  			(*byte)(unsafe.Pointer(&connectExFunc.addr)),
   989  			uint32(unsafe.Sizeof(connectExFunc.addr)),
   990  			&n, nil, 0)
   991  	})
   992  	return connectExFunc.err
   993  }
   994  
   995  func connectEx(s Handle, name unsafe.Pointer, namelen int32, sendBuf *byte, sendDataLen uint32, bytesSent *uint32, overlapped *Overlapped) (err error) {
   996  	r1, _, e1 := Syscall9(connectExFunc.addr, 7, uintptr(s), uintptr(name), uintptr(namelen), uintptr(unsafe.Pointer(sendBuf)), uintptr(sendDataLen), uintptr(unsafe.Pointer(bytesSent)), uintptr(unsafe.Pointer(overlapped)), 0, 0)
   997  	if r1 == 0 {
   998  		if e1 != 0 {
   999  			err = error(e1)
  1000  		} else {
  1001  			err = EINVAL
  1002  		}
  1003  	}
  1004  	return
  1005  }
  1006  
  1007  func ConnectEx(fd Handle, sa Sockaddr, sendBuf *byte, sendDataLen uint32, bytesSent *uint32, overlapped *Overlapped) error {
  1008  	err := LoadConnectEx()
  1009  	if err != nil {
  1010  		return errorspkg.New("failed to find ConnectEx: " + err.Error())
  1011  	}
  1012  	ptr, n, err := sa.sockaddr()
  1013  	if err != nil {
  1014  		return err
  1015  	}
  1016  	return connectEx(fd, ptr, n, sendBuf, sendDataLen, bytesSent, overlapped)
  1017  }
  1018  
  1019  // Invented structures to support what package os expects.
  1020  type Rusage struct {
  1021  	CreationTime Filetime
  1022  	ExitTime     Filetime
  1023  	KernelTime   Filetime
  1024  	UserTime     Filetime
  1025  }
  1026  
  1027  type WaitStatus struct {
  1028  	ExitCode uint32
  1029  }
  1030  
  1031  func (w WaitStatus) Exited() bool { return true }
  1032  
  1033  func (w WaitStatus) ExitStatus() int { return int(w.ExitCode) }
  1034  
  1035  func (w WaitStatus) Signal() Signal { return -1 }
  1036  
  1037  func (w WaitStatus) CoreDump() bool { return false }
  1038  
  1039  func (w WaitStatus) Stopped() bool { return false }
  1040  
  1041  func (w WaitStatus) Continued() bool { return false }
  1042  
  1043  func (w WaitStatus) StopSignal() Signal { return -1 }
  1044  
  1045  func (w WaitStatus) Signaled() bool { return false }
  1046  
  1047  func (w WaitStatus) TrapCause() int { return -1 }
  1048  
  1049  // Timespec is an invented structure on Windows, but here for
  1050  // consistency with the syscall package for other operating systems.
  1051  type Timespec struct {
  1052  	Sec  int64
  1053  	Nsec int64
  1054  }
  1055  
  1056  func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) }
  1057  
  1058  func NsecToTimespec(nsec int64) (ts Timespec) {
  1059  	ts.Sec = nsec / 1e9
  1060  	ts.Nsec = nsec % 1e9
  1061  	return
  1062  }
  1063  
  1064  // TODO(brainman): fix all needed for net
  1065  
  1066  func Accept(fd Handle) (nfd Handle, sa Sockaddr, err error) { return 0, nil, EWINDOWS }
  1067  func Recvfrom(fd Handle, p []byte, flags int) (n int, from Sockaddr, err error) {
  1068  	return 0, nil, EWINDOWS
  1069  }
  1070  func Sendto(fd Handle, p []byte, flags int, to Sockaddr) (err error)       { return EWINDOWS }
  1071  func SetsockoptTimeval(fd Handle, level, opt int, tv *Timeval) (err error) { return EWINDOWS }
  1072  
  1073  // The Linger struct is wrong but we only noticed after Go 1.
  1074  // sysLinger is the real system call structure.
  1075  
  1076  // BUG(brainman): The definition of Linger is not appropriate for direct use
  1077  // with Setsockopt and Getsockopt.
  1078  // Use SetsockoptLinger instead.
  1079  
  1080  type Linger struct {
  1081  	Onoff  int32
  1082  	Linger int32
  1083  }
  1084  
  1085  type sysLinger struct {
  1086  	Onoff  uint16
  1087  	Linger uint16
  1088  }
  1089  
  1090  type IPMreq struct {
  1091  	Multiaddr [4]byte /* in_addr */
  1092  	Interface [4]byte /* in_addr */
  1093  }
  1094  
  1095  type IPv6Mreq struct {
  1096  	Multiaddr [16]byte /* in6_addr */
  1097  	Interface uint32
  1098  }
  1099  
  1100  func GetsockoptInt(fd Handle, level, opt int) (int, error) { return -1, EWINDOWS }
  1101  
  1102  func SetsockoptLinger(fd Handle, level, opt int, l *Linger) (err error) {
  1103  	sys := sysLinger{Onoff: uint16(l.Onoff), Linger: uint16(l.Linger)}
  1104  	return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(&sys)), int32(unsafe.Sizeof(sys)))
  1105  }
  1106  
  1107  func SetsockoptInet4Addr(fd Handle, level, opt int, value [4]byte) (err error) {
  1108  	return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(&value[0])), 4)
  1109  }
  1110  func SetsockoptIPMreq(fd Handle, level, opt int, mreq *IPMreq) (err error) {
  1111  	return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(mreq)), int32(unsafe.Sizeof(*mreq)))
  1112  }
  1113  func SetsockoptIPv6Mreq(fd Handle, level, opt int, mreq *IPv6Mreq) (err error) { return EWINDOWS }
  1114  
  1115  func Getpid() (pid int) { return int(getCurrentProcessId()) }
  1116  
  1117  func FindFirstFile(name *uint16, data *Win32finddata) (handle Handle, err error) {
  1118  	// NOTE(rsc): The Win32finddata struct is wrong for the system call:
  1119  	// the two paths are each one uint16 short. Use the correct struct,
  1120  	// a win32finddata1, and then copy the results out.
  1121  	// There is no loss of expressivity here, because the final
  1122  	// uint16, if it is used, is supposed to be a NUL, and Go doesn't need that.
  1123  	// For Go 1.1, we might avoid the allocation of win32finddata1 here
  1124  	// by adding a final Bug [2]uint16 field to the struct and then
  1125  	// adjusting the fields in the result directly.
  1126  	var data1 win32finddata1
  1127  	handle, err = findFirstFile1(name, &data1)
  1128  	if err == nil {
  1129  		copyFindData(data, &data1)
  1130  	}
  1131  	return
  1132  }
  1133  
  1134  func FindNextFile(handle Handle, data *Win32finddata) (err error) {
  1135  	var data1 win32finddata1
  1136  	err = findNextFile1(handle, &data1)
  1137  	if err == nil {
  1138  		copyFindData(data, &data1)
  1139  	}
  1140  	return
  1141  }
  1142  
  1143  func getProcessEntry(pid int) (*ProcessEntry32, error) {
  1144  	snapshot, err := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)
  1145  	if err != nil {
  1146  		return nil, err
  1147  	}
  1148  	defer CloseHandle(snapshot)
  1149  	var procEntry ProcessEntry32
  1150  	procEntry.Size = uint32(unsafe.Sizeof(procEntry))
  1151  	if err = Process32First(snapshot, &procEntry); err != nil {
  1152  		return nil, err
  1153  	}
  1154  	for {
  1155  		if procEntry.ProcessID == uint32(pid) {
  1156  			return &procEntry, nil
  1157  		}
  1158  		err = Process32Next(snapshot, &procEntry)
  1159  		if err != nil {
  1160  			return nil, err
  1161  		}
  1162  	}
  1163  }
  1164  
  1165  func Getppid() (ppid int) {
  1166  	pe, err := getProcessEntry(Getpid())
  1167  	if err != nil {
  1168  		return -1
  1169  	}
  1170  	return int(pe.ParentProcessID)
  1171  }
  1172  
  1173  // TODO(brainman): fix all needed for os
  1174  func Fchdir(fd Handle) (err error)             { return EWINDOWS }
  1175  func Link(oldpath, newpath string) (err error) { return EWINDOWS }
  1176  func Symlink(path, link string) (err error)    { return EWINDOWS }
  1177  
  1178  func Fchmod(fd Handle, mode uint32) (err error)        { return EWINDOWS }
  1179  func Chown(path string, uid int, gid int) (err error)  { return EWINDOWS }
  1180  func Lchown(path string, uid int, gid int) (err error) { return EWINDOWS }
  1181  func Fchown(fd Handle, uid int, gid int) (err error)   { return EWINDOWS }
  1182  
  1183  func Getuid() (uid int)                  { return -1 }
  1184  func Geteuid() (euid int)                { return -1 }
  1185  func Getgid() (gid int)                  { return -1 }
  1186  func Getegid() (egid int)                { return -1 }
  1187  func Getgroups() (gids []int, err error) { return nil, EWINDOWS }
  1188  
  1189  type Signal int
  1190  
  1191  func (s Signal) Signal() {}
  1192  
  1193  func (s Signal) String() string {
  1194  	if 0 <= s && int(s) < len(signals) {
  1195  		str := signals[s]
  1196  		if str != "" {
  1197  			return str
  1198  		}
  1199  	}
  1200  	return "signal " + itoa.Itoa(int(s))
  1201  }
  1202  
  1203  func LoadCreateSymbolicLink() error {
  1204  	return procCreateSymbolicLinkW.Find()
  1205  }
  1206  
  1207  // Readlink returns the destination of the named symbolic link.
  1208  func Readlink(path string, buf []byte) (n int, err error) {
  1209  	fd, err := CreateFile(StringToUTF16Ptr(path), GENERIC_READ, 0, nil, OPEN_EXISTING,
  1210  		FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_BACKUP_SEMANTICS, 0)
  1211  	if err != nil {
  1212  		return -1, err
  1213  	}
  1214  	defer CloseHandle(fd)
  1215  
  1216  	rdbbuf := make([]byte, MAXIMUM_REPARSE_DATA_BUFFER_SIZE)
  1217  	var bytesReturned uint32
  1218  	err = DeviceIoControl(fd, FSCTL_GET_REPARSE_POINT, nil, 0, &rdbbuf[0], uint32(len(rdbbuf)), &bytesReturned, nil)
  1219  	if err != nil {
  1220  		return -1, err
  1221  	}
  1222  
  1223  	rdb := (*reparseDataBuffer)(unsafe.Pointer(&rdbbuf[0]))
  1224  	var s string
  1225  	switch rdb.ReparseTag {
  1226  	case IO_REPARSE_TAG_SYMLINK:
  1227  		data := (*symbolicLinkReparseBuffer)(unsafe.Pointer(&rdb.reparseBuffer))
  1228  		p := (*[0xffff]uint16)(unsafe.Pointer(&data.PathBuffer[0]))
  1229  		s = UTF16ToString(p[data.SubstituteNameOffset/2 : (data.SubstituteNameOffset+data.SubstituteNameLength)/2])
  1230  		if data.Flags&_SYMLINK_FLAG_RELATIVE == 0 {
  1231  			if len(s) >= 4 && s[:4] == `\??\` {
  1232  				s = s[4:]
  1233  				switch {
  1234  				case len(s) >= 2 && s[1] == ':': // \??\C:\foo\bar
  1235  					// do nothing
  1236  				case len(s) >= 4 && s[:4] == `UNC\`: // \??\UNC\foo\bar
  1237  					s = `\\` + s[4:]
  1238  				default:
  1239  					// unexpected; do nothing
  1240  				}
  1241  			} else {
  1242  				// unexpected; do nothing
  1243  			}
  1244  		}
  1245  	case _IO_REPARSE_TAG_MOUNT_POINT:
  1246  		data := (*mountPointReparseBuffer)(unsafe.Pointer(&rdb.reparseBuffer))
  1247  		p := (*[0xffff]uint16)(unsafe.Pointer(&data.PathBuffer[0]))
  1248  		s = UTF16ToString(p[data.SubstituteNameOffset/2 : (data.SubstituteNameOffset+data.SubstituteNameLength)/2])
  1249  		if len(s) >= 4 && s[:4] == `\??\` { // \??\C:\foo\bar
  1250  			s = s[4:]
  1251  		} else {
  1252  			// unexpected; do nothing
  1253  		}
  1254  	default:
  1255  		// the path is not a symlink or junction but another type of reparse
  1256  		// point
  1257  		return -1, ENOENT
  1258  	}
  1259  	n = copy(buf, []byte(s))
  1260  
  1261  	return n, nil
  1262  }
  1263  
  1264  // Deprecated: CreateIoCompletionPort has the wrong function signature. Use x/sys/windows.CreateIoCompletionPort.
  1265  func CreateIoCompletionPort(filehandle Handle, cphandle Handle, key uint32, threadcnt uint32) (Handle, error) {
  1266  	return createIoCompletionPort(filehandle, cphandle, uintptr(key), threadcnt)
  1267  }
  1268  
  1269  // Deprecated: GetQueuedCompletionStatus has the wrong function signature. Use x/sys/windows.GetQueuedCompletionStatus.
  1270  func GetQueuedCompletionStatus(cphandle Handle, qty *uint32, key *uint32, overlapped **Overlapped, timeout uint32) error {
  1271  	var ukey uintptr
  1272  	var pukey *uintptr
  1273  	if key != nil {
  1274  		ukey = uintptr(*key)
  1275  		pukey = &ukey
  1276  	}
  1277  	err := getQueuedCompletionStatus(cphandle, qty, pukey, overlapped, timeout)
  1278  	if key != nil {
  1279  		*key = uint32(ukey)
  1280  		if uintptr(*key) != ukey && err == nil {
  1281  			err = errorspkg.New("GetQueuedCompletionStatus returned key overflow")
  1282  		}
  1283  	}
  1284  	return err
  1285  }
  1286  
  1287  // Deprecated: PostQueuedCompletionStatus has the wrong function signature. Use x/sys/windows.PostQueuedCompletionStatus.
  1288  func PostQueuedCompletionStatus(cphandle Handle, qty uint32, key uint32, overlapped *Overlapped) error {
  1289  	return postQueuedCompletionStatus(cphandle, qty, uintptr(key), overlapped)
  1290  }
  1291  
  1292  // newProcThreadAttributeList allocates new PROC_THREAD_ATTRIBUTE_LIST, with
  1293  // the requested maximum number of attributes, which must be cleaned up by
  1294  // deleteProcThreadAttributeList.
  1295  func newProcThreadAttributeList(maxAttrCount uint32) (*_PROC_THREAD_ATTRIBUTE_LIST, error) {
  1296  	var size uintptr
  1297  	err := initializeProcThreadAttributeList(nil, maxAttrCount, 0, &size)
  1298  	if err != ERROR_INSUFFICIENT_BUFFER {
  1299  		if err == nil {
  1300  			return nil, errorspkg.New("unable to query buffer size from InitializeProcThreadAttributeList")
  1301  		}
  1302  		return nil, err
  1303  	}
  1304  	// size is guaranteed to be ≥1 by initializeProcThreadAttributeList.
  1305  	al := (*_PROC_THREAD_ATTRIBUTE_LIST)(unsafe.Pointer(&make([]byte, size)[0]))
  1306  	err = initializeProcThreadAttributeList(al, maxAttrCount, 0, &size)
  1307  	if err != nil {
  1308  		return nil, err
  1309  	}
  1310  	return al, nil
  1311  }
  1312  
  1313  // RegEnumKeyEx enumerates the subkeys of an open registry key.
  1314  // Each call retrieves information about one subkey. name is
  1315  // a buffer that should be large enough to hold the name of the
  1316  // subkey plus a null terminating character. nameLen is its
  1317  // length. On return, nameLen will contain the actual length of the
  1318  // subkey.
  1319  //
  1320  // Should name not be large enough to hold the subkey, this function
  1321  // will return ERROR_MORE_DATA, and must be called again with an
  1322  // appropriately sized buffer.
  1323  //
  1324  // reserved must be nil. class and classLen behave like name and nameLen
  1325  // but for the class of the subkey, except that they are optional.
  1326  // lastWriteTime, if not nil, will be populated with the time the subkey
  1327  // was last written.
  1328  //
  1329  // The caller must enumerate all subkeys in order. That is
  1330  // RegEnumKeyEx must be called with index starting at 0, incrementing
  1331  // the index until the function returns ERROR_NO_MORE_ITEMS, or with
  1332  // the index of the last subkey (obtainable from RegQueryInfoKey),
  1333  // decrementing until index 0 is enumerated.
  1334  //
  1335  // Successive calls to this API must happen on the same OS thread,
  1336  // so call runtime.LockOSThread before calling this function.
  1337  func RegEnumKeyEx(key Handle, index uint32, name *uint16, nameLen *uint32, reserved *uint32, class *uint16, classLen *uint32, lastWriteTime *Filetime) (regerrno error) {
  1338  	return regEnumKeyEx(key, index, name, nameLen, reserved, class, classLen, lastWriteTime)
  1339  }
  1340  

View as plain text