Black Lives Matter. Support the Equal Justice Initiative.

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

View as plain text