]> git.lizzy.rs Git - rust.git/blob - src/libpanic_unwind/seh.rs
Rollup merge of #58440 - gnzlbg:v6, r=japaric
[rust.git] / src / libpanic_unwind / seh.rs
1 //! Windows SEH
2 //!
3 //! On Windows (currently only on MSVC), the default exception handling
4 //! mechanism is Structured Exception Handling (SEH). This is quite different
5 //! than Dwarf-based exception handling (e.g., what other unix platforms use) in
6 //! terms of compiler internals, so LLVM is required to have a good deal of
7 //! extra support for SEH.
8 //!
9 //! In a nutshell, what happens here is:
10 //!
11 //! 1. The `panic` function calls the standard Windows function
12 //!    `_CxxThrowException` to throw a C++-like exception, triggering the
13 //!    unwinding process.
14 //! 2. All landing pads generated by the compiler use the personality function
15 //!    `__CxxFrameHandler3`, a function in the CRT, and the unwinding code in
16 //!    Windows will use this personality function to execute all cleanup code on
17 //!    the stack.
18 //! 3. All compiler-generated calls to `invoke` have a landing pad set as a
19 //!    `cleanuppad` LLVM instruction, which indicates the start of the cleanup
20 //!    routine. The personality (in step 2, defined in the CRT) is responsible
21 //!    for running the cleanup routines.
22 //! 4. Eventually the "catch" code in the `try` intrinsic (generated by the
23 //!    compiler) is executed and indicates that control should come back to
24 //!    Rust. This is done via a `catchswitch` plus a `catchpad` instruction in
25 //!    LLVM IR terms, finally returning normal control to the program with a
26 //!    `catchret` instruction.
27 //!
28 //! Some specific differences from the gcc-based exception handling are:
29 //!
30 //! * Rust has no custom personality function, it is instead *always*
31 //!   `__CxxFrameHandler3`. Additionally, no extra filtering is performed, so we
32 //!   end up catching any C++ exceptions that happen to look like the kind we're
33 //!   throwing. Note that throwing an exception into Rust is undefined behavior
34 //!   anyway, so this should be fine.
35 //! * We've got some data to transmit across the unwinding boundary,
36 //!   specifically a `Box<dyn Any + Send>`. Like with Dwarf exceptions
37 //!   these two pointers are stored as a payload in the exception itself. On
38 //!   MSVC, however, there's no need for an extra heap allocation because the
39 //!   call stack is preserved while filter functions are being executed. This
40 //!   means that the pointers are passed directly to `_CxxThrowException` which
41 //!   are then recovered in the filter function to be written to the stack frame
42 //!   of the `try` intrinsic.
43 //!
44 //! [win64]: http://msdn.microsoft.com/en-us/library/1eyas8tf.aspx
45 //! [llvm]: http://llvm.org/docs/ExceptionHandling.html#background-on-windows-exceptions
46
47 #![allow(nonstandard_style)]
48 #![allow(private_no_mangle_fns)]
49
50 use alloc::boxed::Box;
51 use core::any::Any;
52 use core::mem;
53 use core::raw;
54
55 use crate::windows as c;
56 use libc::{c_int, c_uint};
57
58 // First up, a whole bunch of type definitions. There's a few platform-specific
59 // oddities here, and a lot that's just blatantly copied from LLVM. The purpose
60 // of all this is to implement the `panic` function below through a call to
61 // `_CxxThrowException`.
62 //
63 // This function takes two arguments. The first is a pointer to the data we're
64 // passing in, which in this case is our trait object. Pretty easy to find! The
65 // next, however, is more complicated. This is a pointer to a `_ThrowInfo`
66 // structure, and it generally is just intended to just describe the exception
67 // being thrown.
68 //
69 // Currently the definition of this type [1] is a little hairy, and the main
70 // oddity (and difference from the online article) is that on 32-bit the
71 // pointers are pointers but on 64-bit the pointers are expressed as 32-bit
72 // offsets from the `__ImageBase` symbol. The `ptr_t` and `ptr!` macro in the
73 // modules below are used to express this.
74 //
75 // The maze of type definitions also closely follows what LLVM emits for this
76 // sort of operation. For example, if you compile this C++ code on MSVC and emit
77 // the LLVM IR:
78 //
79 //      #include <stdin.h>
80 //
81 //      void foo() {
82 //          uint64_t a[2] = {0, 1};
83 //          throw a;
84 //      }
85 //
86 // That's essentially what we're trying to emulate. Most of the constant values
87 // below were just copied from LLVM, I'm at least not 100% sure what's going on
88 // everywhere. For example the `.PA_K\0` and `.PEA_K\0` strings below (stuck in
89 // the names of a few of these) I'm not actually sure what they do, but it seems
90 // to mirror what LLVM does!
91 //
92 // In any case, these structures are all constructed in a similar manner, and
93 // it's just somewhat verbose for us.
94 //
95 // [1]: http://www.geoffchappell.com/studies/msvc/language/predefined/
96
97 #[cfg(target_arch = "x86")]
98 #[macro_use]
99 mod imp {
100     pub type ptr_t = *mut u8;
101     pub const OFFSET: i32 = 4;
102
103     pub const NAME1: [u8; 7] = [b'.', b'P', b'A', b'_', b'K', 0, 0];
104     pub const NAME2: [u8; 7] = [b'.', b'P', b'A', b'X', 0, 0, 0];
105
106     macro_rules! ptr {
107         (0) => (0 as *mut u8);
108         ($e:expr) => ($e as *mut u8);
109     }
110 }
111
112 #[cfg(any(target_arch = "x86_64", target_arch = "arm"))]
113 #[macro_use]
114 mod imp {
115     pub type ptr_t = u32;
116     pub const OFFSET: i32 = 8;
117
118     pub const NAME1: [u8; 7] = [b'.', b'P', b'E', b'A', b'_', b'K', 0];
119     pub const NAME2: [u8; 7] = [b'.', b'P', b'E', b'A', b'X', 0, 0];
120
121     extern "C" {
122         pub static __ImageBase: u8;
123     }
124
125     macro_rules! ptr {
126         (0) => (0);
127         ($e:expr) => {
128             (($e as usize) - (&imp::__ImageBase as *const _ as usize)) as u32
129         }
130     }
131 }
132
133 #[repr(C)]
134 pub struct _ThrowInfo {
135     pub attributes: c_uint,
136     pub pnfnUnwind: imp::ptr_t,
137     pub pForwardCompat: imp::ptr_t,
138     pub pCatchableTypeArray: imp::ptr_t,
139 }
140
141 #[repr(C)]
142 pub struct _CatchableTypeArray {
143     pub nCatchableTypes: c_int,
144     pub arrayOfCatchableTypes: [imp::ptr_t; 2],
145 }
146
147 #[repr(C)]
148 pub struct _CatchableType {
149     pub properties: c_uint,
150     pub pType: imp::ptr_t,
151     pub thisDisplacement: _PMD,
152     pub sizeOrOffset: c_int,
153     pub copy_function: imp::ptr_t,
154 }
155
156 #[repr(C)]
157 pub struct _PMD {
158     pub mdisp: c_int,
159     pub pdisp: c_int,
160     pub vdisp: c_int,
161 }
162
163 #[repr(C)]
164 pub struct _TypeDescriptor {
165     pub pVFTable: *const u8,
166     pub spare: *mut u8,
167     pub name: [u8; 7],
168 }
169
170 static mut THROW_INFO: _ThrowInfo = _ThrowInfo {
171     attributes: 0,
172     pnfnUnwind: ptr!(0),
173     pForwardCompat: ptr!(0),
174     pCatchableTypeArray: ptr!(0),
175 };
176
177 static mut CATCHABLE_TYPE_ARRAY: _CatchableTypeArray = _CatchableTypeArray {
178     nCatchableTypes: 2,
179     arrayOfCatchableTypes: [ptr!(0), ptr!(0)],
180 };
181
182 static mut CATCHABLE_TYPE1: _CatchableType = _CatchableType {
183     properties: 1,
184     pType: ptr!(0),
185     thisDisplacement: _PMD {
186         mdisp: 0,
187         pdisp: -1,
188         vdisp: 0,
189     },
190     sizeOrOffset: imp::OFFSET,
191     copy_function: ptr!(0),
192 };
193
194 static mut CATCHABLE_TYPE2: _CatchableType = _CatchableType {
195     properties: 1,
196     pType: ptr!(0),
197     thisDisplacement: _PMD {
198         mdisp: 0,
199         pdisp: -1,
200         vdisp: 0,
201     },
202     sizeOrOffset: imp::OFFSET,
203     copy_function: ptr!(0),
204 };
205
206 extern "C" {
207     // The leading `\x01` byte here is actually a magical signal to LLVM to
208     // *not* apply any other mangling like prefixing with a `_` character.
209     //
210     // This symbol is the vtable used by C++'s `std::type_info`. Objects of type
211     // `std::type_info`, type descriptors, have a pointer to this table. Type
212     // descriptors are referenced by the C++ EH structures defined above and
213     // that we construct below.
214     #[link_name = "\x01??_7type_info@@6B@"]
215     static TYPE_INFO_VTABLE: *const u8;
216 }
217
218 // We use #[lang = "msvc_try_filter"] here as this is the type descriptor which
219 // we'll use in LLVM's `catchpad` instruction which ends up also being passed as
220 // an argument to the C++ personality function.
221 //
222 // Again, I'm not entirely sure what this is describing, it just seems to work.
223 #[cfg_attr(not(test), lang = "msvc_try_filter")]
224 static mut TYPE_DESCRIPTOR1: _TypeDescriptor = _TypeDescriptor {
225     pVFTable: unsafe { &TYPE_INFO_VTABLE } as *const _ as *const _,
226     spare: 0 as *mut _,
227     name: imp::NAME1,
228 };
229
230 static mut TYPE_DESCRIPTOR2: _TypeDescriptor = _TypeDescriptor {
231     pVFTable: unsafe { &TYPE_INFO_VTABLE } as *const _ as *const _,
232     spare: 0 as *mut _,
233     name: imp::NAME2,
234 };
235
236 pub unsafe fn panic(data: Box<dyn Any + Send>) -> u32 {
237     use core::intrinsics::atomic_store;
238
239     // _CxxThrowException executes entirely on this stack frame, so there's no
240     // need to otherwise transfer `data` to the heap. We just pass a stack
241     // pointer to this function.
242     //
243     // The first argument is the payload being thrown (our two pointers), and
244     // the second argument is the type information object describing the
245     // exception (constructed above).
246     let ptrs = mem::transmute::<_, raw::TraitObject>(data);
247     let mut ptrs = [ptrs.data as u64, ptrs.vtable as u64];
248     let mut ptrs_ptr = ptrs.as_mut_ptr();
249
250     // This... may seems surprising, and justifiably so. On 32-bit MSVC the
251     // pointers between these structure are just that, pointers. On 64-bit MSVC,
252     // however, the pointers between structures are rather expressed as 32-bit
253     // offsets from `__ImageBase`.
254     //
255     // Consequently, on 32-bit MSVC we can declare all these pointers in the
256     // `static`s above. On 64-bit MSVC, we would have to express subtraction of
257     // pointers in statics, which Rust does not currently allow, so we can't
258     // actually do that.
259     //
260     // The next best thing, then is to fill in these structures at runtime
261     // (panicking is already the "slow path" anyway). So here we reinterpret all
262     // of these pointer fields as 32-bit integers and then store the
263     // relevant value into it (atomically, as concurrent panics may be
264     // happening). Technically the runtime will probably do a nonatomic read of
265     // these fields, but in theory they never read the *wrong* value so it
266     // shouldn't be too bad...
267     //
268     // In any case, we basically need to do something like this until we can
269     // express more operations in statics (and we may never be able to).
270     atomic_store(&mut THROW_INFO.pCatchableTypeArray as *mut _ as *mut u32,
271                  ptr!(&CATCHABLE_TYPE_ARRAY as *const _) as u32);
272     atomic_store(&mut CATCHABLE_TYPE_ARRAY.arrayOfCatchableTypes[0] as *mut _ as *mut u32,
273                  ptr!(&CATCHABLE_TYPE1 as *const _) as u32);
274     atomic_store(&mut CATCHABLE_TYPE_ARRAY.arrayOfCatchableTypes[1] as *mut _ as *mut u32,
275                  ptr!(&CATCHABLE_TYPE2 as *const _) as u32);
276     atomic_store(&mut CATCHABLE_TYPE1.pType as *mut _ as *mut u32,
277                  ptr!(&TYPE_DESCRIPTOR1 as *const _) as u32);
278     atomic_store(&mut CATCHABLE_TYPE2.pType as *mut _ as *mut u32,
279                  ptr!(&TYPE_DESCRIPTOR2 as *const _) as u32);
280
281     c::_CxxThrowException(&mut ptrs_ptr as *mut _ as *mut _,
282                           &mut THROW_INFO as *mut _ as *mut _);
283     u32::max_value()
284 }
285
286 pub fn payload() -> [u64; 2] {
287     [0; 2]
288 }
289
290 pub unsafe fn cleanup(payload: [u64; 2]) -> Box<dyn Any + Send> {
291     mem::transmute(raw::TraitObject {
292         data: payload[0] as *mut _,
293         vtable: payload[1] as *mut _,
294     })
295 }
296
297 // This is required by the compiler to exist (e.g., it's a lang item), but
298 // it's never actually called by the compiler because __C_specific_handler
299 // or _except_handler3 is the personality function that is always used.
300 // Hence this is just an aborting stub.
301 #[lang = "eh_personality"]
302 #[cfg(not(test))]
303 fn rust_eh_personality() {
304     unsafe { core::intrinsics::abort() }
305 }