gtsocial-umbx

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README | LICENSE

syscall_windows.go (80915B)


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