Skip to content

Instantly share code, notes, and snippets.

@alexcrichton
Last active October 14, 2021 21:34
Show Gist options
  • Save alexcrichton/320af45116d1d52a5802a9254c0ea067 to your computer and use it in GitHub Desktop.
Save alexcrichton/320af45116d1d52a5802a9254c0ea067 to your computer and use it in GitHub Desktop.
use std::ptr;
const SIZE: usize = 50 * 1024 * 1024;
fn main() {
unsafe {
let ptr = libc::mmap(
ptr::null_mut(),
SIZE,
libc::PROT_READ | libc::PROT_WRITE,
libc::MAP_PRIVATE | libc::MAP_ANONYMOUS,
-1,
0,
);
assert!(
ptr != libc::MAP_FAILED,
"failed to mmap: {}",
std::io::Error::last_os_error()
);
let start = std::time::Instant::now();
let rc = libc::mprotect(ptr, SIZE, libc::PROT_READ | libc::PROT_EXEC);
assert!(
rc == 0,
"failed to mprotect: {}",
std::io::Error::last_os_error()
);
println!("mprotect with no touched pages {:?}", start.elapsed());
let ptr = libc::mmap(
ptr::null_mut(),
SIZE,
libc::PROT_READ | libc::PROT_WRITE,
libc::MAP_PRIVATE | libc::MAP_ANONYMOUS,
-1,
0,
);
assert!(
ptr != libc::MAP_FAILED,
"failed to mmap: {}",
std::io::Error::last_os_error()
);
for i in 0..SIZE / 4096 {
*(ptr as *mut u8).add(i * 4096) = 1;
}
let start = std::time::Instant::now();
let rc = libc::mprotect(ptr, SIZE, libc::PROT_READ | libc::PROT_EXEC);
assert!(
rc == 0,
"failed to mprotect: {}",
std::io::Error::last_os_error()
);
println!("mprotect with touched pages {:?}", start.elapsed());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment