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