How does provenance work for hard coded addresses?

In Rust (and really C/C++ too but they use different terminology) there is a concept of pointer provenance. Generally it is safe to:

  • Take a pointer to some existing allocation
  • Do math on the pointer that keeps it within the bounds of that allocation
  • Dereference the pointer

But doing math on it that puts it outside the original allocation and then dereferencing it is UB. But sometimes when doing low level programming you want to hard code that a particular memory address is used for something. The obvious way to write that is something like:

let p = 0xDEADBEEF as *mut i32;

But then can I dereference p? There may never be any explicit allocation done from Rust's perspective at that address. Even if there were, if we don't want the overhead of explicitly storing a pointer when we already know the address, we would probably do the above to make the pointer "from scratch" fairly often rather than letting the provenance be transferred by copying the pointer we got from the allocation function. Is this allowed in Rust's memory model at all? To be clear I'm not asking about lifetime, for purposes of this discussion we can assume everything at the address is 'static.

The entire model is not completely settled yet, but you can

let p = with_exposed_provenance::<i32>(0xDEADBEEF).cast_mut();

to let Miri know that it's "foreign memory".

You can read about the exposed provenance concept here.

3 Likes

You might want to read this article too.

1 Like

If possible it can be nice to let Rust just not think about addresses for it, by doing some sort of

#[some_linker_magic_to_put_this_at(0xDEADBEEF)]
extern static mut WHATEVER_IT_IS: i32;

Then it's a "normal" static to the rust code, which never needs to think about its address as any more special than any other externally-defined static.

(Though TBH I don't actually know how to spell that magic.)

3 Likes

You can have a linker script define the value of a symbol. I don't think you can do it on the rust side though.

2 Likes