forked from elastic/gosigar
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsigar_windows.go
519 lines (409 loc) · 12.2 KB
/
sigar_windows.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
// Copyright (c) 2012 VMware, Inc.
package sigar
// #include <stdlib.h>
// #include <windows.h>
import "C"
import (
"bytes"
"fmt"
"os"
"path/filepath"
"syscall"
"time"
"unsafe"
"github.com/StackExchange/wmi"
)
var (
modpsapi = syscall.NewLazyDLL("psapi.dll")
modkernel32 = syscall.NewLazyDLL("kernel32.dll")
procEnumProcesses = modpsapi.NewProc("EnumProcesses")
procGetProcessMemoryInfo = modpsapi.NewProc("GetProcessMemoryInfo")
procGetProcessTimes = modkernel32.NewProc("GetProcessTimes")
procGetProcessImageFileName = modpsapi.NewProc("GetProcessImageFileNameA")
procCreateToolhelp32Snapshot = modkernel32.NewProc("CreateToolhelp32Snapshot")
procProcess32First = modkernel32.NewProc("Process32FirstW")
procGetDiskFreeSpaceExW = modkernel32.NewProc("GetDiskFreeSpaceExW")
procGetLogicalDriveStringsW = modkernel32.NewProc("GetLogicalDriveStringsW")
procGetDriveType = modkernel32.NewProc("GetDriveTypeW")
provGetVolumeInformation = modkernel32.NewProc("GetVolumeInformationW")
)
const (
PROCESS_ALL_ACCESS = 0x001f0fff
TH32CS_SNAPPROCESS = 0x02
MAX_PATH = 260
)
type PROCESS_MEMORY_COUNTERS_EX struct {
CB uint32
PageFaultCount uint32
PeakWorkingSetSize uintptr
WorkingSetSize uintptr
QuotaPeakPagedPoolUsage uintptr
QuotaPagedPoolUsage uintptr
QuotaPeakNonPagedPoolUsage uintptr
QuotaNonPagedPoolUsage uintptr
PagefileUsage uintptr
PeakPagefileUsage uintptr
PrivateUsage uintptr
}
// PROCESSENTRY32 is the Windows API structure that contains a process's
// information. Do not modify or reorder.
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms684839(v=vs.85).aspx
type PROCESSENTRY32 struct {
Size uint32
CntUsage uint32
ProcessID uint32
DefaultHeapID uintptr
ModuleID uint32
CntThreads uint32
ParentProcessID uint32
PriorityClassBase int32
Flags uint32
ExeFile [MAX_PATH]uint16
}
// Win32_Process represents a process on the Windows operating system. If
// additional fields are added here (that match the Windows struct) they will
// automatically be populated when calling getWin32Process.
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa394372(v=vs.85).aspx
type Win32_Process struct {
CommandLine string
}
func init() {
}
func (self *LoadAverage) Get() error {
return nil
}
func (self *Uptime) Get() error {
return nil
}
func (self *Mem) Get() error {
var statex C.MEMORYSTATUSEX
statex.dwLength = C.DWORD(unsafe.Sizeof(statex))
succeeded := C.GlobalMemoryStatusEx(&statex)
if succeeded == C.FALSE {
return syscall.GetLastError()
}
self.Total = uint64(statex.ullTotalPhys)
self.Free = uint64(statex.ullAvailPhys)
self.Used = self.Total - self.Free
vtotal := uint64(statex.ullTotalVirtual)
self.ActualFree = uint64(statex.ullAvailVirtual)
self.ActualUsed = vtotal - self.ActualFree
return nil
}
func (self *Swap) Get() error {
//return notImplemented()
return nil
}
func (self *Cpu) Get() error {
var lpIdleTime, lpKernelTime, lpUserTime C.FILETIME
succeeded := C.GetSystemTimes(&lpIdleTime, &lpKernelTime, &lpUserTime)
if succeeded == C.FALSE {
return syscall.GetLastError()
}
LOT := float64(0.0000001)
HIT := (LOT * 4294967296.0)
idle := ((HIT * float64(lpIdleTime.dwHighDateTime)) + (LOT * float64(lpIdleTime.dwLowDateTime)))
user := ((HIT * float64(lpUserTime.dwHighDateTime)) + (LOT * float64(lpUserTime.dwLowDateTime)))
kernel := ((HIT * float64(lpKernelTime.dwHighDateTime)) + (LOT * float64(lpKernelTime.dwLowDateTime)))
system := (kernel - idle)
self.Idle = uint64(idle)
self.User = uint64(user)
self.Sys = uint64(system)
return nil
}
func (self *CpuList) Get() error {
//return notImplemented()
return nil
}
func (self *FileSystemList) Get() error {
/*
Get a list of the disks:
fsutil fsinfo drives
Get driver type:
fsutil fsinfo drivetype C:
Get volume info:
fsutil fsinfo volumeinfo C:
*/
NullTermToStrings := func(b []byte) []string {
list := []string{}
for _, x := range bytes.SplitN(b, []byte{0, 0}, -1) {
x = bytes.Replace(x, []byte{0}, []byte{}, -1)
if len(x) == 0 {
break
}
list = append(list, string(x))
}
return list
}
GetDriveTypeString := func(drivetype uintptr) string {
switch drivetype {
case 1:
return "Invalid"
case 2:
return "Removable drive"
case 3:
return "Fixed drive"
case 4:
return "Remote drive"
case 5:
return "CDROM"
case 6:
return "RAM disk"
default:
return "Unknown"
}
}
lpBuffer := make([]byte, 254)
ret, _, _ := procGetLogicalDriveStringsW.Call(
uintptr(len(lpBuffer)),
uintptr(unsafe.Pointer(&lpBuffer[0])))
if ret == 0 {
return fmt.Errorf("GetLogicalDriveStringsW %v", syscall.GetLastError())
}
fss := NullTermToStrings(lpBuffer)
for _, fs := range fss {
typepath, _ := syscall.UTF16PtrFromString(fs)
typeret, _, _ := procGetDriveType.Call(uintptr(unsafe.Pointer(typepath)))
if typeret == 0 {
return fmt.Errorf("GetDriveTypeW %v", syscall.GetLastError())
}
/* TODO volumeinfo by calling GetVolumeInformationW */
d := FileSystem{
DirName: fs,
DevName: fs,
TypeName: GetDriveTypeString(typeret),
}
self.List = append(self.List, d)
}
return nil
}
// Retrieves the process identifier for each process object in the system.
func (self *ProcList) Get() error {
var enumSize int
var pids [1024]C.DWORD
// If the function succeeds, the return value is nonzero.
ret, _, _ := procEnumProcesses.Call(
uintptr(unsafe.Pointer(&pids[0])),
uintptr(unsafe.Sizeof(pids)),
uintptr(unsafe.Pointer(&enumSize)),
)
if ret == 0 {
return syscall.GetLastError()
}
results := []int{}
pids_size := enumSize / int(unsafe.Sizeof(pids[0]))
for _, pid := range pids[:pids_size] {
results = append(results, int(pid))
}
self.List = results
return nil
}
func FiletimeToDuration(ft *syscall.Filetime) time.Duration {
n := int64(ft.HighDateTime)<<32 + int64(ft.LowDateTime) // in 100-nanosecond intervals
return time.Duration(n*100) * time.Nanosecond
}
func CarrayToString(c [MAX_PATH]byte) string {
end := 0
for {
if c[end] == 0 {
break
}
end++
}
return string(c[:end])
}
func (self *ProcState) Get(pid int) error {
var err error
self.Name, err = GetProcName(pid)
if err != nil {
return err
}
self.State, err = GetProcStatus(pid)
if err != nil {
return err
}
self.Ppid, err = GetParentPid(pid)
if err != nil {
return err
}
self.Username, err = GetProcCredName(pid)
if err != nil {
return err
}
return nil
}
func GetProcName(pid int) (string, error) {
handle, err := syscall.OpenProcess(syscall.PROCESS_QUERY_INFORMATION, false, uint32(pid))
defer syscall.CloseHandle(handle)
if err != nil {
return "", fmt.Errorf("OpenProcess fails with %v", err)
}
var nameProc [MAX_PATH]byte
ret, _, _ := procGetProcessImageFileName.Call(
uintptr(handle),
uintptr(unsafe.Pointer(&nameProc)),
uintptr(MAX_PATH),
)
if ret == 0 {
return "", syscall.GetLastError()
}
return filepath.Base(CarrayToString(nameProc)), nil
}
func GetProcCredName(pid int) (string, error) {
var err error
handle, err := syscall.OpenProcess(syscall.PROCESS_QUERY_INFORMATION, false, uint32(pid))
if err != nil {
return "", fmt.Errorf("OpenProcess fails with %v", err)
}
defer syscall.CloseHandle(handle)
var token syscall.Token
// Find process token via win32
err = syscall.OpenProcessToken(handle, syscall.TOKEN_QUERY, &token)
if err != nil {
return "", fmt.Errorf("Error opening process token %v", err)
}
// Find the token user
tokenUser, err := token.GetTokenUser()
if err != nil {
return "", fmt.Errorf("Error getting token user %v", err)
}
// Close token to prevent handle leaks
err = token.Close()
if err != nil {
return "", fmt.Errorf("Error failed to closed process token")
}
// look up domain account by sid
account, domain, _, err := tokenUser.User.Sid.LookupAccount("localhost")
if err != nil {
return "", fmt.Errorf("Error looking up sid %v", err)
}
return fmt.Sprintf("%s\\%s", domain, account), nil
}
func GetProcStatus(pid int) (RunState, error) {
handle, err := syscall.OpenProcess(syscall.PROCESS_QUERY_INFORMATION, false, uint32(pid))
defer syscall.CloseHandle(handle)
if err != nil {
return RunStateUnknown, fmt.Errorf("OpenProcess fails with %v", err)
}
var ec uint32
e := syscall.GetExitCodeProcess(syscall.Handle(handle), &ec)
if e != nil {
return RunStateUnknown, os.NewSyscallError("GetExitCodeProcess", e)
}
if ec == 259 { //still active
return RunStateRun, nil
}
return RunStateSleep, nil
}
func GetParentPid(pid int) (int, error) {
handle, _, _ := procCreateToolhelp32Snapshot.Call(
uintptr(TH32CS_SNAPPROCESS),
uintptr(uint32(pid)),
)
if handle < 0 {
return 0, syscall.GetLastError()
}
defer syscall.CloseHandle(syscall.Handle(handle))
var entry PROCESSENTRY32
entry.Size = uint32(unsafe.Sizeof(entry))
ret, _, _ := procProcess32First.Call(handle, uintptr(unsafe.Pointer(&entry)))
if ret == 0 {
return 0, fmt.Errorf("Error retrieving process info.")
}
return int(entry.ParentProcessID), nil
}
func (self *ProcMem) Get(pid int) error {
handle, err := syscall.OpenProcess(PROCESS_ALL_ACCESS, false, uint32(pid))
defer syscall.CloseHandle(handle)
if err != nil {
return fmt.Errorf("OpenProcess fails with %v", err)
}
var mem PROCESS_MEMORY_COUNTERS_EX
mem.CB = uint32(unsafe.Sizeof(mem))
r1, _, e1 := procGetProcessMemoryInfo.Call(
uintptr(handle),
uintptr(unsafe.Pointer(&mem)),
uintptr(mem.CB),
)
if r1 == 0 {
if e1 != nil {
return error(e1)
} else {
return syscall.EINVAL
}
}
self.Resident = uint64(mem.WorkingSetSize)
self.Size = uint64(mem.PrivateUsage)
// Size contains only to the Private Bytes
// Virtual Bytes are the Working Set plus paged Private Bytes and standby list.
return nil
}
func (self *ProcTime) Get(pid int) error {
handle, err := syscall.OpenProcess(syscall.PROCESS_QUERY_INFORMATION, false, uint32(pid))
defer syscall.CloseHandle(handle)
if err != nil {
return fmt.Errorf("OpenProcess fails with %v", err)
}
var CPU syscall.Rusage
if err := syscall.GetProcessTimes(handle, &CPU.CreationTime, &CPU.ExitTime, &CPU.KernelTime, &CPU.UserTime); err != nil {
return fmt.Errorf("GetProcessTimes fails with %v", err)
}
// convert to millis
self.StartTime = uint64(FiletimeToDuration(&CPU.CreationTime).Nanoseconds() / 1e6)
self.User = uint64(FiletimeToDuration(&CPU.UserTime).Nanoseconds() / 1e6)
self.Sys = uint64(FiletimeToDuration(&CPU.KernelTime).Nanoseconds() / 1e6)
self.Total = self.User + self.Sys
return nil
}
func (self *ProcArgs) Get(pid int) error {
process, err := getWin32Process(int32(pid))
if err != nil {
return fmt.Errorf("could not get CommandLine: %v", err)
}
var args []string
args = append(args, process.CommandLine)
self.List = args
return nil
}
func (self *ProcExe) Get(pid int) error {
return notImplemented()
}
func (self *FileSystemUsage) Get(path string) error {
/*
Get free, available, total free bytes:
fsutil volume diskfree C:
*/
var availableBytes C.ULARGE_INTEGER
var totalBytes C.ULARGE_INTEGER
var totalFreeBytes C.ULARGE_INTEGER
pathChars := C.CString(path)
defer C.free(unsafe.Pointer(pathChars))
succeeded := C.GetDiskFreeSpaceEx((*C.CHAR)(pathChars), &availableBytes, &totalBytes, &totalFreeBytes)
if succeeded == C.FALSE {
return syscall.GetLastError()
}
self.Total = *(*uint64)(unsafe.Pointer(&totalBytes))
self.Free = *(*uint64)(unsafe.Pointer(&totalFreeBytes))
self.Used = self.Total - self.Free
self.Avail = *(*uint64)(unsafe.Pointer(&availableBytes))
return nil
}
func notImplemented() error {
panic("Not Implemented")
return nil
}
// getWin32Process gets information about the process with the given process ID.
// It uses a WMI query to get the information from the local system.
func getWin32Process(pid int32) (Win32_Process, error) {
var dst []Win32_Process
query := fmt.Sprintf("WHERE ProcessId = %d", pid)
q := wmi.CreateQuery(&dst, query)
err := wmi.Query(q, &dst)
if err != nil {
return Win32_Process{}, fmt.Errorf("could not get Win32_Process %s: %v", query, err)
}
if len(dst) < 1 {
return Win32_Process{}, fmt.Errorf("could not get Win32_Process %s: Process not found", query)
}
return dst[0], nil
}