use std::mem::MaybeUninit;
use sync::*; // pub(crate) use std::sync::atomic::{AtomicPtr, Ordering, fence};
mod sync;
struct Stack<T> {
head: AtomicPtr<Node<T>>,
}
impl<T> Drop for Stack<T> {
fn drop(&mut self) {
// todo!()
}
}
unsafe impl<T: Send> Send for Stack<T> {}
unsafe impl<T> Sync for Stack<T> {}
struct Node<T> {
data: MaybeUninit<T>,
next: *mut Node<T>,
}
impl<T> Stack<T> {
fn new() -> Self {
Self {
head: AtomicPtr::new(std::ptr::null_mut()),
}
}
fn push(&self, data: T) {
let node = Box::into_raw(Box::new(Node {
data: MaybeUninit::new(data),
next: std::ptr::null_mut(),
}));
let mut head = self.head.load(Ordering::Relaxed);
loop {
unsafe { &mut *node }.next = head;
match self
.head
.compare_exchange_weak(head, node, Ordering::Release, Ordering::Relaxed)
{
Ok(_) => break,
Err(actual) => {
head = actual;
}
}
}
}
fn pop(&self) -> Option<T> {
let mut head = self.head.load(Ordering::Relaxed);
// this fence prevents the above load from loading a detached head...
// because a detached head is deallocated and we might dereference it to reach `next`.
fence(Ordering::SeqCst); // a SC fence here (to synchronize with the below fence)
loop {
if head.is_null() {
return None;
}
let next = unsafe { &*head }.next;
match self
.head
.compare_exchange_weak(head, next, Ordering::Relaxed, Ordering::Relaxed)
{
Ok(head) => {
fence(Ordering::SeqCst); // a SC fence here
let data = unsafe { (&mut *head).data.assume_init_read() };
drop(unsafe { Box::from_raw(head) });
return Some(data);
}
Err(actual) => {
head = actual;
}
}
}
}
}
some things that could be wrong and are confusing:
mixing memory orderings with SeqCst, should I avoid this? Is the behavior unpredictable?
Does SeqCst Ordering act correctly on the load? (an Acquire fence is placed below the load, so I just placed the SeqCst fence below as well.)
Can the job be done with just a single SeqCst fence?
How to test this? I tried testing this very basic implementation using loom, but loom doesn't seem to be complaining even when I comment out the fences
I know that I could have used some very nice crates for memory reclamation here, but I was just trying things. Same thing goes for using fences and not using Ordering::SeqCst directly on the atomic operation
There's a data race between two pops.
It's possible to read from head.next in the loop and deallocate the head ptr at the end of pop at the same time in different threads.
For example:
Thread 1: at end of pop right before dealloc gets suspended
Thread 2: starts pop and loads head
Thread 1: continues execution and deallocs head
Thread 2: tries to read head.next, which is UB because it's a use after free
One of them will fail the compare_exchange_weak. Essentially, the compare_exchange steals ownership of the head node, and this is the correct way to implement a lock free linked list.
This is insufficient. I checked this against Miri, and it reported a UAF and a Stack Borrow conflict.
The problem here is that while compare_exchange_weak may steal ownership, the pop in two different threads may both read the same head value at the same time, one will win and the other may be UB depending on how they are scheduled. I think @SkiFire13 did a better job of explaining the ordering.
Here's a playground link, where I switched all orderings to SeqCst (not that Miri supports that, it supports AcqRel) and fixed a few spurious references that shouldn't be created
Here's the error
error: Undefined Behavior: Data race detected between (1) non-atomic read on thread `unnamed-4` and (2) retag write of type `Node<i32>` on thread `unnamed-3` at alloc7858
--> /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:1569:9
|
1569 | Box(unsafe { Unique::new_unchecked(raw) }, alloc)
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ (2) just happened here
|
help: and (1) occurred earlier here
--> src/main.rs:60:33
|
60 | let next = unsafe { (*head).next };
| ^^^^^^^^^^^^
= help: retags occur on all (re)borrows and as well as when references are copied or moved
= help: retags permit optimizations that insert speculative reads or writes
= help: therefore from the perspective of data races, a retag has the same implications as a read or write
= help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior
= help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information
= note: this is on thread `unnamed-3`
= note: stack backtrace:
0: std::boxed::Box::<Node<i32>>::from_raw_in
at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:1569:9: 1569:58
1: std::boxed::Box::<Node<i32>>::from_raw
at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:1338:18: 1338:48
2: Stack::<i32>::pop
at src/main.rs:68:35: 68:54
3: main::{closure#0}::{closure#2}
at src/main.rs:96:17: 96:25
note: the last function in that backtrace got called indirectly due to this code
--> src/main.rs:94:9
|
94 | / s.spawn(|| {
95 | | for i in 0..1000 {
96 | | st.pop();
97 | | }
98 | | });
| |__________^
I see, but this also doesn't guarantee that the next consecutive load will not load a detached head, as the load is allowed to load a previous value as well? Please correct me if I am wrong.