]> git.lizzy.rs Git - rust.git/blob - src/shims/panic.rs
Auto merge of #1832 - hyd-dev:1776-follow-up, r=RalfJung
[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 log::trace;
15
16 use rustc_ast::Mutability;
17 use rustc_middle::{mir, ty};
18 use rustc_span::Symbol;
19 use rustc_target::spec::abi::Abi;
20 use rustc_target::spec::PanicStrategy;
21
22 use crate::*;
23 use helpers::check_arg_count;
24
25 /// Holds all of the relevant data for when unwinding hits a `try` frame.
26 #[derive(Debug)]
27 pub struct CatchUnwindData<'tcx> {
28     /// The `catch_fn` callback to call in case of a panic.
29     catch_fn: Scalar<Tag>,
30     /// The `data` argument for that callback.
31     data: Scalar<Tag>,
32     /// The return place from the original call to `try`.
33     dest: PlaceTy<'tcx, Tag>,
34     /// The return block from the original call to `try`.
35     ret: mir::BasicBlock,
36 }
37
38 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
39 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
40     /// Handles the special `miri_start_panic` intrinsic, which is called
41     /// by libpanic_unwind to delegate the actual unwinding process to Miri.
42     fn handle_miri_start_panic(
43         &mut self,
44         abi: Abi,
45         link_name: Symbol,
46         args: &[OpTy<'tcx, Tag>],
47         unwind: StackPopUnwind,
48     ) -> InterpResult<'tcx> {
49         let this = self.eval_context_mut();
50
51         trace!("miri_start_panic: {:?}", this.frame().instance);
52
53         // Get the raw pointer stored in arg[0] (the panic payload).
54         let &[ref payload] = this.check_shim(abi, Abi::Rust, link_name, args)?;
55         let payload = this.read_scalar(payload)?.check_init()?;
56         let thread = this.active_thread_mut();
57         assert!(thread.panic_payload.is_none(), "the panic runtime should avoid double-panics");
58         thread.panic_payload = Some(payload);
59
60         // Jump to the unwind block to begin unwinding.
61         this.unwind_to_block(unwind)?;
62         return Ok(());
63     }
64
65     /// Handles the `try` intrinsic, the underlying implementation of `std::panicking::try`.
66     fn handle_try(
67         &mut self,
68         args: &[OpTy<'tcx, Tag>],
69         dest: &PlaceTy<'tcx, Tag>,
70         ret: mir::BasicBlock,
71     ) -> InterpResult<'tcx> {
72         let this = self.eval_context_mut();
73
74         // Signature:
75         //   fn r#try(try_fn: fn(*mut u8), data: *mut u8, catch_fn: fn(*mut u8, *mut u8)) -> i32
76         // Calls `try_fn` with `data` as argument. If that executes normally, returns 0.
77         // If that unwinds, calls `catch_fn` with the first argument being `data` and
78         // then second argument being a target-dependent `payload` (i.e. it is up to us to define
79         // what that is), and returns 1.
80         // The `payload` is passed (by libstd) to `__rust_panic_cleanup`, which is then expected to
81         // return a `Box<dyn Any + Send + 'static>`.
82         // In Miri, `miri_start_panic` is passed exactly that type, so we make the `payload` simply
83         // a pointer to `Box<dyn Any + Send + 'static>`.
84
85         // Get all the arguments.
86         let &[ref try_fn, ref data, ref catch_fn] = check_arg_count(args)?;
87         let try_fn = this.read_scalar(try_fn)?.check_init()?;
88         let data = this.read_scalar(data)?.check_init()?;
89         let catch_fn = this.read_scalar(catch_fn)?.check_init()?;
90
91         // Now we make a function call, and pass `data` as first and only argument.
92         let f_instance = this.memory.get_fn(try_fn)?.as_instance()?;
93         trace!("try_fn: {:?}", f_instance);
94         let ret_place = MPlaceTy::dangling(this.machine.layouts.unit, this).into();
95         this.call_function(
96             f_instance,
97             Abi::Rust,
98             &[data.into()],
99             Some(&ret_place),
100             // Directly return to caller.
101             StackPopCleanup::Goto { ret: Some(ret), unwind: StackPopUnwind::Skip },
102         )?;
103
104         // We ourselves will return `0`, eventually (will be overwritten if we catch a panic).
105         this.write_null(dest)?;
106
107         // In unwind mode, we tag this frame with the extra data needed to catch unwinding.
108         // This lets `handle_stack_pop` (below) know that we should stop unwinding
109         // when we pop this frame.
110         if this.tcx.sess.panic_strategy() == PanicStrategy::Unwind {
111             this.frame_mut().extra.catch_unwind =
112                 Some(CatchUnwindData { catch_fn, data, dest: *dest, ret });
113         }
114
115         return Ok(());
116     }
117
118     fn handle_stack_pop(
119         &mut self,
120         mut extra: FrameData<'tcx>,
121         unwinding: bool,
122     ) -> InterpResult<'tcx, StackPopJump> {
123         let this = self.eval_context_mut();
124
125         trace!("handle_stack_pop(extra = {:?}, unwinding = {})", extra, unwinding);
126         if let Some(stacked_borrows) = &this.memory.extra.stacked_borrows {
127             stacked_borrows.borrow_mut().end_call(extra.call_id);
128         }
129
130         // We only care about `catch_panic` if we're unwinding - if we're doing a normal
131         // return, then we don't need to do anything special.
132         if let (true, Some(catch_unwind)) = (unwinding, extra.catch_unwind.take()) {
133             // We've just popped a frame that was pushed by `try`,
134             // and we are unwinding, so we should catch that.
135             trace!(
136                 "unwinding: found catch_panic frame during unwinding: {:?}",
137                 this.frame().instance
138             );
139
140             // We set the return value of `try` to 1, since there was a panic.
141             this.write_scalar(Scalar::from_i32(1), &catch_unwind.dest)?;
142
143             // The Thread's `panic_payload` holds what was passed to `miri_start_panic`.
144             // This is exactly the second argument we need to pass to `catch_fn`.
145             let payload = this.active_thread_mut().panic_payload.take().unwrap();
146
147             // Push the `catch_fn` stackframe.
148             let f_instance = this.memory.get_fn(catch_unwind.catch_fn)?.as_instance()?;
149             trace!("catch_fn: {:?}", f_instance);
150             let ret_place = MPlaceTy::dangling(this.machine.layouts.unit, this).into();
151             this.call_function(
152                 f_instance,
153                 Abi::Rust,
154                 &[catch_unwind.data.into(), payload.into()],
155                 Some(&ret_place),
156                 // Directly return to caller of `try`.
157                 StackPopCleanup::Goto { ret: Some(catch_unwind.ret), unwind: StackPopUnwind::Skip },
158             )?;
159
160             // We pushed a new stack frame, the engine should not do any jumping now!
161             Ok(StackPopJump::NoJump)
162         } else {
163             Ok(StackPopJump::Normal)
164         }
165     }
166
167     /// Start a panic in the interpreter with the given message as payload.
168     fn start_panic(&mut self, msg: &str, unwind: StackPopUnwind) -> InterpResult<'tcx> {
169         let this = self.eval_context_mut();
170
171         // First arg: message.
172         let msg = this.allocate_str(msg, MiriMemoryKind::Machine.into(), Mutability::Not);
173
174         // Call the lang item.
175         let panic = this.tcx.lang_items().panic_fn().unwrap();
176         let panic = ty::Instance::mono(this.tcx.tcx, panic);
177         this.call_function(
178             panic,
179             Abi::Rust,
180             &[msg.to_ref()],
181             None,
182             StackPopCleanup::Goto { ret: None, unwind },
183         )
184     }
185
186     fn assert_panic(
187         &mut self,
188         msg: &mir::AssertMessage<'tcx>,
189         unwind: Option<mir::BasicBlock>,
190     ) -> InterpResult<'tcx> {
191         use rustc_middle::mir::AssertKind::*;
192         let this = self.eval_context_mut();
193
194         match msg {
195             BoundsCheck { index, len } => {
196                 // Forward to `panic_bounds_check` lang item.
197
198                 // First arg: index.
199                 let index = this.read_scalar(&this.eval_operand(index, None)?)?;
200                 // Second arg: len.
201                 let len = this.read_scalar(&this.eval_operand(len, None)?)?;
202
203                 // Call the lang item.
204                 let panic_bounds_check = this.tcx.lang_items().panic_bounds_check_fn().unwrap();
205                 let panic_bounds_check = ty::Instance::mono(this.tcx.tcx, panic_bounds_check);
206                 this.call_function(
207                     panic_bounds_check,
208                     Abi::Rust,
209                     &[index.into(), len.into()],
210                     None,
211                     StackPopCleanup::Goto {
212                         ret: None,
213                         unwind: match unwind {
214                             Some(cleanup) => StackPopUnwind::Cleanup(cleanup),
215                             None => StackPopUnwind::Skip,
216                         },
217                     },
218                 )?;
219             }
220             _ => {
221                 // Forward everything else to `panic` lang item.
222                 this.start_panic(
223                     msg.description(),
224                     match unwind {
225                         Some(cleanup) => StackPopUnwind::Cleanup(cleanup),
226                         None => StackPopUnwind::Skip,
227                     },
228                 )?;
229             }
230         }
231         Ok(())
232     }
233 }