wasmtime/runtime/vm/traphandlers.rs
1//! WebAssembly trap handling, which is built on top of the lower-level
2//! signalhandling mechanisms.
3
4#![cfg_attr(
5 all(not(has_native_signals), not(feature = "pulley")),
6 expect(unused, reason = "easier to not #[cfg] methods and all related types")
7)]
8
9mod backtrace;
10
11#[cfg(feature = "coredump")]
12#[path = "traphandlers/coredump_enabled.rs"]
13mod coredump;
14#[cfg(not(feature = "coredump"))]
15#[path = "traphandlers/coredump_disabled.rs"]
16mod coredump;
17
18#[cfg(all(has_native_signals))]
19mod signals;
20#[cfg(all(has_native_signals))]
21pub use self::signals::*;
22
23#[cfg(feature = "gc")]
24use crate::ThrownException;
25#[cfg(has_native_signals)]
26use crate::runtime::module::lookup_code;
27use crate::runtime::store::{ExecutorRef, StoreOpaque};
28use crate::runtime::vm::sys::traphandlers;
29use crate::runtime::vm::{InterpreterRef, VMContext, VMStore, VMStoreContext, f32x4, f64x2, i8x16};
30use crate::{EntryStoreContext, prelude::*};
31use crate::{StoreContextMut, WasmBacktrace};
32use core::cell::Cell;
33use core::num::NonZeroU32;
34use core::ptr::{self, NonNull};
35use wasmtime_unwinder::Handler;
36
37#[cfg(feature = "debug")]
38pub(crate) use self::backtrace::Activation;
39pub use self::backtrace::Backtrace;
40#[cfg(feature = "gc")]
41pub use wasmtime_unwinder::Frame;
42
43pub use self::coredump::CoreDumpStack;
44pub use self::tls::tls_eager_initialize;
45#[cfg(feature = "async")]
46pub use self::tls::{AsyncWasmCallState, PreviousAsyncWasmCallState};
47
48pub use traphandlers::SignalHandler;
49
50pub(crate) struct TrapRegisters {
51 pub pc: usize,
52 pub fp: usize,
53 /// The return address of the trapping function, on platforms where it is
54 /// held in a register (rather than on the stack) until the function sets
55 /// up its frame.
56 ///
57 /// This is only consulted for stack-overflow traps, which on such
58 /// platforms (s390x and Pulley) occur before the trapping function has
59 /// set up its frame, while `fp` is still its caller's frame pointer. See
60 /// `set_jit_trap` for how this is used.
61 pub lr: Option<usize>,
62}
63
64/// Return value from `test_if_trap`.
65#[cfg(has_native_signals)]
66pub(crate) enum TrapTest {
67 /// Not a wasm trap, need to delegate to whatever process handler is next.
68 NotWasm,
69 /// This trap was handled by the embedder via custom embedding APIs.
70 #[cfg(all(has_native_signals, not(miri)))]
71 HandledByEmbedder,
72 /// This is a wasm trap, it needs to be handled.
73 Trap(Handler),
74}
75
76fn lazy_per_thread_init() {
77 traphandlers::lazy_per_thread_init();
78}
79
80/// Raises a preexisting trap or exception and unwinds.
81///
82/// If the preexisting state has registered a trap, this function will execute
83/// the `Handler::resume` to make its way back to the original exception
84/// handler created when Wasm was entered. If the state has registered an
85/// exception, this function will perform the unwind action registered: either
86/// resetting PC, FP, and SP to the handler in the middle of the Wasm
87/// activation on the stack, or the entry trampoline back to the the host, if
88/// the exception is uncaught.
89///
90/// This is currently only called from the `raise` builtin of
91/// Wasmtime. This builtin is only used when the host returns back to
92/// wasm and indicates that a trap or exception should be raised. In
93/// this situation the host has already stored trap or exception
94/// information within the `CallThreadState` and this is the low-level
95/// operation to actually perform an unwind.
96///
97/// Note that this function is used both for Pulley and for native execution.
98/// For Pulley this function will return and the interpreter will be
99/// responsible for handling the control-flow transfer. For native this
100/// function will not return as the control flow transfer will be handled
101/// internally.
102///
103/// # Safety
104///
105/// Only safe to call when wasm code is on the stack, aka `catch_traps` must
106/// have been previously called. Additionally no Rust destructors can be on the
107/// stack. They will be skipped and not executed.
108pub(super) unsafe fn raise_preexisting_trap(store: &mut dyn VMStore) {
109 tls::with(|info| unsafe { info.unwrap().unwind(store) })
110}
111
112/// Invokes the closure `f` and handles any error/panic/trap that happens
113/// within.
114///
115/// This will invoke the closure `f` with the provided `store` and the closure
116/// will return a value that implements `HostResult`. This trait abstracts over
117/// how host values are translated to ABI values when going back into wasm.
118/// Some examples are:
119///
120/// * `T` - bare return types (not results) are simply returned as-is. No
121/// `catch_unwind` happens as if a trap can't happen then the host shouldn't
122/// be panicking or invoking user code.
123///
124/// * `Result<(), E>` - this represents an ABI return value of `bool` which
125/// indicates whether the call succeeded. This return value will catch panics
126/// and record trap information as `E`.
127///
128/// * `Result<u32, E>` - the ABI return value here is `u64` where on success
129/// the 32-bit result is zero-extended and `u64::MAX` as a return value
130/// indicates that a trap or panic happened.
131///
132/// This is primarily used in conjunction with the Cranelift-and-host boundary.
133/// This function acts as a bridge between the two to appropriately handle
134/// encoding host values to Cranelift-understood ABIs via the `HostResult`
135/// trait.
136///
137/// The `uncaught_exception` parameter controls what happens when `f` throws an
138/// exception (returns a `ThrownException` error). Core wasm host functions
139/// propagate the exception to their wasm caller, but component host functions
140/// and intrinsics are a component boundary which exceptions cannot cross, so
141/// there the exception is instead turned into a trap.
142#[inline]
143pub fn catch_unwind_and_record_trap<R>(
144 store: &mut dyn VMStore,
145 uncaught_exception: UncaughtException,
146 f: impl FnOnce(&mut dyn VMStore) -> R,
147) -> R::Abi
148where
149 R: HostResult,
150{
151 // Wasm has called out to the host.
152 store.on_wasm_to_host_transition();
153
154 // Invoke the closure `f`, optionally catching unwinds depending on `R`. The
155 // return value is always provided and if unwind information is provided
156 // (e.g. `ret` is a "false"-y value) then it's recorded in TLS for the
157 // unwind operation that's about to happen from Cranelift-generated code.
158 let (ret, unwind) = R::maybe_catch_unwind(store, |store| f(store));
159 if let Some(mut unwind) = unwind {
160 if let UnwindReason::Trap(Ok(trap)) = &mut unwind {
161 uncaught_exception.apply(&mut trap.reason);
162 }
163 tls::with(|info| info.unwrap().record_unwind(unwind));
164 }
165
166 ret
167}
168
169/// A trait used in conjunction with `catch_unwind_and_record_trap` to convert a
170/// Rust-based type to a specific ABI while handling traps/unwinds.
171///
172/// This type is implemented for return values from host function calls and
173/// libcalls. The `Abi` value of this trait represents either a successful
174/// execution with some payload state or that a failed execution happened. In
175/// the event of a failed execution the state of the failure itself is stored
176/// within `CallThreadState::unwind`. Cranelift-compiled code is expected to
177/// test for this failure sentinel and process it accordingly.
178///
179/// See `catch_unwind_and_record_trap` for some more information as well.
180pub trait HostResult {
181 /// The type of the value that's returned to Cranelift-compiled code. Needs
182 /// to be ABI-safe to pass through an `extern "C"` return value.
183 type Abi: Copy;
184
185 /// Executes `f` and returns the ABI/unwind information as a result.
186 ///
187 /// This may optionally catch unwinds during execution depending on this
188 /// implementation. The ABI return value is unconditionally provided. If an
189 /// unwind was detected (e.g. a host panic or a wasm trap) then that's
190 /// additionally returned as well.
191 ///
192 /// If an unwind is returned then it's expected that when the host returns
193 /// back to wasm (which should be soon after calling this through
194 /// `catch_unwind_and_record_trap`) then wasm will very quickly turn around
195 /// and initiate an unwind (currently through `raise_preexisting_trap`).
196 fn maybe_catch_unwind(
197 store: &mut dyn VMStore,
198 f: impl FnOnce(&mut dyn VMStore) -> Self,
199 ) -> (Self::Abi, Option<UnwindReason>);
200}
201
202// Base case implementations that do not catch unwinds. These are for libcalls
203// that neither trap nor execute user code. The raw value is the ABI itself.
204//
205// Panics in these libcalls will result in a process abort as unwinding is not
206// allowed via Rust through `extern "C"` function boundaries.
207macro_rules! host_result_no_catch {
208 ($($t:ty,)*) => {
209 $(
210 impl HostResult for $t {
211 type Abi = $t;
212 #[allow(unreachable_code, reason = "some types uninhabited on some platforms")]
213 fn maybe_catch_unwind(
214 store: &mut dyn VMStore,
215 f: impl FnOnce(&mut dyn VMStore) -> $t,
216 ) -> ($t, Option<UnwindReason>) {
217 (f(store), None)
218 }
219 }
220 )*
221 }
222}
223
224host_result_no_catch! {
225 (),
226 bool,
227 u32,
228 *mut u8,
229 u64,
230 f32,
231 f64,
232 usize,
233 i8x16,
234 f32x4,
235 f64x2,
236}
237
238impl HostResult for NonNull<u8> {
239 type Abi = *mut u8;
240 fn maybe_catch_unwind(
241 store: &mut dyn VMStore,
242 f: impl FnOnce(&mut dyn VMStore) -> Self,
243 ) -> (*mut u8, Option<UnwindReason>) {
244 (f(store).as_ptr(), None)
245 }
246}
247
248/// Implementation of `HostResult` for `Result<T, E>`.
249///
250/// This is where things get interesting for `HostResult`. This is generically
251/// defined to allow many shapes of the `Result` type to be returned from host
252/// calls or libcalls. To do this an extra trait requirement is placed on the
253/// successful result `T`: `HostResultHasUnwindSentinel`.
254///
255/// The general requirement is that `T` says what ABI it has, and the ABI must
256/// have a sentinel value which indicates that an unwind in wasm should happen.
257/// For example if `T = ()` then `true` means that the call succeeded and
258/// `false` means that an unwind happened. Here the sentinel is `false` and the
259/// ABI is `bool`.
260///
261/// This is the only implementation of `HostResult` which actually catches
262/// unwinds as there's a sentinel to encode.
263impl<T, E> HostResult for Result<T, E>
264where
265 T: HostResultHasUnwindSentinel,
266 E: Into<TrapReason>,
267{
268 type Abi = T::Abi;
269
270 fn maybe_catch_unwind(
271 store: &mut dyn VMStore,
272 f: impl FnOnce(&mut dyn VMStore) -> Result<T, E>,
273 ) -> (T::Abi, Option<UnwindReason>) {
274 // First wrap `f` in call hooks if that feature is enabled. This is used
275 // as a "pretty far down in the stack" mechanism of ensuring that hooks
276 // aren't forgotten.
277 //
278 // Note that by being placed here this is handling:
279 //
280 // * libcalls
281 // * host functions
282 // * component versions of the above
283 //
284 // This specifically is NOT handling libcalls where the result can't
285 // carry a result. This should be safe as anything which doesn't return
286 // a `Result` sort of has to be simple enough to not allow recursion so
287 // it's just a brief exit from the guest to the host.
288 //
289 // Also note that this only happens with the `call-hook` feature because
290 // this otherwise imposes a dynamic dispatch on the `store` trait object
291 // which otherwise can't be optimized away.
292 #[cfg(feature = "call-hook")]
293 let f = move |store: &mut dyn VMStore| {
294 store.call_hook(crate::CallHook::CallingHost)?;
295
296 let res = f(store);
297
298 // Note that if this returns a trap then `ret` is discarded
299 // entirely.
300 store.call_hook(crate::CallHook::ReturningFromHost)?;
301
302 res.map_err(|e| e.into())
303 };
304
305 // Next prepare the closure `f` as something that'll be invoked to
306 // generate the return value of this function. This is the
307 // conditionally, below, passed to `catch_unwind`.
308 let f = move || match f(store) {
309 Ok(ret) => {
310 let abi = ret.into_abi();
311 debug_assert!(abi != T::SENTINEL);
312 (abi, None)
313 }
314 Err(reason) => (T::SENTINEL, Some(UnwindReason::from(reason))),
315 };
316
317 // With `panic=unwind` use `std::panic::catch_unwind` to catch possible
318 // panics to rethrow.
319 #[cfg(all(feature = "std", panic = "unwind"))]
320 {
321 match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {
322 Ok(result) => result,
323 Err(err) => (T::SENTINEL, Some(UnwindReason::Panic(err))),
324 }
325 }
326
327 // With `panic=abort` there's no use in using `std::panic::catch_unwind`
328 // since it won't actually catch anything. Note that
329 // `std::panic::catch_unwind` will technically optimize to this but having
330 // this branch avoids using the `std::panic` module entirely.
331 #[cfg(not(all(feature = "std", panic = "unwind")))]
332 {
333 f()
334 }
335 }
336}
337
338/// Trait used in conjunction with `HostResult for Result<T, E>` where this is
339/// the trait bound on `T`.
340///
341/// This is for values in the "ok" position of a `Result` return value. Each
342/// value can have a separate ABI from itself (e.g. `type Abi`) and must be
343/// convertible to the ABI. Additionally all implementations of this trait have
344/// a "sentinel value" which indicates that an unwind happened. This means that
345/// no valid instance of `Self` should generate the `SENTINEL` via the
346/// `into_abi` function.
347pub unsafe trait HostResultHasUnwindSentinel {
348 /// The Cranelift-understood ABI of this value (should not be `Self`).
349 type Abi: Copy + PartialEq;
350
351 /// A value that indicates that an unwind should happen and is tested for in
352 /// Cranelift-generated code.
353 const SENTINEL: Self::Abi;
354
355 /// Converts this value into the ABI representation. Should never returned
356 /// the `SENTINEL` value.
357 fn into_abi(self) -> Self::Abi;
358}
359
360/// No return value from the host is represented as a `bool` in the ABI. Here
361/// `true` means that execution succeeded while `false` is the sentinel used to
362/// indicate an unwind.
363unsafe impl HostResultHasUnwindSentinel for () {
364 type Abi = bool;
365 const SENTINEL: bool = false;
366 fn into_abi(self) -> bool {
367 true
368 }
369}
370
371unsafe impl HostResultHasUnwindSentinel for NonZeroU32 {
372 type Abi = u32;
373 const SENTINEL: Self::Abi = 0;
374 fn into_abi(self) -> Self::Abi {
375 self.get()
376 }
377}
378
379/// A 32-bit return value can be inflated to a 64-bit return value in the ABI.
380/// In this manner a successful result is a zero-extended 32-bit value and the
381/// failure sentinel is `u64::MAX` or -1 as a signed integer.
382unsafe impl HostResultHasUnwindSentinel for u32 {
383 type Abi = u64;
384 const SENTINEL: u64 = u64::MAX;
385 fn into_abi(self) -> u64 {
386 self.into()
387 }
388}
389
390/// If there is not actual successful result (e.g. an empty enum) then the ABI
391/// can be `()`, or nothing, because there's no successful result and it's
392/// always a failure.
393unsafe impl HostResultHasUnwindSentinel for core::convert::Infallible {
394 type Abi = ();
395 const SENTINEL: () = ();
396 fn into_abi(self) {
397 match self {}
398 }
399}
400
401unsafe impl HostResultHasUnwindSentinel for bool {
402 type Abi = u32;
403 const SENTINEL: Self::Abi = u32::MAX;
404 fn into_abi(self) -> Self::Abi {
405 u32::from(self)
406 }
407}
408
409unsafe impl HostResultHasUnwindSentinel for *mut u8 {
410 type Abi = *mut u8;
411 const SENTINEL: Self::Abi = ptr::without_provenance_mut(usize::MAX);
412 fn into_abi(self) -> Self::Abi {
413 self
414 }
415}
416
417/// A helper structure to schlep from this module to the
418/// `crate::trap::from_runtime_box` function.
419///
420/// This is boxed up on the heap to keep movement around optimized. This is
421/// mutated after creation to fill in `backtrace` in some situations as well.
422#[derive(Debug)]
423pub struct Trap {
424 /// Original reason from where this trap originated.
425 pub reason: TrapReason,
426 /// Wasm backtrace of the trap, if any.
427 pub backtrace: Option<Backtrace>,
428 /// The Wasm Coredump, if any.
429 pub coredumpstack: Option<CoreDumpStack>,
430}
431
432/// Enumeration of different methods of raising a trap (or a sentinel
433/// for an exception).
434#[derive(Debug)]
435pub enum TrapReason {
436 /// A user-defined error has been raised, such as through a host function
437 /// call.
438 ///
439 /// This is constructed naturally through various `From` conversions leading
440 /// into a `TrapReason`. For example host functions returning `Result<()>`
441 /// will have any errors put here.
442 ///
443 /// Note that this variant can also represent an embedder-thrown exception.
444 /// Embedder-thrown exceptions are encoded as `ThrownException.into()` which
445 /// then looks for various handlers on the stack.
446 User(Error),
447
448 /// A trap raised from Cranelift-generated code.
449 Jit {
450 /// The program counter where this trap originated.
451 ///
452 /// This is later used with side tables from compilation to translate
453 /// the trapping address to a trap code.
454 pc: usize,
455
456 /// If the trap was a memory-related trap such as SIGSEGV then this
457 /// field will contain the address of the inaccessible data.
458 ///
459 /// Note that wasm loads/stores are not guaranteed to fill in this
460 /// information. Dynamically-bounds-checked memories, for example, will
461 /// not access an invalid address but may instead load from NULL or may
462 /// explicitly jump to a `ud2` instruction. This is only available for
463 /// fault-based traps which are one of the main ways, but not the only
464 /// way, to run wasm.
465 faulting_addr: Option<usize>,
466
467 /// The trap code associated with this trap.
468 trap: wasmtime_environ::CompiledTrap,
469 },
470}
471
472impl<E> From<E> for TrapReason
473where
474 E: Into<Error>,
475{
476 fn from(error: E) -> Self {
477 TrapReason::User(error.into())
478 }
479}
480
481/// Controls what happens when a Wasm exception escapes a `catch_traps`
482/// activation without being caught by a handler on its stack.
483#[derive(Copy, Clone, PartialEq, Eq, Debug)]
484pub enum UncaughtException {
485 /// Propagate the exception to the host as a `ThrownException`.
486 Propagate,
487 /// Convert the escaping exception into a `Trap::UncaughtException`.
488 #[cfg(feature = "component-model")]
489 Trap,
490}
491
492impl UncaughtException {
493 fn apply(self, reason: &mut TrapReason) {
494 #[cfg(all(feature = "gc", feature = "component-model"))]
495 if self == UncaughtException::Trap
496 && let TrapReason::User(err) = reason
497 && err.is::<ThrownException>()
498 {
499 // FIXME: this throws away the entire `err` and replaces it with a
500 // `Trap`, so any context on `err` is lost.
501 *err = crate::Trap::UncaughtException.into();
502 }
503 let _ = (self, reason);
504 }
505}
506
507/// Catches any wasm traps that happen within the execution of `closure`,
508/// returning them as a `Result`.
509pub fn catch_traps<T, F>(
510 store: &mut StoreContextMut<'_, T>,
511 old_state: &mut EntryStoreContext,
512 uncaught_exception: UncaughtException,
513 mut closure: F,
514) -> Result<()>
515where
516 F: FnMut(NonNull<VMContext>, Option<InterpreterRef<'_>>) -> bool,
517{
518 let caller = store.0.default_caller();
519
520 let result =
521 CallThreadState::new(store.0, old_state, uncaught_exception).with(|_cx| {
522 match store.0.executor() {
523 ExecutorRef::Interpreter(r) => closure(caller, Some(r)),
524 #[cfg(has_host_compiler_backend)]
525 ExecutorRef::Native => closure(caller, None),
526 }
527 });
528
529 // Wasm has returned, unwound or trapped back to the host.
530 store.0.on_wasm_to_host_transition();
531
532 match result {
533 Ok(x) => Ok(x),
534 Err(UnwindReason::Trap(reason)) => Err(crate::trap::from_runtime_box(store.0, reason?)),
535 #[cfg(all(feature = "std", panic = "unwind"))]
536 Err(UnwindReason::Panic(panic)) => std::panic::resume_unwind(panic),
537 }
538}
539
540// Module to hide visibility of the `CallThreadState::prev` field and force
541// usage of its accessor methods.
542mod call_thread_state {
543 use super::*;
544 use crate::EntryStoreContext;
545 use crate::runtime::vm::{Unwind, VMStackChain};
546
547 /// Temporary state stored on the stack which is registered in the `tls`
548 /// module below for calls into wasm.
549 ///
550 /// This structure is stored on the stack and allocated during the
551 /// `catch_traps` function above. The purpose of this structure is to track
552 /// the state of an "activation" or a sequence of 0-or-more contiguous
553 /// WebAssembly call frames. A `CallThreadState` always lives on the stack
554 /// and additionally maintains pointers to previous states to form a linked
555 /// list of activations.
556 ///
557 /// One of the primary goals of `CallThreadState` is to store the state of
558 /// various fields in `VMStoreContext` when it was created. This is done
559 /// because calling WebAssembly will clobber these fields otherwise.
560 ///
561 /// Another major purpose of `CallThreadState` is to assist with unwinding
562 /// and track state necessary when an unwind happens for the original
563 /// creator of `CallThreadState` to determine why the unwind happened.
564 ///
565 /// Note that this structure is pointed-to from TLS, hence liberal usage of
566 /// interior mutability here since that only gives access to
567 /// `&CallThreadState`.
568 pub struct CallThreadState {
569 /// Unwind state set when initiating an unwind and read when
570 /// the control transfer occurs (after the `raise` point is
571 /// reached for host-code destinations and right when
572 /// performing the jump for Wasm-code destinations).
573 pub(super) unwind: Cell<Option<UnwindReason>>,
574 pub(super) uncaught_exception: UncaughtException,
575 #[cfg(all(has_native_signals))]
576 pub(super) signal_handler: Option<*const SignalHandler>,
577 pub(super) capture_backtrace: bool,
578 #[cfg(feature = "coredump")]
579 pub(super) capture_coredump: bool,
580
581 pub(crate) vm_store_context: Cell<NonNull<VMStoreContext>>,
582 pub(crate) unwinder: &'static dyn Unwind,
583
584 pub(super) prev: Cell<tls::Ptr>,
585
586 // The state of the runtime for the *previous* `CallThreadState` for
587 // this same store. Our *current* state is saved in `self.vm_store_context`,
588 // etc. We need access to the old values of these
589 // fields because the `VMStoreContext` typically doesn't change across
590 // nested calls into Wasm (i.e. they are typically calls back into the
591 // same store and `self.vm_store_context == self.prev.vm_store_context`) and we must to
592 // maintain the list of contiguous-Wasm-frames stack regions for
593 // backtracing purposes.
594 old_state: *mut EntryStoreContext,
595 }
596
597 impl Drop for CallThreadState {
598 fn drop(&mut self) {
599 // Unwind information should not be present as it should have
600 // already been processed.
601 debug_assert!(self.unwind.replace(None).is_none());
602 }
603 }
604
605 impl CallThreadState {
606 #[inline]
607 pub(super) fn new(
608 store: &mut StoreOpaque,
609 old_state: *mut EntryStoreContext,
610 uncaught_exception: UncaughtException,
611 ) -> CallThreadState {
612 CallThreadState {
613 unwind: Cell::new(None),
614 uncaught_exception,
615 unwinder: store.unwinder(),
616 #[cfg(all(has_native_signals))]
617 signal_handler: store.signal_handler(),
618 capture_backtrace: store.engine().config().wasm_backtrace_max_frames.is_some(),
619 #[cfg(feature = "coredump")]
620 capture_coredump: store.engine().config().coredump_on_trap,
621 vm_store_context: Cell::new(store.vm_store_context_ptr()),
622 prev: Cell::new(ptr::null()),
623 old_state,
624 }
625 }
626
627 /// Get the saved FP upon exit from Wasm for the previous `CallThreadState`.
628 ///
629 /// # Safety
630 ///
631 /// Requires that the saved last Wasm trampoline FP points to
632 /// a valid trampoline frame, or is null.
633 pub unsafe fn old_last_wasm_exit_fp(&self) -> usize {
634 let trampoline_fp = unsafe { (&*self.old_state).last_wasm_exit_trampoline_fp };
635 // SAFETY: `trampoline_fp` is either a valid FP from an
636 // active trampoline frame or is null.
637 unsafe { VMStoreContext::wasm_exit_fp_from_trampoline_fp(trampoline_fp) }
638 }
639
640 /// Get the saved PC upon exit from Wasm for the previous `CallThreadState`.
641 pub unsafe fn old_last_wasm_exit_pc(&self) -> usize {
642 unsafe { (&*self.old_state).last_wasm_exit_pc }
643 }
644
645 /// Get the saved FP upon entry into Wasm for the previous `CallThreadState`.
646 pub unsafe fn old_last_wasm_entry_fp(&self) -> usize {
647 unsafe { (&*self.old_state).last_wasm_entry_fp }
648 }
649
650 /// Get the saved `VMStackChain` for the previous `CallThreadState`.
651 pub unsafe fn old_stack_chain(&self) -> VMStackChain {
652 unsafe { (&*self.old_state).stack_chain.clone() }
653 }
654
655 /// Get the previous `CallThreadState`.
656 pub fn prev(&self) -> tls::Ptr {
657 self.prev.get()
658 }
659
660 /// Pushes this `CallThreadState` activation on to the linked list
661 /// stored in TLS.
662 ///
663 /// This method will take the current head of the linked list, stored in
664 /// our TLS pointer, and move it into `prev`. The TLS pointer is then
665 /// updated to `self`.
666 ///
667 /// # Panics
668 ///
669 /// Panics if this activation is already in a linked list (e.g.
670 /// `self.prev` is set).
671 #[inline]
672 pub(crate) unsafe fn push(&self) {
673 assert!(self.prev.get().is_null());
674 self.prev.set(tls::raw::replace(self));
675 }
676
677 /// Pops this `CallThreadState` from the linked list stored in TLS.
678 ///
679 /// This method will restore `self.prev` into the head of the linked
680 /// list stored in TLS and will additionally null-out `self.prev`.
681 ///
682 /// # Panics
683 ///
684 /// Panics if this activation isn't the head of the list.
685 #[inline]
686 pub(crate) unsafe fn pop(&self) {
687 let prev = self.prev.replace(ptr::null());
688 let head = tls::raw::replace(prev);
689 assert!(core::ptr::eq(head, self));
690 }
691
692 /// Swaps the state in this `CallThreadState`'s `VMStoreContext` with
693 /// the state in `EntryStoreContext` that was saved when this
694 /// activation was created.
695 ///
696 /// This method is using during suspension of a fiber to restore the
697 /// store back to what it originally was and prepare it to be resumed
698 /// later on. This takes various fields of `VMStoreContext` and swaps
699 /// them with what was saved in `EntryStoreContext`. That restores
700 /// a store to just before this activation was called but saves off the
701 /// fields of this activation to get restored/resumed at a later time.
702 #[cfg(feature = "async")]
703 pub(super) unsafe fn swap(&self) {
704 unsafe fn swap<T>(a: &core::cell::UnsafeCell<T>, b: &mut T) {
705 unsafe { core::mem::swap(&mut *a.get(), b) }
706 }
707
708 unsafe {
709 let cx = self.vm_store_context.get().as_ref();
710 swap(
711 &cx.last_wasm_exit_trampoline_fp,
712 &mut (*self.old_state).last_wasm_exit_trampoline_fp,
713 );
714 swap(
715 &cx.last_wasm_exit_pc,
716 &mut (*self.old_state).last_wasm_exit_pc,
717 );
718 swap(
719 &cx.last_wasm_entry_fp,
720 &mut (*self.old_state).last_wasm_entry_fp,
721 );
722 swap(
723 &cx.last_wasm_entry_sp,
724 &mut (*self.old_state).last_wasm_entry_sp,
725 );
726 swap(
727 &cx.last_wasm_entry_trap_handler,
728 &mut (*self.old_state).last_wasm_entry_trap_handler,
729 );
730 swap(&cx.stack_chain, &mut (*self.old_state).stack_chain);
731 }
732 }
733 }
734}
735pub use call_thread_state::*;
736
737#[cfg(feature = "gc")]
738use super::compute_handler;
739
740/// The reasons why Wasmtime might unwind, stored within `CallThreadState`.
741pub enum UnwindReason {
742 /// The host panicked.
743 ///
744 /// In this situation Wasmtime must transfer the panic payload across Wasm
745 /// code since the native unwinder isn't guaranteed to be able to unwind
746 /// wasm. Once wasm is unwound, however, the panic is re-thrown on the
747 /// other side to propagate like usual.
748 #[cfg(all(feature = "std", panic = "unwind"))]
749 Panic(Box<dyn std::any::Any + Send>),
750
751 /// Wasm or the host raised a trap for some reason.
752 ///
753 /// This is specifically stored as a `Result` to carry the `OutOfMemory`
754 /// error from when this is allocated to the catch-site of the error.
755 /// Otherwise keeping this in a `Box` means that moving this value in and
756 /// out of `CallThreadState` is optimized. Specifically the "hot function"
757 /// doesn't need a slow path which is much larger with lots of memcpy's and
758 /// such.
759 Trap(Result<Box<Trap>, OutOfMemory>),
760}
761
762impl<E> From<E> for UnwindReason
763where
764 E: Into<TrapReason>,
765{
766 fn from(value: E) -> UnwindReason {
767 UnwindReason::Trap(try_new::<Box<_>>(Trap {
768 reason: value.into(),
769 backtrace: None,
770 coredumpstack: None,
771 }))
772 }
773}
774
775impl CallThreadState {
776 #[inline]
777 fn with(mut self, closure: impl FnOnce(&CallThreadState) -> bool) -> Result<(), UnwindReason> {
778 let succeeded = tls::set(&mut self, |me| closure(me));
779 if succeeded {
780 Ok(())
781 } else {
782 Err(self.read_unwind())
783 }
784 }
785
786 #[cold]
787 fn read_unwind(&self) -> UnwindReason {
788 self.unwind.replace(None).unwrap()
789 }
790
791 /// Records the unwind information provided within this `CallThreadState`.
792 ///
793 /// This function is used to stash metadata for why an unwind is about to
794 /// happen. The actual unwind is expected to happen after this function is
795 /// called using the `unwind` function below. This function is expected to
796 /// be called from the host or a signal handler the moment a trap happens.
797 /// Signal handlers then immediately unwind to the entry state, and host
798 /// functions will return back to the entry trampoline which will
799 /// immediately turn around and call the `unwind` function below.
800 ///
801 /// Note that this is a relatively low-level function and will panic if
802 /// misused.
803 ///
804 /// # Panics
805 ///
806 /// Panics if unwind information has already been recorded as that should
807 /// have been processed first.
808 fn record_unwind(&self, reason: UnwindReason) {
809 if cfg!(debug_assertions) {
810 let prev = self.unwind.replace(None);
811 assert!(prev.is_none());
812 }
813
814 self.unwind.set(Some(reason));
815 }
816
817 /// Helper function to perform an actual unwinding operation.
818 ///
819 /// This must be preceded by a `record_unwind` operation above to be
820 /// processed correctly on the other side.
821 ///
822 /// This is not used for signals-based-traps. When a signal is caught the
823 /// thread's register state is updated to the entrypoint handler. This is
824 /// only used for host-initiated traps. Note that this includes the host
825 /// implementation of throwing a wasm exception.
826 ///
827 /// Note that this function is expected to be called with the wasm backtrace
828 /// in such a state that it represents the unwinding condition.
829 /// Effectively, if a wasm backtrace is captured here, it reflects why the
830 /// unwind happened.
831 ///
832 /// # Unsafety
833 ///
834 /// This function is not safe if a corresponding handler wasn't already
835 /// setup in the entry trampoline. Additionally this isn't safe as it may
836 /// skip all Rust destructors on the stack, if there are any, for native
837 /// executors as `Handler::resume` will be used.
838 unsafe fn unwind(&self, store: &mut dyn VMStore) {
839 #[allow(unused_mut, reason = "only mutated in `debug` configuration")]
840 let mut unwind = self.unwind.replace(None);
841
842 // If configured, fire a debug event for the cause of unwinding here.
843 //
844 // Note that by firing a debug event the trap being handled can be
845 // subtly different. For example in the event of a thrown exception the
846 // debug handler might take the exception from the store and put
847 // another one there, changing the type of the exception being thrown.
848 // This notably means that the calculation for what to do about `unwind`
849 // happens after this block, down below.
850 //
851 // Also note that this can execute arbitrary WebAssembly code within
852 // this block due to the store's debug handler. That means that we
853 // might be paused here for quite some time.
854 #[cfg(feature = "debug")]
855 if let Some(UnwindReason::Trap(Ok(trap))) = &unwind {
856 #[cfg(feature = "gc")]
857 use wasmtime_core::alloc::PanicOnOom;
858
859 let result = match &trap.reason {
860 TrapReason::User(err) => {
861 let mut event = crate::DebugEvent::HostcallError(err);
862 if let Some(trap) = err.downcast_ref() {
863 event = crate::DebugEvent::Trap(*trap);
864 }
865
866 if let Some(trap) = err.downcast_ref() {
867 event = crate::DebugEvent::Trap(*trap);
868 }
869
870 // For `ThrownException` errors that indicates that we should
871 // look at the store to see if there's a pending exception
872 // there, and if so then that's a different debug event than the
873 // `HostcallError`.
874 //
875 // TODO(#12069): handle allocation failure here
876 #[cfg(feature = "gc")]
877 if err.is::<ThrownException>()
878 && let Some(exn) = store.pending_exception_owned_rooted().panic_on_oom()
879 {
880 event = crate::DebugEvent::Exception(exn.clone());
881 }
882
883 // The debug handler is embedder code and may panic. This
884 // function is called from the `raise` libcall, which
885 // doesn't catch panics, so catch them here and replace
886 // the unwind reason with the panic so that it's
887 // resumed on the other side of wasm, like a panic in a
888 // host function.
889 let f = || {
890 store
891 .block_on_debug_handler(event)
892 .map_err(UnwindReason::from)
893 };
894
895 #[cfg(all(feature = "std", panic = "unwind"))]
896 {
897 match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {
898 Ok(result) => result,
899 Err(panic) => Err(UnwindReason::Panic(panic)),
900 }
901 }
902
903 #[cfg(not(all(feature = "std", panic = "unwind")))]
904 {
905 f()
906 }
907 }
908
909 TrapReason::Jit { .. } => {
910 // Not handled here. JIT traps only show up via signal
911 // handlers, and the debugger isn't invoked from signal
912 // handlers at this time.
913 Ok(())
914 }
915 };
916
917 // If the debugger invocation itself resulted in an `Err`
918 // (which can only come from the `block_on` hitting a
919 // failure mode, or from the handler panicking), we need to
920 // override our unwind with that reason.
921 if let Err(reason) = result {
922 unwind = Some(reason);
923 }
924 }
925
926 let handler;
927 let payload1;
928 let payload2;
929
930 // Determine, from `unwind`, the `handler` and payloads that will be
931 // used to resume execution to. Note that the entry trampoline into wasm
932 // setup an entrypoint handler meaning we're guaranteed *something* to
933 // unwind to. In the case of a wasm exception, however, we may want to
934 // unwind to a different landing pad on the stack which is in-wasm.
935 'done: {
936 if let Some(UnwindReason::Trap(Ok(trap))) = &mut unwind {
937 let mut has_backtrace = trap.backtrace.is_some();
938
939 if let TrapReason::User(err) = &trap.reason {
940 // If this trap indicates an exception is being thrown, aka
941 // `ThrownException`, and there's a stored exception within the
942 // store to lookup tag information for, then do so here. If
943 // there's a wasm handler for this exception on the stack then
944 // that's the handler to resume to.
945 //
946 // Note that `unwind` is intentionally dropped on the floor
947 // here. We're resuming back into wasm with a normal state
948 // meaning we're no longer in an exceptional state. By doing
949 // this the internal `self.unwind` state reflects `None`.
950 //
951 // SAFETY: we are invoking `compute_handler()` while Wasm is
952 // on the stack and we have re-entered via a trampoline, as
953 // required by its stack-walking logic.
954 #[cfg(feature = "gc")]
955 if err.is::<ThrownException>()
956 && let Some((instance, tag)) = store.pending_exception_tag_and_instance()
957 && let Some(catch) = unsafe { compute_handler(store, instance, tag) }
958 {
959 handler = catch;
960 // Take the pending exception at this time and use it as
961 // payload.
962 payload1 = usize::try_from(
963 store.expose_pending_exception_to_wasm().unwrap().get(),
964 )
965 .expect("GC ref does not fit in usize");
966 payload2 = 0;
967 drop(unwind);
968 break 'done;
969 }
970
971 has_backtrace = has_backtrace || err.is::<WasmBacktrace>();
972 }
973
974 // If doesn't yet already have a backtrace, and one's not been
975 // captured yet, then assign one now.
976 if !has_backtrace {
977 trap.backtrace = self.capture_backtrace(store.vm_store_context_mut(), None);
978 trap.coredumpstack = self.capture_coredump(store.vm_store_context_mut(), None);
979 }
980
981 // Handle `UncaughtException` if we've come this far (as caught
982 // exceptions are handled above).
983 self.uncaught_exception.apply(&mut trap.reason);
984 }
985
986 // If this wasn't a wasm-caught exception, then catch the exception
987 // within the original entrypoint into wasm. Note that in this
988 // situation the `unwind` value is replaced within `self` to ensure
989 // that it's picked up on the other side of the trampoline catching
990 // this error.
991 handler = entry_trap_handler(store.vm_store_context());
992 payload1 = 0;
993 payload2 = 0;
994 self.unwind.set(unwind);
995 break 'done; // be sure `'done` is considered used
996 }
997
998 unsafe {
999 self.resume_to_exception_handler(store.executor(), &handler, payload1, payload2);
1000 }
1001 }
1002
1003 pub(crate) fn entry_trap_handler(&self) -> Handler {
1004 unsafe { entry_trap_handler(self.vm_store_context.get().as_ref()) }
1005 }
1006
1007 unsafe fn resume_to_exception_handler(
1008 &self,
1009 executor: ExecutorRef<'_>,
1010 handler: &Handler,
1011 payload1: usize,
1012 payload2: usize,
1013 ) {
1014 unsafe {
1015 match executor {
1016 ExecutorRef::Interpreter(mut r) => {
1017 r.resume_to_exception_handler(handler, payload1, payload2)
1018 }
1019 #[cfg(has_host_compiler_backend)]
1020 ExecutorRef::Native => handler.resume_tailcc(payload1, payload2),
1021 }
1022 }
1023 }
1024
1025 fn capture_backtrace(
1026 &self,
1027 limits: *const VMStoreContext,
1028 trap_pc_and_fp: Option<(usize, usize)>,
1029 ) -> Option<Backtrace> {
1030 if !self.capture_backtrace {
1031 return None;
1032 }
1033
1034 Some(unsafe { Backtrace::new_with_trap_state(limits, self.unwinder, self, trap_pc_and_fp) })
1035 }
1036
1037 pub(crate) fn iter<'a>(&'a self) -> impl Iterator<Item = &'a Self> + 'a {
1038 let mut state = Some(self);
1039 core::iter::from_fn(move || {
1040 let this = state?;
1041 state = unsafe { this.prev().as_ref() };
1042 Some(this)
1043 })
1044 }
1045
1046 /// Trap handler using our thread-local state.
1047 ///
1048 /// * `regs` - some special program registers at the time that the trap
1049 /// happened, for example `pc`.
1050 /// * `faulting_addr` - the system-provided address that the a fault, if
1051 /// any, happened at. This is used when debug-asserting that all segfaults
1052 /// are known to live within a `Store<T>` in a valid range.
1053 /// * `call_handler` - a closure used to invoke the platform-specific
1054 /// signal handler for each instance, if available.
1055 ///
1056 /// Attempts to handle the trap if it's a wasm trap. Returns a `TrapTest`
1057 /// which indicates what this could be, such as:
1058 ///
1059 /// * `TrapTest::NotWasm` - not a wasm fault, this should get forwarded to
1060 /// the next platform-specific fault handler.
1061 /// * `TrapTest::HandledByEmbedder` - the embedder `call_handler` handled
1062 /// this signal, nothing else to do.
1063 /// * `TrapTest::Trap` - this is a wasm trap an the stack needs to be
1064 /// unwound now.
1065 #[cfg(has_native_signals)]
1066 pub(crate) fn test_if_trap(
1067 &self,
1068 regs: TrapRegisters,
1069 faulting_addr: Option<usize>,
1070 call_handler: impl FnOnce(&SignalHandler) -> bool,
1071 ) -> TrapTest {
1072 // First up see if any instance registered has a custom trap handler,
1073 // in which case run them all. If anything handles the trap then we
1074 // return that the trap was handled.
1075 let _ = &call_handler;
1076 #[cfg(all(has_native_signals, not(miri)))]
1077 if let Some(handler) = self.signal_handler {
1078 if unsafe { call_handler(&*handler) } {
1079 return TrapTest::HandledByEmbedder;
1080 }
1081 }
1082
1083 // If this fault wasn't in wasm code, then it's not our problem
1084 let Some((code, text_offset)) = lookup_code(regs.pc) else {
1085 return TrapTest::NotWasm;
1086 };
1087
1088 // If the fault was at a location that was not marked as potentially
1089 // trapping, then that's a bug in Cranelift/Winch/etc. Don't try to
1090 // catch the trap and pretend this isn't wasm so the program likely
1091 // aborts.
1092 let Some(trap) = code.lookup_trap_code(text_offset) else {
1093 return TrapTest::NotWasm;
1094 };
1095
1096 // If all that passed then this is indeed a wasm trap, so return the
1097 // `Handler` setup in the original wasm frame.
1098 self.set_jit_trap(regs, faulting_addr, trap);
1099 let entry_handler = self.entry_trap_handler();
1100 TrapTest::Trap(entry_handler)
1101 }
1102
1103 pub(crate) fn set_jit_trap(
1104 &self,
1105 TrapRegisters { pc, fp, lr }: TrapRegisters,
1106 faulting_addr: Option<usize>,
1107 trap: wasmtime_environ::CompiledTrap,
1108 ) {
1109 // The backtrace starts at the trapping PC and FP, except for stack
1110 // overflows that are detected before the trapping function has set up
1111 // its frame (indicated by the presence of `lr`). In that case we
1112 // attribute the stack overflow to the call site in the caller, as if the
1113 // caller were responsible for allocating the callee's frame: we start
1114 // the backtrace at the return address in the caller, with the caller's
1115 // FP, which is still the current one. The PC recorded in the trap
1116 // reason remains the actual trapping PC, so the backtrace's youngest
1117 // frame is treated like any other return address and resolves to the
1118 // call instruction.
1119 let backtrace_pc = match trap {
1120 wasmtime_environ::CompiledTrap::Normal(wasmtime_environ::Trap::StackOverflow) => {
1121 lr.unwrap_or(pc)
1122 }
1123 _ => pc,
1124 };
1125 self.record_jit_trap(pc, faulting_addr, trap, Some((backtrace_pc, fp)));
1126 }
1127
1128 /// Records a trap at `pc`, capturing a backtrace starting from
1129 /// `backtrace_pc_and_fp` in the current activation.
1130 ///
1131 /// If `backtrace_pc_and_fp` is `None` then the current activation has no
1132 /// Wasm frames, and only older activations are included in the backtrace.
1133 pub(crate) fn record_jit_trap(
1134 &self,
1135 pc: usize,
1136 faulting_addr: Option<usize>,
1137 trap: wasmtime_environ::CompiledTrap,
1138 backtrace_pc_and_fp: Option<(usize, usize)>,
1139 ) {
1140 let mut unwind = UnwindReason::from(TrapReason::Jit {
1141 pc,
1142 faulting_addr,
1143 trap,
1144 });
1145 if let UnwindReason::Trap(Ok(trap)) = &mut unwind {
1146 trap.backtrace =
1147 self.capture_backtrace(self.vm_store_context.get().as_ptr(), backtrace_pc_and_fp);
1148 trap.coredumpstack =
1149 self.capture_coredump(self.vm_store_context.get().as_ptr(), backtrace_pc_and_fp);
1150 }
1151 self.record_unwind(unwind);
1152 }
1153}
1154
1155fn entry_trap_handler(vm_store_context: &VMStoreContext) -> Handler {
1156 unsafe {
1157 let fp = *vm_store_context.last_wasm_entry_fp.get();
1158 let sp = *vm_store_context.last_wasm_entry_sp.get();
1159 let pc = *vm_store_context.last_wasm_entry_trap_handler.get();
1160 Handler { pc, sp, fp }
1161 }
1162}
1163
1164/// A private inner module managing the state of Wasmtime's thread-local storage
1165/// (TLS) state.
1166///
1167/// Wasmtime at this time has a single pointer of TLS. This single pointer of
1168/// TLS is the totality of all TLS required by Wasmtime. By keeping this as
1169/// small as possible it generally makes it easier to integrate with external
1170/// systems and implement features such as fiber context switches. This single
1171/// TLS pointer is declared in platform-specific modules to handle platform
1172/// differences, so this module here uses getters/setters which delegate to
1173/// platform-specific implementations.
1174///
1175/// The single TLS pointer used by Wasmtime is morally
1176/// `Option<&CallThreadState>` meaning that it's a possibly-present pointer to
1177/// some state. This pointer is a pointer to the most recent (youngest)
1178/// `CallThreadState` activation, or the most recent call into WebAssembly.
1179///
1180/// This TLS pointer is additionally the head of a linked list of activations
1181/// that are all stored on the stack for the current thread. Each time
1182/// WebAssembly is recursively invoked by an embedder will push a new entry into
1183/// this linked list. This singly-linked list is maintained with its head in TLS
1184/// node pointers are stored in `CallThreadState::prev`.
1185///
1186/// An example stack might look like this:
1187///
1188/// ```text
1189/// ┌─────────────────────┐◄───── highest, or oldest, stack address
1190/// │ native stack frames │
1191/// │ ... │
1192/// │ ┌───────────────┐◄─┼──┐
1193/// │ │CallThreadState│ │ │
1194/// │ └───────────────┘ │ p
1195/// ├─────────────────────┤ r
1196/// │ wasm stack frames │ e
1197/// │ ... │ v
1198/// ├─────────────────────┤ │
1199/// │ native stack frames │ │
1200/// │ ... │ │
1201/// │ ┌───────────────┐◄─┼──┼── TLS pointer
1202/// │ │CallThreadState├──┼──┘
1203/// │ └───────────────┘ │
1204/// ├─────────────────────┤
1205/// │ wasm stack frames │
1206/// │ ... │
1207/// ├─────────────────────┤
1208/// │ native stack frames │
1209/// │ ... │
1210/// └─────────────────────┘◄───── smallest, or youngest, stack address
1211/// ```
1212///
1213/// # Fibers and async
1214///
1215/// Wasmtime supports stack-switching with fibers to implement async. This means
1216/// that Wasmtime will temporarily execute code on a separate stack and then
1217/// suspend from this stack back to the embedder for async operations. Doing
1218/// this safely requires manual management of the TLS pointer updated by
1219/// Wasmtime.
1220///
1221/// For example when a fiber is suspended that means that the TLS pointer needs
1222/// to be restored to whatever it was when the fiber was resumed. Additionally
1223/// this may need to pop multiple `CallThreadState` activations, one for each
1224/// one located on the fiber stack itself.
1225///
1226/// The `AsyncWasmCallState` and `PreviousAsyncWasmCallState` structures in this
1227/// module are used to manage this state, namely:
1228///
1229/// * The `AsyncWasmCallState` structure represents the state of a suspended
1230/// fiber. This is a linked list, in reverse order, from oldest activation on
1231/// the fiber to youngest activation on the fiber.
1232///
1233/// * The `PreviousAsyncWasmCallState` structure represents a pointer within our
1234/// thread's TLS linked list of activations when a fiber was resumed. This
1235/// pointer is used during fiber suspension to know when to stop popping
1236/// activations from the thread's linked list.
1237///
1238/// Note that this means that the directionality of linked list links is
1239/// opposite when stored in TLS vs when stored for a suspended fiber. The
1240/// thread's current list pointed to by TLS is youngest-to-oldest links, while a
1241/// suspended fiber stores oldest-to-youngest links.
1242pub(crate) mod tls {
1243 #[cfg(all(feature = "component-model-async", feature = "gc"))]
1244 use crate::module::ModuleRegistry;
1245 #[cfg(all(feature = "component-model-async", feature = "gc"))]
1246 use crate::store::StoreOpaque;
1247
1248 use super::CallThreadState;
1249
1250 pub use raw::Ptr;
1251
1252 // An even *more* inner module for dealing with TLS. This actually has the
1253 // thread local variable and has functions to access the variable.
1254 //
1255 // Note that this is specially done to fully encapsulate that the accessors
1256 // for tls may or may not be inlined. Wasmtime's async support employs stack
1257 // switching which can resume execution on different OS threads. This means
1258 // that borrows of our TLS pointer must never live across accesses because
1259 // otherwise the access may be split across two threads and cause unsafety.
1260 //
1261 // This also means that extra care is taken by the runtime to save/restore
1262 // these TLS values when the runtime may have crossed threads.
1263 //
1264 // Note, though, that if async support is disabled at compile time then
1265 // these functions are free to be inlined.
1266 pub(super) mod raw {
1267 use super::CallThreadState;
1268
1269 pub type Ptr = *const CallThreadState;
1270
1271 const _: () = {
1272 assert!(core::mem::align_of::<CallThreadState>() > 1);
1273 };
1274
1275 fn tls_get() -> (Ptr, bool) {
1276 let mut initialized = false;
1277 let p = crate::runtime::vm::sys::tls_get().map_addr(|a| {
1278 initialized = (a & 1) != 0;
1279 a & !1
1280 });
1281 (p.cast(), initialized)
1282 }
1283
1284 fn tls_set(ptr: Ptr, initialized: bool) {
1285 let encoded = ptr.map_addr(|a| a | usize::from(initialized));
1286 crate::runtime::vm::sys::tls_set(encoded.cast_mut().cast::<u8>());
1287 }
1288
1289 #[cfg_attr(feature = "async", inline(never))] // see module docs
1290 #[cfg_attr(not(feature = "async"), inline)]
1291 pub fn replace(val: Ptr) -> Ptr {
1292 // When a new value is configured that means that we may be
1293 // entering WebAssembly so check to see if this thread has
1294 // performed per-thread initialization for traps.
1295 let (prev, initialized) = tls_get();
1296 if !initialized {
1297 super::super::lazy_per_thread_init();
1298 }
1299 tls_set(val, true);
1300 prev
1301 }
1302
1303 /// Eagerly initialize thread-local runtime functionality. This will be performed
1304 /// lazily by the runtime if users do not perform it eagerly.
1305 #[cfg_attr(feature = "async", inline(never))] // see module docs
1306 #[cfg_attr(not(feature = "async"), inline)]
1307 pub fn initialize() {
1308 let (state, initialized) = tls_get();
1309 if initialized {
1310 return;
1311 }
1312 super::super::lazy_per_thread_init();
1313 tls_set(state, true);
1314 }
1315
1316 #[cfg_attr(feature = "async", inline(never))] // see module docs
1317 #[cfg_attr(not(feature = "async"), inline)]
1318 pub fn get() -> Ptr {
1319 tls_get().0
1320 }
1321 }
1322
1323 pub use raw::initialize as tls_eager_initialize;
1324 #[cfg(all(feature = "component-model-async", feature = "gc"))]
1325 use wasmtime_unwinder::Unwind;
1326
1327 /// Opaque state used to persist the state of the `CallThreadState`
1328 /// activations associated with a fiber stack that's used as part of an
1329 /// async wasm call.
1330 #[cfg(feature = "async")]
1331 pub struct AsyncWasmCallState {
1332 // The head of a linked list of activations that are currently present
1333 // on an async call's fiber stack. This pointer points to the oldest
1334 // activation frame where the `prev` links internally link to younger
1335 // activation frames.
1336 //
1337 // When pushed onto a thread this linked list is traversed to get pushed
1338 // onto the current thread at the time.
1339 //
1340 // If this pointer is null then that means that the fiber this state is
1341 // associated with has no activations.
1342 state: raw::Ptr,
1343 }
1344
1345 // SAFETY: This is a relatively unsafe unsafe block and not really all that
1346 // well audited. The general idea is that the linked list of activations
1347 // owned by `self.state` are safe to send to other threads, but that relies
1348 // on everything internally being safe as well as stack variables and such.
1349 // This is more-or-less tied to the very large comment in `fiber.rs` about
1350 // `unsafe impl Send` there.
1351 #[cfg(feature = "async")]
1352 unsafe impl Send for AsyncWasmCallState {}
1353
1354 #[cfg(feature = "async")]
1355 impl AsyncWasmCallState {
1356 /// Creates new state that initially starts as null.
1357 pub fn new() -> AsyncWasmCallState {
1358 AsyncWasmCallState {
1359 state: core::ptr::null_mut(),
1360 }
1361 }
1362
1363 /// Pushes the saved state of this wasm's call onto the current thread's
1364 /// state.
1365 ///
1366 /// This will iterate over the linked list of states stored within
1367 /// `self` and push them sequentially onto the current thread's
1368 /// activation list.
1369 ///
1370 /// The returned `PreviousAsyncWasmCallState` captures the state of this
1371 /// thread just before this operation, and it must have its `restore`
1372 /// method called to restore the state when the async wasm is suspended
1373 /// from.
1374 ///
1375 /// # Unsafety
1376 ///
1377 /// Must be carefully coordinated with
1378 /// `PreviousAsyncWasmCallState::restore` and fiber switches to ensure
1379 /// that this doesn't push stale data and the data is popped
1380 /// appropriately.
1381 pub unsafe fn push(self) -> PreviousAsyncWasmCallState {
1382 // First save the state of TLS as-is so when this state is popped
1383 // off later on we know where to stop.
1384 let ret = PreviousAsyncWasmCallState { state: raw::get() };
1385
1386 // The oldest activation, if present, has various `VMStoreContext`
1387 // fields saved within it. These fields were the state for the
1388 // *youngest* activation when a suspension previously happened. By
1389 // swapping them back into the store this is an O(1) way of
1390 // restoring the state of a store's metadata fields at the time of
1391 // the suspension.
1392 //
1393 // The store's previous values before this function will all get
1394 // saved in the oldest activation's state on the stack. The store's
1395 // current state then describes the youngest activation which is
1396 // restored via the loop below.
1397 unsafe {
1398 if let Some(state) = self.state.as_ref() {
1399 state.swap();
1400 }
1401 }
1402
1403 // Our `state` pointer is a linked list of oldest-to-youngest so by
1404 // pushing in order of the list we restore the youngest-to-oldest
1405 // list as stored in the state of this current thread.
1406 let mut ptr = self.state;
1407 unsafe {
1408 while let Some(state) = ptr.as_ref() {
1409 ptr = state.prev.replace(core::ptr::null_mut());
1410 state.push();
1411 }
1412 }
1413 ret
1414 }
1415
1416 /// Performs a runtime check that this state is indeed null.
1417 pub fn assert_null(&self) {
1418 assert!(self.state.is_null());
1419 }
1420
1421 /// Asserts that the current CallThreadState pointer, if present, is not
1422 /// in the `range` specified.
1423 ///
1424 /// This is used when exiting a future in Wasmtime to assert that the
1425 /// current CallThreadState pointer does not point within the stack
1426 /// we're leaving (e.g. allocated for a fiber).
1427 pub fn assert_current_state_not_in_range(range: core::ops::Range<usize>) {
1428 let p = raw::get() as usize;
1429 assert!(!range.contains(&p));
1430 }
1431
1432 #[cfg(all(feature = "component-model-async", feature = "gc"))]
1433 pub(crate) fn trace_gc_roots(
1434 &mut self,
1435 modules: &ModuleRegistry,
1436 unwind: &dyn Unwind,
1437 gc_roots_list: &mut crate::vm::GcRootsList,
1438 ) {
1439 let mut ptr = self.state;
1440 unsafe {
1441 while let Some(state) = ptr.as_ref() {
1442 ptr = state.prev.get();
1443
1444 // Skip activations that entered no Wasm.
1445 if state.old_last_wasm_exit_pc() == 0 {
1446 continue;
1447 }
1448
1449 let _ = wasmtime_unwinder::visit_frames::<()>(
1450 unwind,
1451 state.old_last_wasm_exit_pc(),
1452 state.old_last_wasm_exit_fp(),
1453 state.old_last_wasm_entry_fp(),
1454 |frame| {
1455 StoreOpaque::trace_wasm_stack_frame(modules, gc_roots_list, frame);
1456 core::ops::ControlFlow::Continue(())
1457 },
1458 );
1459 }
1460 }
1461 }
1462 }
1463
1464 /// Opaque state used to help control TLS state across stack switches for
1465 /// async support.
1466 ///
1467 /// This structure is returned from [`AsyncWasmCallState::push`] and
1468 /// represents the state of this thread's TLS variable prior to the push
1469 /// operation.
1470 #[cfg(feature = "async")]
1471 pub struct PreviousAsyncWasmCallState {
1472 // The raw value of this thread's TLS pointer when this structure was
1473 // created. This is not dereferenced or inspected but is used to halt
1474 // linked list traversal in [`PreviousAsyncWasmCallState::restore`].
1475 state: raw::Ptr,
1476 }
1477
1478 #[cfg(feature = "async")]
1479 impl PreviousAsyncWasmCallState {
1480 /// Pops a fiber's linked list of activations and stores them in
1481 /// `AsyncWasmCallState`.
1482 ///
1483 /// This will pop the top activation of this current thread continuously
1484 /// until it reaches whatever the current activation was when
1485 /// [`AsyncWasmCallState::push`] was originally called.
1486 ///
1487 /// # Unsafety
1488 ///
1489 /// Must be paired with a `push` and only performed at a time when a
1490 /// fiber is being suspended.
1491 pub unsafe fn restore(self) -> AsyncWasmCallState {
1492 let thread_head = self.state;
1493 core::mem::forget(self);
1494 let mut ret = AsyncWasmCallState::new();
1495 loop {
1496 // If the current TLS state is as we originally found it, then
1497 // this loop is finished.
1498 //
1499 // Note, though, that before exiting, if the oldest
1500 // `CallThreadState` is present, the current state of
1501 // `VMStoreContext` is saved off within it. This will save the
1502 // current state, before this function, of `VMStoreContext`
1503 // into the `EntryStoreContext` stored with the oldest
1504 // activation. This is a bit counter-intuitive where the state
1505 // for the youngest activation is stored in the "old" state
1506 // of the oldest activation.
1507 //
1508 // What this does is restores the state of the store to just
1509 // before this async fiber was started. The fiber's state will
1510 // be entirely self-contained in the fiber itself and the
1511 // returned `AsyncWasmCallState`. Resumption above in
1512 // `AsyncWasmCallState::push` will perform the swap back into
1513 // the store to hook things up again.
1514 let ptr = raw::get();
1515 if ptr == thread_head {
1516 unsafe {
1517 if let Some(state) = ret.state.as_ref() {
1518 state.swap();
1519 }
1520 }
1521
1522 break ret;
1523 }
1524
1525 // Pop this activation from the current thread's TLS state, and
1526 // then afterwards push it onto our own linked list within this
1527 // `AsyncWasmCallState`. Note that the linked list in
1528 // `AsyncWasmCallState` is stored in reverse order so a
1529 // subsequent `push` later on pushes everything in the right
1530 // order.
1531 unsafe {
1532 (*ptr).pop();
1533 if let Some(state) = ret.state.as_ref() {
1534 (*ptr).prev.set(state);
1535 }
1536 }
1537 ret.state = ptr;
1538 }
1539 }
1540 }
1541
1542 #[cfg(feature = "async")]
1543 impl Drop for PreviousAsyncWasmCallState {
1544 fn drop(&mut self) {
1545 panic!("must be consumed with `restore`");
1546 }
1547 }
1548
1549 /// Configures thread local state such that for the duration of the
1550 /// execution of `closure` any call to `with` will yield `state`, unless
1551 /// this is recursively called again.
1552 #[inline]
1553 pub fn set<R>(state: &mut CallThreadState, closure: impl FnOnce(&CallThreadState) -> R) -> R {
1554 struct Reset<'a> {
1555 state: &'a CallThreadState,
1556 }
1557
1558 impl Drop for Reset<'_> {
1559 #[inline]
1560 fn drop(&mut self) {
1561 unsafe {
1562 self.state.pop();
1563 }
1564 }
1565 }
1566
1567 unsafe {
1568 state.push();
1569 let reset = Reset { state };
1570 closure(reset.state)
1571 }
1572 }
1573
1574 /// Returns the last pointer configured with `set` above, if any.
1575 pub fn with<R>(closure: impl FnOnce(Option<&CallThreadState>) -> R) -> R {
1576 let p = raw::get();
1577 unsafe { closure(if p.is_null() { None } else { Some(&*p) }) }
1578 }
1579}