syscall_windows.go 72 KB

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