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