Skip to content

Truly independent web browser

LibJS+LibWeb: Keep at most Error.stackTraceLimit frames in error stacks

Andreas Kling15a9f6ed4871
diff --git a/Libraries/LibJS/Runtime/ErrorData.cpp b/Libraries/LibJS/Runtime/ErrorData.cpp
index 66038a57369..1b1b5310777 100644
--- a/Libraries/LibJS/Runtime/ErrorData.cpp
+++ b/Libraries/LibJS/Runtime/ErrorData.cpp
@@ -56,4 +56,11 @@ GC::Ref<ErrorDataCell> ErrorDataCell::capture(VM& vm)
return cell_ref_from_abi<ErrorDataCell>(cell);
}
+GC::Ref<ErrorDataCell> ErrorDataCell::capture_whole_stack(VM& vm)
+{
+ auto* cell = js_error_data_cell_capture_whole_stack(vm_to_abi(vm));
+ VERIFY(cell);
+ return cell_ref_from_abi<ErrorDataCell>(cell);
+}
+
}
diff --git a/Libraries/LibJS/Runtime/ErrorData.h b/Libraries/LibJS/Runtime/ErrorData.h
index 4f2b7858cac..6c21a7f15b7 100644
--- a/Libraries/LibJS/Runtime/ErrorData.h
+++ b/Libraries/LibJS/Runtime/ErrorData.h
@@ -60,6 +60,10 @@ class JS_API ErrorDataCell final : public EngineCell {
public:
static GC::Ref<ErrorDataCell> capture(VM&);
+ // Every frame of the call stack, whatever Error.stackTraceLimit is, for a trace of the running code that is not the
+ // stack of an error.
+ static GC::Ref<ErrorDataCell> capture_whole_stack(VM&);
+
ErrorData& error_data() { return *reinterpret_cast<ErrorData*>(this); }
ErrorData const& error_data() const { return *reinterpret_cast<ErrorData const*>(this); }
};
diff --git a/Libraries/LibJS/Runtime/VM.cpp b/Libraries/LibJS/Runtime/VM.cpp
index e2671fee97d..2de7b4d3794 100644
--- a/Libraries/LibJS/Runtime/VM.cpp
+++ b/Libraries/LibJS/Runtime/VM.cpp
@@ -543,6 +543,11 @@ Vector<StackTraceElement> VM::stack_trace() const
return stack_trace;
}
+Optional<SourceRange> VM::innermost_source_range() const
+{
+ return source_range_from_abi(js_vm_innermost_source_range(vm_abi(*this)));
+}
+
Optional<SourceRange> VM::take_throw_site_of(Value value)
{
auto throw_site = source_range_from_abi(js_vm_throw_site_of(vm_abi(*this), value_to_abi(value)));
diff --git a/Libraries/LibJS/Runtime/VM.h b/Libraries/LibJS/Runtime/VM.h
index c5834fad25e..8d1acabd15e 100644
--- a/Libraries/LibJS/Runtime/VM.h
+++ b/Libraries/LibJS/Runtime/VM.h
@@ -462,6 +462,9 @@ public:
// throw.
[[nodiscard]] Optional<SourceRange> take_throw_site_of(Value);
+ // The source range of the innermost frame on the stack that has one, as the first such element of stack_trace().
+ [[nodiscard]] Optional<SourceRange> innermost_source_range() const;
+
private:
friend class InterpreterStack;
friend struct HostHookThunks;
diff --git a/Libraries/LibJS/Rust/src/embedding/error.rs b/Libraries/LibJS/Rust/src/embedding/error.rs
index 54a9b7b248c..d138d28b4aa 100644
--- a/Libraries/LibJS/Rust/src/embedding/error.rs
+++ b/Libraries/LibJS/Rust/src/embedding/error.rs
@@ -202,8 +202,8 @@ pub unsafe extern "C" fn js_error_data_stack_string(
owned_utf16_string_into_abi(error_data.stack_string(compact))
}
-/// How many frames the call stack of `error_data` has, the outermost execution context included. Call on the VM's
-/// thread.
+/// How many frames the call stack of `error_data` has, the outermost execution context included when the stack was not
+/// cut at Error.stackTraceLimit. Call on the VM's thread.
///
/// # Safety
///
@@ -276,3 +276,16 @@ pub unsafe extern "C" fn js_error_data_cell_capture(vm: *mut JSVM) -> *mut JSErr
let vm = unsafe { vm_from_abi(vm) };
cell_into_abi(ErrorDataCell::capture(vm))
}
+
+/// ErrorDataCell::capture_whole_stack(vm): error data with every frame of the current call stack, whatever
+/// Error.stackTraceLimit is, for a trace of the running code that is not the stack of an error. Call on the VM's thread.
+///
+/// # Safety
+///
+/// `vm` must be the embedder's VM.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn js_error_data_cell_capture_whole_stack(vm: *mut JSVM) -> *mut JSErrorDataCell {
+ // SAFETY: The caller passes its VM.
+ let vm = unsafe { vm_from_abi(vm) };
+ cell_into_abi(ErrorDataCell::capture_whole_stack(vm))
+}
diff --git a/Libraries/LibJS/Rust/src/embedding/vm.rs b/Libraries/LibJS/Rust/src/embedding/vm.rs
index 24ac2b10e1b..47266e16e21 100644
--- a/Libraries/LibJS/Rust/src/embedding/vm.rs
+++ b/Libraries/LibJS/Rust/src/embedding/vm.rs
@@ -148,6 +148,19 @@ pub unsafe extern "C" fn js_vm_throw_site_of(vm: *mut JSVM, value: JSValue) -> J
source_range_into_abi(vm.throw_site_of(value_from_abi(value)).as_ref())
}
+/// VM::innermost_source_range(): the source range of the innermost frame on the stack that has one, or none. Only the
+/// VM's thread may call this.
+///
+/// # Safety
+///
+/// `vm` must be a live VM.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn js_vm_innermost_source_range(vm: *mut JSVM) -> JSDebuggerSourceRange {
+ // SAFETY: The caller passes a live VM.
+ let vm = unsafe { vm_from_abi(vm) };
+ source_range_into_abi(vm.innermost_source_range().as_ref())
+}
+
/// VM::take_throw_site_of(): forgets where `value` was thrown, if it is the last exception thrown. Only the VM's thread
/// may call this.
///
diff --git a/Libraries/LibJS/Rust/src/interpreter/vm.rs b/Libraries/LibJS/Rust/src/interpreter/vm.rs
index a88b8961fd6..467682aa542 100644
--- a/Libraries/LibJS/Rust/src/interpreter/vm.rs
+++ b/Libraries/LibJS/Rust/src/interpreter/vm.rs
@@ -1534,24 +1534,30 @@ impl Vm {
pub fn stack_trace(&self) -> MarkedVec<'_, StackTraceElement> {
let stack_trace = MarkedVec::new(self);
self.for_each_stack_frame_top_to_bottom(|frame| {
- // NB: Builtins written in JavaScript show up like other builtins, without a position in their source.
- let runs_builtin = frame
- .function
- .is_some_and(|function| function.is::<NativeJavaScriptBackedFunction>());
- let source_range = frame
- .executable
- .filter(|_| !runs_builtin)
- .map(|executable| executable.get_source_range(frame.program_counter));
stack_trace.push(StackTraceElement {
execution_context: NonNull::from(frame.execution_context),
function: frame.function,
- source_range,
+ source_range: frame.source_range(),
});
ControlFlow::Continue(())
});
stack_trace
}
+ /// The source range of the innermost frame that has one, as the first such element of stack_trace() has, without
+ /// walking the rest of the stack.
+ pub fn innermost_source_range(&self) -> Option<SourceRange> {
+ let mut source_range = None;
+ self.for_each_stack_frame_top_to_bottom(|frame| {
+ source_range = frame.source_range();
+ if source_range.is_some() {
+ return ControlFlow::Break(());
+ }
+ ControlFlow::Continue(())
+ });
+ source_range
+ }
+
/// Calls `callback` with each frame from the running one down, until it breaks, like
/// for_each_execution_context_top_to_bottom(), and with the frames of calls that JIT code inlined and runs without
/// execution contexts of their own (see INLINED_CALL_SITE_BIT), between the callee frame of the call they make and
@@ -2469,6 +2475,19 @@ pub struct StackFrame<'a> {
pub inlined_call: Option<InlinedCallStackFrame>,
}
+impl StackFrame<'_> {
+ /// Where the frame is in the source of its executable, which is nowhere for a frame that runs no bytecode.
+ pub fn source_range(&self) -> Option<SourceRange> {
+ // NB: Builtins written in JavaScript show up like other builtins, without a position in their source.
+ let runs_builtin = self
+ .function
+ .is_some_and(|function| function.is::<NativeJavaScriptBackedFunction>());
+ self.executable
+ .filter(|_| !runs_builtin)
+ .map(|executable| executable.get_source_range(self.program_counter))
+ }
+}
+
/// Where the values of a frame of a call that JIT code inlined are: the inlined call site of the code running the
/// execution context of the stack frame, the JIT frame, and the frame's frame state there (see
/// jit::translate::call_site_frame_arguments()).
diff --git a/Libraries/LibJS/Rust/src/runtime/common_property_names.rs b/Libraries/LibJS/Rust/src/runtime/common_property_names.rs
index dcdf0ee1e7e..2ef3ff360ee 100644
--- a/Libraries/LibJS/Rust/src/runtime/common_property_names.rs
+++ b/Libraries/LibJS/Rust/src/runtime/common_property_names.rs
@@ -546,6 +546,7 @@ define_common_property_names! {
SQRT1_2,
SQRT2,
stack,
+ stackTraceLimit,
startOfDay,
startsWith,
status,
diff --git a/Libraries/LibJS/Rust/src/runtime/error_constructor.rs b/Libraries/LibJS/Rust/src/runtime/error_constructor.rs
index d8cdd80f035..e99e014b3bb 100644
--- a/Libraries/LibJS/Rust/src/runtime/error_constructor.rs
+++ b/Libraries/LibJS/Rust/src/runtime/error_constructor.rs
@@ -16,6 +16,7 @@ use crate::runtime::completion::ThrowCompletionOr;
use crate::runtime::error::{
Error, EvalError, InternalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError,
};
+use crate::runtime::error_data::DEFAULT_STACK_TRACE_LIMIT;
use crate::runtime::function_object::FunctionObject;
use crate::runtime::intrinsics::Intrinsics;
use crate::runtime::native_function::{NativeFunction, define_native_function_class, raw_native};
@@ -65,6 +66,14 @@ impl ErrorConstructor {
PropertyAttributes::new(Attribute::CONFIGURABLE),
);
+ // NB: Not in the specification, but the other engines have it: how many frames the stack of a new error keeps.
+ object.define_direct_property(
+ vm,
+ &vm.names.stackTraceLimit,
+ Value::from_i32(DEFAULT_STACK_TRACE_LIMIT),
+ PropertyAttributes::new(Attribute::WRITABLE | Attribute::ENUMERABLE | Attribute::CONFIGURABLE),
+ );
+
let attributes = PropertyAttributes::new(Attribute::WRITABLE | Attribute::CONFIGURABLE);
object.define_native_function(
vm,
diff --git a/Libraries/LibJS/Rust/src/runtime/error_data.rs b/Libraries/LibJS/Rust/src/runtime/error_data.rs
index ab11d94bf34..d2ff29066a5 100644
--- a/Libraries/LibJS/Rust/src/runtime/error_data.rs
+++ b/Libraries/LibJS/Rust/src/runtime/error_data.rs
@@ -5,6 +5,7 @@
*/
use core::cell::Cell;
+use core::ops::ControlFlow;
use ak::Utf16String;
use libjs_runtime_macros::Trace;
@@ -60,29 +61,55 @@ impl StackFrameSyntax {
}
}
+/// The initial value of Error.stackTraceLimit.
+pub const DEFAULT_STACK_TRACE_LIMIT: i32 = 10;
+
+/// How many frames a new error keeps: the value of Error.stackTraceLimit on the %Error% of the current realm, cut to an
+/// integer, with negative numbers and NaN as 0 and Infinity as every frame. None, for no stack at all, when the property
+/// is not a number, which includes an accessor (whose getter is never called) and a deleted property. The other engines
+/// limit their stacks too, and pages read and set this property to see the frames they expect.
+pub fn stack_trace_limit(vm: &Vm) -> Option<usize> {
+ let Some(realm) = vm.current_realm() else {
+ return Some(DEFAULT_STACK_TRACE_LIMIT as usize);
+ };
+ let error_constructor = realm.intrinsics().error_constructor(vm);
+ let value = error_constructor.storage_get(vm, &vm.names.stackTraceLimit)?.value;
+ if value.is_int32() {
+ return Some(usize::try_from(value.as_i32()).unwrap_or(0));
+ }
+ if !value.is_number() {
+ return None;
+ }
+ // NB: The cast saturates, and takes NaN to 0.
+ Some(value.as_f64() as usize)
+}
+
/// [[ErrorData]]: the call stack an error was created on.
#[derive(Trace)]
pub struct ErrorData {
#[gc(untraced)]
traceback: Vec<TracebackFrame>,
+ /// How many of the frames, from the innermost, the stack string shows, or None for an error that captured no stack,
+ /// whose stack is undefined.
+ shown_frame_count: Option<usize>,
cached_string: Cell<Option<Gc<PrimitiveString>>>,
}
impl ErrorData {
pub fn new(vm: &Vm) -> Self {
- Self {
- traceback: Self::populate_stack(vm, 0),
- cached_string: Cell::new(None),
- }
+ Self::capture(vm, 0, stack_trace_limit(vm))
}
/// Error data captured by an Error constructor, whose own frame is the innermost one. A stack string shows the
/// code that called the constructor, never the constructor itself, so that frame is left out.
pub fn new_in_constructor(vm: &Vm) -> Self {
- Self {
- traceback: Self::populate_stack(vm, 1),
- cached_string: Cell::new(None),
- }
+ Self::capture(vm, 1, stack_trace_limit(vm))
+ }
+
+ /// Error data with every frame of the call stack, whatever Error.stackTraceLimit is, for a trace of the running code
+ /// that is not the stack of an error.
+ pub fn with_whole_stack(vm: &Vm) -> Self {
+ Self::capture(vm, 0, Some(usize::MAX))
}
/// Error data for an exception whose source location came from another agent.
@@ -92,6 +119,29 @@ impl ErrorData {
function_name: Utf16String::default(),
cached_source_range: Some(source_range),
}],
+ shown_frame_count: Some(0),
+ cached_string: Cell::new(None),
+ }
+ }
+
+ fn capture(vm: &Vm, skipped_innermost_frames: usize, limit: Option<usize>) -> Self {
+ let Some(limit) = limit else {
+ return Self {
+ traceback: Vec::new(),
+ shown_frame_count: None,
+ cached_string: Cell::new(None),
+ };
+ };
+ let (traceback, reached_limit) = Self::populate_stack(vm, skipped_innermost_frames, limit);
+ // NB: A stack string leaves out the outermost execution context, the last frame when the walk got to it.
+ let shown_frame_count = if reached_limit {
+ traceback.len()
+ } else {
+ traceback.len().saturating_sub(1)
+ };
+ Self {
+ traceback,
+ shown_frame_count: Some(shown_frame_count),
cached_string: Cell::new(None),
}
}
@@ -109,25 +159,42 @@ impl ErrorData {
self.traceback_storage_size() + function_names_size
}
- fn populate_stack(vm: &Vm, skipped_innermost_frames: usize) -> Vec<TracebackFrame> {
- let stack_trace = vm.stack_trace();
- let mut traceback = Vec::with_capacity(stack_trace.len().saturating_sub(skipped_innermost_frames));
- for element in stack_trace.values().iter().skip(skipped_innermost_frames) {
+ /// The frames from the running one down, after the innermost `skipped_innermost_frames`, until there are `limit`
+ /// of them, and whether the walk stopped there with frames left below. The walk never goes further, so capture
+ /// costs the same at any depth.
+ fn populate_stack(vm: &Vm, mut skipped_innermost_frames: usize, limit: usize) -> (Vec<TracebackFrame>, bool) {
+ let mut traceback = Vec::new();
+ let mut reached_limit = false;
+ vm.for_each_stack_frame_top_to_bottom(|frame| {
+ if skipped_innermost_frames > 0 {
+ skipped_innermost_frames -= 1;
+ return ControlFlow::Continue(());
+ }
+ if traceback.len() == limit {
+ reached_limit = true;
+ return ControlFlow::Break(());
+ }
traceback.push(TracebackFrame {
- function_name: element
+ function_name: frame
.function
.map(|function| function.name_for_call_stack())
.unwrap_or_default(),
- cached_source_range: element.source_range.clone(),
+ cached_source_range: frame.source_range(),
});
- }
- traceback
+ ControlFlow::Continue(())
+ });
+ (traceback, reached_limit)
}
pub fn traceback(&self) -> &[TracebackFrame] {
&self.traceback
}
+ /// Whether the error captured a stack; its stack is undefined if not.
+ pub fn has_stack(&self) -> bool {
+ self.shown_frame_count.is_some()
+ }
+
pub fn set_cached_string(&self, string: Gc<PrimitiveString>) {
self.cached_string.set(Some(string));
}
@@ -141,7 +208,8 @@ impl ErrorData {
}
pub fn stack_string_with_syntax(&self, compact: CompactTraceback, syntax: StackFrameSyntax) -> Utf16String {
- if self.traceback.is_empty() {
+ let used_frames = self.shown_frame_count.unwrap_or(0);
+ if used_frames == 0 {
return Utf16String::default();
}
@@ -194,10 +262,8 @@ impl ErrorData {
a.function_name == b.function_name
};
- // Note: We don't want to capture the global execution context, so we omit the last frame
// Note: The error's name and message get prepended by Error.prototype.stack
let mut repetitions: usize = 0;
- let used_frames = self.traceback.len() - 1;
for i in 0..used_frames {
let frame = &self.traceback[i];
if compact == CompactTraceback::Yes && i + 1 < used_frames {
@@ -254,6 +320,11 @@ impl ErrorDataCell {
Self::create(vm, ErrorData::new(vm))
}
+ /// Error data with every frame of the call stack, as ErrorData::with_whole_stack() has.
+ pub fn capture_whole_stack(vm: &Vm) -> Gc<ErrorDataCell> {
+ Self::create(vm, ErrorData::with_whole_stack(vm))
+ }
+
/// Error data for an exception whose source location came from another agent.
pub fn from_source_range(vm: &Vm, source_range: SourceRange) -> Gc<ErrorDataCell> {
Self::create(vm, ErrorData::from_source_range(source_range))
diff --git a/Libraries/LibJS/Rust/src/runtime/error_prototype.rs b/Libraries/LibJS/Rust/src/runtime/error_prototype.rs
index 6d3e7539c16..05f0399fe3a 100644
--- a/Libraries/LibJS/Rust/src/runtime/error_prototype.rs
+++ b/Libraries/LibJS/Rust/src/runtime/error_prototype.rs
@@ -146,6 +146,11 @@ impl ErrorPrototype {
return Ok(Value::UNDEFINED);
};
+ // NB: An error made while Error.stackTraceLimit was not a number captured no stack, and has none to show.
+ if !error_data.has_stack() {
+ return Ok(Value::UNDEFINED);
+ }
+
// OPTIMIZATION: Avoid recomputing the stack string if we already have it cached.
// At least one major engine does this as well, so it's not expected that changing
// the name or message properties updates the stack string.
diff --git a/Libraries/LibWeb/ContentSecurityPolicy/Violation.cpp b/Libraries/LibWeb/ContentSecurityPolicy/Violation.cpp
index 5a58e0527dc..860fe0c2d62 100644
--- a/Libraries/LibWeb/ContentSecurityPolicy/Violation.cpp
+++ b/Libraries/LibWeb/ContentSecurityPolicy/Violation.cpp
@@ -62,18 +62,12 @@ GC::Ref<Violation> Violation::create_a_violation_object_for_global_policy_and_di
// NOTE: User agents need to ensure that the source file is the URL requested by the page, pre-redirects. If that’s
// not possible, user agents need to strip the URL down to an origin to avoid unintentional leakage.
// NB: We use the innermost stack frame that has a source location.
- for (auto const& frame : JS::VM::the().stack_trace()) {
- if (!frame.source_range.has_value())
- continue;
- auto const& source_range = *frame.source_range;
- auto source_file = URL::Parser::basic_parse(source_range.filename().utf16_view());
- if (!source_file.has_value())
- break;
-
- violation->m_source_file = source_file.release_value();
- violation->m_line_number = source_range.start.line;
- violation->m_column_number = source_range.start.column;
- break;
+ if (auto source_range = JS::VM::the().innermost_source_range(); source_range.has_value()) {
+ if (auto source_file = URL::Parser::basic_parse(source_range->filename().utf16_view()); source_file.has_value()) {
+ violation->m_source_file = source_file.release_value();
+ violation->m_line_number = source_range->start.line;
+ violation->m_column_number = source_range->start.column;
+ }
}
// 3. If global is a Window object, set violation’s referrer to global’s document's referrer.
diff --git a/Libraries/LibWeb/HTML/ErrorInformation.cpp b/Libraries/LibWeb/HTML/ErrorInformation.cpp
index 271aba022e9..9de55e432ac 100644
--- a/Libraries/LibWeb/HTML/ErrorInformation.cpp
+++ b/Libraries/LibWeb/HTML/ErrorInformation.cpp
@@ -79,16 +79,10 @@ ErrorInformation extract_error_information(JS::VM& vm, JS::Value exception)
attributes.colno = throw_site->start.column;
}
// NB: Otherwise, we fall back to try and find the location of the invocation of the function itself.
- else {
- for (auto const& frame : vm.stack_trace()) {
- if (frame.source_range.has_value()) {
- auto const& source_range = *frame.source_range;
- attributes.filename = source_range.filename();
- attributes.lineno = source_range.start.line;
- attributes.colno = source_range.start.column;
- break;
- }
- }
+ else if (auto source_range = vm.innermost_source_range(); source_range.has_value()) {
+ attributes.filename = source_range->filename();
+ attributes.lineno = source_range->start.line;
+ attributes.colno = source_range->start.column;
}
// 4. Return attributes.
diff --git a/Libraries/LibWeb/WebDriver/BiDi/RemoteValue.cpp b/Libraries/LibWeb/WebDriver/BiDi/RemoteValue.cpp
index ba3e1f5c9d7..46c38b12073 100644
--- a/Libraries/LibWeb/WebDriver/BiDi/RemoteValue.cpp
+++ b/Libraries/LibWeb/WebDriver/BiDi/RemoteValue.cpp
@@ -1507,7 +1507,7 @@ JsonObject current_stack_trace(JS::VM& vm)
{
// The current stack trace is the result of construct a stack trace given a list of stack frames representing the
// callstack of the running execution context.
- return construct_a_stack_trace(JS::ErrorDataCell::capture(vm)->error_data().traceback());
+ return construct_a_stack_trace(JS::ErrorDataCell::capture_whole_stack(vm)->error_data().traceback());
}
// https://w3c.github.io/webdriver-bidi/#get-exception-details
diff --git a/Tests/LibJS/Runtime/builtins/Error/Error.stackTraceLimit.js b/Tests/LibJS/Runtime/builtins/Error/Error.stackTraceLimit.js
new file mode 100644
index 00000000000..a24650dec1d
--- /dev/null
+++ b/Tests/LibJS/Runtime/builtins/Error/Error.stackTraceLimit.js
@@ -0,0 +1,159 @@
+function recurse(depth, callback) {
+ return depth > 0 ? recurse(depth - 1, callback) : callback();
+}
+
+function frameLines(stack) {
+ return stack.split("\n").filter(line => line.startsWith(" at "));
+}
+
+function withStackTraceLimit(limit, callback) {
+ const saved = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit");
+ if (limit === undefined) delete Error.stackTraceLimit;
+ else Error.stackTraceLimit = limit;
+ try {
+ return callback();
+ } finally {
+ Object.defineProperty(Error, "stackTraceLimit", saved);
+ }
+}
+
+function stackAtDepth(depth, limit, makeError = () => new Error("deep")) {
+ return withStackTraceLimit(limit, () => recurse(depth, makeError).stack);
+}
+
+test("is a writable, enumerable and configurable data property with the value 10", () => {
+ expect(Object.hasOwn(Error, "stackTraceLimit")).toBeTrue();
+ const descriptor = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit");
+ expect(descriptor.value).toBe(10);
+ expect(descriptor.writable).toBeTrue();
+ expect(descriptor.enumerable).toBeTrue();
+ expect(descriptor.configurable).toBeTrue();
+ expect(Object.hasOwn(TypeError, "stackTraceLimit")).toBeFalse();
+});
+
+test("errors keep 10 frames by default", () => {
+ const stack = recurse(30, () => new Error("deep")).stack;
+ expect(stack.split("\n")[0]).toBe("Error: deep");
+ const frames = frameLines(stack);
+ expect(frames).toHaveLength(10);
+ expect(frames[0].includes("Error.stackTraceLimit.js:")).toBeTrue();
+ expect(frames[1].includes("at recurse (")).toBeTrue();
+});
+
+test("numbers limit the frames", () => {
+ expect(frameLines(stackAtDepth(30, 3))).toHaveLength(3);
+ expect(frameLines(stackAtDepth(30, 3.9))).toHaveLength(3);
+ expect(frameLines(stackAtDepth(30, 25))).toHaveLength(25);
+ expect(frameLines(stackAtDepth(30, 1))[0].includes("Error.stackTraceLimit.js:")).toBeTrue();
+});
+
+test("zero, negative numbers and NaN keep no frames", () => {
+ for (const limit of [0, -0, -1, -Infinity, NaN]) {
+ const stack = stackAtDepth(30, limit);
+ expect(stack.split("\n")[0]).toBe("Error: deep");
+ expect(frameLines(stack)).toHaveLength(0);
+ }
+});
+
+test("Infinity keeps every frame", () => {
+ const deep = frameLines(stackAtDepth(200, Infinity));
+ expect(deep.length).toBeGreaterThan(200);
+ expect(frameLines(stackAtDepth(10, Infinity)).length).toBe(deep.length - 190);
+});
+
+test("a stack shorter than the limit is not cut", () => {
+ // NB: Every stack is taken from the same line, so that their frames are the same.
+ let all;
+ const stacks = [];
+ for (const extra of [null, 0, 1, -1]) {
+ const frames = frameLines(stackAtDepth(0, extra === null ? Infinity : all.length + extra));
+ if (extra === null) all = frames;
+ else stacks.push(frames);
+ }
+ const [sameAsCount, oneMore, oneLess] = stacks;
+ expect(all.length).toBeLessThan(100);
+ expect(sameAsCount).toEqual(all);
+ expect(oneMore).toEqual(all);
+ expect(oneLess).toEqual(all.slice(0, -1));
+});
+
+test("a value that is not a number captures no stack", () => {
+ for (const limit of ["5", {}, null, true, 5n, Symbol.iterator, undefined]) {
+ expect(stackAtDepth(5, limit)).toBeUndefined();
+ expect(withStackTraceLimit(limit, () => recurse(5, () => new TypeError("t")))).toBeInstanceOf(TypeError);
+ }
+ // NB: A stack captured with a limit is kept when the limit changes.
+ const error = withStackTraceLimit(2, () => new Error());
+ expect(withStackTraceLimit("x", () => frameLines(error.stack))).toHaveLength(2);
+});
+
+test("deleting the property captures no stack", () => {
+ let error;
+ withStackTraceLimit(5, () => {
+ delete Error.stackTraceLimit;
+ error = new Error("gone");
+ });
+ expect(error.stack).toBeUndefined();
+ expect(error.message).toBe("gone");
+});
+
+test("an accessor is not a number, and its getter does not run", () => {
+ let getterCalls = 0;
+ const saved = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit");
+ Object.defineProperty(Error, "stackTraceLimit", {
+ get() {
+ getterCalls++;
+ return 3;
+ },
+ configurable: true,
+ });
+ try {
+ expect(new Error().stack).toBeUndefined();
+ } finally {
+ Object.defineProperty(Error, "stackTraceLimit", saved);
+ }
+ expect(getterCalls).toBe(0);
+});
+
+test("a value inherited by Error is not read", () => {
+ const savedPrototype = Object.getPrototypeOf(Error);
+ Object.setPrototypeOf(Error, { stackTraceLimit: 2 });
+ try {
+ expect(stackAtDepth(5, undefined)).toBeUndefined();
+ } finally {
+ Object.setPrototypeOf(Error, savedPrototype);
+ }
+});
+
+test("errors the engine makes take the limit", () => {
+ const makeTypeError = () => {
+ try {
+ null.property;
+ } catch (error) {
+ return error;
+ }
+ };
+ expect(frameLines(stackAtDepth(30, 4, makeTypeError))).toHaveLength(4);
+ expect(stackAtDepth(30, "4", makeTypeError)).toBeUndefined();
+
+ function overflow() {
+ return overflow() + 1;
+ }
+ let rangeError;
+ try {
+ overflow();
+ } catch (error) {
+ rangeError = error;
+ }
+ // NB: The error of a stack overflow is an InternalError.
+ expect(rangeError).toBeInstanceOf(Error);
+ expect(frameLines(rangeError.stack).length).toBeLessThanOrEqual(10);
+});
+
+test("every error type takes the limit", () => {
+ for (const ErrorType of [EvalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError, InternalError]) {
+ expect(frameLines(stackAtDepth(30, 2, () => new ErrorType()))).toHaveLength(2);
+ }
+ expect(frameLines(stackAtDepth(30, 2, () => new AggregateError([])))).toHaveLength(2);
+ expect(frameLines(stackAtDepth(30, 2, () => new SuppressedError(1, 2)))).toHaveLength(2);
+});
diff --git a/Tests/LibJS/Runtime/jit/invalidation-and-inlined-calls.js b/Tests/LibJS/Runtime/jit/invalidation-and-inlined-calls.js
index 7d4d05f8af3..e2b548b1110 100644
--- a/Tests/LibJS/Runtime/jit/invalidation-and-inlined-calls.js
+++ b/Tests/LibJS/Runtime/jit/invalidation-and-inlined-calls.js
@@ -124,18 +124,25 @@ test("exceptions thrown by calls in inlined callees", () => {
});
test("stack traces taken in calls of inlined callees", () => {
- const failures = compareCompiledWithInterpreter(
- () => {
- function where() {
- return new Error("here").stack.split("\n").length;
- }
- const inner = value => where() + value;
- const middle = value => inner(value) * 2;
- return value => middle(value);
- },
- { warmUp: (log, i) => [i], probes: { double: () => [0.5], string: () => ["x"] } }
- );
- expect(failures).toEqual([]);
+ // NB: The count of every frame, which is more than the default limit keeps.
+ const savedStackTraceLimit = Error.stackTraceLimit;
+ Error.stackTraceLimit = Infinity;
+ try {
+ const failures = compareCompiledWithInterpreter(
+ () => {
+ function where() {
+ return new Error("here").stack.split("\n").length;
+ }
+ const inner = value => where() + value;
+ const middle = value => inner(value) * 2;
+ return value => middle(value);
+ },
+ { warmUp: (log, i) => [i], probes: { double: () => [0.5], string: () => ["x"] } }
+ );
+ expect(failures).toEqual([]);
+ } finally {
+ Error.stackTraceLimit = savedStackTraceLimit;
+ }
});
test("re-entering compiled code from calls of inlined callees", () => {
diff --git a/Tests/LibWeb/Text/expected/error-stack-trace-limit.txt b/Tests/LibWeb/Text/expected/error-stack-trace-limit.txt
new file mode 100644
index 00000000000..f0b4c99ffd0
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/error-stack-trace-limit.txt
@@ -0,0 +1,7 @@
+inner window Error.stackTraceLimit: 10
+inner limit 2, inner error: 2
+inner limit 2, outer error: 10
+inner limit "x", inner error: undefined
+chrome: 10 3 0, DOMException 3
+gecko: 10 3 0, DOMException 3
+webkit: 10 3 0, DOMException 3
diff --git a/Tests/LibWeb/Text/input/error-stack-trace-limit.html b/Tests/LibWeb/Text/input/error-stack-trace-limit.html
new file mode 100644
index 00000000000..3b25b03f539
--- /dev/null
+++ b/Tests/LibWeb/Text/input/error-stack-trace-limit.html
@@ -0,0 +1,51 @@
+<!DOCTYPE html>
+<script src="include.js"></script>
+<iframe id="frame" srcdoc="<script>function makeError() { return new Error('inner'); }</script>"></iframe>
+<script>
+ function recurse(depth, callback) {
+ return depth > 0 ? recurse(depth - 1, callback) : callback();
+ }
+
+ function frameCount(stack) {
+ if (stack === undefined) return "undefined";
+ return stack.split("\n").filter(line => line.startsWith(" at ") || line.includes("@")).length;
+ }
+
+ asyncTest(done => {
+ frame.onload = () => {
+ const innerWindow = frame.contentWindow;
+ const savedOuter = Error.stackTraceLimit;
+ const savedInner = innerWindow.Error.stackTraceLimit;
+ try {
+ println(`inner window Error.stackTraceLimit: ${innerWindow.Error.stackTraceLimit}`);
+
+ // An error takes the limit of the realm whose Error constructor makes it.
+ innerWindow.Error.stackTraceLimit = 2;
+ println(`inner limit 2, inner error: ${frameCount(recurse(20, innerWindow.makeError).stack)}`);
+ println(`inner limit 2, outer error: ${frameCount(recurse(20, () => new Error()).stack)}`);
+ innerWindow.Error.stackTraceLimit = "x";
+ println(`inner limit "x", inner error: ${frameCount(recurse(20, innerWindow.makeError).stack)}`);
+ innerWindow.Error.stackTraceLimit = savedInner;
+
+ // The limit is the same in every navigator compatibility mode.
+ for (const mode of ["chrome", "gecko", "webkit"]) {
+ internals.setNavigatorCompatibilityMode(mode);
+ Error.stackTraceLimit = 10;
+ const limited = frameCount(recurse(20, () => new Error()).stack);
+ Error.stackTraceLimit = 3;
+ const three = frameCount(recurse(20, () => new Error()).stack);
+ Error.stackTraceLimit = 0;
+ const none = frameCount(recurse(20, () => new Error()).stack);
+ Error.stackTraceLimit = 3;
+ const domException = frameCount(recurse(20, () => new DOMException("d")).stack);
+ println(`${mode}: ${limited} ${three} ${none}, DOMException ${domException}`);
+ }
+ } finally {
+ internals.setNavigatorCompatibilityMode("chrome");
+ Error.stackTraceLimit = savedOuter;
+ innerWindow.Error.stackTraceLimit = savedInner;
+ }
+ done();
+ };
+ });
+</script>