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