-
Notifications
You must be signed in to change notification settings - Fork 408
/
mod.rs
300 lines (257 loc) · 11.2 KB
/
mod.rs
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
use winapi::um::processthreadsapi::{OpenProcess, OpenThread, GetThreadId, SuspendThread, ResumeThread};
use winapi::um::winnt::{ACCESS_MASK, MAXIMUM_ALLOWED, PROCESS_QUERY_INFORMATION,
PROCESS_VM_READ, PROCESS_SUSPEND_RESUME, THREAD_QUERY_INFORMATION, THREAD_GET_CONTEXT, THREAD_ALL_ACCESS,
WCHAR, HANDLE};
use winapi::shared::minwindef::{FALSE, DWORD, MAX_PATH, ULONG};
use winapi::shared::ntdef::PUNICODE_STRING;
use winapi::um::handleapi::{CloseHandle};
use winapi::um::winbase::QueryFullProcessImageNameW;
use winapi::um::winnt::OSVERSIONINFOEXW;
use std::ffi::OsString;
use std::os::windows::ffi::{OsStringExt};
use winapi::shared::ntdef::{PVOID, NTSTATUS, USHORT, VOID, NULL};
pub use read_process_memory::{Pid, ProcessHandle, CopyAddress};
pub type Tid = Pid;
use super::Error;
mod unwinder;
mod symbolication;
mod syscalls_x64;
use self::syscalls_x64::{Syscall, lookup_syscall};
pub use self::unwinder::Unwinder;
pub use self::symbolication::Symbolicator;
pub struct Process {
pub pid: Pid,
pub handle: ProcessHandle
}
#[link(name="ntdll")]
extern "system" {
// using these undocumented api's seems to be the best way to suspend/resume a process
// on windows (using the toolhelp32snapshot api to get threads doesn't seem practical tbh)
// https://j00ru.vexillium.org/2009/08/suspending-processes-in-windows/
fn RtlNtStatusToDosError(status: NTSTATUS) -> ULONG;
fn NtSuspendProcess(process: HANDLE) -> NTSTATUS;
fn NtResumeProcess(process: HANDLE) -> NTSTATUS;
// using GetVersion/GetVersionEx from processthreadsapi returns incorrect information after win 8.1,
// unless we provide a application manifest file, which is currently not fully supported w/ rust
// https://github.com/rust-lang/rfcs/issues/721
// https://stackoverflow.com/questions/17399302/how-can-i-detect-windows-8-1-in-a-desktop-application
// hack around this by using RtlGetVersion instead
fn RtlGetVersion(lpVersionInformation: &mut OSVERSIONINFOEXW) -> NTSTATUS;
fn NtQueryInformationThread(thread: HANDLE, info_class: u32, info: PVOID, info_len: ULONG, ret_len: * mut ULONG) -> NTSTATUS;
fn NtQueryInformationProcess(process: HANDLE, info_class: u32, info: PVOID, info_len: ULONG, ret_len: * mut ULONG) -> NTSTATUS;
fn NtGetNextThread(process: HANDLE, thread: HANDLE, access: ACCESS_MASK, attritubes: ULONG, flags: ULONG, new_thread: *mut HANDLE) -> NTSTATUS;
}
impl Process {
pub fn new(pid: Pid) -> Result<Process, Error> {
// we can't just use try_into_prcess_handle here because we need some additional permissions
unsafe {
let handle = OpenProcess(PROCESS_VM_READ | PROCESS_SUSPEND_RESUME | PROCESS_QUERY_INFORMATION
| THREAD_QUERY_INFORMATION | THREAD_GET_CONTEXT, FALSE, pid);
if handle == (0 as std::os::windows::io::RawHandle) {
return Err(Error::from(std::io::Error::last_os_error()));
}
Ok(Process{pid, handle: ProcessHandle(handle)})
}
}
pub fn handle(&self) -> ProcessHandle { self.handle }
pub fn exe(&self) -> Result<String, Error> {
unsafe {
let mut size = MAX_PATH as DWORD;
let mut filename: [WCHAR; MAX_PATH] = std::mem::zeroed();
let ret = QueryFullProcessImageNameW(self.handle.0, 0, filename.as_mut_ptr(), &mut size);
if ret == 0 {
return Err(std::io::Error::last_os_error().into());
}
Ok(OsString::from_wide(&filename[0..size as usize]).to_string_lossy().into_owned())
}
}
pub fn lock(&self) -> Result<Lock, Error> {
Ok(Lock::new(self.handle)?)
}
pub fn cwd(&self) -> Result<String, Error> {
// TODO: get the CWD.
// seems a little involved: http://wj32.org/wp/2009/01/24/howto-get-the-command-line-of-processes/
// steps:
// 1) NtQueryInformationProcess to get PebBaseAddress, which ProcessParameters
// is at some constant offset (+10 on 32 bit etc)
// 2) ReadProcessMemory to get RTL_USER_PROCESS_PARAMETERS struct
// 3) get CWD from the struct (has UNICODE_DATA object with ptr + length to CWD)
unimplemented!("cwd is unimplemented on windows")
}
pub fn cmdline(&self) -> Result<Vec<String>, Error> {
unsafe {
// figure how much storage we need to allocate for cmdline.
let mut size: ULONG = 0;
NtQueryInformationProcess(self.handle.0, 60, std::ptr::null_mut(), 0, &size as *const _ as *mut _);
if size == 0 {
// the above call always fails (with an error like 'The program issued a command but the
// command length is incorrect.'). It should set the size to how many chars we need to allocate
// . If the size is still 0 though, default to some decently sized number
size = 65536;
}
// Get the commandline
let storage = vec![0_u16; size as usize];
let ret = NtQueryInformationProcess(self.handle.0, 60,
(&storage as &[u16]) as * const _ as * mut _,
size, &size as *const _ as *mut _);
if ret != 0 {
return Err(Error::from(std::io::Error::from_raw_os_error(RtlNtStatusToDosError(ret) as i32)));
}
let unicode: PUNICODE_STRING = (&storage as &[u16]) as * const _ as * mut _;
let chars = std::slice::from_raw_parts((*unicode).Buffer, (*unicode).Length as usize);
let mut ret = Vec::new();
ret.push(String::from_utf16_lossy(chars));
Ok(ret)
}
}
pub fn threads(&self) -> Result<Vec<Thread>, Error> {
let mut ret = Vec::new();
unsafe {
let mut thread: HANDLE = std::mem::zeroed();
while NtGetNextThread(self.handle.0, thread, MAXIMUM_ALLOWED, 0, 0,
&mut thread as *mut HANDLE) == 0 {
ret.push(Thread{ thread: ProcessHandle(thread) });
}
}
Ok(ret)
}
pub fn unwinder(&self) -> Result<unwinder::Unwinder, Error> {
unwinder::Unwinder::new(self.handle.0)
}
pub fn symbolicator(&self) -> Result<Symbolicator, Error> {
Symbolicator::new(self.handle.0)
}
}
impl Drop for Process {
fn drop(&mut self) {
unsafe { CloseHandle(self.handle.0); }
}
}
impl super::ProcessMemory for Process {
fn read(&self, addr: usize, buf: &mut [u8]) -> Result<(), Error> {
Ok(self.handle.copy_address(addr, buf)?)
}
}
#[derive(Eq, PartialEq, Hash, Clone)]
pub struct Thread {
thread: ProcessHandle,
}
impl Thread {
pub fn new(tid: Tid) -> Result<Thread, Error> {
// we can't just use try_into_prcess_handle here because we need some additional permissions
unsafe {
let thread = OpenThread(THREAD_ALL_ACCESS, FALSE, tid);
if thread == (0 as std::os::windows::io::RawHandle) {
return Err(Error::from(std::io::Error::last_os_error()));
}
Ok(Thread { thread: ProcessHandle(thread) })
}
}
pub fn lock(&self) -> Result<ThreadLock, Error> {
ThreadLock::new(self.thread)
}
pub fn id(&self) -> Result<Tid, Error> {
unsafe { Ok(GetThreadId(self.thread.0)) }
}
pub fn active(&self) -> Result<bool, Error> {
// Getting whether a thread is active or not is suprisingly difficult on windows
// we're getting the syscall the thread is doing here, and then checking against a list
// of known waiting syscalls to get this
unsafe {
let mut data = std::mem::zeroed::<THREAD_LAST_SYSCALL_INFORMATION>();
let ret = NtQueryInformationThread(self.thread.0, 21,
&mut data as *mut _ as *mut VOID,
std::mem::size_of::<THREAD_LAST_SYSCALL_INFORMATION>() as u32,
NULL as *mut u32);
// if we're not in a syscall, we're active
if ret != 0 {
return Ok(true);
}
// Get the major/minor/build version of the current windows systems
let mut os_info = std::mem::zeroed::<OSVERSIONINFOEXW>();
os_info.dwOSVersionInfoSize = std::mem::size_of::<OSVERSIONINFOEXW>() as DWORD;
if RtlGetVersion(&mut os_info) != 0 {
return Err(Error::from(std::io::Error::from_raw_os_error(RtlNtStatusToDosError(ret) as i32)));
}
// TODO: blocked IO comes up as active here too (like prompt_toolkit\eventloop\inputhook.py)
// should we also check the IO Pending flag? Or add NTReadFile as 'idle' ?
// resolve the syscallnumber, and check if the thread is waiting
let active = match lookup_syscall(os_info.dwMajorVersion,
os_info.dwMinorVersion,
os_info.dwBuildNumber,
data.syscall_number.into()) {
Some(Syscall::NtWaitForAlertByThreadId) => false,
Some(Syscall::NtWaitForDebugEvent) => false,
Some(Syscall::NtWaitForKeyedEvent) => false,
Some(Syscall::NtWaitForMultipleObjects) => false,
Some(Syscall::NtWaitForMultipleObjects32) => false,
Some(Syscall::NtWaitForSingleObject) => false,
Some(Syscall::NtWaitForWnfNotifications) => false,
Some(Syscall::NtWaitForWorkViaWorkerFactory) => false,
Some(Syscall::NtWaitHighEventPair) => false,
Some(Syscall::NtWaitLowEventPair) => false,
_ => true
};
Ok(active)
}
}
}
impl Drop for Thread {
fn drop(&mut self) {
unsafe { CloseHandle(self.thread.0); }
}
}
pub struct Lock {
process: ProcessHandle
}
impl Lock {
pub fn new(process: ProcessHandle) -> Result<Lock, Error> {
unsafe {
let ret = NtSuspendProcess(process.0);
if ret != 0 {
return Err(Error::from(std::io::Error::from_raw_os_error(RtlNtStatusToDosError(ret) as i32)));
}
}
Ok(Lock{process})
}
}
impl Drop for Lock {
fn drop(&mut self) {
unsafe {
let ret = NtResumeProcess(self.process.0);
if ret != 0 {
panic!("Failed to resume process: {}",
std::io::Error::from_raw_os_error(RtlNtStatusToDosError(ret) as i32));
}
}
}
}
pub struct ThreadLock {
thread: ProcessHandle
}
impl ThreadLock {
pub fn new(thread: ProcessHandle) -> Result<ThreadLock, Error> {
unsafe {
let ret = SuspendThread(thread.0);
if ret.wrapping_add(1) == 0 {
return Err(std::io::Error::last_os_error().into());
}
Ok(ThreadLock{thread})
}
}
}
impl Drop for ThreadLock {
fn drop(&mut self) {
unsafe {
if ResumeThread(self.thread.0).wrapping_add(1) == 0 {
panic!("Failed to resume thread {}", std::io::Error::last_os_error());
}
}
}
}
#[repr(C)]
#[derive(Copy, Clone, Debug)]
struct THREAD_LAST_SYSCALL_INFORMATION {
arg1: PVOID,
syscall_number: USHORT
}