Skip to content

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

C++

Move games under the runtime publication locks

Leonardo Lobato37b75d333a83
diff --git a/src/homebrew/ps5.cpp b/src/homebrew/ps5.cpp
index 470c3f4..643c2bb 100644
--- a/src/homebrew/ps5.cpp
+++ b/src/homebrew/ps5.cpp
@@ -210,7 +210,7 @@ int main() {
// Before the title's /data grant: a title whose credentials changed may fail to load system modules.
const int keyboard_module = sceSysmoduleLoadModule(kKeyboardModule);
const int system_keyboard_module = playden::ps5::SystemKeyboard::Preload();
- const auto native_access = playden::ps5::PrepareNativeStartup(PLAYDEN_PS5_TITLE_ID);
+ auto native_access = playden::ps5::PrepareNativeStartup(PLAYDEN_PS5_TITLE_ID);
hui::ps5::Display display;
if (display.width() <= 0 && !display.open(3840, 2160)) {
hui::sys::log("Playden Hui display failed"); hui::sys::park();
@@ -344,23 +344,6 @@ int main() {
playden::app::AppendLogLine(log_root, "install.log", line);
});
playden::LocalSessionRepository install_sessions(user_root);
- // A console-formatted M.2's root belongs to root: Playden's folder there is made as root.
- auto install_volumes = playden::steam::DiscoverInstallVolumes(
- playden::steam::ConsoleVolumeCandidates(paths.title_root, playden::ps5::EffectiveGamesRoot(paths)),
- [](const std::function<bool()>& work) { return playden::ps5::WithRoot(work); });
- for (const auto& volume : install_volumes)
- playden::app::AppendLogLine(log_root, "install.log", "volume id=" + volume.id + " root=" + volume.games_root +
- " writable=" + (volume.available ? "1" : "0"));
- playden::steam::InstallService installs(install_runner, install_sessions, std::move(install_volumes));
- // A games folder made over FTP is often root's and 0755: checked (and opened up) as a download starts.
- // Only the games folder itself: the primary volume's parent is /data, never chmodded.
- installs.SetFolderCheck([](const std::string& games_root) {
- const std::filesystem::path root(games_root);
- return playden::runtime::EnsureWritableFolders(
- {root},
- [](const std::function<bool()>& work) { return playden::ps5::WithRoot(work); },
- [](const std::string& line) { playden::app::AppendLogLine(log_root, "install.log", line); });
- });
playden::steam::CmClient cloud_cm(paths.trust_store, library_storage);
cloud_cm.SetOwner("cloud");
cloud_cm.SetSharedSession(steam_cm);
@@ -429,6 +412,8 @@ int main() {
config.boundary = "/data";
config.state_root = std::filesystem::path(paths.runtime_data_root) / "runtime-state";
config.homebrew_root = "/data/homebrew";
+ config.layout_paths = rt::LayoutPaths{paths.title_root, "/data/playden/user", "/data/playden/logs",
+ "/data/playden-games", "/data/playden/runtime-state", "/data"};
config.as_root = [](const std::function<bool()>& work) { return playden::ps5::WithRoot(work); };
config.writable_folders = {"/data/homebrew", "/data/playden", "/data/playden-games", "/data/playden/user",
"/data/playden/logs"};
@@ -542,6 +527,35 @@ int main() {
if (!runtime_host->Start())
playden::app::AppendLogLine(log_root, "runtime.log", "runtime worker could not start");
}
+ if (runtime_host && !runtime_host->WaitForStartup()) {
+ native_access.runtime_ready = false;
+ native_access.error = runtime_host->Snapshot().reason;
+ show_root_access_missing(display, native_access);
+ display.close();
+ hui::sys::quit();
+ return 0;
+ }
+ auto games_root = playden::ps5::EffectiveGamesRoot(paths);
+ if (const auto journal = playden::runtime::LoadLayoutJournal("/data/playden/runtime-state");
+ journal && (journal->step == "games-moved" || journal->step == "done"))
+ games_root = "/data/playden-games";
+ // A console-formatted M.2's root belongs to root: Playden's folder there is made as root.
+ auto install_volumes = playden::steam::DiscoverInstallVolumes(
+ playden::steam::ConsoleVolumeCandidates(paths.title_root, games_root),
+ [](const std::function<bool()>& work) { return playden::ps5::WithRoot(work); });
+ for (const auto& volume : install_volumes)
+ playden::app::AppendLogLine(log_root, "install.log", "volume id=" + volume.id + " root=" + volume.games_root +
+ " writable=" + (volume.available ? "1" : "0"));
+ playden::steam::InstallService installs(install_runner, install_sessions, std::move(install_volumes));
+ // A games folder made over FTP is often root's and 0755: checked (and opened up) as a download starts.
+ // Only the games folder itself: the primary volume's parent is /data, never chmodded.
+ installs.SetFolderCheck([](const std::string& games_root) {
+ const std::filesystem::path root(games_root);
+ return playden::runtime::EnsureWritableFolders(
+ {root},
+ [](const std::function<bool()>& work) { return playden::ps5::WithRoot(work); },
+ [](const std::string& line) { playden::app::AppendLogLine(log_root, "install.log", line); });
+ });
playden::homebrew::Controller services(simulation, auth, sessions,&library_service,&persistence,&app_details,&installs,&cloud,
runtime_host.get(), [](const std::string& line) {
playden::app::AppendLogLine(log_root, "auth.log", "sign-in " + line);
diff --git a/src/homebrew/runtime_host.cpp b/src/homebrew/runtime_host.cpp
index ec8683d..69874b2 100644
--- a/src/homebrew/runtime_host.cpp
+++ b/src/homebrew/runtime_host.cpp
@@ -16,6 +16,7 @@
#include "runtime/steam_stub.h"
#include "runtime/steamworks.h"
#include "runtime/writable_folders.h"
+#include "platform/managed_file_lock.h"
#include "steam/backend/cloud_mapping.h"
#include "steam/backend/json.h"
@@ -377,6 +378,12 @@ void RuntimeHost::Shutdown() {
}
}
+bool RuntimeHost::WaitForStartup() {
+ std::unique_lock<std::mutex> lock(mutex_);
+ published_.wait(lock, [this] { return stopping_ || snapshot_.status != RuntimeHostStatus::kStarting; });
+ return snapshot_.status == RuntimeHostStatus::kReady;
+}
+
RuntimeSnapshot RuntimeHost::Snapshot() const {
std::lock_guard<std::mutex> lock(mutex_);
return snapshot_;
@@ -1296,9 +1303,65 @@ std::string RuntimeHost::PublishSavedSettings(Composition& c, const rt::RuntimeI
return {};
}
-void RuntimeHost::MoveGameRecords(Composition& c) {
+bool RuntimeHost::MoveGames(Composition& c, std::string* error) {
+ auto move = config_.moved_games_root ? config_.moved_games_root() : std::nullopt;
+ auto journal = rt::LoadLayoutJournal(config_.state_root);
+ const bool rename_pending = config_.layout_paths && journal && journal->step == "games";
+ const auto console_path = [this](const std::filesystem::path& path) {
+ if (config_.host_namespace_prefix.empty()) return path.string();
+ return (std::filesystem::path("/") / path.lexically_relative(config_.host_namespace_prefix)).string();
+ };
+ if (rename_pending) move = std::make_pair(console_path(config_.layout_paths->app_root / "games"),
+ console_path(config_.layout_paths->games_root));
+ if (!move) return true;
+ // All leases precede every activity check and survive the rename AND record rewrite.
+ std::vector<platform::ManagedFileLock> leases;
+ const auto postpone = [&](const std::string& why) {
+ Log("layout games postponed: " + why);
+ if (rename_pending && std::filesystem::exists(config_.layout_paths->app_root / "games")) return true;
+ *error = "The games move could not finish: " + why;
+ return false;
+ };
+ for (const auto& record : c.repository.Snapshot()) {
+ if (!rt::RebaseInstallPath(record.install_path, move->first, move->second)) continue;
+ const auto rebased = rt::RebaseInstallPath(record.install_path, move->first, move->second);
+ // Missing game folders have nothing Home can be using at either location.
+ if (!std::filesystem::is_directory(HostPath(record.install_path)) &&
+ !std::filesystem::is_directory(HostPath(*rebased))) continue;
+ const auto control_path = HostPath(record.data_root) / ".playden-control";
+ 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 postpone("the publication lock for " + record.title_id + " is unavailable or held");
+ leases.push_back(std::move(*lease));
+ }
+ if (rename_pending) {
+ auto ops = config_.layout_operations;
+ ops.defer_games = false;
+ ops.as_root = config_.as_root;
+ ops.log = [this](const std::string& line) { Log(line); };
+ ops.title_running = [&c](const std::string& title) -> std::optional<bool> {
+ const auto activity = c.coordinator->Activity(title);
+ if (activity == rt::NativeActivity::kUnknown) return std::nullopt;
+ return activity != rt::NativeActivity::kStopped;
+ };
+ const auto moved = rt::MigrateLayout(*config_.layout_paths, ops);
+ if (!moved.runtime_ready) { *error = moved.notice; return false; }
+ if (!moved.games_moved) return true;
+ }
+ if (!MoveGameRecords(c)) { *error = "The moved games' records could not be saved."; return false; }
+ return true;
+}
+
+bool RuntimeHost::MoveGameRecords(Composition& c) {
c.games_move = config_.moved_games_root ? config_.moved_games_root() : std::nullopt;
- if (!c.games_move) return;
+ if (!c.games_move) return true;
+ if (!config_.host_namespace_prefix.empty()) {
+ for (auto* path : {&c.games_move->first, &c.games_move->second}) {
+ const auto relative = std::filesystem::path(*path).lexically_relative(config_.host_namespace_prefix);
+ if (!relative.empty() && *relative.begin() != "..") *path = (std::filesystem::path("/") / relative).string();
+ }
+ }
const auto& [from, to] = *c.games_move;
// Records on other drives (USB, M.2) stay; the ones under the old root name the new one and
// keep the old one until a publication names the new folder.
@@ -1315,10 +1378,11 @@ void RuntimeHost::MoveGameRecords(Composition& c) {
Log("layout move records=" + std::to_string(moved.size()) + " from=" + from + " to=" + to + " " +
(written.ok() ? std::string("rewritten") : "failed: " + written.message()));
// Nothing is marked done while the records still name the old root.
- if (!written.ok()) { c.games_move.reset(); return; }
+ if (!written.ok()) { c.games_move.reset(); return false; }
}
const auto indexes = RebaseCloudIndexes(HostPath(to) / ".playden-saves", from, to);
if (indexes) Log("layout move cloud indexes=" + std::to_string(indexes));
+ return true;
}
void RuntimeHost::FinishGamesMove(Composition& c) {
@@ -2848,15 +2912,15 @@ void RuntimeHost::Run() {
[this, &c](const rt::RuntimeInstall& record) { return DrivePublication(c, record); });
Log("startup loading records");
const auto loaded = c.repository.Load();
- if (!loaded.ok()) {
+ std::string move_error;
+ if (!loaded.ok() || !MoveGames(c, &move_error)) {
Log("runtime records unavailable: " + loaded.message());
- unavailable("Runtime install records are unavailable: " + loaded.message());
+ unavailable(move_error.empty() ? "Runtime install records are unavailable: " + loaded.message() : move_error);
composition.reset();
} else {
// Startup only reads durable state. Records with a journal wait for an
// explicit recovery action; nothing resumes, registers or rebuilds here.
Log("startup records loaded installs=" + std::to_string(c.repository.Snapshot().size()));
- MoveGameRecords(c);
LoadGeneratedRecipes(c);
Log("startup generated recipes loaded");
PublishInstalls(c);
diff --git a/src/homebrew/runtime_host.hpp b/src/homebrew/runtime_host.hpp
index b0d7e51..65534c6 100644
--- a/src/homebrew/runtime_host.hpp
+++ b/src/homebrew/runtime_host.hpp
@@ -13,6 +13,7 @@
#include <chrono>
#include <condition_variable>
+#include "runtime/layout_migration.h"
#include <cstdint>
#include <filesystem>
#include <functional>
@@ -126,6 +127,8 @@ struct RuntimeHostConfig {
// "games-moved"; nothing otherwise. finish_games_move: called once every moved Ready game is
// republished; false keeps the move pending for the next start. Empty: LoadLayoutJournal and
// MarkLayoutDone on state_root.
+ std::optional<runtime::LayoutPaths> layout_paths;
+ runtime::LayoutOps layout_operations;
std::function<std::optional<std::pair<std::string, std::string>>()> moved_games_root;
std::function<bool(std::string* error)> finish_games_move;
// SQLite and the native readers run on this worker. PS5 std::thread stacks are
@@ -295,6 +298,8 @@ class RuntimeHost {
bool Start();
void Shutdown();
RuntimeSnapshot Snapshot() const;
+ // Before any download service receives its games root.
+ bool WaitForStartup();
// The same state without a copy per call: shared and read-only, made again only after a change.
// The UI reads it many times a frame; Snapshot() copies every field each time.
std::shared_ptr<const RuntimeSnapshot> Shared() const;
@@ -373,7 +378,8 @@ class RuntimeHost {
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);
+ bool MoveGames(Composition& composition, std::string* error);
+ bool MoveGameRecords(Composition& composition);
void FinishGamesMove(Composition& composition);
// Empty when the game's Ready title is stopped with no launch pending, otherwise why not.
std::string MaintenanceRefusal(Composition& composition, const runtime::RuntimeInstall& record);
diff --git a/src/platform/ps5/native_startup.cpp b/src/platform/ps5/native_startup.cpp
index 42cac61..9061c3a 100644
--- a/src/platform/ps5/native_startup.cpp
+++ b/src/platform/ps5/native_startup.cpp
@@ -162,8 +162,8 @@ NativeAccessResult PrepareNativeStartup(const std::string& title_id) {
if (!result.runtime_ready && !context.grant_diagnostic.empty())
result.error += "; " + context.grant_diagnostic;
// The 0.6 layout: user data, logs and games leave the app folder once. Still
- // single-threaded here, so the short root raises (the games rename, renames out of
- // root-owned stub folders, creating /data/playden-games) affect no other thread.
+ // single-threaded here; only user data and logs move. The runtime worker moves
+ // games under publication leases before download services receive their volume paths.
std::vector<std::string> layout_lines;
if (result.runtime_ready && !result.paths.runtime_data_root.empty()) {
namespace fs = std::filesystem;
@@ -176,18 +176,9 @@ NativeAccessResult PrepareNativeStartup(const std::string& title_id) {
layout.state_root = data_root / "runtime-state";
layout.boundary = data_root.parent_path();
runtime::LayoutOps layout_ops;
+ layout_ops.defer_games = true;
layout_ops.as_root = [](const std::function<bool()>& work) { return WithRoot(work); };
layout_ops.log = [&layout_lines](const std::string& line) { layout_lines.push_back(line); };
- // Read-only kernel process list: the game of a launch session left pending.
- layout_ops.title_running = [&layout_lines](const std::string& title) -> std::optional<bool> {
- std::string reason;
- const auto activity = ReadTitleActivity(title, &reason);
- if (activity == runtime::NativeActivity::kUnknown) {
- layout_lines.push_back("title activity " + title + " unknown: " + reason);
- return std::nullopt;
- }
- return activity == runtime::NativeActivity::kActive;
- };
const auto moved = runtime::MigrateLayout(layout, layout_ops);
result.paths.user_root = moved.user_root.string();
result.paths.user_log_root = moved.log_root.string();
diff --git a/src/runtime/layout_migration.cpp b/src/runtime/layout_migration.cpp
index f5b9c10..4ccfb68 100644
--- a/src/runtime/layout_migration.cpp
+++ b/src/runtime/layout_migration.cpp
@@ -455,6 +455,7 @@ LayoutResult MigrateLayout(const LayoutPaths& paths, const LayoutOps& ops) {
if (journal.step != "games" && !save("games", old_games, paths.games_root))
return hold("the move record can't be written (" + error + ")");
+ if (ops.defer_games) return finish();
const auto moved_games = [&] {
if (!ensure_games_root() || !save("games-moved", old_games, paths.games_root)) {
uncertain = true;
diff --git a/src/runtime/layout_migration.h b/src/runtime/layout_migration.h
index 598fd2f..1002e8d 100644
--- a/src/runtime/layout_migration.h
+++ b/src/runtime/layout_migration.h
@@ -22,6 +22,7 @@ struct LayoutPaths {
};
struct LayoutOps {
+ bool defer_games = false; // startup leaves the games step to RuntimeHost under publication leases
// Directory durability barrier; empty uses open+fsync.
std::function<bool(const std::filesystem::path&)> sync;
// rename(2); returns the errno as an error_code. Empty: the real rename.
@@ -73,7 +74,8 @@ struct LayoutResult {
std::string notice; // one line for the user, when the move is held back
};
-// Single-threaded, before any service starts, after the root grant. Never copies,
+// User/log stages run before services, after the grant. With defer_games, RuntimeHost
+// resumes the games stage under publication leases. Never copies,
// never merges into a non-empty target, never replaces an existing entry.
LayoutResult MigrateLayout(const LayoutPaths& paths, const LayoutOps& ops);
diff --git a/tests/homebrew_runtime_host_test.cpp b/tests/homebrew_runtime_host_test.cpp
index 125856c..a3eef99 100644
--- a/tests/homebrew_runtime_host_test.cpp
+++ b/tests/homebrew_runtime_host_test.cpp
@@ -2625,6 +2625,72 @@ void PrepareThenMoveGames(Fixture& fixture, const RuntimeHostConfig& config, Gam
move.journal = std::make_pair(std::string(kOldGames), std::string(kNewGames));
}
+// The worker owns the actual rename, with every title excluded until records name the new root.
+void WorkerMovesGamesUnderPublicationLease() {
+ Fixture fixture;
+ auto kit = SyntheticKit(fixture.root / "kit");
+ unsigned uuids = 0;
+ GamesMove move;
+ auto config = MoveConfig(fixture, kit, &uuids, move);
+ PrepareThenMoveGames(fixture, config, move);
+ const auto old = fixture.root / "data/homebrew/FAKE77031/games";
+ const auto target = fixture.root / "data/playden-games";
+ fs::rename(target, old);
+ config.layout_paths = LayoutPaths{old.parent_path(), fixture.root / "data/playden/user",
+ fixture.root / "data/playden/logs", target, config.state_root, fixture.root / "data"};
+ const std::string text = "{\"step\":\"games\",\"from\":\"" + old.string() + "\",\"to\":\"" + target.string() + "\"}";
+ CHECK(playden::Storage(config.state_root.string()).WriteDurable(kLayoutJournal, playden::Bytes(text.begin(), text.end())).ok());
+ const auto lock_path = fixture.root / "data/playden/games/steam-220/.playden-control/publication.lock";
+ const auto busy = [&] {
+ const int fd = ::open(lock_path.c_str(), O_RDONLY);
+ CHECK(fd >= 0);
+ const bool held = ::flock(fd, LOCK_SH | LOCK_NB) != 0;
+ ::close(fd);
+ return held;
+ };
+ unsigned rename_checks = 0, record_checks = 0;
+ config.layout_operations.rename = [&](const fs::path& from, const fs::path& to) -> std::error_code {
+ CHECK(from == old && to == target && busy());
+ ++rename_checks;
+ return ::rename(from.c_str(), to.c_str()) == 0 ? std::error_code{} : std::error_code{errno, std::generic_category()};
+ };
+ config.moved_games_root = [&]() -> std::optional<std::pair<std::string, std::string>> {
+ const auto journal = LoadLayoutJournal(config.state_root);
+ if (!journal || journal->step != "games-moved") return std::nullopt;
+ CHECK(busy()); // Called by MoveGameRecords before UpdateAll publishes the new paths.
+ ++record_checks;
+ return std::make_pair(std::string(kOldGames), std::string(kNewGames));
+ };
+ config.finish_games_move = {};
+ // A Home launch's reader lease prevents the rename even if the activity query says stopped.
+ const int reader = ::open(lock_path.c_str(), O_RDONLY);
+ CHECK(reader >= 0 && ::flock(reader, LOCK_SH | LOCK_NB) == 0);
+ {
+ RuntimeHost host(config);
+ CHECK(host.Start() && host.WaitForStartup());
+ CHECK(fs::exists(old) && !fs::exists(target) && rename_checks == 0 && record_checks == 0);
+ host.Shutdown();
+ }
+ ::close(reader);
+ // An active or suspended title also postpones after the writer lease is acquired.
+ fixture.activity->store(static_cast<int>(NativeActivity::kActive));
+ {
+ RuntimeHost host(config);
+ CHECK(host.Start() && host.WaitForStartup());
+ CHECK(fs::exists(old) && !fs::exists(target) && rename_checks == 0);
+ host.Shutdown();
+ }
+ fixture.activity->store(static_cast<int>(NativeActivity::kStopped));
+ {
+ RuntimeHost host(config);
+ CHECK(host.Start() && host.WaitForStartup());
+ CHECK(!fs::exists(old) && fs::exists(target) && rename_checks == 1 && record_checks == 1);
+ CHECK(!busy());
+ CHECK(host.Snapshot().installs.front().install_path == std::string(kNewGames) + "/220");
+ host.Shutdown();
+ }
+}
+
// What the moved game's published files and record name after the move finished.
void CheckRepublishedAtNewRoot(Fixture& fixture) {
const auto records = Read(fixture.root / "data/runtime-state/installs.json");
@@ -3604,6 +3670,7 @@ void MovedGameWithUnreadableOperationRepublishes() {
int main(int argc, char** argv) {
CHECK(argc == 2);
g_runtime_dir = argv[1];
+ WorkerMovesGamesUnderPublicationLease();
NoKitRefusesPreparationWithoutDurableEffects();
QueuedPreparationIsPublishedUntilTaken();
HoldsEffectiveUidWhileWorking();
diff --git a/tests/layout_migration_test.cpp b/tests/layout_migration_test.cpp
index 2a75a70..948a58d 100644
--- a/tests/layout_migration_test.cpp
+++ b/tests/layout_migration_test.cpp
@@ -440,6 +440,17 @@ void RevertKeepsConflictsAndJournal() {
const auto resumed = MigrateLayout(f->paths, f->ops);
CHECK(resumed.games_moved && resumed.notice.empty() && Moved(f->paths));
}
+void StartupDefersGamesWithoutActivityChecks() {
+ auto f = Make("deferred-games");
+ WriteInstalls(f->paths, false);
+ f->ops.defer_games = true;
+ f->ops.title_running = [](const std::string&) -> std::optional<bool> { CHECK(false); return {}; };
+ const auto result = MigrateLayout(f->paths, f->ops);
+ CHECK(result.runtime_ready && result.user_moved && result.logs_moved && !result.games_moved);
+ CHECK(fs::exists(f->paths.app_root / "games/220") && !fs::exists(f->paths.games_root));
+ CHECK(LoadLayoutJournal(f->paths.state_root)->step == "games");
+}
+
void PartialUserMoveBlocksServicesAndOnlyMovesForward() {
auto f = Make("partial-user");
const auto old = f->paths.app_root / "playden-data";
@@ -511,6 +522,7 @@ int main() {
CHECK(mkdtemp(pattern));
g_base = fs::canonical(pattern);
::umask(022);
+ StartupDefersGamesWithoutActivityChecks();
PartialUserMoveBlocksServicesAndOnlyMovesForward();
FailedDirectorySyncKeepsUserStepBlocked();
RenameParentsSyncBeforeJournalAdvances();
diff --git a/tests/test_native_startup_order.py b/tests/test_native_startup_order.py
index 9ca2841..d959810 100644
--- a/tests/test_native_startup_order.py
+++ b/tests/test_native_startup_order.py
@@ -13,3 +13,6 @@ startup = (root / "src/platform/ps5/native_startup.cpp").read_text()
assert "if (!moved.runtime_ready)" in startup
failure = startup.split("if (!moved.runtime_ready)", 1)[1].split("}", 1)[0]
assert "result.runtime_ready = false;" in failure
+
+assert "layout_ops.defer_games = true;" in startup
+assert main.index("runtime_host->WaitForStartup()") < main.index("InstallService installs")