]> git.lizzy.rs Git - rust.git/blob - src/shims/panic.rs
adjust for goto_block refactoring
[rust.git] / src / 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_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.
13
14 use rustc::mir;
15 use crate::*;
16 use super::machine::FrameData;
17 use rustc_target::spec::PanicStrategy;
18 use crate::rustc_target::abi::LayoutOf;
19
20 /// Holds all of the relevant data for a call to
21 /// `__rust_maybe_catch_panic`.
22 ///
23 /// If a panic occurs, we update this data with
24 /// the information from the panic site.
25 #[derive(Debug)]
26 pub struct CatchUnwindData<'tcx> {
27     /// The dereferenced `data_ptr` argument passed to `__rust_maybe_catch_panic`.
28     pub data_place: MPlaceTy<'tcx, Tag>,
29     /// The dereferenced `vtable_ptr` argument passed to `__rust_maybe_catch_panic`.
30     pub vtable_place: MPlaceTy<'tcx, Tag>,
31     /// The `dest` from the original call to `__rust_maybe_catch_panic`.
32     pub dest: PlaceTy<'tcx, Tag>,
33 }
34
35 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
36 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
37
38     /// Handles the special "miri_start_panic" intrinsic, which is called
39     /// by libpanic_unwind to delegate the actual unwinding process to Miri.
40     #[inline(always)]
41     fn handle_miri_start_panic(
42         &mut self,
43         args: &[OpTy<'tcx, Tag>],
44         unwind: Option<mir::BasicBlock>
45     ) -> InterpResult<'tcx> {
46         let this = self.eval_context_mut();
47
48         trace!("miri_start_panic: {:?}", this.frame().span);
49
50         // Get the raw pointer stored in arg[0] (the panic payload).
51         let scalar = this.read_immediate(args[0])?;
52         assert!(this.machine.panic_payload.is_none(), "the panic runtime should avoid double-panics");
53         this.machine.panic_payload = Some(scalar);
54
55         // Jump to the unwind block to begin unwinding.
56         this.unwind_to_block(unwind);
57         return Ok(())
58     }
59
60     #[inline(always)]
61     fn handle_catch_panic(
62         &mut self,
63         args: &[OpTy<'tcx, Tag>],
64         dest: PlaceTy<'tcx, Tag>,
65         ret: mir::BasicBlock,
66     ) -> InterpResult<'tcx> {
67         let this = self.eval_context_mut();
68         let tcx = &{this.tcx.tcx};
69
70         // fn __rust_maybe_catch_panic(
71         //     f: fn(*mut u8),
72         //     data: *mut u8,
73         //     data_ptr: *mut usize,
74         //     vtable_ptr: *mut usize,
75         // ) -> u32
76
77         // Get all the arguments.
78         let f = this.read_scalar(args[0])?.not_undef()?;
79         let f_arg = this.read_scalar(args[1])?.not_undef()?;
80         let data_place = this.deref_operand(args[2])?;
81         let vtable_place = this.deref_operand(args[3])?;
82
83         // Now we make a function call, and pass `f_arg` as first and only argument.
84         let f_instance = this.memory.get_fn(f)?.as_instance()?;
85         trace!("__rust_maybe_catch_panic: {:?}", f_instance);
86         // TODO: consider making this reusable? `InterpCx::step` does something similar
87         // for the TLS destructors, and of course `eval_main`.
88         let mir = this.load_mir(f_instance.def, None)?;
89         let ret_place =
90             MPlaceTy::dangling(this.layout_of(tcx.mk_unit())?, this).into();
91         this.push_stack_frame(
92             f_instance,
93             mir.span,
94             mir,
95             Some(ret_place),
96             // Directly return to caller.
97             StackPopCleanup::Goto { ret: Some(ret), unwind: None },
98         )?;
99
100         let mut args = this.frame().body.args_iter();
101         // First argument.
102         let arg_local = args
103             .next()
104             .expect("Argument to __rust_maybe_catch_panic does not take enough arguments.");
105         let arg_dest = this.local_place(arg_local)?;
106         this.write_scalar(f_arg, arg_dest)?;
107         // No more arguments.
108         args.next().expect_none("__rust_maybe_catch_panic argument has more arguments than expected");
109
110         // We ourselves will return `0`, eventually (will be overwritten if we catch a panic).
111         this.write_null(dest)?;
112
113         // In unwind mode, we tag this frame with some extra data.
114         // This lets `handle_stack_pop` (below) know that we should stop unwinding
115         // when we pop this frame.
116         if this.tcx.tcx.sess.panic_strategy() == PanicStrategy::Unwind {
117             this.frame_mut().extra.catch_panic = Some(CatchUnwindData {
118                 data_place,
119                 vtable_place,
120                 dest,
121             })
122         }
123
124         return Ok(());
125     }
126
127     #[inline(always)]
128     fn handle_stack_pop(
129         &mut self,
130         mut extra: FrameData<'tcx>,
131         unwinding: bool
132     ) -> InterpResult<'tcx, StackPopInfo> {
133         let this = self.eval_context_mut();
134
135         trace!("handle_stack_pop(extra = {:?}, unwinding = {})", extra, unwinding);
136
137         // We only care about `catch_panic` if we're unwinding - if we're doing a normal
138         // return, then we don't need to do anything special.
139         let res = if let (true, Some(unwind_data)) = (unwinding, extra.catch_panic.take()) {
140             // We've just popped a frame that was pushed by `__rust_maybe_catch_panic`,
141             // and we are unwinding, so we should catch that.
142             trace!("unwinding: found catch_panic frame during unwinding: {:?}", this.frame().span);
143
144             // `panic_payload` now holds a `*mut (dyn Any + Send)`,
145             // provided by the `miri_start_panic` intrinsic.
146             // We want to split this into its consituient parts -
147             // the data and vtable pointers - and store them according to
148             // `unwind_data`, i.e., we store them where `__rust_maybe_catch_panic`
149             // was told to put them.
150             let payload = this.machine.panic_payload.take().unwrap();
151             let payload = this.ref_to_mplace(payload)?;
152             let payload_data_place = payload.ptr;
153             let payload_vtable_place = payload.meta.expect("Expected fat pointer");
154
155             this.write_scalar(payload_data_place, unwind_data.data_place.into())?;
156             this.write_scalar(payload_vtable_place, unwind_data.vtable_place.into())?;
157
158             // We set the return value of `__rust_maybe_catch_panic` to 1,
159             // since there was a panic.
160             let dest = unwind_data.dest;
161             this.write_scalar(Scalar::from_int(1, dest.layout.size), dest)?;
162
163             StackPopInfo::StopUnwinding
164         } else {
165             StackPopInfo::Normal
166         };
167         this.memory.extra.stacked_borrows.borrow_mut().end_call(extra.call_id);
168         Ok(res)
169     }
170 }