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
66
67
68
69
70
71
72
73
74
//! FFI bindings for non-local goto
//!
//! ```
//! use crash_handler::jmp;
//!
//! unsafe {
//!     let mut jmp_buf = std::mem::MaybeUninit::uninit();
//!
//!     let val = jmp::sigsetjmp(jmp_buf.as_mut_ptr(), 1);
//!
//!     if val == 0 {
//!         jmp::siglongjmp(jmp_buf.as_mut_ptr(), 22);
//!     } else {
//!         assert_eq!(val, 22);
//!     }
//! }
//! ```

cfg_if::cfg_if! {
    if #[cfg(target_arch = "x86_64")] {
        #[repr(C)]
        #[doc(hidden)]
        pub struct __jmp_buf([u64; 8]);
    } else if #[cfg(target_arch = "x86")] {
        #[repr(C)]
        #[doc(hidden)]
        pub struct __jmp_buf([u32; 6]);
    } else if #[cfg(target_arch = "arm")] {
        #[repr(C)]
        #[doc(hidden)]
        pub struct __jmp_buf([u64; 32]);
    } else if #[cfg(target_arch = "aarch64")] {
        #[repr(C)]
        #[doc(hidden)]
        pub struct __jmp_buf([u64; 22]);
    }
}

/// A jump buffer.
///
/// This is essentially the register state of a point in execution at the time
/// of a [`sigsetjmp`] call that can be returned to by passing this buffer to
/// [`siglongjmp`].
#[repr(C)]
pub struct JmpBuf {
    /// CPU context
    __jmp_buf: __jmp_buf,
    /// Whether the signal mask was saved
    __fl: u32,
    /// Saved signal mask
    __ss: [u32; 32],
}

extern "C" {
    /// Set jump point for a non-local goto.
    ///
    /// The return value will be 0 if this is a direct invocation (ie the "first
    /// time" `sigsetjmp` is executed), and will be the value passed to `siglongjmp`
    /// otherwise.
    ///
    /// See [sigsetjmp](https://man7.org/linux/man-pages/man3/sigsetjmp.3p.html)
    /// for more information.
    #[cfg_attr(target_env = "gnu", link_name = "__sigsetjmp")]
    pub fn sigsetjmp(jb: *mut JmpBuf, save_mask: i32) -> i32;
    /// Non-local goto with signal handling
    ///
    /// The value passed here will be returned by `sigsetjmp` when returning
    /// to that callsite. Note that passing a value of 0 here will be changed
    /// to a 1.
    ///
    /// See [siglongjmp](https://man7.org/linux/man-pages/man3/siglongjmp.3p.html)
    /// for more information.
    pub fn siglongjmp(jb: *mut JmpBuf, val: i32) -> !;
}