Play your Steam library's Windows games on a jailbroken PS5.
C++
Move user data, logs and games out of the app folder
Leonardo Lobato3d0ca12b86be
diff --git a/cmake/HomebrewPS5.cmake b/cmake/HomebrewPS5.cmakeindex 7ac0d20..05b0137 100644--- a/cmake/HomebrewPS5.cmake+++ b/cmake/HomebrewPS5.cmake@@ -128,7 +128,7 @@ function(playden_add_homebrew_ps5_title)$<$<COMPILE_LANGUAGE:CXX>:-fno-exceptions;-fno-rtti>)target_compile_features(playden_ps5_app PRIVATE cxx_std_20)target_link_libraries(playden_ps5_app PRIVATE playden_hui playden_library playden_steam_auth- playden_homebrew_controller playden_local_session_repository playden_steam_library playden_steam_cm playden_native_access)+ playden_homebrew_controller playden_local_session_repository playden_steam_library playden_steam_cm playden_native_access playden_runtime_layout_migration)set(host_tool "${host}/ps5-native-tool")set(libc_prx "${host}/libc.prx")@@ -157,20 +157,20 @@ function(playden_add_homebrew_ps5_title)$<TARGET_FILE:playden_self_update> $<TARGET_FILE:playden_miniz> $<TARGET_FILE:playden_steam_http> $<TARGET_FILE:playden_steam_protocol>$<TARGET_FILE:playden_steam_auth>$<TARGET_FILE:playden_steam_core> $<TARGET_FILE:playden_diagnostic_log> $<TARGET_FILE:playden_storage>- $<TARGET_FILE:playden_library> $<TARGET_FILE:playden_native_access> $<TARGET_FILE:playden_managed_directory> $<TARGET_FILE:playden_runtime_steamworks> $<TARGET_FILE:playden_runtime_artifact_hash> $<TARGET_FILE:playden_runtime_settings_storage> $<TARGET_FILE:playden_runtime_private_directories> $<TARGET_FILE:playden_runtime_session_reconciler> $<TARGET_FILE:playden_runtime_launch_service> $<TARGET_FILE:playden_runtime_install_service> $<TARGET_FILE:playden_runtime_installs> $<TARGET_FILE:playden_game_paths>+ $<TARGET_FILE:playden_library> $<TARGET_FILE:playden_native_access> $<TARGET_FILE:playden_managed_directory> $<TARGET_FILE:playden_runtime_steamworks> $<TARGET_FILE:playden_runtime_artifact_hash> $<TARGET_FILE:playden_runtime_settings_storage> $<TARGET_FILE:playden_runtime_private_directories> $<TARGET_FILE:playden_runtime_session_reconciler> $<TARGET_FILE:playden_runtime_launch_service> $<TARGET_FILE:playden_runtime_install_service> $<TARGET_FILE:playden_runtime_installs> $<TARGET_FILE:playden_runtime_layout_migration> $<TARGET_FILE:playden_game_paths>${PLAYDEN_STEAM_LINK_ARCHIVES} ${title_database_archives}--end-group --as-needed ${link_stubs}WORKING_DIRECTORY "${out}/link"DEPENDS "${common_dialog_stub}" playden_ps5_runtime playden_ps5_shims playden_ps5_app playden_hui playden_homebrew_ui playden_homebrew_model ${title_database_targets}playden_homebrew_qr playden_homebrew_controller playden_local_session_repository playden_auth_diagnosticsplayden_homebrew_artwork_cache playden_homebrew_artwork playden_persistence_controller playden_persistence_service playden_preferences playden_library_controller playden_library_service playden_steam_library playden_steam_cm playden_steam_cm_codec playden_depot_codec- playden_library playden_self_update playden_miniz playden_steam_auth playden_steam_http playden_steam_protocol playden_steam_core playden_diagnostic_log playden_storage playden_native_access playden_managed_directory playden_runtime_steamworks playden_runtime_artifact_hash playden_runtime_settings_storage playden_runtime_private_directories playden_runtime_session_reconciler playden_runtime_launch_service playden_runtime_install_service playden_runtime_installs playden_game_paths+ playden_library playden_self_update playden_miniz playden_steam_auth playden_steam_http playden_steam_protocol playden_steam_core playden_diagnostic_log playden_storage playden_native_access playden_managed_directory playden_runtime_steamworks playden_runtime_artifact_hash playden_runtime_settings_storage playden_runtime_private_directories playden_runtime_session_reconciler playden_runtime_launch_service playden_runtime_install_service playden_runtime_installs playden_runtime_layout_migration playden_game_paths$<TARGET_OBJECTS:playden_ps5_runtime> $<TARGET_OBJECTS:playden_ps5_shims>$<TARGET_OBJECTS:playden_ps5_app>$<TARGET_FILE:playden_self_update> $<TARGET_FILE:playden_miniz> $<TARGET_FILE:playden_steam_http> $<TARGET_FILE:playden_steam_protocol>$<TARGET_FILE:playden_steam_auth>$<TARGET_FILE:playden_steam_core> $<TARGET_FILE:playden_diagnostic_log> $<TARGET_FILE:playden_storage>- $<TARGET_FILE:playden_library> $<TARGET_FILE:playden_native_access> $<TARGET_FILE:playden_managed_directory> $<TARGET_FILE:playden_runtime_steamworks> $<TARGET_FILE:playden_runtime_artifact_hash> $<TARGET_FILE:playden_runtime_settings_storage> $<TARGET_FILE:playden_runtime_private_directories> $<TARGET_FILE:playden_runtime_session_reconciler> $<TARGET_FILE:playden_runtime_launch_service> $<TARGET_FILE:playden_runtime_install_service> $<TARGET_FILE:playden_runtime_installs> $<TARGET_FILE:playden_game_paths>+ $<TARGET_FILE:playden_library> $<TARGET_FILE:playden_native_access> $<TARGET_FILE:playden_managed_directory> $<TARGET_FILE:playden_runtime_steamworks> $<TARGET_FILE:playden_runtime_artifact_hash> $<TARGET_FILE:playden_runtime_settings_storage> $<TARGET_FILE:playden_runtime_private_directories> $<TARGET_FILE:playden_runtime_session_reconciler> $<TARGET_FILE:playden_runtime_launch_service> $<TARGET_FILE:playden_runtime_install_service> $<TARGET_FILE:playden_runtime_installs> $<TARGET_FILE:playden_runtime_layout_migration> $<TARGET_FILE:playden_game_paths>$<TARGET_FILE:playden_homebrew_qr> $<TARGET_FILE:playden_homebrew_controller>$<TARGET_FILE:playden_homebrew_artwork_cache> $<TARGET_FILE:playden_homebrew_artwork> $<TARGET_FILE:playden_persistence_controller> $<TARGET_FILE:playden_persistence_service> $<TARGET_FILE:playden_preferences> $<TARGET_FILE:playden_library_controller> $<TARGET_FILE:playden_library_service> $<TARGET_FILE:playden_steam_library> $<TARGET_FILE:playden_steam_cm> $<TARGET_FILE:playden_steam_cm_codec> $<TARGET_FILE:playden_depot_codec>$<TARGET_FILE:playden_local_session_repository> $<TARGET_FILE:playden_auth_diagnostics>diff --git a/cmake/PlaydenCore.cmake b/cmake/PlaydenCore.cmakeindex fb741de..f85c1e6 100644--- a/cmake/PlaydenCore.cmake+++ b/cmake/PlaydenCore.cmake@@ -94,6 +94,11 @@ target_include_directories(playden_runtime_private_directories PUBLIC "${CMAKE_Starget_compile_features(playden_runtime_private_directories PUBLIC cxx_std_17)target_link_libraries(playden_runtime_private_directories PUBLIC playden_managed_directory)+add_library(playden_runtime_layout_migration STATIC "${CMAKE_SOURCE_DIR}/src/runtime/layout_migration.cpp")+target_include_directories(playden_runtime_layout_migration PUBLIC "${CMAKE_SOURCE_DIR}/src")+target_compile_features(playden_runtime_layout_migration PUBLIC cxx_std_17)+target_link_libraries(playden_runtime_layout_migration PUBLIC playden_runtime_installs playden_runtime_private_directories)+add_library(playden_runtime_package_installer STATIC "${CMAKE_SOURCE_DIR}/src/runtime/package_installer.cpp")target_include_directories(playden_runtime_package_installer PUBLIC "${CMAKE_SOURCE_DIR}/src")target_compile_features(playden_runtime_package_installer PUBLIC cxx_std_17)@@ -194,6 +199,9 @@ if(BUILD_TESTING AND NOT PLAYDEN_PLATFORM_PS5)add_executable(runtime_install_service_test "${CMAKE_SOURCE_DIR}/tests/runtime_install_service_test.cpp")target_link_libraries(runtime_install_service_test PRIVATE playden_runtime_install_service)add_test(NAME runtime_install_service COMMAND runtime_install_service_test)+ add_executable(layout_migration_test "${CMAKE_SOURCE_DIR}/tests/layout_migration_test.cpp")+ target_link_libraries(layout_migration_test PRIVATE playden_runtime_layout_migration)+ add_test(NAME layout_migration COMMAND layout_migration_test)add_executable(native_access_test "${CMAKE_SOURCE_DIR}/tests/native_access_test.cpp")target_link_libraries(native_access_test PRIVATE playden_native_access)add_test(NAME native_access COMMAND native_access_test)diff --git a/src/homebrew/ps5.cpp b/src/homebrew/ps5.cppindex b375379..01b3058 100644--- a/src/homebrew/ps5.cpp+++ b/src/homebrew/ps5.cpp@@ -187,7 +187,9 @@ int main() {}const auto& paths = native_access.paths;title_root = paths.title_root;- log_root = paths.log_root;+ // After the grant, user data, logs and games live outside the app folder (0.5 layout).+ log_root = playden::ps5::EffectiveLogRoot(paths);+ const std::string user_root = playden::ps5::EffectiveUserRoot(paths);// Startup checkpoints: a launch that never shows its first frame can be told// apart from one that never opened the display.playden::app::AppendLogLine(log_root, "launch.log", "display open width=" + std::to_string(display.width()) +@@ -217,18 +219,23 @@ int main() {if (playden::runtime::LoadSettingsData(paths.title_root + "/runtime", &presets, &recipes, &reason))simulation.SetSettingsData(std::move(presets), std::move(recipes));else- playden::app::AppendLogLine(paths.log_root, "launch.log", "game settings data unavailable: " + reason);+ playden::app::AppendLogLine(log_root, "launch.log", "game settings data unavailable: " + reason);}#if !PLAYDEN_UI_SIMULATIONstd::string settings_reason;- const auto settings_file = playden::runtime::PrepareGameSettingsStorage(paths.steam_state_root, &settings_reason);+ const auto settings_file = playden::runtime::PrepareGameSettingsStorage(user_root, &settings_reason);if (!settings_file)- playden::app::AppendLogLine(paths.log_root, "launch.log",+ playden::app::AppendLogLine(log_root, "launch.log","private game settings unavailable: " + settings_reason);- else playden::app::AppendLogLine(paths.log_root, "launch.log", "game settings storage initialized");+ else playden::app::AppendLogLine(log_root, "launch.log", "game settings storage initialized");+ // The layout move held something back this start: say so where the logs are read.+ if (!native_access.notice.empty()) {+ playden::app::AppendLogLine(log_root, "runtime.log", "layout notice: " + native_access.notice);+ simulation.ShowLayoutNotice(native_access.notice);+ }// An empty path disables live writes and surfaces a settings load error.simulation.SetGameSettingsFile(settings_file.value_or(std::filesystem::path{}));- playden::Storage auth_storage(paths.steam_state_root);+ playden::Storage auth_storage(user_root);// One line per Steam CM logon or refusal, with Steam's result code (#51).playden::steam::SetCmLog([](const std::string& line) {playden::app::AppendLogLine(log_root, "steam-cm.log", line);@@ -252,12 +259,12 @@ int main() {playden::app::AppendLogLine(log_root, "auth.log", std::string("restored path=") + path + " before " + before +" after " + after);});- playden::LocalSessionRepository sessions(paths.steam_state_root, [](const std::string& diagnostic) {+ playden::LocalSessionRepository sessions(user_root, [](const std::string& diagnostic) {playden::app::AppendLogLine(log_root, "storage.log", diagnostic);});playden::steam::LibraryClient owned_library(paths.trust_store);- playden::LocalSessionRepository library_sessions(paths.steam_state_root);- playden::Storage library_storage(paths.steam_state_root);+ playden::LocalSessionRepository library_sessions(user_root);+ playden::Storage library_storage(user_root);playden::steam::CmClient cm_client(paths.trust_store, library_storage);cm_client.SetOwner("library");cm_client.SetSharedSession(steam_cm);@@ -271,7 +278,7 @@ int main() {details_cm.SetOwner("details");details_cm.SetSharedSession(steam_cm);playden::steam::CmAppDetailsSource details_source(details_cm);- playden::LocalSessionRepository details_sessions(paths.steam_state_root);+ playden::LocalSessionRepository details_sessions(user_root);playden::steam::AppDetailsService app_details(details_source, details_sessions);playden::steam::CmClient install_cm(paths.trust_store, library_storage);install_cm.SetOwner("install");@@ -294,10 +301,10 @@ int main() {std::snprintf(line, sizeof(line), "app=%u step=%s result=%s detail=%s", app, step, category, detail);playden::app::AppendLogLine(log_root, "install.log", line);});- playden::LocalSessionRepository install_sessions(paths.steam_state_root);+ playden::LocalSessionRepository install_sessions(user_root);// A console-formatted M.2's root belongs to root: Playden's folder there is made as root.auto install_volumes = playden::steam::DiscoverInstallVolumes(- playden::steam::ConsoleVolumeCandidates(paths.title_root),+ playden::steam::ConsoleVolumeCandidates(paths.title_root, playden::ps5::EffectiveGamesRoot(paths)),[](const std::function<bool()>& work) { return playden::ps5::WithRoot(work); });for (const auto& volume : install_volumes)playden::app::AppendLogLine(log_root, "install.log", "volume id=" + volume.id + " root=" + volume.games_root +@@ -311,9 +318,9 @@ int main() {cloud_runner.SetLog([](playden::GameId app, const char* event, const std::string& message) {playden::app::AppendLogLine(log_root, "cloud.log", "app=" + std::to_string(app) + " event=" + event + " " + message);});- playden::LocalSessionRepository cloud_sessions(paths.steam_state_root);+ playden::LocalSessionRepository cloud_sessions(user_root);playden::steam::CloudService cloud(cloud_runner, cloud_sessions);- simulation.SetLogDirectory(paths.log_root);+ simulation.SetLogDirectory(log_root);// Playden's own update: it looks for a newer release on GitHub at startup, stages it on// request, and swaps the app (and kit) when Playden quits for it. Start() runs before the// runtime admits the kit: an update that did not take puts the previous kit back.@@ -327,6 +334,7 @@ int main() {update_config.kits_root = "/data/playden/kits";update_config.appmeta_root = std::string("/user/appmeta/") + PLAYDEN_PS5_TITLE_ID;update_config.registered_app_root = std::string("/user/app/") + PLAYDEN_PS5_TITLE_ID;+ update_config.layout_journal = "/data/playden/runtime-state/layout-0.5.json";update_config.current = playden::update::CurrentVersion();update_config.fetch = [&update_http](const playden::steam::HttpRequest& request, const std::atomic<bool>& cancel) {return update_http.Perform(request, cancel);@@ -360,7 +368,7 @@ int main() {self_update.Start();self_update.Check(false);// "Export as recipe" writes next to the logs, which are read over FTP already.- simulation.SetRecipeExportTarget(paths.log_root, playden::ps5::ConsoleFirmwareVersion().value_or(""));+ simulation.SetRecipeExportTarget(log_root, playden::ps5::ConsoleFirmwareVersion().value_or(""));// Per-game runtime: private bottles and PS5 titles from the admitted kit.// Its worker owns OWNER records, native inventory and publication.std::unique_ptr<playden::homebrew::RuntimeHost> runtime_host;@@ -478,7 +486,7 @@ int main() {};runtime_host = std::make_unique<playden::homebrew::RuntimeHost>(std::move(config));if (!runtime_host->Start())- playden::app::AppendLogLine(paths.log_root, "runtime.log", "runtime worker could not start");+ playden::app::AppendLogLine(log_root, "runtime.log", "runtime worker could not start");}playden::homebrew::Controller services(simulation, auth, sessions,&library_service,&persistence,&app_details,&installs,&cloud,runtime_host.get(), [](const std::string& line) {diff --git a/src/homebrew/simulation.cpp b/src/homebrew/simulation.cppindex 093eab5..8333109 100644--- a/src/homebrew/simulation.cpp+++ b/src/homebrew/simulation.cpp@@ -997,7 +997,7 @@ void Simulation::UpdateRuntimeProblem(const std::string& raw) {if (!live()) return;std::string words;if (raw.find("data root") != std::string::npos)- words = "Playden can't use its game folder /data/playden. Make it writable (chmod 777 over FTP) and restart Playden.";+ words = "Playden can't use its data folder /data/playden. Make it writable (chmod 777 over FTP) and restart Playden.";else if (raw.find("directory boundary") != std::string::npos)words = "The console's /data is mounted in a way Playden can't use. ShadowMountPlus 1.7beta4 or later does this: ""load 1.7beta2 and restart Playden.";@@ -1013,6 +1013,12 @@ void Simulation::UpdateRuntimeProblem(const std::string& raw) {rebuild_view();}+void Simulation::ShowLayoutNotice(const std::string& text) {+ if (!live() || text.empty()) return;+ push_notice({"layout", text, "", false, kLiveNoticeSeconds * 2, false, ""});+ rebuild_view();+}+void Simulation::UpdateSelfUpdate(const LiveSelfUpdate& update) {if (!live()) return;const LiveSelfUpdate before = state_.self_update;diff --git a/src/homebrew/simulation.hpp b/src/homebrew/simulation.hppindex 30801d1..7c6b992 100644--- a/src/homebrew/simulation.hpp+++ b/src/homebrew/simulation.hpp@@ -623,6 +623,8 @@ public:// The game runtime could not start (raw: its log reason; empty: it runs). Shown on every screen// until it is fixed, with the reason under Settings › Runtime status (#64).void UpdateRuntimeProblem(const std::string& raw);+ // Live mode: a one-line note from startup's data layout move (a step held back this start).+ void ShowLayoutNotice(const std::string& text);// Live mode: Playden's own update, and what the player asked of it: "check" (from Settings),// "install", "cancel", "restart" (apply at quit; quit follows), "rollback" (put the previous// version back at quit; quit follows) and "acknowledge" (a finished update's message was shown).diff --git a/src/platform/ps5/native_access.cpp b/src/platform/ps5/native_access.cppindex 95c3d4c..e59bafc 100644--- a/src/platform/ps5/native_access.cpp+++ b/src/platform/ps5/native_access.cpp@@ -26,8 +26,15 @@ NativePaths PathsAt(const std::string& root) {Join(root, "playden-data"), Join(root, "logs"), {}};}+// Where Playden will keep its state: the stubs must be writable (or creatable).+// Granted starts keep it outside the app folder (0.5 layout), so there the stubs+// only need to be readable folders: over FTP they are root's and 0755.+enum class StubState { kWritable, kReadable };+bool ValidatePaths(const NativeAccessOps& ops, const NativePaths& paths,- bool known_fresh_state, std::string* error) {+ bool known_fresh_state, StubState stubs, std::string* error) {+ const auto stub_access = stubs == StubState::kWritable ? NativePathAccess::kReadWrite+ : NativePathAccess::kRead;if (ops.path_kind(ops.context, paths.title_root.c_str()) !=NativePathKind::kDirectory ||!ops.path_accessible(ops.context, paths.title_root.c_str(),@@ -57,7 +64,7 @@ bool ValidatePaths(const NativeAccessOps& ops, const NativePaths& paths,}if (state == NativePathKind::kDirectory &&!ops.path_accessible(ops.context, paths.steam_state_root.c_str(),- NativePathAccess::kReadWrite)) {+ stub_access)) {*error = "existing Steam state root is inaccessible";return false;}@@ -68,12 +75,12 @@ bool ValidatePaths(const NativeAccessOps& ops, const NativePaths& paths,return false;}if (logs == NativePathKind::kDirectory &&- !ops.path_accessible(ops.context, paths.log_root.c_str(),- NativePathAccess::kReadWrite)) {+ !ops.path_accessible(ops.context, paths.log_root.c_str(), stub_access)) {*error = "existing log root is inaccessible";return false;}- if ((state == NativePathKind::kMissing || logs == NativePathKind::kMissing) &&+ if (stubs == StubState::kWritable &&+ (state == NativePathKind::kMissing || logs == NativePathKind::kMissing) &&!ops.path_accessible(ops.context, paths.title_root.c_str(),NativePathAccess::kReadWrite)) {*error = "fresh Steam state or log root cannot be created";@@ -126,7 +133,8 @@ NativeAccessResult NativeAccessBootstrap::LauncherFallback(if (stable && source_identity_captured_ && ops_.read_source_identity) {std::string path_error;std::string identity;- if (ValidatePaths(ops_, *stable, options_.known_fresh_state, &path_error) &&+ if (ValidatePaths(ops_, *stable, options_.known_fresh_state,+ StubState::kWritable, &path_error) &&ops_.read_source_identity(ops_.context, stable->title_root.c_str(),&identity) &&!identity.empty() && identity == source_identity_) {@@ -139,7 +147,8 @@ NativeAccessResult NativeAccessBootstrap::LauncherFallback(const NativePaths sandbox = PathsAt(options_.sandbox_root);std::string path_error;- if (!ValidatePaths(ops_, sandbox, options_.known_fresh_state, &path_error)) {+ if (!ValidatePaths(ops_, sandbox, options_.known_fresh_state,+ StubState::kWritable, &path_error)) {result.error += "; launcher paths unavailable: " + path_error;return result;}@@ -201,7 +210,8 @@ NativeAccessResult NativeAccessBootstrap::PrepareAccess() {} else {std::string sandbox_error;if (!ValidatePaths(ops_, PathsAt(options_.sandbox_root),- options_.known_fresh_state, &sandbox_error)) {+ options_.known_fresh_state, StubState::kReadable,+ &sandbox_error)) {return LauncherFallback("launcher source is invalid: " + sandbox_error);}if (!ops_.read_source_identity(ops_.context,@@ -219,7 +229,8 @@ NativeAccessResult NativeAccessBootstrap::PrepareAccess() {const NativePaths stable = PathsAt(stable_root);auto stable_title_ready = [&]() {std::string ignored;- if (!ValidatePaths(ops_, stable, options_.known_fresh_state, &ignored))+ if (!ValidatePaths(ops_, stable, options_.known_fresh_state,+ StubState::kReadable, &ignored))return false;std::string identity;return ops_.read_source_identity(ops_.context, stable_root.c_str(),@@ -248,7 +259,8 @@ NativeAccessResult NativeAccessBootstrap::PrepareAccess() {&stable);std::string path_error;- if (!ValidatePaths(ops_, stable, options_.known_fresh_state, &path_error)) {+ if (!ValidatePaths(ops_, stable, options_.known_fresh_state,+ StubState::kReadable, &path_error)) {return LauncherFallback("stable launcher source is invalid: " + path_error,&stable);}diff --git a/src/platform/ps5/native_access.h b/src/platform/ps5/native_access.hindex bf924a6..3c11822 100644--- a/src/platform/ps5/native_access.h+++ b/src/platform/ps5/native_access.h@@ -49,6 +49,13 @@ struct NativeAccessOptions {bool require_grant = false;};+// Package paths: the title, its assets and trust store, and the stub+// playden-data/logs folders. Granted starts need the stubs only as readable+// folders; a launcher without the grant keeps its state there, so they must be+// writable. After the grant, the+// 0.5 layout move fills user_root, user_log_root and games_root (each at the+// new place once its step has moved, else the old in-app one). Not granted:+// they stay empty and the package paths are used.struct NativePaths {std::string title_root;std::string assets_root;@@ -56,8 +63,22 @@ struct NativePaths {std::string steam_state_root;std::string log_root;std::string runtime_data_root;+ std::string user_root;+ std::string user_log_root;+ std::string games_root;};+// Where services keep user data, logs and console-storage games this start.+inline const std::string& EffectiveUserRoot(const NativePaths& paths) {+ return paths.user_root.empty() ? paths.steam_state_root : paths.user_root;+}+inline const std::string& EffectiveLogRoot(const NativePaths& paths) {+ return paths.user_log_root.empty() ? paths.log_root : paths.user_log_root;+}+inline std::string EffectiveGamesRoot(const NativePaths& paths) {+ return paths.games_root.empty() ? paths.title_root + "/games" : paths.games_root;+}+struct NativeAccessResult {bool launcher_ready = false;bool runtime_ready = false;@@ -65,6 +86,7 @@ struct NativeAccessResult {bool already_accessible = false;NativePaths paths;std::string error;+ std::string notice; // one line for the user about the data layout, when set};// Orders the portable parts of startup around the root-view change. Successfuldiff --git a/src/platform/ps5/native_startup.cpp b/src/platform/ps5/native_startup.cppindex efe1087..f13a704 100644--- a/src/platform/ps5/native_startup.cpp+++ b/src/platform/ps5/native_startup.cpp@@ -1,5 +1,8 @@#include "platform/ps5/native_startup.h"#include "platform/ps5/native_access_posix.h"+#include "platform/ps5/title_activity.h"+#include "platform/ps5/title_allow_list.h"+#include "runtime/layout_migration.h"#include <EGL/egl.h>#include "steam/backend/native_network.h"#include "app/diagnostic_log.h"@@ -10,6 +13,7 @@#include <sys/stat.h>#include <time.h>#include <unistd.h>+#include <vector>extern "C" int sceUserServiceInitialize(const void*);#if PLAYDEN_NATIVE_ACCESS_SOURCE@@ -53,16 +57,16 @@ int PrepareGraphics(void* data) {return result;}-void ReportSessionAccess(const std::string& root, const char* stage) {- const std::string file = root + "/playden-data/session.v1";+void ReportSessionAccess(const std::string& state_root, const std::string& log_root, const char* stage) {+ const std::string file = state_root + "/session.v1";struct stat metadata{};const int status = stat(file.c_str(), &metadata);const int status_error = status ? errno : 0;const int descriptor = open(file.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK);const int open_error = descriptor < 0 ? errno : 0;if (descriptor >= 0) close(descriptor);- app::AppendLogLine(root + "/logs", "native-startup.log",- std::string("session access stage=") + stage ++ app::AppendLogLine(log_root, "native-startup.log",+ std::string("session access stage=") + stage + " file=" + file +" uid=" + std::to_string(getuid()) + " euid=" + std::to_string(geteuid()) +" gid=" + std::to_string(getgid()) + " egid=" + std::to_string(getegid()) +" stat_error=" + std::to_string(status_error) +@@ -72,6 +76,17 @@ void ReportSessionAccess(const std::string& root, const char* stage) {" open_error=" + std::to_string(open_error));}+// After the grant, before the layout move has run this start: the session file+// is at /data/playden/user once an earlier start moved it, else in the app folder.+// The line stays in the app's logs: writing into /data/playden/logs before the+// move would make that folder look taken.+void ReportGrantedSessionAccess(const std::string& title_id, const char* stage) {+ const std::string stable = "/data/homebrew/" + title_id;+ struct stat metadata{};+ const bool moved = stat("/data/playden/user/session.v1", &metadata) == 0;+ ReportSessionAccess(moved ? "/data/playden/user" : stable + "/playden-data", stable + "/logs", stage);+}+int RequestData(void* data) {#if PLAYDEN_NATIVE_ACCESS_SOURCEauto& context = *static_cast<StartupContext*>(data);@@ -91,7 +106,7 @@ int RequestData(void* data) {}if (helper.empty()) return ENOENT;const uid_t original_effective_uid = geteuid();- ReportSessionAccess("/app0", "before-grant");+ ReportSessionAccess("/app0/playden-data", "/app0/logs", "before-grant");struct pw_lapy_elevation_diagnostics diagnostic{};const int grant = pw_lapy_elevation_request_at_detailed(static_cast<std::int32_t>(getpid()), helper.c_str(), &diagnostic);@@ -100,7 +115,7 @@ int RequestData(void* data) {" status=" + (diagnostic.helper_status_valid ? std::to_string(diagnostic.helper_status) : "unavailable") +" error=" + std::to_string(diagnostic.error);if (grant != 0) return grant_error ? grant_error : EIO;- ReportSessionAccess("/data/homebrew/" + context.title_id, "after-grant");+ ReportGrantedSessionAccess(context.title_id, "after-grant");// The filesystem grant must not change ownership of the launcher's private// session/settings files. Let the kernel clone/update the credential normally;// keep the granted root view and verify effective UID before services start.@@ -110,7 +125,7 @@ int RequestData(void* data) {return restore_error;}if (geteuid() != original_effective_uid) return EACCES;- ReportSessionAccess("/data/homebrew/" + context.title_id, "after-uid-restore");+ ReportGrantedSessionAccess(context.title_id, "after-uid-restore");// The helper may still be settling the process after its cooperative reply.struct timespec delay{1, 0};while (nanosleep(&delay, &delay) != 0)@@ -138,7 +153,43 @@ NativeAccessResult PrepareNativeStartup(const std::string& title_id) {auto result = bootstrap.Prepare();if (!result.runtime_ready && !context.grant_diagnostic.empty())result.error += "; " + context.grant_diagnostic;- const std::string logs = result.launcher_ready ? result.paths.log_root : "/app0/logs";+ // The 0.5 layout: user data, logs and games leave the app folder once. Still+ // single-threaded here, so the short root raises (the games rename, renames out of+ // root-owned stub folders, creating /data/playden-games) affect no other thread.+ std::vector<std::string> layout_lines;+ if (result.runtime_ready && !result.paths.runtime_data_root.empty()) {+ namespace fs = std::filesystem;+ const fs::path data_root = result.paths.runtime_data_root;+ runtime::LayoutPaths layout;+ layout.app_root = result.paths.title_root;+ layout.user_root = data_root / "user";+ layout.log_root = data_root / "logs";+ layout.games_root = data_root.parent_path() / "playden-games";+ layout.state_root = data_root / "runtime-state";+ layout.boundary = data_root.parent_path();+ runtime::LayoutOps layout_ops;+ layout_ops.as_root = [](const std::function<bool()>& work) { return WithRoot(work); };+ layout_ops.log = [&layout_lines](const std::string& line) { layout_lines.push_back(line); };+ // Read-only kernel process list: the game of a launch session left pending.+ layout_ops.title_running = [&layout_lines](const std::string& title) -> std::optional<bool> {+ std::string reason;+ const auto activity = ReadTitleActivity(title, &reason);+ if (activity == runtime::NativeActivity::kUnknown) {+ layout_lines.push_back("title activity " + title + " unknown: " + reason);+ return std::nullopt;+ }+ return activity == runtime::NativeActivity::kActive;+ };+ const auto moved = runtime::MigrateLayout(layout, layout_ops);+ result.paths.user_root = moved.user_root.string();+ result.paths.user_log_root = moved.log_root.string();+ result.paths.games_root = moved.games_root.string();+ result.notice = moved.notice;+ }+ const std::string logs = result.launcher_ready ? EffectiveLogRoot(result.paths) : "/app0/logs";+ for (const auto& line : layout_lines) app::AppendLogLine(logs, "native-startup.log", line);+ if (!result.paths.user_root.empty())+ ReportSessionAccess(result.paths.user_root, logs, "after-layout");if (!context.grant_diagnostic.empty())app::AppendLogLine(logs, "native-startup.log", context.grant_diagnostic);app::AppendLogLine(logs, "native-startup.log",diff --git a/src/runtime/layout_migration.cpp b/src/runtime/layout_migration.cppnew file mode 100644index 0000000..f0dd438--- /dev/null+++ b/src/runtime/layout_migration.cpp@@ -0,0 +1,501 @@+#include "runtime/layout_migration.h"+#include "runtime/game_install.h"+#include "runtime/private_directories.h"+#include "platform/storage.h"+#include "steam/backend/json.h"++#include <algorithm>+#include <cctype>+#include <cerrno>+#include <cstdio>+#include <cstring>+#include <fcntl.h>+#include <unistd.h>+#include <sys/stat.h>+#include <vector>++namespace playden::runtime {+namespace fs = std::filesystem;+namespace {+constexpr const char* kMovedMarker = "MOVED.txt";+constexpr const char* kGamesMarker = "games-MOVED.txt";++enum Step { kNone, kUser, kLogs, kGames, kGamesMoved, kDone };++Step StepIndex(const std::string& step) {+ if (step == "user") return kUser;+ if (step == "logs") return kLogs;+ if (step == "games") return kGames;+ if (step == "games-moved") return kGamesMoved;+ if (step == "done") return kDone;+ // An interrupted revert left both layouts in use: resume the move from the start.+ if (step.rfind("revert-", 0) == 0) return kUser;+ return kNone;+}++void Log(const LayoutOps& ops, const std::string& line) {+ if (ops.log) ops.log("layout: " + line);+}++std::error_code Rename(const LayoutOps& ops, const fs::path& from, const fs::path& to) {+ if (ops.rename) return ops.rename(from, to);+ if (::rename(from.c_str(), to.c_str()) == 0) return {};+ return {errno, std::generic_category()};+}++bool AsRoot(const LayoutOps& ops, const std::function<bool()>& work) {+ return ops.as_root ? ops.as_root(work) : work();+}++// Renames as the app user; a folder only root may write gets a second try as root.+std::error_code RenameEntry(const LayoutOps& ops, const fs::path& from, const fs::path& to) {+ auto error = Rename(ops, from, to);+ if ((error.value() == EACCES || error.value() == EPERM) && ops.as_root) {+ std::error_code rooted;+ const bool ran = ops.as_root([&] { rooted = Rename(ops, from, to); return !rooted; });+ if (!rooted && ran) return {};+ if (rooted) error = rooted;+ }+ return error;+}++std::string Describe(const std::error_code& error) {+ return "errno=" + std::to_string(error.value()) + " (" + error.message() + ")";+}++// 0: missing, 1: directory, 2: something else.+int Kind(const fs::path& path) {+ struct stat info{};+ if (::lstat(path.c_str(), &info) != 0) return errno == ENOENT ? 0 : 2;+ return S_ISDIR(info.st_mode) ? 1 : 2;+}++bool Exists(const fs::path& path) {+ struct stat info{};+ return ::lstat(path.c_str(), &info) == 0 || errno != ENOENT;+}++// Entries, without the markers this move leaves behind. Nothing when unreadable.+std::optional<std::vector<std::string>> Entries(const fs::path& directory) {+ std::vector<std::string> names;+ std::error_code error;+ for (fs::directory_iterator it(directory, error), end; !error && it != end; it.increment(error)) {+ const auto name = it->path().filename().string();+ if (name != kMovedMarker && name != kGamesMarker) names.push_back(name);+ }+ if (error) return std::nullopt;+ std::sort(names.begin(), names.end());+ return names;+}++// Where a log named `name` lands in `to`: its own name, else "name.moved", "name.moved.2", ...+// (each interrupted start can leave one more copy). Nothing when all are taken.+std::optional<fs::path> LogTarget(const fs::path& to, const std::string& name) {+ if (!Exists(to / name)) return to / name;+ for (int copy = 1; copy <= 100; ++copy) {+ auto target = to / (name + ".moved" + (copy == 1 ? std::string() : "." + std::to_string(copy)));+ if (!Exists(target)) return target;+ }+ return std::nullopt;+}++bool EmptyDirectory(const fs::path& directory) {+ const auto names = Entries(directory);+ return names && names->empty();+}++// A shared (0777) folder, made as root when the app user can't create it there.+bool EnsureSharedDirectory(const LayoutOps& ops, const fs::path& directory) {+ const int kind = Kind(directory);+ if (kind == 1) return true;+ if (kind == 2) return false;+ const auto make = [&] {+ return (::mkdir(directory.c_str(), 0777) == 0 || Kind(directory) == 1) && ::chmod(directory.c_str(), 0777) == 0;+ };+ if (make()) return true;+ return (errno == EACCES || errno == EPERM) && AsRoot(ops, make) && Kind(directory) == 1;+}++void WriteMarker(const LayoutOps& ops, const fs::path& file, const std::string& text) {+ FILE* out = std::fopen(file.c_str(), "w");+ const bool written = out && std::fputs(text.c_str(), out) >= 0;+ if (out && std::fclose(out) != 0) Log(ops, "could not close " + file.string());+ if (!written) Log(ops, "could not write " + file.string() + ": " + std::strerror(errno));+}++std::string Escape(const std::string& text) {+ std::string out;+ for (const unsigned char c : text) {+ if (c == '"' || c == '\\') { out += '\\'; out += static_cast<char>(c); }+ else if (c < 0x20) { char hex[8]; std::snprintf(hex, sizeof hex, "\\u%04x", c); out += hex; }+ else out += static_cast<char>(c);+ }+ return out;+}++bool PrepareState(const LayoutPaths& paths, std::string* error) {+ return EnsurePrivateDirectories(paths.boundary, paths.state_root, paths.state_root, error);+}++bool SaveJournal(const fs::path& state_root, const LayoutJournal& journal, std::string* error) {+ const std::string text = "{\"step\":\"" + Escape(journal.step) + "\",\"from\":\"" + Escape(journal.from) ++ "\",\"to\":\"" + Escape(journal.to) + "\",\"postponed\":" ++ std::to_string(journal.postponed) + "}\n";+ const auto written = Storage(state_root.string()).WriteDurable(kLayoutJournal, Bytes(text.begin(), text.end()));+ if (!written.ok() && error) *error = written.message();+ return written.ok();+}++// Whether a game's publication receipt (publication-state.v1, a small JSON file) is committed.+// Read-only, without the publisher lease: the receipt is replaced whole, never edited in place.+bool ReceiptCommitted(const fs::path& path) {+ const int fd = ::open(path.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC);+ if (fd < 0) return false;+ std::string text(8192, '\0');+ std::size_t done = 0;+ for (ssize_t count; done < text.size() && (count = ::read(fd, text.data() + done, text.size() - done)) > 0;)+ done += static_cast<std::size_t>(count);+ const bool whole = done < text.size();+ ::close(fd);+ text.resize(done);+ const auto root = whole ? steam::json::Parse(text) : std::nullopt;+ const auto* phase = root && root->is_object() ? root->Find("phase") : nullptr;+ return phase && phase->is_string() && phase->text() == "committed";+}++// The title of a pending launch session (StorageLaunchSessionJournal's PLAYDEN-LAUNCH-V1 file:+// its 4th line is the title ID in hex). Nothing when the file is not one.+std::optional<std::string> PendingLaunchTitle(const Bytes& bytes) {+ const std::string text(bytes.begin(), bytes.end());+ std::vector<std::string> lines;+ for (std::size_t start = 0; start <= text.size() && lines.size() < 4;) {+ const auto end = text.find('\n', start);+ if (end == std::string::npos) break;+ lines.push_back(text.substr(start, end - start));+ start = end + 1;+ }+ if (lines.size() < 4 || lines[0] != "PLAYDEN-LAUNCH-V1" || lines[3].empty() || lines[3].size() % 2 || lines[3].size() > 64)+ return std::nullopt;+ std::string title;+ for (std::size_t i = 0; i < lines[3].size(); i += 2) {+ unsigned value = 0;+ if (std::sscanf(lines[3].c_str() + i, "%2x", &value) != 1 || !std::isxdigit(static_cast<unsigned char>(lines[3][i])) ||+ !std::isxdigit(static_cast<unsigned char>(lines[3][i + 1])))+ return std::nullopt;+ title.push_back(static_cast<char>(value));+ }+ for (const char c : title)+ if (!std::isalnum(static_cast<unsigned char>(c))) return std::nullopt;+ return title;+}++// What would make the games rename strand an operation: a prepare/publication journal+// in the install records, an active settings operation in a game's control folder, or+// a launch session (StorageLaunchSessionJournal's pending file) for a game that may run.+// A pending session is only cleared once Playden sees its game end, which a game closed+// while Playden was not running never shows: its title is asked about (ops.title_running).+std::optional<std::string> PendingJournal(const LayoutPaths& paths, const LayoutOps& ops) {+ Storage storage(paths.state_root.string());+ const auto launch = storage.ReadDurable("launch-pending.v1", 64 * 1024);+ if (launch.ok()) {+ const auto title = PendingLaunchTitle(launch.value());+ const auto running = title && ops.title_running ? ops.title_running(*title) : std::nullopt;+ Log(ops, "pending launch title=" + (title ? *title : std::string("unreadable")) + " running=" ++ (running ? (*running ? "yes" : "no") : "unknown"));+ if (!running || *running)+ return std::string("the last game you started from Playden may still be running or suspended. Close it, and "+ "Playden moves them the next time it starts");+ } else if (launch.error() != StorageError::kNotFound) {+ return "the pending launch session can't be read (" + launch.message() + ")";+ }+ RuntimeInstallRepository repository(storage, "installs.json", {});+ const auto loaded = repository.Load();+ if (!loaded.ok()) return "the install records can't be read (" + loaded.message() + ")";+ for (const auto& record : repository.Snapshot()) {+ if (record.journal)+ return "install " + record.install_id + " has a pending " + record.journal->operation + " journal";+ // data_root is /data/playden/games/<id>; map it under this layout's boundary.+ const auto relative = fs::path(record.data_root).lexically_relative("/data");+ if (relative.empty() || *relative.begin() == "..") continue;+ // The last operation stays in the control folder after it commits; only one whose receipt+ // isn't committed is still in flight. (One being captured has a record journal, above.)+ const auto control = paths.boundary / relative / ".playden-control";+ if (Exists(control / "settings-operation.v1") && !ReceiptCommitted(control / "publication-state.v1"))+ return "install " + record.install_id + " has a pending settings publication";+ }+ return std::nullopt;+}++// Moves every entry of `from` into `to`, never replacing one. A failed entry puts+// back what this call moved, so this start keeps one complete layout. Logs keep+// every copy of a name: the moving one gets ".moved", ".moved.2", ...+bool MoveEntries(const LayoutOps& ops, const fs::path& from, const fs::path& to, bool logs, std::string* reason) {+ if (Kind(from) != 1) return true; // fresh install: nothing to move+ const auto names = Entries(from);+ if (!names) {+ *reason = from.string() + " can't be listed";+ return false;+ }+ std::vector<std::pair<fs::path, fs::path>> moved;+ for (const auto& name : *names) {+ const auto slot = logs ? LogTarget(to, name) : Exists(to / name) ? std::nullopt : std::optional(to / name);+ if (!slot) {+ *reason = (from / name).string() + " and " + (to / name).string() + " both exist";+ break;+ }+ const auto& target = *slot;+ const auto error = RenameEntry(ops, from / name, target);+ if (error) {+ *reason = "rename " + (from / name).string() + " -> " + target.string() + " failed " + Describe(error);+ break;+ }+ moved.emplace_back(from / name, target);+ }+ if (moved.size() == names->size()) return true;+ for (auto it = moved.rbegin(); it != moved.rend(); ++it) {+ const auto error = RenameEntry(ops, it->second, it->first);+ if (error) Log(ops, "could not put back " + it->second.string() + ": " + Describe(error));+ }+ return false;+}++std::string MovedText(const fs::path& to) {+ return "Playden 0.5 moved this folder's contents to " + to.string() + "\n";+}+} // namespace++std::optional<LayoutJournal> LoadLayoutJournal(const fs::path& state_root, std::string* error) {+ if (error) error->clear();+ const auto read = Storage(state_root.string()).ReadDurable(kLayoutJournal, 64 * 1024);+ if (!read.ok()) {+ if (error && read.error() != StorageError::kNotFound) *error = read.message();+ return std::nullopt;+ }+ const auto root = steam::json::Parse(std::string_view(reinterpret_cast<const char*>(read.value().data()),+ read.value().size()));+ const auto* step = root && root->is_object() ? root->Find("step") : nullptr;+ const auto* from = root && root->is_object() ? root->Find("from") : nullptr;+ const auto* to = root && root->is_object() ? root->Find("to") : nullptr;+ const auto* postponed = root && root->is_object() ? root->Find("postponed") : nullptr;+ if (!step || !step->is_string() || !from || !from->is_string() || !to || !to->is_string()) {+ if (error) *error = "layout journal is malformed";+ return std::nullopt;+ }+ LayoutJournal journal{step->text(), from->text(), to->text(), 0};+ if (postponed && postponed->is_number() && postponed->AsUint64() && *postponed->AsUint64() < 1000000)+ journal.postponed = static_cast<int>(*postponed->AsUint64());+ return journal;+}++bool MarkLayoutDone(const fs::path& state_root, std::string* error) {+ std::string load_error;+ auto journal = LoadLayoutJournal(state_root, &load_error);+ if (!journal) {+ if (error) *error = load_error.empty() ? "no layout journal" : load_error;+ return false;+ }+ journal->step = "done";+ journal->postponed = 0;+ return SaveJournal(state_root, *journal, error);+}++LayoutResult MigrateLayout(const LayoutPaths& paths, const LayoutOps& ops) {+ const auto old_user = paths.app_root / "playden-data";+ const auto old_logs = paths.app_root / "logs";+ const auto old_games = paths.app_root / "games";+ LayoutResult result;+ const auto finish = [&] {+ result.user_root = result.user_moved ? paths.user_root : old_user;+ result.log_root = result.logs_moved ? paths.log_root : old_logs;+ result.games_root = result.games_moved ? paths.games_root : old_games;+ if (!result.notice.empty()) Log(ops, "notice: " + result.notice);+ return result;+ };+ const auto hold = [&](const std::string& why) {+ Log(ops, why);+ result.notice = "Playden kept some data in its app folder: " + why;+ return finish();+ };++ std::string error;+ if (!PrepareState(paths, &error)) return hold("the runtime state folder is unavailable (" + error + ")");+ auto loaded = LoadLayoutJournal(paths.state_root, &error);+ if (!loaded && !error.empty()) return hold("the move record " + (paths.state_root / kLayoutJournal).string() ++ " can't be read (" + error + ")");+ LayoutJournal journal = loaded.value_or(LayoutJournal{});+ // Once the games step is done the games folder exists, shared: a fresh install has+ // none to move. One that came with the moved games keeps its mode.+ const auto ensure_games_root = [&] {+ if (Kind(paths.games_root) == 0 && !EnsureSharedDirectory(ops, paths.games_root))+ Log(ops, paths.games_root.string() + " can't be created: " + std::strerror(errno));+ };+ const Step initial = StepIndex(journal.step);+ if (initial >= kGamesMoved) {+ result.user_moved = result.logs_moved = result.games_moved = true;+ ensure_games_root();+ return finish();+ }+ // After an interrupted revert both places hold Playden's own files: merge them back.+ const bool reverted = journal.step.rfind("revert-", 0) == 0;+ const auto save = [&](const char* step, const fs::path& from, const fs::path& to, int postponed = 0) {+ LayoutJournal updated{step, from.string(), to.string(), postponed};+ if (!SaveJournal(paths.state_root, updated, &error)) return false;+ journal = updated;+ return true;+ };++ // User data, then logs: the stub folders stay for the pre-grant path checks.+ // A step is recorded before it starts; a target that already had files is refused+ // only before then, since afterwards its files are the move's own.+ struct Tree { Step step; const char* name; fs::path from, to; bool logs; bool* moved; };+ const Tree trees[] = {{kUser, "user", old_user, paths.user_root, false, &result.user_moved},+ {kLogs, "logs", old_logs, paths.log_root, true, &result.logs_moved}};+ for (const auto& tree : trees) {+ if (initial > tree.step) { *tree.moved = true; continue; }+ if (journal.step != tree.name && !reverted) {+ const int kind = Kind(tree.to);+ if (kind == 2 || (kind == 1 && !EmptyDirectory(tree.to)))+ return hold(tree.to.string() + " already has files; " + tree.from.string() + " was kept. "+ "Move them aside and restart Playden.");+ }+ if (!EnsureSharedDirectory(ops, tree.to)) return hold(tree.to.string() + " can't be created");+ if (journal.step != tree.name && !save(tree.name, tree.from, tree.to))+ return hold("the move record can't be written (" + error + ")");+ std::string reason;+ if (!MoveEntries(ops, tree.from, tree.to, tree.logs, &reason)) return hold(reason);+ if (Kind(tree.from) == 1) WriteMarker(ops, tree.from / kMovedMarker, MovedText(tree.to));+ Log(ops, "moved " + tree.from.string() + " to " + tree.to.string());+ *tree.moved = true;+ }++ if (journal.step != "games" && !save("games", old_games, paths.games_root))+ return hold("the move record can't be written (" + error + ")");+ const auto moved_games = [&] {+ if (!save("games-moved", old_games, paths.games_root))+ Log(ops, "games are at " + paths.games_root.string() + " but the move record can't be written (" + error ++ "); the next start records it");+ result.games_moved = true;+ ensure_games_root();+ };+ const int old_kind = Kind(old_games);+ if (old_kind == 0) {+ // Nothing to move, or an interrupted start already renamed it.+ moved_games();+ return finish();+ }+ const auto postpone = [&](const std::string& why, bool tell_now) {+ const int count = journal.postponed + 1;+ if (!save("games", old_games, paths.games_root, count)) Log(ops, "the move record can't be written (" + error + ")");+ Log(ops, "games move postponed (" + std::to_string(count) + "): " + why);+ if (tell_now || count >= kLayoutPostponeNoticeAfter)+ result.notice = "Playden couldn't move your games to " + paths.games_root.string() + " yet: " + why;+ return finish();+ };+ if (old_kind != 1) {+ Log(ops, "games: " + old_games.string() + " is not a folder; nothing was moved");+ result.notice = old_games.string() + " is not a folder, so Playden left it in place.";+ return finish();+ }+ const int new_kind = Kind(paths.games_root);+ if (new_kind == 2 || (new_kind == 1 && !EmptyDirectory(paths.games_root))) {+ Log(ops, "games: " + paths.games_root.string() + " already has files; " + old_games.string() + " was kept");+ result.notice = paths.games_root.string() + " already has files, so Playden kept your games in " ++ old_games.string() + ". Move them aside and restart Playden.";+ return finish();+ }+ if (const auto pending = PendingJournal(paths, ops)) return postpone(*pending, false);+ std::error_code rename_error;+ const bool ran = AsRoot(ops, [&] {+ rename_error = Rename(ops, old_games, paths.games_root);+ return !rename_error;+ });+ if (rename_error || !ran) {+ if (rename_error.value() == EXDEV)+ return postpone(paths.games_root.string() + " is on another drive; nothing was copied", true);+ return postpone("rename failed " + (rename_error ? Describe(rename_error) : std::string("(root unavailable)")),+ true);+ }+ Log(ops, "moved " + old_games.string() + " to " + paths.games_root.string());+ moved_games();+ WriteMarker(ops, paths.app_root / kGamesMarker, MovedText(paths.games_root));+ return finish();+}++RevertResult RevertLayout(const LayoutPaths& paths, const LayoutOps& ops) {+ RevertResult result;+ std::string error;+ if (Kind(paths.state_root) == 0) {+ result.complete = true; // never moved+ return result;+ }+ auto journal = LoadLayoutJournal(paths.state_root, &error);+ if (!journal) {+ if (!error.empty()) result.error = "the move record can't be read: " + error;+ else result.complete = true; // never moved+ return result;+ }+ const auto save = [&](const char* step) {+ LayoutJournal updated = *journal;+ updated.step = step;+ if (!SaveJournal(paths.state_root, updated, &error)) {+ result.error = "the move record can't be written: " + error;+ return false;+ }+ return true;+ };+ const auto old_games = paths.app_root / "games";+ if (!save("revert-games")) return result;+ std::string problems;+ if (Kind(paths.games_root) == 1) {+ const int old_kind = Kind(old_games);+ if (old_kind == 0 || (old_kind == 1 && EmptyDirectory(old_games))) {+ std::error_code rename_error;+ const bool ran = AsRoot(ops, [&] {+ rename_error = Rename(ops, paths.games_root, old_games);+ return !rename_error;+ });+ if (rename_error || !ran) problems += "games rename failed " + Describe(rename_error) + "; ";+ else Log(ops, "moved " + paths.games_root.string() + " back to " + old_games.string());+ } else {+ problems += old_games.string() + " already has files; ";+ }+ }+ std::remove((paths.app_root / kGamesMarker).c_str());++ struct Tree { const char* step; fs::path from, to; bool logs; };+ const Tree trees[] = {{"revert-logs", paths.log_root, paths.app_root / "logs", true},+ {"revert-user", paths.user_root, paths.app_root / "playden-data", false}};+ for (const auto& tree : trees) {+ if (!save(tree.step)) return result;+ std::remove((tree.to / kMovedMarker).c_str());+ if (Kind(tree.from) != 1) continue;+ if (!EnsureSharedDirectory(ops, tree.to)) { problems += tree.to.string() + " can't be created; "; continue; }+ const auto names = Entries(tree.from);+ if (!names) { problems += tree.from.string() + " can't be listed; "; continue; }+ for (const auto& name : *names) {+ const auto target =+ tree.logs ? LogTarget(tree.to, name) : Exists(tree.to / name) ? std::nullopt : std::optional(tree.to / name);+ if (!target) {+ problems += (tree.to / name).string() + " already exists; ";+ continue;+ }+ const auto rename_error = RenameEntry(ops, tree.from / name, *target);+ if (rename_error) problems += "rename " + (tree.from / name).string() + " failed " + Describe(rename_error) + "; ";+ }+ Log(ops, "moved " + tree.from.string() + " back to " + tree.to.string());+ }+ if (!problems.empty()) {+ result.error = problems;+ Log(ops, "revert incomplete: " + problems);+ return result;+ }+ const auto removed = Storage(paths.state_root.string()).RemoveDurable(kLayoutJournal);+ if (!removed.ok()) {+ result.error = "the move record can't be removed: " + removed.message();+ return result;+ }+ result.complete = true;+ return result;+}++} // namespace playden::runtimediff --git a/src/runtime/layout_migration.h b/src/runtime/layout_migration.hnew file mode 100644index 0000000..4dbec63--- /dev/null+++ b/src/runtime/layout_migration.h@@ -0,0 +1,79 @@+#pragma once+// layout_migration.h - The 0.5.0 one-time move of user data, logs and games out of the app folder.+// Copyright (c) 2026 Playden contributors+// SPDX-License-Identifier: MIT+#include <filesystem>+#include <functional>+#include <optional>+#include <string>+#include <system_error>++namespace playden::runtime {++// Old places are inside the app folder (app_root); new ones are outside it.+struct LayoutPaths {+ std::filesystem::path app_root; // /data/homebrew/<title>: holds playden-data, logs and games+ std::filesystem::path user_root; // /data/playden/user+ std::filesystem::path log_root; // /data/playden/logs+ std::filesystem::path games_root; // /data/playden-games+ std::filesystem::path state_root; // /data/playden/runtime-state (private, holds the journal)+ std::filesystem::path boundary; // trusted parent the runtime creates state_root under (/data)+};++struct LayoutOps {+ // rename(2); returns the errno as an error_code. Empty: the real rename.+ std::function<std::error_code(const std::filesystem::path&, const std::filesystem::path&)> rename;+ // Runs work with root's effective UID. Empty: runs it directly (tests).+ std::function<bool(const std::function<bool()>&)> as_root;+ std::function<void(const std::string&)> log;+ // Whether a title (of a pending launch session) runs or is suspended; nothing: unknown.+ // Empty: unknown (the games move waits for the session to end).+ std::function<std::optional<bool>(const std::string& title_id)> title_running;+};++inline constexpr const char* kLayoutJournal = "layout-0.5.json";+// Pending-journal postponements of the games step before the user is told.+inline constexpr int kLayoutPostponeNoticeAfter = 3;++// Steps, in order: "user", "logs", "games", "games-moved", "done". A step is+// written before its action, so an interrupted move resumes there. At+// "games-moved", from/to are the old and new games prefixes; the runtime host+// rewrites its records, republishes, then calls MarkLayoutDone. RevertLayout+// writes "revert-games", "revert-logs", "revert-user", then removes the journal.+struct LayoutJournal {+ std::string step;+ std::string from;+ std::string to;+ int postponed = 0; // starts the games step waited for a pending install, publication or launch+};++// Nothing when there is no journal (or it can't be read; `error` says which).+std::optional<LayoutJournal> LoadLayoutJournal(const std::filesystem::path& state_root,+ std::string* error = nullptr);+bool MarkLayoutDone(const std::filesystem::path& state_root, std::string* error = nullptr);++struct LayoutResult {+ bool user_moved = false; // user data lives at paths.user_root+ bool logs_moved = false; // logs live at paths.log_root+ bool games_moved = false; // games live at paths.games_root+ // Effective roots for this start: the new place when that step has completed, else the old one.+ std::filesystem::path user_root;+ std::filesystem::path log_root;+ std::filesystem::path games_root;+ std::string notice; // one line for the user, when the move is held back+};++// Single-threaded, before any service starts, after the root grant. Never copies,+// never merges into a non-empty target, never replaces an existing entry.+LayoutResult MigrateLayout(const LayoutPaths& paths, const LayoutOps& ops);++struct RevertResult {+ bool complete = false; // everything is back in the app folder and the journal is gone+ std::string error;+};++// The reverse move, for a restore below 0.5.0. Entries that would replace an+// existing one stay in the new place, and the journal is kept so it can be retried.+RevertResult RevertLayout(const LayoutPaths& paths, const LayoutOps& ops);++} // namespace playden::runtimediff --git a/src/steam/install_volumes.cpp b/src/steam/install_volumes.cppindex 5fdcb3d..356b33f 100644--- a/src/steam/install_volumes.cpp+++ b/src/steam/install_volumes.cpp@@ -161,9 +161,12 @@ std::vector<InstallVolume> DiscoverInstallVolumes(const std::vector<VolumeCandidreturn volumes;}-std::vector<VolumeCandidate> ConsoleVolumeCandidates(const std::string& title_root) {+std::vector<VolumeCandidate> ConsoleVolumeCandidates(const std::string& title_root, const std::string& games_root) {+ const auto primary = games_root.empty() ? title_root + "/games" : games_root;+ const auto slash = primary.find_last_of('/');+ const auto mount = games_root.empty() ? title_root : slash == 0 ? std::string("/") : primary.substr(0, slash);return {- {InstallService::kPrimaryVolumeId, "Console storage", title_root, title_root + "/games"},+ {InstallService::kPrimaryVolumeId, "Console storage", mount, primary},{"m2", "M.2 SSD", "/mnt/ext1", "/mnt/ext1/playden/games", true},{"extended", "Extended storage", "/mnt/ext0", "/mnt/ext0/playden/games", true},{"usb0", "USB drive", "/mnt/usb0", "/mnt/usb0/playden/games", true},diff --git a/src/steam/install_volumes.h b/src/steam/install_volumes.hindex 49499a0..76499c5 100644--- a/src/steam/install_volumes.h+++ b/src/steam/install_volumes.h@@ -34,9 +34,11 @@ using AsRoot = std::function<bool(const std::function<bool()>& work)>;std::vector<InstallVolume> DiscoverInstallVolumes(const std::vector<VolumeCandidate>& candidates,const AsRoot& as_root = {});-// Candidate drives for the PS5 title: console storage under the verified title-// root, then extended storage and USB drives. Use the stable root after a grant.-std::vector<VolumeCandidate> ConsoleVolumeCandidates(const std::string& title_root = "/app0");+// Candidate drives for the PS5 title: console storage, then extended storage and+// USB drives. Console storage is games_root (after the grant, the 0.5 layout's+// /data/playden-games), or title_root/games when it is empty.+std::vector<VolumeCandidate> ConsoleVolumeCandidates(const std::string& title_root = "/app0",+ const std::string& games_root = {});struct VolumeSpace {std::uint64_t total_bytes = 0;diff --git a/src/update/update_service.cpp b/src/update/update_service.cppindex 9dcfee1..7a2656a 100644--- a/src/update/update_service.cpp+++ b/src/update/update_service.cpp@@ -4,6 +4,7 @@#include <sys/stat.h>#include <unistd.h>+#include <cerrno>#include <cstdio>#include <utility>@@ -287,8 +288,32 @@ std::optional<UpdateService::Backup> UpdateService::LatestBackup() const {return latest;}+namespace {+// 0.5.0 moved user data, logs and games out of the app folder; an older version finds none of it.+constexpr Version kLayoutBoundary{0, 5, 0};+} // namespace++std::string UpdateService::LayoutRefusal(const Version& to) const {+ if (!(to < kLayoutBoundary)) return {};+ if (!(config_.current < kLayoutBoundary)) return "this version uses the 0.5 data layout";+ if (config_.layout_journal.empty()) return {};+ // Moved (or being moved) when the move record is there; unknown counts as moved.+ struct stat info{};+ if (::lstat(config_.layout_journal.c_str(), &info) == 0) return "the 0.5 layout move record exists";+ if (errno != ENOENT) return "the 0.5 layout move record can't be checked (errno=" + std::to_string(errno) + ")";+ return {};+}+void UpdateService::FindPrevious() {- const auto backup = LatestBackup();+ auto backup = LatestBackup();+ if (backup) {+ const auto refusal = LayoutRefusal(backup->version);+ if (!refusal.empty()) {+ Log("go back to " + backup->version.ToString() + " not offered: it can't read the 0.5 data layout (" ++ refusal + ")");+ backup.reset();+ }+ }Set([&](UpdateSnapshot& s) {s.previous = backup && backup->version != config_.current ? backup->version.ToString() : std::string();});@@ -730,6 +755,10 @@ bool UpdateService::StageApp(const Release& release, const UpdateManifest& manifbool UpdateService::RollBackAtQuit() {const auto backup = LatestBackup();if (!backup) return false;+ if (const auto refusal = LayoutRefusal(backup->version); !refusal.empty()) {+ Log("going back refused: " + backup->version.ToString() + " can't read the 0.5 data layout (" + refusal + ")");+ return false;+ }const std::string stamp = std::to_string(config_.now());const std::string replaced = config_.work_root + "/replaced/" + config_.current.ToString() + "-" + stamp;// The kit that update replaced: ".previous-<kit_id>-<time>" with the backup's time. An updatediff --git a/src/update/update_service.h b/src/update/update_service.hindex 8d738b4..8f2c41e 100644--- a/src/update/update_service.h+++ b/src/update/update_service.h@@ -26,6 +26,9 @@ struct UpdateConfig {std::string kits_root; // /data/playden/kits; the kit lives at <kits_root>/<kit_id>std::string appmeta_root; // /user/appmeta/FAKE77031std::string registered_app_root; // /user/app/FAKE77031+ // The 0.5 layout move's record (/data/playden/runtime-state/layout-0.5.json). While it exists,+ // going back below 0.5.0 is refused whatever the current version. Empty: the version rule only.+ std::string layout_journal;Version current;Fetch fetch;std::function<std::optional<std::string>(const std::string& path)> hash_file;@@ -129,6 +132,8 @@ class UpdateService {void DoInstall();void ConfirmApplied(const std::string& state);bool RollBackAtQuit();+ // Why going back to `to` is refused (it can't read the 0.5 data layout), or empty.+ std::string LayoutRefusal(const Version& to) const;void FindPrevious();void LoadCurrentNotes();std::string PageFor(const std::string& tag) const;diff --git a/tests/install_volumes_test.cpp b/tests/install_volumes_test.cppindex 486b74a..200a4d2 100644--- a/tests/install_volumes_test.cpp+++ b/tests/install_volumes_test.cpp@@ -88,6 +88,13 @@ int main() {CHECK(!console.empty() && console[0].id == InstallService::kPrimaryVolumeId && console[0].games_root == "/app0/games");CHECK(!console[0].require_mount_point);for (std::size_t index = 1; index < console.size(); ++index) CHECK(console[index].require_mount_point);+ // After the grant, console storage is the games root outside the app folder.+ const auto granted = ConsoleVolumeCandidates("/data/homebrew/FAKE77031", "/data/playden-games");+ CHECK(granted.size() == console.size() && granted[0].id == InstallService::kPrimaryVolumeId);+ CHECK(granted[0].games_root == "/data/playden-games" && granted[0].mount == "/data" && !granted[0].require_mount_point);+ CHECK(ConsoleVolumeCandidates("/data/homebrew/FAKE77031")[0].games_root == "/data/homebrew/FAKE77031/games");+ for (std::size_t index = 1; index < granted.size(); ++index)+ CHECK(granted[index].games_root == console[index].games_root);const auto space = QueryVolumeSpace(base.string());CHECK(space && space->total_bytes > 0 && space->free_bytes <= space->total_bytes);diff --git a/tests/layout_migration_test.cpp b/tests/layout_migration_test.cppnew file mode 100644index 0000000..647b304--- /dev/null+++ b/tests/layout_migration_test.cpp@@ -0,0 +1,436 @@+#include "runtime/layout_migration.h"+#include "platform/storage.h"++#include <cerrno>+#include <cstdio>+#include <cstdlib>+#include <filesystem>+#include <fstream>+#include <memory>+#include <sstream>+#include <string>+#include <sys/stat.h>+#include <unistd.h>+#include <vector>++#define CHECK(c) do { if (!(c)) { std::fprintf(stderr, "%s:%d: %s\n", __FILE__, __LINE__, #c); std::exit(1); } } while (0)++namespace fs = std::filesystem;+using namespace playden::runtime;++namespace {+fs::path g_base;++struct Fixture {+ LayoutPaths paths;+ LayoutOps ops;+ std::vector<std::string> lines;+ int root_calls = 0;+};++void Write(const fs::path& file, const std::string& text, mode_t mode = 0644) {+ std::ofstream(file) << text;+ CHECK(chmod(file.c_str(), mode) == 0);+}++std::string Read(const fs::path& file) {+ std::ifstream in(file);+ std::stringstream text;+ text << in.rdbuf();+ return text.str();+}++unsigned Mode(const fs::path& path) {+ struct stat info{};+ CHECK(lstat(path.c_str(), &info) == 0);+ return info.st_mode & 07777;+}++std::unique_ptr<Fixture> Make(const std::string& name) {+ auto fixture = std::make_unique<Fixture>();+ const auto data = g_base / name / "data";+ auto& paths = fixture->paths;+ paths.boundary = data;+ paths.app_root = data / "homebrew" / "FAKE77031";+ paths.user_root = data / "playden" / "user";+ paths.log_root = data / "playden" / "logs";+ paths.games_root = data / "playden-games";+ paths.state_root = data / "playden" / "runtime-state";+ fs::create_directories(paths.app_root / "playden-data" / "game-settings-private");+ fs::create_directories(paths.app_root / "logs");+ fs::create_directories(paths.app_root / "games" / "220");+ CHECK(chmod((paths.app_root / "playden-data" / "game-settings-private").c_str(), 0700) == 0);+ Write(paths.app_root / "playden-data" / "session.v1", "credentials", 0600);+ Write(paths.app_root / "playden-data" / "game-settings-private" / "game-settings.json", "{}", 0600);+ Write(paths.app_root / "playden-data" / "library.json", "[]");+ Write(paths.app_root / "logs" / "native-startup.log", "pre-grant\n");+ Write(paths.app_root / "logs" / "runtime.log", "old run\n");+ Write(paths.app_root / "games" / "220" / "game.exe", "MZ");+ fs::create_directories(paths.app_root / "games" / ".playden-games");+ auto* raw = fixture.get();+ fixture->ops.log = [raw](const std::string& line) { raw->lines.push_back(line); };+ fixture->ops.as_root = [raw](const std::function<bool()>& work) { ++raw->root_calls; return work(); };+ return fixture;+}++bool Moved(const LayoutPaths& paths) {+ return fs::exists(paths.user_root / "session.v1") && fs::exists(paths.user_root / "library.json") &&+ fs::exists(paths.user_root / "game-settings-private" / "game-settings.json") &&+ fs::exists(paths.log_root / "native-startup.log") && fs::exists(paths.log_root / "runtime.log") &&+ fs::exists(paths.games_root / "220" / "game.exe") && fs::exists(paths.games_root / ".playden-games");+}++// A valid install record; `journal` adds a pending operation.+void WriteInstalls(const LayoutPaths& paths, bool journal) {+ const std::string record =+ "{\"schema_version\":1,\"install_id\":\"i220\",\"title_id\":\"FAKE78001\",\"app_id\":220,"+ "\"data_root\":\"/data/playden/games/i220\",\"default_profile_id\":\"default\",\"runtime_bundle_id\":\"kit\","+ "\"recipe_id\":\"generic\",\"recipe_version\":\"1\",\"settings_revision\":1,\"exit_policy\":\"exit-title\","+ "\"launch_entry_id\":\"main\",\"launch_path\":\"game.exe\",\"launch_arguments\":\"\","+ "\"launch_working_directory\":\"\",\"install_path\":\"" + (paths.app_root / "games" / "220").string() + "\","+ "\"volume_id\":\"internal\",\"state\":\"preparing\",\"artifacts\":[],\"last_failure\":null,\"journal\":" ++ std::string(journal ? "{\"operation_id\":\"op1\",\"operation\":\"prepare\",\"step\":\"bottle\"}" : "null") + "}";+ const std::string text = "{\"schema_version\":1,\"reservations\":[{\"install_id\":\"i220\",\"title_id\":\"FAKE78001\"}],"+ "\"installs\":[" + record + "]}";+ fs::create_directories(paths.state_root);+ CHECK(chmod(paths.state_root.c_str(), 0700) == 0);+ CHECK(playden::Storage(paths.state_root.string()).WriteDurable("installs.json", playden::Bytes(text.begin(), text.end())).ok());+}++void MovesUserDataLogsAndGames() {+ auto f = Make("moves");+ const auto result = MigrateLayout(f->paths, f->ops);+ CHECK(result.user_moved && result.logs_moved && result.games_moved && result.notice.empty());+ CHECK(result.user_root == f->paths.user_root && result.log_root == f->paths.log_root &&+ result.games_root == f->paths.games_root);+ CHECK(Moved(f->paths));+ CHECK(Mode(f->paths.user_root) == 0777 && Mode(f->paths.log_root) == 0777);+ CHECK(Mode(f->paths.user_root / "session.v1") == 0600);+ CHECK(Mode(f->paths.user_root / "game-settings-private") == 0700);+ CHECK(Read(f->paths.user_root / "session.v1") == "credentials");+ CHECK(f->root_calls == 1); // only the games rename+ const auto journal = LoadLayoutJournal(f->paths.state_root);+ CHECK(journal && journal->step == "games-moved");+ CHECK(journal->from == (f->paths.app_root / "games").string() && journal->to == f->paths.games_root.string());+ CHECK(Mode(f->paths.state_root / kLayoutJournal) == 0600);+ CHECK(Read(f->paths.app_root / "games-MOVED.txt").find(f->paths.games_root.string()) != std::string::npos);+ // Later starts change nothing until the runtime host marks the move done.+ const auto again = MigrateLayout(f->paths, f->ops);+ CHECK(again.games_moved && again.user_root == f->paths.user_root && f->root_calls == 1);+ CHECK(MarkLayoutDone(f->paths.state_root));+ const auto done = LoadLayoutJournal(f->paths.state_root);+ CHECK(done && done->step == "done" && done->from == journal->from && done->to == journal->to);+ CHECK(MigrateLayout(f->paths, f->ops).games_moved);+}++void KeepsStubFolders() {+ auto f = Make("stubs");+ MigrateLayout(f->paths, f->ops);+ for (const auto* stub : {"playden-data", "logs"}) {+ const auto folder = f->paths.app_root / stub;+ CHECK(fs::is_directory(folder));+ std::vector<std::string> names;+ for (const auto& entry : fs::directory_iterator(folder)) names.push_back(entry.path().filename().string());+ CHECK(names.size() == 1 && names[0] == "MOVED.txt");+ }+ CHECK(Read(f->paths.app_root / "playden-data" / "MOVED.txt").find(f->paths.user_root.string()) != std::string::npos);+ CHECK(Read(f->paths.app_root / "logs" / "MOVED.txt").find(f->paths.log_root.string()) != std::string::npos);+ CHECK(!fs::exists(f->paths.app_root / "games"));+ // The next start's pre-grant lines land in the stub again; the move is not redone.+ Write(f->paths.app_root / "logs" / "native-startup.log", "next start\n");+ MigrateLayout(f->paths, f->ops);+ CHECK(Read(f->paths.app_root / "logs" / "native-startup.log") == "next start\n");+}++void ResumesAfterEachStep() {+ // Interrupted inside the user step: half the entries already moved.+ {+ auto f = Make("resume-user");+ fs::create_directories(f->paths.user_root);+ fs::rename(f->paths.app_root / "playden-data" / "library.json", f->paths.user_root / "library.json");+ fs::create_directories(f->paths.state_root);+ CHECK(chmod(f->paths.state_root.c_str(), 0700) == 0);+ const std::string text = "{\"step\":\"user\",\"from\":\"a\",\"to\":\"b\",\"postponed\":0}";+ CHECK(playden::Storage(f->paths.state_root.string()).WriteDurable(kLayoutJournal, playden::Bytes(text.begin(), text.end())).ok());+ const auto result = MigrateLayout(f->paths, f->ops);+ CHECK(result.games_moved && result.notice.empty() && Moved(f->paths));+ }+ // Interrupted inside the logs step, after the next start wrote its pre-grant lines.+ {+ auto f = Make("resume-logs");+ auto ops = f->ops;+ int renames = 0;+ // Fail the second log entry once: the move puts the first back and holds.+ ops.rename = [&](const fs::path& from, const fs::path& to) -> std::error_code {+ if (from.parent_path().filename() == "logs" && ++renames == 2) return {EIO, std::generic_category()};+ return ::rename(from.c_str(), to.c_str()) == 0 ? std::error_code{} : std::error_code{errno, std::generic_category()};+ };+ const auto held = MigrateLayout(f->paths, ops);+ CHECK(held.user_moved && !held.logs_moved && !held.games_moved && !held.notice.empty());+ CHECK(held.log_root == f->paths.app_root / "logs" && held.games_root == f->paths.app_root / "games");+ CHECK(fs::exists(f->paths.app_root / "logs" / "native-startup.log") && !fs::exists(f->paths.log_root / "native-startup.log"));+ CHECK(LoadLayoutJournal(f->paths.state_root)->step == "logs");+ // A crash left one log moved; the next start writes the same name again.+ fs::rename(f->paths.app_root / "logs" / "native-startup.log", f->paths.log_root / "native-startup.log");+ Write(f->paths.app_root / "logs" / "native-startup.log", "next start\n");+ const auto result = MigrateLayout(f->paths, f->ops);+ CHECK(result.logs_moved && result.games_moved && result.notice.empty());+ CHECK(Read(f->paths.log_root / "native-startup.log") == "pre-grant\n");+ CHECK(Read(f->paths.log_root / "native-startup.log.moved") == "next start\n");+ }+ // Interrupted after the games rename, before games-moved was written.+ {+ auto f = Make("resume-games");+ CHECK(MigrateLayout(f->paths, f->ops).games_moved);+ const std::string text = "{\"step\":\"games\",\"from\":\"a\",\"to\":\"b\",\"postponed\":0}";+ CHECK(playden::Storage(f->paths.state_root.string()).WriteDurable(kLayoutJournal, playden::Bytes(text.begin(), text.end())).ok());+ const auto result = MigrateLayout(f->paths, f->ops);+ CHECK(result.games_moved && result.games_root == f->paths.games_root);+ const auto journal = LoadLayoutJournal(f->paths.state_root);+ CHECK(journal->step == "games-moved" && journal->from == (f->paths.app_root / "games").string());+ }+}++void WriteJournal(const LayoutPaths& paths, const std::string& file, const std::string& text) {+ fs::create_directories(paths.state_root);+ CHECK(chmod(paths.state_root.c_str(), 0700) == 0);+ CHECK(playden::Storage(paths.state_root.string()).WriteDurable(file, playden::Bytes(text.begin(), text.end())).ok());+}++// Every interrupted logs step can leave one more copy of a name: each keeps its own.+void LogsStepInterruptedTwice() {+ auto f = Make("logs-twice");+ fs::create_directories(f->paths.user_root);+ fs::create_directories(f->paths.log_root);+ for (const auto& name : {"session.v1", "library.json", "game-settings-private"})+ fs::rename(f->paths.app_root / "playden-data" / name, f->paths.user_root / name);+ Write(f->paths.log_root / "native-startup.log", "first\n");+ Write(f->paths.log_root / "native-startup.log.moved", "second\n");+ Write(f->paths.app_root / "logs" / "native-startup.log", "third\n");+ WriteJournal(f->paths, kLayoutJournal, "{\"step\":\"logs\",\"from\":\"a\",\"to\":\"b\",\"postponed\":0}");+ const auto result = MigrateLayout(f->paths, f->ops);+ CHECK(result.logs_moved && result.games_moved && result.notice.empty() && Moved(f->paths));+ CHECK(Read(f->paths.log_root / "native-startup.log") == "first\n");+ CHECK(Read(f->paths.log_root / "native-startup.log.moved") == "second\n");+ CHECK(Read(f->paths.log_root / "native-startup.log.moved.2") == "third\n");+}++// A fresh install has no games to move: the shared games folder is still made, 0777.+void FreshInstallMakesSharedGamesFolder() {+ auto f = Make("fresh-games");+ fs::remove_all(f->paths.app_root / "games");+ const auto result = MigrateLayout(f->paths, f->ops);+ CHECK(result.games_moved && result.notice.empty());+ CHECK(fs::is_directory(f->paths.games_root) && Mode(f->paths.games_root) == 0777);+ // Gone later (made by hand, removed by hand): the next start makes it again.+ fs::remove(f->paths.games_root);+ CHECK(MigrateLayout(f->paths, f->ops).games_moved && Mode(f->paths.games_root) == 0777);+ // One that came with the games keeps its mode.+ auto moved = Make("moved-games");+ CHECK(chmod((moved->paths.app_root / "games").c_str(), 0755) == 0);+ CHECK(MigrateLayout(moved->paths, moved->ops).games_moved && Mode(moved->paths.games_root) == 0755);+}++// A launch session still pending: the game may run or be suspended from its old folder.+void PostponesGamesWhileLaunchPending() {+ auto f = Make("launch");+ WriteJournal(f->paths, "launch-pending.v1", "session");+ const auto result = MigrateLayout(f->paths, f->ops);+ CHECK(result.user_moved && result.logs_moved && !result.games_moved && result.notice.empty());+ CHECK(fs::exists(f->paths.app_root / "games" / "220") && !fs::exists(f->paths.games_root));+ CHECK(LoadLayoutJournal(f->paths.state_root)->postponed == 1);+ bool logged = false;+ for (const auto& line : f->lines) logged = logged || line.find("pending launch title=unreadable running=unknown") != std::string::npos;+ CHECK(logged);+ CHECK(playden::Storage(f->paths.state_root.string()).RemoveDurable("launch-pending.v1").ok());+ const auto moved = MigrateLayout(f->paths, f->ops);+ CHECK(moved.games_moved && Moved(f->paths) && LoadLayoutJournal(f->paths.state_root)->postponed == 0);+}++// A pending session (StorageLaunchSessionJournal's format) whose game the console says has+// ended no longer holds the move: that happens whenever Playden started the last game.+void PendingLaunchOfStoppedGameMoves() {+ const auto hex = [](const std::string& text) {+ std::string out;+ for (const unsigned char c : text) { char pair[3]; std::snprintf(pair, sizeof(pair), "%02x", c); out += pair; }+ return out;+ };+ const std::string session = "PLAYDEN-LAUNCH-V1\n" + hex("00000000-0000-4000-8000-000000000001") + "\n" ++ hex("steam-220") + "\n" + hex("FAKE78001") + "\n" + hex("wine-wow64") ++ "\n1\n\n2\n1760000000\n1760000001\n0\n0\n\n";+ // Running (or suspended), unknown, or no query: the move waits.+ for (const auto answer : {std::optional<bool>(true), std::optional<bool>(), std::optional<bool>(false)}) {+ for (const bool query : {true, false}) {+ if (!query && answer != std::optional<bool>(true)) continue;+ auto f = Make(std::string("launch-title-") + (answer ? (*answer ? "running" : "stopped") : "unknown") ++ (query ? "" : "-noquery"));+ WriteJournal(f->paths, "launch-pending.v1", session);+ std::vector<std::string> asked;+ if (query)+ f->ops.title_running = [&asked, answer](const std::string& title) { asked.push_back(title); return answer; };+ const auto result = MigrateLayout(f->paths, f->ops);+ const bool moves = query && answer == std::optional<bool>(false);+ CHECK(result.games_moved == moves && Moved(f->paths) == moves);+ CHECK(query ? asked == std::vector<std::string>{"FAKE78001"} : asked.empty());+ if (!moves) {+ CHECK(LoadLayoutJournal(f->paths.state_root)->postponed == 1);+ // Told once the move kept waiting, in words that say what to do.+ for (int start = 2; start <= kLayoutPostponeNoticeAfter; ++start) {+ const auto later = MigrateLayout(f->paths, f->ops);+ CHECK(later.notice.empty() == (start < kLayoutPostponeNoticeAfter));+ if (!later.notice.empty())+ CHECK(later.notice.find("the last game you started from Playden may still be running or suspended. Close it") !=+ std::string::npos);+ }+ }+ }+ }+}++void PostponesGamesWhileJournalPending() {+ auto f = Make("pending");+ WriteInstalls(f->paths, true);+ for (int start = 1; start <= kLayoutPostponeNoticeAfter; ++start) {+ const auto result = MigrateLayout(f->paths, f->ops);+ CHECK(result.user_moved && result.logs_moved && !result.games_moved);+ CHECK(result.games_root == f->paths.app_root / "games" && fs::exists(f->paths.app_root / "games" / "220"));+ CHECK(!fs::exists(f->paths.games_root) && f->root_calls == 0);+ CHECK(LoadLayoutJournal(f->paths.state_root)->postponed == start);+ CHECK(result.notice.empty() == (start < kLayoutPostponeNoticeAfter));+ }+ bool logged = false;+ for (const auto& line : f->lines) logged = logged || line.find("pending prepare journal") != std::string::npos;+ CHECK(logged);+ // A settings publication still in flight in the game's control folder also holds it back:+ // its receipt is pending, or missing.+ WriteInstalls(f->paths, false);+ const auto control = f->paths.boundary / "playden" / "games" / "i220" / ".playden-control";+ fs::create_directories(control);+ Write(control / "settings-operation.v1", "x", 0600);+ CHECK(!MigrateLayout(f->paths, f->ops).games_moved);+ Write(control / "publication-state.v1", "{\"schema_version\":1,\"phase\":\"pending\"}", 0600);+ CHECK(!MigrateLayout(f->paths, f->ops).games_moved);+ // Once committed, the operation stays in the folder but is done: the games move.+ Write(control / "publication-state.v1", "{\"schema_version\":1,\"phase\":\"committed\"}", 0600);+ const auto result = MigrateLayout(f->paths, f->ops);+ CHECK(result.games_moved && result.notice.empty() && Moved(f->paths));+ CHECK(LoadLayoutJournal(f->paths.state_root)->postponed == 0);+}++// A Ready game keeps its last, committed publication's operation in its control folder; that+// doesn't hold the games back.+void MovesReadyGameWithCommittedPublication() {+ auto f = Make("committed");+ WriteInstalls(f->paths, false);+ const auto control = f->paths.boundary / "playden" / "games" / "i220" / ".playden-control";+ fs::create_directories(control);+ Write(control / "settings-operation.v1", "x", 0600);+ Write(control / "publication-state.v1",+ "{\"schema_version\":1,\"phase\":\"committed\",\"transaction_id\":\"t\",\"settings_revision\":1}\n", 0600);+ const auto result = MigrateLayout(f->paths, f->ops);+ CHECK(result.games_moved && result.notice.empty() && Moved(f->paths));+ CHECK(LoadLayoutJournal(f->paths.state_root)->step == "games-moved");+}++void RefusesToMergeIntoNonEmptyTarget() {+ {+ auto f = Make("merge-user");+ fs::create_directories(f->paths.user_root);+ Write(f->paths.user_root / "someone-elses.txt", "x");+ const auto result = MigrateLayout(f->paths, f->ops);+ CHECK(!result.user_moved && !result.logs_moved && !result.games_moved && !result.notice.empty());+ CHECK(result.user_root == f->paths.app_root / "playden-data");+ CHECK(fs::exists(f->paths.app_root / "playden-data" / "session.v1") && !fs::exists(f->paths.user_root / "session.v1"));+ CHECK(!LoadLayoutJournal(f->paths.state_root)); // nothing started, so the next start checks again+ bool both = false;+ for (const auto& line : f->lines)+ both = both || (line.find(f->paths.user_root.string()) != std::string::npos &&+ line.find((f->paths.app_root / "playden-data").string()) != std::string::npos);+ CHECK(both);+ CHECK(!MigrateLayout(f->paths, f->ops).user_moved);+ }+ {+ auto f = Make("merge-games");+ fs::create_directories(f->paths.games_root / "other");+ const auto result = MigrateLayout(f->paths, f->ops);+ CHECK(result.user_moved && result.logs_moved && !result.games_moved && !result.notice.empty());+ CHECK(result.games_root == f->paths.app_root / "games" && fs::exists(f->paths.app_root / "games" / "220"));+ CHECK(!fs::exists(f->paths.games_root / "220"));+ }+}++void AbortsOnCrossDevice() {+ auto f = Make("exdev");+ f->ops.rename = [](const fs::path& from, const fs::path& to) -> std::error_code {+ if (from.filename() == "games") return {EXDEV, std::generic_category()};+ return ::rename(from.c_str(), to.c_str()) == 0 ? std::error_code{} : std::error_code{errno, std::generic_category()};+ };+ const auto result = MigrateLayout(f->paths, f->ops);+ CHECK(result.user_moved && result.logs_moved && !result.games_moved);+ CHECK(result.notice.find("another drive") != std::string::npos);+ CHECK(fs::exists(f->paths.app_root / "games" / "220" / "game.exe") && !fs::exists(f->paths.games_root));+ CHECK(LoadLayoutJournal(f->paths.state_root)->step == "games");+}++void RevertsTheMove() {+ auto f = Make("revert");+ // Never moved: nothing to do.+ CHECK(RevertLayout(f->paths, f->ops).complete);+ CHECK(MigrateLayout(f->paths, f->ops).games_moved);+ Write(f->paths.log_root / "runtime-0.5.log", "new\n");+ Write(f->paths.app_root / "logs" / "native-startup.log", "next start\n");+ const auto calls = f->root_calls;+ const auto reverted = RevertLayout(f->paths, f->ops);+ CHECK(reverted.complete && reverted.error.empty());+ CHECK(f->root_calls == calls + 1);+ const auto app = f->paths.app_root;+ CHECK(Read(app / "playden-data" / "session.v1") == "credentials" && Mode(app / "playden-data" / "session.v1") == 0600);+ CHECK(Mode(app / "playden-data" / "game-settings-private") == 0700);+ CHECK(fs::exists(app / "games" / "220" / "game.exe") && !fs::exists(f->paths.games_root));+ CHECK(fs::exists(app / "logs" / "runtime-0.5.log"));+ CHECK(Read(app / "logs" / "native-startup.log") == "next start\n");+ CHECK(Read(app / "logs" / "native-startup.log.moved") == "pre-grant\n");+ CHECK(!fs::exists(app / "playden-data" / "MOVED.txt") && !fs::exists(app / "logs" / "MOVED.txt") &&+ !fs::exists(app / "games-MOVED.txt"));+ CHECK(!LoadLayoutJournal(f->paths.state_root));+ // A later 0.5 start moves everything again.+ const auto again = MigrateLayout(f->paths, f->ops);+ CHECK(again.games_moved && again.notice.empty() && Moved(f->paths));+}++void RevertKeepsConflictsAndJournal() {+ auto f = Make("revert-conflict");+ CHECK(MigrateLayout(f->paths, f->ops).games_moved);+ Write(f->paths.app_root / "playden-data" / "session.v1", "written by 0.4\n", 0600);+ const auto reverted = RevertLayout(f->paths, f->ops);+ CHECK(!reverted.complete && reverted.error.find("session.v1") != std::string::npos);+ CHECK(Read(f->paths.user_root / "session.v1") == "credentials");+ CHECK(LoadLayoutJournal(f->paths.state_root)->step == "revert-user");+ // A 0.5 start after the failed revert merges both places back.+ fs::remove(f->paths.app_root / "playden-data" / "session.v1");+ const auto resumed = MigrateLayout(f->paths, f->ops);+ CHECK(resumed.games_moved && resumed.notice.empty() && Moved(f->paths));+}+} // namespace++int main() {+ char pattern[] = "/tmp/playden-layout-XXXXXX";+ CHECK(mkdtemp(pattern));+ g_base = fs::canonical(pattern);+ ::umask(022);+ MovesUserDataLogsAndGames();+ KeepsStubFolders();+ ResumesAfterEachStep();+ PostponesGamesWhileJournalPending();+ LogsStepInterruptedTwice();+ FreshInstallMakesSharedGamesFolder();+ PostponesGamesWhileLaunchPending();+ PendingLaunchOfStoppedGameMoves();+ MovesReadyGameWithCommittedPublication();+ RefusesToMergeIntoNonEmptyTarget();+ AbortsOnCrossDevice();+ RevertsTheMove();+ RevertKeepsConflictsAndJournal();+ fs::remove_all(g_base);+ std::puts("layout migration tests passed");+}diff --git a/tests/native_access_test.cpp b/tests/native_access_test.cppindex 3ba6de9..5bacd76 100644--- a/tests/native_access_test.cpp+++ b/tests/native_access_test.cpp@@ -158,6 +158,35 @@ void PathsRemainValidAfterGrant() {CHECK(original_identity < grant && grant < stable_identity);}+// The bootstrap keeps the package paths; the startup move fills the split roots.+void SplitRootsFallBackToPackagePaths() {+ auto fake = OrdinaryLauncher();+ NativeAccessBootstrap bootstrap(Ops(fake), Options());+ auto result = bootstrap.Prepare();+ CHECK(result.runtime_ready && result.notice.empty());+ CHECK(result.paths.user_root.empty() && result.paths.user_log_root.empty() && result.paths.games_root.empty());+ CHECK(playden::ps5::EffectiveUserRoot(result.paths) == std::string(kStableRoot) + "/playden-data");+ CHECK(playden::ps5::EffectiveLogRoot(result.paths) == std::string(kStableRoot) + "/logs");+ CHECK(playden::ps5::EffectiveGamesRoot(result.paths) == std::string(kStableRoot) + "/games");+ result.paths.user_root = "/data/playden/user";+ result.paths.user_log_root = "/data/playden/logs";+ result.paths.games_root = "/data/playden-games";+ CHECK(playden::ps5::EffectiveUserRoot(result.paths) == "/data/playden/user");+ CHECK(playden::ps5::EffectiveLogRoot(result.paths) == "/data/playden/logs");+ CHECK(playden::ps5::EffectiveGamesRoot(result.paths) == "/data/playden-games");+ // The stub folders are still what the bootstrap validates.+ CHECK(result.paths.steam_state_root == std::string(kStableRoot) + "/playden-data");+ CHECK(result.paths.log_root == std::string(kStableRoot) + "/logs");++ auto denied = OrdinaryLauncher();+ denied.grant_result = 1;+ NativeAccessBootstrap fallback(Ops(denied), Options());+ const auto launcher = fallback.Prepare();+ CHECK(launcher.launcher_ready && !launcher.runtime_ready);+ CHECK(launcher.paths.user_root.empty() && launcher.paths.games_root.empty());+ CHECK(playden::ps5::EffectiveGamesRoot(launcher.paths) == launcher.paths.title_root + "/games");+}+void DeferredUserServiceRunsAfterGrantAndBeforeReturning() {auto fake = OrdinaryLauncher();auto options = Options();@@ -338,7 +367,8 @@ void PartialStableVisibilityStillRequestsGrant() {CHECK(result.paths.title_root == kStableRoot);}-void FreshStateRequiresWritableParent() {+// Only a launcher without the grant creates its state in the app folder.+void FreshStateRequiresWritableParentWithoutGrant() {auto fake = OrdinaryLauncher();AddTree(fake, kStableRoot, false);fake.identities[kStableRoot] = fake.identities[kAppRoot];@@ -346,7 +376,17 @@ void FreshStateRequiresWritableParent() {fake.read_only.insert(kStableRoot);fake.expose_stable_after_grant = false;NativeAccessBootstrap bootstrap(Ops(fake), Options(true));- CHECK(!bootstrap.Prepare().runtime_ready);+ CHECK(bootstrap.Prepare().runtime_ready);++ auto launcher = OrdinaryLauncher();+ launcher.paths.erase(std::string(kAppRoot) + "/playden-data");+ launcher.paths.erase(std::string(kAppRoot) + "/logs");+ launcher.read_only.insert(kAppRoot);+ launcher.grant_result = 13;+ NativeAccessBootstrap fallback(Ops(launcher), Options(true));+ const auto refused = fallback.Prepare();+ CHECK(!refused.launcher_ready && !refused.runtime_ready && launcher.grants == 1);+ CHECK(refused.error.find("cannot be created") != std::string::npos);auto populated = OrdinaryLauncher();AddTree(populated, kStableRoot);@@ -358,6 +398,53 @@ void FreshStateRequiresWritableParent() {CHECK(populated.grants == 0);}+// Stubs copied over FTP are root's and 0755: a granted start keeps nothing there.+void RootOwnedStubsAllowGrantedStart() {+ auto fake = OrdinaryLauncher();+ for (const auto* root : {kAppRoot, kStableRoot}) {+ fake.read_only.insert(std::string(root) + "/playden-data");+ fake.read_only.insert(std::string(root) + "/logs");+ }+ auto options = Options();+ options.require_grant = true;+ NativeAccessBootstrap bootstrap(Ops(fake), options);++ const auto result = bootstrap.Prepare();++ CHECK(result.launcher_ready && result.runtime_ready && result.granted);+ CHECK(result.paths.title_root == kStableRoot && fake.grants == 1);+ CHECK(result.paths.runtime_data_root == kRuntimeRoot);+ CHECK(result.error.empty());+}++// Without the grant the launcher keeps its state in the stubs: they must be writable.+void NoGrantFallbackRequiresWritableStubs() {+ auto fake = OrdinaryLauncher();+ fake.read_only.insert(std::string(kAppRoot) + "/playden-data");+ fake.read_only.insert(std::string(kAppRoot) + "/logs");+ fake.grant_result = 13;+ auto options = Options();+ options.require_grant = true;+ NativeAccessBootstrap bootstrap(Ops(fake), options);++ const auto result = bootstrap.Prepare();++ CHECK(!result.launcher_ready && !result.runtime_ready && fake.grants == 1);+ CHECK(result.error.find("grant") != std::string::npos);+ CHECK(result.error.find("inaccessible") != std::string::npos);++ // A stable title that matches but whose stubs are read-only is no launcher either.+ auto stable = OrdinaryLauncher();+ AddTree(stable, kStableRoot);+ stable.identities[kStableRoot] = stable.identities[kAppRoot];+ stable.read_only.insert(std::string(kStableRoot) + "/playden-data");+ stable.grant_result = 13;+ NativeAccessBootstrap stable_bootstrap(Ops(stable), options);+ const auto sandbox = stable_bootstrap.Prepare();+ CHECK(sandbox.launcher_ready && !sandbox.runtime_ready);+ CHECK(sandbox.paths.title_root == kAppRoot);+}+void StableTitleWithoutManagedAccessIsNotRuntimeReady() {auto fake = OrdinaryLauncher();AddTree(fake, kStableRoot);@@ -419,8 +506,11 @@ int main() {InaccessibleExistingStateIsRejectedBeforeGrant();PartialStableVisibilityStillRequestsGrant();StableTitleWithoutManagedAccessIsNotRuntimeReady();- FreshStateRequiresWritableParent();+ FreshStateRequiresWritableParentWithoutGrant();+ RootOwnedStubsAllowGrantedStart();+ NoGrantFallbackRequiresWritableStubs();PostGrantStableTitleSupportsLauncherWithoutManagedAccess();WritableManagedParentAllowsFirstRuntimeDirectoryCreation();+ SplitRootsFallBackToPackagePaths();std::puts("native_access_test passed");}diff --git a/tests/self_update_service_test.cpp b/tests/self_update_service_test.cppindex 4330b64..d9aa64d 100644--- a/tests/self_update_service_test.cpp+++ b/tests/self_update_service_test.cpp@@ -538,6 +538,46 @@ int main() {CHECK(!service.Snapshot().rollback_requested && !service.ApplyAtQuit());RemoveTree(fixture.root);}+ // Going back never crosses 0.5.0: older versions can't read the data it moved out of the app.+ {+ Fixture fixture;+ fixture.root = zip_fixture::TempFolder("service-layout");+ Installed(fixture.root);+ Put(fixture.root + "/playden/self-update/backup/0.4.2-900/eboot.bin", "eboot 0.4.2");+ UpdateService service(fixture.Config({0, 5, 0}));+ service.Start();+ CHECK(service.Snapshot().previous.empty());+ service.RequestRollback();+ CHECK(!service.Snapshot().rollback_requested && !service.ApplyAtQuit());+ CHECK(Exists(fixture.root + "/playden/self-update/backup/0.4.2-900/eboot.bin"));+ RemoveTree(fixture.root);+ }+ // This branch may still report a version below 0.5.0: the move record alone refuses going back.+ {+ Fixture fixture;+ fixture.root = zip_fixture::TempFolder("service-journal");+ Installed(fixture.root);+ Put(fixture.root + "/playden/self-update/backup/0.4.2-900/eboot.bin", "eboot 0.4.2");+ const std::string journal = fixture.root + "/playden/runtime-state/layout-0.5.json";+ Put(journal, "{\"step\":\"done\"}");+ auto config = fixture.Config({0, 4, 0});+ config.layout_journal = journal;+ UpdateService refused(config);+ refused.Start();+ CHECK(refused.Snapshot().previous.empty());+ refused.RequestRollback();+ CHECK(!refused.Snapshot().rollback_requested && !refused.ApplyAtQuit());+ CHECK(Exists(fixture.root + "/playden/self-update/backup/0.4.2-900/eboot.bin"));+ CHECK(Read(fixture.root + "/homebrew/FAKE77031/eboot.bin") == "eboot 0.2.0");+ // Without the record (never moved, or reverted) it is offered.+ CHECK(unlink(journal.c_str()) == 0);+ UpdateService offered(config);+ offered.Start();+ CHECK(offered.Snapshot().previous == "0.4.2");+ offered.RequestRollback();+ CHECK(offered.Snapshot().rollback_requested);+ RemoveTree(fixture.root);+ }// GitHub out of reach.{Fixture fixture;