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