about summary refs log tree commit diff
path: root/src/test/run-make-fulldeps/foreign-exceptions/foo.rs
blob: 9c2045c8c89f72c24dcfe78d61d095578b5ae5a8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// Tests that C++ exceptions can unwind through Rust code, run destructors and
// are ignored by catch_unwind. Also tests that Rust panics can unwind through
// C++ code.

// For linking libstdc++ on MinGW
#![cfg_attr(all(windows, target_env = "gnu"), feature(static_nobundle))]
#![feature(unwind_attributes)]

use std::panic::{catch_unwind, AssertUnwindSafe};

struct DropCheck<'a>(&'a mut bool);
impl<'a> Drop for DropCheck<'a> {
    fn drop(&mut self) {
        println!("DropCheck::drop");
        *self.0 = true;
    }
}

extern "C" {
    fn throw_cxx_exception();

    #[unwind(allowed)]
    fn cxx_catch_callback(cb: extern "C" fn(), ok: *mut bool);
}

#[no_mangle]
#[unwind(allowed)]
extern "C" fn rust_catch_callback(cb: extern "C" fn(), rust_ok: &mut bool) {
    let _caught_unwind = catch_unwind(AssertUnwindSafe(|| {
        let _drop = DropCheck(rust_ok);
        cb();
        unreachable!("should have unwound instead of returned");
    }));
    unreachable!("catch_unwind should not have caught foreign exception");
}

fn throw_rust_panic() {
    #[unwind(allowed)]
    extern "C" fn callback() {
        println!("throwing rust panic");
        panic!(1234i32);
    }

    let mut dropped = false;
    let mut cxx_ok = false;
    let caught_unwind = catch_unwind(AssertUnwindSafe(|| {
        let _drop = DropCheck(&mut dropped);
        unsafe {
            cxx_catch_callback(callback, &mut cxx_ok);
        }
        unreachable!("should have unwound instead of returned");
    }));
    println!("caught rust panic");
    assert!(dropped);
    assert!(caught_unwind.is_err());
    let panic_obj = caught_unwind.unwrap_err();
    let panic_int = *panic_obj.downcast_ref::<i32>().unwrap();
    assert_eq!(panic_int, 1234);
    assert!(cxx_ok);
}

fn main() {
    unsafe { throw_cxx_exception() };
    throw_rust_panic();
}