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