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