1 use std::collections::{hash_map::Entry, HashMap, VecDeque};
2 use std::convert::TryFrom;
3 use std::num::NonZeroU32;
6 use rustc_index::vec::{Idx, IndexVec};
10 /// We cannot use the `newtype_index!` macro because we have to use 0 as a
11 /// sentinel value meaning that the identifier is not assigned. This is because
12 /// the pthreads static initializers initialize memory with zeros (see the
13 /// `src/shims/sync.rs` file).
14 macro_rules! declare_id {
16 /// 0 is used to indicate that the id was not yet assigned and,
17 /// therefore, is not a valid identifier.
18 #[derive(Clone, Copy, Debug, PartialOrd, Ord, PartialEq, Eq, Hash)]
19 pub struct $name(NonZeroU32);
22 // Panics if `id == 0`.
23 pub fn from_u32(id: u32) -> Self {
24 Self(NonZeroU32::new(id).unwrap())
29 fn new(idx: usize) -> Self {
30 // We use 0 as a sentinel value (see the comment above) and,
31 // therefore, need to shift by one when converting from an index
33 let shifted_idx = u32::try_from(idx).unwrap().checked_add(1).unwrap();
34 $name(NonZeroU32::new(shifted_idx).unwrap())
36 fn index(self) -> usize {
37 // See the comment in `Self::new`.
38 // (This cannot underflow because self is NonZeroU32.)
39 usize::try_from(self.0.get() - 1).unwrap()
44 pub fn to_u32_scalar<'tcx>(&self) -> Scalar<Tag> {
45 Scalar::from_u32(self.0.get())
54 #[derive(Default, Debug)]
56 /// The thread that currently owns the lock.
57 owner: Option<ThreadId>,
58 /// How many times the mutex was locked by the owner.
60 /// The queue of threads waiting for this mutex.
61 queue: VecDeque<ThreadId>,
64 declare_id!(RwLockId);
66 /// The read-write lock state.
67 #[derive(Default, Debug)]
69 /// The writer thread that currently owns the lock.
70 writer: Option<ThreadId>,
71 /// The readers that currently own the lock and how many times they acquired
73 readers: HashMap<ThreadId, usize>,
74 /// The queue of writer threads waiting for this lock.
75 writer_queue: VecDeque<ThreadId>,
76 /// The queue of reader threads waiting for this lock.
77 reader_queue: VecDeque<ThreadId>,
80 declare_id!(CondvarId);
82 /// A thread waiting on a conditional variable.
84 struct CondvarWaiter {
85 /// The thread that is waiting on this variable.
87 /// The mutex on which the thread is waiting.
91 /// The conditional variable state.
92 #[derive(Default, Debug)]
94 waiters: VecDeque<CondvarWaiter>,
97 /// The state of all synchronization variables.
98 #[derive(Default, Debug)]
99 pub(super) struct SynchronizationState {
100 mutexes: IndexVec<MutexId, Mutex>,
101 rwlocks: IndexVec<RwLockId, RwLock>,
102 condvars: IndexVec<CondvarId, Condvar>,
105 // Public interface to synchronization primitives. Please note that in most
106 // cases, the function calls are infallible and it is the client's (shim
107 // implementation's) responsibility to detect and deal with erroneous
109 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
110 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
112 /// Create state for a new mutex.
113 fn mutex_create(&mut self) -> MutexId {
114 let this = self.eval_context_mut();
115 this.machine.threads.sync.mutexes.push(Default::default())
119 /// Get the id of the thread that currently owns this lock.
120 fn mutex_get_owner(&mut self, id: MutexId) -> ThreadId {
121 let this = self.eval_context_ref();
122 this.machine.threads.sync.mutexes[id].owner.unwrap()
127 fn mutex_is_locked(&mut self, id: MutexId) -> bool {
128 let this = self.eval_context_mut();
129 this.machine.threads.sync.mutexes[id].owner.is_some()
132 /// Lock by setting the mutex owner and increasing the lock count.
133 fn mutex_lock(&mut self, id: MutexId, thread: ThreadId) {
134 let this = self.eval_context_mut();
135 let mutex = &mut this.machine.threads.sync.mutexes[id];
136 if let Some(current_owner) = mutex.owner {
137 assert_eq!(thread, current_owner, "mutex already locked by another thread");
139 mutex.lock_count > 0,
140 "invariant violation: lock_count == 0 iff the thread is unlocked"
143 mutex.owner = Some(thread);
145 mutex.lock_count = mutex.lock_count.checked_add(1).unwrap();
148 /// Try unlocking by decreasing the lock count and returning the old lock
149 /// count. If the lock count reaches 0, release the lock and potentially
150 /// give to a new owner. If the lock was not locked by `expected_owner`,
155 expected_owner: ThreadId,
156 ) -> InterpResult<'tcx, Option<usize>> {
157 let this = self.eval_context_mut();
158 let mutex = &mut this.machine.threads.sync.mutexes[id];
159 if let Some(current_owner) = mutex.owner {
161 if current_owner != expected_owner {
162 // Only the owner can unlock the mutex.
165 let old_lock_count = mutex.lock_count;
166 mutex.lock_count = old_lock_count
168 .expect("invariant violation: lock_count == 0 iff the thread is unlocked");
169 if mutex.lock_count == 0 {
171 // The mutex is completely unlocked. Try transfering ownership
172 // to another thread.
173 this.mutex_dequeue_and_lock(id);
175 Ok(Some(old_lock_count))
177 // Mutex is unlocked.
183 /// Put the thread into the queue waiting for the mutex.
184 fn mutex_enqueue_and_block(&mut self, id: MutexId, thread: ThreadId) {
185 let this = self.eval_context_mut();
186 assert!(this.mutex_is_locked(id), "queing on unlocked mutex");
187 this.machine.threads.sync.mutexes[id].queue.push_back(thread);
188 this.block_thread(thread);
192 /// Take a thread out of the queue waiting for the mutex, and lock
193 /// the mutex for it. Returns `true` if some thread has the mutex now.
194 fn mutex_dequeue_and_lock(&mut self, id: MutexId) -> bool {
195 let this = self.eval_context_mut();
196 if let Some(thread) = this.machine.threads.sync.mutexes[id].queue.pop_front() {
197 this.unblock_thread(thread);
198 this.mutex_lock(id, thread);
206 /// Create state for a new read write lock.
207 fn rwlock_create(&mut self) -> RwLockId {
208 let this = self.eval_context_mut();
209 this.machine.threads.sync.rwlocks.push(Default::default())
214 fn rwlock_is_locked(&mut self, id: RwLockId) -> bool {
215 let this = self.eval_context_mut();
216 this.machine.threads.sync.rwlocks[id].writer.is_some()
217 || this.machine.threads.sync.rwlocks[id].readers.is_empty().not()
221 /// Check if write locked.
222 fn rwlock_is_write_locked(&mut self, id: RwLockId) -> bool {
223 let this = self.eval_context_mut();
224 this.machine.threads.sync.rwlocks[id].writer.is_some()
227 /// Read-lock the lock by adding the `reader` the list of threads that own
229 fn rwlock_reader_lock(&mut self, id: RwLockId, reader: ThreadId) {
230 let this = self.eval_context_mut();
231 assert!(!this.rwlock_is_write_locked(id), "the lock is write locked");
232 let count = this.machine.threads.sync.rwlocks[id].readers.entry(reader).or_insert(0);
233 *count = count.checked_add(1).expect("the reader counter overflowed");
236 /// Try read-unlock the lock for `reader`. Returns `true` if succeeded,
237 /// `false` if this `reader` did not hold the lock.
238 fn rwlock_reader_unlock(&mut self, id: RwLockId, reader: ThreadId) -> bool {
239 let this = self.eval_context_mut();
240 match this.machine.threads.sync.rwlocks[id].readers.entry(reader) {
241 Entry::Occupied(mut entry) => {
242 let count = entry.get_mut();
243 assert!(*count > 0, "rwlock locked with count == 0");
250 Entry::Vacant(_) => false,
255 /// Put the reader in the queue waiting for the lock and block it.
256 fn rwlock_enqueue_and_block_reader(
261 let this = self.eval_context_mut();
262 assert!(this.rwlock_is_write_locked(id), "queueing on not write locked lock");
263 this.machine.threads.sync.rwlocks[id].reader_queue.push_back(reader);
264 this.block_thread(reader);
268 /// Take a reader out the queue waiting for the lock.
269 /// Returns `true` if some thread got the rwlock.
270 fn rwlock_dequeue_and_lock_reader(&mut self, id: RwLockId) -> bool {
271 let this = self.eval_context_mut();
272 if let Some(reader) = this.machine.threads.sync.rwlocks[id].reader_queue.pop_front() {
273 this.unblock_thread(reader);
274 this.rwlock_reader_lock(id, reader);
282 /// Lock by setting the writer that owns the lock.
283 fn rwlock_writer_lock(&mut self, id: RwLockId, writer: ThreadId) {
284 let this = self.eval_context_mut();
285 assert!(!this.rwlock_is_locked(id), "the rwlock is already locked");
286 this.machine.threads.sync.rwlocks[id].writer = Some(writer);
290 /// Try to unlock by removing the writer.
291 fn rwlock_writer_unlock(&mut self, id: RwLockId) -> Option<ThreadId> {
292 let this = self.eval_context_mut();
293 this.machine.threads.sync.rwlocks[id].writer.take()
297 /// Put the writer in the queue waiting for the lock.
298 fn rwlock_enqueue_and_block_writer(
303 let this = self.eval_context_mut();
304 assert!(this.rwlock_is_locked(id), "queueing on unlocked lock");
305 this.machine.threads.sync.rwlocks[id].writer_queue.push_back(writer);
306 this.block_thread(writer);
310 /// Take the writer out the queue waiting for the lock.
311 /// Returns `true` if some thread got the rwlock.
312 fn rwlock_dequeue_and_lock_writer(&mut self, id: RwLockId) -> bool {
313 let this = self.eval_context_mut();
314 if let Some(writer) = this.machine.threads.sync.rwlocks[id].writer_queue.pop_front() {
315 this.unblock_thread(writer);
316 this.rwlock_writer_lock(id, writer);
324 /// Create state for a new conditional variable.
325 fn condvar_create(&mut self) -> CondvarId {
326 let this = self.eval_context_mut();
327 this.machine.threads.sync.condvars.push(Default::default())
331 /// Is the conditional variable awaited?
332 fn condvar_is_awaited(&mut self, id: CondvarId) -> bool {
333 let this = self.eval_context_mut();
334 !this.machine.threads.sync.condvars[id].waiters.is_empty()
337 /// Mark that the thread is waiting on the conditional variable.
338 fn condvar_wait(&mut self, id: CondvarId, thread: ThreadId, mutex: MutexId) {
339 let this = self.eval_context_mut();
340 let waiters = &mut this.machine.threads.sync.condvars[id].waiters;
341 assert!(waiters.iter().all(|waiter| waiter.thread != thread), "thread is already waiting");
342 waiters.push_back(CondvarWaiter { thread, mutex });
345 /// Wake up some thread (if there is any) sleeping on the conditional
347 fn condvar_signal(&mut self, id: CondvarId) -> Option<(ThreadId, MutexId)> {
348 let this = self.eval_context_mut();
349 this.machine.threads.sync.condvars[id]
352 .map(|waiter| (waiter.thread, waiter.mutex))
356 /// Remove the thread from the queue of threads waiting on this conditional variable.
357 fn condvar_remove_waiter(&mut self, id: CondvarId, thread: ThreadId) {
358 let this = self.eval_context_mut();
359 this.machine.threads.sync.condvars[id].waiters.retain(|waiter| waiter.thread != thread);