Skip to content

patchguard: Add macro/impl to allow patch disabling #15

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ readme = "README.md"
repository = "https://github.com/mehcode/guerrilla"
documentation = "https://docs.rs/guerrilla"
authors = ["Ryan Leckey <[email protected]>"]
edition = "2021"

[target.'cfg(any(unix, macos))'.dependencies]
libc = "0.2.43"
Expand Down
38 changes: 37 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -181,9 +181,10 @@ fn assemble_jmp_to_address(address: usize, mut relative: isize) -> ([u8; JMP_MAX
/// When this structure is dropped (falls out of scope), the patch will be reverted and the function will return
/// to its original state.
pub struct PatchGuard {
ptr: *mut u8,
pub ptr: *mut u8,
len: usize,
data: [u8; JMP_MAX_SIZE],
patch: [u8; JMP_MAX_SIZE],
}

impl Drop for PatchGuard {
Expand All @@ -194,6 +195,20 @@ impl Drop for PatchGuard {
}
}

impl PatchGuard {
pub fn revert(&self) {
unsafe {
copy_to_protected_address(self.ptr, &self.data[..self.len]);
}
}

pub fn restore(&self) {
unsafe {
copy_to_protected_address(self.ptr, &self.patch[..self.len]);
}
}
}

#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
const UNSAFE_LEADING_BYTES: [u8; 4] = [
0xC3, // ret near
Expand Down Expand Up @@ -238,6 +253,7 @@ macro_rules! define_patch {
ptr: target,
len,
data: original,
patch,
}
}
);
Expand All @@ -254,6 +270,26 @@ define_patch!(patch7(A, B, C, D, E, F, G,));
define_patch!(patch8(A, B, C, D, E, F, G, H,));
define_patch!(patch9(A, B, C, D, E, F, G, H, I,));

#[macro_export]
macro_rules! disable_patch {
($guard:expr, async $($body:tt)*) => {{
$guard.revert();
let result = async { $($body)* }.await;
$guard.restore();
result
}};

($guard:expr, $($body:tt)*) => {{
$guard.revert();
let result = (|| { $($body)* })();
$guard.restore();
result
}};
}

unsafe impl Send for PatchGuard {}
unsafe impl Sync for PatchGuard {}

#[cfg(test)]
#[inline(never)]
fn tiny() {}
Expand Down