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