]> git.lizzy.rs Git - rust.git/blob - src/shims/panic.rs
Auto merge of #1227 - RalfJung:unwind, 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 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 when unwinding hits a `try` frame.
21 #[derive(Debug)]
22 pub struct CatchUnwindData<'tcx> {
23     /// The `catch_fn` callback to call in case of a panic.
24     catch_fn: Scalar<Tag>,
25     /// The `data` argument for that callback.
26     data: Scalar<Tag>,
27     /// The return place from the original call to `try`.
28     dest: PlaceTy<'tcx, Tag>,
29     /// The return block from the original call to `try`.
30     ret: mir::BasicBlock,
31 }
32
33 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
34 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
35     /// Handles the special `miri_start_panic` intrinsic, which is called
36     /// by libpanic_unwind to delegate the actual unwinding process to Miri.
37     fn handle_miri_start_panic(
38         &mut self,
39         args: &[OpTy<'tcx, Tag>],
40         unwind: Option<mir::BasicBlock>,
41     ) -> InterpResult<'tcx> {
42         let this = self.eval_context_mut();
43
44         trace!("miri_start_panic: {:?}", this.frame().span);
45
46         // Get the raw pointer stored in arg[0] (the panic payload).
47         let payload = this.read_scalar(args[0])?.not_undef()?;
48         assert!(
49             this.machine.panic_payload.is_none(),
50             "the panic runtime should avoid double-panics"
51         );
52         this.machine.panic_payload = Some(payload);
53
54         // Jump to the unwind block to begin unwinding.
55         this.unwind_to_block(unwind);
56         return Ok(());
57     }
58
59     /// Handles the `try` intrinsic, the underlying implementation of `std::panicking::try`.
60     fn handle_try(
61         &mut self,
62         args: &[OpTy<'tcx, Tag>],
63         dest: PlaceTy<'tcx, Tag>,
64         ret: mir::BasicBlock,
65     ) -> InterpResult<'tcx> {
66         let this = self.eval_context_mut();
67
68         // Signature:
69         //   fn r#try(try_fn: fn(*mut u8), data: *mut u8, catch_fn: fn(*mut u8, *mut u8)) -> i32
70         // Calls `try_fn` with `data` as argument. If that executes normally, returns 0.
71         // If that unwinds, calls `catch_fn` with the first argument being `data` and
72         // then second argument being a target-dependent `payload` (i.e. it is up to us to define
73         // what that is), and returns 1.
74         // The `payload` is passed (by libstd) to `__rust_panic_cleanup`, which is then expected to
75         // return a `Box<dyn Any + Send + 'static>`.
76         // In Miri, `miri_start_panic` is passed exactly that type, so we make the `payload` simply
77         // a pointer to `Box<dyn Any + Send + 'static>`.
78
79         // Get all the arguments.
80         let try_fn = this.read_scalar(args[0])?.not_undef()?;
81         let data = this.read_scalar(args[1])?.not_undef()?;
82         let catch_fn = this.read_scalar(args[2])?.not_undef()?;
83
84         // Now we make a function call, and pass `data` as first and only argument.
85         let f_instance = this.memory.get_fn(try_fn)?.as_instance()?;
86         trace!("try_fn: {:?}", f_instance);
87         let ret_place = MPlaceTy::dangling(this.layout_of(this.tcx.mk_unit())?, this).into();
88         this.call_function(
89             f_instance,
90             &[data.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 the extra data needed to catch unwinding.
100         // This lets `handle_stack_pop` (below) know that we should stop unwinding
101         // when we pop this frame.
102         if this.tcx.sess.panic_strategy() == PanicStrategy::Unwind {
103             this.frame_mut().extra.catch_unwind = Some(CatchUnwindData { catch_fn, data, dest, ret });
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, StackPopJump> {
114         let this = self.eval_context_mut();
115
116         trace!("handle_stack_pop(extra = {:?}, unwinding = {})", extra, unwinding);
117         if let Some(stacked_borrows) = this.memory.extra.stacked_borrows.as_ref() {
118             stacked_borrows.borrow_mut().end_call(extra.call_id);
119         }
120
121         // We only care about `catch_panic` if we're unwinding - if we're doing a normal
122         // return, then we don't need to do anything special.
123         if let (true, Some(catch_unwind)) = (unwinding, extra.catch_unwind.take()) {
124             // We've just popped a frame that was pushed by `try`,
125             // and we are unwinding, so we should catch that.
126             trace!("unwinding: found catch_panic frame during unwinding: {:?}", this.frame().span);
127
128             // We set the return value of `try` to 1, since there was a panic.
129             this.write_scalar(Scalar::from_i32(1), catch_unwind.dest)?;
130
131             // `panic_payload` holds what was passed to `miri_start_panic`.
132             // This is exactly the second argument we need to pass to `catch_fn`.
133             let payload = this.machine.panic_payload.take().unwrap();
134
135             // Push the `catch_fn` stackframe.
136             let f_instance = this.memory.get_fn(catch_unwind.catch_fn)?.as_instance()?;
137             trace!("catch_fn: {:?}", f_instance);
138             let ret_place = MPlaceTy::dangling(this.layout_of(this.tcx.mk_unit())?, this).into();
139             this.call_function(
140                 f_instance,
141                 &[catch_unwind.data.into(), payload.into()],
142                 Some(ret_place),
143                 // Directly return to caller of `try`.
144                 StackPopCleanup::Goto { ret: Some(catch_unwind.ret), unwind: None },
145             )?;
146
147             // We pushed a new stack frame, the engine should not do any jumping now!
148             Ok(StackPopJump::NoJump)
149         } else {
150             Ok(StackPopJump::Normal)
151         }
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 }