Since f() as a foreign function uses the memory pointed by buf (but this information is hard for rustc to infer because f takes no argument) and assumes the memory is correctly initialized there, it would be really bad if rustc can reorder buf[0] = 42 after the function call. Is there any guarantee that memory reordering won't happen around an FFI call?
Not sure how it's possible for f to use the memory on foreign stack, to be honest. Anyway, I've made a little test (indexing replaced with get_mut, so that there's no panic in the assembly):
Because buf is an exclusive reference, it is UB for any code (including foreign code) to access the buffer in any way except through the buf local variable, or something derived from it.
If you use &[Cell<u8>] instead, and pass the buffer over the FFI barrier somewhere, the compiler appears to do the right thing:
The assembly then looks reasonable to me, but I don't know what in this code tells rustc not to do the elision. I know ptr::write_volatile is a thing but I am just wondering if it is necessary for the case.
When it comes to safety of something like this, looking at the assembly is not particularly illuminating. Since if your code has undefined behavior, the compiler is allowed to compile your code into literally anything, which includes it doing what you wanted (but changing its mind in a week!).
You need to make sure that the kind of reference you are using permits this kind of access. A &[Cell<u8>] is one such reference type. Raw pointers is another. Check out the table here for a list of the guarantees in play.
That link is useful! it's not clear to me that it is UB if the foreign function takes a pointer argument, I think this is something allowed by Stacked Borrows?