unc_vm_vm/trap/traphandlers.rs
1// This file contains code from external sources.
2// Attributions: https://github.com/wasmerio/wasmer/blob/master/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 unc_vm_register_setjmp(
19 jmp_buf: *mut *const u8,
20 callback: extern "C" fn(*mut u8),
21 payload: *mut u8,
22 ) -> i32;
23 fn unc_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 unc_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::<_, extern "C" fn(VMFunctionEnvironment, *const VMFunctionBody, *mut u8)>(
154 trampoline,
155 )(callee_env, callee, values_vec);
156 })
157}
158
159/// Catches any wasm traps that happen within the execution of `closure`,
160/// returning them as a `Result`.
161///
162/// # Safety
163///
164/// Soundness must not depend on `closure` destructors being run.
165pub unsafe fn catch_traps<F>(mut closure: F) -> Result<(), Trap>
166where
167 F: FnMut(),
168{
169 return CallThreadState::new().with(|cx| {
170 unc_vm_register_setjmp(
171 cx.jmp_buf.as_ptr(),
172 call_closure::<F>,
173 &mut closure as *mut F as *mut u8,
174 )
175 });
176
177 extern "C" fn call_closure<F>(payload: *mut u8)
178 where
179 F: FnMut(),
180 {
181 unsafe { (*(payload as *mut F))() }
182 }
183}
184
185/// Catches any wasm traps that happen within the execution of `closure`,
186/// returning them as a `Result`, with the closure contents.
187///
188/// The main difference from this method and `catch_traps`, is that is able
189/// to return the results from the closure.
190///
191/// # Safety
192///
193/// Check [`catch_traps`].
194pub unsafe fn catch_traps_with_result<F, R>(mut closure: F) -> Result<R, Trap>
195where
196 F: FnMut() -> R,
197{
198 let mut global_results = MaybeUninit::<R>::uninit();
199 catch_traps(|| {
200 global_results.as_mut_ptr().write(closure());
201 })?;
202 Ok(global_results.assume_init())
203}
204
205/// Temporary state stored on the stack which is registered in the `tls` module
206/// below for calls into wasm.
207pub struct CallThreadState {
208 unwind: UnsafeCell<MaybeUninit<UnwindReason>>,
209 jmp_buf: Cell<*const u8>,
210 prev: Cell<tls::Ptr>,
211}
212
213enum UnwindReason {
214 /// A panic caused by the host
215 Panic(Box<dyn Any + Send>),
216 /// A custom error triggered by the user
217 UserTrap(Box<dyn Error + Send + Sync>),
218 /// A Trap triggered by a wasm libcall
219 LibTrap(Trap),
220 /// A trap caused by the Wasm generated code
221 WasmTrap { backtrace: Backtrace, pc: usize, signal_trap: Option<TrapCode> },
222}
223
224impl<'a> CallThreadState {
225 #[inline]
226 fn new() -> Self {
227 Self {
228 unwind: UnsafeCell::new(MaybeUninit::uninit()),
229 jmp_buf: Cell::new(ptr::null()),
230 prev: Cell::new(ptr::null()),
231 }
232 }
233
234 fn with(self, closure: impl FnOnce(&Self) -> i32) -> Result<(), Trap> {
235 let ret = tls::set(&self, || closure(&self))?;
236 if ret != 0 {
237 return Ok(());
238 }
239 // We will only reach this path if ret == 0. And that will
240 // only happen if a trap did happen. As such, it's safe to
241 // assume that the `unwind` field is already initialized
242 // at this moment.
243 match unsafe { (*self.unwind.get()).as_ptr().read() } {
244 UnwindReason::UserTrap(data) => Err(Trap::User(data)),
245 UnwindReason::LibTrap(trap) => Err(trap),
246 UnwindReason::WasmTrap { backtrace, pc, signal_trap } => {
247 Err(Trap::wasm(pc, backtrace, signal_trap))
248 }
249 UnwindReason::Panic(panic) => std::panic::resume_unwind(panic),
250 }
251 }
252
253 fn unwind_with(&self, reason: UnwindReason) -> ! {
254 unsafe {
255 (*self.unwind.get()).as_mut_ptr().write(reason);
256 unc_vm_unwind(self.jmp_buf.get());
257 }
258 }
259}
260
261// A private inner module for managing the TLS state that we require across
262// calls in wasm. The WebAssembly code is called from C++ and then a trap may
263// happen which requires us to read some contextual state to figure out what to
264// do with the trap. This `tls` module is used to persist that information from
265// the caller to the trap site.
266mod tls {
267 use super::CallThreadState;
268 use crate::Trap;
269 use std::mem;
270 use std::ptr;
271
272 pub use raw::Ptr;
273
274 // An even *more* inner module for dealing with TLS. This actually has the
275 // thread local variable and has functions to access the variable.
276 //
277 // Note that this is specially done to fully encapsulate that the accessors
278 // for tls must not be inlined. Wasmer's async support will employ stack
279 // switching which can resume execution on different OS threads. This means
280 // that borrows of our TLS pointer must never live across accesses because
281 // otherwise the access may be split across two threads and cause unsafety.
282 //
283 // This also means that extra care is taken by the runtime to save/restore
284 // these TLS values when the runtime may have crossed threads.
285 mod raw {
286 use super::CallThreadState;
287 use crate::Trap;
288 use std::cell::Cell;
289 use std::ptr;
290
291 pub type Ptr = *const CallThreadState;
292
293 // The first entry here is the `Ptr` which is what's used as part of the
294 // public interface of this module. The second entry is a boolean which
295 // allows the runtime to perform per-thread initialization if necessary
296 // for handling traps (e.g. setting up ports on macOS and sigaltstack on
297 // Unix).
298 thread_local!(static PTR: Cell<Ptr> = const { Cell::new(ptr::null()) });
299
300 #[inline(never)] // see module docs for why this is here
301 pub fn replace(val: Ptr) -> Result<Ptr, Trap> {
302 PTR.with(|p| {
303 // When a new value is configured that means that we may be
304 // entering WebAssembly so check to see if this thread has
305 // performed per-thread initialization for traps.
306 let prev = p.get();
307 p.set(val);
308 Ok(prev)
309 })
310 }
311
312 #[inline(never)] // see module docs for why this is here
313 pub fn get() -> Ptr {
314 PTR.with(|p| p.get())
315 }
316 }
317
318 /// Opaque state used to help control TLS state across stack switches for
319 /// async support.
320 pub struct TlsRestore(raw::Ptr);
321
322 impl TlsRestore {
323 /// Takes the TLS state that is currently configured and returns a
324 /// token that is used to replace it later.
325 ///
326 /// # Safety
327 ///
328 /// This is not a safe operation since it's intended to only be used
329 /// with stack switching found with fibers and async unc_vm.
330 pub unsafe fn take() -> Result<Self, Trap> {
331 // Our tls pointer must be set at this time, and it must not be
332 // null. We need to restore the previous pointer since we're
333 // removing ourselves from the call-stack, and in the process we
334 // null out our own previous field for safety in case it's
335 // accidentally used later.
336 let raw = raw::get();
337 assert!(!raw.is_null());
338 let prev = (*raw).prev.replace(ptr::null());
339 raw::replace(prev)?;
340 Ok(Self(raw))
341 }
342
343 /// Restores a previous tls state back into this thread's TLS.
344 ///
345 /// # Safety
346 ///
347 /// This is unsafe because it's intended to only be used within the
348 /// context of stack switching within unc_vm.
349 pub unsafe fn replace(self) -> Result<(), super::Trap> {
350 // We need to configure our previous TLS pointer to whatever is in
351 // TLS at this time, and then we set the current state to ourselves.
352 let prev = raw::get();
353 assert!((*self.0).prev.get().is_null());
354 (*self.0).prev.set(prev);
355 raw::replace(self.0)?;
356 Ok(())
357 }
358 }
359
360 /// Configures thread local state such that for the duration of the
361 /// execution of `closure` any call to `with` will yield `ptr`, unless this
362 /// is recursively called again.
363 pub fn set<R>(state: &CallThreadState, closure: impl FnOnce() -> R) -> Result<R, Trap> {
364 struct Reset<'a>(&'a CallThreadState);
365
366 impl Drop for Reset<'_> {
367 #[inline]
368 fn drop(&mut self) {
369 raw::replace(self.0.prev.replace(ptr::null()))
370 .expect("tls should be previously initialized");
371 }
372 }
373
374 // Note that this extension of the lifetime to `'static` should be
375 // safe because we only ever access it below with an anonymous
376 // lifetime, meaning `'static` never leaks out of this module.
377 let ptr = unsafe { mem::transmute::<*const CallThreadState, _>(state) };
378 let prev = raw::replace(ptr)?;
379 state.prev.set(prev);
380 let _reset = Reset(state);
381 Ok(closure())
382 }
383
384 /// Returns the last pointer configured with `set` above. Panics if `set`
385 /// has not been previously called and not returned.
386 pub fn with<R>(closure: impl FnOnce(Option<&CallThreadState>) -> R) -> R {
387 let p = raw::get();
388 unsafe { closure(if p.is_null() { None } else { Some(&*p) }) }
389 }
390}
391
392extern "C" fn signal_less_trap_handler(pc: *const u8, trap: TrapCode) {
393 let jmp_buf = tls::with(|info| {
394 let backtrace = Backtrace::new_unresolved();
395 let info = info.unwrap();
396 unsafe {
397 (*info.unwind.get()).as_mut_ptr().write(UnwindReason::WasmTrap {
398 backtrace,
399 signal_trap: Some(trap),
400 pc: pc as usize,
401 });
402 info.jmp_buf.get()
403 }
404 });
405 unsafe {
406 unc_vm_unwind(jmp_buf);
407 }
408}
409
410/// Returns pointer to the trap handler used in VMContext.
411pub fn get_trap_handler() -> *const u8 {
412 signal_less_trap_handler as *const u8
413}