rust/tests/compile-fail/data_race/dealloc_read_race_stack_drop.rs
JCTyblaidd c4ccd0b6a1 Fix nits
Co-authored-by: bjorn3 <bjorn3@users.noreply.github.com>
2020-12-13 11:04:58 +00:00

54 lines
1.6 KiB
Rust

// ignore-windows: Concurrency on Windows is not supported yet.
// compile-flags: -Zmiri-disable-isolation
use std::thread::{spawn, sleep};
use std::ptr::null_mut;
use std::sync::atomic::{Ordering, AtomicPtr};
use std::time::Duration;
#[derive(Copy, Clone)]
struct EvilSend<T>(pub T);
unsafe impl<T> Send for EvilSend<T> {}
unsafe impl<T> Sync for EvilSend<T> {}
pub fn main() {
// Shared atomic pointer
let pointer = AtomicPtr::new(null_mut::<usize>());
let ptr = EvilSend(&pointer as *const AtomicPtr<usize>);
// Note: this is scheduler-dependent
// the operations need to occur in
// order, otherwise the allocation is
// not visible to the other-thread to
// detect the race:
// 1. stack-allocate
// 2. read
// 3. stack-deallocate
unsafe {
let j1 = spawn(move || {
// Concurrent allocate the memory.
// Uses relaxed semantics to not generate
// a release sequence.
let pointer = &*ptr.0;
let mut stack_var = 0usize;
pointer.store(&mut stack_var as *mut _, Ordering::Release);
sleep(Duration::from_millis(1000));
// NOTE: the race is also detected with thread 0, and so reported for thread 0 instead of 2, unsure of the cause.
drop(stack_var);
}); //~ ERROR Data race detected between DEALLOCATE on Thread(id = 1) and READ on Thread(id = 0, name = "main")
let j2 = spawn(move || {
let pointer = &*ptr.0;
*pointer.load(Ordering::Acquire)
});
j1.join().unwrap();
j2.join().unwrap();
}
}