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