Machine code: Difference between revisions

Enhanced Rust
(Added Rust)
(Enhanced Rust)
Line 817:
This is heavily inspired by https://www.jonathanturner.org/2015/12/building-a-simple-jit-in-rust.html<br />
Hence, only working on Linux (the only other way to disable memory execution protection on other OSes was to use other crates, which kind of defeats the purpose.)
<lang Rust>extern crate libc;
extern crate libc;
 
use std::mem;
use std::ptr::copy;
 
const PAGE_SIZE: usize = 4096;
 
#[cfg(all(
target_os = "linux",
any(target_pointer_width = "32", target_pointer_width = "64")
))]
fn main() {
letuse size = 9std::mem;
use std::memptr;
let bytes: [u8; 9] = [0x8b, 0x44, 0x24, 0x04, 0x03, 0x44, 0x24, 0x08, 0xc3];
 
const PAGE_SIZE let page_size: usize = 4096;
let (bytes, size): (Vec<u8>, usize) = if cfg!(target_pointer_width = "32") {
(
let bytes: [u8; 9] = vec![0x8b, 0x44, 0x24, 0x04, 0x03, 0x44, 0x24, 0x08, 0xc3];,
9,
)
} else {
(vec![0x48, 0x89, 0xf8, 0x48, 0x01, 0xf0, 0xc3], 7)
};
let f: fn(u8, u8) -> u8 = unsafe {
let mut page: *mut libc::c_void = memptr::uninitializednull_mut();
libc::posix_memalign(&mut page, PAGE_SIZEpage_size, size);
libc::mprotect(
page,
Line 836 ⟶ 844:
libc::PROT_EXEC | libc::PROT_READ | libc::PROT_WRITE,
);
let contents: *mut u8 = mem::transmute(page) as *mut u8;
ptr::copy(bytes.as_ptr(), contents, 9);
mem::transmute(contents)
};
 
println!("{}",let return_value = f(7, 12));
println!("Returned value: {}", return_value);
assert_eq!(return_value, 19);
}
 
#[cfg(any(
not(target_os = "linux"),
not(any(target_pointer_width = "32", target_pointer_width = "64"))
))]
fn main() {
println!("Not supported on this platform.");
}
</lang>