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