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