Lightpanda: the headless browser designed for AI and automation
crash: fix various document.close bugs
Karl Seguinf9803b844d73
diff --git a/src/browser/Frame.zig b/src/browser/Frame.zigindex 941bc863d..69c45930c 100644--- a/src/browser/Frame.zig+++ b/src/browser/Frame.zig@@ -452,7 +452,16 @@ pub fn init(self: *Frame, frame_id: u32, page: *Page, opts: InitOpts) !void {}pub fn deinit(self: *Frame) void {+ // open/write become no-ops.+ self.document._navigated_away = true;for (self.child_frames.items) |frame| {+ // The <iframe> outlives its frame in our (now inactive) document:+ // removing it later must not discard the freed frame.+ if (frame.iframe) |iframe| {+ // the <iframe> outlives it frame. If the <iframe> is removed again,+ // don't try to free the frame again.+ iframe._window = null;+ }frame.deinit();}@@ -1440,15 +1449,9 @@ fn iframeCompletedLoading(self: *Frame, iframe: *IFrame, delays_load: bool) voidconst entered = self.js.enter(&hs);defer entered.exit();- blk: {- const event = Event.initTrusted(comptime .wrap("load"), .{}, self.page) catch |err| {- log.err(.frame, "iframe event init", .{ .err = err, .url = iframe.srcAttribute() });- break :blk;- };- self._event_manager.dispatch(iframe.asNode().asEventTarget(), event) catch |err| {- log.debug(.js, "iframe onload", .{ .err = err, .url = iframe.srcAttribute() });- };- }+ self.fireIFrameLoad(iframe) catch |err| {+ log.debug(.js, "iframe onload", .{ .err = err, .url = iframe.srcAttribute() });+ };if (delays_load) {self.pendingLoadCompleted();@@ -1467,16 +1470,29 @@ pub fn pendingLoadCompleted(self: *Frame) void {// A document.open() has been closed. If it was opened after it loaded, it// will re-trigger DOMContentLoaded and load.-pub fn scriptCreatedParserDone(self: *Frame) void {+pub fn scriptCreatedParserDone(self: *Frame) !void {switch (self._load_state) {.parsing, .load => {},.waiting => self._load_state = .parsing,.complete => {- self._load_state = .parsing;- self._parent_notified = false;- // the parent was already released the first time, we don't- // want documentIsComplete to re-trigger it.- self._delays_parent_load = false;+ // Queued, as in Chrome: firing from within document.close() lets+ // a load handler that writes + closes again recurse into itself.+ return self.js.scheduler.add(self, struct {+ fn run(ctx: *anyopaque) !?u32 {+ const f: *Frame = @ptrCast(@alignCast(ctx));+ // re-opened since: its own close() queues the events+ if (f.document._script_created_parser != null) {+ return null;+ }+ f._load_state = .parsing;+ f._parent_notified = false;+ // the parent was already released the first time, we don't+ // want documentIsComplete to re-trigger it.+ f._delays_parent_load = false;+ f.documentIsComplete();+ return null;+ }+ }.run, 0, .{ .name = "frame.scriptCreatedParserDone" });},}self.documentIsComplete();@@ -1536,6 +1552,12 @@ fn _documentIsComplete(self: *Frame) !void {try self._event_manager.dispatchDirect(window_target, event, .{ .inject_target = false, .context = "page load" });}+ if (self.window._closed) {+ // discarded by its own load handler: no longer active, and discard()+ // released the parent already+ return;+ }+self._session.notification.dispatch(.frame_loaded, &.{.req_id = self._req_id,.frame_id = self._frame_id,@@ -2792,6 +2814,20 @@ pub fn loadExternalStylesheet(self: *Frame, link: *Element.Html.Link, href: []cotry self.fireElementEvent(element, comptime .wrap("load"));}+// https://html.spec.whatwg.org/multipage/iframe-embed-object.html#iframe-load-event-steps+// A document.open() from within this event mutes the element's later loads.+fn fireIFrameLoad(self: *Frame, iframe: *IFrame) !void {+ const child_doc = if (iframe._window) |w| w._frame.document else null;+ if (child_doc) |doc| {+ if (doc._mute_iframe_load) return;+ doc._iframe_load_in_progress = true;+ }+ defer if (child_doc) |doc| {+ doc._iframe_load_in_progress = false;+ };+ try self.fireElementEvent(iframe.asElement(), comptime .wrap("load"));+}+fn fireElementEvent(self: *Frame, el: *Element, name: String) !void {const event = try Event.initTrusted(name, .{}, self.page);try self._event_manager.dispatch(el.asEventTarget(), event);@@ -2819,7 +2855,11 @@ fn dispatchQueuedEvents(self: *Frame) !void {switch (queued.kind) {.load => {if (has_dom_load_listener or self._event_manager.hasHandler(element.asEventTarget(), "load")) {- try self.fireElementEvent(element, comptime .wrap("load"));+ if (html_element.is(IFrame)) |iframe| {+ try self.fireIFrameLoad(iframe);+ } else {+ try self.fireElementEvent(element, comptime .wrap("load"));+ }}},.@"error" => {diff --git a/src/browser/parser/Parser.zig b/src/browser/parser/Parser.zigindex 2b51ba678..463ff41c4 100644--- a/src/browser/parser/Parser.zig+++ b/src/browser/parser/Parser.zig@@ -416,7 +416,8 @@ pub const Streaming = struct {while (true) {try self.feed(input);if (self.pending_input.items.len == 0) {- return;+ // document.write's text must be visible when it returns,+ return self.parser.flushPendingText();}// Scripts that ran during the feed queued more markup via// re-entrant read(). This swaps the buffers, and ensures thatdiff --git a/src/browser/tests/document/open_load_events.html b/src/browser/tests/document/open_load_events.htmlindex 163acb249..1b98cf894 100644--- a/src/browser/tests/document/open_load_events.html+++ b/src/browser/tests/document/open_load_events.html@@ -82,3 +82,76 @@});}</script>++<script id=close_from_load_handler type=module>+ {+ const state = await testing.async();++ // Each window load opens, writes + closes again: the next load must be+ // queued, not fired from within close() (which recursed, and crashed on+ // the write).+ const iframe = document.createElement('iframe');+ document.body.appendChild(iframe);+ const cw = iframe.contentWindow;+ let depth = 0;+ let max_depth = 0;+ let count = 0;++ const rewrite = () => {+ const doc = cw.document;+ doc.open();+ // open() erased the window's listeners+ cw.addEventListener('load', onload);+ doc.write('<b id=n>' + count + '</b>');+ doc.close();+ };+ const onload = () => {+ depth += 1;+ max_depth = Math.max(max_depth, depth);+ count += 1;+ if (count < 3) {+ rewrite();+ } else {+ state.resolve();+ }+ depth -= 1;+ };+ setTimeout(rewrite, 5);++ await state.done(() => {+ testing.expectEqual(1, max_depth);+ testing.expectEqual(3, count);+ testing.expectEqual('2', cw.document.getElementById('n').textContent);+ });+ }+</script>++<!--+ https://html.spec.whatwg.org/multipage/iframe-embed-object.html#iframe-load-event-steps+ open() from within the iframe element's load event mutes its later ones.+-->+<script id=open_during_iframe_load_mutes type=module>+ {+ const state = await testing.async();++ const iframe = document.createElement('iframe');+ let loads = 0;+ let window_loads = 0;+ iframe.addEventListener('load', () => {+ loads += 1;+ if (loads > 1) return;+ const doc = iframe.contentDocument;+ doc.open();+ iframe.contentWindow.addEventListener('load', () => window_loads += 1);+ doc.write('<p>muted</p>');+ doc.close();+ setTimeout(() => state.resolve(), 10);+ });+ document.body.appendChild(iframe);++ await state.done(() => {+ testing.expectEqual(1, loads);+ testing.expectEqual(1, window_loads);+ });+ }+</script>diff --git a/src/browser/tests/frames/document_write.html b/src/browser/tests/frames/document_write.htmlindex 7565c28c5..b7d7416ff 100644--- a/src/browser/tests/frames/document_write.html+++ b/src/browser/tests/frames/document_write.html@@ -48,3 +48,78 @@});}</script>++<!-- Written text is in the DOM when write() returns, not only after close(). -->+<script id=iframe_write_text_visible>+{+ const iframe = document.createElement('iframe');+ document.documentElement.appendChild(iframe);++ const doc = iframe.contentDocument;+ doc.write('WRITE HAPPENED');+ testing.expectEqual('WRITE HAPPENED', doc.body.innerHTML);+ doc.write(' AGAIN');+ testing.expectEqual('WRITE HAPPENED AGAIN', doc.body.innerHTML);+ doc.close();+}+</script>++<!--+ A document whose frame navigated away is inactive: write() is a no-op. Its+ <iframe> outlives the (torn down) child frame, so removing it must not crash.+-->+<script id=write_to_navigated_away_document type=module>+{+ const state = await testing.async();++ const iframe = document.createElement('iframe');+ let old_doc = null;+ iframe.onload = () => {+ if (old_doc === null) {+ old_doc = iframe.contentDocument;+ old_doc.body.appendChild(old_doc.createElement('iframe'));+ iframe.src = 'support/sub2.html';+ return;+ }+ old_doc.write('WRITE HAPPENED');+ state.resolve();+ };+ iframe.src = 'support/page.html';+ document.documentElement.appendChild(iframe);++ await state.done(() => {+ testing.expectEqual('IFRAME', old_doc.body.lastChild.tagName);+ old_doc.body.lastChild.remove();+ testing.expectEqual(null, old_doc.querySelector('iframe'));+ testing.expectEqual('sub2 div1', iframe.contentDocument.getElementById('div-1').textContent);+ });+}+</script>++<!-- Same, for the document of an iframe nested in the navigated-away one. -->+<script id=write_to_nested_navigated_away_document type=module>+{+ const state = await testing.async();++ const iframe = document.createElement('iframe');+ let inner_doc = null;+ iframe.onload = () => {+ if (inner_doc === null) {+ const doc = iframe.contentDocument;+ const inner = doc.createElement('iframe');+ doc.body.appendChild(inner);+ inner_doc = inner.contentDocument;+ iframe.src = 'support/sub2.html';+ return;+ }+ inner_doc.write('<p>WRITE HAPPENED</p>');+ state.resolve();+ };+ iframe.src = 'support/page.html';+ document.documentElement.appendChild(iframe);++ await state.done(() => {+ testing.expectEqual('', inner_doc.body.innerHTML);+ });+}+</script>diff --git a/src/browser/tests/frames/remove.html b/src/browser/tests/frames/remove.htmlindex 521098013..b64f66ae0 100644--- a/src/browser/tests/frames/remove.html+++ b/src/browser/tests/frames/remove.html@@ -144,3 +144,24 @@});}</script>++<!-- removed by its own window load handler: discard already released the+ parent, the rest of the load steps must not notify it again -->+<script id=removed_by_own_load_handler type=module>+ {+ const state = await testing.async();++ const f = document.createElement('iframe');+ window.removeLoadingFrame = () => {+ f.remove();+ setTimeout(() => state.resolve(), 10);+ };+ f.srcdoc = '<script>onload = () => parent.removeLoadingFrame();<\/script>';+ document.body.appendChild(f);++ await state.done(() => {+ delete window.removeLoadingFrame;+ testing.expectEqual(null, f.contentWindow);+ });+ }+</script>diff --git a/src/browser/webapi/Document.zig b/src/browser/webapi/Document.zigindex 61019eea9..d21882e43 100644--- a/src/browser/webapi/Document.zig+++ b/src/browser/webapi/Document.zig@@ -71,6 +71,12 @@ _ready_state: ReadyState = .loading,_load_aborted: bool = false,// HTML's "active parser was aborted" flag also makes open/write no-ops._active_parser_aborted: bool = false,+// Its frame navigated to another document: open/write are no-ops.+_navigated_away: bool = false,+// The iframe load event steps' flags: a document.open() while the element's+// load event fires for this document mutes its later ones.+_iframe_load_in_progress: bool = false,+_mute_iframe_load: bool = false,_current_script: ?*Element.Html.Script = null,_elements_by_id: std.StringHashMapUnmanaged(*Element) = .empty,// Track IDs that were removed from the map - they might have duplicates in the tree@@ -1085,7 +1091,7 @@ fn writeInternal(self: *Document, text: []const []const u8, append_newline: boolreturn error.InvalidStateError;}- if (self._active_parser_aborted) return;+ if (self._active_parser_aborted or self._navigated_away) return;const html = blk: {var joined: std.ArrayList(u8) = .empty;@@ -1213,7 +1219,7 @@ pub fn open(self: *Document, call_frame: *Frame) !*Document {return error.InvalidStateError;}- if (self._active_parser_aborted or frame._load_state == .parsing) {+ if (self._active_parser_aborted or self._navigated_away or frame._load_state == .parsing) {return self;}@@ -1221,6 +1227,10 @@ pub fn open(self: *Document, call_frame: *Frame) !*Document {return self;}+ if (self._iframe_load_in_progress) {+ self._mute_iframe_load = true;+ }+// If we aren't parsing, then open clears the document.const doc_node = self.asNode();@@ -1298,8 +1308,12 @@ fn finishScriptCreatedParser(self: *Document, frame: *Frame) !void {// Even if flushPendingText errors, the handle is already finished and we// must not retain the Streaming — defer so the error path also drops it.// (Streaming.done nulls its own handle, so dropping the struct is safe.)- defer self._script_created_parser = null;- try self._script_created_parser.?.done();+ // Dropped before the load steps below: a load handler can write() again,+ // which must open a fresh parser rather than feed this finished one.+ {+ defer self._script_created_parser = null;+ try self._script_created_parser.?.done();+ }// The write'd markup is fully parsed; run any deferred scripts it produced// (e.g. inline modules) before firing the load event. This frame's initial@@ -1307,7 +1321,7 @@ fn finishScriptCreatedParser(self: *Document, frame: *Frame) !void {// iframe written into via document.write), so we can't rely on it.frame._script_manager.base.scriptCreatedParseDone();- frame.scriptCreatedParserDone();+ try frame.scriptCreatedParserDone();}fn getFirstElementChild(self: *Document) ?*Element {