...

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

Documentation: golang.org/x/sys/windows

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

View as plain text