syscall_windows.go 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837
  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Windows system calls.
  5. package windows
  6. import (
  7. errorspkg "errors"
  8. "fmt"
  9. "runtime"
  10. "sync"
  11. "syscall"
  12. "time"
  13. "unicode/utf16"
  14. "unsafe"
  15. )
  16. type Handle uintptr
  17. type HWND uintptr
  18. const (
  19. InvalidHandle = ^Handle(0)
  20. InvalidHWND = ^HWND(0)
  21. // Flags for DefineDosDevice.
  22. DDD_EXACT_MATCH_ON_REMOVE = 0x00000004
  23. DDD_NO_BROADCAST_SYSTEM = 0x00000008
  24. DDD_RAW_TARGET_PATH = 0x00000001
  25. DDD_REMOVE_DEFINITION = 0x00000002
  26. // Return values for GetDriveType.
  27. DRIVE_UNKNOWN = 0
  28. DRIVE_NO_ROOT_DIR = 1
  29. DRIVE_REMOVABLE = 2
  30. DRIVE_FIXED = 3
  31. DRIVE_REMOTE = 4
  32. DRIVE_CDROM = 5
  33. DRIVE_RAMDISK = 6
  34. // File system flags from GetVolumeInformation and GetVolumeInformationByHandle.
  35. FILE_CASE_SENSITIVE_SEARCH = 0x00000001
  36. FILE_CASE_PRESERVED_NAMES = 0x00000002
  37. FILE_FILE_COMPRESSION = 0x00000010
  38. FILE_DAX_VOLUME = 0x20000000
  39. FILE_NAMED_STREAMS = 0x00040000
  40. FILE_PERSISTENT_ACLS = 0x00000008
  41. FILE_READ_ONLY_VOLUME = 0x00080000
  42. FILE_SEQUENTIAL_WRITE_ONCE = 0x00100000
  43. FILE_SUPPORTS_ENCRYPTION = 0x00020000
  44. FILE_SUPPORTS_EXTENDED_ATTRIBUTES = 0x00800000
  45. FILE_SUPPORTS_HARD_LINKS = 0x00400000
  46. FILE_SUPPORTS_OBJECT_IDS = 0x00010000
  47. FILE_SUPPORTS_OPEN_BY_FILE_ID = 0x01000000
  48. FILE_SUPPORTS_REPARSE_POINTS = 0x00000080
  49. FILE_SUPPORTS_SPARSE_FILES = 0x00000040
  50. FILE_SUPPORTS_TRANSACTIONS = 0x00200000
  51. FILE_SUPPORTS_USN_JOURNAL = 0x02000000
  52. FILE_UNICODE_ON_DISK = 0x00000004
  53. FILE_VOLUME_IS_COMPRESSED = 0x00008000
  54. FILE_VOLUME_QUOTAS = 0x00000020
  55. // Flags for LockFileEx.
  56. LOCKFILE_FAIL_IMMEDIATELY = 0x00000001
  57. LOCKFILE_EXCLUSIVE_LOCK = 0x00000002
  58. // Return value of SleepEx and other APC functions
  59. WAIT_IO_COMPLETION = 0x000000C0
  60. )
  61. // StringToUTF16 is deprecated. Use UTF16FromString instead.
  62. // If s contains a NUL byte this function panics instead of
  63. // returning an error.
  64. func StringToUTF16(s string) []uint16 {
  65. a, err := UTF16FromString(s)
  66. if err != nil {
  67. panic("windows: string with NUL passed to StringToUTF16")
  68. }
  69. return a
  70. }
  71. // UTF16FromString returns the UTF-16 encoding of the UTF-8 string
  72. // s, with a terminating NUL added. If s contains a NUL byte at any
  73. // location, it returns (nil, syscall.EINVAL).
  74. func UTF16FromString(s string) ([]uint16, error) {
  75. return syscall.UTF16FromString(s)
  76. }
  77. // UTF16ToString returns the UTF-8 encoding of the UTF-16 sequence s,
  78. // with a terminating NUL and any bytes after the NUL removed.
  79. func UTF16ToString(s []uint16) string {
  80. return syscall.UTF16ToString(s)
  81. }
  82. // StringToUTF16Ptr is deprecated. Use UTF16PtrFromString instead.
  83. // If s contains a NUL byte this function panics instead of
  84. // returning an error.
  85. func StringToUTF16Ptr(s string) *uint16 { return &StringToUTF16(s)[0] }
  86. // UTF16PtrFromString returns pointer to the UTF-16 encoding of
  87. // the UTF-8 string s, with a terminating NUL added. If s
  88. // contains a NUL byte at any location, it returns (nil, syscall.EINVAL).
  89. func UTF16PtrFromString(s string) (*uint16, error) {
  90. a, err := UTF16FromString(s)
  91. if err != nil {
  92. return nil, err
  93. }
  94. return &a[0], nil
  95. }
  96. // UTF16PtrToString takes a pointer to a UTF-16 sequence and returns the corresponding UTF-8 encoded string.
  97. // If the pointer is nil, it returns the empty string. It assumes that the UTF-16 sequence is terminated
  98. // at a zero word; if the zero word is not present, the program may crash.
  99. func UTF16PtrToString(p *uint16) string {
  100. if p == nil {
  101. return ""
  102. }
  103. if *p == 0 {
  104. return ""
  105. }
  106. // Find NUL terminator.
  107. n := 0
  108. for ptr := unsafe.Pointer(p); *(*uint16)(ptr) != 0; n++ {
  109. ptr = unsafe.Pointer(uintptr(ptr) + unsafe.Sizeof(*p))
  110. }
  111. return string(utf16.Decode(unsafe.Slice(p, n)))
  112. }
  113. func Getpagesize() int { return 4096 }
  114. // NewCallback converts a Go function to a function pointer conforming to the stdcall calling convention.
  115. // This is useful when interoperating with Windows code requiring callbacks.
  116. // The argument is expected to be a function with one uintptr-sized result. The function must not have arguments with size larger than the size of uintptr.
  117. func NewCallback(fn interface{}) uintptr {
  118. return syscall.NewCallback(fn)
  119. }
  120. // NewCallbackCDecl converts a Go function to a function pointer conforming to the cdecl calling convention.
  121. // This is useful when interoperating with Windows code requiring callbacks.
  122. // The argument is expected to be a function with one uintptr-sized result. The function must not have arguments with size larger than the size of uintptr.
  123. func NewCallbackCDecl(fn interface{}) uintptr {
  124. return syscall.NewCallbackCDecl(fn)
  125. }
  126. // windows api calls
  127. //sys GetLastError() (lasterr error)
  128. //sys LoadLibrary(libname string) (handle Handle, err error) = LoadLibraryW
  129. //sys LoadLibraryEx(libname string, zero Handle, flags uintptr) (handle Handle, err error) = LoadLibraryExW
  130. //sys FreeLibrary(handle Handle) (err error)
  131. //sys GetProcAddress(module Handle, procname string) (proc uintptr, err error)
  132. //sys GetModuleFileName(module Handle, filename *uint16, size uint32) (n uint32, err error) = kernel32.GetModuleFileNameW
  133. //sys GetModuleHandleEx(flags uint32, moduleName *uint16, module *Handle) (err error) = kernel32.GetModuleHandleExW
  134. //sys SetDefaultDllDirectories(directoryFlags uint32) (err error)
  135. //sys AddDllDirectory(path *uint16) (cookie uintptr, err error) = kernel32.AddDllDirectory
  136. //sys RemoveDllDirectory(cookie uintptr) (err error) = kernel32.RemoveDllDirectory
  137. //sys SetDllDirectory(path string) (err error) = kernel32.SetDllDirectoryW
  138. //sys GetVersion() (ver uint32, err error)
  139. //sys FormatMessage(flags uint32, msgsrc uintptr, msgid uint32, langid uint32, buf []uint16, args *byte) (n uint32, err error) = FormatMessageW
  140. //sys ExitProcess(exitcode uint32)
  141. //sys IsWow64Process(handle Handle, isWow64 *bool) (err error) = IsWow64Process
  142. //sys IsWow64Process2(handle Handle, processMachine *uint16, nativeMachine *uint16) (err error) = IsWow64Process2?
  143. //sys CreateFile(name *uint16, access uint32, mode uint32, sa *SecurityAttributes, createmode uint32, attrs uint32, templatefile Handle) (handle Handle, err error) [failretval==InvalidHandle] = CreateFileW
  144. //sys CreateNamedPipe(name *uint16, flags uint32, pipeMode uint32, maxInstances uint32, outSize uint32, inSize uint32, defaultTimeout uint32, sa *SecurityAttributes) (handle Handle, err error) [failretval==InvalidHandle] = CreateNamedPipeW
  145. //sys ConnectNamedPipe(pipe Handle, overlapped *Overlapped) (err error)
  146. //sys GetNamedPipeInfo(pipe Handle, flags *uint32, outSize *uint32, inSize *uint32, maxInstances *uint32) (err error)
  147. //sys GetNamedPipeHandleState(pipe Handle, state *uint32, curInstances *uint32, maxCollectionCount *uint32, collectDataTimeout *uint32, userName *uint16, maxUserNameSize uint32) (err error) = GetNamedPipeHandleStateW
  148. //sys SetNamedPipeHandleState(pipe Handle, state *uint32, maxCollectionCount *uint32, collectDataTimeout *uint32) (err error) = SetNamedPipeHandleState
  149. //sys readFile(handle Handle, buf []byte, done *uint32, overlapped *Overlapped) (err error) = ReadFile
  150. //sys writeFile(handle Handle, buf []byte, done *uint32, overlapped *Overlapped) (err error) = WriteFile
  151. //sys GetOverlappedResult(handle Handle, overlapped *Overlapped, done *uint32, wait bool) (err error)
  152. //sys SetFilePointer(handle Handle, lowoffset int32, highoffsetptr *int32, whence uint32) (newlowoffset uint32, err error) [failretval==0xffffffff]
  153. //sys CloseHandle(handle Handle) (err error)
  154. //sys GetStdHandle(stdhandle uint32) (handle Handle, err error) [failretval==InvalidHandle]
  155. //sys SetStdHandle(stdhandle uint32, handle Handle) (err error)
  156. //sys findFirstFile1(name *uint16, data *win32finddata1) (handle Handle, err error) [failretval==InvalidHandle] = FindFirstFileW
  157. //sys findNextFile1(handle Handle, data *win32finddata1) (err error) = FindNextFileW
  158. //sys FindClose(handle Handle) (err error)
  159. //sys GetFileInformationByHandle(handle Handle, data *ByHandleFileInformation) (err error)
  160. //sys GetFileInformationByHandleEx(handle Handle, class uint32, outBuffer *byte, outBufferLen uint32) (err error)
  161. //sys SetFileInformationByHandle(handle Handle, class uint32, inBuffer *byte, inBufferLen uint32) (err error)
  162. //sys GetCurrentDirectory(buflen uint32, buf *uint16) (n uint32, err error) = GetCurrentDirectoryW
  163. //sys SetCurrentDirectory(path *uint16) (err error) = SetCurrentDirectoryW
  164. //sys CreateDirectory(path *uint16, sa *SecurityAttributes) (err error) = CreateDirectoryW
  165. //sys RemoveDirectory(path *uint16) (err error) = RemoveDirectoryW
  166. //sys DeleteFile(path *uint16) (err error) = DeleteFileW
  167. //sys MoveFile(from *uint16, to *uint16) (err error) = MoveFileW
  168. //sys MoveFileEx(from *uint16, to *uint16, flags uint32) (err error) = MoveFileExW
  169. //sys LockFileEx(file Handle, flags uint32, reserved uint32, bytesLow uint32, bytesHigh uint32, overlapped *Overlapped) (err error)
  170. //sys UnlockFileEx(file Handle, reserved uint32, bytesLow uint32, bytesHigh uint32, overlapped *Overlapped) (err error)
  171. //sys GetComputerName(buf *uint16, n *uint32) (err error) = GetComputerNameW
  172. //sys GetComputerNameEx(nametype uint32, buf *uint16, n *uint32) (err error) = GetComputerNameExW
  173. //sys SetEndOfFile(handle Handle) (err error)
  174. //sys 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. }