Repository navigation
Expand file tree
/
Copy pathModuleInfo.cpp
More file actions
637 lines (587 loc) · 27.2 KB
/
Copy pathModuleInfo.cpp
File metadata and controls
637 lines (587 loc) · 27.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
#include <algorithm>
#include "prx/libkernel/include/Api.hpp"
#include <cstdint>
#include <cstddef>
#include <cstring>
#include <iterator>
#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/DirectMemory/DirectMemory.hpp"
#include "prx/libkernel/KernelErrors.hpp"
#include "prx/libkernel/Module/EhFrame.hpp"
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#include <psapi.h>
#include <filesystem>
#elif defined(__APPLE__)
#include "prx/libc/include/specifics/linux/ElfTypes.hpp"
#include <dlfcn.h>
#include <mach-o/dyld.h>
#include <mach-o/getsect.h>
#include <mach-o/loader.h>
#else
#include <dlfcn.h>
#include <link.h>
#include <mutex>
#include <unistd.h>
#include <unordered_map>
#endif
extern "C" std::int32_t ModuleIdForImage_nid_no_patch(const void* native);
namespace {
constexpr char Caller[] = "sceKernelGetModuleInfoFromAddr";
constexpr char GuestModuleSuffix[] = ".guest.prx";
constexpr std::uint64_t TerminatorSize = 4;
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("module info: ") + field + " exceeds 32 bits");
return static_cast<std::uint32_t>(value);
}
std::string ModuleName(std::string fileName) {
if (fileName.size() > sizeof(GuestModuleSuffix) - 1 && fileName.ends_with(GuestModuleSuffix))
fileName.resize(fileName.size() - (sizeof(GuestModuleSuffix) - 1));
return fileName;
}
template<typename TInfo>
void SetName(TInfo& info, const std::string& name) {
if (name.size() >= sizeof(info.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;
};
std::uint64_t PageSpan(std::uint64_t address, std::uint64_t size) {
constexpr std::uint64_t pageMask = PS5_PAGE_SIZE - 1;
return ((address + size + pageMask) & ~pageMask) - (address & ~pageMask);
}
#ifndef _WIN32
template<typename TInfo>
struct ImageSearch {
std::uintptr_t address;
TInfo* 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;
}
#ifndef __APPLE__
struct FrameTableCache {
std::mutex mutex;
unsigned long long unloads = 0;
std::unordered_map<std::uintptr_t, EhFrame::Tables> tables;
};
#endif
EhFrame::Tables FrameTables(const dl_phdr_info& image, std::uintptr_t header) {
const auto contains = [&](std::uintptr_t begin, std::uint64_t size) { return Contains(image, begin, size); };
#ifdef __APPLE__
// The macOS image list reports no unload count that could invalidate cached tables.
return EhFrame::ReadTables(contains, header, Caller);
#else
static auto& cache = *new FrameTableCache();
std::lock_guard lock(cache.mutex);
if (cache.unloads != image.dlpi_subs) {
cache.tables.clear();
cache.unloads = image.dlpi_subs;
}
if (const auto found = cache.tables.find(header); found != cache.tables.end()) return found->second;
return cache.tables.emplace(header, EhFrame::ReadTables(contains, header, Caller)).first->second;
#endif
}
std::string ImageName(const dl_phdr_info& image) {
std::string path = image.dlpi_name ? image.dlpi_name : "";
if (path.empty()) {
char executable[4096];
#ifdef __APPLE__
std::uint32_t capacity = sizeof(executable);
if (_NSGetExecutablePath(executable, &capacity) != 0) throw std::runtime_error("sceKernelGetModuleInfoFromAddr: cannot resolve the executable path");
path = executable;
#else
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<std::size_t>(length));
#endif
}
return ModuleName(path.substr(path.find_last_of('/') + 1));
}
template<typename TInfo>
void Fill(const dl_phdr_info& image, TInfo& info) {
SetName(info, ImageName(image));
#ifndef __APPLE__
// A macOS image has no ELF TLS module or dynamic section; its TLS and init/fini stay zero.
if constexpr (Extended<TInfo>) info.tls_index = ToU32(image.dlpi_tls_modid, "TLS module index");
#endif
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 constexpr (Extended<TInfo>) {
#ifndef __APPLE__
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
#endif
if (header.p_type == PT_GNU_EH_FRAME) {
const auto tables = FrameTables(image, address);
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");
}
#ifndef __APPLE__
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;
}
}
#endif
}
}
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<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;
}
#ifdef __APPLE__
// The dlopen handle of the image holding `address` (the executable's for the main image), which
// identifies its module; null when no image holds it. The image stays loaded, so the handle stays valid.
const void* NativeImage(std::uintptr_t address) {
Dl_info symbol{};
if (!::dladdr(reinterpret_cast<const void*>(address), &symbol) || symbol.dli_fname == nullptr) return nullptr;
const bool executable = symbol.dli_fbase == _dyld_get_image_header(0);
void* native = ::dlopen(executable ? nullptr : symbol.dli_fname, RTLD_LAZY | RTLD_NOLOAD);
if (native != nullptr) ::dlclose(native);
return native;
}
#endif
#ifdef __APPLE__
std::vector<Elf64_Phdr> SegmentHeaders(const mach_header_64* header) {
std::vector<Elf64_Phdr> headers;
const auto* command = reinterpret_cast<const load_command*>(header + 1);
for (std::uint32_t index = 0; index < header->ncmds; ++index) {
if (command->cmd == LC_SEGMENT_64) {
const auto* segment = reinterpret_cast<const segment_command_64*>(command);
if (segment->initprot != VM_PROT_NONE && segment->vmsize != 0) {
Elf64_Phdr loaded{};
loaded.p_type = PT_LOAD;
loaded.p_flags = ((segment->initprot & VM_PROT_READ) ? PF_R : 0) | ((segment->initprot & VM_PROT_WRITE) ? PF_W : 0) |
((segment->initprot & VM_PROT_EXECUTE) ? PF_X : 0);
loaded.p_offset = segment->fileoff;
loaded.p_vaddr = segment->vmaddr;
loaded.p_filesz = segment->filesize;
loaded.p_memsz = segment->vmsize;
headers.push_back(loaded);
}
}
command = reinterpret_cast<const load_command*>(reinterpret_cast<const char*>(command) + command->cmdsize);
}
return headers;
}
struct RelinkedImage {
const void* header;
dl_phdr_info info;
};
int CollectRelinkedImage(dl_phdr_info* image, std::size_t, void* data) {
Dl_info symbol{};
if (!::dladdr(image->dlpi_phdr, &symbol) || symbol.dli_fbase == nullptr)
throw std::runtime_error("module info: no image holds a relinked image's program headers");
static_cast<std::vector<RelinkedImage>*>(data)->push_back({symbol.dli_fbase, *image});
return 0;
}
bool HostLibrary(const mach_header_64* header, const char* path) {
if (header->magic != MH_MAGIC_64 || header->filetype != MH_DYLIB || path == nullptr) return false;
if (!std::string_view(path).ends_with(".prx")) return false;
unsigned long size = 0;
return getsectiondata(header, "__APS5DATA", "__meta", &size) == nullptr;
}
int CallHostLibrary(std::uint32_t index, const mach_header_64* header, int (*callback)(dl_phdr_info*, std::size_t, void*), void* data) {
const char* path = _dyld_get_image_name(index);
if (!HostLibrary(header, path)) return 0;
const auto headers = SegmentHeaders(header);
if (headers.size() > std::numeric_limits<std::uint16_t>::max())
throw std::runtime_error(std::string("module info: too many segments in ") + path);
dl_phdr_info info{};
info.dlpi_addr = static_cast<std::uintptr_t>(_dyld_get_image_vmaddr_slide(index));
info.dlpi_name = path;
info.dlpi_phdr = headers.data();
info.dlpi_phnum = static_cast<std::uint16_t>(headers.size());
return callback(&info, sizeof(info), data);
}
#endif
int IterateModuleImages(int (*callback)(dl_phdr_info*, std::size_t, void*), void* data) {
#ifdef __APPLE__
std::vector<RelinkedImage> relinked;
dl_iterate_phdr(CollectRelinkedImage, &relinked);
for (std::uint32_t index = 0; index < _dyld_image_count(); ++index) {
const auto* header = reinterpret_cast<const mach_header_64*>(_dyld_get_image_header(index));
if (header == nullptr) continue;
const auto found = std::find_if(relinked.begin(), relinked.end(), [header](const RelinkedImage& image) { return image.header == header; });
const int result = found != relinked.end() ? callback(&found->info, sizeof(found->info), data) : CallHostLibrary(index, header, callback, data);
if (result != 0) return result;
}
return 0;
#else
return dl_iterate_phdr(callback, data);
#endif
}
int SearchModuleImages(int (*callback)(dl_phdr_info*, std::size_t, void*), void* data) {
#ifdef __APPLE__
if (const int result = dl_iterate_phdr(callback, data); result != 0) return result;
for (std::uint32_t index = 0; index < _dyld_image_count(); ++index) {
const auto* header = reinterpret_cast<const mach_header_64*>(_dyld_get_image_header(index));
if (header == nullptr) continue;
if (const int result = CallHostLibrary(index, header, callback, data); result != 0) return result;
}
return 0;
#else
return dl_iterate_phdr(callback, data);
#endif
}
std::vector<GuestImage> GuestImages() {
std::vector<std::uintptr_t> addresses;
IterateModuleImages(CollectGuestImage, &addresses);
std::vector<GuestImage> images;
for (const auto address : addresses) {
#ifdef __APPLE__
const void* native = NativeImage(address);
if (native == nullptr) throw std::runtime_error("sceKernelGetModuleList: no image handle for a loaded image");
#else
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");
#endif
images.push_back({native, address});
}
return images;
}
int AddGuestSegmentBytes(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(GuestModuleSuffix)) return 0;
constexpr auto allAccess = PF_R | PF_W | PF_X;
for (std::uint16_t i = 0; i < image->dlpi_phnum; ++i) {
const auto& header = image->dlpi_phdr[i];
if (header.p_type != PT_LOAD || header.p_offset == 0 || (header.p_flags & allAccess) == allAccess) continue;
*static_cast<std::uint64_t*>(data) += PageSpan(header.p_vaddr, header.p_memsz);
}
return 0;
}
std::uint64_t GuestSegmentBytes() {
std::uint64_t bytes = 0;
dl_iterate_phdr(AddGuestSegmentBytes, &bytes);
return bytes;
}
#ifdef __APPLE__
// A macOS image's native handle is a dlopen handle, which carries no path: the image holding its
// address names it, and the executable stands for the main program as Linux's unnamed image does.
bool SystemImage(const GuestImage& image) {
Dl_info symbol{};
if (!::dladdr(reinterpret_cast<const void*>(image.address), &symbol) || symbol.dli_fname == nullptr)
throw std::runtime_error("module info: no image holds a loaded guest image's address");
if (symbol.dli_fbase == _dyld_get_image_header(0)) return false;
return !std::string_view(symbol.dli_fname).ends_with(GuestModuleSuffix);
}
#else
bool SystemImage(const GuestImage& image) {
const auto* name = static_cast<const link_map*>(image.native)->l_name;
const std::string_view path = name ? name : "";
return !path.empty() && !path.ends_with(GuestModuleSuffix);
}
#endif
#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;
}
std::int32_t SectionProtection(const IMAGE_SECTION_HEADER& section) {
const auto characteristics = section.Characteristics;
return ((characteristics & IMAGE_SCN_MEM_READ) ? ProtRead : 0) | ((characteristics & IMAGE_SCN_MEM_WRITE) ? ProtWrite : 0) | ((characteristics & IMAGE_SCN_MEM_EXECUTE) ? ProtExecute : 0);
}
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("module info: GetModuleFileNameW failed with error " + std::to_string(GetLastError()));
if (length < path.size()) {
path.resize(length);
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()));
}
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;
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 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) {
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;
const auto prot = SectionProtection(section);
if (prot == 0 || info.segment_count >= std::size(info.segments)) continue;
auto& segment = info.segments[info.segment_count++];
segment.address = start;
segment.size = ToU32(section.Misc.VirtualSize, "segment size");
segment.prot = prot;
}
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;
}
std::uint64_t ImageSegmentBytes(std::uintptr_t base) {
const auto* dos = reinterpret_cast<const IMAGE_DOS_HEADER*>(base);
const auto* nt = reinterpret_cast<const IMAGE_NT_HEADERS64*>(base + static_cast<std::uintptr_t>(dos->e_lfanew));
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");
std::uint64_t bytes = 0;
for (unsigned i = 0; i < sectionCount; ++i) {
const auto& section = sections[i];
if (SectionProtection(section) == 0 || (relinked && std::strncmp(reinterpret_cast<const char*>(section.Name), ".elf", 4) != 0)) continue;
bytes += PageSpan(section.VirtualAddress, section.Misc.VirtualSize);
}
return bytes;
}
std::uint64_t GuestSegmentBytes() {
const auto executable = reinterpret_cast<std::uintptr_t>(GetModuleHandleW(nullptr));
constexpr std::wstring_view suffix = L".guest.prx";
std::uint64_t bytes = 0;
for (const auto& image : GuestImages()) {
if (image.address != executable) {
const auto path = ModulePath(reinterpret_cast<HMODULE>(image.address));
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;
}
bytes += ImageSegmentBytes(image.address);
}
return bytes;
}
bool SystemImage(const GuestImage& image) {
if (image.address == reinterpret_cast<std::uintptr_t>(GetModuleHandleW(nullptr))) return false;
constexpr std::wstring_view suffix = L".guest.prx";
const auto path = ModulePath(reinterpret_cast<HMODULE>(image.address));
return 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;
}
#endif
template<typename TInfo>
int FillModuleInfo(KernelModule handle, TInfo* info, bool titleOnly) {
if (!info) return SCE_KERNEL_ERROR_EFAULT;
if (info->st_size != sizeof(TInfo)) return SCE_KERNEL_ERROR_EINVAL;
for (const auto& image : GuestImages()) {
if (ModuleIdForImage_nid_no_patch(image.native) != handle) continue;
if (titleOnly && SystemImage(image)) return SCE_KERNEL_ERROR_EPERM;
TInfo result{};
result.st_size = sizeof(TInfo);
#ifdef _WIN32
if (!Fill(image.address, result)) return SCE_KERNEL_ERROR_ESRCH;
#else
ImageSearch<TInfo> search{image.address, &result, false};
SearchModuleImages(FindImage<TInfo>, &search);
if (!search.found) return SCE_KERNEL_ERROR_ESRCH;
if constexpr (std::is_same_v<TInfo, ModuleInfoEx>) result.id = handle;
#endif
*info = result;
return 0;
}
return SCE_KERNEL_ERROR_ESRCH;
}
int FillModuleList(KernelModule* handles, std::size_t count, std::size_t* actual, bool titleOnly) {
if (!handles) return SCE_KERNEL_ERROR_EFAULT;
auto images = GuestImages();
if (titleOnly) std::erase_if(images, SystemImage);
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;
if (!actual) return SCE_KERNEL_ERROR_EFAULT;
*actual = images.size();
return 0;
}
}
extern "C" {
int APS5_VABI sceKernelGetModuleInfoFromAddr(std::uint64_t address, int flags, ModuleInfoEx* info) {
if (flags != 1 && flags != 2) {
if (!info) throw std::invalid_argument("sceKernelGetModuleInfoFromAddr: null info with flags " + std::to_string(flags));
*info = {};
return SCE_KERNEL_ERROR_EINVAL;
}
if (!info) return SCE_KERNEL_ERROR_EFAULT;
ModuleInfoEx result{};
#ifdef _WIN32
MEMORY_BASIC_INFORMATION memory{};
const bool found = Fill(static_cast<std::uintptr_t>(address), result) &&
VirtualQuery(reinterpret_cast<LPCVOID>(address), &memory, sizeof(memory)) == sizeof(memory);
const GuestImage image{nullptr, found ? reinterpret_cast<std::uintptr_t>(memory.AllocationBase) : 0};
#elif defined(__APPLE__)
const void* native = NativeImage(static_cast<std::uintptr_t>(address));
ImageSearch<ModuleInfoEx> search{static_cast<std::uintptr_t>(address), &result, false};
if (native != nullptr) SearchModuleImages(FindImage<ModuleInfoEx>, &search);
const bool found = search.found;
if (found) result.id = ModuleIdForImage_nid_no_patch(native);
const GuestImage image{native, static_cast<std::uintptr_t>(address)};
#else
Dl_info symbol{};
link_map* native = nullptr;
ImageSearch<ModuleInfoEx> search{static_cast<std::uintptr_t>(address), &result, false};
if (dladdr1(reinterpret_cast<const void*>(address), &symbol, reinterpret_cast<void**>(&native), RTLD_DL_LINKMAP) && native)
dl_iterate_phdr(FindImage<ModuleInfoEx>, &search);
const bool found = search.found;
if (found) result.id = ModuleIdForImage_nid_no_patch(native);
const GuestImage image{native, 0};
#endif
if (!found || (flags == 2 && SystemImage(image))) {
*info = {};
return SCE_KERNEL_ERROR_ESRCH;
}
*info = result;
return 0;
}
int APS5_VABI sceKernelGetModuleList(KernelModule* handles, std::size_t count, std::size_t* actual) {
return FillModuleList(handles, count, actual, false);
}
int APS5_VABI sceKernelGetModuleList2(KernelModule* handles, std::size_t count, std::size_t* actual) {
return FillModuleList(handles, count, actual, true);
}
int APS5_VABI sceKernelGetModuleInfo(KernelModule handle, ModuleInfo* info) {
return FillModuleInfo(handle, info, false);
}
int APS5_VABI sceKernelGetModuleInfo2(KernelModule handle, ModuleInfo* info) {
return FillModuleInfo(handle, info, true);
}
int GetModuleInfoExByHandle_nid_no_patch(KernelModule handle, ModuleInfoEx* info) {
return FillModuleInfo(handle, info, false);
}
std::int32_t APS5_VABI sceKernelGetLibkernelTextLocation_nid_postfix(void** address, std::size_t* size) {
if (!address || !size) throw std::invalid_argument("sceKernelGetLibkernelTextLocation: null argument");
const auto images = GuestImages();
if (images.empty()) throw std::runtime_error("sceKernelGetLibkernelTextLocation: the main program is not loaded");
ModuleInfo info{};
#ifdef _WIN32
const bool found = Fill(images.front().address, info);
#else
ImageSearch<ModuleInfo> search{images.front().address, &info, false};
SearchModuleImages(FindImage<ModuleInfo>, &search);
const bool found = search.found;
#endif
if (!found || info.segment_count == 0)
throw std::runtime_error("sceKernelGetLibkernelTextLocation: the main program has no segments");
*address = reinterpret_cast<void*>(static_cast<std::uintptr_t>(info.segments[0].address));
*size = info.segments[0].size;
return 0;
}
std::int32_t APS5_VABI sceKernelInternalMemoryGetModuleSegmentInfo_nid_postfix(InternalSegmentInfo* result) {
if (!result) throw std::invalid_argument("sceKernelInternalMemoryGetModuleSegmentInfo: result is null");
void* address = nullptr;
std::size_t size = 0;
const auto status = sceKernelGetLibkernelTextLocation_nid_postfix(&address, &size);
if (status != 0) return status;
*result = {reinterpret_cast<std::uintptr_t>(address), size};
return 0;
}
std::uint64_t GuestImageSegmentBytes_nid_no_patch() {
return GuestSegmentBytes();
}
}