]> git.lizzy.rs Git - rust.git/blob - tests/run-make-fulldeps/foreign-exceptions/foo.rs
Rollup merge of #106618 - jmillikin:os-net-rustdoc-wasm32, r=JohnTitor
[rust.git] / tests / run-make-fulldeps / foreign-exceptions / foo.rs
1 // Tests that C++ exceptions can unwind through Rust code run destructors and
2 // are caught by catch_unwind. Also tests that Rust panics can unwind through
3 // C++ code.
4
5 #![feature(c_unwind)]
6
7 use std::panic::{catch_unwind, AssertUnwindSafe};
8
9 struct DropCheck<'a>(&'a mut bool);
10 impl<'a> Drop for DropCheck<'a> {
11     fn drop(&mut self) {
12         println!("DropCheck::drop");
13         *self.0 = true;
14     }
15 }
16
17 extern "C" {
18     fn test_cxx_exception();
19 }
20
21 extern "C-unwind" {
22     fn cxx_catch_callback(cb: extern "C-unwind" fn(), ok: *mut bool);
23 }
24
25 #[no_mangle]
26 extern "C-unwind" fn rust_catch_callback(cb: extern "C-unwind" fn(), rust_ok: &mut bool) {
27     let _drop = DropCheck(rust_ok);
28     cb();
29     unreachable!("should have unwound instead of returned");
30 }
31
32 fn test_rust_panic() {
33     extern "C-unwind" fn callback() {
34         println!("throwing rust panic");
35         panic!(1234i32);
36     }
37
38     let mut dropped = false;
39     let mut cxx_ok = false;
40     let caught_unwind = catch_unwind(AssertUnwindSafe(|| {
41         let _drop = DropCheck(&mut dropped);
42         unsafe {
43             cxx_catch_callback(callback, &mut cxx_ok);
44         }
45         unreachable!("should have unwound instead of returned");
46     }));
47     println!("caught rust panic");
48     assert!(dropped);
49     assert!(caught_unwind.is_err());
50     let panic_obj = caught_unwind.unwrap_err();
51     let panic_int = *panic_obj.downcast_ref::<i32>().unwrap();
52     assert_eq!(panic_int, 1234);
53     assert!(cxx_ok);
54 }
55
56 fn main() {
57     unsafe { test_cxx_exception() };
58     test_rust_panic();
59 }