Skip to main content

wasmer_vm/trap/
traphandlers.rs

1// This file contains code from external sources.
2// Attributions: https://github.com/wasmerio/wasmer/blob/main/docs/ATTRIBUTIONS.md
3
4#![allow(static_mut_refs)]
5
6//! WebAssembly trap handling, which is built on top of the lower-level
7//! signalhandling mechanisms.
8
9use super::trap::UnwindReason;
10use crate::Trap;
11#[cfg(all(unix, feature = "experimental-host-interrupt"))]
12use crate::interrupt_registry;
13use backtrace::Backtrace;
14use bytesize::ByteSize;
15use core::ptr::{read, read_unaligned};
16use corosensei::stack::{DefaultStack, Stack};
17use corosensei::trap::{CoroutineTrapHandler, TrapHandlerRegs};
18use corosensei::{CoroutineResult, ScopedCoroutine, Yielder};
19use scopeguard::defer;
20use std::any::Any;
21use std::cell::Cell;
22use std::error::Error;
23use std::io;
24use std::mem;
25#[cfg(unix)]
26use std::mem::MaybeUninit;
27use std::ptr::{self, NonNull};
28use std::sync::atomic::{AtomicPtr, AtomicUsize, Ordering, compiler_fence};
29use std::sync::{LazyLock, Once};
30use wasmer_types::TrapCode;
31
32/// Convenience extension for [`Stack`] that exposes the total mapped size.
33trait StackExt: Stack {
34    /// Returns the total size of the stack mapping (including guard page).
35    fn size(&self) -> usize {
36        self.base().get() - self.limit().get()
37    }
38}
39impl<T: Stack> StackExt for T {}
40
41/// Configuration for the runtime VM
42/// Currently only the stack size is configurable
43pub struct VMConfig {
44    /// Optional stack size (in byte) of the VM. Value lower than 8K will be rounded to 8K.
45    pub wasm_stack_size: Option<usize>,
46}
47
48// TrapInformation can be stored in the "Undefined Instruction" itself.
49// On x86_64, 0xC? select a "Register" for the Mod R/M part of "ud1" (so with no other bytes after)
50// On Arm64, the udf allows for a 16bits values, so we'll use the same 0xC? to store the trapinfo
51static MAGIC: u8 = 0xc0;
52
53static DEFAULT_STACK_SIZE: AtomicUsize = AtomicUsize::new(ByteSize::mib(1).as_u64() as usize);
54
55/// Maximum allowed default stack size (100 MiB) for the process-wide
56/// configuration set via `set_stack_size`.
57pub const MAX_STACK_SIZE: usize = ByteSize::mib(100).as_u64() as usize;
58
59// Current definition of `ucontext_t` in the `libc` crate is incorrect
60// on aarch64-apple-drawing so it's defined here with a more accurate definition.
61#[repr(C)]
62#[cfg(all(target_arch = "aarch64", target_os = "macos"))]
63#[allow(non_camel_case_types)]
64struct ucontext_t {
65    uc_onstack: libc::c_int,
66    uc_sigmask: libc::sigset_t,
67    uc_stack: libc::stack_t,
68    uc_link: *mut libc::ucontext_t,
69    uc_mcsize: usize,
70    uc_mcontext: libc::mcontext_t,
71}
72
73#[cfg(all(unix, not(all(target_arch = "aarch64", target_os = "macos"))))]
74use libc::ucontext_t;
75
76/// Sets the process-wide default stack size for new Wasmer coroutines.
77/// The value is clamped to [8 KiB, MAX_STACK_SIZE].
78pub fn set_stack_size(size: usize) {
79    DEFAULT_STACK_SIZE.store(
80        size.clamp(ByteSize::kib(8).as_u64() as usize, MAX_STACK_SIZE),
81        Ordering::Relaxed,
82    );
83}
84
85/// Returns the process-wide default stack size in bytes.
86pub fn get_stack_size() -> usize {
87    DEFAULT_STACK_SIZE.load(Ordering::Relaxed)
88}
89
90/// Pool of pre-allocated coroutine stacks to avoid repeated mmap syscalls.
91/// Acts as the cross-thread overflow store; per-thread reuse is served by
92/// `TLS_STACK` to keep the hot path atomic-free.
93static STACK_POOL: LazyLock<crossbeam_queue::SegQueue<DefaultStack>> =
94    LazyLock::new(crossbeam_queue::SegQueue::new);
95
96/// Per-thread cache holding a single ready-to-use coroutine stack. The hot
97/// path of `on_wasm_stack` pops from here without touching the global
98/// `STACK_POOL`'s atomics; only the first call on a thread or re-entrant
99/// nested calls fall back to the pool.
100///
101/// On thread exit the held stack (if any) is pushed to `STACK_POOL` so memory
102/// cycles correctly across thread lifetimes (no mmap leaks).
103struct StackCache(Cell<Option<DefaultStack>>);
104
105impl Drop for StackCache {
106    fn drop(&mut self) {
107        if let Some(stack) = self.0.take() {
108            STACK_POOL.push(stack);
109        }
110    }
111}
112
113thread_local! {
114    static TLS_STACK: StackCache = const { StackCache(Cell::new(None)) };
115}
116
117/// Acquire a coroutine stack large enough for `min_size`. Prefers the
118/// thread-local cache (no atomics), falls back to the global `STACK_POOL`,
119/// then allocates a fresh stack.
120fn acquire_stack(min_size: usize) -> DefaultStack {
121    // Fast path: thread-local cache. Steady-state per-thread reuse never
122    // touches the SegQueue.
123    if let Some(stack) = TLS_STACK.with(|cache| cache.0.take()) {
124        if stack.size() >= min_size {
125            return stack;
126        }
127        // Undersized — discard (mirrors the existing `STACK_POOL.pop().filter(...)`
128        // behavior of not holding undersized stacks in rotation).
129        drop(stack);
130    }
131    // Cross-thread overflow pool. Single pop, single filter — same semantics
132    // as the pre-TLS implementation.
133    STACK_POOL
134        .pop()
135        .filter(|s| s.size() >= min_size)
136        .unwrap_or_else(|| DefaultStack::new(min_size).unwrap())
137}
138
139/// Release a coroutine stack. Prefers the thread-local slot if empty (no
140/// atomics); otherwise pushes to the global `STACK_POOL` so the stack is
141/// still reusable by other threads.
142fn release_stack(stack: DefaultStack) {
143    let displaced = TLS_STACK.with(|cache| cache.0.replace(Some(stack)));
144    if let Some(displaced) = displaced {
145        STACK_POOL.push(displaced);
146    }
147}
148
149/// Drains the coroutine stack pool at the moment it runs.
150///
151/// This is intended to be called before retrying with a larger stack size so
152/// that the pool does not keep serving cached undersized stacks.
153///
154/// Note that `STACK_POOL` is a global, concurrently used queue and that each
155/// thread also keeps a private cached stack in TLS. Other threads may push
156/// stacks back into the pool (for example, when their Wasm execution
157/// finishes) while or after this function is running, and TLS-cached stacks
158/// on other threads are not touched. As a result, this function provides
159/// only a best-effort drain: there is no guarantee that no undersized stacks
160/// exist immediately after it returns unless the caller ensures, via external
161/// synchronization, that no other Wasm executions can return stacks to the
162/// pool while this function runs. The current thread's TLS-cached stack is
163/// drained as part of this call.
164pub fn drain_stack_pool() {
165    // Drain the calling thread's TLS slot first (best-effort across threads
166    // still applies — other threads' caches aren't touched).
167    if let Some(stack) = TLS_STACK.with(|cache| cache.0.take()) {
168        drop(stack);
169    }
170    while STACK_POOL.pop().is_some() {}
171}
172
173cfg_select! {
174    unix => {
175        /// Function which may handle custom signals while processing traps.
176        pub type TrapHandlerFn<'a> = dyn Fn(libc::c_int, *const libc::siginfo_t, *const libc::c_void) -> bool + Send + Sync + 'a;
177    }
178    target_os = "windows" => {
179        /// Function which may handle custom signals while processing traps.
180        pub type TrapHandlerFn<'a> = dyn Fn(*mut windows_sys::Win32::System::Diagnostics::Debug::EXCEPTION_POINTERS) -> bool + Send + Sync + 'a;
181    }
182}
183
184// Process an IllegalOpcode to see if it has a TrapCode payload
185unsafe fn process_illegal_op(addr: usize) -> Option<TrapCode> {
186    let mut val: Option<u8> = None;
187    unsafe {
188        if cfg!(target_arch = "x86_64") {
189            val = if read(addr as *mut u8) & 0xf0 == 0x40
190                && read((addr + 1) as *mut u8) == 0x0f
191                && read((addr + 2) as *mut u8) == 0xb9
192            {
193                Some(read((addr + 3) as *mut u8))
194            } else if read(addr as *mut u8) == 0x0f && read((addr + 1) as *mut u8) == 0xb9 {
195                Some(read((addr + 2) as *mut u8))
196            } else {
197                None
198            }
199        }
200        if cfg!(target_arch = "aarch64") {
201            val = if read_unaligned(addr as *mut u32) & 0xffff0000 == 0 {
202                Some(read(addr as *mut u8))
203            } else {
204                None
205            }
206        }
207        if cfg!(target_arch = "riscv64") {
208            let addr = addr as *mut u32;
209            // Check if 'unimp' instruction
210            val = if read(addr) == 0xc0001073 {
211                // Read from the instruction we emitted: 'addi a0, xzero, $payload'
212                // and take the encoded immediate value (upper 12-bits).
213                let prev_insn = read(addr.sub(1));
214                if (prev_insn & 0xffff) == 0x0513 {
215                    Some((prev_insn >> 20) as u8)
216                } else {
217                    None
218                }
219            } else {
220                None
221            };
222        }
223    }
224
225    // The direct encoding of a trap into the instruction is unused on RISC-V:
226    if cfg!(target_arch = "x86_64") || cfg!(target_arch = "aarch64") {
227        val = val.and_then(|val| {
228            if val & MAGIC == MAGIC {
229                Some(val & 0xf)
230            } else {
231                None
232            }
233        });
234    }
235
236    match val {
237        None => None,
238        Some(val) => match val {
239            0 => Some(TrapCode::StackOverflow),
240            1 => Some(TrapCode::HeapAccessOutOfBounds),
241            2 => Some(TrapCode::HeapMisaligned),
242            3 => Some(TrapCode::TableAccessOutOfBounds),
243            4 => Some(TrapCode::IndirectCallToNull),
244            5 => Some(TrapCode::BadSignature),
245            6 => Some(TrapCode::IntegerOverflow),
246            7 => Some(TrapCode::IntegerDivisionByZero),
247            8 => Some(TrapCode::BadConversionToInteger),
248            9 => Some(TrapCode::UnreachableCodeReached),
249            10 => Some(TrapCode::UnalignedAtomic),
250            _ => None,
251        },
252    }
253}
254
255cfg_select! {
256    unix => {
257        static mut PREV_SIGSEGV: MaybeUninit<libc::sigaction> = MaybeUninit::uninit();
258        static mut PREV_SIGBUS: MaybeUninit<libc::sigaction> = MaybeUninit::uninit();
259        static mut PREV_SIGILL: MaybeUninit<libc::sigaction> = MaybeUninit::uninit();
260        static mut PREV_SIGFPE: MaybeUninit<libc::sigaction> = MaybeUninit::uninit();
261
262        #[cfg(feature = "experimental-host-interrupt")]
263        static mut PREV_SIGUSR1: MaybeUninit<libc::sigaction> = MaybeUninit::uninit();
264
265        unsafe fn platform_init() { unsafe {
266            let register = |slot: &mut MaybeUninit<libc::sigaction>, signal: i32, nodefer: bool| {
267                let mut handler: libc::sigaction = mem::zeroed();
268                // The flags here are relatively careful, and they are...
269                //
270                // SA_SIGINFO gives us access to information like the program
271                // counter from where the fault happened.
272                //
273                // SA_ONSTACK allows us to handle signals on an alternate stack,
274                // so that the handler can run in response to running out of
275                // stack space on the main stack. Rust installs an alternate
276                // stack with sigaltstack, so we rely on that.
277                //
278                // SA_NODEFER allows us to reenter the signal handler if we
279                // crash while handling the signal, and fall through to the
280                // Breakpad handler by testing handlingSegFault.
281                handler.sa_flags = libc::SA_SIGINFO | libc::SA_ONSTACK;
282                if nodefer {
283                    handler.sa_flags |= libc::SA_NODEFER;
284                }
285                handler.sa_sigaction = trap_handler as *const () as usize;
286                libc::sigemptyset(&mut handler.sa_mask);
287                if libc::sigaction(signal, &handler, slot.as_mut_ptr()) != 0 {
288                    panic!(
289                        "unable to install signal handler: {}",
290                        io::Error::last_os_error(),
291                    );
292                }
293            };
294
295            // Allow handling OOB with signals on all architectures
296            register(&mut PREV_SIGSEGV, libc::SIGSEGV, true);
297
298            // Handle `unreachable` instructions which execute `ud2` right now
299            register(&mut PREV_SIGILL, libc::SIGILL, true);
300
301            // SIGUSR1 is used to interrupt long-running WASM code.
302            // It doesn't use NODEFER since, if a second interruption
303            // request comes in while one is already being processed,
304            // there's nothing meaningful we can do.
305            #[cfg(feature = "experimental-host-interrupt")]
306            register(&mut PREV_SIGUSR1, libc::SIGUSR1, false);
307
308            // x86 uses SIGFPE to report division by zero
309            if cfg!(target_arch = "x86") || cfg!(target_arch = "x86_64") {
310                register(&mut PREV_SIGFPE, libc::SIGFPE, true);
311            }
312
313            // On ARM, handle Unaligned Accesses.
314            // On Darwin, guard page accesses are raised as SIGBUS.
315            if cfg!(target_arch = "arm") || cfg!(target_vendor = "apple") {
316                register(&mut PREV_SIGBUS, libc::SIGBUS, true);
317            }
318
319            // This is necessary to support debugging under LLDB on Darwin.
320            // For more details see https://github.com/mono/mono/commit/8e75f5a28e6537e56ad70bf870b86e22539c2fb7
321            #[cfg(target_vendor = "apple")]
322            {
323                use mach2::exception_types::*;
324                use mach2::kern_return::*;
325                use mach2::port::*;
326                use mach2::thread_status::*;
327                use mach2::traps::*;
328                use mach2::mach_types::*;
329
330                unsafe extern "C" {
331                    fn task_set_exception_ports(
332                        task: task_t,
333                        exception_mask: exception_mask_t,
334                        new_port: mach_port_t,
335                        behavior: exception_behavior_t,
336                        new_flavor: thread_state_flavor_t,
337                    ) -> kern_return_t;
338                }
339
340                #[allow(non_snake_case)]
341                #[cfg(target_arch = "x86_64")]
342                let MACHINE_THREAD_STATE = x86_THREAD_STATE64;
343                #[allow(non_snake_case)]
344                #[cfg(target_arch = "aarch64")]
345                let MACHINE_THREAD_STATE = 6;
346
347                task_set_exception_ports(
348                    mach_task_self(),
349                    EXC_MASK_BAD_ACCESS | EXC_MASK_ARITHMETIC | EXC_MASK_BAD_INSTRUCTION,
350                    MACH_PORT_NULL,
351                    EXCEPTION_STATE_IDENTITY as exception_behavior_t,
352                    MACHINE_THREAD_STATE,
353                );
354            }
355        }}
356
357        unsafe extern "C" fn trap_handler(
358            signum: libc::c_int,
359            siginfo: *mut libc::siginfo_t,
360            context: *mut libc::c_void,
361        ) { unsafe {
362            let previous = match signum {
363                libc::SIGSEGV => &PREV_SIGSEGV,
364                libc::SIGBUS => &PREV_SIGBUS,
365                libc::SIGFPE => &PREV_SIGFPE,
366                libc::SIGILL => &PREV_SIGILL,
367                #[cfg(feature = "experimental-host-interrupt")]
368                libc::SIGUSR1 => &PREV_SIGUSR1,
369                _ => panic!("unknown signal: {signum}"),
370            };
371            // We try to get the fault address associated to this signal
372            let maybe_fault_address = match signum {
373                libc::SIGSEGV | libc::SIGBUS => {
374                    Some((*siginfo).si_addr() as usize)
375                }
376                _ => None,
377            };
378            let trap_code = match signum {
379                // check if it was cased by a UD and if the Trap info is a payload to it
380                libc::SIGILL => {
381                    let addr = (*siginfo).si_addr() as usize;
382                    process_illegal_op(addr)
383                }
384                #[cfg(feature = "experimental-host-interrupt")]
385                libc::SIGUSR1 => {
386                    // If we're not running WASM code from the specific store for which
387                    // an interrupt was requested, there's nothing to do.
388                    if !interrupt_registry::on_interrupted() {
389                        return;
390                    }
391                    Some(TrapCode::HostInterrupt)
392                }
393                _ => None,
394            };
395            let ucontext = &mut *(context as *mut ucontext_t);
396            let (pc, sp) = get_pc_sp(ucontext);
397            let handled = TrapHandlerContext::handle_trap(
398                pc,
399                sp,
400                maybe_fault_address,
401                trap_code,
402                |regs| update_context(ucontext, regs),
403                |handler| handler(signum, siginfo, context),
404            );
405
406            if handled {
407                return;
408            }
409
410            // If we're not running WASM code at all, there's nothing to
411            // do for an interrupt.
412            #[cfg(feature = "experimental-host-interrupt")]
413            if signum == libc::SIGUSR1 {
414                return;
415            }
416
417            // This signal is not for any compiled wasm code we expect, so we
418            // need to forward the signal to the next handler. If there is no
419            // next handler (SIG_IGN or SIG_DFL), then it's time to crash. To do
420            // this, we set the signal back to its original disposition and
421            // return. This will cause the faulting op to be re-executed which
422            // will crash in the normal way. If there is a next handler, call
423            // it. It will either crash synchronously, fix up the instruction
424            // so that execution can continue and return, or trigger a crash by
425            // returning the signal to it's original disposition and returning.
426            let previous = &*previous.as_ptr();
427            if previous.sa_flags & libc::SA_SIGINFO != 0 {
428                mem::transmute::<
429                    usize,
430                    extern "C" fn(libc::c_int, *mut libc::siginfo_t, *mut libc::c_void),
431                >(previous.sa_sigaction)(signum, siginfo, context)
432            } else if previous.sa_sigaction == libc::SIG_DFL
433            {
434                libc::sigaction(signum, previous, ptr::null_mut());
435            } else if previous.sa_sigaction != libc::SIG_IGN {
436                mem::transmute::<usize, extern "C" fn(libc::c_int)>(
437                    previous.sa_sigaction
438                )(signum)
439            }
440        }}
441
442        unsafe fn get_pc_sp(context: &ucontext_t) -> (usize, usize) {
443            let (pc, sp);
444            cfg_select! {
445                all(
446                    any(target_os = "linux", target_os = "android"),
447                    target_arch = "x86_64",
448                ) => {
449                    pc = context.uc_mcontext.gregs[libc::REG_RIP as usize] as usize;
450                    sp = context.uc_mcontext.gregs[libc::REG_RSP as usize] as usize;
451                }
452                all(
453                    any(target_os = "linux", target_os = "android"),
454                    target_arch = "x86",
455                ) => {
456                    pc = context.uc_mcontext.gregs[libc::REG_EIP as usize] as usize;
457                    sp = context.uc_mcontext.gregs[libc::REG_ESP as usize] as usize;
458                }
459                all(target_os = "freebsd", target_arch = "x86") => {
460                    pc = context.uc_mcontext.mc_eip as usize;
461                    sp = context.uc_mcontext.mc_esp as usize;
462                }
463                all(target_os = "freebsd", target_arch = "x86_64") => {
464                    pc = context.uc_mcontext.mc_rip as usize;
465                    sp = context.uc_mcontext.mc_rsp as usize;
466                }
467                all(target_vendor = "apple", target_arch = "x86_64") => {
468                    let mcontext = unsafe { &*context.uc_mcontext };
469                    pc = mcontext.__ss.__rip as usize;
470                    sp = mcontext.__ss.__rsp as usize;
471                }
472                all(
473                        any(target_os = "linux", target_os = "android"),
474                        target_arch = "aarch64",
475                    ) => {
476                    pc = context.uc_mcontext.pc as usize;
477                    sp = context.uc_mcontext.sp as usize;
478                }
479                all(
480                    any(target_os = "linux", target_os = "android"),
481                    target_arch = "arm",
482                ) => {
483                    pc = context.uc_mcontext.arm_pc as usize;
484                    sp = context.uc_mcontext.arm_sp as usize;
485                }
486                all(
487                    any(target_os = "linux", target_os = "android"),
488                    any(target_arch = "riscv64", target_arch = "riscv32"),
489                ) => {
490                    pc = context.uc_mcontext.__gregs[libc::REG_PC] as usize;
491                    sp = context.uc_mcontext.__gregs[libc::REG_SP] as usize;
492                }
493                all(target_vendor = "apple", target_arch = "aarch64") => {
494                    let mcontext = unsafe { &*context.uc_mcontext };
495                    pc = mcontext.__ss.__pc as usize;
496                    sp = mcontext.__ss.__sp as usize;
497                }
498                all(target_os = "freebsd", target_arch = "aarch64") => {
499                    pc = context.uc_mcontext.mc_gpregs.gp_elr as usize;
500                    sp = context.uc_mcontext.mc_gpregs.gp_sp as usize;
501                }
502                all(target_os = "linux", target_arch = "loongarch64") => {
503                    pc = context.uc_mcontext.__gregs[1] as usize;
504                    sp = context.uc_mcontext.__gregs[3] as usize;
505                }
506                all(target_os = "linux", target_arch = "powerpc64") => {
507                    pc = (*context.uc_mcontext.regs).nip as usize;
508                    sp = (*context.uc_mcontext.regs).gpr[1] as usize;
509                }
510                _ => {
511                    compile_error!("Unsupported platform");
512                }
513            };
514            (pc, sp)
515        }
516
517        unsafe fn update_context(context: &mut ucontext_t, regs: TrapHandlerRegs) {
518            cfg_select! {
519                all(
520                        any(target_os = "linux", target_os = "android"),
521                        target_arch = "x86_64",
522                    ) => {
523                    let TrapHandlerRegs { rip, rsp, rbp, rdi, rsi } = regs;
524                    context.uc_mcontext.gregs[libc::REG_RIP as usize] = rip as i64;
525                    context.uc_mcontext.gregs[libc::REG_RSP as usize] = rsp as i64;
526                    context.uc_mcontext.gregs[libc::REG_RBP as usize] = rbp as i64;
527                    context.uc_mcontext.gregs[libc::REG_RDI as usize] = rdi as i64;
528                    context.uc_mcontext.gregs[libc::REG_RSI as usize] = rsi as i64;
529                }
530                all(
531                    any(target_os = "linux", target_os = "android"),
532                    target_arch = "x86",
533                ) => {
534                    let TrapHandlerRegs { eip, esp, ebp, ecx, edx } = regs;
535                    context.uc_mcontext.gregs[libc::REG_EIP as usize] = eip as i32;
536                    context.uc_mcontext.gregs[libc::REG_ESP as usize] = esp as i32;
537                    context.uc_mcontext.gregs[libc::REG_EBP as usize] = ebp as i32;
538                    context.uc_mcontext.gregs[libc::REG_ECX as usize] = ecx as i32;
539                    context.uc_mcontext.gregs[libc::REG_EDX as usize] = edx as i32;
540                }
541                all(target_vendor = "apple", target_arch = "x86_64") => {
542                    let TrapHandlerRegs { rip, rsp, rbp, rdi, rsi } = regs;
543                    let mcontext = unsafe { &mut *context.uc_mcontext };
544                    mcontext.__ss.__rip = rip;
545                    mcontext.__ss.__rsp = rsp;
546                    mcontext.__ss.__rbp = rbp;
547                    mcontext.__ss.__rdi = rdi;
548                    mcontext.__ss.__rsi = rsi;
549                }
550                all(target_os = "freebsd", target_arch = "x86") => {
551                    let TrapHandlerRegs { eip, esp, ebp, ecx, edx } = regs;
552                    context.uc_mcontext.mc_eip = eip as libc::register_t;
553                    context.uc_mcontext.mc_esp = esp as libc::register_t;
554                    context.uc_mcontext.mc_ebp = ebp as libc::register_t;
555                    context.uc_mcontext.mc_ecx = ecx as libc::register_t;
556                    context.uc_mcontext.mc_edx = edx as libc::register_t;
557                }
558                all(target_os = "freebsd", target_arch = "x86_64") => {
559                    let TrapHandlerRegs { rip, rsp, rbp, rdi, rsi } = regs;
560                    context.uc_mcontext.mc_rip = rip as libc::register_t;
561                    context.uc_mcontext.mc_rsp = rsp as libc::register_t;
562                    context.uc_mcontext.mc_rbp = rbp as libc::register_t;
563                    context.uc_mcontext.mc_rdi = rdi as libc::register_t;
564                    context.uc_mcontext.mc_rsi = rsi as libc::register_t;
565                }
566                all(
567                        any(target_os = "linux", target_os = "android"),
568                        target_arch = "aarch64",
569                    ) => {
570                    let TrapHandlerRegs { pc, sp, x0, x1, x29, lr } = regs;
571                    context.uc_mcontext.pc = pc;
572                    context.uc_mcontext.sp = sp;
573                    context.uc_mcontext.regs[0] = x0;
574                    context.uc_mcontext.regs[1] = x1;
575                    context.uc_mcontext.regs[29] = x29;
576                    context.uc_mcontext.regs[30] = lr;
577                }
578                all(
579                        any(target_os = "linux", target_os = "android"),
580                        target_arch = "arm",
581                    ) => {
582                    let TrapHandlerRegs {
583                        pc,
584                        r0,
585                        r1,
586                        r7,
587                        r11,
588                        r13,
589                        r14,
590                        cpsr_thumb,
591                        cpsr_endian,
592                    } = regs;
593                    context.uc_mcontext.arm_pc = pc;
594                    context.uc_mcontext.arm_r0 = r0;
595                    context.uc_mcontext.arm_r1 = r1;
596                    context.uc_mcontext.arm_r7 = r7;
597                    context.uc_mcontext.arm_fp = r11;
598                    context.uc_mcontext.arm_sp = r13;
599                    context.uc_mcontext.arm_lr = r14;
600                    if cpsr_thumb {
601                        context.uc_mcontext.arm_cpsr |= 0x20;
602                    } else {
603                        context.uc_mcontext.arm_cpsr &= !0x20;
604                    }
605                    if cpsr_endian {
606                        context.uc_mcontext.arm_cpsr |= 0x200;
607                    } else {
608                        context.uc_mcontext.arm_cpsr &= !0x200;
609                    }
610                }
611                all(
612                    any(target_os = "linux", target_os = "android"),
613                    any(target_arch = "riscv64", target_arch = "riscv32"),
614                ) => {
615                    let TrapHandlerRegs { pc, ra, sp, a0, a1, s0 } = regs;
616                    context.uc_mcontext.__gregs[libc::REG_PC] = pc as libc::c_ulong;
617                    context.uc_mcontext.__gregs[libc::REG_RA] = ra as libc::c_ulong;
618                    context.uc_mcontext.__gregs[libc::REG_SP] = sp as libc::c_ulong;
619                    context.uc_mcontext.__gregs[libc::REG_A0] = a0 as libc::c_ulong;
620                    context.uc_mcontext.__gregs[libc::REG_A0 + 1] = a1 as libc::c_ulong;
621                    context.uc_mcontext.__gregs[libc::REG_S0] = s0 as libc::c_ulong;
622                }
623                all(target_vendor = "apple", target_arch = "aarch64") => {
624                    let TrapHandlerRegs { pc, sp, x0, x1, x29, lr } = regs;
625                    let mcontext = unsafe { &mut *context.uc_mcontext };
626                    mcontext.__ss.__pc = pc;
627                    mcontext.__ss.__sp = sp;
628                    mcontext.__ss.__x[0] = x0;
629                    mcontext.__ss.__x[1] = x1;
630                    mcontext.__ss.__fp = x29;
631                    mcontext.__ss.__lr = lr;
632                }
633                all(target_os = "freebsd", target_arch = "aarch64") => {
634                    let TrapHandlerRegs { pc, sp, x0, x1, x29, lr } = regs;
635                    context.uc_mcontext.mc_gpregs.gp_elr = pc as libc::register_t;
636                    context.uc_mcontext.mc_gpregs.gp_sp = sp as libc::register_t;
637                    context.uc_mcontext.mc_gpregs.gp_x[0] = x0 as libc::register_t;
638                    context.uc_mcontext.mc_gpregs.gp_x[1] = x1 as libc::register_t;
639                    context.uc_mcontext.mc_gpregs.gp_x[29] = x29 as libc::register_t;
640                    context.uc_mcontext.mc_gpregs.gp_lr = lr as libc::register_t;
641                }
642                all(target_os = "linux", target_arch = "loongarch64") => {
643                    let TrapHandlerRegs { pc, sp, a0, a1, fp, ra } = regs;
644                    context.uc_mcontext.__pc = pc;
645                    context.uc_mcontext.__gregs[1] = ra;
646                    context.uc_mcontext.__gregs[3] = sp;
647                    context.uc_mcontext.__gregs[4] = a0;
648                    context.uc_mcontext.__gregs[5] = a1;
649                    context.uc_mcontext.__gregs[22] = fp;
650                }
651                all(target_os = "linux", target_arch = "powerpc64") => {
652                    let TrapHandlerRegs { pc, sp, r3, r4, r31, lr } = regs;
653                    (*context.uc_mcontext.regs).nip = pc;
654                    (*context.uc_mcontext.regs).gpr[1] = sp;
655                    (*context.uc_mcontext.regs).gpr[3] = r3;
656                    (*context.uc_mcontext.regs).gpr[4] = r4;
657                    (*context.uc_mcontext.regs).gpr[31] = r31;
658                    (*context.uc_mcontext.regs).link = lr;
659                }
660                _ => {
661                    compile_error!("Unsupported platform");
662                }
663            };
664        }
665    }
666    target_os = "windows" => {
667        use windows_sys::Win32::System::Diagnostics::Debug::{
668            AddVectoredExceptionHandler,
669            CONTEXT,
670            EXCEPTION_CONTINUE_EXECUTION,
671            EXCEPTION_CONTINUE_SEARCH,
672            EXCEPTION_POINTERS,
673        };
674        use windows_sys::Win32::Foundation::{
675            EXCEPTION_ACCESS_VIOLATION,
676            EXCEPTION_ILLEGAL_INSTRUCTION,
677            EXCEPTION_INT_DIVIDE_BY_ZERO,
678            EXCEPTION_INT_OVERFLOW,
679            EXCEPTION_STACK_OVERFLOW,
680        };
681
682        unsafe fn platform_init() {
683            unsafe {
684                // our trap handler needs to go first, so that we can recover from
685                // wasm faults and continue execution, so pass `1` as a true value
686                // here.
687                let handler = AddVectoredExceptionHandler(1, Some(exception_handler));
688                if handler.is_null() {
689                    panic!("failed to add exception handler: {}", io::Error::last_os_error());
690                }
691            }
692        }
693
694        unsafe extern "system" fn exception_handler(
695            exception_info: *mut EXCEPTION_POINTERS
696        ) -> i32 {
697            unsafe {
698                // Check the kind of exception, since we only handle a subset within
699                // wasm code. If anything else happens we want to defer to whatever
700                // the rest of the system wants to do for this exception.
701                let record = &*(*exception_info).ExceptionRecord;
702                if record.ExceptionCode != EXCEPTION_ACCESS_VIOLATION &&
703                    record.ExceptionCode != EXCEPTION_ILLEGAL_INSTRUCTION &&
704                    record.ExceptionCode != EXCEPTION_STACK_OVERFLOW &&
705                    record.ExceptionCode != EXCEPTION_INT_DIVIDE_BY_ZERO &&
706                    record.ExceptionCode != EXCEPTION_INT_OVERFLOW
707                {
708                    return EXCEPTION_CONTINUE_SEARCH;
709                }
710
711                // FIXME: this is what the previous C++ did to make sure that TLS
712                // works by the time we execute this trap handling code. This isn't
713                // exactly super easy to call from Rust though and it's not clear we
714                // necessarily need to do so. Leaving this here in case we need this
715                // in the future, but for now we can probably wait until we see a
716                // strange fault before figuring out how to reimplement this in
717                // Rust.
718                //
719                // if (!NtCurrentTeb()->Reserved1[sThreadLocalArrayPointerIndex]) {
720                //     return EXCEPTION_CONTINUE_SEARCH;
721                // }
722
723                let context = &mut *(*exception_info).ContextRecord;
724                let (pc, sp) = get_pc_sp(context);
725
726                // We try to get the fault address associated to this exception.
727                let maybe_fault_address = match record.ExceptionCode {
728                    EXCEPTION_ACCESS_VIOLATION => Some(record.ExceptionInformation[1]),
729                    EXCEPTION_STACK_OVERFLOW => Some(sp),
730                    _ => None,
731                };
732                let trap_code = match record.ExceptionCode {
733                    // check if it was cased by a UD and if the Trap info is a payload to it
734                    EXCEPTION_ILLEGAL_INSTRUCTION => {
735                        process_illegal_op(pc)
736                    }
737                    _ => None,
738                };
739                // This is basically the same as the unix version above, only with a
740                // few parameters tweaked here and there.
741                let handled = TrapHandlerContext::handle_trap(
742                    pc,
743                    sp,
744                    maybe_fault_address,
745                    trap_code,
746                    |regs| update_context(context, regs),
747                    |handler| handler(exception_info),
748                );
749
750                if handled {
751                    EXCEPTION_CONTINUE_EXECUTION
752                } else {
753                    EXCEPTION_CONTINUE_SEARCH
754                }
755            }
756        }
757
758        unsafe fn get_pc_sp(context: &CONTEXT) -> (usize, usize) {
759            let (pc, sp);
760            cfg_select! {
761                target_arch = "x86_64" => {
762                    pc = context.Rip as usize;
763                    sp = context.Rsp as usize;
764                }
765                target_arch = "x86" => {
766                    pc = context.Eip as usize;
767                    sp = context.Esp as usize;
768                }
769                _ => {
770                    compile_error!("Unsupported platform");
771                }
772            };
773            (pc, sp)
774        }
775
776        unsafe fn update_context(context: &mut CONTEXT, regs: TrapHandlerRegs) {
777            cfg_select! {
778                target_arch = "x86_64" => {
779                    let TrapHandlerRegs { rip, rsp, rbp, rdi, rsi } = regs;
780                    context.Rip = rip;
781                    context.Rsp = rsp;
782                    context.Rbp = rbp;
783                    context.Rdi = rdi;
784                    context.Rsi = rsi;
785                }
786                target_arch = "x86" => {
787                    let TrapHandlerRegs { eip, esp, ebp, ecx, edx } = regs;
788                    context.Eip = eip;
789                    context.Esp = esp;
790                    context.Ebp = ebp;
791                    context.Ecx = ecx;
792                    context.Edx = edx;
793                }
794                _ => {
795                    compile_error!("Unsupported platform");
796                }
797            };
798        }
799    }
800}
801
802/// This function is required to be called before any WebAssembly is entered.
803/// This will configure global state such as signal handlers to prepare the
804/// process to receive wasm traps.
805///
806/// This function must not only be called globally once before entering
807/// WebAssembly but it must also be called once-per-thread that enters
808/// WebAssembly. Currently in wasmer's integration this function is called on
809/// creation of a `Store`.
810pub fn init_traps() {
811    // Miri cannot call `sigaction`/`sigemptyset`, and nothing under Miri
812    // executes compiled Wasm, so there is no trap for a handler to catch.
813    // Without this, building a `Store` at all is out of reach there, and the
814    // store-context tests that need one cannot run.
815    if cfg!(miri) {
816        return;
817    }
818    static INIT: Once = Once::new();
819    INIT.call_once(|| unsafe {
820        platform_init();
821    });
822}
823
824/// Raises a user-defined trap immediately.
825///
826/// This function performs as-if a wasm trap was just executed, only the trap
827/// has a dynamic payload associated with it which is user-provided. This trap
828/// payload is then returned from `catch_traps` below.
829///
830/// # Safety
831///
832/// Only safe to call when wasm code is on the stack, aka `catch_traps` must
833/// have been previous called and not yet returned.
834/// Additionally no Rust destructors may be on the stack.
835/// They will be skipped and not executed.
836pub unsafe fn raise_user_trap(data: Box<dyn Error + Send + Sync>) -> ! {
837    unsafe { unwind_with(UnwindReason::UserTrap(data)) }
838}
839
840/// Raises a trap from inside library code immediately.
841///
842/// This function performs as-if a wasm trap was just executed. This trap
843/// payload is then returned from `catch_traps` below.
844///
845/// # Safety
846///
847/// Only safe to call when wasm code is on the stack, aka `catch_traps` must
848/// have been previous called and not yet returned.
849/// Additionally no Rust destructors may be on the stack.
850/// They will be skipped and not executed.
851pub unsafe fn raise_lib_trap(trap: Trap) -> ! {
852    unsafe { unwind_with(UnwindReason::LibTrap(trap)) }
853}
854
855/// Carries a Rust panic across wasm code and resumes the panic on the other
856/// side.
857///
858/// # Safety
859///
860/// Only safe to call when wasm code is on the stack, aka `catch_traps` must
861/// have been previously called and not returned. Additionally no Rust destructors may be on the
862/// stack. They will be skipped and not executed.
863pub unsafe fn resume_panic(payload: Box<dyn Any + Send>) -> ! {
864    unsafe { unwind_with(UnwindReason::Panic(payload)) }
865}
866
867/// Catches any wasm traps that happen within the execution of `closure`,
868/// returning them as a `Result`.
869///
870/// # Safety
871///
872/// Highly unsafe since `closure` won't have any dtors run.
873pub unsafe fn catch_traps<F, R: 'static>(
874    trap_handler: Option<*const TrapHandlerFn<'static>>,
875    config: &VMConfig,
876    closure: F,
877) -> Result<R, Trap>
878where
879    F: FnOnce() -> R + 'static,
880{
881    // Ensure that per-thread initialization is done.
882    lazy_per_thread_init()?;
883    let stack_size = config
884        .wasm_stack_size
885        .unwrap_or_else(|| DEFAULT_STACK_SIZE.load(Ordering::Relaxed));
886    on_wasm_stack(stack_size, trap_handler, closure).map_err(UnwindReason::into_trap)
887}
888
889// We need two separate thread-local variables here:
890// - YIELDER is set within the new stack and is used to unwind back to the root
891//   of the stack from inside it.
892// - TRAP_HANDLER is set from outside the new stack and is solely used from
893//   signal handlers. It must be atomic since it is used by signal handlers.
894//
895// We also do per-thread signal stack initialization on the first time
896// TRAP_HANDLER is accessed.
897thread_local! {
898    static YIELDER: Cell<Option<NonNull<Yielder<(), UnwindReason>>>> = const { Cell::new(None) };
899    static TRAP_HANDLER: AtomicPtr<TrapHandlerContext> = const { AtomicPtr::new(ptr::null_mut()) };
900}
901
902/// Read-only information that is used by signal handlers to handle and recover
903/// from traps.
904#[allow(clippy::type_complexity)]
905struct TrapHandlerContext {
906    inner: *const u8,
907    handle_trap: fn(
908        *const u8,
909        usize,
910        usize,
911        Option<usize>,
912        Option<TrapCode>,
913        &mut dyn FnMut(TrapHandlerRegs),
914    ) -> bool,
915    custom_trap: Option<*const TrapHandlerFn<'static>>,
916}
917struct TrapHandlerContextInner<T> {
918    /// Information about the currently running coroutine. This is used to
919    /// reset execution to the root of the coroutine when a trap is handled.
920    coro_trap_handler: CoroutineTrapHandler<Result<T, UnwindReason>>,
921}
922
923impl TrapHandlerContext {
924    /// Runs the given function with a trap handler context. The previous
925    /// trap handler context is preserved and restored afterwards.
926    fn install<T, R>(
927        custom_trap: Option<*const TrapHandlerFn<'static>>,
928        coro_trap_handler: CoroutineTrapHandler<Result<T, UnwindReason>>,
929        f: impl FnOnce() -> R,
930    ) -> R {
931        // Type-erase the trap handler function so that it can be placed in TLS.
932        fn func<T>(
933            ptr: *const u8,
934            pc: usize,
935            sp: usize,
936            maybe_fault_address: Option<usize>,
937            trap_code: Option<TrapCode>,
938            update_regs: &mut dyn FnMut(TrapHandlerRegs),
939        ) -> bool {
940            unsafe {
941                (*(ptr as *const TrapHandlerContextInner<T>)).handle_trap(
942                    pc,
943                    sp,
944                    maybe_fault_address,
945                    trap_code,
946                    update_regs,
947                )
948            }
949        }
950        let inner = TrapHandlerContextInner { coro_trap_handler };
951        let ctx = Self {
952            inner: &inner as *const _ as *const u8,
953            handle_trap: func::<T>,
954            custom_trap,
955        };
956
957        compiler_fence(Ordering::Release);
958        let prev = TRAP_HANDLER.with(|ptr| {
959            let prev = ptr.load(Ordering::Relaxed);
960            ptr.store(&ctx as *const Self as *mut Self, Ordering::Relaxed);
961            prev
962        });
963
964        defer! {
965            TRAP_HANDLER.with(|ptr| ptr.store(prev, Ordering::Relaxed));
966            compiler_fence(Ordering::Acquire);
967        }
968
969        f()
970    }
971
972    /// Attempts to handle the trap if it's a wasm trap.
973    unsafe fn handle_trap(
974        pc: usize,
975        sp: usize,
976        maybe_fault_address: Option<usize>,
977        trap_code: Option<TrapCode>,
978        mut update_regs: impl FnMut(TrapHandlerRegs),
979        call_handler: impl Fn(&TrapHandlerFn<'static>) -> bool,
980    ) -> bool {
981        unsafe {
982            let ptr = TRAP_HANDLER.with(|ptr| ptr.load(Ordering::Relaxed));
983            if ptr.is_null() {
984                return false;
985            }
986
987            let ctx = &*ptr;
988
989            // Check if this trap is handled by a custom trap handler.
990            if let Some(trap_handler) = ctx.custom_trap
991                && call_handler(&*trap_handler)
992            {
993                return true;
994            }
995
996            (ctx.handle_trap)(
997                ctx.inner,
998                pc,
999                sp,
1000                maybe_fault_address,
1001                trap_code,
1002                &mut update_regs,
1003            )
1004        }
1005    }
1006}
1007
1008impl<T> TrapHandlerContextInner<T> {
1009    unsafe fn handle_trap(
1010        &self,
1011        pc: usize,
1012        sp: usize,
1013        maybe_fault_address: Option<usize>,
1014        trap_code: Option<TrapCode>,
1015        update_regs: &mut dyn FnMut(TrapHandlerRegs),
1016    ) -> bool {
1017        unsafe {
1018            // Check if this trap occurred while executing on the Wasm stack. We can
1019            // only recover from traps if that is the case.
1020            if !self.coro_trap_handler.stack_ptr_in_bounds(sp) {
1021                return false;
1022            }
1023
1024            let signal_trap = trap_code.or_else(|| {
1025                maybe_fault_address.map(|addr| {
1026                    if self.coro_trap_handler.stack_ptr_in_bounds(addr) {
1027                        TrapCode::StackOverflow
1028                    } else {
1029                        TrapCode::HeapAccessOutOfBounds
1030                    }
1031                })
1032            });
1033
1034            // Don't try to generate a backtrace for stack overflows: unwinding
1035            // information is often not precise enough to properly describe what is
1036            // happening during a function prologue, which can lead the unwinder to
1037            // read invalid memory addresses.
1038            //
1039            // See: https://github.com/rust-lang/backtrace-rs/pull/357
1040            let backtrace = if signal_trap == Some(TrapCode::StackOverflow) {
1041                Backtrace::from(vec![])
1042            } else {
1043                Backtrace::new_unresolved()
1044            };
1045
1046            // Set up the register state for exception return to force the
1047            // coroutine to return to its caller with UnwindReason::WasmTrap.
1048            let unwind = UnwindReason::WasmTrap {
1049                backtrace,
1050                signal_trap,
1051                pc,
1052            };
1053            let regs = self
1054                .coro_trap_handler
1055                .setup_trap_handler(move || Err(unwind));
1056            update_regs(regs);
1057            true
1058        }
1059    }
1060}
1061
1062unsafe fn unwind_with(reason: UnwindReason) -> ! {
1063    unsafe {
1064        let yielder = YIELDER
1065            .with(|cell| cell.replace(None))
1066            .expect("not running on Wasm stack");
1067
1068        yielder.as_ref().suspend(reason);
1069
1070        // on_wasm_stack will forcibly reset the coroutine stack after yielding.
1071        unreachable!();
1072    }
1073}
1074
1075/// Runs the given function on a separate stack so that its stack usage can be
1076/// bounded. Stack overflows and other traps can be caught and execution
1077/// returned to the root of the stack.
1078fn on_wasm_stack<F: FnOnce() -> T + 'static, T: 'static>(
1079    stack_size: usize,
1080    trap_handler: Option<*const TrapHandlerFn<'static>>,
1081    f: F,
1082) -> Result<T, UnwindReason> {
1083    // Reuse a cached stack — TLS first (atomic-free hot path), then the
1084    // cross-thread overflow pool, then allocate fresh. Size mismatches
1085    // (e.g. after `drain_stack_pool()` + a stack-size change) are filtered
1086    // inside `acquire_stack`. `base() - limit()` is the full mmap region
1087    // (including guard page), which is always >= the requested size for
1088    // stacks allocated with that size.
1089    let stack = acquire_stack(stack_size);
1090    let mut stack = scopeguard::guard(stack, release_stack);
1091
1092    // Create a coroutine with a new stack to run the function on.
1093    let coro = ScopedCoroutine::with_stack(&mut *stack, move |yielder, ()| {
1094        // Save the yielder to TLS so that it can be used later.
1095        YIELDER.with(|cell| cell.set(Some(yielder.into())));
1096
1097        Ok(f())
1098    });
1099
1100    // Ensure that YIELDER is reset on exit even if the coroutine panics,
1101    defer! {
1102        YIELDER.with(|cell| cell.set(None));
1103    }
1104
1105    coro.scope(|mut coro_ref| {
1106        // Set up metadata for the trap handler for the duration of the coroutine
1107        // execution. This is restored to its previous value afterwards.
1108        TrapHandlerContext::install(trap_handler, coro_ref.trap_handler(), || {
1109            match coro_ref.resume(()) {
1110                CoroutineResult::Yield(trap) => {
1111                    // This came from unwind_with which requires that there be only
1112                    // Wasm code on the stack.
1113                    unsafe {
1114                        coro_ref.force_reset();
1115                    }
1116                    Err(trap)
1117                }
1118                CoroutineResult::Return(result) => result,
1119            }
1120        })
1121    })
1122}
1123
1124/// When executing on the Wasm stack, temporarily switch back to the host stack
1125/// to perform an operation that should not be constrained by the Wasm stack
1126/// limits.
1127///
1128/// This is particularly important since the usage of the Wasm stack is under
1129/// the control of untrusted code. Malicious code could artificially induce a
1130/// stack overflow in the middle of a sensitive host operations (e.g. growing
1131/// a memory) which would be hard to recover from.
1132pub fn on_host_stack<F: FnOnce() -> T, T>(f: F) -> T {
1133    // Reset YIEDER to None for the duration of this call to indicate that we
1134    // are no longer on the Wasm stack.
1135    let yielder_ptr = YIELDER.with(|cell| cell.replace(None));
1136
1137    // If we are already on the host stack, execute the function directly. This
1138    // happens if a host function is called directly from the API.
1139    let yielder = match yielder_ptr {
1140        Some(ptr) => unsafe { ptr.as_ref() },
1141        None => return f(),
1142    };
1143
1144    // Restore YIELDER upon exiting normally or unwinding.
1145    defer! {
1146        YIELDER.with(|cell| cell.set(yielder_ptr));
1147    }
1148
1149    // on_parent_stack requires the closure to be Send so that the Yielder
1150    // cannot be called from the parent stack. This is not a problem for us
1151    // since we don't expose the Yielder.
1152    struct SendWrapper<T>(T);
1153    unsafe impl<T> Send for SendWrapper<T> {}
1154    let wrapped = SendWrapper(f);
1155    yielder.on_parent_stack(move || {
1156        let wrapped = wrapped;
1157        (wrapped.0)()
1158    })
1159}
1160
1161#[cfg(windows)]
1162pub fn lazy_per_thread_init() -> Result<(), Trap> {
1163    // We need additional space on the stack to handle stack overflow
1164    // exceptions. Rust's initialization code sets this to 0x5000 but this
1165    // seems to be insufficient in practice.
1166    use windows_sys::Win32::System::Threading::SetThreadStackGuarantee;
1167    if unsafe { SetThreadStackGuarantee(&mut 0x10000) } == 0 {
1168        panic!("failed to set thread stack guarantee");
1169    }
1170
1171    Ok(())
1172}
1173
1174/// A module for registering a custom alternate signal stack (sigaltstack).
1175///
1176/// Rust's libstd installs an alternate stack with size `SIGSTKSZ`, which is not
1177/// always large enough for our signal handling code. Override it by creating
1178/// and registering our own alternate stack that is large enough and has a guard
1179/// page.
1180#[cfg(unix)]
1181pub fn lazy_per_thread_init() -> Result<(), Trap> {
1182    use std::ptr::null_mut;
1183
1184    thread_local! {
1185        /// Thread-local state is lazy-initialized on the first time it's used,
1186        /// and dropped when the thread exits.
1187        static TLS: Tls = unsafe { init_sigstack() };
1188    }
1189
1190    /// The size of the sigaltstack (not including the guard, which will be
1191    /// added). Make this large enough to run our signal handlers.
1192    const MIN_STACK_SIZE: usize = ByteSize::kib(64).as_u64() as usize;
1193
1194    enum Tls {
1195        OutOfMemory,
1196        Allocated {
1197            mmap_ptr: *mut libc::c_void,
1198            mmap_size: usize,
1199        },
1200        BigEnough,
1201    }
1202
1203    unsafe fn init_sigstack() -> Tls {
1204        unsafe {
1205            // Check to see if the existing sigaltstack, if it exists, is big
1206            // enough. If so we don't need to allocate our own.
1207            let mut old_stack = mem::zeroed();
1208            let r = libc::sigaltstack(ptr::null(), &mut old_stack);
1209            assert_eq!(r, 0, "learning about sigaltstack failed");
1210            if old_stack.ss_flags & libc::SS_DISABLE == 0 && old_stack.ss_size >= MIN_STACK_SIZE {
1211                return Tls::BigEnough;
1212            }
1213
1214            // ... but failing that we need to allocate our own, so do all that
1215            // here.
1216            let page_size: usize = region::page::size();
1217            let guard_size = page_size;
1218            let alloc_size = guard_size + MIN_STACK_SIZE;
1219
1220            let ptr = libc::mmap(
1221                null_mut(),
1222                alloc_size,
1223                libc::PROT_NONE,
1224                libc::MAP_PRIVATE | libc::MAP_ANON,
1225                -1,
1226                0,
1227            );
1228            if ptr == libc::MAP_FAILED {
1229                return Tls::OutOfMemory;
1230            }
1231
1232            // Prepare the stack with readable/writable memory and then register it
1233            // with `sigaltstack`.
1234            let stack_ptr = (ptr as usize + guard_size) as *mut libc::c_void;
1235            let r = libc::mprotect(
1236                stack_ptr,
1237                MIN_STACK_SIZE,
1238                libc::PROT_READ | libc::PROT_WRITE,
1239            );
1240            assert_eq!(r, 0, "mprotect to configure memory for sigaltstack failed");
1241            let new_stack = libc::stack_t {
1242                ss_sp: stack_ptr,
1243                ss_flags: 0,
1244                ss_size: MIN_STACK_SIZE,
1245            };
1246            let r = libc::sigaltstack(&new_stack, ptr::null_mut());
1247            assert_eq!(r, 0, "registering new sigaltstack failed");
1248
1249            Tls::Allocated {
1250                mmap_ptr: ptr,
1251                mmap_size: alloc_size,
1252            }
1253        }
1254    }
1255
1256    // Ensure TLS runs its initializer and return an error if it failed to
1257    // set up a separate stack for signal handlers.
1258    return TLS.with(|tls| {
1259        if let Tls::OutOfMemory = tls {
1260            Err(Trap::oom())
1261        } else {
1262            Ok(())
1263        }
1264    });
1265
1266    impl Drop for Tls {
1267        fn drop(&mut self) {
1268            let (ptr, size) = match self {
1269                Self::Allocated {
1270                    mmap_ptr,
1271                    mmap_size,
1272                } => (*mmap_ptr, *mmap_size),
1273                _ => return,
1274            };
1275            unsafe {
1276                // Deallocate the stack memory.
1277                let r = libc::munmap(ptr, size);
1278                debug_assert_eq!(r, 0, "munmap failed during thread shutdown");
1279            }
1280        }
1281    }
1282}
1283
1284#[cfg(test)]
1285mod tests {
1286    use super::*;
1287    use std::sync::Mutex;
1288
1289    // Guards tests that mutate global state (DEFAULT_STACK_SIZE, STACK_POOL).
1290    // Rust runs tests in parallel by default; this mutex serializes them so
1291    // they don't step on each other.
1292    static GLOBAL_STATE: Mutex<()> = Mutex::new(());
1293
1294    /// Saves the current stack size and restores it on drop (even on panic).
1295    struct RestoreStackSize(usize);
1296    impl Drop for RestoreStackSize {
1297        fn drop(&mut self) {
1298            set_stack_size(self.0);
1299        }
1300    }
1301
1302    #[test]
1303    fn max_stack_size_is_100mb() {
1304        assert_eq!(MAX_STACK_SIZE, ByteSize::mib(100).as_u64() as usize);
1305    }
1306
1307    #[test]
1308    fn get_set_stack_size_roundtrip() {
1309        let _lock = GLOBAL_STATE.lock().unwrap();
1310        let _restore = RestoreStackSize(get_stack_size());
1311        let new_size = ByteSize::mib(4).as_u64() as usize;
1312        set_stack_size(new_size);
1313        assert_eq!(get_stack_size(), new_size);
1314    }
1315
1316    #[test]
1317    fn set_stack_size_clamps_to_min() {
1318        let _lock = GLOBAL_STATE.lock().unwrap();
1319        let _restore = RestoreStackSize(get_stack_size());
1320        set_stack_size(1); // way below 8 KiB minimum
1321        assert_eq!(get_stack_size(), ByteSize::kib(8).as_u64() as usize);
1322    }
1323
1324    #[test]
1325    fn set_stack_size_clamps_to_max() {
1326        let _lock = GLOBAL_STATE.lock().unwrap();
1327        let _restore = RestoreStackSize(get_stack_size());
1328        set_stack_size(usize::MAX);
1329        assert_eq!(get_stack_size(), MAX_STACK_SIZE);
1330    }
1331
1332    #[test]
1333    fn drain_stack_pool_empties_pool() {
1334        let _lock = GLOBAL_STATE.lock().unwrap();
1335        let stack = DefaultStack::new(ByteSize::mib(1).as_u64() as usize).unwrap();
1336        STACK_POOL.push(stack);
1337        assert!(!STACK_POOL.is_empty());
1338        drain_stack_pool();
1339        assert!(STACK_POOL.is_empty());
1340    }
1341
1342    #[test]
1343    fn drain_stack_pool_is_idempotent() {
1344        let _lock = GLOBAL_STATE.lock().unwrap();
1345        drain_stack_pool();
1346        drain_stack_pool(); // second call on empty pool should not panic
1347        assert!(STACK_POOL.is_empty());
1348    }
1349
1350    /// The stack pool is not size-aware, so after a stack size increase it keeps
1351    /// serving cached undersized stacks. `drain_stack_pool()` breaks the cycle.
1352    ///
1353    /// 1. A call fills the pool with 500 KiB stacks (simulating normal execution).
1354    /// 2. The caller doubles the default to 1 MiB (simulating overflow retry).
1355    /// 3. WITHOUT draining, the pool still hands back a 500 KiB stack — the
1356    ///    retry would overflow again, creating an infinite loop.
1357    /// 4. After `drain_stack_pool()`, the pool is empty and the next allocation
1358    ///    must use the new, larger size.
1359    #[test]
1360    fn pool_returns_stale_stack_without_drain() {
1361        let _lock = GLOBAL_STATE.lock().unwrap();
1362        let _restore = RestoreStackSize(get_stack_size());
1363        drain_stack_pool();
1364
1365        // --- Phase 1: simulate normal execution that returns a 500 KiB stack ---
1366        let small_size = ByteSize::kib(500).as_u64() as usize;
1367        let small_stack = DefaultStack::new(small_size).unwrap();
1368        STACK_POOL.push(small_stack);
1369
1370        // --- Phase 2: "overflow detected" — caller doubles the default ---
1371        let big_size = ByteSize::mib(1).as_u64() as usize;
1372        set_stack_size(big_size);
1373        assert_eq!(get_stack_size(), big_size);
1374
1375        // --- Phase 3: WITHOUT drain, pool still returns the old small stack ---
1376        // This is the bug: the caller asked for a bigger stack but the pool
1377        // serves a cached undersized one, causing the retry to overflow again.
1378        let stale = STACK_POOL.pop();
1379        assert!(
1380            stale.is_some(),
1381            "pool should still contain the old stack (the bug scenario)"
1382        );
1383
1384        // --- Phase 4: with drain, pool is empty — next alloc uses new size ---
1385        STACK_POOL.push(stale.unwrap());
1386        drain_stack_pool();
1387        assert!(
1388            STACK_POOL.pop().is_none(),
1389            "after drain, pool must be empty so a fresh stack is allocated at the new size"
1390        );
1391    }
1392
1393    /// `on_wasm_stack` discards undersized stacks from the pool and allocates
1394    /// a fresh one instead of blindly reusing whatever the pool returns.
1395    #[test]
1396    fn on_wasm_stack_discards_undersized_stack() {
1397        let _lock = GLOBAL_STATE.lock().unwrap();
1398        let _restore = RestoreStackSize(get_stack_size());
1399        drain_stack_pool();
1400        clear_tls_stack();
1401
1402        // Push an undersized stack into the pool.
1403        let small_size = ByteSize::kib(500).as_u64() as usize;
1404        let small_stack = DefaultStack::new(small_size).unwrap();
1405        STACK_POOL.push(small_stack);
1406
1407        // Request a larger stack via on_wasm_stack.
1408        let big_size = ByteSize::mib(1).as_u64() as usize;
1409        let result = on_wasm_stack(big_size, None, || 42);
1410
1411        assert_eq!(result.expect("on_wasm_stack should succeed"), 42);
1412        // The undersized stack was discarded; the correctly-sized stack
1413        // allocated for the call now lives in the TLS cache (the hot path).
1414        // It will end up in the global pool only on thread exit or eviction.
1415        let returned = TLS_STACK
1416            .with(|cache| cache.0.take())
1417            .or_else(|| STACK_POOL.pop())
1418            .expect("stack should have been returned to TLS cache or pool");
1419        assert!(
1420            returned.size() >= big_size,
1421            "returned stack must be at least as large as the requested size"
1422        );
1423
1424        // Ensure no residual TLS state leaks into other tests sharing the
1425        // runner thread. `take()` above already cleared the slot, but be
1426        // explicit so future edits cannot drop this guarantee silently.
1427        clear_tls_stack();
1428    }
1429
1430    /// After a wasm call, the freshly-used stack stays in the thread-local
1431    /// cache so subsequent calls on the same thread reuse it without touching
1432    /// the global SegQueue.
1433    #[test]
1434    fn tls_stack_caches_after_first_call() {
1435        let _lock = GLOBAL_STATE.lock().unwrap();
1436        let _restore = RestoreStackSize(get_stack_size());
1437        drain_stack_pool();
1438        clear_tls_stack();
1439
1440        let size = get_stack_size();
1441
1442        // First call: TLS + pool both empty → allocate fresh; stack ends in TLS.
1443        assert!(on_wasm_stack(size, None, || ()).is_ok());
1444        assert!(
1445            STACK_POOL.is_empty(),
1446            "pool should still be empty after a TLS-served call"
1447        );
1448
1449        // Verify TLS holds a stack, then put it back.
1450        let cached_present = TLS_STACK.with(|cache| {
1451            let taken = cache.0.take();
1452            let present = taken.is_some();
1453            cache.0.set(taken);
1454            present
1455        });
1456        assert!(cached_present, "TLS slot should hold the post-call stack");
1457
1458        // Second call should consume from TLS; pool stays empty.
1459        assert!(on_wasm_stack(size, None, || ()).is_ok());
1460        assert!(
1461            STACK_POOL.is_empty(),
1462            "second call must not push to the global pool"
1463        );
1464        let still_cached = TLS_STACK.with(|cache| {
1465            let taken = cache.0.take();
1466            let present = taken.is_some();
1467            cache.0.set(taken);
1468            present
1469        });
1470        assert!(
1471            still_cached,
1472            "TLS slot should still hold a stack after the second call"
1473        );
1474
1475        // Cleanup: clear TLS so we don't leak into other tests. The cached
1476        // stack here is dropped rather than returned to the pool; the next
1477        // test starts with `drain_stack_pool()` anyway, so there is no
1478        // observable difference.
1479        clear_tls_stack();
1480    }
1481
1482    /// On thread exit, the TLS cache's `Drop` impl returns the held stack to
1483    /// the global pool so memory cycles correctly across thread lifetimes.
1484    #[test]
1485    fn tls_stack_returns_to_pool_on_thread_exit() {
1486        // Keep other tests from draining the pool or changing the stack size
1487        // until the worker exits and we inspect its returned stack. The worker
1488        // calls on_wasm_stack without acquiring this test-only mutex.
1489        let _lock = GLOBAL_STATE.lock().unwrap();
1490        let _restore = RestoreStackSize(get_stack_size());
1491        drain_stack_pool();
1492        clear_tls_stack();
1493
1494        let size = get_stack_size();
1495        let handle = std::thread::spawn(move || {
1496            assert!(on_wasm_stack(size, None, || ()).is_ok());
1497        });
1498        handle.join().unwrap();
1499
1500        // The spawned thread's TLS cache was dropped on join; the stack must
1501        // have made it back to the global pool.
1502        let returned = STACK_POOL
1503            .pop()
1504            .expect("thread exit should return TLS-cached stack to the global pool");
1505        assert!(returned.size() >= size);
1506    }
1507
1508    // -----------------------------------------------------------------
1509    // Test helpers
1510    // -----------------------------------------------------------------
1511
1512    /// Clears the current thread's TLS slot so tests don't see state from
1513    /// previous tests (they share the same thread under cargo test's
1514    /// per-test serialization via `GLOBAL_STATE`).
1515    fn clear_tls_stack() {
1516        TLS_STACK.with(|cache| cache.0.set(None));
1517    }
1518
1519    /// `base().get() - limit().get()` (i.e. `Stack::size`) is constant per
1520    /// `DefaultStack` instance, but `base().get()` itself uniquely identifies
1521    /// the mmap allocation. We use it as a cheap identity check to see which
1522    /// stack was returned by acquire/release.
1523    fn stack_id(stack: &DefaultStack) -> usize {
1524        stack.base().get()
1525    }
1526
1527    // -----------------------------------------------------------------
1528    // acquire_stack mechanics
1529    // -----------------------------------------------------------------
1530
1531    #[test]
1532    fn acquire_allocates_fresh_when_tls_and_pool_empty() {
1533        let _lock = GLOBAL_STATE.lock().unwrap();
1534        let _restore = RestoreStackSize(get_stack_size());
1535        drain_stack_pool();
1536        clear_tls_stack();
1537
1538        let size = get_stack_size();
1539        let stack = acquire_stack(size);
1540        assert!(
1541            stack.size() >= size,
1542            "freshly allocated stack must satisfy min_size"
1543        );
1544
1545        drop(stack);
1546        clear_tls_stack();
1547        drain_stack_pool();
1548    }
1549
1550    #[test]
1551    fn acquire_prefers_tls_over_pool() {
1552        let _lock = GLOBAL_STATE.lock().unwrap();
1553        let _restore = RestoreStackSize(get_stack_size());
1554        drain_stack_pool();
1555        clear_tls_stack();
1556
1557        let size = get_stack_size();
1558        let tls_stack = DefaultStack::new(size).unwrap();
1559        let tls_id = stack_id(&tls_stack);
1560        TLS_STACK.with(|cache| cache.0.set(Some(tls_stack)));
1561
1562        let pool_stack = DefaultStack::new(size).unwrap();
1563        let pool_id = stack_id(&pool_stack);
1564        STACK_POOL.push(pool_stack);
1565
1566        let got = acquire_stack(size);
1567        assert_eq!(stack_id(&got), tls_id, "acquire must prefer TLS over pool");
1568        assert_ne!(stack_id(&got), pool_id);
1569
1570        drop(got);
1571        clear_tls_stack();
1572        drain_stack_pool();
1573    }
1574
1575    #[test]
1576    fn acquire_uses_pool_when_tls_empty() {
1577        let _lock = GLOBAL_STATE.lock().unwrap();
1578        let _restore = RestoreStackSize(get_stack_size());
1579        drain_stack_pool();
1580        clear_tls_stack();
1581
1582        let size = get_stack_size();
1583        let pool_stack = DefaultStack::new(size).unwrap();
1584        let pool_id = stack_id(&pool_stack);
1585        STACK_POOL.push(pool_stack);
1586
1587        let got = acquire_stack(size);
1588        assert_eq!(
1589            stack_id(&got),
1590            pool_id,
1591            "acquire must consume from pool when TLS is empty"
1592        );
1593        assert!(
1594            STACK_POOL.is_empty(),
1595            "pool stack must be removed when used"
1596        );
1597
1598        drop(got);
1599        clear_tls_stack();
1600        drain_stack_pool();
1601    }
1602
1603    #[test]
1604    fn acquire_discards_undersized_tls_then_allocates() {
1605        let _lock = GLOBAL_STATE.lock().unwrap();
1606        let _restore = RestoreStackSize(get_stack_size());
1607        drain_stack_pool();
1608        clear_tls_stack();
1609
1610        let small_size = ByteSize::kib(512).as_u64() as usize;
1611        let undersized = DefaultStack::new(small_size).unwrap();
1612        TLS_STACK.with(|cache| cache.0.set(Some(undersized)));
1613
1614        let big_size = ByteSize::mib(2).as_u64() as usize;
1615        let got = acquire_stack(big_size);
1616
1617        // The acquired stack must be at least the requested size. We do NOT
1618        // compare base addresses: the OS can reuse a freshly munmap'd
1619        // virtual address for the next mmap, so pointer identity is not a
1620        // reliable "is this a different stack" check across a drop+alloc.
1621        // The meaningful semantic is that the undersized stack was taken
1622        // out of rotation (TLS empty, not silently pushed to the pool) and
1623        // the returned stack is sized correctly.
1624        assert!(
1625            got.size() >= big_size,
1626            "acquired stack must satisfy big_size"
1627        );
1628        let tls_empty = TLS_STACK.with(|cache| {
1629            let s = cache.0.take();
1630            let empty = s.is_none();
1631            cache.0.set(s);
1632            empty
1633        });
1634        assert!(
1635            tls_empty,
1636            "undersized TLS stack must have been taken and discarded"
1637        );
1638        assert!(
1639            STACK_POOL.is_empty(),
1640            "undersized TLS stack must be discarded, not pushed to the pool",
1641        );
1642
1643        drop(got);
1644        clear_tls_stack();
1645        drain_stack_pool();
1646    }
1647
1648    #[test]
1649    fn acquire_discards_undersized_pool_then_allocates() {
1650        let _lock = GLOBAL_STATE.lock().unwrap();
1651        let _restore = RestoreStackSize(get_stack_size());
1652        drain_stack_pool();
1653        clear_tls_stack();
1654
1655        let small_size = ByteSize::kib(512).as_u64() as usize;
1656        let undersized = DefaultStack::new(small_size).unwrap();
1657        STACK_POOL.push(undersized);
1658
1659        let big_size = ByteSize::mib(2).as_u64() as usize;
1660        let got = acquire_stack(big_size);
1661
1662        // Same caveat as the TLS variant: mmap may reuse the virtual
1663        // address of the dropped undersized stack for the new big stack,
1664        // so we verify the semantic outcome — the pool was drained of the
1665        // undersized entry and the returned stack is sized correctly.
1666        assert!(
1667            got.size() >= big_size,
1668            "acquired stack must satisfy big_size"
1669        );
1670        assert!(
1671            STACK_POOL.is_empty(),
1672            "undersized pool stack must have been popped, filtered out and dropped",
1673        );
1674
1675        drop(got);
1676        clear_tls_stack();
1677        drain_stack_pool();
1678    }
1679
1680    // -----------------------------------------------------------------
1681    // release_stack mechanics
1682    // -----------------------------------------------------------------
1683
1684    #[test]
1685    fn release_into_empty_tls_caches_there() {
1686        let _lock = GLOBAL_STATE.lock().unwrap();
1687        drain_stack_pool();
1688        clear_tls_stack();
1689
1690        let size = get_stack_size();
1691        let stack = DefaultStack::new(size).unwrap();
1692        let id = stack_id(&stack);
1693        release_stack(stack);
1694
1695        let in_tls = TLS_STACK
1696            .with(|cache| cache.0.take())
1697            .expect("release into empty TLS should leave the stack in TLS");
1698        assert_eq!(stack_id(&in_tls), id);
1699        assert!(
1700            STACK_POOL.is_empty(),
1701            "pool must not be touched when TLS is empty"
1702        );
1703
1704        drain_stack_pool();
1705    }
1706
1707    #[test]
1708    fn release_into_occupied_tls_displaces_older_to_pool() {
1709        let _lock = GLOBAL_STATE.lock().unwrap();
1710        drain_stack_pool();
1711        clear_tls_stack();
1712
1713        let size = get_stack_size();
1714        let older = DefaultStack::new(size).unwrap();
1715        let older_id = stack_id(&older);
1716        TLS_STACK.with(|cache| cache.0.set(Some(older)));
1717
1718        let newer = DefaultStack::new(size).unwrap();
1719        let newer_id = stack_id(&newer);
1720        release_stack(newer);
1721
1722        let in_tls = TLS_STACK
1723            .with(|cache| cache.0.take())
1724            .expect("TLS should hold the newly-released stack");
1725        assert_eq!(
1726            stack_id(&in_tls),
1727            newer_id,
1728            "newer stack must displace into TLS"
1729        );
1730
1731        let displaced = STACK_POOL
1732            .pop()
1733            .expect("older stack should have been pushed to global pool");
1734        assert_eq!(
1735            stack_id(&displaced),
1736            older_id,
1737            "displaced stack must be the older one"
1738        );
1739
1740        drain_stack_pool();
1741    }
1742
1743    // -----------------------------------------------------------------
1744    // drain_stack_pool extended semantics
1745    // -----------------------------------------------------------------
1746
1747    #[test]
1748    fn drain_stack_pool_clears_calling_thread_tls_slot() {
1749        let _lock = GLOBAL_STATE.lock().unwrap();
1750        drain_stack_pool();
1751        clear_tls_stack();
1752
1753        let stack = DefaultStack::new(get_stack_size()).unwrap();
1754        TLS_STACK.with(|cache| cache.0.set(Some(stack)));
1755
1756        drain_stack_pool();
1757
1758        let tls_empty = TLS_STACK.with(|cache| cache.0.take().is_none());
1759        assert!(
1760            tls_empty,
1761            "drain_stack_pool must also clear current thread's TLS slot"
1762        );
1763        assert!(STACK_POOL.is_empty());
1764    }
1765
1766    // -----------------------------------------------------------------
1767    // on_wasm_stack functional behavior
1768    // -----------------------------------------------------------------
1769
1770    #[test]
1771    fn on_wasm_stack_passes_closure_value_back() {
1772        let _lock = GLOBAL_STATE.lock().unwrap();
1773        let _restore = RestoreStackSize(get_stack_size());
1774        drain_stack_pool();
1775        clear_tls_stack();
1776
1777        let r = on_wasm_stack(get_stack_size(), None, || 12345u32);
1778        assert_eq!(r.ok(), Some(12345));
1779
1780        clear_tls_stack();
1781        drain_stack_pool();
1782    }
1783
1784    #[test]
1785    fn on_wasm_stack_passes_owning_result_back() {
1786        let _lock = GLOBAL_STATE.lock().unwrap();
1787        let _restore = RestoreStackSize(get_stack_size());
1788        drain_stack_pool();
1789        clear_tls_stack();
1790
1791        // Use a heap-allocated value to verify the move-out path: the
1792        // closure produces a `Vec<u8>` that must travel from the coroutine
1793        // stack back to the host.
1794        let r = on_wasm_stack(get_stack_size(), None, || vec![0u8, 1, 2, 3, 4]);
1795        assert_eq!(r.ok(), Some(vec![0u8, 1, 2, 3, 4]));
1796
1797        clear_tls_stack();
1798        drain_stack_pool();
1799    }
1800
1801    #[test]
1802    fn many_calls_do_not_grow_global_pool() {
1803        let _lock = GLOBAL_STATE.lock().unwrap();
1804        let _restore = RestoreStackSize(get_stack_size());
1805        drain_stack_pool();
1806        clear_tls_stack();
1807
1808        // With TLS caching, repeated single-threaded calls must keep
1809        // reusing the same TLS stack and never push to the global pool.
1810        for _ in 0..1000 {
1811            assert!(on_wasm_stack(get_stack_size(), None, || ()).is_ok());
1812        }
1813        assert!(
1814            STACK_POOL.is_empty(),
1815            "1000 sequential calls should not grow the global pool (TLS handles reuse)"
1816        );
1817
1818        clear_tls_stack();
1819        drain_stack_pool();
1820    }
1821
1822    // -----------------------------------------------------------------
1823    // Trap and unwind paths
1824    // -----------------------------------------------------------------
1825
1826    #[test]
1827    fn raise_user_trap_yields_err() {
1828        let _lock = GLOBAL_STATE.lock().unwrap();
1829        let _restore = RestoreStackSize(get_stack_size());
1830        drain_stack_pool();
1831        clear_tls_stack();
1832
1833        let r: Result<(), UnwindReason> = on_wasm_stack(get_stack_size(), None, || unsafe {
1834            raise_user_trap(Box::new(io::Error::other("user trap from test")));
1835        });
1836        assert!(r.is_err(), "raise_user_trap must produce Err");
1837
1838        clear_tls_stack();
1839        drain_stack_pool();
1840    }
1841
1842    #[test]
1843    fn raise_lib_trap_yields_err() {
1844        let _lock = GLOBAL_STATE.lock().unwrap();
1845        let _restore = RestoreStackSize(get_stack_size());
1846        drain_stack_pool();
1847        clear_tls_stack();
1848
1849        let r: Result<(), UnwindReason> = on_wasm_stack(get_stack_size(), None, || unsafe {
1850            raise_lib_trap(Trap::lib(TrapCode::IntegerDivisionByZero));
1851        });
1852        assert!(r.is_err(), "raise_lib_trap must produce Err");
1853
1854        clear_tls_stack();
1855        drain_stack_pool();
1856    }
1857
1858    #[test]
1859    fn resume_panic_yields_err_without_unwinding() {
1860        // `resume_panic` packages the payload as `UnwindReason::Panic`. The
1861        // host-side panic resumption lives in `UnwindReason::into_trap`,
1862        // which we do NOT call here — `on_wasm_stack` itself just returns
1863        // the Err, so the test does not actually panic.
1864        let _lock = GLOBAL_STATE.lock().unwrap();
1865        let _restore = RestoreStackSize(get_stack_size());
1866        drain_stack_pool();
1867        clear_tls_stack();
1868
1869        let r: Result<(), UnwindReason> = on_wasm_stack(get_stack_size(), None, || unsafe {
1870            resume_panic(Box::new("panic payload from test"));
1871        });
1872        assert!(
1873            r.is_err(),
1874            "resume_panic must surface as Err to on_wasm_stack"
1875        );
1876
1877        clear_tls_stack();
1878        drain_stack_pool();
1879    }
1880
1881    #[test]
1882    fn trap_does_not_corrupt_subsequent_calls() {
1883        // After a trap, the per-call coroutine is force-reset and dropped.
1884        // The TLS stack cache and global pool must remain in a usable state
1885        // so that subsequent calls succeed.
1886        let _lock = GLOBAL_STATE.lock().unwrap();
1887        let _restore = RestoreStackSize(get_stack_size());
1888        drain_stack_pool();
1889        clear_tls_stack();
1890
1891        let trapped: Result<(), UnwindReason> = on_wasm_stack(get_stack_size(), None, || unsafe {
1892            raise_user_trap(Box::new(io::Error::other("first call traps")));
1893        });
1894        assert!(trapped.is_err());
1895
1896        // Subsequent normal call must still succeed.
1897        let ok = on_wasm_stack(get_stack_size(), None, || 7u32);
1898        assert_eq!(ok.ok(), Some(7), "calls after a trap must still work");
1899
1900        clear_tls_stack();
1901        drain_stack_pool();
1902    }
1903
1904    // -----------------------------------------------------------------
1905    // on_host_stack
1906    // -----------------------------------------------------------------
1907
1908    #[test]
1909    fn on_host_stack_outside_coroutine_runs_inline() {
1910        // `on_host_stack` outside any wasm coroutine just runs `f()` directly
1911        // (no stack switch); this asserts the no-yielder branch still works.
1912        let _lock = GLOBAL_STATE.lock().unwrap();
1913        let n = on_host_stack(|| 99i32);
1914        assert_eq!(n, 99);
1915    }
1916
1917    #[test]
1918    fn on_host_stack_inside_wasm_switches_and_returns() {
1919        let _lock = GLOBAL_STATE.lock().unwrap();
1920        let _restore = RestoreStackSize(get_stack_size());
1921        drain_stack_pool();
1922        clear_tls_stack();
1923
1924        let r = on_wasm_stack(get_stack_size(), None, || on_host_stack(|| 88i32));
1925        assert_eq!(r.ok(), Some(88));
1926
1927        clear_tls_stack();
1928        drain_stack_pool();
1929    }
1930
1931    // -----------------------------------------------------------------
1932    // Re-entrancy
1933    // -----------------------------------------------------------------
1934
1935    #[test]
1936    fn reentrant_call_returns_value() {
1937        let _lock = GLOBAL_STATE.lock().unwrap();
1938        let _restore = RestoreStackSize(get_stack_size());
1939        drain_stack_pool();
1940        clear_tls_stack();
1941
1942        let outer = on_wasm_stack(get_stack_size(), None, || {
1943            on_wasm_stack(get_stack_size(), None, || 42i32).expect("inner must succeed")
1944        });
1945        assert_eq!(outer.ok(), Some(42));
1946
1947        clear_tls_stack();
1948        drain_stack_pool();
1949    }
1950
1951    #[test]
1952    fn reentrant_calls_run_to_completion_under_pool_pressure() {
1953        // The outer call's stack is held by its scopeguard for the duration
1954        // of the call; the inner call must therefore pop a separate stack
1955        // from the pool (or allocate one). With a pre-populated pool the
1956        // inner call should consume that stack; either way the nested call
1957        // chain must complete without deadlocking or panicking from
1958        // corosensei.
1959        use std::sync::Arc;
1960        use std::sync::atomic::{AtomicUsize, Ordering as O};
1961
1962        let _lock = GLOBAL_STATE.lock().unwrap();
1963        let _restore = RestoreStackSize(get_stack_size());
1964        drain_stack_pool();
1965        clear_tls_stack();
1966
1967        // Pre-populate the pool with one stack so the inner call can grab
1968        // it instead of allocating.
1969        let pre = DefaultStack::new(get_stack_size()).unwrap();
1970        STACK_POOL.push(pre);
1971
1972        let inner_completed = Arc::new(AtomicUsize::new(0));
1973        let inner_completed_outer = inner_completed.clone();
1974        let _ = on_wasm_stack(get_stack_size(), None, move || {
1975            let inner_completed = inner_completed_outer.clone();
1976            let inner = on_wasm_stack(get_stack_size(), None, move || {
1977                inner_completed.fetch_add(1, O::Relaxed);
1978            });
1979            assert!(inner.is_ok(), "inner re-entrant call must succeed");
1980        });
1981        assert_eq!(
1982            inner_completed.load(O::Relaxed),
1983            1,
1984            "inner closure must have executed exactly once",
1985        );
1986
1987        clear_tls_stack();
1988        drain_stack_pool();
1989    }
1990
1991    #[test]
1992    fn reentrant_inner_trap_does_not_kill_outer() {
1993        let _lock = GLOBAL_STATE.lock().unwrap();
1994        let _restore = RestoreStackSize(get_stack_size());
1995        drain_stack_pool();
1996        clear_tls_stack();
1997
1998        let outer = on_wasm_stack(get_stack_size(), None, || {
1999            let inner: Result<i32, UnwindReason> =
2000                on_wasm_stack(get_stack_size(), None, || unsafe {
2001                    raise_user_trap(Box::new(io::Error::other("inner trap")));
2002                });
2003            // Outer observes inner's Err and recovers.
2004            match inner {
2005                Err(_) => 1234i32,
2006                Ok(_) => panic!("inner should have trapped"),
2007            }
2008        });
2009        assert_eq!(
2010            outer.ok(),
2011            Some(1234),
2012            "outer must recover after inner trap and run to completion"
2013        );
2014
2015        clear_tls_stack();
2016        drain_stack_pool();
2017    }
2018
2019    #[test]
2020    fn reentrant_with_on_host_stack_in_between() {
2021        // Outer wasm → on_host_stack → inner wasm. This exercises the
2022        // YIELDER save/restore in `unwind_with` / `on_host_stack` against
2023        // a re-entrant boundary.
2024        let _lock = GLOBAL_STATE.lock().unwrap();
2025        let _restore = RestoreStackSize(get_stack_size());
2026        drain_stack_pool();
2027        clear_tls_stack();
2028
2029        let r = on_wasm_stack(get_stack_size(), None, || {
2030            on_host_stack(|| {
2031                on_wasm_stack(get_stack_size(), None, || 5i32).expect("nested inner must succeed")
2032            })
2033        });
2034        assert_eq!(r.ok(), Some(5));
2035
2036        clear_tls_stack();
2037        drain_stack_pool();
2038    }
2039
2040    // -----------------------------------------------------------------
2041    // Concurrency
2042    // -----------------------------------------------------------------
2043
2044    #[test]
2045    fn many_threads_in_parallel_all_succeed() {
2046        let _lock = GLOBAL_STATE.lock().unwrap();
2047        let _restore = RestoreStackSize(get_stack_size());
2048        drain_stack_pool();
2049
2050        use std::sync::Arc;
2051        use std::sync::atomic::{AtomicUsize, Ordering as O};
2052
2053        let counter = Arc::new(AtomicUsize::new(0));
2054        const THREADS: usize = 8;
2055        const CALLS_PER_THREAD: usize = 200;
2056
2057        let handles: Vec<_> = (0..THREADS)
2058            .map(|_| {
2059                let counter = counter.clone();
2060                std::thread::spawn(move || {
2061                    let size = get_stack_size();
2062                    for _ in 0..CALLS_PER_THREAD {
2063                        if on_wasm_stack(size, None, || 1u32).ok() == Some(1) {
2064                            counter.fetch_add(1, O::Relaxed);
2065                        }
2066                    }
2067                })
2068            })
2069            .collect();
2070        for h in handles {
2071            h.join().unwrap();
2072        }
2073
2074        assert_eq!(counter.load(O::Relaxed), THREADS * CALLS_PER_THREAD);
2075        // Pool should now hold at most `THREADS` stacks (one per thread that
2076        // exited). Each thread also drops its TLS slot on exit, which pushes
2077        // the stack to the pool.
2078        let mut pooled = 0usize;
2079        while STACK_POOL.pop().is_some() {
2080            pooled += 1;
2081        }
2082        assert!(
2083            pooled <= THREADS,
2084            "pool should hold at most one stack per terminated thread (got {pooled} for {THREADS} threads)"
2085        );
2086
2087        clear_tls_stack();
2088        drain_stack_pool();
2089    }
2090
2091    // -----------------------------------------------------------------
2092    // Stack size dynamics
2093    // -----------------------------------------------------------------
2094
2095    #[test]
2096    fn growing_request_discards_smaller_tls_stack() {
2097        let _lock = GLOBAL_STATE.lock().unwrap();
2098        let _restore = RestoreStackSize(get_stack_size());
2099        drain_stack_pool();
2100        clear_tls_stack();
2101
2102        // First call at a small size populates TLS with a small stack.
2103        let small = ByteSize::mib(1).as_u64() as usize;
2104        set_stack_size(small);
2105        assert!(on_wasm_stack(small, None, || ()).is_ok());
2106
2107        let cached_size = TLS_STACK.with(|cache| {
2108            let s = cache.0.take();
2109            let sz = s.as_ref().map_or(0, |s| s.size());
2110            cache.0.set(s);
2111            sz
2112        });
2113        assert!(
2114            cached_size >= small,
2115            "TLS should hold the small-sized stack"
2116        );
2117
2118        // Now request a larger stack. acquire_stack should discard the TLS
2119        // entry and either pop a big-enough one from pool or allocate.
2120        let big = ByteSize::mib(4).as_u64() as usize;
2121        set_stack_size(big);
2122        assert!(on_wasm_stack(big, None, || ()).is_ok());
2123
2124        // The TLS slot should now hold a stack that's big enough.
2125        let cached_size = TLS_STACK.with(|cache| {
2126            let s = cache.0.take();
2127            let sz = s.as_ref().map_or(0, |s| s.size());
2128            cache.0.set(s);
2129            sz
2130        });
2131        assert!(
2132            cached_size >= big,
2133            "TLS should hold the bigger stack after size bump"
2134        );
2135
2136        clear_tls_stack();
2137        drain_stack_pool();
2138    }
2139}