syscall_windows.go 53 KB

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