Lightpanda: the headless browser designed for AI and automation
add guard to protect against recursive error reporting in WGS
Karl Seguin6a7be26b6cee
diff --git a/src/browser/EventManager.zig b/src/browser/EventManager.zigindex 2c438e399..36b937cf6 100644--- a/src/browser/EventManager.zig+++ b/src/browser/EventManager.zig@@ -334,7 +334,7 @@ fn dispatchNode(self: *EventManager, target: *Node, event: *Event) !void {// Inline handlers (e.g. onclick property) follow the same "report,// don't propagate" rule as addEventListener listeners — see Listener.run.- const handler_return = try callInlineHandler(frame, &ls.local, inline_handler, target_et, event);+ const handler_return = try callInlineHandler(&ls.local, inline_handler, target_et, event);processHandlerReturnValue(event, handler_return);if (adjusted) |a| {@@ -387,7 +387,7 @@ fn dispatchNode(self: *EventManager, target: *Node, event: *Event) !void {const adjusted: ?AdjustedTargets = if (event._needs_retargeting) .apply(event, current_target) else null;- const handler_return = try callInlineHandler(frame, &ls.local, inline_handler, current_target, event);+ const handler_return = try callInlineHandler(&ls.local, inline_handler, current_target, event);processHandlerReturnValue(event, handler_return);if (adjusted) |a| {@@ -455,30 +455,24 @@ fn legacyType(event: *const Event) ?lp.String {}// Calls an inline handler (onclick attribute or property). An exception it-// doesn't catch is reported to the window — its "error" event and onerror-// fire, as for an addEventListener listener (Listener.run) — and dispatch-// carries on.-fn callInlineHandler(frame: *Frame, local: *const js.Local, handler: js.Function.Global, this: *EventTarget, event: *Event) error{ExecutionTerminated}!?js.Value {+// doesn't catch is reported to the global, as for an addEventListener+// listener (Listener.run), and dispatch carries on.+fn callInlineHandler(local: *const js.Local, handler: js.Function.Global, this: *EventTarget, event: *Event) error{ExecutionTerminated}!?js.Value {var try_catch: js.TryCatch = undefined;try_catch.init(local);defer try_catch.deinit();- return local.toLocal(handler).callWithThisRethrow(js.Value, this, .{event}) catch |err| {- if (err == error.ExecutionTerminated) {- return error.ExecutionTerminated;- }- if (err == error.JsException or err == error.TryCatchRethrow) {- if (try_catch.exceptionValue()) |exc| {- // reportError also counts the error on the page.- frame.window.reportError(exc, frame) catch |report_err| {- log.debug(.event, "inline handler report error", .{ .err = report_err });- };- return null;- }- }- frame.page.recordJsError(err);- log.debug(.event, "inline handler", .{ .err = err });- return null;+ return local.toLocal(handler).callWithThisRethrow(js.Value, this, .{event}) catch |err| switch (err) {+ error.ExecutionTerminated => return error.ExecutionTerminated,+ error.JsException, error.TryCatchRethrow => {+ Listener.reportException(&try_catch, local);+ return null;+ },+ else => {+ local.ctx.page.recordJsError(err);+ log.debug(.event, "inline handler", .{ .err = err });+ return null;+ },};}diff --git a/src/browser/EventManagerBase.zig b/src/browser/EventManagerBase.zigindex 15823f048..49e5f6b92 100644--- a/src/browser/EventManagerBase.zig+++ b/src/browser/EventManagerBase.zig@@ -541,19 +541,15 @@ pub const Listener = struct {// Reports a listener exception to the relevant global (firing// window.onerror / an "error" event) without stopping the dispatch.- fn reportException(try_catch: *js.TryCatch, local: *const js.Local) void {+ pub fn reportException(try_catch: *js.TryCatch, local: *const js.Local) void {const exc = try_catch.exceptionValue() orelse return;reportExceptionValue(local, exc);}fn reportExceptionValue(local: *const js.Local, exc: js.Value) void {- switch (local.ctx.global) {- .frame => |frame| frame.window.reportError(exc, frame) catch |err| {- log.debug(.event, "listener report error", .{ .err = err });- },- // No worker error-event plumbing here (yet); still count it.- .worker => local.ctx.page.recordJsError(error.JsException),- }+ local.ctx.global.reportError(exc) catch |err| {+ log.debug(.event, "listener report error", .{ .err = err });+ };}};diff --git a/src/browser/js/Execution.zig b/src/browser/js/Execution.zigindex f9f0d03c2..760338bfb 100644--- a/src/browser/js/Execution.zig+++ b/src/browser/js/Execution.zig@@ -28,6 +28,7 @@const std = @import("std");const lp = @import("lightpanda");+const Value = @import("Value.zig");const Context = @import("Context.zig");const Scheduler = @import("Scheduler.zig");const Page = @import("../Page.zig");@@ -177,6 +178,10 @@ pub fn dispatch(return self.js.global.dispatch(target, event, handler, opts);}+pub fn reportError(self: *const Execution, err: Value) !void {+ return self.js.global.reportError(err);+}+pub fn hasDirectListeners(self: *const Execution, target: *EventTarget, typ: []const u8, handler: anytype) bool {return self.js.global.hasDirectListeners(target, typ, handler);}diff --git a/src/browser/tests/worker/report-error-worker.js b/src/browser/tests/worker/report-error-worker.jsnew file mode 100644index 000000000..8a1a0d355--- /dev/null+++ b/src/browser/tests/worker/report-error-worker.js@@ -0,0 +1,34 @@+// Uncaught exceptions from callbacks inside a worker are reported to the+// worker global: its "error" event fires with the thrown value.+const seen = [];+let reentrant = 0;+self.addEventListener('error', (e) => {+ if (reentrant > 0) {+ // Reached again from our own throw below: the guard failed.+ reentrant += 1;+ if (reentrant < 5) throw new Error('again');+ return;+ }+ const msg = e.error && e.error.message;+ seen.push(msg);+ if (msg === 'reentrant') {+ reentrant = 1;+ // Thrown while reporting: must not be reported again.+ throw new Error('again');+ }+});++self.onmessage = (e) => {+ if (e.data === 'throw') {+ throw new Error('onmessage');+ }+};++const target = new EventTarget();+target.addEventListener('ping', () => { throw new Error('listener'); });+target.dispatchEvent(new Event('ping'));++setTimeout(() => { throw new Error('setTimeout'); }, 0);+setTimeout(() => { throw new Error('reentrant'); }, 5);++setTimeout(() => postMessage({ seen: seen.slice().sort(), reentrant }), 20);diff --git a/src/browser/tests/worker/worker.html b/src/browser/tests/worker/worker.htmlindex 29472fa72..dd6b39096 100644--- a/src/browser/tests/worker/worker.html+++ b/src/browser/tests/worker/worker.html@@ -576,6 +576,21 @@}</script>+<script id="worker_reports_callback_exceptions" type=module>+ {+ const state = await testing.async();+ const worker = new Worker('./report-error-worker.js');+ worker.onmessage = (e) => state.resolve(e.data);+ worker.postMessage('throw');++ await state.done((data) => {+ testing.expectEqual('listener,onmessage,reentrant,setTimeout', data.seen.join(','));+ testing.expectEqual(1, data.reentrant);+ worker.terminate();+ });+ }+</script>+<script id="worker_missing_script_fires_error" type=module>// A non-2xx script response is a load failure, and must keep firing the// error event: it travels the same error callback as a cancellation.diff --git a/src/browser/webapi/Timers.zig b/src/browser/webapi/Timers.zigindex 3ce67f8aa..bd501797e 100644--- a/src/browser/webapi/Timers.zig+++ b/src/browser/webapi/Timers.zig@@ -232,7 +232,7 @@ const ScheduleCallback = struct {if (err == error.JsException or err == error.TryCatchRethrow) {if (try_catch.exceptionValue()) |exc| {// reportError also counts the error on the page.- self.exec.js.global.reportError(exc) catch |report_err| {+ self.exec.reportError(exc) catch |report_err| {log.debug(.js, context ++ " report error", .{ .name = self.name, .err = report_err });};return;diff --git a/src/browser/webapi/WorkerGlobalScope.zig b/src/browser/webapi/WorkerGlobalScope.zigindex 95255f1b4..4abbb39be 100644--- a/src/browser/webapi/WorkerGlobalScope.zig+++ b/src/browser/webapi/WorkerGlobalScope.zig@@ -118,6 +118,7 @@ _caches: ?*CacheStorage = null,_on_error: ?JS.Function.Global = null,_on_rejection_handled: ?JS.Function.Global = null,_on_unhandled_rejection: ?JS.Function.Global = null,+_reporting_error: bool = false,_location: WorkerLocation,@@ -467,8 +468,16 @@ fn importScript(self: *WorkerGlobalScope, arena: Allocator, url: [:0]const u8) !}pub fn reportError(self: *WorkerGlobalScope, err: JS.Value) !void {+ // See Window.reportError: an exception thrown while reporting isn't reported.+ if (self._reporting_error) {+ return;+ }+self.page.recordJsError(error.JsException);+ self._reporting_error = true;+ defer self._reporting_error = false;+const error_event = try ErrorEvent.initTrusted(comptime .wrap("error"), .{.@"error" = try err.persist(),.message = err.toStringSlice() catch "Unknown error",