]> git.lizzy.rs Git - rust.git/blob - src/test/run-make-fulldeps/foreign-exceptions/foo.rs
83adf000d9efe2776b55adbf680b911e406d4c09
[rust.git] / src / test / run-make-fulldeps / foreign-exceptions / foo.rs
1 // Tests that C++ exceptions can unwind through Rust code, run destructors and
2 // are ignored by catch_unwind. Also tests that Rust panics can unwind through
3 // C++ code.
4
5 #![feature(unwind_attributes)]
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 throw_cxx_exception();
19
20     #[unwind(allowed)]
21     fn cxx_catch_callback(cb: extern "C" fn(), ok: *mut bool);
22 }
23
24 #[no_mangle]
25 #[unwind(allowed)]
26 extern "C" fn rust_catch_callback(cb: extern "C" fn(), rust_ok: &mut bool) {
27     let _caught_unwind = catch_unwind(AssertUnwindSafe(|| {
28         let _drop = DropCheck(rust_ok);
29         cb();
30         unreachable!("should have unwound instead of returned");
31     }));
32     unreachable!("catch_unwind should not have caught foreign exception");
33 }
34
35 fn throw_rust_panic() {
36     #[unwind(allowed)]
37     extern "C" fn callback() {
38         println!("throwing rust panic");
39         panic!(1234i32);
40     }
41
42     let mut dropped = false;
43     let mut cxx_ok = false;
44     let caught_unwind = catch_unwind(AssertUnwindSafe(|| {
45         let _drop = DropCheck(&mut dropped);
46         unsafe {
47             cxx_catch_callback(callback, &mut cxx_ok);
48         }
49         unreachable!("should have unwound instead of returned");
50     }));
51     println!("caught rust panic");
52     assert!(dropped);
53     assert!(caught_unwind.is_err());
54     let panic_obj = caught_unwind.unwrap_err();
55     let panic_int = *panic_obj.downcast_ref::<i32>().unwrap();
56     assert_eq!(panic_int, 1234);
57     assert!(cxx_ok);
58 }
59
60 fn main() {
61     unsafe { throw_cxx_exception() };
62     throw_rust_panic();
63 }