I am experimenting with building a JIT that executes x86 instructions that the program produces. I think I have created a valid slice of x86 byte code that should print "Hello World", but I am not sure how to call it.
I am casting a pointer to the start of a vector to a void function and calling it:
fn main() {
let msg: &[u8] = b"Hello World\0";
let mut byte_codes: Vec<u8> = Vec::with_capacity(1000);
// Move width into edx
byte_codes.extend_from_slice(&[0xba, msg.len() as u8, 0, 0, 0]);
// Msg to write
byte_codes.push(0xb9);
byte_codes.extend_from_slice(&(msg.as_ptr() as u64).to_be_bytes());
// File descriptor and sys call
byte_codes.extend_from_slice(&[0xbb, 0x01, 0, 0, 0]);
byte_codes.extend_from_slice(&[0xb8, 0x04, 0, 0, 0]);
// Sys call
byte_codes.extend_from_slice(&[0xcd, 0x80]);
// Return
byte_codes.push(0xc3);
let func_ptr = byte_codes.as_ptr();
unsafe {
let func: fn() -> () = func_ptr.cast::<fn() -> ()>().read();
func();
}
}
Executing this returns:
error: process didn't exit successfully: `target\debug\run-bytecode.exe` (exit code: 0xc0000005, STATUS_ACCESS_VIOLATION)
Removing all bytecode except the return call also leads to the same error.
I'm not sure what that error means. Is there a issue with the bytecode or is my function casting incorrect? How can I get it printing "Hello World"?