Merge pull request #12970 from MarcZX10/feat/title-instance-lock

feat(libkernel): stop a second copy of a title with ANYPS5_INSTANCE_LOCK
This commit is contained in:
Adrià authored and GitHub committed 2026-11-08 09:16:58 +01:00
commit 5bd71fb5bc
14 files changed
+632

No files matched your search

@@ -32,6 +32,7 @@
#include "prx/libc/include/HostExecutable.hpp"
#include "prx/libkernel/KernelErrors.hpp"
#include "prx/libkernel/AppMetadata/include/AppMetadata.hpp"
#include "prx/libkernel/System/include/InstanceLockHost.hpp"
#include "prx/libSceSystemService/SystemService.hpp"
#include "prx/libSceSystemService/DateTimeLocale.hpp"
#include "prx/libSceUserService/UserService.hpp"
@@ -144,6 +145,7 @@ HostLaunch PrepareLaunch(const char* path, const char* const* arguments) {
void StartHostExecutable(HostLaunch& launch) {
LogFileRelease_nid_no_patch();
ReleaseHostInstanceLock();
STARTUPINFOW startup{};
startup.cb = sizeof(startup);
PROCESS_INFORMATION process{};
+59
View File
@@ -76,6 +76,8 @@ add_library(libkernel SHARED EXCLUDE_FROM_ALL
${CMAKE_CURRENT_SOURCE_DIR}/System/src/HostPerformanceProcess.cpp
${CMAKE_CURRENT_SOURCE_DIR}/System/src/HostPerformanceStartup.cpp
${CMAKE_CURRENT_SOURCE_DIR}/System/src/MimallocRestart.cpp
${CMAKE_CURRENT_SOURCE_DIR}/System/src/InstanceLock.cpp
${CMAKE_CURRENT_SOURCE_DIR}/System/src/InstanceLockStartup.cpp
${CMAKE_CURRENT_SOURCE_DIR}/System/src/SystemConfiguration.cpp
${CMAKE_CURRENT_SOURCE_DIR}/System/src/Login.cpp
${CMAKE_CURRENT_SOURCE_DIR}/System/src/Getlogin.cpp
@@ -104,10 +106,14 @@ endif()
target_include_directories(libkernel PRIVATE ${LIBS_INCLUDE_DIR})
target_include_directories(libkernel PRIVATE ${LIBS_INCLUDE_DIR}/nid/include)
if(NOT WIN32)
target_sources(libkernel PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/System/src/InstanceLockPosix.cpp)
endif()
target_link_libraries(libkernel PRIVATE ${CMAKE_DL_LIBS})
target_link_libraries(libkernel PRIVATE libc)
if(WIN32)
target_sources(libkernel PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/File/src/TrustedRoots.cpp)
target_sources(libkernel PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/System/src/InstanceLockWindows.cpp)
target_link_libraries(libkernel PRIVATE ws2_32 shell32 advapi32 crypt32 wbemuuid ole32 oleaut32)
target_link_libraries(libkernel PRIVATE iphlpapi)
target_compile_definitions(libkernel PRIVATE _WIN32_WINNT=0x0602)
@@ -1850,6 +1856,59 @@ if(BUILD_TESTING)
set_tests_properties(host_cpu PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libkernel>")
endif()
add_test_executable(instance_lock_tests ${LIBS_INCLUDE_DIR}/tests/InstanceLock.cpp)
target_include_directories(instance_lock_tests PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(instance_lock_tests PRIVATE libkernel libc)
configure_windows_unwind(instance_lock_tests)
add_test(NAME instance_lock COMMAND instance_lock_tests)
if(WIN32)
set_tests_properties(instance_lock PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libkernel>")
endif()
add_test_executable(instance_lock_host_tests ${LIBS_INCLUDE_DIR}/tests/InstanceLockHost.cpp)
target_include_directories(instance_lock_host_tests PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(instance_lock_host_tests PRIVATE libkernel libc)
configure_windows_unwind(instance_lock_host_tests)
add_test(NAME instance_lock_host COMMAND instance_lock_host_tests)
if(WIN32)
set_tests_properties(instance_lock_host PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libkernel>")
endif()
add_test_executable(instance_lock_startup_tests ${LIBS_INCLUDE_DIR}/tests/InstanceLockStartup.cpp)
target_include_directories(instance_lock_startup_tests PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(instance_lock_startup_tests PRIVATE libkernel libc)
configure_windows_unwind(instance_lock_startup_tests)
set(instanceLockTitle "{\"titleId\":\"PPSA00000\",\"localizedParameters\":{\"en-US\":{\"titleName\":\"Example\"}}}")
set(instanceLockCases held:on:title:held unset:unset:title:nothing off:off:title:nothing notitle:on:none:nothing)
if(NOT WIN32)
list(APPEND instanceLockCases second:on:title:second invalid:unset:none:invalid unreadable:unset:untitled:unreadable)
endif()
foreach(instanceLockCase IN LISTS instanceLockCases)
string(REPLACE ":" ";" instanceLockCase ${instanceLockCase})
list(GET instanceLockCase 0 instanceLockName)
list(GET instanceLockCase 1 instanceLockValue)
list(GET instanceLockCase 2 instanceLockFixture)
list(GET instanceLockCase 3 instanceLockMode)
set(instanceLockRun ${CMAKE_CURRENT_BINARY_DIR}/instance_lock_startup_${instanceLockName})
file(REMOVE_RECURSE ${instanceLockRun})
file(MAKE_DIRECTORY ${instanceLockRun})
if(instanceLockFixture STREQUAL "title")
file(WRITE ${instanceLockRun}/app0/sce_sys/param.json "${instanceLockTitle}")
elseif(instanceLockFixture STREQUAL "untitled")
file(WRITE ${instanceLockRun}/app0/sce_sys/param.json "{\"downloadDataSize\":0}")
endif()
add_test(NAME instance_lock_startup_${instanceLockName} COMMAND instance_lock_startup_tests ${instanceLockMode}
WORKING_DIRECTORY ${instanceLockRun})
if(instanceLockValue STREQUAL "unset")
set_tests_properties(instance_lock_startup_${instanceLockName} PROPERTIES ENVIRONMENT_MODIFICATION "ANYPS5_INSTANCE_LOCK=unset:")
else()
set_tests_properties(instance_lock_startup_${instanceLockName} PROPERTIES ENVIRONMENT "ANYPS5_INSTANCE_LOCK=${instanceLockValue}")
endif()
if(WIN32)
set_tests_properties(instance_lock_startup_${instanceLockName} PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libkernel>")
endif()
endforeach()
add_test_executable(guest_system_configuration_tests ${LIBS_INCLUDE_DIR}/tests/GuestSystemConfiguration.cpp)
target_include_directories(guest_system_configuration_tests PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(guest_system_configuration_tests PRIVATE libkernel libc)
@@ -0,0 +1,25 @@
#ifndef CORE_LIBS_PRX_LIBKERNEL_SYSTEM_INCLUDE_INSTANCELOCK_HPP
#define CORE_LIBS_PRX_LIBKERNEL_SYSTEM_INCLUDE_INSTANCELOCK_HPP
#include <filesystem>
#include <string_view>
enum class InstanceLockMode {
Off,
On,
};
constexpr char InstanceLockVariable[] = "ANYPS5_INSTANCE_LOCK";
constexpr char InstanceLockFileName[] = ".anyps5-instance.lock";
class IInstanceLockBackend {
public:
virtual ~IInstanceLockBackend() = default;
virtual bool TryLock(const std::filesystem::path& file) = 0;
};
InstanceLockMode ParseInstanceLockMode(const char* value);
std::filesystem::path InstanceLockPath(const std::filesystem::path& root);
void AcquireInstanceLock(IInstanceLockBackend& backend, const std::filesystem::path& root, std::string_view titleId);
#endif
@@ -0,0 +1,11 @@
#ifndef CORE_LIBS_PRX_LIBKERNEL_SYSTEM_INCLUDE_INSTANCELOCKHOST_HPP
#define CORE_LIBS_PRX_LIBKERNEL_SYSTEM_INCLUDE_INSTANCELOCKHOST_HPP
#include "prx/libkernel/System/include/InstanceLock.hpp"
#include <memory>
std::unique_ptr<IInstanceLockBackend> MakeHostInstanceLockBackend();
void ReleaseHostInstanceLock();
#endif
@@ -0,0 +1,25 @@
#include "prx/libkernel/System/include/InstanceLock.hpp"
#include <stdexcept>
#include <string>
#include <string_view>
InstanceLockMode ParseInstanceLockMode(const char* value) {
if (value == nullptr || value[0] == '\0') return InstanceLockMode::Off;
const std::string_view text(value);
if (text == "off") return InstanceLockMode::Off;
if (text == "on") return InstanceLockMode::On;
throw std::runtime_error(std::string(InstanceLockVariable) + " must be on or off, not '" + std::string(text) + "'");
}
std::filesystem::path InstanceLockPath(const std::filesystem::path& root) {
return root / InstanceLockFileName;
}
void AcquireInstanceLock(IInstanceLockBackend& backend, const std::filesystem::path& root, std::string_view titleId) {
const auto file = InstanceLockPath(root);
if (backend.TryLock(file)) return;
throw std::runtime_error("title " + std::string(titleId) + " is already running from " + root.string() + ": another process holds " + file.string() +
". Two copies of one title share this directory's save data and app data and can corrupt each other. Close the other copy, or set " +
InstanceLockVariable + "=off to run both.");
}
@@ -0,0 +1,55 @@
#include "prx/libkernel/System/include/InstanceLockHost.hpp"
#include <cerrno>
#include <cstring>
#include <fcntl.h>
#include <stdexcept>
#include <string>
#include <sys/file.h>
#include <unistd.h>
namespace {
std::string Describe(const std::filesystem::path& file, const char* action, int error) {
return std::string("cannot ") + action + " the instance lock " + file.string() + ": " + std::strerror(error) + ". Set " + InstanceLockVariable + "=off to skip this check.";
}
class PosixInstanceLockBackend final : public IInstanceLockBackend {
public:
PosixInstanceLockBackend() = default;
PosixInstanceLockBackend(const PosixInstanceLockBackend&) = delete;
PosixInstanceLockBackend& operator=(const PosixInstanceLockBackend&) = delete;
~PosixInstanceLockBackend() override {
if (descriptor >= 0) ::close(descriptor);
}
bool TryLock(const std::filesystem::path& file) override {
if (descriptor >= 0) throw std::logic_error("the instance lock is already held on " + file.string());
int opened;
do {
opened = ::open(file.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0644);
} while (opened < 0 && errno == EINTR);
if (opened < 0) throw std::runtime_error(Describe(file, "open", errno));
int result;
do {
result = ::flock(opened, LOCK_EX | LOCK_NB);
} while (result != 0 && errno == EINTR);
if (result != 0) {
const int error = errno;
::close(opened);
if (error == EWOULDBLOCK) return false;
throw std::runtime_error(Describe(file, "lock", error));
}
descriptor = opened;
return true;
}
private:
int descriptor = -1;
};
}
std::unique_ptr<IInstanceLockBackend> MakeHostInstanceLockBackend() {
return std::make_unique<PosixInstanceLockBackend>();
}
@@ -0,0 +1,45 @@
#include "prx/libkernel/AppMetadata/include/AppMetadata.hpp"
#include "prx/libkernel/System/include/InstanceLockHost.hpp"
#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <memory>
#include <stdexcept>
#include <string>
#include <string_view>
namespace {
std::unique_ptr<IInstanceLockBackend>& HeldBackend() {
static auto* backend = new std::unique_ptr<IInstanceLockBackend>;
return *backend;
}
bool HasTitleMetadata(const std::filesystem::path& root) {
const auto metadata = root / "app0" / "sce_sys";
return std::filesystem::exists(metadata / "param.json") || std::filesystem::exists(metadata / "param.sfo");
}
const bool InstanceLockChecked = [] {
if (ParseInstanceLockMode(std::getenv("ANYPS5_INSTANCE_LOCK")) == InstanceLockMode::Off) return false;
const auto root = std::filesystem::current_path();
if (!HasTitleMetadata(root)) return false;
AppTitleId titleId{};
try {
titleId = GetAppTitleId_nid_postfix();
} catch (const std::exception& error) {
throw std::runtime_error(std::string("cannot read the title ID of the title in ") + root.string() + " for the instance lock: " + error.what() + ". Set " +
InstanceLockVariable + "=off to skip this check.");
}
auto backend = MakeHostInstanceLockBackend();
AcquireInstanceLock(*backend, root, std::string_view(titleId.value, strnlen(titleId.value, sizeof(titleId.value))));
HeldBackend() = std::move(backend);
return true;
}();
}
void ReleaseHostInstanceLock() {
HeldBackend().reset();
}
@@ -0,0 +1,46 @@
#include "prx/libkernel/System/include/InstanceLockHost.hpp"
#include <stdexcept>
#include <string>
#include <windows.h>
namespace {
std::string Describe(const std::filesystem::path& file, const char* action, DWORD error) {
return std::string("cannot ") + action + " the instance lock " + file.string() + ": Windows error " + std::to_string(error) + ". Set " + InstanceLockVariable +
"=off to skip this check.";
}
class WindowsInstanceLockBackend final : public IInstanceLockBackend {
public:
WindowsInstanceLockBackend() = default;
WindowsInstanceLockBackend(const WindowsInstanceLockBackend&) = delete;
WindowsInstanceLockBackend& operator=(const WindowsInstanceLockBackend&) = delete;
~WindowsInstanceLockBackend() override {
if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
}
bool TryLock(const std::filesystem::path& file) override {
if (handle != INVALID_HANDLE_VALUE) throw std::logic_error("the instance lock is already held on " + file.string());
const HANDLE opened = CreateFileW(file.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
if (opened == INVALID_HANDLE_VALUE) throw std::runtime_error(Describe(file, "open", GetLastError()));
OVERLAPPED region{};
if (!LockFileEx(opened, LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY, 0, 1, 0, &region)) {
const DWORD error = GetLastError();
CloseHandle(opened);
if (error == ERROR_LOCK_VIOLATION) return false;
throw std::runtime_error(Describe(file, "lock", error));
}
handle = opened;
return true;
}
private:
HANDLE handle = INVALID_HANDLE_VALUE;
};
}
std::unique_ptr<IInstanceLockBackend> MakeHostInstanceLockBackend() {
return std::make_unique<WindowsInstanceLockBackend>();
}
+105
View File
@@ -0,0 +1,105 @@
#include "prx/libkernel/System/include/InstanceLock.hpp"
#include <filesystem>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
static void Require(bool condition, const std::string& message) {
if (!condition) throw std::runtime_error(message);
}
namespace {
class FakeBackend final : public IInstanceLockBackend {
public:
explicit FakeBackend(bool acquired) : acquired(acquired) {}
bool TryLock(const std::filesystem::path& file) override {
requested.push_back(file);
if (failure) throw std::runtime_error("cannot open " + file.string());
return acquired;
}
std::vector<std::filesystem::path> requested;
bool failure = false;
private:
bool acquired;
};
}
static void CheckModeParsing() {
Require(ParseInstanceLockMode(nullptr) == InstanceLockMode::Off, "an unset variable must be off");
Require(ParseInstanceLockMode("") == InstanceLockMode::Off, "an empty value must be off");
Require(ParseInstanceLockMode("off") == InstanceLockMode::Off, "off must be off");
Require(ParseInstanceLockMode("on") == InstanceLockMode::On, "on must be on");
}
static void CheckModeRejection() {
for (const char* value : {"1", "ON", "auto", "true", " on", "on ", "0"}) {
bool thrown = false;
try {
ParseInstanceLockMode(value);
} catch (const std::runtime_error& error) {
const std::string message = error.what();
thrown = true;
Require(message.find("ANYPS5_INSTANCE_LOCK") != std::string::npos, std::string("the error for '") + value + "' must name the variable: " + message);
Require(message.find(std::string("'") + value + "'") != std::string::npos, std::string("the error must quote '") + value + "': " + message);
}
Require(thrown, std::string("'") + value + "' must be rejected");
}
}
static void CheckPath() {
const std::filesystem::path root = std::filesystem::path("data") / "run";
Require(InstanceLockPath(root) == root / ".anyps5-instance.lock", "the lock file must sit directly in the root");
}
static void CheckAcquired() {
FakeBackend backend(true);
AcquireInstanceLock(backend, "root", "PPSA00000");
Require(backend.requested.size() == 1, "the backend must be asked once");
Require(backend.requested[0] == InstanceLockPath("root"), "the backend must be asked for the lock file in the root");
}
static void CheckHeld() {
FakeBackend backend(false);
bool thrown = false;
try {
AcquireInstanceLock(backend, "root", "PPSA00000");
} catch (const std::runtime_error& error) {
const std::string message = error.what();
thrown = true;
Require(message.find("PPSA00000") != std::string::npos, "the error must name the title ID: " + message);
Require(message.find(InstanceLockPath("root").string()) != std::string::npos, "the error must name the lock file: " + message);
Require(message.find("ANYPS5_INSTANCE_LOCK=off") != std::string::npos, "the error must name the variable that turns the check off: " + message);
}
Require(thrown, "a held lock must stop the second instance");
}
static void CheckBackendFailurePropagates() {
FakeBackend backend(true);
backend.failure = true;
bool thrown = false;
try {
AcquireInstanceLock(backend, "root", "PPSA00000");
} catch (const std::runtime_error& error) {
thrown = std::string(error.what()).find("cannot open") != std::string::npos;
}
Require(thrown, "a backend failure must reach the caller unchanged");
}
int main() {
try {
CheckModeParsing();
CheckModeRejection();
CheckPath();
CheckAcquired();
CheckHeld();
CheckBackendFailurePropagates();
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
return 1;
}
return 0;
}
+151
View File
@@ -0,0 +1,151 @@
#include "prx/libkernel/System/include/InstanceLockHost.hpp"
#include <cerrno>
#include <filesystem>
#include <iostream>
#include <stdexcept>
#include <string>
#ifdef _WIN32
#include <windows.h>
#else
#include <csignal>
#include <fcntl.h>
#include <sys/wait.h>
#include <unistd.h>
#endif
static void Require(bool condition, const std::string& message) {
if (!condition) throw std::runtime_error(message);
}
namespace {
class ScratchDirectory {
public:
ScratchDirectory() {
#ifdef _WIN32
const auto id = std::to_string(GetCurrentProcessId());
#else
const auto id = std::to_string(getpid());
#endif
path = std::filesystem::temp_directory_path() / ("anyps5-instance-lock-host-" + id);
std::filesystem::remove_all(path);
std::filesystem::create_directories(path);
}
~ScratchDirectory() {
std::error_code error;
std::filesystem::remove_all(path, error);
}
std::filesystem::path path;
};
}
static void CheckSecondHandleIsRefused() {
ScratchDirectory scratch;
const auto file = InstanceLockPath(scratch.path);
auto first = MakeHostInstanceLockBackend();
auto second = MakeHostInstanceLockBackend();
Require(first->TryLock(file), "the first lock must be taken");
Require(std::filesystem::exists(file), "the lock file must exist while held");
Require(!second->TryLock(file), "a second handle must be refused while the first is held");
Require(!second->TryLock(file), "a refused handle must be refused again");
}
static void CheckReleaseOnDestruction() {
ScratchDirectory scratch;
const auto file = InstanceLockPath(scratch.path);
auto first = MakeHostInstanceLockBackend();
Require(first->TryLock(file), "the first lock must be taken");
first.reset();
auto second = MakeHostInstanceLockBackend();
Require(second->TryLock(file), "the lock must be free once its holder is gone, with the stale file left in place");
}
static void CheckRootsAreIndependent() {
ScratchDirectory scratch;
const auto left = scratch.path / "left";
const auto right = scratch.path / "right";
std::filesystem::create_directories(left);
std::filesystem::create_directories(right);
auto first = MakeHostInstanceLockBackend();
auto second = MakeHostInstanceLockBackend();
Require(first->TryLock(InstanceLockPath(left)), "the left root must lock");
Require(second->TryLock(InstanceLockPath(right)), "a different root must not conflict");
}
static void CheckUnwritableRootThrows() {
ScratchDirectory scratch;
const auto file = InstanceLockPath(scratch.path / "missing");
auto backend = MakeHostInstanceLockBackend();
bool thrown = false;
try {
backend->TryLock(file);
} catch (const std::runtime_error& error) {
const std::string message = error.what();
thrown = true;
Require(message.find(file.string()) != std::string::npos, "the error must name the lock file: " + message);
Require(message.find("ANYPS5_INSTANCE_LOCK=off") != std::string::npos, "the error must name the variable: " + message);
}
Require(thrown, "a lock file that cannot be created must throw, not pass silently");
}
static void CheckLockedTwiceThrows() {
ScratchDirectory scratch;
const auto file = InstanceLockPath(scratch.path);
auto backend = MakeHostInstanceLockBackend();
Require(backend->TryLock(file), "the lock must be taken");
bool thrown = false;
try {
backend->TryLock(file);
} catch (const std::logic_error&) {
thrown = true;
}
Require(thrown, "locking twice with one backend must throw");
}
#ifndef _WIN32
static void CheckExecDoesNotInherit() {
ScratchDirectory scratch;
const auto file = InstanceLockPath(scratch.path);
auto first = MakeHostInstanceLockBackend();
Require(first->TryLock(file), "the lock must be taken");
int ready[2];
Require(pipe(ready) == 0, "pipe failed");
Require(fcntl(ready[0], F_SETFD, FD_CLOEXEC) == 0, "fcntl failed");
Require(fcntl(ready[1], F_SETFD, FD_CLOEXEC) == 0, "fcntl failed");
const pid_t child = fork();
Require(child >= 0, "fork failed");
if (child == 0) {
execl("/bin/sleep", "sleep", "60", static_cast<char*>(nullptr));
_exit(127);
}
close(ready[1]);
char byte;
while (read(ready[0], &byte, 1) < 0 && errno == EINTR) {
}
close(ready[0]);
first.reset();
auto second = MakeHostInstanceLockBackend();
const bool taken = second->TryLock(file);
kill(child, SIGKILL);
waitpid(child, nullptr, 0);
Require(taken, "a program started by exec must not keep the lock alive");
}
#endif
int main() {
try {
CheckSecondHandleIsRefused();
CheckReleaseOnDestruction();
CheckRootsAreIndependent();
CheckUnwritableRootThrows();
CheckLockedTwiceThrows();
#ifndef _WIN32
CheckExecDoesNotInherit();
#endif
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
return 1;
}
return 0;
}
+93
View File
@@ -0,0 +1,93 @@
#include "prx/libkernel/System/include/InstanceLockHost.hpp"
#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <iterator>
#include <stdexcept>
#include <string>
static void Require(bool condition, const std::string& message) {
if (!condition) throw std::runtime_error(message);
}
static std::filesystem::path LockFile() {
return InstanceLockPath(std::filesystem::current_path());
}
static void CheckHeldAndReleased() {
auto other = MakeHostInstanceLockBackend();
Require(std::filesystem::exists(LockFile()), "start-up must have created the lock file");
Require(!other->TryLock(LockFile()), "start-up must hold the lock for the whole process");
ReleaseHostInstanceLock();
Require(other->TryLock(LockFile()), "ReleaseHostInstanceLock must free the lock");
}
static void CheckNothingCreated() {
Require(!std::filesystem::exists(LockFile()), "no lock file may be created: " + LockFile().string());
}
#ifndef _WIN32
static int RunChild(const std::string& executable, const char* mode, const std::filesystem::path& errors) {
const std::string command = std::string("ANYPS5_INSTANCE_LOCK=") + mode + " '" + executable + "' child >/dev/null 2>'" + errors.string() + "'";
return std::system(command.c_str());
}
static std::string Read(const std::filesystem::path& path) {
std::ifstream file(path);
return std::string(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>());
}
static void CheckInvalidValue(const std::string& executable) {
const auto errors = std::filesystem::current_path() / "child-errors.txt";
for (const char* value : {"yes", "1", "ON", "auto"}) {
Require(RunChild(executable, value, errors) != 0, std::string("a copy with the value '") + value + "' must stop");
const auto message = Read(errors);
Require(message.find(std::string("ANYPS5_INSTANCE_LOCK must be on or off, not '") + value + "'") != std::string::npos,
std::string("the error must name the variable and quote '") + value + "': " + message);
}
Require(RunChild(executable, "", errors) == 0, "an empty value must be the same as unset: " + Read(errors));
}
static void CheckUnreadableTitle(const std::string& executable) {
const auto errors = std::filesystem::current_path() / "child-errors.txt";
Require(RunChild(executable, "off", errors) == 0, "a copy with the check off must ignore the unreadable title: " + Read(errors));
Require(RunChild(executable, "on", errors) != 0, "a title whose ID cannot be read must stop with the check on");
const auto message = Read(errors);
Require(message.find(std::filesystem::current_path().string()) != std::string::npos, "the error must name the directory: " + message);
Require(message.find("ANYPS5_INSTANCE_LOCK=off") != std::string::npos, "the error must name the variable: " + message);
Require(!std::filesystem::exists(LockFile()), "no lock file may be created when the title ID is unreadable");
}
static void CheckSecondInstance(const std::string& executable) {
const auto errors = std::filesystem::current_path() / "child-errors.txt";
Require(RunChild(executable, "off", errors) == 0, "a copy with the check off must run beside the holder: " + Read(errors));
Require(RunChild(executable, "on", errors) != 0, "a second copy with the check on must stop");
const auto message = Read(errors);
Require(message.find("PPSA00000") != std::string::npos, "the error must name the title ID: " + message);
Require(message.find(std::filesystem::current_path().string()) != std::string::npos, "the error must name the directory: " + message);
Require(message.find(LockFile().string()) != std::string::npos, "the error must name the lock file: " + message);
Require(message.find("ANYPS5_INSTANCE_LOCK=off") != std::string::npos, "the error must name the variable: " + message);
ReleaseHostInstanceLock();
Require(RunChild(executable, "on", errors) == 0, "a copy must start once the holder released the lock: " + Read(errors));
}
#endif
int main(int argc, char** argv) {
try {
const std::string mode = argc > 1 ? argv[1] : "";
if (mode == "child") return 0;
if (mode == "held") CheckHeldAndReleased();
else if (mode == "nothing") CheckNothingCreated();
#ifndef _WIN32
else if (mode == "second") CheckSecondInstance(argv[0]);
else if (mode == "invalid") CheckInvalidValue(argv[0]);
else if (mode == "unreadable") CheckUnreadableTitle(argv[0]);
#endif
else throw std::runtime_error("unknown mode '" + mode + "'");
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
return 1;
}
return 0;
}
+1
View File
@@ -699,6 +699,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti
| Name | Kind | Source | Default | Description |
|------|------|--------|---------|-------------|
| `ANYPS5_INSTANCE_LOCK` | string | `core/libs/prx/libkernel/System/src/InstanceLockStartup.cpp` | | `on` keeps a second copy of a title from starting in a directory where one runs, by locking `.anyps5-instance.lock` there for the process lifetime; unset, empty and `off` lock nothing; any other value stops start-up with an error naming the variable |
| `ANYPS5_LOADEXEC_ARGV_SKIP` | string | `core/libs/prx/libkernel/System/src/Process.cpp` | | on Windows, set to `1` to drop the first process argument and clear the variable |
| `APS5_COARSE_TIMED_WAITS` | presence | `core/libs/prx/libkernel/Time/TimedWait.cpp` | | on Windows, rounds timed waits up to the scheduler tick |
| `APS5_DIRECT_MEMORY_FROM_FLEXIBLE` | presence | `core/libs/prx/libkernel/DirectMemory/Export.cpp` | | reports 12736 MiB less the configured flexible-memory size as the direct-memory size, and stops direct-memory allocation there, instead of 13824 MiB |
+6
View File
@@ -412,6 +412,12 @@
- [send and recv](../../../core/libs/prx/libkernel/Socket/src/Udp.cpp) (libkernel) pass the guest buffer to the host call without a guest copy helper, so an unreadable or unwritable buffer is whatever the host does (a host fault signal is possible), where `sendto` and `recvfrom` fail with `EFAULT`. On Windows a stream receive whose writable prefix is shorter than the queued data fails with `EFAULT`, but data arriving after the check, or `MSG_WAITALL`, can return the prefix as a short success where FreeBSD fails. Linux and macOS return the bytes copied before a fault on a stream, where FreeBSD returns `EFAULT`.
- [equeue pending-event bound](../../../core/libs/prx/libkernel/Equeue/Equeue.cpp) (libkernel) - an undrained registration keeps the armed event plus at most 64 queued events: a trigger past the cap drops the oldest queued event and keeps the latest payload, and an `AddEvent` carrying more than 64 queued events keeps the latest 64. Drained bursts report as before. The console's queue depth and which completion it keeps are unknown
- [title sandbox app0 alias](../../../core/libs/prx/libkernel/AppMetadata/src/AppMetadata.cpp) (libkernel) - aliases `/mnt/sandbox/<titleId>_000/app0` to the application directory `/app0` when metadata is loaded; console jail sandbox mounts for other virtual directories under `/mnt/sandbox` remain unmeasured.
- [Instance lock on network file systems](../../../core/libs/prx/libkernel/System/src/InstanceLockPosix.cpp) (libkernel) - `ANYPS5_INSTANCE_LOCK=on` takes `flock` on Linux and macOS and `LockFileEx` on Windows on `.anyps5-instance.lock` in the directory the title runs from. Whether that lock excludes a second copy when the directory is on NFS, SMB, FUSE or another network file system, or one started from another host, is not measured: such a file system can grant the lock locally without telling the other side, or refuse it. A refusal other than "held" stops start-up with the error naming the variable.
- [Instance lock on Windows](../../../core/libs/prx/libkernel/System/src/InstanceLockWindows.cpp) (libkernel) - the Windows backend (`CreateFileW` with read and write sharing, then an exclusive one-byte `LockFileEx` with `LOCKFILE_FAIL_IMMEDIATELY`) is written from the Win32 documentation and was compiled with MinGW but not run on Windows. A tool that opens `.anyps5-instance.lock` without sharing (an antivirus scanner or a backup agent) makes the open fail with a sharing violation, which stops start-up as an error naming the variable, not as an already-running title. Windows sharing modes of the locked file on ReFS and on SMB shares are not measured.
- [Instance lock on macOS](../../../core/libs/prx/libkernel/System/src/InstanceLockPosix.cpp) (libkernel) - macOS uses the same `flock` backend as Linux. It was not built or run on macOS, and `flock` on APFS, HFS+ and network volumes is not measured.
- [Instance lock start-up](../../../core/libs/prx/libkernel/System/src/InstanceLockStartup.cpp) (libkernel) - the check runs from a static initializer of libkernel, as the host CPU check does: the error is the uncaught exception that ends the process, not a message of the title's own start-up path, and on Windows it runs while the library loads. Only a working directory that holds `app0/sce_sys/param.json` or `param.sfo` is locked; a title run from another working directory takes no lock, and its data is the one relative to that directory.
- [Instance lock across a restart](../../../core/libs/prx/libkernel/System/src/InstanceLockStartup.cpp) (libkernel) - `sceSystemServiceLoadExec` on Linux and macOS replaces the image with `execv`, which closes the close-on-exec lock descriptor before the new image takes the lock again; a third copy started in that gap can take it first and the restarted title then stops with the already-running error. On Windows the lock is released just before `CreateProcessW` with the same gap. A title that starts a second copy of itself from the same directory by other means (`posix_spawn`, a new process of its own) stops with that error while `ANYPS5_INSTANCE_LOCK=on`. A `fork` child that does not exec keeps the lock until it exits.
- [Instance lock default](../../../core/libs/prx/libkernel/System/src/InstanceLockStartup.cpp) (libkernel) - `ANYPS5_INSTANCE_LOCK` is off unless set, so titles keep today's behaviour. It is not on by default because no title was run with it on beyond the repository's fixtures: with it on, a title whose `param.json` has no readable title ID now stops at start-up instead of at its first title ID query, and the restart, self-spawn and file system cases in the neighbouring entries are unmeasured.
- [mimalloc restart](../../../core/libs/prx/libkernel/System/src/MimallocRestart.cpp) (libkernel) - when the `execv` that restarts the title with `APS5_MIMALLOC` fails, the title prints the error and goes on with the system allocator, but an `ANYPS5_LOG_FILE` copy stays stopped: libkernel gave the standard streams back to the terminal before the `execv`, and libc cannot take them again, so the rest of the output reaches the terminal only. LoadExec stops the title when its `execv` fails. Only that log-file copy is handed back before the `execv`: a descriptor without close-on-exec or a lock that another libc initializer took before libkernel's constructor runs is carried into the restarted process.
- [sigemptyset, sigfillset, sigaddset, sigdelset, sigismember](../../../core/libs/prx/libkernel/System/src/SignalSets.cpp) (libkernel) copy the 16-byte set through `GuestCopyIn_nid_no_patch` and `GuestCopyOut_nid_no_patch` and fail with -1 and `EFAULT` for a null or unusable set as a host-safety fallback. FreeBSD 11.4's [`sigsetops.c`](https://github.com/freebsd/freebsd-src/blob/release/11.4.0/lib/libc/gen/sigsetops.c) works on the set in user space with no system call, so a bad pointer faults the process on a console and has no errno; `EFAULT` was not measured there. A signal outside 1 to 128 gives `EINVAL` before the set is touched, as in the source.
- [sceKernelGetModuleList, sceKernelGetModuleList2, sceKernelGetModuleInfo, sceKernelGetModuleInfo2](../../../core/libs/prx/libkernel/Module/src/ModuleInfo.cpp) (libkernel) validate `handles`, `actual`, and `info` buffers with `GuestCopyIn_nid_no_patch` and `GuestCopyOut_nid_no_patch`, returning `SCE_KERNEL_ERROR_EFAULT` on bad memory as host-safety fallbacks. Console fault handling is unmeasured.
+8
View File
@@ -390,6 +390,14 @@ Games ask whether an add-on (downloadable content) is installed with `sceNpEntit
Games also ask for the console's date format and time format with `sceSystemServiceParamGetInt`. Without any setting the date format is day, month, year and the time format is 24-hour. `ANYPS5_DATE_FORMAT` sets the date format to 0 (year, month, day), 1 (day, month, year) or 2 (month, day, year), and `ANYPS5_TIME_FORMAT` sets the time format to 0 (12-hour) or 1 (24-hour). For example, `ANYPS5_DATE_FORMAT=2` with `ANYPS5_TIME_FORMAT=0` gives month, day, year and a 12-hour clock. Either variable also accepts `auto` (in any letter case), which takes the choice from the host's short date and time patterns: on Linux the locale named by the first of `LC_ALL`, `LC_TIME` and `LANG` that is set and not empty (`LANGUAGE` and `LC_MESSAGES` do not count), on Windows the user's short date and time formats from the Region settings, and on macOS the current locale. Only the order of the day, month and year and whether the clock is 12-hour or 24-hour are used; separators and names are not. When the host has no preference (nothing set, the `C` and `POSIX` locales, a locale that is not installed) or its date pattern has an order the console has no format for, the value stays 1 and one line on stderr names the variable. The host is read once per process, so every query then answers the same. The time zone and summer time already follow the host. An empty value is the same as an unset one; any other value stops the game at its first query of that parameter with an error that names the variable.
### One copy of a title at a time
Two copies of one title started from the same directory share its save data (`_sd/`), app data (`data/`) and download data (`download0/`) and can corrupt each other. Set `ANYPS5_INSTANCE_LOCK=on` to keep the second copy from starting. The first copy takes an operating-system lock on `.anyps5-instance.lock` in the directory the game runs from (the one that holds `app0/`) and keeps it until it exits. The system releases it when the process ends or crashes, so a file left behind does no harm; AnyPS5 never deletes it. Unset, empty or `off` takes no lock and creates no file.
The second copy stops before it runs, with an error that names the title ID, the directory, the lock file and the variable, and says to set `ANYPS5_INSTANCE_LOCK=off` to run both anyway. Copies started from different directories share nothing and do not conflict. Only a directory that holds `app0/sce_sys/param.json` or `param.sfo` is locked.
Any other value, a title ID that cannot be read and a lock file that cannot be created stop the game at start-up with an error that names the variable. The lock only keeps two copies apart; it is not a backup and does not protect save data from anything else. Windows, macOS and network file systems are not verified; see the [libkernel technical debt](../dev/debt/libkernel.md).
### Trophies
A game unlocks a trophy by posting a `_UnlockTrophy` event with an int32 `_trophy_id` property to `libSceNpUniversalDataSystem`, or through the statistics rules described below. The unlock is stored in `_trophy/<user id>_<service label>.txt` in the directory the game runs in (the one that holds `app0/`), one `<trophy id> <unlock time>` line per trophy; the time is an RTC tick, microseconds since 0001-01-01 UTC. Delete the file before starting the game to lock its trophies again. Each new unlock prints one line, such as `[trophy] PPSA01556 unlocked trophy 12 for user 268435456`; unlocking a trophy again prints nothing. `sceNpTrophy2GetTrophyInfo`, `sceNpTrophy2GetTrophyInfoArray` and `sceNpTrophy2GetGameInfo` report the stored unlocks and their times to the game. When the game's trophy data is loaded (see below), a posted unlock of a trophy that the data does not have, of the platinum, or of a progressive trophy is not stored and prints the reason, such as `[trophy] ignored the posted unlock of trophy 0 for user 268435456: it is the platinum, which unlocks with the last trophy that names it`; the platinum unlocks with the last trophy that names it, and a progressive trophy through its statistic. Without trophy data every posted id of 0 or more is stored, and the platinum is not unlocked when the other trophies are.