miri/concurrency/
init_once.rs

1use std::cell::RefCell;
2use std::collections::VecDeque;
3use std::rc::Rc;
4
5use super::thread::DynUnblockCallback;
6use super::vector_clock::VClock;
7use crate::*;
8
9#[derive(Default, Debug, Copy, Clone, PartialEq, Eq)]
10/// The current status of a one time initialization.
11pub enum InitOnceStatus {
12    #[default]
13    Uninitialized,
14    Begun,
15    Complete,
16}
17
18/// The one time initialization state.
19#[derive(Default, Debug)]
20pub(super) struct InitOnce {
21    status: InitOnceStatus,
22    waiters: VecDeque<ThreadId>,
23    clock: VClock,
24}
25
26impl InitOnce {
27    #[inline]
28    pub fn status(&self) -> InitOnceStatus {
29        self.status
30    }
31
32    /// Begin initializing this InitOnce. Must only be called after checking that it is currently
33    /// uninitialized.
34    #[inline]
35    pub fn begin(&mut self) {
36        assert_eq!(
37            self.status(),
38            InitOnceStatus::Uninitialized,
39            "beginning already begun or complete init once"
40        );
41        self.status = InitOnceStatus::Begun;
42    }
43}
44
45#[derive(Default, Clone, Debug)]
46pub struct InitOnceRef(Rc<RefCell<InitOnce>>);
47
48impl InitOnceRef {
49    pub fn new() -> Self {
50        Self(Default::default())
51    }
52
53    pub fn status(&self) -> InitOnceStatus {
54        self.0.borrow().status()
55    }
56
57    pub fn begin(&self) {
58        self.0.borrow_mut().begin();
59    }
60
61    pub fn queue_is_empty(&self) -> bool {
62        self.0.borrow().waiters.is_empty()
63    }
64}
65
66impl VisitProvenance for InitOnceRef {
67    // InitOnce contains no provenance.
68    fn visit_provenance(&self, _visit: &mut VisitWith<'_>) {}
69}
70
71impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
72pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
73    /// Put the thread into the queue waiting for the initialization.
74    #[inline]
75    fn init_once_enqueue_and_block(
76        &mut self,
77        init_once_ref: InitOnceRef,
78        callback: DynUnblockCallback<'tcx>,
79    ) {
80        let this = self.eval_context_mut();
81        let thread = this.active_thread();
82        let mut init_once = init_once_ref.0.borrow_mut();
83        assert_ne!(init_once.status, InitOnceStatus::Complete, "queueing on complete init once");
84
85        init_once.waiters.push_back(thread);
86        this.block_thread(BlockReason::InitOnce, None, callback);
87    }
88
89    #[inline]
90    fn init_once_complete(&mut self, init_once_ref: &InitOnceRef) -> InterpResult<'tcx> {
91        let this = self.eval_context_mut();
92
93        let mut init_once = init_once_ref.0.borrow_mut();
94        assert_eq!(
95            init_once.status,
96            InitOnceStatus::Begun,
97            "completing already complete or uninit init once"
98        );
99
100        init_once.status = InitOnceStatus::Complete;
101
102        // Each complete happens-before the end of the wait
103        this.release_clock(|clock| init_once.clock.clone_from(clock))?;
104
105        // Wake up everyone.
106        // need to take the queue to avoid having `this` be borrowed multiple times
107        let waiters = std::mem::take(&mut init_once.waiters);
108        drop(init_once);
109        for waiter in waiters {
110            this.unblock_thread(waiter, BlockReason::InitOnce)?;
111        }
112
113        interp_ok(())
114    }
115
116    #[inline]
117    fn init_once_fail(&mut self, init_once_ref: &InitOnceRef) -> InterpResult<'tcx> {
118        let this = self.eval_context_mut();
119        let mut init_once = init_once_ref.0.borrow_mut();
120        assert_eq!(
121            init_once.status,
122            InitOnceStatus::Begun,
123            "failing already completed or uninit init once"
124        );
125        // This is again uninitialized.
126        init_once.status = InitOnceStatus::Uninitialized;
127
128        // Each complete happens-before the end of the wait
129        this.release_clock(|clock| init_once.clock.clone_from(clock))?;
130
131        // Wake up one waiting thread, so they can go ahead and try to init this.
132        if let Some(waiter) = init_once.waiters.pop_front() {
133            drop(init_once);
134            this.unblock_thread(waiter, BlockReason::InitOnce)?;
135        }
136
137        interp_ok(())
138    }
139
140    /// Synchronize with the previous completion of an InitOnce.
141    /// Must only be called after checking that it is complete.
142    #[inline]
143    fn init_once_observe_completed(&mut self, init_once_ref: &InitOnceRef) -> InterpResult<'tcx> {
144        let this = self.eval_context_mut();
145        let init_once = init_once_ref.0.borrow();
146
147        assert_eq!(
148            init_once.status,
149            InitOnceStatus::Complete,
150            "observing the completion of incomplete init once"
151        );
152
153        this.acquire_clock(&init_once.clock)
154    }
155}