near_vm_vm/trap/
traphandlers.rs

1// This file contains code from external sources.
2// Attributions: https://github.com/wasmerio/wasmer/blob/2.3.0/ATTRIBUTIONS.md
3
4//! WebAssembly trap handling, which is built on top of the lower-level
5//! signalhandling mechanisms.
6
7use super::trapcode::TrapCode;
8use crate::vmcontext::{VMFunctionBody, VMFunctionEnvironment, VMTrampoline};
9use backtrace::Backtrace;
10use std::any::Any;
11use std::cell::{Cell, UnsafeCell};
12use std::error::Error;
13use std::mem::{self, MaybeUninit};
14use std::ptr;
15pub use tls::TlsRestore;
16
17extern "C" {
18    fn near_vm_register_setjmp(
19        jmp_buf: *mut *const u8,
20        callback: extern "C" fn(*mut u8),
21        payload: *mut u8,
22    ) -> i32;
23    fn near_vm_unwind(jmp_buf: *const u8) -> !;
24}
25
26/// Raises a user-defined trap immediately.
27///
28/// This function performs as-if a wasm trap was just executed, only the trap
29/// has a dynamic payload associated with it which is user-provided. This trap
30/// payload is then returned from `catch_traps` below.
31///
32/// # Safety
33///
34/// Only safe to call when wasm code is on the stack, aka `catch_traps` must
35/// have been previous called and not yet returned.
36/// Additionally no Rust destructors may be on the stack.
37/// They will be skipped and not executed.
38pub unsafe fn raise_user_trap(data: Box<dyn Error + Send + Sync>) -> ! {
39    tls::with(|info| info.unwrap().unwind_with(UnwindReason::UserTrap(data)))
40}
41
42/// Raises a trap from inside library code immediately.
43///
44/// This function performs as-if a wasm trap was just executed. This trap
45/// payload is then returned from `catch_traps` below.
46///
47/// # Safety
48///
49/// Only safe to call when wasm code is on the stack, aka `catch_traps` must
50/// have been previous called and not yet returned.
51/// Additionally no Rust destructors may be on the stack.
52/// They will be skipped and not executed.
53pub unsafe fn raise_lib_trap(trap: Trap) -> ! {
54    tls::with(|info| info.unwrap().unwind_with(UnwindReason::LibTrap(trap)))
55}
56
57/// Carries a Rust panic across wasm code and resumes the panic on the other
58/// side.
59///
60/// # Safety
61///
62/// Only safe to call when wasm code is on the stack, aka `catch_traps` must
63/// have been previously called and not returned. Additionally no Rust destructors may be on the
64/// stack. They will be skipped and not executed.
65pub unsafe fn resume_panic(payload: Box<dyn Any + Send>) -> ! {
66    tls::with(|info| info.unwrap().unwind_with(UnwindReason::Panic(payload)))
67}
68
69/// Stores trace message with backtrace.
70#[derive(Debug)]
71pub enum Trap {
72    /// A user-raised trap through `raise_user_trap`.
73    User(Box<dyn Error + Send + Sync>),
74
75    /// A trap raised from the Wasm generated code
76    ///
77    /// Note: this trap is deterministic (assuming a deterministic host implementation)
78    Wasm {
79        /// The program counter in generated code where this trap happened.
80        pc: usize,
81        /// Native stack backtrace at the time the trap occurred
82        backtrace: Backtrace,
83        /// Optional trapcode associated to the signal that caused the trap
84        signal_trap: Option<TrapCode>,
85    },
86
87    /// A trap raised from a wasm libcall
88    ///
89    /// Note: this trap is deterministic (assuming a deterministic host implementation)
90    Lib {
91        /// Code of the trap.
92        trap_code: TrapCode,
93        /// Native stack backtrace at the time the trap occurred
94        backtrace: Backtrace,
95    },
96
97    /// A trap indicating that the runtime was unable to allocate sufficient memory.
98    ///
99    /// Note: this trap is nondeterministic, since it depends on the host system.
100    OOM {
101        /// Native stack backtrace at the time the OOM occurred
102        backtrace: Backtrace,
103    },
104}
105
106impl Trap {
107    /// Construct a new Wasm trap with the given source location and backtrace.
108    ///
109    /// Internally saves a backtrace when constructed.
110    pub fn wasm(pc: usize, backtrace: Backtrace, signal_trap: Option<TrapCode>) -> Self {
111        Self::Wasm { pc, backtrace, signal_trap }
112    }
113
114    /// Construct a new Wasm trap with the given trap code.
115    ///
116    /// Internally saves a backtrace when constructed.
117    pub fn lib(trap_code: TrapCode) -> Self {
118        let backtrace = Backtrace::new_unresolved();
119        Self::Lib { trap_code, backtrace }
120    }
121
122    /// Construct a new OOM trap with the given source location and trap code.
123    ///
124    /// Internally saves a backtrace when constructed.
125    pub fn oom() -> Self {
126        let backtrace = Backtrace::new_unresolved();
127        Self::OOM { backtrace }
128    }
129}
130
131/// Call the VM function pointed to by `callee`.
132///
133/// * `callee_env` - the function environment
134/// * `trampoline` - the jit-generated trampoline whose ABI takes 3 values, the
135///    callee funcenv, the `callee` argument below, and then the `values_vec` argument.
136/// * `callee` - the 2nd argument to the `trampoline` function
137/// * `values_vec` - points to a buffer which holds the incoming arguments, and to
138///   which the outgoing return values will be written.
139///
140/// Prefer invoking this via `Instance::invoke_trampoline`.
141///
142/// # Safety
143///
144/// Wildly unsafe because it calls raw function pointers and reads/writes raw
145/// function pointers.
146pub unsafe fn near_vm_call_trampoline(
147    callee_env: VMFunctionEnvironment,
148    trampoline: VMTrampoline,
149    callee: *const VMFunctionBody,
150    values_vec: *mut u8,
151) -> Result<(), Trap> {
152    catch_traps(|| {
153        mem::transmute::<
154            VMTrampoline,
155            extern "C" fn(VMFunctionEnvironment, *const VMFunctionBody, *mut u8),
156        >(trampoline)(callee_env, callee, values_vec);
157    })
158}
159
160/// Catches any wasm traps that happen within the execution of `closure`,
161/// returning them as a `Result`.
162///
163/// # Safety
164///
165/// Soundness must not depend on `closure` destructors being run.
166pub unsafe fn catch_traps<F>(mut closure: F) -> Result<(), Trap>
167where
168    F: FnMut(),
169{
170    return CallThreadState::new().with(|cx| {
171        near_vm_register_setjmp(
172            cx.jmp_buf.as_ptr(),
173            call_closure::<F>,
174            &mut closure as *mut F as *mut u8,
175        )
176    });
177
178    extern "C" fn call_closure<F>(payload: *mut u8)
179    where
180        F: FnMut(),
181    {
182        unsafe { (*(payload as *mut F))() }
183    }
184}
185
186/// Catches any wasm traps that happen within the execution of `closure`,
187/// returning them as a `Result`, with the closure contents.
188///
189/// The main difference from this method and `catch_traps`, is that is able
190/// to return the results from the closure.
191///
192/// # Safety
193///
194/// Check [`catch_traps`].
195pub unsafe fn catch_traps_with_result<F, R>(mut closure: F) -> Result<R, Trap>
196where
197    F: FnMut() -> R,
198{
199    let mut global_results = MaybeUninit::<R>::uninit();
200    catch_traps(|| {
201        global_results.as_mut_ptr().write(closure());
202    })?;
203    Ok(global_results.assume_init())
204}
205
206/// Temporary state stored on the stack which is registered in the `tls` module
207/// below for calls into wasm.
208pub struct CallThreadState {
209    unwind: UnsafeCell<MaybeUninit<UnwindReason>>,
210    jmp_buf: Cell<*const u8>,
211    prev: Cell<tls::Ptr>,
212}
213
214enum UnwindReason {
215    /// A panic caused by the host
216    Panic(Box<dyn Any + Send>),
217    /// A custom error triggered by the user
218    UserTrap(Box<dyn Error + Send + Sync>),
219    /// A Trap triggered by a wasm libcall
220    LibTrap(Trap),
221    /// A trap caused by the Wasm generated code
222    WasmTrap { backtrace: Backtrace, pc: usize, signal_trap: Option<TrapCode> },
223}
224
225impl<'a> CallThreadState {
226    #[inline]
227    fn new() -> Self {
228        Self {
229            unwind: UnsafeCell::new(MaybeUninit::uninit()),
230            jmp_buf: Cell::new(ptr::null()),
231            prev: Cell::new(ptr::null()),
232        }
233    }
234
235    fn with(self, closure: impl FnOnce(&Self) -> i32) -> Result<(), Trap> {
236        let ret = tls::set(&self, || closure(&self))?;
237        if ret != 0 {
238            return Ok(());
239        }
240        // We will only reach this path if ret == 0. And that will
241        // only happen if a trap did happen. As such, it's safe to
242        // assume that the `unwind` field is already initialized
243        // at this moment.
244        match unsafe { (*self.unwind.get()).as_ptr().read() } {
245            UnwindReason::UserTrap(data) => Err(Trap::User(data)),
246            UnwindReason::LibTrap(trap) => Err(trap),
247            UnwindReason::WasmTrap { backtrace, pc, signal_trap } => {
248                Err(Trap::wasm(pc, backtrace, signal_trap))
249            }
250            UnwindReason::Panic(panic) => std::panic::resume_unwind(panic),
251        }
252    }
253
254    fn unwind_with(&self, reason: UnwindReason) -> ! {
255        unsafe {
256            (*self.unwind.get()).as_mut_ptr().write(reason);
257            near_vm_unwind(self.jmp_buf.get());
258        }
259    }
260}
261
262// A private inner module for managing the TLS state that we require across
263// calls in wasm. The WebAssembly code is called from C++ and then a trap may
264// happen which requires us to read some contextual state to figure out what to
265// do with the trap. This `tls` module is used to persist that information from
266// the caller to the trap site.
267mod tls {
268    use super::CallThreadState;
269    use crate::Trap;
270    use std::mem;
271    use std::ptr;
272
273    pub use raw::Ptr;
274
275    // An even *more* inner module for dealing with TLS. This actually has the
276    // thread local variable and has functions to access the variable.
277    //
278    // Note that this is specially done to fully encapsulate that the accessors
279    // for tls must not be inlined. Wasmer's async support will employ stack
280    // switching which can resume execution on different OS threads. This means
281    // that borrows of our TLS pointer must never live across accesses because
282    // otherwise the access may be split across two threads and cause unsafety.
283    //
284    // This also means that extra care is taken by the runtime to save/restore
285    // these TLS values when the runtime may have crossed threads.
286    mod raw {
287        use super::CallThreadState;
288        use crate::Trap;
289        use std::cell::Cell;
290        use std::ptr;
291
292        pub type Ptr = *const CallThreadState;
293
294        // The first entry here is the `Ptr` which is what's used as part of the
295        // public interface of this module. The second entry is a boolean which
296        // allows the runtime to perform per-thread initialization if necessary
297        // for handling traps (e.g. setting up ports on macOS and sigaltstack on
298        // Unix).
299        thread_local!(static PTR: Cell<Ptr> = const { Cell::new(ptr::null()) });
300
301        #[inline(never)] // see module docs for why this is here
302        pub fn replace(val: Ptr) -> Result<Ptr, Trap> {
303            PTR.with(|p| {
304                // When a new value is configured that means that we may be
305                // entering WebAssembly so check to see if this thread has
306                // performed per-thread initialization for traps.
307                let prev = p.get();
308                p.set(val);
309                Ok(prev)
310            })
311        }
312
313        #[inline(never)] // see module docs for why this is here
314        pub fn get() -> Ptr {
315            PTR.with(|p| p.get())
316        }
317    }
318
319    /// Opaque state used to help control TLS state across stack switches for
320    /// async support.
321    pub struct TlsRestore(raw::Ptr);
322
323    impl TlsRestore {
324        /// Takes the TLS state that is currently configured and returns a
325        /// token that is used to replace it later.
326        ///
327        /// # Safety
328        ///
329        /// This is not a safe operation since it's intended to only be used
330        /// with stack switching found with fibers and async near_vm.
331        pub unsafe fn take() -> Result<Self, Trap> {
332            // Our tls pointer must be set at this time, and it must not be
333            // null. We need to restore the previous pointer since we're
334            // removing ourselves from the call-stack, and in the process we
335            // null out our own previous field for safety in case it's
336            // accidentally used later.
337            let raw = raw::get();
338            assert!(!raw.is_null());
339            let prev = (*raw).prev.replace(ptr::null());
340            raw::replace(prev)?;
341            Ok(Self(raw))
342        }
343
344        /// Restores a previous tls state back into this thread's TLS.
345        ///
346        /// # Safety
347        ///
348        /// This is unsafe because it's intended to only be used within the
349        /// context of stack switching within near_vm.
350        pub unsafe fn replace(self) -> Result<(), super::Trap> {
351            // We need to configure our previous TLS pointer to whatever is in
352            // TLS at this time, and then we set the current state to ourselves.
353            let prev = raw::get();
354            assert!((*self.0).prev.get().is_null());
355            (*self.0).prev.set(prev);
356            raw::replace(self.0)?;
357            Ok(())
358        }
359    }
360
361    /// Configures thread local state such that for the duration of the
362    /// execution of `closure` any call to `with` will yield `ptr`, unless this
363    /// is recursively called again.
364    pub fn set<R>(state: &CallThreadState, closure: impl FnOnce() -> R) -> Result<R, Trap> {
365        struct Reset<'a>(&'a CallThreadState);
366
367        impl Drop for Reset<'_> {
368            #[inline]
369            fn drop(&mut self) {
370                raw::replace(self.0.prev.replace(ptr::null()))
371                    .expect("tls should be previously initialized");
372            }
373        }
374
375        // Note that this extension of the lifetime to `'static` should be
376        // safe because we only ever access it below with an anonymous
377        // lifetime, meaning `'static` never leaks out of this module.
378        let ptr = unsafe { mem::transmute::<*const CallThreadState, _>(state) };
379        let prev = raw::replace(ptr)?;
380        state.prev.set(prev);
381        let _reset = Reset(state);
382        Ok(closure())
383    }
384
385    /// Returns the last pointer configured with `set` above. Panics if `set`
386    /// has not been previously called and not returned.
387    pub fn with<R>(closure: impl FnOnce(Option<&CallThreadState>) -> R) -> R {
388        let p = raw::get();
389        unsafe { closure(if p.is_null() { None } else { Some(&*p) }) }
390    }
391}
392
393extern "C" fn signal_less_trap_handler(pc: *const u8, trap: TrapCode) {
394    let jmp_buf = tls::with(|info| {
395        let backtrace = Backtrace::new_unresolved();
396        let info = info.unwrap();
397        unsafe {
398            (*info.unwind.get()).as_mut_ptr().write(UnwindReason::WasmTrap {
399                backtrace,
400                signal_trap: Some(trap),
401                pc: pc as usize,
402            });
403            info.jmp_buf.get()
404        }
405    });
406    unsafe {
407        near_vm_unwind(jmp_buf);
408    }
409}
410
411/// Returns pointer to the trap handler used in VMContext.
412pub fn get_trap_handler() -> *const u8 {
413    signal_less_trap_handler as *const u8
414}