You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1153 lines
44 KiB

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