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_ast::Mutability;
17 use rustc_middle::{mir, ty};
18 use rustc_target::spec::abi::Abi;
19 use rustc_target::spec::PanicStrategy;
22 use helpers::check_arg_count;
24 /// Holds all of the relevant data for when unwinding hits a `try` frame.
26 pub struct CatchUnwindData<'tcx> {
27 /// The `catch_fn` callback to call in case of a panic.
28 catch_fn: Scalar<Tag>,
29 /// The `data` argument for that callback.
31 /// The return place from the original call to `try`.
32 dest: PlaceTy<'tcx, Tag>,
33 /// The return block from the original call to `try`.
37 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
38 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
39 /// Handles the special `miri_start_panic` intrinsic, which is called
40 /// by libpanic_unwind to delegate the actual unwinding process to Miri.
41 fn handle_miri_start_panic(
43 args: &[OpTy<'tcx, Tag>],
44 unwind: Option<mir::BasicBlock>,
45 ) -> InterpResult<'tcx> {
46 let this = self.eval_context_mut();
48 trace!("miri_start_panic: {:?}", this.frame().instance);
49 // Make sure we only start unwinding when this matches our panic strategy.
50 if this.tcx.sess.panic_strategy() != PanicStrategy::Unwind {
51 throw_ub_format!("unwinding despite panic=abort");
54 // Get the raw pointer stored in arg[0] (the panic payload).
55 let &[ref payload] = check_arg_count(args)?;
56 let payload = this.read_scalar(payload)?.check_init()?;
57 let thread = this.active_thread_mut();
58 assert!(thread.panic_payload.is_none(), "the panic runtime should avoid double-panics");
59 thread.panic_payload = Some(payload);
61 // Jump to the unwind block to begin unwinding.
62 this.unwind_to_block(unwind);
66 /// Handles the `try` intrinsic, the underlying implementation of `std::panicking::try`.
69 args: &[OpTy<'tcx, Tag>],
70 dest: &PlaceTy<'tcx, Tag>,
72 ) -> InterpResult<'tcx> {
73 let this = self.eval_context_mut();
76 // fn r#try(try_fn: fn(*mut u8), data: *mut u8, catch_fn: fn(*mut u8, *mut u8)) -> i32
77 // Calls `try_fn` with `data` as argument. If that executes normally, returns 0.
78 // If that unwinds, calls `catch_fn` with the first argument being `data` and
79 // then second argument being a target-dependent `payload` (i.e. it is up to us to define
80 // what that is), and returns 1.
81 // The `payload` is passed (by libstd) to `__rust_panic_cleanup`, which is then expected to
82 // return a `Box<dyn Any + Send + 'static>`.
83 // In Miri, `miri_start_panic` is passed exactly that type, so we make the `payload` simply
84 // a pointer to `Box<dyn Any + Send + 'static>`.
86 // Get all the arguments.
87 let &[ref try_fn, ref data, ref catch_fn] = check_arg_count(args)?;
88 let try_fn = this.read_scalar(try_fn)?.check_init()?;
89 let data = this.read_scalar(data)?.check_init()?;
90 let catch_fn = this.read_scalar(catch_fn)?.check_init()?;
92 // Now we make a function call, and pass `data` as first and only argument.
93 let f_instance = this.memory.get_fn(try_fn)?.as_instance()?;
94 trace!("try_fn: {:?}", f_instance);
95 let ret_place = MPlaceTy::dangling(this.machine.layouts.unit, this).into();
101 // Directly return to caller.
102 StackPopCleanup::Goto { ret: Some(ret), unwind: None },
105 // We ourselves will return `0`, eventually (will be overwritten if we catch a panic).
106 this.write_null(dest)?;
108 // In unwind mode, we tag this frame with the extra data needed to catch unwinding.
109 // This lets `handle_stack_pop` (below) know that we should stop unwinding
110 // when we pop this frame.
111 if this.tcx.sess.panic_strategy() == PanicStrategy::Unwind {
112 this.frame_mut().extra.catch_unwind =
113 Some(CatchUnwindData { catch_fn, data, dest: *dest, ret });
121 mut extra: FrameData<'tcx>,
123 ) -> InterpResult<'tcx, StackPopJump> {
124 let this = self.eval_context_mut();
126 trace!("handle_stack_pop(extra = {:?}, unwinding = {})", extra, unwinding);
127 if let Some(stacked_borrows) = &this.memory.extra.stacked_borrows {
128 stacked_borrows.borrow_mut().end_call(extra.call_id);
131 // We only care about `catch_panic` if we're unwinding - if we're doing a normal
132 // return, then we don't need to do anything special.
133 if let (true, Some(catch_unwind)) = (unwinding, extra.catch_unwind.take()) {
134 // We've just popped a frame that was pushed by `try`,
135 // and we are unwinding, so we should catch that.
137 "unwinding: found catch_panic frame during unwinding: {:?}",
138 this.frame().instance
141 // We set the return value of `try` to 1, since there was a panic.
142 this.write_scalar(Scalar::from_i32(1), &catch_unwind.dest)?;
144 // The Thread's `panic_payload` holds what was passed to `miri_start_panic`.
145 // This is exactly the second argument we need to pass to `catch_fn`.
146 let payload = this.active_thread_mut().panic_payload.take().unwrap();
148 // Push the `catch_fn` stackframe.
149 let f_instance = this.memory.get_fn(catch_unwind.catch_fn)?.as_instance()?;
150 trace!("catch_fn: {:?}", f_instance);
151 let ret_place = MPlaceTy::dangling(this.machine.layouts.unit, this).into();
155 &[catch_unwind.data.into(), payload.into()],
157 // Directly return to caller of `try`.
158 StackPopCleanup::Goto { ret: Some(catch_unwind.ret), unwind: None },
161 // We pushed a new stack frame, the engine should not do any jumping now!
162 Ok(StackPopJump::NoJump)
164 Ok(StackPopJump::Normal)
168 /// Starta a panic in the interpreter with the given message as payload.
169 fn start_panic(&mut self, msg: &str, unwind: Option<mir::BasicBlock>) -> InterpResult<'tcx> {
170 let this = self.eval_context_mut();
172 // First arg: message.
173 let msg = this.allocate_str(msg, MiriMemoryKind::Machine.into(), Mutability::Not);
175 // Call the lang item.
176 let panic = this.tcx.lang_items().panic_fn().unwrap();
177 let panic = ty::Instance::mono(this.tcx.tcx, panic);
183 StackPopCleanup::Goto { ret: None, unwind },
189 msg: &mir::AssertMessage<'tcx>,
190 unwind: Option<mir::BasicBlock>,
191 ) -> InterpResult<'tcx> {
192 use rustc_middle::mir::AssertKind::*;
193 let this = self.eval_context_mut();
196 BoundsCheck { index, len } => {
197 // Forward to `panic_bounds_check` lang item.
200 let index = this.read_scalar(&this.eval_operand(index, None)?)?;
202 let len = this.read_scalar(&this.eval_operand(len, None)?)?;
204 // Call the lang item.
205 let panic_bounds_check = this.tcx.lang_items().panic_bounds_check_fn().unwrap();
206 let panic_bounds_check = ty::Instance::mono(this.tcx.tcx, panic_bounds_check);
210 &[index.into(), len.into()],
212 StackPopCleanup::Goto { ret: None, unwind },
216 // Forward everything else to `panic` lang item.
217 this.start_panic(msg.description(), unwind)?;