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
use std::{
io,
marker::PhantomData,
mem::{self, ManuallyDrop, MaybeUninit},
ops::{Deref, DerefMut, RangeBounds},
os::windows::prelude::AsRawHandle,
ptr, slice,
};
use windows_sys::Win32::System::{
Diagnostics::Debug::{FlushInstructionCache, ReadProcessMemory, WriteProcessMemory},
Memory::{
MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_EXECUTE_READWRITE, PAGE_READWRITE,
VirtualAllocEx, VirtualFreeEx,
},
SystemInformation::GetSystemInfo,
};
use crate::{
process::{BorrowedProcess, Process},
utils,
win_defs::DWORD,
};
/// A owned buffer in the memory space of a (remote) process.
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "process-memory")))]
#[derive(Debug)]
pub struct ProcessMemoryBuffer<'a>(ProcessMemorySlice<'a>);
impl<'a> Deref for ProcessMemoryBuffer<'a> {
type Target = ProcessMemorySlice<'a>;
fn deref(&self) -> &ProcessMemorySlice<'a> {
&self.0
}
}
impl<'a> DerefMut for ProcessMemoryBuffer<'a> {
fn deref_mut(&mut self) -> &mut ProcessMemorySlice<'a> {
&mut self.0
}
}
impl<'a> AsRef<ProcessMemorySlice<'a>> for ProcessMemoryBuffer<'a> {
fn as_ref(&self) -> &ProcessMemorySlice<'a> {
self
}
}
impl<'a> AsMut<ProcessMemorySlice<'a>> for ProcessMemoryBuffer<'a> {
fn as_mut(&mut self) -> &mut ProcessMemorySlice<'a> {
self
}
}
impl<'a> ProcessMemoryBuffer<'a> {
/// Allocates a new buffer of the given length in the given process. Both data and code can be stored in the buffer.
pub fn allocate(process: BorrowedProcess<'a>, len: usize) -> Result<Self, io::Error> {
Self::allocate_code(process, len)
}
/// Allocates a new buffer with the size of a memory page in the given process.
pub fn allocate_page(process: BorrowedProcess<'a>) -> Result<Self, io::Error> {
Self::allocate_code(process, Self::os_page_size())
}
/// Allocates a new data buffer of the given length in the given process.
pub fn allocate_data(process: BorrowedProcess<'a>, len: usize) -> Result<Self, io::Error> {
Self::allocate_with_options(process, len, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)
}
/// Allocates a new data buffer with the size of a memory page in the given process.
pub fn allocate_data_page(process: BorrowedProcess<'a>) -> Result<Self, io::Error> {
Self::allocate_data(process, Self::os_page_size())
}
/// Allocates a new codea buffer of the given length in the given process.
pub fn allocate_code(process: BorrowedProcess<'a>, len: usize) -> Result<Self, io::Error> {
Self::allocate_with_options(
process,
len,
MEM_COMMIT | MEM_RESERVE,
PAGE_EXECUTE_READWRITE,
)
}
/// Allocates a new code buffer with the size of a memory page in the given process.
pub fn allocate_code_page(process: BorrowedProcess<'a>) -> Result<Self, io::Error> {
Self::allocate_code(process, Self::os_page_size())
}
fn allocate_with_options(
process: BorrowedProcess<'a>,
len: usize,
allocation_type: DWORD,
protection: DWORD,
) -> Result<Self, io::Error> {
let ptr = unsafe {
VirtualAllocEx(
process.as_raw_handle().cast(),
ptr::null_mut(),
len,
allocation_type,
protection,
)
};
if ptr.is_null() {
Err(io::Error::last_os_error())
} else {
Ok(unsafe { Self::from_raw_parts(ptr.cast(), len, process) })
}
}
/// Allocates a new buffer with enough space to store a value of type `T` in the given process.
pub fn allocate_for<T>(process: BorrowedProcess<'a>) -> Result<Self, io::Error> {
Self::allocate_data(process, mem::size_of::<T>())
}
/// Allocates a new buffer with enough space to store a value of type `T` in the given process.
pub fn allocate_and_write<T: ?Sized>(
process: BorrowedProcess<'a>,
s: &T,
) -> Result<Self, io::Error> {
let buf = Self::allocate_data(process, mem::size_of_val(s))?;
buf.write_struct(0, s)?;
Ok(buf)
}
/// Constructs a new buffer from the given raw parts.
///
/// # Safety
/// The caller must ensure that the designated region of memory
/// - is valid
/// - was allocated using [`VirtualAllocEx`]
/// - can be deallocated using [`VirtualFreeEx`]
/// - can be read using [`ReadProcessMemory`]
/// - can be written to using [`WriteProcessMemory`]
/// - will not be deallocated by other code
pub const unsafe fn from_raw_parts(
ptr: *mut u8,
len: usize,
process: BorrowedProcess<'a>,
) -> Self {
Self(unsafe { ProcessMemorySlice::from_raw_parts(ptr, len, process) })
}
/// Constructs a new buffer from the given raw parts.
#[must_use]
pub fn into_raw_parts(self) -> (*mut u8, usize, BorrowedProcess<'a>) {
let parts = (self.ptr, self.len, self.process);
self.leak();
parts
}
/// Leaks the buffer and returns the underlying memory slice if the buffer is allocated in the current process.
pub fn into_dangling_local_slice(self) -> Result<&'static mut [u8], Self> {
if self.process.is_current() {
let slice = unsafe { slice::from_raw_parts_mut(self.ptr, self.len) };
self.leak();
Ok(slice)
} else {
Err(self)
}
}
/// Leaks the buffer and returns a [`ProcessMemorySlice`] spanning this buffer.
#[allow(clippy::must_use_candidate)]
pub fn leak(self) -> ProcessMemorySlice<'a> {
let this = ManuallyDrop::new(self);
this.0
}
/// Constructs a new slice spanning the whole buffer.
#[must_use]
pub fn as_slice(&self) -> &ProcessMemorySlice<'a> {
self.as_ref()
}
/// Constructs a new mutable slice spanning the whole buffer.
#[must_use]
pub fn as_mut_slice(&mut self) -> &mut ProcessMemorySlice<'a> {
self.as_mut()
}
/// Frees the buffer.
pub fn free(mut self) -> Result<(), (Self, io::Error)> {
unsafe { self.dangerous_free() }.map_err(|e| (self, e))
}
unsafe fn dangerous_free(&mut self) -> Result<(), io::Error> {
let result = unsafe {
VirtualFreeEx(
self.process.as_raw_handle().cast(),
self.as_ptr().cast(),
0,
MEM_RELEASE,
)
};
if result != 0 || !self.process().is_alive() {
Ok(())
} else {
Err(io::Error::last_os_error())
}
}
/// Returns the memory page size of the operating system.
#[must_use]
pub fn os_page_size() -> usize {
let mut system_info = MaybeUninit::uninit();
unsafe { GetSystemInfo(system_info.as_mut_ptr()) };
unsafe { system_info.assume_init() }.dwPageSize as usize
}
}
impl Drop for ProcessMemoryBuffer<'_> {
fn drop(&mut self) {
let result = unsafe { self.dangerous_free() };
debug_assert!(
result.is_ok(),
"Failed to free process memory buffer: {result:?}"
);
}
}
/// A unowned slice of a buffer in the memory space of a (remote) process.
#[derive(Debug, Clone, Copy)]
pub struct ProcessMemorySlice<'a> {
process: BorrowedProcess<'a>,
ptr: *mut u8,
len: usize,
data: PhantomData<&'a [u8]>,
}
unsafe impl Send for ProcessMemorySlice<'_> {}
impl<'a> ProcessMemorySlice<'a> {
/// Constructs a new slice from the given raw parts.
///
/// # Safety
/// The caller must ensure that the designated region of memory
/// - is valid
/// - was allocated using [`VirtualAllocEx`]
/// - can be read using [`ReadProcessMemory`]
/// - can be written to using [`WriteProcessMemory`]
/// - will live as long as the slice is used
pub const unsafe fn from_raw_parts(
ptr: *mut u8,
len: usize,
process: BorrowedProcess<'a>,
) -> Self {
Self {
ptr,
len,
process,
data: PhantomData,
}
}
/// Returns whether the memory is allocated in the current process.
#[must_use]
pub fn is_local(&self) -> bool {
self.process().is_current()
}
/// Returns whether the memory is allocated in another process.
#[must_use]
pub fn is_remote(&self) -> bool {
!self.is_local()
}
/// Returns the process the buffer is allocated in.
#[must_use]
pub const fn process(&self) -> BorrowedProcess<'a> {
self.process
}
/// Returns the length of the buffer.
#[must_use]
pub const fn len(&self) -> usize {
self.len
}
/// Returns whether the buffer is empty.
#[must_use]
pub const fn is_empty(&self) -> bool {
self.len() == 0
}
/// Copies the contents of this buffer starting from the given offset to the given local buffer.
///
/// # Panics
/// This function will panic if the given offset plus the given buffer length exceeds this buffer's length.
pub fn read(&self, offset: usize, buf: &mut [u8]) -> Result<(), io::Error> {
assert!(offset + buf.len() <= self.len, "read out of bounds");
if self.is_local() {
unsafe {
ptr::copy(self.ptr.add(offset), buf.as_mut_ptr(), buf.len());
}
return Ok(());
}
let mut bytes_read = 0;
let result = unsafe {
ReadProcessMemory(
self.process.as_raw_handle().cast(),
self.ptr.add(offset).cast(),
buf.as_mut_ptr().cast(),
buf.len(),
&raw mut bytes_read,
)
};
if result == 0 {
Err(io::Error::last_os_error())
} else {
assert_eq!(bytes_read, buf.len());
Ok(())
}
}
/// Reads a value of type `T` from this buffer starting from the given offset.
///
/// # Panics
/// This function will panic if the given offset plus the size of the value exceeds this buffer's length.
///
/// # Safety
/// The caller must ensure that the designated region of memory contains a valid instance of type `T` at the given offset.
pub unsafe fn read_struct<T>(&self, offset: usize) -> Result<T, io::Error> {
let mut uninit_value = MaybeUninit::<T>::uninit();
self.read(offset, unsafe {
slice::from_raw_parts_mut(uninit_value.as_mut_ptr().cast(), mem::size_of::<T>())
})?;
Ok(unsafe { uninit_value.assume_init() })
}
/// Copies the contents of the given local buffer to this buffer at the given offset.
///
/// # Panics
/// This function will panic if the given offset plus the size of the local buffer exceeds this buffer's length.
pub fn write(&self, offset: usize, buf: &[u8]) -> Result<(), io::Error> {
assert!(offset + buf.len() <= self.len, "write out of bounds");
if self.is_local() {
unsafe {
ptr::copy(buf.as_ptr(), self.ptr.add(offset), buf.len());
}
return Ok(());
}
let mut bytes_written = 0;
if buf.is_empty() {
// This works around a discrepancy between Wine and actual Windows.
// On Wine, a 0 sized write fails, on Windows this suceeds. Will file as bug soon.
return Ok(());
}
let result = unsafe {
WriteProcessMemory(
self.process.as_raw_handle().cast(),
self.ptr.add(offset).cast(),
buf.as_ptr().cast(),
buf.len(),
&raw mut bytes_written,
)
};
if result == 0 {
Err(io::Error::last_os_error())
} else {
assert_eq!(bytes_written, buf.len());
Ok(())
}
}
/// Writes a value of type `T` to this buffer at the given offset.
///
/// # Panics
/// This function will panic if the given offset plus the given buffer length exceeds this buffer's length.
pub fn write_struct<T: ?Sized>(&self, offset: usize, s: &T) -> Result<(), io::Error> {
self.write(offset, unsafe {
slice::from_raw_parts(ptr::from_ref(s).cast::<u8>(), mem::size_of_val(s))
})
}
/// Returns a pointer to the start of the buffer.
///
/// # Note
/// The returned pointer is only valid in the target process.
#[must_use]
pub const fn as_ptr(&self) -> *mut u8 {
self.ptr
}
/// Returns a slice of this buffer.
#[must_use]
pub fn slice(&self, bounds: impl RangeBounds<usize>) -> Self {
let range = utils::range_from_bounds(self.ptr as usize, self.len, &bounds);
Self {
process: self.process,
ptr: range.start as *mut _,
len: range.len(),
data: PhantomData,
}
}
/// Constructs a new slice spanning the whole buffer.
#[must_use]
pub fn as_local_slice(&self) -> Option<&[u8]> {
if self.is_local() {
Some(unsafe { slice::from_raw_parts(self.ptr, self.len) })
} else {
None
}
}
/// Constructs a new mutable slice spanning the whole buffer.
#[must_use]
pub fn as_local_slice_mut(&mut self) -> Option<&mut [u8]> {
if self.is_local() {
Some(unsafe { slice::from_raw_parts_mut(self.ptr, self.len) })
} else {
None
}
}
/// Flushes the CPU instruction cache for the whole buffer.
/// This may be necesary if the buffer is used to store dynamically generated code. For details see [`FlushInstructionCache`].
pub fn flush_instruction_cache(&self) -> Result<(), io::Error> {
let result = unsafe {
FlushInstructionCache(
self.process.as_raw_handle().cast(),
self.as_ptr().cast(),
self.len,
)
};
if result == 0 {
Err(io::Error::last_os_error())
} else {
Ok(())
}
}
}