]> git.lizzy.rs Git - rust.git/blob - library/panic_unwind/src/seh.rs
Auto merge of #103299 - nikic:usub-overflow, r=wesleywiser
[rust.git] / library / panic_unwind / src / 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]: https://docs.microsoft.com/en-us/cpp/build/exception-handling-x64
45 //! [llvm]: https://llvm.org/docs/ExceptionHandling.html#background-on-windows-exceptions
46
47 #![allow(nonstandard_style)]
48
49 use alloc::boxed::Box;
50 use core::any::Any;
51 use core::mem::{self, ManuallyDrop};
52 use core::ptr;
53 use libc::{c_int, c_uint, c_void};
54
55 // NOTE(nbdd0121): The `canary` field will be part of stable ABI after `c_unwind` stabilization.
56 #[repr(C)]
57 struct Exception {
58     // See `gcc.rs` on why this is present. We already have a static here so just use it.
59     canary: *const _TypeDescriptor,
60
61     // This needs to be an Option because we catch the exception by reference
62     // and its destructor is executed by the C++ runtime. When we take the Box
63     // out of the exception, we need to leave the exception in a valid state
64     // for its destructor to run without double-dropping the Box.
65     data: Option<Box<dyn Any + Send>>,
66 }
67
68 // First up, a whole bunch of type definitions. There's a few platform-specific
69 // oddities here, and a lot that's just blatantly copied from LLVM. The purpose
70 // of all this is to implement the `panic` function below through a call to
71 // `_CxxThrowException`.
72 //
73 // This function takes two arguments. The first is a pointer to the data we're
74 // passing in, which in this case is our trait object. Pretty easy to find! The
75 // next, however, is more complicated. This is a pointer to a `_ThrowInfo`
76 // structure, and it generally is just intended to just describe the exception
77 // being thrown.
78 //
79 // Currently the definition of this type [1] is a little hairy, and the main
80 // oddity (and difference from the online article) is that on 32-bit the
81 // pointers are pointers but on 64-bit the pointers are expressed as 32-bit
82 // offsets from the `__ImageBase` symbol. The `ptr_t` and `ptr!` macro in the
83 // modules below are used to express this.
84 //
85 // The maze of type definitions also closely follows what LLVM emits for this
86 // sort of operation. For example, if you compile this C++ code on MSVC and emit
87 // the LLVM IR:
88 //
89 //      #include <stdint.h>
90 //
91 //      struct rust_panic {
92 //          rust_panic(const rust_panic&);
93 //          ~rust_panic();
94 //
95 //          uint64_t x[2];
96 //      };
97 //
98 //      void foo() {
99 //          rust_panic a = {0, 1};
100 //          throw a;
101 //      }
102 //
103 // That's essentially what we're trying to emulate. Most of the constant values
104 // below were just copied from LLVM,
105 //
106 // In any case, these structures are all constructed in a similar manner, and
107 // it's just somewhat verbose for us.
108 //
109 // [1]: https://www.geoffchappell.com/studies/msvc/language/predefined/
110
111 #[cfg(target_arch = "x86")]
112 #[macro_use]
113 mod imp {
114     pub type ptr_t = *mut u8;
115
116     macro_rules! ptr {
117         (0) => {
118             core::ptr::null_mut()
119         };
120         ($e:expr) => {
121             $e as *mut u8
122         };
123     }
124 }
125
126 #[cfg(not(target_arch = "x86"))]
127 #[macro_use]
128 mod imp {
129     pub type ptr_t = u32;
130
131     extern "C" {
132         pub static __ImageBase: u8;
133     }
134
135     macro_rules! ptr {
136         (0) => (0);
137         ($e:expr) => {
138             (($e as usize) - (&imp::__ImageBase as *const _ as usize)) as u32
139         }
140     }
141 }
142
143 #[repr(C)]
144 pub struct _ThrowInfo {
145     pub attributes: c_uint,
146     pub pmfnUnwind: imp::ptr_t,
147     pub pForwardCompat: imp::ptr_t,
148     pub pCatchableTypeArray: imp::ptr_t,
149 }
150
151 #[repr(C)]
152 pub struct _CatchableTypeArray {
153     pub nCatchableTypes: c_int,
154     pub arrayOfCatchableTypes: [imp::ptr_t; 1],
155 }
156
157 #[repr(C)]
158 pub struct _CatchableType {
159     pub properties: c_uint,
160     pub pType: imp::ptr_t,
161     pub thisDisplacement: _PMD,
162     pub sizeOrOffset: c_int,
163     pub copyFunction: imp::ptr_t,
164 }
165
166 #[repr(C)]
167 pub struct _PMD {
168     pub mdisp: c_int,
169     pub pdisp: c_int,
170     pub vdisp: c_int,
171 }
172
173 #[repr(C)]
174 pub struct _TypeDescriptor {
175     pub pVFTable: *const u8,
176     pub spare: *mut u8,
177     pub name: [u8; 11],
178 }
179
180 // Note that we intentionally ignore name mangling rules here: we don't want C++
181 // to be able to catch Rust panics by simply declaring a `struct rust_panic`.
182 //
183 // When modifying, make sure that the type name string exactly matches
184 // the one used in `compiler/rustc_codegen_llvm/src/intrinsic.rs`.
185 const TYPE_NAME: [u8; 11] = *b"rust_panic\0";
186
187 static mut THROW_INFO: _ThrowInfo = _ThrowInfo {
188     attributes: 0,
189     pmfnUnwind: ptr!(0),
190     pForwardCompat: ptr!(0),
191     pCatchableTypeArray: ptr!(0),
192 };
193
194 static mut CATCHABLE_TYPE_ARRAY: _CatchableTypeArray =
195     _CatchableTypeArray { nCatchableTypes: 1, arrayOfCatchableTypes: [ptr!(0)] };
196
197 static mut CATCHABLE_TYPE: _CatchableType = _CatchableType {
198     properties: 0,
199     pType: ptr!(0),
200     thisDisplacement: _PMD { mdisp: 0, pdisp: -1, vdisp: 0 },
201     sizeOrOffset: mem::size_of::<Exception>() as c_int,
202     copyFunction: ptr!(0),
203 };
204
205 extern "C" {
206     // The leading `\x01` byte here is actually a magical signal to LLVM to
207     // *not* apply any other mangling like prefixing with a `_` character.
208     //
209     // This symbol is the vtable used by C++'s `std::type_info`. Objects of type
210     // `std::type_info`, type descriptors, have a pointer to this table. Type
211     // descriptors are referenced by the C++ EH structures defined above and
212     // that we construct below.
213     #[link_name = "\x01??_7type_info@@6B@"]
214     static TYPE_INFO_VTABLE: *const u8;
215 }
216
217 // This type descriptor is only used when throwing an exception. The catch part
218 // is handled by the try intrinsic, which generates its own TypeDescriptor.
219 //
220 // This is fine since the MSVC runtime uses string comparison on the type name
221 // to match TypeDescriptors rather than pointer equality.
222 static mut TYPE_DESCRIPTOR: _TypeDescriptor = _TypeDescriptor {
223     pVFTable: unsafe { &TYPE_INFO_VTABLE } as *const _ as *const _,
224     spare: core::ptr::null_mut(),
225     name: TYPE_NAME,
226 };
227
228 // Destructor used if the C++ code decides to capture the exception and drop it
229 // without propagating it. The catch part of the try intrinsic will set the
230 // first word of the exception object to 0 so that it is skipped by the
231 // destructor.
232 //
233 // Note that x86 Windows uses the "thiscall" calling convention for C++ member
234 // functions instead of the default "C" calling convention.
235 //
236 // The exception_copy function is a bit special here: it is invoked by the MSVC
237 // runtime under a try/catch block and the panic that we generate here will be
238 // used as the result of the exception copy. This is used by the C++ runtime to
239 // support capturing exceptions with std::exception_ptr, which we can't support
240 // because Box<dyn Any> isn't clonable.
241 macro_rules! define_cleanup {
242     ($abi:tt $abi2:tt) => {
243         unsafe extern $abi fn exception_cleanup(e: *mut Exception) {
244             if let Exception { data: Some(b), .. } = e.read() {
245                 drop(b);
246                 super::__rust_drop_panic();
247             }
248         }
249         unsafe extern $abi2 fn exception_copy(_dest: *mut Exception,
250                                              _src: *mut Exception)
251                                              -> *mut Exception {
252             panic!("Rust panics cannot be copied");
253         }
254     }
255 }
256 cfg_if::cfg_if! {
257    if #[cfg(target_arch = "x86")] {
258        define_cleanup!("thiscall" "thiscall-unwind");
259    } else {
260        define_cleanup!("C" "C-unwind");
261    }
262 }
263
264 pub unsafe fn panic(data: Box<dyn Any + Send>) -> u32 {
265     use core::intrinsics::atomic_store_seqcst;
266
267     // _CxxThrowException executes entirely on this stack frame, so there's no
268     // need to otherwise transfer `data` to the heap. We just pass a stack
269     // pointer to this function.
270     //
271     // The ManuallyDrop is needed here since we don't want Exception to be
272     // dropped when unwinding. Instead it will be dropped by exception_cleanup
273     // which is invoked by the C++ runtime.
274     let mut exception = ManuallyDrop::new(Exception { canary: &TYPE_DESCRIPTOR, data: Some(data) });
275     let throw_ptr = &mut exception as *mut _ as *mut _;
276
277     // This... may seems surprising, and justifiably so. On 32-bit MSVC the
278     // pointers between these structure are just that, pointers. On 64-bit MSVC,
279     // however, the pointers between structures are rather expressed as 32-bit
280     // offsets from `__ImageBase`.
281     //
282     // Consequently, on 32-bit MSVC we can declare all these pointers in the
283     // `static`s above. On 64-bit MSVC, we would have to express subtraction of
284     // pointers in statics, which Rust does not currently allow, so we can't
285     // actually do that.
286     //
287     // The next best thing, then is to fill in these structures at runtime
288     // (panicking is already the "slow path" anyway). So here we reinterpret all
289     // of these pointer fields as 32-bit integers and then store the
290     // relevant value into it (atomically, as concurrent panics may be
291     // happening). Technically the runtime will probably do a nonatomic read of
292     // these fields, but in theory they never read the *wrong* value so it
293     // shouldn't be too bad...
294     //
295     // In any case, we basically need to do something like this until we can
296     // express more operations in statics (and we may never be able to).
297     atomic_store_seqcst(
298         &mut THROW_INFO.pmfnUnwind as *mut _ as *mut u32,
299         ptr!(exception_cleanup) as u32,
300     );
301     atomic_store_seqcst(
302         &mut THROW_INFO.pCatchableTypeArray as *mut _ as *mut u32,
303         ptr!(&CATCHABLE_TYPE_ARRAY as *const _) as u32,
304     );
305     atomic_store_seqcst(
306         &mut CATCHABLE_TYPE_ARRAY.arrayOfCatchableTypes[0] as *mut _ as *mut u32,
307         ptr!(&CATCHABLE_TYPE as *const _) as u32,
308     );
309     atomic_store_seqcst(
310         &mut CATCHABLE_TYPE.pType as *mut _ as *mut u32,
311         ptr!(&TYPE_DESCRIPTOR as *const _) as u32,
312     );
313     atomic_store_seqcst(
314         &mut CATCHABLE_TYPE.copyFunction as *mut _ as *mut u32,
315         ptr!(exception_copy) as u32,
316     );
317
318     extern "system-unwind" {
319         fn _CxxThrowException(pExceptionObject: *mut c_void, pThrowInfo: *mut u8) -> !;
320     }
321
322     _CxxThrowException(throw_ptr, &mut THROW_INFO as *mut _ as *mut _);
323 }
324
325 pub unsafe fn cleanup(payload: *mut u8) -> Box<dyn Any + Send> {
326     // A null payload here means that we got here from the catch (...) of
327     // __rust_try. This happens when a non-Rust foreign exception is caught.
328     if payload.is_null() {
329         super::__rust_foreign_exception();
330     }
331     let exception = payload as *mut Exception;
332     let canary = ptr::addr_of!((*exception).canary).read();
333     if !ptr::eq(canary, &TYPE_DESCRIPTOR) {
334         // A foreign Rust exception.
335         super::__rust_foreign_exception();
336     }
337     (*exception).data.take().unwrap()
338 }