A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
fibers: post-merge review updates to raw fibers. (#15229)
Chris Fallin8dd7a5418628
diff --git a/crates/fiber/src/miri.rs b/crates/fiber/src/miri.rsindex fe6c2d5651..0ac8a78f21 100644--- a/crates/fiber/src/miri.rs+++ b/crates/fiber/src/miri.rs@@ -16,6 +16,10 @@//! to support stack-switching in a first-class manner.use crate::{Result, RunResult, RuntimeFiberStack};++/// Raw fibers are never supported under Miri (see `RawFiber::is_supported`),+/// but still refer to this crate's stack-switching routines.+pub(crate) use crate::stackswitch::raw;use std::boxed::Box;use std::cell::Cell;use std::io;diff --git a/crates/fiber/src/nostd.rs b/crates/fiber/src/nostd.rsindex de2efbc19c..c2c8704d29 100644--- a/crates/fiber/src/nostd.rs+++ b/crates/fiber/src/nostd.rs@@ -26,6 +26,9 @@//! its own resumption information into this slot as well.use crate::stackswitch::*;++/// Raw fibers use this crate's stack-switching routines.+pub(crate) use crate::stackswitch::raw;use crate::{Result, RunResult, RuntimeFiberStack};use alloc::boxed::Box;use core::cell::Cell;diff --git a/crates/fiber/src/raw.rs b/crates/fiber/src/raw.rsindex 6ce8c2af72..81cf2a5caf 100644--- a/crates/fiber/src/raw.rs+++ b/crates/fiber/src/raw.rs@@ -9,23 +9,16 @@ use core::sync::atomic::Ordering;use wasmtime_environ::collections::TryVec;use wasmtime_environ::error::{Error, Result, bail, ensure};-cfg_select! {- all(windows, feature = "std", not(miri)) => {- mod windows;- use windows as sys;- }- _ => {- mod stackswitch;- use stackswitch as sys;- }-}+// The platform's raw-fiber backend, selected along with the rest of the+// platform's fiber implementation in `lib.rs`.+use crate::imp::raw as sys;/// The entry point of a raw fiber.////// This is called on the fiber's stack with the `arg` given to/// [`RawFiber::new`] and the fiber's [`RawFiber::switch_arg`]. It must never/// return.-pub type RawFiberEntry = unsafe extern "C" fn(arg: *mut u8, switch_arg: *mut u8);+pub type RawFiberEntry = unsafe extern "C" fn(arg: *mut u8, switch_arg: *mut u8) -> !;/// The lifecycle of a [`RawFiber`].///@@ -185,7 +178,7 @@ impl RawFiber {/// argument, to suspend itself. It returns when the fiber is next/// resumed.pub fn switch_routine() -> unsafe extern "C" fn(*mut u8) {- sys::switch_routine()+ sys::switch_routine}/// The argument which code on this fiber passes to@@ -249,7 +242,7 @@ impl RawFiber {}fn saved_sp_slot(&self) -> *mut usize {- // See the layout diagrams in `unix.rs` and `raw/windows.rs`: the+ // See the layout diagrams in `unix.rs` and `windows/raw.rs`: the// second slot below the top holds the stack pointer to resume the// fiber at.self.switch_arg().cast::<usize>().wrapping_sub(2)@@ -366,36 +359,59 @@ impl RawFiberSnapshot {}}-#[cfg(test)]+// The code on these tests' fibers must not include any Rust frames, so it is+// written in assembly, for x86_64 Linux only.+#[cfg(all(test, target_arch = "x86_64", target_os = "linux"))]mod tests {use super::*;use core::cell::Cell;/// State shared between a test and the code on its raw fiber.#[derive(Default)]+ #[repr(C)]struct Shared {observed: Cell<u64>,finished: Cell<bool>,}- /// Yields the values 1, 2, 3 and then finishes. The counter is local to- /// the fiber, so a restored snapshot rewinds it.- unsafe extern "C" fn count_to_three(arg: *mut u8, switch_arg: *mut u8) {- // SAFETY: tests pass a `Shared` that outlives the fiber's use.- let shared = unsafe { &*arg.cast::<Shared>() };- let switch = RawFiber::switch_routine();- let mut count = 0;- while count < 3 {- count += 1;- shared.observed.set(count);- // SAFETY: this is the switch routine for this fiber.- unsafe { switch(switch_arg) };- }- shared.finished.set(true);- // SAFETY: as above.- unsafe { switch(switch_arg) };- // Resuming a terminal fiber is rejected by `RawFiber::resume`.- std::process::abort();+ /// Yields the values 1, 2, 3 and then finishes. The counter is in `rbx`,+ /// which the switch routine spills to the fiber's stack, so a restored+ /// snapshot rewinds it.+ ///+ /// Resuming the fiber after it finishes, which `RawFiber::resume` rejects,+ /// traps.+ #[unsafe(naked)]+ unsafe extern "C" fn count_to_three(+ arg: *mut u8, /* rdi */+ switch_arg: *mut u8, /* rsi */+ ) -> ! {+ core::arch::naked_asm!(+ "+ // A frame record, for `suspended_frame`. This also aligns the+ // stack for the calls below.+ push rbp+ mov rbp, rsp++ mov r12, rdi+ mov r13, rsi+ xor ebx, ebx+ 2:+ inc rbx+ mov qword ptr [r12 + {observed}], rbx+ mov rdi, r13+ call {switch}+ cmp rbx, 3+ jb 2b++ mov byte ptr [r12 + {finished}], 1+ mov rdi, r13+ call {switch}+ ud2+ ",+ observed = const core::mem::offset_of!(Shared, observed),+ finished = const core::mem::offset_of!(Shared, finished),+ switch = sym sys::switch_routine,+ );}fn fiber(shared: &Shared) -> Option<RawFiber> {@@ -516,37 +532,24 @@ mod tests {#[test]fn resume_on_another_thread() {- let shared = std::sync::Arc::new(SharedSync::default());- if !RawFiber::is_supported() {+ let shared = Shared::default();+ let Some(mut fiber) = fiber(&shared) else {return;- }- unsafe extern "C" fn entry(arg: *mut u8, switch_arg: *mut u8) {- let shared = unsafe { &*arg.cast::<SharedSync>() };- let switch = RawFiber::switch_routine();- loop {- shared.0.fetch_add(1, core::sync::atomic::Ordering::Relaxed);- unsafe { switch(switch_arg) };- }- }- #[derive(Default)]- struct SharedSync(core::sync::atomic::AtomicUsize);-- let stack = FiberStack::new(64 * 1024, false).unwrap();- let arg = std::sync::Arc::as_ptr(&shared).cast_mut().cast();- let mut fiber = unsafe { RawFiber::new(stack, entry, arg) }- .map_err(|e| e.0)- .unwrap();+ };unsafe { fiber.resume().unwrap() };let snapshot = fiber.snapshot().unwrap();+ // `shared` is only accessed by the fiber while this thread waits for+ // the other one.let mut fiber = std::thread::spawn(move || {unsafe { fiber.resume().unwrap() };fiber}).join().unwrap();+ assert_eq!(shared.observed.get(), 2);unsafe { fiber.restore(&snapshot).unwrap() };unsafe { fiber.resume().unwrap() };- assert_eq!(shared.0.load(core::sync::atomic::Ordering::Relaxed), 3);+ assert_eq!(shared.observed.get(), 2);}#[test]@@ -573,16 +576,10 @@ mod tests {};assert!(fiber.suspended_frame().is_none());unsafe { fiber.resume().unwrap() };- if let Some((pc, fp)) = fiber.suspended_frame() {- // Without frame pointers in this Rust entry, `fp` may still be- // the initial one: the top of the stack.- let range = fiber.stack().range().unwrap();- assert!(- range.start <= fp && fp <= range.end,- "{fp:#x} vs {range:x?}"- );- let entry = count_to_three as *const () as usize;- assert!(pc > entry && pc < entry + 4096, "{pc:#x} vs {entry:#x}");- }+ let (pc, fp) = fiber.suspended_frame().unwrap();+ let range = fiber.stack().range().unwrap();+ assert!(range.contains(&fp), "{fp:#x} vs {range:x?}");+ let entry = count_to_three as *const () as usize;+ assert!(pc > entry && pc < entry + 0x100, "{pc:#x} vs {entry:#x}");}}diff --git a/crates/fiber/src/stackswitch.rs b/crates/fiber/src/stackswitch.rsindex b117ecd694..9eb4b980a2 100644--- a/crates/fiber/src/stackswitch.rs+++ b/crates/fiber/src/stackswitch.rs@@ -4,6 +4,9 @@// included modules below; their symbols are visible in the binary and// accessed via the `extern "C"` declarations below that.+/// Raw fibers on top of the routines here.+pub(crate) mod raw;+cfg_select! {// Miri uses another fiber implementation, but raw fibers still refer to// the routines here.@@ -88,6 +91,7 @@ mod supported {mod unsupported {pub const SUPPORTED_ARCH: bool = false;pub const RAW_FIBERS: bool = false;+ pub const SUSPENDED_FRAME: Option<(usize, usize)> = None;pub(crate) unsafe fn wasmtime_fiber_init(_top_of_stack: *mut u8,diff --git a/crates/fiber/src/stackswitch/aarch64.rs b/crates/fiber/src/stackswitch/aarch64.rsindex 9ffdd06f3e..fa67dc37e3 100644--- a/crates/fiber/src/stackswitch/aarch64.rs+++ b/crates/fiber/src/stackswitch/aarch64.rs@@ -10,6 +10,11 @@use core::arch::naked_asm;+/// The indices, in words from a suspended raw fiber's saved stack pointer, of+/// the frame pointer and return address that `wasmtime_fiber_switch_` spills+/// for its caller. Keep in sync with that routine.+pub(crate) const SUSPENDED_FRAME: Option<(usize, usize)> = Some((18, 19));+#[inline(never)] // FIXME(rust-lang/rust#148307)pub(crate) unsafe extern "C" fn wasmtime_fiber_switch(top_of_stack: *mut u8) {unsafe { wasmtime_fiber_switch_(top_of_stack) }diff --git a/crates/fiber/src/stackswitch/arm.rs b/crates/fiber/src/stackswitch/arm.rsindex b462d8530b..4de6e5b300 100644--- a/crates/fiber/src/stackswitch/arm.rs+++ b/crates/fiber/src/stackswitch/arm.rs@@ -10,6 +10,16 @@use core::arch::naked_asm;+/// The indices, in words from a suspended raw fiber's saved stack pointer, of+/// the frame pointer and return address that `wasmtime_fiber_switch_` spills+/// for its caller. The frame pointer is `r7` in Thumb code and `r11`+/// otherwise. Keep in sync with that routine.+pub(crate) const SUSPENDED_FRAME: Option<(usize, usize)> = if cfg!(target_feature = "thumb-mode") {+ Some((3, 8))+} else {+ Some((7, 8))+};+#[inline(never)] // FIXME(rust-lang/rust#148307)pub(crate) unsafe extern "C" fn wasmtime_fiber_switch(top_of_stack: *mut u8) {unsafe { wasmtime_fiber_switch_(top_of_stack) }diff --git a/crates/fiber/src/stackswitch/custom.rs b/crates/fiber/src/stackswitch/custom.rsindex 21f2e45c1c..a43d76a821 100644--- a/crates/fiber/src/stackswitch/custom.rs+++ b/crates/fiber/src/stackswitch/custom.rs@@ -26,6 +26,7 @@ pub(crate) const SUPPORTED_ARCH: bool = true;// The embedder's routines need not use the stack layout that raw fiber// snapshots depend on.pub(crate) const RAW_FIBERS: bool = false;+pub(crate) const SUSPENDED_FRAME: Option<(usize, usize)> = None;pub(crate) unsafe extern "C" fn wasmtime_fiber_switch_(_top_of_stack: *mut u8) {unreachable!()diff --git a/crates/fiber/src/stackswitch/loongarch64.rs b/crates/fiber/src/stackswitch/loongarch64.rsindex 2bb11dc725..c5834a92fe 100644--- a/crates/fiber/src/stackswitch/loongarch64.rs+++ b/crates/fiber/src/stackswitch/loongarch64.rs@@ -7,6 +7,11 @@use core::arch::naked_asm;+/// The indices, in words from a suspended raw fiber's saved stack pointer, of+/// the frame pointer and return address that `wasmtime_fiber_switch_` spills+/// for its caller. Keep in sync with that routine.+pub(crate) const SUSPENDED_FRAME: Option<(usize, usize)> = Some((18, 19));+#[inline(never)] // FIXME(rust-lang/rust#148307)pub(crate) unsafe extern "C" fn wasmtime_fiber_switch(top_of_stack: *mut u8) {unsafe { wasmtime_fiber_switch_(top_of_stack) }diff --git a/crates/fiber/src/raw/stackswitch.rs b/crates/fiber/src/stackswitch/raw.rssimilarity index 71%rename from crates/fiber/src/raw/stackswitch.rsrename to crates/fiber/src/stackswitch/raw.rsindex 45e98d4bcb..6568cc4f68 100644--- a/crates/fiber/src/raw/stackswitch.rs+++ b/crates/fiber/src/stackswitch/raw.rs@@ -2,31 +2,17 @@//! suspended context on the fiber's stack in the reserved-slot layout//! documented in `unix.rs`.-use super::RawFiberEntry;-use crate::stackswitch::{- RAW_FIBERS, wasmtime_fiber_init, wasmtime_fiber_switch, wasmtime_fiber_switch_,-};+use super::{RAW_FIBERS, wasmtime_fiber_init, wasmtime_fiber_switch};+use crate::RawFiberEntry;use wasmtime_environ::error::{Result, format_err};+pub(crate) use super::SUSPENDED_FRAME;+pub(crate) use super::wasmtime_fiber_switch_ as switch_routine;+pub fn supported() -> bool {RAW_FIBERS}-pub fn switch_routine() -> unsafe extern "C" fn(*mut u8) {- wasmtime_fiber_switch_-}--// Indices, in words from the saved stack pointer, of the frame-// pointer and return address that the switch routine spills. Keep-// in sync with `wasmtime_fiber_switch_` in `stackswitch/*.rs`.-pub const SUSPENDED_FRAME: Option<(usize, usize)> = if cfg!(target_arch = "x86_64") {- Some((5, 6))-} else if cfg!(target_arch = "aarch64") {- Some((18, 19))-} else {- None-};-pub struct Fiber;impl Fiber {diff --git a/crates/fiber/src/stackswitch/riscv32imac.rs b/crates/fiber/src/stackswitch/riscv32imac.rsindex 55a3445d3f..7b4918bb64 100644--- a/crates/fiber/src/stackswitch/riscv32imac.rs+++ b/crates/fiber/src/stackswitch/riscv32imac.rs@@ -10,6 +10,11 @@use core::arch::naked_asm;+/// The indices, in words from a suspended raw fiber's saved stack pointer, of+/// the frame pointer and return address that `wasmtime_fiber_switch_` spills+/// for its caller. Keep in sync with that routine.+pub(crate) const SUSPENDED_FRAME: Option<(usize, usize)> = Some((14, 15));+#[inline(never)] // FIXME(rust-lang/rust#148307)pub(crate) unsafe extern "C" fn wasmtime_fiber_switch(top_of_stack: *mut u8) {unsafe { wasmtime_fiber_switch_(top_of_stack) }diff --git a/crates/fiber/src/stackswitch/riscv64.rs b/crates/fiber/src/stackswitch/riscv64.rsindex e05f0e3062..4647d8448f 100644--- a/crates/fiber/src/stackswitch/riscv64.rs+++ b/crates/fiber/src/stackswitch/riscv64.rs@@ -7,6 +7,11 @@use core::arch::naked_asm;+/// The indices, in words from a suspended raw fiber's saved stack pointer, of+/// the frame pointer and return address that `wasmtime_fiber_switch_` spills+/// for its caller. Keep in sync with that routine.+pub(crate) const SUSPENDED_FRAME: Option<(usize, usize)> = Some((24, 25));+#[inline(never)] // FIXME(rust-lang/rust#148307)pub(crate) unsafe extern "C" fn wasmtime_fiber_switch(top_of_stack: *mut u8) {unsafe { wasmtime_fiber_switch_(top_of_stack) }diff --git a/crates/fiber/src/stackswitch/s390x.rs b/crates/fiber/src/stackswitch/s390x.rsindex e657989966..b56ab3291f 100644--- a/crates/fiber/src/stackswitch/s390x.rs+++ b/crates/fiber/src/stackswitch/s390x.rs@@ -7,6 +7,14 @@use core::arch::naked_asm;+/// The indices, in words from a suspended raw fiber's saved stack pointer, of+/// the frame pointer and return address that `wasmtime_fiber_switch_` spills+/// for its caller. As in Wasmtime's unwinder, the "frame pointer" is the+/// caller's stack pointer, `%r15`, which addresses its back chain; `stmg`+/// spills it, with `%r14`, into the caller's register save area. Keep in sync+/// with that routine.+pub(crate) const SUSPENDED_FRAME: Option<(usize, usize)> = Some((23, 22));+#[inline(never)] // FIXME(rust-lang/rust#148307)pub(crate) unsafe extern "C" fn wasmtime_fiber_switch(top_of_stack: *mut u8) {unsafe { wasmtime_fiber_switch_(top_of_stack) }diff --git a/crates/fiber/src/stackswitch/x86.rs b/crates/fiber/src/stackswitch/x86.rsindex 5f32bacee9..3242a57ba5 100644--- a/crates/fiber/src/stackswitch/x86.rs+++ b/crates/fiber/src/stackswitch/x86.rs@@ -12,6 +12,11 @@use core::arch::naked_asm;+/// The indices, in words from a suspended raw fiber's saved stack pointer, of+/// the frame pointer and return address that `wasmtime_fiber_switch_` spills+/// for its caller. Keep in sync with that routine.+pub(crate) const SUSPENDED_FRAME: Option<(usize, usize)> = Some((3, 4));+#[inline(never)] // FIXME(rust-lang/rust#148307)pub(crate) unsafe extern "C" fn wasmtime_fiber_switch(top_of_stack: *mut u8) {unsafe { wasmtime_fiber_switch_(top_of_stack) }diff --git a/crates/fiber/src/stackswitch/x86_64.rs b/crates/fiber/src/stackswitch/x86_64.rsindex e0536dbe62..d5247c7708 100644--- a/crates/fiber/src/stackswitch/x86_64.rs+++ b/crates/fiber/src/stackswitch/x86_64.rs@@ -7,6 +7,11 @@use core::arch::naked_asm;+/// The indices, in words from a suspended raw fiber's saved stack pointer, of+/// the frame pointer and return address that `wasmtime_fiber_switch_` spills+/// for its caller. Keep in sync with that routine.+pub(crate) const SUSPENDED_FRAME: Option<(usize, usize)> = Some((5, 6));+#[inline(never)] // FIXME(rust-lang/rust#148307)pub(crate) unsafe extern "C" fn wasmtime_fiber_switch(top_of_stack: *mut u8) {unsafe { wasmtime_fiber_switch_(top_of_stack) }diff --git a/crates/fiber/src/unix.rs b/crates/fiber/src/unix.rsindex d39cb12fd0..d4ccb33fea 100644--- a/crates/fiber/src/unix.rs+++ b/crates/fiber/src/unix.rs@@ -30,6 +30,9 @@//! its own resumption information into this slot as well.use crate::stackswitch::*;++/// Raw fibers use this crate's stack-switching routines.+pub(crate) use crate::stackswitch::raw;use crate::{RunResult, RuntimeFiberStack};use std::boxed::Box;use std::cell::Cell;diff --git a/crates/fiber/src/windows.rs b/crates/fiber/src/windows.rsindex f8f303d0f3..80c342134d 100644--- a/crates/fiber/src/windows.rs+++ b/crates/fiber/src/windows.rs@@ -10,13 +10,16 @@ use wasmtime_environ::prelude::*;use windows_sys::Win32::Foundation::*;use windows_sys::Win32::System::Threading::*;+/// Raw fibers on top of Windows fibers.+pub(crate) mod raw;+pub type Error = io::Error;#[derive(Debug)]pub struct FiberStack {pub(crate) size: usize,// Windows allocates a fiber's stack when creating the fiber, so its- // location is only known while a raw fiber owns it. See `raw/windows.rs`.+ // location is only known while a raw fiber owns it. See `windows/raw.rs`.pub(crate) raw_range: Option<Range<usize>>,}diff --git a/crates/fiber/src/raw/windows.rs b/crates/fiber/src/windows/raw.rssimilarity index 96%rename from crates/fiber/src/raw/windows.rsrename to crates/fiber/src/windows/raw.rsindex 32beeabd50..64d29bac3d 100644--- a/crates/fiber/src/raw/windows.rs+++ b/crates/fiber/src/windows/raw.rs@@ -32,10 +32,8 @@//! A raw fiber's `FiberStack` reports its range as the bottom of the stack's//! reservation up to `top`, which is also what it reports as the stack's top.+use super::{FIBER_FLAG_FLOAT_SWITCH, delete_fiber, set_stack_guarantee, with_current_fiber};use crate::RawFiberEntry;-use crate::windows::{- FIBER_FLAG_FLOAT_SWITCH, delete_fiber, set_stack_guarantee, with_current_fiber,-};use std::ffi::c_void;use std::io;use std::ptr;@@ -73,6 +71,7 @@ cfg_select! {}pub(crate) use asm::SUSPENDED_FRAME;+pub(crate) use asm::wasmtime_fiber_suspend as switch_routine;/// A raw fiber's underlying Windows fiber, which owns its stack's memory.pub(crate) struct Fiber(*mut c_void);@@ -117,10 +116,6 @@ fn user_shadow_stacks() -> bool {flags & ENABLE_USER_SHADOW_STACK != 0}-pub(crate) fn switch_routine() -> unsafe extern "C" fn(*mut u8) {- asm::wasmtime_fiber_suspend-}-unsafe extern "system" fn fiber_start(data: *mut c_void) {unsafe {set_stack_guarantee();diff --git a/crates/fiber/src/raw/windows/aarch64.rs b/crates/fiber/src/windows/raw/aarch64.rssimilarity index 97%rename from crates/fiber/src/raw/windows/aarch64.rsrename to crates/fiber/src/windows/raw/aarch64.rsindex e300a049b2..eb96f21af7 100644--- a/crates/fiber/src/raw/windows/aarch64.rs+++ b/crates/fiber/src/windows/raw/aarch64.rs@@ -1,7 +1,7 @@// A WORD OF CAUTION//// This file needs to be kept in sync with itself and with the layout-// documented in `raw/windows.rs`, and `SUSPENDED_FRAME` with the frame that+// documented in `windows/raw.rs`, and `SUSPENDED_FRAME` with the frame that// `wasmtime_fiber_suspend` spills. It closely follows `x86_64.rs`.use core::arch::naked_asm;@@ -93,7 +93,7 @@ pub unsafe extern "C" fn wasmtime_fiber_suspend(top: *mut u8 /* x0 */) {);}-/// Sets up the top of the stack as documented in `raw/windows.rs`, reports `top`+/// Sets up the top of the stack as documented in `windows/raw.rs`, reports `top`/// through `top_out`, suspends, and then calls `entry(arg, top)` when first/// resumed.///diff --git a/crates/fiber/src/raw/windows/x86_64.rs b/crates/fiber/src/windows/raw/x86_64.rssimilarity index 97%rename from crates/fiber/src/raw/windows/x86_64.rsrename to crates/fiber/src/windows/raw/x86_64.rsindex 3028a99428..14d006525c 100644--- a/crates/fiber/src/raw/windows/x86_64.rs+++ b/crates/fiber/src/windows/raw/x86_64.rs@@ -1,7 +1,7 @@// A WORD OF CAUTION//// This file needs to be kept in sync with itself and with the layout-// documented in `raw/windows.rs`, and `SUSPENDED_FRAME` with the frame that+// documented in `windows/raw.rs`, and `SUSPENDED_FRAME` with the frame that// `wasmtime_fiber_suspend` spills.use core::arch::naked_asm;@@ -105,7 +105,7 @@ pub unsafe extern "C" fn wasmtime_fiber_suspend(top: *mut u8 /* rcx */) {);}-/// Sets up the top of the stack as documented in `raw/windows.rs`, reports `top`+/// Sets up the top of the stack as documented in `windows/raw.rs`, reports `top`/// through `top_out`, suspends, and then calls `entry(arg, top)` when first/// resumed.///