Skip to content

Truly independent web browser

LibJS: Call capturing native functions directly from JIT code

Timothy Flynna367e24105fa
diff --git a/Libraries/LibJS/JIT/ARCHITECTURE.md b/Libraries/LibJS/JIT/ARCHITECTURE.md
index b36304b767e..4dbe756e655 100644
--- a/Libraries/LibJS/JIT/ARCHITECTURE.md
+++ b/Libraries/LibJS/JIT/ARCHITECTURE.md
@@ -224,7 +224,7 @@ Exits: E = eager, L = lazy. Every node that can exit has a frame state. "Call" m
| SliceArguments | `Array.prototype.slice.call(arguments, start)` of an arguments object never created. | E | Frame | | call, allocates |
| **Calls** | | | | | |
| CallDirect | A `Call` to its feedback's ECMAScript target, entering its code directly. | L, throws | Any | Any | call, allocates |
-| CallNative | A `Call` to its feedback's native target, in the interpreter's lightweight frame. | L, throws | Any | Any | call, allocates |
+| CallNative | A `Call` to its feedback's raw or capturing native target, in the interpreter's lightweight frame. Capturing functions enter through a thunk that reads the function from that frame. | L, throws | Any | Any | call, allocates |
| CallNativeAccessor | The raw native getter (of a `GetById` or `GetLength`) or setter (of a `PutById`) that the checks before it established the property has, called like `CallNative` calls its target. A getter of a platform object attribute backed by a field reads the main world wrapper it would return inline where there is one, if the interpreter validated the cache entries for that. The getter's result (for the setter, its result too). | L, throws | Any | Any | call, allocates |
| CallForwardingArguments | `f.apply(this, arguments)` with an arguments object never created. | L, throws | Any | Any | call, allocates |
| CallSlowPath | One bytecode instruction through the interpreter's slow path, on SSA operands, with SSA outputs, with a frame state after the instruction. `saves_registers`: in a cold block, preserving every register. | L unless it saves registers; throws per opcode | Any | Any | call unless it saves registers; allocates |
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs b/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs
index 32ec28758e1..2fc67be65e3 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs
@@ -463,7 +463,7 @@ impl GraphBuilder<'_> {
}
/// Builds a `Call` whose feedback saw a single callee that JIT code can
- /// call directly as a `CallDirect` node (or a `CallNative` node for raw
+ /// call directly as a `CallDirect` node (or a `CallNative` node for
/// native functions), or returns `None` if it did not.
pub(super) fn try_direct_call(&mut self, instruction: &Instruction) -> Result<Option<Flow>, CompileFailure> {
let Instruction::Call {
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/call.rs b/Libraries/LibJS/JIT/Rust/src/codegen/call.rs
index 1aa2a0062e2..03b24a868f0 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/call.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/call.rs
@@ -20,7 +20,7 @@
//! (`RuntimeInfo::dynamic_calls`). Calls the fast path cannot make take the
//! generic path through `RuntimeInfo::jit_call`.
//!
-//! Native calls (`Op::CallNative`): JIT code calls the single raw native
+//! Native calls (`Op::CallNative`): JIT code calls the single native
//! function a `Call` instruction saw in the lightweight frame the
//! interpreter's `Call` fast path builds for raw native functions, and lets
//! the runtime unwind the frame if the function throws.
@@ -1061,7 +1061,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
self.masm.branch_if_stack_pointer_below(&limit, slow);
}
- /// `CallNative`: calls the raw native function a `Call` instruction saw
+ /// `CallNative`: calls the native function a `Call` instruction saw
/// the way the interpreter's `Call` fast path does: in a lightweight frame
/// without an executable, linked to the calling frame, whose slots are
/// the arguments. Other callees take the generic path.
diff --git a/Libraries/LibJS/JIT/Rust/src/snapshot.rs b/Libraries/LibJS/JIT/Rust/src/snapshot.rs
index f7dd8c29043..a18bb20a50e 100644
--- a/Libraries/LibJS/JIT/Rust/src/snapshot.rs
+++ b/Libraries/LibJS/JIT/Rust/src/snapshot.rs
@@ -590,8 +590,9 @@ impl FunctionFrameFields {
}
}
-/// A raw native function that JIT code calls directly, in the lightweight
+/// A native function that JIT code calls directly, in the lightweight
/// frame the interpreter's call fast path builds for raw native functions.
+/// Capturing native functions use an entry that reads the function from that frame.
/// The compiled code must list `function` and `realm` in
/// `CompiledCode::embedded_cells`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
diff --git a/Libraries/LibJS/Rust/src/jit/snapshot.rs b/Libraries/LibJS/Rust/src/jit/snapshot.rs
index b67eaf587e2..a6b297b46d8 100644
--- a/Libraries/LibJS/Rust/src/jit/snapshot.rs
+++ b/Libraries/LibJS/Rust/src/jit/snapshot.rs
@@ -37,7 +37,7 @@ use crate::interpreter::vm::Vm;
use crate::layout::cell::{CellHeader, Gc};
use crate::layout::environment::DeclarativeEnvironment;
use crate::layout::function_object::{
- DirectGetterFunction, EcmascriptFunctionObject, FunctionObject, RawNativeFunction,
+ DirectGetterFunction, EcmascriptFunctionObject, FunctionObject, NativeFunction, RawNativeFunction,
};
use crate::layout::object::{Object, TYPED_ARRAY_CACHED_DATA_OFFSET_INVALID, TypedArrayBase};
use crate::layout::property_lookup_cache::{GlobalVariableCache, PropertyLookupCache, PropertyLookupCacheEntryType};
@@ -341,16 +341,23 @@ fn direct_call_target(feedback: &CallFeedback) -> Option<(Gc<EcmascriptFunctionO
function.can_inline_call().then_some((function, closures))
}
-/// The target of a call site if it is a raw native function that JIT code can call directly, in the frame the
+/// The target and entry of a call site if it is a native function that JIT code can call directly, in the frame the
/// interpreter's call fast path builds for it. Function.prototype.call and apply forward their calls, which the runtime
/// does for JIT code.
-fn native_call_target(vm: &Vm, feedback: &CallFeedback) -> Option<Gc<RawNativeFunction>> {
+fn native_call_target(vm: &Vm, feedback: &CallFeedback) -> Option<(Gc<NativeFunction>, u64)> {
if !RAW_NATIVE_FUNCTIONS_RETURN_IN_REGISTERS || feedback.flags.get() & call_feedback_flags::POLYMORPHIC != 0 {
return None;
}
- let function = feedback.target()?.downcast::<RawNativeFunction>()?;
- (!FunctionPrototype::is_call_function(vm, &function) && !FunctionPrototype::is_apply_function(vm, &function))
- .then_some(function)
+ let function = feedback.target()?.downcast::<NativeFunction>()?;
+ let entry = if let Some(raw) = function.downcast::<RawNativeFunction>() {
+ if FunctionPrototype::is_call_function(vm, &raw) || FunctionPrototype::is_apply_function(vm, &raw) {
+ return None;
+ }
+ raw.native_function(vm)?
+ } else {
+ function.capturing_call_entry()?
+ };
+ Some((function, entry as usize as u64))
}
/// The words of an ECMAScript function its frames start with, which stay the same for its lifetime.
@@ -910,10 +917,7 @@ impl SnapshotBuilder<'_> {
&& !(closures && environment.is_some())
{
snapshot.direct_call = Some(self.direct_call_target_snapshot(function, environment, closures));
- } else if let Some(function) = native_call_target(self.vm, call) {
- let entry = function
- .native_function(self.vm)
- .map_or(0, |pointer| pointer as usize as u64);
+ } else if let Some((function, entry)) = native_call_target(self.vm, call) {
snapshot.native_call = Some(NativeCallTarget {
function: self.cell(function),
realm: self.cell(function.realm()),
diff --git a/Libraries/LibJS/Rust/src/runtime/native_function.rs b/Libraries/LibJS/Rust/src/runtime/native_function.rs
index ac60fd71c31..c3e9e70036d 100644
--- a/Libraries/LibJS/Rust/src/runtime/native_function.rs
+++ b/Libraries/LibJS/Rust/src/runtime/native_function.rs
@@ -244,6 +244,16 @@ impl NativeFunction {
function.native_function.captures().downcast_ref::<C>()
}
+ /// The entry JIT code can call in an already initialized native frame, if this is a capturing native function.
+ #[cfg(feature = "jit")]
+ pub(crate) fn capturing_call_entry(&self) -> RawNativeFunctionPointer {
+ self.as_native_function_gc().downcast::<CapturingNativeFunction>()?;
+ crate::raw_native!(|vm| {
+ let function = vm.active_function_object().expect("the native frame has its function");
+ CapturingNativeFunction::call(cast_ref(&*function), vm)
+ })
+ }
+
pub fn as_native_function_gc(&self) -> Gc<NativeFunction> {
Gc::from_ref(self)
}
diff --git a/Tests/LibJS/Runtime/jit/capturing-native-calls.js b/Tests/LibJS/Runtime/jit/capturing-native-calls.js
new file mode 100644
index 00000000000..cccbf25e193
--- /dev/null
+++ b/Tests/LibJS/Runtime/jit/capturing-native-calls.js
@@ -0,0 +1,50 @@
+test("capturing native calls retain their state and guard the target", () => {
+ const first = Proxy.revocable({}, {});
+ const second = Proxy.revocable({}, {});
+ function invoke(revoke) {
+ return revoke();
+ }
+ jit.prepare(invoke);
+ for (let i = 0; i < 20; ++i) expect(invoke(first.revoke)).toBeUndefined();
+ expect(jit.compile(invoke) || !jit.enabled).toBeTrue();
+ gc();
+ expect(invoke(first.revoke)).toBeUndefined();
+ expect(Reflect.ownKeys(second.proxy)).toEqual([]);
+ expect(invoke(second.revoke)).toBeUndefined();
+ expect(() => Reflect.ownKeys(second.proxy)).toThrow(TypeError);
+ expect(invoke(() => 42)).toBe(42);
+});
+
+test("exceptions from capturing native calls unwind inlined callers", () => {
+ const failures = compareCompiledWithInterpreter(
+ () => {
+ function strictArguments() {
+ "use strict";
+ return arguments;
+ }
+ const thrower = Object.getOwnPropertyDescriptor(strictArguments(), "callee").get;
+ function inner(value) {
+ thrower(value);
+ }
+ function middle(value) {
+ return inner(value);
+ }
+ return (value, log) => {
+ gc();
+ try {
+ return middle(value);
+ } catch (error) {
+ log.push(error instanceof TypeError);
+ return value;
+ } finally {
+ log.push("finally");
+ }
+ };
+ },
+ {
+ warmUp: (log, i) => [i, log],
+ probes: { object: log => [{ marker: 42 }, log] },
+ }
+ );
+ expect(failures).toEqual([]);
+});