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