summaryrefslogtreecommitdiff
path: root/vendor/github.com/keybase/go-ps/process_windows.go
blob: e4d89e308db1c3a0b3315695ae276b9c36e6dd89 (plain)
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
// +build windows

package ps

import (
	"fmt"
	"syscall"
	"unsafe"
)

// Windows API functions
var (
	modKernel32                  = syscall.NewLazyDLL("kernel32.dll")
	procCloseHandle              = modKernel32.NewProc("CloseHandle")
	procCreateToolhelp32Snapshot = modKernel32.NewProc("CreateToolhelp32Snapshot")
	procProcess32First           = modKernel32.NewProc("Process32FirstW")
	procProcess32Next            = modKernel32.NewProc("Process32NextW")
	procModule32First            = modKernel32.NewProc("Module32FirstW")
	procModule32Next             = modKernel32.NewProc("Module32NextW")
)

// Some constants from the Windows API
const (
	ERROR_NO_MORE_FILES = 0x12
	MAX_PATH            = 260
	MAX_MODULE_NAME32   = 255
)

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
}

// WindowsProcess is an implementation of Process for Windows.
type WindowsProcess struct {
	pid  int
	ppid int
	exe  string
}

// Pid returns process id
func (p *WindowsProcess) Pid() int {
	return p.pid
}

// PPid returns parent process id
func (p *WindowsProcess) PPid() int {
	return p.ppid
}

// Executable returns process executable name
func (p *WindowsProcess) Executable() string {
	return p.exe
}

// Path returns path to process executable
func (p *WindowsProcess) Path() (string, error) {
	processModules, err := modules(p.pid)
	if err != nil {
		return "", err
	}
	if len(processModules) == 0 {
		return "", fmt.Errorf("No modules found for process")
	}
	return processModules[0].path, nil
}

func ptrToString(c []uint16) string {
	i := 0
	for {
		if c[i] == 0 {
			return syscall.UTF16ToString(c[:i])
		}
		i++
	}
}

func newWindowsProcess(e *PROCESSENTRY32) *WindowsProcess {
	return &WindowsProcess{
		pid:  int(e.ProcessID),
		ppid: int(e.ParentProcessID),
		exe:  ptrToString(e.ExeFile[:]),
	}
}

func findProcess(pid int) (Process, error) {
	return findProcessWithFn(processes, pid)
}

func findProcessWithFn(processesFn processesFn, pid int) (Process, error) {
	ps, err := processesFn()
	if err != nil {
		return nil, fmt.Errorf("Error listing processes: %s", err)
	}

	for _, p := range ps {
		if p.Pid() == pid {
			return p, nil
		}
	}

	return nil, nil
}

func processes() ([]Process, error) {
	handle, _, _ := procCreateToolhelp32Snapshot.Call(
		0x00000002,
		0)
	if handle < 0 {
		return nil, syscall.GetLastError()
	}
	defer procCloseHandle.Call(handle)

	var entry PROCESSENTRY32
	entry.Size = uint32(unsafe.Sizeof(entry))
	ret, _, _ := procProcess32First.Call(handle, uintptr(unsafe.Pointer(&entry)))
	if ret == 0 {
		return nil, fmt.Errorf("Error retrieving process info.")
	}

	results := make([]Process, 0, 50)
	for {
		results = append(results, newWindowsProcess(&entry))

		ret, _, _ := procProcess32Next.Call(handle, uintptr(unsafe.Pointer(&entry)))
		if ret == 0 {
			break
		}
	}

	return results, nil
}

// MODULEENTRY32 is the Windows API structure that contains a modules's
// information.
type MODULEENTRY32 struct {
	Size         uint32
	ModuleID     uint32
	ProcessID    uint32
	GlblcntUsage uint32
	ProccntUsage uint32
	ModBaseAddr  *uint8
	ModBaseSize  uint32
	HModule      uintptr
	SzModule     [MAX_MODULE_NAME32 + 1]uint16
	SzExePath    [MAX_PATH]uint16
}

type windowsModule struct {
	name string
	path string
}

func newWindowsModule(e *MODULEENTRY32) windowsModule {
	return windowsModule{
		name: ptrToString(e.SzModule[:]),
		path: ptrToString(e.SzExePath[:]),
	}
}

func modules(pid int) ([]windowsModule, error) {
	handle, _, _ := procCreateToolhelp32Snapshot.Call(
		0x00000008, // TH32CS_SNAPMODULE
		uintptr(uint32(pid)))
	if handle < 0 {
		return nil, syscall.GetLastError()
	}
	defer procCloseHandle.Call(handle)

	var entry MODULEENTRY32
	entry.Size = uint32(unsafe.Sizeof(entry))
	ret, _, _ := procModule32First.Call(handle, uintptr(unsafe.Pointer(&entry)))
	if ret == 0 {
		return nil, fmt.Errorf("Error retrieving module info")
	}

	results := make([]windowsModule, 0, 50)
	for {
		results = append(results, newWindowsModule(&entry))

		ret, _, _ := procModule32Next.Call(handle, uintptr(unsafe.Pointer(&entry)))
		if ret == 0 {
			break
		}
	}

	return results, nil
}