]> git.lizzy.rs Git - rust.git/blob - src/shims/panic.rs
2968bd9b58d8c6a0c1785881a3e471c6783199f2
[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 rustc::ty::{self, layout::LayoutOf};
16 use rustc_target::spec::PanicStrategy;
17 use rustc_span::source_map::Span;
18
19 use crate::*;
20
21 /// Holds all of the relevant data for a call to
22 /// `__rust_maybe_catch_panic`.
23 ///
24 /// If a panic occurs, we update this data with
25 /// the information from the panic site.
26 #[derive(Debug)]
27 pub struct CatchUnwindData<'tcx> {
28     /// The dereferenced `data_ptr` argument passed to `__rust_maybe_catch_panic`.
29     pub data_place: MPlaceTy<'tcx, Tag>,
30     /// The dereferenced `vtable_ptr` argument passed to `__rust_maybe_catch_panic`.
31     pub vtable_place: MPlaceTy<'tcx, Tag>,
32     /// The `dest` from the original call to `__rust_maybe_catch_panic`.
33     pub dest: PlaceTy<'tcx, Tag>,
34 }
35
36 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
37 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
38     /// Handles the special "miri_start_panic" intrinsic, which is called
39     /// by libpanic_unwind to delegate the actual unwinding process to Miri.
40     fn handle_miri_start_panic(
41         &mut self,
42         args: &[OpTy<'tcx, Tag>],
43         unwind: Option<mir::BasicBlock>,
44     ) -> InterpResult<'tcx> {
45         let this = self.eval_context_mut();
46
47         trace!("miri_start_panic: {:?}", this.frame().span);
48
49         // Get the raw pointer stored in arg[0] (the panic payload).
50         let scalar = this.read_immediate(args[0])?;
51         assert!(
52             this.machine.panic_payload.is_none(),
53             "the panic runtime should avoid double-panics"
54         );
55         this.machine.panic_payload = Some(scalar);
56
57         // Jump to the unwind block to begin unwinding.
58         this.unwind_to_block(unwind);
59         return Ok(());
60     }
61
62     fn handle_catch_panic(
63         &mut self,
64         args: &[OpTy<'tcx, Tag>],
65         dest: PlaceTy<'tcx, Tag>,
66         ret: mir::BasicBlock,
67     ) -> InterpResult<'tcx> {
68         let this = self.eval_context_mut();
69         let tcx = &{ this.tcx.tcx };
70
71         // fn __rust_maybe_catch_panic(
72         //     f: fn(*mut u8),
73         //     data: *mut u8,
74         //     data_ptr: *mut usize,
75         //     vtable_ptr: *mut usize,
76         // ) -> u32
77
78         // Get all the arguments.
79         let f = this.read_scalar(args[0])?.not_undef()?;
80         let f_arg = this.read_scalar(args[1])?.not_undef()?;
81         let data_place = this.deref_operand(args[2])?;
82         let vtable_place = this.deref_operand(args[3])?;
83
84         // Now we make a function call, and pass `f_arg` as first and only argument.
85         let f_instance = this.memory.get_fn(f)?.as_instance()?;
86         trace!("__rust_maybe_catch_panic: {:?}", f_instance);
87         let ret_place = MPlaceTy::dangling(this.layout_of(tcx.mk_unit())?, this).into();
88         this.call_function(
89             f_instance,
90             &[f_arg.into()],
91             Some(ret_place),
92             // Directly return to caller.
93             StackPopCleanup::Goto { ret: Some(ret), unwind: None },
94         )?;
95
96         // We ourselves will return `0`, eventually (will be overwritten if we catch a panic).
97         this.write_null(dest)?;
98
99         // In unwind mode, we tag this frame with some extra data.
100         // This lets `handle_stack_pop` (below) know that we should stop unwinding
101         // when we pop this frame.
102         if this.tcx.tcx.sess.panic_strategy() == PanicStrategy::Unwind {
103             this.frame_mut().extra.catch_panic =
104                 Some(CatchUnwindData { data_place, vtable_place, dest })
105         }
106
107         return Ok(());
108     }
109
110     fn handle_stack_pop(
111         &mut self,
112         mut extra: FrameData<'tcx>,
113         unwinding: bool,
114     ) -> InterpResult<'tcx, StackPopInfo> {
115         let this = self.eval_context_mut();
116
117         trace!("handle_stack_pop(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         let res = if let (true, Some(unwind_data)) = (unwinding, extra.catch_panic.take()) {
122             // We've just popped a frame that was pushed by `__rust_maybe_catch_panic`,
123             // and we are unwinding, so we should catch that.
124             trace!("unwinding: found catch_panic frame during unwinding: {:?}", this.frame().span);
125
126             // `panic_payload` now holds a `*mut (dyn Any + Send)`,
127             // provided by the `miri_start_panic` intrinsic.
128             // We want to split this into its consituient parts -
129             // the data and vtable pointers - and store them according to
130             // `unwind_data`, i.e., we store them where `__rust_maybe_catch_panic`
131             // was told to put them.
132             let payload = this.machine.panic_payload.take().unwrap();
133             let payload = this.ref_to_mplace(payload)?;
134             let payload_data_place = payload.ptr;
135             let payload_vtable_place = payload.meta.unwrap_meta();
136
137             this.write_scalar(payload_data_place, unwind_data.data_place.into())?;
138             this.write_scalar(payload_vtable_place, unwind_data.vtable_place.into())?;
139
140             // We set the return value of `__rust_maybe_catch_panic` to 1,
141             // since there was a panic.
142             let dest = unwind_data.dest;
143             this.write_scalar(Scalar::from_int(1, dest.layout.size), dest)?;
144
145             StackPopInfo::StopUnwinding
146         } else {
147             StackPopInfo::Normal
148         };
149         if let Some(stacked_borrows) = this.memory.extra.stacked_borrows.as_ref() {
150             stacked_borrows.borrow_mut().end_call(extra.call_id);
151         }
152         Ok(res)
153     }
154
155     /// Starta a panic in the interpreter with the given message as payload.
156     fn start_panic(
157         &mut self,
158         msg: &str,
159         unwind: Option<mir::BasicBlock>,
160     ) -> InterpResult<'tcx> {
161         let this = self.eval_context_mut();
162
163         // First arg: message.
164         let msg = this.allocate_str(msg, MiriMemoryKind::Machine.into());
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             &[msg.to_ref()],
172             None,
173             StackPopCleanup::Goto { ret: None, unwind },
174         )
175     }
176
177     fn assert_panic(
178         &mut self,
179         span: Span,
180         msg: &mir::AssertMessage<'tcx>,
181         unwind: Option<mir::BasicBlock>,
182     ) -> InterpResult<'tcx> {
183         use rustc::mir::AssertKind::*;
184         let this = self.eval_context_mut();
185
186         match msg {
187             BoundsCheck { ref index, ref len } => {
188                 // Forward to `panic_bounds_check` lang item.
189
190                 // First arg: Caller location.
191                 let location = this.alloc_caller_location_for_span(span);
192                 // Second arg: index.
193                 let index = this.read_scalar(this.eval_operand(index, None)?)?;
194                 // Third arg: len.
195                 let len = this.read_scalar(this.eval_operand(len, None)?)?;
196
197                 // Call the lang item.
198                 let panic_bounds_check = this.tcx.lang_items().panic_bounds_check_fn().unwrap();
199                 let panic_bounds_check = ty::Instance::mono(this.tcx.tcx, panic_bounds_check);
200                 this.call_function(
201                     panic_bounds_check,
202                     &[location.ptr.into(), index.into(), len.into()],
203                     None,
204                     StackPopCleanup::Goto { ret: None, unwind },
205                 )?;
206             }
207             _ => {
208                 // Forward everything else to `panic` lang item.
209                 this.start_panic(msg.description(), unwind)?;
210             }
211         }
212         Ok(())
213     }
214 }