syscall_windows.go 73 KB

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