Skip to content

Truly independent web browser

UI/Qt: Invalidate a web view’s AX elements when the view goes away

sideshowbarkerf555fa9fec5b
diff --git a/Tests/LibWeb/AccessibilityBridgeMac/tests/test_view_teardown.py b/Tests/LibWeb/AccessibilityBridgeMac/tests/test_view_teardown.py
new file mode 100644
index 00000000000..0f5ed786d32
--- /dev/null
+++ b/Tests/LibWeb/AccessibilityBridgeMac/tests/test_view_teardown.py
@@ -0,0 +1,80 @@
+"""An element an assistive technology holds outlives the view it came from."""
+
+from __future__ import annotations
+
+import pathlib
+import sys
+import time
+import unittest
+
+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
+
+from AppKit import NSApplicationActivateIgnoringOtherApps # noqa: E402
+from AppKit import NSRunningApplication # noqa: E402
+from AppKit import NSWorkspace # noqa: E402
+from ApplicationServices import kAXRoleAttribute # noqa: E402
+from ApplicationServices import kAXTitleAttribute # noqa: E402
+from harness import FIXTURE_DIR # noqa: E402
+from harness import LadybirdContext # noqa: E402
+from harness import wait_for # noqa: E402
+from harness import wait_for_descendant_by_role # noqa: E402
+from harness.ladybird import _ax_attr # noqa: E402
+from Quartz import kCGEventFlagMaskCommand # noqa: E402
+
+from tests.test_native_control_key_editing import send_native_key # noqa: E402
+
+KEY_CODE_1 = 18
+KEY_CODE_T = 17
+KEY_CODE_W = 13
+
+
+class HeldElementOutlivesItsViewTests(unittest.TestCase):
+ """Regression: an element of a closed tab crashed Ladybird when an assistive technology read it.
+
+ The elements of a web view hold a raw pointer into the view's accessibility tree, which goes away with the view.
+ An element the tree dropped gives the pointer up, but one that was still in the tree when its tab closed kept it,
+ and the next attribute an assistive technology asked of it read the freed tree (a SIGBUS in
+ AccessibilityTreeManager::node()). Now the view's going away invalidates every element its overlay vended."""
+
+ def setUp(self):
+ super().setUp()
+ self._previous_application = NSWorkspace.sharedWorkspace().frontmostApplication()
+ self.ctx = LadybirdContext((FIXTURE_DIR / "sibling_insert.html").as_uri(), launch_via_launch_services=True)
+ self.addCleanup(self._cleanup)
+ self.ctx.start()
+
+ def _cleanup(self):
+ self.ctx.stop()
+ if self._previous_application:
+ self._previous_application.activateWithOptions_(NSApplicationActivateIgnoringOtherApps)
+
+ def test_reading_an_element_of_a_closed_tab_does_not_crash(self):
+ beta = wait_for_descendant_by_role(self.ctx.web, "AXButton", title="Beta")
+ self.assertIsNotNone(beta, "sibling_insert.html must expose its Beta button")
+ self.assertEqual(_ax_attr(beta, kAXTitleAttribute), "Beta")
+
+ # A second tab keeps the window open once the first one closes.
+ send_native_key(self.ctx.pid, KEY_CODE_T, kCGEventFlagMaskCommand)
+ time.sleep(1.0)
+ send_native_key(self.ctx.pid, KEY_CODE_1, kCGEventFlagMaskCommand)
+ time.sleep(0.5)
+ send_native_key(self.ctx.pid, KEY_CODE_W, kCGEventFlagMaskCommand)
+
+ # Once the first tab's view is gone, its element answers nothing, and Ladybird keeps running.
+ def element_is_gone():
+ return _ax_attr(beta, kAXRoleAttribute) is None
+
+ self.assertTrue(wait_for(element_is_gone, timeout=10.0), "the closed tab's element still answers")
+ for _ in range(20):
+ _ax_attr(beta, kAXTitleAttribute)
+ _ax_attr(beta, kAXRoleAttribute)
+ time.sleep(0.05)
+ application = NSRunningApplication.runningApplicationWithProcessIdentifier_(self.ctx.pid)
+ self.assertTrue(
+ application is not None and not application.isTerminated(),
+ "Ladybird exited after an element of a closed tab was read",
+ )
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/UI/Qt/WebContentView.cpp b/UI/Qt/WebContentView.cpp
index a6e7285c314..654b3830308 100644
--- a/UI/Qt/WebContentView.cpp
+++ b/UI/Qt/WebContentView.cpp
@@ -382,6 +382,11 @@ WebContentView::WebContentView(QWidget* window, Optional<u64> hub_view_id, WebCo
WebContentView::~WebContentView()
{
+#if defined(Q_OS_MACOS)
+ // An assistive technology can still hold elements of this view's accessibility tree, which goes away with it.
+ uninstall_accessibility(this);
+#endif
+
#ifdef LADYBIRD_QT_USE_IOSURFACE_LAYER
destroy_iosurface_layer();
#elif defined(LADYBIRD_QT_USE_VULKAN_WINDOW)
diff --git a/UI/Qt/WebContentViewAccessibility.h b/UI/Qt/WebContentViewAccessibility.h
index c3143bf5953..c7ddf05b496 100644
--- a/UI/Qt/WebContentViewAccessibility.h
+++ b/UI/Qt/WebContentViewAccessibility.h
@@ -18,6 +18,9 @@ class WebContentView;
// Attaches LadybirdAccessibilityElement objects to the QWidget's underlying NSView — bypassing Qt's Cocoa accessibility
// bridge entirely.
void install_accessibility(WebContentView* view);
+// Invalidates every element that the view's overlay vended, before the view and its accessibility tree go away: an
+// assistive technology can hold an element longer than either.
+void uninstall_accessibility(WebContentView* view);
// announce_load: a page's first tree announces the load and has AppKit look the focus up again; the trees DOM mutations
// bring do neither. report_focus: the first tree an assistive technology that arrived mid-page gets has AppKit look the
// focus up again. Both only while the view holds the keyboard focus in the key window.
diff --git a/UI/Qt/WebContentViewAccessibility.mm b/UI/Qt/WebContentViewAccessibility.mm
index 7b8411cbb88..3d4f7ec1ea4 100644
--- a/UI/Qt/WebContentViewAccessibility.mm
+++ b/UI/Qt/WebContentViewAccessibility.mm
@@ -33,6 +33,8 @@ extern "C" void NSAccessibilityHandleFocusChanged();
@property (nonatomic, assign) Ladybird::WebContentView* webContentView;
@property (nonatomic, strong) NSMutableDictionary<NSNumber*, LadybirdAccessibilityElement*>* elements;
+- (void)detach;
+
@end
@implementation WebContentAccessibilityView
@@ -51,6 +53,23 @@ extern "C" void NSAccessibilityHandleFocusChanged();
return self;
}
+- (void)dealloc
+{
+ [self detach];
+}
+
+// The elements this overlay vended hold raw pointers into the view's accessibility tree, and an assistive technology
+// can hold them longer than the overlay, the view, and the tree. So once the overlay goes away, or its view does, they
+// are all invalidated, and the overlay itself reaches into neither the view nor the tree again.
+- (void)detach
+{
+ for (LadybirdAccessibilityElement* element in _elements.allValues)
+ [element invalidate];
+ [_elements removeAllObjects];
+ _manager = nullptr;
+ _webContentView = nullptr;
+}
+
- (NSView*)hitTest:(NSPoint)point
{
return nil;
@@ -75,6 +94,8 @@ extern "C" void NSAccessibilityHandleFocusChanged();
if (existing)
return existing;
+ if (!_manager)
+ return nil;
auto const* data = _manager->node(nodeID);
if (!data)
return nil;
@@ -93,6 +114,8 @@ extern "C" void NSAccessibilityHandleFocusChanged();
// pixel ratio that LocalAccessible::Bounds() converts with), so a CSS pixel is zoom_level() points. No device-
// pixel-ratio scaling on top of that — convertRect works in points. (Blink and WebKit zoom in layout instead, so
// their AX bounds come out zoomed already.)
+ if (!_webContentView)
+ return NSZeroRect;
auto zoom = _webContentView->zoom_level();
NSRect zoomed_rect = NSMakeRect(viewRect.origin.x * zoom, viewRect.origin.y * zoom, viewRect.size.width * zoom, viewRect.size.height * zoom);
NSRect window_rect = [self convertRect:zoomed_rect toView:nil];
@@ -102,6 +125,8 @@ extern "C" void NSAccessibilityHandleFocusChanged();
- (NSRect)accessibilityViewRectForScreenPoint:(NSPoint)screenPoint
{
// The inverse: a screen point to CSS pixels, so points divided by the zoom level.
+ if (!_webContentView)
+ return NSZeroRect;
NSRect screen_rect = NSMakeRect(screenPoint.x, screenPoint.y, 0, 0);
NSRect window_rect = [self.window convertRectFromScreen:screen_rect];
NSPoint view_point = [self convertPoint:window_rect.origin fromView:nil];
@@ -116,6 +141,8 @@ extern "C" void NSAccessibilityHandleFocusChanged();
// focused. VoiceOver also sets the focus on what its cursor moves to when the keyboard focus follows that cursor,
// the AXWebArea first as the cursor enters the page. Leave the focus alone if the view or a child of it, such as
// the crash overlay's buttons, already has it.
+ if (!_webContentView)
+ return;
auto& view = *_webContentView;
auto* focus_widget = view.window()->focusWidget();
auto focus_is_in_view = focus_widget && (focus_widget == &view || view.isAncestorOf(focus_widget));
@@ -512,6 +539,12 @@ void update_accessibility_tree(WebContentView* view, bool announce_load, bool re
NSAccessibilityHandleFocusChanged();
}
+void uninstall_accessibility(WebContentView* view)
+{
+ if (auto* overlay = get_overlay(view))
+ [overlay detach];
+}
+
void post_accessibility_focus_changed(WebContentView* view, i64 node_id)
{
auto* overlay = get_overlay(view);