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
13 changes: 13 additions & 0 deletions core/libs/SceTypes.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,19 @@ struct ModuleSegmentInfo {
std::int32_t prot;
};

struct ModuleInfo {
std::uint64_t st_size;
char name[256];
ModuleSegmentInfo segments[4];
std::uint32_t segment_count;
std::uint8_t fingerprint[20];
};
static_assert(offsetof(ModuleInfo, name) == 0x8);
static_assert(offsetof(ModuleInfo, segments) == 0x108);
static_assert(offsetof(ModuleInfo, segment_count) == 0x148);
static_assert(offsetof(ModuleInfo, fingerprint) == 0x14C);
static_assert(sizeof(ModuleInfo) == 0x160);

struct ModuleInfoEx {
std::uint64_t st_size;
char name[256];
Expand Down
191 changes: 150 additions & 41 deletions core/libs/prx/libkernel/Module/src/ModuleInfo.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
#include <limits>
#include <stdexcept>
#include <string>
#include <string_view>
#include <type_traits>
#include <vector>
#include "SceTypes.hpp"
#include "prx/libc/include/General.hpp"
#include "prx/libkernel/KernelErrors.hpp"
Expand All @@ -14,6 +17,7 @@
#define NOMINMAX
#endif
#include <windows.h>
#include <psapi.h>
#include <filesystem>
#else
#include <dlfcn.h>
Expand All @@ -32,9 +36,12 @@ constexpr std::int32_t ProtRead = 1;
constexpr std::int32_t ProtWrite = 2;
constexpr std::int32_t ProtExecute = 4;

template<typename TInfo>
constexpr bool Extended = std::is_same_v<TInfo, ModuleInfoEx>;

std::uint32_t ToU32(std::uint64_t value, const char* field) {
if (value > std::numeric_limits<std::uint32_t>::max())
throw std::runtime_error(std::string("sceKernelGetModuleInfoFromAddr: ") + field + " exceeds 32 bits");
throw std::runtime_error(std::string("module info: ") + field + " exceeds 32 bits");
return static_cast<std::uint32_t>(value);
}

Expand All @@ -44,16 +51,23 @@ std::string ModuleName(std::string fileName) {
return fileName;
}

void SetName(ModuleInfoEx& info, const std::string& name) {
template<typename TInfo>
void SetName(TInfo& info, const std::string& name) {
if (name.size() >= sizeof(info.name))
throw std::runtime_error("sceKernelGetModuleInfoFromAddr: module name too long: " + name);
throw std::runtime_error("module info: module name too long: " + name);
std::memcpy(info.name, name.c_str(), name.size() + 1);
}

struct GuestImage {
const void* native;
std::uintptr_t address;
};

#ifndef _WIN32
template<typename TInfo>
struct ImageSearch {
std::uintptr_t address;
ModuleInfoEx* info;
TInfo* info;
bool found;
};

Expand All @@ -78,10 +92,10 @@ std::string ImageName(const dl_phdr_info& image) {
return ModuleName(path.substr(path.find_last_of('/') + 1));
}

void Fill(const dl_phdr_info& image, ModuleInfoEx& info) {
const auto contains = [&](std::uintptr_t begin, std::uint64_t size) { return Contains(image, begin, size); };
template<typename TInfo>
void Fill(const dl_phdr_info& image, TInfo& info) {
SetName(info, ImageName(image));
info.tls_index = ToU32(image.dlpi_tls_modid, "TLS module index");
if constexpr (Extended<TInfo>) 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;
Expand All @@ -90,34 +104,64 @@ void Fill(const dl_phdr_info& image, ModuleInfoEx& info) {
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) {
const auto tables = EhFrame::ReadTables(contains, address, Caller);
info.eh_frame_hdr_addr = address;
info.eh_frame_hdr_size = ToU32(header.p_memsz, "eh_frame_hdr size");
info.eh_frame_addr = tables.frames;
info.eh_frame_size = ToU32(tables.framesSize + TerminatorSize, "eh_frame size");
} else if (header.p_type == PT_DYNAMIC) {
for (const auto* entry = reinterpret_cast<const ElfW(Dyn)*>(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;
} else if constexpr (Extended<TInfo>) {
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) {
const auto contains = [&](std::uintptr_t begin, std::uint64_t size) { return Contains(image, begin, size); };
const auto tables = EhFrame::ReadTables(contains, address, Caller);
info.eh_frame_hdr_addr = address;
info.eh_frame_hdr_size = ToU32(header.p_memsz, "eh_frame_hdr size");
info.eh_frame_addr = tables.frames;
info.eh_frame_size = ToU32(tables.framesSize + TerminatorSize, "eh_frame size");
} else if (header.p_type == PT_DYNAMIC) {
for (const auto* entry = reinterpret_cast<const ElfW(Dyn)*>(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;
if constexpr (Extended<TInfo>) info.ref_count = 1;
}

template<typename TInfo>
int FindImage(dl_phdr_info* image, std::size_t, void* data) {
auto& search = *static_cast<ImageSearch*>(data);
auto& search = *static_cast<ImageSearch<TInfo>*>(data);
if (!Contains(*image, search.address, 1)) return 0;
Fill(*image, *search.info);
search.found = true;
return 1;
}

int CollectGuestImage(dl_phdr_info* image, std::size_t, void* data) {
const std::string_view name = image->dlpi_name ? image->dlpi_name : "";
if (!name.empty() && !name.ends_with(".prx")) return 0;
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;
static_cast<std::vector<std::uintptr_t>*>(data)->push_back(image->dlpi_addr + header.p_vaddr);
return 0;
}
return 0;
}

std::vector<GuestImage> GuestImages() {
std::vector<std::uintptr_t> addresses;
dl_iterate_phdr(CollectGuestImage, &addresses);
std::vector<GuestImage> images;
for (const auto address : addresses) {
Dl_info symbol{};
link_map* native = nullptr;
if (!dladdr1(reinterpret_cast<const void*>(address), &symbol, reinterpret_cast<void**>(&native), RTLD_DL_LINKMAP) || !native)
throw std::runtime_error("sceKernelGetModuleList: no link map for a loaded image");
images.push_back({native, address});
}
return images;
}
#else
bool SectionNamed(const IMAGE_SECTION_HEADER& section, const char* name) {
return std::strncmp(reinterpret_cast<const char*>(section.Name), name, IMAGE_SIZEOF_SHORT_NAME) == 0;
Expand All @@ -128,51 +172,60 @@ std::int32_t SectionProtection(const IMAGE_SECTION_HEADER& section) {
return ((characteristics & IMAGE_SCN_MEM_READ) ? ProtRead : 0) | ((characteristics & IMAGE_SCN_MEM_WRITE) ? ProtWrite : 0) | ((characteristics & IMAGE_SCN_MEM_EXECUTE) ? ProtExecute : 0);
}

std::string ImageName(HMODULE module) {
std::wstring ModulePath(HMODULE module) {
std::wstring path(MAX_PATH, L'\0');
for (;;) {
const auto length = GetModuleFileNameW(module, path.data(), static_cast<DWORD>(path.size()));
if (length == 0) throw std::runtime_error("sceKernelGetModuleInfoFromAddr: cannot resolve the module path");
if (length == 0) throw std::runtime_error("module info: GetModuleFileNameW failed with error " + std::to_string(GetLastError()));
if (length < path.size()) {
path.resize(length);
break;
return path;
}
path.resize(path.size() * 2);
}
}

std::string ImageName(HMODULE module) {
const auto path = ModulePath(module);
const auto fileName = std::filesystem::path(path).filename().u8string();
return ModuleName(std::string(fileName.begin(), fileName.end()));
}

bool Fill(std::uintptr_t address, ModuleInfoEx& info) {
template<typename TInfo>
bool Fill(std::uintptr_t address, TInfo& info) {
MEMORY_BASIC_INFORMATION memory{};
if (VirtualQuery(reinterpret_cast<LPCVOID>(address), &memory, sizeof(memory)) != sizeof(memory) || memory.Type != MEM_IMAGE) return false;
const auto base = reinterpret_cast<std::uintptr_t>(memory.AllocationBase);
const auto* dos = reinterpret_cast<const IMAGE_DOS_HEADER*>(base);
if (dos->e_magic != IMAGE_DOS_SIGNATURE) return false;
const auto* nt = reinterpret_cast<const IMAGE_NT_HEADERS64*>(base + static_cast<std::uintptr_t>(dos->e_lfanew));
if (nt->Signature != IMAGE_NT_SIGNATURE || nt->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC) return false;
const std::uint64_t imageSize = nt->OptionalHeader.SizeOfImage;
const auto contains = [&](std::uintptr_t begin, std::uint64_t size) { return begin >= base && begin - base <= imageSize && size <= imageSize - (begin - base); };
SetName(info, ImageName(reinterpret_cast<HMODULE>(base)));
const auto* sections = IMAGE_FIRST_SECTION(nt);
const auto sectionCount = nt->FileHeader.NumberOfSections;
bool relinked = false;
for (unsigned i = 0; i < sectionCount; ++i) relinked = relinked || SectionNamed(sections[i], ".elf0");
EhFrame::Tables tables;
const bool hasEhmeta = EhFrame::ReadEhmeta(base, *nt, Caller, tables);
if (hasEhmeta) {
info.eh_frame_hdr_addr = tables.header;
info.eh_frame_hdr_size = ToU32(tables.headerSize, "eh_frame_hdr size");
info.eh_frame_addr = tables.frames;
info.eh_frame_size = ToU32(tables.framesSize + TerminatorSize, "eh_frame size");
if constexpr (Extended<TInfo>) {
if (hasEhmeta) {
info.eh_frame_hdr_addr = tables.header;
info.eh_frame_hdr_size = ToU32(tables.headerSize, "eh_frame_hdr size");
info.eh_frame_addr = tables.frames;
info.eh_frame_size = ToU32(tables.framesSize + TerminatorSize, "eh_frame size");
}
}
for (unsigned i = 0; i < sectionCount; ++i) {
const auto& section = sections[i];
const auto start = base + section.VirtualAddress;
if (SectionNamed(section, ".ehmeta")) continue;
if (SectionNamed(section, ".ehfram") && !hasEhmeta) {
info.eh_frame_addr = start;
info.eh_frame_size = ToU32(EhFrame::FramesSize(contains, start, Caller) + TerminatorSize, "eh_frame size");
if constexpr (Extended<TInfo>) {
const std::uint64_t imageSize = nt->OptionalHeader.SizeOfImage;
const auto contains = [&](std::uintptr_t begin, std::uint64_t size) { return begin >= base && begin - base <= imageSize && size <= imageSize - (begin - base); };
info.eh_frame_addr = start;
info.eh_frame_size = ToU32(EhFrame::FramesSize(contains, start, Caller) + TerminatorSize, "eh_frame size");
}
continue;
}
if (relinked && std::strncmp(reinterpret_cast<const char*>(section.Name), ".elf", 4) != 0) continue;
Expand All @@ -183,10 +236,37 @@ bool Fill(std::uintptr_t address, ModuleInfoEx& info) {
segment.size = ToU32(section.Misc.VirtualSize, "segment size");
segment.prot = prot;
}
info.id = ModuleIdForImage_nid_no_patch(reinterpret_cast<const void*>(base));
info.ref_count = 1;
if constexpr (Extended<TInfo>) {
info.id = ModuleIdForImage_nid_no_patch(reinterpret_cast<const void*>(base));
info.ref_count = 1;
}
return true;
}

std::vector<GuestImage> GuestImages() {
const HANDLE process = GetCurrentProcess();
std::vector<HMODULE> modules(64);
for (;;) {
DWORD needed = 0;
const auto size = static_cast<DWORD>(modules.size() * sizeof(HMODULE));
if (!EnumProcessModules(process, modules.data(), size, &needed))
throw std::runtime_error("sceKernelGetModuleList: EnumProcessModules failed with error " + std::to_string(GetLastError()));
modules.resize(needed / sizeof(HMODULE));
if (needed <= size) break;
}
const HMODULE executable = GetModuleHandleW(nullptr);
constexpr std::wstring_view suffix = L".prx";
std::vector<GuestImage> images;
for (const auto module : modules) {
if (module != executable) {
const auto path = ModulePath(module);
if (path.size() < suffix.size() || CompareStringOrdinal(path.data() + path.size() - suffix.size(), static_cast<int>(suffix.size()), suffix.data(), static_cast<int>(suffix.size()), TRUE) != CSTR_EQUAL)
continue;
}
images.push_back({module, reinterpret_cast<std::uintptr_t>(module)});
}
return images;
}
#endif

}
Expand All @@ -207,13 +287,42 @@ int APS5_VABI sceKernelGetModuleInfoFromAddr(std::uint64_t address, int flags, M
link_map* native = nullptr;
if (!dladdr1(reinterpret_cast<const void*>(address), &symbol, reinterpret_cast<void**>(&native), RTLD_DL_LINKMAP) || !native)
return SCE_KERNEL_ERROR_ESRCH;
ImageSearch search{static_cast<std::uintptr_t>(address), &result, false};
dl_iterate_phdr(FindImage, &search);
ImageSearch<ModuleInfoEx> search{static_cast<std::uintptr_t>(address), &result, false};
dl_iterate_phdr(FindImage<ModuleInfoEx>, &search);
if (!search.found) return SCE_KERNEL_ERROR_ESRCH;
result.id = ModuleIdForImage_nid_no_patch(native);
#endif
*info = result;
return 0;
}

int APS5_VABI sceKernelGetModuleList(KernelModule* handles, std::size_t count, std::size_t* actual) {
if (!handles || !actual) return SCE_KERNEL_ERROR_EFAULT;
const auto images = GuestImages();
for (std::size_t i = 0; i < images.size() && i < count; ++i) handles[i] = ModuleIdForImage_nid_no_patch(images[i].native);
if (images.size() > count) return SCE_KERNEL_ERROR_ENOMEM;
*actual = images.size();
return 0;
}

int APS5_VABI sceKernelGetModuleInfo(KernelModule handle, ModuleInfo* info) {
if (!info) return SCE_KERNEL_ERROR_EFAULT;
if (info->st_size != sizeof(ModuleInfo)) return SCE_KERNEL_ERROR_EINVAL;
for (const auto& image : GuestImages()) {
if (ModuleIdForImage_nid_no_patch(image.native) != handle) continue;
ModuleInfo result{};
result.st_size = sizeof(ModuleInfo);
#ifdef _WIN32
if (!Fill(image.address, result)) return SCE_KERNEL_ERROR_ESRCH;
#else
ImageSearch<ModuleInfo> search{image.address, &result, false};
dl_iterate_phdr(FindImage<ModuleInfo>, &search);
if (!search.found) return SCE_KERNEL_ERROR_ESRCH;
#endif
*info = result;
return 0;
}
return SCE_KERNEL_ERROR_ESRCH;
}

}
Loading
Loading