From ba8c8c4b05d262951a2c1eb4141258ce8196bdb1 Mon Sep 17 00:00:00 2001 From: alfalfa-star Date: Mon, 5 Oct 2026 19:55:15 +0200 Subject: [PATCH] feat(libkernel): implement sceKernelGetModuleInfoFromAddr A title's libc.prx calls it from __cxa_thread_atexit with flags 2 and stores the returned module id in the destructor record. The 0x1A8-byte info reports the name, id, TLS block, init and fini procedures, eh_frame_hdr and eh_frame, and up to four load segments of the image containing the address. The id is the loader handle when the image was opened through sceKernelLoadStartModule and otherwise a stable id from the same range. Unknown flags and st_size values throw. Co-Authored-By: Claude Opus 5.5 --- core/libs/SceTypes.hpp | 36 +++- core/libs/prx/libkernel/CMakeLists.txt | 10 + .../libkernel/Module/src/DynamicLoader.cpp | 10 + core/libs/prx/libkernel/Module/src/Module.cpp | 8 - .../prx/libkernel/Module/src/ModuleInfo.cpp | 186 ++++++++++++++++++ core/libs/tests/GuestModuleInfo.cpp | 64 ++++++ docs/dev/TechnicalDebt.md | 1 + 7 files changed, 302 insertions(+), 13 deletions(-) create mode 100644 core/libs/prx/libkernel/Module/src/ModuleInfo.cpp create mode 100644 core/libs/tests/GuestModuleInfo.cpp diff --git a/core/libs/SceTypes.hpp b/core/libs/SceTypes.hpp index f58476bec..84a48a94f 100644 --- a/core/libs/SceTypes.hpp +++ b/core/libs/SceTypes.hpp @@ -199,13 +199,39 @@ struct FileStat { KernelTimespec st_birthtim; }; -struct ModuleInfo { - std::uint64_t size; - std::uint64_t info[32]; - KernelModule handle; - std::uint8_t pad[156]; +struct ModuleSegmentInfo { + std::uint64_t address; + std::uint32_t size; + std::int32_t prot; }; +struct ModuleInfoEx { + std::uint64_t st_size; + char name[256]; + KernelModule id; + std::uint32_t tls_index; + std::uint64_t tls_init_addr; + std::uint32_t tls_init_size; + std::uint32_t tls_size; + std::uint32_t tls_offset; + std::uint32_t tls_align; + std::uint64_t init_proc_addr; + std::uint64_t fini_proc_addr; + std::uint64_t reserved1; + std::uint64_t reserved2; + std::uint64_t eh_frame_hdr_addr; + std::uint64_t eh_frame_addr; + std::uint32_t eh_frame_hdr_size; + std::uint32_t eh_frame_size; + ModuleSegmentInfo segments[4]; + std::uint32_t segment_count; + std::uint32_t ref_count; +}; +static_assert(offsetof(ModuleInfoEx, id) == 0x108); +static_assert(offsetof(ModuleInfoEx, eh_frame_hdr_addr) == 0x148); +static_assert(offsetof(ModuleInfoEx, segments) == 0x160); +static_assert(sizeof(ModuleInfoEx) == 0x1A8); + struct ModuleInfoForUnwind { std::uint64_t st_size; char name[256]; diff --git a/core/libs/prx/libkernel/CMakeLists.txt b/core/libs/prx/libkernel/CMakeLists.txt index 2e5364b1b..fdc0e284a 100644 --- a/core/libs/prx/libkernel/CMakeLists.txt +++ b/core/libs/prx/libkernel/CMakeLists.txt @@ -36,6 +36,7 @@ add_library(libkernel SHARED EXCLUDE_FROM_ALL ${CMAKE_CURRENT_SOURCE_DIR}/EventFlag/src/EventFlag.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Module/src/Module.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Module/src/DynamicLoader.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/Module/src/ModuleInfo.cpp ${LIBS_INCLUDE_DIR}/nid/src/NidCompute.cpp ${LIBS_INCLUDE_DIR}/nid/src/Sha1.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Aio/src/Aio.cpp @@ -98,6 +99,15 @@ if(BUILD_TESTING) set_tests_properties(guest_dynamic_loader PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() + if(NOT WIN32) + add_test_executable(guest_module_info_tests ${LIBS_INCLUDE_DIR}/tests/GuestModuleInfo.cpp) + target_include_directories(guest_module_info_tests PRIVATE ${LIBS_INCLUDE_DIR}) + target_link_libraries(guest_module_info_tests PRIVATE libkernel libc) + add_dependencies(guest_module_info_tests guest_module_fixture) + add_test(NAME guest_module_info COMMAND guest_module_info_tests $) + set_tests_properties(guest_module_info PROPERTIES + WORKING_DIRECTORY "$") + endif() add_test_executable(guest_filesystem_tests ${LIBS_INCLUDE_DIR}/tests/GuestFilesystem.cpp) target_include_directories(guest_filesystem_tests PRIVATE ${LIBS_INCLUDE_DIR}) target_link_libraries(guest_filesystem_tests PRIVATE libkernel libc) diff --git a/core/libs/prx/libkernel/Module/src/DynamicLoader.cpp b/core/libs/prx/libkernel/Module/src/DynamicLoader.cpp index e1091def8..b85934bb8 100644 --- a/core/libs/prx/libkernel/Module/src/DynamicLoader.cpp +++ b/core/libs/prx/libkernel/Module/src/DynamicLoader.cpp @@ -37,6 +37,7 @@ struct Module { std::mutex modulesMutex; std::map> modules; std::uintptr_t nextHandle = 0x20000000; +std::map imageIds; void* Symbol(Module& module, const char* name) { #ifdef _WIN32 return reinterpret_cast(GetProcAddress(static_cast(module.native), name)); @@ -123,4 +124,13 @@ int APS5_VABI dlclose_nid_postfix(void* handle) { module.reset(); return 0; } +std::int32_t ModuleIdForImage_nid_no_patch(const void* native) { + std::lock_guard lock(modulesMutex); + for (const auto& [handle, module] : modules) { + if (module->native == native) return static_cast(handle); + } + const auto [found, inserted] = imageIds.emplace(native, nextHandle); + if (inserted) ++nextHandle; + return static_cast(found->second); +} } diff --git a/core/libs/prx/libkernel/Module/src/Module.cpp b/core/libs/prx/libkernel/Module/src/Module.cpp index 3e5ba3656..1d52dc2ea 100644 --- a/core/libs/prx/libkernel/Module/src/Module.cpp +++ b/core/libs/prx/libkernel/Module/src/Module.cpp @@ -84,14 +84,6 @@ int APS5_VABI sceKernelGetModuleInfoForUnwind(uint64_t addr, int flags, ModuleIn #endif } -int APS5_VABI sceKernelGetModuleInfoFromAddr(uint64_t addr, int n, ModuleInfo* r) { - (void)addr; - (void)n; - (void)r; - NotImplemented_nid_no_patch(__func__); - return 0; -} - KernelModule APS5_VABI sceKernelLoadStartModule(const char* module_file_name, size_t args, const void* argp, uint32_t flags, const KernelLoadModuleOpt* opt, int* res) { (void)args; (void)argp; diff --git a/core/libs/prx/libkernel/Module/src/ModuleInfo.cpp b/core/libs/prx/libkernel/Module/src/ModuleInfo.cpp new file mode 100644 index 000000000..926f25ae5 --- /dev/null +++ b/core/libs/prx/libkernel/Module/src/ModuleInfo.cpp @@ -0,0 +1,186 @@ +#include +#include +#include +#include +#include +#include +#include +#include "SceTypes.hpp" +#include "prx/libc/include/General.hpp" +#include "prx/libkernel/KernelErrors.hpp" +#ifndef _WIN32 +#include +#include +#include +#endif + +extern "C" std::int32_t ModuleIdForImage_nid_no_patch(const void* native); + +namespace { + +#ifndef _WIN32 +constexpr char GuestModuleSuffix[] = ".guest.prx"; +constexpr std::int32_t ProtRead = 1; +constexpr std::int32_t ProtWrite = 2; +constexpr std::int32_t ProtExecute = 4; + +struct ImageSearch { + std::uintptr_t address; + ModuleInfoEx* info; + bool found; +}; + +bool Contains(const dl_phdr_info& image, std::uintptr_t begin, std::uint64_t size) { + for (std::uint16_t i = 0; i < image.dlpi_phnum; ++i) { + const auto& header = image.dlpi_phdr[i]; + if (header.p_type != PT_LOAD) continue; + const std::uintptr_t start = image.dlpi_addr + header.p_vaddr; + if (begin >= start && begin - start <= header.p_memsz && size <= header.p_memsz - (begin - start)) return true; + } + return false; +} + +std::uint32_t ToU32(std::uint64_t value, const char* field) { + if (value > std::numeric_limits::max()) + throw std::runtime_error(std::string("sceKernelGetModuleInfoFromAddr: ") + field + " exceeds 32 bits"); + return static_cast(value); +} + +std::uintptr_t EhFrameAddress(const dl_phdr_info& image, std::uintptr_t header) { + if (!Contains(image, header, 8)) + throw std::runtime_error("sceKernelGetModuleInfoFromAddr: eh_frame_hdr outside the image"); + const auto* bytes = reinterpret_cast(header); + if (bytes[0] != 1) throw std::runtime_error("sceKernelGetModuleInfoFromAddr: unsupported eh_frame_hdr version"); + const std::uintptr_t field = header + 4; + switch (bytes[1]) { + case 0x1b: { + std::int32_t offset; + std::memcpy(&offset, bytes + 4, sizeof(offset)); + return field + static_cast(offset); + } + case 0x03: { + std::uint32_t value; + std::memcpy(&value, bytes + 4, sizeof(value)); + return value; + } + case 0x00: { + std::uint64_t value; + if (!Contains(image, header, 12)) + throw std::runtime_error("sceKernelGetModuleInfoFromAddr: eh_frame_hdr outside the image"); + std::memcpy(&value, bytes + 4, sizeof(value)); + return static_cast(value); + } + default: + throw std::runtime_error("sceKernelGetModuleInfoFromAddr: unsupported eh_frame_ptr encoding"); + } +} + +std::uint64_t EhFrameSize(const dl_phdr_info& image, std::uintptr_t frame) { + std::uintptr_t position = frame; + for (;;) { + if (!Contains(image, position, 4)) + throw std::runtime_error("sceKernelGetModuleInfoFromAddr: eh_frame outside the image"); + std::uint32_t length; + std::memcpy(&length, reinterpret_cast(position), sizeof(length)); + position += 4; + if (length == 0) return position - frame; + std::uint64_t recordLength = length; + if (length == 0xffffffffu) { + if (!Contains(image, position, 8)) + throw std::runtime_error("sceKernelGetModuleInfoFromAddr: eh_frame outside the image"); + std::memcpy(&recordLength, reinterpret_cast(position), sizeof(recordLength)); + position += 8; + } + if (!Contains(image, position, recordLength)) + throw std::runtime_error("sceKernelGetModuleInfoFromAddr: eh_frame record outside the image"); + position += recordLength; + } +} + +std::string ImageName(const dl_phdr_info& image) { + std::string path = image.dlpi_name ? image.dlpi_name : ""; + if (path.empty()) { + char executable[4096]; + const auto length = ::readlink("/proc/self/exe", executable, sizeof(executable) - 1); + if (length < 0) throw std::runtime_error("sceKernelGetModuleInfoFromAddr: cannot resolve the executable path"); + path.assign(executable, static_cast(length)); + } + std::string name = path.substr(path.find_last_of('/') + 1); + if (name.size() > sizeof(GuestModuleSuffix) - 1 && name.ends_with(GuestModuleSuffix)) + name.resize(name.size() - (sizeof(GuestModuleSuffix) - 1)); + return name; +} + +void Fill(const dl_phdr_info& image, ModuleInfoEx& info) { + const auto name = ImageName(image); + if (name.size() >= sizeof(info.name)) + throw std::runtime_error("sceKernelGetModuleInfoFromAddr: module name too long: " + name); + std::memcpy(info.name, name.c_str(), name.size() + 1); + info.tls_index = ToU32(image.dlpi_tls_modid, "TLS module index"); + for (std::uint16_t i = 0; i < image.dlpi_phnum; ++i) { + const auto& header = image.dlpi_phdr[i]; + const std::uintptr_t address = image.dlpi_addr + header.p_vaddr; + if (header.p_type == PT_LOAD && info.segment_count < std::size(info.segments)) { + auto& segment = info.segments[info.segment_count++]; + segment.address = address; + segment.size = ToU32(header.p_memsz, "segment size"); + segment.prot = ((header.p_flags & PF_R) ? ProtRead : 0) | ((header.p_flags & PF_W) ? ProtWrite : 0) | ((header.p_flags & PF_X) ? ProtExecute : 0); + } else if (header.p_type == PT_TLS) { + info.tls_init_addr = address; + info.tls_init_size = ToU32(header.p_filesz, "TLS image size"); + info.tls_size = ToU32(header.p_memsz, "TLS size"); + info.tls_align = ToU32(header.p_align, "TLS alignment"); + } else if (header.p_type == PT_GNU_EH_FRAME) { + info.eh_frame_hdr_addr = address; + info.eh_frame_hdr_size = ToU32(header.p_memsz, "eh_frame_hdr size"); + info.eh_frame_addr = EhFrameAddress(image, address); + info.eh_frame_size = ToU32(EhFrameSize(image, info.eh_frame_addr), "eh_frame size"); + } else if (header.p_type == PT_DYNAMIC) { + for (const auto* entry = reinterpret_cast(address); entry->d_tag != DT_NULL; ++entry) { + if (entry->d_tag == DT_INIT) info.init_proc_addr = image.dlpi_addr + entry->d_un.d_ptr; + else if (entry->d_tag == DT_FINI) info.fini_proc_addr = image.dlpi_addr + entry->d_un.d_ptr; + } + } + } + info.ref_count = 1; +} + +int FindImage(dl_phdr_info* image, std::size_t, void* data) { + auto& search = *static_cast(data); + if (!Contains(*image, search.address, 1)) return 0; + Fill(*image, *search.info); + search.found = true; + return 1; +} +#endif + +} + +extern "C" { + +int APS5_VABI sceKernelGetModuleInfoFromAddr(std::uint64_t address, int flags, ModuleInfoEx* info) { + if (!info) return SCE_KERNEL_ERROR_EFAULT; + if (flags != 2) throw std::invalid_argument("sceKernelGetModuleInfoFromAddr: unsupported flags " + std::to_string(flags)); + if (info->st_size != sizeof(ModuleInfoEx)) + throw std::invalid_argument("sceKernelGetModuleInfoFromAddr: unsupported st_size " + std::to_string(info->st_size)); +#ifdef _WIN32 + (void)address; + NotImplemented_nid_no_patch(__func__); + return 0; +#else + Dl_info symbol{}; + link_map* native = nullptr; + if (!dladdr1(reinterpret_cast(address), &symbol, reinterpret_cast(&native), RTLD_DL_LINKMAP) || !native) + return SCE_KERNEL_ERROR_ESRCH; + ModuleInfoEx result{}; + result.st_size = sizeof(ModuleInfoEx); + ImageSearch search{static_cast(address), &result, false}; + dl_iterate_phdr(FindImage, &search); + if (!search.found) return SCE_KERNEL_ERROR_ESRCH; + result.id = ModuleIdForImage_nid_no_patch(native); + *info = result; + return 0; +#endif +} + +} diff --git a/core/libs/tests/GuestModuleInfo.cpp b/core/libs/tests/GuestModuleInfo.cpp new file mode 100644 index 000000000..5921931c9 --- /dev/null +++ b/core/libs/tests/GuestModuleInfo.cpp @@ -0,0 +1,64 @@ +#include "SceTypes.hpp" +#include "prx/libkernel/KernelErrors.hpp" +#include +#include +#include +#include +#include +extern "C" { +void* APS5_VABI dlopen_nid_postfix(const char*, int); +void* APS5_VABI dlsym_nid_postfix(void*, const char*); +int APS5_VABI dlclose_nid_postfix(void*); +int APS5_VABI sceKernelGetModuleInfoFromAddr(std::uint64_t, int, ModuleInfoEx*); +} +static void Require(bool value) { if (!value) std::abort(); } +template +static bool ThrowsInvalidArgument(TFunction function) { + try { + function(); + } catch (const std::invalid_argument&) { + return true; + } + return false; +} +static ModuleInfoEx Query(const void* address, int expected) { + ModuleInfoEx info{}; + info.st_size = sizeof(ModuleInfoEx); + Require(sceKernelGetModuleInfoFromAddr(reinterpret_cast(address), 2, &info) == expected); + return info; +} +int main(int argc, char** argv) { + Require(argc == 2); + void* module = dlopen_nid_postfix(argv[1], 2); + Require(module != nullptr); + const void* add = dlsym_nid_postfix(module, "GuestModuleAdd"); + Require(add != nullptr); + const auto info = Query(add, 0); + Require(info.st_size == sizeof(ModuleInfoEx)); + Require(info.id == static_cast(reinterpret_cast(module))); + Require(std::string(info.name) == std::string(argv[1]).substr(std::string(argv[1]).find_last_of("/\\") + 1)); + Require(info.segment_count > 0 && info.segment_count <= 4 && info.ref_count == 1); + bool executable = false; + for (std::uint32_t i = 0; i < info.segment_count; ++i) { + const auto& segment = info.segments[i]; + if (reinterpret_cast(add) >= segment.address && reinterpret_cast(add) - segment.address < segment.size) + executable = (segment.prot & 5) == 5; + } + Require(executable); + Require(info.eh_frame_hdr_addr != 0 && info.eh_frame_hdr_size != 0 && info.eh_frame_addr != 0 && info.eh_frame_size != 0); + Require(info.init_proc_addr == 0 || info.init_proc_addr >= info.segments[0].address); + const auto self = Query(reinterpret_cast(&Require), 0); + Require(self.id != info.id && Query(reinterpret_cast(&Query), 0).id == self.id); + void* second = dlopen_nid_postfix(argv[1], 2); + Require(second && Query(add, 0).id == info.id); + Require(dlclose_nid_postfix(second) == 0); + int local = 0; + Query(&local, SCE_KERNEL_ERROR_ESRCH); + Require(sceKernelGetModuleInfoFromAddr(reinterpret_cast(add), 2, nullptr) == SCE_KERNEL_ERROR_EFAULT); + ModuleInfoEx invalid{}; + invalid.st_size = sizeof(ModuleInfoEx); + Require(ThrowsInvalidArgument([&] { sceKernelGetModuleInfoFromAddr(reinterpret_cast(add), 1, &invalid); })); + invalid.st_size = sizeof(ModuleInfoEx) - 8; + Require(ThrowsInvalidArgument([&] { sceKernelGetModuleInfoFromAddr(reinterpret_cast(add), 2, &invalid); })); + Require(dlclose_nid_postfix(module) == 0); +} diff --git a/docs/dev/TechnicalDebt.md b/docs/dev/TechnicalDebt.md index 02ea84a84..6b7eee902 100644 --- a/docs/dev/TechnicalDebt.md +++ b/docs/dev/TechnicalDebt.md @@ -40,6 +40,7 @@ Throughout the project, every function at every stage either **does exactly what - [gQkqkLttcpw](../../core/libs/prx/libSceAgc/Acb/src/Control.cpp) (libSceAgc) - unknown name, signature - [sceAgcDcbPrimeUtcl2](../../core/libs/prx/libSceAgc/DcbState/src/Display.cpp) (libSceAgc) - assumed to write the packet `sceAgcAcbPrimeUtcl2` writes: PRIME_UTCL2 has the same 5 dwords on the graphics and compute rings. Not confirmed on a title. Both write a NOP of that size, as there is no TLB to prime - [sceKernelInternalMemoryGetModuleSegmentInfo](../../core/libs/prx/libkernel/Module/src/Module.cpp) (libkernel) - unknown signature +- [sceKernelGetModuleInfoFromAddr](../../core/libs/prx/libkernel/Module/src/ModuleInfo.cpp) (libkernel) - the 0x1A8-byte info layout follows the [shadPS4](https://github.com/shadps4-emu/shadPS4) reimplementation; a title's `libc.prx` reads only `id` (PPSA14632). The meaning of `flags` is unknown; only 2 is accepted, as is only the full `st_size`. The id is the `sceKernelLoadStartModule` handle of an image opened through the loader and otherwise a stable id from the same range. The name is the host file name without `.guest.prx`. An image with more than 4 load segments (the converted executable has 7) reports its first 4. `tls_offset` is 0 and `ref_count` is 1, as the host loader exposes neither. Not implemented on Windows - [sceKernelSyncOnAddressWait](../../core/libs/prx/libkernel/SyncOnAddress/src/SyncOnAddress.cpp) (libkernel) - the only known caller passes a null timeout and a name string as the fourth argument; the timeout is assumed to point to microseconds like the other kernel waits, and the name is ignored - [sceKernelMapNamedFlexibleMemoryInternal](../../core/libs/prx/libkernel/DirectMemory/Export.cpp) (libkernel) - flag 0x8000 unknown; only the sceKernelMapNamedFlexibleMemory flags are accepted - [sceLibcInternalBacktraceForGame](../../core/libs/prx/libc/src/HeapDiagnostics.cpp) (libSceLibcInternal, implemented in libc) - unknown signature