Skip to content

Truly independent web browser

LibWeb: Keep fetch engine commands in order across nested event loops

Andreas Kling2fbe806b68e9
diff --git a/Libraries/LibWeb/Fetch/Engine/FetchExecutor.cpp b/Libraries/LibWeb/Fetch/Engine/FetchExecutor.cpp
index 52cf0f7a432..0634840ca5d 100644
--- a/Libraries/LibWeb/Fetch/Engine/FetchExecutor.cpp
+++ b/Libraries/LibWeb/Fetch/Engine/FetchExecutor.cpp
@@ -21,13 +21,48 @@ void FetchExecutor::post(EngineCommand command)
if (m_shut_down.load(AK::MemoryOrder::memory_order_acquire))
return;
+ // NB: A task runs every pending command, oldest first, and not just the one it was posted with. A task can run in a
+ // nested event loop, such as the one a sync XHR spins, while tasks posted before it still wait in the outer
+ // loop. The engine must still see the commands in posting order, and the nested loop must also run the commands
+ // it waits for.
+ {
+ MutexLocker locker { m_pending_commands_mutex };
+ m_pending_commands.enqueue(move(command));
+ }
+
// The task keeps the executor, and so the engine, alive until it has run or been dropped.
- auto run_command = [self = NonnullRefPtr(*this), command = move(command)]() mutable {
- if (self->m_shut_down.load(AK::MemoryOrder::memory_order_acquire))
- return;
- self->m_engine->handle_command(move(command));
- };
- post_task(move(run_command));
+ auto run_pending_commands = [self = NonnullRefPtr(*this)] { self->run_pending_commands(); };
+ if (!post_task(move(run_pending_commands)))
+ drop_pending_commands();
+}
+
+void FetchExecutor::run_pending_commands()
+{
+ for (;;) {
+ Optional<EngineCommand> command;
+ {
+ MutexLocker locker { m_pending_commands_mutex };
+ if (m_pending_commands.is_empty())
+ return;
+ command = m_pending_commands.dequeue();
+ }
+ if (m_shut_down.load(AK::MemoryOrder::memory_order_acquire))
+ continue;
+ m_engine->handle_command(command.release_value());
+ }
+}
+
+void FetchExecutor::drop_pending_commands()
+{
+ // NB: Without a loop to run on, no command that is still pending can ever run. They are destroyed after the lock is
+ // released.
+ Vector<EngineCommand> pending_commands;
+ {
+ MutexLocker locker { m_pending_commands_mutex };
+ pending_commands.ensure_capacity(m_pending_commands.size());
+ while (!m_pending_commands.is_empty())
+ pending_commands.unchecked_append(m_pending_commands.dequeue());
+ }
}
void FetchExecutor::shutdown()
diff --git a/Libraries/LibWeb/Fetch/Engine/FetchExecutor.h b/Libraries/LibWeb/Fetch/Engine/FetchExecutor.h
index 102a6084a4f..0fc26e8bf23 100644
--- a/Libraries/LibWeb/Fetch/Engine/FetchExecutor.h
+++ b/Libraries/LibWeb/Fetch/Engine/FetchExecutor.h
@@ -9,7 +9,9 @@
#include <AK/Atomic.h>
#include <AK/AtomicRefCounted.h>
#include <AK/Function.h>
+#include <AK/Mutex.h>
#include <AK/NonnullOwnPtr.h>
+#include <AK/Queue.h>
#include <LibWeb/Export.h>
#include <LibWeb/Fetch/Engine/EngineCommand.h>
#include <LibWeb/Fetch/Engine/EngineCommandSink.h>
@@ -32,11 +34,17 @@ protected:
FetchExecutorServices const& services() const { return m_services; }
- virtual void post_task(Function<void()>) = 0;
+ // Answers false if the task can never run, as the loop it would run on is gone.
+ virtual bool post_task(Function<void()>) = 0;
private:
+ void run_pending_commands();
+ void drop_pending_commands();
+
FetchExecutorServices m_services;
NonnullOwnPtr<EngineCommandSink> m_engine;
+ Mutex m_pending_commands_mutex;
+ Queue<EngineCommand> m_pending_commands;
Atomic<bool> m_shut_down { false };
};
diff --git a/Libraries/LibWeb/Fetch/Engine/InlineFetchExecutor.cpp b/Libraries/LibWeb/Fetch/Engine/InlineFetchExecutor.cpp
index 1d11ab93f94..09c12a2412b 100644
--- a/Libraries/LibWeb/Fetch/Engine/InlineFetchExecutor.cpp
+++ b/Libraries/LibWeb/Fetch/Engine/InlineFetchExecutor.cpp
@@ -18,12 +18,13 @@ InlineFetchExecutor::InlineFetchExecutor(FetchExecutorServices services, Nonnull
{
}
-void InlineFetchExecutor::post_task(Function<void()> task)
+bool InlineFetchExecutor::post_task(Function<void()> task)
{
auto loop = services().event_loop->take();
if (!loop)
- return;
+ return false;
loop->deferred_invoke(move(task));
+ return true;
}
}
diff --git a/Libraries/LibWeb/Fetch/Engine/InlineFetchExecutor.h b/Libraries/LibWeb/Fetch/Engine/InlineFetchExecutor.h
index 58bcbcb9b8e..d4877be3b44 100644
--- a/Libraries/LibWeb/Fetch/Engine/InlineFetchExecutor.h
+++ b/Libraries/LibWeb/Fetch/Engine/InlineFetchExecutor.h
@@ -19,7 +19,7 @@ public:
private:
InlineFetchExecutor(FetchExecutorServices, NonnullOwnPtr<EngineCommandSink>);
- virtual void post_task(Function<void()>) override;
+ virtual bool post_task(Function<void()>) override;
};
}
diff --git a/Tests/LibWeb/Crash/Fetch/fetch-started-before-sync-xhr-in-resumed-parser.html b/Tests/LibWeb/Crash/Fetch/fetch-started-before-sync-xhr-in-resumed-parser.html
new file mode 100644
index 00000000000..92458ca9aee
--- /dev/null
+++ b/Tests/LibWeb/Crash/Fetch/fetch-started-before-sync-xhr-in-resumed-parser.html
@@ -0,0 +1,60 @@
+<!doctype html>
+<html class="test-wait">
+ <body>
+ <script>
+ const runId = crypto.randomUUID();
+ const styleSheetPath = `fetch-started-before-sync-xhr-style-sheet-${runId}`;
+
+ const request = new XMLHttpRequest();
+ request.open("POST", "/echo", false);
+ request.setRequestHeader("Content-Type", "application/json");
+ request.send(
+ JSON.stringify({
+ method: "GET",
+ path: `/echo/${styleSheetPath}`,
+ status: 200,
+ headers: { "Content-Type": "text/css" },
+ wait_for_unblock: styleSheetPath,
+ })
+ );
+
+ async function waitForRequest(path) {
+ while (true) {
+ const response = await fetch(`/recorded-request-headers${path}`, { cache: "no-store" });
+ if (response.ok) return;
+ await new Promise(resolve => setTimeout(resolve, 5));
+ }
+ }
+
+ async function finish() {
+ await fetch(`/unblock/${styleSheetPath}`, { cache: "no-store" });
+ document.documentElement.classList.remove("test-wait");
+ }
+
+ window.addEventListener("message", async event => {
+ if (event.data === "child-parser-about-to-block") {
+ // The child's parser waits for the style sheet before it runs its next script.
+ await waitForRequest(`/echo/${styleSheetPath}`);
+
+ // Removing the style sheet resumes the child's parser from a deferred invocation. The fetch below
+ // is started after it, and the child's script starts a sync XHR before the fetch has started.
+ const childDocument = document.querySelector("iframe").contentDocument;
+ childDocument.querySelector("link").remove();
+ fetch("data:text/plain,started-before-the-sync-xhr").then(finish, finish);
+ }
+ });
+
+ const iframe = document.createElement("iframe");
+ iframe.srcdoc = `
+ <script>parent.postMessage("child-parser-about-to-block", "*");<\/script>
+ <link rel="stylesheet" href="/echo/${styleSheetPath}">
+ <script>
+ const request = new XMLHttpRequest();
+ request.open("GET", "data:text/plain,sync", false);
+ request.send();
+ <\/script>
+ `;
+ document.body.append(iframe);
+ </script>
+ </body>
+</html>
diff --git a/Tests/LibWeb/TestConfig.ini b/Tests/LibWeb/TestConfig.ini
index db30be21c3d..54ae2611e2c 100644
--- a/Tests/LibWeb/TestConfig.ini
+++ b/Tests/LibWeb/TestConfig.ini
@@ -76,6 +76,7 @@ Text/input/wpt-import/html/cross-origin-embedder-policy/shared-workers.https.htm
Text/input/wpt-import/dom/events/event-listener-not-fully-active-adopted-node.html
Text/input/wpt-import/dom/events/event-listener-not-fully-active-navigated.html
Crash/DOM/shared-resource-request-finalize-while-in-flight.html
+Crash/Fetch/fetch-started-before-sync-xhr-in-resumed-parser.html
Text/input/css/linked-stylesheet-redirect-base-url.html
Text/input/HTML/initial-about-blank-window-outlives-abandoned-navigation.html
Crash/HTML/location-href-setter-during-navigation-from-initial-about-blank.html
diff --git a/Tests/LibWeb/TestFetchExecutor.cpp b/Tests/LibWeb/TestFetchExecutor.cpp
index 9426eb3ab7a..57b5c013bf0 100644
--- a/Tests/LibWeb/TestFetchExecutor.cpp
+++ b/Tests/LibWeb/TestFetchExecutor.cpp
@@ -83,6 +83,55 @@ TEST_CASE(commands_run_on_the_loop_in_posting_order)
EXPECT(thread.is_current_thread());
}
+TEST_CASE(commands_run_in_posting_order_when_a_command_spins_a_nested_loop)
+{
+ Core::EventLoop loop;
+ RecordedCommands recorded;
+ RefPtr<InlineFetchExecutor> executor;
+
+ // The first command posts a third one and spins a nested loop until it has run, as a sync XHR does.
+ class SpinningSink final : public EngineCommandSink {
+ public:
+ SpinningSink(RecordedCommands& recorded, RefPtr<InlineFetchExecutor>& executor)
+ : m_recorded(recorded)
+ , m_executor(executor)
+ {
+ }
+
+ virtual void handle_command(EngineCommand command) override
+ {
+ auto fetch_id = command.get<Command::Stop>().fetch_id.value();
+ m_recorded.fetch_ids.append(fetch_id);
+ if (fetch_id != 1)
+ return;
+ m_executor->post(Command::Stop { .fetch_id = FetchId(3) });
+ // NB: The cap keeps the test finite when the nested loop does not run the third command.
+ for (auto turns = 0; turns < 10 && !m_recorded.fetch_ids.contains_slow(3); ++turns)
+ Core::EventLoop::current().pump(Core::EventLoop::WaitMode::PollForEvents);
+ m_ran_inside_nested_loop = m_recorded.fetch_ids.contains_slow(3);
+ }
+
+ bool ran_inside_nested_loop() const { return m_ran_inside_nested_loop; }
+
+ private:
+ RecordedCommands& m_recorded;
+ RefPtr<InlineFetchExecutor>& m_executor;
+ bool m_ran_inside_nested_loop { false };
+ };
+
+ auto sink = make<SpinningSink>(recorded, executor);
+ auto& spinning_sink = *sink;
+ executor = InlineFetchExecutor::create(services_for_current_thread(), move(sink));
+ executor->post(Command::Stop { .fetch_id = FetchId(1) });
+ executor->post(Command::Stop { .fetch_id = FetchId(2) });
+
+ loop.pump(Core::EventLoop::WaitMode::PollForEvents);
+ EXPECT_EQ(recorded.fetch_ids, (Vector<u64> { 1, 2, 3 }));
+ EXPECT(spinning_sink.ran_inside_nested_loop());
+ EXPECT(!has_queued_tasks(*executor));
+ executor = nullptr;
+}
+
TEST_CASE(an_executor_on_another_thread_runs_its_commands_there)
{
Core::EventLoop main_loop;