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.
9 //! In a nutshell, what happens here is:
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
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.
28 //! Some specific differences from the gcc-based exception handling are:
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.
44 //! [win64]: https://docs.microsoft.com/en-us/cpp/build/exception-handling-x64
45 //! [llvm]: http://llvm.org/docs/ExceptionHandling.html#background-on-windows-exceptions
47 #![allow(nonstandard_style)]
49 use alloc
::boxed
::Box
;
51 use core
::mem
::{self, ManuallyDrop}
;
52 use libc
::{c_int, c_uint, c_void}
;
55 // This needs to be an Option because we catch the exception by reference
56 // and its destructor is executed by the C++ runtime. When we take the Box
57 // out of the exception, we need to leave the exception in a valid state
58 // for its destructor to run without double-dropping the Box.
59 data
: Option
<Box
<dyn Any
+ Send
>>,
62 // First up, a whole bunch of type definitions. There's a few platform-specific
63 // oddities here, and a lot that's just blatantly copied from LLVM. The purpose
64 // of all this is to implement the `panic` function below through a call to
65 // `_CxxThrowException`.
67 // This function takes two arguments. The first is a pointer to the data we're
68 // passing in, which in this case is our trait object. Pretty easy to find! The
69 // next, however, is more complicated. This is a pointer to a `_ThrowInfo`
70 // structure, and it generally is just intended to just describe the exception
73 // Currently the definition of this type [1] is a little hairy, and the main
74 // oddity (and difference from the online article) is that on 32-bit the
75 // pointers are pointers but on 64-bit the pointers are expressed as 32-bit
76 // offsets from the `__ImageBase` symbol. The `ptr_t` and `ptr!` macro in the
77 // modules below are used to express this.
79 // The maze of type definitions also closely follows what LLVM emits for this
80 // sort of operation. For example, if you compile this C++ code on MSVC and emit
83 // #include <stdint.h>
85 // struct rust_panic {
86 // rust_panic(const rust_panic&);
93 // rust_panic a = {0, 1};
97 // That's essentially what we're trying to emulate. Most of the constant values
98 // below were just copied from LLVM,
100 // In any case, these structures are all constructed in a similar manner, and
101 // it's just somewhat verbose for us.
103 // [1]: http://www.geoffchappell.com/studies/msvc/language/predefined/
105 #[cfg(target_arch = "x86")]
108 pub type ptr_t
= *mut u8;
112 core
::ptr
::null_mut()
120 #[cfg(not(target_arch = "x86"))]
123 pub type ptr_t
= u32;
126 pub static __ImageBase
: u8;
132 (($e
as usize) - (&imp
::__ImageBase
as *const _
as usize)) as u32
138 pub struct _ThrowInfo
{
139 pub attributes
: c_uint
,
140 pub pmfnUnwind
: imp
::ptr_t
,
141 pub pForwardCompat
: imp
::ptr_t
,
142 pub pCatchableTypeArray
: imp
::ptr_t
,
146 pub struct _CatchableTypeArray
{
147 pub nCatchableTypes
: c_int
,
148 pub arrayOfCatchableTypes
: [imp
::ptr_t
; 1],
152 pub struct _CatchableType
{
153 pub properties
: c_uint
,
154 pub pType
: imp
::ptr_t
,
155 pub thisDisplacement
: _PMD
,
156 pub sizeOrOffset
: c_int
,
157 pub copyFunction
: imp
::ptr_t
,
168 pub struct _TypeDescriptor
{
169 pub pVFTable
: *const u8,
174 // Note that we intentionally ignore name mangling rules here: we don't want C++
175 // to be able to catch Rust panics by simply declaring a `struct rust_panic`.
177 // When modifying, make sure that the type name string exactly matches
178 // the one used in src/librustc_codegen_llvm/intrinsic.rs.
179 const TYPE_NAME
: [u8; 11] = *b
"rust_panic\0";
181 static mut THROW_INFO
: _ThrowInfo
= _ThrowInfo
{
184 pForwardCompat
: ptr
!(0),
185 pCatchableTypeArray
: ptr
!(0),
188 static mut CATCHABLE_TYPE_ARRAY
: _CatchableTypeArray
=
189 _CatchableTypeArray { nCatchableTypes: 1, arrayOfCatchableTypes: [ptr!(0)] }
;
191 static mut CATCHABLE_TYPE
: _CatchableType
= _CatchableType
{
194 thisDisplacement
: _PMD { mdisp: 0, pdisp: -1, vdisp: 0 }
,
195 sizeOrOffset
: mem
::size_of
::<Exception
>() as c_int
,
196 copyFunction
: ptr
!(0),
200 // The leading `\x01` byte here is actually a magical signal to LLVM to
201 // *not* apply any other mangling like prefixing with a `_` character.
203 // This symbol is the vtable used by C++'s `std::type_info`. Objects of type
204 // `std::type_info`, type descriptors, have a pointer to this table. Type
205 // descriptors are referenced by the C++ EH structures defined above and
206 // that we construct below.
207 #[link_name = "\x01??_7type_info@@6B@"]
208 static TYPE_INFO_VTABLE
: *const u8;
211 // This type descriptor is only used when throwing an exception. The catch part
212 // is handled by the try intrinsic, which generates its own TypeDescriptor.
214 // This is fine since the MSVC runtime uses string comparison on the type name
215 // to match TypeDescriptors rather than pointer equality.
216 #[cfg_attr(bootstrap, lang = "eh_catch_typeinfo")]
217 static mut TYPE_DESCRIPTOR
: _TypeDescriptor
= _TypeDescriptor
{
218 pVFTable
: unsafe { &TYPE_INFO_VTABLE }
as *const _
as *const _
,
219 spare
: core
::ptr
::null_mut(),
223 // Destructor used if the C++ code decides to capture the exception and drop it
224 // without propagating it. The catch part of the try intrinsic will set the
225 // first word of the exception object to 0 so that it is skipped by the
228 // Note that x86 Windows uses the "thiscall" calling convention for C++ member
229 // functions instead of the default "C" calling convention.
231 // The exception_copy function is a bit special here: it is invoked by the MSVC
232 // runtime under a try/catch block and the panic that we generate here will be
233 // used as the result of the exception copy. This is used by the C++ runtime to
234 // support capturing exceptions with std::exception_ptr, which we can't support
235 // because Box<dyn Any> isn't clonable.
236 macro_rules
! define_cleanup
{
238 unsafe extern $abi
fn exception_cleanup(e
: *mut Exception
) {
239 if let Exception { data: Some(b) }
= e
.read() {
241 super::__rust_drop_panic();
245 unsafe extern $abi
fn exception_copy(_dest
: *mut Exception
,
246 _src
: *mut Exception
)
248 panic
!("Rust panics cannot be copied");
253 if #[cfg(target_arch = "x86")] {
254 define_cleanup
!("thiscall");
256 define_cleanup
!("C");
260 pub unsafe fn panic(data
: Box
<dyn Any
+ Send
>) -> u32 {
261 use core
::intrinsics
::atomic_store
;
263 // _CxxThrowException executes entirely on this stack frame, so there's no
264 // need to otherwise transfer `data` to the heap. We just pass a stack
265 // pointer to this function.
267 // The ManuallyDrop is needed here since we don't want Exception to be
268 // dropped when unwinding. Instead it will be dropped by exception_cleanup
269 // which is invoked by the C++ runtime.
270 let mut exception
= ManuallyDrop
::new(Exception { data: Some(data) }
);
271 let throw_ptr
= &mut exception
as *mut _
as *mut _
;
273 // This... may seems surprising, and justifiably so. On 32-bit MSVC the
274 // pointers between these structure are just that, pointers. On 64-bit MSVC,
275 // however, the pointers between structures are rather expressed as 32-bit
276 // offsets from `__ImageBase`.
278 // Consequently, on 32-bit MSVC we can declare all these pointers in the
279 // `static`s above. On 64-bit MSVC, we would have to express subtraction of
280 // pointers in statics, which Rust does not currently allow, so we can't
283 // The next best thing, then is to fill in these structures at runtime
284 // (panicking is already the "slow path" anyway). So here we reinterpret all
285 // of these pointer fields as 32-bit integers and then store the
286 // relevant value into it (atomically, as concurrent panics may be
287 // happening). Technically the runtime will probably do a nonatomic read of
288 // these fields, but in theory they never read the *wrong* value so it
289 // shouldn't be too bad...
291 // In any case, we basically need to do something like this until we can
292 // express more operations in statics (and we may never be able to).
293 atomic_store(&mut THROW_INFO
.pmfnUnwind
as *mut _
as *mut u32, ptr
!(exception_cleanup
) as u32);
295 &mut THROW_INFO
.pCatchableTypeArray
as *mut _
as *mut u32,
296 ptr
!(&CATCHABLE_TYPE_ARRAY
as *const _
) as u32,
299 &mut CATCHABLE_TYPE_ARRAY
.arrayOfCatchableTypes
[0] as *mut _
as *mut u32,
300 ptr
!(&CATCHABLE_TYPE
as *const _
) as u32,
303 &mut CATCHABLE_TYPE
.pType
as *mut _
as *mut u32,
304 ptr
!(&TYPE_DESCRIPTOR
as *const _
) as u32,
307 &mut CATCHABLE_TYPE
.copyFunction
as *mut _
as *mut u32,
308 ptr
!(exception_copy
) as u32,
313 pub fn _CxxThrowException(pExceptionObject
: *mut c_void
, pThrowInfo
: *mut u8) -> !;
316 _CxxThrowException(throw_ptr
, &mut THROW_INFO
as *mut _
as *mut _
);
319 pub unsafe fn cleanup(payload
: *mut u8) -> Box
<dyn Any
+ Send
> {
320 let exception
= &mut *(payload
as *mut Exception
);
321 exception
.data
.take().unwrap()
324 // This is required by the compiler to exist (e.g., it's a lang item), but
325 // it's never actually called by the compiler because __C_specific_handler
326 // or _except_handler3 is the personality function that is always used.
327 // Hence this is just an aborting stub.
328 #[lang = "eh_personality"]
330 fn rust_eh_personality() {
331 unsafe { core::intrinsics::abort() }