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
use crate::error::{CrosswinError, Result};
use crate::windows::handles::ProcessHandle;
use crate::processes::{MemoryInfo, ProcessPriority};
#[cfg(feature = "win32")]
use windows::Win32::Foundation::{WAIT_OBJECT_0, WAIT_TIMEOUT};
#[cfg(feature = "win32")]
use windows::Win32::System::Threading::{
OpenProcess, TerminateProcess, GetCurrentProcess, GetExitCodeProcess,
WaitForSingleObject, SetPriorityClass, GetPriorityClass,
PROCESS_TERMINATE, PROCESS_QUERY_INFORMATION, PROCESS_QUERY_LIMITED_INFORMATION,
PROCESS_SET_INFORMATION, PROCESS_SUSPEND_RESUME, PROCESS_ALL_ACCESS,
INFINITE,
};
#[cfg(feature = "win32")]
use windows::Win32::System::Diagnostics::ToolHelp::{
CreateToolhelp32Snapshot, Thread32First, Thread32Next, THREADENTRY32, TH32CS_SNAPTHREAD,
};
#[cfg(feature = "win32")]
use windows::Win32::System::Threading::{OpenThread, SuspendThread, ResumeThread, THREAD_SUSPEND_RESUME};
#[cfg(feature = "win32")]
use windows::Win32::System::ProcessStatus::{GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS};
/// Access rights for opening a process
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProcessAccess {
/// Query limited information
QueryLimitedInformation,
/// Query full information
QueryInformation,
/// Terminate the process
Terminate,
/// Set process information
SetInformation,
/// Suspend/resume threads
SuspendResume,
/// All access rights
AllAccess,
}
#[cfg(feature = "win32")]
impl ProcessAccess {
fn to_windows_flags(&self) -> u32 {
match self {
ProcessAccess::QueryLimitedInformation => PROCESS_QUERY_LIMITED_INFORMATION.0,
ProcessAccess::QueryInformation => PROCESS_QUERY_INFORMATION.0,
ProcessAccess::Terminate => PROCESS_TERMINATE.0,
ProcessAccess::SetInformation => PROCESS_SET_INFORMATION.0,
ProcessAccess::SuspendResume => PROCESS_SUSPEND_RESUME.0,
ProcessAccess::AllAccess => PROCESS_ALL_ACCESS.0,
}
}
}
/// Represents an opened process with various operations
#[derive(Debug)]
pub struct Process {
handle: Option<ProcessHandle>,
pid: u32,
}
impl Process {
/// Get the current process
pub fn current() -> Result<Self> {
#[cfg(feature = "win32")]
{
unsafe {
let handle = GetCurrentProcess();
let pid = windows::Win32::System::Threading::GetCurrentProcessId();
Ok(Process {
handle: Some(ProcessHandle::from_windows_handle(handle)),
pid,
})
}
}
#[cfg(not(feature = "win32"))]
{
Ok(Process {
handle: None,
pid: 0,
})
}
}
/// Open a process by PID with specified access rights
pub fn open(pid: u32, _access: ProcessAccess) -> Result<Self> {
#[cfg(feature = "win32")]
{
unsafe {
let handle = OpenProcess(
windows::Win32::System::Threading::PROCESS_ACCESS_RIGHTS(_access.to_windows_flags()),
false,
pid,
)
.map_err(|e| {
if e.code().0 == 0x80070005u32 as i32 {
// ERROR_ACCESS_DENIED
CrosswinError::access_denied("process", Some(pid))
} else if e.code().0 == 0x80070057u32 as i32 {
// ERROR_INVALID_PARAMETER (process doesn't exist)
CrosswinError::process_not_found(pid)
} else {
CrosswinError::win32("OpenProcess", e.code().0 as u32, e.to_string())
}
})?;
Ok(Process {
handle: Some(ProcessHandle::from_windows_handle(handle)),
pid,
})
}
}
#[cfg(not(feature = "win32"))]
{
Ok(Process {
handle: None,
pid,
})
}
}
/// Get the process ID
pub fn pid(&self) -> u32 {
self.pid
}
/// Get the process handle (if available)
pub fn handle(&self) -> Option<&ProcessHandle> {
self.handle.as_ref()
}
/// Terminate the process with the given exit code
pub fn terminate(&self, _exit_code: u32) -> Result<()> {
#[cfg(feature = "win32")]
{
let handle = self.handle.as_ref()
.ok_or_else(|| CrosswinError::invalid_parameter("handle", "Process handle is not available"))?;
unsafe {
TerminateProcess(handle.as_handle().as_windows_handle(), _exit_code)
.map_err(|e| CrosswinError::win32(
"TerminateProcess",
e.code().0 as u32,
e.to_string()
))?;
}
Ok(())
}
#[cfg(not(feature = "win32"))]
{
Err(CrosswinError::invalid_parameter("platform", "Not supported on this platform"))
}
}
/// Suspend all threads in the process.
///
/// Per-thread errors are surfaced: on the first unrecoverable failure (after
/// attempting every thread) a `CrosswinError::Win32` is returned.
pub fn suspend(&self) -> Result<()> {
#[cfg(feature = "win32")]
{
use crate::windows::handles::Handle;
unsafe {
let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0)
.map_err(|e| CrosswinError::win32(
"CreateToolhelp32Snapshot",
e.code().0 as u32,
e.to_string()
))?;
// RAII closes snapshot even on early return.
let _snapshot_guard = Handle::from_windows_handle(snapshot);
let mut entry = THREADENTRY32::default();
entry.dwSize = std::mem::size_of::<THREADENTRY32>() as u32;
let mut first_error: Option<CrosswinError> = None;
if Thread32First(snapshot, &mut entry).is_ok() {
loop {
if entry.th32OwnerProcessID == self.pid {
match OpenThread(THREAD_SUSPEND_RESUME, false, entry.th32ThreadID) {
Ok(thread_handle) => {
let _guard = Handle::from_windows_handle(thread_handle);
if SuspendThread(thread_handle) == u32::MAX {
let code = windows::Win32::Foundation::GetLastError().0;
if first_error.is_none() {
first_error = Some(CrosswinError::win32(
"SuspendThread",
code,
format!("thread {} could not be suspended", entry.th32ThreadID),
));
}
}
}
Err(e) => {
if first_error.is_none() {
first_error = Some(CrosswinError::win32(
"OpenThread",
e.code().0 as u32,
e.to_string(),
));
}
}
}
}
if Thread32Next(snapshot, &mut entry).is_err() {
break;
}
}
}
if let Some(err) = first_error {
return Err(err);
}
Ok(())
}
}
#[cfg(not(feature = "win32"))]
{
Err(CrosswinError::invalid_parameter("platform", "Not supported on this platform"))
}
}
/// Resume all threads in the process.
///
/// Per-thread errors are surfaced: on the first unrecoverable failure (after
/// attempting every thread) a `CrosswinError::Win32` is returned.
pub fn resume(&self) -> Result<()> {
#[cfg(feature = "win32")]
{
use crate::windows::handles::Handle;
unsafe {
let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0)
.map_err(|e| CrosswinError::win32(
"CreateToolhelp32Snapshot",
e.code().0 as u32,
e.to_string()
))?;
let _snapshot_guard = Handle::from_windows_handle(snapshot);
let mut entry = THREADENTRY32::default();
entry.dwSize = std::mem::size_of::<THREADENTRY32>() as u32;
let mut first_error: Option<CrosswinError> = None;
if Thread32First(snapshot, &mut entry).is_ok() {
loop {
if entry.th32OwnerProcessID == self.pid {
match OpenThread(THREAD_SUSPEND_RESUME, false, entry.th32ThreadID) {
Ok(thread_handle) => {
let _guard = Handle::from_windows_handle(thread_handle);
if ResumeThread(thread_handle) == u32::MAX {
let code = windows::Win32::Foundation::GetLastError().0;
if first_error.is_none() {
first_error = Some(CrosswinError::win32(
"ResumeThread",
code,
format!("thread {} could not be resumed", entry.th32ThreadID),
));
}
}
}
Err(e) => {
if first_error.is_none() {
first_error = Some(CrosswinError::win32(
"OpenThread",
e.code().0 as u32,
e.to_string(),
));
}
}
}
}
if Thread32Next(snapshot, &mut entry).is_err() {
break;
}
}
}
if let Some(err) = first_error {
return Err(err);
}
Ok(())
}
}
#[cfg(not(feature = "win32"))]
{
Err(CrosswinError::invalid_parameter("platform", "Not supported on this platform"))
}
}
/// Wait for the process to exit, with an optional timeout in milliseconds
/// Returns the exit code if the process exits, or None if timeout occurs
pub fn wait_for_exit(&self, _timeout_ms: Option<u32>) -> Result<Option<u32>> {
#[cfg(feature = "win32")]
{
let handle = self.handle.as_ref()
.ok_or_else(|| CrosswinError::invalid_parameter("handle", "Process handle is not available"))?;
unsafe {
let timeout = _timeout_ms.unwrap_or(INFINITE);
let wait_result = WaitForSingleObject(handle.as_handle().as_windows_handle(), timeout);
match wait_result {
WAIT_OBJECT_0 => {
let mut exit_code = 0u32;
GetExitCodeProcess(handle.as_handle().as_windows_handle(), &mut exit_code)
.map_err(|e| CrosswinError::win32(
"GetExitCodeProcess",
e.code().0 as u32,
e.to_string()
))?;
Ok(Some(exit_code))
}
WAIT_TIMEOUT => Ok(None),
_ => Err(CrosswinError::win32(
"WaitForSingleObject",
wait_result.0,
"Wait failed".to_string()
)),
}
}
}
#[cfg(not(feature = "win32"))]
{
Err(CrosswinError::invalid_parameter("platform", "Not supported on this platform"))
}
}
/// Get memory information for the process
pub fn get_memory_info(&self) -> Result<MemoryInfo> {
#[cfg(feature = "win32")]
{
let handle = self.handle.as_ref()
.ok_or_else(|| CrosswinError::invalid_parameter("handle", "Process handle is not available"))?;
unsafe {
let mut counters: PROCESS_MEMORY_COUNTERS = std::mem::zeroed();
counters.cb = std::mem::size_of::<PROCESS_MEMORY_COUNTERS>() as u32;
GetProcessMemoryInfo(
handle.as_handle().as_windows_handle(),
&mut counters,
counters.cb,
)
.map_err(|e| CrosswinError::win32(
"GetProcessMemoryInfo",
e.code().0 as u32,
e.to_string()
))?;
Ok(MemoryInfo {
working_set_size: counters.WorkingSetSize as u64,
peak_working_set_size: counters.PeakWorkingSetSize as u64,
page_file_usage: counters.PagefileUsage as u64,
peak_page_file_usage: counters.PeakPagefileUsage as u64,
})
}
}
#[cfg(not(feature = "win32"))]
{
Err(CrosswinError::invalid_parameter("platform", "Not supported on this platform"))
}
}
/// Get the priority class of the process
pub fn get_priority(&self) -> Result<ProcessPriority> {
#[cfg(feature = "win32")]
{
let handle = self.handle.as_ref()
.ok_or_else(|| CrosswinError::invalid_parameter("handle", "Process handle is not available"))?;
unsafe {
let priority = GetPriorityClass(handle.as_handle().as_windows_handle());
if priority == 0 {
return Err(CrosswinError::win32(
"GetPriorityClass",
windows::Win32::Foundation::GetLastError().0,
"Failed to get priority class".to_string()
));
}
ProcessPriority::from_windows_constant(priority)
.ok_or_else(|| CrosswinError::invalid_parameter(
"priority",
&format!("Unknown priority class: {}", priority)
))
}
}
#[cfg(not(feature = "win32"))]
{
Err(CrosswinError::invalid_parameter("platform", "Not supported on this platform"))
}
}
/// Set the priority class of the process
pub fn set_priority(&self, _priority: ProcessPriority) -> Result<()> {
#[cfg(feature = "win32")]
{
let handle = self.handle.as_ref()
.ok_or_else(|| CrosswinError::invalid_parameter("handle", "Process handle is not available"))?;
unsafe {
SetPriorityClass(
handle.as_handle().as_windows_handle(),
windows::Win32::System::Threading::PROCESS_CREATION_FLAGS(_priority.to_windows_constant())
)
.map_err(|e| CrosswinError::win32(
"SetPriorityClass",
e.code().0 as u32,
e.to_string()
))?;
}
Ok(())
}
#[cfg(not(feature = "win32"))]
{
Err(CrosswinError::invalid_parameter("platform", "Not supported on this platform"))
}
}
/// Returns `true` when the process is still running.
///
/// Polls `WaitForSingleObject` with a zero timeout. Returns `false` if the
/// process has exited or the handle is unavailable.
pub fn is_running(&self) -> bool {
#[cfg(feature = "win32")]
{
let handle = match self.handle.as_ref() {
Some(h) => h,
None => return false,
};
unsafe {
let result = WaitForSingleObject(handle.as_handle().as_windows_handle(), 0);
result == WAIT_TIMEOUT
}
}
#[cfg(not(feature = "win32"))]
{
false
}
}
}