Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ch. 20: Address soundness issues and introduce Miri #4062

Merged
merged 6 commits into from
Nov 6, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Ch. 20: Fix safety handling in the static mut example
- Add `SAFETY` documentation on the unsafe function and comments on the
  unsafe invocation in the code samples.
- Discuss the soundness issues in more depth and explain the idiomatic
  use of those `SAFETY` comments.
  • Loading branch information
chriskrycho committed Nov 6, 2024
commit 48d0b7686bf65b7325e20c817c57b559075fe629
15 changes: 8 additions & 7 deletions listings/ch20-advanced-features/listing-20-10/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
static mut COUNTER: u32 = 0;

fn add_to_count(inc: u32) {
unsafe {
COUNTER += inc;
}
/// SAFETY: Calling this from more than a single thread at a time is undefined
/// behavior, so you *must* guarantee you only call it from a single thread at
/// a time.
unsafe fn add_to_count(inc: u32) {
COUNTER += inc;
}

fn main() {
add_to_count(3);

unsafe {
println!("COUNTER: {COUNTER}");
// SAFETY: This is only called from a single thread in `main`.
add_to_count(3);
println!("COUNTER: {}", COUNTER);
}
}
10 changes: 9 additions & 1 deletion src/ch20-01-unsafe-rust.md
Original file line number Diff line number Diff line change
Expand Up @@ -402,7 +402,15 @@ As with regular variables, we specify mutability using the `mut` keyword. Any
code that reads or writes from `COUNTER` must be within an `unsafe` block. This
code compiles and prints `COUNTER: 3` as we would expect because it’s single
threaded. Having multiple threads access `COUNTER` would likely result in data
races.
races, so it is undefined behavior. Therefore, we need to mark the entire
function as `unsafe`, and document the safety limitation, so anyone calling the
function knows what they are and are not allowed to do safely.

Whenever we write an unsafe function, it is idiomatic to write a comment
starting with `SAFETY` and explaining what the caller needs to do to call the
function safely. Likewise, whenever we perform an unsafe operation, it is
idiomatic to write a comment starting with `SAFETY` to explain how the safety
rules are upheld.

With mutable data that is globally accessible, it’s difficult to ensure there
are no data races, which is why Rust considers mutable static variables to be
Expand Down