syscall_windows.go 85 KB

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