Skip to content

Commit

Permalink
config: catch and ignore panics in callbacks
Browse files Browse the repository at this point in the history
  • Loading branch information
mahkoh committed Mar 6, 2024
1 parent 86e5824 commit 69f5be4
Showing 1 changed file with 21 additions and 6 deletions.
27 changes: 21 additions & 6 deletions jay-config/src/_private/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ use {
future::Future,
mem,
ops::Deref,
panic::{catch_unwind, AssertUnwindSafe},
pin::Pin,
ptr,
rc::Rc,
Expand All @@ -49,11 +50,17 @@ fn cb<T, F: FnMut(T) + 'static>(f: F) -> Callback<T> {

fn run_cb<T>(name: &str, cb: &Callback<T>, t: T) {
match cb.try_borrow_mut() {
Ok(mut cb) => cb(t),
Ok(mut cb) => ignore_panic(name, || cb(t)),
Err(_) => log::error!("Cannot invoke {name} callback because it is already running"),
}
}

fn ignore_panic(name: &str, f: impl FnOnce()) {
if catch_unwind(AssertUnwindSafe(f)).is_err() {
log::error!("A panic occurred in a {name} callback");
}
}

pub(crate) struct Client {
configure: extern "C" fn(),
srv_data: *const u8,
Expand Down Expand Up @@ -863,10 +870,18 @@ impl Client {
if let Some(fut) = fut {
let mut fut = fut.borrow_mut();
let fut = &mut *fut;
if let Poll::Ready(()) =
let res = catch_unwind(AssertUnwindSafe(|| {
fut.task.as_mut().poll(&mut Context::from_waker(&fut.waker))
{
futures.tasks.borrow_mut().remove(&id);
}));
match res {
Err(_) => {
log::error!("A task panicked");
futures.tasks.borrow_mut().remove(&id);
}
Ok(Poll::Ready(())) => {
futures.tasks.borrow_mut().remove(&id);
}
Ok(_) => {}
}
}
}
Expand Down Expand Up @@ -966,7 +981,7 @@ impl Client {
}
ServerMessage::GraphicsInitialized => {
if let Some(handler) = self.on_graphics_initialized.take() {
handler();
ignore_panic("graphics initialized", handler);
}
}
ServerMessage::Clear => {
Expand All @@ -992,7 +1007,7 @@ impl Client {
}
ServerMessage::DevicesEnumerated => {
if let Some(handler) = self.on_devices_enumerated.take() {
handler();
ignore_panic("devices enumerated", handler);
}
}
ServerMessage::InterestReady { id, writable, res } => {
Expand Down

0 comments on commit 69f5be4

Please sign in to comment.