Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,34 @@ jobs:
wasm-pack test --node crates/$x --no-default-features
done

panic_unwind_build:
name: Build with -Cpanic=unwind
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6

- uses: dtolnay/rust-toolchain@master
with:
toolchain: nightly
target: wasm32-unknown-unknown
components: rust-src

- uses: actions/cache@v4
with:
path: |
~/.cargo/registry
~/.cargo/git
target
key: cargo-${{ runner.os }}-panic-unwind-${{ hashFiles('**/Cargo.toml') }}
restore-keys: |
cargo-${{ runner.os }}-panic-unwind-
cargo-${{ runner.os }}-

- name: Build crates with panic=unwind
env:
RUSTFLAGS: '-Cpanic=unwind'
run: cargo build -p gloo-timers -p gloo-events -p gloo-render -p gloo-net -p gloo-worker --all-features --target wasm32-unknown-unknown -Zbuild-std=std,panic_unwind

test-history-wasi:
name: Test gloo-history WASI
runs-on: ubuntu-latest
Expand Down
53 changes: 47 additions & 6 deletions crates/events/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,24 @@ use wasm_bindgen::closure::Closure;
use wasm_bindgen::{JsCast, UnwrapThrowExt};
use web_sys::{AddEventListenerOptions, Event, EventTarget};

/// Bound carrying the unwind-safety requirement on [`EventListener`] callbacks.
///
/// Under `panic = "unwind"` on wasm the callback is invoked across a
/// `catch_unwind` boundary inside `wasm_bindgen`, so this resolves to
/// [`std::panic::UnwindSafe`]. Under any other panic strategy it is a no-op
/// blanket. Wrap non-`UnwindSafe` captures in [`std::panic::AssertUnwindSafe`]
/// at the call site.
#[cfg(all(target_arch = "wasm32", panic = "unwind"))]
pub trait CallbackUnwindSafe: std::panic::UnwindSafe {}
#[cfg(all(target_arch = "wasm32", panic = "unwind"))]
impl<T: std::panic::UnwindSafe> CallbackUnwindSafe for T {}

#[doc(hidden)]
#[cfg(not(all(target_arch = "wasm32", panic = "unwind")))]
pub trait CallbackUnwindSafe {}
#[cfg(not(all(target_arch = "wasm32", panic = "unwind")))]
impl<T> CallbackUnwindSafe for T {}

/// Specifies whether the event listener is run during the capture or bubble phase.
///
/// The official specification has [a good explanation](https://www.w3.org/TR/DOM-Level-3-Events/#event-flow)
Expand Down Expand Up @@ -331,9 +349,18 @@ impl EventListener {
pub fn new<S, F>(target: &EventTarget, event_type: S, callback: F) -> Self
where
S: Into<Cow<'static, str>>,
F: FnMut(&Event) + 'static,
F: FnMut(&Event) + 'static + CallbackUnwindSafe,
{
let callback = Closure::wrap(Box::new(callback) as Box<dyn FnMut(&Event)>);
// The `Box<F> as Box<dyn FnMut(&Event)>` coercion erases the static
// `UnwindSafe` bound that wasm-bindgen 0.2.117+ requires under
// `panic = "unwind"`. The `CallbackUnwindSafe` bound on `F` has
// enforced unwind safety at the call site, so the internal
// `_assert_unwind_safe` is sound.
let inner = Box::new(callback) as Box<dyn FnMut(&Event)>;
#[cfg(all(target_arch = "wasm32", panic = "unwind"))]
let callback = Closure::wrap_assert_unwind_safe(inner);
#[cfg(not(all(target_arch = "wasm32", panic = "unwind")))]
let callback = Closure::wrap(inner);

NEW_OPTIONS.with(move |options| {
Self::raw_new(
Expand Down Expand Up @@ -371,8 +398,13 @@ impl EventListener {
pub fn once<S, F>(target: &EventTarget, event_type: S, callback: F) -> Self
where
S: Into<Cow<'static, str>>,
F: FnOnce(&Event) + 'static,
F: FnOnce(&Event) + 'static + CallbackUnwindSafe,
{
// See `EventListener::new` for the rationale on the cfg-gated
// `_assert_unwind_safe` variant.
#[cfg(all(target_arch = "wasm32", panic = "unwind"))]
let callback = Closure::once_assert_unwind_safe(callback);
#[cfg(not(all(target_arch = "wasm32", panic = "unwind")))]
let callback = Closure::once(callback);

ONCE_OPTIONS.with(move |options| {
Expand Down Expand Up @@ -450,9 +482,14 @@ impl EventListener {
) -> Self
where
S: Into<Cow<'static, str>>,
F: FnMut(&Event) + 'static,
F: FnMut(&Event) + 'static + CallbackUnwindSafe,
{
let callback = Closure::wrap(Box::new(callback) as Box<dyn FnMut(&Event)>);
// See `EventListener::new` for the rationale.
let inner = Box::new(callback) as Box<dyn FnMut(&Event)>;
#[cfg(all(target_arch = "wasm32", panic = "unwind"))]
let callback = Closure::wrap_assert_unwind_safe(inner);
#[cfg(not(all(target_arch = "wasm32", panic = "unwind")))]
let callback = Closure::wrap(inner);

Self::raw_new(
target,
Expand Down Expand Up @@ -514,8 +551,12 @@ impl EventListener {
) -> Self
where
S: Into<Cow<'static, str>>,
F: FnOnce(&Event) + 'static,
F: FnOnce(&Event) + 'static + CallbackUnwindSafe,
{
// See `EventListener::new` for the rationale.
#[cfg(all(target_arch = "wasm32", panic = "unwind"))]
let callback = Closure::once_assert_unwind_safe(callback);
#[cfg(not(all(target_arch = "wasm32", panic = "unwind")))]
let callback = Closure::once(callback);

Self::raw_new(
Expand Down
4 changes: 2 additions & 2 deletions crates/net/src/eventsource/futures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ impl EventSource {
let message_callback: Closure<dyn FnMut(MessageEvent)> = {
let event_type = event_type.clone();
let sender = message_sender.clone();
Closure::wrap(Box::new(move |e: MessageEvent| {
wrap_internal!(Box::new(move |e: MessageEvent| {
let event_type = event_type.clone();
let _ = sender.unbounded_send(StreamMessage::Message(event_type, e));
}) as Box<dyn FnMut(MessageEvent)>)
Expand All @@ -192,7 +192,7 @@ impl EventSource {
.map_err(js_to_js_error)?;

let error_callback: Closure<dyn FnMut(web_sys::Event)> = {
Closure::wrap(Box::new(move |e: web_sys::Event| {
wrap_internal!(Box::new(move |e: web_sys::Event| {
let is_connecting = e
.current_target()
.map(|target| target.unchecked_into::<web_sys::EventSource>())
Expand Down
23 changes: 23 additions & 0 deletions crates/net/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,29 @@
)]
#![cfg_attr(docsrs, feature(doc_cfg))]

// wasm-bindgen 0.2.117+ requires `MaybeUnwindSafe` on closure inputs under
// `panic = "unwind"`. The `Box::new(...) as Box<dyn Fn*>` coercion used to
// construct internal event callbacks erases any static `UnwindSafe` bound,
// so we route through `Closure::wrap_assert_unwind_safe` instead. The
// assertion is sound: every callback in this crate only forwards to ops on
// state we exclusively own — lock-free `mpsc::UnboundedSender` pushes and
// single-shot `Option<Waker>` takes/wakes — so a panic across the
// `catch_unwind` boundary leaves observers seeing only states that are
// legitimately reachable (a missing wake, a missing message). On any other
// panic strategy this reduces to plain `Closure::wrap`.
#[cfg(all(target_arch = "wasm32", panic = "unwind"))]
macro_rules! wrap_internal {
($e:expr) => {
wasm_bindgen::closure::Closure::wrap_assert_unwind_safe($e)
};
}
#[cfg(not(all(target_arch = "wasm32", panic = "unwind")))]
macro_rules! wrap_internal {
($e:expr) => {
wasm_bindgen::closure::Closure::wrap($e)
};
}

mod error;
#[cfg(feature = "eventsource")]
#[cfg_attr(docsrs, doc(cfg(feature = "eventsource")))]
Expand Down
8 changes: 4 additions & 4 deletions crates/net/src/websocket/futures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ impl WebSocket {

let open_callback: Closure<dyn FnMut()> = {
let waker = Rc::clone(&waker);
Closure::wrap(Box::new(move || {
wrap_internal!(Box::new(move || {
if let Some(waker) = waker.borrow_mut().take() {
waker.wake();
}
Expand All @@ -151,7 +151,7 @@ impl WebSocket {

let message_callback: Closure<dyn FnMut(MessageEvent)> = {
let sender = sender.clone();
Closure::wrap(Box::new(move |e: MessageEvent| {
wrap_internal!(Box::new(move |e: MessageEvent| {
let msg = parse_message(e);
let _ = sender.unbounded_send(StreamMessage::Message(msg));
}) as Box<dyn FnMut(MessageEvent)>)
Expand All @@ -163,7 +163,7 @@ impl WebSocket {
let error_callback: Closure<dyn FnMut(web_sys::Event)> = {
let sender = sender.clone();
let waker = Rc::clone(&waker);
Closure::wrap(Box::new(move |_e: web_sys::Event| {
wrap_internal!(Box::new(move |_e: web_sys::Event| {
if let Some(waker) = waker.borrow_mut().take() {
waker.wake();
}
Expand All @@ -175,7 +175,7 @@ impl WebSocket {
.map_err(js_to_js_error)?;

let close_callback: Closure<dyn FnMut(web_sys::CloseEvent)> = {
Closure::wrap(Box::new(move |e: web_sys::CloseEvent| {
wrap_internal!(Box::new(move |e: web_sys::CloseEvent| {
let close_event = CloseEvent {
code: e.code(),
reason: e.reason(),
Expand Down
40 changes: 37 additions & 3 deletions crates/render/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,25 @@ use std::rc::Rc;
use wasm_bindgen::JsCast;
use wasm_bindgen::prelude::*;

/// Bound carrying the unwind-safety requirement on [`request_animation_frame`]
/// callbacks.
///
/// Under `panic = "unwind"` on wasm the callback is invoked across a
/// `catch_unwind` boundary inside `wasm_bindgen`, so this resolves to
/// [`std::panic::UnwindSafe`]. Under any other panic strategy it is a no-op
/// blanket. Wrap non-`UnwindSafe` captures in [`std::panic::AssertUnwindSafe`]
/// at the call site.
#[cfg(all(target_arch = "wasm32", panic = "unwind"))]
pub trait CallbackUnwindSafe: std::panic::UnwindSafe {}
#[cfg(all(target_arch = "wasm32", panic = "unwind"))]
impl<T: std::panic::UnwindSafe> CallbackUnwindSafe for T {}

#[doc(hidden)]
#[cfg(not(all(target_arch = "wasm32", panic = "unwind")))]
pub trait CallbackUnwindSafe {}
#[cfg(not(all(target_arch = "wasm32", panic = "unwind")))]
impl<T> CallbackUnwindSafe for T {}

/// Handle for [`request_animation_frame`].
#[derive(Debug)]
pub struct AnimationFrame {
Expand Down Expand Up @@ -40,16 +59,31 @@ impl Drop for AnimationFrame {
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/requestAnimationFrame)
pub fn request_animation_frame<F>(callback_once: F) -> AnimationFrame
where
F: FnOnce(f64) + 'static,
F: FnOnce(f64) + 'static + CallbackUnwindSafe,
{
let callback_wrapper = Rc::new(RefCell::new(Some(CallbackWrapper(Box::new(callback_once)))));
// The internal trampoline captures `Rc<RefCell<Option<CallbackWrapper>>>`
// which is not `UnwindSafe`. Asserting unwind safety here is sound: the
// `borrow_mut().take()` releases the borrow before invoking the user
// closure, and a panic inside the user closure leaves the cell holding
// `None` — a valid post-fire state. `Drop` checks `is_some()` and skips
// cancellation when the slot is already empty. The `CallbackUnwindSafe`
// bound on the public API enforces unwind safety at the call site.
let callback: Closure<dyn Fn(JsValue)> = {
let callback_wrapper = Rc::clone(&callback_wrapper);
Closure::wrap(Box::new(move |v: JsValue| {
let inner = Box::new(move |v: JsValue| {
let time: f64 = v.as_f64().unwrap_or(0.0);
let callback = callback_wrapper.borrow_mut().take().unwrap().0;
callback(time);
}))
}) as Box<dyn Fn(JsValue)>;
#[cfg(all(target_arch = "wasm32", panic = "unwind"))]
{
Closure::wrap_assert_unwind_safe(inner)
}
#[cfg(not(all(target_arch = "wasm32", panic = "unwind")))]
{
Closure::wrap(inner)
}
};

let render_id = web_sys::window()
Expand Down
42 changes: 40 additions & 2 deletions crates/timers/src/callback.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,25 @@ use js_sys::Function;
use wasm_bindgen::prelude::*;
use wasm_bindgen::{JsCast, JsValue};

/// Bound carrying the unwind-safety requirement on [`Timeout::new`] /
/// [`Interval::new`] callbacks.
///
/// Under `panic = "unwind"` on wasm the callback is invoked across a
/// `catch_unwind` boundary inside `wasm_bindgen`, so this resolves to
/// [`std::panic::UnwindSafe`]. Under any other panic strategy it is a no-op
/// blanket. Wrap non-`UnwindSafe` captures in [`std::panic::AssertUnwindSafe`]
/// at the call site.
#[cfg(all(target_arch = "wasm32", panic = "unwind"))]
pub trait CallbackUnwindSafe: std::panic::UnwindSafe {}
#[cfg(all(target_arch = "wasm32", panic = "unwind"))]
impl<T: std::panic::UnwindSafe> CallbackUnwindSafe for T {}

#[doc(hidden)]
#[cfg(not(all(target_arch = "wasm32", panic = "unwind")))]
pub trait CallbackUnwindSafe {}
#[cfg(not(all(target_arch = "wasm32", panic = "unwind")))]
impl<T> CallbackUnwindSafe for T {}

#[wasm_bindgen]
unsafe extern "C" {
#[wasm_bindgen(js_name = "setTimeout", catch)]
Expand Down Expand Up @@ -57,8 +76,18 @@ impl Timeout {
/// ```
pub fn new<F>(millis: u32, callback: F) -> Timeout
where
F: 'static + FnOnce(),
F: 'static + FnOnce() + CallbackUnwindSafe,
{
// Under `panic = "unwind"` we use the `_assert_unwind_safe` variant
// because `WasmClosureFnOnce` selection erases `F` into a trait-object
// dispatch that no longer carries the static `UnwindSafe` bound — the
// same dyn-erasure problem wasm-bindgen handles internally. The
// `CallbackUnwindSafe` bound on the public API has already enforced
// the requirement at the call site. On any other panic strategy
// `Closure::once` is unchanged and works on any 0.2.x wasm-bindgen.
#[cfg(all(target_arch = "wasm32", panic = "unwind"))]
let closure = Closure::once_assert_unwind_safe(callback);
#[cfg(not(all(target_arch = "wasm32", panic = "unwind")))]
let closure = Closure::once(callback);

let id = set_timeout(
Expand Down Expand Up @@ -158,8 +187,17 @@ impl Interval {
/// ```
pub fn new<F>(millis: u32, callback: F) -> Interval
where
F: 'static + FnMut(),
F: 'static + FnMut() + CallbackUnwindSafe,
{
// Same rationale as `Timeout::new`: the `Box<F> as Box<dyn FnMut()>`
// coercion erases the `UnwindSafe` bound, so under `panic = "unwind"`
// we use `_assert_unwind_safe` to acknowledge the erasure (the public
// `CallbackUnwindSafe` bound has already enforced unwind safety at
// the call site). Otherwise the original `Closure::wrap` path is
// preserved for older wasm-bindgen compatibility.
#[cfg(all(target_arch = "wasm32", panic = "unwind"))]
let closure = Closure::wrap_assert_unwind_safe(Box::new(callback) as Box<dyn FnMut()>);
#[cfg(not(all(target_arch = "wasm32", panic = "unwind")))]
let closure = Closure::wrap(Box::new(callback) as Box<dyn FnMut()>);

let id = set_interval(
Expand Down
Loading
Loading