Skip to content

Commit

Permalink
Merge pull request #72 from james7132/fix-iter-ub
Browse files Browse the repository at this point in the history
Replace non-atomic load with an atomic one
  • Loading branch information
Amanieu authored Feb 20, 2024
2 parents 0c2163c + 0f6c705 commit 7db3f74
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
10 changes: 10 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,13 @@ jobs:
- run: cargo fmt -- --check
- run: cargo test
- run: cargo bench
miri:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install Rust
run: rustup toolchain install nightly --component miri && rustup default nightly
- run: cargo miri test
env:
MIRIFLAGS: -Zmiri-strict-provenance -Zmiri-symbolic-alignment-check -Zmiri-disable-isolation
RUSTFLAGS: ${{ env.RUSTFLAGS }} -Z randomize-layout
25 changes: 23 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,8 +216,7 @@ impl<T: Send> ThreadLocal<T> {
}
unsafe {
let entry = &*bucket_ptr.add(thread.index);
// Read without atomic operations as only this thread can set the value.
if (&entry.present as *const _ as *const bool).read() {
if entry.present.load(Ordering::Relaxed) {
Some(&*(&*entry.value.get()).as_ptr())
} else {
None
Expand Down Expand Up @@ -606,6 +605,28 @@ mod tests {
assert_eq!(vec![1, 2, 3], v);
}

#[test]
fn miri_iter_soundness_check() {
let tls = Arc::new(ThreadLocal::new());
let _local = tls.get_or(|| Box::new(1));

let tls2 = tls.clone();
let join_1 = thread::spawn(move || {
let _tls = tls2.get_or(|| Box::new(2));
let iter = tls2.iter();
for item in iter {
println!("{:?}", item);
}
});

let iter = tls.iter();
for item in iter {
println!("{:?}", item);
}

join_1.join().ok();
}

#[test]
fn test_drop() {
let local = ThreadLocal::new();
Expand Down

0 comments on commit 7db3f74

Please sign in to comment.