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