syscall_windows.go 85 KB

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