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
use std::mem::{self, MaybeUninit};
use std::slice;
pub use bytemuck::Pod;
use super::ffi;
#[derive(Debug)]
pub enum Error {
FailedRead,
}
pub type Result<T> = std::result::Result<T, Error>;
pub type Address = u64;
#[derive(Debug)]
pub struct Process(pub(crate) u64);
impl Process {
pub fn read<T: Pod>(&self, addr: Address) -> Result<T> {
unsafe {
let mut buf = MaybeUninit::uninit();
self.read_into_buf(
addr,
slice::from_raw_parts_mut(buf.as_mut_ptr() as *mut u8, mem::size_of::<T>()),
)?;
Ok(buf.assume_init())
}
}
pub fn module(&self, name: &str) -> Option<Address> {
unsafe {
match ffi::process_get_module_address(self.0, name.as_ptr() as u32, name.len() as u32) {
0 => None,
n => Some(n),
}
}
}
pub fn read_into_buf(&self, addr: Address, buf: &mut [u8]) -> Result<()> {
unsafe {
(ffi::process_read(self.0, addr, buf.as_mut_ptr() as u32, buf.len() as u32) != 0)
.then_some(())
.ok_or(Error::FailedRead)
}
}
pub fn read_cstr(&self, base: u64) -> Result<String> {
const MAX_STR_LEN: usize = 256;
let mut buf = vec![0u8; MAX_STR_LEN];
unsafe {
(ffi::process_read(
self.0,
base,
buf.as_mut_ptr() as u32,
MAX_STR_LEN as u32 - 1,
) != 0)
.then_some(())
.ok_or(Error::FailedRead)?;
}
buf.truncate(buf.iter().position(|&x| x == 0).expect("string too long") + 1);
let cstr = std::ffi::CString::from_vec_with_nul(buf).expect("invalid unicode");
Ok(cstr.to_string_lossy().to_string())
}
}
impl Drop for Process {
fn drop(&mut self) {
unsafe {
ffi::process_detach(self.0);
}
}
}