Skip to content

Instantly share code, notes, and snippets.

@joshlf
Created September 21, 2017 22:39
Show Gist options
  • Save joshlf/d4af584e4722aebe7f3dfc6050dbbf3d to your computer and use it in GitHub Desktop.
Save joshlf/d4af584e4722aebe7f3dfc6050dbbf3d to your computer and use it in GitHub Desktop.
A function to test that invalid accesses result in SIGSEGV
#[cfg(target_os = "linux")]
unsafe fn test_no_perms(ptr: *mut u8, read: bool, old_perm: Perm) {
use libc::{c_int, mprotect, signal, SIGSEGV, size_t};
static mut got_signal: bool = false;
static mut __ptr: *mut u8 = 0 as *mut _;
// reset got_signal back to false after previous call
let gs_signal = &mut got_signal;
*gs_signal = false;
let ptr_ptr = &mut __ptr;
*ptr_ptr = ptr;
{
type HandlerTy = unsafe extern "C" fn(c_int);
unsafe extern "C" fn handler(signum: c_int) {
libc::exit(123);
eprintln!("foobar");
let gs_signal = &mut got_signal;
*gs_signal = true;
mprotect(*__ptr as *mut _, 4096, PROT_READ_WRITE_EXEC);
}
signal(libc::SIGSEGV, handler as HandlerTy as usize);
if read {
test::black_box(ptr::read_volatile(ptr));
} else {
test::black_box(ptr::write_volatile(ptr, 0));
}
mprotect(ptr as *mut _, 1, old_perm);
}
assert!(got_signal, "didn't get SIGSEGV");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment