Path: blob/main/vendor/golang.org/x/sys/windows/syscall_windows.go
2880 views
// Copyright 2009 The Go Authors. All rights reserved.1// Use of this source code is governed by a BSD-style2// license that can be found in the LICENSE file.34// Windows system calls.56package windows78import (9errorspkg "errors"10"fmt"11"runtime"12"sync"13"syscall"14"time"15"unicode/utf16"16"unsafe"17)1819type (20Handle uintptr21HWND uintptr22)2324const (25InvalidHandle = ^Handle(0)26InvalidHWND = ^HWND(0)2728// Flags for DefineDosDevice.29DDD_EXACT_MATCH_ON_REMOVE = 0x0000000430DDD_NO_BROADCAST_SYSTEM = 0x0000000831DDD_RAW_TARGET_PATH = 0x0000000132DDD_REMOVE_DEFINITION = 0x000000023334// Return values for GetDriveType.35DRIVE_UNKNOWN = 036DRIVE_NO_ROOT_DIR = 137DRIVE_REMOVABLE = 238DRIVE_FIXED = 339DRIVE_REMOTE = 440DRIVE_CDROM = 541DRIVE_RAMDISK = 64243// File system flags from GetVolumeInformation and GetVolumeInformationByHandle.44FILE_CASE_SENSITIVE_SEARCH = 0x0000000145FILE_CASE_PRESERVED_NAMES = 0x0000000246FILE_FILE_COMPRESSION = 0x0000001047FILE_DAX_VOLUME = 0x2000000048FILE_NAMED_STREAMS = 0x0004000049FILE_PERSISTENT_ACLS = 0x0000000850FILE_READ_ONLY_VOLUME = 0x0008000051FILE_SEQUENTIAL_WRITE_ONCE = 0x0010000052FILE_SUPPORTS_ENCRYPTION = 0x0002000053FILE_SUPPORTS_EXTENDED_ATTRIBUTES = 0x0080000054FILE_SUPPORTS_HARD_LINKS = 0x0040000055FILE_SUPPORTS_OBJECT_IDS = 0x0001000056FILE_SUPPORTS_OPEN_BY_FILE_ID = 0x0100000057FILE_SUPPORTS_REPARSE_POINTS = 0x0000008058FILE_SUPPORTS_SPARSE_FILES = 0x0000004059FILE_SUPPORTS_TRANSACTIONS = 0x0020000060FILE_SUPPORTS_USN_JOURNAL = 0x0200000061FILE_UNICODE_ON_DISK = 0x0000000462FILE_VOLUME_IS_COMPRESSED = 0x0000800063FILE_VOLUME_QUOTAS = 0x000000206465// Flags for LockFileEx.66LOCKFILE_FAIL_IMMEDIATELY = 0x0000000167LOCKFILE_EXCLUSIVE_LOCK = 0x000000026869// Return value of SleepEx and other APC functions70WAIT_IO_COMPLETION = 0x000000C071)7273// StringToUTF16 is deprecated. Use UTF16FromString instead.74// If s contains a NUL byte this function panics instead of75// returning an error.76func StringToUTF16(s string) []uint16 {77a, err := UTF16FromString(s)78if err != nil {79panic("windows: string with NUL passed to StringToUTF16")80}81return a82}8384// UTF16FromString returns the UTF-16 encoding of the UTF-8 string85// s, with a terminating NUL added. If s contains a NUL byte at any86// location, it returns (nil, syscall.EINVAL).87func UTF16FromString(s string) ([]uint16, error) {88return syscall.UTF16FromString(s)89}9091// UTF16ToString returns the UTF-8 encoding of the UTF-16 sequence s,92// with a terminating NUL and any bytes after the NUL removed.93func UTF16ToString(s []uint16) string {94return syscall.UTF16ToString(s)95}9697// StringToUTF16Ptr is deprecated. Use UTF16PtrFromString instead.98// If s contains a NUL byte this function panics instead of99// returning an error.100func StringToUTF16Ptr(s string) *uint16 { return &StringToUTF16(s)[0] }101102// UTF16PtrFromString returns pointer to the UTF-16 encoding of103// the UTF-8 string s, with a terminating NUL added. If s104// contains a NUL byte at any location, it returns (nil, syscall.EINVAL).105func UTF16PtrFromString(s string) (*uint16, error) {106a, err := UTF16FromString(s)107if err != nil {108return nil, err109}110return &a[0], nil111}112113// UTF16PtrToString takes a pointer to a UTF-16 sequence and returns the corresponding UTF-8 encoded string.114// If the pointer is nil, it returns the empty string. It assumes that the UTF-16 sequence is terminated115// at a zero word; if the zero word is not present, the program may crash.116func UTF16PtrToString(p *uint16) string {117if p == nil {118return ""119}120if *p == 0 {121return ""122}123124// Find NUL terminator.125n := 0126for ptr := unsafe.Pointer(p); *(*uint16)(ptr) != 0; n++ {127ptr = unsafe.Pointer(uintptr(ptr) + unsafe.Sizeof(*p))128}129return UTF16ToString(unsafe.Slice(p, n))130}131132func Getpagesize() int { return 4096 }133134// NewCallback converts a Go function to a function pointer conforming to the stdcall calling convention.135// This is useful when interoperating with Windows code requiring callbacks.136// 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.137func NewCallback(fn interface{}) uintptr {138return syscall.NewCallback(fn)139}140141// NewCallbackCDecl converts a Go function to a function pointer conforming to the cdecl calling convention.142// This is useful when interoperating with Windows code requiring callbacks.143// 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.144func NewCallbackCDecl(fn interface{}) uintptr {145return syscall.NewCallbackCDecl(fn)146}147148// windows api calls149150//sys GetLastError() (lasterr error)151//sys LoadLibrary(libname string) (handle Handle, err error) = LoadLibraryW152//sys LoadLibraryEx(libname string, zero Handle, flags uintptr) (handle Handle, err error) = LoadLibraryExW153//sys FreeLibrary(handle Handle) (err error)154//sys GetProcAddress(module Handle, procname string) (proc uintptr, err error)155//sys GetModuleFileName(module Handle, filename *uint16, size uint32) (n uint32, err error) = kernel32.GetModuleFileNameW156//sys GetModuleHandleEx(flags uint32, moduleName *uint16, module *Handle) (err error) = kernel32.GetModuleHandleExW157//sys SetDefaultDllDirectories(directoryFlags uint32) (err error)158//sys AddDllDirectory(path *uint16) (cookie uintptr, err error) = kernel32.AddDllDirectory159//sys RemoveDllDirectory(cookie uintptr) (err error) = kernel32.RemoveDllDirectory160//sys SetDllDirectory(path string) (err error) = kernel32.SetDllDirectoryW161//sys GetVersion() (ver uint32, err error)162//sys FormatMessage(flags uint32, msgsrc uintptr, msgid uint32, langid uint32, buf []uint16, args *byte) (n uint32, err error) = FormatMessageW163//sys ExitProcess(exitcode uint32)164//sys IsWow64Process(handle Handle, isWow64 *bool) (err error) = IsWow64Process165//sys IsWow64Process2(handle Handle, processMachine *uint16, nativeMachine *uint16) (err error) = IsWow64Process2?166//sys CreateFile(name *uint16, access uint32, mode uint32, sa *SecurityAttributes, createmode uint32, attrs uint32, templatefile Handle) (handle Handle, err error) [failretval==InvalidHandle] = CreateFileW167//sys CreateNamedPipe(name *uint16, flags uint32, pipeMode uint32, maxInstances uint32, outSize uint32, inSize uint32, defaultTimeout uint32, sa *SecurityAttributes) (handle Handle, err error) [failretval==InvalidHandle] = CreateNamedPipeW168//sys ConnectNamedPipe(pipe Handle, overlapped *Overlapped) (err error)169//sys DisconnectNamedPipe(pipe Handle) (err error)170//sys GetNamedPipeClientProcessId(pipe Handle, clientProcessID *uint32) (err error)171//sys GetNamedPipeServerProcessId(pipe Handle, serverProcessID *uint32) (err error)172//sys GetNamedPipeInfo(pipe Handle, flags *uint32, outSize *uint32, inSize *uint32, maxInstances *uint32) (err error)173//sys GetNamedPipeHandleState(pipe Handle, state *uint32, curInstances *uint32, maxCollectionCount *uint32, collectDataTimeout *uint32, userName *uint16, maxUserNameSize uint32) (err error) = GetNamedPipeHandleStateW174//sys SetNamedPipeHandleState(pipe Handle, state *uint32, maxCollectionCount *uint32, collectDataTimeout *uint32) (err error) = SetNamedPipeHandleState175//sys readFile(handle Handle, buf []byte, done *uint32, overlapped *Overlapped) (err error) = ReadFile176//sys writeFile(handle Handle, buf []byte, done *uint32, overlapped *Overlapped) (err error) = WriteFile177//sys GetOverlappedResult(handle Handle, overlapped *Overlapped, done *uint32, wait bool) (err error)178//sys SetFilePointer(handle Handle, lowoffset int32, highoffsetptr *int32, whence uint32) (newlowoffset uint32, err error) [failretval==0xffffffff]179//sys CloseHandle(handle Handle) (err error)180//sys GetStdHandle(stdhandle uint32) (handle Handle, err error) [failretval==InvalidHandle]181//sys SetStdHandle(stdhandle uint32, handle Handle) (err error)182//sys findFirstFile1(name *uint16, data *win32finddata1) (handle Handle, err error) [failretval==InvalidHandle] = FindFirstFileW183//sys findNextFile1(handle Handle, data *win32finddata1) (err error) = FindNextFileW184//sys FindClose(handle Handle) (err error)185//sys GetFileInformationByHandle(handle Handle, data *ByHandleFileInformation) (err error)186//sys GetFileInformationByHandleEx(handle Handle, class uint32, outBuffer *byte, outBufferLen uint32) (err error)187//sys SetFileInformationByHandle(handle Handle, class uint32, inBuffer *byte, inBufferLen uint32) (err error)188//sys GetCurrentDirectory(buflen uint32, buf *uint16) (n uint32, err error) = GetCurrentDirectoryW189//sys SetCurrentDirectory(path *uint16) (err error) = SetCurrentDirectoryW190//sys CreateDirectory(path *uint16, sa *SecurityAttributes) (err error) = CreateDirectoryW191//sys RemoveDirectory(path *uint16) (err error) = RemoveDirectoryW192//sys DeleteFile(path *uint16) (err error) = DeleteFileW193//sys MoveFile(from *uint16, to *uint16) (err error) = MoveFileW194//sys MoveFileEx(from *uint16, to *uint16, flags uint32) (err error) = MoveFileExW195//sys LockFileEx(file Handle, flags uint32, reserved uint32, bytesLow uint32, bytesHigh uint32, overlapped *Overlapped) (err error)196//sys UnlockFileEx(file Handle, reserved uint32, bytesLow uint32, bytesHigh uint32, overlapped *Overlapped) (err error)197//sys GetComputerName(buf *uint16, n *uint32) (err error) = GetComputerNameW198//sys GetComputerNameEx(nametype uint32, buf *uint16, n *uint32) (err error) = GetComputerNameExW199//sys SetEndOfFile(handle Handle) (err error)200//sys SetFileValidData(handle Handle, validDataLength int64) (err error)201//sys GetSystemTimeAsFileTime(time *Filetime)202//sys GetSystemTimePreciseAsFileTime(time *Filetime)203//sys GetTimeZoneInformation(tzi *Timezoneinformation) (rc uint32, err error) [failretval==0xffffffff]204//sys CreateIoCompletionPort(filehandle Handle, cphandle Handle, key uintptr, threadcnt uint32) (handle Handle, err error)205//sys GetQueuedCompletionStatus(cphandle Handle, qty *uint32, key *uintptr, overlapped **Overlapped, timeout uint32) (err error)206//sys PostQueuedCompletionStatus(cphandle Handle, qty uint32, key uintptr, overlapped *Overlapped) (err error)207//sys CancelIo(s Handle) (err error)208//sys CancelIoEx(s Handle, o *Overlapped) (err error)209//sys CreateProcess(appName *uint16, commandLine *uint16, procSecurity *SecurityAttributes, threadSecurity *SecurityAttributes, inheritHandles bool, creationFlags uint32, env *uint16, currentDir *uint16, startupInfo *StartupInfo, outProcInfo *ProcessInformation) (err error) = CreateProcessW210//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.CreateProcessAsUserW211//sys initializeProcThreadAttributeList(attrlist *ProcThreadAttributeList, attrcount uint32, flags uint32, size *uintptr) (err error) = InitializeProcThreadAttributeList212//sys deleteProcThreadAttributeList(attrlist *ProcThreadAttributeList) = DeleteProcThreadAttributeList213//sys updateProcThreadAttribute(attrlist *ProcThreadAttributeList, flags uint32, attr uintptr, value unsafe.Pointer, size uintptr, prevvalue unsafe.Pointer, returnedsize *uintptr) (err error) = UpdateProcThreadAttribute214//sys OpenProcess(desiredAccess uint32, inheritHandle bool, processId uint32) (handle Handle, err error)215//sys ShellExecute(hwnd Handle, verb *uint16, file *uint16, args *uint16, cwd *uint16, showCmd int32) (err error) [failretval<=32] = shell32.ShellExecuteW216//sys GetWindowThreadProcessId(hwnd HWND, pid *uint32) (tid uint32, err error) = user32.GetWindowThreadProcessId217//sys LoadKeyboardLayout(name *uint16, flags uint32) (hkl Handle, err error) [failretval==0] = user32.LoadKeyboardLayoutW218//sys UnloadKeyboardLayout(hkl Handle) (err error) = user32.UnloadKeyboardLayout219//sys GetKeyboardLayout(tid uint32) (hkl Handle) = user32.GetKeyboardLayout220//sys ToUnicodeEx(vkey uint32, scancode uint32, keystate *byte, pwszBuff *uint16, cchBuff int32, flags uint32, hkl Handle) (ret int32) = user32.ToUnicodeEx221//sys GetShellWindow() (shellWindow HWND) = user32.GetShellWindow222//sys MessageBox(hwnd HWND, text *uint16, caption *uint16, boxtype uint32) (ret int32, err error) [failretval==0] = user32.MessageBoxW223//sys ExitWindowsEx(flags uint32, reason uint32) (err error) = user32.ExitWindowsEx224//sys shGetKnownFolderPath(id *KNOWNFOLDERID, flags uint32, token Token, path **uint16) (ret error) = shell32.SHGetKnownFolderPath225//sys TerminateProcess(handle Handle, exitcode uint32) (err error)226//sys GetExitCodeProcess(handle Handle, exitcode *uint32) (err error)227//sys getStartupInfo(startupInfo *StartupInfo) = GetStartupInfoW228//sys GetProcessTimes(handle Handle, creationTime *Filetime, exitTime *Filetime, kernelTime *Filetime, userTime *Filetime) (err error)229//sys DuplicateHandle(hSourceProcessHandle Handle, hSourceHandle Handle, hTargetProcessHandle Handle, lpTargetHandle *Handle, dwDesiredAccess uint32, bInheritHandle bool, dwOptions uint32) (err error)230//sys WaitForSingleObject(handle Handle, waitMilliseconds uint32) (event uint32, err error) [failretval==0xffffffff]231//sys waitForMultipleObjects(count uint32, handles uintptr, waitAll bool, waitMilliseconds uint32) (event uint32, err error) [failretval==0xffffffff] = WaitForMultipleObjects232//sys GetTempPath(buflen uint32, buf *uint16) (n uint32, err error) = GetTempPathW233//sys CreatePipe(readhandle *Handle, writehandle *Handle, sa *SecurityAttributes, size uint32) (err error)234//sys GetFileType(filehandle Handle) (n uint32, err error)235//sys CryptAcquireContext(provhandle *Handle, container *uint16, provider *uint16, provtype uint32, flags uint32) (err error) = advapi32.CryptAcquireContextW236//sys CryptReleaseContext(provhandle Handle, flags uint32) (err error) = advapi32.CryptReleaseContext237//sys CryptGenRandom(provhandle Handle, buflen uint32, buf *byte) (err error) = advapi32.CryptGenRandom238//sys GetEnvironmentStrings() (envs *uint16, err error) [failretval==nil] = kernel32.GetEnvironmentStringsW239//sys FreeEnvironmentStrings(envs *uint16) (err error) = kernel32.FreeEnvironmentStringsW240//sys GetEnvironmentVariable(name *uint16, buffer *uint16, size uint32) (n uint32, err error) = kernel32.GetEnvironmentVariableW241//sys SetEnvironmentVariable(name *uint16, value *uint16) (err error) = kernel32.SetEnvironmentVariableW242//sys ExpandEnvironmentStrings(src *uint16, dst *uint16, size uint32) (n uint32, err error) = kernel32.ExpandEnvironmentStringsW243//sys CreateEnvironmentBlock(block **uint16, token Token, inheritExisting bool) (err error) = userenv.CreateEnvironmentBlock244//sys DestroyEnvironmentBlock(block *uint16) (err error) = userenv.DestroyEnvironmentBlock245//sys getTickCount64() (ms uint64) = kernel32.GetTickCount64246//sys GetFileTime(handle Handle, ctime *Filetime, atime *Filetime, wtime *Filetime) (err error)247//sys SetFileTime(handle Handle, ctime *Filetime, atime *Filetime, wtime *Filetime) (err error)248//sys GetFileAttributes(name *uint16) (attrs uint32, err error) [failretval==INVALID_FILE_ATTRIBUTES] = kernel32.GetFileAttributesW249//sys SetFileAttributes(name *uint16, attrs uint32) (err error) = kernel32.SetFileAttributesW250//sys GetFileAttributesEx(name *uint16, level uint32, info *byte) (err error) = kernel32.GetFileAttributesExW251//sys GetCommandLine() (cmd *uint16) = kernel32.GetCommandLineW252//sys commandLineToArgv(cmd *uint16, argc *int32) (argv **uint16, err error) [failretval==nil] = shell32.CommandLineToArgvW253//sys LocalFree(hmem Handle) (handle Handle, err error) [failretval!=0]254//sys LocalAlloc(flags uint32, length uint32) (ptr uintptr, err error)255//sys SetHandleInformation(handle Handle, mask uint32, flags uint32) (err error)256//sys FlushFileBuffers(handle Handle) (err error)257//sys GetFullPathName(path *uint16, buflen uint32, buf *uint16, fname **uint16) (n uint32, err error) = kernel32.GetFullPathNameW258//sys GetLongPathName(path *uint16, buf *uint16, buflen uint32) (n uint32, err error) = kernel32.GetLongPathNameW259//sys GetShortPathName(longpath *uint16, shortpath *uint16, buflen uint32) (n uint32, err error) = kernel32.GetShortPathNameW260//sys GetFinalPathNameByHandle(file Handle, filePath *uint16, filePathSize uint32, flags uint32) (n uint32, err error) = kernel32.GetFinalPathNameByHandleW261//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.CreateFileMappingW262//sys MapViewOfFile(handle Handle, access uint32, offsetHigh uint32, offsetLow uint32, length uintptr) (addr uintptr, err error)263//sys UnmapViewOfFile(addr uintptr) (err error)264//sys FlushViewOfFile(addr uintptr, length uintptr) (err error)265//sys VirtualLock(addr uintptr, length uintptr) (err error)266//sys VirtualUnlock(addr uintptr, length uintptr) (err error)267//sys VirtualAlloc(address uintptr, size uintptr, alloctype uint32, protect uint32) (value uintptr, err error) = kernel32.VirtualAlloc268//sys VirtualFree(address uintptr, size uintptr, freetype uint32) (err error) = kernel32.VirtualFree269//sys VirtualProtect(address uintptr, size uintptr, newprotect uint32, oldprotect *uint32) (err error) = kernel32.VirtualProtect270//sys VirtualProtectEx(process Handle, address uintptr, size uintptr, newProtect uint32, oldProtect *uint32) (err error) = kernel32.VirtualProtectEx271//sys VirtualQuery(address uintptr, buffer *MemoryBasicInformation, length uintptr) (err error) = kernel32.VirtualQuery272//sys VirtualQueryEx(process Handle, address uintptr, buffer *MemoryBasicInformation, length uintptr) (err error) = kernel32.VirtualQueryEx273//sys ReadProcessMemory(process Handle, baseAddress uintptr, buffer *byte, size uintptr, numberOfBytesRead *uintptr) (err error) = kernel32.ReadProcessMemory274//sys WriteProcessMemory(process Handle, baseAddress uintptr, buffer *byte, size uintptr, numberOfBytesWritten *uintptr) (err error) = kernel32.WriteProcessMemory275//sys TransmitFile(s Handle, handle Handle, bytesToWrite uint32, bytsPerSend uint32, overlapped *Overlapped, transmitFileBuf *TransmitFileBuffers, flags uint32) (err error) = mswsock.TransmitFile276//sys ReadDirectoryChanges(handle Handle, buf *byte, buflen uint32, watchSubTree bool, mask uint32, retlen *uint32, overlapped *Overlapped, completionRoutine uintptr) (err error) = kernel32.ReadDirectoryChangesW277//sys FindFirstChangeNotification(path string, watchSubtree bool, notifyFilter uint32) (handle Handle, err error) [failretval==InvalidHandle] = kernel32.FindFirstChangeNotificationW278//sys FindNextChangeNotification(handle Handle) (err error)279//sys FindCloseChangeNotification(handle Handle) (err error)280//sys CertOpenSystemStore(hprov Handle, name *uint16) (store Handle, err error) = crypt32.CertOpenSystemStoreW281//sys CertOpenStore(storeProvider uintptr, msgAndCertEncodingType uint32, cryptProv uintptr, flags uint32, para uintptr) (handle Handle, err error) = crypt32.CertOpenStore282//sys CertEnumCertificatesInStore(store Handle, prevContext *CertContext) (context *CertContext, err error) [failretval==nil] = crypt32.CertEnumCertificatesInStore283//sys CertAddCertificateContextToStore(store Handle, certContext *CertContext, addDisposition uint32, storeContext **CertContext) (err error) = crypt32.CertAddCertificateContextToStore284//sys CertCloseStore(store Handle, flags uint32) (err error) = crypt32.CertCloseStore285//sys CertDeleteCertificateFromStore(certContext *CertContext) (err error) = crypt32.CertDeleteCertificateFromStore286//sys CertDuplicateCertificateContext(certContext *CertContext) (dupContext *CertContext) = crypt32.CertDuplicateCertificateContext287//sys PFXImportCertStore(pfx *CryptDataBlob, password *uint16, flags uint32) (store Handle, err error) = crypt32.PFXImportCertStore288//sys CertGetCertificateChain(engine Handle, leaf *CertContext, time *Filetime, additionalStore Handle, para *CertChainPara, flags uint32, reserved uintptr, chainCtx **CertChainContext) (err error) = crypt32.CertGetCertificateChain289//sys CertFreeCertificateChain(ctx *CertChainContext) = crypt32.CertFreeCertificateChain290//sys CertCreateCertificateContext(certEncodingType uint32, certEncoded *byte, encodedLen uint32) (context *CertContext, err error) [failretval==nil] = crypt32.CertCreateCertificateContext291//sys CertFreeCertificateContext(ctx *CertContext) (err error) = crypt32.CertFreeCertificateContext292//sys CertVerifyCertificateChainPolicy(policyOID uintptr, chain *CertChainContext, para *CertChainPolicyPara, status *CertChainPolicyStatus) (err error) = crypt32.CertVerifyCertificateChainPolicy293//sys CertGetNameString(certContext *CertContext, nameType uint32, flags uint32, typePara unsafe.Pointer, name *uint16, size uint32) (chars uint32) = crypt32.CertGetNameStringW294//sys CertFindExtension(objId *byte, countExtensions uint32, extensions *CertExtension) (ret *CertExtension) = crypt32.CertFindExtension295//sys CertFindCertificateInStore(store Handle, certEncodingType uint32, findFlags uint32, findType uint32, findPara unsafe.Pointer, prevCertContext *CertContext) (cert *CertContext, err error) [failretval==nil] = crypt32.CertFindCertificateInStore296//sys CertFindChainInStore(store Handle, certEncodingType uint32, findFlags uint32, findType uint32, findPara unsafe.Pointer, prevChainContext *CertChainContext) (certchain *CertChainContext, err error) [failretval==nil] = crypt32.CertFindChainInStore297//sys CryptAcquireCertificatePrivateKey(cert *CertContext, flags uint32, parameters unsafe.Pointer, cryptProvOrNCryptKey *Handle, keySpec *uint32, callerFreeProvOrNCryptKey *bool) (err error) = crypt32.CryptAcquireCertificatePrivateKey298//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.CryptQueryObject299//sys CryptDecodeObject(encodingType uint32, structType *byte, encodedBytes *byte, lenEncodedBytes uint32, flags uint32, decoded unsafe.Pointer, decodedLen *uint32) (err error) = crypt32.CryptDecodeObject300//sys CryptProtectData(dataIn *DataBlob, name *uint16, optionalEntropy *DataBlob, reserved uintptr, promptStruct *CryptProtectPromptStruct, flags uint32, dataOut *DataBlob) (err error) = crypt32.CryptProtectData301//sys CryptUnprotectData(dataIn *DataBlob, name **uint16, optionalEntropy *DataBlob, reserved uintptr, promptStruct *CryptProtectPromptStruct, flags uint32, dataOut *DataBlob) (err error) = crypt32.CryptUnprotectData302//sys WinVerifyTrustEx(hwnd HWND, actionId *GUID, data *WinTrustData) (ret error) = wintrust.WinVerifyTrustEx303//sys RegOpenKeyEx(key Handle, subkey *uint16, options uint32, desiredAccess uint32, result *Handle) (regerrno error) = advapi32.RegOpenKeyExW304//sys RegCloseKey(key Handle) (regerrno error) = advapi32.RegCloseKey305//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.RegQueryInfoKeyW306//sys RegEnumKeyEx(key Handle, index uint32, name *uint16, nameLen *uint32, reserved *uint32, class *uint16, classLen *uint32, lastWriteTime *Filetime) (regerrno error) = advapi32.RegEnumKeyExW307//sys RegQueryValueEx(key Handle, name *uint16, reserved *uint32, valtype *uint32, buf *byte, buflen *uint32) (regerrno error) = advapi32.RegQueryValueExW308//sys RegNotifyChangeKeyValue(key Handle, watchSubtree bool, notifyFilter uint32, event Handle, asynchronous bool) (regerrno error) = advapi32.RegNotifyChangeKeyValue309//sys GetCurrentProcessId() (pid uint32) = kernel32.GetCurrentProcessId310//sys ProcessIdToSessionId(pid uint32, sessionid *uint32) (err error) = kernel32.ProcessIdToSessionId311//sys ClosePseudoConsole(console Handle) = kernel32.ClosePseudoConsole312//sys createPseudoConsole(size uint32, in Handle, out Handle, flags uint32, pconsole *Handle) (hr error) = kernel32.CreatePseudoConsole313//sys GetConsoleMode(console Handle, mode *uint32) (err error) = kernel32.GetConsoleMode314//sys SetConsoleMode(console Handle, mode uint32) (err error) = kernel32.SetConsoleMode315//sys GetConsoleScreenBufferInfo(console Handle, info *ConsoleScreenBufferInfo) (err error) = kernel32.GetConsoleScreenBufferInfo316//sys setConsoleCursorPosition(console Handle, position uint32) (err error) = kernel32.SetConsoleCursorPosition317//sys GetConsoleCP() (cp uint32, err error) = kernel32.GetConsoleCP318//sys GetConsoleOutputCP() (cp uint32, err error) = kernel32.GetConsoleOutputCP319//sys SetConsoleCP(cp uint32) (err error) = kernel32.SetConsoleCP320//sys SetConsoleOutputCP(cp uint32) (err error) = kernel32.SetConsoleOutputCP321//sys WriteConsole(console Handle, buf *uint16, towrite uint32, written *uint32, reserved *byte) (err error) = kernel32.WriteConsoleW322//sys ReadConsole(console Handle, buf *uint16, toread uint32, read *uint32, inputControl *byte) (err error) = kernel32.ReadConsoleW323//sys GetNumberOfConsoleInputEvents(console Handle, numevents *uint32) (err error) = kernel32.GetNumberOfConsoleInputEvents324//sys FlushConsoleInputBuffer(console Handle) (err error) = kernel32.FlushConsoleInputBuffer325//sys resizePseudoConsole(pconsole Handle, size uint32) (hr error) = kernel32.ResizePseudoConsole326//sys CreateToolhelp32Snapshot(flags uint32, processId uint32) (handle Handle, err error) [failretval==InvalidHandle] = kernel32.CreateToolhelp32Snapshot327//sys Module32First(snapshot Handle, moduleEntry *ModuleEntry32) (err error) = kernel32.Module32FirstW328//sys Module32Next(snapshot Handle, moduleEntry *ModuleEntry32) (err error) = kernel32.Module32NextW329//sys Process32First(snapshot Handle, procEntry *ProcessEntry32) (err error) = kernel32.Process32FirstW330//sys Process32Next(snapshot Handle, procEntry *ProcessEntry32) (err error) = kernel32.Process32NextW331//sys Thread32First(snapshot Handle, threadEntry *ThreadEntry32) (err error)332//sys Thread32Next(snapshot Handle, threadEntry *ThreadEntry32) (err error)333//sys DeviceIoControl(handle Handle, ioControlCode uint32, inBuffer *byte, inBufferSize uint32, outBuffer *byte, outBufferSize uint32, bytesReturned *uint32, overlapped *Overlapped) (err error)334// This function returns 1 byte BOOLEAN rather than the 4 byte BOOL.335//sys CreateSymbolicLink(symlinkfilename *uint16, targetfilename *uint16, flags uint32) (err error) [failretval&0xff==0] = CreateSymbolicLinkW336//sys CreateHardLink(filename *uint16, existingfilename *uint16, reserved uintptr) (err error) [failretval&0xff==0] = CreateHardLinkW337//sys GetCurrentThreadId() (id uint32)338//sys CreateEvent(eventAttrs *SecurityAttributes, manualReset uint32, initialState uint32, name *uint16) (handle Handle, err error) [failretval == 0 || e1 == ERROR_ALREADY_EXISTS] = kernel32.CreateEventW339//sys CreateEventEx(eventAttrs *SecurityAttributes, name *uint16, flags uint32, desiredAccess uint32) (handle Handle, err error) [failretval == 0 || e1 == ERROR_ALREADY_EXISTS] = kernel32.CreateEventExW340//sys OpenEvent(desiredAccess uint32, inheritHandle bool, name *uint16) (handle Handle, err error) = kernel32.OpenEventW341//sys SetEvent(event Handle) (err error) = kernel32.SetEvent342//sys ResetEvent(event Handle) (err error) = kernel32.ResetEvent343//sys PulseEvent(event Handle) (err error) = kernel32.PulseEvent344//sys CreateMutex(mutexAttrs *SecurityAttributes, initialOwner bool, name *uint16) (handle Handle, err error) [failretval == 0 || e1 == ERROR_ALREADY_EXISTS] = kernel32.CreateMutexW345//sys CreateMutexEx(mutexAttrs *SecurityAttributes, name *uint16, flags uint32, desiredAccess uint32) (handle Handle, err error) [failretval == 0 || e1 == ERROR_ALREADY_EXISTS] = kernel32.CreateMutexExW346//sys OpenMutex(desiredAccess uint32, inheritHandle bool, name *uint16) (handle Handle, err error) = kernel32.OpenMutexW347//sys ReleaseMutex(mutex Handle) (err error) = kernel32.ReleaseMutex348//sys SleepEx(milliseconds uint32, alertable bool) (ret uint32) = kernel32.SleepEx349//sys CreateJobObject(jobAttr *SecurityAttributes, name *uint16) (handle Handle, err error) = kernel32.CreateJobObjectW350//sys AssignProcessToJobObject(job Handle, process Handle) (err error) = kernel32.AssignProcessToJobObject351//sys TerminateJobObject(job Handle, exitCode uint32) (err error) = kernel32.TerminateJobObject352//sys SetErrorMode(mode uint32) (ret uint32) = kernel32.SetErrorMode353//sys ResumeThread(thread Handle) (ret uint32, err error) [failretval==0xffffffff] = kernel32.ResumeThread354//sys SetPriorityClass(process Handle, priorityClass uint32) (err error) = kernel32.SetPriorityClass355//sys GetPriorityClass(process Handle) (ret uint32, err error) = kernel32.GetPriorityClass356//sys QueryInformationJobObject(job Handle, JobObjectInformationClass int32, JobObjectInformation uintptr, JobObjectInformationLength uint32, retlen *uint32) (err error) = kernel32.QueryInformationJobObject357//sys SetInformationJobObject(job Handle, JobObjectInformationClass uint32, JobObjectInformation uintptr, JobObjectInformationLength uint32) (ret int, err error)358//sys GenerateConsoleCtrlEvent(ctrlEvent uint32, processGroupID uint32) (err error)359//sys GetProcessId(process Handle) (id uint32, err error)360//sys QueryFullProcessImageName(proc Handle, flags uint32, exeName *uint16, size *uint32) (err error) = kernel32.QueryFullProcessImageNameW361//sys OpenThread(desiredAccess uint32, inheritHandle bool, threadId uint32) (handle Handle, err error)362//sys SetProcessPriorityBoost(process Handle, disable bool) (err error) = kernel32.SetProcessPriorityBoost363//sys GetProcessWorkingSetSizeEx(hProcess Handle, lpMinimumWorkingSetSize *uintptr, lpMaximumWorkingSetSize *uintptr, flags *uint32)364//sys SetProcessWorkingSetSizeEx(hProcess Handle, dwMinimumWorkingSetSize uintptr, dwMaximumWorkingSetSize uintptr, flags uint32) (err error)365//sys ClearCommBreak(handle Handle) (err error)366//sys ClearCommError(handle Handle, lpErrors *uint32, lpStat *ComStat) (err error)367//sys EscapeCommFunction(handle Handle, dwFunc uint32) (err error)368//sys GetCommState(handle Handle, lpDCB *DCB) (err error)369//sys GetCommModemStatus(handle Handle, lpModemStat *uint32) (err error)370//sys GetCommTimeouts(handle Handle, timeouts *CommTimeouts) (err error)371//sys PurgeComm(handle Handle, dwFlags uint32) (err error)372//sys SetCommBreak(handle Handle) (err error)373//sys SetCommMask(handle Handle, dwEvtMask uint32) (err error)374//sys SetCommState(handle Handle, lpDCB *DCB) (err error)375//sys SetCommTimeouts(handle Handle, timeouts *CommTimeouts) (err error)376//sys SetupComm(handle Handle, dwInQueue uint32, dwOutQueue uint32) (err error)377//sys WaitCommEvent(handle Handle, lpEvtMask *uint32, lpOverlapped *Overlapped) (err error)378//sys GetActiveProcessorCount(groupNumber uint16) (ret uint32)379//sys GetMaximumProcessorCount(groupNumber uint16) (ret uint32)380//sys EnumWindows(enumFunc uintptr, param unsafe.Pointer) (err error) = user32.EnumWindows381//sys EnumChildWindows(hwnd HWND, enumFunc uintptr, param unsafe.Pointer) = user32.EnumChildWindows382//sys GetClassName(hwnd HWND, className *uint16, maxCount int32) (copied int32, err error) = user32.GetClassNameW383//sys GetDesktopWindow() (hwnd HWND) = user32.GetDesktopWindow384//sys GetForegroundWindow() (hwnd HWND) = user32.GetForegroundWindow385//sys IsWindow(hwnd HWND) (isWindow bool) = user32.IsWindow386//sys IsWindowUnicode(hwnd HWND) (isUnicode bool) = user32.IsWindowUnicode387//sys IsWindowVisible(hwnd HWND) (isVisible bool) = user32.IsWindowVisible388//sys GetGUIThreadInfo(thread uint32, info *GUIThreadInfo) (err error) = user32.GetGUIThreadInfo389//sys GetLargePageMinimum() (size uintptr)390391// Volume Management Functions392//sys DefineDosDevice(flags uint32, deviceName *uint16, targetPath *uint16) (err error) = DefineDosDeviceW393//sys DeleteVolumeMountPoint(volumeMountPoint *uint16) (err error) = DeleteVolumeMountPointW394//sys FindFirstVolume(volumeName *uint16, bufferLength uint32) (handle Handle, err error) [failretval==InvalidHandle] = FindFirstVolumeW395//sys FindFirstVolumeMountPoint(rootPathName *uint16, volumeMountPoint *uint16, bufferLength uint32) (handle Handle, err error) [failretval==InvalidHandle] = FindFirstVolumeMountPointW396//sys FindNextVolume(findVolume Handle, volumeName *uint16, bufferLength uint32) (err error) = FindNextVolumeW397//sys FindNextVolumeMountPoint(findVolumeMountPoint Handle, volumeMountPoint *uint16, bufferLength uint32) (err error) = FindNextVolumeMountPointW398//sys FindVolumeClose(findVolume Handle) (err error)399//sys FindVolumeMountPointClose(findVolumeMountPoint Handle) (err error)400//sys GetDiskFreeSpaceEx(directoryName *uint16, freeBytesAvailableToCaller *uint64, totalNumberOfBytes *uint64, totalNumberOfFreeBytes *uint64) (err error) = GetDiskFreeSpaceExW401//sys GetDriveType(rootPathName *uint16) (driveType uint32) = GetDriveTypeW402//sys GetLogicalDrives() (drivesBitMask uint32, err error) [failretval==0]403//sys GetLogicalDriveStrings(bufferLength uint32, buffer *uint16) (n uint32, err error) [failretval==0] = GetLogicalDriveStringsW404//sys GetVolumeInformation(rootPathName *uint16, volumeNameBuffer *uint16, volumeNameSize uint32, volumeNameSerialNumber *uint32, maximumComponentLength *uint32, fileSystemFlags *uint32, fileSystemNameBuffer *uint16, fileSystemNameSize uint32) (err error) = GetVolumeInformationW405//sys GetVolumeInformationByHandle(file Handle, volumeNameBuffer *uint16, volumeNameSize uint32, volumeNameSerialNumber *uint32, maximumComponentLength *uint32, fileSystemFlags *uint32, fileSystemNameBuffer *uint16, fileSystemNameSize uint32) (err error) = GetVolumeInformationByHandleW406//sys GetVolumeNameForVolumeMountPoint(volumeMountPoint *uint16, volumeName *uint16, bufferlength uint32) (err error) = GetVolumeNameForVolumeMountPointW407//sys GetVolumePathName(fileName *uint16, volumePathName *uint16, bufferLength uint32) (err error) = GetVolumePathNameW408//sys GetVolumePathNamesForVolumeName(volumeName *uint16, volumePathNames *uint16, bufferLength uint32, returnLength *uint32) (err error) = GetVolumePathNamesForVolumeNameW409//sys QueryDosDevice(deviceName *uint16, targetPath *uint16, max uint32) (n uint32, err error) [failretval==0] = QueryDosDeviceW410//sys SetVolumeLabel(rootPathName *uint16, volumeName *uint16) (err error) = SetVolumeLabelW411//sys SetVolumeMountPoint(volumeMountPoint *uint16, volumeName *uint16) (err error) = SetVolumeMountPointW412//sys InitiateSystemShutdownEx(machineName *uint16, message *uint16, timeout uint32, forceAppsClosed bool, rebootAfterShutdown bool, reason uint32) (err error) = advapi32.InitiateSystemShutdownExW413//sys SetProcessShutdownParameters(level uint32, flags uint32) (err error) = kernel32.SetProcessShutdownParameters414//sys GetProcessShutdownParameters(level *uint32, flags *uint32) (err error) = kernel32.GetProcessShutdownParameters415//sys clsidFromString(lpsz *uint16, pclsid *GUID) (ret error) = ole32.CLSIDFromString416//sys stringFromGUID2(rguid *GUID, lpsz *uint16, cchMax int32) (chars int32) = ole32.StringFromGUID2417//sys coCreateGuid(pguid *GUID) (ret error) = ole32.CoCreateGuid418//sys CoTaskMemFree(address unsafe.Pointer) = ole32.CoTaskMemFree419//sys CoInitializeEx(reserved uintptr, coInit uint32) (ret error) = ole32.CoInitializeEx420//sys CoUninitialize() = ole32.CoUninitialize421//sys CoGetObject(name *uint16, bindOpts *BIND_OPTS3, guid *GUID, functionTable **uintptr) (ret error) = ole32.CoGetObject422//sys getProcessPreferredUILanguages(flags uint32, numLanguages *uint32, buf *uint16, bufSize *uint32) (err error) = kernel32.GetProcessPreferredUILanguages423//sys getThreadPreferredUILanguages(flags uint32, numLanguages *uint32, buf *uint16, bufSize *uint32) (err error) = kernel32.GetThreadPreferredUILanguages424//sys getUserPreferredUILanguages(flags uint32, numLanguages *uint32, buf *uint16, bufSize *uint32) (err error) = kernel32.GetUserPreferredUILanguages425//sys getSystemPreferredUILanguages(flags uint32, numLanguages *uint32, buf *uint16, bufSize *uint32) (err error) = kernel32.GetSystemPreferredUILanguages426//sys findResource(module Handle, name uintptr, resType uintptr) (resInfo Handle, err error) = kernel32.FindResourceW427//sys SizeofResource(module Handle, resInfo Handle) (size uint32, err error) = kernel32.SizeofResource428//sys LoadResource(module Handle, resInfo Handle) (resData Handle, err error) = kernel32.LoadResource429//sys LockResource(resData Handle) (addr uintptr, err error) = kernel32.LockResource430431// Version APIs432//sys GetFileVersionInfoSize(filename string, zeroHandle *Handle) (bufSize uint32, err error) = version.GetFileVersionInfoSizeW433//sys GetFileVersionInfo(filename string, handle uint32, bufSize uint32, buffer unsafe.Pointer) (err error) = version.GetFileVersionInfoW434//sys VerQueryValue(block unsafe.Pointer, subBlock string, pointerToBufferPointer unsafe.Pointer, bufSize *uint32) (err error) = version.VerQueryValueW435436// Process Status API (PSAPI)437//sys enumProcesses(processIds *uint32, nSize uint32, bytesReturned *uint32) (err error) = psapi.EnumProcesses438//sys EnumProcessModules(process Handle, module *Handle, cb uint32, cbNeeded *uint32) (err error) = psapi.EnumProcessModules439//sys EnumProcessModulesEx(process Handle, module *Handle, cb uint32, cbNeeded *uint32, filterFlag uint32) (err error) = psapi.EnumProcessModulesEx440//sys GetModuleInformation(process Handle, module Handle, modinfo *ModuleInfo, cb uint32) (err error) = psapi.GetModuleInformation441//sys GetModuleFileNameEx(process Handle, module Handle, filename *uint16, size uint32) (err error) = psapi.GetModuleFileNameExW442//sys GetModuleBaseName(process Handle, module Handle, baseName *uint16, size uint32) (err error) = psapi.GetModuleBaseNameW443//sys QueryWorkingSetEx(process Handle, pv uintptr, cb uint32) (err error) = psapi.QueryWorkingSetEx444445// NT Native APIs446//sys rtlNtStatusToDosErrorNoTeb(ntstatus NTStatus) (ret syscall.Errno) = ntdll.RtlNtStatusToDosErrorNoTeb447//sys rtlGetVersion(info *OsVersionInfoEx) (ntstatus error) = ntdll.RtlGetVersion448//sys rtlGetNtVersionNumbers(majorVersion *uint32, minorVersion *uint32, buildNumber *uint32) = ntdll.RtlGetNtVersionNumbers449//sys RtlGetCurrentPeb() (peb *PEB) = ntdll.RtlGetCurrentPeb450//sys RtlInitUnicodeString(destinationString *NTUnicodeString, sourceString *uint16) = ntdll.RtlInitUnicodeString451//sys RtlInitString(destinationString *NTString, sourceString *byte) = ntdll.RtlInitString452//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.NtCreateFile453//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.NtCreateNamedPipeFile454//sys NtSetInformationFile(handle Handle, iosb *IO_STATUS_BLOCK, inBuffer *byte, inBufferLen uint32, class uint32) (ntstatus error) = ntdll.NtSetInformationFile455//sys RtlDosPathNameToNtPathName(dosName *uint16, ntName *NTUnicodeString, ntFileNamePart *uint16, relativeName *RTL_RELATIVE_NAME) (ntstatus error) = ntdll.RtlDosPathNameToNtPathName_U_WithStatus456//sys RtlDosPathNameToRelativeNtPathName(dosName *uint16, ntName *NTUnicodeString, ntFileNamePart *uint16, relativeName *RTL_RELATIVE_NAME) (ntstatus error) = ntdll.RtlDosPathNameToRelativeNtPathName_U_WithStatus457//sys RtlDefaultNpAcl(acl **ACL) (ntstatus error) = ntdll.RtlDefaultNpAcl458//sys NtQueryInformationProcess(proc Handle, procInfoClass int32, procInfo unsafe.Pointer, procInfoLen uint32, retLen *uint32) (ntstatus error) = ntdll.NtQueryInformationProcess459//sys NtSetInformationProcess(proc Handle, procInfoClass int32, procInfo unsafe.Pointer, procInfoLen uint32) (ntstatus error) = ntdll.NtSetInformationProcess460//sys NtQuerySystemInformation(sysInfoClass int32, sysInfo unsafe.Pointer, sysInfoLen uint32, retLen *uint32) (ntstatus error) = ntdll.NtQuerySystemInformation461//sys NtSetSystemInformation(sysInfoClass int32, sysInfo unsafe.Pointer, sysInfoLen uint32) (ntstatus error) = ntdll.NtSetSystemInformation462//sys RtlAddFunctionTable(functionTable *RUNTIME_FUNCTION, entryCount uint32, baseAddress uintptr) (ret bool) = ntdll.RtlAddFunctionTable463//sys RtlDeleteFunctionTable(functionTable *RUNTIME_FUNCTION) (ret bool) = ntdll.RtlDeleteFunctionTable464465// Desktop Window Manager API (Dwmapi)466//sys DwmGetWindowAttribute(hwnd HWND, attribute uint32, value unsafe.Pointer, size uint32) (ret error) = dwmapi.DwmGetWindowAttribute467//sys DwmSetWindowAttribute(hwnd HWND, attribute uint32, value unsafe.Pointer, size uint32) (ret error) = dwmapi.DwmSetWindowAttribute468469// Windows Multimedia API470//sys TimeBeginPeriod (period uint32) (err error) [failretval != 0] = winmm.timeBeginPeriod471//sys TimeEndPeriod (period uint32) (err error) [failretval != 0] = winmm.timeEndPeriod472473// syscall interface implementation for other packages474475// GetCurrentProcess returns the handle for the current process.476// It is a pseudo handle that does not need to be closed.477// The returned error is always nil.478//479// Deprecated: use CurrentProcess for the same Handle without the nil480// error.481func GetCurrentProcess() (Handle, error) {482return CurrentProcess(), nil483}484485// CurrentProcess returns the handle for the current process.486// It is a pseudo handle that does not need to be closed.487func CurrentProcess() Handle { return Handle(^uintptr(1 - 1)) }488489// GetCurrentThread returns the handle for the current thread.490// It is a pseudo handle that does not need to be closed.491// The returned error is always nil.492//493// Deprecated: use CurrentThread for the same Handle without the nil494// error.495func GetCurrentThread() (Handle, error) {496return CurrentThread(), nil497}498499// CurrentThread returns the handle for the current thread.500// It is a pseudo handle that does not need to be closed.501func CurrentThread() Handle { return Handle(^uintptr(2 - 1)) }502503// GetProcAddressByOrdinal retrieves the address of the exported504// function from module by ordinal.505func GetProcAddressByOrdinal(module Handle, ordinal uintptr) (proc uintptr, err error) {506r0, _, e1 := syscall.Syscall(procGetProcAddress.Addr(), 2, uintptr(module), ordinal, 0)507proc = uintptr(r0)508if proc == 0 {509err = errnoErr(e1)510}511return512}513514func Exit(code int) { ExitProcess(uint32(code)) }515516func makeInheritSa() *SecurityAttributes {517var sa SecurityAttributes518sa.Length = uint32(unsafe.Sizeof(sa))519sa.InheritHandle = 1520return &sa521}522523func Open(path string, mode int, perm uint32) (fd Handle, err error) {524if len(path) == 0 {525return InvalidHandle, ERROR_FILE_NOT_FOUND526}527pathp, err := UTF16PtrFromString(path)528if err != nil {529return InvalidHandle, err530}531var access uint32532switch mode & (O_RDONLY | O_WRONLY | O_RDWR) {533case O_RDONLY:534access = GENERIC_READ535case O_WRONLY:536access = GENERIC_WRITE537case O_RDWR:538access = GENERIC_READ | GENERIC_WRITE539}540if mode&O_CREAT != 0 {541access |= GENERIC_WRITE542}543if mode&O_APPEND != 0 {544access &^= GENERIC_WRITE545access |= FILE_APPEND_DATA546}547sharemode := uint32(FILE_SHARE_READ | FILE_SHARE_WRITE)548var sa *SecurityAttributes549if mode&O_CLOEXEC == 0 {550sa = makeInheritSa()551}552var createmode uint32553switch {554case mode&(O_CREAT|O_EXCL) == (O_CREAT | O_EXCL):555createmode = CREATE_NEW556case mode&(O_CREAT|O_TRUNC) == (O_CREAT | O_TRUNC):557createmode = CREATE_ALWAYS558case mode&O_CREAT == O_CREAT:559createmode = OPEN_ALWAYS560case mode&O_TRUNC == O_TRUNC:561createmode = TRUNCATE_EXISTING562default:563createmode = OPEN_EXISTING564}565var attrs uint32 = FILE_ATTRIBUTE_NORMAL566if perm&S_IWRITE == 0 {567attrs = FILE_ATTRIBUTE_READONLY568}569h, e := CreateFile(pathp, access, sharemode, sa, createmode, attrs, 0)570return h, e571}572573func Read(fd Handle, p []byte) (n int, err error) {574var done uint32575e := ReadFile(fd, p, &done, nil)576if e != nil {577if e == ERROR_BROKEN_PIPE {578// NOTE(brainman): work around ERROR_BROKEN_PIPE is returned on reading EOF from stdin579return 0, nil580}581return 0, e582}583return int(done), nil584}585586func Write(fd Handle, p []byte) (n int, err error) {587if raceenabled {588raceReleaseMerge(unsafe.Pointer(&ioSync))589}590var done uint32591e := WriteFile(fd, p, &done, nil)592if e != nil {593return 0, e594}595return int(done), nil596}597598func ReadFile(fd Handle, p []byte, done *uint32, overlapped *Overlapped) error {599err := readFile(fd, p, done, overlapped)600if raceenabled {601if *done > 0 {602raceWriteRange(unsafe.Pointer(&p[0]), int(*done))603}604raceAcquire(unsafe.Pointer(&ioSync))605}606return err607}608609func WriteFile(fd Handle, p []byte, done *uint32, overlapped *Overlapped) error {610if raceenabled {611raceReleaseMerge(unsafe.Pointer(&ioSync))612}613err := writeFile(fd, p, done, overlapped)614if raceenabled && *done > 0 {615raceReadRange(unsafe.Pointer(&p[0]), int(*done))616}617return err618}619620var ioSync int64621622func Seek(fd Handle, offset int64, whence int) (newoffset int64, err error) {623var w uint32624switch whence {625case 0:626w = FILE_BEGIN627case 1:628w = FILE_CURRENT629case 2:630w = FILE_END631}632hi := int32(offset >> 32)633lo := int32(offset)634// use GetFileType to check pipe, pipe can't do seek635ft, _ := GetFileType(fd)636if ft == FILE_TYPE_PIPE {637return 0, syscall.EPIPE638}639rlo, e := SetFilePointer(fd, lo, &hi, w)640if e != nil {641return 0, e642}643return int64(hi)<<32 + int64(rlo), nil644}645646func Close(fd Handle) (err error) {647return CloseHandle(fd)648}649650var (651Stdin = getStdHandle(STD_INPUT_HANDLE)652Stdout = getStdHandle(STD_OUTPUT_HANDLE)653Stderr = getStdHandle(STD_ERROR_HANDLE)654)655656func getStdHandle(stdhandle uint32) (fd Handle) {657r, _ := GetStdHandle(stdhandle)658return r659}660661const ImplementsGetwd = true662663func Getwd() (wd string, err error) {664b := make([]uint16, 300)665n, e := GetCurrentDirectory(uint32(len(b)), &b[0])666if e != nil {667return "", e668}669return string(utf16.Decode(b[0:n])), nil670}671672func Chdir(path string) (err error) {673pathp, err := UTF16PtrFromString(path)674if err != nil {675return err676}677return SetCurrentDirectory(pathp)678}679680func Mkdir(path string, mode uint32) (err error) {681pathp, err := UTF16PtrFromString(path)682if err != nil {683return err684}685return CreateDirectory(pathp, nil)686}687688func Rmdir(path string) (err error) {689pathp, err := UTF16PtrFromString(path)690if err != nil {691return err692}693return RemoveDirectory(pathp)694}695696func Unlink(path string) (err error) {697pathp, err := UTF16PtrFromString(path)698if err != nil {699return err700}701return DeleteFile(pathp)702}703704func Rename(oldpath, newpath string) (err error) {705from, err := UTF16PtrFromString(oldpath)706if err != nil {707return err708}709to, err := UTF16PtrFromString(newpath)710if err != nil {711return err712}713return MoveFileEx(from, to, MOVEFILE_REPLACE_EXISTING)714}715716func ComputerName() (name string, err error) {717var n uint32 = MAX_COMPUTERNAME_LENGTH + 1718b := make([]uint16, n)719e := GetComputerName(&b[0], &n)720if e != nil {721return "", e722}723return string(utf16.Decode(b[0:n])), nil724}725726func DurationSinceBoot() time.Duration {727return time.Duration(getTickCount64()) * time.Millisecond728}729730func Ftruncate(fd Handle, length int64) (err error) {731type _FILE_END_OF_FILE_INFO struct {732EndOfFile int64733}734var info _FILE_END_OF_FILE_INFO735info.EndOfFile = length736return SetFileInformationByHandle(fd, FileEndOfFileInfo, (*byte)(unsafe.Pointer(&info)), uint32(unsafe.Sizeof(info)))737}738739func Gettimeofday(tv *Timeval) (err error) {740var ft Filetime741GetSystemTimeAsFileTime(&ft)742*tv = NsecToTimeval(ft.Nanoseconds())743return nil744}745746func Pipe(p []Handle) (err error) {747if len(p) != 2 {748return syscall.EINVAL749}750var r, w Handle751e := CreatePipe(&r, &w, makeInheritSa(), 0)752if e != nil {753return e754}755p[0] = r756p[1] = w757return nil758}759760func Utimes(path string, tv []Timeval) (err error) {761if len(tv) != 2 {762return syscall.EINVAL763}764pathp, e := UTF16PtrFromString(path)765if e != nil {766return e767}768h, e := CreateFile(pathp,769FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, nil,770OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0)771if e != nil {772return e773}774defer CloseHandle(h)775a := NsecToFiletime(tv[0].Nanoseconds())776w := NsecToFiletime(tv[1].Nanoseconds())777return SetFileTime(h, nil, &a, &w)778}779780func UtimesNano(path string, ts []Timespec) (err error) {781if len(ts) != 2 {782return syscall.EINVAL783}784pathp, e := UTF16PtrFromString(path)785if e != nil {786return e787}788h, e := CreateFile(pathp,789FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, nil,790OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0)791if e != nil {792return e793}794defer CloseHandle(h)795a := NsecToFiletime(TimespecToNsec(ts[0]))796w := NsecToFiletime(TimespecToNsec(ts[1]))797return SetFileTime(h, nil, &a, &w)798}799800func Fsync(fd Handle) (err error) {801return FlushFileBuffers(fd)802}803804func Chmod(path string, mode uint32) (err error) {805p, e := UTF16PtrFromString(path)806if e != nil {807return e808}809attrs, e := GetFileAttributes(p)810if e != nil {811return e812}813if mode&S_IWRITE != 0 {814attrs &^= FILE_ATTRIBUTE_READONLY815} else {816attrs |= FILE_ATTRIBUTE_READONLY817}818return SetFileAttributes(p, attrs)819}820821func LoadGetSystemTimePreciseAsFileTime() error {822return procGetSystemTimePreciseAsFileTime.Find()823}824825func LoadCancelIoEx() error {826return procCancelIoEx.Find()827}828829func LoadSetFileCompletionNotificationModes() error {830return procSetFileCompletionNotificationModes.Find()831}832833func WaitForMultipleObjects(handles []Handle, waitAll bool, waitMilliseconds uint32) (event uint32, err error) {834// Every other win32 array API takes arguments as "pointer, count", except for this function. So we835// can't declare it as a usual [] type, because mksyscall will use the opposite order. We therefore836// trivially stub this ourselves.837838var handlePtr *Handle839if len(handles) > 0 {840handlePtr = &handles[0]841}842return waitForMultipleObjects(uint32(len(handles)), uintptr(unsafe.Pointer(handlePtr)), waitAll, waitMilliseconds)843}844845// net api calls846847const socket_error = uintptr(^uint32(0))848849//sys WSAStartup(verreq uint32, data *WSAData) (sockerr error) = ws2_32.WSAStartup850//sys WSACleanup() (err error) [failretval==socket_error] = ws2_32.WSACleanup851//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.WSAIoctl852//sys WSALookupServiceBegin(querySet *WSAQUERYSET, flags uint32, handle *Handle) (err error) [failretval==socket_error] = ws2_32.WSALookupServiceBeginW853//sys WSALookupServiceNext(handle Handle, flags uint32, size *int32, querySet *WSAQUERYSET) (err error) [failretval==socket_error] = ws2_32.WSALookupServiceNextW854//sys WSALookupServiceEnd(handle Handle) (err error) [failretval==socket_error] = ws2_32.WSALookupServiceEnd855//sys socket(af int32, typ int32, protocol int32) (handle Handle, err error) [failretval==InvalidHandle] = ws2_32.socket856//sys sendto(s Handle, buf []byte, flags int32, to unsafe.Pointer, tolen int32) (err error) [failretval==socket_error] = ws2_32.sendto857//sys recvfrom(s Handle, buf []byte, flags int32, from *RawSockaddrAny, fromlen *int32) (n int32, err error) [failretval==-1] = ws2_32.recvfrom858//sys Setsockopt(s Handle, level int32, optname int32, optval *byte, optlen int32) (err error) [failretval==socket_error] = ws2_32.setsockopt859//sys Getsockopt(s Handle, level int32, optname int32, optval *byte, optlen *int32) (err error) [failretval==socket_error] = ws2_32.getsockopt860//sys bind(s Handle, name unsafe.Pointer, namelen int32) (err error) [failretval==socket_error] = ws2_32.bind861//sys connect(s Handle, name unsafe.Pointer, namelen int32) (err error) [failretval==socket_error] = ws2_32.connect862//sys getsockname(s Handle, rsa *RawSockaddrAny, addrlen *int32) (err error) [failretval==socket_error] = ws2_32.getsockname863//sys getpeername(s Handle, rsa *RawSockaddrAny, addrlen *int32) (err error) [failretval==socket_error] = ws2_32.getpeername864//sys listen(s Handle, backlog int32) (err error) [failretval==socket_error] = ws2_32.listen865//sys shutdown(s Handle, how int32) (err error) [failretval==socket_error] = ws2_32.shutdown866//sys Closesocket(s Handle) (err error) [failretval==socket_error] = ws2_32.closesocket867//sys AcceptEx(ls Handle, as Handle, buf *byte, rxdatalen uint32, laddrlen uint32, raddrlen uint32, recvd *uint32, overlapped *Overlapped) (err error) = mswsock.AcceptEx868//sys GetAcceptExSockaddrs(buf *byte, rxdatalen uint32, laddrlen uint32, raddrlen uint32, lrsa **RawSockaddrAny, lrsalen *int32, rrsa **RawSockaddrAny, rrsalen *int32) = mswsock.GetAcceptExSockaddrs869//sys WSARecv(s Handle, bufs *WSABuf, bufcnt uint32, recvd *uint32, flags *uint32, overlapped *Overlapped, croutine *byte) (err error) [failretval==socket_error] = ws2_32.WSARecv870//sys WSASend(s Handle, bufs *WSABuf, bufcnt uint32, sent *uint32, flags uint32, overlapped *Overlapped, croutine *byte) (err error) [failretval==socket_error] = ws2_32.WSASend871//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.WSARecvFrom872//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.WSASendTo873//sys WSASocket(af int32, typ int32, protocol int32, protoInfo *WSAProtocolInfo, group uint32, flags uint32) (handle Handle, err error) [failretval==InvalidHandle] = ws2_32.WSASocketW874//sys WSADuplicateSocket(s Handle, processID uint32, info *WSAProtocolInfo) (err error) [failretval!=0] = ws2_32.WSADuplicateSocketW875//sys GetHostByName(name string) (h *Hostent, err error) [failretval==nil] = ws2_32.gethostbyname876//sys GetServByName(name string, proto string) (s *Servent, err error) [failretval==nil] = ws2_32.getservbyname877//sys Ntohs(netshort uint16) (u uint16) = ws2_32.ntohs878//sys GetProtoByName(name string) (p *Protoent, err error) [failretval==nil] = ws2_32.getprotobyname879//sys DnsQuery(name string, qtype uint16, options uint32, extra *byte, qrs **DNSRecord, pr *byte) (status error) = dnsapi.DnsQuery_W880//sys DnsRecordListFree(rl *DNSRecord, freetype uint32) = dnsapi.DnsRecordListFree881//sys DnsNameCompare(name1 *uint16, name2 *uint16) (same bool) = dnsapi.DnsNameCompare_W882//sys GetAddrInfoW(nodename *uint16, servicename *uint16, hints *AddrinfoW, result **AddrinfoW) (sockerr error) = ws2_32.GetAddrInfoW883//sys FreeAddrInfoW(addrinfo *AddrinfoW) = ws2_32.FreeAddrInfoW884//sys GetIfEntry(pIfRow *MibIfRow) (errcode error) = iphlpapi.GetIfEntry885//sys GetAdaptersInfo(ai *IpAdapterInfo, ol *uint32) (errcode error) = iphlpapi.GetAdaptersInfo886//sys SetFileCompletionNotificationModes(handle Handle, flags uint8) (err error) = kernel32.SetFileCompletionNotificationModes887//sys WSAEnumProtocols(protocols *int32, protocolBuffer *WSAProtocolInfo, bufferLength *uint32) (n int32, err error) [failretval==-1] = ws2_32.WSAEnumProtocolsW888//sys WSAGetOverlappedResult(h Handle, o *Overlapped, bytes *uint32, wait bool, flags *uint32) (err error) = ws2_32.WSAGetOverlappedResult889//sys GetAdaptersAddresses(family uint32, flags uint32, reserved uintptr, adapterAddresses *IpAdapterAddresses, sizePointer *uint32) (errcode error) = iphlpapi.GetAdaptersAddresses890//sys GetACP() (acp uint32) = kernel32.GetACP891//sys MultiByteToWideChar(codePage uint32, dwFlags uint32, str *byte, nstr int32, wchar *uint16, nwchar int32) (nwrite int32, err error) = kernel32.MultiByteToWideChar892//sys getBestInterfaceEx(sockaddr unsafe.Pointer, pdwBestIfIndex *uint32) (errcode error) = iphlpapi.GetBestInterfaceEx893//sys GetIfEntry2Ex(level uint32, row *MibIfRow2) (errcode error) = iphlpapi.GetIfEntry2Ex894//sys GetUnicastIpAddressEntry(row *MibUnicastIpAddressRow) (errcode error) = iphlpapi.GetUnicastIpAddressEntry895//sys NotifyIpInterfaceChange(family uint16, callback uintptr, callerContext unsafe.Pointer, initialNotification bool, notificationHandle *Handle) (errcode error) = iphlpapi.NotifyIpInterfaceChange896//sys NotifyUnicastIpAddressChange(family uint16, callback uintptr, callerContext unsafe.Pointer, initialNotification bool, notificationHandle *Handle) (errcode error) = iphlpapi.NotifyUnicastIpAddressChange897//sys CancelMibChangeNotify2(notificationHandle Handle) (errcode error) = iphlpapi.CancelMibChangeNotify2898899// For testing: clients can set this flag to force900// creation of IPv6 sockets to return EAFNOSUPPORT.901var SocketDisableIPv6 bool902903type RawSockaddrInet4 struct {904Family uint16905Port uint16906Addr [4]byte /* in_addr */907Zero [8]uint8908}909910type RawSockaddrInet6 struct {911Family uint16912Port uint16913Flowinfo uint32914Addr [16]byte /* in6_addr */915Scope_id uint32916}917918type RawSockaddr struct {919Family uint16920Data [14]int8921}922923type RawSockaddrAny struct {924Addr RawSockaddr925Pad [100]int8926}927928type Sockaddr interface {929sockaddr() (ptr unsafe.Pointer, len int32, err error) // lowercase; only we can define Sockaddrs930}931932type SockaddrInet4 struct {933Port int934Addr [4]byte935raw RawSockaddrInet4936}937938func (sa *SockaddrInet4) sockaddr() (unsafe.Pointer, int32, error) {939if sa.Port < 0 || sa.Port > 0xFFFF {940return nil, 0, syscall.EINVAL941}942sa.raw.Family = AF_INET943p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port))944p[0] = byte(sa.Port >> 8)945p[1] = byte(sa.Port)946sa.raw.Addr = sa.Addr947return unsafe.Pointer(&sa.raw), int32(unsafe.Sizeof(sa.raw)), nil948}949950type SockaddrInet6 struct {951Port int952ZoneId uint32953Addr [16]byte954raw RawSockaddrInet6955}956957func (sa *SockaddrInet6) sockaddr() (unsafe.Pointer, int32, error) {958if sa.Port < 0 || sa.Port > 0xFFFF {959return nil, 0, syscall.EINVAL960}961sa.raw.Family = AF_INET6962p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port))963p[0] = byte(sa.Port >> 8)964p[1] = byte(sa.Port)965sa.raw.Scope_id = sa.ZoneId966sa.raw.Addr = sa.Addr967return unsafe.Pointer(&sa.raw), int32(unsafe.Sizeof(sa.raw)), nil968}969970type RawSockaddrUnix struct {971Family uint16972Path [UNIX_PATH_MAX]int8973}974975type SockaddrUnix struct {976Name string977raw RawSockaddrUnix978}979980func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, int32, error) {981name := sa.Name982n := len(name)983if n > len(sa.raw.Path) {984return nil, 0, syscall.EINVAL985}986if n == len(sa.raw.Path) && name[0] != '@' {987return nil, 0, syscall.EINVAL988}989sa.raw.Family = AF_UNIX990for i := 0; i < n; i++ {991sa.raw.Path[i] = int8(name[i])992}993// length is family (uint16), name, NUL.994sl := int32(2)995if n > 0 {996sl += int32(n) + 1997}998if sa.raw.Path[0] == '@' || (sa.raw.Path[0] == 0 && sl > 3) {999// Check sl > 3 so we don't change unnamed socket behavior.1000sa.raw.Path[0] = 01001// Don't count trailing NUL for abstract address.1002sl--1003}10041005return unsafe.Pointer(&sa.raw), sl, nil1006}10071008type RawSockaddrBth struct {1009AddressFamily [2]byte1010BtAddr [8]byte1011ServiceClassId [16]byte1012Port [4]byte1013}10141015type SockaddrBth struct {1016BtAddr uint641017ServiceClassId GUID1018Port uint3210191020raw RawSockaddrBth1021}10221023func (sa *SockaddrBth) sockaddr() (unsafe.Pointer, int32, error) {1024family := AF_BTH1025sa.raw = RawSockaddrBth{1026AddressFamily: *(*[2]byte)(unsafe.Pointer(&family)),1027BtAddr: *(*[8]byte)(unsafe.Pointer(&sa.BtAddr)),1028Port: *(*[4]byte)(unsafe.Pointer(&sa.Port)),1029ServiceClassId: *(*[16]byte)(unsafe.Pointer(&sa.ServiceClassId)),1030}1031return unsafe.Pointer(&sa.raw), int32(unsafe.Sizeof(sa.raw)), nil1032}10331034func (rsa *RawSockaddrAny) Sockaddr() (Sockaddr, error) {1035switch rsa.Addr.Family {1036case AF_UNIX:1037pp := (*RawSockaddrUnix)(unsafe.Pointer(rsa))1038sa := new(SockaddrUnix)1039if pp.Path[0] == 0 {1040// "Abstract" Unix domain socket.1041// Rewrite leading NUL as @ for textual display.1042// (This is the standard convention.)1043// Not friendly to overwrite in place,1044// but the callers below don't care.1045pp.Path[0] = '@'1046}10471048// Assume path ends at NUL.1049// This is not technically the Linux semantics for1050// abstract Unix domain sockets--they are supposed1051// to be uninterpreted fixed-size binary blobs--but1052// everyone uses this convention.1053n := 01054for n < len(pp.Path) && pp.Path[n] != 0 {1055n++1056}1057sa.Name = string(unsafe.Slice((*byte)(unsafe.Pointer(&pp.Path[0])), n))1058return sa, nil10591060case AF_INET:1061pp := (*RawSockaddrInet4)(unsafe.Pointer(rsa))1062sa := new(SockaddrInet4)1063p := (*[2]byte)(unsafe.Pointer(&pp.Port))1064sa.Port = int(p[0])<<8 + int(p[1])1065sa.Addr = pp.Addr1066return sa, nil10671068case AF_INET6:1069pp := (*RawSockaddrInet6)(unsafe.Pointer(rsa))1070sa := new(SockaddrInet6)1071p := (*[2]byte)(unsafe.Pointer(&pp.Port))1072sa.Port = int(p[0])<<8 + int(p[1])1073sa.ZoneId = pp.Scope_id1074sa.Addr = pp.Addr1075return sa, nil1076}1077return nil, syscall.EAFNOSUPPORT1078}10791080func Socket(domain, typ, proto int) (fd Handle, err error) {1081if domain == AF_INET6 && SocketDisableIPv6 {1082return InvalidHandle, syscall.EAFNOSUPPORT1083}1084return socket(int32(domain), int32(typ), int32(proto))1085}10861087func SetsockoptInt(fd Handle, level, opt int, value int) (err error) {1088v := int32(value)1089return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(&v)), int32(unsafe.Sizeof(v)))1090}10911092func Bind(fd Handle, sa Sockaddr) (err error) {1093ptr, n, err := sa.sockaddr()1094if err != nil {1095return err1096}1097return bind(fd, ptr, n)1098}10991100func Connect(fd Handle, sa Sockaddr) (err error) {1101ptr, n, err := sa.sockaddr()1102if err != nil {1103return err1104}1105return connect(fd, ptr, n)1106}11071108func GetBestInterfaceEx(sa Sockaddr, pdwBestIfIndex *uint32) (err error) {1109ptr, _, err := sa.sockaddr()1110if err != nil {1111return err1112}1113return getBestInterfaceEx(ptr, pdwBestIfIndex)1114}11151116func Getsockname(fd Handle) (sa Sockaddr, err error) {1117var rsa RawSockaddrAny1118l := int32(unsafe.Sizeof(rsa))1119if err = getsockname(fd, &rsa, &l); err != nil {1120return1121}1122return rsa.Sockaddr()1123}11241125func Getpeername(fd Handle) (sa Sockaddr, err error) {1126var rsa RawSockaddrAny1127l := int32(unsafe.Sizeof(rsa))1128if err = getpeername(fd, &rsa, &l); err != nil {1129return1130}1131return rsa.Sockaddr()1132}11331134func Listen(s Handle, n int) (err error) {1135return listen(s, int32(n))1136}11371138func Shutdown(fd Handle, how int) (err error) {1139return shutdown(fd, int32(how))1140}11411142func WSASendto(s Handle, bufs *WSABuf, bufcnt uint32, sent *uint32, flags uint32, to Sockaddr, overlapped *Overlapped, croutine *byte) (err error) {1143var rsa unsafe.Pointer1144var l int321145if to != nil {1146rsa, l, err = to.sockaddr()1147if err != nil {1148return err1149}1150}1151return WSASendTo(s, bufs, bufcnt, sent, flags, (*RawSockaddrAny)(unsafe.Pointer(rsa)), l, overlapped, croutine)1152}11531154func LoadGetAddrInfo() error {1155return procGetAddrInfoW.Find()1156}11571158var connectExFunc struct {1159once sync.Once1160addr uintptr1161err error1162}11631164func LoadConnectEx() error {1165connectExFunc.once.Do(func() {1166var s Handle1167s, connectExFunc.err = Socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)1168if connectExFunc.err != nil {1169return1170}1171defer CloseHandle(s)1172var n uint321173connectExFunc.err = WSAIoctl(s,1174SIO_GET_EXTENSION_FUNCTION_POINTER,1175(*byte)(unsafe.Pointer(&WSAID_CONNECTEX)),1176uint32(unsafe.Sizeof(WSAID_CONNECTEX)),1177(*byte)(unsafe.Pointer(&connectExFunc.addr)),1178uint32(unsafe.Sizeof(connectExFunc.addr)),1179&n, nil, 0)1180})1181return connectExFunc.err1182}11831184func connectEx(s Handle, name unsafe.Pointer, namelen int32, sendBuf *byte, sendDataLen uint32, bytesSent *uint32, overlapped *Overlapped) (err error) {1185r1, _, 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)1186if r1 == 0 {1187if e1 != 0 {1188err = error(e1)1189} else {1190err = syscall.EINVAL1191}1192}1193return1194}11951196func ConnectEx(fd Handle, sa Sockaddr, sendBuf *byte, sendDataLen uint32, bytesSent *uint32, overlapped *Overlapped) error {1197err := LoadConnectEx()1198if err != nil {1199return errorspkg.New("failed to find ConnectEx: " + err.Error())1200}1201ptr, n, err := sa.sockaddr()1202if err != nil {1203return err1204}1205return connectEx(fd, ptr, n, sendBuf, sendDataLen, bytesSent, overlapped)1206}12071208var sendRecvMsgFunc struct {1209once sync.Once1210sendAddr uintptr1211recvAddr uintptr1212err error1213}12141215func loadWSASendRecvMsg() error {1216sendRecvMsgFunc.once.Do(func() {1217var s Handle1218s, sendRecvMsgFunc.err = Socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)1219if sendRecvMsgFunc.err != nil {1220return1221}1222defer CloseHandle(s)1223var n uint321224sendRecvMsgFunc.err = WSAIoctl(s,1225SIO_GET_EXTENSION_FUNCTION_POINTER,1226(*byte)(unsafe.Pointer(&WSAID_WSARECVMSG)),1227uint32(unsafe.Sizeof(WSAID_WSARECVMSG)),1228(*byte)(unsafe.Pointer(&sendRecvMsgFunc.recvAddr)),1229uint32(unsafe.Sizeof(sendRecvMsgFunc.recvAddr)),1230&n, nil, 0)1231if sendRecvMsgFunc.err != nil {1232return1233}1234sendRecvMsgFunc.err = WSAIoctl(s,1235SIO_GET_EXTENSION_FUNCTION_POINTER,1236(*byte)(unsafe.Pointer(&WSAID_WSASENDMSG)),1237uint32(unsafe.Sizeof(WSAID_WSASENDMSG)),1238(*byte)(unsafe.Pointer(&sendRecvMsgFunc.sendAddr)),1239uint32(unsafe.Sizeof(sendRecvMsgFunc.sendAddr)),1240&n, nil, 0)1241})1242return sendRecvMsgFunc.err1243}12441245func WSASendMsg(fd Handle, msg *WSAMsg, flags uint32, bytesSent *uint32, overlapped *Overlapped, croutine *byte) error {1246err := loadWSASendRecvMsg()1247if err != nil {1248return err1249}1250r1, _, 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)))1251if r1 == socket_error {1252err = errnoErr(e1)1253}1254return err1255}12561257func WSARecvMsg(fd Handle, msg *WSAMsg, bytesReceived *uint32, overlapped *Overlapped, croutine *byte) error {1258err := loadWSASendRecvMsg()1259if err != nil {1260return err1261}1262r1, _, 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)1263if r1 == socket_error {1264err = errnoErr(e1)1265}1266return err1267}12681269// Invented structures to support what package os expects.1270type Rusage struct {1271CreationTime Filetime1272ExitTime Filetime1273KernelTime Filetime1274UserTime Filetime1275}12761277type WaitStatus struct {1278ExitCode uint321279}12801281func (w WaitStatus) Exited() bool { return true }12821283func (w WaitStatus) ExitStatus() int { return int(w.ExitCode) }12841285func (w WaitStatus) Signal() Signal { return -1 }12861287func (w WaitStatus) CoreDump() bool { return false }12881289func (w WaitStatus) Stopped() bool { return false }12901291func (w WaitStatus) Continued() bool { return false }12921293func (w WaitStatus) StopSignal() Signal { return -1 }12941295func (w WaitStatus) Signaled() bool { return false }12961297func (w WaitStatus) TrapCause() int { return -1 }12981299// Timespec is an invented structure on Windows, but here for1300// consistency with the corresponding package for other operating systems.1301type Timespec struct {1302Sec int641303Nsec int641304}13051306func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) }13071308func NsecToTimespec(nsec int64) (ts Timespec) {1309ts.Sec = nsec / 1e91310ts.Nsec = nsec % 1e91311return1312}13131314// TODO(brainman): fix all needed for net13151316func Accept(fd Handle) (nfd Handle, sa Sockaddr, err error) { return 0, nil, syscall.EWINDOWS }13171318func Recvfrom(fd Handle, p []byte, flags int) (n int, from Sockaddr, err error) {1319var rsa RawSockaddrAny1320l := int32(unsafe.Sizeof(rsa))1321n32, err := recvfrom(fd, p, int32(flags), &rsa, &l)1322n = int(n32)1323if err != nil {1324return1325}1326from, err = rsa.Sockaddr()1327return1328}13291330func Sendto(fd Handle, p []byte, flags int, to Sockaddr) (err error) {1331ptr, l, err := to.sockaddr()1332if err != nil {1333return err1334}1335return sendto(fd, p, int32(flags), ptr, l)1336}13371338func SetsockoptTimeval(fd Handle, level, opt int, tv *Timeval) (err error) { return syscall.EWINDOWS }13391340// The Linger struct is wrong but we only noticed after Go 1.1341// sysLinger is the real system call structure.13421343// BUG(brainman): The definition of Linger is not appropriate for direct use1344// with Setsockopt and Getsockopt.1345// Use SetsockoptLinger instead.13461347type Linger struct {1348Onoff int321349Linger int321350}13511352type sysLinger struct {1353Onoff uint161354Linger uint161355}13561357type IPMreq struct {1358Multiaddr [4]byte /* in_addr */1359Interface [4]byte /* in_addr */1360}13611362type IPv6Mreq struct {1363Multiaddr [16]byte /* in6_addr */1364Interface uint321365}13661367func GetsockoptInt(fd Handle, level, opt int) (int, error) {1368v := int32(0)1369l := int32(unsafe.Sizeof(v))1370err := Getsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(&v)), &l)1371return int(v), err1372}13731374func SetsockoptLinger(fd Handle, level, opt int, l *Linger) (err error) {1375sys := sysLinger{Onoff: uint16(l.Onoff), Linger: uint16(l.Linger)}1376return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(&sys)), int32(unsafe.Sizeof(sys)))1377}13781379func SetsockoptInet4Addr(fd Handle, level, opt int, value [4]byte) (err error) {1380return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(&value[0])), 4)1381}13821383func SetsockoptIPMreq(fd Handle, level, opt int, mreq *IPMreq) (err error) {1384return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(mreq)), int32(unsafe.Sizeof(*mreq)))1385}13861387func SetsockoptIPv6Mreq(fd Handle, level, opt int, mreq *IPv6Mreq) (err error) {1388return syscall.EWINDOWS1389}13901391func EnumProcesses(processIds []uint32, bytesReturned *uint32) error {1392// EnumProcesses syscall expects the size parameter to be in bytes, but the code generated with mksyscall uses1393// the length of the processIds slice instead. Hence, this wrapper function is added to fix the discrepancy.1394var p *uint321395if len(processIds) > 0 {1396p = &processIds[0]1397}1398size := uint32(len(processIds) * 4)1399return enumProcesses(p, size, bytesReturned)1400}14011402func Getpid() (pid int) { return int(GetCurrentProcessId()) }14031404func FindFirstFile(name *uint16, data *Win32finddata) (handle Handle, err error) {1405// NOTE(rsc): The Win32finddata struct is wrong for the system call:1406// the two paths are each one uint16 short. Use the correct struct,1407// a win32finddata1, and then copy the results out.1408// There is no loss of expressivity here, because the final1409// uint16, if it is used, is supposed to be a NUL, and Go doesn't need that.1410// For Go 1.1, we might avoid the allocation of win32finddata1 here1411// by adding a final Bug [2]uint16 field to the struct and then1412// adjusting the fields in the result directly.1413var data1 win32finddata11414handle, err = findFirstFile1(name, &data1)1415if err == nil {1416copyFindData(data, &data1)1417}1418return1419}14201421func FindNextFile(handle Handle, data *Win32finddata) (err error) {1422var data1 win32finddata11423err = findNextFile1(handle, &data1)1424if err == nil {1425copyFindData(data, &data1)1426}1427return1428}14291430func getProcessEntry(pid int) (*ProcessEntry32, error) {1431snapshot, err := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)1432if err != nil {1433return nil, err1434}1435defer CloseHandle(snapshot)1436var procEntry ProcessEntry321437procEntry.Size = uint32(unsafe.Sizeof(procEntry))1438if err = Process32First(snapshot, &procEntry); err != nil {1439return nil, err1440}1441for {1442if procEntry.ProcessID == uint32(pid) {1443return &procEntry, nil1444}1445err = Process32Next(snapshot, &procEntry)1446if err != nil {1447return nil, err1448}1449}1450}14511452func Getppid() (ppid int) {1453pe, err := getProcessEntry(Getpid())1454if err != nil {1455return -11456}1457return int(pe.ParentProcessID)1458}14591460// TODO(brainman): fix all needed for os1461func Fchdir(fd Handle) (err error) { return syscall.EWINDOWS }1462func Link(oldpath, newpath string) (err error) { return syscall.EWINDOWS }1463func Symlink(path, link string) (err error) { return syscall.EWINDOWS }14641465func Fchmod(fd Handle, mode uint32) (err error) { return syscall.EWINDOWS }1466func Chown(path string, uid int, gid int) (err error) { return syscall.EWINDOWS }1467func Lchown(path string, uid int, gid int) (err error) { return syscall.EWINDOWS }1468func Fchown(fd Handle, uid int, gid int) (err error) { return syscall.EWINDOWS }14691470func Getuid() (uid int) { return -1 }1471func Geteuid() (euid int) { return -1 }1472func Getgid() (gid int) { return -1 }1473func Getegid() (egid int) { return -1 }1474func Getgroups() (gids []int, err error) { return nil, syscall.EWINDOWS }14751476type Signal int14771478func (s Signal) Signal() {}14791480func (s Signal) String() string {1481if 0 <= s && int(s) < len(signals) {1482str := signals[s]1483if str != "" {1484return str1485}1486}1487return "signal " + itoa(int(s))1488}14891490func LoadCreateSymbolicLink() error {1491return procCreateSymbolicLinkW.Find()1492}14931494// Readlink returns the destination of the named symbolic link.1495func Readlink(path string, buf []byte) (n int, err error) {1496fd, err := CreateFile(StringToUTF16Ptr(path), GENERIC_READ, 0, nil, OPEN_EXISTING,1497FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_BACKUP_SEMANTICS, 0)1498if err != nil {1499return -1, err1500}1501defer CloseHandle(fd)15021503rdbbuf := make([]byte, MAXIMUM_REPARSE_DATA_BUFFER_SIZE)1504var bytesReturned uint321505err = DeviceIoControl(fd, FSCTL_GET_REPARSE_POINT, nil, 0, &rdbbuf[0], uint32(len(rdbbuf)), &bytesReturned, nil)1506if err != nil {1507return -1, err1508}15091510rdb := (*reparseDataBuffer)(unsafe.Pointer(&rdbbuf[0]))1511var s string1512switch rdb.ReparseTag {1513case IO_REPARSE_TAG_SYMLINK:1514data := (*symbolicLinkReparseBuffer)(unsafe.Pointer(&rdb.reparseBuffer))1515p := (*[0xffff]uint16)(unsafe.Pointer(&data.PathBuffer[0]))1516s = UTF16ToString(p[data.PrintNameOffset/2 : (data.PrintNameLength-data.PrintNameOffset)/2])1517case IO_REPARSE_TAG_MOUNT_POINT:1518data := (*mountPointReparseBuffer)(unsafe.Pointer(&rdb.reparseBuffer))1519p := (*[0xffff]uint16)(unsafe.Pointer(&data.PathBuffer[0]))1520s = UTF16ToString(p[data.PrintNameOffset/2 : (data.PrintNameLength-data.PrintNameOffset)/2])1521default:1522// the path is not a symlink or junction but another type of reparse1523// point1524return -1, syscall.ENOENT1525}1526n = copy(buf, []byte(s))15271528return n, nil1529}15301531// GUIDFromString parses a string in the form of1532// "{XXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}" into a GUID.1533func GUIDFromString(str string) (GUID, error) {1534guid := GUID{}1535str16, err := syscall.UTF16PtrFromString(str)1536if err != nil {1537return guid, err1538}1539err = clsidFromString(str16, &guid)1540if err != nil {1541return guid, err1542}1543return guid, nil1544}15451546// GenerateGUID creates a new random GUID.1547func GenerateGUID() (GUID, error) {1548guid := GUID{}1549err := coCreateGuid(&guid)1550if err != nil {1551return guid, err1552}1553return guid, nil1554}15551556// String returns the canonical string form of the GUID,1557// in the form of "{XXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}".1558func (guid GUID) String() string {1559var str [100]uint161560chars := stringFromGUID2(&guid, &str[0], int32(len(str)))1561if chars <= 1 {1562return ""1563}1564return string(utf16.Decode(str[:chars-1]))1565}15661567// KnownFolderPath returns a well-known folder path for the current user, specified by one of1568// the FOLDERID_ constants, and chosen and optionally created based on a KF_ flag.1569func KnownFolderPath(folderID *KNOWNFOLDERID, flags uint32) (string, error) {1570return Token(0).KnownFolderPath(folderID, flags)1571}15721573// KnownFolderPath returns a well-known folder path for the user token, specified by one of1574// the FOLDERID_ constants, and chosen and optionally created based on a KF_ flag.1575func (t Token) KnownFolderPath(folderID *KNOWNFOLDERID, flags uint32) (string, error) {1576var p *uint161577err := shGetKnownFolderPath(folderID, flags, t, &p)1578if err != nil {1579return "", err1580}1581defer CoTaskMemFree(unsafe.Pointer(p))1582return UTF16PtrToString(p), nil1583}15841585// RtlGetVersion returns the version of the underlying operating system, ignoring1586// manifest semantics but is affected by the application compatibility layer.1587func RtlGetVersion() *OsVersionInfoEx {1588info := &OsVersionInfoEx{}1589info.osVersionInfoSize = uint32(unsafe.Sizeof(*info))1590// According to documentation, this function always succeeds.1591// The function doesn't even check the validity of the1592// osVersionInfoSize member. Disassembling ntdll.dll indicates1593// that the documentation is indeed correct about that.1594_ = rtlGetVersion(info)1595return info1596}15971598// RtlGetNtVersionNumbers returns the version of the underlying operating system,1599// ignoring manifest semantics and the application compatibility layer.1600func RtlGetNtVersionNumbers() (majorVersion, minorVersion, buildNumber uint32) {1601rtlGetNtVersionNumbers(&majorVersion, &minorVersion, &buildNumber)1602buildNumber &= 0xffff1603return1604}16051606// GetProcessPreferredUILanguages retrieves the process preferred UI languages.1607func GetProcessPreferredUILanguages(flags uint32) ([]string, error) {1608return getUILanguages(flags, getProcessPreferredUILanguages)1609}16101611// GetThreadPreferredUILanguages retrieves the thread preferred UI languages for the current thread.1612func GetThreadPreferredUILanguages(flags uint32) ([]string, error) {1613return getUILanguages(flags, getThreadPreferredUILanguages)1614}16151616// GetUserPreferredUILanguages retrieves information about the user preferred UI languages.1617func GetUserPreferredUILanguages(flags uint32) ([]string, error) {1618return getUILanguages(flags, getUserPreferredUILanguages)1619}16201621// GetSystemPreferredUILanguages retrieves the system preferred UI languages.1622func GetSystemPreferredUILanguages(flags uint32) ([]string, error) {1623return getUILanguages(flags, getSystemPreferredUILanguages)1624}16251626func getUILanguages(flags uint32, f func(flags uint32, numLanguages *uint32, buf *uint16, bufSize *uint32) error) ([]string, error) {1627size := uint32(128)1628for {1629var numLanguages uint321630buf := make([]uint16, size)1631err := f(flags, &numLanguages, &buf[0], &size)1632if err == ERROR_INSUFFICIENT_BUFFER {1633continue1634}1635if err != nil {1636return nil, err1637}1638buf = buf[:size]1639if numLanguages == 0 || len(buf) == 0 { // GetProcessPreferredUILanguages may return numLanguages==0 with "\0\0"1640return []string{}, nil1641}1642if buf[len(buf)-1] == 0 {1643buf = buf[:len(buf)-1] // remove terminating null1644}1645languages := make([]string, 0, numLanguages)1646from := 01647for i, c := range buf {1648if c == 0 {1649languages = append(languages, string(utf16.Decode(buf[from:i])))1650from = i + 11651}1652}1653return languages, nil1654}1655}16561657func SetConsoleCursorPosition(console Handle, position Coord) error {1658return setConsoleCursorPosition(console, *((*uint32)(unsafe.Pointer(&position))))1659}16601661func GetStartupInfo(startupInfo *StartupInfo) error {1662getStartupInfo(startupInfo)1663return nil1664}16651666func (s NTStatus) Errno() syscall.Errno {1667return rtlNtStatusToDosErrorNoTeb(s)1668}16691670func langID(pri, sub uint16) uint32 { return uint32(sub)<<10 | uint32(pri) }16711672func (s NTStatus) Error() string {1673b := make([]uint16, 300)1674n, 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)1675if err != nil {1676return fmt.Sprintf("NTSTATUS 0x%08x", uint32(s))1677}1678// trim terminating \r and \n1679for ; n > 0 && (b[n-1] == '\n' || b[n-1] == '\r'); n-- {1680}1681return string(utf16.Decode(b[:n]))1682}16831684// NewNTUnicodeString returns a new NTUnicodeString structure for use with native1685// NT APIs that work over the NTUnicodeString type. Note that most Windows APIs1686// do not use NTUnicodeString, and instead UTF16PtrFromString should be used for1687// the more common *uint16 string type.1688func NewNTUnicodeString(s string) (*NTUnicodeString, error) {1689s16, err := UTF16FromString(s)1690if err != nil {1691return nil, err1692}1693n := uint16(len(s16) * 2)1694return &NTUnicodeString{1695Length: n - 2, // subtract 2 bytes for the NULL terminator1696MaximumLength: n,1697Buffer: &s16[0],1698}, nil1699}17001701// Slice returns a uint16 slice that aliases the data in the NTUnicodeString.1702func (s *NTUnicodeString) Slice() []uint16 {1703// Note: this rounds the length down, if it happens1704// to (incorrectly) be odd. Probably safer than rounding up.1705return unsafe.Slice(s.Buffer, s.MaximumLength/2)[:s.Length/2]1706}17071708func (s *NTUnicodeString) String() string {1709return UTF16ToString(s.Slice())1710}17111712// NewNTString returns a new NTString structure for use with native1713// NT APIs that work over the NTString type. Note that most Windows APIs1714// do not use NTString, and instead UTF16PtrFromString should be used for1715// the more common *uint16 string type.1716func NewNTString(s string) (*NTString, error) {1717var nts NTString1718s8, err := BytePtrFromString(s)1719if err != nil {1720return nil, err1721}1722RtlInitString(&nts, s8)1723return &nts, nil1724}17251726// Slice returns a byte slice that aliases the data in the NTString.1727func (s *NTString) Slice() []byte {1728slice := unsafe.Slice(s.Buffer, s.MaximumLength)1729return slice[:s.Length]1730}17311732func (s *NTString) String() string {1733return ByteSliceToString(s.Slice())1734}17351736// FindResource resolves a resource of the given name and resource type.1737func FindResource(module Handle, name, resType ResourceIDOrString) (Handle, error) {1738var namePtr, resTypePtr uintptr1739var name16, resType16 *uint161740var err error1741resolvePtr := func(i interface{}, keep **uint16) (uintptr, error) {1742switch v := i.(type) {1743case string:1744*keep, err = UTF16PtrFromString(v)1745if err != nil {1746return 0, err1747}1748return uintptr(unsafe.Pointer(*keep)), nil1749case ResourceID:1750return uintptr(v), nil1751}1752return 0, errorspkg.New("parameter must be a ResourceID or a string")1753}1754namePtr, err = resolvePtr(name, &name16)1755if err != nil {1756return 0, err1757}1758resTypePtr, err = resolvePtr(resType, &resType16)1759if err != nil {1760return 0, err1761}1762resInfo, err := findResource(module, namePtr, resTypePtr)1763runtime.KeepAlive(name16)1764runtime.KeepAlive(resType16)1765return resInfo, err1766}17671768func LoadResourceData(module, resInfo Handle) (data []byte, err error) {1769size, err := SizeofResource(module, resInfo)1770if err != nil {1771return1772}1773resData, err := LoadResource(module, resInfo)1774if err != nil {1775return1776}1777ptr, err := LockResource(resData)1778if err != nil {1779return1780}1781data = unsafe.Slice((*byte)(unsafe.Pointer(ptr)), size)1782return1783}17841785// PSAPI_WORKING_SET_EX_BLOCK contains extended working set information for a page.1786type PSAPI_WORKING_SET_EX_BLOCK uint6417871788// Valid returns the validity of this page.1789// If this bit is 1, the subsequent members are valid; otherwise they should be ignored.1790func (b PSAPI_WORKING_SET_EX_BLOCK) Valid() bool {1791return (b & 1) == 11792}17931794// ShareCount is the number of processes that share this page. The maximum value of this member is 7.1795func (b PSAPI_WORKING_SET_EX_BLOCK) ShareCount() uint64 {1796return b.intField(1, 3)1797}17981799// Win32Protection is the memory protection attributes of the page. For a list of values, see1800// https://docs.microsoft.com/en-us/windows/win32/memory/memory-protection-constants1801func (b PSAPI_WORKING_SET_EX_BLOCK) Win32Protection() uint64 {1802return b.intField(4, 11)1803}18041805// Shared returns the shared status of this page.1806// If this bit is 1, the page can be shared.1807func (b PSAPI_WORKING_SET_EX_BLOCK) Shared() bool {1808return (b & (1 << 15)) == 11809}18101811// Node is the NUMA node. The maximum value of this member is 63.1812func (b PSAPI_WORKING_SET_EX_BLOCK) Node() uint64 {1813return b.intField(16, 6)1814}18151816// Locked returns the locked status of this page.1817// If this bit is 1, the virtual page is locked in physical memory.1818func (b PSAPI_WORKING_SET_EX_BLOCK) Locked() bool {1819return (b & (1 << 22)) == 11820}18211822// LargePage returns the large page status of this page.1823// If this bit is 1, the page is a large page.1824func (b PSAPI_WORKING_SET_EX_BLOCK) LargePage() bool {1825return (b & (1 << 23)) == 11826}18271828// Bad returns the bad status of this page.1829// If this bit is 1, the page is has been reported as bad.1830func (b PSAPI_WORKING_SET_EX_BLOCK) Bad() bool {1831return (b & (1 << 31)) == 11832}18331834// intField extracts an integer field in the PSAPI_WORKING_SET_EX_BLOCK union.1835func (b PSAPI_WORKING_SET_EX_BLOCK) intField(start, length int) uint64 {1836var mask PSAPI_WORKING_SET_EX_BLOCK1837for pos := start; pos < start+length; pos++ {1838mask |= (1 << pos)1839}18401841masked := b & mask1842return uint64(masked >> start)1843}18441845// PSAPI_WORKING_SET_EX_INFORMATION contains extended working set information for a process.1846type PSAPI_WORKING_SET_EX_INFORMATION struct {1847// The virtual address.1848VirtualAddress Pointer1849// A PSAPI_WORKING_SET_EX_BLOCK union that indicates the attributes of the page at VirtualAddress.1850VirtualAttributes PSAPI_WORKING_SET_EX_BLOCK1851}18521853// CreatePseudoConsole creates a windows pseudo console.1854func CreatePseudoConsole(size Coord, in Handle, out Handle, flags uint32, pconsole *Handle) error {1855// We need this wrapper to manually cast Coord to uint32. The autogenerated wrappers only1856// accept arguments that can be casted to uintptr, and Coord can't.1857return createPseudoConsole(*((*uint32)(unsafe.Pointer(&size))), in, out, flags, pconsole)1858}18591860// ResizePseudoConsole resizes the internal buffers of the pseudo console to the width and height specified in `size`.1861func ResizePseudoConsole(pconsole Handle, size Coord) error {1862// We need this wrapper to manually cast Coord to uint32. The autogenerated wrappers only1863// accept arguments that can be casted to uintptr, and Coord can't.1864return resizePseudoConsole(pconsole, *((*uint32)(unsafe.Pointer(&size))))1865}18661867// DCB constants. See https://learn.microsoft.com/en-us/windows/win32/api/winbase/ns-winbase-dcb.1868const (1869CBR_110 = 1101870CBR_300 = 3001871CBR_600 = 6001872CBR_1200 = 12001873CBR_2400 = 24001874CBR_4800 = 48001875CBR_9600 = 96001876CBR_14400 = 144001877CBR_19200 = 192001878CBR_38400 = 384001879CBR_57600 = 576001880CBR_115200 = 1152001881CBR_128000 = 1280001882CBR_256000 = 25600018831884DTR_CONTROL_DISABLE = 0x000000001885DTR_CONTROL_ENABLE = 0x000000101886DTR_CONTROL_HANDSHAKE = 0x0000002018871888RTS_CONTROL_DISABLE = 0x000000001889RTS_CONTROL_ENABLE = 0x000010001890RTS_CONTROL_HANDSHAKE = 0x000020001891RTS_CONTROL_TOGGLE = 0x0000300018921893NOPARITY = 01894ODDPARITY = 11895EVENPARITY = 21896MARKPARITY = 31897SPACEPARITY = 418981899ONESTOPBIT = 01900ONE5STOPBITS = 11901TWOSTOPBITS = 21902)19031904// EscapeCommFunction constants. See https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-escapecommfunction.1905const (1906SETXOFF = 11907SETXON = 21908SETRTS = 31909CLRRTS = 41910SETDTR = 51911CLRDTR = 61912SETBREAK = 81913CLRBREAK = 91914)19151916// PurgeComm constants. See https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-purgecomm.1917const (1918PURGE_TXABORT = 0x00011919PURGE_RXABORT = 0x00021920PURGE_TXCLEAR = 0x00041921PURGE_RXCLEAR = 0x00081922)19231924// SetCommMask constants. See https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-setcommmask.1925const (1926EV_RXCHAR = 0x00011927EV_RXFLAG = 0x00021928EV_TXEMPTY = 0x00041929EV_CTS = 0x00081930EV_DSR = 0x00101931EV_RLSD = 0x00201932EV_BREAK = 0x00401933EV_ERR = 0x00801934EV_RING = 0x01001935)193619371938