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
655 stars 57 forks source link

Do ZST `Box`es violate provenance monotonicity? #529

Closed joshlf closed 2 weeks ago

joshlf commented 1 month ago

(Writing on my phone; apologies for the lack of formatting.)

Per the Box module-level docs:

For zero-sized values, the Box pointer still has to be valid for reads and writes and sufficiently aligned. In particular, casting any aligned non-zero integer literal to a raw pointer produces a valid pointer, but a pointer pointing into previously allocated memory that since got freed is not valid. The recommended way to build a Box to a ZST if Box::new cannot be used is to use ptr::NonNull::dangling.

I'm trying to interpret "pointer pointing into previously allocated memory." IIUC, an integer whose address is the same as previously-allocated memory should be fine, so what really distinguishes these two cases is whether or not the pointer in question has provenance for the previously-freed allocation.

However, this implies that Box violates provenance monotonicity: an operation with a provenance-free pointer (one cast from a bare integer) is sound, while the same operation with a provenance-carrying integer is not.

Am I understanding this correctly?

RalfJung commented 1 month ago

Good catch! That's an outdated copy of the pointer validity docs that hasn't been updated for https://github.com/rust-lang/rust/issues/117945.

RalfJung commented 2 weeks ago

Funny... the PR with the "fixes" annotation got merged a week ago, but now @saethlin pushing this somewhere led to the issue actually getting closed...

saethlin commented 2 weeks ago

Yeah... that was me updating my fork. There's some kind of GitHub bug here.

RalfJung commented 2 weeks ago

I think it might be a permission thing. bors doesn't have permissions to close issues in this repo, but you do.