Do function pointers require provenance? ⁠fn() -> usize -> fn()

This snippet currently triggers Miri:

It complains (kinda justified) that we just acquired a pointer with no provenance. But do function pointers really need provenance? They’re always const, so I don’t think we miss any optimizations that way.

I don't think fn() is required to point to a constant function in the compiled binary.

You can certainly dynamically build a function at run time (though you'd probably want to use extern "C" for that since Rust's ABI isn't stable)

1 Like

Could you explain how this would work? This could be useful for a project I'm working on.

"build" was probably a misleading way for me to put that. I just mean on most modern processors you can copy some machine code to a block of executable memory, cast the address to a function pointer, and call it. Assuming your dynamic machine code and the code calling the function pointer agree on ABI level details it will work just how a normally compiled function would

1 Like

Currently there is an open issue in Unsafe Code Guidelines repository about whether function pointers need provenance.

6 Likes

You also need to tell the processor that you modified its instructions, otherwise it may execute whatever data was in that part of memory at some point in the past, because it didn't know that it shouldn't just use its cache of whatever it had read before.

The standard function for doing that is usually __clear_cache

2 Likes