syscall_windows.go 54 KB

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