1 //! Panic runtime for Miri.
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_panic` intrinsic instead of the
7 //! target-native panic runtime. (This lives in the rustc repo.)
8 //! - An implementation of `miri_start_panic` 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.
16 use rustc_middle::{mir, ty};
17 use rustc_target::spec::PanicStrategy;
20 use helpers::check_arg_count;
22 /// Holds all of the relevant data for when unwinding hits a `try` frame.
24 pub struct CatchUnwindData<'tcx> {
25 /// The `catch_fn` callback to call in case of a panic.
26 catch_fn: Scalar<Tag>,
27 /// The `data` argument for that callback.
29 /// The return place from the original call to `try`.
30 dest: PlaceTy<'tcx, Tag>,
31 /// The return block from the original call to `try`.
35 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
36 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
37 /// Handles the special `miri_start_panic` intrinsic, which is called
38 /// by libpanic_unwind to delegate the actual unwinding process to Miri.
39 fn handle_miri_start_panic(
41 args: &[OpTy<'tcx, Tag>],
42 unwind: Option<mir::BasicBlock>,
43 ) -> InterpResult<'tcx> {
44 let this = self.eval_context_mut();
46 trace!("miri_start_panic: {:?}", this.frame().instance);
48 // Get the raw pointer stored in arg[0] (the panic payload).
49 let &[payload] = check_arg_count(args)?;
50 let payload = this.read_scalar(payload)?.check_init()?;
51 let thread = this.active_thread_mut();
53 thread.panic_payload.is_none(),
54 "the panic runtime should avoid double-panics"
56 thread.panic_payload = Some(payload);
58 // Jump to the unwind block to begin unwinding.
59 this.unwind_to_block(unwind);
63 /// Handles the `try` intrinsic, the underlying implementation of `std::panicking::try`.
66 args: &[OpTy<'tcx, Tag>],
67 dest: PlaceTy<'tcx, Tag>,
69 ) -> InterpResult<'tcx> {
70 let this = self.eval_context_mut();
73 // fn r#try(try_fn: fn(*mut u8), data: *mut u8, catch_fn: fn(*mut u8, *mut u8)) -> i32
74 // Calls `try_fn` with `data` as argument. If that executes normally, returns 0.
75 // If that unwinds, calls `catch_fn` with the first argument being `data` and
76 // then second argument being a target-dependent `payload` (i.e. it is up to us to define
77 // what that is), and returns 1.
78 // The `payload` is passed (by libstd) to `__rust_panic_cleanup`, which is then expected to
79 // return a `Box<dyn Any + Send + 'static>`.
80 // In Miri, `miri_start_panic` is passed exactly that type, so we make the `payload` simply
81 // a pointer to `Box<dyn Any + Send + 'static>`.
83 // Get all the arguments.
84 let &[try_fn, data, catch_fn] = check_arg_count(args)?;
85 let try_fn = this.read_scalar(try_fn)?.check_init()?;
86 let data = this.read_scalar(data)?.check_init()?;
87 let catch_fn = this.read_scalar(catch_fn)?.check_init()?;
89 // Now we make a function call, and pass `data` as first and only argument.
90 let f_instance = this.memory.get_fn(try_fn)?.as_instance()?;
91 trace!("try_fn: {:?}", f_instance);
92 let ret_place = MPlaceTy::dangling(this.machine.layouts.unit, this).into();
97 // Directly return to caller.
98 StackPopCleanup::Goto { ret: Some(ret), unwind: None },
101 // We ourselves will return `0`, eventually (will be overwritten if we catch a panic).
102 this.write_null(dest)?;
104 // In unwind mode, we tag this frame with the extra data needed to catch unwinding.
105 // This lets `handle_stack_pop` (below) know that we should stop unwinding
106 // when we pop this frame.
107 if this.tcx.sess.panic_strategy() == PanicStrategy::Unwind {
108 this.frame_mut().extra.catch_unwind = Some(CatchUnwindData { catch_fn, data, dest, ret });
116 mut extra: FrameData<'tcx>,
118 ) -> InterpResult<'tcx, StackPopJump> {
119 let this = self.eval_context_mut();
121 trace!("handle_stack_pop(extra = {:?}, unwinding = {})", extra, unwinding);
122 if let Some(stacked_borrows) = &this.memory.extra.stacked_borrows {
123 stacked_borrows.borrow_mut().end_call(extra.call_id);
126 // We only care about `catch_panic` if we're unwinding - if we're doing a normal
127 // return, then we don't need to do anything special.
128 if let (true, Some(catch_unwind)) = (unwinding, extra.catch_unwind.take()) {
129 // We've just popped a frame that was pushed by `try`,
130 // and we are unwinding, so we should catch that.
131 trace!("unwinding: found catch_panic frame during unwinding: {:?}", this.frame().instance);
133 // We set the return value of `try` to 1, since there was a panic.
134 this.write_scalar(Scalar::from_i32(1), catch_unwind.dest)?;
136 // The Thread's `panic_payload` holds what was passed to `miri_start_panic`.
137 // This is exactly the second argument we need to pass to `catch_fn`.
138 let payload = this.active_thread_mut().panic_payload.take().unwrap();
140 // Push the `catch_fn` stackframe.
141 let f_instance = this.memory.get_fn(catch_unwind.catch_fn)?.as_instance()?;
142 trace!("catch_fn: {:?}", f_instance);
143 let ret_place = MPlaceTy::dangling(this.machine.layouts.unit, this).into();
146 &[catch_unwind.data.into(), payload.into()],
148 // Directly return to caller of `try`.
149 StackPopCleanup::Goto { ret: Some(catch_unwind.ret), unwind: None },
152 // We pushed a new stack frame, the engine should not do any jumping now!
153 Ok(StackPopJump::NoJump)
155 Ok(StackPopJump::Normal)
159 /// Starta a panic in the interpreter with the given message as payload.
163 unwind: Option<mir::BasicBlock>,
164 ) -> InterpResult<'tcx> {
165 let this = self.eval_context_mut();
167 // First arg: message.
168 let msg = this.allocate_str(msg, MiriMemoryKind::Machine.into());
170 // Call the lang item.
171 let panic = this.tcx.lang_items().panic_fn().unwrap();
172 let panic = ty::Instance::mono(this.tcx.tcx, panic);
177 StackPopCleanup::Goto { ret: None, unwind },
183 msg: &mir::AssertMessage<'tcx>,
184 unwind: Option<mir::BasicBlock>,
185 ) -> InterpResult<'tcx> {
186 use rustc_middle::mir::AssertKind::*;
187 let this = self.eval_context_mut();
190 BoundsCheck { index, len } => {
191 // Forward to `panic_bounds_check` lang item.
194 let index = this.read_scalar(this.eval_operand(index, None)?)?;
196 let len = this.read_scalar(this.eval_operand(len, None)?)?;
198 // Call the lang item.
199 let panic_bounds_check = this.tcx.lang_items().panic_bounds_check_fn().unwrap();
200 let panic_bounds_check = ty::Instance::mono(this.tcx.tcx, panic_bounds_check);
203 &[index.into(), len.into()],
205 StackPopCleanup::Goto { ret: None, unwind },
209 // Forward everything else to `panic` lang item.
210 this.start_panic(msg.description(), unwind)?;