book
book copied to clipboard
Ch. 20: Address soundness issues and introduce Miri
[!IMPORTANT] This cannot be merged as is, because it uses new syntax from Rust 1.82.0 (out in about two weeks!), so we cannot merge till we have updated to require 1.82.0, but in the meantime this PR gives us a handy way to get eyes on it so we can validate that everything it says is correct.
This makes three major changes to the unsafe section:
-
It uses the newly-stabilized[^stabilized]
&rawborrow operator to more safely get raw pointers, with&raw constand&raw mutrespectively. These provide a safe(r) way of getting raw pointers. These are part of the Rust effort to handle provenance correctly and thereby make unsafe safer and easier to work with—and while we’re not going to get into those details, this is definitely a better way to work than the castas *const i32andas *mut i32. -
It updates the
static mut COUNTERexample to use anunsafe fninstead of a safe function around anunsafeblock, since it is necessary for the caller to guarantee that the function is not called from multiple threads. To make the existing safe function actually safe, it would need to introduce some kind of locking mechanism, I think. Leaving it as an unsafe function gives us a nice opportunity to include// SAFETY: …comments, though, and thus to teach a bit more about idiomatic authoring and usage of unsafe code. -
It introduces Miri at the end of the section! I used Miri to investigate some of the issues folks had flagged up, and credit to the Miri team: it is very easy to use. The main thing I think we should think about here is whether we need more prose or explanation around installing nightly Rust.
[^stabilized]: as of Rust 1.82.0, arriving 2024/10/16