Skip to content

Truly independent web browser

LibWebView: Track clean exits in the session store

sideshowbarker7603a89b6f17
diff --git a/Libraries/LibWebView/Application.cpp b/Libraries/LibWebView/Application.cpp
index 36bcbc45855..7b3c3bbf51b 100644
--- a/Libraries/LibWebView/Application.cpp
+++ b/Libraries/LibWebView/Application.cpp
@@ -211,6 +211,12 @@ Application::Application(Optional<ByteString> ladybird_binary_path)
Application::~Application()
{
+#if !defined(AK_OS_WINDOWS)
+ // No event loop runs the handlers during teardown, so a signal from here on takes its default action again.
+ for (auto handler : m_session_signal_handlers)
+ Core::EventLoop::unregister_signal(handler);
+#endif
+
#if defined(AK_OS_MACOS)
// Stop bootstrap callbacks before destroying the state they use.
m_mach_port_server.clear();
@@ -251,6 +257,12 @@ Application::~Application()
m_process_manager = nullptr;
m_browser_process = nullptr;
+ // Only a normal exit gets this far, and only after every teardown step above, so a crash never records a clean one.
+ if (m_default_session && m_default_session->session_store) {
+ m_default_session->session_store->flush_dirty_state();
+ m_default_session->session_store->mark_clean_exit();
+ }
+
s_the = nullptr;
}
@@ -1732,6 +1744,19 @@ ErrorOr<void> Application::launch_services()
on_recently_closed_entries_changed();
};
+#if !defined(AK_OS_WINDOWS)
+ // A run stopped by SIGINT or SIGTERM ends like a quit, rather than like a crash: It saves the session, leaves its
+ // windows for the next launch to recover, and records a clean exit.
+ if (m_default_session->session_store->is_persistent()) {
+ for (auto signal_number : { SIGINT, SIGTERM }) {
+ m_session_signal_handlers.append(Core::EventLoop::register_signal(signal_number, [this](int) {
+ m_default_session->session_store->application_quitting();
+ m_event_loop->quit(0);
+ }));
+ }
+ }
+#endif
+
VERIFY(m_event_loop);
m_autocomplete_service = make<AutocompleteService>(*m_event_loop, move(history_database_directory));
m_autocomplete_service->update_bookmarks(autocomplete_bookmark_snapshot(*m_bookmark_store));
diff --git a/Libraries/LibWebView/Application.h b/Libraries/LibWebView/Application.h
index 3d0442f0a6b..5c2faa667a2 100644
--- a/Libraries/LibWebView/Application.h
+++ b/Libraries/LibWebView/Application.h
@@ -588,6 +588,7 @@ private:
OwnPtr<Core::File> m_cpu_profiler_control_socket;
bool m_cpu_profiler_claimed { false };
Vector<int> m_cpu_profiler_signal_handlers;
+ Vector<int> m_session_signal_handlers;
RequestServerOptions m_request_server_options;
WebContentOptions m_web_content_options;
RefPtr<FontService> m_font_service;
diff --git a/Libraries/LibWebView/SessionStore.cpp b/Libraries/LibWebView/SessionStore.cpp
index 754ea0748eb..338b6c4fa6f 100644
--- a/Libraries/LibWebView/SessionStore.cpp
+++ b/Libraries/LibWebView/SessionStore.cpp
@@ -6,6 +6,7 @@
#include <AK/Array.h>
#include <AK/Checked.h>
+#include <AK/NumericLimits.h>
#include <AK/QuickSort.h>
#include <LibCore/Timer.h>
#include <LibDatabase/ResultRow.h>
@@ -22,6 +23,7 @@ static constexpr u32 SESSIONS_SCHEMA_USER_AGENT_INITIATED_VERSION = 2u;
static constexpr u32 SESSIONS_SCHEMA_DIRECTIVE_STATE_VERSION = 3u;
static constexpr u32 SESSIONS_SCHEMA_DOCUMENT_POLICY_VERSION = 4u;
static constexpr u32 SESSIONS_SCHEMA_PINNED_TABS_VERSION = 5u;
+static constexpr u32 SESSIONS_SCHEMA_SESSION_LIFECYCLE_VERSION = 6u;
static constexpr u32 MAX_CLOSED_TABS = 25;
static constexpr u32 MAX_CLOSED_WINDOWS = 5;
static constexpr size_t MAX_ACTIVE_URL_BYTES = 8uz * 1024 * 1024;
@@ -221,6 +223,16 @@ ErrorOr<Database::MigrationOutcome> SessionStore::PersistedStorage::migrate_sche
ALTER TABLE SessionTabs ADD COLUMN pinned INTEGER NOT NULL DEFAULT 0;
)#"sv,
},
+ {
+ .version = SESSIONS_SCHEMA_SESSION_LIFECYCLE_VERSION,
+ .sql = R"#(
+ CREATE TABLE IF NOT EXISTS SessionLifecycle (
+ id INTEGER PRIMARY KEY CHECK (id = 1),
+ clean_exit INTEGER NOT NULL,
+ consecutive_unclean_exits INTEGER NOT NULL
+ );
+ )#"sv,
+ },
});
return database.migrate("Sessions"sv, migrations, mode);
@@ -259,6 +271,8 @@ ErrorOr<SessionStore::PersistedStorage> SessionStore::PersistedStorage::create(D
statements.select_open_sessions = TRY(database.prepare_statement("SELECT id FROM Sessions WHERE kind = :open_window_kind ORDER BY id;"sv));
statements.recover_open_session = TRY(database.prepare_statement("UPDATE Sessions SET kind = :closed_window_kind, closed_time = :closed_time, close_sequence = :close_sequence, source_window_id = NULL, source_tab_index = NULL, origin = :origin WHERE id = :id;"sv));
statements.delete_empty_open_sessions = TRY(database.prepare_statement("DELETE FROM Sessions WHERE kind = :open_window_kind AND NOT EXISTS (SELECT 1 FROM SessionTabs WHERE session_id = Sessions.id);"sv));
+ statements.select_lifecycle = TRY(database.prepare_statement("SELECT clean_exit, consecutive_unclean_exits FROM SessionLifecycle WHERE id = 1;"sv));
+ statements.write_lifecycle = TRY(database.prepare_statement("INSERT INTO SessionLifecycle (id, clean_exit, consecutive_unclean_exits) VALUES (1, :clean_exit, :consecutive_unclean_exits) ON CONFLICT (id) DO UPDATE SET clean_exit = excluded.clean_exit, consecutive_unclean_exits = excluded.consecutive_unclean_exits;"sv));
statements.snapshot_statements = TRY(prepare_session_history_snapshot_statements(database));
return PersistedStorage { database, move(statements) };
@@ -749,9 +763,12 @@ ErrorOr<void> SessionStore::PersistedStorage::clear_closed_units(ClearClosedUnit
});
}
-ErrorOr<void> SessionStore::PersistedStorage::recover_open_windows(RecoveryWrite const& write, IdAllocator& close_sequence_allocator)
+ErrorOr<SessionStore::RecoveryResult> SessionStore::PersistedStorage::recover_open_windows(RecoveryWrite const& write, IdAllocator& close_sequence_allocator)
{
- return database->transaction([&]() -> ErrorOr<void> {
+ RecoveryResult result;
+ TRY(database->transaction([&]() -> ErrorOr<void> {
+ result.consecutive_unclean_exits = TRY(record_run_start());
+
TRY(database->try_execute_bound_statement(statements.delete_empty_open_sessions, [&](auto& bind) -> ErrorOr<void> {
return bind("open_window_kind"sv, to_underlying(UnitKind::OpenWindow));
}));
@@ -779,7 +796,8 @@ ErrorOr<void> SessionStore::PersistedStorage::recover_open_windows(RecoveryWrite
}
TRY(prune_closed_units(UnitKind::ClosedTab, write.closed_tab_limit));
return prune_closed_units(UnitKind::ClosedWindow, write.closed_window_limit);
- });
+ }));
+ return result;
}
ErrorOr<void> SessionStore::PersistedStorage::delete_session_rows(SessionWindowId window_id)
@@ -789,6 +807,47 @@ ErrorOr<void> SessionStore::PersistedStorage::delete_session_rows(SessionWindowI
});
}
+ErrorOr<void> SessionStore::PersistedStorage::write_lifecycle(bool clean_exit, u32 consecutive_unclean_exits)
+{
+ return database->try_execute_bound_statement(statements.write_lifecycle, [&](auto& bind) -> ErrorOr<void> {
+ TRY(bind("clean_exit"sv, i64 { clean_exit ? 1 : 0 }));
+ TRY(bind("consecutive_unclean_exits"sv, i64 { consecutive_unclean_exits }));
+ return {};
+ });
+}
+
+// Runs inside the recovery transaction, so it opens none of its own.
+ErrorOr<u32> SessionStore::PersistedStorage::record_run_start()
+{
+ // A first run has no row yet, and counts as following a clean exit.
+ bool last_run_exited_cleanly = true;
+ u32 consecutive_unclean_exits = 0;
+ TRY(database->try_execute_bound_statement(
+ statements.select_lifecycle,
+ [](auto&) -> ErrorOr<void> { return {}; },
+ [&](Database::ResultRow& row) -> ErrorOr<void> {
+ // A row that fails to read (a value that isn't an integer, or a count outside u32) counts the same way as a
+ // first run, so the write below repairs it. Failing recovery instead would leave every later launch with a
+ // transient store, since nothing else ever rewrites the row.
+ auto clean_exit = row.read_integer<i64>("clean_exit"sv);
+ auto unclean_exits = row.read_integer<u32>("consecutive_unclean_exits"sv);
+ if (clean_exit.is_error() || unclean_exits.is_error())
+ return {};
+ last_run_exited_cleanly = clean_exit.value() != 0;
+ consecutive_unclean_exits = unclean_exits.value();
+ return {};
+ }));
+
+ if (last_run_exited_cleanly)
+ consecutive_unclean_exits = 0;
+ else if (consecutive_unclean_exits < NumericLimits<u32>::max())
+ ++consecutive_unclean_exits;
+
+ // This run counts as unclean until mark_clean_exit() says otherwise.
+ TRY(write_lifecycle(false, consecutive_unclean_exits));
+ return consecutive_unclean_exits;
+}
+
ErrorOr<void> SessionStore::PersistedStorage::prune_closed_units(UnitKind kind, u32 max_units)
{
return database->try_execute_bound_statement(statements.prune_closed, [&](auto& bind) -> ErrorOr<void> {
@@ -1166,12 +1225,13 @@ ErrorOr<void> SessionStore::run_startup_recovery(UnixDateTime recovered_at)
m_tab_id_allocator = allocators.tab_ids;
m_close_sequence_allocator = allocators.close_sequences;
- TRY(m_persisted_storage->recover_open_windows({
- .recovered_at = canonicalized_to_milliseconds(recovered_at),
- .closed_tab_limit = max_closed_units(UnitKind::ClosedTab),
- .closed_window_limit = max_closed_units(UnitKind::ClosedWindow),
- },
+ auto recovery = TRY(m_persisted_storage->recover_open_windows({
+ .recovered_at = canonicalized_to_milliseconds(recovered_at),
+ .closed_tab_limit = max_closed_units(UnitKind::ClosedTab),
+ .closed_window_limit = max_closed_units(UnitKind::ClosedWindow),
+ },
m_close_sequence_allocator));
+ m_consecutive_unclean_exits = recovery.consecutive_unclean_exits;
m_transient_storage.set_closed_units(TRY(m_persisted_storage->load_closed_units()));
return {};
@@ -1809,6 +1869,15 @@ void SessionStore::application_quit_aborted()
m_quitting = false;
}
+void SessionStore::mark_clean_exit()
+{
+ m_consecutive_unclean_exits = 0;
+ if (!m_persisted_storage.has_value())
+ return;
+ if (auto result = m_persisted_storage->write_lifecycle(true, 0); result.is_error())
+ dbgln("Unable to record a clean exit in the session store: {}", result.error());
+}
+
bool SessionStore::has_closed_units() const
{
return m_transient_storage.has_closed_units();
diff --git a/Libraries/LibWebView/SessionStore.h b/Libraries/LibWebView/SessionStore.h
index 20dd2e07393..249bc7a8915 100644
--- a/Libraries/LibWebView/SessionStore.h
+++ b/Libraries/LibWebView/SessionStore.h
@@ -120,6 +120,14 @@ public:
void application_quitting();
void application_quit_aborted();
+ // How many runs in a row, ending with the one before this, ended without mark_clean_exit().
+ u32 consecutive_unclean_exits() const { return m_consecutive_unclean_exits; }
+
+ // Records that this run is ending normally. Only a normal teardown calls it, so a crash never records one.
+ void mark_clean_exit();
+
+ bool is_persistent() const { return m_persisted_storage.has_value(); }
+
bool has_closed_units() const;
ErrorOr<Optional<ClosedSessionUnit>> take_most_recently_closed();
ErrorOr<void> remove_entries_accessed_since(UnixDateTime);
@@ -176,6 +184,8 @@ private:
Database::StatementID select_open_sessions;
Database::StatementID recover_open_session;
Database::StatementID delete_empty_open_sessions;
+ Database::StatementID select_lifecycle;
+ Database::StatementID write_lifecycle;
SessionHistorySnapshotStatements snapshot_statements;
};
@@ -303,6 +313,10 @@ private:
u32 closed_window_limit { 0 };
};
+ struct RecoveryResult {
+ u32 consecutive_unclean_exits { 0 };
+ };
+
// Applies mutations atomically while preserving persisted row invariants.
struct PersistedStorage {
static ErrorOr<Database::MigrationOutcome> migrate_schema(Database::Database&, Database::MigrationMode);
@@ -316,9 +330,10 @@ private:
ErrorOr<void> close_window(ClosedWindowWrite const&);
ErrorOr<void> discard_tab(DiscardTabWrite const&);
ErrorOr<void> clear_closed_units(ClearClosedUnitsWrite const&);
- ErrorOr<void> recover_open_windows(RecoveryWrite const&, IdAllocator& close_sequence_allocator);
+ ErrorOr<RecoveryResult> recover_open_windows(RecoveryWrite const&, IdAllocator& close_sequence_allocator);
ErrorOr<void> delete_session_rows(SessionWindowId);
ErrorOr<void> prune_closed_units(UnitKind, u32 max_units);
+ ErrorOr<void> write_lifecycle(bool clean_exit, u32 consecutive_unclean_exits);
ErrorOr<IdAllocators> create_id_allocators();
ErrorOr<SessionHistorySnapshot> load_tab_snapshot(SessionTabId, size_t current_used_step_index);
@@ -329,6 +344,7 @@ private:
Statements statements;
private:
+ ErrorOr<u32> record_run_start();
ErrorOr<void> apply_tab_row_write(TabWrite const&);
ErrorOr<void> apply_window_metadata(WindowMetadataWrite const&);
ErrorOr<void> insert_closed_unit_row(ClosedUnitWrite const&);
@@ -433,6 +449,7 @@ private:
Optional<PendingClearClosedUnits> m_pending_clear_closed_units;
Vector<WindowMetadataWrite> m_retired_window_metadata;
bool m_quitting { false };
+ u32 m_consecutive_unclean_exits { 0 };
IdAllocator m_session_id_allocator;
IdAllocator m_tab_id_allocator;
diff --git a/Tests/LibWebView/TestSessionHistorySnapshotStorage.cpp b/Tests/LibWebView/TestSessionHistorySnapshotStorage.cpp
index 821f4635800..1a302b904b1 100644
--- a/Tests/LibWebView/TestSessionHistorySnapshotStorage.cpp
+++ b/Tests/LibWebView/TestSessionHistorySnapshotStorage.cpp
@@ -533,6 +533,7 @@ TEST_CASE(snapshot_entries_saved_before_the_user_agent_initiated_column_load_as_
// Take the database back to the baseline schema, keeping the entry's row.
TRY_OR_FAIL(database->execute_raw(R"#(
+ DROP TABLE SessionLifecycle;
ALTER TABLE SessionTabs DROP COLUMN pinned;
ALTER TABLE SessionPolicyContainers DROP COLUMN force_load_at_top;
ALTER TABLE SessionEntries DROP COLUMN directive_state_value;
@@ -543,7 +544,7 @@ TEST_CASE(snapshot_entries_saved_before_the_user_agent_initiated_column_load_as_
)#"sv));
auto migrated_statements = prepare_snapshot_tables(*database);
- EXPECT_EQ(TRY_OR_FAIL(database->schema_version("Sessions"sv)), Optional<u32> { 5u });
+ EXPECT_EQ(TRY_OR_FAIL(database->schema_version("Sessions"sv)), Optional<u32> { 6u });
auto loaded = TRY_OR_FAIL(load_session_history_snapshot(*database, migrated_statements, 42, 0));
EXPECT_EQ(loaded.entries.size(), 1uz);
diff --git a/Tests/LibWebView/TestSessionStore.cpp b/Tests/LibWebView/TestSessionStore.cpp
index 64cacacbd1a..a5a9579cee9 100644
--- a/Tests/LibWebView/TestSessionStore.cpp
+++ b/Tests/LibWebView/TestSessionStore.cpp
@@ -75,6 +75,7 @@ static SessionTabId open_tab(SessionStore& store, SessionWindowId window, String
// Takes the schema back to SESSIONS_SCHEMA_DOCUMENT_POLICY_VERSION, so every migration after it runs again.
static void rewind_sessions_schema_to_version_4(Database::Database& database)
{
+ MUST(database.execute_raw("DROP TABLE SessionLifecycle;"sv));
MUST(database.execute_raw("ALTER TABLE SessionTabs DROP COLUMN pinned;"sv));
MUST(database.execute_raw("UPDATE SchemaVersions SET version = 4 WHERE store = 'Sessions';"sv));
}
@@ -87,7 +88,7 @@ TEST_CASE(fresh_database_migrates_to_the_latest_schema)
for (auto table : { "Sessions"sv, "SessionTabs"sv, "SessionUsedSteps"sv, "SessionHistories"sv, "SessionNestedHistories"sv, "SessionEntries"sv })
EXPECT(TRY_OR_FAIL(database->table_exists(table)));
- EXPECT_EQ(TRY_OR_FAIL(database->schema_version("Sessions"sv)), Optional<u32> { 5u });
+ EXPECT_EQ(TRY_OR_FAIL(database->schema_version("Sessions"sv)), Optional<u32> { 6u });
}
TEST_CASE(deleting_a_session_cascades_through_its_tabs)
@@ -134,7 +135,7 @@ TEST_CASE(version_4_database_migrates_to_the_latest_schema)
rewind_sessions_schema_to_version_4(*database);
EXPECT_EQ(TRY_OR_FAIL(SessionStore::migrate_schema(*database)), Database::MigrationOutcome::Success);
- EXPECT_EQ(TRY_OR_FAIL(database->schema_version("Sessions"sv)), Optional<u32> { 5u });
+ EXPECT_EQ(TRY_OR_FAIL(database->schema_version("Sessions"sv)), Optional<u32> { 6u });
EXPECT_EQ(select_i64(*database, "SELECT pinned FROM SessionTabs WHERE id = 2;"_string), 0);
}
@@ -1298,6 +1299,39 @@ TEST_CASE(aborted_quit_resumes_demotion)
EXPECT(store->has_closed_units());
}
+TEST_CASE(a_first_run_counts_as_following_a_clean_exit)
+{
+ auto database = create_session_database();
+ auto store = TRY_OR_FAIL(SessionStore::create(*database));
+ EXPECT_EQ(store->consecutive_unclean_exits(), 0u);
+}
+
+TEST_CASE(a_corrupt_lifecycle_row_counts_as_following_a_clean_exit)
+{
+ auto database = create_session_database();
+ TRY_OR_FAIL(database->execute_raw("INSERT INTO SessionLifecycle (id, clean_exit, consecutive_unclean_exits) VALUES (1, 0, -1);"sv));
+
+ EXPECT_EQ(TRY_OR_FAIL(SessionStore::create(*database))->consecutive_unclean_exits(), 0u);
+
+ // The run start rewrote the row, so the next run counts the one before it as unclean.
+ EXPECT_EQ(TRY_OR_FAIL(SessionStore::create(*database))->consecutive_unclean_exits(), 1u);
+}
+
+TEST_CASE(unclean_exits_count_up_until_a_clean_exit)
+{
+ auto database = create_session_database();
+
+ // A store destroyed without mark_clean_exit() is what a crash leaves behind.
+ (void)TRY_OR_FAIL(SessionStore::create(*database));
+ EXPECT_EQ(TRY_OR_FAIL(SessionStore::create(*database))->consecutive_unclean_exits(), 1u);
+ {
+ auto store = TRY_OR_FAIL(SessionStore::create(*database));
+ EXPECT_EQ(store->consecutive_unclean_exits(), 2u);
+ store->mark_clean_exit();
+ }
+ EXPECT_EQ(TRY_OR_FAIL(SessionStore::create(*database))->consecutive_unclean_exits(), 0u);
+}
+
TEST_CASE(retention_keeps_the_newest_closed_units)
{
auto database = create_session_database();