1 use std::collections::{hash_map::Entry, HashMap, VecDeque};
2 use std::convert::TryFrom;
3 use std::num::NonZeroU32;
8 use rustc_index::vec::{Idx, IndexVec};
12 /// We cannot use the `newtype_index!` macro because we have to use 0 as a
13 /// sentinel value meaning that the identifier is not assigned. This is because
14 /// the pthreads static initializers initialize memory with zeros (see the
15 /// `src/shims/sync.rs` file).
16 macro_rules! declare_id {
18 /// 0 is used to indicate that the id was not yet assigned and,
19 /// therefore, is not a valid identifier.
20 #[derive(Clone, Copy, Debug, PartialOrd, Ord, PartialEq, Eq, Hash)]
21 pub struct $name(NonZeroU32);
24 // Panics if `id == 0`.
25 pub fn from_u32(id: u32) -> Self {
26 Self(NonZeroU32::new(id).unwrap())
31 fn new(idx: usize) -> Self {
32 // We use 0 as a sentinel value (see the comment above) and,
33 // therefore, need to shift by one when converting from an index
35 let shifted_idx = u32::try_from(idx).unwrap().checked_add(1).unwrap();
36 $name(NonZeroU32::new(shifted_idx).unwrap())
38 fn index(self) -> usize {
39 // See the comment in `Self::new`.
40 // (This cannot underflow because self is NonZeroU32.)
41 usize::try_from(self.0.get() - 1).unwrap()
46 pub fn to_u32_scalar<'tcx>(&self) -> Scalar<Tag> {
47 Scalar::from_u32(self.0.get())
56 #[derive(Default, Debug)]
58 /// The thread that currently owns the lock.
59 owner: Option<ThreadId>,
60 /// How many times the mutex was locked by the owner.
62 /// The queue of threads waiting for this mutex.
63 queue: VecDeque<ThreadId>,
64 /// Data race handle, this tracks the happens-before
65 /// relationship between each mutex access. It is
66 /// released to during unlock and acquired from during
67 /// locking, and therefore stores the clock of the last
68 /// thread to release this mutex.
72 declare_id!(RwLockId);
74 /// The read-write lock state.
75 #[derive(Default, Debug)]
77 /// The writer thread that currently owns the lock.
78 writer: Option<ThreadId>,
79 /// The readers that currently own the lock and how many times they acquired
81 readers: HashMap<ThreadId, usize>,
82 /// The queue of writer threads waiting for this lock.
83 writer_queue: VecDeque<ThreadId>,
84 /// The queue of reader threads waiting for this lock.
85 reader_queue: VecDeque<ThreadId>,
86 /// Data race handle for writers, tracks the happens-before
87 /// ordering between each write access to a rwlock and is updated
88 /// after a sequence of concurrent readers to track the happens-
89 /// before ordering between the set of previous readers and
90 /// the current writer.
91 /// Contains the clock of the last thread to release a writer
92 /// lock or the joined clock of the set of last threads to release
93 /// shared reader locks.
95 /// Data race handle for readers, this is temporary storage
96 /// for the combined happens-before ordering for between all
97 /// concurrent readers and the next writer, and the value
98 /// is stored to the main data_race variable once all
99 /// readers are finished.
100 /// Has to be stored separately since reader lock acquires
101 /// must load the clock of the last write and must not
102 /// add happens-before orderings between shared reader
104 data_race_reader: VClock,
107 declare_id!(CondvarId);
109 /// A thread waiting on a conditional variable.
111 struct CondvarWaiter {
112 /// The thread that is waiting on this variable.
114 /// The mutex on which the thread is waiting.
118 /// The conditional variable state.
119 #[derive(Default, Debug)]
121 waiters: VecDeque<CondvarWaiter>,
122 /// Tracks the happens-before relationship
123 /// between a cond-var signal and a cond-var
124 /// wait during a non-suprious signal event.
125 /// Contains the clock of the last thread to
126 /// perform a futex-signal.
131 #[derive(Default, Debug)]
133 waiters: VecDeque<FutexWaiter>,
134 /// Tracks the happens-before relationship
135 /// between a futex-wake and a futex-wait
136 /// during a non-spurious wake event.
137 /// Contains the clock of the last thread to
138 /// perform a futex-wake.
142 /// A thread waiting on a futex.
145 /// The thread that is waiting on this futex.
149 /// The state of all synchronization variables.
150 #[derive(Default, Debug)]
151 pub(super) struct SynchronizationState {
152 mutexes: IndexVec<MutexId, Mutex>,
153 rwlocks: IndexVec<RwLockId, RwLock>,
154 condvars: IndexVec<CondvarId, Condvar>,
155 futexes: HashMap<u64, Futex>,
158 // Private extension trait for local helper methods
159 impl<'mir, 'tcx: 'mir> EvalContextExtPriv<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
160 trait EvalContextExtPriv<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
161 /// Take a reader out of the queue waiting for the lock.
162 /// Returns `true` if some thread got the rwlock.
164 fn rwlock_dequeue_and_lock_reader(&mut self, id: RwLockId) -> bool {
165 let this = self.eval_context_mut();
166 if let Some(reader) = this.machine.threads.sync.rwlocks[id].reader_queue.pop_front() {
167 this.unblock_thread(reader);
168 this.rwlock_reader_lock(id, reader);
175 /// Take the writer out of the queue waiting for the lock.
176 /// Returns `true` if some thread got the rwlock.
178 fn rwlock_dequeue_and_lock_writer(&mut self, id: RwLockId) -> bool {
179 let this = self.eval_context_mut();
180 if let Some(writer) = this.machine.threads.sync.rwlocks[id].writer_queue.pop_front() {
181 this.unblock_thread(writer);
182 this.rwlock_writer_lock(id, writer);
189 /// Take a thread out of the queue waiting for the mutex, and lock
190 /// the mutex for it. Returns `true` if some thread has the mutex now.
192 fn mutex_dequeue_and_lock(&mut self, id: MutexId) -> bool {
193 let this = self.eval_context_mut();
194 if let Some(thread) = this.machine.threads.sync.mutexes[id].queue.pop_front() {
195 this.unblock_thread(thread);
196 this.mutex_lock(id, thread);
204 // Public interface to synchronization primitives. Please note that in most
205 // cases, the function calls are infallible and it is the client's (shim
206 // implementation's) responsibility to detect and deal with erroneous
208 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
209 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
211 /// Create state for a new mutex.
212 fn mutex_create(&mut self) -> MutexId {
213 let this = self.eval_context_mut();
214 this.machine.threads.sync.mutexes.push(Default::default())
218 /// Get the id of the thread that currently owns this lock.
219 fn mutex_get_owner(&mut self, id: MutexId) -> ThreadId {
220 let this = self.eval_context_ref();
221 this.machine.threads.sync.mutexes[id].owner.unwrap()
226 fn mutex_is_locked(&self, id: MutexId) -> bool {
227 let this = self.eval_context_ref();
228 this.machine.threads.sync.mutexes[id].owner.is_some()
231 /// Lock by setting the mutex owner and increasing the lock count.
232 fn mutex_lock(&mut self, id: MutexId, thread: ThreadId) {
233 let this = self.eval_context_mut();
234 let mutex = &mut this.machine.threads.sync.mutexes[id];
235 if let Some(current_owner) = mutex.owner {
236 assert_eq!(thread, current_owner, "mutex already locked by another thread");
238 mutex.lock_count > 0,
239 "invariant violation: lock_count == 0 iff the thread is unlocked"
242 mutex.owner = Some(thread);
244 mutex.lock_count = mutex.lock_count.checked_add(1).unwrap();
245 if let Some(data_race) = &this.memory.extra.data_race {
246 data_race.validate_lock_acquire(&mutex.data_race, thread);
250 /// Try unlocking by decreasing the lock count and returning the old lock
251 /// count. If the lock count reaches 0, release the lock and potentially
252 /// give to a new owner. If the lock was not locked by `expected_owner`,
254 fn mutex_unlock(&mut self, id: MutexId, expected_owner: ThreadId) -> Option<usize> {
255 let this = self.eval_context_mut();
256 let mutex = &mut this.machine.threads.sync.mutexes[id];
257 if let Some(current_owner) = mutex.owner {
259 if current_owner != expected_owner {
260 // Only the owner can unlock the mutex.
263 let old_lock_count = mutex.lock_count;
264 mutex.lock_count = old_lock_count
266 .expect("invariant violation: lock_count == 0 iff the thread is unlocked");
267 if mutex.lock_count == 0 {
269 // The mutex is completely unlocked. Try transfering ownership
270 // to another thread.
271 if let Some(data_race) = &this.memory.extra.data_race {
272 data_race.validate_lock_release(&mut mutex.data_race, current_owner);
274 this.mutex_dequeue_and_lock(id);
278 // Mutex is not locked.
284 /// Put the thread into the queue waiting for the mutex.
285 fn mutex_enqueue_and_block(&mut self, id: MutexId, thread: ThreadId) {
286 let this = self.eval_context_mut();
287 assert!(this.mutex_is_locked(id), "queing on unlocked mutex");
288 this.machine.threads.sync.mutexes[id].queue.push_back(thread);
289 this.block_thread(thread);
293 /// Create state for a new read write lock.
294 fn rwlock_create(&mut self) -> RwLockId {
295 let this = self.eval_context_mut();
296 this.machine.threads.sync.rwlocks.push(Default::default())
301 fn rwlock_is_locked(&self, id: RwLockId) -> bool {
302 let this = self.eval_context_ref();
303 let rwlock = &this.machine.threads.sync.rwlocks[id];
305 "rwlock_is_locked: {:?} writer is {:?} and there are {} reader threads (some of which could hold multiple read locks)",
308 rwlock.readers.len(),
310 rwlock.writer.is_some() || rwlock.readers.is_empty().not()
314 /// Check if write locked.
315 fn rwlock_is_write_locked(&self, id: RwLockId) -> bool {
316 let this = self.eval_context_ref();
317 let rwlock = &this.machine.threads.sync.rwlocks[id];
318 trace!("rwlock_is_write_locked: {:?} writer is {:?}", id, rwlock.writer);
319 rwlock.writer.is_some()
322 /// Read-lock the lock by adding the `reader` the list of threads that own
324 fn rwlock_reader_lock(&mut self, id: RwLockId, reader: ThreadId) {
325 let this = self.eval_context_mut();
326 assert!(!this.rwlock_is_write_locked(id), "the lock is write locked");
327 trace!("rwlock_reader_lock: {:?} now also held (one more time) by {:?}", id, reader);
328 let rwlock = &mut this.machine.threads.sync.rwlocks[id];
329 let count = rwlock.readers.entry(reader).or_insert(0);
330 *count = count.checked_add(1).expect("the reader counter overflowed");
331 if let Some(data_race) = &this.memory.extra.data_race {
332 data_race.validate_lock_acquire(&rwlock.data_race, reader);
336 /// Try read-unlock the lock for `reader` and potentially give the lock to a new owner.
337 /// Returns `true` if succeeded, `false` if this `reader` did not hold the lock.
338 fn rwlock_reader_unlock(&mut self, id: RwLockId, reader: ThreadId) -> bool {
339 let this = self.eval_context_mut();
340 let rwlock = &mut this.machine.threads.sync.rwlocks[id];
341 match rwlock.readers.entry(reader) {
342 Entry::Occupied(mut entry) => {
343 let count = entry.get_mut();
344 assert!(*count > 0, "rwlock locked with count == 0");
347 trace!("rwlock_reader_unlock: {:?} no longer held by {:?}", id, reader);
350 trace!("rwlock_reader_unlock: {:?} held one less time by {:?}", id, reader);
353 Entry::Vacant(_) => return false, // we did not even own this lock
355 if let Some(data_race) = &this.memory.extra.data_race {
356 data_race.validate_lock_release_shared(&mut rwlock.data_race_reader, reader);
359 // The thread was a reader. If the lock is not held any more, give it to a writer.
360 if this.rwlock_is_locked(id).not() {
361 // All the readers are finished, so set the writer data-race handle to the value
362 // of the union of all reader data race handles, since the set of readers
363 // happen-before the writers
364 let rwlock = &mut this.machine.threads.sync.rwlocks[id];
365 rwlock.data_race.clone_from(&rwlock.data_race_reader);
366 this.rwlock_dequeue_and_lock_writer(id);
372 /// Put the reader in the queue waiting for the lock and block it.
373 fn rwlock_enqueue_and_block_reader(&mut self, id: RwLockId, reader: ThreadId) {
374 let this = self.eval_context_mut();
375 assert!(this.rwlock_is_write_locked(id), "read-queueing on not write locked rwlock");
376 this.machine.threads.sync.rwlocks[id].reader_queue.push_back(reader);
377 this.block_thread(reader);
381 /// Lock by setting the writer that owns the lock.
382 fn rwlock_writer_lock(&mut self, id: RwLockId, writer: ThreadId) {
383 let this = self.eval_context_mut();
384 assert!(!this.rwlock_is_locked(id), "the rwlock is already locked");
385 trace!("rwlock_writer_lock: {:?} now held by {:?}", id, writer);
386 let rwlock = &mut this.machine.threads.sync.rwlocks[id];
387 rwlock.writer = Some(writer);
388 if let Some(data_race) = &this.memory.extra.data_race {
389 data_race.validate_lock_acquire(&rwlock.data_race, writer);
394 /// Try to unlock by removing the writer.
395 fn rwlock_writer_unlock(&mut self, id: RwLockId, expected_writer: ThreadId) -> bool {
396 let this = self.eval_context_mut();
397 let rwlock = &mut this.machine.threads.sync.rwlocks[id];
398 if let Some(current_writer) = rwlock.writer {
399 if current_writer != expected_writer {
400 // Only the owner can unlock the rwlock.
403 rwlock.writer = None;
404 trace!("rwlock_writer_unlock: {:?} unlocked by {:?}", id, expected_writer);
405 // Release memory to both reader and writer vector clocks
406 // since this writer happens-before both the union of readers once they are finished
407 // and the next writer
408 if let Some(data_race) = &this.memory.extra.data_race {
409 data_race.validate_lock_release(&mut rwlock.data_race, current_writer);
410 data_race.validate_lock_release(&mut rwlock.data_race_reader, current_writer);
412 // The thread was a writer.
414 // We are prioritizing writers here against the readers. As a
415 // result, not only readers can starve writers, but also writers can
417 if this.rwlock_dequeue_and_lock_writer(id) {
418 // Someone got the write lock, nice.
420 // Give the lock to all readers.
421 while this.rwlock_dequeue_and_lock_reader(id) {
432 /// Put the writer in the queue waiting for the lock.
433 fn rwlock_enqueue_and_block_writer(&mut self, id: RwLockId, writer: ThreadId) {
434 let this = self.eval_context_mut();
435 assert!(this.rwlock_is_locked(id), "write-queueing on unlocked rwlock");
436 this.machine.threads.sync.rwlocks[id].writer_queue.push_back(writer);
437 this.block_thread(writer);
441 /// Create state for a new conditional variable.
442 fn condvar_create(&mut self) -> CondvarId {
443 let this = self.eval_context_mut();
444 this.machine.threads.sync.condvars.push(Default::default())
448 /// Is the conditional variable awaited?
449 fn condvar_is_awaited(&mut self, id: CondvarId) -> bool {
450 let this = self.eval_context_mut();
451 !this.machine.threads.sync.condvars[id].waiters.is_empty()
454 /// Mark that the thread is waiting on the conditional variable.
455 fn condvar_wait(&mut self, id: CondvarId, thread: ThreadId, mutex: MutexId) {
456 let this = self.eval_context_mut();
457 let waiters = &mut this.machine.threads.sync.condvars[id].waiters;
458 assert!(waiters.iter().all(|waiter| waiter.thread != thread), "thread is already waiting");
459 waiters.push_back(CondvarWaiter { thread, mutex });
462 /// Wake up some thread (if there is any) sleeping on the conditional
464 fn condvar_signal(&mut self, id: CondvarId) -> Option<(ThreadId, MutexId)> {
465 let this = self.eval_context_mut();
466 let current_thread = this.get_active_thread();
467 let condvar = &mut this.machine.threads.sync.condvars[id];
468 let data_race = &this.memory.extra.data_race;
470 // Each condvar signal happens-before the end of the condvar wake
471 if let Some(data_race) = data_race {
472 data_race.validate_lock_release(&mut condvar.data_race, current_thread);
474 condvar.waiters.pop_front().map(|waiter| {
475 if let Some(data_race) = data_race {
476 data_race.validate_lock_acquire(&mut condvar.data_race, waiter.thread);
478 (waiter.thread, waiter.mutex)
483 /// Remove the thread from the queue of threads waiting on this conditional variable.
484 fn condvar_remove_waiter(&mut self, id: CondvarId, thread: ThreadId) {
485 let this = self.eval_context_mut();
486 this.machine.threads.sync.condvars[id].waiters.retain(|waiter| waiter.thread != thread);
489 fn futex_wait(&mut self, addr: u64, thread: ThreadId) {
490 let this = self.eval_context_mut();
491 let futex = &mut this.machine.threads.sync.futexes.entry(addr).or_default();
492 let waiters = &mut futex.waiters;
493 assert!(waiters.iter().all(|waiter| waiter.thread != thread), "thread is already waiting");
494 waiters.push_back(FutexWaiter { thread });
497 fn futex_wake(&mut self, addr: u64) -> Option<ThreadId> {
498 let this = self.eval_context_mut();
499 let current_thread = this.get_active_thread();
500 let futex = &mut this.machine.threads.sync.futexes.get_mut(&addr)?;
501 let data_race = &this.memory.extra.data_race;
503 // Each futex-wake happens-before the end of the futex wait
504 if let Some(data_race) = data_race {
505 data_race.validate_lock_release(&mut futex.data_race, current_thread);
507 let res = futex.waiters.pop_front().map(|waiter| {
508 if let Some(data_race) = data_race {
509 data_race.validate_lock_acquire(&futex.data_race, waiter.thread);
516 fn futex_remove_waiter(&mut self, addr: u64, thread: ThreadId) {
517 let this = self.eval_context_mut();
518 if let Some(futex) = this.machine.threads.sync.futexes.get_mut(&addr) {
519 futex.waiters.retain(|waiter| waiter.thread != thread);