Stream: t-lang/wg-unsafe-code-guidelines

Topic: pointer comparisons

Wanja Hentze (May 07 2019 at 14:31, on Zulip):

So I do realize that, in C, comparing pointers that are not from the same allocation is undefined behavior.
In Rust, arbitrary pointers can be compared safely using either Eq or Ord.
But if I run that code in miri, I get an error.
Does that mean that comparisons of unrelated pointers are secretly UB? Or is this just something miri can not reason about?

Wanja Hentze (May 07 2019 at 14:35, on Zulip):

More concretely, should I be able to write the following function without UB?
fn is_in_bounds(ptr: *const T, slice: *const [T])

RalfJ (May 07 2019 at 20:31, on Zulip):

But if I run that code in miri, I get an error.

That is a limitation of Miri, not an indication of UB. The issues for that is

RalfJ (May 07 2019 at 20:32, on Zulip):

ptr comparison between any two pointers is safe in Rust.

RalfJ (May 07 2019 at 20:32, on Zulip):

there are some thorny questions around specifying that precisely though :/

Elichai Turkel (Mar 13 2020 at 09:58, on Zulip):

I have a question in the same line of thought.
Because in rust we disallow this: let a: [u8]; let ptr1: *const u8 = &a[0]; let a1 = unsafe {*ptr1.offset(1)}; (we require you to get a pointer to the whole slice).
do we even promise that let a: [u8]; let ptr1: *const u8 = a.as_ptr().wrapping_add(1); let ptr2 = &a[1]; assert_eq!(ptr1, ptr2);?
I thought about that while reading which in their he calculates pointer offsets a lot and I wonder if we promise that two pointers to the same "object" are always equivalent even if you obtain them in different ways, and they have different validity requirements.

RalfJ (Mar 15 2020 at 10:40, on Zulip):

uh wow talk about stream necromancy^^

RalfJ (Mar 15 2020 at 10:41, on Zulip):

we've implemented ptr-int-casts since the original qustion, so basically everything about it changed

RalfJ (Mar 15 2020 at 10:42, on Zulip):

@Elichai Turkel that's a good question, and I would formally state it has "how much does pointer provenance affect pointer comparison"

RalfJ (Mar 15 2020 at 10:42, on Zulip):

I would hope that the stacked borrow tag does not affect comparison, and I think that reflects what LLVM dos, but since LLVM is very unsound around ptr-int casts, that's hard to say for sure.

RalfJ (Mar 15 2020 at 10:43, on Zulip):

other provenance, like the original allocation the pointer "comes from", certainly can affect ptr comparison in LLVM

RalfJ (Mar 15 2020 at 10:43, on Zulip):

that should mean that casting ptrs to integers and comparing those is actually a different operation than comparing the pointers. unfortunately LLVM will optimize the former to the latter. which is wrong (part of the unsoundness I mentioned).

Last update: Mar 30 2020 at 23:45UTC