Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add interrupt handler callback support #126

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
4 changes: 2 additions & 2 deletions src/bindings/compile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ pub fn compile<'a>(
};

// check for error
context.ensure_no_excpetion()?;
context.ensure_no_exception()?;
Ok(value)
}

Expand All @@ -45,7 +45,7 @@ pub fn run_compiled_function<'a>(
OwnedJsValue::new(context, v)
};

context.ensure_no_excpetion().map_err(|e| {
context.ensure_no_exception().map_err(|e| {
if let ExecutionError::Internal(msg) = e {
ExecutionError::Internal(format!("Could not evaluate compiled function: {}", msg))
} else {
Expand Down
45 changes: 43 additions & 2 deletions src/bindings/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ mod value;
use std::{
ffi::CString,
os::raw::{c_int, c_void},
sync::Mutex,
sync::Mutex, panic::RefUnwindSafe,
};

use libquickjs_sys as q;
Expand Down Expand Up @@ -83,6 +83,30 @@ where
((boxed_f, data), Some(trampoline::<F>))
}

type InterruptHandlerWrapper = dyn Fn(*mut q::JSRuntime) -> i32;
fn interrupt_handler_trampoline<F>(
closure: F,
) -> ((Box<InterruptHandlerWrapper>, *mut c_void), unsafe extern "C" fn(*mut q::JSRuntime, *mut c_void) -> i32)
where
F: Fn(*mut q::JSRuntime) -> i32 + 'static,
{
unsafe extern "C" fn trampoline<F>(
rt: *mut q::JSRuntime,
closure_ptr: *mut c_void
) -> i32
where
F: Fn(*mut q::JSRuntime) -> i32 + 'static,
{
let closure: &mut F = &mut *(closure_ptr as *mut F);
(*closure)(rt)
}

let boxed_f = Box::new(closure);
let data_ptr = (&*boxed_f) as *const F as *mut c_void;

((boxed_f, data_ptr), trampoline::<F>)
}

/// OwnedValueRef wraps a Javascript value from the quickjs runtime.
/// It prevents leaks by ensuring that the inner value is deallocated on drop.
pub struct OwnedValueRef<'a> {
Expand Down Expand Up @@ -340,6 +364,7 @@ pub struct ContextWrapper {
/// the closure.
// A Mutex is used over a RefCell because it needs to be unwind-safe.
callbacks: Mutex<Vec<(Box<WrappedCallback>, Box<q::JSValue>)>>,
interrupt_handler: Mutex<Option<Box<InterruptHandlerWrapper>>>
}

impl Drop for ContextWrapper {
Expand Down Expand Up @@ -380,6 +405,7 @@ impl ContextWrapper {
runtime,
context,
callbacks: Mutex::new(Vec::new()),
interrupt_handler: Mutex::new(None)
};

Ok(wrapper)
Expand Down Expand Up @@ -501,7 +527,7 @@ impl ContextWrapper {
}

/// Returns `Result::Err` when an error ocurred.
pub(crate) fn ensure_no_excpetion(&self) -> Result<(), ExecutionError> {
pub(crate) fn ensure_no_exception(&self) -> Result<(), ExecutionError> {
if let Some(e) = self.get_exception() {
Err(e)
} else {
Expand Down Expand Up @@ -734,4 +760,19 @@ impl ContextWrapper {
global.set_property(name, cfunc.into_value())?;
Ok(())
}

pub fn set_interrupt_handler<'a, F: Fn() -> bool + 'static + RefUnwindSafe>(&'a self, handler: F) {
let wrapper = move |_rt: *mut q::JSRuntime| {
let result = std::panic::catch_unwind(|| handler());
match result {
Ok(false) => 0,
_ => 1
}
};
let pair = interrupt_handler_trampoline(wrapper);
*self.interrupt_handler.lock().unwrap() = Some(pair.0.0);
unsafe {
q::JS_SetInterruptHandler(self.runtime, Some(pair.1), pair.0.1)
};
}
}
11 changes: 9 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ mod value;
#[cfg(test)]
mod tests;

use std::{convert::TryFrom, error, fmt};
use std::{convert::TryFrom, error, fmt, panic::RefUnwindSafe};

pub use self::{
callback::{Arguments, Callback},
Expand Down Expand Up @@ -355,7 +355,7 @@ impl Context {
/// use quick_js::{Context, JsValue};
/// let context = Context::new().unwrap();
///
/// // Register a closue as a callback under the "add" name.
/// // Register a closure as a callback under the "add" name.
/// // The 'add' function can now be called from Javascript code.
/// context.add_callback("add", |a: i32, b: i32| { a + b }).unwrap();
///
Expand All @@ -373,4 +373,11 @@ impl Context {
) -> Result<(), ExecutionError> {
self.wrapper.add_callback(name, callback)
}

/// Set an interrupt handler callback.
/// This is "regularly called by the engine when it is executing code".
/// This must return a `bool`. If its value is `true`, or the handler function panics, JS execution halts.
pub fn set_interrupt_handler<F: Fn() -> bool + 'static + RefUnwindSafe>(&self, handler: F) {
self.wrapper.set_interrupt_handler(handler);
}
}
14 changes: 14 additions & 0 deletions src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -622,3 +622,17 @@ fn test_global_setter() {
ctx.set_global("a", "a").unwrap();
ctx.eval("a + 1").unwrap();
}

// test interrupt handler, ensuring that closure data works
#[test]
fn test_interrupt_handler() {
use std::sync::atomic::{AtomicUsize, Ordering};
let ctx = Context::new().unwrap();
let arg = AtomicUsize::new(0);
ctx.set_interrupt_handler(move || {
let counter = arg.fetch_add(1, Ordering::Relaxed);
println!("{}", counter);
counter == 10
});
assert_eq!(ctx.eval("while (1) {}"), Err(ExecutionError::Exception(JsValue::String("InternalError: interrupted".to_string()))));
}