Source file src/syscall/syscall_windows.go

Documentation: syscall

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

View as plain text