NewsCrawler.org

Pointer Provenance in Rust vs C++

This is a personal exploration of pointer provenance in Rust, a concept the author found hard to picture. Provenance[1] is the compiler's record of which memory allocation a pointer was derived from, and it is not stored as a separate field next to the address. In a sample compiled with -O2, Clang returns 1 without rereading x, because it assumes a pointer not derived from x cannot point to x.

The author inspects this in LLVM IR[2], where the compiler compares the root origins of pointers to decide whether two pointers can touch the same memory. In C++, casting &x to an integer exposes its address, so anyone may rebuild a pointer to x, and the compiler gives up the optimization. In Rust, addr() reads the address without exposing provenance, but in the author's test the optimization was still given up, as in C++.

with_addr() lets a pointer hold flag bits in its unused low bits while keeping the original provenance, which is useful in lock-free data structures. A tagged pointer must not be dereferenced while it is misaligned for u32, since that is undefined behavior[3]. The legacy approach of casting to usize and back still runs, but Miri[4] warns about the integer-to-pointer cast.

Read the original sofiabelen.github.ioDiscussion

Sources

Published: First seen: Читать по-русски

Open as a page