Play your Steam library's Windows games on a jailbroken PS5.
C++
Harden imported game copies on the console
Leonardo Lobato89d13c9a4b6b
diff --git a/src/homebrew/controller.cpp b/src/homebrew/controller.cppindex 7e6aa51..ac12281 100644--- a/src/homebrew/controller.cpp+++ b/src/homebrew/controller.cpp@@ -10,8 +10,16 @@ namespace playden::homebrew {namespace {// RuntimeHost names games by runtime number (a Steam game's app ID); 0 stands for no game, as it// did. For a call: the game's number, given out on first use. Nothing when the runtime has none for-// it (RuntimeHost logs why to the runtime log); the call is then not made.-std::optional<std::uint32_t> RuntimeApp(RuntimeHost& runtime, const GameId& id) {+// it (RuntimeHost logs why to the runtime log); the call is then not made. A first number that+// would wait for the runtime worker is not given out: *busy says to ask again later. This is the+// one for the main thread, which never waits for the runtime worker.+std::optional<std::uint32_t> RuntimeApp(RuntimeHost& runtime, const GameId& id, bool* busy) {+ *busy = false;+ if (id == GameId{}) return 0u;+ return runtime.RuntimeNumberFor(id, busy);+}+// For a store's own worker thread, which may wait for the runtime worker (never the main thread).+std::optional<std::uint32_t> RuntimeAppWaiting(RuntimeHost& runtime, const GameId& id) {if (id == GameId{}) return 0u;return runtime.RuntimeNumberFor(id);}@@ -81,19 +89,23 @@ void Controller::Start(app::PersistenceService* persistence_service) {std::lock_guard<std::mutex> lock(gate_mutex_);if (gate_blocked_.count(id)) return false;}- if (!runtime_) return true;- const auto app = RuntimeApp(*runtime_, id);+ // Only Steam's games have Cloud saves: another store's game needs no runtime number here.+ if (!CloudCapable(id) || !runtime_) return true;+ bool busy = false;+ const auto app = RuntimeApp(*runtime_, id, &busy);return app && runtime_->ActivityNow(*app, std::chrono::seconds(5)) == runtime::NativeActivity::kStopped;});}Controller::~Controller() { Shutdown(); }void Controller::Shutdown() {- if (!service_) return;+ if (shut_down_) return;+ shut_down_ = true;// Preserve a confirmed sign-out queued by the last input frame before exit.- for (const auto action : model_.TakeServiceActions()) {- if (action.store == Store::kSteam && (action == ServiceAction::SignOut || action == ServiceAction::SwitchAccount) &&- phase_!=Phase::ClearLibrary && phase_!=Phase::ClearOrganization && phase_!=Phase::SignOut) SignOut(false);- }+ if (service_)+ for (const auto action : model_.TakeServiceActions()) {+ if (action.store == Store::kSteam && (action == ServiceAction::SignOut || action == ServiceAction::SwitchAccount) &&+ phase_!=Phase::ClearLibrary && phase_!=Phase::ClearOrganization && phase_!=Phase::SignOut) SignOut(false);+ }begin_after_clear_=false;// Each step is logged before it starts and with its time after, so a hang shows where it stopped.const auto step = [this](const char* name, const auto& work) {@@ -108,13 +120,20 @@ void Controller::Shutdown() {if(library_) step("library", [&] { library_->Shutdown(); library_->Tick(); AdvanceClear(); });if(persistence_) step("persistence", [&] { persistence_->FlushAndShutdown(); AdvanceOrganizationClear(); });if(app_details_) step("details", [&] { app_details_->Shutdown(); });+ // A copy or move waiting for the runtime (RuntimeHost::Relocate) stops waiting first, so the+ // install service and the Local store's worker it blocks are joined at once; it resumes at the+ // next start.+ if(runtime_) runtime_->BeginClosing();+ // The install service stops whether or not a Steam account is registered: its Local copy runner+ // calls into the Local store, which the caller destroys after this (host.cpp, ps5.cpp).if(installs_) step("installs", [&] { installs_->Shutdown(); });if(cloud_) step("cloud", [&] { cloud_->Shutdown(); });if(runtime_) step("runtime", [&] { runtime_->Shutdown(); });- service_->Shutdown();- service_ = nullptr;persistence_.reset();library_.reset();+ if (!service_) return;+ service_->Shutdown();+ service_ = nullptr;phase_ = Phase::Idle;Update(AuthState::SignedOut,{},true);}@@ -453,7 +472,7 @@ void Controller::TickCloud() {case CloudRequestKind::RemoveLeftover:// The kept bottle and the game's sync state; no PS5 title is involved.if (runtime_)- if (const auto app = RuntimeApp(*runtime_, request.game_id)) runtime_->DeleteKeptBottle(*app);+ WithApp(request.game_id, [this](std::uint32_t app) { runtime_->DeleteKeptBottle(app); });if (!saves_root_.empty() && CloudCapable(request.game_id))cloud_->Forget({request.game_id, {}, saves_root_ + "/" + ToKey(request.game_id)});after_play_.erase(request.game_id);@@ -523,9 +542,12 @@ void Controller::TickCloud() {const auto id = held.request.game_id;if (runtime.status == RuntimeHostStatus::kStarting) { waiting.push_back(held); continue; }if (!held.asked) {+ bool busy = false;+ const auto app = RuntimeApp(*runtime_, id, &busy);+ if (busy) { waiting.push_back(held); continue; } // asked again next tickheld.asked = true;held.after = runtime.activity_serial;- if (const auto app = RuntimeApp(*runtime_, id)) runtime_->CheckActivity(*app);+ if (app) runtime_->CheckActivity(*app);waiting.push_back(held);continue;}@@ -601,7 +623,7 @@ void Controller::TickCloud() {// so wait long enough for the answers instead (#51).job.deadline = now + kJobActivityWait;for (const auto& id : job.ids)- if (const auto app = RuntimeApp(*runtime_, id)) runtime_->CheckActivity(*app);+ WithApp(id, [this](std::uint32_t app) { runtime_->CheckActivity(app); });answered = false;} else {for (const auto id : job.ids) {@@ -745,8 +767,21 @@ void Controller::TickCloud() {// Per-game runtime: queue Prepare with the Steam install's location, queue Play,// and project the runtime host's state for installed games. The worker checks a// Play request; this thread, the application thread, then starts the title.+// Runs `use` with the game's runtime number. The main thread never waits for the runtime worker: a+// first number that would is asked for again next tick (a game the Local store added or reconciled+// already has one). Nothing runs for a game the runtime has no number for.+void Controller::WithApp(const GameId& id, std::function<void(std::uint32_t)> use) {+ if (!runtime_) return;+ bool busy = false;+ const auto app = RuntimeApp(*runtime_, id, &busy);+ if (busy) { deferred_runtime_.push_back([this, id, use = std::move(use)] { WithApp(id, use); }); return; }+ if (app) use(*app);+}+void Controller::TickRuntime() {if (!runtime_) return;+ // Calls that waited for the runtime worker (a game's first number) are asked again, in order.+ for (auto& again : std::exchange(deferred_runtime_, {})) again();{// The name each installed game's PS5 title should carry.// Keyed by runtime number; a game with none yet has no title to name.@@ -762,46 +797,53 @@ void Controller::TickRuntime() {runtime_->HoldPreparations(model_.state().quit_waiting);// A drop-folder game's files are opened before each Play and Prepare.std::vector<GameId> opened_plays, opened_prepares;- ReleaseDropFolderOpens(opened_plays, opened_prepares);+ std::vector<std::pair<GameId, bool>> opened_submits;+ ReleaseDropFolderOpens(opened_plays, opened_prepares, opened_submits);for (const auto id : model_.TakeRuntimePrepareRequests())- if (!HoldForDropFolder(id, false)) RequestPrepare(id);+ if (!HoldForDropFolder(id, DropFolderNext::kPrepare)) RequestPrepare(id);for (const auto id : opened_prepares) RequestPrepare(id);+ for (const auto& [id, announce] : opened_submits) {+ // Recreate bottle's wait for its preparation to start counts from now.+ if (const auto pending = recreate_.find(id); pending != recreate_.end())+ pending->second.submitted_at = std::chrono::steady_clock::now();+ SubmitPrepare(id, announce);+ }// A game Playden still holds back moves to the front once it is asked for.// The latest choice wins: a game Playden still holds back moves first once it is asked for.for (const auto id : model_.TakePrepareNextRequests()) {- const auto app = RuntimeApp(*runtime_, id);+ bool busy = false;+ const auto app = RuntimeApp(*runtime_, id, &busy);if (app && runtime_->PrepareNext(*app)) prepare_next_pending_.reset();else prepare_next_pending_ = id;}for (const auto& done : model_.TakePreparedDismissals())- if (const auto app = RuntimeApp(*runtime_, done.game_id)) runtime_->DismissPrepared(*app, done.finished_at);+ WithApp(done.game_id, [this, done](std::uint32_t app) { runtime_->DismissPrepared(app, done.finished_at); });if (model_.TakePreparedClear()) runtime_->ClearPrepared();if (model_.TakeRuntimeCleanupRequest()) runtime_->CleanUpRequests();for (const auto& id : model_.TakeKeptDeleteRequests())- if (const auto app = RuntimeApp(*runtime_, id)) runtime_->DeleteKeptBottle(*app);+ WithApp(id, [this](std::uint32_t app) { runtime_->DeleteKeptBottle(app); });for (const auto& id : model_.TakeActivityRequests())- if (const auto app = RuntimeApp(*runtime_, id)) runtime_->CheckActivity(*app);+ WithApp(id, [this](std::uint32_t app) { runtime_->CheckActivity(app); });for (const auto id : model_.TakeProgramScanRequests())if (const auto root = game_roots_.find(id); root != game_roots_.end())- if (const auto app = RuntimeApp(*runtime_, id)) runtime_->ScanPrograms(*app, root->second);- for (const auto& [id, kind] : model_.TakeMaintenanceRequests()) {- const auto app = RuntimeApp(*runtime_, id);- if (!app) continue;- if (kind == MaintenanceKind::RecreateBottle) {- if (recreate_.count(id)) continue;- recreate_[id] = {runtime_->Shared()->removals_handled, false, false, {}, {}};- recreate_results_.erase(id);- runtime_->Remove(*app, false);+ WithApp(id, [this, path = root->second](std::uint32_t app) { runtime_->ScanPrograms(app, path); });+ for (const auto& [id, kind] : model_.TakeMaintenanceRequests())+ WithApp(id, [this, id = id, kind = kind](std::uint32_t app) {+ if (kind == MaintenanceKind::RecreateBottle) {+ if (recreate_.count(id)) return;+ recreate_[id] = {runtime_->Shared()->removals_handled, false, false, {}, {}};+ recreate_results_.erase(id);+ runtime_->Remove(app, false);+ ++play_notes_revision_;+ return;+ }+ recreate_results_.erase(id); // the sheet shows the newest request++play_notes_revision_;- continue;- }- recreate_results_.erase(id); // the sheet shows the newest request- ++play_notes_revision_;- runtime_->Maintain(*app, kind == MaintenanceKind::ClearShaderCache ? RuntimeMaintenance::kClearShaderCache- : kind == MaintenanceKind::Repair ? RuntimeMaintenance::kRepair- : kind == MaintenanceKind::BackupSaves ? RuntimeMaintenance::kBackupSaves- : RuntimeMaintenance::kApplySettings);- }+ runtime_->Maintain(app, kind == MaintenanceKind::ClearShaderCache ? RuntimeMaintenance::kClearShaderCache+ : kind == MaintenanceKind::Repair ? RuntimeMaintenance::kRepair+ : kind == MaintenanceKind::BackupSaves ? RuntimeMaintenance::kBackupSaves+ : RuntimeMaintenance::kApplySettings);+ });{const auto current_shared = runtime_->Shared();const auto& current = *current_shared;@@ -813,7 +855,7 @@ void Controller::TickRuntime() {}}auto plays = model_.TakeRuntimePlayRequests();- std::erase_if(plays, [this](GameId id) { return HoldForDropFolder(id, true); });+ std::erase_if(plays, [this](GameId id) { return HoldForDropFolder(id, DropFolderNext::kPlay); });plays.insert(plays.end(), opened_plays.begin(), opened_plays.end());{const auto prepared_shared = runtime_->Shared();@@ -895,7 +937,8 @@ void Controller::TickRuntime() {if (prepared.preparing_app) break;if (!game_roots_.count(*it)) { ++it; continue; }const auto* record = record_of(*it);- if (record && record->awaiting_registration) SubmitPrepare(*it, false);+ if (record && record->awaiting_registration && !HoldForDropFolder(*it, DropFolderNext::kRegistrationCheck))+ SubmitPrepare(*it, false);it = startup_awaiting_.erase(it);break; // one at a time, after the worker takes it}@@ -940,10 +983,17 @@ void Controller::TickRuntime() {pending.prepare_submitted = true;pending.refusal = refusal_of(id);pending.submitted_at = std::chrono::steady_clock::now();- SubmitPrepare(id);+ if (!HoldForDropFolder(id, DropFolderNext::kRecreate)) {+ SubmitPrepare(id);+ } else if (!drop_folder_opens_.count(id)) {+ finish(false, "Playden is busy. Try again in a moment.");+ continue;+ }++it;continue;}+ // Its drop folder's files are still being opened (that has a timeout of its own).+ if (drop_folder_opens_.count(id)) { ++it; continue; }if (IsNumber(prepared, prepared.preparing_app, id)) { pending.seen_preparing = true; ++it; continue; }const bool unseen_too_long = !pending.seen_preparing && !PrepareQueued(prepared, NumberIn(prepared, id)) &&std::chrono::steady_clock::now() - pending.submitted_at > std::chrono::seconds(15);@@ -1021,7 +1071,9 @@ void Controller::TickRuntime() {for (const auto id : plays_ready_) {// Never start a game while its saves are moving; it starts once they stop.if (cloud_busy_.count(id)) { later.push_back(id); continue; }- const auto app = RuntimeApp(*runtime_, id);+ bool busy = false;+ const auto app = RuntimeApp(*runtime_, id, &busy);+ if (busy) { later.push_back(id); continue; } // the game's first number waits for the runtime workerif (!app) continue;play_queued_.insert(id);++plays_requested_;@@ -1301,7 +1353,11 @@ void Controller::BeginUninstall(GameId id, bool delete_saves) {if (!runtime_) { if (installs_) installs_->Uninstall(id); return; }// A preparation still waiting would make a title for files about to be deleted: it leaves the queue.// One already running finishes first (TickUninstalls waits), so its title is removed with the rest.- if (const auto app = RuntimeApp(*runtime_, id)) runtime_->WithdrawPrepare(*app);+ // A game with no number yet has nothing queued to withdraw (queuing gives it one).+ {+ bool busy = false;+ if (const auto app = RuntimeApp(*runtime_, id, &busy)) runtime_->WithdrawPrepare(*app);+ }std::erase(auto_prepare_, id);prepare_after_details_.erase(id);play_after_prepare_.erase(id);@@ -1340,7 +1396,7 @@ void Controller::TickUninstalls() {switch (action.kind) {case UninstallAction::Kind::kNone: break;case UninstallAction::Kind::kRemoveTitle:- if (const auto app = RuntimeApp(*runtime_, id)) runtime_->Remove(*app, action.delete_saves);+ WithApp(id, [this, delete_saves = action.delete_saves](std::uint32_t app) { runtime_->Remove(app, delete_saves); });++play_notes_revision_;break;// The title is gone, so no title points at the files about to be deleted.@@ -1391,7 +1447,23 @@ void Controller::TickImports() {// Outcomes are kept for the latest requests only: one never answered is dropped with the oldest.while (import_requests_.size() > stores::local::LocalLibrarySource::kMaxOutcomes * 2) import_requests_.erase(import_requests_.begin());};- for (const auto& request : model_.TakeImportRequests()) {+ // A copy or move's install record carries the game's runtime number (given out now if it has+ // none); a game set up from its drive folder keeps its PS5 title, which follows the files. A+ // first number is written to the runtime records, which wait while the runtime worker starts up+ // or works through a batch: the request waits here instead, a tick at a time, and the frame+ // goes on.+ const auto transfer_number = [this](const ImportRequest& request, std::uint32_t* number) {+ *number = 0;+ if (!runtime_) return true;+ bool busy = false;+ *number = RuntimeApp(*runtime_, request.game_id, &busy).value_or(0u);+ if (busy) held_import_transfers_.push_back(request);+ return !busy;+ };+ auto requests = std::exchange(held_import_transfers_, {});+ for (auto& request : model_.TakeImportRequests()) requests.push_back(std::move(request));+ for (const auto& request : requests) {+ std::uint32_t number = 0;switch (request.kind) {case ImportRequestKind::LookForGames: local_->LookForGames(); break;case ImportRequestKind::Add: track(local_->Add(request.volume_id, request.folder, request.program), request); break;@@ -1399,18 +1471,12 @@ void Controller::TickImports() {if (request.game_id.store == Store::kLocal) held_import_removals_.push_back(request.game_id);break;case ImportRequestKind::CopyIntoPlayden:- if (request.game_id.store == Store::kLocal) {- // The copy's install record carries the game's runtime number (given out now if it has- // none); a game set up from its drive folder keeps its PS5 title, which follows the copy.- const auto number = runtime_ ? RuntimeApp(*runtime_, request.game_id).value_or(0u) : 0u;+ if (request.game_id.store == Store::kLocal && transfer_number(request, &number))track(local_->CopyIntoPlayden(request.game_id.value, request.volume_id, number), request);- }break;case ImportRequestKind::MoveIntoPlayden:- if (request.game_id.store == Store::kLocal) {- const auto number = runtime_ ? RuntimeApp(*runtime_, request.game_id).value_or(0u) : 0u;+ if (request.game_id.store == Store::kLocal && transfer_number(request, &number))track(local_->MoveIntoPlayden(request.game_id.value, number), request);- }break;}}@@ -1433,6 +1499,9 @@ void Controller::TickImports() {[&](const stores::local::ImportOutcome& o) { return o.request == it->first; });if (outcome == snapshot->outcomes.end()) { ++it; continue; }if (!outcome->ok) model_.NotifyImportFailed(it->second, outcome->message);+ // A game just added: the program chosen with it goes into its Game settings.+ else if (it->second.kind == ImportRequestKind::Add && !outcome->id.empty())+ model_.SeedGameProgram(GameId::Local(outcome->id), it->second.program);it = import_requests_.erase(it);}// Once imports.json is read: copies that finished or stopped while Playden was closed are settled.@@ -1444,7 +1513,8 @@ void Controller::TickImports() {auto* installs = installs_; // outlives the Local store's workerauto* runtime = runtime_; // so does the runtime hostlocal_->Reconcile([installs] { return installs->Snapshot(); }, [installs](const GameId& id) { installs->Cancel(id); },- [runtime](const GameId& id) { return runtime ? RuntimeApp(*runtime, id).value_or(0u) : 0u; });+ [runtime](const GameId& id) { return runtime ? RuntimeAppWaiting(*runtime, id).value_or(0u) : 0u; });+ local_->SetRuntimeNumber([runtime](const GameId& id) { return runtime ? RuntimeAppWaiting(*runtime, id).value_or(0u) : 0u; });// A copy restored at start waited for imports.json: it carries on now.installs_->RetryWaiting(Store::kLocal);}@@ -1453,7 +1523,7 @@ void Controller::TickImports() {std::vector<LiveImportCandidate> candidates;for (const auto& candidate : snapshot->candidates) {LiveImportCandidate live{candidate.volume, candidate.folder, candidate.path, candidate.title, {},- candidate.total_bytes, candidate.ascii_ok, candidate.partial, {}};+ candidate.total_bytes, candidate.ascii_ok, candidate.partial, {}, candidate.file_count};for (const auto& program : candidate.programs) live.programs.push_back({program.path, program.bytes, program.helper});if (!candidate.imported_id.empty()) live.imported = GameId::Local(candidate.imported_id);candidates.push_back(std::move(live));@@ -1465,39 +1535,66 @@ void Controller::TickImports() {if (library_) library_->Refresh(Store::kLocal);}}-bool Controller::HoldForDropFolder(GameId id, bool play) {+bool Controller::HoldForDropFolder(GameId id, DropFolderNext next) {if (id.store != Store::kLocal || !local_) return false;const auto* location = LocationOf(id);if (!location || location->managed() || !location->available ||location->volume_id != stores::local::ImportStore::kDropFolderVolume)return false;+ // The player asked: a stop is said, and the game page says what it waits for.+ const bool asked = next == DropFolderNext::kPlay || next == DropFolderNext::kPrepare;auto& open = drop_folder_opens_[id];- if (!open.request && !(open.request = local_->OpenForPlay(id.value))) {+ if (!open.request) {+ open.request = local_->OpenForPlay(id.value);+ open.started = std::chrono::steady_clock::now();+ }+ if (!open.request) {+ // The Local store is busy: the caller stops (a Recreate bottle loop finishes its own entry).drop_folder_opens_.erase(id);- model_.NotifyPlayStopped(id, "Playden is busy. Press Play again in a moment.");+ if (asked) model_.NotifyPlayStopped(id, "Playden is busy. Press Play again in a moment.");return true;}- (play ? open.play : open.prepare) = true;- play_notes_[id] = "Opening the game's files…";- ++play_notes_revision_;+ switch (next) {+ case DropFolderNext::kPlay: open.play = true; break;+ case DropFolderNext::kPrepare: open.prepare = true; break;+ case DropFolderNext::kRecreate: open.recreate = true; break;+ case DropFolderNext::kRegistrationCheck: open.registration_check = true; break;+ }+ if (asked) {+ play_notes_[id] = "Opening the game's files…";+ ++play_notes_revision_;+ }return true;}-void Controller::ReleaseDropFolderOpens(std::vector<GameId>& plays, std::vector<GameId>& prepares) {+void Controller::ReleaseDropFolderOpens(std::vector<GameId>& plays, std::vector<GameId>& prepares,+ std::vector<std::pair<GameId, bool>>& submits) {if (drop_folder_opens_.empty() || !local_) return;const auto snapshot = local_->Snapshot();+ const auto now = std::chrono::steady_clock::now();for (auto it = drop_folder_opens_.begin(); it != drop_folder_opens_.end();) {const auto outcome = std::find_if(snapshot->outcomes.begin(), snapshot->outcomes.end(),[&](const stores::local::ImportOutcome& o) { return o.request == it->second.request; });- if (outcome == snapshot->outcomes.end()) { ++it; continue; }+ const bool timed_out = outcome == snapshot->outcomes.end() && now - it->second.started >= drop_folder_open_timeout_;+ if (outcome == snapshot->outcomes.end() && !timed_out) { ++it; continue; }const auto id = it->first;- play_notes_.erase(id);- ++play_notes_revision_;- if (!outcome->ok) {- model_.NotifyPlayStopped(id, outcome->message);- } else {- if (it->second.play) plays.push_back(id);- // Play prepares a game that needs it on its own.- else if (it->second.prepare) prepares.push_back(id);+ const auto& open = it->second;+ if (play_notes_.erase(id)) ++play_notes_revision_;+ if (timed_out || !outcome->ok) {+ const auto message = timed_out ? std::string("Playden couldn't open the game's folder in time.") : outcome->message;+ if (open.play || open.prepare) model_.NotifyPlayStopped(id, message);+ if (open.recreate) {+ recreate_results_[id] = {false, message};+ recreate_.erase(id);+ ++play_notes_revision_;+ }+ } else if (open.play) {+ plays.push_back(id); // Play prepares a game that needs it on its own+ if (open.recreate) submits.emplace_back(id, true);+ } else if (open.prepare) {+ prepares.push_back(id);+ if (open.recreate) submits.emplace_back(id, true);+ } else if (open.recreate || open.registration_check) {+ submits.emplace_back(id, open.recreate);}it = drop_folder_opens_.erase(it);}@@ -1653,12 +1750,18 @@ void Controller::RequestPrepare(GameId id) {void Controller::SubmitPrepare(GameId id, bool announce) {const auto root = game_roots_.find(id);if (!runtime_ || root == game_roots_.end()) return;- const auto app = RuntimeApp(*runtime_, id);+ bool busy = false;+ const auto app = RuntimeApp(*runtime_, id, &busy);+ if (busy) { // the game's first number waits for the runtime worker: again next tick+ deferred_runtime_.push_back([this, id, announce] { SubmitPrepare(id, announce); });+ return;+ }if (!app) return;if (announce) ready_watch_[id] = {false, std::chrono::steady_clock::now()};else ready_watch_.erase(id);- // An imported game starts the program chosen when it was added: Game settings has it before its- // first preparation, unless the player picked another one there.+ // An imported game starts the program chosen when it was added: written into Game settings when+ // it was added, or here before its first preparation if that couldn't be; never over the player's+ // own choice or reset (SeedGameProgram).if (id.store == Store::kLocal && local_) {const auto snapshot = local_->Snapshot();for (const auto& game : snapshot->games)diff --git a/src/homebrew/controller.hpp b/src/homebrew/controller.hppindex ee1fbf3..80bcb11 100644--- a/src/homebrew/controller.hpp+++ b/src/homebrew/controller.hpp@@ -71,6 +71,8 @@ class Controller {// model's import requests (look for games, add, remove) go to it, and removing an imported game// removes its PS5 title first, keeping its bottle as kept data. Set before the first Tick.void SetLocalLibrary(stores::local::LocalLibrarySource* local) { local_ = local; }+ // Tests: how long a Play or preparation waits for a drop-folder game's files to be opened.+ void SetDropFolderOpenTimeout(std::chrono::milliseconds timeout) { drop_folder_open_timeout_ = timeout; }Controller(const Controller&) = delete;Controller& operator=(const Controller&) = delete;private:@@ -139,22 +141,36 @@ class Controller {// Removals asked for before the Local store's first snapshot reached the locations: until then a// game's folder (and so its PS5 title's removal first) isn't known.std::vector<GameId> held_import_removals_;+ // Copies and moves into Playden whose game's first runtime number waits for the runtime worker+ // (starting up, or in a batch): asked again on the next tick, in order.+ std::vector<ImportRequest> held_import_transfers_;+ // Runtime calls whose game's first number waited for the runtime worker: made again on the next+ // tick, in order. The main thread never waits for that worker.+ std::vector<std::function<void()>> deferred_runtime_;+ void WithApp(const GameId& id, std::function<void(std::uint32_t)> use);// The player's add, copy, move and removal requests sent to the Local store, by request number,// until their outcome: a refusal reaches the model as a notice.std::map<std::uint64_t, ImportRequest> import_requests_;// Copies into Playden were reconciled with the install service after the first imports.json read.bool copies_reconciled_ = false;- // Play and Prepare of a game playing from the drop folder wait for its files to be opened- // (LocalLibrarySource::OpenForPlay); a failure stops them with the walk's sentence.+ // Play and every preparation of a game playing from the drop folder (the player's Prepare,+ // Recreate bottle, the startup check of a title waiting for the PS5) wait for its files to be+ // opened (LocalLibrarySource::OpenForPlay); a failure stops them with the walk's sentence, and so+ // does an opening with no outcome within the timeout (its outcome may have left the store's list).+ enum class DropFolderNext { kPlay, kPrepare, kRecreate, kRegistrationCheck };struct DropFolderOpen {std::uint64_t request = 0;- bool play = false, prepare = false;+ bool play = false, prepare = false, recreate = false, registration_check = false;+ std::chrono::steady_clock::time_point started;};std::map<GameId, DropFolderOpen> drop_folder_opens_;+ std::chrono::milliseconds drop_folder_open_timeout_ = std::chrono::seconds(60);// True when the request waits (or was stopped) for the drop folder.- bool HoldForDropFolder(GameId id, bool play);- // Finished openings: their requests go on (into plays and prepares) or stop.- void ReleaseDropFolderOpens(std::vector<GameId>& plays, std::vector<GameId>& prepares);+ bool HoldForDropFolder(GameId id, DropFolderNext next);+ // Finished openings: their requests go on (into plays, prepares and direct submissions, with+ // their announce flag) or stop.+ void ReleaseDropFolderOpens(std::vector<GameId>& plays, std::vector<GameId>& prepares,+ std::vector<std::pair<GameId, bool>>& submits);const installs::InstalledLocation* LocationOf(GameId id) const;// Whether Cloud saves apply to the game: a Cloud service exists and the game's store has them.bool CloudCapable(GameId id) const { return cloud_ && Traits(id.store).cloud_saves; }@@ -294,6 +310,7 @@ class Controller {steam::RequestId request_ = 0;std::uint64_t generation_ = 0;Phase phase_ = Phase::Idle;+ bool shut_down_ = false; // Shutdown ranbool begin_after_clear_ = false;// A QR sign-in for an account that is already signed in: its library and organization stay, and// a cancel or failure goes back to the saved sign-in.diff --git a/src/homebrew/host.cpp b/src/homebrew/host.cppindex d84c591..f18ab1c 100644--- a/src/homebrew/host.cpp+++ b/src/homebrew/host.cpp@@ -578,6 +578,7 @@ int main(int argc, char** argv) {std::uint32_t runtime_number) {return runner->Move(*service, entry, source, runtime_number);};+ import_config.remove_copy_folder = [runner = copy_runner.get()](const std::string& root) { return runner->Remove(root); };auto local_library = std::make_unique<playden::stores::local::LocalLibrarySource>(*imports, std::move(import_config));auto* local = local_library.get();copy_runner->SetChanged([local] { local->Reload(); });@@ -728,6 +729,11 @@ int main(int argc, char** argv) {if (controller) SDL_GameControllerClose(controller);SDL_StopTextInput();if (services) services->Shutdown();+ // The install service stops before the Local store goes (`stores` is destroyed before+ // `installs`): its copy runner's change callback calls into the Local store. Explicit here, so+ // it doesn't rest on the controller's shutdown or on declaration order.+ if (installs) installs->Shutdown();+ if (copy_runner) copy_runner->SetChanged({});if (artwork) artwork->Shutdown();render.reset();SDL_GL_DeleteContext(context);diff --git a/src/homebrew/ps5.cpp b/src/homebrew/ps5.cppindex 6a855a9..63b713e 100644--- a/src/homebrew/ps5.cpp+++ b/src/homebrew/ps5.cpp@@ -503,6 +503,11 @@ 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;+ config.try_hold_effective_uid = [](bool* busy) {+ auto held = playden::ps5::TryHoldEffectiveUid();+ *busy = !held;+ return held;+ };// 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) {@@ -636,6 +641,7 @@ int main() {std::uint32_t runtime_number) {return runner->Move(installs, entry, source, runtime_number);};+ import_config.remove_copy_folder = [runner = copy_runner.get()](const std::string& root) { return runner->Remove(root); };auto source = std::make_unique<playden::stores::local::LocalLibrarySource>(*imports, std::move(import_config));local_library = source.get();copy_runner->SetChanged([local_library] { local_library->Reload(); });@@ -837,6 +843,11 @@ int main() {#if !PLAYDEN_UI_SIMULATIONplayden::app::AppendLogLine(log_root, "launch.log", "quit requested");services.Shutdown();+ // The install service stops before the Local store goes (`stores` is destroyed before+ // `installs`): its copy runner's change callback calls into the Local store. Explicit here,+ // so it doesn't rest on the controller's shutdown or on declaration order.+ installs.Shutdown();+ if (copy_runner) copy_runner->SetChanged({});playden::app::AppendLogLine(log_root, "launch.log", "shutdown artwork start");artwork.Shutdown();playden::app::AppendLogLine(log_root, "launch.log", "shutdown self-update start");diff --git a/src/homebrew/runtime_host.cpp b/src/homebrew/runtime_host.cppindex a91f7ea..42812ef 100644--- a/src/homebrew/runtime_host.cpp+++ b/src/homebrew/runtime_host.cpp@@ -64,6 +64,14 @@ constexpr std::int64_t kPreflightFreshMs = 5000;constexpr char kActivityUnknown[] ="The PS5 could not tell Playden whether the game is running. Restart the PS5, then try again.";+// A relocated game's republish refused because its old publication can't be verified against the+// new folder (VerifyMovedPublication, or the title's artifacts): only a new title gets past that.+// The capture step reports its moved-publication check under its own code, so its words tell.+bool UnverifiableMovedPublication(const std::string& code, const std::string& message) {+ return code == "publication-moved" || code == "publication-preflight-previous" || code == "artifact-invalid" ||+ (code == "publication-request-capture" && message.find("not the verified publication") != std::string::npos);+}+// A moved game whose publication can't be redone: Recreate bottle (confirmed) prepares it again.constexpr char kRecreateHint[] = " Use Maintenance > Recreate bottle on the game page to prepare it again.";@@ -1091,12 +1099,28 @@ void RuntimeHost::Publish(const std::function<void(RuntimeSnapshot&)>& change) {published_.notify_all();}-std::optional<std::uint32_t> RuntimeHost::RuntimeNumberFor(const GameId& game) {+std::optional<std::uint32_t> RuntimeHost::RuntimeNumberFor(const GameId& game, bool* busy) {+ if (busy) *busy = false;if (const auto app = game.steam_app()) return app;if (!game.valid()) {Log("runtime number refused: invalid game " + ToKey(game));return std::nullopt;}+ {+ std::lock_guard<std::mutex> lock(numbers_mutex_);+ if (const auto found = numbers_.find(game); found != numbers_.end()) return found->second;+ }+ // A new number is written to installs.json, which takes the effective-UID hold: taken here first,+ // before the repository's lock. The worker holds it around startup and each batch while using the+ // repository, so a lookup already inside the repository would wait for the worker and the worker+ // for the lookup.+ std::shared_ptr<void> held;+ if (busy && config_.try_hold_effective_uid) {+ held = config_.try_hold_effective_uid(busy);+ if (*busy) return std::nullopt;+ } else if (config_.hold_effective_uid) {+ held = config_.hold_effective_uid();+ }std::uint32_t number = 0;{// The repository serializes this with the worker's own use of it (its writes included).@@ -1157,17 +1181,20 @@ RuntimeRelocationResult RuntimeHost::Relocate(RuntimeRelocation request, std::chRuntimeRelocationResult busy;busy.outcome = RuntimeRelocationResult::Outcome::kBusy;busy.message = "Playden is busy with this game. Try again in a moment.";+ RuntimeRelocationResult closing = busy;+ closing.message = kRelocationClosing;auto pending = std::make_shared<PendingRelocation>();pending->request = std::move(request);std::unique_lock<std::mutex> lock(mutex_);- if (stopping_) return busy;+ if (stopping_ || closing_) return closing;relocation_requests_.push_back(pending);wake_.notify_all();const auto settled = [&] { return pending->result.has_value() || (stopping_ && !pending->started); };- if (!published_.wait_for(lock, timeout, [&] { return settled() || pending->started; })) {+ const bool answered = published_.wait_for(lock, timeout, [&] { return settled() || pending->started || closing_; });+ if (!answered || (!pending->started && !pending->result)) {// Not started yet: it never will.pending->abandoned = true;- return busy;+ return answered ? closing : busy;}// Once started it runs to the end (the files may be moving): wait for its answer.published_.wait(lock, settled);@@ -1175,6 +1202,14 @@ RuntimeRelocationResult RuntimeHost::Relocate(RuntimeRelocation request, std::chreturn *pending->result;}+void RuntimeHost::BeginClosing() {+ {+ std::lock_guard<std::mutex> lock(mutex_);+ closing_ = true;+ }+ published_.notify_all();+}+void RuntimeHost::ReportWork(std::uint64_t done, std::uint64_t total) {if (total == 0) return;const int percent = static_cast<int>(std::min<std::uint64_t>(done, total) * 100 / total);@@ -1494,8 +1529,9 @@ std::string RuntimeHost::UnlinkDxvkConfig(const rt::RuntimeInstall& record) {std::string RuntimeHost::RepublishSettings(Composition& c, const rt::RuntimeInstall& record, bool* published,bool steam_account_known, bool* prepare_again,- std::string* upgrade_deferred) {+ std::string* upgrade_deferred, std::string* code) {if (published) *published = false;+ if (code) code->clear();if (prepare_again) *prepare_again = false;if (upgrade_deferred) upgrade_deferred->clear();// A recipe this kit cannot run is refused before the game's files or bottle change.@@ -1520,7 +1556,7 @@ std::string RuntimeHost::RepublishSettings(Composition& c, const rt::RuntimeInstreturn {};}}- auto refused = PublishSavedSettings(c, record, published, steam_account_known, prepare_again);+ auto refused = PublishSavedSettings(c, record, published, steam_account_known, prepare_again, code);if (refused.empty() || !upgrade_only) return refused;Log("settings update app=" + std::to_string(record.runtime_number) + " unowned upgrade deferred, owned publication kept: " +refused);@@ -1534,7 +1570,8 @@ std::string RuntimeHost::RepublishSettings(Composition& c, const rt::RuntimeInst}std::string RuntimeHost::PublishSavedSettings(Composition& c, const rt::RuntimeInstall& record, bool* published,- bool steam_account_known, bool* prepare_again) {+ bool steam_account_known, bool* prepare_again, std::string* code) {+ if (code) code->clear();// Refusals only a new preparation gets past (the title's recipe or settings can't be published again).const auto again = [prepare_again](std::string message) {if (prepare_again) *prepare_again = true;@@ -1667,7 +1704,10 @@ std::string RuntimeHost::PublishSavedSettings(Composition& c, const rt::RuntimeILog("settings update request app=" + std::to_string(record.runtime_number) + " transaction=" + request.transaction_id +" revision=" + std::to_string(record.settings_revision) + "->" + std::to_string(saved.revision) + " state=" +std::to_string(static_cast<int>(requested.state)) + " code=" + requested.code + " message=" + requested.message);- if (requested.state != rt::PackageActionState::kComplete) return "The settings could not be applied: " + requested.message;+ if (requested.state != rt::PackageActionState::kComplete) {+ if (code) *code = requested.code;+ return "The settings could not be applied: " + requested.message;+ }const auto armed = c.records.Find(record.install_id);if (!armed) return "The game's install record is missing.";const auto resumed = c.owner->ResumeRequested(*armed, c.request_directory, config_.host_namespace_prefix);@@ -1683,7 +1723,10 @@ std::string RuntimeHost::PublishSavedSettings(Composition& c, const rt::RuntimeIDropUpgradeRequest(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;+ if (resumed.state != rt::PackageActionState::kComplete) {+ if (code) *code = resumed.code;+ return "The settings could not be applied: " + resumed.message;+ }if (published) *published = true;if (const auto current = c.records.Find(record.install_id)) OpenGameFolders(c, *current);if (moved) FinishGamesMove(c);@@ -1882,18 +1925,22 @@ RuntimeRelocationResult RuntimeHost::RunRelocate(Composition& c, const RuntimeRereturn answer(Outcome::kDone, busy);}bool published = false;- const auto refused = RepublishSettings(c, *current, &published);+ std::string code;+ const auto refused = RepublishSettings(c, *current, &published, true, nullptr, nullptr, &code);if (refused.empty()) {Log("relocate app=" + app + " republished at " + request.to);return answer(Outcome::kDone);}- if (!c.kit) {- Log("relocate app=" + app + " republish waits: " + refused);+ if (!c.kit || !UnverifiableMovedPublication(code, refused)) {+ // Anything else (the title running or its activity unknown, the lease or the storage busy, no+ // kit): the record stays marked moved, and Play or the next start publishes it, as after the+ // 0.6 games move.+ Log("relocate app=" + app + " republish waits" + (code.empty() ? std::string() : " code=" + code) + ": " + refused);return answer(Outcome::kDone, refused);}// The moved publication can't be verified: as for a game installed again on another drive, the// old title goes, keeping its saves, and the game is prepared again where it is now.- Log("relocate app=" + app + " republish failed, removing the old title keeping saves: " + refused);+ Log("relocate app=" + app + " republish failed code=" + code + ", removing the old title keeping saves: " + refused);auto result = answer(Outcome::kDone);result.prepare_again = true;Publish([&](RuntimeSnapshot& s) { s.removing_app = request.runtime_number; });diff --git a/src/homebrew/runtime_host.hpp b/src/homebrew/runtime_host.hppindex ed292ff..5a779f5 100644--- a/src/homebrew/runtime_host.hpp+++ b/src/homebrew/runtime_host.hpp@@ -93,6 +93,10 @@ struct RuntimeHostConfig {// 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;+ // hold_effective_uid without waiting, for RuntimeNumberFor's callers that would rather come back+ // later than wait for a batch: sets *busy and returns nothing when another thread holds it+ // (ps5::TryHoldEffectiveUid). Empty: RuntimeNumberFor waits, with hold_effective_uid.+ std::function<std::shared_ptr<void>(bool* busy)> try_hold_effective_uid;// Runs work with root raised (ps5::WithRoot), as UpdateConfig::as_root; used on the worker,// whose batch hold keeps other threads from raising root meanwhile. Empty: folders can't be fixed.std::function<bool(const std::function<bool()>& work)> as_root;@@ -345,6 +349,9 @@ struct RuntimeRelocation {std::function<std::string()> move_files;};+// What RuntimeHost::Relocate answers once Playden is closing (BeginClosing).+inline constexpr const char* kRelocationClosing = "Playden is closing.";+struct RuntimeRelocationResult {enum class Outcome {kDone, // the game plays from `to` (its record names it; a marked republish may still wait)@@ -422,10 +429,12 @@ class RuntimeHost {void Maintain(std::uint32_t runtime_number, RuntimeMaintenance action);// A game's runtime number, which every call above takes: a Steam game's app ID; for a game from// another store, the number of its install record, or a new one, saved before it is returned.- // Any thread; it may write installs.json (briefly waiting for the worker's write in progress).- // Nothing when the game is invalid, the runtime records are not loaded (yet) or the write fails;- // the runtime log says which. RuntimeSnapshot::runtime_games lists the number before it returns.- std::optional<std::uint32_t> RuntimeNumberFor(const GameId& game);+ // Any thread. A new number is written to installs.json under the effective-UID hold, so it waits+ // while the worker starts up or works through a batch; with `busy`, it returns nothing at once+ // and sets *busy instead (ask again later). Nothing otherwise when the game is invalid, the+ // runtime records are not loaded (yet) or the write fails; the runtime log says which.+ // RuntimeSnapshot::runtime_games lists the number before it returns.+ std::optional<std::uint32_t> RuntimeNumberFor(const GameId& game, bool* busy = nullptr);// Makes `request.to` the game's folder, keeping its PS5 title, runtime number and bottle (the// 0.6 games move's republish, for one game): with the game's publication lease held and its title// stopped, move_files runs, then one record write names the new folder (moved_from the old one)@@ -433,8 +442,13 @@ class RuntimeHost {// back to removing the old title, keeping its saves (prepare_again). A record already naming `to`// (a restart after its write) only finishes the republish. Blocks the calling thread (never the// worker's) until the worker answers; a request the worker hasn't started within `timeout` is- // dropped and answers kBusy.+ // dropped and answers kBusy. Once Playden is closing (BeginClosing), a request not started yet+ // answers kBusy with kRelocationClosing at once: the copy or move resumes at the next start.RuntimeRelocationResult Relocate(RuntimeRelocation request, std::chrono::milliseconds timeout);+ // Playden is quitting: callers waiting in Relocate for a relocation the worker hasn't started stop+ // waiting now, and new ones are refused, so the install and Local workers they block can be+ // joined before this host shuts down. Doesn't stop the worker (Shutdown does); safe to call twice.+ void BeginClosing();// Application thread only: starts the title of a prepared launch session.// Returns false when no session is waiting.bool Handoff();@@ -465,12 +479,15 @@ class RuntimeHost {// *prepare_again: refused for a reason only a new preparation gets past (recipe or settings).// The unowned upgrade alone (not moved, no newer settings) never refuses: its failure is in// *upgrade_deferred and the owned publication stays, as it played before.+ // `code`: the publication's failure code when the publication itself refused (empty otherwise).std::string RepublishSettings(Composition& composition, const runtime::RuntimeInstall& record,bool* published = nullptr, bool steam_account_known = true,- bool* prepare_again = nullptr, std::string* upgrade_deferred = nullptr);+ bool* prepare_again = nullptr, std::string* upgrade_deferred = nullptr,+ std::string* code = nullptr);// RepublishSettings without the upgrade's fallback.std::string PublishSavedSettings(Composition& composition, const runtime::RuntimeInstall& record,- bool* published, bool steam_account_known, bool* prepare_again);+ bool* published, bool steam_account_known, bool* prepare_again,+ std::string* code = nullptr);// 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);@@ -617,12 +634,15 @@ class RuntimeHost {runtime::LaunchService* launch_ = nullptr;Composition* launch_composition_ = nullptr;pthread_t application_thread_{};- // Runtime numbers of games from other stores. Lock order: numbers_mutex_, then the repository's- // own lock (never the other way round), then mutex_.+ // Runtime numbers of games from other stores. Lock order: the effective-UID hold (which the+ // worker keeps around startup and each batch, repository use included), then numbers_mutex_,+ // then the repository's own lock (never the other way round), then mutex_. A number lookup that+ // may write the repository takes the hold first: a repository write waits for the hold itself.mutable std::mutex numbers_mutex_;std::unordered_map<GameId, std::uint32_t> numbers_; // guarded by numbers_mutex_runtime::RuntimeInstallRepository* numbers_repository_ = nullptr; // guarded by numbers_mutex_bool stopping_ = false;+ bool closing_ = false; // BeginClosing: relocations not started answer at oncebool started_ = false;void* thread_ = nullptr; // pthread_t storage, owned by the implementation};diff --git a/src/homebrew/simulation.cpp b/src/homebrew/simulation.cppindex 3a0c6e1..5d687ea 100644--- a/src/homebrew/simulation.cpp+++ b/src/homebrew/simulation.cpp@@ -317,6 +317,8 @@ std::vector<std::string> context_actions(bool live) {constexpr const char* uninstall_body_kept = "The game's files and its PS5 title are removed from this console. Its saves and ""settings are kept, and installing the game again brings them back.";+constexpr const char* uninstall_body_kept_imported = "The game's files and its PS5 title are removed from this console. Its saves and "+ "settings are kept, and adding the game again brings them back.";constexpr const char* uninstall_body_deleted = "The game's files, its PS5 title and its saves and settings on this console are ""deleted.";constexpr const char* uninstall_batch_body_kept = "Their files and PS5 titles are removed from this console. Their saves and "@@ -627,10 +629,14 @@ std::string import_volume_name(const std::string& volume) {return volume;}-// How long a copy takes at the console's copy speed (about 11 MB/s): "about 14 min".-std::string import_copy_estimate(std::uint64_t bytes) {- constexpr std::uint64_t kBytesPerSecond = 11'000'000;- const auto minutes = std::max<std::uint64_t>(1, (bytes / kBytesPerSecond + 59) / 60);+// How long a copy takes on the console: about 80 MB/s of data plus 15 ms to create each file (file+// creation is serialized, so many small files copy slowly): "under a minute", "about 14 min".+std::string import_copy_estimate(std::uint64_t bytes, std::uint64_t files) {+ constexpr std::uint64_t kBytesPerSecond = 80'000'000;+ constexpr std::uint64_t kMillisecondsPerFile = 15;+ const auto seconds = (bytes + kBytesPerSecond - 1) / kBytesPerSecond + (files * kMillisecondsPerFile + 999) / 1000;+ if (seconds < 60) return "under a minute";+ const auto minutes = (seconds + 59) / 60;if (minutes <= 90) return "about " + std::to_string(minutes) + " min";return "about " + std::to_string((minutes + 30) / 60) + " h";}@@ -643,23 +649,24 @@ std::string import_candidate_key(const LiveImportCandidate& candidate) {std::vector<LiveImportCandidate> fixture_import_candidates() {std::vector<LiveImportCandidate> candidates;const auto add = [&](std::string volume, std::string folder, std::string path, std::string title,- std::uint64_t bytes, bool ascii_ok, std::vector<LiveImportProgram> programs) {+ std::uint64_t bytes, bool ascii_ok, std::vector<LiveImportProgram> programs,+ std::uint64_t files = 0) {LiveImportCandidate candidate;candidate.volume_id = std::move(volume); candidate.folder = std::move(folder); candidate.path = std::move(path);candidate.title = std::move(title); candidate.total_bytes = bytes; candidate.ascii_ok = ascii_ok;- candidate.programs = std::move(programs);+ candidate.programs = std::move(programs); candidate.file_count = files;candidates.push_back(std::move(candidate));};add("usb0", "playden/import/Night Sky", "/mnt/usb0/playden/import/Night Sky", "Night Sky", 412'000'000, true,- {{"NightSky.exe", 18'000'000, false}});+ {{"NightSky.exe", 18'000'000, false}}, 120);add("usb0", "playden/import/Old School Rally", "/mnt/usb0/playden/import/Old School Rally", "Old School Rally",- 938'000'000, true, {{"OldSchoolRally.exe", 640'000'000, false}, {"UnityCrashHandler64.exe", 1'400'000, true}});+ 938'000'000, true, {{"OldSchoolRally.exe", 640'000'000, false}, {"UnityCrashHandler64.exe", 1'400'000, true}}, 2400);add("usb0", "playden/import/Café Étoile", "/mnt/usb0/playden/import/Café Étoile", "Café Étoile", 1'250'000'000,- false, {{"CafeEtoile.exe", 96'000'000, false}, {"redist/vcredist_x64.exe", 14'000'000, true}});+ false, {{"CafeEtoile.exe", 96'000'000, false}, {"redist/vcredist_x64.exe", 14'000'000, true}}, 300);add("m2", "playden/import/Delores", "/mnt/ext1/playden/import/Delores", "Delores", 230'000'000, true,- {{"Delores.exe", 9'000'000, false}});+ {{"Delores.exe", 9'000'000, false}}, 80);add("internal", "playden-import/Hollow Knight", "/data/playden-import/Hollow Knight", "Hollow Knight",- 8'900'000'000, true, {{"hollow_knight.exe", 650'000, false}});+ 8'900'000'000, true, {{"hollow_knight.exe", 650'000, false}}, 1500);add("internal", "playden-import/Tools", "/data/playden-import/Tools", "Tools", 3'000'000, true, {});return candidates;}@@ -1100,8 +1107,12 @@ void Simulation::NotifyImportFailed(const ImportRequest& request, const std::strbool Simulation::SeedGameProgram(GameId id, const std::string& program) {if (!live() || !id.valid() || settings_load_failed_ || game_settings_file_.empty()) return false;if (!rt::ValidateSettingValue(rt::GameRecipe{}, "program", program, nullptr)) return false;+ // Only a record never saved: once the player changed anything (a Program reset included), the+ // choice is theirs.+ if (const auto found = state_.game_settings.find(id);+ found != state_.game_settings.end() && (found->second.revision != 0 || !found->second.overrides.empty()))+ return false;auto& record = state_.game_settings[id];- if (record.overrides.count("program")) return false;record.overrides["program"] = program;++record.revision;save_profile();@@ -3562,15 +3573,22 @@ void Simulation::rebuild_view() {view_.subtitle = import_programs->ascii_ok ? "Choose the program that starts the game." : kImportCopyOnlyText;// The add choice: its folder's candidate, or the game added already (its page's Copy or Move).const LiveImportCandidate* import_choice = nullptr;- std::uint64_t import_choice_bytes = 0;+ std::uint64_t import_choice_bytes = 0, import_choice_files = 0;std::string import_choice_volume;if (modal.id == "import-choice") {if (import_choice_game_.valid()) {const auto* game = find_game(state_, import_choice_game_);if (game && game->install_bytes) import_choice_bytes = *game->install_bytes;+ // An in-place game's size and file count come from the import scan.+ for (const auto& candidate : state_.import_candidates)+ if (candidate.imported == import_choice_game_) {+ if (!import_choice_bytes) import_choice_bytes = candidate.total_bytes;+ import_choice_files = candidate.file_count;+ }if (const auto* external = external_game(import_choice_game_)) import_choice_volume = external->volume_id;} else if ((import_choice = import_candidate(import_programs_key_))) {import_choice_bytes = import_choice->total_bytes;+ import_choice_files = import_choice->file_count;import_choice_volume = import_choice->volume_id;}const bool drop = import_choice_volume == kImportDropVolume;@@ -3967,7 +3985,7 @@ void Simulation::rebuild_view() {else if (modal.id == "import-choice" && action_key == "import-copy") {item.title = "Copy into Playden";item.value = format_bytes(import_choice_bytes);- item.value += (item.value.empty() ? "" : " · ") + import_copy_estimate(import_choice_bytes);+ item.value += (item.value.empty() ? "" : " · ") + import_copy_estimate(import_choice_bytes, import_choice_files);}else if (modal.id == "import-choice" && action_key == "import-move") {item.title = "Move into Playden";@@ -4462,6 +4480,8 @@ void Simulation::rebuild_view() {status.value = job_state_name(copying->state);status.progress = copying->total_bytes == 0 ? 0.0F: static_cast<float>(copying->completed_bytes) / static_cast<float>(copying->total_bytes);+ // A copy that failed (or runs too long) can be cancelled here; the game plays in place again.+ row("details-cancel-copy", RowKind::Action, "Cancel copy", "import-cancel-copy");} else if (const auto* external = in_place ? external_game(game->id) : nullptr; external && external->available) {// Its drive is there: a folder the PS5 can't play from (its name) can still be copied.row("details-copy", RowKind::Action, in_place->volume_id == kImportDropVolume ? "Move into Playden" : "Copy into Playden",@@ -6371,7 +6391,7 @@ void Simulation::activate() {(cloud != state_.cloud.end() && cloud->second.status == CloudStatus::Unsupported);title = "Uninstall this game?";const bool steam = id.store == Store::kSteam;- body = has_title ? uninstall_body_kept+ body = has_title ? (id.store == Store::kLocal ? uninstall_body_kept_imported : uninstall_body_kept): steam ? "The game's files are removed from this console. You can install it again from Steam.": "The game's files are removed from this console.";// Only a store with Cloud saves is worth a word about them.@@ -6396,7 +6416,8 @@ void Simulation::activate() {if (!state_.navigation.modals.empty()) {auto& body = state_.navigation.modals.back().body;const bool batch = pending_destructive_action_ == "installed-selection-uninstall";- const std::string_view kept = batch ? uninstall_batch_body_kept : uninstall_body_kept;+ const std::string_view kept = batch ? uninstall_batch_body_kept+ : state_.navigation.selected_game_id.store == Store::kLocal ? uninstall_body_kept_imported : uninstall_body_kept;const std::string_view deleted = batch ? uninstall_batch_body_deleted : uninstall_body_deleted;const std::string_view from = uninstall_delete_saves_ ? kept : deleted;const std::string_view to = uninstall_delete_saves_ ? deleted : kept;@@ -6570,6 +6591,15 @@ void Simulation::activate() {// An imported game playing from its folder: Copy (a drive) or Move (the drop folder) into Playden.const auto id = state_.navigation.detail_id.value_or(state_.navigation.selected_game_id);if (const auto* external = external_game(id); external && external->available && !import_copy_job(id)) open_import_choice(0, id);+ } else if (action_name == "import-cancel-copy") {+ // The same cancel as Queue's, from the game's page.+ const auto id = state_.navigation.detail_id.value_or(state_.navigation.selected_game_id);+ const auto* job = import_copy_job(id);+ if (!job) return;+ pending_destructive_action_ = "job-cancel-" + job->id;+ ModalEntry confirmation{"confirmation", "Cancel the copy?", state_.navigation.focus_key, {"cancel", "confirm-destructive"}, 0, true};+ confirmation.body = "Stops the copy and deletes what was copied so far. The game keeps playing from its folder.";+ open_modal(std::move(confirmation));} else if (action_name == "import-open-copy") {const auto id = state_.navigation.detail_id.value_or(state_.navigation.selected_game_id);state_.navigation.route = Route::Downloads;diff --git a/src/homebrew/simulation.hpp b/src/homebrew/simulation.hppindex d7125a8..519f732 100644--- a/src/homebrew/simulation.hpp+++ b/src/homebrew/simulation.hpp@@ -222,6 +222,7 @@ struct LiveImportCandidate {bool ascii_ok = false; // can play in placebool partial = false; // the scan stopped at a limit or depthGameId imported; // already in the library as this game; invalid when not+ std::uint64_t file_count = 0; // files in the folder (0 when unknown)bool operator==(const LiveImportCandidate&) const = default;};// Requests for the Local store: look for games, add a candidate (in place), remove an imported game.@@ -709,8 +710,9 @@ public:// Live mode: a request from TakeImportRequests that the Local store refused (an add, copy, move// or removal), with its sentence for the player: shown as a notice, and what waited on it dropped.void NotifyImportFailed(const ImportRequest& request, const std::string& message);- // Writes the program an imported game starts with into its Game settings, unless the player- // chose one already; saved at once so the next preparation reads it. True when it was written.+ // Writes the program an imported game starts with into its Game settings when the game has no+ // saved settings yet (just added); never over anything the player changed, a reset Program+ // included. Saved at once so the next preparation reads it. True when it was written.bool SeedGameProgram(GameId id, const std::string& program);[[nodiscard]] std::vector<GameId> TakeKeptDeleteRequests();// Live mode: maintenance the player confirmed (and settings to apply when the sheetdiff --git a/src/homebrew/view.cpp b/src/homebrew/view.cppindex f88a519..6212dde 100644--- a/src/homebrew/view.cpp+++ b/src/homebrew/view.cpp@@ -3054,8 +3054,13 @@ class Render::ImplCompatibility::Untested : rating->second;const bool installed = installation != nullptr && installation->installed_bytes > 0;// One size for a game: what it takes on the drive (installed, or the install estimate).+ std::optional<std::uint64_t> scanned_bytes; // an imported game playing in place: its folder's size+ for (const auto &candidate : state.import_candidates)+ if (candidate.imported == game->id && candidate.total_bytes > 0)+ scanned_bytes = candidate.total_bytes;const std::string size = installed ? short_size(installation->installed_bytes) :- game->install_bytes ? short_size(*game->install_bytes) : std::string("Unknown");+ game->install_bytes ? short_size(*game->install_bytes) :+ scanned_bytes ? short_size(*scanned_bytes) : std::string("Unknown");const std::string playtime = game->playtime_minutes && *game->playtime_minutes > 0 ?playtime_label(game->playtime_minutes) : std::string("Never played");std::string compat = rating_label(compatibility);diff --git a/src/platform/directory_walk.h b/src/platform/directory_walk.hindex a971f50..6d903cd 100644--- a/src/platform/directory_walk.h+++ b/src/platform/directory_walk.h@@ -20,7 +20,14 @@#endifnamespace playden::platform {-#if defined(PLAYDEN_WALK_BY_PATH)+// Strict: an entry must be the one the parent lists (privileged walks). ReadOnlyFiles: a regular+// file that fails only the inode comparison is still accepted. exFAT/msdosfs numbers an empty file+// (no clusters) differently in readdir than in stat, so every 0-byte file in a game fails the+// comparison. Use it only where the walk reads as the app user, which can't gain anything by+// swapping in a file of its own; directories always keep the strict check.+enum class WalkTrust { kStrict, kReadOnlyFiles };++// The by-path walk is compiled everywhere so host tests can drive it; only PS5 builds use it.namespace walk_detail {struct Opened {std::filesystem::path path;@@ -73,10 +80,9 @@ inline bool ValidName(const char* name) {const std::string text = name ? name : "";return !text.empty() && text != "." && text != ".." && text.find('/') == std::string::npos;}-} // namespace walk_detail// `listed_inode`: the inode the caller read from the parent's listing, saving a second scan.-inline int OpenWalkChild(int parent, const char* name, int flags, std::uint64_t listed_inode = 0) {+inline int OpenChildByPath(int parent, const char* name, int flags, std::uint64_t listed_inode, WalkTrust trust) {std::filesystem::path parent_path;if (!walk_detail::ValidName(name)) { errno = EINVAL; return -1; }if (!walk_detail::PathOf(parent, &parent_path)) return -1;@@ -94,14 +100,26 @@ inline int OpenWalkChild(int parent, const char* name, int flags, std::uint64_tconst std::uint64_t listed = listed_inode ? listed_inode : walk_detail::ListedInode(parent, name);same = listed != 0 && listed == static_cast<std::uint64_t>(opened.st_ino);}+ // Opened without following links and on the parent's device, so a regular file is accepted.+ if (!same && trust == WalkTrust::kReadOnlyFiles && S_ISREG(opened.st_mode) && opened.st_dev == parent_info.st_dev)+ same = true;if (!same) {::close(fd);errno = ESTALE;return -1;}- walk_detail::Remember(fd, path);+ Remember(fd, path);return fd;}+} // namespace walk_detail++#if defined(PLAYDEN_WALK_BY_PATH)+inline int OpenWalkChild(int parent, const char* name, int flags, std::uint64_t listed_inode = 0) {+ return walk_detail::OpenChildByPath(parent, name, flags, listed_inode, WalkTrust::kStrict);+}+inline int OpenWalkChildUnprivileged(int parent, const char* name, int flags, std::uint64_t listed_inode = 0) {+ return walk_detail::OpenChildByPath(parent, name, flags, listed_inode, WalkTrust::kReadOnlyFiles);+}inline int MakeWalkChild(int parent, const char* name, mode_t mode) {std::filesystem::path parent_path;if (!walk_detail::ValidName(name)) { errno = EINVAL; return -1; }@@ -120,6 +138,9 @@ inline int MakeWalkChild(int parent, const char* name, mode_t mode) {inline int OpenWalkChild(int parent, const char* name, int flags, std::uint64_t = 0) {return ::openat(parent, name, flags);}+inline int OpenWalkChildUnprivileged(int parent, const char* name, int flags, std::uint64_t = 0) {+ return ::openat(parent, name, flags);+}inline int MakeWalkChild(int parent, const char* name, mode_t mode) {return ::mkdirat(parent, name, mode);}diff --git a/src/platform/effective_uid.cpp b/src/platform/effective_uid.cppindex 5384264..5d2e365 100644--- a/src/platform/effective_uid.cpp+++ b/src/platform/effective_uid.cpp@@ -25,4 +25,10 @@ std::shared_ptr<void> HoldEffectiveUid() {return std::make_shared<std::unique_lock<std::recursive_mutex>>(RootLock());}+std::shared_ptr<void> TryHoldEffectiveUid() {+ auto lock = std::make_shared<std::unique_lock<std::recursive_mutex>>(RootLock(), std::try_to_lock);+ if (!lock->owns_lock()) return nullptr;+ return lock;+}+} // namespace playden::ps5diff --git a/src/platform/ps5/title_allow_list.h b/src/platform/ps5/title_allow_list.hindex 0b3ac9c..9fe01f9 100644--- a/src/platform/ps5/title_allow_list.h+++ b/src/platform/ps5/title_allow_list.h@@ -36,6 +36,9 @@ bool WithRoot(const std::function<bool()>& work);// 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();+// HoldEffectiveUid without waiting: nothing when another thread holds the token (the runtime+// worker in a batch), so a caller that holds other locks can come back later instead.+std::shared_ptr<void> TryHoldEffectiveUid();// runtime::kTitleRuleAllowList on the console, as root.bool WriteTitleAllowList(const std::string& contents, std::string* error);diff --git a/src/stores/local/copy_plan.cpp b/src/stores/local/copy_plan.cppindex d63a9ef..b86089d 100644--- a/src/stores/local/copy_plan.cpp+++ b/src/stores/local/copy_plan.cpp@@ -208,7 +208,7 @@ CopyPlanBuild BuildCopyPlan(const std::string& source_path, std::size_t max_fileif (name == "." || name == "..") continue;const auto relative = frame.relative.empty() ? name : frame.relative + "/" + name;if (entry->d_type == DT_LNK) return fail(LinkWords(relative), ELOOP);- const int child = platform::OpenWalkChild(frame.fd, name.c_str(), kOpenAny, static_cast<std::uint64_t>(entry->d_fileno));+ const int child = platform::OpenWalkChildUnprivileged(frame.fd, name.c_str(), kOpenAny, static_cast<std::uint64_t>(entry->d_fileno));if (child < 0) {const int error = errno;if (Unsupported(error)) return fail("The game's folder can't be read on this console.", error);diff --git a/src/stores/local/copy_runner.cpp b/src/stores/local/copy_runner.cppindex 3c4ba36..fe32a82 100644--- a/src/stores/local/copy_runner.cpp+++ b/src/stores/local/copy_runner.cpp@@ -92,7 +92,7 @@ class SourceWalk {chain_.push_back(Level{parts[index], fd, {}, false});}Level& folder = chain_.empty() ? root_ : chain_.back();- return platform::OpenWalkChild(folder.fd, parts.back().c_str(), kOpenFile, Listed(folder, parts.back()));+ return platform::OpenWalkChildUnprivileged(folder.fd, parts.back().c_str(), kOpenFile, Listed(folder, parts.back()));}private:diff --git a/src/stores/local/library_source.cpp b/src/stores/local/library_source.cppindex abc43ba..99875af 100644--- a/src/stores/local/library_source.cpp+++ b/src/stores/local/library_source.cpp@@ -1,6 +1,9 @@#include "stores/local/library_source.h"+#include "stores/local/copy_plan.h"+#include <cerrno>+#include <dirent.h>#include <sys/stat.h>#include <algorithm>@@ -215,6 +218,11 @@ std::uint64_t LocalLibrarySource::Reconcile(std::function<installs::InstallSnapsreturn Submit(std::move(job));}+void LocalLibrarySource::SetRuntimeNumber(std::function<std::uint32_t(const GameId&)> runtime_number) {+ std::lock_guard<std::mutex> lock(mutex_);+ runtime_number_ = std::move(runtime_number);+}+std::vector<LibraryEvent> LocalLibrarySource::Pump(std::size_t max_events) {std::lock_guard<std::mutex> lock(mutex_);std::vector<LibraryEvent> result;@@ -334,6 +342,8 @@ void LocalLibrarySource::Execute(const Job& job) {" program=" + job.program);for (auto& candidate : candidates_)if (candidate.volume == job.volume && candidate.folder == folder) candidate.imported_id = added.value().id;+ // Numbered here, on this worker, before the game is listed: the main thread never waits for it.+ WarmRuntimeNumber(job.number_for, added.value().id);++games_revision_;return Outcome(job, true, added.value().id, {});}@@ -403,6 +413,7 @@ void LocalLibrarySource::Execute(const Job& job) {return std::any_of(service.jobs.begin(), service.jobs.end(),[&](const installs::InstallJobView& view) { return view.id == id; });};+ std::set<std::string> numbered; // asked for already, in this passfor (const auto& game : store_.Games()) {if (game.state != ImportState::kCopyQueued && game.state != ImportState::kCopying) continue;const auto id = GameId::Local(game.id);@@ -421,6 +432,7 @@ void LocalLibrarySource::Execute(const Job& job) {const auto source = HostPath(Join(volume->mount, game.folder));if (::lstat(source.c_str(), &info) != 0 && errno == ENOENT) {const auto number = job.number_for ? job.number_for(id) : 0u;+ numbered.insert(game.id);const auto failure = config_.move_into_playden(game, source, number);Log("import move reconciled id=" + game.id + (failure.empty() ? " copied" : ": " + failure));changed = true;@@ -440,6 +452,34 @@ void LocalLibrarySource::Execute(const Job& job) {Log("import copy job cancelled id=" + view.id.value + " (not being copied)");job.cancel_job(view.id);}+ // Copy plan folders no copy owns: a stop between the plan being saved and its job queued+ // (Enqueue), or a copy put back in place above. Its game is gone or plays in place, the+ // service has no job or install for it. Enqueue runs on this worker too, so none is half made.+ if (config_.remove_copy_folder)+ for (const auto& volume : service.volumes) {+ if (!volume.available || volume.games_root.empty()) continue;+ DIR* folder = ::opendir(volume.games_root.c_str());+ if (!folder) continue;+ std::vector<std::string> roots;+ while (const auto* item = ::readdir(folder)) {+ const auto key = ParseKey(item->d_name);+ if (!key || key->store != Store::kLocal || queued(*key) || installed(*key)) continue;+ const auto game = store_.Find(key->value);+ if (game && game->state != ImportState::kInPlace) continue;+ const auto root = volume.games_root + "/" + item->d_name;+ struct stat journal {};+ if (::lstat((root + "/" + kCopyJournalDir).c_str(), &journal) == 0 && S_ISDIR(journal.st_mode))+ roots.push_back(root);+ }+ ::closedir(folder);+ for (const auto& root : roots) {+ const bool removed = config_.remove_copy_folder(root);+ Log("import copy folder " + std::string(removed ? "removed" : "not removed") + " root=" + root ++ " (no copy owns it)");+ }+ }+ for (const auto& game : store_.Games())+ if (!numbered.count(game.id)) WarmRuntimeNumber(job.number_for, game.id);if (changed) ++games_revision_;return Outcome(job, true, {}, {});}@@ -458,6 +498,15 @@ void LocalLibrarySource::Execute(const Job& job) {}}+void LocalLibrarySource::WarmRuntimeNumber(const std::function<std::uint32_t(const GameId&)>& given, const std::string& id) {+ std::function<std::uint32_t(const GameId&)> number_for = given;+ if (!number_for) {+ std::lock_guard<std::mutex> lock(mutex_);+ number_for = runtime_number_;+ }+ if (number_for) number_for(GameId::Local(id));+}+void LocalLibrarySource::Outcome(const Job& job, bool ok, std::string id, std::string message) {outcomes_.push_back({job.request, ok, std::move(id), std::move(message)});if (outcomes_.size() > kMaxOutcomes) outcomes_.erase(outcomes_.begin());diff --git a/src/stores/local/library_source.h b/src/stores/local/library_source.hindex f6a6cfc..5987a75 100644--- a/src/stores/local/library_source.h+++ b/src/stores/local/library_source.h@@ -94,6 +94,10 @@ struct LocalLibraryConfig {// empty string, or a sentence for the player. Empty: games can't be moved.std::function<std::string(const ImportEntry& entry, const std::string& source, std::uint32_t runtime_number)>move_into_playden;+ // Deletes a copy's folder (<games_root>/local-<id>, holding a copy plan) that no copy owns any+ // more; LocalCopyRunner::Remove, which only deletes what Playden recognizes as its own. Reconcile+ // calls it. Empty: such folders stay.+ std::function<bool(const std::string& root)> remove_copy_folder;};// The words for a game that can't play from its folder because of its name (the descriptor rule).@@ -155,11 +159,18 @@ class LocalLibrarySource final : public LibrarySource {// as an install goes back to in_place, unless it is a move whose rename happened (its drop// folder is gone): that one is finished (move_into_playden, with `runtime_number`'s number); and// a copy job whose game isn't being copied (back in place, or gone) is cancelled, which removes- // its partial folder.+ // its partial folder. Last, a copy plan folder in an available games folder that no copy owns (a+ // stop between saving the plan and queuing its job; a game back in place, or gone) is removed+ // (LocalLibraryConfig::remove_copy_folder).std::uint64_t Reconcile(std::function<installs::InstallSnapshot()> installs,std::function<void(const GameId&)> cancel_job,std::function<std::uint32_t(const GameId&)> runtime_number = {});+ // The runtime's number for a game, which may wait for the runtime worker: called on this store's+ // worker for every game it adds and for every game at Reconcile, so the number is known (and the+ // runtime's cache warm) before the main thread, which must never wait, asks for it.+ void SetRuntimeNumber(std::function<std::uint32_t(const GameId&)> runtime_number);+std::shared_ptr<const LocalSnapshot> Snapshot() const;// Cheap: a copy of the last projection.std::vector<installs::InstalledLocation> Locations() const;@@ -180,6 +191,7 @@ class LocalLibrarySource final : public LibrarySource {std::uint64_t Submit(Job job);void Run();void Execute(const Job& job);+ void WarmRuntimeNumber(const std::function<std::uint32_t(const GameId&)>& given, const std::string& id);void EnsureLoaded();bool CheckPresence(); // true when the present volumes changedvoid Scan();@@ -201,6 +213,7 @@ class LocalLibrarySource final : public LibrarySource {std::vector<ImportOutcome> outcomes_;std::uint64_t games_revision_ = 0;+ std::function<std::uint32_t(const GameId&)> runtime_number_; // guarded by mutex_mutable std::mutex mutex_;std::condition_variable wake_;std::deque<Job> pending_;diff --git a/src/stores/local/scanner.cpp b/src/stores/local/scanner.cppindex fbafcd8..f1724ab 100644--- a/src/stores/local/scanner.cpp+++ b/src/stores/local/scanner.cpp@@ -208,7 +208,7 @@ FolderScan ScanGameFolder(const std::string& folder_path) {if (name.front() == '.') continue;if (entry->d_type == DT_LNK) continue;const auto listed = static_cast<std::uint64_t>(entry->d_fileno);- const int child = platform::OpenWalkChild(frame.fd, name.c_str(), kOpenAny, listed);+ const int child = platform::OpenWalkChildUnprivileged(frame.fd, name.c_str(), kOpenAny, listed);if (child < 0) {const int error = errno;if (Unsupported(error)) { scan.error = error; status = ScanStatus::kUnsupported; break; }@@ -261,7 +261,8 @@ ProgramCheck CheckProgram(const std::string& folder, const std::string& program)const auto parts = Split(program);for (std::size_t i = 0; i < parts.size(); ++i) {const bool last = i + 1 == parts.size();- const int child = platform::OpenWalkChild(fd, parts[i].c_str(), last ? kOpenAny : kOpenFolder);+ const int child = last ? platform::OpenWalkChildUnprivileged(fd, parts[i].c_str(), kOpenAny)+ : platform::OpenWalkChild(fd, parts[i].c_str(), kOpenFolder);const int error = errno;::close(fd);if (child < 0) {diff --git a/tests/homebrew_installed_locations_test.cpp b/tests/homebrew_installed_locations_test.cppindex 9cc2bed..ca56e14 100644--- a/tests/homebrew_installed_locations_test.cpp+++ b/tests/homebrew_installed_locations_test.cpp@@ -2,9 +2,11 @@// Task 2.5) and never reaches Steam Cloud (Task 2.6), against a real RuntimeHost.#include "homebrew/controller.hpp"#include "homebrew/runtime_host.hpp"+#include "runtime_host_fixture.h"#include "stores/local/library_source.h"#include "fake_library_source.h"#include "platform/managed_directory.h"+#include "platform/ps5/title_allow_list.h"#include "platform/storage.h"#include "runtime/layout_migration.h"#include "runtime/settings_storage.h"@@ -32,129 +34,21 @@using namespace playden::homebrew;using namespace playden::runtime;using namespace playden::ps5;-#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "%s:%d: CHECK failed: %s\n", __FILE__, __LINE__, #x); std::exit(1); } } while (0)+using namespace playden::test::runtime_host;namespace fs = std::filesystem;namespace {-std::string g_runtime_dir; // the repository's bundled runtime data (recipes, presets, input)--void Write(const fs::path& path, const std::string& bytes, unsigned mode) {- fs::create_directories(path.parent_path());- std::ofstream(path, std::ios::binary | std::ios::trunc) << bytes;- CHECK(chmod(path.c_str(), mode) == 0);-}unsigned Mode(const fs::path& path) {struct stat info{};CHECK(lstat(path.c_str(), &info) == 0);return info.st_mode & 07777;}-std::string Read(const fs::path& path) {- std::ifstream in(path, std::ios::binary);- return {std::istreambuf_iterator<char>(in), {}};-}--struct Fixture {- fs::path root;- unsigned database_reads = 0, registry_mutations = 0;- bool registered = false;- // ShadowMountPlus postpones scans while a title runs: with registers false a- // submission is accepted and listed, but not installed until registered is set.- bool registers = true, submitted = false;- std::shared_ptr<std::atomic<int>> activity = std::make_shared<std::atomic<int>>(static_cast<int>(NativeActivity::kStopped));- Fixture() {- char name[] = "/tmp/playden-runtime-host-XXXXXX"; CHECK(mkdtemp(name));- root = fs::canonical(name);- fs::create_directories(root / "data/homebrew");- }- ~Fixture() { std::error_code ignored; fs::remove_all(root, ignored); }- RuntimeHostConfig Config() {- RuntimeHostConfig config;- config.boundary = root / "data";- config.state_root = root / "data/runtime-state";- config.homebrew_root = root / "data/homebrew";- config.native.database = [this](const std::string& title) {- ++database_reads;- if (!registered) return TitleDatabaseObservation{TitleAvailability::kFree, {}};- return TitleDatabaseObservation{TitleAvailability::kOccupied,- InstalledTitleIdentity{title, "UP9000-FAKE78001_00-PROSPEROWIN00001", "/user/app/FAKE78001/sce_sys"}};- };- config.native.activity = [activity = activity](const std::string&) { return static_cast<NativeActivity>(activity->load()); };- // ShadowMount loopback API: registration makes the title appear installed.- config.registry_transport = [this](const std::string& route, const std::string&) -> std::optional<std::string> {- if (route != "/api/v1/games") { ++registry_mutations; submitted = true; registered = registers; return R"({"status":0})"; }- if (!registered && submitted)- return R"({"status":0,"games":[{"title_id":"FAKE78001","installed":false,"managed":true,)"- R"("source_available":true,"source_type":"folder","path":"/data/homebrew/FAKE78001"}]})";- if (!registered) return R"({"status":0,"games":[]})";- return R"({"status":0,"games":[{"title_id":"FAKE78001","installed":true,"managed":true,)"- R"("source_available":true,"source_type":"folder","path":"/data/homebrew/FAKE78001"}]})";- };- config.admit_kit = [](std::string* reason) -> std::optional<RuntimeKit> {- *reason = "No verified compatibility kit is installed.";- return std::nullopt;- };- config.runtime_dir = g_runtime_dir;- return config;- }-};-// Generous: a loaded build machine (parallel ctest, other builds) can stretch a step past 10 s.-RuntimeSnapshot WaitFor(const RuntimeHost& host, const std::function<bool(const RuntimeSnapshot&)>& done,- int seconds = 30) {- const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(seconds);- for (;;) {- auto snapshot = host.Snapshot();- if (done(snapshot)) return snapshot;- CHECK(std::chrono::steady_clock::now() < deadline);- std::this_thread::sleep_for(std::chrono::milliseconds(2));- }-}-bool Started(const RuntimeSnapshot& s) { return s.status != RuntimeHostStatus::kStarting; }std::uint32_t NumberOf(const RuntimeSnapshot& s, const playden::GameId& game) {for (const auto& [number, id] : s.runtime_games)if (id == game) return number;return 0;}--// A synthetic admitted kit with the production file layout, real SHA-256 and-// the repository's HL2 recipe. It is not a runnable Wine runtime.-RuntimeKit SyntheticKit(const fs::path& kit, const std::string& eboot = "native",- const std::string& kit_id = "kit-1", char files_digest = 'a',- const std::string& runtime = "runtime", const std::string& revision = "rev") {- Write(kit / "titles/variant/eboot.bin", eboot, 0755);- Write(kit / "titles/variant/sce_sys/param.json",- "{\n \"contentId\": \"UP9000-FAKE78001_00-PROSPEROWIN00001\",\n \"localizedParameters\": {\n"- " \"en-US\": {\n \"titleName\": \"Prospero Win\"\n }\n },\n \"titleId\": \"FAKE78001\"\n}\n", 0644);- Write(kit / "titles/variant/sce_sys/icon0.png", "kit-icon", 0644);- Write(kit / ("runtime/wine/" + revision + "/lib/core.prx"), runtime, 0755);- Write(kit / "template/bottle/system.reg", "WINE REGISTRY Version 2\n", 0644);- Write(kit / "template/bottle/user.reg", "WINE REGISTRY Version 2\n", 0644);- Write(kit / "template/bottle/drive_c/windows/win.ini", "", 0644);- Write(kit / "template/bottle/dosdevices/.pw-symlinks", "c:\t../drive_c\nz:\t/\n", 0644);- Write(kit / "recipes/hl2.json", Read(fs::path(g_runtime_dir) / "recipes/steam-220-hl2-v1.json"), 0644);- RuntimeKit admitted;- auto& view = admitted.view;- view.root = kit; view.kit_id = kit_id; view.files_sha256 = std::string(64, files_digest);- view.runtime = {"wine-wow64", revision, "runtime/wine/" + revision};- view.template_path = "template/bottle";- view.template_drive_table = "template/bottle/dosdevices/.pw-symlinks";- view.recipe = {"steam-220-hl2-v1", "1", "recipes/hl2.json", *HashArtifactFile(kit / "recipes/hl2.json")};- view.variants.push_back({"variant", "FAKE78001", "titles/variant"});- for (const auto& [path, mode] : std::vector<std::pair<std::string, unsigned>>{- {"titles/variant/eboot.bin", 0755}, {"titles/variant/sce_sys/param.json", 0644},- {"titles/variant/sce_sys/icon0.png", 0644},- {"runtime/wine/" + revision + "/lib/core.prx", 0755}, {"template/bottle/system.reg", 0644},- {"template/bottle/user.reg", 0644}, {"template/bottle/drive_c/windows/win.ini", 0644},- {"template/bottle/dosdevices/.pw-symlinks", 0644}, {"recipes/hl2.json", 0644}})- view.files.push_back({path, fs::file_size(kit / path), *HashArtifactFile(kit / path), mode});- view.artifacts = {- {"runtime", revision, *HashArtifactFile(kit / ("runtime/wine/" + revision + "/lib/core.prx")),- ImmutableArtifactLocation::kStagedTitle, "win/wine/lib/core.prx"},- {"recipe", "steam-220-hl2-v1-1", *HashArtifactFile(kit / "recipes/hl2.json"),- ImmutableArtifactLocation::kKit, "recipes/hl2.json"}};- admitted.capabilities = {"dxvk", "game-root-unowned", "offline_bottle", "per_game_title", "wow64_i386"};- return admitted;-}} // namespacenamespace {@@ -456,6 +350,125 @@ void ImportedGamePreparesWithoutSteam() {host.Shutdown();}+// The application thread never waits for the runtime worker. A Local game that never got a number+// this session needs one written to installs.json under the effective-UID hold, which the worker+// keeps through a batch: Prepare for it must not freeze the frame. Each tick returns at once, the+// request stays and the preparation happens once the hold is released.+void FirstPrepareOfAnImportedGameNeverWaitsForTheWorker() {+ using playden::GameId;+ using playden::installs::InstalledLocation;+ namespace hb = playden::homebrew;+ const auto local = GameId::Local("7c9e6679-7425-40de-944b-e07fc1f90ae7");+ 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");+ };+ const auto kit = SyntheticKit(fixture.root / "kit");+ config.admit_kit = [&kit](std::string*) { return std::optional<RuntimeKit>(kit); };+ unsigned uuids = 0;+ config.uuid = [&uuids]() -> std::optional<std::string> {+ ++uuids; return std::string("00000000-0000-4000-8000-0000000000") + (uuids < 10 ? "0" : "") + std::to_string(uuids);+ };+ config.unix_time = [] { return std::int64_t{1760000000}; };+ config.settings_record = [&](const GameId&) -> std::optional<GameSettingsRecord> {+ GameSettingsRecord record;+ record.overrides["program"] = "Bin/Game.exe";+ return record;+ };+ config.hold_effective_uid = playden::ps5::HoldEffectiveUid;+ config.try_hold_effective_uid = [](bool* busy) {+ auto held = playden::ps5::TryHoldEffectiveUid();+ *busy = !held;+ return held;+ };+ std::string pe(0x80 + 26, '\0');+ pe[0] = 'M'; pe[1] = 'Z'; pe[0x3c] = 0x40; pe[0x40] = 'P'; pe[0x41] = 'E';+ pe[0x44] = 0x64; pe[0x45] = static_cast<char>(0x86); pe[0x40 + 24] = 0x0b; pe[0x40 + 25] = 0x02;+ const std::string console_root = "/data/playden-import/Second";+ Write(fixture.root / "data/playden-import/Second/Bin/Game.exe", pe, 0644);+ CHECK(chmod((fixture.root / "data/playden-import/Second").c_str(), 0755) == 0);++ hb::Simulation model({}, {}, hb::ModelMode::Live);+ MemorySessions sessions;+ RestoringBackend backend;+ playden::stores::Registry registry;+ registry.Add(std::make_unique<playden::stores::SteamAccount>(backend, sessions));+ auto imported = std::make_unique<playden::test::FakeLibrarySource>();+ registry.Add(std::make_unique<playden::test::FakeLibrarySource>(playden::Store::kSteam));+ imported->games = {playden::test::ImportedGame("7c9e6679-7425-40de-944b-e07fc1f90ae7", "Second import")};+ registry.Add(std::move(imported));+ RuntimeHost host(config);+ CHECK(host.Start());+ hb::Controller controller(model, registry, nullptr, nullptr, nullptr, &host);+ controller.SetExternalLocations([&] {+ return std::vector<InstalledLocation>{{local, console_root, "usb0", true, InstalledLocation::Ownership::kExternal}};+ });+ // One tick, timed: the frame must not wait on the worker's hold.+ std::chrono::steady_clock::duration slowest{};+ const auto tick = [&] {+ const auto before = std::chrono::steady_clock::now();+ controller.Tick();+ slowest = std::max(slowest, std::chrono::steady_clock::now() - before);+ };+ const auto tick_until = [&](const std::function<bool(const RuntimeSnapshot&)>& done) {+ const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(60);+ for (;;) {+ tick();+ const auto snapshot = host.Snapshot();+ if (done(snapshot)) return snapshot;+ CHECK(std::chrono::steady_clock::now() < deadline);+ std::this_thread::sleep_for(std::chrono::milliseconds(2));+ }+ };+ tick_until([&](const RuntimeSnapshot& s) {+ return s.status == RuntimeHostStatus::kReady && model.state().runtime == hb::RuntimeState::Ready &&+ std::any_of(model.state().games.begin(), model.state().games.end(), [&](const hb::Game& game) { return game.id == local; });+ });+ CHECK(NumberOf(host.Snapshot(), local) == 0); // never numbered this session+ // Another thread (the worker, in a batch) holds the effective UID.+ std::mutex hold_mutex;+ std::condition_variable hold_changed;+ bool holding = false, release = false;+ std::thread holder([&] {+ auto held = playden::ps5::HoldEffectiveUid();+ std::unique_lock<std::mutex> lock(hold_mutex);+ holding = true;+ hold_changed.notify_all();+ hold_changed.wait(lock, [&] { return release; });+ });+ {+ std::unique_lock<std::mutex> lock(hold_mutex);+ CHECK(hold_changed.wait_for(lock, std::chrono::seconds(10), [&] { return holding; }));+ }+ model.RequestRuntimePrepare(local);+ const auto until = std::chrono::steady_clock::now() + std::chrono::milliseconds(400);+ while (std::chrono::steady_clock::now() < until) {+ tick();+ std::this_thread::sleep_for(std::chrono::milliseconds(2));+ }+ CHECK(slowest < std::chrono::milliseconds(200)); // none of those ticks waited for the hold+ CHECK(host.Snapshot().prepares_handled == 0 && NumberOf(host.Snapshot(), local) == 0);+ {+ std::lock_guard<std::mutex> lock(hold_mutex);+ release = true;+ }+ hold_changed.notify_all();+ holder.join();+ // The hold released, the request that waited goes through, once.+ const auto done = tick_until([](const RuntimeSnapshot& s) { return s.prepares_handled > 0 && !s.preparing_app; });+ CHECK(NumberOf(done, local) != 0);+ CHECK(done.prepares_handled == 1);+ controller.Shutdown();+ host.Shutdown();+}+// The Local store end to end (import-games Task 3.3): a folder on a USB drive is found, added and// listed with its title; Details offers Play, which prepares it from its folder with the program// chosen at add (written into Game settings first) under a runtime number from 0xF0000000. An@@ -525,6 +538,8 @@ void ImportedGamePlaysInPlace() {// The drop folder's games: FTP leaves them root-owned, simulated by telling the walk the app user// is someone else; the fake root raise runs the work and is counted.std::atomic<unsigned> drop_raises{0};+ std::atomic<unsigned> drop_opens{0};+ std::atomic<bool> hold_opens{false};// imports.json sits next to installs.json, in the folder the runtime host makes private at its start.playden::Storage import_storage((fixture.root / "data/runtime-state").string());std::string id;@@ -548,7 +563,13 @@ void ImportedGamePlaysInPlace() {drop_access.namespace_root = fixture.root;drop_access.app_uid = ::geteuid() + 1;drop_access.as_root = [&drop_raises](const std::function<bool()>& work) { ++drop_raises; return work(); };- local_config.open_drop_folder = local::MakeDropFolderOpener(drop_access);+ // Counted, and held while hold_opens is set (an opening that takes too long).+ local_config.open_drop_folder = [&drop_opens, &hold_opens, opener = local::MakeDropFolderOpener(drop_access)](+ const std::string& path) {+ while (hold_opens.load()) std::this_thread::sleep_for(std::chrono::milliseconds(2));+ ++drop_opens;+ return opener(path);+ };RuntimeHost host(config);CHECK(host.Start());WaitFor(host, Started);@@ -744,7 +765,7 @@ void ImportedGamePlaysInPlace() {// A game copied over FTP into the drop folder: its files are opened when it is added and again// before each Play; a link out of its folder stops Play with the folder named.const auto sky = fixture.root / "data/playden-import/Sky";- run(false, [&](hb::Simulation& model, hb::Controller&, RuntimeHost& host, local::LocalLibrarySource& source,+ run(false, [&](hb::Simulation& model, hb::Controller& controller, RuntimeHost& host, local::LocalLibrarySource& source,const std::function<void(const std::function<bool()>&)>& tick_until) {Write(sky / "Game.exe", pe + std::string(4096, 'x'), 0755);Write(sky / "Data/sky.ini", "[sky]", 0644);@@ -801,6 +822,55 @@ void ImportedGamePlaysInPlace() {});CHECK(launched.size() == before);CHECK(unlink((sky / "Data/out").c_str()) == 0);+ const auto dismiss = [&] {+ for (int i = 0; i < 8 && !model.state().navigation.modals.empty(); ++i)+ if (!(model.action("focus:alert-ok") && model.action("cross"))) model.action("circle");+ CHECK(model.state().navigation.modals.empty());+ };+ dismiss();++ // Recreate bottle prepares the game again only once its files are opened.+ CHECK(chmod((sky / "Data/sky.ini").c_str(), 0644) == 0);+ const auto opens_before = drop_opens.load();+ open_details(model, game);+ CHECK(model.action("focus:details-more") && model.action("cross"));+ CHECK(model.action("focus:game-maintenance") && model.action("cross"));+ // The sheet asks whether the game runs first.+ tick_until([&] { const auto* row = row_of(model, "maintenance-recreate"); return row && row->enabled; });+ CHECK(model.action("focus:maintenance-recreate") && model.action("cross"));+ CHECK(model.action("focus:confirm-destructive") && model.action("cross"));+ tick_until([&] {+ const auto found = model.state().runtime_games.find(game);+ return found != model.state().runtime_games.end() && found->second.maintenance == hb::MaintenanceKind::RecreateBottle &&+ !found->second.maintenance_running;+ });+ {+ const auto& recreated = model.state().runtime_games.at(game);+ if (!recreated.maintenance_ok) std::fprintf(stderr, "Recreate: %s\n", recreated.maintenance_message.c_str());+ CHECK(recreated.maintenance_ok);+ }+ CHECK(drop_opens.load() > opens_before && Mode(sky / "Data/sky.ini") == 0666);+ dismiss();++ // An opening with no outcome in time stops Play with a sentence instead of waiting forever.+ for (int i = 0; i < 8 && model.state().navigation.route != hb::Route::Home; ++i) model.action("circle");+ hold_opens = true;+ controller.SetDropFolderOpenTimeout(std::chrono::milliseconds(200));+ const auto plays_before = launched.size();+ open_details(model, game);+ CHECK(model.action("focus:details-play") && model.action("cross"));+ tick_until([&] {+ const auto& modals = model.state().navigation.modals;+ if (modals.empty()) return false;+ if (modals.back().body.find("Playden couldn't open the game's folder in time.") != std::string::npos) return true;+ // The recreated title never starts either: its own "Can't play" may come up first.+ CHECK(model.action("focus:alert-ok") && model.action("cross"));+ return false;+ });+ hold_opens = false;+ controller.SetDropFolderOpenTimeout(std::chrono::seconds(60));+ for (int i = 0; i < 50; ++i) { controller.Tick(); std::this_thread::sleep_for(std::chrono::milliseconds(2)); }+ CHECK(launched.size() == plays_before);});}@@ -809,6 +879,7 @@ int main(int argc, char** argv) {g_runtime_dir = argv[1];ExternalGameRegistersAfterRestartWithoutCloud();ImportedGamePreparesWithoutSteam();+ FirstPrepareOfAnImportedGameNeverWaitsForTheWorker();ImportedGamePlaysInPlace();std::puts("installed locations tests passed");return 0;diff --git a/tests/homebrew_library_model_test.cpp b/tests/homebrew_library_model_test.cppindex bde0dd5..080f2b1 100644--- a/tests/homebrew_library_model_test.cpp+++ b/tests/homebrew_library_model_test.cpp@@ -2594,7 +2594,7 @@ void live_import_choice_and_details() {{"usb1", "USB drive 2", true, 900'000'000'000, 500'000'000'000}}, "internal");LiveImportCandidate rally;rally.volume_id = "usb0"; rally.folder = "playden/import/Rally"; rally.path = "/mnt/usb0/playden/import/Rally";- rally.title = "Rally"; rally.total_bytes = 8'900'000'000; rally.ascii_ok = true;+ rally.title = "Rally"; rally.total_bytes = 8'900'000'000; rally.ascii_ok = true; rally.file_count = 5000;rally.programs = {{"Rally.exe", 9'000'000, false}};LiveImportCandidate cafe = rally;cafe.folder = "playden/import/Café"; cafe.path = "/mnt/usb0/playden/import/Café"; cafe.title = "Café"; cafe.ascii_ok = false;@@ -2624,7 +2624,7 @@ void live_import_choice_and_details() {activate(model, "import-candidate-usb0:playden/import/Rally");activate(model, "import-program-0");check(find_row(model, "import-play-in-place")->title == "Play from the drive" &&- find_row(model, "import-copy")->value == "8.9 GB · about 14 min" && !has_row(model, "import-move") &&+ find_row(model, "import-copy")->value == "8.9 GB · about 4 min" && !has_row(model, "import-move") &&find_row(model, "storage-picker")->title == "Copy to" && find_row(model, "storage-picker")->value == "Console storage","a drive folder plays from there or is copied, with its size, time and drive");activate(model, "storage-picker");@@ -2659,6 +2659,11 @@ void live_import_choice_and_details() {check(find_row(model, "details-copy") && find_row(model, "details-copy")->title == "Copy into Playden" &&find_row(model, "details-remove") && !has_row(model, "details-cloud") && !has_row(model, "details-uninstall"),"an imported game on a drive offers Copy into Playden and Remove from library");+ // The page's sheet shows the size and estimate the add flow showed (from the scan, the game has no size).+ activate(model, "details-copy");+ check(model.view().surface == "import-choice" && find_row(model, "import-copy")->value == "8.9 GB · about 4 min",+ "the page's copy sheet has the folder's size and the same estimate");+ model.action("circle");// A folder the PS5 can't play from (its name) still offers the copy.model.UpdateExternalGames({{id, "usb0", true, "The game's folder name has characters the PS5 can't play from."}});check(has_row(model, "details-installed") && has_row(model, "details-copy") && has_row(model, "details-remove"),@@ -2669,11 +2674,36 @@ void live_import_choice_and_details() {check(copying && copying->title == "Copying" && copying->progress > 0.49F && copying->progress < 0.51F &&!has_row(model, "details-copy") && !find_row(model, "details-remove")->enabled,"the copy's progress replaces Copy into Playden");+ // A failed copy can be cancelled from the page; the game plays in place again.+ model.UpdateInstalls({{id, playden::homebrew::JobState::Failed, 4'450'000'000, 8'900'000'000, "Copy failed", "usb1"}}, {});+ check(find_row(model, "details-cancel-copy") && !find_row(model, "details-remove")->enabled, "a failed copy offers Cancel copy");+ activate(model, "details-cancel-copy");+ check(model.view().surface == "confirmation", "Cancel copy asks first");+ activate(model, "confirm-destructive");+ const auto cancels = model.TakeInstallRequests();+ check(cancels.size() == 1 && cancels[0].kind == playden::homebrew::InstallRequestKind::Cancel && cancels[0].game_id == id,+ "Cancel copy cancels the copy job like Queue does");+ model.UpdateInstalls({}, {});+ check(has_row(model, "details-copy") && !has_row(model, "details-cancel-copy") && find_row(model, "details-remove")->enabled,+ "after the cancel the game plays in place again");// Copied: Uninstall, not Remove from library.model.UpdateInstalls({}, {{id, 8'900'000'000, "usb1", true}});model.UpdateExternalGames({});check(has_row(model, "details-uninstall") && !has_row(model, "details-remove") && !has_row(model, "details-copy"),"a copied game uninstalls");+ playden::homebrew::LiveRuntimeGame titled;+ titled.game_id = id; titled.status = "Ready"; titled.ready = true; titled.can_play = true; titled.has_title = true;+ model.UpdateRuntime(playden::homebrew::RuntimeState::Ready, {titled});+ activate(model, "details-uninstall");+ check(model.state().navigation.modals.back().body.find("adding the game again brings them back") != std::string::npos &&+ model.state().navigation.modals.back().body.find("installing") == std::string::npos,+ "an imported game's uninstall dialog says adding it again brings the saves back");+ activate(model, "uninstall-delete-saves");+ activate(model, "uninstall-delete-saves");+ check(model.state().navigation.modals.back().body.find("adding the game again") != std::string::npos,+ "the saves choice keeps the imported wording");+ model.action("circle");+ model.TakeInstallRequests();// A refused copy or add is said to the player.model.NotifyImportFailed({ImportRequestKind::CopyIntoPlayden, id, "usb1"}, "Not enough space on USB drive 2.");diff --git a/tests/homebrew_live_model_test.cpp b/tests/homebrew_live_model_test.cppindex c927b38..739d605 100644--- a/tests/homebrew_live_model_test.cpp+++ b/tests/homebrew_live_model_test.cpp@@ -740,6 +740,43 @@ void live_imported_game_steam_app_id(const std::filesystem::path& base) {check(saved() == 0, "an empty Steam app ID clears it");}+// The program chosen when a game was imported goes into its Game settings only while it has none+// saved: a Program the player reset (or changed) in Game settings stays theirs at the next prepare.+void live_imported_program_seeds_once(const std::filesystem::path& base) {+ std::filesystem::create_directories(base);+ std::filesystem::permissions(base, std::filesystem::perms::owner_all);+ const auto file = base / "seed-settings.json";+ const auto fresh = playden::GameId::Local("1b4e28ba-2fa1-41d2-883f-0016d3cca427");+ const auto reset = playden::GameId::Local("6fa459ea-ee8a-4ca4-894e-db77e160355e");+ const auto chosen = playden::GameId::Local("16fd2706-8baf-433b-82eb-8c7fada847da");+ playden::runtime::GameSettingsRecord was_reset; // Program reset to the recipe's: no override, saved+ was_reset.revision = 2;+ playden::runtime::GameSettingsRecord was_chosen;+ was_chosen.revision = 1;+ was_chosen.overrides["program"] = "Other.exe";+ std::string reason;+ check(playden::runtime::SaveGameSettingsFile(file.string(), {{reset, was_reset}, {chosen, was_chosen}}, &reason),+ "seed: settings written");+ auto model = make_live(base);+ model.SetGameSettingsFile(file);+ check(model.SeedGameProgram(fresh, "Bin/Game.exe") &&+ model.state().game_settings.at(fresh).overrides.at("program") == "Bin/Game.exe",+ "seed: a game with no saved settings gets its program");+ check(!model.SeedGameProgram(fresh, "Bin/Other.exe") &&+ model.state().game_settings.at(fresh).overrides.at("program") == "Bin/Game.exe",+ "seed: written once");+ check(!model.SeedGameProgram(reset, "Bin/Game.exe") && !model.state().game_settings.at(reset).overrides.count("program") &&+ model.state().game_settings.at(reset).revision == 2,+ "seed: a Program the player reset stays reset");+ check(!model.SeedGameProgram(chosen, "Bin/Game.exe") &&+ model.state().game_settings.at(chosen).overrides.at("program") == "Other.exe",+ "seed: a Program the player chose stays");+ std::map<playden::GameId, playden::runtime::GameSettingsRecord> loaded;+ check(playden::runtime::LoadGameSettingsFile(file.string(), &loaded, &reason) &&+ loaded.at(fresh).overrides.at("program") == "Bin/Game.exe" && !loaded.at(reset).overrides.count("program"),+ "seed: saved at once");+}+} // namespaceint main() {@@ -754,6 +791,7 @@ int main() {live_settings_follow_the_prepared_title(base);live_program_change_applies_like_other_settings(base);live_imported_game_steam_app_id(base);+ live_imported_program_seeds_once(base);live_starts_clean_and_never_reads_or_writes_fixtures(base);live_dispatches_bounded_service_effects_and_replaces_challenges(base);failed_signout_preserves_account_until_external_clear(base);diff --git a/tests/homebrew_runtime_host_test.cpp b/tests/homebrew_runtime_host_test.cppindex 48b0a44..a20f2bf 100644--- a/tests/homebrew_runtime_host_test.cpp+++ b/tests/homebrew_runtime_host_test.cpp@@ -1,5 +1,7 @@#include "homebrew/runtime_host.hpp"+#include "runtime_host_fixture.h"#include "platform/managed_directory.h"+#include "platform/ps5/title_allow_list.h"#include "platform/storage.h"#include "runtime/layout_migration.h"#include "runtime/artifact_hash.h"@@ -20,86 +22,17 @@#include <thread>#include <atomic>#include <condition_variable>+#include <future>#include <memory>#include <unistd.h>using namespace playden::homebrew;using namespace playden::runtime;using namespace playden::ps5;-#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "%s:%d: CHECK failed: %s\n", __FILE__, __LINE__, #x); std::exit(1); } } while (0)+using namespace playden::test::runtime_host;namespace fs = std::filesystem;namespace {-std::string g_runtime_dir; // the repository's bundled runtime data (recipes, presets, input)--void Write(const fs::path& path, const std::string& bytes, unsigned mode) {- fs::create_directories(path.parent_path());- std::ofstream(path, std::ios::binary | std::ios::trunc) << bytes;- CHECK(chmod(path.c_str(), mode) == 0);-}-std::string Read(const fs::path& path) {- std::ifstream in(path, std::ios::binary);- return {std::istreambuf_iterator<char>(in), {}};-}--struct Fixture {- fs::path root;- unsigned database_reads = 0, registry_mutations = 0;- bool registered = false;- // ShadowMountPlus postpones scans while a title runs: with registers false a- // submission is accepted and listed, but not installed until registered is set.- bool registers = true, submitted = false;- std::shared_ptr<std::atomic<int>> activity = std::make_shared<std::atomic<int>>(static_cast<int>(NativeActivity::kStopped));- Fixture() {- char name[] = "/tmp/playden-runtime-host-XXXXXX"; CHECK(mkdtemp(name));- root = fs::canonical(name);- fs::create_directories(root / "data/homebrew");- }- ~Fixture() { std::error_code ignored; fs::remove_all(root, ignored); }- RuntimeHostConfig Config() {- RuntimeHostConfig config;- config.boundary = root / "data";- config.state_root = root / "data/runtime-state";- config.homebrew_root = root / "data/homebrew";- config.native.database = [this](const std::string& title) {- ++database_reads;- if (!registered) return TitleDatabaseObservation{TitleAvailability::kFree, {}};- return TitleDatabaseObservation{TitleAvailability::kOccupied,- InstalledTitleIdentity{title, "UP9000-FAKE78001_00-PROSPEROWIN00001", "/user/app/FAKE78001/sce_sys"}};- };- config.native.activity = [activity = activity](const std::string&) { return static_cast<NativeActivity>(activity->load()); };- // ShadowMount loopback API: registration makes the title appear installed.- config.registry_transport = [this](const std::string& route, const std::string&) -> std::optional<std::string> {- if (route != "/api/v1/games") { ++registry_mutations; submitted = true; registered = registers; return R"({"status":0})"; }- if (!registered && submitted)- return R"({"status":0,"games":[{"title_id":"FAKE78001","installed":false,"managed":true,)"- R"("source_available":true,"source_type":"folder","path":"/data/homebrew/FAKE78001"}]})";- if (!registered) return R"({"status":0,"games":[]})";- return R"({"status":0,"games":[{"title_id":"FAKE78001","installed":true,"managed":true,)"- R"("source_available":true,"source_type":"folder","path":"/data/homebrew/FAKE78001"}]})";- };- config.admit_kit = [](std::string* reason) -> std::optional<RuntimeKit> {- *reason = "No verified compatibility kit is installed.";- return std::nullopt;- };- config.runtime_dir = g_runtime_dir;- return config;- }-};--// Generous: a loaded build machine (parallel ctest, other builds) can stretch a step past 10 s.-RuntimeSnapshot WaitFor(const RuntimeHost& host, const std::function<bool(const RuntimeSnapshot&)>& done,- int seconds = 30) {- const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(seconds);- for (;;) {- auto snapshot = host.Snapshot();- if (done(snapshot)) return snapshot;- CHECK(std::chrono::steady_clock::now() < deadline);- std::this_thread::sleep_for(std::chrono::milliseconds(2));- }-}-bool Started(const RuntimeSnapshot& s) { return s.status != RuntimeHostStatus::kStarting; }-RuntimePrepareRequest Hl2() { return {220, "/data/homebrew/FAKE77031/games/220", "internal", "Half-Life \"2\""}; }RuntimeInstall Record() {@@ -111,45 +44,6 @@ RuntimeInstall Record() {return record;}-// A synthetic admitted kit with the production file layout, real SHA-256 and-// the repository's HL2 recipe. It is not a runnable Wine runtime.-RuntimeKit SyntheticKit(const fs::path& kit, const std::string& eboot = "native",- const std::string& kit_id = "kit-1", char files_digest = 'a',- const std::string& runtime = "runtime", const std::string& revision = "rev") {- Write(kit / "titles/variant/eboot.bin", eboot, 0755);- Write(kit / "titles/variant/sce_sys/param.json",- "{\n \"contentId\": \"UP9000-FAKE78001_00-PROSPEROWIN00001\",\n \"localizedParameters\": {\n"- " \"en-US\": {\n \"titleName\": \"Prospero Win\"\n }\n },\n \"titleId\": \"FAKE78001\"\n}\n", 0644);- Write(kit / "titles/variant/sce_sys/icon0.png", "kit-icon", 0644);- Write(kit / ("runtime/wine/" + revision + "/lib/core.prx"), runtime, 0755);- Write(kit / "template/bottle/system.reg", "WINE REGISTRY Version 2\n", 0644);- Write(kit / "template/bottle/user.reg", "WINE REGISTRY Version 2\n", 0644);- Write(kit / "template/bottle/drive_c/windows/win.ini", "", 0644);- Write(kit / "template/bottle/dosdevices/.pw-symlinks", "c:\t../drive_c\nz:\t/\n", 0644);- Write(kit / "recipes/hl2.json", Read(fs::path(g_runtime_dir) / "recipes/steam-220-hl2-v1.json"), 0644);- RuntimeKit admitted;- auto& view = admitted.view;- view.root = kit; view.kit_id = kit_id; view.files_sha256 = std::string(64, files_digest);- view.runtime = {"wine-wow64", revision, "runtime/wine/" + revision};- view.template_path = "template/bottle";- view.template_drive_table = "template/bottle/dosdevices/.pw-symlinks";- view.recipe = {"steam-220-hl2-v1", "1", "recipes/hl2.json", *HashArtifactFile(kit / "recipes/hl2.json")};- view.variants.push_back({"variant", "FAKE78001", "titles/variant"});- for (const auto& [path, mode] : std::vector<std::pair<std::string, unsigned>>{- {"titles/variant/eboot.bin", 0755}, {"titles/variant/sce_sys/param.json", 0644},- {"titles/variant/sce_sys/icon0.png", 0644},- {"runtime/wine/" + revision + "/lib/core.prx", 0755}, {"template/bottle/system.reg", 0644},- {"template/bottle/user.reg", 0644}, {"template/bottle/drive_c/windows/win.ini", 0644},- {"template/bottle/dosdevices/.pw-symlinks", 0644}, {"recipes/hl2.json", 0644}})- view.files.push_back({path, fs::file_size(kit / path), *HashArtifactFile(kit / path), mode});- view.artifacts = {- {"runtime", revision, *HashArtifactFile(kit / ("runtime/wine/" + revision + "/lib/core.prx")),- ImmutableArtifactLocation::kStagedTitle, "win/wine/lib/core.prx"},- {"recipe", "steam-220-hl2-v1-1", *HashArtifactFile(kit / "recipes/hl2.json"),- ImmutableArtifactLocation::kKit, "recipes/hl2.json"}};- admitted.capabilities = {"dxvk", "game-root-unowned", "offline_bottle", "per_game_title", "wow64_i386"};- return admitted;-}// A kit before 0.10: game folders must be the app user's and 0700/0755, except on drives// that record no owners, which it can't start games from.RuntimeKit WithoutUnownedRoots(RuntimeKit kit) {@@ -712,7 +606,9 @@ void PreparesExistingDownloadToReady() {{RuntimeHost restarted(config);CHECK(restarted.Start());- CHECK((WaitFor(restarted, Started).prepared == std::vector<PreparedGame>{{220, 1760000000}}));+ // The list is published after the status turns ready: wait for it, not for the status alone.+ const std::vector<PreparedGame> listed{{220, 1760000000}};+ CHECK(WaitFor(restarted, [&](const RuntimeSnapshot& s) { return Started(s) && s.prepared == listed; }, 60).prepared == listed);restarted.DismissPrepared(220, 1759999999);restarted.DismissPrepared(220, 1760000000);CHECK(WaitFor(restarted, [](const RuntimeSnapshot& s) { return s.prepared.empty(); }).prepared.empty());@@ -2315,6 +2211,89 @@ void LocalGameSteamworksAppId() {// Kept bottles are not Steam-only: an imported game's marker names its game, lists after a restart// and gives the game its runtime number back. A Steam marker from before (fixture) still lists.+// A first number for a Local game is written to installs.json, which takes the process-wide+// effective-UID hold. The worker keeps that hold around its whole startup (and each batch) while+// using the repository: a lookup that took the repository's lock first and then waited for the hold+// stopped both threads for good (Playden froze on its first frame with a copy request in+// dev/install-request.txt). The lookup takes the hold first and waits for the worker, or, asked not+// to wait, says the worker is busy and gives nothing out.+void RuntimeNumberWaitsForTheWorkersHold() {+ const auto local_a = playden::GameId::Local("0f8fad5b-d9cb-469f-a165-70867728950e");+ const auto local_b = playden::GameId::Local("7c9e6679-7425-40de-944b-e07fc1f90ae7");+ Fixture fixture;+ auto config = fixture.Config();+ // The console's hold: one recursive lock shared with every durable write.+ config.hold_effective_uid = playden::ps5::HoldEffectiveUid;+ config.try_hold_effective_uid = [](bool* busy) {+ auto held = playden::ps5::TryHoldEffectiveUid();+ *busy = !held;+ return held;+ };+ // The worker stops inside its startup, hold taken and records shared, until the test lets it go.+ std::mutex gate_mutex;+ std::condition_variable gate_changed;+ bool gated = true, at_gate = false;+ config.log = [&](const std::string& line) {+ if (line.rfind("startup records loaded", 0) != 0) return;+ std::unique_lock<std::mutex> lock(gate_mutex);+ at_gate = true;+ gate_changed.notify_all();+ gate_changed.wait(lock, [&] { return !gated; });+ };+ RuntimeHost host(std::move(config));+ CHECK(host.Start());+ {+ std::unique_lock<std::mutex> lock(gate_mutex);+ CHECK(gate_changed.wait_for(lock, std::chrono::seconds(10), [&] { return at_gate; }));+ }+ // Each lookup runs on its own thread: one that never answers (the lookup inside the repository,+ // the worker waiting for it) fails the test instead of stopping it.+ struct Answer { std::optional<std::uint32_t> number; bool busy = false; };+ const auto ask = [&host](const playden::GameId& game, bool wait) {+ return std::async(std::launch::async, [&host, game, wait] {+ Answer answer;+ answer.number = host.RuntimeNumberFor(game, wait ? nullptr : &answer.busy);+ return answer;+ });+ };+ const auto answered = [](std::future<Answer>& answer, int seconds) {+ return answer.wait_for(std::chrono::seconds(seconds)) == std::future_status::ready;+ };+ // Asked not to wait (the application thread, every frame): busy, nothing given out, no number taken.+ auto at_once = ask(local_a, false);+ CHECK(answered(at_once, 20));+ const auto refused = at_once.get();+ CHECK(!refused.number && refused.busy);+ auto steam = ask(playden::GameId::Steam(220), false);+ CHECK(answered(steam, 20));+ const auto steam_answer = steam.get();+ CHECK(steam_answer.number == 220u && !steam_answer.busy);+ // Asked to wait (the Local store's worker): the number arrives once the worker's startup is over.+ auto waiting = ask(local_a, true);+ std::this_thread::sleep_for(std::chrono::milliseconds(200));+ CHECK(!answered(waiting, 0)); // still waiting+ {+ std::lock_guard<std::mutex> lock(gate_mutex);+ gated = false;+ }+ gate_changed.notify_all();+ CHECK(answered(waiting, 20));+ const auto given = waiting.get();+ CHECK(given.number == 0xF0000000u && !given.busy);+ CHECK(WaitFor(host, Started).status == RuntimeHostStatus::kReady);+ CHECK(host.Snapshot().runtime_games.at(0xF0000000u) == local_a);+ bool busy = false;+ CHECK(host.RuntimeNumberFor(local_a, &busy) == 0xF0000000u && !busy); // known: no hold needed+ // Idle, the worker holds nothing: a new number is given out at once.+ std::optional<std::uint32_t> second;+ for (int i = 0; i < 2500 && !second; ++i) {+ second = host.RuntimeNumberFor(local_b, &busy);+ if (!second) { CHECK(busy); std::this_thread::sleep_for(std::chrono::milliseconds(2)); }+ }+ CHECK(second == 0xF0000001u);+ host.Shutdown();+}+void LocalGameKeepsItsBottle() {const auto local = playden::GameId::Local("0f8fad5b-d9cb-469f-a165-70867728950e");const auto other = playden::GameId::Local("7c9e6679-7425-40de-944b-e07fc1f90ae7");@@ -4443,6 +4422,95 @@ void RelocationFallsBackToANewTitle() {host.Shutdown();}+// A republish refused for a reason that isn't the moved publication failing its check (here the+// saved settings, which a restart or Play gets past): the old title stays, its record marked moved,+// and the next start publishes it at the new folder, as after the 0.6 games move.+void RelocationKeepsTheTitleWhenTheRepublishWaits() {+ Fixture fixture;+ GamesMove move;+ const auto kit = SyntheticKit(fixture.root / "kit");+ unsigned uuids = 0;+ auto config = MoveConfig(fixture, kit, &uuids, move);+ const std::string drop = "/data/playden-import/Imported";+ const auto imported = PrepareImported(fixture, config, drop);+ fs::create_directories(fixture.root / "data/playden-games");+ const auto from = fixture.root / fs::path(drop).relative_path();+ const auto to = fixture.root / fs::path(kImportedRoot).relative_path();+ auto stale = std::make_shared<std::atomic<bool>>(true);+ const auto saved = config.settings_record;+ config.settings_record = [stale, saved](const playden::GameId& game) -> std::optional<GameSettingsRecord> {+ auto record = saved(game);+ if (record && stale->load()) record->revision = 0;+ return record;+ };+ {+ RuntimeHost host(config);+ CHECK(host.Start());+ WaitFor(host, Started);+ const auto result = RelocateNow(host, imported.number, [&]() -> std::string {+ return ::rename(from.c_str(), to.c_str()) == 0 ? std::string() : std::string("rename failed");+ });+ CHECK(result.outcome == RuntimeRelocationResult::Outcome::kDone && !result.prepare_again && !result.message.empty());+ CHECK(move.Logged("relocate app=" + std::to_string(imported.number) + " republish waits"));+ CHECK(!move.Logged("relocate app=" + std::to_string(imported.number) + " republish failed"));+ const auto snapshot = host.Snapshot();+ CHECK(snapshot.installs.size() == 1 && snapshot.installs[0].title_id == imported.title_id);+ CHECK(snapshot.installs[0].install_path == kImportedRoot);+ CHECK(Read(fixture.root / "data/runtime-state/installs.json").find("moved_from") != std::string::npos);+ host.Shutdown();+ }+ // The next start republishes it like a game the 0.6 move left marked.+ stale->store(false);+ RuntimeHost host(config);+ CHECK(host.Start());+ WaitFor(host, Started);+ CHECK(move.Logged("startup moved app=" + std::to_string(imported.number) + " republished"));+ CheckRelocated(fixture, host, imported, "internal");+ host.Shutdown();+}++// Quitting while a relocation waits for the worker: the caller stops waiting at once ("Playden is+// closing"), the relocation never runs, and later ones are refused the same way.+void RelocationStopsWaitingWhenPlaydenCloses() {+ Fixture fixture;+ GamesMove move;+ const auto kit = SyntheticKit(fixture.root / "kit");+ unsigned uuids = 0;+ const auto config = MoveConfig(fixture, kit, &uuids, move);+ const std::string drive = "/mnt/usb0/playden/import/Imported";+ const auto imported = PrepareImported(fixture, config, drive);+ RuntimeHost host(config);+ CHECK(host.Start());+ WaitFor(host, Started);+ // A handoff waiting holds relocations back on the worker.+ host.Play(imported.number);+ const auto number = imported.number;+ const auto played = WaitFor(host, [number](const RuntimeSnapshot& s) { return s.handoff_ready || s.play_refusals.count(number); }, 30);+ CHECK(played.handoff_ready);+ std::atomic<bool> moved{false};+ RuntimeRelocationResult result;+ std::atomic<bool> answered{false};+ std::thread waiting([&] {+ result = RelocateNow(host, imported.number, [&]() -> std::string { moved = true; return {}; });+ answered = true;+ });+ std::this_thread::sleep_for(std::chrono::milliseconds(200));+ CHECK(!answered.load());+ const auto closing = std::chrono::steady_clock::now();+ host.BeginClosing();+ waiting.join();+ CHECK(std::chrono::steady_clock::now() - closing < std::chrono::seconds(5));+ CHECK(result.outcome == RuntimeRelocationResult::Outcome::kBusy && result.message == kRelocationClosing);+ const auto again = RelocateNow(host, imported.number);+ CHECK(again.outcome == RuntimeRelocationResult::Outcome::kBusy && again.message == kRelocationClosing);+ // The handoff goes on; the abandoned relocation never runs.+ CHECK(host.Handoff());+ std::this_thread::sleep_for(std::chrono::milliseconds(200));+ CHECK(!moved.load() && host.Snapshot().installs[0].install_path == drive);+ CHECK(!move.Logged("relocate result app="));+ host.Shutdown();+}+int main(int argc, char** argv) {CHECK(argc == 2);g_runtime_dir = argv[1];@@ -4454,6 +4522,7 @@ int main(int argc, char** argv) {HoldsEffectiveUidWhileWorking();StartupReportsJournalsWithoutResuming();LocalGameGetsRuntimeNumber();+ RuntimeNumberWaitsForTheWorkersHold();LocalGameKeepsItsBottle();LocalGameSteamworksAppId();PublicStateRootIsUnavailable();@@ -4503,6 +4572,8 @@ int main(int argc, char** argv) {MovedGameKeepsItsTitle();RelocationResumesAfterRestart();RelocationFallsBackToANewTitle();+ RelocationKeepsTheTitleWhenTheRepublishWaits();+ RelocationStopsWaitingWhenPlaydenCloses();std::puts("runtime host tests passed");return 0;}diff --git a/tests/homebrew_simulation_test.cpp b/tests/homebrew_simulation_test.cppindex 7020dda..726d1b3 100644--- a/tests/homebrew_simulation_test.cpp+++ b/tests/homebrew_simulation_test.cpp@@ -1239,7 +1239,7 @@ static void t18_imported_game_page(const std::filesystem::path& fixtures, const"T18 an imported game's page plays in place and offers Copy and Remove");// Copy: the drive choice, then the copy's progress on the page.press("details-copy");- check(simulation.view().surface == "import-choice" && !row("import-play-in-place") && row("import-copy")->value == "412 MB · about 1 min",+ check(simulation.view().surface == "import-choice" && !row("import-play-in-place") && row("import-copy")->value == "412 MB · under a minute","T18 Copy into Playden from the page asks for the drive");press("storage-picker");check(simulation.view().surface == "storage" && simulation.view().title == "Copy to", "T18 the copy's drive picker");@@ -1252,6 +1252,13 @@ static void t18_imported_game_page(const std::filesystem::path& fixtures, const"T18 the copy runs on the chosen drive and shows on the page");check(simulation.scenario("import-copying"), "T18 import-copying scenario");check(row("details-download")->progress > 0.39F && row("details-download")->progress < 0.41F, "T18 the copy is 40% done");+ // Cancel copy: asks, then the game plays in place again.+ check(row("details-cancel-copy") && row("details-remove") && !row("details-remove")->enabled, "T18 a copy offers Cancel copy");+ press("details-cancel-copy");+ check(simulation.view().surface == "confirmation", "T18 Cancel copy asks first");+ press("confirm-destructive");+ check(row("details-copy") && !row("details-download") && !row("details-cancel-copy") && row("details-remove")->enabled,+ "T18 a cancelled copy returns the game to playing in place");// Remove from library: the folder stays, and can be added again.check(simulation.scenario("import-details"), "T18 import-details again");diff --git a/tests/local_copy_test.cpp b/tests/local_copy_test.cppindex 7d31ac5..d0891eb 100644--- a/tests/local_copy_test.cpp+++ b/tests/local_copy_test.cpp@@ -99,6 +99,7 @@ struct Fixture {std::vector<std::string> log;std::mutex log_mutex;int next_id = 0;+ std::atomic<bool> usb_present{true}; // the source driveFixture() {char name[] = "/tmp/playden-local-copy-XXXXXX";@@ -140,13 +141,14 @@ struct Fixture {LocalLibraryConfig config;config.volumes = {{"internal", "/data", "playden-import", false}, {"usb0", "/mnt/usb0", "playden/import", false}};config.host_prefix = root.string();- config.present = [](const ImportVolume&) { return true; };+ config.present = [this](const ImportVolume& volume) { return volume.volume != "usb0" || usb_present.load(); };config.log = options.log;config.copy_into_playden = [this](const ImportEntry& entry, const std::string& from, const std::string& volume,std::uint32_t number) { return runner->Enqueue(*service, entry, from, volume, number); };config.move_into_playden = [this](const ImportEntry& entry, const std::string& from, std::uint32_t number) {return runner->Move(*service, entry, from, number);};+ config.remove_copy_folder = [this](const std::string& folder) { return runner->Remove(folder); };local = std::make_unique<LocalLibrarySource>(*store, std::move(config));runner->SetChanged([source = local.get()] { source->Reload(); });WaitFor([&] { return local->Snapshot()->loaded || !local->Snapshot()->load_error.empty(); }, "imports loaded");@@ -688,6 +690,34 @@ void ProgramMissingIsRefused() {CHECK(fixture.State() == ImportState::kInPlace && !fs::exists(fixture.Dest()));}+// The copy lives on Playden's storage: it uninstalls, and its game leaves the library, while the+// drive it was copied from is unplugged.+void UninstallWithoutTheSourceDrive() {+ Fixture fixture;+ fixture.Start();+ fixture.Add();+ CHECK(fixture.Outcome(fixture.local->CopyIntoPlayden(kId)).ok);+ WaitFor([&] { return fixture.Installed() && fixture.State() == ImportState::kCopied; }, "copied");+ // The drive goes: its folder with it.+ fixture.usb_present = false;+ fs::rename(fixture.root / "mnt/usb0", fixture.root / "unplugged");+ fixture.local->CheckVolumes();+ WaitFor([&] { return !fixture.local->Snapshot()->present_volumes.count("usb0"); }, "the drive gone");+ // A restart without the drive, too.+ fixture.Stop();+ fixture.Start();+ CHECK(fixture.Installed() && fixture.State() == ImportState::kCopied);+ auto* service = fixture.service.get();+ CHECK(fixture.Outcome(fixture.local->Reconcile([service] { return service->Snapshot(); },+ [service](const GameId& id) { service->Cancel(id); })).ok);+ CHECK(fixture.local->Locations().empty());+ fixture.service->Uninstall(fixture.Game());+ WaitFor([&] { return !fs::exists(fixture.Dest()); }, "the files removed");+ WaitFor([&] { return fixture.local->Snapshot()->games.empty(); }, "the game out of the library");+ CHECK(!fixture.store->Find(kId) && fixture.store->Removed().size() == 1);+ CHECK(fs::is_regular_file(fixture.root / "unplugged/playden/import/Rally/Bin/Rally.exe"));+}+void CrashBetweenCommitSteps() {Fixture fixture;// Playden stops after the install record, before imports.json says copied.@@ -727,6 +757,46 @@ void ReconcileWithoutJob() {WaitFor([&] { return !fixture.Job(); }, "the stale job cancelled");}+// Playden stopped between saving a copy's plan and queuing its job: the folder has a plan and no+// job. The next start's reconcile puts the game back in place and removes the folder, and a plan+// folder whose game isn't in the library goes too; a copy with its job keeps its folder.+void OrphanCopyFoldersRemoved() {+ Fixture fixture;+ std::atomic<bool> pause{false};+ fixture.options.after_file = [&](const std::string&) {+ if (pause.exchange(false)) fixture.service->Pause(GameId::Local(kId));+ };+ fixture.Start();+ fixture.Add();+ auto build = BuildCopyPlan(fixture.source.string());+ CHECK(build.ok);+ build.plan.program = "Bin/Rally.exe";+ CHECK(SaveCopyPlan(build.plan, fixture.Dest().string()).empty());+ CHECK(fixture.store->QueueCopy(kId).ok());+ const auto stray = fixture.games / "local-16fd2706-8baf-433b-82eb-8c7fada847da";+ CHECK(SaveCopyPlan(build.plan, stray.string()).empty());+ // Not Playden's: a folder without a plan, and one that isn't a Local key.+ fs::create_directories(fixture.games / "local-6fa459ea-ee8a-4ca4-894e-db77e160355e/saves");+ fs::create_directories(fixture.games / "other/.playden-copy");+ auto* service = fixture.service.get();+ const auto reconciled = fixture.local->Reconcile([service] { return service->Snapshot(); },+ [service](const GameId& id) { service->Cancel(id); });+ CHECK(fixture.Outcome(reconciled).ok);+ CHECK(fixture.State() == ImportState::kInPlace);+ CHECK(!fs::exists(fixture.Dest()) && !fs::exists(stray));+ CHECK(fixture.Logged("import copy folder removed root=" + fixture.Dest().string()));+ CHECK(fs::is_directory(fixture.games / "local-6fa459ea-ee8a-4ca4-894e-db77e160355e/saves"));+ CHECK(fs::is_directory(fixture.games / "other/.playden-copy"));+ // A copy with its job keeps its plan folder.+ pause = true;+ CHECK(fixture.Outcome(fixture.local->CopyIntoPlayden(kId)).ok);+ WaitFor([&] { const auto job = fixture.Job(); return job && job->state == InstallJobState::kPaused; }, "paused");+ CHECK(fs::exists(fixture.Dest() / ".playden-copy/plan.json"));+ CHECK(fixture.Outcome(fixture.local->Reconcile([service] { return service->Snapshot(); },+ [service](const GameId& id) { service->Cancel(id); })).ok);+ CHECK(fs::exists(fixture.Dest() / ".playden-copy/plan.json") && fixture.State() != ImportState::kInPlace);+}+void FreeSpaceRefused() {Fixture fixture;// At the start (and on resume): the runner checks what is left against the drive.@@ -781,12 +851,14 @@ int main() {PlanCoversTheTree();LinksAreRefused();CopiesIntoPlayden();+ UninstallWithoutTheSourceDrive();ResumesAfterPauseAndRestart();CancelLeavesNothing();ChangedSourceFails();ProgramMissingIsRefused();CrashBetweenCommitSteps();ReconcileWithoutJob();+ OrphanCopyFoldersRemoved();FreeSpaceRefused();CopyRelocatesItsTitle();MovesDropFolderGame();diff --git a/tests/local_scanner_test.cpp b/tests/local_scanner_test.cppindex 9f53417..5476178 100644--- a/tests/local_scanner_test.cpp+++ b/tests/local_scanner_test.cpp@@ -1,6 +1,7 @@// Ports of the macOS LocalWindowsGameTests, plus the console's walk rules. Built twice: once with// the host's descriptor walk, once with the PS5's walk by path (PLAYDEN_PLATFORM_PS5).#include "stores/local/scanner.h"+#include "platform/directory_walk.h"#include <algorithm>#include <cstdio>@@ -267,7 +268,33 @@ void HelperRules() {} // namespace+#if defined(PLAYDEN_PLATFORM_PS5)+// exFAT lists an empty file under a different inode than stat reports; force that mismatch.+void ListingMismatchOnlyFailsForUnprivilegedRegularFiles() {+ TemporaryDirectory root;+ File(root.path / "game" / "empty.lock", 0);+ fs::create_directories(root.path / "game" / "sub");+ const int parent = playden::platform::OpenDirectoryWalk(root.path / "game");+ CHECK(parent >= 0);+ const std::uint64_t wrong = 1;+ const int flags = O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC;+ int fd = playden::platform::OpenWalkChild(parent, "empty.lock", flags, wrong);+ CHECK(fd < 0 && errno == ESTALE);+ fd = playden::platform::OpenWalkChildUnprivileged(parent, "empty.lock", flags, wrong);+ CHECK(fd >= 0);+ ::close(fd);+ fd = playden::platform::OpenWalkChildUnprivileged(parent, "sub", flags, wrong);+ CHECK(fd < 0 && errno == ESTALE);+ fd = playden::platform::OpenWalkChildUnprivileged(parent, "sub", flags | O_DIRECTORY, wrong);+ CHECK(fd < 0 && errno == ESTALE);+ ::close(parent);+}+#endif+int main() {+#if defined(PLAYDEN_PLATFORM_PS5)+ ListingMismatchOnlyFailsForUnprivilegedRegularFiles();+#endifExecutablesListTheGameFirstAndHelpersLast();GenericFolderNamesUseTheParentAsTitle();ProgramChecks();diff --git a/tests/runtime_host_fixture.h b/tests/runtime_host_fixture.hnew file mode 100644index 0000000..15d443a--- /dev/null+++ b/tests/runtime_host_fixture.h@@ -0,0 +1,144 @@+#pragma once+// The runtime host tests' shared fixture: a temporary console namespace with fake native, registry+// and kit hooks (Fixture), and a synthetic admitted kit (SyntheticKit). Shared by+// homebrew_runtime_host_test.cpp and homebrew_installed_locations_test.cpp.+#include "homebrew/runtime_host.hpp"+#include "platform/ps5/title_allow_list.h"+#include "runtime/artifact_hash.h"++#include <atomic>+#include <chrono>+#include <cstdio>+#include <cstdlib>+#include <filesystem>+#include <fstream>+#include <functional>+#include <iterator>+#include <memory>+#include <optional>+#include <string>+#include <sys/stat.h>+#include <thread>+#include <unistd.h>+#include <utility>+#include <vector>++#ifndef CHECK+#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "%s:%d: CHECK failed: %s\n", __FILE__, __LINE__, #x); std::exit(1); } } while (0)+#endif++// Its own namespace: the tests have names of their own (the model's Game, for one).+namespace playden::test::runtime_host {+using namespace playden::homebrew;+using namespace playden::runtime;+using namespace playden::ps5;++// The repository's bundled runtime data (recipes, presets, input): main sets it from argv.+inline std::string g_runtime_dir;++inline void Write(const std::filesystem::path& path, const std::string& bytes, unsigned mode) {+ std::filesystem::create_directories(path.parent_path());+ std::ofstream(path, std::ios::binary | std::ios::trunc) << bytes;+ CHECK(chmod(path.c_str(), mode) == 0);+}+inline std::string Read(const std::filesystem::path& path) {+ std::ifstream in(path, std::ios::binary);+ return {std::istreambuf_iterator<char>(in), {}};+}+struct Fixture {+ std::filesystem::path root;+ unsigned database_reads = 0, registry_mutations = 0;+ bool registered = false;+ // ShadowMountPlus postpones scans while a title runs: with registers false a+ // submission is accepted and listed, but not installed until registered is set.+ bool registers = true, submitted = false;+ std::shared_ptr<std::atomic<int>> activity = std::make_shared<std::atomic<int>>(static_cast<int>(NativeActivity::kStopped));+ Fixture() {+ char name[] = "/tmp/playden-runtime-host-XXXXXX"; CHECK(mkdtemp(name));+ root = std::filesystem::canonical(name);+ std::filesystem::create_directories(root / "data/homebrew");+ }+ ~Fixture() { std::error_code ignored; std::filesystem::remove_all(root, ignored); }+ RuntimeHostConfig Config() {+ RuntimeHostConfig config;+ config.boundary = root / "data";+ config.state_root = root / "data/runtime-state";+ config.homebrew_root = root / "data/homebrew";+ config.native.database = [this](const std::string& title) {+ ++database_reads;+ if (!registered) return TitleDatabaseObservation{TitleAvailability::kFree, {}};+ return TitleDatabaseObservation{TitleAvailability::kOccupied,+ InstalledTitleIdentity{title, "UP9000-FAKE78001_00-PROSPEROWIN00001", "/user/app/FAKE78001/sce_sys"}};+ };+ config.native.activity = [activity = activity](const std::string&) { return static_cast<NativeActivity>(activity->load()); };+ // ShadowMount loopback API: registration makes the title appear installed.+ config.registry_transport = [this](const std::string& route, const std::string&) -> std::optional<std::string> {+ if (route != "/api/v1/games") { ++registry_mutations; submitted = true; registered = registers; return R"({"status":0})"; }+ if (!registered && submitted)+ return R"({"status":0,"games":[{"title_id":"FAKE78001","installed":false,"managed":true,)"+ R"("source_available":true,"source_type":"folder","path":"/data/homebrew/FAKE78001"}]})";+ if (!registered) return R"({"status":0,"games":[]})";+ return R"({"status":0,"games":[{"title_id":"FAKE78001","installed":true,"managed":true,)"+ R"("source_available":true,"source_type":"folder","path":"/data/homebrew/FAKE78001"}]})";+ };+ config.admit_kit = [](std::string* reason) -> std::optional<RuntimeKit> {+ *reason = "No verified compatibility kit is installed.";+ return std::nullopt;+ };+ config.runtime_dir = g_runtime_dir;+ return config;+ }+};+// Generous: a loaded build machine (parallel ctest, other builds) can stretch a step past 10 s.+inline RuntimeSnapshot WaitFor(const RuntimeHost& host, const std::function<bool(const RuntimeSnapshot&)>& done,+ int seconds = 30) {+ const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(seconds);+ for (;;) {+ auto snapshot = host.Snapshot();+ if (done(snapshot)) return snapshot;+ CHECK(std::chrono::steady_clock::now() < deadline);+ std::this_thread::sleep_for(std::chrono::milliseconds(2));+ }+}+inline bool Started(const RuntimeSnapshot& s) { return s.status != RuntimeHostStatus::kStarting; }+// A synthetic admitted kit with the production file layout, real SHA-256 and+// the repository's HL2 recipe. It is not a runnable Wine runtime.+inline RuntimeKit SyntheticKit(const std::filesystem::path& kit, const std::string& eboot = "native",+ const std::string& kit_id = "kit-1", char files_digest = 'a',+ const std::string& runtime = "runtime", const std::string& revision = "rev") {+ Write(kit / "titles/variant/eboot.bin", eboot, 0755);+ Write(kit / "titles/variant/sce_sys/param.json",+ "{\n \"contentId\": \"UP9000-FAKE78001_00-PROSPEROWIN00001\",\n \"localizedParameters\": {\n"+ " \"en-US\": {\n \"titleName\": \"Prospero Win\"\n }\n },\n \"titleId\": \"FAKE78001\"\n}\n", 0644);+ Write(kit / "titles/variant/sce_sys/icon0.png", "kit-icon", 0644);+ Write(kit / ("runtime/wine/" + revision + "/lib/core.prx"), runtime, 0755);+ Write(kit / "template/bottle/system.reg", "WINE REGISTRY Version 2\n", 0644);+ Write(kit / "template/bottle/user.reg", "WINE REGISTRY Version 2\n", 0644);+ Write(kit / "template/bottle/drive_c/windows/win.ini", "", 0644);+ Write(kit / "template/bottle/dosdevices/.pw-symlinks", "c:\t../drive_c\nz:\t/\n", 0644);+ Write(kit / "recipes/hl2.json", Read(std::filesystem::path(g_runtime_dir) / "recipes/steam-220-hl2-v1.json"), 0644);+ RuntimeKit admitted;+ auto& view = admitted.view;+ view.root = kit; view.kit_id = kit_id; view.files_sha256 = std::string(64, files_digest);+ view.runtime = {"wine-wow64", revision, "runtime/wine/" + revision};+ view.template_path = "template/bottle";+ view.template_drive_table = "template/bottle/dosdevices/.pw-symlinks";+ view.recipe = {"steam-220-hl2-v1", "1", "recipes/hl2.json", *HashArtifactFile(kit / "recipes/hl2.json")};+ view.variants.push_back({"variant", "FAKE78001", "titles/variant"});+ for (const auto& [path, mode] : std::vector<std::pair<std::string, unsigned>>{+ {"titles/variant/eboot.bin", 0755}, {"titles/variant/sce_sys/param.json", 0644},+ {"titles/variant/sce_sys/icon0.png", 0644},+ {"runtime/wine/" + revision + "/lib/core.prx", 0755}, {"template/bottle/system.reg", 0644},+ {"template/bottle/user.reg", 0644}, {"template/bottle/drive_c/windows/win.ini", 0644},+ {"template/bottle/dosdevices/.pw-symlinks", 0644}, {"recipes/hl2.json", 0644}})+ view.files.push_back({path, std::filesystem::file_size(kit / path), *HashArtifactFile(kit / path), mode});+ view.artifacts = {+ {"runtime", revision, *HashArtifactFile(kit / ("runtime/wine/" + revision + "/lib/core.prx")),+ ImmutableArtifactLocation::kStagedTitle, "win/wine/lib/core.prx"},+ {"recipe", "steam-220-hl2-v1-1", *HashArtifactFile(kit / "recipes/hl2.json"),+ ImmutableArtifactLocation::kKit, "recipes/hl2.json"}};+ admitted.capabilities = {"dxvk", "game-root-unowned", "offline_bottle", "per_game_title", "wow64_i386"};+ return admitted;+}++} // namespace playden::test::runtime_host