rust-lang / unsafe-code-guidelines

Forum for discussion about what unsafe code can and can't do
https://rust-lang.github.io/unsafe-code-guidelines
Apache License 2.0
659 stars 57 forks source link

Validity invariant of places #418

Open RalfJung opened 1 year ago

RalfJung commented 1 year ago

Currently, places (the things place expressions evaluate to, which only exist as intermediate concept during the execution of a statement) have an effective validity invariant: they are dereferenceable and aligned (but their contents can be anything). We do not distinguish "safe" and "unsafe" places or anything like that, this applies to all of them.

That's why addr_of!(*ptr) is UB if the pointer dangles or is unaligned.

There's not a ton of strong motivation for this, so -- is that really the semantics we want? https://github.com/rust-lang/unsafe-code-guidelines/issues/319 discusses this to some extend but then diverged a lot into surface language design questions that boil down to "how can we avoid even using place expressions for raw pointer arithmetic".

The design space I see here has several dimensions:

I don't see a good motivation for the 2nd point: even if we don't impose alignment/dereferenceability on places, we still impose it on references, so we know that places created via *reference are aligned and dereferenceable.

My inclination would hence be to simply drop the requirement entirely. This does however open a new question which is currently moot: when doing a place projection, which is basically an offset operation, what are the rules for that? The obvious answer is to say "same as ptr.offset", meaning the question is tracked in #350 and https://github.com/rust-lang/unsafe-code-guidelines/issues/93, but in principle we could also say "same as ptr.wrapping_offset". The latter would have the advantage of making place expressions based on raw pointers entirely safe, only the place-to-value coercion would have to be unsafe.

bjorn3 commented 1 year ago

How would the right alignment to use for loads and stored in backends be determined if the requirement for places to be aligned is dropped? Would it for example the alignment requirement instead apply to typed copies of the value stored behind the place instead of the place itself?

RalfJung commented 1 year ago

Places still have to be aligned when a load or store happens, or when the place is converted to a reference.