Jump to content

Machine code: Difference between revisions

Added Rust
(Add Swift)
(Added Rust)
Line 813:
 
(scheme-free-code code)</lang>
 
=={{header|Rust}}==
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;
 
use std::mem;
use std::ptr::copy;
 
const PAGE_SIZE: usize = 4096;
 
fn main() {
let size = 9;
let bytes: [u8; 9] = [0x8b, 0x44, 0x24, 0x04, 0x03, 0x44, 0x24, 0x08, 0xc3];
let f: fn(u8, u8) -> u8 = unsafe {
let mut page: *mut libc::c_void = mem::uninitialized();
libc::posix_memalign(&mut page, PAGE_SIZE, size);
libc::mprotect(
page,
size,
libc::PROT_EXEC | libc::PROT_READ | libc::PROT_WRITE,
);
let contents: *mut u8 = mem::transmute(page);
copy(bytes.as_ptr(), contents, 9);
mem::transmute(contents)
};
 
println!("{}", f(7, 12));
}
</lang>
 
=={{header|Scala}}==
Cookies help us deliver our services. By using our services, you agree to our use of cookies.