1 use std::collections::{hash_map::Entry, HashMap, VecDeque};
2 use std::num::NonZeroU32;
7 use rustc_index::vec::{Idx, IndexVec};
11 /// We cannot use the `newtype_index!` macro because we have to use 0 as a
12 /// sentinel value meaning that the identifier is not assigned. This is because
13 /// the pthreads static initializers initialize memory with zeros (see the
14 /// `src/shims/sync.rs` file).
15 macro_rules! declare_id {
17 /// 0 is used to indicate that the id was not yet assigned and,
18 /// therefore, is not a valid identifier.
19 #[derive(Clone, Copy, Debug, PartialOrd, Ord, PartialEq, Eq, Hash)]
20 pub struct $name(NonZeroU32);
23 // Panics if `id == 0`.
24 pub fn from_u32(id: u32) -> Self {
25 Self(NonZeroU32::new(id).unwrap())
30 fn new(idx: usize) -> Self {
31 // We use 0 as a sentinel value (see the comment above) and,
32 // therefore, need to shift by one when converting from an index
34 let shifted_idx = u32::try_from(idx).unwrap().checked_add(1).unwrap();
35 $name(NonZeroU32::new(shifted_idx).unwrap())
37 fn index(self) -> usize {
38 // See the comment in `Self::new`.
39 // (This cannot underflow because self is NonZeroU32.)
40 usize::try_from(self.0.get() - 1).unwrap()
45 pub fn to_u32_scalar<'tcx>(&self) -> Scalar<Tag> {
46 Scalar::from_u32(self.0.get())
55 #[derive(Default, Debug)]
57 /// The thread that currently owns the lock.
58 owner: Option<ThreadId>,
59 /// How many times the mutex was locked by the owner.
61 /// The queue of threads waiting for this mutex.
62 queue: VecDeque<ThreadId>,
63 /// Data race handle, this tracks the happens-before
64 /// relationship between each mutex access. It is
65 /// released to during unlock and acquired from during
66 /// locking, and therefore stores the clock of the last
67 /// thread to release this mutex.
71 declare_id!(RwLockId);
73 /// The read-write lock state.
74 #[derive(Default, Debug)]
76 /// The writer thread that currently owns the lock.
77 writer: Option<ThreadId>,
78 /// The readers that currently own the lock and how many times they acquired
80 readers: HashMap<ThreadId, usize>,
81 /// The queue of writer threads waiting for this lock.
82 writer_queue: VecDeque<ThreadId>,
83 /// The queue of reader threads waiting for this lock.
84 reader_queue: VecDeque<ThreadId>,
85 /// Data race handle for writers, tracks the happens-before
86 /// ordering between each write access to a rwlock and is updated
87 /// after a sequence of concurrent readers to track the happens-
88 /// before ordering between the set of previous readers and
89 /// the current writer.
90 /// Contains the clock of the last thread to release a writer
91 /// lock or the joined clock of the set of last threads to release
92 /// shared reader locks.
94 /// Data race handle for readers, this is temporary storage
95 /// for the combined happens-before ordering for between all
96 /// concurrent readers and the next writer, and the value
97 /// is stored to the main data_race variable once all
98 /// readers are finished.
99 /// Has to be stored separately since reader lock acquires
100 /// must load the clock of the last write and must not
101 /// add happens-before orderings between shared reader
103 data_race_reader: VClock,
106 declare_id!(CondvarId);
108 /// A thread waiting on a conditional variable.
110 struct CondvarWaiter {
111 /// The thread that is waiting on this variable.
113 /// The mutex on which the thread is waiting.
117 /// The conditional variable state.
118 #[derive(Default, Debug)]
120 waiters: VecDeque<CondvarWaiter>,
121 /// Tracks the happens-before relationship
122 /// between a cond-var signal and a cond-var
123 /// wait during a non-suprious signal event.
124 /// Contains the clock of the last thread to
125 /// perform a futex-signal.
130 #[derive(Default, Debug)]
132 waiters: VecDeque<FutexWaiter>,
133 /// Tracks the happens-before relationship
134 /// between a futex-wake and a futex-wait
135 /// during a non-spurious wake event.
136 /// Contains the clock of the last thread to
137 /// perform a futex-wake.
141 /// A thread waiting on a futex.
144 /// The thread that is waiting on this futex.
146 /// The bitset used by FUTEX_*_BITSET, or u32::MAX for other operations.
150 /// The state of all synchronization variables.
151 #[derive(Default, Debug)]
152 pub(super) struct SynchronizationState {
153 mutexes: IndexVec<MutexId, Mutex>,
154 rwlocks: IndexVec<RwLockId, RwLock>,
155 condvars: IndexVec<CondvarId, Condvar>,
156 futexes: HashMap<u64, Futex>,
159 // Private extension trait for local helper methods
160 impl<'mir, 'tcx: 'mir> EvalContextExtPriv<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
161 trait EvalContextExtPriv<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
162 /// Take a reader out of the queue waiting for the lock.
163 /// Returns `true` if some thread got the rwlock.
165 fn rwlock_dequeue_and_lock_reader(&mut self, id: RwLockId) -> bool {
166 let this = self.eval_context_mut();
167 if let Some(reader) = this.machine.threads.sync.rwlocks[id].reader_queue.pop_front() {
168 this.unblock_thread(reader);
169 this.rwlock_reader_lock(id, reader);
176 /// Take the writer out of the queue waiting for the lock.
177 /// Returns `true` if some thread got the rwlock.
179 fn rwlock_dequeue_and_lock_writer(&mut self, id: RwLockId) -> bool {
180 let this = self.eval_context_mut();
181 if let Some(writer) = this.machine.threads.sync.rwlocks[id].writer_queue.pop_front() {
182 this.unblock_thread(writer);
183 this.rwlock_writer_lock(id, writer);
190 /// Take a thread out of the queue waiting for the mutex, and lock
191 /// the mutex for it. Returns `true` if some thread has the mutex now.
193 fn mutex_dequeue_and_lock(&mut self, id: MutexId) -> bool {
194 let this = self.eval_context_mut();
195 if let Some(thread) = this.machine.threads.sync.mutexes[id].queue.pop_front() {
196 this.unblock_thread(thread);
197 this.mutex_lock(id, thread);
205 // Public interface to synchronization primitives. Please note that in most
206 // cases, the function calls are infallible and it is the client's (shim
207 // implementation's) responsibility to detect and deal with erroneous
209 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
210 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
212 /// Peek the id of the next mutex
213 fn mutex_next_id(&self) -> MutexId {
214 let this = self.eval_context_ref();
215 this.machine.threads.sync.mutexes.next_index()
219 /// Create state for a new mutex.
220 fn mutex_create(&mut self) -> MutexId {
221 let this = self.eval_context_mut();
222 this.machine.threads.sync.mutexes.push(Default::default())
226 /// Get the id of the thread that currently owns this lock.
227 fn mutex_get_owner(&mut self, id: MutexId) -> ThreadId {
228 let this = self.eval_context_ref();
229 this.machine.threads.sync.mutexes[id].owner.unwrap()
234 fn mutex_is_locked(&self, id: MutexId) -> bool {
235 let this = self.eval_context_ref();
236 this.machine.threads.sync.mutexes[id].owner.is_some()
239 /// Lock by setting the mutex owner and increasing the lock count.
240 fn mutex_lock(&mut self, id: MutexId, thread: ThreadId) {
241 let this = self.eval_context_mut();
242 let mutex = &mut this.machine.threads.sync.mutexes[id];
243 if let Some(current_owner) = mutex.owner {
244 assert_eq!(thread, current_owner, "mutex already locked by another thread");
246 mutex.lock_count > 0,
247 "invariant violation: lock_count == 0 iff the thread is unlocked"
250 mutex.owner = Some(thread);
252 mutex.lock_count = mutex.lock_count.checked_add(1).unwrap();
253 if let Some(data_race) = &this.machine.data_race {
254 data_race.validate_lock_acquire(&mutex.data_race, thread);
258 /// Try unlocking by decreasing the lock count and returning the old lock
259 /// count. If the lock count reaches 0, release the lock and potentially
260 /// give to a new owner. If the lock was not locked by `expected_owner`,
262 fn mutex_unlock(&mut self, id: MutexId, expected_owner: ThreadId) -> Option<usize> {
263 let this = self.eval_context_mut();
264 let mutex = &mut this.machine.threads.sync.mutexes[id];
265 if let Some(current_owner) = mutex.owner {
267 if current_owner != expected_owner {
268 // Only the owner can unlock the mutex.
271 let old_lock_count = mutex.lock_count;
272 mutex.lock_count = old_lock_count
274 .expect("invariant violation: lock_count == 0 iff the thread is unlocked");
275 if mutex.lock_count == 0 {
277 // The mutex is completely unlocked. Try transfering ownership
278 // to another thread.
279 if let Some(data_race) = &this.machine.data_race {
280 data_race.validate_lock_release(&mut mutex.data_race, current_owner);
282 this.mutex_dequeue_and_lock(id);
286 // Mutex is not locked.
292 /// Put the thread into the queue waiting for the mutex.
293 fn mutex_enqueue_and_block(&mut self, id: MutexId, thread: ThreadId) {
294 let this = self.eval_context_mut();
295 assert!(this.mutex_is_locked(id), "queing on unlocked mutex");
296 this.machine.threads.sync.mutexes[id].queue.push_back(thread);
297 this.block_thread(thread);
301 /// Peek the id of the next read write lock
302 fn rwlock_next_id(&self) -> RwLockId {
303 let this = self.eval_context_ref();
304 this.machine.threads.sync.rwlocks.next_index()
308 /// Create state for a new read write lock.
309 fn rwlock_create(&mut self) -> RwLockId {
310 let this = self.eval_context_mut();
311 this.machine.threads.sync.rwlocks.push(Default::default())
316 fn rwlock_is_locked(&self, id: RwLockId) -> bool {
317 let this = self.eval_context_ref();
318 let rwlock = &this.machine.threads.sync.rwlocks[id];
320 "rwlock_is_locked: {:?} writer is {:?} and there are {} reader threads (some of which could hold multiple read locks)",
323 rwlock.readers.len(),
325 rwlock.writer.is_some() || rwlock.readers.is_empty().not()
329 /// Check if write locked.
330 fn rwlock_is_write_locked(&self, id: RwLockId) -> bool {
331 let this = self.eval_context_ref();
332 let rwlock = &this.machine.threads.sync.rwlocks[id];
333 trace!("rwlock_is_write_locked: {:?} writer is {:?}", id, rwlock.writer);
334 rwlock.writer.is_some()
337 /// Read-lock the lock by adding the `reader` the list of threads that own
339 fn rwlock_reader_lock(&mut self, id: RwLockId, reader: ThreadId) {
340 let this = self.eval_context_mut();
341 assert!(!this.rwlock_is_write_locked(id), "the lock is write locked");
342 trace!("rwlock_reader_lock: {:?} now also held (one more time) by {:?}", id, reader);
343 let rwlock = &mut this.machine.threads.sync.rwlocks[id];
344 let count = rwlock.readers.entry(reader).or_insert(0);
345 *count = count.checked_add(1).expect("the reader counter overflowed");
346 if let Some(data_race) = &this.machine.data_race {
347 data_race.validate_lock_acquire(&rwlock.data_race, reader);
351 /// Try read-unlock the lock for `reader` and potentially give the lock to a new owner.
352 /// Returns `true` if succeeded, `false` if this `reader` did not hold the lock.
353 fn rwlock_reader_unlock(&mut self, id: RwLockId, reader: ThreadId) -> bool {
354 let this = self.eval_context_mut();
355 let rwlock = &mut this.machine.threads.sync.rwlocks[id];
356 match rwlock.readers.entry(reader) {
357 Entry::Occupied(mut entry) => {
358 let count = entry.get_mut();
359 assert!(*count > 0, "rwlock locked with count == 0");
362 trace!("rwlock_reader_unlock: {:?} no longer held by {:?}", id, reader);
365 trace!("rwlock_reader_unlock: {:?} held one less time by {:?}", id, reader);
368 Entry::Vacant(_) => return false, // we did not even own this lock
370 if let Some(data_race) = &this.machine.data_race {
371 data_race.validate_lock_release_shared(&mut rwlock.data_race_reader, reader);
374 // The thread was a reader. If the lock is not held any more, give it to a writer.
375 if this.rwlock_is_locked(id).not() {
376 // All the readers are finished, so set the writer data-race handle to the value
377 // of the union of all reader data race handles, since the set of readers
378 // happen-before the writers
379 let rwlock = &mut this.machine.threads.sync.rwlocks[id];
380 rwlock.data_race.clone_from(&rwlock.data_race_reader);
381 this.rwlock_dequeue_and_lock_writer(id);
387 /// Put the reader in the queue waiting for the lock and block it.
388 fn rwlock_enqueue_and_block_reader(&mut self, id: RwLockId, reader: ThreadId) {
389 let this = self.eval_context_mut();
390 assert!(this.rwlock_is_write_locked(id), "read-queueing on not write locked rwlock");
391 this.machine.threads.sync.rwlocks[id].reader_queue.push_back(reader);
392 this.block_thread(reader);
396 /// Lock by setting the writer that owns the lock.
397 fn rwlock_writer_lock(&mut self, id: RwLockId, writer: ThreadId) {
398 let this = self.eval_context_mut();
399 assert!(!this.rwlock_is_locked(id), "the rwlock is already locked");
400 trace!("rwlock_writer_lock: {:?} now held by {:?}", id, writer);
401 let rwlock = &mut this.machine.threads.sync.rwlocks[id];
402 rwlock.writer = Some(writer);
403 if let Some(data_race) = &this.machine.data_race {
404 data_race.validate_lock_acquire(&rwlock.data_race, writer);
409 /// Try to unlock by removing the writer.
410 fn rwlock_writer_unlock(&mut self, id: RwLockId, expected_writer: ThreadId) -> bool {
411 let this = self.eval_context_mut();
412 let rwlock = &mut this.machine.threads.sync.rwlocks[id];
413 if let Some(current_writer) = rwlock.writer {
414 if current_writer != expected_writer {
415 // Only the owner can unlock the rwlock.
418 rwlock.writer = None;
419 trace!("rwlock_writer_unlock: {:?} unlocked by {:?}", id, expected_writer);
420 // Release memory to both reader and writer vector clocks
421 // since this writer happens-before both the union of readers once they are finished
422 // and the next writer
423 if let Some(data_race) = &this.machine.data_race {
424 data_race.validate_lock_release(&mut rwlock.data_race, current_writer);
425 data_race.validate_lock_release(&mut rwlock.data_race_reader, current_writer);
427 // The thread was a writer.
429 // We are prioritizing writers here against the readers. As a
430 // result, not only readers can starve writers, but also writers can
432 if this.rwlock_dequeue_and_lock_writer(id) {
433 // Someone got the write lock, nice.
435 // Give the lock to all readers.
436 while this.rwlock_dequeue_and_lock_reader(id) {
447 /// Put the writer in the queue waiting for the lock.
448 fn rwlock_enqueue_and_block_writer(&mut self, id: RwLockId, writer: ThreadId) {
449 let this = self.eval_context_mut();
450 assert!(this.rwlock_is_locked(id), "write-queueing on unlocked rwlock");
451 this.machine.threads.sync.rwlocks[id].writer_queue.push_back(writer);
452 this.block_thread(writer);
456 /// Peek the id of the next Condvar
457 fn condvar_next_id(&self) -> CondvarId {
458 let this = self.eval_context_ref();
459 this.machine.threads.sync.condvars.next_index()
463 /// Create state for a new conditional variable.
464 fn condvar_create(&mut self) -> CondvarId {
465 let this = self.eval_context_mut();
466 this.machine.threads.sync.condvars.push(Default::default())
470 /// Is the conditional variable awaited?
471 fn condvar_is_awaited(&mut self, id: CondvarId) -> bool {
472 let this = self.eval_context_mut();
473 !this.machine.threads.sync.condvars[id].waiters.is_empty()
476 /// Mark that the thread is waiting on the conditional variable.
477 fn condvar_wait(&mut self, id: CondvarId, thread: ThreadId, mutex: MutexId) {
478 let this = self.eval_context_mut();
479 let waiters = &mut this.machine.threads.sync.condvars[id].waiters;
480 assert!(waiters.iter().all(|waiter| waiter.thread != thread), "thread is already waiting");
481 waiters.push_back(CondvarWaiter { thread, mutex });
484 /// Wake up some thread (if there is any) sleeping on the conditional
486 fn condvar_signal(&mut self, id: CondvarId) -> Option<(ThreadId, MutexId)> {
487 let this = self.eval_context_mut();
488 let current_thread = this.get_active_thread();
489 let condvar = &mut this.machine.threads.sync.condvars[id];
490 let data_race = &this.machine.data_race;
492 // Each condvar signal happens-before the end of the condvar wake
493 if let Some(data_race) = data_race {
494 data_race.validate_lock_release(&mut condvar.data_race, current_thread);
496 condvar.waiters.pop_front().map(|waiter| {
497 if let Some(data_race) = data_race {
498 data_race.validate_lock_acquire(&condvar.data_race, waiter.thread);
500 (waiter.thread, waiter.mutex)
505 /// Remove the thread from the queue of threads waiting on this conditional variable.
506 fn condvar_remove_waiter(&mut self, id: CondvarId, thread: ThreadId) {
507 let this = self.eval_context_mut();
508 this.machine.threads.sync.condvars[id].waiters.retain(|waiter| waiter.thread != thread);
511 fn futex_wait(&mut self, addr: u64, thread: ThreadId, bitset: u32) {
512 let this = self.eval_context_mut();
513 let futex = &mut this.machine.threads.sync.futexes.entry(addr).or_default();
514 let waiters = &mut futex.waiters;
515 assert!(waiters.iter().all(|waiter| waiter.thread != thread), "thread is already waiting");
516 waiters.push_back(FutexWaiter { thread, bitset });
519 fn futex_wake(&mut self, addr: u64, bitset: u32) -> Option<ThreadId> {
520 let this = self.eval_context_mut();
521 let current_thread = this.get_active_thread();
522 let futex = &mut this.machine.threads.sync.futexes.get_mut(&addr)?;
523 let data_race = &this.machine.data_race;
525 // Each futex-wake happens-before the end of the futex wait
526 if let Some(data_race) = data_race {
527 data_race.validate_lock_release(&mut futex.data_race, current_thread);
530 // Wake up the first thread in the queue that matches any of the bits in the bitset.
531 futex.waiters.iter().position(|w| w.bitset & bitset != 0).map(|i| {
532 let waiter = futex.waiters.remove(i).unwrap();
533 if let Some(data_race) = data_race {
534 data_race.validate_lock_acquire(&futex.data_race, waiter.thread);
540 fn futex_remove_waiter(&mut self, addr: u64, thread: ThreadId) {
541 let this = self.eval_context_mut();
542 if let Some(futex) = this.machine.threads.sync.futexes.get_mut(&addr) {
543 futex.waiters.retain(|waiter| waiter.thread != thread);