...
Run Format

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

View as plain text