Skip to content
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
6 changes: 6 additions & 0 deletions src/binding.cc
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,12 @@ void v8__Isolate__SetUseCounterCallback(
isolate->SetUseCounterCallback(callback);
}

void v8__Isolate__SetModifyCodeGenerationFromStringsCallback(
v8::Isolate* isolate,
v8::ModifyCodeGenerationFromStringsCallback2 callback) {
isolate->SetModifyCodeGenerationFromStringsCallback(callback);
}

bool v8__Isolate__AddMessageListener(v8::Isolate* isolate,
v8::MessageCallback callback) {
return isolate->AddMessageListener(callback);
Expand Down
37 changes: 37 additions & 0 deletions src/isolate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -554,6 +554,22 @@ pub struct OomDetails {
pub type OomErrorCallback =
unsafe extern "C" fn(location: *const char, details: &OomDetails);

#[repr(C)]
pub struct ModifyCodeGenerationFromStringsResult<'s> {
pub codegen_allowed: bool,
pub modified_source: Option<Local<'s, String>>,
}

// We use Option<NonNull<T>> which _is_ FFI-safe.
// See https://doc.rust-lang.org/nomicon/other-reprs.html
#[allow(improper_ctypes_definitions)]
pub type ModifyCodeGenerationFromStringsCallback<'s> =
extern "C" fn(
context: Local<'s, Context>,
source: Local<'s, Value>,
is_code_like: bool,
) -> ModifyCodeGenerationFromStringsResult<'s>;

// Windows x64 ABI: MaybeLocal<Value> returned on the stack.
#[cfg(target_os = "windows")]
pub type PrepareStackTraceCallback<'s> =
Expand Down Expand Up @@ -713,6 +729,13 @@ unsafe extern "C" {
isolate: *mut Isolate,
callback: UseCounterCallback,
);
// We use Option<NonNull<T>> which _is_ FFI-safe.
// See https://doc.rust-lang.org/nomicon/other-reprs.html
#[allow(improper_ctypes)]
fn v8__Isolate__SetModifyCodeGenerationFromStringsCallback(
isolate: *mut Isolate,
callback: ModifyCodeGenerationFromStringsCallback,
);
fn v8__Isolate__RequestInterrupt(
isolate: *const Isolate,
callback: InterruptCallback,
Expand Down Expand Up @@ -1405,6 +1428,20 @@ impl Isolate {
unsafe { v8__Isolate__RemoveGCEpilogueCallback(self, callback, data) }
}

/// This specifies the callback called by v8 when JS is trying to dynamically execute
/// code using `eval` or the `Function` constructor.
///
/// The callback can decide whether to allow code generation and, if so, modify
/// the source code beforehand.
pub fn set_modify_code_generation_from_strings_callback(
&mut self,
callback: ModifyCodeGenerationFromStringsCallback,
) {
unsafe {
v8__Isolate__SetModifyCodeGenerationFromStringsCallback(self, callback)
}
}

/// Add a callback to invoke in case the heap size is close to the heap limit.
/// If multiple callbacks are added, only the most recently added callback is
/// invoked.
Expand Down
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,8 @@ pub use isolate::MemoryPressureLevel;
pub use isolate::MessageCallback;
pub use isolate::MessageErrorLevel;
pub use isolate::MicrotasksPolicy;
pub use isolate::ModifyCodeGenerationFromStringsCallback;
pub use isolate::ModifyCodeGenerationFromStringsResult;
pub use isolate::ModuleImportPhase;
pub use isolate::NearHeapLimitCallback;
pub use isolate::OomDetails;
Expand Down
46 changes: 46 additions & 0 deletions tests/test_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12018,6 +12018,52 @@ fn use_counter_callback() {
assert_eq!(COUNT.load(Ordering::Relaxed), 1);
}

#[test]
fn code_generation_from_strings_callback() {
static CODEGEN_ALLOWED: AtomicBool = AtomicBool::new(false);
static COUNT: AtomicUsize = AtomicUsize::new(0);

#[allow(improper_ctypes_definitions)]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if we should change how Local is defined to avoid this..?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I'm not sure how to fix this either. It pretty much boils down to a Option<NonNull<T>>, which should be safe over FFI, but maybe the type with PhantomData is too complex for the compiler to detect it as such.

extern "C" fn callback<'s>(
_context: v8::Local<'s, v8::Context>,
_source: v8::Local<'s, v8::Value>,
_is_code_like: bool,
) -> v8::ModifyCodeGenerationFromStringsResult<'s> {
COUNT.fetch_add(1, Ordering::Relaxed);
v8::ModifyCodeGenerationFromStringsResult {
codegen_allowed: CODEGEN_ALLOWED.load(Ordering::Relaxed),
modified_source: None,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use modified_source to demonstrate the feature

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi, sorry for the late reply!

All relevant APIs used to interact with V8 strings seem to require a reference to a HandleScope, which isn't available in the callback. Therefore, it doesn't seem to be possible to create a new string for the modified source. I could return the source parameter unmodified, but the effect would be equivalent to returning None anyway.

I'm aware that this is a pretty big limitation. I guess providing a HandleScope in the callback would be more complex than the current solution where I'm directly passing the extern "C" function, but I could try to look into how some of the other callbacks are implemented.

}
}

let _setup_guard = setup::parallel_test();
let mut isolate = v8::Isolate::new(Default::default());
isolate.set_modify_code_generation_from_strings_callback(callback);
let mut scope = v8::HandleScope::new(&mut isolate);
let context = v8::Context::new(&mut scope, Default::default());
// Must be set to false, otherwise code generation is unconditionally allowed and the callback is never used
context.set_allow_generation_from_strings(false);

let scope = &mut v8::ContextScope::new(&mut scope, context);

// Code generation should be disallowed
{
let tc = &mut v8::TryCatch::new(scope);
eval(tc, "eval('1 + 1')");
assert_eq!(
tc.message().unwrap().get(tc).to_rust_string_lossy(tc),
"Uncaught EvalError: Code generation from strings disallowed for this context"
);
assert_eq!(COUNT.load(Ordering::Relaxed), 1);
}

// Enable code generation
CODEGEN_ALLOWED.store(true, Ordering::Relaxed);
let result: Option<v8::Local<'_, v8::Value>> = eval(scope, "eval('1 + 1')");
assert_eq!(result.unwrap().number_value(scope).unwrap(), 2.0);
assert_eq!(COUNT.load(Ordering::Relaxed), 2);
}

#[test]
fn test_eternals() {
let _setup_guard = setup::parallel_test();
Expand Down
Loading