How can I execute hex opcodes directly in Rust?

Here is how you can do it in a const fashion:

#[cfg(target_os = "linux")]
fn hello_world () -> !
{
    mod namespaced {
        // #[link(section = ".text")]
        #[link_section = ".text"] /* EDIT */
        #[no_mangle]
        static hello_world: [u8; 38] =
            *b"\x6a\x01\x5f\x89\xf8\x6a\x0d\x5a\xeb\x0a\x5e\x0f\x05\x6a\x3c\x58\xff\xcf\x0f\x05\xe8\xf1\xff\xff\xff\x48\x65\x6c\x6c\x6f\x20\x77\x6f\x72\x6c\x64\x21\x0a"
        ;
    }
    extern "C" {
        fn hello_world () -> !;
    }
    unsafe {
        hello_world()
    }
}
  • (The byte code calls write(1, "Hello, World!\n", 13) and then exit(0) so that it effectively never returns)

  • Playground (EDIT: fix the link section annotation as show in this thread)

6 Likes