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 owner
149 /// and the old lock count. If the lock count reaches 0, release the lock
150 /// and potentially give to a new owner. If the lock was not locked, return
153 /// Note: It is the caller's responsibility to check that the thread that
154 /// unlocked the lock actually is the same one, which owned it.
158 expected_owner: ThreadId,
159 ) -> InterpResult<'tcx, Option<usize>> {
160 let this = self.eval_context_mut();
161 let mutex = &mut this.machine.threads.sync.mutexes[id];
162 if let Some(current_owner) = mutex.owner {
164 if current_owner != expected_owner {
165 // Only the owner can unlock the mutex.
168 let old_lock_count = mutex.lock_count;
169 mutex.lock_count = old_lock_count
171 .expect("invariant violation: lock_count == 0 iff the thread is unlocked");
172 if mutex.lock_count == 0 {
174 // The mutex is completely unlocked. Try transfering ownership
175 // to another thread.
176 if let Some(new_owner) = this.mutex_dequeue(id) {
177 this.mutex_lock(id, new_owner);
178 this.unblock_thread(new_owner)?;
181 Ok(Some(old_lock_count))
183 // Mutex is unlocked.
189 /// Put the thread into the queue waiting for the lock.
190 fn mutex_enqueue(&mut self, id: MutexId, thread: ThreadId) {
191 let this = self.eval_context_mut();
192 assert!(this.mutex_is_locked(id), "queing on unlocked mutex");
193 this.machine.threads.sync.mutexes[id].queue.push_back(thread);
197 /// Take a thread out of the queue waiting for the lock.
198 fn mutex_dequeue(&mut self, id: MutexId) -> Option<ThreadId> {
199 let this = self.eval_context_mut();
200 this.machine.threads.sync.mutexes[id].queue.pop_front()
204 /// Create state for a new read write lock.
205 fn rwlock_create(&mut self) -> RwLockId {
206 let this = self.eval_context_mut();
207 this.machine.threads.sync.rwlocks.push(Default::default())
212 fn rwlock_is_locked(&mut self, id: RwLockId) -> bool {
213 let this = self.eval_context_mut();
214 this.machine.threads.sync.rwlocks[id].writer.is_some()
215 || this.machine.threads.sync.rwlocks[id].readers.is_empty().not()
219 /// Check if write locked.
220 fn rwlock_is_write_locked(&mut self, id: RwLockId) -> bool {
221 let this = self.eval_context_mut();
222 this.machine.threads.sync.rwlocks[id].writer.is_some()
225 /// Read-lock the lock by adding the `reader` the list of threads that own
227 fn rwlock_reader_lock(&mut self, id: RwLockId, reader: ThreadId) {
228 let this = self.eval_context_mut();
229 assert!(!this.rwlock_is_write_locked(id), "the lock is write locked");
230 let count = this.machine.threads.sync.rwlocks[id].readers.entry(reader).or_insert(0);
231 *count = count.checked_add(1).expect("the reader counter overflowed");
234 /// Try read-unlock the lock for `reader`. Returns `true` if succeeded,
235 /// `false` if this `reader` did not hold the lock.
236 fn rwlock_reader_unlock(&mut self, id: RwLockId, reader: ThreadId) -> bool {
237 let this = self.eval_context_mut();
238 match this.machine.threads.sync.rwlocks[id].readers.entry(reader) {
239 Entry::Occupied(mut entry) => {
240 let count = entry.get_mut();
241 assert!(*count > 0, "rwlock locked with count == 0");
248 Entry::Vacant(_) => false,
253 /// Put the reader in the queue waiting for the lock and block it.
254 fn rwlock_enqueue_and_block_reader(
258 ) -> InterpResult<'tcx> {
259 let this = self.eval_context_mut();
260 assert!(this.rwlock_is_write_locked(id), "queueing on not write locked lock");
261 this.machine.threads.sync.rwlocks[id].reader_queue.push_back(reader);
262 this.block_thread(reader)
266 /// Take a reader out the queue waiting for the lock.
267 fn rwlock_dequeue_reader(&mut self, id: RwLockId) -> Option<ThreadId> {
268 let this = self.eval_context_mut();
269 this.machine.threads.sync.rwlocks[id].reader_queue.pop_front()
273 /// Lock by setting the writer that owns the lock.
274 fn rwlock_writer_lock(&mut self, id: RwLockId, writer: ThreadId) {
275 let this = self.eval_context_mut();
276 assert!(!this.rwlock_is_locked(id), "the lock is already locked");
277 this.machine.threads.sync.rwlocks[id].writer = Some(writer);
281 /// Try to unlock by removing the writer.
282 fn rwlock_writer_unlock(&mut self, id: RwLockId) -> Option<ThreadId> {
283 let this = self.eval_context_mut();
284 this.machine.threads.sync.rwlocks[id].writer.take()
288 /// Put the writer in the queue waiting for the lock.
289 fn rwlock_enqueue_and_block_writer(
293 ) -> InterpResult<'tcx> {
294 let this = self.eval_context_mut();
295 assert!(this.rwlock_is_locked(id), "queueing on unlocked lock");
296 this.machine.threads.sync.rwlocks[id].writer_queue.push_back(writer);
297 this.block_thread(writer)
301 /// Take the writer out the queue waiting for the lock.
302 fn rwlock_dequeue_writer(&mut self, id: RwLockId) -> Option<ThreadId> {
303 let this = self.eval_context_mut();
304 this.machine.threads.sync.rwlocks[id].writer_queue.pop_front()
308 /// Create state for a new conditional variable.
309 fn condvar_create(&mut self) -> CondvarId {
310 let this = self.eval_context_mut();
311 this.machine.threads.sync.condvars.push(Default::default())
315 /// Is the conditional variable awaited?
316 fn condvar_is_awaited(&mut self, id: CondvarId) -> bool {
317 let this = self.eval_context_mut();
318 !this.machine.threads.sync.condvars[id].waiters.is_empty()
321 /// Mark that the thread is waiting on the conditional variable.
322 fn condvar_wait(&mut self, id: CondvarId, thread: ThreadId, mutex: MutexId) {
323 let this = self.eval_context_mut();
324 let waiters = &mut this.machine.threads.sync.condvars[id].waiters;
325 assert!(waiters.iter().all(|waiter| waiter.thread != thread), "thread is already waiting");
326 waiters.push_back(CondvarWaiter { thread, mutex });
329 /// Wake up some thread (if there is any) sleeping on the conditional
331 fn condvar_signal(&mut self, id: CondvarId) -> Option<(ThreadId, MutexId)> {
332 let this = self.eval_context_mut();
333 this.machine.threads.sync.condvars[id]
336 .map(|waiter| (waiter.thread, waiter.mutex))
340 /// Remove the thread from the queue of threads waiting on this conditional variable.
341 fn condvar_remove_waiter(&mut self, id: CondvarId, thread: ThreadId) {
342 let this = self.eval_context_mut();
343 this.machine.threads.sync.condvars[id].waiters.retain(|waiter| waiter.thread != thread);