]> git.lizzy.rs Git - rust.git/blob - src/sync.rs
add an assertion
[rust.git] / src / sync.rs
1 use std::collections::{hash_map::Entry, HashMap, VecDeque};
2 use std::convert::TryFrom;
3 use std::num::NonZeroU32;
4 use std::ops::Not;
5
6 use rustc_index::vec::{Idx, IndexVec};
7
8 use crate::*;
9
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 {
15     ($name: ident) => {
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);
20
21         impl $name {
22             // Panics if `id == 0`.
23             pub fn from_u32(id: u32) -> Self {
24                 Self(NonZeroU32::new(id).unwrap())
25             }
26         }
27
28         impl Idx for $name {
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
32                 // into a vector.
33                 let shifted_idx = u32::try_from(idx).unwrap().checked_add(1).unwrap();
34                 $name(NonZeroU32::new(shifted_idx).unwrap())
35             }
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()
40             }
41         }
42
43         impl $name {
44             pub fn to_u32_scalar<'tcx>(&self) -> Scalar<Tag> {
45                 Scalar::from_u32(self.0.get())
46             }
47         }
48     };
49 }
50
51 declare_id!(MutexId);
52
53 /// The mutex state.
54 #[derive(Default, Debug)]
55 struct Mutex {
56     /// The thread that currently owns the lock.
57     owner: Option<ThreadId>,
58     /// How many times the mutex was locked by the owner.
59     lock_count: usize,
60     /// The queue of threads waiting for this mutex.
61     queue: VecDeque<ThreadId>,
62 }
63
64 declare_id!(RwLockId);
65
66 /// The read-write lock state.
67 #[derive(Default, Debug)]
68 struct RwLock {
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
72     /// the lock.
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>,
78 }
79
80 declare_id!(CondvarId);
81
82 /// A thread waiting on a conditional variable.
83 #[derive(Debug)]
84 struct CondvarWaiter {
85     /// The thread that is waiting on this variable.
86     thread: ThreadId,
87     /// The mutex on which the thread is waiting.
88     mutex: MutexId,
89 }
90
91 /// The conditional variable state.
92 #[derive(Default, Debug)]
93 struct Condvar {
94     waiters: VecDeque<CondvarWaiter>,
95 }
96
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>,
103 }
104
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
108 // situations.
109 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
110 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
111     #[inline]
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())
116     }
117
118     #[inline]
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()
123     }
124
125     #[inline]
126     /// Check if locked.
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()
130     }
131
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");
138             assert!(
139                 mutex.lock_count > 0,
140                 "invariant violation: lock_count == 0 iff the thread is unlocked"
141             );
142         } else {
143             mutex.owner = Some(thread);
144         }
145         mutex.lock_count = mutex.lock_count.checked_add(1).unwrap();
146     }
147
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
151     /// `None`.
152     ///
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.
155     fn mutex_unlock(
156         &mut self,
157         id: MutexId,
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 {
163             // Mutex is locked.
164             if current_owner != expected_owner {
165                 // Only the owner can unlock the mutex.
166                 return Ok(None);
167             }
168             let old_lock_count = mutex.lock_count;
169             mutex.lock_count = old_lock_count
170                 .checked_sub(1)
171                 .expect("invariant violation: lock_count == 0 iff the thread is unlocked");
172             if mutex.lock_count == 0 {
173                 mutex.owner = None;
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)?;
179                 }
180             }
181             Ok(Some(old_lock_count))
182         } else {
183             // Mutex is unlocked.
184             Ok(None)
185         }
186     }
187
188     #[inline]
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);
194     }
195
196     #[inline]
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()
201     }
202
203     #[inline]
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())
208     }
209
210     #[inline]
211     /// Check if locked.
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()
216     }
217
218     #[inline]
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()
223     }
224
225     /// Read-lock the lock by adding the `reader` the list of threads that own
226     /// this lock.
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");
232     }
233
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");
242                 *count -= 1;
243                 if *count == 0 {
244                     entry.remove();
245                 }
246                 true
247             }
248             Entry::Vacant(_) => false,
249         }
250     }
251
252     #[inline]
253     /// Put the reader in the queue waiting for the lock and block it.
254     fn rwlock_enqueue_and_block_reader(
255         &mut self,
256         id: RwLockId,
257         reader: ThreadId,
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)
263     }
264
265     #[inline]
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()
270     }
271
272     #[inline]
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);
278     }
279
280     #[inline]
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()
285     }
286
287     #[inline]
288     /// Put the writer in the queue waiting for the lock.
289     fn rwlock_enqueue_and_block_writer(
290         &mut self,
291         id: RwLockId,
292         writer: ThreadId,
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)
298     }
299
300     #[inline]
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()
305     }
306
307     #[inline]
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())
312     }
313
314     #[inline]
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()
319     }
320
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 });
327     }
328
329     /// Wake up some thread (if there is any) sleeping on the conditional
330     /// variable.
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]
334             .waiters
335             .pop_front()
336             .map(|waiter| (waiter.thread, waiter.mutex))
337     }
338
339     #[inline]
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);
344     }
345 }