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 $name(NonZeroU32::new(u32::try_from(idx).unwrap() + 1).unwrap())
35 fn index(self) -> usize {
36 // See the comment in `Self::new`.
37 usize::try_from(self.0.get() - 1).unwrap()
42 pub fn to_u32_scalar<'tcx>(&self) -> Scalar<Tag> {
43 Scalar::from_u32(self.0.get())
52 #[derive(Default, Debug)]
54 /// The thread that currently owns the lock.
55 owner: Option<ThreadId>,
56 /// How many times the mutex was locked by the owner.
58 /// The queue of threads waiting for this mutex.
59 queue: VecDeque<ThreadId>,
62 declare_id!(RwLockId);
64 /// The read-write lock state.
65 #[derive(Default, Debug)]
67 /// The writer thread that currently owns the lock.
68 writer: Option<ThreadId>,
69 /// The readers that currently own the lock and how many times they acquired
71 readers: HashMap<ThreadId, usize>,
72 /// The queue of writer threads waiting for this lock.
73 writer_queue: VecDeque<ThreadId>,
74 /// The queue of reader threads waiting for this lock.
75 reader_queue: VecDeque<ThreadId>,
78 declare_id!(CondvarId);
80 /// A thread waiting on a conditional variable.
82 struct CondvarWaiter {
83 /// The thread that is waiting on this variable.
85 /// The mutex on which the thread is waiting.
89 /// The conditional variable state.
90 #[derive(Default, Debug)]
92 waiters: VecDeque<CondvarWaiter>,
95 /// The state of all synchronization variables.
96 #[derive(Default, Debug)]
97 pub(super) struct SynchronizationState {
98 mutexes: IndexVec<MutexId, Mutex>,
99 rwlocks: IndexVec<RwLockId, RwLock>,
100 condvars: IndexVec<CondvarId, Condvar>,
103 // Public interface to synchronization primitives. Please note that in most
104 // cases, the function calls are infallible and it is the client's (shim
105 // implementation's) responsibility to detect and deal with erroneous
107 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
108 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
110 /// Create state for a new mutex.
111 fn mutex_create(&mut self) -> MutexId {
112 let this = self.eval_context_mut();
113 this.machine.threads.sync.mutexes.push(Default::default())
117 /// Get the id of the thread that currently owns this lock.
118 fn mutex_get_owner(&mut self, id: MutexId) -> ThreadId {
119 let this = self.eval_context_ref();
120 this.machine.threads.sync.mutexes[id].owner.unwrap()
125 fn mutex_is_locked(&mut self, id: MutexId) -> bool {
126 let this = self.eval_context_mut();
127 this.machine.threads.sync.mutexes[id].owner.is_some()
130 /// Lock by setting the mutex owner and increasing the lock count.
131 fn mutex_lock(&mut self, id: MutexId, thread: ThreadId) {
132 let this = self.eval_context_mut();
133 let mutex = &mut this.machine.threads.sync.mutexes[id];
134 if let Some(current_owner) = mutex.owner {
135 assert_eq!(thread, current_owner, "mutex already locked by another thread");
137 mutex.lock_count > 0,
138 "invariant violation: lock_count == 0 iff the thread is unlocked"
141 mutex.owner = Some(thread);
143 mutex.lock_count = mutex.lock_count.checked_add(1).unwrap();
146 /// Try unlocking by decreasing the lock count and returning the old owner
147 /// and the old lock count. If the lock count reaches 0, release the lock
148 /// and potentially give to a new owner. If the lock was not locked, return
151 /// Note: It is the caller's responsibility to check that the thread that
152 /// unlocked the lock actually is the same one, which owned it.
153 fn mutex_unlock(&mut self, id: MutexId) -> InterpResult<'tcx, Option<(ThreadId, usize)>> {
154 let this = self.eval_context_mut();
155 let mutex = &mut this.machine.threads.sync.mutexes[id];
156 if let Some(current_owner) = mutex.owner {
158 let old_lock_count = mutex.lock_count;
159 mutex.lock_count = old_lock_count
161 .expect("invariant violation: lock_count == 0 iff the thread is unlocked");
162 if mutex.lock_count == 0 {
164 // The mutex is completely unlocked. Try transfering ownership
165 // to another thread.
166 if let Some(new_owner) = this.mutex_dequeue(id) {
167 this.mutex_lock(id, new_owner);
168 this.unblock_thread(new_owner)?;
171 Ok(Some((current_owner, old_lock_count)))
173 // Mutex is unlocked.
179 /// Put the thread into the queue waiting for the lock.
180 fn mutex_enqueue(&mut self, id: MutexId, thread: ThreadId) {
181 let this = self.eval_context_mut();
182 this.machine.threads.sync.mutexes[id].queue.push_back(thread);
186 /// Take a thread out of the queue waiting for the lock.
187 fn mutex_dequeue(&mut self, id: MutexId) -> Option<ThreadId> {
188 let this = self.eval_context_mut();
189 this.machine.threads.sync.mutexes[id].queue.pop_front()
193 /// Create state for a new read write lock.
194 fn rwlock_create(&mut self) -> RwLockId {
195 let this = self.eval_context_mut();
196 this.machine.threads.sync.rwlocks.push(Default::default())
201 fn rwlock_is_locked(&mut self, id: RwLockId) -> bool {
202 let this = self.eval_context_mut();
203 this.machine.threads.sync.rwlocks[id].writer.is_some()
204 || this.machine.threads.sync.rwlocks[id].readers.is_empty().not()
208 /// Check if write locked.
209 fn rwlock_is_write_locked(&mut self, id: RwLockId) -> bool {
210 let this = self.eval_context_mut();
211 this.machine.threads.sync.rwlocks[id].writer.is_some()
214 /// Read-lock the lock by adding the `reader` the list of threads that own
216 fn rwlock_reader_lock(&mut self, id: RwLockId, reader: ThreadId) {
217 let this = self.eval_context_mut();
218 assert!(!this.rwlock_is_write_locked(id), "the lock is write locked");
219 let count = this.machine.threads.sync.rwlocks[id].readers.entry(reader).or_insert(0);
220 *count = count.checked_add(1).expect("the reader counter overflowed");
223 /// Try read-unlock the lock for `reader`. Returns `true` if succeeded,
224 /// `false` if this `reader` did not hold the lock.
225 fn rwlock_reader_unlock(&mut self, id: RwLockId, reader: ThreadId) -> bool {
226 let this = self.eval_context_mut();
227 match this.machine.threads.sync.rwlocks[id].readers.entry(reader) {
228 Entry::Occupied(mut entry) => {
229 let count = entry.get_mut();
236 Entry::Vacant(_) => false,
241 /// Put the reader in the queue waiting for the lock and block it.
242 fn rwlock_enqueue_and_block_reader(
246 ) -> InterpResult<'tcx> {
247 let this = self.eval_context_mut();
248 assert!(this.rwlock_is_write_locked(id), "queueing on not write locked lock");
249 this.machine.threads.sync.rwlocks[id].reader_queue.push_back(reader);
250 this.block_thread(reader)
254 /// Take a reader out the queue waiting for the lock.
255 fn rwlock_dequeue_reader(&mut self, id: RwLockId) -> Option<ThreadId> {
256 let this = self.eval_context_mut();
257 this.machine.threads.sync.rwlocks[id].reader_queue.pop_front()
261 /// Lock by setting the writer that owns the lock.
262 fn rwlock_writer_lock(&mut self, id: RwLockId, writer: ThreadId) {
263 let this = self.eval_context_mut();
264 assert!(!this.rwlock_is_locked(id), "the lock is already locked");
265 this.machine.threads.sync.rwlocks[id].writer = Some(writer);
269 /// Try to unlock by removing the writer.
270 fn rwlock_writer_unlock(&mut self, id: RwLockId) -> Option<ThreadId> {
271 let this = self.eval_context_mut();
272 this.machine.threads.sync.rwlocks[id].writer.take()
276 /// Put the writer in the queue waiting for the lock.
277 fn rwlock_enqueue_and_block_writer(
281 ) -> InterpResult<'tcx> {
282 let this = self.eval_context_mut();
283 assert!(this.rwlock_is_locked(id), "queueing on unlocked lock");
284 this.machine.threads.sync.rwlocks[id].writer_queue.push_back(writer);
285 this.block_thread(writer)
289 /// Take the writer out the queue waiting for the lock.
290 fn rwlock_dequeue_writer(&mut self, id: RwLockId) -> Option<ThreadId> {
291 let this = self.eval_context_mut();
292 this.machine.threads.sync.rwlocks[id].writer_queue.pop_front()
296 /// Create state for a new conditional variable.
297 fn condvar_create(&mut self) -> CondvarId {
298 let this = self.eval_context_mut();
299 this.machine.threads.sync.condvars.push(Default::default())
303 /// Is the conditional variable awaited?
304 fn condvar_is_awaited(&mut self, id: CondvarId) -> bool {
305 let this = self.eval_context_mut();
306 !this.machine.threads.sync.condvars[id].waiters.is_empty()
309 /// Mark that the thread is waiting on the conditional variable.
310 fn condvar_wait(&mut self, id: CondvarId, thread: ThreadId, mutex: MutexId) {
311 let this = self.eval_context_mut();
312 let waiters = &mut this.machine.threads.sync.condvars[id].waiters;
313 assert!(waiters.iter().all(|waiter| waiter.thread != thread), "thread is already waiting");
314 waiters.push_back(CondvarWaiter { thread, mutex });
317 /// Wake up some thread (if there is any) sleeping on the conditional
319 fn condvar_signal(&mut self, id: CondvarId) -> Option<(ThreadId, MutexId)> {
320 let this = self.eval_context_mut();
321 this.machine.threads.sync.condvars[id]
324 .map(|waiter| (waiter.thread, waiter.mutex))
328 /// Remove the thread from the queue of threads waiting on this conditional variable.
329 fn condvar_remove_waiter(&mut self, id: CondvarId, thread: ThreadId) {
330 let this = self.eval_context_mut();
331 this.machine.threads.sync.condvars[id].waiters.retain(|waiter| waiter.thread != thread);