Skip to main content

jmp_scape/
lib.rs

1//! The jmp-scape crate provides access to `setjmp` and `sigsetjmp`
2//! functionality, via an interface that ensures LLVM won't miscompile things.
3//!
4//! Forked from [`cee-scape`](https://github.com/pnkfelix/cee-scape); credit for
5//! the original design and implementation belongs to the upstream authors.
6//!
7//! # Example usage
8//!
9//! The main intention is for this interface to be used with C code that expects
10//! to longjmp via jump buffers established at Rust-to-C FFI boundaries.
11//!
12//! Here is an example, where we are using `extern "C"` functions as stand-ins
13//! for the code you would normally expect to find in an external C library.
14//!
15//! ```rust
16//! mod pretend_this_comes_from_c {
17//!     use jmp_scape::JmpBuf;
18//!
19//!     // Returns sum of a and b, but longjmps through `env` if either argument
20//!     // is negative (passing 1) or if the sum overflows (passing 2).
21//!     pub extern "C" fn careful_sum(env: JmpBuf, a: i32, b: i32) -> i32 {
22//!         check_values(env, a, b);
23//!         return a + b;
24//!     }
25//!
26//!     extern "C" fn check_values(env: JmpBuf, a: i32, b: i32) {
27//!         use jmp_scape::longjmp;
28//!         if a < 0 || b < 0 { unsafe { longjmp(env, -1); } }
29//!         if (i32::MAX - a) < b { unsafe { longjmp(env, -2); } }
30//!     }
31//! }
32//!
33//! use pretend_this_comes_from_c::careful_sum as sum;
34//! use jmp_scape::call_with_setjmp;
35//!
36//! assert_eq!(call_with_setjmp(|env| { sum(env, 10, 20) + 1000 }), 1030);
37//! assert_eq!(call_with_setjmp(|env| { sum(env, -10, 20) + 1000 }), -1);
38//! assert_eq!(call_with_setjmp(|env| { sum(env, 10, -20) + 1000 }), -1);
39//! assert_eq!(call_with_setjmp(|env| { sum(env, i32::MAX, 1) + 1000 }), -2);
40//! ```
41//!
42//! # Background on `setjmp` and `longjmp`.
43//!
44//! The `setjmp` and `longjmp` functions in C are used as the basis for
45//! "non-local jumps", also known as "escape continuations". It is a way to have
46//! a chain of calls "`entry` calls `middle_1` calls `middle_2` calls
47//! `innermost`", where the bodies of `middle_1` or `middle_2` or `innermost`
48//! might at some point decide that they want to jump all the way back to
49//! `entry` without having to pass through the remaining code that they would
50//! normally have to execute when returning via each of their respective
51//! callers.
52//!
53//! In C, this is done by having `entry` first call `setjmp` to initialize a
54//! jump enviroment (which would hold, for example, the current stack pointer
55//! and, if present, the current frame pointer), and then passing a pointer to
56//! that jump environment along during each of the child subroutines of A. If at
57//! any point a child subroutine wants to jump back to the point where `setjmp`
58//! had first returned, that child subroutine invoke `longjmp`, which reestablishes
59//! the stack to the position it had when `setjmp` had originally returned.
60//!
61//! # Safety (or lack thereof)
62//!
63//! This crate cannot ensure that the usual Rust control-flow rules are upheld,
64//! which means that the act of actually doing a longjmp/siglongjmp to a
65//! non-local jump environment (aka continuation) is *unsafe*.
66//!
67//! For example, several Rust API's rely on an assumption that they will always
68//! run some specific cleanup code after a callback is done. Such cleanup is
69//! sometimes encoded as a Rust destructor, but it can also just be directly
70//! encoded as straight-line code waiting to be run.
71//!
72//! Calls to `longjmp` blatantly break these assumptions. A `longjmp` invocation
73//! does not invoke any Rust destructors, and it does not "unwind the stack".
74//! All pending cleanup code between the `longjmp` invocation and the target
75//! jump environment (i.e. the place where the relevant `setjmp` first returned)
76//! is skipped.
77//!
78//! ```rust
79//! use std::cell::Cell;
80//! // This emulates a data structure that has an ongoing invariant:
81//! // the `depth` is incremented/decremented according to entry/exit
82//! // to a given callback (see `DepthTracker::enter` below).
83//! pub struct DepthTracker { depth: Cell<usize>, }
84//!
85//! let track = DepthTracker::new();
86//! jmp_scape::call_with_setjmp(|env| {
87//!     track.enter(|| {
88//!         // This is what we expect: depth is larger in context of
89//!         // DepthTracker::enter callback
90//!         assert_eq!(track.depth(), 1);
91//!         "normal case"
92//!     });
93//!     0
94//! });
95//!
96//! // Normal case: the tracked depth has returned to zero.
97//! assert_eq!(track.depth(), 0);
98//!
99//! assert_eq!(jmp_scape::call_with_setjmp(|env| {
100//!     track.enter(|| {
101//!         // This is what we expect: depth is larger in context of
102//!         // DepthTracker::enter callback
103//!         assert_eq!(track.depth(), 1);
104//!         // DIFFERENT: Now we bypass the DepthTracker's cleanup code.
105//!         unsafe { jmp_scape::longjmp(env, 4) }
106//!         "abnormal case"
107//!     });
108//!     0
109//! }), 4);
110//!
111//! // This is the "surprise" due to the DIFFERENT line: longjmp skipped
112//! // over the decrement from returning from the callback, and so the count
113//! // is not consistent with what the data structure expects.
114//! assert_eq!(track.depth(), 1 /* not 0 */);
115//!
116//! // (These are just support routines for the `DepthTracker` above.)
117//! impl DepthTracker {
118//!     pub fn depth(&self) -> usize {
119//!         self.depth.get()
120//!     }
121//!     pub fn enter<X>(&self, callback: impl FnOnce() -> X) -> X {
122//!         self.update(|x|x+1);
123//!         let ret = callback();
124//!         self.update(|x|x-1);
125//!         ret
126//!     }
127//!     fn update(&self, effect: impl Fn(usize) -> usize) {
128//!         self.depth.set(effect(self.depth.get()));
129//!     }
130//!     pub fn new() -> Self {
131//!         DepthTracker { depth: Cell::new(0) }
132//!     }
133//! }
134//! ```
135//!
136//! In short, the `longjmp` routine is a blunt instrument. When a `longjmp`
137//! invocation skips some cleanup code, the compiler cannot know whether
138//! skipping that cleanup code was exactly what the program author intended, or
139//! if it represents a programming error.
140//!
141//! Furthermore, much cleanup code of this form is enforcing *Rust safety
142//! invariants*. This is why `longjmp` is provided here as an *unsafe* method;
143//! that is a reminder that while one can invoke `call_with_setjmp` safely, the
144//! obligation remains to audit whether any invocations of `longjmp` on the
145//! provided jump environment are breaking those safety invariants by skipping
146//! over such cleanup code.
147//!
148//! # Some static checking
149//!
150//! While not all of Rust's safety rules are statically enforced, one important
151//! one is enforced: When invoking `call_with_setjmp`, the saved jump
152//! environment is not allowed to escape the scope of the callback that is fed
153//! to `call_with_setjmp`:
154//!
155//! ```compile_fail
156//! let mut escaped = None;
157//! jmp_scape::call_with_setjmp(|env| {
158//!     // If `env` were allowed to escape...
159//!     escaped = Some(env);
160//!     0
161//! });
162//! // ... it would be bad if we could then do this with it.
163//! unsafe { jmp_scape::longjmp(escaped.unwrap(), 1); }
164//! ```
165//!
166//! We also cannot share jump environments across threads, because it is
167//! undefined behavior to `longjmp` via a jump environments that was initialized
168//! by a call to `setjmp` in a different thread.
169//!
170//! ```compile_fail
171//! jmp_scape::call_with_setjmp(move |env| {
172//!     std::thread::scope(|s| {
173//!         s.spawn(move || {
174//!             unsafe { jmp_scape::longjmp(env, 1); }
175//!         });
176//!         0
177//!     })
178//! });
179//! ```
180#![cfg_attr(not(test), no_std)]
181
182use libc::c_int;
183
184#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
185mod glibc_compat;
186#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
187mod macos_compat;
188#[cfg(target_os = "linux")]
189use glibc_compat as struct_defs;
190#[cfg(target_os = "macos")]
191use macos_compat as struct_defs;
192
193pub use crate::struct_defs::{JmpBufFields, JmpBufStruct};
194pub use crate::struct_defs::{SigJmpBufFields, SigJmpBufStruct};
195
196
197
198/// This is the type of the first argument that is fed to longjmp.
199pub type JmpBuf = *const JmpBufFields;
200
201/// This is the type of the first argument that is fed to siglongjmp.
202pub type SigJmpBuf = *const SigJmpBufFields;
203
204unsafe extern "C" {
205    /// Given a calling environment `jbuf` (which one can acquire via
206    /// `call_with_setjmp`) and a non-zero value `val`, moves the stack and
207    /// program counters to match the return position of where `jbuf` was
208    /// established via a call to `setjmp`, and then returns `val` from that
209    /// spot.
210    ///
211    /// You should only provide non-zero values for `val`. A zero-value may or
212    /// may not be replaced with a non-zero value for the return to the
213    /// non-local jump environment, depending on the underlying C library that
214    /// is linked in. (It may be silently replaced with a non-zero value, as a
215    /// non-zero value is the only way for the internal machinery to distinguish
216    /// between the first return from the initial call versus a non-local
217    /// return).
218    ///
219    /// FIXME: include safety note here, including the issues with destructors
220    pub fn longjmp(jbuf: JmpBuf, val: c_int) -> !;
221
222    /// Given a calling environment `jbuf` (which one can acquire via
223    /// `call_with_sigsetjmp`) and a non-zero value `val`, moves the stack and
224    /// program counters to match the return position of where `jbuf` was
225    /// established via a call to `setjmp`, and then returns `val` from that
226    /// spot.
227    ///
228    /// You should only provide non-zero values for `val`. A zero-value may or
229    /// may not be replaced with a non-zero value for the return to the
230    /// non-local jump environment, depending on the underlying C library that
231    /// is linked in. (It may be silently replaced with a non-zero value, as a
232    /// non-zero value is the only way for the internal machinery to distinguish
233    /// between the first return from the initial call versus a non-local
234    /// return).
235    ///
236    /// FIXME: include safety note here, including the issues with destructors
237    pub fn siglongjmp(jbuf: SigJmpBuf, val: c_int) -> !;
238}
239
240// FIXME: figure out how to access feature cfg'ing. (And then, look into linting
241// against people trying to do "the obvious things".)
242
243#[cfg(not(feature = "use_c_to_interface_with_setjmp"))]
244mod asm_based;
245#[cfg(not(feature = "use_c_to_interface_with_setjmp"))]
246pub use asm_based::{call_with_setjmp, call_with_sigsetjmp};
247
248#[cfg(feature = "use_c_to_interface_with_setjmp")]
249mod cee_based;
250#[cfg(feature = "use_c_to_interface_with_setjmp")]
251pub use cee_based::{call_with_setjmp, call_with_sigsetjmp};
252
253#[cfg(test)]
254mod tests {
255    // longjmp never returns, and its signature reflects that. But its noisy to
256    // be warned about it in the tests below, where the whole point is to ensure
257    // that everything *is* skipped in the expected manner.
258    #![allow(unreachable_code)]
259
260    use super::*;
261    use expect_test::expect;
262
263    #[test]
264    fn setjmp_basically_works() {
265        assert_eq!(call_with_setjmp(|_env| { 0 }), 0);
266        assert_eq!(call_with_setjmp(|_env| { 3 }), 3);
267        assert_eq!(
268            call_with_setjmp(|env| {
269                unsafe {
270                    longjmp(env, 4);
271                }
272                3
273            }),
274            4
275        );
276    }
277
278    #[test]
279    fn sigsetjmp_basically_works() {
280        assert_eq!(call_with_sigsetjmp(true, |_env| { 0 }), 0);
281        assert_eq!(call_with_sigsetjmp(true, |_env| { 3 }), 3);
282        assert_eq!(
283            call_with_sigsetjmp(true, |env| {
284                unsafe {
285                    siglongjmp(env, 4);
286                }
287                3
288            }),
289            4
290        );
291    }
292
293    #[test]
294    fn check_control_flow_details_1() {
295        // The basic test template: record control flow points via record, and
296        // compare them in the test output.
297        let mut record = String::new();
298        let result = call_with_setjmp(|env| {
299            record.push_str("A");
300            unsafe {
301                longjmp(env, 4);
302            }
303            record.push_str(" B");
304            0
305        });
306        assert_eq!(result, 4);
307        expect![["A"]].assert_eq(&record);
308    }
309
310    #[test]
311    fn check_control_flow_details_2() {
312        let mut record = String::new();
313        let result = call_with_setjmp(|_env1| {
314            record.push_str("A");
315            let ret = call_with_setjmp(|env2| {
316                record.push_str(" B");
317                unsafe {
318                    longjmp(env2, 4);
319                }
320                record.push_str(" C");
321                0
322            });
323            record.push_str(" D");
324            ret + 1
325        });
326        assert_eq!(result, 5);
327        expect![["A B D"]].assert_eq(&record);
328    }
329
330    #[test]
331    fn check_control_flow_details_3() {
332        let mut record = String::new();
333        let result = call_with_setjmp(|env1| {
334            record.push_str("A");
335            let ret = call_with_setjmp(|_env2| {
336                record.push_str(" B");
337                unsafe {
338                    longjmp(env1, 4);
339                }
340                record.push_str(" C");
341                0
342            });
343            record.push_str(" D");
344            ret + 1
345        });
346        assert_eq!(result, 4);
347        expect![["A B"]].assert_eq(&record);
348    }
349
350    #[cfg(feature = "test_c_integration")]
351    #[test]
352    fn c_integration() {
353        unsafe extern "C" {
354            fn subtract_but_longjmp_if_underflow(env: JmpBuf, a: u32, b: u32) -> u32;
355        }
356        assert_eq!(
357            call_with_setjmp(|env| {
358                (unsafe { subtract_but_longjmp_if_underflow(env, 10, 3) }) as c_int
359            }),
360            7
361        );
362
363        assert_eq!(
364            call_with_setjmp(|env| {
365                unsafe {
366                    subtract_but_longjmp_if_underflow(env, 3, 10);
367                    panic!("should never get here.");
368                }
369            }),
370            7
371        );
372    }
373
374    #[cfg(feature = "test_c_integration")]
375    #[test]
376    fn check_c_layout() {
377        // This type is defined in test_c_integration
378        #[repr(C)]
379        #[derive(Copy, Clone, Default, Debug)]
380        struct LayoutOfJmpBufs {
381            jb_size: usize,
382            jb_align: usize,
383            sigjb_size: usize,
384            sigjb_align: usize,
385        }
386
387        unsafe extern "C" {
388            fn get_c_jmpbuf_layout() -> LayoutOfJmpBufs;
389        }
390
391        let cinfo = unsafe { get_c_jmpbuf_layout() };
392        // Dump the info so that if the test fails the right values are easy
393        // enough to find.
394        eprintln!("Note: C jmp_buf/sigjmp_buf layout info: {cinfo:?}");
395
396        assert_eq!(cinfo.jb_size, core::mem::size_of::<JmpBufStruct>());
397        assert_eq!(cinfo.jb_align, core::mem::align_of::<JmpBufStruct>());
398        assert_eq!(cinfo.sigjb_size, core::mem::size_of::<SigJmpBufStruct>());
399        assert_eq!(cinfo.sigjb_align, core::mem::align_of::<SigJmpBufStruct>());
400    }
401}
402
403#[cfg(test)]
404mod tests_of_drop_interaction {
405    use std::sync::atomic::{AtomicUsize, Ordering};
406    use super::{call_with_setjmp, call_with_sigsetjmp};
407    struct IncrementOnDrop(&'static str, &'static AtomicUsize);
408    impl IncrementOnDrop {
409        fn new(name: &'static str, state: &'static AtomicUsize) -> Self {
410            println!("called new for {name}");
411            IncrementOnDrop(name, state)
412        }
413    }
414    impl Drop for IncrementOnDrop {
415        fn drop(&mut self) {
416            println!("called drop on {}", self.0);
417            self.1.fetch_add(1, Ordering::Relaxed);
418        }
419    }
420
421    #[test]
422    fn does_ptr_read_cause_a_double_drop_for_setjmp() {
423        static STATE: AtomicUsize = AtomicUsize::new(0);
424        let iod = IncrementOnDrop::new("iod", &STATE);
425        call_with_setjmp(move |_env| {
426            println!("at callback 1 start: {}", iod.1.load(Ordering::Relaxed));
427            let _own_it = iod;
428            0
429        });
430        println!("callback done, drop counter: {}", STATE.load(Ordering::Relaxed));
431        assert_eq!(STATE.load(Ordering::Relaxed), 1);
432        let iod = IncrementOnDrop::new("iod", &STATE);
433        call_with_setjmp(move |_env| {
434            println!("at callback 2 start: {}", iod.1.load(Ordering::Relaxed));
435            let _own_it = iod;
436            0
437        });
438        println!("callback done, drop counter: {}", STATE.load(Ordering::Relaxed));
439        assert_eq!(STATE.load(Ordering::Relaxed), 2);
440    }
441
442    #[test]
443    fn does_ptr_read_cause_a_double_drop_for_sigsetjmp() {
444        static STATE: AtomicUsize = AtomicUsize::new(0);
445        let iod = IncrementOnDrop::new("iod", &STATE);
446        call_with_sigsetjmp(false, move |_env| {
447            println!("at callback 3 start: {}", iod.1.load(Ordering::Relaxed));
448            let _own_it = iod;
449            0
450        });
451        println!("callback done, drop counter: {}", STATE.load(Ordering::Relaxed));
452        assert_eq!(STATE.load(Ordering::Relaxed), 1);
453        let iod = IncrementOnDrop::new("iod", &STATE);
454        call_with_sigsetjmp(true, move |_env| {
455            println!("at callback 4 start: {}", iod.1.load(Ordering::Relaxed));
456            let _own_it = iod;
457            0
458        });
459        println!("callback done, drop counter: {}", STATE.load(Ordering::Relaxed));
460        assert_eq!(STATE.load(Ordering::Relaxed), 2);
461    }
462
463    // FIXME: This test probably shouldn't be written this way. The intended safety property
464    // for calling longjmp is that there *are no* destructors waiting to run between the
465    // longjmp and its associated setjmp (and that we otherwise have UB).
466    #[test]
467    fn mix_drop_with_longjmp() {
468        use crate::longjmp;
469
470        static STATE: AtomicUsize = AtomicUsize::new(0);
471        // The above cases were checking that "normal" control flow,
472        // with no longjmp's involved, would not cause a double-drop.
473        // But as soon as longjmp is in the mix, we can no lonbger
474        // guarantee that the closure passed into call_with_setjmp will be dropped
475        let iod = IncrementOnDrop::new("iod", &STATE);
476        call_with_setjmp(move |env1| {
477            println!("at callback 1 start: {}", iod.1.load(Ordering::Relaxed));
478            let _own_it = iod;
479            unsafe { longjmp(env1, 4) }
480        });
481        println!("callback done, drop counter: {}", STATE.load(Ordering::Relaxed));
482        assert_eq!(STATE.load(Ordering::Relaxed), 0);
483    }
484}