Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion core/libs/prx/libSceSystemService/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,15 @@ if(BUILD_TESTING)
add_test(NAME guest_quick_exit COMMAND guest_system_exit_tests --quick-exit)
add_test(NAME guest_immediate_exit COMMAND guest_system_exit_tests --immediate)
add_test(NAME guest_return_from_main COMMAND guest_system_exit_tests --return-from-main)
add_test(NAME guest_system_relaunch COMMAND guest_system_exit_tests --relaunch-driver)
set_tests_properties(guest_system_exit PROPERTIES
PASS_REGULAR_EXPRESSION "Guest shutdown and atexit completed")
set_tests_properties(guest_quick_exit PROPERTIES
PASS_REGULAR_EXPRESSION "Guest quick_exit handlers completed")
set_tests_properties(guest_system_relaunch PROPERTIES
PASS_REGULAR_EXPRESSION "Guest relaunch completed" TIMEOUT 30)
if(WIN32)
set_tests_properties(guest_system_exit guest_system_exit_parameters guest_immediate_exit guest_return_from_main guest_quick_exit PROPERTIES ENVIRONMENT_MODIFICATION
set_tests_properties(guest_system_exit guest_system_exit_parameters guest_immediate_exit guest_return_from_main guest_quick_exit guest_system_relaunch PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
add_test_executable(guest_system_service_tests ${LIBS_INCLUDE_DIR}/tests/GuestSystemService.cpp)
Expand Down
168 changes: 164 additions & 4 deletions core/libs/prx/libSceSystemService/Export.cpp
Original file line number Diff line number Diff line change
@@ -1,12 +1,21 @@
#include <cerrno>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <charconv>
#include <filesystem>
#include <stdexcept>
#include <string>
#include <string_view>
#include <system_error>
#include <vector>
#if defined(_WIN32)
#include <windows.h>
#elif defined(__linux__)
#include <unistd.h>
#endif
#include "prx/libc/include/Shutdown.hpp"
#include "SceTypes.hpp"
#include "prx/libc/include/General.hpp"
Expand All @@ -29,18 +38,169 @@ int ConsoleLanguage() {
return language;
}

constexpr char MainExecutable[] = "/app0/eboot.bin";
constexpr char ApplicationRoot[] = "/app0/";
constexpr char MainExecutableVariable[] = "APS5_EBOOT";
#if defined(_WIN32)
constexpr wchar_t MainExecutableVariableWide[] = L"APS5_EBOOT";
#endif

[[noreturn]] void UnconvertedExecutable(const std::string& message) {
NotImplemented_nid_no_patch(("sceSystemServiceLoadExec: " + message).c_str());
std::abort();
}

std::string ConvertedExecutableName(const char* path) {
std::string_view relative(path);
if (!relative.starts_with(ApplicationRoot)) UnconvertedExecutable(std::string("executables outside /app0 (") + path + ")");
relative.remove_prefix(std::size(ApplicationRoot) - 1);
std::string name;
while (true) {
const std::size_t separator = relative.find('/');
const std::string_view component = relative.substr(0, separator);
if (component.empty() || component == "." || component == "..") UnconvertedExecutable(std::string("a path with an empty, . or .. component (") + path + ")");
name += (name.empty() ? "" : ".") + std::string(component);
if (separator == std::string_view::npos) return name;
relative.remove_prefix(separator + 1);
}
}

#if defined(_WIN32)
std::wstring Utf16(const std::string& text) {
if (text.empty()) return {};
const int size = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, text.data(), static_cast<int>(text.size()), nullptr, 0);
if (size <= 0) throw std::runtime_error("sceSystemServiceLoadExec: argument is not valid UTF-8");
std::wstring wide(static_cast<std::size_t>(size), L'\0');
MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, text.data(), static_cast<int>(text.size()), wide.data(), size);
return wide;
}

std::wstring QuotedArgument(const std::wstring& argument) {
if (!argument.empty() && argument.find_first_of(L" \t\n\v\"") == std::wstring::npos) return argument;
std::wstring quoted = L"\"";
for (std::size_t index = 0;; ++index) {
std::size_t backslashes = 0;
while (index < argument.size() && argument[index] == L'\\') {
++backslashes;
++index;
}
if (index == argument.size()) {
quoted.append(backslashes * 2, L'\\');
break;
}
quoted.append(argument[index] == L'"' ? backslashes * 2 + 1 : backslashes, L'\\');
quoted.push_back(argument[index]);
}
quoted.push_back(L'"');
return quoted;
}

struct HostLaunch {
std::wstring executable;
std::wstring commandLine;
};

HostLaunch PrepareLaunch(const char* path, const char* const* arguments) {
std::wstring own(32768, L'\0');
const DWORD length = GetModuleFileNameW(nullptr, own.data(), static_cast<DWORD>(own.size()));
if (length == 0 || length >= own.size()) {
throw std::runtime_error("sceSystemServiceLoadExec: GetModuleFileNameW failed with error " + std::to_string(GetLastError()));
}
own.resize(length);
HostLaunch launch;
const std::filesystem::path ownPath(own);
if (std::strcmp(path, MainExecutable) == 0) {
std::wstring main(32768, L'\0');
const DWORD mainLength = GetEnvironmentVariableW(MainExecutableVariableWide, main.data(), static_cast<DWORD>(main.size()));
launch.executable = mainLength > 0 && mainLength < main.size() ? main.substr(0, mainLength) : own;
} else {
const auto target = ownPath.parent_path() / (Utf16(ConvertedExecutableName(path)) + ownPath.extension().wstring());
if (!std::filesystem::is_regular_file(target)) {
UnconvertedExecutable(std::string(path) + " without its converted executable; relink with --executable " + (path + std::size(ApplicationRoot) - 1));
}
launch.executable = target.wstring();
}
if (GetEnvironmentVariableW(MainExecutableVariableWide, nullptr, 0) == 0 && !SetEnvironmentVariableW(MainExecutableVariableWide, own.c_str())) {
throw std::runtime_error(std::string("sceSystemServiceLoadExec: cannot set ") + MainExecutableVariable);
}
launch.commandLine = L"\"" + launch.executable + L"\"";
for (std::size_t index = 0; arguments != nullptr && arguments[index] != nullptr; ++index) {
launch.commandLine += L" " + QuotedArgument(Utf16(arguments[index]));
}
return launch;
}

void StartHostExecutable(HostLaunch& launch) {
STARTUPINFOW startup{};
startup.cb = sizeof(startup);
PROCESS_INFORMATION process{};
if (!CreateProcessW(launch.executable.c_str(), launch.commandLine.data(), nullptr, nullptr, TRUE, 0, nullptr, nullptr, &startup, &process)) {
throw std::runtime_error("sceSystemServiceLoadExec: CreateProcessW failed with error " + std::to_string(GetLastError()));
}
CloseHandle(process.hThread);
CloseHandle(process.hProcess);
}
#elif defined(__linux__)
struct HostLaunch {
std::string executable;
std::vector<std::string> arguments;
};

HostLaunch PrepareLaunch(const char* path, const char* const* arguments) {
std::error_code error;
const auto own = std::filesystem::read_symlink("/proc/self/exe", error);
if (error) throw std::runtime_error("sceSystemServiceLoadExec: cannot read /proc/self/exe: " + error.message());
HostLaunch launch;
if (std::strcmp(path, MainExecutable) == 0) {
const char* main = std::getenv(MainExecutableVariable);
launch.executable = main != nullptr && *main != '\0' ? main : own.string();
} else {
const auto target = own.parent_path() / (ConvertedExecutableName(path) + own.extension().string());
if (!std::filesystem::is_regular_file(target)) {
UnconvertedExecutable(std::string(path) + " without its converted executable; relink with --executable " + (path + std::size(ApplicationRoot) - 1));
}
launch.executable = target.string();
}
if (setenv(MainExecutableVariable, own.c_str(), 0) != 0) {
throw std::runtime_error(std::string("sceSystemServiceLoadExec: cannot set ") + MainExecutableVariable);
}
launch.arguments.push_back(launch.executable);
for (std::size_t index = 0; arguments != nullptr && arguments[index] != nullptr; ++index) launch.arguments.emplace_back(arguments[index]);
return launch;
}

void StartHostExecutable(HostLaunch& launch) {
std::vector<char*> argv;
for (auto& argument : launch.arguments) argv.push_back(argument.data());
argv.push_back(nullptr);
::execv(launch.executable.c_str(), argv.data());
throw std::runtime_error("sceSystemServiceLoadExec: execv failed: " + std::string(std::strerror(errno)));
}
#else
struct HostLaunch {};

HostLaunch PrepareLaunch(const char*, const char* const*) {
UnconvertedExecutable("starting an executable on this host");
}

void StartHostExecutable(HostLaunch&) {}
#endif

}

extern "C" {

int APS5_VABI sceSystemServiceLoadExec(const char* path, const char* const* arguments) {
if (!path || !*path) return SYSTEM_SERVICE_ERROR_PARAMETER;
if (std::strcmp(path, "exit") != 0) {
NotImplemented_nid_no_patch("sceSystemServiceLoadExec: executable replacement");
if (std::strcmp(path, "exit") == 0) {
LibcRunShutdown_nid_postfix();
std::exit(0);
}
(void)arguments;
auto launch = PrepareLaunch(path, arguments);
LibcRunShutdown_nid_postfix();
std::exit(0);
std::fflush(nullptr);
StartHostExecutable(launch);
LibcTerminate_nid_no_patch(0);
}

int APS5_VABI sceSystemServiceDisableNoticeScreenSkipFlagAutoSet(void) {
Expand Down
122 changes: 118 additions & 4 deletions core/libs/tests/GuestSystemExit.cpp
Original file line number Diff line number Diff line change
@@ -1,12 +1,21 @@
#include "prx/libc/include/general/VabiMacros.hpp"
#include "prx/libc/include/Shutdown.hpp"
#include "prx/libSceSystemService/SystemService.hpp"
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <iterator>
#include <stdexcept>
#include <cstring>
#include <string>
#include <thread>
#ifdef _WIN32
#include <windows.h>
#else
#include <sys/wait.h>
#include <unistd.h>
#endif
extern "C" int APS5_VABI sceSystemServiceLoadExec(const char*, const char* const*);
extern "C" void APS5_VABI _Exit_nid_postfix(int);
Expand All @@ -33,6 +42,79 @@ void UnexpectedCleanup() { std::_Exit(3); }
#ifdef _WIN32
void WINAPI UnexpectedDetach(PVOID) { TerminateProcess(GetCurrentProcess(), 4); }
#endif
constexpr char RelaunchMarker[] = "ANYPS5_TEST_RELAUNCH_MARKER";
constexpr char MainExecutable[] = "ANYPS5_TEST_MAIN_EXECUTABLE";
void SetVariable(const char* name, const char* value) {
#ifdef _WIN32
Require(SetEnvironmentVariableA(name, value) != 0);
Require(_putenv_s(name, value) == 0);
#else
Require(setenv(name, value, 1) == 0);
#endif
}
std::filesystem::path OwnExecutable() {
#ifdef _WIN32
std::wstring executable(32768, L'\0');
executable.resize(GetModuleFileNameW(nullptr, executable.data(), static_cast<DWORD>(executable.size())));
return executable;
#else
return std::filesystem::read_symlink("/proc/self/exe");
#endif
}
void AppendMarker(const std::string& line) {
const char* marker = std::getenv(RelaunchMarker);
Require(marker != nullptr);
std::ofstream(marker, std::ios::app) << line << '\n';
}
void MainShutdown() { AppendMarker("shutdown"); }
void SecondaryShutdown() { AppendMarker("secondary shutdown"); }
int RunRelaunchingChild(const std::filesystem::path& self) {
#ifdef _WIN32
std::wstring commandLine = L"\"" + self.wstring() + L"\" --relaunch";
STARTUPINFOW startup{};
startup.cb = sizeof(startup);
PROCESS_INFORMATION process{};
Require(CreateProcessW(self.c_str(), commandLine.data(), nullptr, nullptr, TRUE, 0, nullptr, nullptr, &startup, &process) != 0);
WaitForSingleObject(process.hProcess, INFINITE);
DWORD code = 1;
GetExitCodeProcess(process.hProcess, &code);
CloseHandle(process.hThread);
CloseHandle(process.hProcess);
return static_cast<int>(code);
#else
const pid_t child = fork();
Require(child >= 0);
if (child == 0) {
execl(self.c_str(), self.c_str(), "--relaunch", static_cast<char*>(nullptr));
std::_Exit(127);
}
int status = 0;
Require(waitpid(child, &status, 0) == child);
return WIFEXITED(status) ? WEXITSTATUS(status) : 1;
#endif
}
int DriveRelaunch() {
const auto self = OwnExecutable();
const auto secondary = self.parent_path() / ("picker.picker.bin" + self.extension().string());
std::filesystem::copy_file(self, secondary, std::filesystem::copy_options::overwrite_existing);
const auto marker = std::filesystem::temp_directory_path() / ("anyps5-relaunch-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()) + ".txt");
SetVariable(RelaunchMarker, marker.string().c_str());
SetVariable(MainExecutable, self.string().c_str());
Require(RunRelaunchingChild(self) == 0);
std::string text;
for (int attempt = 0; attempt < 200 && text.find("relaunched") == std::string::npos; ++attempt) {
std::this_thread::sleep_for(std::chrono::milliseconds(50));
std::ifstream file(marker);
text.assign(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>());
}
std::error_code ignored;
std::filesystem::remove(marker, ignored);
for (int attempt = 0; attempt < 100 && std::filesystem::exists(secondary) && !std::filesystem::remove(secondary, ignored); ++attempt)
std::this_thread::sleep_for(std::chrono::milliseconds(50));
Require(text == "shutdown\narguments: --secondary|two words|quote\"d\\|\nsecondary shutdown\nrelaunched\n");
std::puts("Guest relaunch completed");
return 0;
}
}
int main(int argc, char** argv) {
if (argc > 1 && std::strcmp(argv[1], "--immediate") == 0) {
Expand All @@ -55,6 +137,31 @@ int main(int argc, char** argv) {
quick_exit_nid_postfix(0);
return 2;
}
if (argc > 1 && std::strcmp(argv[1], "--relaunch-driver") == 0) {
return DriveRelaunch();
}
if (argc > 1 && std::strcmp(argv[1], "--relaunch") == 0) {
LibcRegisterShutdown_nid_postfix(MainShutdown);
const char* const arguments[] = {"--secondary", "two words", "quote\"d\\", "", nullptr};
sceSystemServiceLoadExec("/app0/picker/picker.bin", arguments);
return 2;
}
if (argc > 1 && std::strcmp(argv[1], "--secondary") == 0) {
Require(OwnExecutable().filename().string().starts_with("picker.picker.bin"));
std::string received = "arguments:";
for (int index = 1; index < argc; ++index) received += std::string(index == 1 ? " " : "|") + argv[index];
AppendMarker(received);
LibcRegisterShutdown_nid_postfix(SecondaryShutdown);
const char* const arguments[] = {"--relaunched", nullptr};
sceSystemServiceLoadExec("/app0/eboot.bin", arguments);
return 2;
}
if (argc > 1 && std::strcmp(argv[1], "--relaunched") == 0) {
const char* main = std::getenv(MainExecutable);
Require(main != nullptr && std::filesystem::equivalent(OwnExecutable(), main));
AppendMarker("relaunched");
return 0;
}
if (argc > 1) {
LibcRegisterShutdown_nid_postfix(Cleanup);
Require(std::atexit(VerifyExit) == 0);
Expand All @@ -63,8 +170,15 @@ int main(int argc, char** argv) {
}
Require(sceSystemServiceLoadExec(nullptr, nullptr) == SYSTEM_SERVICE_ERROR_PARAMETER);
Require(sceSystemServiceLoadExec("", nullptr) == SYSTEM_SERVICE_ERROR_PARAMETER);
bool rejected = false;
try { sceSystemServiceLoadExec("/app0/another.bin", nullptr); }
catch (const std::runtime_error&) { rejected = true; }
Require(rejected);
for (const char* path : {"/app0/another.bin", "/data/eboot.bin", "/app0/../eboot.bin", "/app0//eboot.bin"}) {
bool rejected = false;
try { sceSystemServiceLoadExec(path, nullptr); }
catch (const std::runtime_error&) { rejected = true; }
Require(rejected);
}
#ifdef _WIN32
Require(GetEnvironmentVariableA("APS5_EBOOT", nullptr, 0) == 0);
#else
Require(std::getenv("APS5_EBOOT") == nullptr);
#endif
}
2 changes: 2 additions & 0 deletions core/relinker/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -440,6 +440,8 @@ if(BUILD_TESTING)
${CMAKE_CURRENT_SOURCE_DIR}/relinker/tests/test_guest_module_dir.py $<TARGET_FILE:relinker>)
add_test(NAME guest_module_directories COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/relinker/tests/test_guest_module_directories.py $<TARGET_FILE:relinker>)
add_test(NAME relinker_executables COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/relinker/tests/test_executables.py $<TARGET_FILE:relinker>)
add_test(NAME sce_module_path COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/relinker/tests/test_sce_module_path.py $<TARGET_FILE:relinker>)
add_test(NAME linux_guest_stack COMMAND ${Python3_EXECUTABLE}
Expand Down
1 change: 1 addition & 0 deletions core/relinker/cli/include/Cli.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ struct Args {
std::string runPath = "$ORIGIN/libs";
std::set<std::string> excludedSceModules;
std::vector<std::string> moduleDirectories;
std::vector<std::string> executables;
};

Args ParseArgs(int argc, char* argv[]);
Expand Down
Loading
Loading