miri/shims/
panic.rs

1//! Panic runtime for Miri.
2//!
3//! The core pieces of the runtime are:
4//! - An implementation of `__rust_maybe_catch_panic` that pushes the invoked stack frame with
5//!   some extra metadata derived from the panic-catching arguments of `__rust_maybe_catch_panic`.
6//! - A hack in `libpanic_unwind` that calls the `miri_start_unwind` intrinsic instead of the
7//!   target-native panic runtime. (This lives in the rustc repo.)
8//! - An implementation of `miri_start_unwind` that stores its argument (the panic payload), and then
9//!   immediately returns, but on the *unwind* edge (not the normal return edge), thus initiating unwinding.
10//! - A hook executed each time a frame is popped, such that if the frame pushed by `__rust_maybe_catch_panic`
11//!   gets popped *during unwinding*, we take the panic payload and store it according to the extra
12//!   metadata we remembered when pushing said frame.
13
14use rustc_abi::ExternAbi;
15use rustc_middle::{mir, ty};
16use rustc_target::spec::PanicStrategy;
17
18use self::helpers::check_intrinsic_arg_count;
19use crate::*;
20
21/// Holds all of the relevant data for when unwinding hits a `try` frame.
22#[derive(Debug)]
23pub struct CatchUnwindData<'tcx> {
24    /// The `catch_fn` callback to call in case of a panic.
25    catch_fn: Pointer,
26    /// The `data` argument for that callback.
27    data: ImmTy<'tcx>,
28    /// The return place from the original call to `try`.
29    dest: MPlaceTy<'tcx>,
30    /// The return block from the original call to `try`.
31    ret: Option<mir::BasicBlock>,
32}
33
34impl VisitProvenance for CatchUnwindData<'_> {
35    fn visit_provenance(&self, visit: &mut VisitWith<'_>) {
36        let CatchUnwindData { catch_fn, data, dest, ret: _ } = self;
37        catch_fn.visit_provenance(visit);
38        data.visit_provenance(visit);
39        dest.visit_provenance(visit);
40    }
41}
42
43impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
44pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
45    /// Handles the special `miri_start_unwind` intrinsic, which is called
46    /// by libpanic_unwind to delegate the actual unwinding process to Miri.
47    fn handle_miri_start_unwind(&mut self, payload: &OpTy<'tcx>) -> InterpResult<'tcx> {
48        let this = self.eval_context_mut();
49
50        trace!("miri_start_unwind: {:?}", this.frame().instance());
51
52        let payload = this.read_immediate(payload)?;
53        let thread = this.active_thread_mut();
54        thread.panic_payloads.push(payload);
55
56        interp_ok(())
57    }
58
59    /// Handles the `try` intrinsic, the underlying implementation of `std::panicking::try`.
60    fn handle_catch_unwind(
61        &mut self,
62        args: &[OpTy<'tcx>],
63        dest: &MPlaceTy<'tcx>,
64        ret: Option<mir::BasicBlock>,
65    ) -> InterpResult<'tcx> {
66        let this = self.eval_context_mut();
67
68        // Signature:
69        //   fn r#try(try_fn: fn(*mut u8), data: *mut u8, catch_fn: fn(*mut u8, *mut u8)) -> i32
70        // Calls `try_fn` with `data` as argument. If that executes normally, returns 0.
71        // If that unwinds, calls `catch_fn` with the first argument being `data` and
72        // then second argument being a target-dependent `payload` (i.e. it is up to us to define
73        // what that is), and returns 1.
74        // The `payload` is passed (by libstd) to `__rust_panic_cleanup`, which is then expected to
75        // return a `Box<dyn Any + Send + 'static>`.
76        // In Miri, `miri_start_unwind` is passed exactly that type, so we make the `payload` simply
77        // a pointer to `Box<dyn Any + Send + 'static>`.
78
79        // Get all the arguments.
80        let [try_fn, data, catch_fn] = check_intrinsic_arg_count(args)?;
81        let try_fn = this.read_pointer(try_fn)?;
82        let data = this.read_immediate(data)?;
83        let catch_fn = this.read_pointer(catch_fn)?;
84
85        // Now we make a function call, and pass `data` as first and only argument.
86        let f_instance = this.get_ptr_fn(try_fn)?.as_instance()?;
87        trace!("try_fn: {:?}", f_instance);
88        this.call_function(
89            f_instance,
90            ExternAbi::Rust,
91            &[data.clone()],
92            None,
93            // Directly return to caller.
94            StackPopCleanup::Goto { ret, unwind: mir::UnwindAction::Continue },
95        )?;
96
97        // We ourselves will return `0`, eventually (will be overwritten if we catch a panic).
98        this.write_null(dest)?;
99
100        // In unwind mode, we tag this frame with the extra data needed to catch unwinding.
101        // This lets `handle_stack_pop` (below) know that we should stop unwinding
102        // when we pop this frame.
103        if this.tcx.sess.panic_strategy() == PanicStrategy::Unwind {
104            this.frame_mut().extra.catch_unwind =
105                Some(CatchUnwindData { catch_fn, data, dest: dest.clone(), ret });
106        }
107
108        interp_ok(())
109    }
110
111    fn handle_stack_pop_unwind(
112        &mut self,
113        mut extra: FrameExtra<'tcx>,
114        unwinding: bool,
115    ) -> InterpResult<'tcx, ReturnAction> {
116        let this = self.eval_context_mut();
117        trace!("handle_stack_pop_unwind(extra = {:?}, unwinding = {})", extra, unwinding);
118
119        // We only care about `catch_panic` if we're unwinding - if we're doing a normal
120        // return, then we don't need to do anything special.
121        if let (true, Some(catch_unwind)) = (unwinding, extra.catch_unwind.take()) {
122            // We've just popped a frame that was pushed by `try`,
123            // and we are unwinding, so we should catch that.
124            trace!(
125                "unwinding: found catch_panic frame during unwinding: {:?}",
126                this.frame().instance()
127            );
128
129            // We set the return value of `try` to 1, since there was a panic.
130            this.write_scalar(Scalar::from_i32(1), &catch_unwind.dest)?;
131
132            // The Thread's `panic_payload` holds what was passed to `miri_start_unwind`.
133            // This is exactly the second argument we need to pass to `catch_fn`.
134            let payload = this.active_thread_mut().panic_payloads.pop().unwrap();
135
136            // Push the `catch_fn` stackframe.
137            let f_instance = this.get_ptr_fn(catch_unwind.catch_fn)?.as_instance()?;
138            trace!("catch_fn: {:?}", f_instance);
139            this.call_function(
140                f_instance,
141                ExternAbi::Rust,
142                &[catch_unwind.data, payload],
143                None,
144                // Directly return to caller of `try`.
145                StackPopCleanup::Goto {
146                    ret: catch_unwind.ret,
147                    // `catch_fn` must not unwind.
148                    unwind: mir::UnwindAction::Unreachable,
149                },
150            )?;
151
152            // We pushed a new stack frame, the engine should not do any jumping now!
153            interp_ok(ReturnAction::NoJump)
154        } else {
155            interp_ok(ReturnAction::Normal)
156        }
157    }
158
159    /// Start a panic in the interpreter with the given message as payload.
160    fn start_panic(&mut self, msg: &str, unwind: mir::UnwindAction) -> InterpResult<'tcx> {
161        let this = self.eval_context_mut();
162
163        // First arg: message.
164        let msg = this.allocate_str_dedup(msg)?;
165
166        // Call the lang item.
167        let panic = this.tcx.lang_items().panic_fn().unwrap();
168        let panic = ty::Instance::mono(this.tcx.tcx, panic);
169        this.call_function(
170            panic,
171            ExternAbi::Rust,
172            &[this.mplace_to_ref(&msg)?],
173            None,
174            StackPopCleanup::Goto { ret: None, unwind },
175        )
176    }
177
178    /// Start a non-unwinding panic in the interpreter with the given message as payload.
179    fn start_panic_nounwind(&mut self, msg: &str) -> InterpResult<'tcx> {
180        let this = self.eval_context_mut();
181
182        // First arg: message.
183        let msg = this.allocate_str_dedup(msg)?;
184
185        // Call the lang item.
186        let panic = this.tcx.lang_items().panic_nounwind().unwrap();
187        let panic = ty::Instance::mono(this.tcx.tcx, panic);
188        this.call_function(
189            panic,
190            ExternAbi::Rust,
191            &[this.mplace_to_ref(&msg)?],
192            None,
193            StackPopCleanup::Goto { ret: None, unwind: mir::UnwindAction::Unreachable },
194        )
195    }
196
197    fn assert_panic(
198        &mut self,
199        msg: &mir::AssertMessage<'tcx>,
200        unwind: mir::UnwindAction,
201    ) -> InterpResult<'tcx> {
202        use rustc_middle::mir::AssertKind::*;
203        let this = self.eval_context_mut();
204
205        match msg {
206            BoundsCheck { index, len } => {
207                // Forward to `panic_bounds_check` lang item.
208
209                // First arg: index.
210                let index = this.read_immediate(&this.eval_operand(index, None)?)?;
211                // Second arg: len.
212                let len = this.read_immediate(&this.eval_operand(len, None)?)?;
213
214                // Call the lang item.
215                let panic_bounds_check = this.tcx.lang_items().panic_bounds_check_fn().unwrap();
216                let panic_bounds_check = ty::Instance::mono(this.tcx.tcx, panic_bounds_check);
217                this.call_function(
218                    panic_bounds_check,
219                    ExternAbi::Rust,
220                    &[index, len],
221                    None,
222                    StackPopCleanup::Goto { ret: None, unwind },
223                )?;
224            }
225            MisalignedPointerDereference { required, found } => {
226                // Forward to `panic_misaligned_pointer_dereference` lang item.
227
228                // First arg: required.
229                let required = this.read_immediate(&this.eval_operand(required, None)?)?;
230                // Second arg: found.
231                let found = this.read_immediate(&this.eval_operand(found, None)?)?;
232
233                // Call the lang item.
234                let panic_misaligned_pointer_dereference =
235                    this.tcx.lang_items().panic_misaligned_pointer_dereference_fn().unwrap();
236                let panic_misaligned_pointer_dereference =
237                    ty::Instance::mono(this.tcx.tcx, panic_misaligned_pointer_dereference);
238                this.call_function(
239                    panic_misaligned_pointer_dereference,
240                    ExternAbi::Rust,
241                    &[required, found],
242                    None,
243                    StackPopCleanup::Goto { ret: None, unwind },
244                )?;
245            }
246
247            _ => {
248                // Call the lang item associated with this message.
249                let fn_item = this.tcx.require_lang_item(msg.panic_function(), None);
250                let instance = ty::Instance::mono(this.tcx.tcx, fn_item);
251                this.call_function(
252                    instance,
253                    ExternAbi::Rust,
254                    &[],
255                    None,
256                    StackPopCleanup::Goto { ret: None, unwind },
257                )?;
258            }
259        }
260        interp_ok(())
261    }
262}