| 1 | // Adapted from: |
| 2 | // |
| 3 | // https://rust-lang.zulipchat.com/#narrow/stream/210922-project-ffi-unwind/topic/cost.20of.20supporting.20longjmp.20without.20annotations/near/301840755 |
| 4 | // |
| 5 | // ```rust |
| 6 | // unsafe fn setjmp<F: FnOnce() -> c_int>(env: *mut jmp_buf, f: F) -> c_int { |
| 7 | // let mut f = core::mem::MaybeUninit::new(f); |
| 8 | // extern "C" fn call_f<F: FnOnce() -> c_int>(f: *mut F) -> c_int { |
| 9 | // (unsafe { f.read() })() |
| 10 | // } |
| 11 | // let ret: c_int; |
| 12 | // std::arch::asm!( |
| 13 | // "call setjmp", |
| 14 | // "test eax, eax", |
| 15 | // "jne 1f", |
| 16 | // "mov rdi, r12", |
| 17 | // "call {}", |
| 18 | // "1:", |
| 19 | // sym call_f::<F>, |
| 20 | // in("rdi") env, |
| 21 | // in("r12") f.as_mut_ptr(), |
| 22 | // lateout("rax") ret, |
| 23 | // clobber_abi("C"), |
| 24 | // ); |
| 25 | // ret |
| 26 | // } |
| 27 | // ``` |
| 28 | |
| 29 | // Some notes about inline asm: |
| 30 | // |
| 31 | // * For System-V, first three arguments for x86_64 are [rdi,rsi,rdx]. (This |
| 32 | // code never passes more than three arguments.) |
| 33 | // |
| 34 | // For Microsft x86, Wikipedia says the first three arguments are [rcx,rdx, r8]. |
| 35 | // |
| 36 | // * call instructions (like to _setjmp) can trample caller-save registers, but |
| 37 | // not callee save ones. We can direct the compiler to assign the bits of |
| 38 | // state that need to live across calls to *callee-save* registers. |
| 39 | // |
| 40 | // * The set of callee-save registers depends on the ABI. |
| 41 | // |
| 42 | // System-V callee-save regs are [RBX, RSP, RBP, R12, 13, R14, R15] |
| 43 | // |
| 44 | // Microsoft x64 callee-save regs are [RBX, RBP, RDI, RSI, RSP, R12, R13, R14, R15]. |
| 45 | // |
| 46 | // (as a separate gotcha, one must also allocate shadow space on the stack |
| 47 | // immediately before any calls in that convention) |
| 48 | // |
| 49 | // So, there's at the very least a number of things to double-check here. |
| 50 | // |
| 51 | // * If we were writing *all* the machine code, then we would have to include |
| 52 | // code here to save and restore state regardless of that choice between |
| 53 | // caller- or callee-save. But we are not writing all the machine code; LLVM |
| 54 | // is going to handle the stack shuffling for us. All we need to do is assign |
| 55 | // registers according to the roles we want them to play. |
| 56 | |
| 57 | use crate::{JmpBuf, JmpBufFields, JmpBufStruct}; |
| 58 | use crate::{SigJmpBuf, SigJmpBufFields, SigJmpBufStruct}; |
| 59 | use libc::c_int; |
| 60 | use std::mem::MaybeUninit; |
| 61 | |
| 62 | #[cfg(target_arch = "x86_64")] |
| 63 | macro_rules! maybesig_setjmp_asm { |
| 64 | ($setjmp:ident, $jbuf_ptr:ident, $ifsig_savemask:ident, $closure_env_ptr:ident, $c2r:ident, $ret:ident) => { |
| 65 | std::arch::asm!( |
| 66 | // savemask is already in position rsi.. |
| 67 | "mov rdi, r12", // move jbuf_ptr into arg position for sigsetjmp call |
| 68 | "call {tmp}", // fills in jbuf; future longjmp calls go here. |
| 69 | "test eax, eax", // inspect return value of setjmp |
| 70 | "jne 1f", // if non-zero, skip the callback invocation |
| 71 | "mov rdi, r12", // otherwise, move jbuf ptr into position... |
| 72 | "mov rsi, r13", // ... and move callback ptrs into position... |
| 73 | "call r14" , // ... and invoke the callback |
| 74 | "1:", // at this point, rax carries the return value (from either outcome) |
| 75 | // we let compiler pick this register since we don't need to preseve |
| 76 | // it across the first call. |
| 77 | tmp = in(reg) $setjmp, |
| 78 | in("rsi") $ifsig_savemask, |
| 79 | // we use [r12,r13,r14] explicitly as they are always callee-save |
| 80 | // and thus will be preserved across the call to setjmp. |
| 81 | in("r12") $jbuf_ptr, |
| 82 | in("r13") $closure_env_ptr, |
| 83 | in("r14") $c2r, |
| 84 | // we use rax explicitly since we just pass along return register |
| 85 | // set by the return path (be it normal return or via longjmp). |
| 86 | out("rax") $ret, |
| 87 | clobber_abi("sysv64"), // clobber abi reflects call effects, including {eax,rdi,rsi}... |
| 88 | out("rdi") _, // ... but, we write rdi before reading sigsetjmp; avoid collision. |
| 89 | ); |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | #[cfg(target_arch = "aarch64")] |
| 94 | macro_rules! maybesig_setjmp_asm { |
| 95 | ($sigsetjmp:ident, $jbuf_ptr:ident, $ifsig_savemask:ident, $closure_env_ptr:ident, $c2r:ident, $ret:ident) => { |
| 96 | std::arch::asm!( |
| 97 | // savemask, if needed, is already in x1 |
| 98 | "mov x0, x21", // move saved jbuf_ptr to sigsetjmp param position. (savemask is already in position) |
| 99 | "blr {tmp}", // fills in jbuf; future longjmp calls go here. |
| 100 | "cbnz w0, 1f", // if return value non-zero, skip the callback invocation |
| 101 | // (and if return value non-zero, we cannot assume register state has been restored!) |
| 102 | "mov x0, x21", // move saved jmp buf into callback's arg position |
| 103 | "mov x1, x20", // move saved closure env into callback's arg position |
| 104 | "blr x22", // invoke the callback |
| 105 | "1:", // at this point, x0 carries the return value (from either outcome) |
| 106 | // we let compiler pick this register since we don't need to preseve |
| 107 | // it across the first call. |
| 108 | tmp = in(reg) $sigsetjmp, |
| 109 | in("x1") $ifsig_savemask, // savemask arg position for sigsetjmp |
| 110 | out("x0") $ret, // the output will be stored here. |
| 111 | // [x20,x21,x22] are all callee-save registers for the normal sigsetjmp return. |
| 112 | // we will have them to reference. |
| 113 | in("x20") $closure_env_ptr, |
| 114 | in("x21") $jbuf_ptr, |
| 115 | in("x22") $c2r, |
| 116 | clobber_abi("C"), // clobber abi reflects call effects, including {x0,x1,x2,x3}... |
| 117 | ); |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | /// Covers the usual use case for setjmp: it invokes the callback, and the code |
| 122 | /// of the callback can use longjmp to exit early from the call_with_setjmp. |
| 123 | #[inline(never)] // see https://github.com/pnkfelix/cee-scape/issues/14 |
| 124 | pub fn call_with_setjmp<F>(mut callback: F) -> c_int |
| 125 | where |
| 126 | F: for<'a> FnOnce(&'a JmpBufFields) -> c_int, |
| 127 | { |
| 128 | extern "C" fn call_from_c_to_rust<F>(jbuf: JmpBuf, closure_env_ptr: *mut F) -> c_int |
| 129 | where |
| 130 | F: for<'a> FnOnce(&'a JmpBufFields) -> c_int, |
| 131 | { |
| 132 | // Dereference `closure_env_ptr` with .read() to acquire ownership of |
| 133 | // the FnOnce object, then call it. (See also the forget note below.) |
| 134 | // |
| 135 | // Note that `closure_env_ptr` is not a raw function pointer, it's a |
| 136 | // pointer to a FnOnce; the code we call comes from the generic `F`. |
| 137 | unsafe { (closure_env_ptr.read())(&*jbuf) } |
| 138 | } |
| 139 | unsafe { |
| 140 | let mut jbuf = MaybeUninit::<JmpBufStruct>::zeroed().assume_init(); |
| 141 | let ret: c_int; |
| 142 | let jbuf_ptr = std::ptr::addr_of_mut!(jbuf); |
| 143 | let closure_env_ptr = std::ptr::addr_of_mut!(callback); |
| 144 | |
| 145 | // The callback is now effectively owned by `closure_env_ptr` (i.e., the |
| 146 | // `closure_env_ptr.read()` call in `call_from_c_to_rust` will take a |
| 147 | // direct bitwise copy of its state, and pass that ownership into the |
| 148 | // FnOnce::call_once invocation.) |
| 149 | // |
| 150 | // Therefore, we need to forget about our own ownership of the callback now. |
| 151 | std::mem::forget(callback); |
| 152 | |
| 153 | // Note: we never call _setjmp from Rust code, just from the assembly |
| 154 | // block below. |
| 155 | extern "C" { |
| 156 | #[cfg_attr(target_os = "macos", link_name = "_setjmp")] |
| 157 | #[cfg_attr(target_os = "linux", link_name = "_setjmp")] |
| 158 | fn find_your_targets_setjmp(env: JmpBuf) -> c_int; |
| 159 | } |
| 160 | let setjmp = find_your_targets_setjmp; |
| 161 | let c2r = call_from_c_to_rust::<F>; |
| 162 | let unused_savemask: c_int = 0; // why can't we do `MaybeUninit::uninit().assume_init()` (this is unused). |
| 163 | |
| 164 | maybesig_setjmp_asm!(setjmp, jbuf_ptr, unused_savemask, closure_env_ptr, c2r, ret); |
| 165 | |
| 166 | ret |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | /// Covers the usual use case for sigsetjmp: it invokes the callback, and the code |
| 171 | /// of the callback can use siglongjmp to exit early from the call_with_sigsetjmp. |
| 172 | #[inline(never)] // see https://github.com/pnkfelix/cee-scape/issues/14 |
| 173 | pub fn call_with_sigsetjmp<F>(savemask: bool, mut callback: F) -> c_int |
| 174 | where |
| 175 | F: for<'a> FnOnce(&'a SigJmpBufFields) -> c_int, |
| 176 | { |
| 177 | extern "C" fn call_from_c_to_rust<F>(jbuf: SigJmpBuf, closure_env_ptr: *mut F) -> c_int |
| 178 | where |
| 179 | F: for<'a> FnOnce(&'a SigJmpBufFields) -> c_int, |
| 180 | { |
| 181 | // Dereference `closure_env_ptr` with .read() to acquire ownership of |
| 182 | // the FnOnce object, then call it. (See also the forget note below.) |
| 183 | // |
| 184 | // Note that `closure_env_ptr` is not a raw function pointer, it's a |
| 185 | // pointer to a FnOnce; the code we call comes from the generic `F`. |
| 186 | unsafe { (closure_env_ptr.read())(&*jbuf) } |
| 187 | } |
| 188 | |
| 189 | let savemask: c_int = if savemask { 1 } else { 0 }; |
| 190 | |
| 191 | unsafe { |
| 192 | let mut jbuf = MaybeUninit::<SigJmpBufStruct>::zeroed().assume_init(); |
| 193 | let ret: c_int; |
| 194 | let jbuf_ptr = std::ptr::addr_of_mut!(jbuf); |
| 195 | let closure_env_ptr = std::ptr::addr_of_mut!(callback); |
| 196 | |
| 197 | // The callback is now effectively owned by `closure_env_ptr` (i.e., the |
| 198 | // `closure_env_ptr.read()` call in `call_from_c_to_rust` will take a |
| 199 | // direct bitwise copy of its state, and pass that ownership into the |
| 200 | // FnOnce::call_once invocation.) |
| 201 | // |
| 202 | // Therefore, we need to forget about our own ownership of the callback now. |
| 203 | std::mem::forget(callback); |
| 204 | |
| 205 | // Note: we never call _setjmp from Rust code, just from the assembly |
| 206 | // block below. |
| 207 | extern "C" { |
| 208 | #[cfg_attr(target_os = "macos", link_name = "sigsetjmp")] |
| 209 | #[cfg_attr(target_os = "linux", link_name = "__sigsetjmp")] |
| 210 | fn find_your_targets_sigsetjmp(env: SigJmpBuf, savemask: c_int) -> c_int; |
| 211 | } |
| 212 | let sigsetjmp = find_your_targets_sigsetjmp; |
| 213 | let c2r = call_from_c_to_rust::<F>; |
| 214 | |
| 215 | maybesig_setjmp_asm!(sigsetjmp, jbuf_ptr, savemask, closure_env_ptr, c2r, ret); |
| 216 | |
| 217 | ret |
| 218 | } |
| 219 | } |