Truly independent web browser
LibJS+LibWeb+WebContent: Keep long error stacks for an attached debugger
Andreas Kling9c18cdc283d0
diff --git a/Libraries/LibJS/Runtime/ErrorData.cpp b/Libraries/LibJS/Runtime/ErrorData.cppindex 1b1b5310777..e9d16fbba8f 100644--- a/Libraries/LibJS/Runtime/ErrorData.cpp+++ b/Libraries/LibJS/Runtime/ErrorData.cpp@@ -30,11 +30,8 @@ Utf16String ErrorData::stack_string(CompactTraceback compact) constreturn owned_utf16_string_from_abi(js_error_data_stack_string(error_data_to_abi(*this), compact == CompactTraceback::Yes));}-Vector<TracebackFrame, 32> ErrorData::traceback() const+static Vector<TracebackFrame, 32> innermost_traceback_frames(JSErrorData const* error_data, size_t frame_count){- auto const* error_data = error_data_to_abi(*this);- auto frame_count = js_error_data_traceback_length(error_data);-Vector<TracebackFrame, 32> traceback;traceback.ensure_capacity(frame_count);for (size_t index = 0; index < frame_count; ++index) {@@ -49,6 +46,18 @@ Vector<TracebackFrame, 32> ErrorData::traceback() constreturn traceback;}+Vector<TracebackFrame, 32> ErrorData::traceback() const+{+ auto const* error_data = error_data_to_abi(*this);+ return innermost_traceback_frames(error_data, js_error_data_traceback_length(error_data));+}++Vector<TracebackFrame, 32> ErrorData::script_visible_traceback() const+{+ auto const* error_data = error_data_to_abi(*this);+ return innermost_traceback_frames(error_data, js_error_data_script_visible_traceback_length(error_data));+}+GC::Ref<ErrorDataCell> ErrorDataCell::capture(VM& vm){auto* cell = js_error_data_cell_capture(vm_to_abi(vm));diff --git a/Libraries/LibJS/Runtime/ErrorData.h b/Libraries/LibJS/Runtime/ErrorData.hindex 6c21a7f15b7..be20209491d 100644--- a/Libraries/LibJS/Runtime/ErrorData.h+++ b/Libraries/LibJS/Runtime/ErrorData.h@@ -48,6 +48,10 @@ public:// The frames are copied out of the runtime, so this returns them by value.[[nodiscard]] Vector<TracebackFrame, 32> traceback() const;+ // NB: The innermost frames that the error would keep if the VM kept no long stack traces. What script can observe+ // reads only these, so it does not change while a debugger is attached; traceback() is for the debugger.+ [[nodiscard]] Vector<TracebackFrame, 32> script_visible_traceback() const;+protected:ErrorData() = delete;~ErrorData() = delete;diff --git a/Libraries/LibJS/Runtime/VM.cpp b/Libraries/LibJS/Runtime/VM.cppindex 2de7b4d3794..bc275e92444 100644--- a/Libraries/LibJS/Runtime/VM.cpp+++ b/Libraries/LibJS/Runtime/VM.cpp@@ -543,6 +543,11 @@ Vector<StackTraceElement> VM::stack_trace() constreturn stack_trace;}+void VM::set_keeps_long_stack_traces(bool keeps_long_stack_traces)+{+ js_vm_set_keeps_long_stack_traces(vm_abi(*this), keeps_long_stack_traces);+}+Optional<SourceRange> VM::innermost_source_range() const{return source_range_from_abi(js_vm_innermost_source_range(vm_abi(*this)));diff --git a/Libraries/LibJS/Runtime/VM.h b/Libraries/LibJS/Runtime/VM.hindex 8d1acabd15e..e7666ba79f8 100644--- a/Libraries/LibJS/Runtime/VM.h+++ b/Libraries/LibJS/Runtime/VM.h@@ -462,6 +462,11 @@ public:// throw.[[nodiscard]] Optional<SourceRange> take_throw_site_of(Value);+ // Whether errors keep at least 200 frames, for a debugger that lists them, even when Error.stackTraceLimit is not a+ // number. What script can observe stays the same: stack strings show as many frames as Error.stackTraceLimit says,+ // and ErrorData::script_visible_traceback() has the frames that the error would keep without this.+ void set_keeps_long_stack_traces(bool);+// 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;diff --git a/Libraries/LibJS/Rust/src/embedding/error.rs b/Libraries/LibJS/Rust/src/embedding/error.rsindex d138d28b4aa..e3c0264d82a 100644--- a/Libraries/LibJS/Rust/src/embedding/error.rs+++ b/Libraries/LibJS/Rust/src/embedding/error.rs@@ -214,6 +214,22 @@ pub unsafe extern "C" fn js_error_data_traceback_length(error_data: *const JSErrunsafe { error_data_from_abi(error_data) }.traceback().len()}+/// How many frames of the call stack of `error_data`, from the innermost, script can observe: those the error would+/// keep if the VM kept no long stack traces, which js_error_data_traceback_frame writes as it writes the others. The+/// embedder reads only these for what script can observe, so that does not change while a debugger is attached. Call+/// on the VM's thread.+///+/// # Safety+///+/// `error_data` must be error data, or an error data cell, of a live cell of the embedder's VM.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn js_error_data_script_visible_traceback_length(error_data: *const JSErrorData) -> usize {+ // SAFETY: The caller passes error data of a live cell.+ unsafe { error_data_from_abi(error_data) }+ .script_visible_traceback()+ .len()+}+/// A frame of the call stack of an error, as C++ TracebackFrame: the name of the frame's function, and where in its/// source the frame was, which is an empty filename at line and column 0 without a source range. With a source range,/// `source_code` is the frame's source code, which the embedder retains to keep it, and null otherwise. The views anddiff --git a/Libraries/LibJS/Rust/src/embedding/vm.rs b/Libraries/LibJS/Rust/src/embedding/vm.rsindex 47266e16e21..5f34db936ab 100644--- a/Libraries/LibJS/Rust/src/embedding/vm.rs+++ b/Libraries/LibJS/Rust/src/embedding/vm.rs@@ -148,6 +148,20 @@ pub unsafe extern "C" fn js_vm_throw_site_of(vm: *mut JSVM, value: JSValue) -> Jsource_range_into_abi(vm.throw_site_of(value_from_abi(value)).as_ref())}+/// VM::set_keeps_long_stack_traces(): whether errors keep at least 200 frames, even when Error.stackTraceLimit is not a+/// number, for an embedder whose debugger lists the frames of an error. What script can observe stays the same: stack+/// strings show as many frames as Error.stackTraceLimit says, and js_error_data_script_visible_traceback_length() counts+/// the frames the error would keep without this. 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_set_keeps_long_stack_traces(vm: *mut JSVM, keeps_long_stack_traces: bool) {+ // SAFETY: The caller passes a live VM.+ unsafe { vm_from_abi(vm) }.set_keeps_long_stack_traces(keeps_long_stack_traces);+}+/// 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.///diff --git a/Libraries/LibJS/Rust/src/interpreter/vm.rs b/Libraries/LibJS/Rust/src/interpreter/vm.rsindex 467682aa542..8734b2059e5 100644--- a/Libraries/LibJS/Rust/src/interpreter/vm.rs+++ b/Libraries/LibJS/Rust/src/interpreter/vm.rs@@ -656,6 +656,9 @@ pub struct Vm {host_finalize_import_meta: Cell<HostFinalizeImportMeta>,host_get_supported_import_attributes: Cell<HostGetSupportedImportAttributes>,dynamic_imports_allowed: Cell<bool>,+ /// Whether errors keep at least LONG_STACK_TRACE_FRAME_COUNT frames, for a debugger that lists them, even when+ /// Error.stackTraceLimit is not a number. Their stack strings and script-visible frames stay as without it.+ keeps_long_stack_traces: Cell<bool>,loaded_modules: OnceCell<Gc<LoadedModules>>,module_execution_depth: Cell<u32>,module_async_evaluation_count: Cell<u64>, // [[ModuleAsyncEvaluationCount]]@@ -827,6 +830,7 @@ impl Vm {host_finalize_import_meta: Cell::new(default_host_finalize_import_meta),host_get_supported_import_attributes: Cell::new(default_host_get_supported_import_attributes),dynamic_imports_allowed: Cell::new(false),+ keeps_long_stack_traces: Cell::new(false),loaded_modules: OnceCell::new(),module_execution_depth: Cell::new(0),module_async_evaluation_count: Cell::new(0),@@ -1982,6 +1986,14 @@ impl Vm {self.dynamic_imports_allowed.set(value);}+ pub fn keeps_long_stack_traces(&self) -> bool {+ self.keeps_long_stack_traces.get()+ }++ pub fn set_keeps_long_stack_traces(&self, value: bool) {+ self.keeps_long_stack_traces.set(value);+ }+pub fn enter_module_execution(&self) {self.module_execution_depth.set(self.module_execution_depth.get() + 1);}diff --git a/Libraries/LibJS/Rust/src/runtime/error_data.rs b/Libraries/LibJS/Rust/src/runtime/error_data.rsindex f6f8653199a..d967f19306d 100644--- a/Libraries/LibJS/Rust/src/runtime/error_data.rs+++ b/Libraries/LibJS/Rust/src/runtime/error_data.rs@@ -65,6 +65,10 @@ impl StackFrameSyntax {/// The initial value of Error.stackTraceLimit.pub const DEFAULT_STACK_TRACE_LIMIT: i32 = 10;+/// How many frames an error keeps at least while the VM keeps long stack traces, as it does for a debugger that lists+/// them.+pub const LONG_STACK_TRACE_FRAME_COUNT: usize = 200;+/// 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@@ -100,9 +104,14 @@ pub enum SkippedFrames {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.+ /// How many of the frames, from the innermost, the stack string shows, or None for an error without a stack, whose+ /// stack is undefined. Such an error has frames only while the VM keeps long stack traces.shown_frame_count: Option<usize>,+ /// How many of the frames, from the innermost, the error would keep if the VM kept no long stack traces. What script+ /// can observe, such as the location of an error event, reads only these, so it does not change while a debugger is+ /// attached. Unlike shown_frame_count, it counts the outermost execution context when the walk got to it inside the+ /// limit.+ script_visible_frame_count: usize,cached_string: Cell<Option<Gc<PrimitiveString>>>,}@@ -151,28 +160,41 @@ impl ErrorData {cached_source_range: Some(source_range),}],shown_frame_count: Some(0),+ script_visible_frame_count: 1,cached_string: Cell::new(None),}}+ /// Error data with at most `limit` frames below those that `skipped_frames` leaves out, or with no stack for a+ /// `limit` of None. While the VM keeps long stack traces, it keeps at least LONG_STACK_TRACE_FRAME_COUNT frames for+ /// the debugger, even with no stack, but the stack string and the script-visible frames stay as without them.fn capture(vm: &Vm, skipped_frames: SkippedFrames, limit: Option<usize>) -> Self {- let Some(limit) = limit else {- return Self {- traceback: Vec::new(),- shown_frame_count: None,- cached_string: Cell::new(None),- };+ let captured_limit = match limit {+ Some(limit) if vm.keeps_long_stack_traces() => limit.max(LONG_STACK_TRACE_FRAME_COUNT),+ Some(limit) => limit,+ None if vm.keeps_long_stack_traces() => LONG_STACK_TRACE_FRAME_COUNT,+ None => {+ return Self {+ traceback: Vec::new(),+ shown_frame_count: None,+ script_visible_frame_count: 0,+ cached_string: Cell::new(None),+ };+ }};- let (traceback, reached_limit) = Self::populate_stack(vm, skipped_frames, limit);+ let (traceback, reached_limit) = Self::populate_stack(vm, skipped_frames, captured_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 {+ let frame_count = if reached_limit {traceback.len()} else {traceback.len().saturating_sub(1)};+ let shown_frame_count = limit.map(|limit| frame_count.min(limit));+ let script_visible_frame_count = limit.map_or(0, |limit| traceback.len().min(limit));Self {traceback,- shown_frame_count: Some(shown_frame_count),+ shown_frame_count,+ script_visible_frame_count,cached_string: Cell::new(None),}}@@ -226,11 +248,17 @@ impl ErrorData {(traceback, reached_limit)}+ /// Every frame the error kept, for a debugger that lists them.pub fn traceback(&self) -> &[TracebackFrame] {&self.traceback}- /// Whether the error captured a stack; its stack is undefined if not.+ /// The frames the error would keep if the VM kept no long stack traces, for what script can observe.+ pub fn script_visible_traceback(&self) -> &[TracebackFrame] {+ &self.traceback[..self.script_visible_frame_count]+ }++ /// Whether the error has a stack string; its stack is undefined if not, even with frames kept for a debugger.pub fn has_stack(&self) -> bool {self.shown_frame_count.is_some()}diff --git a/Libraries/LibWeb/HTML/ErrorInformation.cpp b/Libraries/LibWeb/HTML/ErrorInformation.cppindex 1f1737b4137..18eebb19096 100644--- a/Libraries/LibWeb/HTML/ErrorInformation.cpp+++ b/Libraries/LibWeb/HTML/ErrorInformation.cpp@@ -60,10 +60,11 @@ ErrorInformation extract_error_information(JS::VM& vm, JS::Value exception)// NB: Take the throw site even when an Error's traceback gives the location, so the VM stops keeping it alive.auto throw_site = vm.take_throw_site_of(exception);- // NB: If we got an Error object, then try and extract the information from the location the object was made.+ // NB: If we got an Error object, then try and extract the information from the location the object was made. Only+ // the script-visible frames count, so the location does not change while a debugger is attached.bool has_location = false;if (auto object = exception.as_if<JS::Object>(); object && object->error_data()) {- for (auto const& frame : object->error_data()->traceback()) {+ for (auto const& frame : object->error_data()->script_visible_traceback()) {auto source_range = frame.source_range();if (source_range.start.line != 0 || source_range.start.column != 0) {attributes.filename = source_range.filename();diff --git a/Libraries/LibWeb/Internals/Internals.cpp b/Libraries/LibWeb/Internals/Internals.cppindex 122e65a55f0..1b06d8b0c78 100644--- a/Libraries/LibWeb/Internals/Internals.cpp+++ b/Libraries/LibWeb/Internals/Internals.cpp@@ -1253,6 +1253,11 @@ Utf16String Internals::devtools_log_table(GC::Root<JS::Object> const& table_datareturn Utf16String::from_utf8(arguments.serialized());}+void Internals::set_long_stack_traces_enabled(bool enabled)+{+ vm().set_keeps_long_stack_traces(enabled);+}+// The names of the own properties of a logged object, if it's still kept.Utf16String Internals::devtools_logged_properties(u64 object_id){diff --git a/Libraries/LibWeb/Internals/Internals.h b/Libraries/LibWeb/Internals/Internals.hindex ecf79c9c144..8722254e1f2 100644--- a/Libraries/LibWeb/Internals/Internals.h+++ b/Libraries/LibWeb/Internals/Internals.h@@ -144,6 +144,7 @@ public:Utf16String devtools_log(GC::RootVector<JS::Value> const& arguments);Utf16String devtools_logged_properties(u64 object_id);Utf16String devtools_log_table(GC::Root<JS::Object> const& table_data);+ void set_long_stack_traces_enabled(bool);Optional<Vector<String>> complete_console_input(Utf16String const& input);void find_in_page(Utf16String const& query, bool highlight_all);diff --git a/Libraries/LibWeb/Internals/Internals.idl b/Libraries/LibWeb/Internals/Internals.idlindex 941bfbaab6c..ac7e2d73364 100644--- a/Libraries/LibWeb/Internals/Internals.idl+++ b/Libraries/LibWeb/Internals/Internals.idl@@ -148,6 +148,8 @@ interface Internals {DOMString devtoolsLog(sequence<any> arguments);DOMString devtoolsLoggedProperties(unsigned long long objectId);DOMString devtoolsLogTable(object tableData);+ // Whether errors keep long stack traces, as they do while a DevTools client or a WebDriver BiDi session is attached.+ undefined setLongStackTracesEnabled(boolean enabled);sequence<DOMString>? completeConsoleInput(DOMString input);// Drive marked/preedit-text composition via the same path platform input methods use. setMarkedTextFromInputMethoddiff --git a/Services/WebContent/PageClient.cpp b/Services/WebContent/PageClient.cppindex 0c813929ee4..1be1310f573 100644--- a/Services/WebContent/PageClient.cpp+++ b/Services/WebContent/PageClient.cpp@@ -27,6 +27,7 @@#include <LibJS/Runtime/ConsoleObject.h>#include <LibMedia/Sinks/AudioOutputFactory.h>#include <LibMediaClient/RemotePlaybackManager.h>+#include <LibWeb/Bindings/MainThreadVM.h>#include <LibWeb/CSS/StyleScope.h>#include <LibWeb/CSS/StyleSheetIdentifier.h>#include <LibWeb/CSS/StyleSheetImport.h>@@ -178,11 +179,23 @@ PageClient::PageClient(PageHost& owner, Web::PageId id, Optional<Web::HTML::CrosPageClient::~PageClient() = default;+// How many pages of this process have a DevTools client.+static size_t s_pages_with_devtools_client = 0;++// Errors keep long stacks while a DevTools client or a WebDriver BiDi session may list their frames.+void PageClient::update_keeps_long_stack_traces()+{+ Web::Bindings::main_thread_vm().set_keeps_long_stack_traces(s_pages_with_devtools_client > 0 || Web::WebDriver::BiDi::is_active());+}+void PageClient::finalize(){Base::finalize();- if (m_has_devtools_client)+ if (m_has_devtools_client) {m_network_activity_observers->page_did_lose_devtools_client();+ --s_pages_with_devtools_client;+ update_keeps_long_stack_traces();+ }}void PageClient::visit_edges(JS::Cell::Visitor& visitor)@@ -1824,8 +1837,11 @@ void PageClient::page_did_close()m_is_closed = true;// A closed page has no DevTools client.- if (exchange(m_has_devtools_client, false))+ if (exchange(m_has_devtools_client, false)) {m_network_activity_observers->page_did_lose_devtools_client();+ --s_pages_with_devtools_client;+ update_keeps_long_stack_traces();+ }// NOTE: This only removes the strong reference the PageHost has for this PageClient.// It will be GC'd 'later'.@@ -2595,10 +2611,14 @@ void PageClient::set_has_devtools_client(bool has_devtools_client)if (m_has_devtools_client == has_devtools_client)return;m_has_devtools_client = has_devtools_client;- if (has_devtools_client)+ if (has_devtools_client) {m_network_activity_observers->page_did_gain_devtools_client();- else+ ++s_pages_with_devtools_client;+ } else {m_network_activity_observers->page_did_lose_devtools_client();+ --s_pages_with_devtools_client;+ }+ update_keeps_long_stack_traces();for (auto& navigable : Web::HTML::all_local_navigables()) {if (&navigable->page() != &page())diff --git a/Services/WebContent/PageClient.h b/Services/WebContent/PageClient.hindex be327bebd50..c5e5316115e 100644--- a/Services/WebContent/PageClient.h+++ b/Services/WebContent/PageClient.h@@ -123,6 +123,7 @@ public:void select_dropdown_closed(Optional<u32> const& selected_item_id);void set_has_devtools_client(bool);+ static void update_keeps_long_stack_traces();bool has_devtools_client() const { return m_has_devtools_client; }virtual bool has_active_devtools_client() const override { return has_devtools_client(); }void start_sending_console_output(bool messages, bool errors);diff --git a/Services/WebContent/WebDriverBiDi.cpp b/Services/WebContent/WebDriverBiDi.cppindex a55ebb99e01..43a5a2231b2 100644--- a/Services/WebContent/WebDriverBiDi.cpp+++ b/Services/WebContent/WebDriverBiDi.cpp@@ -50,6 +50,7 @@ void set_webdriver_bidi_session_state(Web::WebDriver::BiDiSessionState state)}Web::WebDriver::BiDi::set_session_state(move(state));+ PageClient::update_keeps_long_stack_traces();}// https://w3c.github.io/webdriver-bidi/#command-browsingContext-creatediff --git a/Tests/LibWeb/Text/expected/error-stack-with-long-stack-traces.txt b/Tests/LibWeb/Text/expected/error-stack-with-long-stack-traces.txtnew file mode 100644index 00000000000..fc5b60a63d2--- /dev/null+++ b/Tests/LibWeb/Text/expected/error-stack-with-long-stack-traces.txt@@ -0,0 +1,10 @@+off: default limit, stack lines 11+off: limit 3, stack lines 4+off: limit 0, made then thrown {"lineno":3,"colno":3}+off: not a number, stack undefined+off: not a number, made then thrown {"lineno":3,"colno":3}+on: default limit, stack lines 11+on: limit 3, stack lines 4+on: limit 0, made then thrown {"lineno":3,"colno":3}+on: not a number, stack undefined+on: not a number, made then thrown {"lineno":3,"colno":3}diff --git a/Tests/LibWeb/Text/input/error-stack-with-long-stack-traces.html b/Tests/LibWeb/Text/input/error-stack-with-long-stack-traces.htmlnew file mode 100644index 00000000000..5cd1ab725dd--- /dev/null+++ b/Tests/LibWeb/Text/input/error-stack-with-long-stack-traces.html@@ -0,0 +1,52 @@+<!DOCTYPE html>+<script src="include.js"></script>+<script>+ removeTestErrorHandler();++ function runUncaught(source) {+ let reported;+ window.onerror = (message, filename, lineno, colno) => {+ reported = { lineno, colno };+ return true;+ };+ const script = document.createElement("script");+ script.textContent = source;+ document.body.appendChild(script);+ window.onerror = null;+ script.remove();+ return reported;+ }++ function stackLineCount(depth) {+ if (depth > 0)+ return stackLineCount(depth - 1);+ return new Error().stack.split("\n").filter(line => line.length).length;+ }++ function check(mode) {+ Error.stackTraceLimit = 10;+ println(`${mode}: default limit, stack lines ${stackLineCount(250)}`);+ Error.stackTraceLimit = 3;+ println(`${mode}: limit 3, stack lines ${stackLineCount(250)}`);++ const madeThenThrown = `\n var error = new Error("made");\n throw error;`;+ Error.stackTraceLimit = 0;+ println(`${mode}: limit 0, made then thrown ${JSON.stringify(runUncaught(madeThenThrown))}`);++ Error.stackTraceLimit = "not a number";+ println(`${mode}: not a number, stack ${new Error().stack}`);+ println(`${mode}: not a number, made then thrown ${JSON.stringify(runUncaught(madeThenThrown))}`);+ }++ test(() => {+ const savedStackTraceLimit = Error.stackTraceLimit;+ try {+ check("off");+ internals.setLongStackTracesEnabled(true);+ check("on");+ } finally {+ internals.setLongStackTracesEnabled(false);+ Error.stackTraceLimit = savedStackTraceLimit;+ }+ });+</script>