Debian Codegraph @

sys/windows/syscall_windows.go

raw symbols SCIP
1 package windows
2
3 import (
4 "fmt"
5 "syscall"
6 "time"
7 "unsafe"
8
9 "github.com/pkg/errors"
10 )
11
12 var (
13 sizeofUint32 = 4
14 sizeofProcessEntry32 = uint32(unsafe.Sizeof(ProcessEntry32{}))
15 sizeofProcessMemoryCountersEx = uint32(unsafe.Sizeof(ProcessMemoryCountersEx{}))
16 sizeofMemoryStatusEx = uint32(unsafe.Sizeof(MemoryStatusEx{}))
17 )
18
19 // Process-specific access rights. Others are declared in the syscall package.
20 // https://msdn.microsoft.com/en-us/library/windows/desktop/ms684880(v=vs.85).aspx
21 const (
22 PROCESS_QUERY_LIMITED_INFORMATION uint32 = 0x1000
23 PROCESS_VM_READ uint32 = 0x0010
24 )
25
26 // MAX_PATH is the maximum length for a path in Windows.
27 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx
28 const MAX_PATH = 260
29
30 // DriveType represents a type of drive (removable, fixed, CD-ROM, RAM disk, or
31 // network drive).
32 type DriveType uint32
33
34 // Drive types as returned by GetDriveType.
35 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa364939(v=vs.85).aspx
36 const (
37 DRIVE_UNKNOWN DriveType = iota
38 DRIVE_NO_ROOT_DIR
39 DRIVE_REMOVABLE
40 DRIVE_FIXED
41 DRIVE_REMOTE
42 DRIVE_CDROM
43 DRIVE_RAMDISK
44 )
45
46 func (dt DriveType) String() string {
47 names := map[DriveType]string{
48 DRIVE_UNKNOWN: "unknown",
49 DRIVE_NO_ROOT_DIR: "invalid",
50 DRIVE_REMOVABLE: "removable",
51 DRIVE_FIXED: "fixed",
52 DRIVE_REMOTE: "remote",
53 DRIVE_CDROM: "cdrom",
54 DRIVE_RAMDISK: "ramdisk",
55 }
56
57 name, found := names[dt]
58 if !found {
59 return "unknown DriveType value"
60 }
61 return name
62 }
63
64 // Flags that can be used with CreateToolhelp32Snapshot.
65 const (
66 TH32CS_INHERIT uint32 = 0x80000000 // Indicates that the snapshot handle is to be inheritable.
67 TH32CS_SNAPHEAPLIST uint32 = 0x00000001 // Includes all heaps of the process specified in th32ProcessID in the snapshot.
68 TH32CS_SNAPMODULE uint32 = 0x00000008 // Includes all modules of the process specified in th32ProcessID in the snapshot.
69 TH32CS_SNAPMODULE32 uint32 = 0x00000010 // Includes all 32-bit modules of the process specified in th32ProcessID in the snapshot when called from a 64-bit process.
70 TH32CS_SNAPPROCESS uint32 = 0x00000002 // Includes all processes in the system in the snapshot.
71 TH32CS_SNAPTHREAD uint32 = 0x00000004 // Includes all threads in the system in the snapshot.
72 )
73
74 // ProcessEntry32 is an equivalent representation of PROCESSENTRY32 in the
75 // Windows API. It contains a process's information. Do not modify or reorder.
76 // https://msdn.microsoft.com/en-us/library/windows/desktop/ms684839(v=vs.85).aspx
77 type ProcessEntry32 struct {
78 size uint32
79 CntUsage uint32
80 ProcessID uint32
81 DefaultHeapID uintptr
82 ModuleID uint32
83 CntThreads uint32
84 ParentProcessID uint32
85 PriorityClassBase int32
86 Flags uint32
87 exeFile [MAX_PATH]uint16
88 }
89
90 // ExeFile returns the name of the executable file for the process. It does
91 // not contain the full path.
92 func (p ProcessEntry32) ExeFile() string {
93 return syscall.UTF16ToString(p.exeFile[:])
94 }
95
96 func (p ProcessEntry32) String() string {
97 return fmt.Sprintf("{CntUsage:%v ProcessID:%v DefaultHeapID:%v ModuleID:%v "+
98 "CntThreads:%v ParentProcessID:%v PriorityClassBase:%v Flags:%v ExeFile:%v",
99 p.CntUsage, p.ProcessID, p.DefaultHeapID, p.ModuleID, p.CntThreads,
100 p.ParentProcessID, p.PriorityClassBase, p.Flags, p.ExeFile())
101 }
102
103 // MemoryStatusEx is an equivalent representation of MEMORYSTATUSEX in the
104 // Windows API. It contains information about the current state of both physical
105 // and virtual memory, including extended memory.
106 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa366770
107 type MemoryStatusEx struct {
108 length uint32
109 MemoryLoad uint32
110 TotalPhys uint64
111 AvailPhys uint64
112 TotalPageFile uint64
113 AvailPageFile uint64
114 TotalVirtual uint64
115 AvailVirtual uint64
116 AvailExtendedVirtual uint64
117 }
118
119 // ProcessMemoryCountersEx is an equivalent representation of
120 // PROCESS_MEMORY_COUNTERS_EX in the Windows API.
121 // https://msdn.microsoft.com/en-us/library/windows/desktop/ms684874(v=vs.85).aspx
122 type ProcessMemoryCountersEx struct {
123 cb uint32
124 PageFaultCount uint32
125 PeakWorkingSetSize uintptr
126 WorkingSetSize uintptr
127 QuotaPeakPagedPoolUsage uintptr
128 QuotaPagedPoolUsage uintptr
129 QuotaPeakNonPagedPoolUsage uintptr
130 QuotaNonPagedPoolUsage uintptr
131 PagefileUsage uintptr
132 PeakPagefileUsage uintptr
133 PrivateUsage uintptr
134 }
135
136 // GetLogicalDriveStrings returns a list of drives in the system.
137 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa364975(v=vs.85).aspx
138 func GetLogicalDriveStrings() ([]string, error) {
139 // Determine the size of the buffer required to receive all drives.
140 bufferLength, err := _GetLogicalDriveStringsW(0, nil)
141 if err != nil {
142 return nil, errors.Wrap(err, "GetLogicalDriveStringsW failed to get buffer length")
143 }
144 if bufferLength < 0 {
145 return nil, errors.New("GetLogicalDriveStringsW returned an invalid buffer length")
146 }
147
148 buffer := make([]uint16, bufferLength)
149 _, err = _GetLogicalDriveStringsW(uint32(len(buffer)), &buffer[0])
150 if err != nil {
151 return nil, errors.Wrap(err, "GetLogicalDriveStringsW failed")
152 }
153
154 // Split the uint16 slice at null-terminators.
155 var startIdx int
156 var drivesUTF16 [][]uint16
157 for i, value := range buffer {
158 if value == 0 {
159 drivesUTF16 = append(drivesUTF16, buffer[startIdx:i])
160 startIdx = i + 1
161 }
162 }
163
164 // Convert the utf16 slices to strings.
165 drives := make([]string, 0, len(drivesUTF16))
166 for _, driveUTF16 := range drivesUTF16 {
167 if len(driveUTF16) > 0 {
168 drives = append(drives, syscall.UTF16ToString(driveUTF16))
169 }
170 }
171
172 return drives, nil
173 }
174
175 // GlobalMemoryStatusEx retrieves information about the system's current usage
176 // of both physical and virtual memory.
177 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa366589(v=vs.85).aspx
178 func GlobalMemoryStatusEx() (MemoryStatusEx, error) {
179 memoryStatusEx := MemoryStatusEx{length: sizeofMemoryStatusEx}
180 err := _GlobalMemoryStatusEx(&memoryStatusEx)
181 if err != nil {
182 return MemoryStatusEx{}, errors.Wrap(err, "GlobalMemoryStatusEx failed")
183 }
184
185 return memoryStatusEx, nil
186 }
187
188 // GetProcessMemoryInfo retrieves information about the memory usage of the
189 // specified process.
190 // https://msdn.microsoft.com/en-us/library/windows/desktop/ms683219(v=vs.85).aspx
191 func GetProcessMemoryInfo(handle syscall.Handle) (ProcessMemoryCountersEx, error) {
192 processMemoryCountersEx := ProcessMemoryCountersEx{cb: sizeofProcessMemoryCountersEx}
193 err := _GetProcessMemoryInfo(handle, &processMemoryCountersEx, processMemoryCountersEx.cb)
194 if err != nil {
195 return ProcessMemoryCountersEx{}, errors.Wrap(err, "GetProcessMemoryInfo failed")
196 }
197
198 return processMemoryCountersEx, nil
199 }
200
201 // GetProcessImageFileName Retrieves the name of the executable file for the
202 // specified process.
203 // https://msdn.microsoft.com/en-us/library/windows/desktop/ms683217(v=vs.85).aspx
204 func GetProcessImageFileName(handle syscall.Handle) (string, error) {
205 buffer := make([]uint16, MAX_PATH)
206 _, err := _GetProcessImageFileName(handle, &buffer[0], uint32(len(buffer)))
207 if err != nil {
208 return "", errors.Wrap(err, "GetProcessImageFileName failed")
209 }
210
211 return syscall.UTF16ToString(buffer), nil
212 }
213
214 // GetSystemTimes retrieves system timing information. On a multiprocessor
215 // system, the values returned are the sum of the designated times across all
216 // processors. The returned kernel time does not include the system idle time.
217 // https://msdn.microsoft.com/en-us/library/windows/desktop/ms724400(v=vs.85).aspx
218 func GetSystemTimes() (idle, kernel, user time.Duration, err error) {
219 var idleTime, kernelTime, userTime syscall.Filetime
220 err = _GetSystemTimes(&idleTime, &kernelTime, &userTime)
221 if err != nil {
222 return 0, 0, 0, errors.Wrap(err, "GetSystemTimes failed")
223 }
224
225 idle = FiletimeToDuration(&idleTime)
226 kernel = FiletimeToDuration(&kernelTime) // Kernel time includes idle time so we subtract it out.
227 user = FiletimeToDuration(&userTime)
228
229 return idle, kernel - idle, user, nil
230 }
231
232 // FiletimeToDuration converts a Filetime to a time.Duration. Do not use this
233 // method to convert a Filetime to an actual clock time, for that use
234 // Filetime.Nanosecond().
235 func FiletimeToDuration(ft *syscall.Filetime) time.Duration {
236 n := int64(ft.HighDateTime)<<32 + int64(ft.LowDateTime) // in 100-nanosecond intervals
237 return time.Duration(n * 100)
238 }
239
240 // GetDriveType Determines whether a disk drive is a removable, fixed, CD-ROM,
241 // RAM disk, or network drive. A trailing backslash is required on the
242 // rootPathName.
243 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa364939
244 func GetDriveType(rootPathName string) (DriveType, error) {
245 rootPathNamePtr, err := syscall.UTF16PtrFromString(rootPathName)
246 if err != nil {
247 return DRIVE_UNKNOWN, errors.Wrapf(err, "UTF16PtrFromString failed for rootPathName=%v", rootPathName)
248 }
249
250 dt, err := _GetDriveType(rootPathNamePtr)
251 if err != nil {
252 return DRIVE_UNKNOWN, errors.Wrapf(err, "GetDriveType failed for rootPathName=%v", rootPathName)
253 }
254
255 return dt, nil
256 }
257
258 // EnumProcesses retrieves the process identifier for each process object in the
259 // system. This function can return a max of 65536 PIDs. If there are more
260 // processes than that then this will not return them all.
261 // https://msdn.microsoft.com/en-us/library/windows/desktop/ms682629(v=vs.85).aspx
262 func EnumProcesses() ([]uint32, error) {
263 enumProcesses := func(size int) ([]uint32, error) {
264 var (
265 pids = make([]uint32, size)
266 sizeBytes = len(pids) * sizeofUint32
267 bytesWritten uint32
268 )
269
270 err := _EnumProcesses(&pids[0], uint32(sizeBytes), &bytesWritten)
271
272 pidsWritten := int(bytesWritten) / sizeofUint32
273 if int(bytesWritten)%sizeofUint32 != 0 || pidsWritten > len(pids) {
274 return nil, errors.Errorf("EnumProcesses returned an invalid bytesWritten value of %v", bytesWritten)
275 }
276 pids = pids[:pidsWritten]
277
278 return pids, err
279 }
280
281 // Retry the EnumProcesses call with larger arrays if needed.
282 size := 2048
283 var pids []uint32
284 for tries := 0; tries < 5; tries++ {
285 var err error
286 pids, err = enumProcesses(size)
287 if err != nil {
288 return nil, errors.Wrap(err, "EnumProcesses failed")
289 }
290
291 if len(pids) < size {
292 break
293 }
294
295 // Increase the size the pids array and retry the enumProcesses call
296 // because the array wasn't large enough to hold all of the processes.
297 size *= 2
298 }
299
300 return pids, nil
301 }
302
303 // GetDiskFreeSpaceEx retrieves information about the amount of space that is
304 // available on a disk volume, which is the total amount of space, the total
305 // amount of free space, and the total amount of free space available to the
306 // user that is associated with the calling thread.
307 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa364937(v=vs.85).aspx
308 func GetDiskFreeSpaceEx(directoryName string) (freeBytesAvailable, totalNumberOfBytes, totalNumberOfFreeBytes uint64, err error) {
309 directoryNamePtr, err := syscall.UTF16PtrFromString(directoryName)
310 if err != nil {
311 return 0, 0, 0, errors.Wrapf(err, "UTF16PtrFromString failed for directoryName=%v", directoryName)
312 }
313
314 err = _GetDiskFreeSpaceEx(directoryNamePtr, &freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes)
315 if err != nil {
316 return 0, 0, 0, err
317 }
318
319 return freeBytesAvailable, totalNumberOfBytes, totalNumberOfFreeBytes, nil
320 }
321
322 // CreateToolhelp32Snapshot takes a snapshot of the specified processes, as well
323 // as the heaps, modules, and threads used by these processes.
324 // https://msdn.microsoft.com/en-us/library/windows/desktop/ms682489(v=vs.85).aspx
325 func CreateToolhelp32Snapshot(flags, pid uint32) (syscall.Handle, error) {
326 h, err := _CreateToolhelp32Snapshot(flags, pid)
327 if err != nil {
328 return syscall.InvalidHandle, err
329 }
330 if h == syscall.InvalidHandle {
331 return syscall.InvalidHandle, syscall.GetLastError()
332 }
333
334 return h, nil
335 }
336
337 // Process32First retrieves information about the first process encountered in a
338 // system snapshot.
339 // https://msdn.microsoft.com/en-us/library/windows/desktop/ms684834
340 func Process32First(handle syscall.Handle) (ProcessEntry32, error) {
341 processEntry32 := ProcessEntry32{size: sizeofProcessEntry32}
342 err := _Process32First(handle, &processEntry32)
343 if err != nil {
344 return ProcessEntry32{}, errors.Wrap(err, "Process32First failed")
345 }
346
347 return processEntry32, nil
348 }
349
350 // Process32Next retrieves information about the next process recorded in a
351 // system snapshot. When there are no more processes to iterate then
352 // syscall.ERROR_NO_MORE_FILES is returned (use errors.Cause() to unwrap).
353 // https://msdn.microsoft.com/en-us/library/windows/desktop/ms684836
354 func Process32Next(handle syscall.Handle) (ProcessEntry32, error) {
355 processEntry32 := ProcessEntry32{size: sizeofProcessEntry32}
356 err := _Process32Next(handle, &processEntry32)
357 if err != nil {
358 return ProcessEntry32{}, errors.Wrap(err, "Process32Next failed")
359 }
360
361 return processEntry32, nil
362 }
363
364 // Use "GOOS=windows go generate -v -x ." to generate the source.
365
366 // Add -trace to enable debug prints around syscalls.
367 //go:generate go run $GOROOT/src/syscall/mksyscall_windows.go -output zsyscall_windows.go syscall_windows.go
368
369 // Windows API calls
370 //sys _GlobalMemoryStatusEx(buffer *MemoryStatusEx) (err error) = kernel32.GlobalMemoryStatusEx
371 //sys _GetLogicalDriveStringsW(bufferLength uint32, buffer *uint16) (length uint32, err error) = kernel32.GetLogicalDriveStringsW
372 //sys _GetProcessMemoryInfo(handle syscall.Handle, psmemCounters *ProcessMemoryCountersEx, cb uint32) (err error) = psapi.GetProcessMemoryInfo
373 //sys _GetProcessImageFileName(handle syscall.Handle, outImageFileName *uint16, size uint32) (length uint32, err error) = psapi.GetProcessImageFileNameW
374 //sys _GetSystemTimes(idleTime *syscall.Filetime, kernelTime *syscall.Filetime, userTime *syscall.Filetime) (err error) = kernel32.GetSystemTimes
375 //sys _GetDriveType(rootPathName *uint16) (dt DriveType, err error) = kernel32.GetDriveTypeW
376 //sys _EnumProcesses(processIds *uint32, sizeBytes uint32, bytesReturned *uint32) (err error) = psapi.EnumProcesses
377 //sys _GetDiskFreeSpaceEx(directoryName *uint16, freeBytesAvailable *uint64, totalNumberOfBytes *uint64, totalNumberOfFreeBytes *uint64) (err error) = kernel32.GetDiskFreeSpaceExW
378 //sys _Process32First(handle syscall.Handle, processEntry32 *ProcessEntry32) (err error) = kernel32.Process32FirstW
379 //sys _Process32Next(handle syscall.Handle, processEntry32 *ProcessEntry32) (err error) = kernel32.Process32NextW
380 //sys _CreateToolhelp32Snapshot(flags uint32, processID uint32) (handle syscall.Handle, err error) = kernel32.CreateToolhelp32Snapshot
381 //sys _NtQuerySystemInformation(systemInformationClass uint32, systemInformation *byte, systemInformationLength uint32, returnLength *uint32) (ntstatus uint32, err error) = ntdll.NtQuerySystemInformation
382 //sys _NtQueryInformationProcess(processHandle syscall.Handle, processInformationClass uint32, processInformation *byte, processInformationLength uint32, returnLength *uint32) (ntstatus uint32, err error) = ntdll.NtQueryInformationProcess
383 //sys _LookupPrivilegeName(systemName string, luid *int64, buffer *uint16, size *uint32) (err error) = advapi32.LookupPrivilegeNameW
384 //sys _LookupPrivilegeValue(systemName string, name string, luid *int64) (err error) = advapi32.LookupPrivilegeValueW
385 //sys _AdjustTokenPrivileges(token syscall.Token, releaseAll bool, input *byte, outputSize uint32, output *byte, requiredSize *uint32) (success bool, err error) [true] = advapi32.AdjustTokenPrivileges