本站源代码
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.

1335 lines
52KB

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