How can I execute hex opcodes directly in Rust?

Have you considered writing raw asm files, then compiling them and linking to them via build.rs? It would avoid any issues with the Rust calling convention, and undefined behavior within Rust if you interact with the raw ASM purely through a C api.

I believe https://github.com/briansmith/ring uses this strategy for some of the crypto operations which need to be constant-time, but I don't know the details of how that works.


With that said, @chrisd's version of your snippet should work, assuming that you write correct bytecode to implement the C calling convention for the platform you're targeting. You might run into issues with alignment or OS security features - I don't know enough about those to say whether you would.

For safety, I would highly recommend wrapping it in a target-specific cfg block.

fn do_thing() {
    #[cfg(all(target_arch = "x86_64", target_os = "linux"))]
    {
        // call into asm code
    }
    #[cfg(not(all(target_arch = "x86_64", target_os = "linux")))]
    {
        // panic or fallback
    }
}

In const it's complaining because it will try to turn those bytes into a C-function-ptr at compile time, and the compiler assumes that isn't even allowed (since it very well might not be, even with a correct function).