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