]> git.lizzy.rs Git - rust.git/blob - src/shims/panic.rs
281fe1e671bb440fa748bc81d7233f01b779c245
[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, abi::LayoutOf};
18
19 use crate::*;
20
21 /// Holds all of the relevant data for when unwinding hits a `try` frame.
22 #[derive(Debug)]
23 pub struct CatchUnwindData<'tcx> {
24     /// The `catch_fn` callback to call in case of a panic.
25     catch_fn: Scalar<Tag>,
26     /// The `data` argument for that callback.
27     data: Scalar<Tag>,
28     /// The return place from the original call to `try`.
29     dest: PlaceTy<'tcx, Tag>,
30     /// The return block from the original call to `try`.
31     ret: mir::BasicBlock,
32 }
33
34 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
35 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
36     /// Check if panicking is supported on this target, and give a good error otherwise.
37     fn check_panic_supported(&self) -> InterpResult<'tcx> {
38         match self.eval_context_ref().tcx.sess.target.target.target_os.as_str() {
39             "linux" | "macos" => Ok(()),
40             _ => throw_unsup_format!("panicking is not supported on this target"),
41         }
42     }
43
44     /// Handles the special `miri_start_panic` intrinsic, which is called
45     /// by libpanic_unwind to delegate the actual unwinding process to Miri.
46     fn handle_miri_start_panic(
47         &mut self,
48         args: &[OpTy<'tcx, Tag>],
49         unwind: Option<mir::BasicBlock>,
50     ) -> InterpResult<'tcx> {
51         let this = self.eval_context_mut();
52
53         trace!("miri_start_panic: {:?}", this.frame().instance);
54
55         // Get the raw pointer stored in arg[0] (the panic payload).
56         let payload = this.read_scalar(args[0])?.not_undef()?;
57         assert!(
58             this.machine.panic_payload.is_none(),
59             "the panic runtime should avoid double-panics"
60         );
61         this.machine.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 try_fn = this.read_scalar(args[0])?.not_undef()?;
90         let data = this.read_scalar(args[1])?.not_undef()?;
91         let catch_fn = this.read_scalar(args[2])?.not_undef()?;
92
93         // Now we make a function call, and pass `data` as first and only argument.
94         let f_instance = this.memory.get_fn(try_fn)?.as_instance()?;
95         trace!("try_fn: {:?}", f_instance);
96         let ret_place = MPlaceTy::dangling(this.layout_of(this.tcx.mk_unit())?, this).into();
97         this.call_function(
98             f_instance,
99             &[data.into()],
100             Some(ret_place),
101             // Directly return to caller.
102             StackPopCleanup::Goto { ret: Some(ret), unwind: None },
103         )?;
104
105         // We ourselves will return `0`, eventually (will be overwritten if we catch a panic).
106         this.write_null(dest)?;
107
108         // In unwind mode, we tag this frame with the extra data needed to catch unwinding.
109         // This lets `handle_stack_pop` (below) know that we should stop unwinding
110         // when we pop this frame.
111         if this.tcx.sess.panic_strategy() == PanicStrategy::Unwind {
112             this.frame_mut().extra.catch_unwind = Some(CatchUnwindData { catch_fn, data, 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.as_ref() {
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!("unwinding: found catch_panic frame during unwinding: {:?}", this.frame().instance);
136
137             // We set the return value of `try` to 1, since there was a panic.
138             this.write_scalar(Scalar::from_i32(1), catch_unwind.dest)?;
139
140             // `panic_payload` holds what was passed to `miri_start_panic`.
141             // This is exactly the second argument we need to pass to `catch_fn`.
142             let payload = this.machine.panic_payload.take().unwrap();
143
144             // Push the `catch_fn` stackframe.
145             let f_instance = this.memory.get_fn(catch_unwind.catch_fn)?.as_instance()?;
146             trace!("catch_fn: {:?}", f_instance);
147             let ret_place = MPlaceTy::dangling(this.layout_of(this.tcx.mk_unit())?, this).into();
148             this.call_function(
149                 f_instance,
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: None },
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(
165         &mut self,
166         msg: &str,
167         unwind: Option<mir::BasicBlock>,
168     ) -> InterpResult<'tcx> {
169         let this = self.eval_context_mut();
170
171         // First arg: message.
172         let msg = this.allocate_str(msg, MiriMemoryKind::Machine.into());
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             &[msg.to_ref()],
180             None,
181             StackPopCleanup::Goto { ret: None, unwind },
182         )
183     }
184
185     fn assert_panic(
186         &mut self,
187         msg: &mir::AssertMessage<'tcx>,
188         unwind: Option<mir::BasicBlock>,
189     ) -> InterpResult<'tcx> {
190         use rustc_middle::mir::AssertKind::*;
191         let this = self.eval_context_mut();
192
193         match msg {
194             BoundsCheck { index, len } => {
195                 // Forward to `panic_bounds_check` lang item.
196
197                 // First arg: index.
198                 let index = this.read_scalar(this.eval_operand(index, None)?)?;
199                 // Second arg: len.
200                 let len = this.read_scalar(this.eval_operand(len, None)?)?;
201
202                 // Call the lang item.
203                 let panic_bounds_check = this.tcx.lang_items().panic_bounds_check_fn().unwrap();
204                 let panic_bounds_check = ty::Instance::mono(this.tcx.tcx, panic_bounds_check);
205                 this.call_function(
206                     panic_bounds_check,
207                     &[index.into(), len.into()],
208                     None,
209                     StackPopCleanup::Goto { ret: None, unwind },
210                 )?;
211             }
212             _ => {
213                 // Forward everything else to `panic` lang item.
214                 this.start_panic(msg.description(), unwind)?;
215             }
216         }
217         Ok(())
218     }
219 }