]> git.lizzy.rs Git - rust.git/blob - src/shims/panic.rs
rustup+fix
[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
18 use crate::*;
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     /// 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(
40         &mut self,
41         args: &[OpTy<'tcx, Tag>],
42         unwind: Option<mir::BasicBlock>,
43     ) -> InterpResult<'tcx> {
44         let this = self.eval_context_mut();
45
46         trace!("miri_start_panic: {:?}", this.frame().span);
47
48         // Get the raw pointer stored in arg[0] (the panic payload).
49         let scalar = this.read_immediate(args[0])?;
50         assert!(
51             this.machine.panic_payload.is_none(),
52             "the panic runtime should avoid double-panics"
53         );
54         this.machine.panic_payload = Some(scalar);
55
56         // Jump to the unwind block to begin unwinding.
57         this.unwind_to_block(unwind);
58         return Ok(());
59     }
60
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         let ret_place = MPlaceTy::dangling(this.layout_of(tcx.mk_unit())?, this).into();
87         this.call_function(
88             f_instance,
89             &[f_arg.into()],
90             Some(ret_place),
91             // Directly return to caller.
92             StackPopCleanup::Goto { ret: Some(ret), unwind: None },
93         )?;
94
95         // We ourselves will return `0`, eventually (will be overwritten if we catch a panic).
96         this.write_null(dest)?;
97
98         // In unwind mode, we tag this frame with some extra data.
99         // This lets `handle_stack_pop` (below) know that we should stop unwinding
100         // when we pop this frame.
101         if this.tcx.tcx.sess.panic_strategy() == PanicStrategy::Unwind {
102             this.frame_mut().extra.catch_panic =
103                 Some(CatchUnwindData { data_place, vtable_place, dest })
104         }
105
106         return Ok(());
107     }
108
109     fn handle_stack_pop(
110         &mut self,
111         mut extra: FrameData<'tcx>,
112         unwinding: bool,
113     ) -> InterpResult<'tcx, StackPopInfo> {
114         let this = self.eval_context_mut();
115
116         trace!("handle_stack_pop(extra = {:?}, unwinding = {})", extra, unwinding);
117
118         // We only care about `catch_panic` if we're unwinding - if we're doing a normal
119         // return, then we don't need to do anything special.
120         let res = if let (true, Some(unwind_data)) = (unwinding, extra.catch_panic.take()) {
121             // We've just popped a frame that was pushed by `__rust_maybe_catch_panic`,
122             // and we are unwinding, so we should catch that.
123             trace!("unwinding: found catch_panic frame during unwinding: {:?}", this.frame().span);
124
125             // `panic_payload` now holds a `*mut (dyn Any + Send)`,
126             // provided by the `miri_start_panic` intrinsic.
127             // We want to split this into its consituient parts -
128             // the data and vtable pointers - and store them according to
129             // `unwind_data`, i.e., we store them where `__rust_maybe_catch_panic`
130             // was told to put them.
131             let payload = this.machine.panic_payload.take().unwrap();
132             let payload = this.ref_to_mplace(payload)?;
133             let payload_data_place = payload.ptr;
134             let payload_vtable_place = payload.meta.unwrap_meta();
135
136             this.write_scalar(payload_data_place, unwind_data.data_place.into())?;
137             this.write_scalar(payload_vtable_place, unwind_data.vtable_place.into())?;
138
139             // We set the return value of `__rust_maybe_catch_panic` to 1,
140             // since there was a panic.
141             let dest = unwind_data.dest;
142             this.write_scalar(Scalar::from_int(1, dest.layout.size), dest)?;
143
144             StackPopInfo::StopUnwinding
145         } else {
146             StackPopInfo::Normal
147         };
148         if let Some(stacked_borrows) = this.memory.extra.stacked_borrows.as_ref() {
149             stacked_borrows.borrow_mut().end_call(extra.call_id);
150         }
151         Ok(res)
152     }
153
154     /// Starta a panic in the interpreter with the given message as payload.
155     fn start_panic(
156         &mut self,
157         msg: &str,
158         unwind: Option<mir::BasicBlock>,
159     ) -> InterpResult<'tcx> {
160         let this = self.eval_context_mut();
161
162         // First arg: message.
163         let msg = this.allocate_str(msg, MiriMemoryKind::Machine.into());
164
165         // Call the lang item.
166         let panic = this.tcx.lang_items().panic_fn().unwrap();
167         let panic = ty::Instance::mono(this.tcx.tcx, panic);
168         this.call_function(
169             panic,
170             &[msg.to_ref()],
171             None,
172             StackPopCleanup::Goto { ret: None, unwind },
173         )
174     }
175
176     fn assert_panic(
177         &mut self,
178         msg: &mir::AssertMessage<'tcx>,
179         unwind: Option<mir::BasicBlock>,
180     ) -> InterpResult<'tcx> {
181         use rustc::mir::AssertKind::*;
182         let this = self.eval_context_mut();
183
184         match msg {
185             BoundsCheck { ref index, ref len } => {
186                 // Forward to `panic_bounds_check` lang item.
187
188                 // First arg: index.
189                 let index = this.read_scalar(this.eval_operand(index, None)?)?;
190                 // Second arg: len.
191                 let len = this.read_scalar(this.eval_operand(len, None)?)?;
192
193                 // Call the lang item.
194                 let panic_bounds_check = this.tcx.lang_items().panic_bounds_check_fn().unwrap();
195                 let panic_bounds_check = ty::Instance::mono(this.tcx.tcx, panic_bounds_check);
196                 this.call_function(
197                     panic_bounds_check,
198                     &[index.into(), len.into()],
199                     None,
200                     StackPopCleanup::Goto { ret: None, unwind },
201                 )?;
202             }
203             _ => {
204                 // Forward everything else to `panic` lang item.
205                 this.start_panic(msg.description(), unwind)?;
206             }
207         }
208         Ok(())
209     }
210 }