]> git.lizzy.rs Git - rust.git/blob - src/test/run-make-fulldeps/foreign-exceptions/foo.rs
Rollup merge of #66044 - RalfJung:uninit-lint, r=oli-obk
[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 // For linking libstdc++ on MinGW
6 #![cfg_attr(all(windows, target_env = "gnu"), feature(static_nobundle))]
7
8 #![feature(unwind_attributes)]
9
10 use std::panic::{catch_unwind, AssertUnwindSafe};
11
12 struct DropCheck<'a>(&'a mut bool);
13 impl<'a> Drop for DropCheck<'a> {
14     fn drop(&mut self) {
15         println!("DropCheck::drop");
16         *self.0 = true;
17     }
18 }
19
20 extern "C" {
21     fn throw_cxx_exception();
22
23     #[unwind(allowed)]
24     fn cxx_catch_callback(cb: extern "C" fn(), ok: *mut bool);
25 }
26
27 #[no_mangle]
28 #[unwind(allowed)]
29 extern "C" fn rust_catch_callback(cb: extern "C" fn(), rust_ok: &mut bool) {
30     let _caught_unwind = catch_unwind(AssertUnwindSafe(|| {
31         let _drop = DropCheck(rust_ok);
32         cb();
33         unreachable!("should have unwound instead of returned");
34     }));
35     unreachable!("catch_unwind should not have caught foreign exception");
36 }
37
38 fn throw_rust_panic() {
39     #[unwind(allowed)]
40     extern "C" fn callback() {
41         println!("throwing rust panic");
42         panic!(1234i32);
43     }
44
45     let mut dropped = false;
46     let mut cxx_ok = false;
47     let caught_unwind = catch_unwind(AssertUnwindSafe(|| {
48         let _drop = DropCheck(&mut dropped);
49         unsafe {
50             cxx_catch_callback(callback, &mut cxx_ok);
51         }
52         unreachable!("should have unwound instead of returned");
53     }));
54     println!("caught rust panic");
55     assert!(dropped);
56     assert!(caught_unwind.is_err());
57     let panic_obj = caught_unwind.unwrap_err();
58     let panic_int = *panic_obj.downcast_ref::<i32>().unwrap();
59     assert_eq!(panic_int, 1234);
60     assert!(cxx_ok);
61 }
62
63 fn main() {
64     unsafe { throw_cxx_exception() };
65     throw_rust_panic();
66 }