forge/patch.rs
1use sys::patch::{Patch as SysPatch, *};
2
3/// A memory patch that can be enabled or disabled at runtime.
4/// When enabled, the patch will overwrite the target bytes with the patch bytes.
5/// When disabled, the original bytes will be restored.
6///
7/// The patch will be automatically disabled and cleaned up when dropped.
8pub struct Patch {
9 inner: SysPatch,
10}
11
12impl Patch {
13 /// Creates a new patch at the given address with the given patch bytes.
14 /// The patch is enabled if `enable` is true, otherwise it is created in a disabled state.
15 pub fn new(addr: u32, bytes: &[u8], enable: bool) -> Self {
16 Self {
17 inner: unsafe { forge_patch_create(addr, bytes.as_ptr().cast(), bytes.len() as u32, enable) },
18 }
19 }
20
21 /// Gets the address that this patch targets.
22 pub fn addr(&self) -> u32 {
23 self.inner.addr
24 }
25
26 /// Gets the length of this patch in bytes.
27 pub fn len(&self) -> u32 {
28 self.inner.size
29 }
30
31 /// Returns `true` if this patch is currently enabled.
32 pub fn enabled(&self) -> bool {
33 self.inner.enabled
34 }
35
36 /// Enables this patch, applying the patch bytes to the target address.
37 pub fn enable(&mut self) {
38 unsafe {
39 forge_patch_enable(&mut self.inner);
40 }
41 }
42
43 /// Disables this patch, restoring the original bytes at the target address.
44 pub fn disable(&mut self) {
45 unsafe {
46 forge_patch_disable(&mut self.inner);
47 }
48 }
49
50 /// Returns a byte slice of the patch bytes that will be written when this patch is enabled.
51 pub fn patch_bytes(&self) -> &[u8] {
52 unsafe { core::slice::from_raw_parts(self.inner.patch_bytes.cast(), self.inner.size as usize) }
53 }
54
55 /// Returns a byte slice of the original bytes that are overwritten when this patch is enabled.
56 pub fn original_bytes(&self) -> &[u8] {
57 unsafe { core::slice::from_raw_parts(self.inner.original_bytes.cast(), self.inner.size as usize) }
58 }
59}
60
61impl core::ops::Drop for Patch {
62 fn drop(&mut self) {
63 unsafe {
64 forge_patch_destroy(&mut self.inner);
65 }
66 }
67}