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