Source file src/cmd/vendor/golang.org/x/sys/windows/syscall_windows.go

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Windows system calls.
     6  
     7  package windows
     8  
     9  import (
    10  	errorspkg "errors"
    11  	"fmt"
    12  	"runtime"
    13  	"sync"
    14  	"syscall"
    15  	"time"
    16  	"unicode/utf16"
    17  	"unsafe"
    18  
    19  	"golang.org/x/sys/internal/unsafeheader"
    20  )
    21  
    22  type Handle uintptr
    23  type HWND uintptr
    24  
    25  const (
    26  	InvalidHandle = ^Handle(0)
    27  	InvalidHWND   = ^HWND(0)
    28  
    29  	// Flags for DefineDosDevice.
    30  	DDD_EXACT_MATCH_ON_REMOVE = 0x00000004
    31  	DDD_NO_BROADCAST_SYSTEM   = 0x00000008
    32  	DDD_RAW_TARGET_PATH       = 0x00000001
    33  	DDD_REMOVE_DEFINITION     = 0x00000002
    34  
    35  	// Return values for GetDriveType.
    36  	DRIVE_UNKNOWN     = 0
    37  	DRIVE_NO_ROOT_DIR = 1
    38  	DRIVE_REMOVABLE   = 2
    39  	DRIVE_FIXED       = 3
    40  	DRIVE_REMOTE      = 4
    41  	DRIVE_CDROM       = 5
    42  	DRIVE_RAMDISK     = 6
    43  
    44  	// File system flags from GetVolumeInformation and GetVolumeInformationByHandle.
    45  	FILE_CASE_SENSITIVE_SEARCH        = 0x00000001
    46  	FILE_CASE_PRESERVED_NAMES         = 0x00000002
    47  	FILE_FILE_COMPRESSION             = 0x00000010
    48  	FILE_DAX_VOLUME                   = 0x20000000
    49  	FILE_NAMED_STREAMS                = 0x00040000
    50  	FILE_PERSISTENT_ACLS              = 0x00000008
    51  	FILE_READ_ONLY_VOLUME             = 0x00080000
    52  	FILE_SEQUENTIAL_WRITE_ONCE        = 0x00100000
    53  	FILE_SUPPORTS_ENCRYPTION          = 0x00020000
    54  	FILE_SUPPORTS_EXTENDED_ATTRIBUTES = 0x00800000
    55  	FILE_SUPPORTS_HARD_LINKS          = 0x00400000
    56  	FILE_SUPPORTS_OBJECT_IDS          = 0x00010000
    57  	FILE_SUPPORTS_OPEN_BY_FILE_ID     = 0x01000000
    58  	FILE_SUPPORTS_REPARSE_POINTS      = 0x00000080
    59  	FILE_SUPPORTS_SPARSE_FILES        = 0x00000040
    60  	FILE_SUPPORTS_TRANSACTIONS        = 0x00200000
    61  	FILE_SUPPORTS_USN_JOURNAL         = 0x02000000
    62  	FILE_UNICODE_ON_DISK              = 0x00000004
    63  	FILE_VOLUME_IS_COMPRESSED         = 0x00008000
    64  	FILE_VOLUME_QUOTAS                = 0x00000020
    65  
    66  	// Flags for LockFileEx.
    67  	LOCKFILE_FAIL_IMMEDIATELY = 0x00000001
    68  	LOCKFILE_EXCLUSIVE_LOCK   = 0x00000002
    69  
    70  	// Return value of SleepEx and other APC functions
    71  	WAIT_IO_COMPLETION = 0x000000C0
    72  )
    73  
    74  // StringToUTF16 is deprecated. Use UTF16FromString instead.
    75  // If s contains a NUL byte this function panics instead of
    76  // returning an error.
    77  func StringToUTF16(s string) []uint16 {
    78  	a, err := UTF16FromString(s)
    79  	if err != nil {
    80  		panic("windows: string with NUL passed to StringToUTF16")
    81  	}
    82  	return a
    83  }
    84  
    85  // UTF16FromString returns the UTF-16 encoding of the UTF-8 string
    86  // s, with a terminating NUL added. If s contains a NUL byte at any
    87  // location, it returns (nil, syscall.EINVAL).
    88  func UTF16FromString(s string) ([]uint16, error) {
    89  	for i := 0; i < len(s); i++ {
    90  		if s[i] == 0 {
    91  			return nil, syscall.EINVAL
    92  		}
    93  	}
    94  	return utf16.Encode([]rune(s + "\x00")), nil
    95  }
    96  
    97  // UTF16ToString returns the UTF-8 encoding of the UTF-16 sequence s,
    98  // with a terminating NUL and any bytes after the NUL removed.
    99  func UTF16ToString(s []uint16) string {
   100  	for i, v := range s {
   101  		if v == 0 {
   102  			s = s[:i]
   103  			break
   104  		}
   105  	}
   106  	return string(utf16.Decode(s))
   107  }
   108  
   109  // StringToUTF16Ptr is deprecated. Use UTF16PtrFromString instead.
   110  // If s contains a NUL byte this function panics instead of
   111  // returning an error.
   112  func StringToUTF16Ptr(s string) *uint16 { return &StringToUTF16(s)[0] }
   113  
   114  // UTF16PtrFromString returns pointer to the UTF-16 encoding of
   115  // the UTF-8 string s, with a terminating NUL added. If s
   116  // contains a NUL byte at any location, it returns (nil, syscall.EINVAL).
   117  func UTF16PtrFromString(s string) (*uint16, error) {
   118  	a, err := UTF16FromString(s)
   119  	if err != nil {
   120  		return nil, err
   121  	}
   122  	return &a[0], nil
   123  }
   124  
   125  // UTF16PtrToString takes a pointer to a UTF-16 sequence and returns the corresponding UTF-8 encoded string.
   126  // If the pointer is nil, it returns the empty string. It assumes that the UTF-16 sequence is terminated
   127  // at a zero word; if the zero word is not present, the program may crash.
   128  func UTF16PtrToString(p *uint16) string {
   129  	if p == nil {
   130  		return ""
   131  	}
   132  	if *p == 0 {
   133  		return ""
   134  	}
   135  
   136  	// Find NUL terminator.
   137  	n := 0
   138  	for ptr := unsafe.Pointer(p); *(*uint16)(ptr) != 0; n++ {
   139  		ptr = unsafe.Pointer(uintptr(ptr) + unsafe.Sizeof(*p))
   140  	}
   141  
   142  	var s []uint16
   143  	h := (*unsafeheader.Slice)(unsafe.Pointer(&s))
   144  	h.Data = unsafe.Pointer(p)
   145  	h.Len = n
   146  	h.Cap = n
   147  
   148  	return string(utf16.Decode(s))
   149  }
   150  
   151  func Getpagesize() int { return 4096 }
   152  
   153  // NewCallback converts a Go function to a function pointer conforming to the stdcall calling convention.
   154  // This is useful when interoperating with Windows code requiring callbacks.
   155  // The argument is expected to be a function with with one uintptr-sized result. The function must not have arguments with size larger than the size of uintptr.
   156  func NewCallback(fn interface{}) uintptr {
   157  	return syscall.NewCallback(fn)
   158  }
   159  
   160  // NewCallbackCDecl converts a Go function to a function pointer conforming to the cdecl calling convention.
   161  // This is useful when interoperating with Windows code requiring callbacks.
   162  // The argument is expected to be a function with with one uintptr-sized result. The function must not have arguments with size larger than the size of uintptr.
   163  func NewCallbackCDecl(fn interface{}) uintptr {
   164  	return syscall.NewCallbackCDecl(fn)
   165  }
   166  
   167  // windows api calls
   168  
   169  //sys	GetLastError() (lasterr error)
   170  //sys	LoadLibrary(libname string) (handle Handle, err error) = LoadLibraryW
   171  //sys	LoadLibraryEx(libname string, zero Handle, flags uintptr) (handle Handle, err error) = LoadLibraryExW
   172  //sys	FreeLibrary(handle Handle) (err error)
   173  //sys	GetProcAddress(module Handle, procname string) (proc uintptr, err error)
   174  //sys	GetModuleFileName(module Handle, filename *uint16, size uint32) (n uint32, err error) = kernel32.GetModuleFileNameW
   175  //sys	GetModuleHandleEx(flags uint32, moduleName *uint16, module *Handle) (err error) = kernel32.GetModuleHandleExW
   176  //sys	SetDefaultDllDirectories(directoryFlags uint32) (err error)
   177  //sys	SetDllDirectory(path string) (err error) = kernel32.SetDllDirectoryW
   178  //sys	GetVersion() (ver uint32, err error)
   179  //sys	FormatMessage(flags uint32, msgsrc uintptr, msgid uint32, langid uint32, buf []uint16, args *byte) (n uint32, err error) = FormatMessageW
   180  //sys	ExitProcess(exitcode uint32)
   181  //sys	IsWow64Process(handle Handle, isWow64 *bool) (err error) = IsWow64Process
   182  //sys	IsWow64Process2(handle Handle, processMachine *uint16, nativeMachine *uint16) (err error) = IsWow64Process2?
   183  //sys	CreateFile(name *uint16, access uint32, mode uint32, sa *SecurityAttributes, createmode uint32, attrs uint32, templatefile Handle) (handle Handle, err error) [failretval==InvalidHandle] = CreateFileW
   184  //sys	CreateNamedPipe(name *uint16, flags uint32, pipeMode uint32, maxInstances uint32, outSize uint32, inSize uint32, defaultTimeout uint32, sa *SecurityAttributes) (handle Handle, err error)  [failretval==InvalidHandle] = CreateNamedPipeW
   185  //sys	ConnectNamedPipe(pipe Handle, overlapped *Overlapped) (err error)
   186  //sys	GetNamedPipeInfo(pipe Handle, flags *uint32, outSize *uint32, inSize *uint32, maxInstances *uint32) (err error)
   187  //sys	GetNamedPipeHandleState(pipe Handle, state *uint32, curInstances *uint32, maxCollectionCount *uint32, collectDataTimeout *uint32, userName *uint16, maxUserNameSize uint32) (err error) = GetNamedPipeHandleStateW
   188  //sys	SetNamedPipeHandleState(pipe Handle, state *uint32, maxCollectionCount *uint32, collectDataTimeout *uint32) (err error) = SetNamedPipeHandleState
   189  //sys	ReadFile(handle Handle, buf []byte, done *uint32, overlapped *Overlapped) (err error)
   190  //sys	WriteFile(handle Handle, buf []byte, done *uint32, overlapped *Overlapped) (err error)
   191  //sys	GetOverlappedResult(handle Handle, overlapped *Overlapped, done *uint32, wait bool) (err error)
   192  //sys	SetFilePointer(handle Handle, lowoffset int32, highoffsetptr *int32, whence uint32) (newlowoffset uint32, err error) [failretval==0xffffffff]
   193  //sys	CloseHandle(handle Handle) (err error)
   194  //sys	GetStdHandle(stdhandle uint32) (handle Handle, err error) [failretval==InvalidHandle]
   195  //sys	SetStdHandle(stdhandle uint32, handle Handle) (err error)
   196  //sys	findFirstFile1(name *uint16, data *win32finddata1) (handle Handle, err error) [failretval==InvalidHandle] = FindFirstFileW
   197  //sys	findNextFile1(handle Handle, data *win32finddata1) (err error) = FindNextFileW
   198  //sys	FindClose(handle Handle) (err error)
   199  //sys	GetFileInformationByHandle(handle Handle, data *ByHandleFileInformation) (err error)
   200  //sys	GetFileInformationByHandleEx(handle Handle, class uint32, outBuffer *byte, outBufferLen uint32) (err error)
   201  //sys	SetFileInformationByHandle(handle Handle, class uint32, inBuffer *byte, inBufferLen uint32) (err error)
   202  //sys	GetCurrentDirectory(buflen uint32, buf *uint16) (n uint32, err error) = GetCurrentDirectoryW
   203  //sys	SetCurrentDirectory(path *uint16) (err error) = SetCurrentDirectoryW
   204  //sys	CreateDirectory(path *uint16, sa *SecurityAttributes) (err error) = CreateDirectoryW
   205  //sys	RemoveDirectory(path *uint16) (err error) = RemoveDirectoryW
   206  //sys	DeleteFile(path *uint16) (err error) = DeleteFileW
   207  //sys	MoveFile(from *uint16, to *uint16) (err error) = MoveFileW
   208  //sys	MoveFileEx(from *uint16, to *uint16, flags uint32) (err error) = MoveFileExW
   209  //sys	LockFileEx(file Handle, flags uint32, reserved uint32, bytesLow uint32, bytesHigh uint32, overlapped *Overlapped) (err error)
   210  //sys	UnlockFileEx(file Handle, reserved uint32, bytesLow uint32, bytesHigh uint32, overlapped *Overlapped) (err error)
   211  //sys	GetComputerName(buf *uint16, n *uint32) (err error) = GetComputerNameW
   212  //sys	GetComputerNameEx(nametype uint32, buf *uint16, n *uint32) (err error) = GetComputerNameExW
   213  //sys	SetEndOfFile(handle Handle) (err error)
   214  //sys	GetSystemTimeAsFileTime(time *Filetime)
   215  //sys	GetSystemTimePreciseAsFileTime(time *Filetime)
   216  //sys	GetTimeZoneInformation(tzi *Timezoneinformation) (rc uint32, err error) [failretval==0xffffffff]
   217  //sys	CreateIoCompletionPort(filehandle Handle, cphandle Handle, key uintptr, threadcnt uint32) (handle Handle, err error)
   218  //sys	GetQueuedCompletionStatus(cphandle Handle, qty *uint32, key *uintptr, overlapped **Overlapped, timeout uint32) (err error)
   219  //sys	PostQueuedCompletionStatus(cphandle Handle, qty uint32, key uintptr, overlapped *Overlapped) (err error)
   220  //sys	CancelIo(s Handle) (err error)
   221  //sys	CancelIoEx(s Handle, o *Overlapped) (err error)
   222  //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
   223  //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
   224  //sys   initializeProcThreadAttributeList(attrlist *ProcThreadAttributeList, attrcount uint32, flags uint32, size *uintptr) (err error) = InitializeProcThreadAttributeList
   225  //sys   deleteProcThreadAttributeList(attrlist *ProcThreadAttributeList) = DeleteProcThreadAttributeList
   226  //sys   updateProcThreadAttribute(attrlist *ProcThreadAttributeList, flags uint32, attr uintptr, value unsafe.Pointer, size uintptr, prevvalue unsafe.Pointer, returnedsize *uintptr) (err error) = UpdateProcThreadAttribute
   227  //sys	OpenProcess(desiredAccess uint32, inheritHandle bool, processId uint32) (handle Handle, err error)
   228  //sys	ShellExecute(hwnd Handle, verb *uint16, file *uint16, args *uint16, cwd *uint16, showCmd int32) (err error) [failretval<=32] = shell32.ShellExecuteW
   229  //sys	GetWindowThreadProcessId(hwnd HWND, pid *uint32) (tid uint32, err error) = user32.GetWindowThreadProcessId
   230  //sys	GetShellWindow() (shellWindow HWND) = user32.GetShellWindow
   231  //sys	MessageBox(hwnd HWND, text *uint16, caption *uint16, boxtype uint32) (ret int32, err error) [failretval==0] = user32.MessageBoxW
   232  //sys	ExitWindowsEx(flags uint32, reason uint32) (err error) = user32.ExitWindowsEx
   233  //sys	shGetKnownFolderPath(id *KNOWNFOLDERID, flags uint32, token Token, path **uint16) (ret error) = shell32.SHGetKnownFolderPath
   234  //sys	TerminateProcess(handle Handle, exitcode uint32) (err error)
   235  //sys	GetExitCodeProcess(handle Handle, exitcode *uint32) (err error)
   236  //sys	GetStartupInfo(startupInfo *StartupInfo) (err error) = GetStartupInfoW
   237  //sys	GetProcessTimes(handle Handle, creationTime *Filetime, exitTime *Filetime, kernelTime *Filetime, userTime *Filetime) (err error)
   238  //sys	DuplicateHandle(hSourceProcessHandle Handle, hSourceHandle Handle, hTargetProcessHandle Handle, lpTargetHandle *Handle, dwDesiredAccess uint32, bInheritHandle bool, dwOptions uint32) (err error)
   239  //sys	WaitForSingleObject(handle Handle, waitMilliseconds uint32) (event uint32, err error) [failretval==0xffffffff]
   240  //sys	waitForMultipleObjects(count uint32, handles uintptr, waitAll bool, waitMilliseconds uint32) (event uint32, err error) [failretval==0xffffffff] = WaitForMultipleObjects
   241  //sys	GetTempPath(buflen uint32, buf *uint16) (n uint32, err error) = GetTempPathW
   242  //sys	CreatePipe(readhandle *Handle, writehandle *Handle, sa *SecurityAttributes, size uint32) (err error)
   243  //sys	GetFileType(filehandle Handle) (n uint32, err error)
   244  //sys	CryptAcquireContext(provhandle *Handle, container *uint16, provider *uint16, provtype uint32, flags uint32) (err error) = advapi32.CryptAcquireContextW
   245  //sys	CryptReleaseContext(provhandle Handle, flags uint32) (err error) = advapi32.CryptReleaseContext
   246  //sys	CryptGenRandom(provhandle Handle, buflen uint32, buf *byte) (err error) = advapi32.CryptGenRandom
   247  //sys	GetEnvironmentStrings() (envs *uint16, err error) [failretval==nil] = kernel32.GetEnvironmentStringsW
   248  //sys	FreeEnvironmentStrings(envs *uint16) (err error) = kernel32.FreeEnvironmentStringsW
   249  //sys	GetEnvironmentVariable(name *uint16, buffer *uint16, size uint32) (n uint32, err error) = kernel32.GetEnvironmentVariableW
   250  //sys	SetEnvironmentVariable(name *uint16, value *uint16) (err error) = kernel32.SetEnvironmentVariableW
   251  //sys	ExpandEnvironmentStrings(src *uint16, dst *uint16, size uint32) (n uint32, err error) = kernel32.ExpandEnvironmentStringsW
   252  //sys	CreateEnvironmentBlock(block **uint16, token Token, inheritExisting bool) (err error) = userenv.CreateEnvironmentBlock
   253  //sys	DestroyEnvironmentBlock(block *uint16) (err error) = userenv.DestroyEnvironmentBlock
   254  //sys	getTickCount64() (ms uint64) = kernel32.GetTickCount64
   255  //sys	SetFileTime(handle Handle, ctime *Filetime, atime *Filetime, wtime *Filetime) (err error)
   256  //sys	GetFileAttributes(name *uint16) (attrs uint32, err error) [failretval==INVALID_FILE_ATTRIBUTES] = kernel32.GetFileAttributesW
   257  //sys	SetFileAttributes(name *uint16, attrs uint32) (err error) = kernel32.SetFileAttributesW
   258  //sys	GetFileAttributesEx(name *uint16, level uint32, info *byte) (err error) = kernel32.GetFileAttributesExW
   259  //sys	GetCommandLine() (cmd *uint16) = kernel32.GetCommandLineW
   260  //sys	CommandLineToArgv(cmd *uint16, argc *int32) (argv *[8192]*[8192]uint16, err error) [failretval==nil] = shell32.CommandLineToArgvW
   261  //sys	LocalFree(hmem Handle) (handle Handle, err error) [failretval!=0]
   262  //sys	LocalAlloc(flags uint32, length uint32) (ptr uintptr, err error)
   263  //sys	SetHandleInformation(handle Handle, mask uint32, flags uint32) (err error)
   264  //sys	FlushFileBuffers(handle Handle) (err error)
   265  //sys	GetFullPathName(path *uint16, buflen uint32, buf *uint16, fname **uint16) (n uint32, err error) = kernel32.GetFullPathNameW
   266  //sys	GetLongPathName(path *uint16, buf *uint16, buflen uint32) (n uint32, err error) = kernel32.GetLongPathNameW
   267  //sys	GetShortPathName(longpath *uint16, shortpath *uint16, buflen uint32) (n uint32, err error) = kernel32.GetShortPathNameW
   268  //sys	GetFinalPathNameByHandle(file Handle, filePath *uint16, filePathSize uint32, flags uint32) (n uint32, err error) = kernel32.GetFinalPathNameByHandleW
   269  //sys	CreateFileMapping(fhandle Handle, sa *SecurityAttributes, prot uint32, maxSizeHigh uint32, maxSizeLow uint32, name *uint16) (handle Handle, err error) [failretval == 0 || e1 == ERROR_ALREADY_EXISTS] = kernel32.CreateFileMappingW
   270  //sys	MapViewOfFile(handle Handle, access uint32, offsetHigh uint32, offsetLow uint32, length uintptr) (addr uintptr, err error)
   271  //sys	UnmapViewOfFile(addr uintptr) (err error)
   272  //sys	FlushViewOfFile(addr uintptr, length uintptr) (err error)
   273  //sys	VirtualLock(addr uintptr, length uintptr) (err error)
   274  //sys	VirtualUnlock(addr uintptr, length uintptr) (err error)
   275  //sys	VirtualAlloc(address uintptr, size uintptr, alloctype uint32, protect uint32) (value uintptr, err error) = kernel32.VirtualAlloc
   276  //sys	VirtualFree(address uintptr, size uintptr, freetype uint32) (err error) = kernel32.VirtualFree
   277  //sys	VirtualProtect(address uintptr, size uintptr, newprotect uint32, oldprotect *uint32) (err error) = kernel32.VirtualProtect
   278  //sys	VirtualProtectEx(process Handle, address uintptr, size uintptr, newProtect uint32, oldProtect *uint32) (err error) = kernel32.VirtualProtectEx
   279  //sys	VirtualQuery(address uintptr, buffer *MemoryBasicInformation, length uintptr) (err error) = kernel32.VirtualQuery
   280  //sys	VirtualQueryEx(process Handle, address uintptr, buffer *MemoryBasicInformation, length uintptr) (err error) = kernel32.VirtualQueryEx
   281  //sys	ReadProcessMemory(process Handle, baseAddress uintptr, buffer *byte, size uintptr, numberOfBytesRead *uintptr) (err error) = kernel32.ReadProcessMemory
   282  //sys	WriteProcessMemory(process Handle, baseAddress uintptr, buffer *byte, size uintptr, numberOfBytesWritten *uintptr) (err error) = kernel32.WriteProcessMemory
   283  //sys	TransmitFile(s Handle, handle Handle, bytesToWrite uint32, bytsPerSend uint32, overlapped *Overlapped, transmitFileBuf *TransmitFileBuffers, flags uint32) (err error) = mswsock.TransmitFile
   284  //sys	ReadDirectoryChanges(handle Handle, buf *byte, buflen uint32, watchSubTree bool, mask uint32, retlen *uint32, overlapped *Overlapped, completionRoutine uintptr) (err error) = kernel32.ReadDirectoryChangesW
   285  //sys	FindFirstChangeNotification(path string, watchSubtree bool, notifyFilter uint32) (handle Handle, err error) [failretval==InvalidHandle] = kernel32.FindFirstChangeNotificationW
   286  //sys	FindNextChangeNotification(handle Handle) (err error)
   287  //sys	FindCloseChangeNotification(handle Handle) (err error)
   288  //sys	CertOpenSystemStore(hprov Handle, name *uint16) (store Handle, err error) = crypt32.CertOpenSystemStoreW
   289  //sys	CertOpenStore(storeProvider uintptr, msgAndCertEncodingType uint32, cryptProv uintptr, flags uint32, para uintptr) (handle Handle, err error) = crypt32.CertOpenStore
   290  //sys	CertEnumCertificatesInStore(store Handle, prevContext *CertContext) (context *CertContext, err error) [failretval==nil] = crypt32.CertEnumCertificatesInStore
   291  //sys	CertAddCertificateContextToStore(store Handle, certContext *CertContext, addDisposition uint32, storeContext **CertContext) (err error) = crypt32.CertAddCertificateContextToStore
   292  //sys	CertCloseStore(store Handle, flags uint32) (err error) = crypt32.CertCloseStore
   293  //sys	CertDeleteCertificateFromStore(certContext *CertContext) (err error) = crypt32.CertDeleteCertificateFromStore
   294  //sys	CertDuplicateCertificateContext(certContext *CertContext) (dupContext *CertContext) = crypt32.CertDuplicateCertificateContext
   295  //sys	PFXImportCertStore(pfx *CryptDataBlob, password *uint16, flags uint32) (store Handle, err error) = crypt32.PFXImportCertStore
   296  //sys	CertGetCertificateChain(engine Handle, leaf *CertContext, time *Filetime, additionalStore Handle, para *CertChainPara, flags uint32, reserved uintptr, chainCtx **CertChainContext) (err error) = crypt32.CertGetCertificateChain
   297  //sys	CertFreeCertificateChain(ctx *CertChainContext) = crypt32.CertFreeCertificateChain
   298  //sys	CertCreateCertificateContext(certEncodingType uint32, certEncoded *byte, encodedLen uint32) (context *CertContext, err error) [failretval==nil] = crypt32.CertCreateCertificateContext
   299  //sys	CertFreeCertificateContext(ctx *CertContext) (err error) = crypt32.CertFreeCertificateContext
   300  //sys	CertVerifyCertificateChainPolicy(policyOID uintptr, chain *CertChainContext, para *CertChainPolicyPara, status *CertChainPolicyStatus) (err error) = crypt32.CertVerifyCertificateChainPolicy
   301  //sys	CertGetNameString(certContext *CertContext, nameType uint32, flags uint32, typePara unsafe.Pointer, name *uint16, size uint32) (chars uint32) = crypt32.CertGetNameStringW
   302  //sys	CertFindExtension(objId *byte, countExtensions uint32, extensions *CertExtension) (ret *CertExtension) = crypt32.CertFindExtension
   303  //sys   CertFindCertificateInStore(store Handle, certEncodingType uint32, findFlags uint32, findType uint32, findPara unsafe.Pointer, prevCertContext *CertContext) (cert *CertContext, err error) [failretval==nil] = crypt32.CertFindCertificateInStore
   304  //sys   CertFindChainInStore(store Handle, certEncodingType uint32, findFlags uint32, findType uint32, findPara unsafe.Pointer, prevChainContext *CertChainContext) (certchain *CertChainContext, err error) [failretval==nil] = crypt32.CertFindChainInStore
   305  //sys   CryptAcquireCertificatePrivateKey(cert *CertContext, flags uint32, parameters unsafe.Pointer, cryptProvOrNCryptKey *Handle, keySpec *uint32, callerFreeProvOrNCryptKey *bool) (err error) = crypt32.CryptAcquireCertificatePrivateKey
   306  //sys	CryptQueryObject(objectType uint32, object unsafe.Pointer, expectedContentTypeFlags uint32, expectedFormatTypeFlags uint32, flags uint32, msgAndCertEncodingType *uint32, contentType *uint32, formatType *uint32, certStore *Handle, msg *Handle, context *unsafe.Pointer) (err error) = crypt32.CryptQueryObject
   307  //sys	CryptDecodeObject(encodingType uint32, structType *byte, encodedBytes *byte, lenEncodedBytes uint32, flags uint32, decoded unsafe.Pointer, decodedLen *uint32) (err error) = crypt32.CryptDecodeObject
   308  //sys	CryptProtectData(dataIn *DataBlob, name *uint16, optionalEntropy *DataBlob, reserved uintptr, promptStruct *CryptProtectPromptStruct, flags uint32, dataOut *DataBlob) (err error) = crypt32.CryptProtectData
   309  //sys	CryptUnprotectData(dataIn *DataBlob, name **uint16, optionalEntropy *DataBlob, reserved uintptr, promptStruct *CryptProtectPromptStruct, flags uint32, dataOut *DataBlob) (err error) = crypt32.CryptUnprotectData
   310  //sys	WinVerifyTrustEx(hwnd HWND, actionId *GUID, data *WinTrustData) (ret error) = wintrust.WinVerifyTrustEx
   311  //sys	RegOpenKeyEx(key Handle, subkey *uint16, options uint32, desiredAccess uint32, result *Handle) (regerrno error) = advapi32.RegOpenKeyExW
   312  //sys	RegCloseKey(key Handle) (regerrno error) = advapi32.RegCloseKey
   313  //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
   314  //sys	RegEnumKeyEx(key Handle, index uint32, name *uint16, nameLen *uint32, reserved *uint32, class *uint16, classLen *uint32, lastWriteTime *Filetime) (regerrno error) = advapi32.RegEnumKeyExW
   315  //sys	RegQueryValueEx(key Handle, name *uint16, reserved *uint32, valtype *uint32, buf *byte, buflen *uint32) (regerrno error) = advapi32.RegQueryValueExW
   316  //sys	RegNotifyChangeKeyValue(key Handle, watchSubtree bool, notifyFilter uint32, event Handle, asynchronous bool) (regerrno error) = advapi32.RegNotifyChangeKeyValue
   317  //sys	GetCurrentProcessId() (pid uint32) = kernel32.GetCurrentProcessId
   318  //sys	ProcessIdToSessionId(pid uint32, sessionid *uint32) (err error) = kernel32.ProcessIdToSessionId
   319  //sys	GetConsoleMode(console Handle, mode *uint32) (err error) = kernel32.GetConsoleMode
   320  //sys	SetConsoleMode(console Handle, mode uint32) (err error) = kernel32.SetConsoleMode
   321  //sys	GetConsoleScreenBufferInfo(console Handle, info *ConsoleScreenBufferInfo) (err error) = kernel32.GetConsoleScreenBufferInfo
   322  //sys	setConsoleCursorPosition(console Handle, position uint32) (err error) = kernel32.SetConsoleCursorPosition
   323  //sys	WriteConsole(console Handle, buf *uint16, towrite uint32, written *uint32, reserved *byte) (err error) = kernel32.WriteConsoleW
   324  //sys	ReadConsole(console Handle, buf *uint16, toread uint32, read *uint32, inputControl *byte) (err error) = kernel32.ReadConsoleW
   325  //sys	CreateToolhelp32Snapshot(flags uint32, processId uint32) (handle Handle, err error) [failretval==InvalidHandle] = kernel32.CreateToolhelp32Snapshot
   326  //sys	Module32First(snapshot Handle, moduleEntry *ModuleEntry32) (err error) = kernel32.Module32FirstW
   327  //sys	Module32Next(snapshot Handle, moduleEntry *ModuleEntry32) (err error) = kernel32.Module32NextW
   328  //sys	Process32First(snapshot Handle, procEntry *ProcessEntry32) (err error) = kernel32.Process32FirstW
   329  //sys	Process32Next(snapshot Handle, procEntry *ProcessEntry32) (err error) = kernel32.Process32NextW
   330  //sys	Thread32First(snapshot Handle, threadEntry *ThreadEntry32) (err error)
   331  //sys	Thread32Next(snapshot Handle, threadEntry *ThreadEntry32) (err error)
   332  //sys	DeviceIoControl(handle Handle, ioControlCode uint32, inBuffer *byte, inBufferSize uint32, outBuffer *byte, outBufferSize uint32, bytesReturned *uint32, overlapped *Overlapped) (err error)
   333  // This function returns 1 byte BOOLEAN rather than the 4 byte BOOL.
   334  //sys	CreateSymbolicLink(symlinkfilename *uint16, targetfilename *uint16, flags uint32) (err error) [failretval&0xff==0] = CreateSymbolicLinkW
   335  //sys	CreateHardLink(filename *uint16, existingfilename *uint16, reserved uintptr) (err error) [failretval&0xff==0] = CreateHardLinkW
   336  //sys	GetCurrentThreadId() (id uint32)
   337  //sys	CreateEvent(eventAttrs *SecurityAttributes, manualReset uint32, initialState uint32, name *uint16) (handle Handle, err error) [failretval == 0 || e1 == ERROR_ALREADY_EXISTS] = kernel32.CreateEventW
   338  //sys	CreateEventEx(eventAttrs *SecurityAttributes, name *uint16, flags uint32, desiredAccess uint32) (handle Handle, err error) [failretval == 0 || e1 == ERROR_ALREADY_EXISTS] = kernel32.CreateEventExW
   339  //sys	OpenEvent(desiredAccess uint32, inheritHandle bool, name *uint16) (handle Handle, err error) = kernel32.OpenEventW
   340  //sys	SetEvent(event Handle) (err error) = kernel32.SetEvent
   341  //sys	ResetEvent(event Handle) (err error) = kernel32.ResetEvent
   342  //sys	PulseEvent(event Handle) (err error) = kernel32.PulseEvent
   343  //sys	CreateMutex(mutexAttrs *SecurityAttributes, initialOwner bool, name *uint16) (handle Handle, err error) [failretval == 0 || e1 == ERROR_ALREADY_EXISTS] = kernel32.CreateMutexW
   344  //sys	CreateMutexEx(mutexAttrs *SecurityAttributes, name *uint16, flags uint32, desiredAccess uint32) (handle Handle, err error) [failretval == 0 || e1 == ERROR_ALREADY_EXISTS] = kernel32.CreateMutexExW
   345  //sys	OpenMutex(desiredAccess uint32, inheritHandle bool, name *uint16) (handle Handle, err error) = kernel32.OpenMutexW
   346  //sys	ReleaseMutex(mutex Handle) (err error) = kernel32.ReleaseMutex
   347  //sys	SleepEx(milliseconds uint32, alertable bool) (ret uint32) = kernel32.SleepEx
   348  //sys	CreateJobObject(jobAttr *SecurityAttributes, name *uint16) (handle Handle, err error) = kernel32.CreateJobObjectW
   349  //sys	AssignProcessToJobObject(job Handle, process Handle) (err error) = kernel32.AssignProcessToJobObject
   350  //sys	TerminateJobObject(job Handle, exitCode uint32) (err error) = kernel32.TerminateJobObject
   351  //sys	SetErrorMode(mode uint32) (ret uint32) = kernel32.SetErrorMode
   352  //sys	ResumeThread(thread Handle) (ret uint32, err error) [failretval==0xffffffff] = kernel32.ResumeThread
   353  //sys	SetPriorityClass(process Handle, priorityClass uint32) (err error) = kernel32.SetPriorityClass
   354  //sys	GetPriorityClass(process Handle) (ret uint32, err error) = kernel32.GetPriorityClass
   355  //sys	QueryInformationJobObject(job Handle, JobObjectInformationClass int32, JobObjectInformation uintptr, JobObjectInformationLength uint32, retlen *uint32) (err error) = kernel32.QueryInformationJobObject
   356  //sys	SetInformationJobObject(job Handle, JobObjectInformationClass uint32, JobObjectInformation uintptr, JobObjectInformationLength uint32) (ret int, err error)
   357  //sys	GenerateConsoleCtrlEvent(ctrlEvent uint32, processGroupID uint32) (err error)
   358  //sys	GetProcessId(process Handle) (id uint32, err error)
   359  //sys	QueryFullProcessImageName(proc Handle, flags uint32, exeName *uint16, size *uint32) (err error) = kernel32.QueryFullProcessImageNameW
   360  //sys	OpenThread(desiredAccess uint32, inheritHandle bool, threadId uint32) (handle Handle, err error)
   361  //sys	SetProcessPriorityBoost(process Handle, disable bool) (err error) = kernel32.SetProcessPriorityBoost
   362  //sys	GetProcessWorkingSetSizeEx(hProcess Handle, lpMinimumWorkingSetSize *uintptr, lpMaximumWorkingSetSize *uintptr, flags *uint32)
   363  //sys	SetProcessWorkingSetSizeEx(hProcess Handle, dwMinimumWorkingSetSize uintptr, dwMaximumWorkingSetSize uintptr, flags uint32) (err error)
   364  //sys	GetCommTimeouts(handle Handle, timeouts *CommTimeouts) (err error)
   365  //sys	SetCommTimeouts(handle Handle, timeouts *CommTimeouts) (err error)
   366  
   367  // Volume Management Functions
   368  //sys	DefineDosDevice(flags uint32, deviceName *uint16, targetPath *uint16) (err error) = DefineDosDeviceW
   369  //sys	DeleteVolumeMountPoint(volumeMountPoint *uint16) (err error) = DeleteVolumeMountPointW
   370  //sys	FindFirstVolume(volumeName *uint16, bufferLength uint32) (handle Handle, err error) [failretval==InvalidHandle] = FindFirstVolumeW
   371  //sys	FindFirstVolumeMountPoint(rootPathName *uint16, volumeMountPoint *uint16, bufferLength uint32) (handle Handle, err error) [failretval==InvalidHandle] = FindFirstVolumeMountPointW
   372  //sys	FindNextVolume(findVolume Handle, volumeName *uint16, bufferLength uint32) (err error) = FindNextVolumeW
   373  //sys	FindNextVolumeMountPoint(findVolumeMountPoint Handle, volumeMountPoint *uint16, bufferLength uint32) (err error) = FindNextVolumeMountPointW
   374  //sys	FindVolumeClose(findVolume Handle) (err error)
   375  //sys	FindVolumeMountPointClose(findVolumeMountPoint Handle) (err error)
   376  //sys	GetDiskFreeSpaceEx(directoryName *uint16, freeBytesAvailableToCaller *uint64, totalNumberOfBytes *uint64, totalNumberOfFreeBytes *uint64) (err error) = GetDiskFreeSpaceExW
   377  //sys	GetDriveType(rootPathName *uint16) (driveType uint32) = GetDriveTypeW
   378  //sys	GetLogicalDrives() (drivesBitMask uint32, err error) [failretval==0]
   379  //sys	GetLogicalDriveStrings(bufferLength uint32, buffer *uint16) (n uint32, err error) [failretval==0] = GetLogicalDriveStringsW
   380  //sys	GetVolumeInformation(rootPathName *uint16, volumeNameBuffer *uint16, volumeNameSize uint32, volumeNameSerialNumber *uint32, maximumComponentLength *uint32, fileSystemFlags *uint32, fileSystemNameBuffer *uint16, fileSystemNameSize uint32) (err error) = GetVolumeInformationW
   381  //sys	GetVolumeInformationByHandle(file Handle, volumeNameBuffer *uint16, volumeNameSize uint32, volumeNameSerialNumber *uint32, maximumComponentLength *uint32, fileSystemFlags *uint32, fileSystemNameBuffer *uint16, fileSystemNameSize uint32) (err error) = GetVolumeInformationByHandleW
   382  //sys	GetVolumeNameForVolumeMountPoint(volumeMountPoint *uint16, volumeName *uint16, bufferlength uint32) (err error) = GetVolumeNameForVolumeMountPointW
   383  //sys	GetVolumePathName(fileName *uint16, volumePathName *uint16, bufferLength uint32) (err error) = GetVolumePathNameW
   384  //sys	GetVolumePathNamesForVolumeName(volumeName *uint16, volumePathNames *uint16, bufferLength uint32, returnLength *uint32) (err error) = GetVolumePathNamesForVolumeNameW
   385  //sys	QueryDosDevice(deviceName *uint16, targetPath *uint16, max uint32) (n uint32, err error) [failretval==0] = QueryDosDeviceW
   386  //sys	SetVolumeLabel(rootPathName *uint16, volumeName *uint16) (err error) = SetVolumeLabelW
   387  //sys	SetVolumeMountPoint(volumeMountPoint *uint16, volumeName *uint16) (err error) = SetVolumeMountPointW
   388  //sys	InitiateSystemShutdownEx(machineName *uint16, message *uint16, timeout uint32, forceAppsClosed bool, rebootAfterShutdown bool, reason uint32) (err error) = advapi32.InitiateSystemShutdownExW
   389  //sys	SetProcessShutdownParameters(level uint32, flags uint32) (err error) = kernel32.SetProcessShutdownParameters
   390  //sys	GetProcessShutdownParameters(level *uint32, flags *uint32) (err error) = kernel32.GetProcessShutdownParameters
   391  //sys	clsidFromString(lpsz *uint16, pclsid *GUID) (ret error) = ole32.CLSIDFromString
   392  //sys	stringFromGUID2(rguid *GUID, lpsz *uint16, cchMax int32) (chars int32) = ole32.StringFromGUID2
   393  //sys	coCreateGuid(pguid *GUID) (ret error) = ole32.CoCreateGuid
   394  //sys	CoTaskMemFree(address unsafe.Pointer) = ole32.CoTaskMemFree
   395  //sys	CoInitializeEx(reserved uintptr, coInit uint32) (ret error) = ole32.CoInitializeEx
   396  //sys	CoUninitialize() = ole32.CoUninitialize
   397  //sys	CoGetObject(name *uint16, bindOpts *BIND_OPTS3, guid *GUID, functionTable **uintptr) (ret error) = ole32.CoGetObject
   398  //sys	getProcessPreferredUILanguages(flags uint32, numLanguages *uint32, buf *uint16, bufSize *uint32) (err error) = kernel32.GetProcessPreferredUILanguages
   399  //sys	getThreadPreferredUILanguages(flags uint32, numLanguages *uint32, buf *uint16, bufSize *uint32) (err error) = kernel32.GetThreadPreferredUILanguages
   400  //sys	getUserPreferredUILanguages(flags uint32, numLanguages *uint32, buf *uint16, bufSize *uint32) (err error) = kernel32.GetUserPreferredUILanguages
   401  //sys	getSystemPreferredUILanguages(flags uint32, numLanguages *uint32, buf *uint16, bufSize *uint32) (err error) = kernel32.GetSystemPreferredUILanguages
   402  //sys	findResource(module Handle, name uintptr, resType uintptr) (resInfo Handle, err error) = kernel32.FindResourceW
   403  //sys	SizeofResource(module Handle, resInfo Handle) (size uint32, err error) = kernel32.SizeofResource
   404  //sys	LoadResource(module Handle, resInfo Handle) (resData Handle, err error) = kernel32.LoadResource
   405  //sys	LockResource(resData Handle) (addr uintptr, err error) = kernel32.LockResource
   406  
   407  // Version APIs
   408  //sys	GetFileVersionInfoSize(filename string, zeroHandle *Handle) (bufSize uint32, err error) = version.GetFileVersionInfoSizeW
   409  //sys	GetFileVersionInfo(filename string, handle uint32, bufSize uint32, buffer unsafe.Pointer) (err error) = version.GetFileVersionInfoW
   410  //sys	VerQueryValue(block unsafe.Pointer, subBlock string, pointerToBufferPointer unsafe.Pointer, bufSize *uint32) (err error) = version.VerQueryValueW
   411  
   412  // Process Status API (PSAPI)
   413  //sys	EnumProcesses(processIds []uint32, bytesReturned *uint32) (err error) = psapi.EnumProcesses
   414  //sys	EnumProcessModules(process Handle, module *Handle, cb uint32, cbNeeded *uint32) (err error) = psapi.EnumProcessModules
   415  //sys	EnumProcessModulesEx(process Handle, module *Handle, cb uint32, cbNeeded *uint32, filterFlag uint32) (err error) = psapi.EnumProcessModulesEx
   416  //sys	GetModuleInformation(process Handle, module Handle, modinfo *ModuleInfo, cb uint32) (err error) = psapi.GetModuleInformation
   417  //sys	GetModuleFileNameEx(process Handle, module Handle, filename *uint16, size uint32) (err error) = psapi.GetModuleFileNameExW
   418  //sys	GetModuleBaseName(process Handle, module Handle, baseName *uint16, size uint32) (err error) = psapi.GetModuleBaseNameW
   419  
   420  // NT Native APIs
   421  //sys	rtlNtStatusToDosErrorNoTeb(ntstatus NTStatus) (ret syscall.Errno) = ntdll.RtlNtStatusToDosErrorNoTeb
   422  //sys	rtlGetVersion(info *OsVersionInfoEx) (ntstatus error) = ntdll.RtlGetVersion
   423  //sys	rtlGetNtVersionNumbers(majorVersion *uint32, minorVersion *uint32, buildNumber *uint32) = ntdll.RtlGetNtVersionNumbers
   424  //sys	RtlGetCurrentPeb() (peb *PEB) = ntdll.RtlGetCurrentPeb
   425  //sys	RtlInitUnicodeString(destinationString *NTUnicodeString, sourceString *uint16) = ntdll.RtlInitUnicodeString
   426  //sys	RtlInitString(destinationString *NTString, sourceString *byte) = ntdll.RtlInitString
   427  //sys	NtCreateFile(handle *Handle, access uint32, oa *OBJECT_ATTRIBUTES, iosb *IO_STATUS_BLOCK, allocationSize *int64, attributes uint32, share uint32, disposition uint32, options uint32, eabuffer uintptr, ealength uint32) (ntstatus error) = ntdll.NtCreateFile
   428  //sys	NtCreateNamedPipeFile(pipe *Handle, access uint32, oa *OBJECT_ATTRIBUTES, iosb *IO_STATUS_BLOCK, share uint32, disposition uint32, options uint32, typ uint32, readMode uint32, completionMode uint32, maxInstances uint32, inboundQuota uint32, outputQuota uint32, timeout *int64) (ntstatus error) = ntdll.NtCreateNamedPipeFile
   429  //sys	NtSetInformationFile(handle Handle, iosb *IO_STATUS_BLOCK, inBuffer *byte, inBufferLen uint32, class uint32) (ntstatus error) = ntdll.NtSetInformationFile
   430  //sys	RtlDosPathNameToNtPathName(dosName *uint16, ntName *NTUnicodeString, ntFileNamePart *uint16, relativeName *RTL_RELATIVE_NAME) (ntstatus error) = ntdll.RtlDosPathNameToNtPathName_U_WithStatus
   431  //sys	RtlDosPathNameToRelativeNtPathName(dosName *uint16, ntName *NTUnicodeString, ntFileNamePart *uint16, relativeName *RTL_RELATIVE_NAME) (ntstatus error) = ntdll.RtlDosPathNameToRelativeNtPathName_U_WithStatus
   432  //sys	RtlDefaultNpAcl(acl **ACL) (ntstatus error) = ntdll.RtlDefaultNpAcl
   433  //sys	NtQueryInformationProcess(proc Handle, procInfoClass int32, procInfo unsafe.Pointer, procInfoLen uint32, retLen *uint32) (ntstatus error) = ntdll.NtQueryInformationProcess
   434  //sys	NtSetInformationProcess(proc Handle, procInfoClass int32, procInfo unsafe.Pointer, procInfoLen uint32) (ntstatus error) = ntdll.NtSetInformationProcess
   435  //sys	NtQuerySystemInformation(sysInfoClass int32, sysInfo unsafe.Pointer, sysInfoLen uint32, retLen *uint32) (ntstatus error) = ntdll.NtQuerySystemInformation
   436  //sys	NtSetSystemInformation(sysInfoClass int32, sysInfo unsafe.Pointer, sysInfoLen uint32) (ntstatus error) = ntdll.NtSetSystemInformation
   437  //sys	RtlAddFunctionTable(functionTable *RUNTIME_FUNCTION, entryCount uint32, baseAddress uintptr) (ret bool) = ntdll.RtlAddFunctionTable
   438  //sys	RtlDeleteFunctionTable(functionTable *RUNTIME_FUNCTION) (ret bool) = ntdll.RtlDeleteFunctionTable
   439  
   440  // syscall interface implementation for other packages
   441  
   442  // GetCurrentProcess returns the handle for the current process.
   443  // It is a pseudo handle that does not need to be closed.
   444  // The returned error is always nil.
   445  //
   446  // Deprecated: use CurrentProcess for the same Handle without the nil
   447  // error.
   448  func GetCurrentProcess() (Handle, error) {
   449  	return CurrentProcess(), nil
   450  }
   451  
   452  // CurrentProcess returns the handle for the current process.
   453  // It is a pseudo handle that does not need to be closed.
   454  func CurrentProcess() Handle { return Handle(^uintptr(1 - 1)) }
   455  
   456  // GetCurrentThread returns the handle for the current thread.
   457  // It is a pseudo handle that does not need to be closed.
   458  // The returned error is always nil.
   459  //
   460  // Deprecated: use CurrentThread for the same Handle without the nil
   461  // error.
   462  func GetCurrentThread() (Handle, error) {
   463  	return CurrentThread(), nil
   464  }
   465  
   466  // CurrentThread returns the handle for the current thread.
   467  // It is a pseudo handle that does not need to be closed.
   468  func CurrentThread() Handle { return Handle(^uintptr(2 - 1)) }
   469  
   470  // GetProcAddressByOrdinal retrieves the address of the exported
   471  // function from module by ordinal.
   472  func GetProcAddressByOrdinal(module Handle, ordinal uintptr) (proc uintptr, err error) {
   473  	r0, _, e1 := syscall.Syscall(procGetProcAddress.Addr(), 2, uintptr(module), ordinal, 0)
   474  	proc = uintptr(r0)
   475  	if proc == 0 {
   476  		err = errnoErr(e1)
   477  	}
   478  	return
   479  }
   480  
   481  func Exit(code int) { ExitProcess(uint32(code)) }
   482  
   483  func makeInheritSa() *SecurityAttributes {
   484  	var sa SecurityAttributes
   485  	sa.Length = uint32(unsafe.Sizeof(sa))
   486  	sa.InheritHandle = 1
   487  	return &sa
   488  }
   489  
   490  func Open(path string, mode int, perm uint32) (fd Handle, err error) {
   491  	if len(path) == 0 {
   492  		return InvalidHandle, ERROR_FILE_NOT_FOUND
   493  	}
   494  	pathp, err := UTF16PtrFromString(path)
   495  	if err != nil {
   496  		return InvalidHandle, err
   497  	}
   498  	var access uint32
   499  	switch mode & (O_RDONLY | O_WRONLY | O_RDWR) {
   500  	case O_RDONLY:
   501  		access = GENERIC_READ
   502  	case O_WRONLY:
   503  		access = GENERIC_WRITE
   504  	case O_RDWR:
   505  		access = GENERIC_READ | GENERIC_WRITE
   506  	}
   507  	if mode&O_CREAT != 0 {
   508  		access |= GENERIC_WRITE
   509  	}
   510  	if mode&O_APPEND != 0 {
   511  		access &^= GENERIC_WRITE
   512  		access |= FILE_APPEND_DATA
   513  	}
   514  	sharemode := uint32(FILE_SHARE_READ | FILE_SHARE_WRITE)
   515  	var sa *SecurityAttributes
   516  	if mode&O_CLOEXEC == 0 {
   517  		sa = makeInheritSa()
   518  	}
   519  	var createmode uint32
   520  	switch {
   521  	case mode&(O_CREAT|O_EXCL) == (O_CREAT | O_EXCL):
   522  		createmode = CREATE_NEW
   523  	case mode&(O_CREAT|O_TRUNC) == (O_CREAT | O_TRUNC):
   524  		createmode = CREATE_ALWAYS
   525  	case mode&O_CREAT == O_CREAT:
   526  		createmode = OPEN_ALWAYS
   527  	case mode&O_TRUNC == O_TRUNC:
   528  		createmode = TRUNCATE_EXISTING
   529  	default:
   530  		createmode = OPEN_EXISTING
   531  	}
   532  	var attrs uint32 = FILE_ATTRIBUTE_NORMAL
   533  	if perm&S_IWRITE == 0 {
   534  		attrs = FILE_ATTRIBUTE_READONLY
   535  	}
   536  	h, e := CreateFile(pathp, access, sharemode, sa, createmode, attrs, 0)
   537  	return h, e
   538  }
   539  
   540  func Read(fd Handle, p []byte) (n int, err error) {
   541  	var done uint32
   542  	e := ReadFile(fd, p, &done, nil)
   543  	if e != nil {
   544  		if e == ERROR_BROKEN_PIPE {
   545  			// NOTE(brainman): work around ERROR_BROKEN_PIPE is returned on reading EOF from stdin
   546  			return 0, nil
   547  		}
   548  		return 0, e
   549  	}
   550  	if raceenabled {
   551  		if done > 0 {
   552  			raceWriteRange(unsafe.Pointer(&p[0]), int(done))
   553  		}
   554  		raceAcquire(unsafe.Pointer(&ioSync))
   555  	}
   556  	return int(done), nil
   557  }
   558  
   559  func Write(fd Handle, p []byte) (n int, err error) {
   560  	if raceenabled {
   561  		raceReleaseMerge(unsafe.Pointer(&ioSync))
   562  	}
   563  	var done uint32
   564  	e := WriteFile(fd, p, &done, nil)
   565  	if e != nil {
   566  		return 0, e
   567  	}
   568  	if raceenabled && done > 0 {
   569  		raceReadRange(unsafe.Pointer(&p[0]), int(done))
   570  	}
   571  	return int(done), nil
   572  }
   573  
   574  var ioSync int64
   575  
   576  func Seek(fd Handle, offset int64, whence int) (newoffset int64, err error) {
   577  	var w uint32
   578  	switch whence {
   579  	case 0:
   580  		w = FILE_BEGIN
   581  	case 1:
   582  		w = FILE_CURRENT
   583  	case 2:
   584  		w = FILE_END
   585  	}
   586  	hi := int32(offset >> 32)
   587  	lo := int32(offset)
   588  	// use GetFileType to check pipe, pipe can't do seek
   589  	ft, _ := GetFileType(fd)
   590  	if ft == FILE_TYPE_PIPE {
   591  		return 0, syscall.EPIPE
   592  	}
   593  	rlo, e := SetFilePointer(fd, lo, &hi, w)
   594  	if e != nil {
   595  		return 0, e
   596  	}
   597  	return int64(hi)<<32 + int64(rlo), nil
   598  }
   599  
   600  func Close(fd Handle) (err error) {
   601  	return CloseHandle(fd)
   602  }
   603  
   604  var (
   605  	Stdin  = getStdHandle(STD_INPUT_HANDLE)
   606  	Stdout = getStdHandle(STD_OUTPUT_HANDLE)
   607  	Stderr = getStdHandle(STD_ERROR_HANDLE)
   608  )
   609  
   610  func getStdHandle(stdhandle uint32) (fd Handle) {
   611  	r, _ := GetStdHandle(stdhandle)
   612  	CloseOnExec(r)
   613  	return r
   614  }
   615  
   616  const ImplementsGetwd = true
   617  
   618  func Getwd() (wd string, err error) {
   619  	b := make([]uint16, 300)
   620  	n, e := GetCurrentDirectory(uint32(len(b)), &b[0])
   621  	if e != nil {
   622  		return "", e
   623  	}
   624  	return string(utf16.Decode(b[0:n])), nil
   625  }
   626  
   627  func Chdir(path string) (err error) {
   628  	pathp, err := UTF16PtrFromString(path)
   629  	if err != nil {
   630  		return err
   631  	}
   632  	return SetCurrentDirectory(pathp)
   633  }
   634  
   635  func Mkdir(path string, mode uint32) (err error) {
   636  	pathp, err := UTF16PtrFromString(path)
   637  	if err != nil {
   638  		return err
   639  	}
   640  	return CreateDirectory(pathp, nil)
   641  }
   642  
   643  func Rmdir(path string) (err error) {
   644  	pathp, err := UTF16PtrFromString(path)
   645  	if err != nil {
   646  		return err
   647  	}
   648  	return RemoveDirectory(pathp)
   649  }
   650  
   651  func Unlink(path string) (err error) {
   652  	pathp, err := UTF16PtrFromString(path)
   653  	if err != nil {
   654  		return err
   655  	}
   656  	return DeleteFile(pathp)
   657  }
   658  
   659  func Rename(oldpath, newpath string) (err error) {
   660  	from, err := UTF16PtrFromString(oldpath)
   661  	if err != nil {
   662  		return err
   663  	}
   664  	to, err := UTF16PtrFromString(newpath)
   665  	if err != nil {
   666  		return err
   667  	}
   668  	return MoveFileEx(from, to, MOVEFILE_REPLACE_EXISTING)
   669  }
   670  
   671  func ComputerName() (name string, err error) {
   672  	var n uint32 = MAX_COMPUTERNAME_LENGTH + 1
   673  	b := make([]uint16, n)
   674  	e := GetComputerName(&b[0], &n)
   675  	if e != nil {
   676  		return "", e
   677  	}
   678  	return string(utf16.Decode(b[0:n])), nil
   679  }
   680  
   681  func DurationSinceBoot() time.Duration {
   682  	return time.Duration(getTickCount64()) * time.Millisecond
   683  }
   684  
   685  func Ftruncate(fd Handle, length int64) (err error) {
   686  	curoffset, e := Seek(fd, 0, 1)
   687  	if e != nil {
   688  		return e
   689  	}
   690  	defer Seek(fd, curoffset, 0)
   691  	_, e = Seek(fd, length, 0)
   692  	if e != nil {
   693  		return e
   694  	}
   695  	e = SetEndOfFile(fd)
   696  	if e != nil {
   697  		return e
   698  	}
   699  	return nil
   700  }
   701  
   702  func Gettimeofday(tv *Timeval) (err error) {
   703  	var ft Filetime
   704  	GetSystemTimeAsFileTime(&ft)
   705  	*tv = NsecToTimeval(ft.Nanoseconds())
   706  	return nil
   707  }
   708  
   709  func Pipe(p []Handle) (err error) {
   710  	if len(p) != 2 {
   711  		return syscall.EINVAL
   712  	}
   713  	var r, w Handle
   714  	e := CreatePipe(&r, &w, makeInheritSa(), 0)
   715  	if e != nil {
   716  		return e
   717  	}
   718  	p[0] = r
   719  	p[1] = w
   720  	return nil
   721  }
   722  
   723  func Utimes(path string, tv []Timeval) (err error) {
   724  	if len(tv) != 2 {
   725  		return syscall.EINVAL
   726  	}
   727  	pathp, e := UTF16PtrFromString(path)
   728  	if e != nil {
   729  		return e
   730  	}
   731  	h, e := CreateFile(pathp,
   732  		FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, nil,
   733  		OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0)
   734  	if e != nil {
   735  		return e
   736  	}
   737  	defer Close(h)
   738  	a := NsecToFiletime(tv[0].Nanoseconds())
   739  	w := NsecToFiletime(tv[1].Nanoseconds())
   740  	return SetFileTime(h, nil, &a, &w)
   741  }
   742  
   743  func UtimesNano(path string, ts []Timespec) (err error) {
   744  	if len(ts) != 2 {
   745  		return syscall.EINVAL
   746  	}
   747  	pathp, e := UTF16PtrFromString(path)
   748  	if e != nil {
   749  		return e
   750  	}
   751  	h, e := CreateFile(pathp,
   752  		FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, nil,
   753  		OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0)
   754  	if e != nil {
   755  		return e
   756  	}
   757  	defer Close(h)
   758  	a := NsecToFiletime(TimespecToNsec(ts[0]))
   759  	w := NsecToFiletime(TimespecToNsec(ts[1]))
   760  	return SetFileTime(h, nil, &a, &w)
   761  }
   762  
   763  func Fsync(fd Handle) (err error) {
   764  	return FlushFileBuffers(fd)
   765  }
   766  
   767  func Chmod(path string, mode uint32) (err error) {
   768  	p, e := UTF16PtrFromString(path)
   769  	if e != nil {
   770  		return e
   771  	}
   772  	attrs, e := GetFileAttributes(p)
   773  	if e != nil {
   774  		return e
   775  	}
   776  	if mode&S_IWRITE != 0 {
   777  		attrs &^= FILE_ATTRIBUTE_READONLY
   778  	} else {
   779  		attrs |= FILE_ATTRIBUTE_READONLY
   780  	}
   781  	return SetFileAttributes(p, attrs)
   782  }
   783  
   784  func LoadGetSystemTimePreciseAsFileTime() error {
   785  	return procGetSystemTimePreciseAsFileTime.Find()
   786  }
   787  
   788  func LoadCancelIoEx() error {
   789  	return procCancelIoEx.Find()
   790  }
   791  
   792  func LoadSetFileCompletionNotificationModes() error {
   793  	return procSetFileCompletionNotificationModes.Find()
   794  }
   795  
   796  func WaitForMultipleObjects(handles []Handle, waitAll bool, waitMilliseconds uint32) (event uint32, err error) {
   797  	// Every other win32 array API takes arguments as "pointer, count", except for this function. So we
   798  	// can't declare it as a usual [] type, because mksyscall will use the opposite order. We therefore
   799  	// trivially stub this ourselves.
   800  
   801  	var handlePtr *Handle
   802  	if len(handles) > 0 {
   803  		handlePtr = &handles[0]
   804  	}
   805  	return waitForMultipleObjects(uint32(len(handles)), uintptr(unsafe.Pointer(handlePtr)), waitAll, waitMilliseconds)
   806  }
   807  
   808  // net api calls
   809  
   810  const socket_error = uintptr(^uint32(0))
   811  
   812  //sys	WSAStartup(verreq uint32, data *WSAData) (sockerr error) = ws2_32.WSAStartup
   813  //sys	WSACleanup() (err error) [failretval==socket_error] = ws2_32.WSACleanup
   814  //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
   815  //sys	socket(af int32, typ int32, protocol int32) (handle Handle, err error) [failretval==InvalidHandle] = ws2_32.socket
   816  //sys	sendto(s Handle, buf []byte, flags int32, to unsafe.Pointer, tolen int32) (err error) [failretval==socket_error] = ws2_32.sendto
   817  //sys	recvfrom(s Handle, buf []byte, flags int32, from *RawSockaddrAny, fromlen *int32) (n int32, err error) [failretval==-1] = ws2_32.recvfrom
   818  //sys	Setsockopt(s Handle, level int32, optname int32, optval *byte, optlen int32) (err error) [failretval==socket_error] = ws2_32.setsockopt
   819  //sys	Getsockopt(s Handle, level int32, optname int32, optval *byte, optlen *int32) (err error) [failretval==socket_error] = ws2_32.getsockopt
   820  //sys	bind(s Handle, name unsafe.Pointer, namelen int32) (err error) [failretval==socket_error] = ws2_32.bind
   821  //sys	connect(s Handle, name unsafe.Pointer, namelen int32) (err error) [failretval==socket_error] = ws2_32.connect
   822  //sys	getsockname(s Handle, rsa *RawSockaddrAny, addrlen *int32) (err error) [failretval==socket_error] = ws2_32.getsockname
   823  //sys	getpeername(s Handle, rsa *RawSockaddrAny, addrlen *int32) (err error) [failretval==socket_error] = ws2_32.getpeername
   824  //sys	listen(s Handle, backlog int32) (err error) [failretval==socket_error] = ws2_32.listen
   825  //sys	shutdown(s Handle, how int32) (err error) [failretval==socket_error] = ws2_32.shutdown
   826  //sys	Closesocket(s Handle) (err error) [failretval==socket_error] = ws2_32.closesocket
   827  //sys	AcceptEx(ls Handle, as Handle, buf *byte, rxdatalen uint32, laddrlen uint32, raddrlen uint32, recvd *uint32, overlapped *Overlapped) (err error) = mswsock.AcceptEx
   828  //sys	GetAcceptExSockaddrs(buf *byte, rxdatalen uint32, laddrlen uint32, raddrlen uint32, lrsa **RawSockaddrAny, lrsalen *int32, rrsa **RawSockaddrAny, rrsalen *int32) = mswsock.GetAcceptExSockaddrs
   829  //sys	WSARecv(s Handle, bufs *WSABuf, bufcnt uint32, recvd *uint32, flags *uint32, overlapped *Overlapped, croutine *byte) (err error) [failretval==socket_error] = ws2_32.WSARecv
   830  //sys	WSASend(s Handle, bufs *WSABuf, bufcnt uint32, sent *uint32, flags uint32, overlapped *Overlapped, croutine *byte) (err error) [failretval==socket_error] = ws2_32.WSASend
   831  //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
   832  //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
   833  //sys	WSASocket(af int32, typ int32, protocol int32, protoInfo *WSAProtocolInfo, group uint32, flags uint32) (handle Handle, err error) [failretval==InvalidHandle] = ws2_32.WSASocketW
   834  //sys	GetHostByName(name string) (h *Hostent, err error) [failretval==nil] = ws2_32.gethostbyname
   835  //sys	GetServByName(name string, proto string) (s *Servent, err error) [failretval==nil] = ws2_32.getservbyname
   836  //sys	Ntohs(netshort uint16) (u uint16) = ws2_32.ntohs
   837  //sys	GetProtoByName(name string) (p *Protoent, err error) [failretval==nil] = ws2_32.getprotobyname
   838  //sys	DnsQuery(name string, qtype uint16, options uint32, extra *byte, qrs **DNSRecord, pr *byte) (status error) = dnsapi.DnsQuery_W
   839  //sys	DnsRecordListFree(rl *DNSRecord, freetype uint32) = dnsapi.DnsRecordListFree
   840  //sys	DnsNameCompare(name1 *uint16, name2 *uint16) (same bool) = dnsapi.DnsNameCompare_W
   841  //sys	GetAddrInfoW(nodename *uint16, servicename *uint16, hints *AddrinfoW, result **AddrinfoW) (sockerr error) = ws2_32.GetAddrInfoW
   842  //sys	FreeAddrInfoW(addrinfo *AddrinfoW) = ws2_32.FreeAddrInfoW
   843  //sys	GetIfEntry(pIfRow *MibIfRow) (errcode error) = iphlpapi.GetIfEntry
   844  //sys	GetAdaptersInfo(ai *IpAdapterInfo, ol *uint32) (errcode error) = iphlpapi.GetAdaptersInfo
   845  //sys	SetFileCompletionNotificationModes(handle Handle, flags uint8) (err error) = kernel32.SetFileCompletionNotificationModes
   846  //sys	WSAEnumProtocols(protocols *int32, protocolBuffer *WSAProtocolInfo, bufferLength *uint32) (n int32, err error) [failretval==-1] = ws2_32.WSAEnumProtocolsW
   847  //sys	WSAGetOverlappedResult(h Handle, o *Overlapped, bytes *uint32, wait bool, flags *uint32) (err error) = ws2_32.WSAGetOverlappedResult
   848  //sys	GetAdaptersAddresses(family uint32, flags uint32, reserved uintptr, adapterAddresses *IpAdapterAddresses, sizePointer *uint32) (errcode error) = iphlpapi.GetAdaptersAddresses
   849  //sys	GetACP() (acp uint32) = kernel32.GetACP
   850  //sys	MultiByteToWideChar(codePage uint32, dwFlags uint32, str *byte, nstr int32, wchar *uint16, nwchar int32) (nwrite int32, err error) = kernel32.MultiByteToWideChar
   851  
   852  // For testing: clients can set this flag to force
   853  // creation of IPv6 sockets to return EAFNOSUPPORT.
   854  var SocketDisableIPv6 bool
   855  
   856  type RawSockaddrInet4 struct {
   857  	Family uint16
   858  	Port   uint16
   859  	Addr   [4]byte /* in_addr */
   860  	Zero   [8]uint8
   861  }
   862  
   863  type RawSockaddrInet6 struct {
   864  	Family   uint16
   865  	Port     uint16
   866  	Flowinfo uint32
   867  	Addr     [16]byte /* in6_addr */
   868  	Scope_id uint32
   869  }
   870  
   871  type RawSockaddr struct {
   872  	Family uint16
   873  	Data   [14]int8
   874  }
   875  
   876  type RawSockaddrAny struct {
   877  	Addr RawSockaddr
   878  	Pad  [100]int8
   879  }
   880  
   881  type Sockaddr interface {
   882  	sockaddr() (ptr unsafe.Pointer, len int32, err error) // lowercase; only we can define Sockaddrs
   883  }
   884  
   885  type SockaddrInet4 struct {
   886  	Port int
   887  	Addr [4]byte
   888  	raw  RawSockaddrInet4
   889  }
   890  
   891  func (sa *SockaddrInet4) sockaddr() (unsafe.Pointer, int32, error) {
   892  	if sa.Port < 0 || sa.Port > 0xFFFF {
   893  		return nil, 0, syscall.EINVAL
   894  	}
   895  	sa.raw.Family = AF_INET
   896  	p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port))
   897  	p[0] = byte(sa.Port >> 8)
   898  	p[1] = byte(sa.Port)
   899  	sa.raw.Addr = sa.Addr
   900  	return unsafe.Pointer(&sa.raw), int32(unsafe.Sizeof(sa.raw)), nil
   901  }
   902  
   903  type SockaddrInet6 struct {
   904  	Port   int
   905  	ZoneId uint32
   906  	Addr   [16]byte
   907  	raw    RawSockaddrInet6
   908  }
   909  
   910  func (sa *SockaddrInet6) sockaddr() (unsafe.Pointer, int32, error) {
   911  	if sa.Port < 0 || sa.Port > 0xFFFF {
   912  		return nil, 0, syscall.EINVAL
   913  	}
   914  	sa.raw.Family = AF_INET6
   915  	p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port))
   916  	p[0] = byte(sa.Port >> 8)
   917  	p[1] = byte(sa.Port)
   918  	sa.raw.Scope_id = sa.ZoneId
   919  	sa.raw.Addr = sa.Addr
   920  	return unsafe.Pointer(&sa.raw), int32(unsafe.Sizeof(sa.raw)), nil
   921  }
   922  
   923  type RawSockaddrUnix struct {
   924  	Family uint16
   925  	Path   [UNIX_PATH_MAX]int8
   926  }
   927  
   928  type SockaddrUnix struct {
   929  	Name string
   930  	raw  RawSockaddrUnix
   931  }
   932  
   933  func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, int32, error) {
   934  	name := sa.Name
   935  	n := len(name)
   936  	if n > len(sa.raw.Path) {
   937  		return nil, 0, syscall.EINVAL
   938  	}
   939  	if n == len(sa.raw.Path) && name[0] != '@' {
   940  		return nil, 0, syscall.EINVAL
   941  	}
   942  	sa.raw.Family = AF_UNIX
   943  	for i := 0; i < n; i++ {
   944  		sa.raw.Path[i] = int8(name[i])
   945  	}
   946  	// length is family (uint16), name, NUL.
   947  	sl := int32(2)
   948  	if n > 0 {
   949  		sl += int32(n) + 1
   950  	}
   951  	if sa.raw.Path[0] == '@' {
   952  		sa.raw.Path[0] = 0
   953  		// Don't count trailing NUL for abstract address.
   954  		sl--
   955  	}
   956  
   957  	return unsafe.Pointer(&sa.raw), sl, nil
   958  }
   959  
   960  func (rsa *RawSockaddrAny) Sockaddr() (Sockaddr, error) {
   961  	switch rsa.Addr.Family {
   962  	case AF_UNIX:
   963  		pp := (*RawSockaddrUnix)(unsafe.Pointer(rsa))
   964  		sa := new(SockaddrUnix)
   965  		if pp.Path[0] == 0 {
   966  			// "Abstract" Unix domain socket.
   967  			// Rewrite leading NUL as @ for textual display.
   968  			// (This is the standard convention.)
   969  			// Not friendly to overwrite in place,
   970  			// but the callers below don't care.
   971  			pp.Path[0] = '@'
   972  		}
   973  
   974  		// Assume path ends at NUL.
   975  		// This is not technically the Linux semantics for
   976  		// abstract Unix domain sockets--they are supposed
   977  		// to be uninterpreted fixed-size binary blobs--but
   978  		// everyone uses this convention.
   979  		n := 0
   980  		for n < len(pp.Path) && pp.Path[n] != 0 {
   981  			n++
   982  		}
   983  		bytes := (*[len(pp.Path)]byte)(unsafe.Pointer(&pp.Path[0]))[0:n]
   984  		sa.Name = string(bytes)
   985  		return sa, nil
   986  
   987  	case AF_INET:
   988  		pp := (*RawSockaddrInet4)(unsafe.Pointer(rsa))
   989  		sa := new(SockaddrInet4)
   990  		p := (*[2]byte)(unsafe.Pointer(&pp.Port))
   991  		sa.Port = int(p[0])<<8 + int(p[1])
   992  		sa.Addr = pp.Addr
   993  		return sa, nil
   994  
   995  	case AF_INET6:
   996  		pp := (*RawSockaddrInet6)(unsafe.Pointer(rsa))
   997  		sa := new(SockaddrInet6)
   998  		p := (*[2]byte)(unsafe.Pointer(&pp.Port))
   999  		sa.Port = int(p[0])<<8 + int(p[1])
  1000  		sa.ZoneId = pp.Scope_id
  1001  		sa.Addr = pp.Addr
  1002  		return sa, nil
  1003  	}
  1004  	return nil, syscall.EAFNOSUPPORT
  1005  }
  1006  
  1007  func Socket(domain, typ, proto int) (fd Handle, err error) {
  1008  	if domain == AF_INET6 && SocketDisableIPv6 {
  1009  		return InvalidHandle, syscall.EAFNOSUPPORT
  1010  	}
  1011  	return socket(int32(domain), int32(typ), int32(proto))
  1012  }
  1013  
  1014  func SetsockoptInt(fd Handle, level, opt int, value int) (err error) {
  1015  	v := int32(value)
  1016  	return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(&v)), int32(unsafe.Sizeof(v)))
  1017  }
  1018  
  1019  func Bind(fd Handle, sa Sockaddr) (err error) {
  1020  	ptr, n, err := sa.sockaddr()
  1021  	if err != nil {
  1022  		return err
  1023  	}
  1024  	return bind(fd, ptr, n)
  1025  }
  1026  
  1027  func Connect(fd Handle, sa Sockaddr) (err error) {
  1028  	ptr, n, err := sa.sockaddr()
  1029  	if err != nil {
  1030  		return err
  1031  	}
  1032  	return connect(fd, ptr, n)
  1033  }
  1034  
  1035  func Getsockname(fd Handle) (sa Sockaddr, err error) {
  1036  	var rsa RawSockaddrAny
  1037  	l := int32(unsafe.Sizeof(rsa))
  1038  	if err = getsockname(fd, &rsa, &l); err != nil {
  1039  		return
  1040  	}
  1041  	return rsa.Sockaddr()
  1042  }
  1043  
  1044  func Getpeername(fd Handle) (sa Sockaddr, err error) {
  1045  	var rsa RawSockaddrAny
  1046  	l := int32(unsafe.Sizeof(rsa))
  1047  	if err = getpeername(fd, &rsa, &l); err != nil {
  1048  		return
  1049  	}
  1050  	return rsa.Sockaddr()
  1051  }
  1052  
  1053  func Listen(s Handle, n int) (err error) {
  1054  	return listen(s, int32(n))
  1055  }
  1056  
  1057  func Shutdown(fd Handle, how int) (err error) {
  1058  	return shutdown(fd, int32(how))
  1059  }
  1060  
  1061  func WSASendto(s Handle, bufs *WSABuf, bufcnt uint32, sent *uint32, flags uint32, to Sockaddr, overlapped *Overlapped, croutine *byte) (err error) {
  1062  	rsa, l, err := to.sockaddr()
  1063  	if err != nil {
  1064  		return err
  1065  	}
  1066  	return WSASendTo(s, bufs, bufcnt, sent, flags, (*RawSockaddrAny)(unsafe.Pointer(rsa)), l, overlapped, croutine)
  1067  }
  1068  
  1069  func LoadGetAddrInfo() error {
  1070  	return procGetAddrInfoW.Find()
  1071  }
  1072  
  1073  var connectExFunc struct {
  1074  	once sync.Once
  1075  	addr uintptr
  1076  	err  error
  1077  }
  1078  
  1079  func LoadConnectEx() error {
  1080  	connectExFunc.once.Do(func() {
  1081  		var s Handle
  1082  		s, connectExFunc.err = Socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)
  1083  		if connectExFunc.err != nil {
  1084  			return
  1085  		}
  1086  		defer CloseHandle(s)
  1087  		var n uint32
  1088  		connectExFunc.err = WSAIoctl(s,
  1089  			SIO_GET_EXTENSION_FUNCTION_POINTER,
  1090  			(*byte)(unsafe.Pointer(&WSAID_CONNECTEX)),
  1091  			uint32(unsafe.Sizeof(WSAID_CONNECTEX)),
  1092  			(*byte)(unsafe.Pointer(&connectExFunc.addr)),
  1093  			uint32(unsafe.Sizeof(connectExFunc.addr)),
  1094  			&n, nil, 0)
  1095  	})
  1096  	return connectExFunc.err
  1097  }
  1098  
  1099  func connectEx(s Handle, name unsafe.Pointer, namelen int32, sendBuf *byte, sendDataLen uint32, bytesSent *uint32, overlapped *Overlapped) (err error) {
  1100  	r1, _, e1 := syscall.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)
  1101  	if r1 == 0 {
  1102  		if e1 != 0 {
  1103  			err = error(e1)
  1104  		} else {
  1105  			err = syscall.EINVAL
  1106  		}
  1107  	}
  1108  	return
  1109  }
  1110  
  1111  func ConnectEx(fd Handle, sa Sockaddr, sendBuf *byte, sendDataLen uint32, bytesSent *uint32, overlapped *Overlapped) error {
  1112  	err := LoadConnectEx()
  1113  	if err != nil {
  1114  		return errorspkg.New("failed to find ConnectEx: " + err.Error())
  1115  	}
  1116  	ptr, n, err := sa.sockaddr()
  1117  	if err != nil {
  1118  		return err
  1119  	}
  1120  	return connectEx(fd, ptr, n, sendBuf, sendDataLen, bytesSent, overlapped)
  1121  }
  1122  
  1123  var sendRecvMsgFunc struct {
  1124  	once     sync.Once
  1125  	sendAddr uintptr
  1126  	recvAddr uintptr
  1127  	err      error
  1128  }
  1129  
  1130  func loadWSASendRecvMsg() error {
  1131  	sendRecvMsgFunc.once.Do(func() {
  1132  		var s Handle
  1133  		s, sendRecvMsgFunc.err = Socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)
  1134  		if sendRecvMsgFunc.err != nil {
  1135  			return
  1136  		}
  1137  		defer CloseHandle(s)
  1138  		var n uint32
  1139  		sendRecvMsgFunc.err = WSAIoctl(s,
  1140  			SIO_GET_EXTENSION_FUNCTION_POINTER,
  1141  			(*byte)(unsafe.Pointer(&WSAID_WSARECVMSG)),
  1142  			uint32(unsafe.Sizeof(WSAID_WSARECVMSG)),
  1143  			(*byte)(unsafe.Pointer(&sendRecvMsgFunc.recvAddr)),
  1144  			uint32(unsafe.Sizeof(sendRecvMsgFunc.recvAddr)),
  1145  			&n, nil, 0)
  1146  		if sendRecvMsgFunc.err != nil {
  1147  			return
  1148  		}
  1149  		sendRecvMsgFunc.err = WSAIoctl(s,
  1150  			SIO_GET_EXTENSION_FUNCTION_POINTER,
  1151  			(*byte)(unsafe.Pointer(&WSAID_WSASENDMSG)),
  1152  			uint32(unsafe.Sizeof(WSAID_WSASENDMSG)),
  1153  			(*byte)(unsafe.Pointer(&sendRecvMsgFunc.sendAddr)),
  1154  			uint32(unsafe.Sizeof(sendRecvMsgFunc.sendAddr)),
  1155  			&n, nil, 0)
  1156  	})
  1157  	return sendRecvMsgFunc.err
  1158  }
  1159  
  1160  func WSASendMsg(fd Handle, msg *WSAMsg, flags uint32, bytesSent *uint32, overlapped *Overlapped, croutine *byte) error {
  1161  	err := loadWSASendRecvMsg()
  1162  	if err != nil {
  1163  		return err
  1164  	}
  1165  	r1, _, e1 := syscall.Syscall6(sendRecvMsgFunc.sendAddr, 6, uintptr(fd), uintptr(unsafe.Pointer(msg)), uintptr(flags), uintptr(unsafe.Pointer(bytesSent)), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(croutine)))
  1166  	if r1 == socket_error {
  1167  		err = errnoErr(e1)
  1168  	}
  1169  	return err
  1170  }
  1171  
  1172  func WSARecvMsg(fd Handle, msg *WSAMsg, bytesReceived *uint32, overlapped *Overlapped, croutine *byte) error {
  1173  	err := loadWSASendRecvMsg()
  1174  	if err != nil {
  1175  		return err
  1176  	}
  1177  	r1, _, e1 := syscall.Syscall6(sendRecvMsgFunc.recvAddr, 5, uintptr(fd), uintptr(unsafe.Pointer(msg)), uintptr(unsafe.Pointer(bytesReceived)), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(croutine)), 0)
  1178  	if r1 == socket_error {
  1179  		err = errnoErr(e1)
  1180  	}
  1181  	return err
  1182  }
  1183  
  1184  // Invented structures to support what package os expects.
  1185  type Rusage struct {
  1186  	CreationTime Filetime
  1187  	ExitTime     Filetime
  1188  	KernelTime   Filetime
  1189  	UserTime     Filetime
  1190  }
  1191  
  1192  type WaitStatus struct {
  1193  	ExitCode uint32
  1194  }
  1195  
  1196  func (w WaitStatus) Exited() bool { return true }
  1197  
  1198  func (w WaitStatus) ExitStatus() int { return int(w.ExitCode) }
  1199  
  1200  func (w WaitStatus) Signal() Signal { return -1 }
  1201  
  1202  func (w WaitStatus) CoreDump() bool { return false }
  1203  
  1204  func (w WaitStatus) Stopped() bool { return false }
  1205  
  1206  func (w WaitStatus) Continued() bool { return false }
  1207  
  1208  func (w WaitStatus) StopSignal() Signal { return -1 }
  1209  
  1210  func (w WaitStatus) Signaled() bool { return false }
  1211  
  1212  func (w WaitStatus) TrapCause() int { return -1 }
  1213  
  1214  // Timespec is an invented structure on Windows, but here for
  1215  // consistency with the corresponding package for other operating systems.
  1216  type Timespec struct {
  1217  	Sec  int64
  1218  	Nsec int64
  1219  }
  1220  
  1221  func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) }
  1222  
  1223  func NsecToTimespec(nsec int64) (ts Timespec) {
  1224  	ts.Sec = nsec / 1e9
  1225  	ts.Nsec = nsec % 1e9
  1226  	return
  1227  }
  1228  
  1229  // TODO(brainman): fix all needed for net
  1230  
  1231  func Accept(fd Handle) (nfd Handle, sa Sockaddr, err error) { return 0, nil, syscall.EWINDOWS }
  1232  
  1233  func Recvfrom(fd Handle, p []byte, flags int) (n int, from Sockaddr, err error) {
  1234  	var rsa RawSockaddrAny
  1235  	l := int32(unsafe.Sizeof(rsa))
  1236  	n32, err := recvfrom(fd, p, int32(flags), &rsa, &l)
  1237  	n = int(n32)
  1238  	if err != nil {
  1239  		return
  1240  	}
  1241  	from, err = rsa.Sockaddr()
  1242  	return
  1243  }
  1244  
  1245  func Sendto(fd Handle, p []byte, flags int, to Sockaddr) (err error) {
  1246  	ptr, l, err := to.sockaddr()
  1247  	if err != nil {
  1248  		return err
  1249  	}
  1250  	return sendto(fd, p, int32(flags), ptr, l)
  1251  }
  1252  
  1253  func SetsockoptTimeval(fd Handle, level, opt int, tv *Timeval) (err error) { return syscall.EWINDOWS }
  1254  
  1255  // The Linger struct is wrong but we only noticed after Go 1.
  1256  // sysLinger is the real system call structure.
  1257  
  1258  // BUG(brainman): The definition of Linger is not appropriate for direct use
  1259  // with Setsockopt and Getsockopt.
  1260  // Use SetsockoptLinger instead.
  1261  
  1262  type Linger struct {
  1263  	Onoff  int32
  1264  	Linger int32
  1265  }
  1266  
  1267  type sysLinger struct {
  1268  	Onoff  uint16
  1269  	Linger uint16
  1270  }
  1271  
  1272  type IPMreq struct {
  1273  	Multiaddr [4]byte /* in_addr */
  1274  	Interface [4]byte /* in_addr */
  1275  }
  1276  
  1277  type IPv6Mreq struct {
  1278  	Multiaddr [16]byte /* in6_addr */
  1279  	Interface uint32
  1280  }
  1281  
  1282  func GetsockoptInt(fd Handle, level, opt int) (int, error) {
  1283  	v := int32(0)
  1284  	l := int32(unsafe.Sizeof(v))
  1285  	err := Getsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(&v)), &l)
  1286  	return int(v), err
  1287  }
  1288  
  1289  func SetsockoptLinger(fd Handle, level, opt int, l *Linger) (err error) {
  1290  	sys := sysLinger{Onoff: uint16(l.Onoff), Linger: uint16(l.Linger)}
  1291  	return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(&sys)), int32(unsafe.Sizeof(sys)))
  1292  }
  1293  
  1294  func SetsockoptInet4Addr(fd Handle, level, opt int, value [4]byte) (err error) {
  1295  	return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(&value[0])), 4)
  1296  }
  1297  func SetsockoptIPMreq(fd Handle, level, opt int, mreq *IPMreq) (err error) {
  1298  	return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(mreq)), int32(unsafe.Sizeof(*mreq)))
  1299  }
  1300  func SetsockoptIPv6Mreq(fd Handle, level, opt int, mreq *IPv6Mreq) (err error) {
  1301  	return syscall.EWINDOWS
  1302  }
  1303  
  1304  func Getpid() (pid int) { return int(GetCurrentProcessId()) }
  1305  
  1306  func FindFirstFile(name *uint16, data *Win32finddata) (handle Handle, err error) {
  1307  	// NOTE(rsc): The Win32finddata struct is wrong for the system call:
  1308  	// the two paths are each one uint16 short. Use the correct struct,
  1309  	// a win32finddata1, and then copy the results out.
  1310  	// There is no loss of expressivity here, because the final
  1311  	// uint16, if it is used, is supposed to be a NUL, and Go doesn't need that.
  1312  	// For Go 1.1, we might avoid the allocation of win32finddata1 here
  1313  	// by adding a final Bug [2]uint16 field to the struct and then
  1314  	// adjusting the fields in the result directly.
  1315  	var data1 win32finddata1
  1316  	handle, err = findFirstFile1(name, &data1)
  1317  	if err == nil {
  1318  		copyFindData(data, &data1)
  1319  	}
  1320  	return
  1321  }
  1322  
  1323  func FindNextFile(handle Handle, data *Win32finddata) (err error) {
  1324  	var data1 win32finddata1
  1325  	err = findNextFile1(handle, &data1)
  1326  	if err == nil {
  1327  		copyFindData(data, &data1)
  1328  	}
  1329  	return
  1330  }
  1331  
  1332  func getProcessEntry(pid int) (*ProcessEntry32, error) {
  1333  	snapshot, err := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)
  1334  	if err != nil {
  1335  		return nil, err
  1336  	}
  1337  	defer CloseHandle(snapshot)
  1338  	var procEntry ProcessEntry32
  1339  	procEntry.Size = uint32(unsafe.Sizeof(procEntry))
  1340  	if err = Process32First(snapshot, &procEntry); err != nil {
  1341  		return nil, err
  1342  	}
  1343  	for {
  1344  		if procEntry.ProcessID == uint32(pid) {
  1345  			return &procEntry, nil
  1346  		}
  1347  		err = Process32Next(snapshot, &procEntry)
  1348  		if err != nil {
  1349  			return nil, err
  1350  		}
  1351  	}
  1352  }
  1353  
  1354  func Getppid() (ppid int) {
  1355  	pe, err := getProcessEntry(Getpid())
  1356  	if err != nil {
  1357  		return -1
  1358  	}
  1359  	return int(pe.ParentProcessID)
  1360  }
  1361  
  1362  // TODO(brainman): fix all needed for os
  1363  func Fchdir(fd Handle) (err error)             { return syscall.EWINDOWS }
  1364  func Link(oldpath, newpath string) (err error) { return syscall.EWINDOWS }
  1365  func Symlink(path, link string) (err error)    { return syscall.EWINDOWS }
  1366  
  1367  func Fchmod(fd Handle, mode uint32) (err error)        { return syscall.EWINDOWS }
  1368  func Chown(path string, uid int, gid int) (err error)  { return syscall.EWINDOWS }
  1369  func Lchown(path string, uid int, gid int) (err error) { return syscall.EWINDOWS }
  1370  func Fchown(fd Handle, uid int, gid int) (err error)   { return syscall.EWINDOWS }
  1371  
  1372  func Getuid() (uid int)                  { return -1 }
  1373  func Geteuid() (euid int)                { return -1 }
  1374  func Getgid() (gid int)                  { return -1 }
  1375  func Getegid() (egid int)                { return -1 }
  1376  func Getgroups() (gids []int, err error) { return nil, syscall.EWINDOWS }
  1377  
  1378  type Signal int
  1379  
  1380  func (s Signal) Signal() {}
  1381  
  1382  func (s Signal) String() string {
  1383  	if 0 <= s && int(s) < len(signals) {
  1384  		str := signals[s]
  1385  		if str != "" {
  1386  			return str
  1387  		}
  1388  	}
  1389  	return "signal " + itoa(int(s))
  1390  }
  1391  
  1392  func LoadCreateSymbolicLink() error {
  1393  	return procCreateSymbolicLinkW.Find()
  1394  }
  1395  
  1396  // Readlink returns the destination of the named symbolic link.
  1397  func Readlink(path string, buf []byte) (n int, err error) {
  1398  	fd, err := CreateFile(StringToUTF16Ptr(path), GENERIC_READ, 0, nil, OPEN_EXISTING,
  1399  		FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_BACKUP_SEMANTICS, 0)
  1400  	if err != nil {
  1401  		return -1, err
  1402  	}
  1403  	defer CloseHandle(fd)
  1404  
  1405  	rdbbuf := make([]byte, MAXIMUM_REPARSE_DATA_BUFFER_SIZE)
  1406  	var bytesReturned uint32
  1407  	err = DeviceIoControl(fd, FSCTL_GET_REPARSE_POINT, nil, 0, &rdbbuf[0], uint32(len(rdbbuf)), &bytesReturned, nil)
  1408  	if err != nil {
  1409  		return -1, err
  1410  	}
  1411  
  1412  	rdb := (*reparseDataBuffer)(unsafe.Pointer(&rdbbuf[0]))
  1413  	var s string
  1414  	switch rdb.ReparseTag {
  1415  	case IO_REPARSE_TAG_SYMLINK:
  1416  		data := (*symbolicLinkReparseBuffer)(unsafe.Pointer(&rdb.reparseBuffer))
  1417  		p := (*[0xffff]uint16)(unsafe.Pointer(&data.PathBuffer[0]))
  1418  		s = UTF16ToString(p[data.PrintNameOffset/2 : (data.PrintNameLength-data.PrintNameOffset)/2])
  1419  	case IO_REPARSE_TAG_MOUNT_POINT:
  1420  		data := (*mountPointReparseBuffer)(unsafe.Pointer(&rdb.reparseBuffer))
  1421  		p := (*[0xffff]uint16)(unsafe.Pointer(&data.PathBuffer[0]))
  1422  		s = UTF16ToString(p[data.PrintNameOffset/2 : (data.PrintNameLength-data.PrintNameOffset)/2])
  1423  	default:
  1424  		// the path is not a symlink or junction but another type of reparse
  1425  		// point
  1426  		return -1, syscall.ENOENT
  1427  	}
  1428  	n = copy(buf, []byte(s))
  1429  
  1430  	return n, nil
  1431  }
  1432  
  1433  // GUIDFromString parses a string in the form of
  1434  // "{XXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}" into a GUID.
  1435  func GUIDFromString(str string) (GUID, error) {
  1436  	guid := GUID{}
  1437  	str16, err := syscall.UTF16PtrFromString(str)
  1438  	if err != nil {
  1439  		return guid, err
  1440  	}
  1441  	err = clsidFromString(str16, &guid)
  1442  	if err != nil {
  1443  		return guid, err
  1444  	}
  1445  	return guid, nil
  1446  }
  1447  
  1448  // GenerateGUID creates a new random GUID.
  1449  func GenerateGUID() (GUID, error) {
  1450  	guid := GUID{}
  1451  	err := coCreateGuid(&guid)
  1452  	if err != nil {
  1453  		return guid, err
  1454  	}
  1455  	return guid, nil
  1456  }
  1457  
  1458  // String returns the canonical string form of the GUID,
  1459  // in the form of "{XXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}".
  1460  func (guid GUID) String() string {
  1461  	var str [100]uint16
  1462  	chars := stringFromGUID2(&guid, &str[0], int32(len(str)))
  1463  	if chars <= 1 {
  1464  		return ""
  1465  	}
  1466  	return string(utf16.Decode(str[:chars-1]))
  1467  }
  1468  
  1469  // KnownFolderPath returns a well-known folder path for the current user, specified by one of
  1470  // the FOLDERID_ constants, and chosen and optionally created based on a KF_ flag.
  1471  func KnownFolderPath(folderID *KNOWNFOLDERID, flags uint32) (string, error) {
  1472  	return Token(0).KnownFolderPath(folderID, flags)
  1473  }
  1474  
  1475  // KnownFolderPath returns a well-known folder path for the user token, specified by one of
  1476  // the FOLDERID_ constants, and chosen and optionally created based on a KF_ flag.
  1477  func (t Token) KnownFolderPath(folderID *KNOWNFOLDERID, flags uint32) (string, error) {
  1478  	var p *uint16
  1479  	err := shGetKnownFolderPath(folderID, flags, t, &p)
  1480  	if err != nil {
  1481  		return "", err
  1482  	}
  1483  	defer CoTaskMemFree(unsafe.Pointer(p))
  1484  	return UTF16PtrToString(p), nil
  1485  }
  1486  
  1487  // RtlGetVersion returns the version of the underlying operating system, ignoring
  1488  // manifest semantics but is affected by the application compatibility layer.
  1489  func RtlGetVersion() *OsVersionInfoEx {
  1490  	info := &OsVersionInfoEx{}
  1491  	info.osVersionInfoSize = uint32(unsafe.Sizeof(*info))
  1492  	// According to documentation, this function always succeeds.
  1493  	// The function doesn't even check the validity of the
  1494  	// osVersionInfoSize member. Disassembling ntdll.dll indicates
  1495  	// that the documentation is indeed correct about that.
  1496  	_ = rtlGetVersion(info)
  1497  	return info
  1498  }
  1499  
  1500  // RtlGetNtVersionNumbers returns the version of the underlying operating system,
  1501  // ignoring manifest semantics and the application compatibility layer.
  1502  func RtlGetNtVersionNumbers() (majorVersion, minorVersion, buildNumber uint32) {
  1503  	rtlGetNtVersionNumbers(&majorVersion, &minorVersion, &buildNumber)
  1504  	buildNumber &= 0xffff
  1505  	return
  1506  }
  1507  
  1508  // GetProcessPreferredUILanguages retrieves the process preferred UI languages.
  1509  func GetProcessPreferredUILanguages(flags uint32) ([]string, error) {
  1510  	return getUILanguages(flags, getProcessPreferredUILanguages)
  1511  }
  1512  
  1513  // GetThreadPreferredUILanguages retrieves the thread preferred UI languages for the current thread.
  1514  func GetThreadPreferredUILanguages(flags uint32) ([]string, error) {
  1515  	return getUILanguages(flags, getThreadPreferredUILanguages)
  1516  }
  1517  
  1518  // GetUserPreferredUILanguages retrieves information about the user preferred UI languages.
  1519  func GetUserPreferredUILanguages(flags uint32) ([]string, error) {
  1520  	return getUILanguages(flags, getUserPreferredUILanguages)
  1521  }
  1522  
  1523  // GetSystemPreferredUILanguages retrieves the system preferred UI languages.
  1524  func GetSystemPreferredUILanguages(flags uint32) ([]string, error) {
  1525  	return getUILanguages(flags, getSystemPreferredUILanguages)
  1526  }
  1527  
  1528  func getUILanguages(flags uint32, f func(flags uint32, numLanguages *uint32, buf *uint16, bufSize *uint32) error) ([]string, error) {
  1529  	size := uint32(128)
  1530  	for {
  1531  		var numLanguages uint32
  1532  		buf := make([]uint16, size)
  1533  		err := f(flags, &numLanguages, &buf[0], &size)
  1534  		if err == ERROR_INSUFFICIENT_BUFFER {
  1535  			continue
  1536  		}
  1537  		if err != nil {
  1538  			return nil, err
  1539  		}
  1540  		buf = buf[:size]
  1541  		if numLanguages == 0 || len(buf) == 0 { // GetProcessPreferredUILanguages may return numLanguages==0 with "\0\0"
  1542  			return []string{}, nil
  1543  		}
  1544  		if buf[len(buf)-1] == 0 {
  1545  			buf = buf[:len(buf)-1] // remove terminating null
  1546  		}
  1547  		languages := make([]string, 0, numLanguages)
  1548  		from := 0
  1549  		for i, c := range buf {
  1550  			if c == 0 {
  1551  				languages = append(languages, string(utf16.Decode(buf[from:i])))
  1552  				from = i + 1
  1553  			}
  1554  		}
  1555  		return languages, nil
  1556  	}
  1557  }
  1558  
  1559  func SetConsoleCursorPosition(console Handle, position Coord) error {
  1560  	return setConsoleCursorPosition(console, *((*uint32)(unsafe.Pointer(&position))))
  1561  }
  1562  
  1563  func (s NTStatus) Errno() syscall.Errno {
  1564  	return rtlNtStatusToDosErrorNoTeb(s)
  1565  }
  1566  
  1567  func langID(pri, sub uint16) uint32 { return uint32(sub)<<10 | uint32(pri) }
  1568  
  1569  func (s NTStatus) Error() string {
  1570  	b := make([]uint16, 300)
  1571  	n, err := FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_FROM_HMODULE|FORMAT_MESSAGE_ARGUMENT_ARRAY, modntdll.Handle(), uint32(s), langID(LANG_ENGLISH, SUBLANG_ENGLISH_US), b, nil)
  1572  	if err != nil {
  1573  		return fmt.Sprintf("NTSTATUS 0x%08x", uint32(s))
  1574  	}
  1575  	// trim terminating \r and \n
  1576  	for ; n > 0 && (b[n-1] == '\n' || b[n-1] == '\r'); n-- {
  1577  	}
  1578  	return string(utf16.Decode(b[:n]))
  1579  }
  1580  
  1581  // NewNTUnicodeString returns a new NTUnicodeString structure for use with native
  1582  // NT APIs that work over the NTUnicodeString type. Note that most Windows APIs
  1583  // do not use NTUnicodeString, and instead UTF16PtrFromString should be used for
  1584  // the more common *uint16 string type.
  1585  func NewNTUnicodeString(s string) (*NTUnicodeString, error) {
  1586  	var u NTUnicodeString
  1587  	s16, err := UTF16PtrFromString(s)
  1588  	if err != nil {
  1589  		return nil, err
  1590  	}
  1591  	RtlInitUnicodeString(&u, s16)
  1592  	return &u, nil
  1593  }
  1594  
  1595  // Slice returns a uint16 slice that aliases the data in the NTUnicodeString.
  1596  func (s *NTUnicodeString) Slice() []uint16 {
  1597  	var slice []uint16
  1598  	hdr := (*unsafeheader.Slice)(unsafe.Pointer(&slice))
  1599  	hdr.Data = unsafe.Pointer(s.Buffer)
  1600  	hdr.Len = int(s.Length)
  1601  	hdr.Cap = int(s.MaximumLength)
  1602  	return slice
  1603  }
  1604  
  1605  func (s *NTUnicodeString) String() string {
  1606  	return UTF16ToString(s.Slice())
  1607  }
  1608  
  1609  // NewNTString returns a new NTString structure for use with native
  1610  // NT APIs that work over the NTString type. Note that most Windows APIs
  1611  // do not use NTString, and instead UTF16PtrFromString should be used for
  1612  // the more common *uint16 string type.
  1613  func NewNTString(s string) (*NTString, error) {
  1614  	var nts NTString
  1615  	s8, err := BytePtrFromString(s)
  1616  	if err != nil {
  1617  		return nil, err
  1618  	}
  1619  	RtlInitString(&nts, s8)
  1620  	return &nts, nil
  1621  }
  1622  
  1623  // Slice returns a byte slice that aliases the data in the NTString.
  1624  func (s *NTString) Slice() []byte {
  1625  	var slice []byte
  1626  	hdr := (*unsafeheader.Slice)(unsafe.Pointer(&slice))
  1627  	hdr.Data = unsafe.Pointer(s.Buffer)
  1628  	hdr.Len = int(s.Length)
  1629  	hdr.Cap = int(s.MaximumLength)
  1630  	return slice
  1631  }
  1632  
  1633  func (s *NTString) String() string {
  1634  	return ByteSliceToString(s.Slice())
  1635  }
  1636  
  1637  // FindResource resolves a resource of the given name and resource type.
  1638  func FindResource(module Handle, name, resType ResourceIDOrString) (Handle, error) {
  1639  	var namePtr, resTypePtr uintptr
  1640  	var name16, resType16 *uint16
  1641  	var err error
  1642  	resolvePtr := func(i interface{}, keep **uint16) (uintptr, error) {
  1643  		switch v := i.(type) {
  1644  		case string:
  1645  			*keep, err = UTF16PtrFromString(v)
  1646  			if err != nil {
  1647  				return 0, err
  1648  			}
  1649  			return uintptr(unsafe.Pointer(*keep)), nil
  1650  		case ResourceID:
  1651  			return uintptr(v), nil
  1652  		}
  1653  		return 0, errorspkg.New("parameter must be a ResourceID or a string")
  1654  	}
  1655  	namePtr, err = resolvePtr(name, &name16)
  1656  	if err != nil {
  1657  		return 0, err
  1658  	}
  1659  	resTypePtr, err = resolvePtr(resType, &resType16)
  1660  	if err != nil {
  1661  		return 0, err
  1662  	}
  1663  	resInfo, err := findResource(module, namePtr, resTypePtr)
  1664  	runtime.KeepAlive(name16)
  1665  	runtime.KeepAlive(resType16)
  1666  	return resInfo, err
  1667  }
  1668  
  1669  func LoadResourceData(module, resInfo Handle) (data []byte, err error) {
  1670  	size, err := SizeofResource(module, resInfo)
  1671  	if err != nil {
  1672  		return
  1673  	}
  1674  	resData, err := LoadResource(module, resInfo)
  1675  	if err != nil {
  1676  		return
  1677  	}
  1678  	ptr, err := LockResource(resData)
  1679  	if err != nil {
  1680  		return
  1681  	}
  1682  	h := (*unsafeheader.Slice)(unsafe.Pointer(&data))
  1683  	h.Data = unsafe.Pointer(ptr)
  1684  	h.Len = int(size)
  1685  	h.Cap = int(size)
  1686  	return
  1687  }
  1688  

View as plain text