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

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

View as plain text