Truly independent web browser
LibJS: Let a promise resolve where the stack is full
Andreas Klingae8f64e24b80
diff --git a/Libraries/LibJS/Rust/src/interpreter/interpreter_stack.rs b/Libraries/LibJS/Rust/src/interpreter/interpreter_stack.rsindex 5034d454445..1c6684ef686 100644--- a/Libraries/LibJS/Rust/src/interpreter/interpreter_stack.rs+++ b/Libraries/LibJS/Rust/src/interpreter/interpreter_stack.rs@@ -24,6 +24,10 @@ pub struct InterpreterStackMemory {impl InterpreterStackMemory {const SIZE: usize = 8 * 1024 * 1024;++ /// What lies past the limit, for allocate_past_limit(). Once a frame is in here, no script can get a frame until it+ /// is gone. So this holds what the steps of a native function nest to at most.+ const RESERVE_SIZE: usize = 64 * 1024;const LAYOUT: Layout = match Layout::from_size_align(Self::SIZE, align_of::<ExecutionContext>()) {Ok(layout) => layout,Err(_) => panic!("the interpreter stack layout is valid"),@@ -42,7 +46,7 @@ impl InterpreterStackMemory {InterpreterStack {base: Cell::new(base),top: Cell::new(base),- limit: Cell::new(base.wrapping_add(Self::SIZE)),+ limit: Cell::new(base.wrapping_add(Self::SIZE - Self::RESERVE_SIZE)),next_frame_id: Cell::new(1),}}@@ -67,6 +71,36 @@ impl InterpreterStack {registers_and_locals_count: u32,constant_count: u32,argument_count: u32,+ ) -> Option<NonNull<ExecutionContext>> {+ self.allocate_below(+ self.limit.get(),+ registers_and_locals_count,+ constant_count,+ argument_count,+ )+ }++ /// As allocate(), for a call that must not fail on a stack that is full: it uses the reserve past the limit.+ pub fn allocate_past_limit(+ &self,+ registers_and_locals_count: u32,+ constant_count: u32,+ argument_count: u32,+ ) -> Option<NonNull<ExecutionContext>> {+ self.allocate_below(+ self.base.get().wrapping_add(InterpreterStackMemory::SIZE),+ registers_and_locals_count,+ constant_count,+ argument_count,+ )+ }++ fn allocate_below(+ &self,+ end: *mut u8,+ registers_and_locals_count: u32,+ constant_count: u32,+ argument_count: u32,) -> Option<NonNull<ExecutionContext>> {let slot_count = registers_and_locals_count.checked_add(constant_count)?@@ -74,12 +108,12 @@ impl InterpreterStack {let size = size_of::<ExecutionContext>() + slot_count as usize * size_of::<Value>();let size = size.next_multiple_of(align_of::<ExecutionContext>());let top = self.top.get();- if (self.limit.get() as usize) - (top as usize) < size {+ if (end as usize).saturating_sub(top as usize) < size {return None;}let frame_id = self.take_next_frame_id();let context = top.cast::<ExecutionContext>();- // SAFETY: The frame fits between top and limit, and nothing else uses that memory.+ // SAFETY: The frame fits between top and the end, and nothing else uses that memory.unsafe {ExecutionContext::initialize_at(context,diff --git a/Libraries/LibJS/Rust/src/runtime/abstract_operations.rs b/Libraries/LibJS/Rust/src/runtime/abstract_operations.rsindex a3814b75a3c..aad4f1a0f9f 100644--- a/Libraries/LibJS/Rust/src/runtime/abstract_operations.rs+++ b/Libraries/LibJS/Rust/src/runtime/abstract_operations.rs@@ -142,11 +142,20 @@ fn with_callee_context<T>(let stack = vm.interpreter_stack();let stack_mark = stack.top.get();- let Some(callee_context) = stack.allocate(+ let (registers_and_locals_count, constant_count, argument_count) = (stack_frame_info.registers_and_locals_count,stack_frame_info.constant_count,stack_frame_info.argument_count,- ) else {+ );+ let callee_context = stack+ .allocate(registers_and_locals_count, constant_count, argument_count)+ .or_else(|| {+ function+ .ignores_stack_space_limit()+ .then(|| stack.allocate_past_limit(registers_and_locals_count, constant_count, argument_count))+ .flatten()+ });+ let Some(callee_context) = callee_context else {return vm.throw_completion(ErrorKind::InternalError, ErrorType::CallStackSizeExceeded, &[]);};let _deallocate_guard = ScopeGuard::new(|| stack.deallocate(stack_mark));diff --git a/Libraries/LibJS/Rust/src/runtime/native_function.rs b/Libraries/LibJS/Rust/src/runtime/native_function.rsindex c3e9e70036d..6c6b40736e3 100644--- a/Libraries/LibJS/Rust/src/runtime/native_function.rs+++ b/Libraries/LibJS/Rust/src/runtime/native_function.rs@@ -29,6 +29,8 @@ pub use crate::layout_forward::{RawNativeFunctionPointer, RawNativeFunctionResuluse crate::runtime::abstract_operations::new_function_environment_for_native_javascript_backed_function;use crate::runtime::class_field_definition::ClassElementName;use crate::runtime::completion::{Throw, ThrowCompletionOr};+use crate::runtime::error::ErrorKind;+use crate::runtime::error_types::ErrorType;use crate::runtime::function_object::{FUNCTION_OBJECT_METHODS, FunctionObject};use crate::runtime::native_javascript_backed_function::NativeJavaScriptBackedFunction;use crate::runtime::object::{MayInterfereWithIndexedPropertyAccess, ObjectMethods, allocate_object};@@ -42,6 +44,8 @@ pub struct NativeFunctionMethods {pub construct: fn(&NativeFunction, &Vm, Gc<FunctionObject>) -> ThrowCompletionOr<Gc<Object>>,pub function_environment_needed: fn(&NativeFunction) -> bool,pub function_environment_bindings_count: fn(&NativeFunction) -> usize,+ /// For a function that the embedder calls as a step that cannot fail. Its own steps must have a bounded stack use.+ pub ignores_stack_space_limit: bool,}pub static NATIVE_FUNCTION_VIRTUAL_METHODS: NativeFunctionMethods = NativeFunctionMethods {@@ -50,6 +54,7 @@ pub static NATIVE_FUNCTION_VIRTUAL_METHODS: NativeFunctionMethods = NativeFuncticonstruct: |_, _, _| unreachable!("NativeFunction::construct has to be overridden"),function_environment_needed: |_| false,function_environment_bindings_count: |_| 0,+ ignores_stack_space_limit: false,};pub static NATIVE_FUNCTION_METHODS: ObjectMethods = ObjectMethods {@@ -334,7 +339,10 @@ impl NativeFunction {// </8.> --------------------------------------------------------------------------// 9. Push calleeContext onto the execution context stack; calleeContext is now the running execution context.- vm.push_execution_context_checking_stack_space(NonNull::from(callee_context))?;+ if vm.did_reach_stack_space_limit() && !function.methods().ignores_stack_space_limit {+ return vm.throw_completion(ErrorKind::InternalError, ErrorType::CallStackSizeExceeded, &[]);+ }+ vm.push_execution_context(NonNull::from(callee_context));// 10. Let result be the Completion Record that is the result of evaluating F in a manner that conforms to the specification of F. thisArgument is the this value, argumentsList provides the named parameters, and the NewTarget value is undefined.let result = function.call(vm);diff --git a/Libraries/LibJS/Rust/src/runtime/object.rs b/Libraries/LibJS/Rust/src/runtime/object.rsindex 61fd1e1a162..079ec675c8a 100644--- a/Libraries/LibJS/Rust/src/runtime/object.rs+++ b/Libraries/LibJS/Rust/src/runtime/object.rs@@ -2077,6 +2077,12 @@ impl Object {(self.methods().function_realm)(self)}+ /// See NativeFunctionMethods::ignores_stack_space_limit.+ pub fn ignores_stack_space_limit(&self) -> bool {+ self.native_function_methods()+ .is_some_and(|methods| methods.ignores_stack_space_limit)+ }+pub fn name_for_call_stack(&self) -> Utf16String {(self.methods().name_for_call_stack)(self)}diff --git a/Libraries/LibJS/Rust/src/runtime/promise_resolving_function.rs b/Libraries/LibJS/Rust/src/runtime/promise_resolving_function.rsindex b14e60252c4..67d444d68fd 100644--- a/Libraries/LibJS/Rust/src/runtime/promise_resolving_function.rs+++ b/Libraries/LibJS/Rust/src/runtime/promise_resolving_function.rs@@ -45,6 +45,9 @@ const _: () = assert!(size_of::<PromiseResolvingFunction>() == 88);static PROMISE_RESOLVING_FUNCTION_VIRTUAL_METHODS: NativeFunctionMethods = NativeFunctionMethods {call: PromiseResolvingFunction::call,+ // NB: An embedder resolves a promise as a step that cannot throw, and it can do so at any stack depth. What these+ // steps run of script, a "then" getter, is a checked call of its own, and its error rejects the promise.+ ignores_stack_space_limit: true,..NATIVE_FUNCTION_VIRTUAL_METHODS};diff --git a/Tests/LibWeb/Text/expected/Workers/worker-promise-at-stack-limit.txt b/Tests/LibWeb/Text/expected/Workers/worker-promise-at-stack-limit.txtnew file mode 100644index 00000000000..f6563985ac2--- /dev/null+++ b/Tests/LibWeb/Text/expected/Workers/worker-promise-at-stack-limit.txt@@ -0,0 +1 @@+finisheddiff --git a/Tests/LibWeb/Text/input/Workers/worker-promise-at-stack-limit.html b/Tests/LibWeb/Text/input/Workers/worker-promise-at-stack-limit.htmlnew file mode 100644index 00000000000..969d27cbf85--- /dev/null+++ b/Tests/LibWeb/Text/input/Workers/worker-promise-at-stack-limit.html@@ -0,0 +1,26 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ const SCRIPT = `+ const blob = new Blob(["x"]);+ let calls = 0;+ function recurse() {+ try {+ recurse();+ } catch {}+ if (calls++ < 200) {+ try {+ blob.text();+ } catch {}+ }+ }+ recurse();+ postMessage("finished");+ `;++ // NB: Resolving a promise is a step that cannot fail, also where the stack has no room for a script function anymore.+ promiseTest(async () => {+ const worker = new Worker(URL.createObjectURL(new Blob([SCRIPT], { type: "text/javascript" })));+ println(await new Promise(resolve => (worker.onmessage = event => resolve(event.data))));+ });+</script>