Skip to content

Play your Steam library's Windows games on a jailbroken PS5.

C++

Recover games the move or an upgrade would strand

Leonardo Lobatob77dcd7a274a
diff --git a/src/homebrew/runtime_host.cpp b/src/homebrew/runtime_host.cpp
index cae1012..8246303 100644
--- a/src/homebrew/runtime_host.cpp
+++ b/src/homebrew/runtime_host.cpp
@@ -920,6 +920,21 @@ static std::string WorkingFolder(const std::string& working, std::string program
return slash == std::string::npos ? std::string() : program.substr(0, slash);
}
+// The game root or its working folder when either isn't a folder (a stale record, an unplugged
+// drive): nothing can be published for it. root is the host path of the record's install_path.
+static std::optional<std::filesystem::path> MissingGameFolder(const std::filesystem::path& root,
+ const rt::RuntimeInstall& record) {
+ const auto folder = WorkingFolder(record.launch_working_directory, record.launch_path, record.launch_in_install_root);
+ const auto working = folder.empty() ? root : root / folder;
+ struct stat info{};
+ const auto is_directory = [&info](const std::filesystem::path& path) {
+ return lstat(path.c_str(), &info) == 0 && S_ISDIR(info.st_mode);
+ };
+ if (!is_directory(root)) return root;
+ if (!is_directory(working)) return working;
+ return std::nullopt;
+}
+
// The folders from the game root down to the program's working folder (where dxvk.conf
// goes) get the same treatment as the root: an owned, world-writable download folder
// becomes 0755. Folders that don't exist yet, links and folders owned by anyone else are
@@ -961,6 +976,27 @@ bool RuntimeHost::NeedsUnownedPublication(const Composition& c, const rt::Runtim
return rt::PublishedGameRootUnowned(record, config_.host_namespace_prefix) == std::optional<bool>(false);
}
+bool RuntimeHost::DropUpgradeRequest(Composition& c, const std::string& install_id, const std::string& why) {
+ const auto current = c.records.Find(install_id);
+ if (!current || current->state != rt::PreparationState::kReady || !current->moved_from.empty() || !current->journal ||
+ current->journal->operation != "settings-request" || current->journal->step != "capture-update")
+ return false;
+ // Only the saved request tells the upgrade (its plan at the record's revision) from a newer
+ // settings update, whose request waits for Resume as before.
+ const auto loaded = rt::LoadSettingsPublicationRequest(c.request_directory, current->journal->operation_id);
+ if (loaded.state != rt::PublicationRecoveryState::kValid || !loaded.request ||
+ loaded.request->plan.settings_revision != current->settings_revision)
+ return false;
+ const auto dropped = c.owner->DiscardRequested(*current, c.request_directory, config_.host_namespace_prefix);
+ Log("settings update app=" + std::to_string(current->app_id) + " unowned upgrade request " + current->journal->operation_id +
+ (dropped.state == rt::PackageActionState::kComplete ? " dropped" : " kept") + ": " + why +
+ (dropped.code.empty() ? std::string{} : " code=" + dropped.code) +
+ (dropped.message.empty() ? std::string{} : " " + dropped.message));
+ if (dropped.state != rt::PackageActionState::kComplete) return false;
+ PublishInstalls(c, install_id);
+ return true;
+}
+
void RuntimeHost::OpenGameFolders(const Composition& c, const rt::RuntimeInstall& record) {
// Only under an unowned publication: an owned one fails the title's start check at 0777.
if (!c.kit || record.install_path.empty() ||
@@ -1079,6 +1115,17 @@ std::string RuntimeHost::RepublishSettings(Composition& c, const rt::RuntimeInst
? config_.settings_record(record.app_id).value_or(rt::GameSettingsRecord{}).revision : 0;
const bool upgrade_only = record.moved_from.empty() && saved_revision <= record.settings_revision &&
NeedsUnownedPublication(c, record);
+ // A game folder that isn't there (a stale record, an unplugged drive) can't be published, and
+ // arming the request first would leave a journal on the record: nothing is armed for it.
+ if (upgrade_only || !record.moved_from.empty()) {
+ if (const auto missing = MissingGameFolder(HostPath(record.install_path), record)) {
+ if (!upgrade_only) return "The moved game's working folder is missing at its new place (" + missing->string() + ").";
+ Log("settings update app=" + std::to_string(record.app_id) + " unowned upgrade skipped: game folder missing (" +
+ missing->string() + ")");
+ if (upgrade_deferred) *upgrade_deferred = "The game folder is missing.";
+ return {};
+ }
+ }
auto refused = PublishSavedSettings(c, record, published, steam_account_known, prepare_again);
if (refused.empty() || !upgrade_only) return refused;
Log("settings update app=" + std::to_string(record.app_id) + " unowned upgrade deferred, owned publication kept: " +
@@ -1235,6 +1282,10 @@ std::string RuntimeHost::PublishSavedSettings(Composition& c, const rt::RuntimeI
if (moved && resumed.state == rt::PackageActionState::kComplete)
if (const auto current = c.records.Find(record.install_id))
c.admission[record.install_id] = c.installer->QuickAdmission(*current);
+ // The upgrade alone is optional: one that failed before its publication began (the request
+ // arm is still on the record) is dropped, and the game keeps playing under its owned publication.
+ if (resumed.state != rt::PackageActionState::kComplete && unowned_upgrade && saved.revision == record.settings_revision)
+ DropUpgradeRequest(c, record.install_id, resumed.message);
PublishInstalls(c, record.install_id);
// A failed update keeps its journal, so Play waits until Resume on the PS5 title finishes it.
if (resumed.state != rt::PackageActionState::kComplete) return "The settings could not be applied: " + resumed.message;
@@ -1272,8 +1323,12 @@ void RuntimeHost::MoveGameRecords(Composition& c) {
void RuntimeHost::FinishGamesMove(Composition& c) {
if (!c.games_move) return;
// Games not prepared yet (or failed) keep their mark; their next preparation publishes the new folder.
+ // So does a Ready one whose folder is gone (installed again elsewhere): it can't be republished
+ // (RepublishSettings), and Uninstall or Recreate bottle clears its mark.
for (const auto& record : c.repository.Snapshot())
- if (!record.moved_from.empty() && record.state == rt::PreparationState::kReady) return;
+ if (!record.moved_from.empty() && record.state == rt::PreparationState::kReady &&
+ !MissingGameFolder(HostPath(record.install_path), record))
+ return;
std::string error;
const bool done = config_.finish_games_move && config_.finish_games_move(&error);
Log(std::string("layout move ") + (done ? "done" : "not marked done: " + error));
@@ -1837,8 +1892,12 @@ std::string RuntimeHost::RunPrepare(Composition& c, const RuntimePrepareRequest&
if (existing->journal) {
const auto resumed = DrivePublication(c, *existing);
PublishInstalls(c);
- if (resumed.state != rt::PackageActionState::kComplete) return resumed.message;
- return {};
+ if (resumed.state == rt::PackageActionState::kComplete) return {};
+ // An unowned upgrade's request that never reached its publication is dropped: the game
+ // keeps its owned publication, and the update goes on below as for any Ready game.
+ if (!DropUpgradeRequest(c, existing->install_id, resumed.message)) return resumed.message;
+ existing = c.records.Find(existing->install_id);
+ if (!existing) return "The game's install record is missing.";
}
bool changed = false;
// Older titles carry the kit's generic name and icon: give them the game's.
@@ -2774,6 +2833,7 @@ void RuntimeHost::Run() {
c.records, *c.installer, *c.coordinator,
c.kit && rt::KitCapabilitiesFromManifest(c.kit->capabilities, true).game_root_unowned,
config_.host_namespace_prefix);
+ c.owner->SetLog([this](const std::string& line) { Log(line); });
c.service = std::make_unique<rt::RuntimeInstallService>(
c.records, *c.installer, *c.coordinator,
[&c](const rt::RuntimeInstall& record) {
@@ -2876,6 +2936,13 @@ void RuntimeHost::Run() {
Log("startup bottle profiles settled=" + std::to_string(settled) + " ms=" +
std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - began).count()));
}
+ // An unowned upgrade's request cut off before its publication began (a crash, a capture
+ // refused on an earlier start) is dropped first: the game plays under its owned publication,
+ // and the pass below tries the upgrade again. Moved games and newer settings keep theirs.
+ for (const auto& record : c.repository.Snapshot())
+ if (record.state == rt::PreparationState::kReady && record.journal && record.moved_from.empty() &&
+ record.journal->operation == "settings-request" && record.journal->step == "capture-update")
+ DropUpgradeRequest(c, record.install_id, "left by an earlier start");
// Games whose folder moved with the games root (0.6) start from Home only once their
// publication names the new folder: republished now, busy titles wait for Play.
// So are games published owned while the kit admits unowned folders (folders opened for
diff --git a/src/homebrew/runtime_host.hpp b/src/homebrew/runtime_host.hpp
index dc6588c..b0d7e51 100644
--- a/src/homebrew/runtime_host.hpp
+++ b/src/homebrew/runtime_host.hpp
@@ -366,6 +366,11 @@ class RuntimeHost {
// A Ready game published owned (schema 2, before 0.6 or by a kit before 0.10) while the kit
// admits unowned game folders: published again as unowned, so folders the player opened pass.
bool NeedsUnownedPublication(const Composition& composition, const runtime::RuntimeInstall& record);
+ // The request of an unowned upgrade alone (same revision, the game not moved) that failed before
+ // its publication began: the record still carries the request arm, so the owned publication the
+ // game played under is intact. Dropped (true), the game plays as before; Play, Update, Repair and
+ // the next start try the upgrade again. Moved games and newer settings keep their request.
+ bool DropUpgradeRequest(Composition& composition, const std::string& install_id, const std::string& why);
// The 0.6 games move: rewrites the records and Cloud indexes under the old games root at startup,
// and marks the move done once no moved Ready game is left to republish.
void MoveGameRecords(Composition& composition);
diff --git a/src/runtime/layout_migration.cpp b/src/runtime/layout_migration.cpp
index 0ac8392..f6dfaa5 100644
--- a/src/runtime/layout_migration.cpp
+++ b/src/runtime/layout_migration.cpp
@@ -211,7 +211,34 @@ std::optional<std::string> PendingJournal(const LayoutPaths& paths, const Layout
RuntimeInstallRepository repository(storage, "installs.json", {});
const auto loaded = repository.Load();
if (!loaded.ok()) return "the install records can't be read (" + loaded.message() + ")";
+ // Only games inside the folder that moves can be stranded by it: installs on USB and M.2
+ // drives keep their paths, so their journals don't hold the move back.
+ // Records name console paths; the host folder is checked too.
+ const auto moving_host = paths.app_root / "games";
+ const auto moving = fs::path("/data") / moving_host.lexically_relative(paths.boundary);
+ // The game's folder on the host, when it sits inside the folder that moves.
+ const auto inside = [&](const std::string& install_path) -> std::optional<fs::path> {
+ for (const auto& root : {moving, moving_host}) {
+ const auto relative = fs::path(install_path).lexically_normal().lexically_relative(root);
+ if (!relative.empty() && *relative.begin() != "..") return moving_host / relative;
+ }
+ return std::nullopt;
+ };
for (const auto& record : repository.Snapshot()) {
+ const auto folder = inside(record.install_path);
+ if (!folder) continue;
+ // A record whose folder is gone (the game was installed again elsewhere) can't be stranded.
+ if (Kind(*folder) != 1) {
+ Log(ops, "install " + record.install_id + " skipped: its folder " + folder->string() + " is missing");
+ continue;
+ }
+ // A game started or suspended from Home still uses its old paths, whatever Playden launched last.
+ if (ops.title_running && !record.title_id.empty()) {
+ const auto running = ops.title_running(record.title_id);
+ if (!running || *running)
+ return "the game " + record.title_id + " may still be running or suspended. Close it, and Playden moves "
+ "them the next time it starts";
+ }
if (record.journal)
return "install " + record.install_id + " has a pending " + record.journal->operation + " journal";
// data_root is /data/playden/games/<id>; map it under this layout's boundary.
diff --git a/src/runtime/settings_publication.cpp b/src/runtime/settings_publication.cpp
index 954bbb7..5f53898 100644
--- a/src/runtime/settings_publication.cpp
+++ b/src/runtime/settings_publication.cpp
@@ -158,6 +158,28 @@ bool OwnedReplacedByUnowned(const std::string& previous_metadata, bool unowned)
}
GameRootMove InPlace(const RuntimeInstall& r) { return {r.install_path, r.install_path}; }
}
+PackageActionResult VerifyCommittedPublicationReceipt(const RuntimeInstall& r, const std::filesystem::path& prefix) {
+ const auto refuse = [](const char* message) { return Failure("publication-receipt", message); };
+ if (!prefix.empty() && (!prefix.is_absolute() || prefix != prefix.lexically_normal())) return refuse("Invalid canonical namespace.");
+ const auto control = Map(prefix, r.data_root + "/.playden-control");
+ auto directory = ManagedDirectory::Open(control, DirectoryPolicy::kPrivate);
+ if (!directory) return refuse("Private publication control directory is unavailable.");
+ auto receipt = ReadReceipt(control, *directory);
+ if (!receipt.ok || receipt.absent) return refuse("The publication receipt is missing, corrupt or unavailable.");
+ PwTitlePublication parsed{};
+ if (pw_title_publication_parse(reinterpret_cast<const uint8_t*>(receipt.bytes.data()), receipt.bytes.size(), &parsed) != PW_OK ||
+ parsed.phase != PW_TITLE_PUBLICATION_COMMITTED || parsed.install_id != r.install_id || parsed.title_id != r.title_id ||
+ parsed.settings_revision != r.settings_revision)
+ return refuse("The publication receipt is not committed for this install at its revision.");
+ auto profiles = ManagedDirectory::Open(Map(prefix, r.data_root + "/library/profiles"), DirectoryPolicy::kPrivate);
+ auto metadata = profiles ? ReadPublicationFile(*profiles, ".playden-publication", 32768) : std::nullopt;
+ PwTitlePublicationMetadata m{};
+ if (!metadata || !metadata->present || HashArtifactBytes(metadata->bytes) != std::optional<std::string>(parsed.publication_sha256) ||
+ pw_title_publication_metadata_parse(reinterpret_cast<const uint8_t*>(metadata->bytes.data()), metadata->bytes.size(), &m) != PW_OK ||
+ m.install_id != r.install_id || m.title_id != r.title_id || m.data_root != r.data_root || m.settings_revision != r.settings_revision)
+ return refuse("The published metadata does not bind the committed receipt.");
+ return {PackageActionState::kComplete, {}, {}};
+}
std::optional<bool> PublishedGameRootUnowned(const RuntimeInstall& r, const std::filesystem::path& prefix) {
if (!prefix.empty() && (!prefix.is_absolute() || prefix != prefix.lexically_normal())) return std::nullopt;
auto profiles = ManagedDirectory::Open(Map(prefix, r.data_root + "/library/profiles"), DirectoryPolicy::kPrivate);
diff --git a/src/runtime/settings_publication.h b/src/runtime/settings_publication.h
index 9eccb0e..0eb1497 100644
--- a/src/runtime/settings_publication.h
+++ b/src/runtime/settings_publication.h
@@ -41,6 +41,12 @@ std::optional<GameRootMove> GameRootMoveOf(const RuntimeInstall& record);
PackageActionResult VerifyMovedPublication(const RuntimeInstall& record, const GameRootMove& move,
const std::string& receipt_bytes, const std::string& metadata_bytes,
const std::filesystem::path& host_namespace_prefix = {}, bool unowned = false);
+// The committed publication a Ready game plays under: its receipt (publication-state.v1) is
+// committed, names this install at the record's revision and binds the published metadata
+// (.playden-publication), which names the same install. Read-only; the caller holds the
+// publisher lease. What the control folder's operation journal is not needed for.
+PackageActionResult VerifyCommittedPublicationReceipt(const RuntimeInstall& record,
+ const std::filesystem::path& host_namespace_prefix = {});
// Whether the game's committed publication (its .playden-publication) admits the game folder
// unowned (metadata schema 3); nothing when there is none or it can't be read.
std::optional<bool> PublishedGameRootUnowned(const RuntimeInstall& record,
diff --git a/src/runtime/settings_publication_journal.cpp b/src/runtime/settings_publication_journal.cpp
index e634fe5..5462095 100644
--- a/src/runtime/settings_publication_journal.cpp
+++ b/src/runtime/settings_publication_journal.cpp
@@ -495,6 +495,30 @@ static PublicationOperationLoad LoadOperationFile(const std::filesystem::path& c
PublicationOperationLoad LoadSettingsPublicationOperation(const std::filesystem::path& control) {
return LoadOperationFile(control, kOperationName);
}
+Result<std::string> SetAsideSettingsPublicationOperation(const std::filesystem::path& control, std::int64_t unix_time) {
+ auto fail = [](StorageError error, std::string message) { return Result<std::string>::Failure(error, std::move(message)); };
+ if (unix_time < 0) return fail(StorageError::kInvalidData, "Invalid set-aside time.");
+ auto directory = platform::ManagedDirectory::Open(control, platform::DirectoryPolicy::kPrivate);
+ if (!directory) return fail(StorageError::kOpenFailed, "Private control directory is unavailable.");
+ const auto active = LoadSettingsPublicationOperation(control);
+ if (active.state != PublicationRecoveryState::kCorrupt)
+ return fail(StorageError::kInvalidData, active.state == PublicationRecoveryState::kAbsent ? "No active journal to set aside." :
+ active.state == PublicationRecoveryState::kValid ? "The active journal loads; it is never set aside." :
+ "The active journal is unavailable, not unreadable: " + active.message);
+ for (unsigned attempt = 1; attempt <= 16; ++attempt) {
+ const auto name = "settings-operation.unreadable-" + std::to_string(unix_time) +
+ (attempt > 1 ? "." + std::to_string(attempt) : std::string()) + ".v1";
+ struct stat existing{};
+ if (directory->InspectChild(name, &existing)) continue;
+ if (errno != ENOENT) return fail(StorageError::kOpenFailed, "The set-aside name cannot be inspected.");
+ if (!directory->RenameChild(kOperationName, *directory, name, false))
+ return fail(StorageError::kRenameFailed, "The unreadable journal could not be set aside: " + std::string(strerror(errno)));
+ if (!directory->Sync() || LoadSettingsPublicationOperation(control).state != PublicationRecoveryState::kAbsent)
+ return fail(StorageError::kSyncFailed, "The journal's absence could not be verified after it was set aside.");
+ return Result<std::string>::Success(name);
+ }
+ return fail(StorageError::kOpenFailed, "No free set-aside name.");
+}
Result<void> ArchiveSettingsPublicationOperation(const std::filesystem::path& control,
const SettingsPublicationOperation& operation, const std::function<bool()>& after_rename) {
std::string reason; auto expected = EncodeSettingsPublicationOperation(operation, &reason);
diff --git a/src/runtime/settings_publication_journal.h b/src/runtime/settings_publication_journal.h
index 6d17d9b..242347a 100644
--- a/src/runtime/settings_publication_journal.h
+++ b/src/runtime/settings_publication_journal.h
@@ -81,6 +81,13 @@ struct PublicationOperationLoad {
Result<void> CreateSettingsPublicationOperation(
const std::filesystem::path& control_directory, const SettingsPublicationOperation& operation);
PublicationOperationLoad LoadSettingsPublicationOperation(const std::filesystem::path& control_directory);
+// Moves an active settings-operation.v1 that no longer loads (LoadSettingsPublicationOperation:
+// kCorrupt, never kUnavailable, which may pass) to settings-operation.unreadable-<unix_time>[.N].v1,
+// never replacing a file and never deleting. The caller holds the publisher lease and has proven
+// the committed publication without it (its receipt and metadata). A journal that loads is never
+// set aside. Nothing reads the new name afterwards. Returns it.
+Result<std::string> SetAsideSettingsPublicationOperation(const std::filesystem::path& control_directory,
+ std::int64_t unix_time);
// Caller must first verify committed semantics and durable Ready OWNER state
// under its exclusive lease. Moves the exact journal to a transaction-specific
// immutable archive without replacing a destination; preserves backups. Retry
diff --git a/src/runtime/settings_publication_owner.cpp b/src/runtime/settings_publication_owner.cpp
index c47ff8e..f0d32fc 100644
--- a/src/runtime/settings_publication_owner.cpp
+++ b/src/runtime/settings_publication_owner.cpp
@@ -1,6 +1,9 @@
#include "runtime/settings_publication_owner.h"
+#include "runtime/publication_contract.h"
#include "platform/managed_file_lock.h"
+#include "platform/storage.h"
#include <cerrno>
+#include <cstring>
#include <unistd.h>
namespace playden::runtime {
namespace {
@@ -127,6 +130,72 @@ PackageActionResult SettingsPublicationOwner::ResumeRequested(const RuntimeInsta
auto dependencies = Dependencies(prefix, GameRootMoveOf(*current));
return PublishSettingsOperation(prepared.value(), OperationPaths(prepared.value(), prefix), dependencies);
}
+PackageActionResult SettingsPublicationOwner::DiscardRequested(const RuntimeInstall& record,
+ const std::filesystem::path& directory, const std::filesystem::path& prefix) {
+ if (!prefix.empty() && (!prefix.is_absolute() || prefix != prefix.lexically_normal()))
+ return Failure("publication-discard-invalid", "Invalid discard namespace.");
+ auto current = records_.Find(record.install_id);
+ if (!current || !SameRuntimeInstallIdentity(*current, record) || current->settings_revision != record.settings_revision ||
+ current->state != PreparationState::kReady || !current->journal || !record.journal ||
+ current->journal->operation != "settings-request" || current->journal->step != "capture-update" ||
+ current->journal->operation_id != record.journal->operation_id ||
+ !IsSettingsPublicationTransactionId(current->journal->operation_id))
+ return Failure("publication-discard-owner", "The install record has no requested update to drop.");
+ const auto transaction = current->journal->operation_id;
+ const auto canonical = std::filesystem::path(current->data_root + "/.playden-control");
+ const auto control_path = prefix.empty() ? canonical : prefix / canonical.relative_path();
+ auto control = platform::ManagedDirectory::Open(control_path, platform::DirectoryPolicy::kPrivate);
+ auto lease = control ? platform::ManagedFileLock::Acquire(*control, "publication.lock", platform::LockMode::kPublisher) : std::nullopt;
+ if (!lease) return Failure("publication-busy", "The publication lock is unavailable or held (the game may be running).");
+ // The committed publication the record plays under: another transaction, at the record's
+ // revision. A pending receipt, or one of this transaction, means the request got further
+ // than its capture (Block then also moved the journal on): nothing is dropped.
+ struct stat info{};
+ if (!control->InspectChild("publication-state.v1", &info) || !S_ISREG(info.st_mode) || info.st_size <= 0 || info.st_size > 8192)
+ return Failure("publication-discard-receipt", "The committed publication's receipt is missing or unreadable.");
+ auto read = Storage(control_path.string()).ReadDurable("publication-state.v1", 8192);
+ PwTitlePublication receipt{};
+ if (!read.ok() || pw_title_publication_parse(read.value().data(), read.value().size(), &receipt) != PW_OK ||
+ receipt.phase != PW_TITLE_PUBLICATION_COMMITTED || receipt.transaction_id == transaction ||
+ receipt.install_id != current->install_id || receipt.title_id != current->title_id ||
+ receipt.settings_revision != current->settings_revision)
+ return Failure("publication-discard-receipt", "The committed publication does not prove this request never applied.");
+ // An active journal of this transaction would mean the same; one that can't be read is the
+ // previous operation's (the record's journal proves this one never blocked OWNER).
+ auto active = LoadSettingsPublicationOperation(control_path);
+ if (active.operation && active.operation->transaction_id == transaction)
+ return Failure("publication-discard-conflict", "The requested operation already has an active journal.");
+ auto observed = records_.Find(record.install_id);
+ if (!observed || !SameRuntimeInstallIdentity(*observed, *current) || observed->state != current->state ||
+ observed->settings_revision != current->settings_revision || !observed->journal ||
+ observed->journal->operation != "settings-request" || observed->journal->operation_id != transaction ||
+ observed->journal->step != "capture-update" || !lease->Validate(*control, "publication.lock"))
+ return Failure("publication-discard-owner", "The install record or the publication lock changed while the request was dropped.");
+ current->journal.reset();
+ current->last_failure.reset();
+ auto saved = Persist(*current);
+ if (saved.state != PackageActionState::kComplete) return saved;
+ // This capture's registry backup and prepared intent are unreferenced too: each retry is a new
+ // transaction, so they would pile up (a backup copies user.reg). Only this transaction's, by name;
+ // RemoveRegularFile admits only an owned regular file, never a link. Best effort.
+ bool removed_any = false;
+ for (const auto& name : {"registry-backup-" + transaction + ".v1", "settings-intent-" + transaction + ".v1"}) {
+ struct stat leftover{};
+ if (!control->InspectChild(name, &leftover)) {
+ if (errno != ENOENT && log_) log_("settings request dropped install=" + current->install_id + ": " + name +
+ " stays (" + std::strerror(errno) + ")");
+ continue;
+ }
+ if (control->RemoveRegularFile(name)) removed_any = true;
+ else if (log_) log_("settings request dropped install=" + current->install_id + ": " + name + " stays (" +
+ std::strerror(errno) + ")");
+ }
+ if (removed_any && !control->Sync() && log_)
+ log_("settings request dropped install=" + current->install_id + ": control folder sync failed");
+ // Unreferenced now; a request that stays is a leftover (RuntimeHost::LeftoverRequests).
+ auto removed = Storage(directory.string()).RemoveDurable("settings-request-" + transaction + ".v1");
+ return {PackageActionState::kComplete, {}, removed.ok() ? std::string{} : "The saved request stays as a leftover: " + removed.message()};
+}
PackageActionResult SettingsPublicationOwner::InitializeControl(const RuntimeInstall& record, const std::string& transaction,
const std::filesystem::path& prefix, const std::function<bool(PublicationControlStep)>& after_step) {
if (!IsSettingsPublicationTransactionId(transaction) ||
@@ -240,12 +309,31 @@ Result<SettingsPublicationOperation> SettingsPublicationOwner::Prepare(const Run
auto lease = control ? platform::ManagedFileLock::Acquire(*control, "publication.lock", platform::LockMode::kPublisher) : std::nullopt;
if (!lease)
return fail("The publication lock is unavailable or held (the game may be running).");
+ // The loader's reason names the file and the check that refused it: a console start once
+ // failed here without the log saying which.
auto recovered = LoadSettingsPublicationOperation(control_path);
+ // A Ready game's last operation that no longer loads (written by another build, damaged) is not
+ // needed: the committed receipt and the published metadata prove the previous state, as they do
+ // when the journal is absent. It is set aside under its own name, never deleted, and the
+ // publication goes on as if it were absent. One merely unavailable (a passing error) is not.
+ if (recovered.state == PublicationRecoveryState::kCorrupt && current->state == PreparationState::kReady &&
+ !(current->journal && current->journal->operation == "settings-publication")) {
+ const auto reason = recovered.message;
+ const auto verified = VerifyCommittedPublicationReceipt(*current, prefix);
+ if (verified.state != PackageActionState::kComplete)
+ return fail("Existing frozen operation is corrupt or unavailable: " + reason + " (kept: " + verified.message + ")");
+ if (!lease->Validate(*control, "publication.lock")) return fail("The publication lock changed before the journal was set aside.");
+ auto aside = SetAsideSettingsPublicationOperation(control_path, time);
+ if (!aside.ok())
+ return fail("Existing frozen operation is corrupt or unavailable: " + reason + " (not set aside: " + aside.message() + ")");
+ if (log_) log_("settings operation set aside install=" + current->install_id + " as " + aside.value() + ": " + reason);
+ recovered = LoadSettingsPublicationOperation(control_path);
+ }
if (recovered.state == PublicationRecoveryState::kCorrupt || recovered.state == PublicationRecoveryState::kUnavailable)
- return fail("Existing frozen operation is corrupt or unavailable.");
+ return fail("Existing frozen operation is corrupt or unavailable: " + recovered.message);
auto intent = LoadPreparedSettingsPublicationOperation(control_path, transaction);
if (intent.state == PublicationRecoveryState::kCorrupt || intent.state == PublicationRecoveryState::kUnavailable)
- return fail("Prepared intent is corrupt or unavailable; preserve its evidence.");
+ return fail("Prepared intent is corrupt or unavailable; preserve its evidence: " + intent.message);
if (intent.operation) {
if (recovered.operation && recovered.operation->transaction_id == transaction) {
std::string reason;
diff --git a/src/runtime/settings_publication_owner.h b/src/runtime/settings_publication_owner.h
index 7552b3b..3dca74e 100644
--- a/src/runtime/settings_publication_owner.h
+++ b/src/runtime/settings_publication_owner.h
@@ -22,6 +22,16 @@ class SettingsPublicationOwner {
PackageActionResult ResumeRequested(const RuntimeInstall& record,
const std::filesystem::path& request_directory,
const std::filesystem::path& host_namespace_prefix = {});
+ // Drops a Ready update's request that never reached its publication: the record's journal is
+ // still settings-request/capture-update, so Block never ran and the committed publication (its
+ // receipt names another transaction, at the record's revision) is untouched. Under the
+ // publisher lease, so a running game (holding it shared) refuses. The record returns to Ready
+ // with no journal; the saved request is removed when it can be (a leftover otherwise). A
+ // capture's files of this transaction (its registry backup, its prepared intent) are removed
+ // too, best effort (logged); no later capture reads them. Other transactions' files stay.
+ PackageActionResult DiscardRequested(const RuntimeInstall& record,
+ const std::filesystem::path& request_directory,
+ const std::filesystem::path& host_namespace_prefix = {});
// Creates (or adopts) only the private control directory and stable empty lock,
// after a durable initial OWNER intent. The data root must already exist. A
// matching interrupted intent resumes; symbolic links and malformed locks refuse.
@@ -29,6 +39,8 @@ class SettingsPublicationOwner {
PackageActionResult InitializeControl(const RuntimeInstall& record, const std::string& transaction_id,
const std::filesystem::path& host_namespace_prefix = {},
const std::function<bool(PublicationControlStep)>& after_step = {});
+ // Lines worth the runtime log (an unreadable journal set aside); nothing by default.
+ void SetLog(std::function<void(const std::string&)> log) { log_ = std::move(log); }
Result<SettingsPublicationOperation> Prepare(const RuntimeInstall& record, const SettingsLaunchPlan& plan,
const std::string& kit_id, const std::string& transaction_id, std::int64_t registry_unix_time,
const std::filesystem::path& host_namespace_prefix = {});
@@ -51,5 +63,6 @@ class SettingsPublicationOwner {
NativeCoordinator& native_;
bool unowned_game_roots_ = false;
std::filesystem::path host_namespace_prefix_;
+ std::function<void(const std::string&)> log_;
};
} // namespace playden::runtime
diff --git a/tests/homebrew_runtime_host_test.cpp b/tests/homebrew_runtime_host_test.cpp
index 11797f5..4549d96 100644
--- a/tests/homebrew_runtime_host_test.cpp
+++ b/tests/homebrew_runtime_host_test.cpp
@@ -14,6 +14,8 @@
#include <iterator>
#include <map>
#include <mutex>
+#include <fcntl.h>
+#include <sys/file.h>
#include <sys/stat.h>
#include <thread>
#include <atomic>
@@ -2986,7 +2988,83 @@ void RestartDuringRepublishResumes() {
// A moved game whose folder is gone from the new place is not published over: it keeps its mark
// and the move stays unfinished.
-void MovedGameMissingAtNewRootKeepsTheMove() {
+// A schema-2 (owned) game whose folder is gone (a stale record, an unplugged drive) is not
+// republished unowned: nothing is armed, so no journal waits on the record.
+void UnownedUpgradeSkippedWhenFolderMissing() {
+ Fixture fixture;
+ auto config = fixture.Config();
+ config.host_namespace_prefix = fixture.root;
+ config.package_paths.console_data_root = "/data";
+ config.package_paths.host_data_root = fixture.root / "data";
+ config.package_operations.hash_file = HashArtifactFile;
+ config.package_operations.hash_bytes = HashArtifactBytes;
+ config.package_operations.free_space_unverifiable = true;
+ config.package_operations.validate_bottle = [](const fs::path& bottle) {
+ return fs::is_regular_file(bottle / "system.reg") && fs::is_regular_file(bottle / "user.reg");
+ };
+ auto kit = SyntheticKit(fixture.root / "kit");
+ kit.capabilities = {"dxvk", "offline_bottle", "per_game_title", kKitDxvkConfig, "wow64_i386"};
+ config.admit_kit = [&kit](std::string*) { return std::optional<RuntimeKit>(kit); };
+ unsigned uuids = 0;
+ config.uuid = [&uuids]() -> std::optional<std::string> {
+ char id[37]; std::snprintf(id, sizeof(id), "00000000-0000-4000-8000-%012u", ++uuids);
+ return std::string(id);
+ };
+ config.unix_time = [] { return std::int64_t{1760000000}; };
+ config.session_data_root = fixture.root / "data";
+ config.launch_title = [](const std::string&, const std::vector<std::string>&) { return TitleResult{true, 0, "launch"}; };
+ GameSettingsRecord saved;
+ config.settings_record = [&saved](std::uint32_t) -> std::optional<GameSettingsRecord> { return saved; };
+ std::vector<std::string> lines;
+ std::mutex lines_mutex;
+ config.log = [&](const std::string& line) { std::lock_guard<std::mutex> lock(lines_mutex); lines.push_back(line); };
+ const auto logged = [&](const std::string& prefix) {
+ std::lock_guard<std::mutex> lock(lines_mutex);
+ return std::any_of(lines.begin(), lines.end(), [&](const std::string& line) { return line.find(prefix) != std::string::npos; });
+ };
+ const auto game = fixture.root / "data/homebrew/FAKE77031/games/220";
+ Write(game / "hl2.exe", "existing-game", 0644);
+ CHECK(chmod(game.c_str(), 0777) == 0);
+ const auto metadata = fixture.root / "data/playden/games/steam-220/library/profiles/.playden-publication";
+ const auto installs = fixture.root / "data/runtime-state/installs.json";
+ {
+ RuntimeHost host(config);
+ CHECK(host.Start());
+ CHECK(WaitFor(host, Started).kit_available);
+ host.Prepare(Hl2());
+ const auto done = WaitFor(host, [](const RuntimeSnapshot& s) {
+ return !s.preparing_app && (s.refusals.count(220) || (!s.installs.empty() && s.installs[0].state == PreparationState::kReady));
+ }, 60);
+ CHECK(!done.refusals.count(220) && done.installs[0].state == PreparationState::kReady);
+ host.Shutdown();
+ }
+ CHECK(Read(metadata).find("schema=2\n") != std::string::npos);
+ CHECK(Read(installs).find("\"journal\":{") == std::string::npos);
+ const auto published = Read(metadata);
+ const auto records = Read(installs);
+ fs::remove_all(game);
+ kit.capabilities = {"dxvk", "game-root-unowned", "offline_bottle", "per_game_title", kKitDxvkConfig, "wow64_i386"};
+ RuntimeHost host(config);
+ CHECK(host.Start());
+ WaitFor(host, Started);
+ CHECK(logged("unowned upgrade skipped: game folder missing ("));
+ CHECK(logged("startup unowned app=220 deferred: "));
+ CHECK(!logged("settings update request"));
+ CHECK(Read(installs).find("\"journal\":{") == std::string::npos && Read(installs) == records);
+ CHECK(Read(metadata) == published);
+ host.Play(220);
+ const auto done = WaitFor(host, [](const RuntimeSnapshot& s) { return s.handoff_ready || s.play_refusals.count(220); }, 30);
+ CHECK(done.play_refusals.count(220) && done.play_refusals.at(220).find("installation volume is unavailable") != std::string::npos);
+ CHECK(!done.handoff_ready);
+ CHECK(!logged("settings update request"));
+ CHECK(Read(installs).find("\"journal\":{") == std::string::npos);
+ CHECK(Read(metadata) == published);
+ host.Shutdown();
+}
+
+// A moved Ready record whose folder is gone (the game was installed again elsewhere) can't be
+// republished: it keeps its mark (Uninstall or Recreate bottle clear it), and the move still finishes.
+void MovedGameMissingAtNewRootLetsTheMoveFinish() {
Fixture fixture;
GamesMove move;
const auto kit = SyntheticKit(fixture.root / "kit");
@@ -2997,8 +3075,9 @@ void MovedGameMissingAtNewRootKeepsTheMove() {
RuntimeHost host(config);
CHECK(host.Start());
WaitFor(host, Started);
- CHECK(move.Logged("startup moved app=220 failed:") && move.Done() == 0);
- CHECK(Read(fixture.root / "data/runtime-state/installs.json").find("moved_from") != std::string::npos);
+ CHECK(move.Logged("startup moved app=220 failed:") && move.Logged("layout move done") && move.Done() == 1);
+ CHECK(Read(fixture.root / "data/runtime-state/installs.json").find(R"("moved_from":"/data/homebrew/FAKE77031/games/220")") !=
+ std::string::npos);
CHECK(Read(fixture.root / "data/homebrew/FAKE78001/game-launch.json").find(kOldGames) != std::string::npos);
host.Shutdown();
}
@@ -3253,6 +3332,275 @@ void KitWithoutSharedProfileKeepsBottlePrivate() {
host.Shutdown();
}
+// A game published owned (schema 2) that then had settings updates committed under the same
+// kit (revision bumps, with registry edits that leave a registry backup and archived
+// operations in its control folder). A capable kit's startup unowned upgrade republishes it at
+// the same revision, after those committed operations (scenario 0).
+// When the control folder's last operation can't be read nor set aside (1: a link in its place),
+// the upgrade's capture is refused with the loader's reason, its request is dropped at once and
+// the game keeps playing under its owned publication: no recovery is needed. A last operation
+// that is gone (2) is not needed: the receipt and the publication prove the previous state.
+// A capture cut off while its request was armed (the lock held, as a game running from Home
+// holds it) leaves that request on the record (what an earlier build left on a console).
+// The next start drops it and tries the upgrade again (3; with the unreadable operation, 6: the
+// upgrade is deferred again and the game plays owned); Update resumes it (5), or, with the
+// unreadable operation, drops it and goes on as for any Ready game (4).
+// A last operation that no longer loads (7: another build's codec, trailing bytes; 9: its registry
+// backup lost its private mode) is set aside under its own name once the committed receipt and the
+// published metadata prove the previous publication, and the upgrade goes through; with a receipt
+// that doesn't (8), it stays, the upgrade is deferred and its request kept for Resume.
+void UnownedUpgradeAfterCommittedSettingsUpdates(int scenario) {
+ Fixture fixture;
+ auto config = fixture.Config();
+ config.host_namespace_prefix = fixture.root;
+ config.package_paths.console_data_root = "/data";
+ config.package_paths.host_data_root = fixture.root / "data";
+ config.package_operations.hash_file = HashArtifactFile;
+ config.package_operations.hash_bytes = HashArtifactBytes;
+ config.package_operations.free_space_unverifiable = true;
+ config.package_operations.validate_bottle = [](const fs::path& bottle) {
+ return fs::is_regular_file(bottle / "system.reg") && fs::is_regular_file(bottle / "user.reg");
+ };
+ auto kit = SyntheticKit(fixture.root / "kit");
+ kit.capabilities = {"dxvk", "offline_bottle", "per_game_title", kKitDxvkConfig, "wow64_i386"};
+ config.admit_kit = [&kit](std::string*) { return std::optional<RuntimeKit>(kit); };
+ unsigned uuids = 0;
+ config.uuid = [&uuids]() -> std::optional<std::string> {
+ char id[37]; std::snprintf(id, sizeof(id), "00000000-0000-4000-8000-%012u", ++uuids);
+ return std::string(id);
+ };
+ config.unix_time = [] { return std::int64_t{1760000000}; };
+ config.session_data_root = fixture.root / "data";
+ config.launch_title = [](const std::string&, const std::vector<std::string>&) { return TitleResult{true, 0, "launch"}; };
+ GameSettingsRecord saved;
+ config.settings_record = [&saved](std::uint32_t) -> std::optional<GameSettingsRecord> { return saved; };
+ std::vector<std::string> lines;
+ std::mutex lines_mutex;
+ config.log = [&](const std::string& line) { std::lock_guard<std::mutex> lock(lines_mutex); lines.push_back(line); };
+ const auto logged = [&](const std::string& text) {
+ std::lock_guard<std::mutex> lock(lines_mutex);
+ return std::any_of(lines.begin(), lines.end(), [&](const std::string& line) { return line.find(text) != std::string::npos; });
+ };
+ const auto game = fixture.root / "data/homebrew/FAKE77031/games/220";
+ Write(game / "hl2.exe", "existing-game", 0644);
+ const auto metadata = fixture.root / "data/playden/games/steam-220/library/profiles/.playden-publication";
+ const auto control = fixture.root / "data/playden/games/steam-220/.playden-control";
+ const auto installs = fixture.root / "data/runtime-state/installs.json";
+ const auto requests = fixture.root / "data/runtime-state/requests";
+ const auto play = [&](RuntimeHost& host) {
+ host.Play(220);
+ const auto done = WaitFor(host, [](const RuntimeSnapshot& s) { return s.handoff_ready || s.play_refusals.count(220); }, 30);
+ if (done.play_refusals.count(220)) std::fprintf(stderr, "Play refused: %s\n", done.play_refusals.at(220).c_str());
+ CHECK(done.handoff_ready && host.Handoff());
+ };
+ {
+ RuntimeHost host(config);
+ CHECK(host.Start());
+ CHECK(WaitFor(host, Started).kit_available);
+ host.Prepare(Hl2());
+ const auto done = WaitFor(host, [](const RuntimeSnapshot& s) {
+ return !s.preparing_app && (s.refusals.count(220) || (!s.installs.empty() && s.installs[0].state == PreparationState::kReady));
+ }, 60);
+ if (done.refusals.count(220)) std::fprintf(stderr, "Prepare refused: %s\n", done.refusals.at(220).c_str());
+ CHECK(!done.refusals.count(220) && done.installs[0].state == PreparationState::kReady);
+ const auto maintain = [&host](RuntimeMaintenance action) {
+ const auto before = host.Snapshot().maintenance_handled;
+ host.Maintain(220, action);
+ return WaitFor(host, [before](const RuntimeSnapshot& s) { return s.maintenance_handled > before; }, 60).maintenance.at(220);
+ };
+ // Several committed updates: a registry edit (Windows version) and a DXVK setting.
+ saved.revision = 2; saved.overrides = {{"windows_version", "win7"}};
+ auto result = maintain(RuntimeMaintenance::kApplySettings);
+ if (!result.ok) std::fprintf(stderr, "update 2: %s\n", result.message.c_str());
+ CHECK(result.ok && result.message == "Settings applied.");
+ saved.revision = 3; saved.overrides = {{"windows_version", "winxp"}, {"frame_limit", "30"}};
+ result = maintain(RuntimeMaintenance::kApplySettings);
+ if (!result.ok) std::fprintf(stderr, "update 3: %s\n", result.message.c_str());
+ CHECK(result.ok && result.message == "Settings applied.");
+ saved.revision = 4; saved.overrides = {{"windows_version", "winxp"}, {"frame_limit", "60"}};
+ result = maintain(RuntimeMaintenance::kApplySettings);
+ if (!result.ok) std::fprintf(stderr, "update 4: %s\n", result.message.c_str());
+ CHECK(result.ok && result.message == "Settings applied.");
+ CHECK(host.Snapshot().installs[0].settings_revision == 4);
+ host.Shutdown();
+ }
+ const auto owned = Read(metadata);
+ CHECK(owned.find("schema=2\n") != std::string::npos);
+ CHECK(Read(installs).find("\"journal\":{") == std::string::npos);
+ const auto backup = control / "registry-backup-00000000-0000-4000-8000-000000000004.v1";
+ CHECK(fs::is_regular_file(control / "settings-operation.v1") && fs::is_regular_file(backup));
+ CHECK(fs::is_regular_file(control / "settings-operation-00000000-0000-4000-8000-000000000003.v1"));
+ const bool unreadable = scenario == 1 || scenario == 4 || scenario == 6;
+ const auto operation = Read(control / "settings-operation.v1");
+ if (unreadable) {
+ fs::rename(control / "settings-operation.v1", control / "settings-operation.saved.v1");
+ fs::create_symlink("settings-operation.saved.v1", control / "settings-operation.v1");
+ }
+ if (scenario == 2) fs::remove(control / "settings-operation.v1");
+ if (scenario == 9) CHECK(chmod(backup.c_str(), 0644) == 0);
+ const auto aside = control / "settings-operation.unreadable-1760000000.v1";
+ if (scenario == 7 || scenario == 8) Write(control / "settings-operation.v1", operation + "trailing", 0600);
+ const auto kept_unreadable = [&] {
+ const bool kept = logged("Existing frozen operation is corrupt or unavailable: Operation journal could not be inspected") &&
+ logged("(not set aside: ") && !logged("settings operation set aside") && !fs::exists(aside) &&
+ fs::is_symlink(control / "settings-operation.v1");
+ if (!kept) {
+ std::lock_guard<std::mutex> guard(lines_mutex);
+ for (const auto& line : lines) if (line.find("220") != std::string::npos) std::fprintf(stderr, "log: %s\n", line.c_str());
+ std::fprintf(stderr, "scenario %d: aside=%d symlink=%d\n", scenario, int(fs::exists(aside)), int(fs::is_symlink(control / "settings-operation.v1")));
+ }
+ return kept;
+ };
+ const auto receipt = Read(control / "publication-state.v1");
+ if (scenario == 8) Write(control / "publication-state.v1", "not a receipt", 0600);
+ kit.capabilities = {"dxvk", "game-root-unowned", "offline_bottle", "per_game_title", kKitDxvkConfig, "wow64_i386"};
+ const auto request = requests / "settings-request-00000000-0000-4000-8000-000000000005.v1";
+ const auto journaled = [&] { return Read(installs).find("\"journal\":{") != std::string::npos; };
+ const auto unowned_published = [&] {
+ const auto published = Read(metadata);
+ return published.find("schema=3\n") != std::string::npos && published.find("game_root.unowned=1\n") != std::string::npos;
+ };
+ if (scenario >= 3 && scenario <= 6) {
+ // The capture finds the lock held: its request stays armed on the record, nothing changed.
+ const int lock = open((control / "publication.lock").c_str(), O_RDONLY);
+ CHECK(lock >= 0 && flock(lock, LOCK_SH) == 0);
+ RuntimeHost host(config);
+ CHECK(host.Start());
+ const auto started = WaitFor(host, Started);
+ CHECK(logged("startup unowned app=220 deferred: "));
+ CHECK(logged("unowned upgrade request 00000000-0000-4000-8000-000000000005 kept: "));
+ CHECK(started.installs[0].recovery_pending);
+ CHECK(journaled() && Read(installs).find("\"step\":\"capture-update\"") != std::string::npos);
+ CHECK(fs::is_regular_file(request) && Read(metadata) == owned);
+ if (scenario == 3 || scenario == 6) {
+ host.Shutdown();
+ CHECK(close(lock) == 0);
+ { std::lock_guard<std::mutex> guard(lines_mutex); lines.clear(); }
+ RuntimeHost restarted(config);
+ CHECK(restarted.Start());
+ WaitFor(restarted, Started);
+ CHECK(logged("unowned upgrade request 00000000-0000-4000-8000-000000000005 dropped: left by an earlier start"));
+ CHECK(!fs::exists(request));
+ if (scenario == 6) {
+ // The upgrade tried again is deferred again, with its reason, and its request dropped.
+ CHECK(kept_unreadable());
+ CHECK(logged("unowned upgrade request 00000000-0000-4000-8000-000000000006 dropped: "));
+ CHECK(logged("startup unowned app=220 deferred: "));
+ CHECK(!journaled() && Read(metadata) == owned);
+ CHECK(restarted.Snapshot().leftover_requests == 4);
+ } else {
+ CHECK(logged("startup unowned app=220 republished"));
+ CHECK(!journaled() && unowned_published());
+ }
+ CHECK(restarted.Snapshot().installs[0].settings_revision == 4 && !restarted.Snapshot().installs[0].recovery_pending);
+ play(restarted);
+ CHECK(!journaled() && (scenario == 6 ? Read(metadata) == owned : unowned_published()));
+ restarted.Shutdown();
+ return;
+ }
+ CHECK(close(lock) == 0);
+ // Update (Resume on the game page) takes the request up.
+ const auto before = host.Snapshot().prepares_handled;
+ host.Prepare(Hl2());
+ const auto updated = WaitFor(host, [before](const RuntimeSnapshot& s) { return s.prepares_handled > before && !s.preparing_app; }, 60);
+ if (updated.refusals.count(220)) std::fprintf(stderr, "Update: %s\n", updated.refusals.at(220).c_str());
+ if (scenario == 5) {
+ // Resumed: the saved request completes as unowned.
+ CHECK(!updated.refusals.count(220));
+ CHECK(logged("publication resume journal=settings-request/capture-update state=0"));
+ CHECK(unowned_published());
+ } else {
+ // Its capture refused again, the request is dropped and the update goes on: the game is as
+ // before the upgrade existed.
+ CHECK(kept_unreadable());
+ CHECK(logged("unowned upgrade request 00000000-0000-4000-8000-000000000005 dropped: "));
+ CHECK(updated.refusals.count(220) && updated.refusals.at(220) == "This game is already prepared.");
+ CHECK(Read(metadata) == owned && !fs::exists(request));
+ }
+ CHECK(!journaled() && !updated.installs[0].recovery_pending && updated.installs[0].settings_revision == 4);
+ play(host);
+ host.Shutdown();
+ return;
+ }
+ RuntimeHost host(config);
+ CHECK(host.Start());
+ WaitFor(host, Started);
+ if (scenario == 8) {
+ CHECK(logged("Existing frozen operation is corrupt or unavailable: Operation is truncated, malformed, altered or has trailing bytes. (kept: "));
+ CHECK(!logged("settings operation set aside"));
+ // Without a receipt that proves the committed publication nothing is touched, not even the
+ // request: the title can't pass its start check either way, and Resume keeps the evidence.
+ CHECK(logged("unowned upgrade request 00000000-0000-4000-8000-000000000005 kept: ") && logged("code=publication-discard-receipt"));
+ CHECK(logged("startup unowned app=220 deferred: "));
+ CHECK(journaled() && fs::exists(request) && Read(metadata) == owned);
+ CHECK(Read(control / "settings-operation.v1") == operation + "trailing" && !fs::exists(aside));
+ CHECK(host.Snapshot().installs[0].recovery_pending);
+ host.Shutdown();
+ return;
+ }
+ if (scenario == 7 || scenario == 9) {
+ CHECK(logged(std::string("settings operation set aside install=steam-220 as settings-operation.unreadable-1760000000.v1: ") +
+ (scenario == 7 ? "Operation is truncated" : "Referenced registry backup is not valid")));
+ CHECK(Read(aside) == (scenario == 7 ? operation + "trailing" : operation));
+ CHECK(fs::is_regular_file(control / "settings-operation.v1") && Read(control / "settings-operation.v1") != Read(aside));
+ CHECK(Read(control / "publication-state.v1") != receipt);
+ }
+ if (scenario == 1) {
+ CHECK(kept_unreadable());
+ CHECK(logged("unowned upgrade request 00000000-0000-4000-8000-000000000005 dropped: "));
+ CHECK(logged("startup unowned app=220 deferred: "));
+ CHECK(!journaled() && !fs::exists(request) && Read(metadata) == owned);
+ // The preparation's and the committed updates' requests are the usual leftovers; the dropped
+ // one is gone.
+ CHECK(host.Snapshot().leftover_requests == 4 && !host.Snapshot().installs[0].recovery_pending);
+ // Play tries the upgrade again, drops its request again, and starts the game as before.
+ play(host);
+ CHECK(logged("unowned upgrade request 00000000-0000-4000-8000-000000000006 dropped: "));
+ CHECK(!journaled() && Read(metadata) == owned);
+ host.Shutdown();
+ return;
+ }
+ if (!logged("startup unowned app=220 republished")) {
+ std::lock_guard<std::mutex> guard(lines_mutex);
+ for (const auto& line : lines) if (line.find("app=220") != std::string::npos) std::fprintf(stderr, "log: %s\n", line.c_str());
+ }
+ CHECK(logged("startup unowned app=220 republished"));
+ CHECK(!journaled() && unowned_published());
+ CHECK(host.Snapshot().installs[0].settings_revision == 4 && !host.Snapshot().installs[0].recovery_pending);
+ play(host);
+ host.Shutdown();
+}
+
+// A moved game whose last operation no longer decodes (written by another build): the move's
+// republish sets it aside, since the committed receipt and the published metadata prove the
+// previous publication, and names the new folder.
+void MovedGameWithUnreadableOperationRepublishes() {
+ Fixture fixture;
+ GamesMove move;
+ const auto kit = SyntheticKit(fixture.root / "kit");
+ unsigned uuids = 0;
+ const auto config = MoveConfig(fixture, kit, &uuids, move);
+ PrepareThenMoveGames(fixture, config, move);
+ const auto control = fixture.root / "data/playden/games/steam-220/.playden-control";
+ const auto operation = Read(control / "settings-operation.v1");
+ CHECK(!operation.empty());
+ Write(control / "settings-operation.v1", operation + "trailing", 0600);
+ RuntimeHost host(config);
+ CHECK(host.Start());
+ const auto started = WaitFor(host, Started);
+ CHECK(started.installs.size() == 1 && started.installs[0].state == PreparationState::kReady);
+ CHECK(move.Logged("settings operation set aside install=steam-220 as settings-operation.unreadable-1760000000.v1: Operation is truncated"));
+ CHECK(move.Logged("startup moved app=220 republished") && move.Done() == 1);
+ CHECK(Read(control / "settings-operation.unreadable-1760000000.v1") == operation + "trailing");
+ CHECK(fs::is_regular_file(control / "settings-operation.v1") && Read(control / "settings-operation.v1") != operation + "trailing");
+ CheckRepublishedAtNewRoot(fixture);
+ host.Play(220);
+ const auto played = WaitFor(host, [](const RuntimeSnapshot& s) { return s.handoff_ready || s.play_refusals.count(220); }, 30);
+ if (played.play_refusals.count(220)) std::fprintf(stderr, "Play refused: %s\n", played.play_refusals.at(220).c_str());
+ CHECK(played.handoff_ready);
+ host.Shutdown();
+}
+
int main(int argc, char** argv) {
CHECK(argc == 2);
g_runtime_dir = argv[1];
@@ -3299,7 +3647,10 @@ int main(int argc, char** argv) {
PlayBeforeRepublishRepublishesFirst();
MigrationSkipsRecordsOutsideOldPrefix();
RestartDuringRepublishResumes();
- MovedGameMissingAtNewRootKeepsTheMove();
+ MovedGameMissingAtNewRootLetsTheMoveFinish();
+ UnownedUpgradeSkippedWhenFolderMissing();
+ for (int scenario = 0; scenario <= 9; ++scenario) UnownedUpgradeAfterCommittedSettingsUpdates(scenario);
+ MovedGameWithUnreadableOperationRepublishes();
std::puts("runtime host tests passed");
return 0;
}
diff --git a/tests/layout_migration_test.cpp b/tests/layout_migration_test.cpp
index 309a696..e215bd8 100644
--- a/tests/layout_migration_test.cpp
+++ b/tests/layout_migration_test.cpp
@@ -81,13 +81,14 @@ bool Moved(const LayoutPaths& paths) {
}
// A valid install record; `journal` adds a pending operation.
-void WriteInstalls(const LayoutPaths& paths, bool journal) {
+void WriteInstalls(const LayoutPaths& paths, bool journal, const std::string& install_path = {}) {
const std::string record =
"{\"schema_version\":1,\"install_id\":\"i220\",\"title_id\":\"FAKE78001\",\"app_id\":220,"
"\"data_root\":\"/data/playden/games/i220\",\"default_profile_id\":\"default\",\"runtime_bundle_id\":\"kit\","
"\"recipe_id\":\"generic\",\"recipe_version\":\"1\",\"settings_revision\":1,\"exit_policy\":\"exit-title\","
"\"launch_entry_id\":\"main\",\"launch_path\":\"game.exe\",\"launch_arguments\":\"\","
- "\"launch_working_directory\":\"\",\"install_path\":\"" + (paths.app_root / "games" / "220").string() + "\","
+ "\"launch_working_directory\":\"\",\"install_path\":\"" +
+ (install_path.empty() ? (paths.app_root / "games" / "220").string() : install_path) + "\","
"\"volume_id\":\"internal\",\"state\":\"preparing\",\"artifacts\":[],\"last_failure\":null,\"journal\":" +
std::string(journal ? "{\"operation_id\":\"op1\",\"operation\":\"prepare\",\"step\":\"bottle\"}" : "null") + "}";
const std::string text = "{\"schema_version\":1,\"reservations\":[{\"install_id\":\"i220\",\"title_id\":\"FAKE78001\"}],"
@@ -249,6 +250,22 @@ void PostponesGamesWhileLaunchPending() {
// A pending session (StorageLaunchSessionJournal's format) whose game the console says has
// ended no longer holds the move: that happens whenever Playden started the last game.
+// A game started or suspended from Home (no pending launch) also holds the move back while it runs.
+void RunningGameFromHomeHoldsTheMove() {
+ for (const bool running : {true, false}) {
+ auto f = Make(std::string("home-") + (running ? "running" : "stopped"));
+ WriteInstalls(f->paths, false);
+ std::vector<std::string> asked;
+ f->ops.title_running = [&asked, running](const std::string& title) {
+ asked.push_back(title);
+ return std::optional<bool>(running);
+ };
+ const auto result = MigrateLayout(f->paths, f->ops);
+ CHECK(result.games_moved == !running && Moved(f->paths) == !running);
+ CHECK(asked == std::vector<std::string>{"FAKE78001"});
+ }
+}
+
void PendingLaunchOfStoppedGameMoves() {
const auto hex = [](const std::string& text) {
std::string out;
@@ -288,6 +305,18 @@ void PendingLaunchOfStoppedGameMoves() {
}
void PostponesGamesWhileJournalPending() {
+ // A pending journal of a game on another drive doesn't hold the move back.
+ {
+ auto usb = Make("pending-usb");
+ WriteInstalls(usb->paths, true, "/mnt/usb0/playden/games/220");
+ CHECK(MigrateLayout(usb->paths, usb->ops).games_moved && Moved(usb->paths));
+ }
+ // Nor does one of a record whose folder is gone (the game was installed again elsewhere).
+ {
+ auto stale = Make("pending-stale");
+ WriteInstalls(stale->paths, true, (stale->paths.app_root / "games" / "999").string());
+ CHECK(MigrateLayout(stale->paths, stale->ops).games_moved && Moved(stale->paths));
+ }
auto f = Make("pending");
WriteInstalls(f->paths, true);
for (int start = 1; start <= kLayoutPostponeNoticeAfter; ++start) {
@@ -426,6 +455,7 @@ int main() {
FreshInstallMakesSharedGamesFolder();
PostponesGamesWhileLaunchPending();
PendingLaunchOfStoppedGameMoves();
+ RunningGameFromHomeHoldsTheMove();
MovesReadyGameWithCommittedPublication();
RefusesToMergeIntoNonEmptyTarget();
AbortsOnCrossDevice();
diff --git a/tests/runtime_settings_publication_test.cpp b/tests/runtime_settings_publication_test.cpp
index 510763c..8b560bf 100644
--- a/tests/runtime_settings_publication_test.cpp
+++ b/tests/runtime_settings_publication_test.cpp
@@ -7,6 +7,8 @@
#include <filesystem>
#include <fstream>
#include <unistd.h>
+#include <fcntl.h>
+#include <sys/file.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/resource.h>
@@ -963,15 +965,98 @@ int main() {
update.install = *ready; ++update.install.settings_revision;
update.plan.settings_revision = update.install.settings_revision;
update.plan.dxvk_config = "# Generated by Playden from this game's settings.\ndxgi.maxFrameRate = 30\n";
+ // A registry edit: its capture leaves a registry backup next to the intent.
+ update.plan.registry = {{"Software\\Wine\\AppDefaults\\probe.exe", "Version", "\"win7\""}};
CHECK(resumed.Request(update, owner_root).state == PackageActionState::kComplete);
auto update_arm = restarted_records.Find(ready->install_id);
CHECK(update_arm && update_arm->settings_revision == ready->settings_revision && update_arm->journal &&
update_arm->journal->operation_id == update.transaction_id && update_arm->journal->step == "capture-update");
CHECK(Read(t.paths.profile) == request.plan.profile_bytes && !fs::exists(t.DxvkPath()));
+ // Registry backups and prepared intents in the control folder, of any transaction.
+ const auto capture_files = [&] {
+ std::size_t count = 0;
+ std::error_code error;
+ for (const auto& entry : fs::directory_iterator(t.control, error)) {
+ const auto name = entry.path().filename().string();
+ count += name.rfind("registry-backup-", 0) == 0 || name.rfind("settings-intent-", 0) == 0;
+ }
+ return count;
+ };
+ const auto baseline = capture_files();
+ const auto first_backup = t.control / ("registry-backup-" + request.transaction_id + ".v1");
+ const bool first_backup_present = fs::exists(first_backup);
if (boundary) {
+ // The committed operation no longer decodes (another build's codec): with a pending receipt
+ // the capture fails closed and the journal stays; with the committed receipt, which binds the
+ // published metadata, it is set aside under its own name and the capture goes on without it.
+ const auto journal = t.control / "settings-operation.v1", receipt = t.control / "publication-state.v1";
+ const auto bytes = Read(journal), committed = Read(receipt);
+ std::ofstream(journal, std::ios::binary | std::ios::trunc) << bytes << "trailing";
+ std::ofstream(receipt, std::ios::binary | std::ios::trunc) << frozen.operation->pending_receipt_bytes;
+ auto refused = resumed.Prepare(update.install, update.plan, update.kit_id, update.transaction_id,
+ update.registry_unix_time, t.root);
+ CHECK(!refused.ok() && refused.message().find("(kept: ") != std::string::npos);
+ CHECK(Read(journal) == bytes + "trailing" && !fs::exists(t.control / "settings-operation.unreadable-1760000000.v1"));
+ std::ofstream(receipt, std::ios::binary | std::ios::trunc) << committed;
auto prepared = resumed.Prepare(update.install, update.plan, update.kit_id, update.transaction_id,
update.registry_unix_time, t.root);
+ if (!prepared.ok()) std::fprintf(stderr, "Prepare: %s\n", prepared.message().c_str());
CHECK(prepared.ok()); // Cold restart after prepared handoff, before publication.
+ CHECK(!fs::exists(journal) && Read(t.control / "settings-operation.unreadable-1760000000.v1") == bytes + "trailing");
+ CHECK(SetAsideSettingsPublicationOperation(t.control, 1760000000).message().find("No active journal") != std::string::npos);
+ }
+ // A Ready update's request that never reached its publication (the record still carries the
+ // request arm) can be dropped: the record returns to its committed publication, the saved
+ // request and its capture's backup and intent go; other transactions' files stay. Not while
+ // the lock is held (the game runs), nor for a journal other than the record's.
+ {
+ const auto update_backup = t.control / ("registry-backup-" + update.transaction_id + ".v1");
+ const auto update_intent = t.control / ("settings-intent-" + update.transaction_id + ".v1");
+ CHECK(fs::exists(update_backup) == (boundary != 0) && fs::exists(update_intent) == (boundary != 0));
+ CHECK(capture_files() == baseline + (boundary ? 2 : 0));
+ // Without a capture, a link under the intent's name is not followed nor removed.
+ const auto outside = t.root / "outside-intent";
+ if (!boundary) {
+ std::ofstream(outside) << "outside";
+ fs::create_symlink(outside, update_intent);
+ }
+ const int held = open((t.control / "publication.lock").c_str(), O_RDONLY);
+ CHECK(held >= 0 && flock(held, LOCK_SH) == 0);
+ CHECK(resumed.DiscardRequested(*update_arm, owner_root, t.root).code == "publication-busy");
+ CHECK(close(held) == 0);
+ auto other = *update_arm; other.journal->operation_id = request.transaction_id;
+ CHECK(resumed.DiscardRequested(other, owner_root, t.root).code == "publication-discard-owner");
+ auto arm = restarted_records.Find(ready->install_id);
+ CHECK(arm && arm->journal && arm->journal->step == "capture-update");
+ const auto dropped = resumed.DiscardRequested(*update_arm, owner_root, t.root);
+ if (dropped.state != PackageActionState::kComplete) std::fprintf(stderr, "Discard: %s %s\n", dropped.code.c_str(), dropped.message.c_str());
+ CHECK(dropped.state == PackageActionState::kComplete && dropped.message.empty());
+ auto back = restarted_records.Find(ready->install_id);
+ CHECK(back && back->state == PreparationState::kReady && !back->journal && !back->last_failure &&
+ back->settings_revision == ready->settings_revision);
+ CHECK(!fs::exists(owner_root / ("settings-request-" + update.transaction_id + ".v1")));
+ CHECK(!fs::exists(update_backup));
+ if (boundary) {
+ CHECK(!fs::exists(update_intent) && capture_files() == baseline);
+ } else {
+ CHECK(fs::is_symlink(update_intent) && Read(outside) == "outside");
+ fs::remove(update_intent);
+ }
+ CHECK(fs::exists(first_backup) == first_backup_present);
+ CHECK(Read(t.paths.profile) == request.plan.profile_bytes && !fs::exists(t.DxvkPath()));
+ CHECK(resumed.DiscardRequested(*update_arm, owner_root, t.root).code == "publication-discard-owner");
+ // The same update, requested again under a new transaction, goes through as before.
+ update.transaction_id = "33333333-3333-4333-8333-333333333333";
+ CHECK(resumed.Request(update, owner_root).state == PackageActionState::kComplete);
+ update_arm = restarted_records.Find(ready->install_id);
+ CHECK(update_arm && update_arm->journal && update_arm->journal->operation_id == update.transaction_id);
+ if (boundary) {
+ auto prepared = resumed.Prepare(update.install, update.plan, update.kit_id, update.transaction_id,
+ update.registry_unix_time, t.root);
+ CHECK(prepared.ok());
+ // A retry leaves only its own capture's files, not the dropped one's as well.
+ CHECK(capture_files() == baseline + 2);
+ }
}
RuntimeInstallRepository update_restart(storage, "installs.json", availability); CHECK(update_restart.Load().ok());
RepositoryInstallRecordStore update_records(update_restart); native.records = &update_records;
@@ -983,6 +1068,9 @@ int main() {
CHECK(updated && updated->state == PreparationState::kReady && !updated->journal &&
updated->settings_revision == update.plan.settings_revision && native.registrations == 1);
CHECK(Read(t.DxvkPath()) == update.plan.dxvk_config);
+ // The committed operation loads: it is never set aside.
+ CHECK(SetAsideSettingsPublicationOperation(t.control, 1760000001).message().find("never set aside") != std::string::npos);
+ CHECK(fs::exists(t.control / "settings-operation.v1") && !fs::exists(t.control / "settings-operation.unreadable-1760000001.v1"));
}
{
Test t; fs::remove_all(t.control);