Truly independent web browser
LibJS: Add Error.captureStackTrace
Andreas Kling76179350259f
diff --git a/Libraries/LibJS/Rust/src/runtime/common_property_names.rs b/Libraries/LibJS/Rust/src/runtime/common_property_names.rsindex 2ef3ff360ee..6d499aed0c6 100644--- a/Libraries/LibJS/Rust/src/runtime/common_property_names.rs+++ b/Libraries/LibJS/Rust/src/runtime/common_property_names.rs@@ -119,6 +119,7 @@ define_common_property_names! {call,callee,caller,+ captureStackTrace,caseFirst,cause,cbrt,diff --git a/Libraries/LibJS/Rust/src/runtime/error_constructor.rs b/Libraries/LibJS/Rust/src/runtime/error_constructor.rsindex e99e014b3bb..d5ffe4cb4c7 100644--- a/Libraries/LibJS/Rust/src/runtime/error_constructor.rs+++ b/Libraries/LibJS/Rust/src/runtime/error_constructor.rs@@ -14,14 +14,17 @@ use crate::layout::value::Value;use crate::runtime::abstract_operations::get_prototype_from_constructor;use crate::runtime::completion::ThrowCompletionOr;use crate::runtime::error::{- Error, EvalError, InternalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError,+ Error, ErrorKind, EvalError, InternalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError,};-use crate::runtime::error_data::DEFAULT_STACK_TRACE_LIMIT;+use crate::runtime::error_data::{DEFAULT_STACK_TRACE_LIMIT, ErrorData, SkippedFrames};+use crate::runtime::error_prototype::stack_string_of;+use crate::runtime::error_types::ErrorType;use crate::runtime::function_object::FunctionObject;use crate::runtime::intrinsics::Intrinsics;use crate::runtime::native_function::{NativeFunction, define_native_function_class, raw_native};use crate::runtime::primitive_string::PrimitiveString;use crate::runtime::property_attributes::{Attribute, PropertyAttributes};+use crate::runtime::property_descriptor::PropertyDescriptor;use crate::runtime::realm::Realm;#[repr(C)]@@ -84,6 +87,15 @@ impl ErrorConstructor {attributes,None,);+ object.define_native_function(+ vm,+ realm,+ &vm.names.captureStackTrace,+ raw_native!(ErrorConstructor::capture_stack_trace),+ 2,+ attributes,+ None,+ );}// 20.5.1.1 Error ( message [ , options ] ), https://tc39.es/ecma262/#sec-error-message@@ -127,6 +139,57 @@ impl ErrorConstructor {Ok(error.upcast())}+ // NB: Not in the specification, but the other engines have it: Error.captureStackTrace(object, function) gives+ // object an own "stack" with the frames of the running code below the innermost frame of function, or below+ // this function's own frame when function is not a function. The stack is a string made at once, in a data+ // property, as some engines do; the others have an accessor.+ fn capture_stack_trace(vm: &Vm) -> ThrowCompletionOr<Value> {+ let object_value = vm.argument(0);+ if !object_value.is_object() {+ return vm.throw_completion(ErrorKind::TypeError, ErrorType::NotAnObject, &[&object_value]);+ }+ let object = object_value.as_object();++ // NB: As the other engines do, refuse a non-extensible object even when it has a "stack" property already.+ if !object.is_extensible(vm)? {+ return vm.throw_completion(+ ErrorKind::TypeError,+ ErrorType::ObjectIsNotExtensible,+ &[&vm.names.stack],+ );+ }++ // NB: A bound function or a proxy has no frame of its own, so it counts as no function at all.+ let function = vm.argument(1);+ let skipped_frames = if function.is_function()+ && !function.as_object().is_bound_function()+ && !function.as_object().is_proxy_object()+ {+ SkippedFrames::UpToFrameOf(function.as_function())+ } else {+ SkippedFrames::Count(1)+ };++ let error_data = ErrorData::new_skipping(vm, skipped_frames);+ let stack = if error_data.has_stack() {+ Value::from_string(PrimitiveString::create(vm, stack_string_of(vm, &object, &error_data)?))+ } else {+ Value::UNDEFINED+ };+ object.define_property_or_throw(+ vm,+ &vm.names.stack,+ &mut PropertyDescriptor {+ value: Some(stack),+ writable: Some(true),+ enumerable: Some(false),+ configurable: Some(true),+ ..PropertyDescriptor::default()+ },+ )?;+ Ok(Value::UNDEFINED)+ }+// 20.5.2.1 Error.isError ( arg ), https://tc39.es/ecma262/#sec-error.iserror#[allow(clippy::unnecessary_wraps, reason = "native functions can throw")]fn is_error(vm: &Vm) -> ThrowCompletionOr<Value> {diff --git a/Libraries/LibJS/Rust/src/runtime/error_data.rs b/Libraries/LibJS/Rust/src/runtime/error_data.rsindex d2ff29066a5..14c8b677643 100644--- a/Libraries/LibJS/Rust/src/runtime/error_data.rs+++ b/Libraries/LibJS/Rust/src/runtime/error_data.rs@@ -13,6 +13,7 @@ use libjs_runtime_macros::Trace;use crate::gc::class::{ExternalMemorySize, GcCell, define_cell};use crate::interpreter::vm::Vm;use crate::layout::cell::{CellHeader, Gc};+use crate::runtime::function_object::FunctionObject;use crate::runtime::primitive_string::PrimitiveString;use crate::source_range::SourceRange;use crate::utf16::{Utf16View, utf16_string_external_memory_size};@@ -84,6 +85,16 @@ pub fn stack_trace_limit(vm: &Vm) -> Option<usize> {Some(value.as_f64() as usize)}+/// Which of the innermost frames a stack leaves out.+#[derive(Clone, Copy)]+pub enum SkippedFrames {+ /// That many frames.+ Count(usize),+ /// Every frame up to the innermost frame of the function, and that frame too: all of them if the function has no+ /// frame on the stack.+ UpToFrameOf(Gc<FunctionObject>),+}+/// [[ErrorData]]: the call stack an error was created on.#[derive(Trace)]pub struct ErrorData {@@ -97,19 +108,25 @@ pub struct ErrorData {impl ErrorData {pub fn new(vm: &Vm) -> Self {- Self::capture(vm, 0, stack_trace_limit(vm))+ Self::capture(vm, SkippedFrames::Count(0), stack_trace_limit(vm))+ }++ /// Error data with the frames below those that `skipped_frames` leaves out, as Error.captureStackTrace() captures+ /// it.+ pub fn new_skipping(vm: &Vm, skipped_frames: SkippedFrames) -> Self {+ Self::capture(vm, skipped_frames, 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::capture(vm, 1, stack_trace_limit(vm))+ Self::capture(vm, SkippedFrames::Count(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))+ Self::capture(vm, SkippedFrames::Count(0), Some(usize::MAX))}/// Error data for an exception whose source location came from another agent.@@ -124,7 +141,7 @@ impl ErrorData {}}- fn capture(vm: &Vm, skipped_innermost_frames: usize, limit: Option<usize>) -> Self {+ fn capture(vm: &Vm, skipped_frames: SkippedFrames, limit: Option<usize>) -> Self {let Some(limit) = limit else {return Self {traceback: Vec::new(),@@ -132,7 +149,7 @@ impl ErrorData {cached_string: Cell::new(None),};};- let (traceback, reached_limit) = Self::populate_stack(vm, skipped_innermost_frames, limit);+ let (traceback, reached_limit) = Self::populate_stack(vm, skipped_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()@@ -159,16 +176,25 @@ impl ErrorData {self.traceback_storage_size() + function_names_size}- /// 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) {+ /// The frames from the running one down, after those `skipped_frames` leaves out, 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, except for the walk to the frame of a function that has none.+ fn populate_stack(vm: &Vm, mut skipped_frames: SkippedFrames, 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(());+ match skipped_frames {+ SkippedFrames::Count(0) => {}+ SkippedFrames::Count(count) => {+ skipped_frames = SkippedFrames::Count(count - 1);+ return ControlFlow::Continue(());+ }+ SkippedFrames::UpToFrameOf(function) => {+ if frame.function == Some(function) {+ skipped_frames = SkippedFrames::Count(0);+ }+ return ControlFlow::Continue(());+ }}if traceback.len() == limit {reached_limit = true;diff --git a/Libraries/LibJS/Rust/src/runtime/error_prototype.rs b/Libraries/LibJS/Rust/src/runtime/error_prototype.rsindex 05f0399fe3a..ad1c561a95b 100644--- a/Libraries/LibJS/Rust/src/runtime/error_prototype.rs+++ b/Libraries/LibJS/Rust/src/runtime/error_prototype.rs@@ -14,7 +14,7 @@ use crate::layout::object::Object;use crate::layout::value::Value;use crate::runtime::completion::ThrowCompletionOr;use crate::runtime::error::ErrorKind;-use crate::runtime::error_data::{CompactTraceback, StackFrameSyntax};+use crate::runtime::error_data::{CompactTraceback, ErrorData, StackFrameSyntax};use crate::runtime::error_types::ErrorType;use crate::runtime::native_function::raw_native;use crate::runtime::object::{MayInterfereWithIndexedPropertyAccess, ORDINARY_OBJECT_METHODS, define_object_class};@@ -160,46 +160,7 @@ impl ErrorPrototype {// 4. Return ? GetStackString(error).// NOTE: These steps are not implemented based on the proposal, but to roughly follow behavior of other browsers.-- let name_property = this_object.get(vm, &vm.names.name)?;- let name = if !name_property.is_undefined() {- name_property.to_utf16_string(vm)?- } else {- Utf16String::from_utf8("Error")- };-- let message_property = this_object.get(vm, &vm.names.message)?;- let message = if !message_property.is_undefined() {- message_property.to_utf16_string(vm)?- } else {- Utf16String::default()- };-- let header = if Utf16View::of_string(&message).is_empty() {- name- } else {- concatenate(&[- Utf16View::of_string(&name),- Utf16View::Ascii(b": "),- Utf16View::of_string(&message),- ])- };-- let syntax = vm.stack_frame_syntax();- let stack_string = error_data.stack_string_with_syntax(CompactTraceback::No, syntax);- // The at-sign syntax is frames only; the name and message head the indented one.- let string = if syntax == StackFrameSyntax::AtSign {- PrimitiveString::create(vm, stack_string)- } else {- PrimitiveString::create(- vm,- concatenate(&[- Utf16View::of_string(&header),- Utf16View::Ascii(b"\n"),- Utf16View::of_string(&stack_string),- ]),- )- };+ let string = PrimitiveString::create(vm, stack_string_of(vm, &this_object, error_data)?);error_data.set_cached_string(string);Ok(Value::from_string(string))}@@ -231,6 +192,48 @@ impl ErrorPrototype {}}+/// The stack string of `object` with the frames of `error_data`. The at-sign syntax has the frames only; in the indented+/// syntax, the object's name and message head them, as Error.prototype.toString() writes them.+pub fn stack_string_of(vm: &Vm, object: &Object, error_data: &ErrorData) -> ThrowCompletionOr<Utf16String> {+ let syntax = vm.stack_frame_syntax();+ let frames = error_data.stack_string_with_syntax(CompactTraceback::No, syntax);+ if syntax == StackFrameSyntax::AtSign {+ return Ok(frames);+ }++ let name_property = object.get(vm, &vm.names.name)?;+ let name = if !name_property.is_undefined() {+ name_property.to_utf16_string(vm)?+ } else {+ Utf16String::from_utf8("Error")+ };++ let message_property = object.get(vm, &vm.names.message)?;+ let message = if !message_property.is_undefined() {+ message_property.to_utf16_string(vm)?+ } else {+ Utf16String::default()+ };++ let header = if Utf16View::of_string(&name).is_empty() {+ message+ } else if Utf16View::of_string(&message).is_empty() {+ name+ } else {+ concatenate(&[+ Utf16View::of_string(&name),+ Utf16View::Ascii(b": "),+ Utf16View::of_string(&message),+ ])+ };++ Ok(concatenate(&[+ Utf16View::of_string(&header),+ Utf16View::Ascii(b"\n"),+ Utf16View::of_string(&frames),+ ]))+}+macro_rules! define_native_error_prototypes {($($prototype:ident: $class_name:literal;)*) => {$(diff --git a/Libraries/LibJS/Rust/src/runtime/error_types.rs b/Libraries/LibJS/Rust/src/runtime/error_types.rsindex 9654ea51736..9f76cfb16eb 100644--- a/Libraries/LibJS/Rust/src/runtime/error_types.rs+++ b/Libraries/LibJS/Rust/src/runtime/error_types.rs@@ -151,6 +151,7 @@ define_error_types! {ObjectDefineOwnPropertyReturnedFalse => "Object's [[DefineOwnProperty]] method returned false",ObjectDeleteReturnedFalse => "Object's [[Delete]] method returned false",ObjectFreezeFailed => "Could not freeze object",+ ObjectIsNotExtensible => "Cannot define property {}, object is not extensible",ObjectPreventExtensionsReturnedFalse => "Object's [[PreventExtensions]] method returned false",ObjectPrototypeWrongType => "Prototype must be an object or null",ObjectSealFailed => "Could not seal object",diff --git a/Tests/LibJS/Runtime/builtins/Error/Error.captureStackTrace.js b/Tests/LibJS/Runtime/builtins/Error/Error.captureStackTrace.jsnew file mode 100644index 00000000000..dd35702e825--- /dev/null+++ b/Tests/LibJS/Runtime/builtins/Error/Error.captureStackTrace.js@@ -0,0 +1,161 @@+function frameLines(stack) {+ return stack.split("\n").filter(line => line.startsWith(" at "));+}++function recurse(depth, callback) {+ return depth > 0 ? recurse(depth - 1, callback) : callback();+}++test("is a function of Error with length 2", () => {+ expect(Error.captureStackTrace).toHaveLength(2);+ expect(Error.captureStackTrace.name).toBe("captureStackTrace");+ const descriptor = Object.getOwnPropertyDescriptor(Error, "captureStackTrace");+ expect(descriptor.writable).toBeTrue();+ expect(descriptor.enumerable).toBeFalse();+ expect(descriptor.configurable).toBeTrue();+ expect(Error.captureStackTrace({})).toBeUndefined();+});++test("defines an own, writable, configurable and not enumerable data property", () => {+ const object = {};+ Error.captureStackTrace(object);+ const descriptor = Object.getOwnPropertyDescriptor(object, "stack");+ expect(typeof descriptor.value).toBe("string");+ expect(descriptor.writable).toBeTrue();+ expect(descriptor.enumerable).toBeFalse();+ expect(descriptor.configurable).toBeTrue();+ expect(Object.keys(object)).toEqual([]);+});++test("the stack starts with the name and message of the object, then the frames of the caller", () => {+ function captureIn(object) {+ Error.captureStackTrace(object);+ return object.stack;+ }+ const lines = captureIn({}).split("\n");+ expect(lines[0]).toBe("Error");+ expect(lines[1].startsWith(" at captureIn (")).toBeTrue();+ expect(captureIn({ name: "Custom", message: "text" }).split("\n")[0]).toBe("Custom: text");+ expect(captureIn({ message: "text" }).split("\n")[0]).toBe("Error: text");+ expect(captureIn({ name: "", message: "text" }).split("\n")[0]).toBe("text");+ expect(captureIn({ name: "Named", message: "" }).split("\n")[0]).toBe("Named");+ expect(captureIn({ toString: () => "ignored" }).split("\n")[0]).toBe("Error");++ const error = new TypeError("first");+ error.message = "second";+ expect(captureIn(error).split("\n")[0]).toBe("TypeError: second");+});++test("the string is made at once", () => {+ const object = { message: "before" };+ Error.captureStackTrace(object);+ object.message = "after";+ expect(object.stack.split("\n")[0]).toBe("Error: before");++ const throwing = {+ get name() {+ throw new Error("from name");+ },+ };+ expect(() => Error.captureStackTrace(throwing)).toThrowWithMessage(Error, "from name");+ expect(Object.hasOwn(throwing, "stack")).toBeFalse();+});++test("frames up to and including the function are left out", () => {+ const object = {};+ function inner() {+ Error.captureStackTrace(object, middle);+ }+ function middle() {+ inner();+ }+ function outer() {+ middle();+ }+ outer();+ const frames = frameLines(object.stack);+ expect(frames[0].startsWith(" at outer (")).toBeTrue();+});++test("the innermost frame of a recursive function is the one left out", () => {+ const object = {};+ function recursive(depth) {+ if (depth > 0) return recursive(depth - 1);+ Error.captureStackTrace(object, recursive);+ }+ recursive(3);+ const frames = frameLines(object.stack);+ expect(frames[0].startsWith(" at recursive (")).toBeTrue();+ expect(frames[3].startsWith(" at recursive (")).toBeFalse();+ expect(frames[2].startsWith(" at recursive (")).toBeTrue();+});++test("a function that is not on the stack leaves out every frame", () => {+ const object = {};+ function notCalled() {}+ Error.captureStackTrace(object, notCalled);+ expect(object.stack).toBe("Error\n");+});++test("a value that is not a function, a bound function and a proxy leave out only the frame of captureStackTrace", () => {+ function capturer(fn) {+ const object = {};+ Error.captureStackTrace(object, fn);+ return frameLines(object.stack)[0];+ }+ for (const fn of [undefined, 5, {}, capturer.bind(null), new Proxy(capturer, {})])+ expect(capturer(fn).startsWith(" at capturer (")).toBeTrue();+});++test("the stack takes Error.stackTraceLimit", () => {+ const saved = Error.stackTraceLimit;+ try {+ Error.stackTraceLimit = 3;+ const object = {};+ recurse(20, () => Error.captureStackTrace(object));+ expect(frameLines(object.stack)).toHaveLength(3);++ Error.stackTraceLimit = 0;+ recurse(20, () => Error.captureStackTrace(object));+ expect(object.stack).toBe("Error\n");++ Error.stackTraceLimit = "x";+ recurse(20, () => Error.captureStackTrace(object));+ expect(Object.hasOwn(object, "stack")).toBeTrue();+ expect(object.stack).toBeUndefined();+ } finally {+ Error.stackTraceLimit = saved;+ }+});++test("replaces a configurable stack property", () => {+ const object = { stack: "old" };+ Error.captureStackTrace(object);+ expect(object.stack.startsWith("Error\n")).toBeTrue();+ expect(Object.keys(object)).toEqual([]);++ const error = new Error("own");+ Error.captureStackTrace(error);+ expect(Object.hasOwn(error, "stack")).toBeTrue();+ expect(error.stack.startsWith("Error: own\n")).toBeTrue();+});++test("errors", () => {+ for (const value of [undefined, null, 1, "string", Symbol.iterator, 1n, true]) {+ expect(() => Error.captureStackTrace(value)).toThrow(TypeError);+ }++ const frozen = Object.freeze({});+ expect(() => Error.captureStackTrace(frozen)).toThrowWithMessage(+ TypeError,+ "Cannot define property stack, object is not extensible"+ );+ const notExtensible = Object.preventExtensions({ stack: "kept" });+ expect(() => Error.captureStackTrace(notExtensible)).toThrow(TypeError);+ expect(notExtensible.stack).toBe("kept");++ const nonConfigurable = {};+ Object.defineProperty(nonConfigurable, "stack", { value: "fixed" });+ expect(() => Error.captureStackTrace(nonConfigurable)).toThrow(TypeError);+ expect(nonConfigurable.stack).toBe("fixed");+});