syscall_windows.go 80 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836
  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. "fmt"
  9. "runtime"
  10. "sync"
  11. "syscall"
  12. "time"
  13. "unicode/utf16"
  14. "unsafe"
  15. )
  16. type Handle uintptr
  17. type HWND uintptr
  18. const (
  19. InvalidHandle = ^Handle(0)
  20. InvalidHWND = ^HWND(0)
  21. // Flags for DefineDosDevice.
  22. DDD_EXACT_MATCH_ON_REMOVE = 0x00000004
  23. DDD_NO_BROADCAST_SYSTEM = 0x00000008
  24. DDD_RAW_TARGET_PATH = 0x00000001
  25. DDD_REMOVE_DEFINITION = 0x00000002
  26. // Return values for GetDriveType.
  27. DRIVE_UNKNOWN = 0
  28. DRIVE_NO_ROOT_DIR = 1
  29. DRIVE_REMOVABLE = 2
  30. DRIVE_FIXED = 3
  31. DRIVE_REMOTE = 4
  32. DRIVE_CDROM = 5
  33. DRIVE_RAMDISK = 6
  34. // File system flags from GetVolumeInformation and GetVolumeInformationByHandle.
  35. FILE_CASE_SENSITIVE_SEARCH = 0x00000001
  36. FILE_CASE_PRESERVED_NAMES = 0x00000002
  37. FILE_FILE_COMPRESSION = 0x00000010
  38. FILE_DAX_VOLUME = 0x20000000
  39. FILE_NAMED_STREAMS = 0x00040000
  40. FILE_PERSISTENT_ACLS = 0x00000008
  41. FILE_READ_ONLY_VOLUME = 0x00080000
  42. FILE_SEQUENTIAL_WRITE_ONCE = 0x00100000
  43. FILE_SUPPORTS_ENCRYPTION = 0x00020000
  44. FILE_SUPPORTS_EXTENDED_ATTRIBUTES = 0x00800000
  45. FILE_SUPPORTS_HARD_LINKS = 0x00400000
  46. FILE_SUPPORTS_OBJECT_IDS = 0x00010000
  47. FILE_SUPPORTS_OPEN_BY_FILE_ID = 0x01000000
  48. FILE_SUPPORTS_REPARSE_POINTS = 0x00000080
  49. FILE_SUPPORTS_SPARSE_FILES = 0x00000040
  50. FILE_SUPPORTS_TRANSACTIONS = 0x00200000
  51. FILE_SUPPORTS_USN_JOURNAL = 0x02000000
  52. FILE_UNICODE_ON_DISK = 0x00000004
  53. FILE_VOLUME_IS_COMPRESSED = 0x00008000
  54. FILE_VOLUME_QUOTAS = 0x00000020
  55. // Flags for LockFileEx.
  56. LOCKFILE_FAIL_IMMEDIATELY = 0x00000001
  57. LOCKFILE_EXCLUSIVE_LOCK = 0x00000002
  58. // Return value of SleepEx and other APC functions
  59. WAIT_IO_COMPLETION = 0x000000C0
  60. )
  61. // StringToUTF16 is deprecated. Use UTF16FromString instead.
  62. // If s contains a NUL byte this function panics instead of
  63. // returning an error.
  64. func StringToUTF16(s string) []uint16 {
  65. a, err := UTF16FromString(s)
  66. if err != nil {
  67. panic("windows: string with NUL passed to StringToUTF16")
  68. }
  69. return a
  70. }
  71. // UTF16FromString returns the UTF-16 encoding of the UTF-8 string
  72. // s, with a terminating NUL added. If s contains a NUL byte at any
  73. // location, it returns (nil, syscall.EINVAL).
  74. func UTF16FromString(s string) ([]uint16, error) {
  75. return syscall.UTF16FromString(s)
  76. }
  77. // UTF16ToString returns the UTF-8 encoding of the UTF-16 sequence s,
  78. // with a terminating NUL and any bytes after the NUL removed.
  79. func UTF16ToString(s []uint16) string {
  80. return syscall.UTF16ToString(s)
  81. }
  82. // StringToUTF16Ptr is deprecated. Use UTF16PtrFromString instead.
  83. // If s contains a NUL byte this function panics instead of
  84. // returning an error.
  85. func StringToUTF16Ptr(s string) *uint16 { return &StringToUTF16(s)[0] }
  86. // UTF16PtrFromString returns pointer to the UTF-16 encoding of
  87. // the UTF-8 string s, with a terminating NUL added. If s
  88. // contains a NUL byte at any location, it returns (nil, syscall.EINVAL).
  89. func UTF16PtrFromString(s string) (*uint16, error) {
  90. a, err := UTF16FromString(s)
  91. if err != nil {
  92. return nil, err
  93. }
  94. return &a[0], nil
  95. }
  96. // UTF16PtrToString takes a pointer to a UTF-16 sequence and returns the corresponding UTF-8 encoded string.
  97. // If the pointer is nil, it returns the empty string. It assumes that the UTF-16 sequence is terminated
  98. // at a zero word; if the zero word is not present, the program may crash.
  99. func UTF16PtrToString(p *uint16) string {
  100. if p == nil {
  101. return ""
  102. }
  103. if *p == 0 {
  104. return ""
  105. }
  106. // Find NUL terminator.
  107. n := 0
  108. for ptr := unsafe.Pointer(p); *(*uint16)(ptr) != 0; n++ {
  109. ptr = unsafe.Pointer(uintptr(ptr) + unsafe.Sizeof(*p))
  110. }
  111. return string(utf16.Decode(unsafe.Slice(p, n)))
  112. }
  113. func Getpagesize() int { return 4096 }
  114. // NewCallback converts a Go function to a function pointer conforming to the stdcall calling convention.
  115. // This is useful when interoperating with Windows code requiring callbacks.
  116. // The argument is expected to be a function with one uintptr-sized result. The function must not have arguments with size larger than the size of uintptr.
  117. func NewCallback(fn interface{}) uintptr {
  118. return syscall.NewCallback(fn)
  119. }
  120. // NewCallbackCDecl converts a Go function to a function pointer conforming to the cdecl calling convention.
  121. // This is useful when interoperating with Windows code requiring callbacks.
  122. // The argument is expected to be a function with one uintptr-sized result. The function must not have arguments with size larger than the size of uintptr.
  123. func NewCallbackCDecl(fn interface{}) uintptr {
  124. return syscall.NewCallbackCDecl(fn)
  125. }
  126. // windows api calls
  127. //sys GetLastError() (lasterr error)
  128. //sys LoadLibrary(libname string) (handle Handle, err error) = LoadLibraryW
  129. //sys LoadLibraryEx(libname string, zero Handle, flags uintptr) (handle Handle, err error) = LoadLibraryExW
  130. //sys FreeLibrary(handle Handle) (err error)
  131. //sys GetProcAddress(module Handle, procname string) (proc uintptr, err error)
  132. //sys GetModuleFileName(module Handle, filename *uint16, size uint32) (n uint32, err error) = kernel32.GetModuleFileNameW
  133. //sys GetModuleHandleEx(flags uint32, moduleName *uint16, module *Handle) (err error) = kernel32.GetModuleHandleExW
  134. //sys SetDefaultDllDirectories(directoryFlags uint32) (err error)
  135. //sys AddDllDirectory(path *uint16) (cookie uintptr, err error) = kernel32.AddDllDirectory
  136. //sys RemoveDllDirectory(cookie uintptr) (err error) = kernel32.RemoveDllDirectory
  137. //sys SetDllDirectory(path string) (err error) = kernel32.SetDllDirectoryW
  138. //sys GetVersion() (ver uint32, err error)
  139. //sys FormatMessage(flags uint32, msgsrc uintptr, msgid uint32, langid uint32, buf []uint16, args *byte) (n uint32, err error) = FormatMessageW
  140. //sys ExitProcess(exitcode uint32)
  141. //sys IsWow64Process(handle Handle, isWow64 *bool) (err error) = IsWow64Process
  142. //sys IsWow64Process2(handle Handle, processMachine *uint16, nativeMachine *uint16) (err error) = IsWow64Process2?
  143. //sys CreateFile(name *uint16, access uint32, mode uint32, sa *SecurityAttributes, createmode uint32, attrs uint32, templatefile Handle) (handle Handle, err error) [failretval==InvalidHandle] = CreateFileW
  144. //sys CreateNamedPipe(name *uint16, flags uint32, pipeMode uint32, maxInstances uint32, outSize uint32, inSize uint32, defaultTimeout uint32, sa *SecurityAttributes) (handle Handle, err error) [failretval==InvalidHandle] = CreateNamedPipeW
  145. //sys ConnectNamedPipe(pipe Handle, overlapped *Overlapped) (err error)
  146. //sys GetNamedPipeInfo(pipe Handle, flags *uint32, outSize *uint32, inSize *uint32, maxInstances *uint32) (err error)
  147. //sys GetNamedPipeHandleState(pipe Handle, state *uint32, curInstances *uint32, maxCollectionCount *uint32, collectDataTimeout *uint32, userName *uint16, maxUserNameSize uint32) (err error) = GetNamedPipeHandleStateW
  148. //sys SetNamedPipeHandleState(pipe Handle, state *uint32, maxCollectionCount *uint32, collectDataTimeout *uint32) (err error) = SetNamedPipeHandleState
  149. //sys readFile(handle Handle, buf []byte, done *uint32, overlapped *Overlapped) (err error) = ReadFile
  150. //sys writeFile(handle Handle, buf []byte, done *uint32, overlapped *Overlapped) (err error) = WriteFile
  151. //sys GetOverlappedResult(handle Handle, overlapped *Overlapped, done *uint32, wait bool) (err error)
  152. //sys SetFilePointer(handle Handle, lowoffset int32, highoffsetptr *int32, whence uint32) (newlowoffset uint32, err error) [failretval==0xffffffff]
  153. //sys CloseHandle(handle Handle) (err error)
  154. //sys GetStdHandle(stdhandle uint32) (handle Handle, err error) [failretval==InvalidHandle]
  155. //sys SetStdHandle(stdhandle uint32, handle Handle) (err error)
  156. //sys findFirstFile1(name *uint16, data *win32finddata1) (handle Handle, err error) [failretval==InvalidHandle] = FindFirstFileW
  157. //sys findNextFile1(handle Handle, data *win32finddata1) (err error) = FindNextFileW
  158. //sys FindClose(handle Handle) (err error)
  159. //sys GetFileInformationByHandle(handle Handle, data *ByHandleFileInformation) (err error)
  160. //sys GetFileInformationByHandleEx(handle Handle, class uint32, outBuffer *byte, outBufferLen uint32) (err error)
  161. //sys SetFileInformationByHandle(handle Handle, class uint32, inBuffer *byte, inBufferLen uint32) (err error)
  162. //sys GetCurrentDirectory(buflen uint32, buf *uint16) (n uint32, err error) = GetCurrentDirectoryW
  163. //sys SetCurrentDirectory(path *uint16) (err error) = SetCurrentDirectoryW
  164. //sys CreateDirectory(path *uint16, sa *SecurityAttributes) (err error) = CreateDirectoryW
  165. //sys RemoveDirectory(path *uint16) (err error) = RemoveDirectoryW
  166. //sys DeleteFile(path *uint16) (err error) = DeleteFileW
  167. //sys MoveFile(from *uint16, to *uint16) (err error) = MoveFileW
  168. //sys MoveFileEx(from *uint16, to *uint16, flags uint32) (err error) = MoveFileExW
  169. //sys LockFileEx(file Handle, flags uint32, reserved uint32, bytesLow uint32, bytesHigh uint32, overlapped *Overlapped) (err error)
  170. //sys UnlockFileEx(file Handle, reserved uint32, bytesLow uint32, bytesHigh uint32, overlapped *Overlapped) (err error)
  171. //sys GetComputerName(buf *uint16, n *uint32) (err error) = GetComputerNameW
  172. //sys GetComputerNameEx(nametype uint32, buf *uint16, n *uint32) (err error) = GetComputerNameExW
  173. //sys SetEndOfFile(handle Handle) (err error)
  174. //sys GetSystemTimeAsFileTime(time *Filetime)
  175. //sys GetSystemTimePreciseAsFileTime(time *Filetime)
  176. //sys GetTimeZoneInformation(tzi *Timezoneinformation) (rc uint32, err error) [failretval==0xffffffff]
  177. //sys CreateIoCompletionPort(filehandle Handle, cphandle Handle, key uintptr, threadcnt uint32) (handle Handle, err error)
  178. //sys GetQueuedCompletionStatus(cphandle Handle, qty *uint32, key *uintptr, overlapped **Overlapped, timeout uint32) (err error)
  179. //sys PostQueuedCompletionStatus(cphandle Handle, qty uint32, key uintptr, overlapped *Overlapped) (err error)
  180. //sys CancelIo(s Handle) (err error)
  181. //sys CancelIoEx(s Handle, o *Overlapped) (err error)
  182. //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
  183. //sys CreateProcessAsUser(token Token, appName *uint16, commandLine *uint16, procSecurity *SecurityAttributes, threadSecurity *SecurityAttributes, inheritHandles bool, creationFlags uint32, env *uint16, currentDir *uint16, startupInfo *StartupInfo, outProcInfo *ProcessInformation) (err error) = advapi32.CreateProcessAsUserW
  184. //sys initializeProcThreadAttributeList(attrlist *ProcThreadAttributeList, attrcount uint32, flags uint32, size *uintptr) (err error) = InitializeProcThreadAttributeList
  185. //sys deleteProcThreadAttributeList(attrlist *ProcThreadAttributeList) = DeleteProcThreadAttributeList
  186. //sys updateProcThreadAttribute(attrlist *ProcThreadAttributeList, flags uint32, attr uintptr, value unsafe.Pointer, size uintptr, prevvalue unsafe.Pointer, returnedsize *uintptr) (err error) = UpdateProcThreadAttribute
  187. //sys OpenProcess(desiredAccess uint32, inheritHandle bool, processId uint32) (handle Handle, err error)
  188. //sys ShellExecute(hwnd Handle, verb *uint16, file *uint16, args *uint16, cwd *uint16, showCmd int32) (err error) [failretval<=32] = shell32.ShellExecuteW
  189. //sys GetWindowThreadProcessId(hwnd HWND, pid *uint32) (tid uint32, err error) = user32.GetWindowThreadProcessId
  190. //sys GetShellWindow() (shellWindow HWND) = user32.GetShellWindow
  191. //sys MessageBox(hwnd HWND, text *uint16, caption *uint16, boxtype uint32) (ret int32, err error) [failretval==0] = user32.MessageBoxW
  192. //sys ExitWindowsEx(flags uint32, reason uint32) (err error) = user32.ExitWindowsEx
  193. //sys shGetKnownFolderPath(id *KNOWNFOLDERID, flags uint32, token Token, path **uint16) (ret error) = shell32.SHGetKnownFolderPath
  194. //sys TerminateProcess(handle Handle, exitcode uint32) (err error)
  195. //sys GetExitCodeProcess(handle Handle, exitcode *uint32) (err error)
  196. //sys getStartupInfo(startupInfo *StartupInfo) = GetStartupInfoW
  197. //sys GetProcessTimes(handle Handle, creationTime *Filetime, exitTime *Filetime, kernelTime *Filetime, userTime *Filetime) (err error)
  198. //sys DuplicateHandle(hSourceProcessHandle Handle, hSourceHandle Handle, hTargetProcessHandle Handle, lpTargetHandle *Handle, dwDesiredAccess uint32, bInheritHandle bool, dwOptions uint32) (err error)
  199. //sys WaitForSingleObject(handle Handle, waitMilliseconds uint32) (event uint32, err error) [failretval==0xffffffff]
  200. //sys waitForMultipleObjects(count uint32, handles uintptr, waitAll bool, waitMilliseconds uint32) (event uint32, err error) [failretval==0xffffffff] = WaitForMultipleObjects
  201. //sys GetTempPath(buflen uint32, buf *uint16) (n uint32, err error) = GetTempPathW
  202. //sys CreatePipe(readhandle *Handle, writehandle *Handle, sa *SecurityAttributes, size uint32) (err error)
  203. //sys GetFileType(filehandle Handle) (n uint32, err error)
  204. //sys CryptAcquireContext(provhandle *Handle, container *uint16, provider *uint16, provtype uint32, flags uint32) (err error) = advapi32.CryptAcquireContextW
  205. //sys CryptReleaseContext(provhandle Handle, flags uint32) (err error) = advapi32.CryptReleaseContext
  206. //sys CryptGenRandom(provhandle Handle, buflen uint32, buf *byte) (err error) = advapi32.CryptGenRandom
  207. //sys GetEnvironmentStrings() (envs *uint16, err error) [failretval==nil] = kernel32.GetEnvironmentStringsW
  208. //sys FreeEnvironmentStrings(envs *uint16) (err error) = kernel32.FreeEnvironmentStringsW
  209. //sys GetEnvironmentVariable(name *uint16, buffer *uint16, size uint32) (n uint32, err error) = kernel32.GetEnvironmentVariableW
  210. //sys SetEnvironmentVariable(name *uint16, value *uint16) (err error) = kernel32.SetEnvironmentVariableW
  211. //sys ExpandEnvironmentStrings(src *uint16, dst *uint16, size uint32) (n uint32, err error) = kernel32.ExpandEnvironmentStringsW
  212. //sys CreateEnvironmentBlock(block **uint16, token Token, inheritExisting bool) (err error) = userenv.CreateEnvironmentBlock
  213. //sys DestroyEnvironmentBlock(block *uint16) (err error) = userenv.DestroyEnvironmentBlock
  214. //sys getTickCount64() (ms uint64) = kernel32.GetTickCount64
  215. //sys GetFileTime(handle Handle, ctime *Filetime, atime *Filetime, wtime *Filetime) (err error)
  216. //sys SetFileTime(handle Handle, ctime *Filetime, atime *Filetime, wtime *Filetime) (err error)
  217. //sys GetFileAttributes(name *uint16) (attrs uint32, err error) [failretval==INVALID_FILE_ATTRIBUTES] = kernel32.GetFileAttributesW
  218. //sys SetFileAttributes(name *uint16, attrs uint32) (err error) = kernel32.SetFileAttributesW
  219. //sys GetFileAttributesEx(name *uint16, level uint32, info *byte) (err error) = kernel32.GetFileAttributesExW
  220. //sys GetCommandLine() (cmd *uint16) = kernel32.GetCommandLineW
  221. //sys commandLineToArgv(cmd *uint16, argc *int32) (argv **uint16, err error) [failretval==nil] = shell32.CommandLineToArgvW
  222. //sys LocalFree(hmem Handle) (handle Handle, err error) [failretval!=0]
  223. //sys LocalAlloc(flags uint32, length uint32) (ptr uintptr, err error)
  224. //sys SetHandleInformation(handle Handle, mask uint32, flags uint32) (err error)
  225. //sys FlushFileBuffers(handle Handle) (err error)
  226. //sys GetFullPathName(path *uint16, buflen uint32, buf *uint16, fname **uint16) (n uint32, err error) = kernel32.GetFullPathNameW
  227. //sys GetLongPathName(path *uint16, buf *uint16, buflen uint32) (n uint32, err error) = kernel32.GetLongPathNameW
  228. //sys GetShortPathName(longpath *uint16, shortpath *uint16, buflen uint32) (n uint32, err error) = kernel32.GetShortPathNameW
  229. //sys GetFinalPathNameByHandle(file Handle, filePath *uint16, filePathSize uint32, flags uint32) (n uint32, err error) = kernel32.GetFinalPathNameByHandleW
  230. //sys CreateFileMapping(fhandle Handle, sa *SecurityAttributes, prot uint32, maxSizeHigh uint32, maxSizeLow uint32, name *uint16) (handle Handle, err error) [failretval == 0 || e1 == ERROR_ALREADY_EXISTS] = kernel32.CreateFileMappingW
  231. //sys MapViewOfFile(handle Handle, access uint32, offsetHigh uint32, offsetLow uint32, length uintptr) (addr uintptr, err error)
  232. //sys UnmapViewOfFile(addr uintptr) (err error)
  233. //sys FlushViewOfFile(addr uintptr, length uintptr) (err error)
  234. //sys VirtualLock(addr uintptr, length uintptr) (err error)
  235. //sys VirtualUnlock(addr uintptr, length uintptr) (err error)
  236. //sys VirtualAlloc(address uintptr, size uintptr, alloctype uint32, protect uint32) (value uintptr, err error) = kernel32.VirtualAlloc
  237. //sys VirtualFree(address uintptr, size uintptr, freetype uint32) (err error) = kernel32.VirtualFree
  238. //sys VirtualProtect(address uintptr, size uintptr, newprotect uint32, oldprotect *uint32) (err error) = kernel32.VirtualProtect
  239. //sys VirtualProtectEx(process Handle, address uintptr, size uintptr, newProtect uint32, oldProtect *uint32) (err error) = kernel32.VirtualProtectEx
  240. //sys VirtualQuery(address uintptr, buffer *MemoryBasicInformation, length uintptr) (err error) = kernel32.VirtualQuery
  241. //sys VirtualQueryEx(process Handle, address uintptr, buffer *MemoryBasicInformation, length uintptr) (err error) = kernel32.VirtualQueryEx
  242. //sys ReadProcessMemory(process Handle, baseAddress uintptr, buffer *byte, size uintptr, numberOfBytesRead *uintptr) (err error) = kernel32.ReadProcessMemory
  243. //sys WriteProcessMemory(process Handle, baseAddress uintptr, buffer *byte, size uintptr, numberOfBytesWritten *uintptr) (err error) = kernel32.WriteProcessMemory
  244. //sys TransmitFile(s Handle, handle Handle, bytesToWrite uint32, bytsPerSend uint32, overlapped *Overlapped, transmitFileBuf *TransmitFileBuffers, flags uint32) (err error) = mswsock.TransmitFile
  245. //sys ReadDirectoryChanges(handle Handle, buf *byte, buflen uint32, watchSubTree bool, mask uint32, retlen *uint32, overlapped *Overlapped, completionRoutine uintptr) (err error) = kernel32.ReadDirectoryChangesW
  246. //sys FindFirstChangeNotification(path string, watchSubtree bool, notifyFilter uint32) (handle Handle, err error) [failretval==InvalidHandle] = kernel32.FindFirstChangeNotificationW
  247. //sys FindNextChangeNotification(handle Handle) (err error)
  248. //sys FindCloseChangeNotification(handle Handle) (err error)
  249. //sys CertOpenSystemStore(hprov Handle, name *uint16) (store Handle, err error) = crypt32.CertOpenSystemStoreW
  250. //sys CertOpenStore(storeProvider uintptr, msgAndCertEncodingType uint32, cryptProv uintptr, flags uint32, para uintptr) (handle Handle, err error) = crypt32.CertOpenStore
  251. //sys CertEnumCertificatesInStore(store Handle, prevContext *CertContext) (context *CertContext, err error) [failretval==nil] = crypt32.CertEnumCertificatesInStore
  252. //sys CertAddCertificateContextToStore(store Handle, certContext *CertContext, addDisposition uint32, storeContext **CertContext) (err error) = crypt32.CertAddCertificateContextToStore
  253. //sys CertCloseStore(store Handle, flags uint32) (err error) = crypt32.CertCloseStore
  254. //sys CertDeleteCertificateFromStore(certContext *CertContext) (err error) = crypt32.CertDeleteCertificateFromStore
  255. //sys CertDuplicateCertificateContext(certContext *CertContext) (dupContext *CertContext) = crypt32.CertDuplicateCertificateContext
  256. //sys PFXImportCertStore(pfx *CryptDataBlob, password *uint16, flags uint32) (store Handle, err error) = crypt32.PFXImportCertStore
  257. //sys CertGetCertificateChain(engine Handle, leaf *CertContext, time *Filetime, additionalStore Handle, para *CertChainPara, flags uint32, reserved uintptr, chainCtx **CertChainContext) (err error) = crypt32.CertGetCertificateChain
  258. //sys CertFreeCertificateChain(ctx *CertChainContext) = crypt32.CertFreeCertificateChain
  259. //sys CertCreateCertificateContext(certEncodingType uint32, certEncoded *byte, encodedLen uint32) (context *CertContext, err error) [failretval==nil] = crypt32.CertCreateCertificateContext
  260. //sys CertFreeCertificateContext(ctx *CertContext) (err error) = crypt32.CertFreeCertificateContext
  261. //sys CertVerifyCertificateChainPolicy(policyOID uintptr, chain *CertChainContext, para *CertChainPolicyPara, status *CertChainPolicyStatus) (err error) = crypt32.CertVerifyCertificateChainPolicy
  262. //sys CertGetNameString(certContext *CertContext, nameType uint32, flags uint32, typePara unsafe.Pointer, name *uint16, size uint32) (chars uint32) = crypt32.CertGetNameStringW
  263. //sys CertFindExtension(objId *byte, countExtensions uint32, extensions *CertExtension) (ret *CertExtension) = crypt32.CertFindExtension
  264. //sys CertFindCertificateInStore(store Handle, certEncodingType uint32, findFlags uint32, findType uint32, findPara unsafe.Pointer, prevCertContext *CertContext) (cert *CertContext, err error) [failretval==nil] = crypt32.CertFindCertificateInStore
  265. //sys CertFindChainInStore(store Handle, certEncodingType uint32, findFlags uint32, findType uint32, findPara unsafe.Pointer, prevChainContext *CertChainContext) (certchain *CertChainContext, err error) [failretval==nil] = crypt32.CertFindChainInStore
  266. //sys CryptAcquireCertificatePrivateKey(cert *CertContext, flags uint32, parameters unsafe.Pointer, cryptProvOrNCryptKey *Handle, keySpec *uint32, callerFreeProvOrNCryptKey *bool) (err error) = crypt32.CryptAcquireCertificatePrivateKey
  267. //sys CryptQueryObject(objectType uint32, object unsafe.Pointer, expectedContentTypeFlags uint32, expectedFormatTypeFlags uint32, flags uint32, msgAndCertEncodingType *uint32, contentType *uint32, formatType *uint32, certStore *Handle, msg *Handle, context *unsafe.Pointer) (err error) = crypt32.CryptQueryObject
  268. //sys CryptDecodeObject(encodingType uint32, structType *byte, encodedBytes *byte, lenEncodedBytes uint32, flags uint32, decoded unsafe.Pointer, decodedLen *uint32) (err error) = crypt32.CryptDecodeObject
  269. //sys CryptProtectData(dataIn *DataBlob, name *uint16, optionalEntropy *DataBlob, reserved uintptr, promptStruct *CryptProtectPromptStruct, flags uint32, dataOut *DataBlob) (err error) = crypt32.CryptProtectData
  270. //sys CryptUnprotectData(dataIn *DataBlob, name **uint16, optionalEntropy *DataBlob, reserved uintptr, promptStruct *CryptProtectPromptStruct, flags uint32, dataOut *DataBlob) (err error) = crypt32.CryptUnprotectData
  271. //sys WinVerifyTrustEx(hwnd HWND, actionId *GUID, data *WinTrustData) (ret error) = wintrust.WinVerifyTrustEx
  272. //sys RegOpenKeyEx(key Handle, subkey *uint16, options uint32, desiredAccess uint32, result *Handle) (regerrno error) = advapi32.RegOpenKeyExW
  273. //sys RegCloseKey(key Handle) (regerrno error) = advapi32.RegCloseKey
  274. //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
  275. //sys RegEnumKeyEx(key Handle, index uint32, name *uint16, nameLen *uint32, reserved *uint32, class *uint16, classLen *uint32, lastWriteTime *Filetime) (regerrno error) = advapi32.RegEnumKeyExW
  276. //sys RegQueryValueEx(key Handle, name *uint16, reserved *uint32, valtype *uint32, buf *byte, buflen *uint32) (regerrno error) = advapi32.RegQueryValueExW
  277. //sys RegNotifyChangeKeyValue(key Handle, watchSubtree bool, notifyFilter uint32, event Handle, asynchronous bool) (regerrno error) = advapi32.RegNotifyChangeKeyValue
  278. //sys GetCurrentProcessId() (pid uint32) = kernel32.GetCurrentProcessId
  279. //sys ProcessIdToSessionId(pid uint32, sessionid *uint32) (err error) = kernel32.ProcessIdToSessionId
  280. //sys ClosePseudoConsole(console Handle) = kernel32.ClosePseudoConsole
  281. //sys createPseudoConsole(size uint32, in Handle, out Handle, flags uint32, pconsole *Handle) (hr error) = kernel32.CreatePseudoConsole
  282. //sys GetConsoleMode(console Handle, mode *uint32) (err error) = kernel32.GetConsoleMode
  283. //sys SetConsoleMode(console Handle, mode uint32) (err error) = kernel32.SetConsoleMode
  284. //sys GetConsoleScreenBufferInfo(console Handle, info *ConsoleScreenBufferInfo) (err error) = kernel32.GetConsoleScreenBufferInfo
  285. //sys setConsoleCursorPosition(console Handle, position uint32) (err error) = kernel32.SetConsoleCursorPosition
  286. //sys WriteConsole(console Handle, buf *uint16, towrite uint32, written *uint32, reserved *byte) (err error) = kernel32.WriteConsoleW
  287. //sys ReadConsole(console Handle, buf *uint16, toread uint32, read *uint32, inputControl *byte) (err error) = kernel32.ReadConsoleW
  288. //sys resizePseudoConsole(pconsole Handle, size uint32) (hr error) = kernel32.ResizePseudoConsole
  289. //sys CreateToolhelp32Snapshot(flags uint32, processId uint32) (handle Handle, err error) [failretval==InvalidHandle] = kernel32.CreateToolhelp32Snapshot
  290. //sys Module32First(snapshot Handle, moduleEntry *ModuleEntry32) (err error) = kernel32.Module32FirstW
  291. //sys Module32Next(snapshot Handle, moduleEntry *ModuleEntry32) (err error) = kernel32.Module32NextW
  292. //sys Process32First(snapshot Handle, procEntry *ProcessEntry32) (err error) = kernel32.Process32FirstW
  293. //sys Process32Next(snapshot Handle, procEntry *ProcessEntry32) (err error) = kernel32.Process32NextW
  294. //sys Thread32First(snapshot Handle, threadEntry *ThreadEntry32) (err error)
  295. //sys Thread32Next(snapshot Handle, threadEntry *ThreadEntry32) (err error)
  296. //sys DeviceIoControl(handle Handle, ioControlCode uint32, inBuffer *byte, inBufferSize uint32, outBuffer *byte, outBufferSize uint32, bytesReturned *uint32, overlapped *Overlapped) (err error)
  297. // This function returns 1 byte BOOLEAN rather than the 4 byte BOOL.
  298. //sys CreateSymbolicLink(symlinkfilename *uint16, targetfilename *uint16, flags uint32) (err error) [failretval&0xff==0] = CreateSymbolicLinkW
  299. //sys CreateHardLink(filename *uint16, existingfilename *uint16, reserved uintptr) (err error) [failretval&0xff==0] = CreateHardLinkW
  300. //sys GetCurrentThreadId() (id uint32)
  301. //sys CreateEvent(eventAttrs *SecurityAttributes, manualReset uint32, initialState uint32, name *uint16) (handle Handle, err error) [failretval == 0 || e1 == ERROR_ALREADY_EXISTS] = kernel32.CreateEventW
  302. //sys CreateEventEx(eventAttrs *SecurityAttributes, name *uint16, flags uint32, desiredAccess uint32) (handle Handle, err error) [failretval == 0 || e1 == ERROR_ALREADY_EXISTS] = kernel32.CreateEventExW
  303. //sys OpenEvent(desiredAccess uint32, inheritHandle bool, name *uint16) (handle Handle, err error) = kernel32.OpenEventW
  304. //sys SetEvent(event Handle) (err error) = kernel32.SetEvent
  305. //sys ResetEvent(event Handle) (err error) = kernel32.ResetEvent
  306. //sys PulseEvent(event Handle) (err error) = kernel32.PulseEvent
  307. //sys CreateMutex(mutexAttrs *SecurityAttributes, initialOwner bool, name *uint16) (handle Handle, err error) [failretval == 0 || e1 == ERROR_ALREADY_EXISTS] = kernel32.CreateMutexW
  308. //sys CreateMutexEx(mutexAttrs *SecurityAttributes, name *uint16, flags uint32, desiredAccess uint32) (handle Handle, err error) [failretval == 0 || e1 == ERROR_ALREADY_EXISTS] = kernel32.CreateMutexExW
  309. //sys OpenMutex(desiredAccess uint32, inheritHandle bool, name *uint16) (handle Handle, err error) = kernel32.OpenMutexW
  310. //sys ReleaseMutex(mutex Handle) (err error) = kernel32.ReleaseMutex
  311. //sys SleepEx(milliseconds uint32, alertable bool) (ret uint32) = kernel32.SleepEx
  312. //sys CreateJobObject(jobAttr *SecurityAttributes, name *uint16) (handle Handle, err error) = kernel32.CreateJobObjectW
  313. //sys AssignProcessToJobObject(job Handle, process Handle) (err error) = kernel32.AssignProcessToJobObject
  314. //sys TerminateJobObject(job Handle, exitCode uint32) (err error) = kernel32.TerminateJobObject
  315. //sys SetErrorMode(mode uint32) (ret uint32) = kernel32.SetErrorMode
  316. //sys ResumeThread(thread Handle) (ret uint32, err error) [failretval==0xffffffff] = kernel32.ResumeThread
  317. //sys SetPriorityClass(process Handle, priorityClass uint32) (err error) = kernel32.SetPriorityClass
  318. //sys GetPriorityClass(process Handle) (ret uint32, err error) = kernel32.GetPriorityClass
  319. //sys QueryInformationJobObject(job Handle, JobObjectInformationClass int32, JobObjectInformation uintptr, JobObjectInformationLength uint32, retlen *uint32) (err error) = kernel32.QueryInformationJobObject
  320. //sys SetInformationJobObject(job Handle, JobObjectInformationClass uint32, JobObjectInformation uintptr, JobObjectInformationLength uint32) (ret int, err error)
  321. //sys GenerateConsoleCtrlEvent(ctrlEvent uint32, processGroupID uint32) (err error)
  322. //sys GetProcessId(process Handle) (id uint32, err error)
  323. //sys QueryFullProcessImageName(proc Handle, flags uint32, exeName *uint16, size *uint32) (err error) = kernel32.QueryFullProcessImageNameW
  324. //sys OpenThread(desiredAccess uint32, inheritHandle bool, threadId uint32) (handle Handle, err error)
  325. //sys SetProcessPriorityBoost(process Handle, disable bool) (err error) = kernel32.SetProcessPriorityBoost
  326. //sys GetProcessWorkingSetSizeEx(hProcess Handle, lpMinimumWorkingSetSize *uintptr, lpMaximumWorkingSetSize *uintptr, flags *uint32)
  327. //sys SetProcessWorkingSetSizeEx(hProcess Handle, dwMinimumWorkingSetSize uintptr, dwMaximumWorkingSetSize uintptr, flags uint32) (err error)
  328. //sys GetCommTimeouts(handle Handle, timeouts *CommTimeouts) (err error)
  329. //sys SetCommTimeouts(handle Handle, timeouts *CommTimeouts) (err error)
  330. //sys GetActiveProcessorCount(groupNumber uint16) (ret uint32)
  331. //sys GetMaximumProcessorCount(groupNumber uint16) (ret uint32)
  332. //sys EnumWindows(enumFunc uintptr, param unsafe.Pointer) (err error) = user32.EnumWindows
  333. //sys EnumChildWindows(hwnd HWND, enumFunc uintptr, param unsafe.Pointer) = user32.EnumChildWindows
  334. //sys GetClassName(hwnd HWND, className *uint16, maxCount int32) (copied int32, err error) = user32.GetClassNameW
  335. //sys GetDesktopWindow() (hwnd HWND) = user32.GetDesktopWindow
  336. //sys GetForegroundWindow() (hwnd HWND) = user32.GetForegroundWindow
  337. //sys IsWindow(hwnd HWND) (isWindow bool) = user32.IsWindow
  338. //sys IsWindowUnicode(hwnd HWND) (isUnicode bool) = user32.IsWindowUnicode
  339. //sys IsWindowVisible(hwnd HWND) (isVisible bool) = user32.IsWindowVisible
  340. //sys GetGUIThreadInfo(thread uint32, info *GUIThreadInfo) (err error) = user32.GetGUIThreadInfo
  341. //sys GetLargePageMinimum() (size uintptr)
  342. // Volume Management Functions
  343. //sys DefineDosDevice(flags uint32, deviceName *uint16, targetPath *uint16) (err error) = DefineDosDeviceW
  344. //sys DeleteVolumeMountPoint(volumeMountPoint *uint16) (err error) = DeleteVolumeMountPointW
  345. //sys FindFirstVolume(volumeName *uint16, bufferLength uint32) (handle Handle, err error) [failretval==InvalidHandle] = FindFirstVolumeW
  346. //sys FindFirstVolumeMountPoint(rootPathName *uint16, volumeMountPoint *uint16, bufferLength uint32) (handle Handle, err error) [failretval==InvalidHandle] = FindFirstVolumeMountPointW
  347. //sys FindNextVolume(findVolume Handle, volumeName *uint16, bufferLength uint32) (err error) = FindNextVolumeW
  348. //sys FindNextVolumeMountPoint(findVolumeMountPoint Handle, volumeMountPoint *uint16, bufferLength uint32) (err error) = FindNextVolumeMountPointW
  349. //sys FindVolumeClose(findVolume Handle) (err error)
  350. //sys FindVolumeMountPointClose(findVolumeMountPoint Handle) (err error)
  351. //sys GetDiskFreeSpaceEx(directoryName *uint16, freeBytesAvailableToCaller *uint64, totalNumberOfBytes *uint64, totalNumberOfFreeBytes *uint64) (err error) = GetDiskFreeSpaceExW
  352. //sys GetDriveType(rootPathName *uint16) (driveType uint32) = GetDriveTypeW
  353. //sys GetLogicalDrives() (drivesBitMask uint32, err error) [failretval==0]
  354. //sys GetLogicalDriveStrings(bufferLength uint32, buffer *uint16) (n uint32, err error) [failretval==0] = GetLogicalDriveStringsW
  355. //sys GetVolumeInformation(rootPathName *uint16, volumeNameBuffer *uint16, volumeNameSize uint32, volumeNameSerialNumber *uint32, maximumComponentLength *uint32, fileSystemFlags *uint32, fileSystemNameBuffer *uint16, fileSystemNameSize uint32) (err error) = GetVolumeInformationW
  356. //sys GetVolumeInformationByHandle(file Handle, volumeNameBuffer *uint16, volumeNameSize uint32, volumeNameSerialNumber *uint32, maximumComponentLength *uint32, fileSystemFlags *uint32, fileSystemNameBuffer *uint16, fileSystemNameSize uint32) (err error) = GetVolumeInformationByHandleW
  357. //sys GetVolumeNameForVolumeMountPoint(volumeMountPoint *uint16, volumeName *uint16, bufferlength uint32) (err error) = GetVolumeNameForVolumeMountPointW
  358. //sys GetVolumePathName(fileName *uint16, volumePathName *uint16, bufferLength uint32) (err error) = GetVolumePathNameW
  359. //sys GetVolumePathNamesForVolumeName(volumeName *uint16, volumePathNames *uint16, bufferLength uint32, returnLength *uint32) (err error) = GetVolumePathNamesForVolumeNameW
  360. //sys QueryDosDevice(deviceName *uint16, targetPath *uint16, max uint32) (n uint32, err error) [failretval==0] = QueryDosDeviceW
  361. //sys SetVolumeLabel(rootPathName *uint16, volumeName *uint16) (err error) = SetVolumeLabelW
  362. //sys SetVolumeMountPoint(volumeMountPoint *uint16, volumeName *uint16) (err error) = SetVolumeMountPointW
  363. //sys InitiateSystemShutdownEx(machineName *uint16, message *uint16, timeout uint32, forceAppsClosed bool, rebootAfterShutdown bool, reason uint32) (err error) = advapi32.InitiateSystemShutdownExW
  364. //sys SetProcessShutdownParameters(level uint32, flags uint32) (err error) = kernel32.SetProcessShutdownParameters
  365. //sys GetProcessShutdownParameters(level *uint32, flags *uint32) (err error) = kernel32.GetProcessShutdownParameters
  366. //sys clsidFromString(lpsz *uint16, pclsid *GUID) (ret error) = ole32.CLSIDFromString
  367. //sys stringFromGUID2(rguid *GUID, lpsz *uint16, cchMax int32) (chars int32) = ole32.StringFromGUID2
  368. //sys coCreateGuid(pguid *GUID) (ret error) = ole32.CoCreateGuid
  369. //sys CoTaskMemFree(address unsafe.Pointer) = ole32.CoTaskMemFree
  370. //sys CoInitializeEx(reserved uintptr, coInit uint32) (ret error) = ole32.CoInitializeEx
  371. //sys CoUninitialize() = ole32.CoUninitialize
  372. //sys CoGetObject(name *uint16, bindOpts *BIND_OPTS3, guid *GUID, functionTable **uintptr) (ret error) = ole32.CoGetObject
  373. //sys getProcessPreferredUILanguages(flags uint32, numLanguages *uint32, buf *uint16, bufSize *uint32) (err error) = kernel32.GetProcessPreferredUILanguages
  374. //sys getThreadPreferredUILanguages(flags uint32, numLanguages *uint32, buf *uint16, bufSize *uint32) (err error) = kernel32.GetThreadPreferredUILanguages
  375. //sys getUserPreferredUILanguages(flags uint32, numLanguages *uint32, buf *uint16, bufSize *uint32) (err error) = kernel32.GetUserPreferredUILanguages
  376. //sys getSystemPreferredUILanguages(flags uint32, numLanguages *uint32, buf *uint16, bufSize *uint32) (err error) = kernel32.GetSystemPreferredUILanguages
  377. //sys findResource(module Handle, name uintptr, resType uintptr) (resInfo Handle, err error) = kernel32.FindResourceW
  378. //sys SizeofResource(module Handle, resInfo Handle) (size uint32, err error) = kernel32.SizeofResource
  379. //sys LoadResource(module Handle, resInfo Handle) (resData Handle, err error) = kernel32.LoadResource
  380. //sys LockResource(resData Handle) (addr uintptr, err error) = kernel32.LockResource
  381. // Version APIs
  382. //sys GetFileVersionInfoSize(filename string, zeroHandle *Handle) (bufSize uint32, err error) = version.GetFileVersionInfoSizeW
  383. //sys GetFileVersionInfo(filename string, handle uint32, bufSize uint32, buffer unsafe.Pointer) (err error) = version.GetFileVersionInfoW
  384. //sys VerQueryValue(block unsafe.Pointer, subBlock string, pointerToBufferPointer unsafe.Pointer, bufSize *uint32) (err error) = version.VerQueryValueW
  385. // Process Status API (PSAPI)
  386. //sys enumProcesses(processIds *uint32, nSize uint32, bytesReturned *uint32) (err error) = psapi.EnumProcesses
  387. //sys EnumProcessModules(process Handle, module *Handle, cb uint32, cbNeeded *uint32) (err error) = psapi.EnumProcessModules
  388. //sys EnumProcessModulesEx(process Handle, module *Handle, cb uint32, cbNeeded *uint32, filterFlag uint32) (err error) = psapi.EnumProcessModulesEx
  389. //sys GetModuleInformation(process Handle, module Handle, modinfo *ModuleInfo, cb uint32) (err error) = psapi.GetModuleInformation
  390. //sys GetModuleFileNameEx(process Handle, module Handle, filename *uint16, size uint32) (err error) = psapi.GetModuleFileNameExW
  391. //sys GetModuleBaseName(process Handle, module Handle, baseName *uint16, size uint32) (err error) = psapi.GetModuleBaseNameW
  392. //sys QueryWorkingSetEx(process Handle, pv uintptr, cb uint32) (err error) = psapi.QueryWorkingSetEx
  393. // NT Native APIs
  394. //sys rtlNtStatusToDosErrorNoTeb(ntstatus NTStatus) (ret syscall.Errno) = ntdll.RtlNtStatusToDosErrorNoTeb
  395. //sys rtlGetVersion(info *OsVersionInfoEx) (ntstatus error) = ntdll.RtlGetVersion
  396. //sys rtlGetNtVersionNumbers(majorVersion *uint32, minorVersion *uint32, buildNumber *uint32) = ntdll.RtlGetNtVersionNumbers
  397. //sys RtlGetCurrentPeb() (peb *PEB) = ntdll.RtlGetCurrentPeb
  398. //sys RtlInitUnicodeString(destinationString *NTUnicodeString, sourceString *uint16) = ntdll.RtlInitUnicodeString
  399. //sys RtlInitString(destinationString *NTString, sourceString *byte) = ntdll.RtlInitString
  400. //sys NtCreateFile(handle *Handle, access uint32, oa *OBJECT_ATTRIBUTES, iosb *IO_STATUS_BLOCK, allocationSize *int64, attributes uint32, share uint32, disposition uint32, options uint32, eabuffer uintptr, ealength uint32) (ntstatus error) = ntdll.NtCreateFile
  401. //sys NtCreateNamedPipeFile(pipe *Handle, access uint32, oa *OBJECT_ATTRIBUTES, iosb *IO_STATUS_BLOCK, share uint32, disposition uint32, options uint32, typ uint32, readMode uint32, completionMode uint32, maxInstances uint32, inboundQuota uint32, outputQuota uint32, timeout *int64) (ntstatus error) = ntdll.NtCreateNamedPipeFile
  402. //sys NtSetInformationFile(handle Handle, iosb *IO_STATUS_BLOCK, inBuffer *byte, inBufferLen uint32, class uint32) (ntstatus error) = ntdll.NtSetInformationFile
  403. //sys RtlDosPathNameToNtPathName(dosName *uint16, ntName *NTUnicodeString, ntFileNamePart *uint16, relativeName *RTL_RELATIVE_NAME) (ntstatus error) = ntdll.RtlDosPathNameToNtPathName_U_WithStatus
  404. //sys RtlDosPathNameToRelativeNtPathName(dosName *uint16, ntName *NTUnicodeString, ntFileNamePart *uint16, relativeName *RTL_RELATIVE_NAME) (ntstatus error) = ntdll.RtlDosPathNameToRelativeNtPathName_U_WithStatus
  405. //sys RtlDefaultNpAcl(acl **ACL) (ntstatus error) = ntdll.RtlDefaultNpAcl
  406. //sys NtQueryInformationProcess(proc Handle, procInfoClass int32, procInfo unsafe.Pointer, procInfoLen uint32, retLen *uint32) (ntstatus error) = ntdll.NtQueryInformationProcess
  407. //sys NtSetInformationProcess(proc Handle, procInfoClass int32, procInfo unsafe.Pointer, procInfoLen uint32) (ntstatus error) = ntdll.NtSetInformationProcess
  408. //sys NtQuerySystemInformation(sysInfoClass int32, sysInfo unsafe.Pointer, sysInfoLen uint32, retLen *uint32) (ntstatus error) = ntdll.NtQuerySystemInformation
  409. //sys NtSetSystemInformation(sysInfoClass int32, sysInfo unsafe.Pointer, sysInfoLen uint32) (ntstatus error) = ntdll.NtSetSystemInformation
  410. //sys RtlAddFunctionTable(functionTable *RUNTIME_FUNCTION, entryCount uint32, baseAddress uintptr) (ret bool) = ntdll.RtlAddFunctionTable
  411. //sys RtlDeleteFunctionTable(functionTable *RUNTIME_FUNCTION) (ret bool) = ntdll.RtlDeleteFunctionTable
  412. // Desktop Window Manager API (Dwmapi)
  413. //sys DwmGetWindowAttribute(hwnd HWND, attribute uint32, value unsafe.Pointer, size uint32) (ret error) = dwmapi.DwmGetWindowAttribute
  414. //sys DwmSetWindowAttribute(hwnd HWND, attribute uint32, value unsafe.Pointer, size uint32) (ret error) = dwmapi.DwmSetWindowAttribute
  415. // Windows Multimedia API
  416. //sys TimeBeginPeriod (period uint32) (err error) [failretval != 0] = winmm.timeBeginPeriod
  417. //sys TimeEndPeriod (period uint32) (err error) [failretval != 0] = winmm.timeEndPeriod
  418. // syscall interface implementation for other packages
  419. // GetCurrentProcess returns the handle for the current process.
  420. // It is a pseudo handle that does not need to be closed.
  421. // The returned error is always nil.
  422. //
  423. // Deprecated: use CurrentProcess for the same Handle without the nil
  424. // error.
  425. func GetCurrentProcess() (Handle, error) {
  426. return CurrentProcess(), nil
  427. }
  428. // CurrentProcess returns the handle for the current process.
  429. // It is a pseudo handle that does not need to be closed.
  430. func CurrentProcess() Handle { return Handle(^uintptr(1 - 1)) }
  431. // GetCurrentThread returns the handle for the current thread.
  432. // It is a pseudo handle that does not need to be closed.
  433. // The returned error is always nil.
  434. //
  435. // Deprecated: use CurrentThread for the same Handle without the nil
  436. // error.
  437. func GetCurrentThread() (Handle, error) {
  438. return CurrentThread(), nil
  439. }
  440. // CurrentThread returns the handle for the current thread.
  441. // It is a pseudo handle that does not need to be closed.
  442. func CurrentThread() Handle { return Handle(^uintptr(2 - 1)) }
  443. // GetProcAddressByOrdinal retrieves the address of the exported
  444. // function from module by ordinal.
  445. func GetProcAddressByOrdinal(module Handle, ordinal uintptr) (proc uintptr, err error) {
  446. r0, _, e1 := syscall.Syscall(procGetProcAddress.Addr(), 2, uintptr(module), ordinal, 0)
  447. proc = uintptr(r0)
  448. if proc == 0 {
  449. err = errnoErr(e1)
  450. }
  451. return
  452. }
  453. func Exit(code int) { ExitProcess(uint32(code)) }
  454. func makeInheritSa() *SecurityAttributes {
  455. var sa SecurityAttributes
  456. sa.Length = uint32(unsafe.Sizeof(sa))
  457. sa.InheritHandle = 1
  458. return &sa
  459. }
  460. func Open(path string, mode int, perm uint32) (fd Handle, err error) {
  461. if len(path) == 0 {
  462. return InvalidHandle, ERROR_FILE_NOT_FOUND
  463. }
  464. pathp, err := UTF16PtrFromString(path)
  465. if err != nil {
  466. return InvalidHandle, err
  467. }
  468. var access uint32
  469. switch mode & (O_RDONLY | O_WRONLY | O_RDWR) {
  470. case O_RDONLY:
  471. access = GENERIC_READ
  472. case O_WRONLY:
  473. access = GENERIC_WRITE
  474. case O_RDWR:
  475. access = GENERIC_READ | GENERIC_WRITE
  476. }
  477. if mode&O_CREAT != 0 {
  478. access |= GENERIC_WRITE
  479. }
  480. if mode&O_APPEND != 0 {
  481. access &^= GENERIC_WRITE
  482. access |= FILE_APPEND_DATA
  483. }
  484. sharemode := uint32(FILE_SHARE_READ | FILE_SHARE_WRITE)
  485. var sa *SecurityAttributes
  486. if mode&O_CLOEXEC == 0 {
  487. sa = makeInheritSa()
  488. }
  489. var createmode uint32
  490. switch {
  491. case mode&(O_CREAT|O_EXCL) == (O_CREAT | O_EXCL):
  492. createmode = CREATE_NEW
  493. case mode&(O_CREAT|O_TRUNC) == (O_CREAT | O_TRUNC):
  494. createmode = CREATE_ALWAYS
  495. case mode&O_CREAT == O_CREAT:
  496. createmode = OPEN_ALWAYS
  497. case mode&O_TRUNC == O_TRUNC:
  498. createmode = TRUNCATE_EXISTING
  499. default:
  500. createmode = OPEN_EXISTING
  501. }
  502. var attrs uint32 = FILE_ATTRIBUTE_NORMAL
  503. if perm&S_IWRITE == 0 {
  504. attrs = FILE_ATTRIBUTE_READONLY
  505. }
  506. h, e := CreateFile(pathp, access, sharemode, sa, createmode, attrs, 0)
  507. return h, e
  508. }
  509. func Read(fd Handle, p []byte) (n int, err error) {
  510. var done uint32
  511. e := ReadFile(fd, p, &done, nil)
  512. if e != nil {
  513. if e == ERROR_BROKEN_PIPE {
  514. // NOTE(brainman): work around ERROR_BROKEN_PIPE is returned on reading EOF from stdin
  515. return 0, nil
  516. }
  517. return 0, e
  518. }
  519. return int(done), nil
  520. }
  521. func Write(fd Handle, p []byte) (n int, err error) {
  522. if raceenabled {
  523. raceReleaseMerge(unsafe.Pointer(&ioSync))
  524. }
  525. var done uint32
  526. e := WriteFile(fd, p, &done, nil)
  527. if e != nil {
  528. return 0, e
  529. }
  530. return int(done), nil
  531. }
  532. func ReadFile(fd Handle, p []byte, done *uint32, overlapped *Overlapped) error {
  533. err := readFile(fd, p, done, overlapped)
  534. if raceenabled {
  535. if *done > 0 {
  536. raceWriteRange(unsafe.Pointer(&p[0]), int(*done))
  537. }
  538. raceAcquire(unsafe.Pointer(&ioSync))
  539. }
  540. return err
  541. }
  542. func WriteFile(fd Handle, p []byte, done *uint32, overlapped *Overlapped) error {
  543. if raceenabled {
  544. raceReleaseMerge(unsafe.Pointer(&ioSync))
  545. }
  546. err := writeFile(fd, p, done, overlapped)
  547. if raceenabled && *done > 0 {
  548. raceReadRange(unsafe.Pointer(&p[0]), int(*done))
  549. }
  550. return err
  551. }
  552. var ioSync int64
  553. func Seek(fd Handle, offset int64, whence int) (newoffset int64, err error) {
  554. var w uint32
  555. switch whence {
  556. case 0:
  557. w = FILE_BEGIN
  558. case 1:
  559. w = FILE_CURRENT
  560. case 2:
  561. w = FILE_END
  562. }
  563. hi := int32(offset >> 32)
  564. lo := int32(offset)
  565. // use GetFileType to check pipe, pipe can't do seek
  566. ft, _ := GetFileType(fd)
  567. if ft == FILE_TYPE_PIPE {
  568. return 0, syscall.EPIPE
  569. }
  570. rlo, e := SetFilePointer(fd, lo, &hi, w)
  571. if e != nil {
  572. return 0, e
  573. }
  574. return int64(hi)<<32 + int64(rlo), nil
  575. }
  576. func Close(fd Handle) (err error) {
  577. return CloseHandle(fd)
  578. }
  579. var (
  580. Stdin = getStdHandle(STD_INPUT_HANDLE)
  581. Stdout = getStdHandle(STD_OUTPUT_HANDLE)
  582. Stderr = getStdHandle(STD_ERROR_HANDLE)
  583. )
  584. func getStdHandle(stdhandle uint32) (fd Handle) {
  585. r, _ := GetStdHandle(stdhandle)
  586. return r
  587. }
  588. const ImplementsGetwd = true
  589. func Getwd() (wd string, err error) {
  590. b := make([]uint16, 300)
  591. n, e := GetCurrentDirectory(uint32(len(b)), &b[0])
  592. if e != nil {
  593. return "", e
  594. }
  595. return string(utf16.Decode(b[0:n])), nil
  596. }
  597. func Chdir(path string) (err error) {
  598. pathp, err := UTF16PtrFromString(path)
  599. if err != nil {
  600. return err
  601. }
  602. return SetCurrentDirectory(pathp)
  603. }
  604. func Mkdir(path string, mode uint32) (err error) {
  605. pathp, err := UTF16PtrFromString(path)
  606. if err != nil {
  607. return err
  608. }
  609. return CreateDirectory(pathp, nil)
  610. }
  611. func Rmdir(path string) (err error) {
  612. pathp, err := UTF16PtrFromString(path)
  613. if err != nil {
  614. return err
  615. }
  616. return RemoveDirectory(pathp)
  617. }
  618. func Unlink(path string) (err error) {
  619. pathp, err := UTF16PtrFromString(path)
  620. if err != nil {
  621. return err
  622. }
  623. return DeleteFile(pathp)
  624. }
  625. func Rename(oldpath, newpath string) (err error) {
  626. from, err := UTF16PtrFromString(oldpath)
  627. if err != nil {
  628. return err
  629. }
  630. to, err := UTF16PtrFromString(newpath)
  631. if err != nil {
  632. return err
  633. }
  634. return MoveFileEx(from, to, MOVEFILE_REPLACE_EXISTING)
  635. }
  636. func ComputerName() (name string, err error) {
  637. var n uint32 = MAX_COMPUTERNAME_LENGTH + 1
  638. b := make([]uint16, n)
  639. e := GetComputerName(&b[0], &n)
  640. if e != nil {
  641. return "", e
  642. }
  643. return string(utf16.Decode(b[0:n])), nil
  644. }
  645. func DurationSinceBoot() time.Duration {
  646. return time.Duration(getTickCount64()) * time.Millisecond
  647. }
  648. func Ftruncate(fd Handle, length int64) (err error) {
  649. curoffset, e := Seek(fd, 0, 1)
  650. if e != nil {
  651. return e
  652. }
  653. defer Seek(fd, curoffset, 0)
  654. _, e = Seek(fd, length, 0)
  655. if e != nil {
  656. return e
  657. }
  658. e = SetEndOfFile(fd)
  659. if e != nil {
  660. return e
  661. }
  662. return nil
  663. }
  664. func Gettimeofday(tv *Timeval) (err error) {
  665. var ft Filetime
  666. GetSystemTimeAsFileTime(&ft)
  667. *tv = NsecToTimeval(ft.Nanoseconds())
  668. return nil
  669. }
  670. func Pipe(p []Handle) (err error) {
  671. if len(p) != 2 {
  672. return syscall.EINVAL
  673. }
  674. var r, w Handle
  675. e := CreatePipe(&r, &w, makeInheritSa(), 0)
  676. if e != nil {
  677. return e
  678. }
  679. p[0] = r
  680. p[1] = w
  681. return nil
  682. }
  683. func Utimes(path string, tv []Timeval) (err error) {
  684. if len(tv) != 2 {
  685. return syscall.EINVAL
  686. }
  687. pathp, e := UTF16PtrFromString(path)
  688. if e != nil {
  689. return e
  690. }
  691. h, e := CreateFile(pathp,
  692. FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, nil,
  693. OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0)
  694. if e != nil {
  695. return e
  696. }
  697. defer CloseHandle(h)
  698. a := NsecToFiletime(tv[0].Nanoseconds())
  699. w := NsecToFiletime(tv[1].Nanoseconds())
  700. return SetFileTime(h, nil, &a, &w)
  701. }
  702. func UtimesNano(path string, ts []Timespec) (err error) {
  703. if len(ts) != 2 {
  704. return syscall.EINVAL
  705. }
  706. pathp, e := UTF16PtrFromString(path)
  707. if e != nil {
  708. return e
  709. }
  710. h, e := CreateFile(pathp,
  711. FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, nil,
  712. OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0)
  713. if e != nil {
  714. return e
  715. }
  716. defer CloseHandle(h)
  717. a := NsecToFiletime(TimespecToNsec(ts[0]))
  718. w := NsecToFiletime(TimespecToNsec(ts[1]))
  719. return SetFileTime(h, nil, &a, &w)
  720. }
  721. func Fsync(fd Handle) (err error) {
  722. return FlushFileBuffers(fd)
  723. }
  724. func Chmod(path string, mode uint32) (err error) {
  725. p, e := UTF16PtrFromString(path)
  726. if e != nil {
  727. return e
  728. }
  729. attrs, e := GetFileAttributes(p)
  730. if e != nil {
  731. return e
  732. }
  733. if mode&S_IWRITE != 0 {
  734. attrs &^= FILE_ATTRIBUTE_READONLY
  735. } else {
  736. attrs |= FILE_ATTRIBUTE_READONLY
  737. }
  738. return SetFileAttributes(p, attrs)
  739. }
  740. func LoadGetSystemTimePreciseAsFileTime() error {
  741. return procGetSystemTimePreciseAsFileTime.Find()
  742. }
  743. func LoadCancelIoEx() error {
  744. return procCancelIoEx.Find()
  745. }
  746. func LoadSetFileCompletionNotificationModes() error {
  747. return procSetFileCompletionNotificationModes.Find()
  748. }
  749. func WaitForMultipleObjects(handles []Handle, waitAll bool, waitMilliseconds uint32) (event uint32, err error) {
  750. // Every other win32 array API takes arguments as "pointer, count", except for this function. So we
  751. // can't declare it as a usual [] type, because mksyscall will use the opposite order. We therefore
  752. // trivially stub this ourselves.
  753. var handlePtr *Handle
  754. if len(handles) > 0 {
  755. handlePtr = &handles[0]
  756. }
  757. return waitForMultipleObjects(uint32(len(handles)), uintptr(unsafe.Pointer(handlePtr)), waitAll, waitMilliseconds)
  758. }
  759. // net api calls
  760. const socket_error = uintptr(^uint32(0))
  761. //sys WSAStartup(verreq uint32, data *WSAData) (sockerr error) = ws2_32.WSAStartup
  762. //sys WSACleanup() (err error) [failretval==socket_error] = ws2_32.WSACleanup
  763. //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
  764. //sys WSALookupServiceBegin(querySet *WSAQUERYSET, flags uint32, handle *Handle) (err error) [failretval==socket_error] = ws2_32.WSALookupServiceBeginW
  765. //sys WSALookupServiceNext(handle Handle, flags uint32, size *int32, querySet *WSAQUERYSET) (err error) [failretval==socket_error] = ws2_32.WSALookupServiceNextW
  766. //sys WSALookupServiceEnd(handle Handle) (err error) [failretval==socket_error] = ws2_32.WSALookupServiceEnd
  767. //sys socket(af int32, typ int32, protocol int32) (handle Handle, err error) [failretval==InvalidHandle] = ws2_32.socket
  768. //sys sendto(s Handle, buf []byte, flags int32, to unsafe.Pointer, tolen int32) (err error) [failretval==socket_error] = ws2_32.sendto
  769. //sys recvfrom(s Handle, buf []byte, flags int32, from *RawSockaddrAny, fromlen *int32) (n int32, err error) [failretval==-1] = ws2_32.recvfrom
  770. //sys Setsockopt(s Handle, level int32, optname int32, optval *byte, optlen int32) (err error) [failretval==socket_error] = ws2_32.setsockopt
  771. //sys Getsockopt(s Handle, level int32, optname int32, optval *byte, optlen *int32) (err error) [failretval==socket_error] = ws2_32.getsockopt
  772. //sys bind(s Handle, name unsafe.Pointer, namelen int32) (err error) [failretval==socket_error] = ws2_32.bind
  773. //sys connect(s Handle, name unsafe.Pointer, namelen int32) (err error) [failretval==socket_error] = ws2_32.connect
  774. //sys getsockname(s Handle, rsa *RawSockaddrAny, addrlen *int32) (err error) [failretval==socket_error] = ws2_32.getsockname
  775. //sys getpeername(s Handle, rsa *RawSockaddrAny, addrlen *int32) (err error) [failretval==socket_error] = ws2_32.getpeername
  776. //sys listen(s Handle, backlog int32) (err error) [failretval==socket_error] = ws2_32.listen
  777. //sys shutdown(s Handle, how int32) (err error) [failretval==socket_error] = ws2_32.shutdown
  778. //sys Closesocket(s Handle) (err error) [failretval==socket_error] = ws2_32.closesocket
  779. //sys AcceptEx(ls Handle, as Handle, buf *byte, rxdatalen uint32, laddrlen uint32, raddrlen uint32, recvd *uint32, overlapped *Overlapped) (err error) = mswsock.AcceptEx
  780. //sys GetAcceptExSockaddrs(buf *byte, rxdatalen uint32, laddrlen uint32, raddrlen uint32, lrsa **RawSockaddrAny, lrsalen *int32, rrsa **RawSockaddrAny, rrsalen *int32) = mswsock.GetAcceptExSockaddrs
  781. //sys WSARecv(s Handle, bufs *WSABuf, bufcnt uint32, recvd *uint32, flags *uint32, overlapped *Overlapped, croutine *byte) (err error) [failretval==socket_error] = ws2_32.WSARecv
  782. //sys WSASend(s Handle, bufs *WSABuf, bufcnt uint32, sent *uint32, flags uint32, overlapped *Overlapped, croutine *byte) (err error) [failretval==socket_error] = ws2_32.WSASend
  783. //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
  784. //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
  785. //sys WSASocket(af int32, typ int32, protocol int32, protoInfo *WSAProtocolInfo, group uint32, flags uint32) (handle Handle, err error) [failretval==InvalidHandle] = ws2_32.WSASocketW
  786. //sys GetHostByName(name string) (h *Hostent, err error) [failretval==nil] = ws2_32.gethostbyname
  787. //sys GetServByName(name string, proto string) (s *Servent, err error) [failretval==nil] = ws2_32.getservbyname
  788. //sys Ntohs(netshort uint16) (u uint16) = ws2_32.ntohs
  789. //sys GetProtoByName(name string) (p *Protoent, err error) [failretval==nil] = ws2_32.getprotobyname
  790. //sys DnsQuery(name string, qtype uint16, options uint32, extra *byte, qrs **DNSRecord, pr *byte) (status error) = dnsapi.DnsQuery_W
  791. //sys DnsRecordListFree(rl *DNSRecord, freetype uint32) = dnsapi.DnsRecordListFree
  792. //sys DnsNameCompare(name1 *uint16, name2 *uint16) (same bool) = dnsapi.DnsNameCompare_W
  793. //sys GetAddrInfoW(nodename *uint16, servicename *uint16, hints *AddrinfoW, result **AddrinfoW) (sockerr error) = ws2_32.GetAddrInfoW
  794. //sys FreeAddrInfoW(addrinfo *AddrinfoW) = ws2_32.FreeAddrInfoW
  795. //sys GetIfEntry(pIfRow *MibIfRow) (errcode error) = iphlpapi.GetIfEntry
  796. //sys GetAdaptersInfo(ai *IpAdapterInfo, ol *uint32) (errcode error) = iphlpapi.GetAdaptersInfo
  797. //sys SetFileCompletionNotificationModes(handle Handle, flags uint8) (err error) = kernel32.SetFileCompletionNotificationModes
  798. //sys WSAEnumProtocols(protocols *int32, protocolBuffer *WSAProtocolInfo, bufferLength *uint32) (n int32, err error) [failretval==-1] = ws2_32.WSAEnumProtocolsW
  799. //sys WSAGetOverlappedResult(h Handle, o *Overlapped, bytes *uint32, wait bool, flags *uint32) (err error) = ws2_32.WSAGetOverlappedResult
  800. //sys GetAdaptersAddresses(family uint32, flags uint32, reserved uintptr, adapterAddresses *IpAdapterAddresses, sizePointer *uint32) (errcode error) = iphlpapi.GetAdaptersAddresses
  801. //sys GetACP() (acp uint32) = kernel32.GetACP
  802. //sys MultiByteToWideChar(codePage uint32, dwFlags uint32, str *byte, nstr int32, wchar *uint16, nwchar int32) (nwrite int32, err error) = kernel32.MultiByteToWideChar
  803. //sys getBestInterfaceEx(sockaddr unsafe.Pointer, pdwBestIfIndex *uint32) (errcode error) = iphlpapi.GetBestInterfaceEx
  804. // For testing: clients can set this flag to force
  805. // creation of IPv6 sockets to return EAFNOSUPPORT.
  806. var SocketDisableIPv6 bool
  807. type RawSockaddrInet4 struct {
  808. Family uint16
  809. Port uint16
  810. Addr [4]byte /* in_addr */
  811. Zero [8]uint8
  812. }
  813. type RawSockaddrInet6 struct {
  814. Family uint16
  815. Port uint16
  816. Flowinfo uint32
  817. Addr [16]byte /* in6_addr */
  818. Scope_id uint32
  819. }
  820. type RawSockaddr struct {
  821. Family uint16
  822. Data [14]int8
  823. }
  824. type RawSockaddrAny struct {
  825. Addr RawSockaddr
  826. Pad [100]int8
  827. }
  828. type Sockaddr interface {
  829. sockaddr() (ptr unsafe.Pointer, len int32, err error) // lowercase; only we can define Sockaddrs
  830. }
  831. type SockaddrInet4 struct {
  832. Port int
  833. Addr [4]byte
  834. raw RawSockaddrInet4
  835. }
  836. func (sa *SockaddrInet4) sockaddr() (unsafe.Pointer, int32, error) {
  837. if sa.Port < 0 || sa.Port > 0xFFFF {
  838. return nil, 0, syscall.EINVAL
  839. }
  840. sa.raw.Family = AF_INET
  841. p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port))
  842. p[0] = byte(sa.Port >> 8)
  843. p[1] = byte(sa.Port)
  844. sa.raw.Addr = sa.Addr
  845. return unsafe.Pointer(&sa.raw), int32(unsafe.Sizeof(sa.raw)), nil
  846. }
  847. type SockaddrInet6 struct {
  848. Port int
  849. ZoneId uint32
  850. Addr [16]byte
  851. raw RawSockaddrInet6
  852. }
  853. func (sa *SockaddrInet6) sockaddr() (unsafe.Pointer, int32, error) {
  854. if sa.Port < 0 || sa.Port > 0xFFFF {
  855. return nil, 0, syscall.EINVAL
  856. }
  857. sa.raw.Family = AF_INET6
  858. p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port))
  859. p[0] = byte(sa.Port >> 8)
  860. p[1] = byte(sa.Port)
  861. sa.raw.Scope_id = sa.ZoneId
  862. sa.raw.Addr = sa.Addr
  863. return unsafe.Pointer(&sa.raw), int32(unsafe.Sizeof(sa.raw)), nil
  864. }
  865. type RawSockaddrUnix struct {
  866. Family uint16
  867. Path [UNIX_PATH_MAX]int8
  868. }
  869. type SockaddrUnix struct {
  870. Name string
  871. raw RawSockaddrUnix
  872. }
  873. func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, int32, error) {
  874. name := sa.Name
  875. n := len(name)
  876. if n > len(sa.raw.Path) {
  877. return nil, 0, syscall.EINVAL
  878. }
  879. if n == len(sa.raw.Path) && name[0] != '@' {
  880. return nil, 0, syscall.EINVAL
  881. }
  882. sa.raw.Family = AF_UNIX
  883. for i := 0; i < n; i++ {
  884. sa.raw.Path[i] = int8(name[i])
  885. }
  886. // length is family (uint16), name, NUL.
  887. sl := int32(2)
  888. if n > 0 {
  889. sl += int32(n) + 1
  890. }
  891. if sa.raw.Path[0] == '@' || (sa.raw.Path[0] == 0 && sl > 3) {
  892. // Check sl > 3 so we don't change unnamed socket behavior.
  893. sa.raw.Path[0] = 0
  894. // Don't count trailing NUL for abstract address.
  895. sl--
  896. }
  897. return unsafe.Pointer(&sa.raw), sl, nil
  898. }
  899. type RawSockaddrBth struct {
  900. AddressFamily [2]byte
  901. BtAddr [8]byte
  902. ServiceClassId [16]byte
  903. Port [4]byte
  904. }
  905. type SockaddrBth struct {
  906. BtAddr uint64
  907. ServiceClassId GUID
  908. Port uint32
  909. raw RawSockaddrBth
  910. }
  911. func (sa *SockaddrBth) sockaddr() (unsafe.Pointer, int32, error) {
  912. family := AF_BTH
  913. sa.raw = RawSockaddrBth{
  914. AddressFamily: *(*[2]byte)(unsafe.Pointer(&family)),
  915. BtAddr: *(*[8]byte)(unsafe.Pointer(&sa.BtAddr)),
  916. Port: *(*[4]byte)(unsafe.Pointer(&sa.Port)),
  917. ServiceClassId: *(*[16]byte)(unsafe.Pointer(&sa.ServiceClassId)),
  918. }
  919. return unsafe.Pointer(&sa.raw), int32(unsafe.Sizeof(sa.raw)), nil
  920. }
  921. func (rsa *RawSockaddrAny) Sockaddr() (Sockaddr, error) {
  922. switch rsa.Addr.Family {
  923. case AF_UNIX:
  924. pp := (*RawSockaddrUnix)(unsafe.Pointer(rsa))
  925. sa := new(SockaddrUnix)
  926. if pp.Path[0] == 0 {
  927. // "Abstract" Unix domain socket.
  928. // Rewrite leading NUL as @ for textual display.
  929. // (This is the standard convention.)
  930. // Not friendly to overwrite in place,
  931. // but the callers below don't care.
  932. pp.Path[0] = '@'
  933. }
  934. // Assume path ends at NUL.
  935. // This is not technically the Linux semantics for
  936. // abstract Unix domain sockets--they are supposed
  937. // to be uninterpreted fixed-size binary blobs--but
  938. // everyone uses this convention.
  939. n := 0
  940. for n < len(pp.Path) && pp.Path[n] != 0 {
  941. n++
  942. }
  943. sa.Name = string(unsafe.Slice((*byte)(unsafe.Pointer(&pp.Path[0])), n))
  944. return sa, nil
  945. case AF_INET:
  946. pp := (*RawSockaddrInet4)(unsafe.Pointer(rsa))
  947. sa := new(SockaddrInet4)
  948. p := (*[2]byte)(unsafe.Pointer(&pp.Port))
  949. sa.Port = int(p[0])<<8 + int(p[1])
  950. sa.Addr = pp.Addr
  951. return sa, nil
  952. case AF_INET6:
  953. pp := (*RawSockaddrInet6)(unsafe.Pointer(rsa))
  954. sa := new(SockaddrInet6)
  955. p := (*[2]byte)(unsafe.Pointer(&pp.Port))
  956. sa.Port = int(p[0])<<8 + int(p[1])
  957. sa.ZoneId = pp.Scope_id
  958. sa.Addr = pp.Addr
  959. return sa, nil
  960. }
  961. return nil, syscall.EAFNOSUPPORT
  962. }
  963. func Socket(domain, typ, proto int) (fd Handle, err error) {
  964. if domain == AF_INET6 && SocketDisableIPv6 {
  965. return InvalidHandle, syscall.EAFNOSUPPORT
  966. }
  967. return socket(int32(domain), int32(typ), int32(proto))
  968. }
  969. func SetsockoptInt(fd Handle, level, opt int, value int) (err error) {
  970. v := int32(value)
  971. return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(&v)), int32(unsafe.Sizeof(v)))
  972. }
  973. func Bind(fd Handle, sa Sockaddr) (err error) {
  974. ptr, n, err := sa.sockaddr()
  975. if err != nil {
  976. return err
  977. }
  978. return bind(fd, ptr, n)
  979. }
  980. func Connect(fd Handle, sa Sockaddr) (err error) {
  981. ptr, n, err := sa.sockaddr()
  982. if err != nil {
  983. return err
  984. }
  985. return connect(fd, ptr, n)
  986. }
  987. func GetBestInterfaceEx(sa Sockaddr, pdwBestIfIndex *uint32) (err error) {
  988. ptr, _, err := sa.sockaddr()
  989. if err != nil {
  990. return err
  991. }
  992. return getBestInterfaceEx(ptr, pdwBestIfIndex)
  993. }
  994. func Getsockname(fd Handle) (sa Sockaddr, err error) {
  995. var rsa RawSockaddrAny
  996. l := int32(unsafe.Sizeof(rsa))
  997. if err = getsockname(fd, &rsa, &l); err != nil {
  998. return
  999. }
  1000. return rsa.Sockaddr()
  1001. }
  1002. func Getpeername(fd Handle) (sa Sockaddr, err error) {
  1003. var rsa RawSockaddrAny
  1004. l := int32(unsafe.Sizeof(rsa))
  1005. if err = getpeername(fd, &rsa, &l); err != nil {
  1006. return
  1007. }
  1008. return rsa.Sockaddr()
  1009. }
  1010. func Listen(s Handle, n int) (err error) {
  1011. return listen(s, int32(n))
  1012. }
  1013. func Shutdown(fd Handle, how int) (err error) {
  1014. return shutdown(fd, int32(how))
  1015. }
  1016. func WSASendto(s Handle, bufs *WSABuf, bufcnt uint32, sent *uint32, flags uint32, to Sockaddr, overlapped *Overlapped, croutine *byte) (err error) {
  1017. var rsa unsafe.Pointer
  1018. var l int32
  1019. if to != nil {
  1020. rsa, l, err = to.sockaddr()
  1021. if err != nil {
  1022. return err
  1023. }
  1024. }
  1025. return WSASendTo(s, bufs, bufcnt, sent, flags, (*RawSockaddrAny)(unsafe.Pointer(rsa)), l, overlapped, croutine)
  1026. }
  1027. func LoadGetAddrInfo() error {
  1028. return procGetAddrInfoW.Find()
  1029. }
  1030. var connectExFunc struct {
  1031. once sync.Once
  1032. addr uintptr
  1033. err error
  1034. }
  1035. func LoadConnectEx() error {
  1036. connectExFunc.once.Do(func() {
  1037. var s Handle
  1038. s, connectExFunc.err = Socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)
  1039. if connectExFunc.err != nil {
  1040. return
  1041. }
  1042. defer CloseHandle(s)
  1043. var n uint32
  1044. connectExFunc.err = WSAIoctl(s,
  1045. SIO_GET_EXTENSION_FUNCTION_POINTER,
  1046. (*byte)(unsafe.Pointer(&WSAID_CONNECTEX)),
  1047. uint32(unsafe.Sizeof(WSAID_CONNECTEX)),
  1048. (*byte)(unsafe.Pointer(&connectExFunc.addr)),
  1049. uint32(unsafe.Sizeof(connectExFunc.addr)),
  1050. &n, nil, 0)
  1051. })
  1052. return connectExFunc.err
  1053. }
  1054. func connectEx(s Handle, name unsafe.Pointer, namelen int32, sendBuf *byte, sendDataLen uint32, bytesSent *uint32, overlapped *Overlapped) (err error) {
  1055. 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)
  1056. if r1 == 0 {
  1057. if e1 != 0 {
  1058. err = error(e1)
  1059. } else {
  1060. err = syscall.EINVAL
  1061. }
  1062. }
  1063. return
  1064. }
  1065. func ConnectEx(fd Handle, sa Sockaddr, sendBuf *byte, sendDataLen uint32, bytesSent *uint32, overlapped *Overlapped) error {
  1066. err := LoadConnectEx()
  1067. if err != nil {
  1068. return errorspkg.New("failed to find ConnectEx: " + err.Error())
  1069. }
  1070. ptr, n, err := sa.sockaddr()
  1071. if err != nil {
  1072. return err
  1073. }
  1074. return connectEx(fd, ptr, n, sendBuf, sendDataLen, bytesSent, overlapped)
  1075. }
  1076. var sendRecvMsgFunc struct {
  1077. once sync.Once
  1078. sendAddr uintptr
  1079. recvAddr uintptr
  1080. err error
  1081. }
  1082. func loadWSASendRecvMsg() error {
  1083. sendRecvMsgFunc.once.Do(func() {
  1084. var s Handle
  1085. s, sendRecvMsgFunc.err = Socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)
  1086. if sendRecvMsgFunc.err != nil {
  1087. return
  1088. }
  1089. defer CloseHandle(s)
  1090. var n uint32
  1091. sendRecvMsgFunc.err = WSAIoctl(s,
  1092. SIO_GET_EXTENSION_FUNCTION_POINTER,
  1093. (*byte)(unsafe.Pointer(&WSAID_WSARECVMSG)),
  1094. uint32(unsafe.Sizeof(WSAID_WSARECVMSG)),
  1095. (*byte)(unsafe.Pointer(&sendRecvMsgFunc.recvAddr)),
  1096. uint32(unsafe.Sizeof(sendRecvMsgFunc.recvAddr)),
  1097. &n, nil, 0)
  1098. if sendRecvMsgFunc.err != nil {
  1099. return
  1100. }
  1101. sendRecvMsgFunc.err = WSAIoctl(s,
  1102. SIO_GET_EXTENSION_FUNCTION_POINTER,
  1103. (*byte)(unsafe.Pointer(&WSAID_WSASENDMSG)),
  1104. uint32(unsafe.Sizeof(WSAID_WSASENDMSG)),
  1105. (*byte)(unsafe.Pointer(&sendRecvMsgFunc.sendAddr)),
  1106. uint32(unsafe.Sizeof(sendRecvMsgFunc.sendAddr)),
  1107. &n, nil, 0)
  1108. })
  1109. return sendRecvMsgFunc.err
  1110. }
  1111. func WSASendMsg(fd Handle, msg *WSAMsg, flags uint32, bytesSent *uint32, overlapped *Overlapped, croutine *byte) error {
  1112. err := loadWSASendRecvMsg()
  1113. if err != nil {
  1114. return err
  1115. }
  1116. 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)))
  1117. if r1 == socket_error {
  1118. err = errnoErr(e1)
  1119. }
  1120. return err
  1121. }
  1122. func WSARecvMsg(fd Handle, msg *WSAMsg, bytesReceived *uint32, overlapped *Overlapped, croutine *byte) error {
  1123. err := loadWSASendRecvMsg()
  1124. if err != nil {
  1125. return err
  1126. }
  1127. 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)
  1128. if r1 == socket_error {
  1129. err = errnoErr(e1)
  1130. }
  1131. return err
  1132. }
  1133. // Invented structures to support what package os expects.
  1134. type Rusage struct {
  1135. CreationTime Filetime
  1136. ExitTime Filetime
  1137. KernelTime Filetime
  1138. UserTime Filetime
  1139. }
  1140. type WaitStatus struct {
  1141. ExitCode uint32
  1142. }
  1143. func (w WaitStatus) Exited() bool { return true }
  1144. func (w WaitStatus) ExitStatus() int { return int(w.ExitCode) }
  1145. func (w WaitStatus) Signal() Signal { return -1 }
  1146. func (w WaitStatus) CoreDump() bool { return false }
  1147. func (w WaitStatus) Stopped() bool { return false }
  1148. func (w WaitStatus) Continued() bool { return false }
  1149. func (w WaitStatus) StopSignal() Signal { return -1 }
  1150. func (w WaitStatus) Signaled() bool { return false }
  1151. func (w WaitStatus) TrapCause() int { return -1 }
  1152. // Timespec is an invented structure on Windows, but here for
  1153. // consistency with the corresponding package for other operating systems.
  1154. type Timespec struct {
  1155. Sec int64
  1156. Nsec int64
  1157. }
  1158. func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) }
  1159. func NsecToTimespec(nsec int64) (ts Timespec) {
  1160. ts.Sec = nsec / 1e9
  1161. ts.Nsec = nsec % 1e9
  1162. return
  1163. }
  1164. // TODO(brainman): fix all needed for net
  1165. func Accept(fd Handle) (nfd Handle, sa Sockaddr, err error) { return 0, nil, syscall.EWINDOWS }
  1166. func Recvfrom(fd Handle, p []byte, flags int) (n int, from Sockaddr, err error) {
  1167. var rsa RawSockaddrAny
  1168. l := int32(unsafe.Sizeof(rsa))
  1169. n32, err := recvfrom(fd, p, int32(flags), &rsa, &l)
  1170. n = int(n32)
  1171. if err != nil {
  1172. return
  1173. }
  1174. from, err = rsa.Sockaddr()
  1175. return
  1176. }
  1177. func Sendto(fd Handle, p []byte, flags int, to Sockaddr) (err error) {
  1178. ptr, l, err := to.sockaddr()
  1179. if err != nil {
  1180. return err
  1181. }
  1182. return sendto(fd, p, int32(flags), ptr, l)
  1183. }
  1184. func SetsockoptTimeval(fd Handle, level, opt int, tv *Timeval) (err error) { return syscall.EWINDOWS }
  1185. // The Linger struct is wrong but we only noticed after Go 1.
  1186. // sysLinger is the real system call structure.
  1187. // BUG(brainman): The definition of Linger is not appropriate for direct use
  1188. // with Setsockopt and Getsockopt.
  1189. // Use SetsockoptLinger instead.
  1190. type Linger struct {
  1191. Onoff int32
  1192. Linger int32
  1193. }
  1194. type sysLinger struct {
  1195. Onoff uint16
  1196. Linger uint16
  1197. }
  1198. type IPMreq struct {
  1199. Multiaddr [4]byte /* in_addr */
  1200. Interface [4]byte /* in_addr */
  1201. }
  1202. type IPv6Mreq struct {
  1203. Multiaddr [16]byte /* in6_addr */
  1204. Interface uint32
  1205. }
  1206. func GetsockoptInt(fd Handle, level, opt int) (int, error) {
  1207. v := int32(0)
  1208. l := int32(unsafe.Sizeof(v))
  1209. err := Getsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(&v)), &l)
  1210. return int(v), err
  1211. }
  1212. func SetsockoptLinger(fd Handle, level, opt int, l *Linger) (err error) {
  1213. sys := sysLinger{Onoff: uint16(l.Onoff), Linger: uint16(l.Linger)}
  1214. return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(&sys)), int32(unsafe.Sizeof(sys)))
  1215. }
  1216. func SetsockoptInet4Addr(fd Handle, level, opt int, value [4]byte) (err error) {
  1217. return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(&value[0])), 4)
  1218. }
  1219. func SetsockoptIPMreq(fd Handle, level, opt int, mreq *IPMreq) (err error) {
  1220. return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(mreq)), int32(unsafe.Sizeof(*mreq)))
  1221. }
  1222. func SetsockoptIPv6Mreq(fd Handle, level, opt int, mreq *IPv6Mreq) (err error) {
  1223. return syscall.EWINDOWS
  1224. }
  1225. func EnumProcesses(processIds []uint32, bytesReturned *uint32) error {
  1226. // EnumProcesses syscall expects the size parameter to be in bytes, but the code generated with mksyscall uses
  1227. // the length of the processIds slice instead. Hence, this wrapper function is added to fix the discrepancy.
  1228. var p *uint32
  1229. if len(processIds) > 0 {
  1230. p = &processIds[0]
  1231. }
  1232. size := uint32(len(processIds) * 4)
  1233. return enumProcesses(p, size, bytesReturned)
  1234. }
  1235. func Getpid() (pid int) { return int(GetCurrentProcessId()) }
  1236. func FindFirstFile(name *uint16, data *Win32finddata) (handle Handle, err error) {
  1237. // NOTE(rsc): The Win32finddata struct is wrong for the system call:
  1238. // the two paths are each one uint16 short. Use the correct struct,
  1239. // a win32finddata1, and then copy the results out.
  1240. // There is no loss of expressivity here, because the final
  1241. // uint16, if it is used, is supposed to be a NUL, and Go doesn't need that.
  1242. // For Go 1.1, we might avoid the allocation of win32finddata1 here
  1243. // by adding a final Bug [2]uint16 field to the struct and then
  1244. // adjusting the fields in the result directly.
  1245. var data1 win32finddata1
  1246. handle, err = findFirstFile1(name, &data1)
  1247. if err == nil {
  1248. copyFindData(data, &data1)
  1249. }
  1250. return
  1251. }
  1252. func FindNextFile(handle Handle, data *Win32finddata) (err error) {
  1253. var data1 win32finddata1
  1254. err = findNextFile1(handle, &data1)
  1255. if err == nil {
  1256. copyFindData(data, &data1)
  1257. }
  1258. return
  1259. }
  1260. func getProcessEntry(pid int) (*ProcessEntry32, error) {
  1261. snapshot, err := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)
  1262. if err != nil {
  1263. return nil, err
  1264. }
  1265. defer CloseHandle(snapshot)
  1266. var procEntry ProcessEntry32
  1267. procEntry.Size = uint32(unsafe.Sizeof(procEntry))
  1268. if err = Process32First(snapshot, &procEntry); err != nil {
  1269. return nil, err
  1270. }
  1271. for {
  1272. if procEntry.ProcessID == uint32(pid) {
  1273. return &procEntry, nil
  1274. }
  1275. err = Process32Next(snapshot, &procEntry)
  1276. if err != nil {
  1277. return nil, err
  1278. }
  1279. }
  1280. }
  1281. func Getppid() (ppid int) {
  1282. pe, err := getProcessEntry(Getpid())
  1283. if err != nil {
  1284. return -1
  1285. }
  1286. return int(pe.ParentProcessID)
  1287. }
  1288. // TODO(brainman): fix all needed for os
  1289. func Fchdir(fd Handle) (err error) { return syscall.EWINDOWS }
  1290. func Link(oldpath, newpath string) (err error) { return syscall.EWINDOWS }
  1291. func Symlink(path, link string) (err error) { return syscall.EWINDOWS }
  1292. func Fchmod(fd Handle, mode uint32) (err error) { return syscall.EWINDOWS }
  1293. func Chown(path string, uid int, gid int) (err error) { return syscall.EWINDOWS }
  1294. func Lchown(path string, uid int, gid int) (err error) { return syscall.EWINDOWS }
  1295. func Fchown(fd Handle, uid int, gid int) (err error) { return syscall.EWINDOWS }
  1296. func Getuid() (uid int) { return -1 }
  1297. func Geteuid() (euid int) { return -1 }
  1298. func Getgid() (gid int) { return -1 }
  1299. func Getegid() (egid int) { return -1 }
  1300. func Getgroups() (gids []int, err error) { return nil, syscall.EWINDOWS }
  1301. type Signal int
  1302. func (s Signal) Signal() {}
  1303. func (s Signal) String() string {
  1304. if 0 <= s && int(s) < len(signals) {
  1305. str := signals[s]
  1306. if str != "" {
  1307. return str
  1308. }
  1309. }
  1310. return "signal " + itoa(int(s))
  1311. }
  1312. func LoadCreateSymbolicLink() error {
  1313. return procCreateSymbolicLinkW.Find()
  1314. }
  1315. // Readlink returns the destination of the named symbolic link.
  1316. func Readlink(path string, buf []byte) (n int, err error) {
  1317. fd, err := CreateFile(StringToUTF16Ptr(path), GENERIC_READ, 0, nil, OPEN_EXISTING,
  1318. FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_BACKUP_SEMANTICS, 0)
  1319. if err != nil {
  1320. return -1, err
  1321. }
  1322. defer CloseHandle(fd)
  1323. rdbbuf := make([]byte, MAXIMUM_REPARSE_DATA_BUFFER_SIZE)
  1324. var bytesReturned uint32
  1325. err = DeviceIoControl(fd, FSCTL_GET_REPARSE_POINT, nil, 0, &rdbbuf[0], uint32(len(rdbbuf)), &bytesReturned, nil)
  1326. if err != nil {
  1327. return -1, err
  1328. }
  1329. rdb := (*reparseDataBuffer)(unsafe.Pointer(&rdbbuf[0]))
  1330. var s string
  1331. switch rdb.ReparseTag {
  1332. case IO_REPARSE_TAG_SYMLINK:
  1333. data := (*symbolicLinkReparseBuffer)(unsafe.Pointer(&rdb.reparseBuffer))
  1334. p := (*[0xffff]uint16)(unsafe.Pointer(&data.PathBuffer[0]))
  1335. s = UTF16ToString(p[data.PrintNameOffset/2 : (data.PrintNameLength-data.PrintNameOffset)/2])
  1336. case IO_REPARSE_TAG_MOUNT_POINT:
  1337. data := (*mountPointReparseBuffer)(unsafe.Pointer(&rdb.reparseBuffer))
  1338. p := (*[0xffff]uint16)(unsafe.Pointer(&data.PathBuffer[0]))
  1339. s = UTF16ToString(p[data.PrintNameOffset/2 : (data.PrintNameLength-data.PrintNameOffset)/2])
  1340. default:
  1341. // the path is not a symlink or junction but another type of reparse
  1342. // point
  1343. return -1, syscall.ENOENT
  1344. }
  1345. n = copy(buf, []byte(s))
  1346. return n, nil
  1347. }
  1348. // GUIDFromString parses a string in the form of
  1349. // "{XXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}" into a GUID.
  1350. func GUIDFromString(str string) (GUID, error) {
  1351. guid := GUID{}
  1352. str16, err := syscall.UTF16PtrFromString(str)
  1353. if err != nil {
  1354. return guid, err
  1355. }
  1356. err = clsidFromString(str16, &guid)
  1357. if err != nil {
  1358. return guid, err
  1359. }
  1360. return guid, nil
  1361. }
  1362. // GenerateGUID creates a new random GUID.
  1363. func GenerateGUID() (GUID, error) {
  1364. guid := GUID{}
  1365. err := coCreateGuid(&guid)
  1366. if err != nil {
  1367. return guid, err
  1368. }
  1369. return guid, nil
  1370. }
  1371. // String returns the canonical string form of the GUID,
  1372. // in the form of "{XXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}".
  1373. func (guid GUID) String() string {
  1374. var str [100]uint16
  1375. chars := stringFromGUID2(&guid, &str[0], int32(len(str)))
  1376. if chars <= 1 {
  1377. return ""
  1378. }
  1379. return string(utf16.Decode(str[:chars-1]))
  1380. }
  1381. // KnownFolderPath returns a well-known folder path for the current user, specified by one of
  1382. // the FOLDERID_ constants, and chosen and optionally created based on a KF_ flag.
  1383. func KnownFolderPath(folderID *KNOWNFOLDERID, flags uint32) (string, error) {
  1384. return Token(0).KnownFolderPath(folderID, flags)
  1385. }
  1386. // KnownFolderPath returns a well-known folder path for the user token, specified by one of
  1387. // the FOLDERID_ constants, and chosen and optionally created based on a KF_ flag.
  1388. func (t Token) KnownFolderPath(folderID *KNOWNFOLDERID, flags uint32) (string, error) {
  1389. var p *uint16
  1390. err := shGetKnownFolderPath(folderID, flags, t, &p)
  1391. if err != nil {
  1392. return "", err
  1393. }
  1394. defer CoTaskMemFree(unsafe.Pointer(p))
  1395. return UTF16PtrToString(p), nil
  1396. }
  1397. // RtlGetVersion returns the version of the underlying operating system, ignoring
  1398. // manifest semantics but is affected by the application compatibility layer.
  1399. func RtlGetVersion() *OsVersionInfoEx {
  1400. info := &OsVersionInfoEx{}
  1401. info.osVersionInfoSize = uint32(unsafe.Sizeof(*info))
  1402. // According to documentation, this function always succeeds.
  1403. // The function doesn't even check the validity of the
  1404. // osVersionInfoSize member. Disassembling ntdll.dll indicates
  1405. // that the documentation is indeed correct about that.
  1406. _ = rtlGetVersion(info)
  1407. return info
  1408. }
  1409. // RtlGetNtVersionNumbers returns the version of the underlying operating system,
  1410. // ignoring manifest semantics and the application compatibility layer.
  1411. func RtlGetNtVersionNumbers() (majorVersion, minorVersion, buildNumber uint32) {
  1412. rtlGetNtVersionNumbers(&majorVersion, &minorVersion, &buildNumber)
  1413. buildNumber &= 0xffff
  1414. return
  1415. }
  1416. // GetProcessPreferredUILanguages retrieves the process preferred UI languages.
  1417. func GetProcessPreferredUILanguages(flags uint32) ([]string, error) {
  1418. return getUILanguages(flags, getProcessPreferredUILanguages)
  1419. }
  1420. // GetThreadPreferredUILanguages retrieves the thread preferred UI languages for the current thread.
  1421. func GetThreadPreferredUILanguages(flags uint32) ([]string, error) {
  1422. return getUILanguages(flags, getThreadPreferredUILanguages)
  1423. }
  1424. // GetUserPreferredUILanguages retrieves information about the user preferred UI languages.
  1425. func GetUserPreferredUILanguages(flags uint32) ([]string, error) {
  1426. return getUILanguages(flags, getUserPreferredUILanguages)
  1427. }
  1428. // GetSystemPreferredUILanguages retrieves the system preferred UI languages.
  1429. func GetSystemPreferredUILanguages(flags uint32) ([]string, error) {
  1430. return getUILanguages(flags, getSystemPreferredUILanguages)
  1431. }
  1432. func getUILanguages(flags uint32, f func(flags uint32, numLanguages *uint32, buf *uint16, bufSize *uint32) error) ([]string, error) {
  1433. size := uint32(128)
  1434. for {
  1435. var numLanguages uint32
  1436. buf := make([]uint16, size)
  1437. err := f(flags, &numLanguages, &buf[0], &size)
  1438. if err == ERROR_INSUFFICIENT_BUFFER {
  1439. continue
  1440. }
  1441. if err != nil {
  1442. return nil, err
  1443. }
  1444. buf = buf[:size]
  1445. if numLanguages == 0 || len(buf) == 0 { // GetProcessPreferredUILanguages may return numLanguages==0 with "\0\0"
  1446. return []string{}, nil
  1447. }
  1448. if buf[len(buf)-1] == 0 {
  1449. buf = buf[:len(buf)-1] // remove terminating null
  1450. }
  1451. languages := make([]string, 0, numLanguages)
  1452. from := 0
  1453. for i, c := range buf {
  1454. if c == 0 {
  1455. languages = append(languages, string(utf16.Decode(buf[from:i])))
  1456. from = i + 1
  1457. }
  1458. }
  1459. return languages, nil
  1460. }
  1461. }
  1462. func SetConsoleCursorPosition(console Handle, position Coord) error {
  1463. return setConsoleCursorPosition(console, *((*uint32)(unsafe.Pointer(&position))))
  1464. }
  1465. func GetStartupInfo(startupInfo *StartupInfo) error {
  1466. getStartupInfo(startupInfo)
  1467. return nil
  1468. }
  1469. func (s NTStatus) Errno() syscall.Errno {
  1470. return rtlNtStatusToDosErrorNoTeb(s)
  1471. }
  1472. func langID(pri, sub uint16) uint32 { return uint32(sub)<<10 | uint32(pri) }
  1473. func (s NTStatus) Error() string {
  1474. b := make([]uint16, 300)
  1475. n, err := FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_FROM_HMODULE|FORMAT_MESSAGE_ARGUMENT_ARRAY, modntdll.Handle(), uint32(s), langID(LANG_ENGLISH, SUBLANG_ENGLISH_US), b, nil)
  1476. if err != nil {
  1477. return fmt.Sprintf("NTSTATUS 0x%08x", uint32(s))
  1478. }
  1479. // trim terminating \r and \n
  1480. for ; n > 0 && (b[n-1] == '\n' || b[n-1] == '\r'); n-- {
  1481. }
  1482. return string(utf16.Decode(b[:n]))
  1483. }
  1484. // NewNTUnicodeString returns a new NTUnicodeString structure for use with native
  1485. // NT APIs that work over the NTUnicodeString type. Note that most Windows APIs
  1486. // do not use NTUnicodeString, and instead UTF16PtrFromString should be used for
  1487. // the more common *uint16 string type.
  1488. func NewNTUnicodeString(s string) (*NTUnicodeString, error) {
  1489. var u NTUnicodeString
  1490. s16, err := UTF16PtrFromString(s)
  1491. if err != nil {
  1492. return nil, err
  1493. }
  1494. RtlInitUnicodeString(&u, s16)
  1495. return &u, nil
  1496. }
  1497. // Slice returns a uint16 slice that aliases the data in the NTUnicodeString.
  1498. func (s *NTUnicodeString) Slice() []uint16 {
  1499. slice := unsafe.Slice(s.Buffer, s.MaximumLength)
  1500. return slice[:s.Length]
  1501. }
  1502. func (s *NTUnicodeString) String() string {
  1503. return UTF16ToString(s.Slice())
  1504. }
  1505. // NewNTString returns a new NTString structure for use with native
  1506. // NT APIs that work over the NTString type. Note that most Windows APIs
  1507. // do not use NTString, and instead UTF16PtrFromString should be used for
  1508. // the more common *uint16 string type.
  1509. func NewNTString(s string) (*NTString, error) {
  1510. var nts NTString
  1511. s8, err := BytePtrFromString(s)
  1512. if err != nil {
  1513. return nil, err
  1514. }
  1515. RtlInitString(&nts, s8)
  1516. return &nts, nil
  1517. }
  1518. // Slice returns a byte slice that aliases the data in the NTString.
  1519. func (s *NTString) Slice() []byte {
  1520. slice := unsafe.Slice(s.Buffer, s.MaximumLength)
  1521. return slice[:s.Length]
  1522. }
  1523. func (s *NTString) String() string {
  1524. return ByteSliceToString(s.Slice())
  1525. }
  1526. // FindResource resolves a resource of the given name and resource type.
  1527. func FindResource(module Handle, name, resType ResourceIDOrString) (Handle, error) {
  1528. var namePtr, resTypePtr uintptr
  1529. var name16, resType16 *uint16
  1530. var err error
  1531. resolvePtr := func(i interface{}, keep **uint16) (uintptr, error) {
  1532. switch v := i.(type) {
  1533. case string:
  1534. *keep, err = UTF16PtrFromString(v)
  1535. if err != nil {
  1536. return 0, err
  1537. }
  1538. return uintptr(unsafe.Pointer(*keep)), nil
  1539. case ResourceID:
  1540. return uintptr(v), nil
  1541. }
  1542. return 0, errorspkg.New("parameter must be a ResourceID or a string")
  1543. }
  1544. namePtr, err = resolvePtr(name, &name16)
  1545. if err != nil {
  1546. return 0, err
  1547. }
  1548. resTypePtr, err = resolvePtr(resType, &resType16)
  1549. if err != nil {
  1550. return 0, err
  1551. }
  1552. resInfo, err := findResource(module, namePtr, resTypePtr)
  1553. runtime.KeepAlive(name16)
  1554. runtime.KeepAlive(resType16)
  1555. return resInfo, err
  1556. }
  1557. func LoadResourceData(module, resInfo Handle) (data []byte, err error) {
  1558. size, err := SizeofResource(module, resInfo)
  1559. if err != nil {
  1560. return
  1561. }
  1562. resData, err := LoadResource(module, resInfo)
  1563. if err != nil {
  1564. return
  1565. }
  1566. ptr, err := LockResource(resData)
  1567. if err != nil {
  1568. return
  1569. }
  1570. data = unsafe.Slice((*byte)(unsafe.Pointer(ptr)), size)
  1571. return
  1572. }
  1573. // PSAPI_WORKING_SET_EX_BLOCK contains extended working set information for a page.
  1574. type PSAPI_WORKING_SET_EX_BLOCK uint64
  1575. // Valid returns the validity of this page.
  1576. // If this bit is 1, the subsequent members are valid; otherwise they should be ignored.
  1577. func (b PSAPI_WORKING_SET_EX_BLOCK) Valid() bool {
  1578. return (b & 1) == 1
  1579. }
  1580. // ShareCount is the number of processes that share this page. The maximum value of this member is 7.
  1581. func (b PSAPI_WORKING_SET_EX_BLOCK) ShareCount() uint64 {
  1582. return b.intField(1, 3)
  1583. }
  1584. // Win32Protection is the memory protection attributes of the page. For a list of values, see
  1585. // https://docs.microsoft.com/en-us/windows/win32/memory/memory-protection-constants
  1586. func (b PSAPI_WORKING_SET_EX_BLOCK) Win32Protection() uint64 {
  1587. return b.intField(4, 11)
  1588. }
  1589. // Shared returns the shared status of this page.
  1590. // If this bit is 1, the page can be shared.
  1591. func (b PSAPI_WORKING_SET_EX_BLOCK) Shared() bool {
  1592. return (b & (1 << 15)) == 1
  1593. }
  1594. // Node is the NUMA node. The maximum value of this member is 63.
  1595. func (b PSAPI_WORKING_SET_EX_BLOCK) Node() uint64 {
  1596. return b.intField(16, 6)
  1597. }
  1598. // Locked returns the locked status of this page.
  1599. // If this bit is 1, the virtual page is locked in physical memory.
  1600. func (b PSAPI_WORKING_SET_EX_BLOCK) Locked() bool {
  1601. return (b & (1 << 22)) == 1
  1602. }
  1603. // LargePage returns the large page status of this page.
  1604. // If this bit is 1, the page is a large page.
  1605. func (b PSAPI_WORKING_SET_EX_BLOCK) LargePage() bool {
  1606. return (b & (1 << 23)) == 1
  1607. }
  1608. // Bad returns the bad status of this page.
  1609. // If this bit is 1, the page is has been reported as bad.
  1610. func (b PSAPI_WORKING_SET_EX_BLOCK) Bad() bool {
  1611. return (b & (1 << 31)) == 1
  1612. }
  1613. // intField extracts an integer field in the PSAPI_WORKING_SET_EX_BLOCK union.
  1614. func (b PSAPI_WORKING_SET_EX_BLOCK) intField(start, length int) uint64 {
  1615. var mask PSAPI_WORKING_SET_EX_BLOCK
  1616. for pos := start; pos < start+length; pos++ {
  1617. mask |= (1 << pos)
  1618. }
  1619. masked := b & mask
  1620. return uint64(masked >> start)
  1621. }
  1622. // PSAPI_WORKING_SET_EX_INFORMATION contains extended working set information for a process.
  1623. type PSAPI_WORKING_SET_EX_INFORMATION struct {
  1624. // The virtual address.
  1625. VirtualAddress Pointer
  1626. // A PSAPI_WORKING_SET_EX_BLOCK union that indicates the attributes of the page at VirtualAddress.
  1627. VirtualAttributes PSAPI_WORKING_SET_EX_BLOCK
  1628. }
  1629. // CreatePseudoConsole creates a windows pseudo console.
  1630. func CreatePseudoConsole(size Coord, in Handle, out Handle, flags uint32, pconsole *Handle) error {
  1631. // We need this wrapper to manually cast Coord to uint32. The autogenerated wrappers only
  1632. // accept arguments that can be casted to uintptr, and Coord can't.
  1633. return createPseudoConsole(*((*uint32)(unsafe.Pointer(&size))), in, out, flags, pconsole)
  1634. }
  1635. // ResizePseudoConsole resizes the internal buffers of the pseudo console to the width and height specified in `size`.
  1636. func ResizePseudoConsole(pconsole Handle, size Coord) error {
  1637. // We need this wrapper to manually cast Coord to uint32. The autogenerated wrappers only
  1638. // accept arguments that can be casted to uintptr, and Coord can't.
  1639. return resizePseudoConsole(pconsole, *((*uint32)(unsafe.Pointer(&size))))
  1640. }