1use std::any::Any;
2use std::cell::RefCell;
3use std::collections::VecDeque;
4use std::collections::hash_map::Entry;
5use std::default::Default;
6use std::ops::Not;
7use std::rc::Rc;
8use std::{fmt, iter};
9
10use rustc_abi::Size;
11use rustc_data_structures::fx::FxHashMap;
12
13use super::vector_clock::VClock;
14use crate::*;
15
16#[derive(Copy, Clone, Hash, PartialEq, Eq, Debug)]
18pub enum AccessKind {
19 Read,
20 Write,
21 Dealloc,
22}
23
24impl fmt::Display for AccessKind {
25 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26 match self {
27 AccessKind::Read => write!(f, "read"),
28 AccessKind::Write => write!(f, "write"),
29 AccessKind::Dealloc => write!(f, "deallocation"),
30 }
31 }
32}
33
34pub trait SyncObj: Any {
36 fn on_access<'tcx>(&self, _access_kind: AccessKind) -> InterpResult<'tcx> {
38 interp_ok(())
39 }
40
41 fn delete_on_write(&self) -> bool {
44 false
45 }
46}
47
48impl dyn SyncObj {
49 #[inline(always)]
50 pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
51 let x: &dyn Any = self;
52 x.downcast_ref()
53 }
54}
55
56impl fmt::Debug for dyn SyncObj {
57 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58 f.debug_struct("SyncObj").finish_non_exhaustive()
59 }
60}
61
62#[derive(Default, Debug)]
64struct Mutex {
65 owner: Option<ThreadId>,
67 lock_count: usize,
69 queue: VecDeque<ThreadId>,
71 clock: VClock,
73}
74
75#[derive(Default, Clone, Debug)]
76pub struct MutexRef(Rc<RefCell<Mutex>>);
77
78impl MutexRef {
79 pub fn new() -> Self {
80 Self(Default::default())
81 }
82
83 pub fn owner(&self) -> Option<ThreadId> {
85 self.0.borrow().owner
86 }
87
88 pub fn queue_is_empty(&self) -> bool {
89 self.0.borrow().queue.is_empty()
90 }
91}
92
93impl VisitProvenance for MutexRef {
94 fn visit_provenance(&self, _visit: &mut VisitWith<'_>) {}
96}
97
98#[derive(Default, Debug)]
100struct RwLock {
101 writer: Option<ThreadId>,
103 readers: FxHashMap<ThreadId, usize>,
106 writer_queue: VecDeque<ThreadId>,
108 reader_queue: VecDeque<ThreadId>,
110 clock_unlocked: VClock,
119 clock_current_readers: VClock,
130}
131
132impl RwLock {
133 #[inline]
134 fn is_locked(&self) -> bool {
136 trace!(
137 "rwlock_is_locked: writer is {:?} and there are {} reader threads (some of which could hold multiple read locks)",
138 self.writer,
139 self.readers.len(),
140 );
141 self.writer.is_some() || self.readers.is_empty().not()
142 }
143
144 #[inline]
146 fn is_write_locked(&self) -> bool {
147 trace!("rwlock_is_write_locked: writer is {:?}", self.writer);
148 self.writer.is_some()
149 }
150}
151
152#[derive(Default, Clone, Debug)]
153pub struct RwLockRef(Rc<RefCell<RwLock>>);
154
155impl RwLockRef {
156 pub fn new() -> Self {
157 Self(Default::default())
158 }
159
160 pub fn is_locked(&self) -> bool {
161 self.0.borrow().is_locked()
162 }
163
164 pub fn is_write_locked(&self) -> bool {
165 self.0.borrow().is_write_locked()
166 }
167
168 pub fn queue_is_empty(&self) -> bool {
169 let inner = self.0.borrow();
170 inner.reader_queue.is_empty() && inner.writer_queue.is_empty()
171 }
172}
173
174impl VisitProvenance for RwLockRef {
175 fn visit_provenance(&self, _visit: &mut VisitWith<'_>) {}
177}
178
179#[derive(Default, Debug)]
181struct Condvar {
182 waiters: VecDeque<ThreadId>,
183 clock: VClock,
189}
190
191#[derive(Default, Clone, Debug)]
192pub struct CondvarRef(Rc<RefCell<Condvar>>);
193
194impl CondvarRef {
195 pub fn new() -> Self {
196 Self(Default::default())
197 }
198
199 pub fn queue_is_empty(&self) -> bool {
200 self.0.borrow().waiters.is_empty()
201 }
202}
203
204impl VisitProvenance for CondvarRef {
205 fn visit_provenance(&self, _visit: &mut VisitWith<'_>) {}
207}
208
209#[derive(Default, Debug)]
211struct Futex {
212 waiters: Vec<FutexWaiter>,
213 clock: VClock,
219}
220
221#[derive(Default, Clone, Debug)]
222pub struct FutexRef(Rc<RefCell<Futex>>);
223
224impl FutexRef {
225 pub fn new() -> Self {
226 Self(Default::default())
227 }
228
229 pub fn waiters(&self) -> usize {
230 self.0.borrow().waiters.len()
231 }
232}
233
234impl VisitProvenance for FutexRef {
235 fn visit_provenance(&self, _visit: &mut VisitWith<'_>) {}
237}
238
239#[derive(Debug)]
241struct FutexWaiter {
242 thread: ThreadId,
244 bitset: u32,
246}
247
248impl<'tcx> EvalContextExtPriv<'tcx> for crate::MiriInterpCx<'tcx> {}
250pub(super) trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> {
251 fn condvar_reacquire_mutex(
252 &mut self,
253 mutex_ref: MutexRef,
254 retval: Scalar,
255 dest: MPlaceTy<'tcx>,
256 ) -> InterpResult<'tcx> {
257 let this = self.eval_context_mut();
258 if let Some(owner) = mutex_ref.owner() {
259 assert_ne!(owner, this.active_thread());
260 this.mutex_enqueue_and_block(mutex_ref, Some((retval, dest)));
261 } else {
262 this.mutex_lock(&mutex_ref)?;
264 this.write_scalar(retval, &dest)?;
266 }
267 interp_ok(())
268 }
269}
270
271impl<'tcx> AllocExtra<'tcx> {
272 fn get_sync<T: 'static>(&self, offset: Size) -> Option<&T> {
273 self.sync_objs.get(&offset).and_then(|s| s.downcast_ref::<T>())
274 }
275}
276
277impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
282pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
283 fn get_sync_or_init<'a, T: SyncObj>(
288 &'a mut self,
289 ptr: Pointer,
290 new: impl FnOnce(&'a mut MiriMachine<'tcx>) -> T,
291 ) -> Option<&'a T>
292 where
293 'tcx: 'a,
294 {
295 let this = self.eval_context_mut();
296 if !this.ptr_try_get_alloc_id(ptr, 0).ok().is_some_and(|(alloc_id, offset, ..)| {
297 let info = this.get_alloc_info(alloc_id);
298 info.kind == AllocKind::LiveData && info.mutbl.is_mut() && offset < info.size
299 }) {
300 return None;
301 }
302 let (alloc, offset, _) = this.ptr_get_alloc_id(ptr, 0).unwrap();
304 let (alloc_extra, machine) = this.get_alloc_extra_mut(alloc).unwrap();
305 if alloc_extra.get_sync::<T>(offset).is_none() {
307 let new = new(machine);
308 alloc_extra.sync_objs.insert(offset, Box::new(new));
309 }
310 Some(alloc_extra.get_sync::<T>(offset).unwrap())
311 }
312
313 fn get_immovable_sync_with_static_init<'a, T: SyncObj>(
330 &'a mut self,
331 obj: &MPlaceTy<'tcx>,
332 init_offset: Size,
333 uninit_val: u8,
334 init_val: u8,
335 new_meta_obj: impl FnOnce(&mut MiriInterpCx<'tcx>) -> InterpResult<'tcx, T>,
336 ) -> InterpResult<'tcx, &'a T>
337 where
338 'tcx: 'a,
339 {
340 assert!(init_val != uninit_val);
341 let this = self.eval_context_mut();
342 this.check_ptr_access(obj.ptr(), obj.layout.size, CheckInAllocMsg::Dereferenceable)?;
343 assert!(init_offset < obj.layout.size); let init_field = obj.offset(init_offset, this.machine.layouts.u8, this)?;
345
346 let (alloc, offset, _) = this.ptr_get_alloc_id(init_field.ptr(), 0)?;
347 let (alloc_extra, _machine) = this.get_alloc_extra_mut(alloc)?;
348 if alloc_extra.get_sync::<T>(offset).is_some() {
350 let (alloc_extra, _machine) = this.get_alloc_extra_mut(alloc).unwrap();
351 return interp_ok(alloc_extra.get_sync::<T>(offset).unwrap());
352 }
353
354 let meta_obj = new_meta_obj(this)?;
356 let (old_init, success) = this
357 .atomic_compare_exchange_scalar(
358 &init_field,
359 &ImmTy::from_scalar(Scalar::from_u8(uninit_val), this.machine.layouts.u8),
360 Scalar::from_u8(init_val),
361 AtomicRwOrd::Relaxed,
362 AtomicReadOrd::Relaxed,
363 false,
364 )?
365 .to_scalar_pair();
366 if !success.to_bool()? {
367 assert_eq!(
369 old_init.to_u8()?,
370 init_val,
371 "`new_meta_obj` should have ensured that this CAS succeeds"
372 );
373 }
374
375 let (alloc_extra, _machine) = this.get_alloc_extra_mut(alloc).unwrap();
376 assert!(meta_obj.delete_on_write());
377 alloc_extra.sync_objs.insert(offset, Box::new(meta_obj));
378 interp_ok(alloc_extra.get_sync::<T>(offset).unwrap())
379 }
380
381 fn init_immovable_sync<'a, T: SyncObj>(
384 &'a mut self,
385 obj: &MPlaceTy<'tcx>,
386 init_offset: Size,
387 init_val: u8,
388 new_meta_obj: T,
389 ) -> InterpResult<'tcx, Option<&'a T>>
390 where
391 'tcx: 'a,
392 {
393 let this = self.eval_context_mut();
394 this.check_ptr_access(obj.ptr(), obj.layout.size, CheckInAllocMsg::Dereferenceable)?;
395 assert!(init_offset < obj.layout.size); let init_field = obj.offset(init_offset, this.machine.layouts.u8, this)?;
397
398 this.write_bytes_ptr(obj.ptr(), iter::repeat_n(0, obj.layout.size.bytes_usize()))?;
400 this.write_scalar(Scalar::from_u8(init_val), &init_field)?;
401
402 let (alloc, offset, _) = this.ptr_get_alloc_id(init_field.ptr(), 0)?;
404 let (alloc_extra, _machine) = this.get_alloc_extra_mut(alloc).unwrap();
405 assert!(new_meta_obj.delete_on_write());
406 alloc_extra.sync_objs.insert(offset, Box::new(new_meta_obj));
407 interp_ok(Some(alloc_extra.get_sync::<T>(offset).unwrap()))
408 }
409
410 fn mutex_lock(&mut self, mutex_ref: &MutexRef) -> InterpResult<'tcx> {
412 let this = self.eval_context_mut();
413 let thread = this.active_thread();
414 let mut mutex = mutex_ref.0.borrow_mut();
415 if let Some(current_owner) = mutex.owner {
416 assert_eq!(thread, current_owner, "mutex already locked by another thread");
417 assert!(
418 mutex.lock_count > 0,
419 "invariant violation: lock_count == 0 iff the thread is unlocked"
420 );
421 } else {
422 mutex.owner = Some(thread);
423 }
424 mutex.lock_count = mutex.lock_count.strict_add(1);
425 this.acquire_clock(&mutex.clock)?;
426 interp_ok(())
427 }
428
429 fn mutex_unlock(&mut self, mutex_ref: &MutexRef) -> InterpResult<'tcx, Option<usize>> {
434 let this = self.eval_context_mut();
435 let mut mutex = mutex_ref.0.borrow_mut();
436 interp_ok(if let Some(current_owner) = mutex.owner {
437 if current_owner != this.machine.threads.active_thread() {
439 return interp_ok(None);
441 }
442 let old_lock_count = mutex.lock_count;
443 mutex.lock_count = old_lock_count.strict_sub(1);
444 if mutex.lock_count == 0 {
445 mutex.owner = None;
446 this.release_clock(|clock| mutex.clock.clone_from(clock))?;
450 let thread_id = mutex.queue.pop_front();
451 drop(mutex);
454 if let Some(thread_id) = thread_id {
455 this.unblock_thread(thread_id, BlockReason::Mutex)?;
456 }
457 }
458 Some(old_lock_count)
459 } else {
460 None
462 })
463 }
464
465 #[inline]
470 fn mutex_enqueue_and_block(
471 &mut self,
472 mutex_ref: MutexRef,
473 retval_dest: Option<(Scalar, MPlaceTy<'tcx>)>,
474 ) {
475 let this = self.eval_context_mut();
476 let thread = this.active_thread();
477 let mut mutex = mutex_ref.0.borrow_mut();
478 mutex.queue.push_back(thread);
479 assert!(mutex.owner.is_some(), "queuing on unlocked mutex");
480 drop(mutex);
481 this.block_thread(
482 BlockReason::Mutex,
483 None,
484 callback!(
485 @capture<'tcx> {
486 mutex_ref: MutexRef,
487 retval_dest: Option<(Scalar, MPlaceTy<'tcx>)>,
488 }
489 |this, unblock: UnblockKind| {
490 assert_eq!(unblock, UnblockKind::Ready);
491
492 assert!(mutex_ref.owner().is_none());
493 this.mutex_lock(&mutex_ref)?;
494
495 if let Some((retval, dest)) = retval_dest {
496 this.write_scalar(retval, &dest)?;
497 }
498
499 interp_ok(())
500 }
501 ),
502 );
503 }
504
505 fn rwlock_reader_lock(&mut self, rwlock_ref: &RwLockRef) -> InterpResult<'tcx> {
508 let this = self.eval_context_mut();
509 let thread = this.active_thread();
510 trace!("rwlock_reader_lock: now also held (one more time) by {:?}", thread);
511 let mut rwlock = rwlock_ref.0.borrow_mut();
512 assert!(!rwlock.is_write_locked(), "the lock is write locked");
513 let count = rwlock.readers.entry(thread).or_insert(0);
514 *count = count.strict_add(1);
515 this.acquire_clock(&rwlock.clock_unlocked)?;
516 interp_ok(())
517 }
518
519 fn rwlock_reader_unlock(&mut self, rwlock_ref: &RwLockRef) -> InterpResult<'tcx, bool> {
522 let this = self.eval_context_mut();
523 let thread = this.active_thread();
524 let mut rwlock = rwlock_ref.0.borrow_mut();
525 match rwlock.readers.entry(thread) {
526 Entry::Occupied(mut entry) => {
527 let count = entry.get_mut();
528 assert!(*count > 0, "rwlock locked with count == 0");
529 *count -= 1;
530 if *count == 0 {
531 trace!("rwlock_reader_unlock: no longer held by {:?}", thread);
532 entry.remove();
533 } else {
534 trace!("rwlock_reader_unlock: held one less time by {:?}", thread);
535 }
536 }
537 Entry::Vacant(_) => return interp_ok(false), }
539 this.release_clock(|clock| rwlock.clock_current_readers.join(clock))?;
541
542 if rwlock.is_locked().not() {
544 let rwlock_ref = &mut *rwlock;
548 rwlock_ref.clock_unlocked.clone_from(&rwlock_ref.clock_current_readers);
549 if let Some(writer) = rwlock_ref.writer_queue.pop_front() {
551 drop(rwlock); this.unblock_thread(writer, BlockReason::RwLock)?;
553 }
554 }
555 interp_ok(true)
556 }
557
558 #[inline]
561 fn rwlock_enqueue_and_block_reader(
562 &mut self,
563 rwlock_ref: RwLockRef,
564 retval: Scalar,
565 dest: MPlaceTy<'tcx>,
566 ) {
567 let this = self.eval_context_mut();
568 let thread = this.active_thread();
569 let mut rwlock = rwlock_ref.0.borrow_mut();
570 rwlock.reader_queue.push_back(thread);
571 assert!(rwlock.is_write_locked(), "read-queueing on not write locked rwlock");
572 drop(rwlock);
573 this.block_thread(
574 BlockReason::RwLock,
575 None,
576 callback!(
577 @capture<'tcx> {
578 rwlock_ref: RwLockRef,
579 retval: Scalar,
580 dest: MPlaceTy<'tcx>,
581 }
582 |this, unblock: UnblockKind| {
583 assert_eq!(unblock, UnblockKind::Ready);
584 this.rwlock_reader_lock(&rwlock_ref)?;
585 this.write_scalar(retval, &dest)?;
586 interp_ok(())
587 }
588 ),
589 );
590 }
591
592 #[inline]
594 fn rwlock_writer_lock(&mut self, rwlock_ref: &RwLockRef) -> InterpResult<'tcx> {
595 let this = self.eval_context_mut();
596 let thread = this.active_thread();
597 trace!("rwlock_writer_lock: now held by {:?}", thread);
598
599 let mut rwlock = rwlock_ref.0.borrow_mut();
600 assert!(!rwlock.is_locked(), "the rwlock is already locked");
601 rwlock.writer = Some(thread);
602 this.acquire_clock(&rwlock.clock_unlocked)?;
603 interp_ok(())
604 }
605
606 #[inline]
609 fn rwlock_writer_unlock(&mut self, rwlock_ref: &RwLockRef) -> InterpResult<'tcx, bool> {
610 let this = self.eval_context_mut();
611 let thread = this.active_thread();
612 let mut rwlock = rwlock_ref.0.borrow_mut();
613 interp_ok(if let Some(current_writer) = rwlock.writer {
614 if current_writer != thread {
615 return interp_ok(false);
617 }
618 rwlock.writer = None;
619 trace!("rwlock_writer_unlock: unlocked by {:?}", thread);
620 this.release_clock(|clock| rwlock.clock_unlocked.clone_from(clock))?;
622
623 if let Some(writer) = rwlock.writer_queue.pop_front() {
629 drop(rwlock); this.unblock_thread(writer, BlockReason::RwLock)?;
631 } else {
632 let readers = std::mem::take(&mut rwlock.reader_queue);
634 drop(rwlock); for reader in readers {
636 this.unblock_thread(reader, BlockReason::RwLock)?;
637 }
638 }
639 true
640 } else {
641 false
642 })
643 }
644
645 #[inline]
648 fn rwlock_enqueue_and_block_writer(
649 &mut self,
650 rwlock_ref: RwLockRef,
651 retval: Scalar,
652 dest: MPlaceTy<'tcx>,
653 ) {
654 let this = self.eval_context_mut();
655 let thread = this.active_thread();
656 let mut rwlock = rwlock_ref.0.borrow_mut();
657 rwlock.writer_queue.push_back(thread);
658 assert!(rwlock.is_locked(), "write-queueing on unlocked rwlock");
659 drop(rwlock);
660 this.block_thread(
661 BlockReason::RwLock,
662 None,
663 callback!(
664 @capture<'tcx> {
665 rwlock_ref: RwLockRef,
666 retval: Scalar,
667 dest: MPlaceTy<'tcx>,
668 }
669 |this, unblock: UnblockKind| {
670 assert_eq!(unblock, UnblockKind::Ready);
671 this.rwlock_writer_lock(&rwlock_ref)?;
672 this.write_scalar(retval, &dest)?;
673 interp_ok(())
674 }
675 ),
676 );
677 }
678
679 fn condvar_wait(
683 &mut self,
684 condvar_ref: CondvarRef,
685 mutex_ref: MutexRef,
686 deadline: Option<Deadline>,
687 retval_succ: Scalar,
688 retval_timeout: Scalar,
689 dest: MPlaceTy<'tcx>,
690 ) -> InterpResult<'tcx> {
691 let this = self.eval_context_mut();
692 if let Some(old_locked_count) = this.mutex_unlock(&mutex_ref)? {
693 if old_locked_count != 1 {
694 throw_unsup_format!(
695 "awaiting a condvar on a mutex acquired multiple times is not supported"
696 );
697 }
698 } else {
699 throw_ub_format!(
700 "awaiting a condvar on a mutex that is unlocked or owned by a different thread"
701 );
702 }
703 let thread = this.active_thread();
704
705 condvar_ref.0.borrow_mut().waiters.push_back(thread);
706 this.block_thread(
707 BlockReason::Condvar,
708 deadline,
709 callback!(
710 @capture<'tcx> {
711 condvar_ref: CondvarRef,
712 mutex_ref: MutexRef,
713 retval_succ: Scalar,
714 retval_timeout: Scalar,
715 dest: MPlaceTy<'tcx>,
716 }
717 |this, unblock: UnblockKind| {
718 match unblock {
719 UnblockKind::Ready => {
720 this.acquire_clock(
722 &condvar_ref.0.borrow().clock,
723 )?;
724 this.condvar_reacquire_mutex(mutex_ref, retval_succ, dest)
727 }
728 UnblockKind::TimedOut => {
729 let thread = this.active_thread();
731 let waiters = &mut condvar_ref.0.borrow_mut().waiters;
732 waiters.retain(|waiter| *waiter != thread);
733 this.condvar_reacquire_mutex(mutex_ref, retval_timeout, dest)
735 }
736 }
737 }
738 ),
739 );
740 interp_ok(())
741 }
742
743 fn condvar_signal(&mut self, condvar_ref: &CondvarRef) -> InterpResult<'tcx, bool> {
746 let this = self.eval_context_mut();
747 let mut condvar = condvar_ref.0.borrow_mut();
748
749 this.release_clock(|clock| condvar.clock.clone_from(clock))?;
751 let Some(waiter) = condvar.waiters.pop_front() else {
752 return interp_ok(false);
753 };
754 drop(condvar);
755 this.unblock_thread(waiter, BlockReason::Condvar)?;
756 interp_ok(true)
757 }
758
759 fn futex_wait(
762 &mut self,
763 futex_ref: FutexRef,
764 bitset: u32,
765 deadline: Option<Deadline>,
766 callback: DynUnblockCallback<'tcx>,
767 ) {
768 let this = self.eval_context_mut();
769 let thread = this.active_thread();
770 let mut futex = futex_ref.0.borrow_mut();
771 let waiters = &mut futex.waiters;
772 assert!(waiters.iter().all(|waiter| waiter.thread != thread), "thread is already waiting");
773 waiters.push(FutexWaiter { thread, bitset });
774 drop(futex);
775
776 this.block_thread(
777 BlockReason::Futex,
778 deadline,
779 callback!(
780 @capture<'tcx> {
781 futex_ref: FutexRef,
782 callback: DynUnblockCallback<'tcx>,
783 }
784 |this, unblock: UnblockKind| {
785 match unblock {
786 UnblockKind::Ready => {
787 let futex = futex_ref.0.borrow();
788 this.acquire_clock(&futex.clock)?;
790 },
791 UnblockKind::TimedOut => {
792 let thread = this.active_thread();
794 let mut futex = futex_ref.0.borrow_mut();
795 futex.waiters.retain(|waiter| waiter.thread != thread);
796 },
797 }
798
799 callback.call(this, unblock)
800 }
801 ),
802 );
803 }
804
805 fn futex_wake(
808 &mut self,
809 futex_ref: &FutexRef,
810 bitset: u32,
811 count: usize,
812 ) -> InterpResult<'tcx, usize> {
813 let this = self.eval_context_mut();
814 let mut futex = futex_ref.0.borrow_mut();
815
816 this.release_clock(|clock| futex.clock.clone_from(clock))?;
818
819 let waiters: Vec<_> =
823 futex.waiters.extract_if(.., |w| w.bitset & bitset != 0).take(count).collect();
824 drop(futex);
825
826 let woken = waiters.len();
827 for waiter in waiters {
828 this.unblock_thread(waiter.thread, BlockReason::Futex)?;
829 }
830
831 interp_ok(woken)
832 }
833}