Play your Steam library's Windows games on a jailbroken PS5.
C++
Start games right after an update or going back
Leonardo Lobato1b830f4dcdee
diff --git a/src/homebrew/ps5.cpp b/src/homebrew/ps5.cppindex 2aa209c..e3b2f27 100644--- a/src/homebrew/ps5.cpp+++ b/src/homebrew/ps5.cpp@@ -436,6 +436,7 @@ int main() {};// An any-title kit's helper serves the game titles listed here (root-owned).config.write_title_allow_list = playden::ps5::WriteTitleAllowList;+ config.hold_effective_uid = playden::ps5::HoldEffectiveUid;// Play: start a prepared title with its session argument. LncUtil is// resolved through the system service module (its static imports are null).config.launch_title = [](const std::string& title, const std::vector<std::string>& arguments) {diff --git a/src/homebrew/runtime_host.cpp b/src/homebrew/runtime_host.cppindex cf9dc6c..52d391d 100644--- a/src/homebrew/runtime_host.cpp+++ b/src/homebrew/runtime_host.cpp@@ -586,6 +586,13 @@ std::size_t RuntimeHost::LeftoverRequests(Composition& c, bool remove) {}bool RuntimeHost::Handoff() {+ {+ std::lock_guard<std::mutex> lock(launch_mutex_);+ if (!launch_ || launch_->Snapshot().state != rt::LaunchState::kReadyToHandoff) return false;+ }+ // The handoff writes the launch journal, whose ownership checks need the app user's effective+ // UID: root raised elsewhere waits until it is done. Taken before launch_mutex_, like the worker.+ const auto held = config_.hold_effective_uid ? config_.hold_effective_uid() : nullptr;rt::LaunchResult result;std::string install_id;{@@ -2199,6 +2206,8 @@ std::string RuntimeHost::DeleteKept(Composition& c, std::uint32_t app) {}void RuntimeHost::Run() {+ const auto hold = [this] { return config_.hold_effective_uid ? config_.hold_effective_uid() : nullptr; };+ auto startup_hold = hold();auto unavailable = [this](std::string reason) {Publish([&](RuntimeSnapshot& s) { s.status = RuntimeHostStatus::kUnavailable; s.reason = std::move(reason); });};@@ -2370,6 +2379,7 @@ void RuntimeHost::Run() {});}}+ startup_hold.reset();for (;;) {std::vector<RuntimePrepareRequest> requests;std::vector<std::uint32_t> plays;@@ -2389,7 +2399,8 @@ void RuntimeHost::Run() {const auto ready = [this] {return stopping_ || (!prepare_requests_.empty() && !snapshot_.handoff_ready) || !play_requests_.empty() ||cleanup_requested_ || measure_requested_ || !activity_requests_.empty() || title_names_changed_ ||- (!remove_requests_.empty() && !snapshot_.handoff_ready) || !kept_delete_requests_.empty() ||+ (!remove_requests_.empty() && !snapshot_.handoff_ready) ||+ (!kept_delete_requests_.empty() && !snapshot_.handoff_ready) ||!scan_requests_.empty() ||(!maintenance_requests_.empty() && !snapshot_.handoff_ready);};@@ -2400,7 +2411,7 @@ void RuntimeHost::Run() {plays.swap(play_requests_);// Removal changes install records that Handoff reads, like preparation.if (!snapshot_.handoff_ready) removals.swap(remove_requests_);- kept_deletes.swap(kept_delete_requests_);+ if (!snapshot_.handoff_ready) kept_deletes.swap(kept_delete_requests_);scans.swap(scan_requests_);// Maintenance changes the bottle and install record, like removal.if (!snapshot_.handoff_ready) maintenance.swap(maintenance_requests_);@@ -2413,6 +2424,7 @@ void RuntimeHost::Run() {names_changed = title_names_changed_;title_names_changed_ = false;}+ const auto batch_hold = hold();if (names_changed && composition) PublishInstalls(*composition);for (const auto& [app, install_path] : scans) {const auto kit = composition && composition->kit@@ -2462,6 +2474,19 @@ void RuntimeHost::Run() {});}}+ {+ // A handoff that became ready during this pass waits for this batch's hold on the effective+ // UID (and its launch check expires): long work goes back to the queue, so the batch ends now.+ std::lock_guard<std::mutex> lock(mutex_);+ if (snapshot_.handoff_ready) {+ remove_requests_.insert(remove_requests_.begin(), removals.begin(), removals.end());+ kept_delete_requests_.insert(kept_delete_requests_.begin(), kept_deletes.begin(), kept_deletes.end());+ maintenance_requests_.insert(maintenance_requests_.begin(), maintenance.begin(), maintenance.end());+ removals.clear();+ kept_deletes.clear();+ maintenance.clear();+ }+ }for (const auto& [app, delete_saves] : removals) {std::string refusal;if (!composition) {diff --git a/src/homebrew/runtime_host.hpp b/src/homebrew/runtime_host.hppindex 324d1b2..c36fed8 100644--- a/src/homebrew/runtime_host.hpp+++ b/src/homebrew/runtime_host.hpp@@ -85,6 +85,10 @@ struct RuntimeHostConfig {std::function<std::int64_t()> unix_time;// Diagnostic lines (no credentials): startup, each preparation step and refusals.std::function<void(const std::string&)> log;+ // Held around startup and each batch of work on the worker: while the token lives, nothing+ // else may raise root, which is process-wide and would fail the worker's ownership checks+ // (ps5::HoldEffectiveUid). Empty holds nothing.+ std::function<std::shared_ptr<void>()> hold_effective_uid;// Receives each prepared title's newest wrapper session log (bounded tail) at// startup. The wrapper writes it inside the private bottle tree, which only// the app user can read.diff --git a/src/homebrew/simulation.cpp b/src/homebrew/simulation.cppindex 2711c68..dd969d6 100644--- a/src/homebrew/simulation.cpp+++ b/src/homebrew/simulation.cpp@@ -839,7 +839,7 @@ void Simulation::UpdateRuntimeProblem(const std::string& raw) {[](const Notice& notice) { return notice.id == "runtime"; }),state_.notices.end());if (!words.empty())- state_.notices.push_back({"runtime", "Games can't start · see Settings › Runtime status", "", true, 0});+ state_.notices.push_back({"runtime", "Games can't start · see Runtime status in Settings", "", true, 0});rebuild_view();}diff --git a/src/platform/ps5/title_allow_list.cpp b/src/platform/ps5/title_allow_list.cppindex 6250fc0..cb22c5f 100644--- a/src/platform/ps5/title_allow_list.cpp+++ b/src/platform/ps5/title_allow_list.cpp@@ -93,6 +93,10 @@ bool WithRoot(const std::function<bool()>& work) {return ::seteuid(user) == 0 && ok;}+std::shared_ptr<void> HoldEffectiveUid() {+ return std::make_shared<std::unique_lock<std::recursive_mutex>>(RootLock());+}+bool WriteTitleAllowList(const std::string& contents, std::string* error) {const std::filesystem::path list = runtime::kTitleRuleAllowList;std::lock_guard<std::recursive_mutex> lock(RootLock());diff --git a/src/platform/ps5/title_allow_list.h b/src/platform/ps5/title_allow_list.hindex e6bf32b..0b3ac9c 100644--- a/src/platform/ps5/title_allow_list.h+++ b/src/platform/ps5/title_allow_list.h@@ -4,6 +4,7 @@// SPDX-License-Identifier: MIT#include <filesystem>#include <functional>+#include <memory>#include <string>#include <sys/types.h>@@ -30,6 +31,12 @@ bool WriteRootOwnedFile(const std::filesystem::path& directory, const std::strin// be restored.bool WithRoot(const std::function<bool()>& work);+// Keeps root from being raised (by WithRoot on any other thread) until the returned token is+// released. The runtime worker holds one around each batch of work: its ownership checks compare+// against the effective UID, so a root raise elsewhere in the middle of them refuses Playden's own+// folders. Work on the holding thread may still use WithRoot.+std::shared_ptr<void> HoldEffectiveUid();+// runtime::kTitleRuleAllowList on the console, as root.bool WriteTitleAllowList(const std::string& contents, std::string* error);} // namespace playden::ps5diff --git a/src/update/update_service.cpp b/src/update/update_service.cppindex 3298fb5..9dcfee1 100644--- a/src/update/update_service.cpp+++ b/src/update/update_service.cpp@@ -168,6 +168,33 @@ bool UpdateService::PrepareWorkRoot() {return ok;}+// A kit left by going back: its files are the app user's, removed by CleanUpLeftovers, but its folder+// sits in the root-owned kits folder. The empty folder goes as root here, at startup, before the+// runtime and the UI run (root is process-wide).+void UpdateService::RemoveEmptyReplacedKits() {+ for (const auto& name : ListFolder(config_.kits_root)) {+ if (name.compare(0, 10, ".replaced-") != 0) continue;+ const std::string path = config_.kits_root + "/" + name;+ if (!IsFolder(path) || !ListFolder(path).empty()) continue;+ if (rmdir(path.c_str()) != 0) config_.as_root([&] { return rmdir(path.c_str()) == 0; });+ if (Exists(path)) Log("could not remove " + path);+ }+}++// The app user's leftovers of a confirmed update, on the worker and without root: the stage, the+// downloads, the replaced entries and the files of a kit left by going back.+void UpdateService::CleanUpLeftovers() {+ std::vector<std::string> paths;+ for (const char* name : {"/stage", "/downloads", "/replaced"})+ if (Exists(config_.work_root + name)) paths.push_back(config_.work_root + name);+ for (const auto& name : ListFolder(config_.kits_root))+ if (name.compare(0, 10, ".replaced-") == 0) paths.push_back(config_.kits_root + "/" + name);+ if (paths.empty()) return;+ Run([paths] {+ for (const auto& path : paths) RemoveTree(path);+ });+}+bool UpdateService::RemoveOwnedTree(const std::string& path) {RemoveTree(path);if (Exists(path)) config_.as_root([&] { RemoveTree(path); return true; });@@ -302,8 +329,12 @@ std::string UpdateService::ReadyKit(const KitPart& kit) const {void UpdateService::Start() {FindPrevious();LoadCurrentNotes();+ RemoveEmptyReplacedKits();std::string text;- if (!ReadSmallFile(StatePath(), &text)) return;+ if (!ReadSmallFile(StatePath(), &text)) {+ CleanUpLeftovers(); // what a start closed before its cleanup finished left behind+ return;+ }const auto state = steam::json::Parse(text);if (!state || !state->is_object()) {Log("unreadable state, removed");@@ -374,26 +405,17 @@ void UpdateService::ConfirmApplied(const std::string& text) {// Only the app user's own leftovers go now. The previous app and kit stay to go back by hand;// older ones are root-owned and are removed at the next update's quit, when nothing else runs.if (!rolled_back) unlink((config_.work_root + "/declined-version").c_str());- Run([this] {- // Normally done at quit; again here in case the process died right after the swap.- config_.as_root([&] {- return RefreshRegisteredCopies(config_.installed_root + "/sce_sys", config_.appmeta_root,- config_.registered_app_root, [this](const std::string& line) { Log(line); });- });- RemoveTree(config_.work_root + "/stage");- RemoveTree(config_.work_root + "/downloads");- RemoveTree(config_.work_root + "/replaced");- // A kit left by going back: its files are the app user's; only its folder in the root-owned- // kits folder needs root, for one rmdir.- for (const auto& name : ListFolder(config_.kits_root)) {- if (name.compare(0, 10, ".replaced-") != 0) continue;- const std::string path = config_.kits_root + "/" + name;- RemoveTree(path);- if (Exists(path)) config_.as_root([&] { return rmdir(path.c_str()) == 0; });- if (Exists(path)) Log("could not remove " + path);- }- unlink(StatePath().c_str());+ // Normally done at quit; again here in case the process died right after the swap. Root is+ // process-wide, so it is raised now, while Start runs before the runtime and the UI: raised from+ // the worker it failed the runtime's ownership checks at the same time ("Games can't start").+ config_.as_root([&] {+ return RefreshRegisteredCopies(config_.installed_root + "/sce_sys", config_.appmeta_root,+ config_.registered_app_root, [this](const std::string& line) { Log(line); });});+ // Confirmed: a start closed before the cleanup below finishes does not confirm again; the next+ // start finds the leftovers without a state and cleans them up.+ unlink(StatePath().c_str());+ CleanUpLeftovers();return;}Log((rolled_back ? "going back to " : "update to ") + field("version") + " did not take effect; running " +diff --git a/src/update/update_service.h b/src/update/update_service.hindex fa0e8fd..8d738b4 100644--- a/src/update/update_service.h+++ b/src/update/update_service.h@@ -146,6 +146,8 @@ class UpdateService {std::string StagedFields() const;bool PrepareWorkRoot();bool RemoveOwnedTree(const std::string& path);+ void RemoveEmptyReplacedKits();+ void CleanUpLeftovers();UpdateConfig config_;std::shared_ptr<Shared> shared_;diff --git a/tests/homebrew_runtime_host_test.cpp b/tests/homebrew_runtime_host_test.cppindex 3ab0831..c01377c 100644--- a/tests/homebrew_runtime_host_test.cpp+++ b/tests/homebrew_runtime_host_test.cpp@@ -271,6 +271,34 @@ void NoKitRefusesPreparationWithoutDurableEffects() {CHECK(fs::is_empty(fixture.root / "data/homebrew"));}+// Root is process-wide on the console: while the worker starts up or works through a batch it holds+// the effective UID, so a root raise elsewhere (an update's cleanup) can't fail its ownership checks.+// Waiting for work, it holds nothing.+void HoldsEffectiveUidWhileWorking() {+ Fixture fixture;+ auto config = fixture.Config();+ std::atomic<int> holds{0};+ std::atomic<bool> admitted_while_held{false};+ config.hold_effective_uid = [&holds]() -> std::shared_ptr<void> {+ ++holds;+ return std::shared_ptr<void>(nullptr, [&holds](void*) { --holds; });+ };+ config.admit_kit = [&](std::string* reason) -> std::optional<RuntimeKit> {+ admitted_while_held = holds > 0;+ *reason = "No verified compatibility kit is installed.";+ return std::nullopt;+ };+ RuntimeHost host(std::move(config));+ CHECK(host.Start());+ CHECK(WaitFor(host, Started).status == RuntimeHostStatus::kReady);+ CHECK(admitted_while_held);+ host.Prepare(Hl2());+ CHECK(WaitFor(host, [](const RuntimeSnapshot& s) { return s.refusals.count(220) != 0; }).refusals.count(220));+ for (int i = 0; i < 200 && holds != 0; ++i) usleep(5000);+ CHECK(holds == 0); // idle: root may be raised again+ host.Shutdown();+}+// A preparation asked for before the runtime is ready is published as queued until the worker// takes it, so Play and Recreate bottle wait instead of reporting it lost.void QueuedPreparationIsPublishedUntilTaken() {@@ -1962,6 +1990,7 @@ int main(int argc, char** argv) {g_runtime_dir = argv[1];NoKitRefusesPreparationWithoutDurableEffects();QueuedPreparationIsPublishedUntilTaken();+ HoldsEffectiveUidWhileWorking();StartupReportsJournalsWithoutResuming();PublicStateRootIsUnavailable();PreparesExistingDownloadToReady();diff --git a/tests/self_update_service_test.cpp b/tests/self_update_service_test.cppindex 2de5c55..4330b64 100644--- a/tests/self_update_service_test.cpp+++ b/tests/self_update_service_test.cpp@@ -7,8 +7,12 @@#include <chrono>#include <cstdio>#include <cstdlib>+#include <functional>#include <map>+#include <mutex>#include <string>+#include <thread>+#include <vector>using namespace playden::update;using playden::steam::HttpRequest;@@ -213,14 +217,36 @@ int main() {CHECK(Read(kits + "/.previous-kitid-1000/manifest.json") == std::string(64, 'b'));// The new version starts: the update is confirmed and old files are cleaned up.- UpdateService next(fixture.Config({0, 3, 0}));+ std::vector<std::thread::id> raised;+ std::mutex raised_mutex;+ const auto record_root = [&](UpdateConfig config) {+ config.as_root = [&](const std::function<bool()>& work) {+ {+ std::lock_guard<std::mutex> lock(raised_mutex);+ raised.push_back(std::this_thread::get_id());+ }+ return work();+ };+ return config;+ };+ const auto root_only_on_this_thread = [&] {+ std::lock_guard<std::mutex> lock(raised_mutex);+ for (const auto& id : raised) CHECK(id == std::this_thread::get_id());+ };+ UpdateService next(record_root(fixture.Config({0, 3, 0})));next.Start();+ // Root is process-wide: it is raised only while Start runs, before the runtime and the UI start,+ // and the confirm is complete by then, so a start closed early does not confirm again.+ CHECK(!raised.empty());+ root_only_on_this_thread();+ CHECK(!Exists(fixture.root + "/playden/self-update/state.json"));next.Check(false); // queued behind the cleanup, not droppedCHECK(next.Snapshot().finished_message == "Playden was updated to 0.3.0." && !next.Snapshot().finished_failed);// What's new: the release notes travel with the update and stay for Settings.CHECK(next.Snapshot().whats_new && next.Snapshot().current_notes == "New things." &&next.Snapshot().current_notes_url == "https://github.com/o/r/releases/tag/v0.3.0");Wait(next);+ root_only_on_this_thread(); // the worker's cleanup never raised rootCHECK(Exists(fixture.root + "/playden/self-update/backup/0.2.0-1000")); // newest backup keptCHECK(!Exists(fixture.root + "/playden/self-update/state.json"));CHECK(Exists(kits + "/kitid") && Exists(kits + "/.previous-kitid-1000") && !Exists(kits + "/.previous-kitid-1"));@@ -244,16 +270,34 @@ int main() {CHECK(Read(kits + "/kitid/manifest.json") == std::string(64, 'b') && !Exists(kits + "/.previous-kitid-1000"));CHECK(ListFolder(fixture.root + "/playden/self-update/backup").empty());CHECK(Read(fixture.root + "/user/appmeta/FAKE77031/param.json") == "old param");- UpdateService back(fixture.Config({0, 2, 0}));+ UpdateService back(record_root(fixture.Config({0, 2, 0})));back.Start();CHECK(back.Snapshot().finished_message == "Playden went back to version 0.2.0." && back.Snapshot().previous.empty());+ CHECK(!Exists(fixture.root + "/playden/self-update/state.json"));Wait(back);+ root_only_on_this_thread();CHECK(!Exists(fixture.root + "/playden/self-update/replaced"));for (const auto& name : ListFolder(kits)) CHECK(name.rfind(".replaced-", 0) != 0); // removed on this start// The version gone back from is still found, but quietly.back.Check(false);Wait(back);CHECK(back.Snapshot().phase == UpdatePhase::kAvailable && back.Snapshot().quiet);+ back.Shutdown();++ // A start closed before its cleanup finished: the next start, with no state left, cleans up+ // without confirming again; an empty kit folder left by going back goes during Start.+ const std::string work = fixture.root + "/playden/self-update";+ Put(work + "/stage/eboot.bin", "stage");+ Put(work + "/downloads/playden-ps5-0.3.0.zip", "zip");+ Put(kits + "/.replaced-kitid-5/runtime/wine.bin", "files");+ CHECK(MakeFolders(kits + "/.replaced-kitid-6"));+ UpdateService resumed(record_root(fixture.Config({0, 2, 0})));+ resumed.Start();+ CHECK(!Exists(kits + "/.replaced-kitid-6") && resumed.Snapshot().finished_message.empty());+ Wait(resumed);+ root_only_on_this_thread();+ CHECK(!Exists(work + "/stage") && !Exists(work + "/downloads") && !Exists(kits + "/.replaced-kitid-5"));+ CHECK(Exists(kits + "/kitid/manifest.json"));RemoveTree(fixture.root);}// A staged update survives a restart without a swap, and a swap that did not take is reported.