core: Rework elf loader

This commit is contained in:
GPUCode 2023-10-26 22:55:13 +03:00
parent fed14ad4ed
commit ca564b928c
7 changed files with 514 additions and 503 deletions

View File

@ -1,122 +1,93 @@
#include "FsFile.h" #include "FsFile.h"
FsFile::FsFile() namespace Common::FS {
{
m_file = nullptr; File::File() = default;
File::File(const std::string& path, OpenMode mode) {
open(path, mode);
} }
FsFile::FsFile(const std::string& path, fsOpenMode mode) File::~File() {
{ close();
Open(path, mode);
} }
bool FsFile::Open(const std::string& path, fsOpenMode mode) bool File::open(const std::string& path, OpenMode mode) {
{ close();
Close(); #ifdef _WIN64
#ifdef _WIN64 fopen_s(&m_file, path.c_str(), getOpenMode(mode));
fopen_s(&m_file, path.c_str(), getOpenMode(mode)); #else
#else m_file = std::fopen(path.c_str(), getOpenMode(mode));
m_file = std::fopen(path.c_str(), getOpenMode(mode)); #endif
#endif return isOpen();
return IsOpen();
} }
bool FsFile::Close() bool File::close() {
{ if (!isOpen() || std::fclose(m_file) != 0) [[unlikely]] {
if (!IsOpen() || std::fclose(m_file) != 0) { m_file = nullptr;
m_file = nullptr; return false;
return false; }
}
m_file = nullptr; m_file = nullptr;
return true; return true;
} }
FsFile::~FsFile() bool File::write(std::span<const u08> data) {
{ return isOpen() && std::fwrite(data.data(), 1, data.size(), m_file) == data.size();
Close();
} }
bool FsFile::Write(const void* src, u64 size) bool File::read(void* data, u64 size) const {
{ return isOpen() && std::fread(data, 1, size, m_file) == size;
if (!IsOpen() || std::fwrite(src, 1, size, m_file) != size) {
return false;
}
return true;
} }
bool FsFile::Read(void* dst, u64 size) bool File::seek(s64 offset, SeekMode mode) {
{ #ifdef _WIN64
if (!IsOpen() || std::fread(dst, 1, size, m_file) != size) { if (!isOpen() || _fseeki64(m_file, offset, getSeekMode(mode)) != 0) {
return false; return false;
} }
return true; #else
if (!isOpen() || fseeko64(m_file, offset, getSeekMode(mode)) != 0) {
return false;
}
#endif
return true;
} }
u32 FsFile::ReadBytes(void* dst, u64 size) u64 File::tell() const {
{ if (isOpen()) [[likely]] {
return std::fread(dst, 1, size, m_file); #ifdef _WIN64
return _ftelli64(m_file);
#else
return ftello64(m_file);
#endif
}
return -1;
} }
bool FsFile::Seek(s64 offset, fsSeekMode mode) u64 File::getFileSize() {
{ #ifdef _WIN64
#ifdef _WIN64 const u64 pos = _ftelli64(m_file);
if (!IsOpen() || _fseeki64(m_file, offset, getSeekMode(mode)) != 0) { if (_fseeki64(m_file, 0, SEEK_END) != 0) {
return false; return 0;
} }
#else
if (!IsOpen() || fseeko64(m_file, offset, getSeekMode(mode)) != 0) { const u64 size = _ftelli64(m_file);
return false; if (_fseeki64(m_file, pos, SEEK_SET) != 0) {
} return 0;
#endif }
return true; #else
} const u64 pos = ftello64(m_file);
if (fseeko64(m_file, 0, SEEK_END) != 0) {
u64 FsFile::Tell() const return 0;
{ }
if (IsOpen()) {
#ifdef _WIN64 const u64 size = ftello64(m_file);
return _ftelli64(m_file); if (fseeko64(m_file, pos, SEEK_SET) != 0) {
#else return 0;
return ftello64(m_file); }
#endif #endif
} return size;
else {
return -1;
}
}
u64 FsFile::getFileSize()
{
#ifdef _WIN64
u64 pos = _ftelli64(m_file);
if (_fseeki64(m_file, 0, SEEK_END) != 0) {
return 0;
}
u64 size = _ftelli64(m_file);
if (_fseeki64(m_file, pos, SEEK_SET) != 0) {
return 0;
}
#else
u64 pos = ftello64(m_file);
if (fseeko64(m_file, 0, SEEK_END) != 0) {
return 0;
}
u64 size = ftello64(m_file);
if (fseeko64(m_file, pos, SEEK_SET) != 0) {
return 0;
}
#endif
return size;
}
bool FsFile::IsOpen() const
{
return m_file != nullptr;
} }
} // namespace Common::FS

View File

@ -1,62 +1,87 @@
#pragma once #pragma once
#include <bit>
#include <cstdio> #include <cstdio>
#include <string> #include <string>
#include <span>
#include <vector>
#include "../types.h" #include "../types.h"
enum fsOpenMode namespace Common::FS {
{
fsRead = 0x1, enum class OpenMode : u32 {
fsWrite = 0x2, Read = 0x1,
fsReadWrite = fsRead | fsWrite Write = 0x2,
ReadWrite = Read | Write
}; };
enum fsSeekMode enum class SeekMode : u32 {
{ Set,
fsSeekSet, Cur,
fsSeekCur, End,
fsSeekEnd,
}; };
class FsFile class File {
{ public:
std::FILE* m_file; File();
public: explicit File(const std::string& path, OpenMode mode = OpenMode::Read);
FsFile(); ~File();
FsFile(const std::string& path, fsOpenMode mode = fsRead);
bool Open(const std::string& path, fsOpenMode mode = fsRead);
bool IsOpen() const;
bool Close();
bool Read(void* dst, u64 size);
u32 ReadBytes(void* dst, u64 size);
bool Write(const void* src, u64 size);
bool Seek(s64 offset, fsSeekMode mode);
u64 getFileSize();
u64 Tell() const;
~FsFile();
const char* getOpenMode(fsOpenMode mode) bool open(const std::string& path, OpenMode mode = OpenMode::Read);
{ bool close();
switch (mode) { bool read(void* data, u64 size) const;
case fsRead: return "rb"; bool write(std::span<const u08> data);
case fsWrite: return "wb"; bool seek(s64 offset, SeekMode mode);
case fsReadWrite: return "r+b"; u64 getFileSize();
} u64 tell() const;
return "r"; template <typename T>
} bool read(T& data) const {
return read(&data, sizeof(T));
}
const int getSeekMode(fsSeekMode mode) template <typename T>
{ bool read(std::vector<T>& data) const {
switch (mode) { return read(data.data(), data.size() * sizeof(T));
case fsSeekSet: return SEEK_SET; }
case fsSeekCur: return SEEK_CUR;
case fsSeekEnd: return SEEK_END;
}
return SEEK_SET; bool isOpen() const {
} return m_file != nullptr;
std::FILE* fileDescr() }
{
return m_file; const char* getOpenMode(OpenMode mode) const {
} switch (mode) {
case OpenMode::Read:
return "rb";
case OpenMode::Write:
return "wb";
case OpenMode::ReadWrite:
return "r+b";
default:
return "r";
}
}
int getSeekMode(SeekMode mode) const {
switch (mode) {
case SeekMode::Set:
return SEEK_SET;
case SeekMode::Cur:
return SEEK_CUR;
case SeekMode::End:
return SEEK_END;
default:
return SEEK_SET;
}
}
[[nodiscard]] std::FILE* fileDescr() const {
return m_file;
}
private:
std::FILE* m_file{};
}; };
} // namespace Common::FS

View File

@ -21,20 +21,19 @@ Linker::~Linker()
{ {
} }
static u64 get_aligned_size(const elf_program_header* phdr) static u64 get_aligned_size(const elf_program_header& phdr)
{ {
return (phdr->p_align != 0 ? (phdr->p_memsz + (phdr->p_align - 1)) & ~(phdr->p_align - 1) : phdr->p_memsz); return (phdr.p_align != 0 ? (phdr.p_memsz + (phdr.p_align - 1)) & ~(phdr.p_align - 1) : phdr.p_memsz);
} }
static u64 calculate_base_size(const elf_header* ehdr, const elf_program_header* phdr) static u64 calculate_base_size(const elf_header& ehdr, std::span<const elf_program_header> phdr)
{ {
u64 base_size = 0; u64 base_size = 0;
for (u16 i = 0; i < ehdr->e_phnum; i++) for (u16 i = 0; i < ehdr.e_phnum; i++)
{ {
if (phdr[i].p_memsz != 0 && (phdr[i].p_type == PT_LOAD || phdr[i].p_type == PT_SCE_RELRO)) if (phdr[i].p_memsz != 0 && (phdr[i].p_type == PT_LOAD || phdr[i].p_type == PT_SCE_RELRO))
{ {
auto phdrh = phdr + i; u64 last_addr = phdr[i].p_vaddr + get_aligned_size(phdr[i]);
u64 last_addr = phdr[i].p_vaddr + get_aligned_size(phdrh);
if (last_addr > base_size) if (last_addr > base_size)
{ {
base_size = last_addr; base_size = last_addr;
@ -73,10 +72,9 @@ Module* Linker::LoadModule(const std::string& elf_name)
std::scoped_lock lock{m_mutex}; std::scoped_lock lock{m_mutex};
auto* m = new Module; auto* m = new Module;
m->linker = this; m->linker = this;
m->elf = new Elf; m->elf.Open(elf_name);
m->elf->Open(elf_name);//load elf
if (m->elf->isElfFile()) if (m->elf.isElfFile())
{ {
LoadModuleToMemory(m); LoadModuleToMemory(m);
LoadDynamicInfo(m); LoadDynamicInfo(m);
@ -107,8 +105,8 @@ Module* Linker::FindModule(/*u32 id*/)
void Linker::LoadModuleToMemory(Module* m) void Linker::LoadModuleToMemory(Module* m)
{ {
//get elf header, program header //get elf header, program header
auto* elf_header = m->elf->GetElfHeader(); const auto elf_header = m->elf.GetElfHeader();
auto* elf_pheader = m->elf->GetProgramHeader(); const auto elf_pheader = m->elf.GetProgramHeader();
u64 base_size = calculate_base_size(elf_header, elf_pheader); u64 base_size = calculate_base_size(elf_header, elf_pheader);
m->aligned_base_size = (base_size & ~(static_cast<u64>(0x1000) - 1)) + 0x1000;//align base size to 0x1000 block size (TODO is that the default block size or it can be changed? m->aligned_base_size = (base_size & ~(static_cast<u64>(0x1000) - 1)) + 0x1000;//align base size to 0x1000 block size (TODO is that the default block size or it can be changed?
@ -120,9 +118,9 @@ void Linker::LoadModuleToMemory(Module* m)
LOG_INFO_IF(debug_loader, "base_size ..............: {:#018x}\n", base_size); LOG_INFO_IF(debug_loader, "base_size ..............: {:#018x}\n", base_size);
LOG_INFO_IF(debug_loader, "aligned_base_size ......: {:#018x}\n", m->aligned_base_size); LOG_INFO_IF(debug_loader, "aligned_base_size ......: {:#018x}\n", m->aligned_base_size);
for (u16 i = 0; i < elf_header->e_phnum; i++) for (u16 i = 0; i < elf_header.e_phnum; i++)
{ {
switch(elf_pheader[i].p_type) switch (elf_pheader[i].p_type)
{ {
case PT_LOAD: case PT_LOAD:
case PT_SCE_RELRO: case PT_SCE_RELRO:
@ -130,53 +128,53 @@ void Linker::LoadModuleToMemory(Module* m)
{ {
u64 segment_addr = elf_pheader[i].p_vaddr + m->base_virtual_addr; u64 segment_addr = elf_pheader[i].p_vaddr + m->base_virtual_addr;
u64 segment_file_size = elf_pheader[i].p_filesz; u64 segment_file_size = elf_pheader[i].p_filesz;
u64 segment_memory_size = get_aligned_size(elf_pheader + i); u64 segment_memory_size = get_aligned_size(elf_pheader[i]);
auto segment_mode = m->elf->ElfPheaderFlagsStr((elf_pheader + i)->p_flags); auto segment_mode = m->elf.ElfPheaderFlagsStr(elf_pheader[i].p_flags);
LOG_INFO_IF(debug_loader, "program header = [{}] type = {}\n",i,m->elf->ElfPheaderTypeStr(elf_pheader[i].p_type)); LOG_INFO_IF(debug_loader, "program header = [{}] type = {}\n",i,m->elf.ElfPheaderTypeStr(elf_pheader[i].p_type));
LOG_INFO_IF(debug_loader, "segment_addr ..........: {:#018x}\n", segment_addr); LOG_INFO_IF(debug_loader, "segment_addr ..........: {:#018x}\n", segment_addr);
LOG_INFO_IF(debug_loader, "segment_file_size .....: {}\n", segment_file_size); LOG_INFO_IF(debug_loader, "segment_file_size .....: {}\n", segment_file_size);
LOG_INFO_IF(debug_loader, "segment_memory_size ...: {}\n", segment_memory_size); LOG_INFO_IF(debug_loader, "segment_memory_size ...: {}\n", segment_memory_size);
LOG_INFO_IF(debug_loader, "segment_mode ..........: {}\n", segment_mode); LOG_INFO_IF(debug_loader, "segment_mode ..........: {}\n", segment_mode);
m->elf->LoadSegment(segment_addr, elf_pheader[i].p_offset, segment_file_size); m->elf.LoadSegment(segment_addr, elf_pheader[i].p_offset, segment_file_size);
} }
else else
{ {
LOG_ERROR_IF(debug_loader, "p_memsz==0 in type {}\n", m->elf->ElfPheaderTypeStr(elf_pheader[i].p_type)); LOG_ERROR_IF(debug_loader, "p_memsz==0 in type {}\n", m->elf.ElfPheaderTypeStr(elf_pheader[i].p_type));
} }
break; break;
case PT_DYNAMIC: case PT_DYNAMIC:
if (elf_pheader[i].p_filesz != 0) if (elf_pheader[i].p_filesz != 0)
{ {
void* dynamic = new u08[elf_pheader[i].p_filesz]; void* dynamic = new u08[elf_pheader[i].p_filesz];
m->elf->LoadSegment(reinterpret_cast<u64>(dynamic), elf_pheader[i].p_offset, elf_pheader[i].p_filesz); m->elf.LoadSegment(reinterpret_cast<u64>(dynamic), elf_pheader[i].p_offset, elf_pheader[i].p_filesz);
m->m_dynamic = dynamic; m->m_dynamic = dynamic;
} }
else else
{ {
LOG_ERROR_IF(debug_loader, "p_filesz==0 in type {}\n", m->elf->ElfPheaderTypeStr(elf_pheader[i].p_type)); LOG_ERROR_IF(debug_loader, "p_filesz==0 in type {}\n", m->elf.ElfPheaderTypeStr(elf_pheader[i].p_type));
} }
break; break;
case PT_SCE_DYNLIBDATA: case PT_SCE_DYNLIBDATA:
if (elf_pheader[i].p_filesz != 0) if (elf_pheader[i].p_filesz != 0)
{ {
void* dynamic = new u08[elf_pheader[i].p_filesz]; void* dynamic = new u08[elf_pheader[i].p_filesz];
m->elf->LoadSegment(reinterpret_cast<u64>(dynamic), elf_pheader[i].p_offset, elf_pheader[i].p_filesz); m->elf.LoadSegment(reinterpret_cast<u64>(dynamic), elf_pheader[i].p_offset, elf_pheader[i].p_filesz);
m->m_dynamic_data = dynamic; m->m_dynamic_data = dynamic;
} }
else else
{ {
LOG_ERROR_IF(debug_loader, "p_filesz==0 in type {}\n", m->elf->ElfPheaderTypeStr(elf_pheader[i].p_type)); LOG_ERROR_IF(debug_loader, "p_filesz==0 in type {}\n", m->elf.ElfPheaderTypeStr(elf_pheader[i].p_type));
} }
break; break;
default: default:
LOG_ERROR_IF(debug_loader, "Unimplemented type {}\n", m->elf->ElfPheaderTypeStr(elf_pheader[i].p_type)); LOG_ERROR_IF(debug_loader, "Unimplemented type {}\n", m->elf.ElfPheaderTypeStr(elf_pheader[i].p_type));
} }
} }
LOG_INFO_IF(debug_loader, "program entry addr ..........: {:#018x}\n", m->elf->GetElfEntry() + m->base_virtual_addr); LOG_INFO_IF(debug_loader, "program entry addr ..........: {:#018x}\n", m->elf.GetElfEntry() + m->base_virtual_addr);
auto* rt1 = reinterpret_cast<uint8_t*>(m->elf->GetElfEntry() + m->base_virtual_addr); auto* rt1 = reinterpret_cast<uint8_t*>(m->elf.GetElfEntry() + m->base_virtual_addr);
ZyanU64 runtime_address = m->elf->GetElfEntry() + m->base_virtual_addr; ZyanU64 runtime_address = m->elf.GetElfEntry() + m->base_virtual_addr;
// Loop over the instructions in our buffer. // Loop over the instructions in our buffer.
ZyanUSize offset = 0; ZyanUSize offset = 0;
@ -681,6 +679,6 @@ void Linker::Execute()
p.argc = 1; p.argc = 1;
p.argv[0] = "eboot.bin"; //hmm should be ok? p.argv[0] = "eboot.bin"; //hmm should be ok?
run_main_entry(m_modules.at(0)->elf->GetElfEntry()+m_modules.at(0)->base_virtual_addr, &p, ProgramExitFunc); run_main_entry(m_modules.at(0)->elf.GetElfEntry()+m_modules.at(0)->base_virtual_addr, &p, ProgramExitFunc);
} }

View File

@ -14,17 +14,17 @@ struct EntryParams {
const char* argv[3]; const char* argv[3];
}; };
/*this struct keeps neccesary info about loaded modules.Main executeable is included too as well*/ // This struct keeps neccesary info about loaded modules. Main executeable is included too as well
struct Module struct Module
{ {
Elf* elf = nullptr; Elf elf;
u64 aligned_base_size = 0; u64 aligned_base_size = 0;
u64 base_virtual_addr = 0; //base virtual address u64 base_virtual_addr = 0; // Base virtual address
Linker* linker = nullptr; Linker* linker = nullptr;
void* m_dynamic = nullptr; void* m_dynamic = nullptr;
void* m_dynamic_data = nullptr; void* m_dynamic_data = nullptr;
DynamicModuleInfo* dynamic_info = nullptr; DynamicModuleInfo* dynamic_info = nullptr;
SymbolsResolver* export_sym = nullptr; SymbolsResolver* export_sym = nullptr;

View File

@ -1,139 +1,188 @@
#include "Elf.h" #include <bit>
#include <Util/log.h>
#include <debug.h>
#include <fmt/core.h> #include <fmt/core.h>
#include <spdlog/pattern_formatter.h> #include <spdlog/pattern_formatter.h>
#include <spdlog/sinks/stdout_color_sinks.h> #include <spdlog/sinks/stdout_color_sinks.h>
#include <spdlog/sinks/basic_file_sink.h>
#include <spdlog/spdlog.h>
#include <magic_enum.hpp> #include <debug.h>
#include "Elf.h"
#include "spdlog/sinks/basic_file_sink.h" static std::string_view getProgramTypeName(program_type_es type) {
#include "spdlog/spdlog.h" switch (type) {
case PT_FAKE:
constexpr bool debug_elf = true; return "PT_FAKE";
case PT_NPDRM_EXEC:
template <> return "PT_NPDRM_EXEC";
struct magic_enum::customize::enum_range<e_type_s> { case PT_NPDRM_DYNLIB:
static constexpr int min = 0xfe00; return "PT_NPDRM_DYNLIB";
static constexpr int max = 0xfe18; case PT_SYSTEM_EXEC:
// (max - min) must be less than UINT16_MAX. return "PT_SYSTEM_EXEC";
}; case PT_SYSTEM_DYNLIB:
return "PT_SYSTEM_DYNLIB";
Elf::~Elf() { Reset(); } case PT_HOST_KERNEL:
return "PT_HOST_KERNEL";
static self_header* load_self(FsFile& f) { case PT_SECURE_MODULE:
// read self header return "PT_SECURE_MODULE";
auto* self = new self_header; case PT_SECURE_KERNEL:
f.Read(self, sizeof(self_header)); return "PT_SECURE_KERNEL";
return self; default:
} return "INVALID";
static self_segment_header* load_self_segments(FsFile& f, u16 num) {
auto* segs = new self_segment_header[num];
f.Read(segs, sizeof(self_segment_header) * num);
return segs;
}
static elf_header* load_elf_header(FsFile& f) {
auto* m_elf_header = new elf_header;
f.Read(m_elf_header, sizeof(elf_header));
return m_elf_header;
}
static elf_program_header* load_program_header(FsFile& f, u64 offset, u16 num) {
auto* phdr = new elf_program_header[num];
f.Seek(offset, fsSeekMode::fsSeekSet);
f.Read(phdr, sizeof(elf_program_header) * num);
return phdr;
}
static elf_section_header* load_section_header(FsFile& f, u64 offset, u16 num) {
if (num == 0) // just in case we don't have section headers
{
return nullptr;
} }
auto* shdr = new elf_section_header[num];
f.Seek(offset, fsSeekMode::fsSeekSet);
f.Read(shdr, sizeof(elf_section_header) * num);
return shdr;
} }
void Elf::Reset() // reset all variables static std::string_view getIdentClassName(ident_class_es elf_class) {
{ switch (elf_class) {
if (m_f != nullptr) { case ELF_CLASS_NONE:
m_f->Close(); return "ELF_CLASS_NONE";
delete m_f; case ELF_CLASS_32:
return "ELF_CLASS_32";
case ELF_CLASS_64:
return "ELF_CLASS_64";
case ELF_CLASS_NUM:
return "ELF_CLASS_NUM";
default:
return "INVALID";
} }
delete m_self; }
delete m_elf_header;
delete m_self_id_header;
delete[] m_self_segments;
delete[] m_elf_phdr;
delete[] m_elf_shdr;
m_self = nullptr; static std::string_view getIdentEndianName(ident_endian_es endian) {
m_self_segments = nullptr; switch (endian) {
m_elf_header = nullptr; case ELF_DATA_NONE:
m_elf_phdr = nullptr; return "ELF_DATA_NONE";
m_elf_shdr = nullptr; case ELF_DATA_2LSB:
m_self_id_header = nullptr; return "ELF_DATA_2LSB";
case ELF_DATA_2MSB:
return "ELF_DATA_2MSB";
case ELF_DATA_NUM:
return "ELF_DATA_NUM";
default:
return "INVALID";
}
}
static std::string_view getIdentVersionName(ident_version_es version) {
switch (version) {
case ELF_VERSION_NONE:
return "ELF_VERSION_NONE";
case ELF_VERSION_CURRENT:
return "ELF_VERSION_CURRENT";
case ELF_VERSION_NUM:
return "ELF_VERSION_NUM";
default:
return "INVALID";
}
}
static std::string_view getIdentOsabiName(ident_osabi_es osabi) {
switch (osabi) {
case ELF_OSABI_NONE:
return "ELF_OSABI_NONE";
case ELF_OSABI_HPUX:
return "ELF_OSABI_HPUX";
case ELF_OSABI_NETBSD:
return "ELF_OSABI_NETBSD";
case ELF_OSABI_LINUX:
return "ELF_OSABI_LINUX";
case ELF_OSABI_SOLARIS:
return "ELF_OSABI_SOLARIS";
case ELF_OSABI_AIX:
return "ELF_OSABI_AIX";
case ELF_OSABI_IRIX:
return "ELF_OSABI_IRIX";
case ELF_OSABI_FREEBSD:
return "ELF_OSABI_FREEBSD";
case ELF_OSABI_TRU64:
return "ELF_OSABI_TRU64";
case ELF_OSABI_MODESTO:
return "ELF_OSABI_MODESTO";
case ELF_OSABI_OPENBSD:
return "ELF_OSABI_OPENBSD";
case ELF_OSABI_OPENVMS:
return "ELF_OSABI_OPENVMS";
case ELF_OSABI_NSK:
return "ELF_OSABI_NSK";
case ELF_OSABI_AROS:
return "ELF_OSABI_AROS";
case ELF_OSABI_ARM_AEABI:
return "ELF_OSABI_ARM_AEABI";
case ELF_OSABI_ARM:
return "ELF_OSABI_ARM";
case ELF_OSABI_STANDALONE:
return "ELF_OSABI_STANDALONE";
default:
return "INVALID";
}
}
static std::string_view getIdentAbiversionName(ident_abiversion_es version) {
switch (version) {
case ELF_ABI_VERSION_AMDGPU_HSA_V2:
return "ELF_ABI_VERSION_AMDGPU_HSA_V2";
case ELF_ABI_VERSION_AMDGPU_HSA_V3:
return "ELF_ABI_VERSION_AMDGPU_HSA_V3";
case ELF_ABI_VERSION_AMDGPU_HSA_V4:
return "ELF_ABI_VERSION_AMDGPU_HSA_V4";
case ELF_ABI_VERSION_AMDGPU_HSA_V5:
return "ELF_ABI_VERSION_AMDGPU_HSA_V5";
default:
return "INVALID";
}
}
Elf::~Elf() {
Reset();
}
void Elf::Reset() {
m_f.close();
} }
void Elf::Open(const std::string& file_name) { void Elf::Open(const std::string& file_name) {
Reset(); // reset all variables Reset();
m_f = new FsFile; m_f.open(file_name, Common::FS::OpenMode::Read);
m_f->Open(file_name, fsOpenMode::fsRead); m_f.read(m_self);
m_self = load_self(*m_f); if (is_self = isSelfFile(); !is_self) {
m_f.seek(0, Common::FS::SeekMode::Set);
bool isself = isSelfFile();
if (!isself) {
delete m_self;
m_self = nullptr;
m_f->Seek(0, fsSeekMode::fsSeekSet); // it is not an self file move to the start of file
} else { } else {
m_self_segments = load_self_segments(*m_f, m_self->segment_count); m_self_segments.resize(m_self.segment_count);
m_f.read(m_self_segments);
} }
auto elfheader_pos = m_f->Tell(); // get the entry pos for elf file const u64 elf_header_pos = m_f.tell();
m_f.read(m_elf_header);
m_elf_header = load_elf_header(*m_f);
if (!isElfFile()) { if (!isElfFile()) {
delete m_elf_header; return;
m_elf_header = nullptr;
} }
if (m_elf_header != nullptr) { const auto load_headers = [this]<typename T>(std::vector<T>& out, u64 offset, u16 num) {
m_elf_phdr = load_program_header(*m_f, elfheader_pos + m_elf_header->e_phoff, m_elf_header->e_phnum); if (!num) {
m_elf_shdr = load_section_header(*m_f, elfheader_pos + m_elf_header->e_shoff, m_elf_header->e_shnum); return;
} }
if (isself && m_elf_header != nullptr) {
out.resize(num);
m_f.seek(offset, Common::FS::SeekMode::Set);
m_f.read(out);
};
load_headers(m_elf_phdr, elf_header_pos + m_elf_header.e_phoff, m_elf_header.e_phnum);
load_headers(m_elf_shdr, elf_header_pos + m_elf_header.e_shoff, m_elf_header.e_shnum);
if (is_self) {
u64 header_size = 0; u64 header_size = 0;
header_size += sizeof(self_header); header_size += sizeof(self_header);
header_size += sizeof(self_segment_header) * m_self->segment_count; header_size += sizeof(self_segment_header) * m_self.segment_count;
header_size += sizeof(elf_header); header_size += sizeof(elf_header);
header_size += m_elf_header->e_phnum * m_elf_header->e_phentsize; header_size += m_elf_header.e_phnum * m_elf_header.e_phentsize;
header_size += m_elf_header->e_shnum * m_elf_header->e_shentsize; header_size += m_elf_header.e_shnum * m_elf_header.e_shentsize;
header_size += 15; header_size += 15;
header_size &= ~15; // align header_size &= ~15; // Align
if (m_elf_header->e_ehsize - header_size >= sizeof(elf_program_id_header)) { if (m_elf_header.e_ehsize - header_size >= sizeof(elf_program_id_header)) {
m_f->Seek(header_size, fsSeekMode::fsSeekSet); m_f.seek(header_size, Common::FS::SeekMode::Set);
m_f.read(m_self_id_header);
m_self_id_header = new elf_program_id_header;
m_f->Read(m_self_id_header, sizeof(elf_program_id_header));
} }
} }
@ -141,26 +190,19 @@ void Elf::Open(const std::string& file_name) {
} }
bool Elf::isSelfFile() const { bool Elf::isSelfFile() const {
if (m_f == nullptr) { if (m_self.magic != self_header::signature) [[unlikely]] {
fmt::print("Not a SELF file. Magic file mismatched! current = {:#x} required = {:#x}\n",
m_self.magic, self_header::signature);
return false; return false;
} }
if (m_self == nullptr) { if (m_self.version != 0x00 || m_self.mode != 0x01 || m_self.endian != 0x01 || m_self.attributes != 0x12) [[unlikely]] {
return false; // if we can't load self header return false fmt::print("Unknown SELF file\n");
}
if (m_self->magic != self_header::signature) {
printf("Not a SELF file. Magic file mismatched! current = 0x%08X required = 0x%08X\n", m_self->magic, self_header::signature);
return false; return false;
} }
if (m_self->version != 0x00 || m_self->mode != 0x01 || m_self->endian != 0x01 || m_self->attributes != 0x12) { if (m_self.category != 0x01 || m_self.program_type != 0x01) [[unlikely]] {
printf("Unknown SELF file\n"); fmt::print("Unknown SELF file\n");
return false;
}
if (m_self->category != 0x01 || m_self->program_type != 0x01) {
printf("Unknown SELF file\n");
return false; return false;
} }
@ -168,68 +210,60 @@ bool Elf::isSelfFile() const {
} }
bool Elf::isElfFile() const { bool Elf::isElfFile() const {
if (m_f == nullptr) { if (m_elf_header.e_ident.magic[EI_MAG0] != ELFMAG0 || m_elf_header.e_ident.magic[EI_MAG1] != ELFMAG1 ||
m_elf_header.e_ident.magic[EI_MAG2] != ELFMAG2 || m_elf_header.e_ident.magic[EI_MAG3] != ELFMAG3) {
fmt::print("ERROR:Not an ELF file magic is wrong!\n");
return false;
}
if (m_elf_header.e_ident.ei_class != ELF_CLASS_64) {
fmt::print("ERROR:e_ident[EI_CLASS] expected 0x02 is ({:#x})\n", static_cast<u32>(m_elf_header.e_ident.ei_class));
return false; return false;
} }
if (m_elf_header == nullptr) { if (m_elf_header.e_ident.ei_data != ELF_DATA_2LSB) {
fmt::print("ERROR:e_ident[EI_DATA] expected 0x01 is ({:#x})\n", static_cast<u32>(m_elf_header.e_ident.ei_data));
return false; return false;
} }
if (m_elf_header->e_ident.magic[EI_MAG0] != ELFMAG0 || m_elf_header->e_ident.magic[EI_MAG1] != ELFMAG1 || if (m_elf_header.e_ident.ei_version != ELF_VERSION_CURRENT) {
m_elf_header->e_ident.magic[EI_MAG2] != ELFMAG2 || m_elf_header->e_ident.magic[EI_MAG3] != ELFMAG3) { fmt::print("ERROR:e_ident[EI_VERSION] expected 0x01 is ({:#x})\n", static_cast<u32>(m_elf_header.e_ident.ei_version));
printf("ERROR:Not an ELF file magic is wrong!\n");
return false;
}
if (m_elf_header->e_ident.ei_class != ELF_CLASS_64) {
printf("ERROR:e_ident[EI_CLASS] expected 0x02 is (0x%x)\n", m_elf_header->e_ident.ei_class);
return false; return false;
} }
if (m_elf_header->e_ident.ei_data != ELF_DATA_2LSB) { if (m_elf_header.e_ident.ei_osabi != ELF_OSABI_FREEBSD) {
printf("ERROR:e_ident[EI_DATA] expected 0x01 is (0x%x)\n", m_elf_header->e_ident.ei_data); fmt::print("ERROR:e_ident[EI_OSABI] expected 0x09 is ({:#x})\n", static_cast<u32>(m_elf_header.e_ident.ei_osabi));
return false; return false;
} }
if (m_elf_header->e_ident.ei_version != ELF_VERSION_CURRENT) { if (m_elf_header.e_ident.ei_abiversion != ELF_ABI_VERSION_AMDGPU_HSA_V2) {
printf("ERROR:e_ident[EI_VERSION] expected 0x01 is (0x%x)\n", m_elf_header->e_ident.ei_version); fmt::print("ERROR:e_ident[EI_ABIVERSION] expected 0x00 is ({:#x})\n", static_cast<u32>(m_elf_header.e_ident.ei_abiversion));
return false; return false;
} }
if (m_elf_header->e_ident.ei_osabi != ELF_OSABI_FREEBSD) { if (m_elf_header.e_type != ET_SCE_DYNEXEC&& m_elf_header.e_type != ET_SCE_DYNAMIC && m_elf_header.e_type != ET_SCE_EXEC) {
printf("ERROR:e_ident[EI_OSABI] expected 0x09 is (0x%x)\n", m_elf_header->e_ident.ei_osabi); fmt::print("ERROR:e_type expected 0xFE10 OR 0xFE18 OR 0xfe00 is ({:#x})\n", static_cast<u32>(m_elf_header.e_type));
return false; return false;
} }
if (m_elf_header->e_ident.ei_abiversion != ELF_ABI_VERSION_AMDGPU_HSA_V2) { if (m_elf_header.e_machine != EM_X86_64) {
printf("ERROR:e_ident[EI_ABIVERSION] expected 0x00 is (0x%x)\n", m_elf_header->e_ident.ei_abiversion); fmt::print("ERROR:e_machine expected 0x3E is ({:#x})\n", static_cast<u32>(m_elf_header.e_machine));
return false; return false;
} }
if (m_elf_header->e_type != ET_SCE_DYNEXEC&& m_elf_header->e_type != ET_SCE_DYNAMIC&& m_elf_header->e_type != ET_SCE_EXEC) { if (m_elf_header.e_version != EV_CURRENT) {
printf("ERROR:e_type expected 0xFE10 OR 0xFE18 OR 0xfe00 is (%04x)\n", m_elf_header->e_type); fmt::print("ERROR:m_elf_header.e_version expected 0x01 is ({:#x})\n", static_cast<u32>(m_elf_header.e_version));
return false; return false;
} }
if (m_elf_header->e_machine != EM_X86_64) { if (m_elf_header.e_phentsize != sizeof(elf_program_header)) {
printf("ERROR:e_machine expected 0x3E is (%04x)\n", m_elf_header->e_machine); fmt::print("ERROR:e_phentsize ({}) != sizeof(elf_program_header)\n", static_cast<u32>(m_elf_header.e_phentsize));
return false; return false;
} }
if (m_elf_header->e_version != EV_CURRENT) { if (m_elf_header.e_shentsize > 0 &&
printf("ERROR:m_elf_header->e_version expected 0x01 is (0x%x)\n", m_elf_header->e_version); m_elf_header.e_shentsize != sizeof(elf_section_header)) // Commercial games doesn't appear to have section headers
return false;
}
if (m_elf_header->e_phentsize != sizeof(elf_program_header)) {
printf("ERROR:e_phentsize (%d) != sizeof(elf_program_header)\n", m_elf_header->e_phentsize);
return false;
}
if (m_elf_header->e_shentsize > 0 &&
m_elf_header->e_shentsize != sizeof(elf_section_header)) // commercial games doesn't appear to have section headers
{ {
printf("ERROR:e_shentsize (%d) != sizeof(elf_section_header)\n", m_elf_header->e_shentsize); fmt::print("ERROR:e_shentsize ({}) != sizeof(elf_section_header)\n", m_elf_header.e_shentsize);
return false; return false;
} }
@ -237,10 +271,10 @@ bool Elf::isElfFile() const {
} }
void Elf::DebugDump() { void Elf::DebugDump() {
if (m_self != nullptr) { // if we load elf instead if (is_self) { // If we load elf instead
spdlog::info(SElfHeaderStr()); spdlog::info(SElfHeaderStr());
spdlog::info("\n"); spdlog::info("\n");
for (u16 i = 0; i < m_self->segment_count; i++) { for (u16 i = 0; i < m_self.segment_count; i++) {
spdlog::info(SELFSegHeader(i)); spdlog::info(SELFSegHeader(i));
} }
spdlog::info("\n"); spdlog::info("\n");
@ -248,67 +282,65 @@ void Elf::DebugDump() {
spdlog::info(ElfHeaderStr()); spdlog::info(ElfHeaderStr());
if (m_elf_header->e_phentsize > 0) { if (m_elf_header.e_phentsize > 0) {
spdlog::info("Program headers:\n"); spdlog::info("Program headers:\n");
for (u16 i = 0; i < m_elf_header->e_phnum; i++) { for (u16 i = 0; i < m_elf_header.e_phnum; i++) {
spdlog::info(ElfPHeaderStr(i)); spdlog::info(ElfPHeaderStr(i));
} }
} }
if (m_elf_header->e_shentsize > 0) { if (m_elf_header.e_shentsize > 0) {
spdlog::info("Section headers:\n"); spdlog::info("Section headers:\n");
for (u16 i = 0; i < m_elf_header->e_shnum; i++) { for (u16 i = 0; i < m_elf_header.e_shnum; i++) {
spdlog::info("--- shdr {} --\n", i); spdlog::info("--- shdr {} --\n", i);
spdlog::info("sh_name ........: {}\n", (m_elf_shdr + i)->sh_name); spdlog::info("sh_name ........: {}\n", m_elf_shdr[i].sh_name);
spdlog::info("sh_type ........: {:#010x}\n", (m_elf_shdr + i)->sh_type); spdlog::info("sh_type ........: {:#010x}\n", m_elf_shdr[i].sh_type);
spdlog::info("sh_flags .......: {:#018x}\n", (m_elf_shdr + i)->sh_flags); spdlog::info("sh_flags .......: {:#018x}\n", m_elf_shdr[i].sh_flags);
spdlog::info("sh_addr ........: {:#018x}\n", (m_elf_shdr + i)->sh_addr); spdlog::info("sh_addr ........: {:#018x}\n", m_elf_shdr[i].sh_addr);
spdlog::info("sh_offset ......: {:#018x}\n", (m_elf_shdr + i)->sh_offset); spdlog::info("sh_offset ......: {:#018x}\n", m_elf_shdr[i].sh_offset);
spdlog::info("sh_size ........: {:#018x}\n", (m_elf_shdr + i)->sh_size); spdlog::info("sh_size ........: {:#018x}\n", m_elf_shdr[i].sh_size);
spdlog::info("sh_link ........: {:#010x}\n", (m_elf_shdr + i)->sh_link); spdlog::info("sh_link ........: {:#010x}\n", m_elf_shdr[i].sh_link);
spdlog::info("sh_info ........: {:#010x}\n", (m_elf_shdr + i)->sh_info); spdlog::info("sh_info ........: {:#010x}\n", m_elf_shdr[i].sh_info);
spdlog::info("sh_addralign ...: {:#018x}\n", (m_elf_shdr + i)->sh_addralign); spdlog::info("sh_addralign ...: {:#018x}\n", m_elf_shdr[i].sh_addralign);
spdlog::info("sh_entsize .....: {:#018x}\n", (m_elf_shdr + i)->sh_entsize); spdlog::info("sh_entsize .....: {:#018x}\n", m_elf_shdr[i].sh_entsize);
} }
} }
if (m_self_id_header != nullptr) {
if (is_self) {
spdlog::info("SELF info:\n"); spdlog::info("SELF info:\n");
spdlog::info("auth id ............: {:#018x}\n", m_self_id_header->authid); spdlog::info("auth id ............: {:#018x}\n", m_self_id_header.authid);
auto program_type = magic_enum::enum_cast<program_type_es>(m_self_id_header->program_type); spdlog::info("program type .......: {}\n", getProgramTypeName(m_self_id_header.program_type));
if (program_type.has_value()) { spdlog::info("app version ........: {:#018x}\n", m_self_id_header.appver);
spdlog::info("program type .......: {}\n", magic_enum::enum_name(program_type.value())); spdlog::info("fw version .........: {:#018x}\n", m_self_id_header.firmver);
} else {
spdlog::info("program type UNK....: {:#018x}\n", (int)m_self_id_header->program_type);
}
spdlog::info("app version ........: {:#018x}\n", m_self_id_header->appver);
spdlog::info("fw version .........: {:#018x}\n", m_self_id_header->firmver);
std::string digest; std::string digest;
for (int i = 0; i < 32; i++) digest += fmt::format("{:02X}", m_self_id_header->digest[i]); for (int i = 0; i < 32; i++) {
digest += fmt::format("{:02X}", m_self_id_header.digest[i]);
}
spdlog::info("digest..............: 0x{}\n",digest); spdlog::info("digest..............: 0x{}\n",digest);
} }
} }
std::string Elf::SElfHeaderStr() { std::string Elf::SElfHeaderStr() {
std::string header = fmt::format("======= SELF HEADER =========\n", m_self->magic); std::string header = fmt::format("======= SELF HEADER =========\n", m_self.magic);
header += fmt::format("magic ..............: 0x{:X}\n", m_self->magic); header += fmt::format("magic ..............: 0x{:X}\n", m_self.magic);
header += fmt::format("version ............: {}\n", m_self->version); header += fmt::format("version ............: {}\n", m_self.version);
header += fmt::format("mode ...............: {:#04x}\n", m_self->mode); header += fmt::format("mode ...............: {:#04x}\n", m_self.mode);
header += fmt::format("endian .............: {}\n", m_self->endian); header += fmt::format("endian .............: {}\n", m_self.endian);
header += fmt::format("attributes .........: {:#04x}\n", m_self->attributes); header += fmt::format("attributes .........: {:#04x}\n", m_self.attributes);
header += fmt::format("category ...........: {:#04x}\n", m_self->category); header += fmt::format("category ...........: {:#04x}\n", m_self.category);
header += fmt::format("program_type........: {:#04x}\n", m_self->program_type); header += fmt::format("program_type........: {:#04x}\n", m_self.program_type);
header += fmt::format("padding1 ...........: {:#06x}\n", m_self->padding1); header += fmt::format("padding1 ...........: {:#06x}\n", m_self.padding1);
header += fmt::format("header size ........: {}\n", m_self->header_size); header += fmt::format("header size ........: {}\n", m_self.header_size);
header += fmt::format("meta size ..........: {}\n", m_self->meta_size); header += fmt::format("meta size ..........: {}\n", m_self.meta_size);
header += fmt::format("file size ..........: {}\n", m_self->file_size); header += fmt::format("file size ..........: {}\n", m_self.file_size);
header += fmt::format("padding2 ...........: {:#010x}\n", m_self->padding2); header += fmt::format("padding2 ...........: {:#010x}\n", m_self.padding2);
header += fmt::format("segment count ......: {}\n", m_self->segment_count); header += fmt::format("segment count ......: {}\n", m_self.segment_count);
header += fmt::format("unknown 1A .........: {:#06x}\n", m_self->unknown1A); header += fmt::format("unknown 1A .........: {:#06x}\n", m_self.unknown1A);
header += fmt::format("padding3 ...........: {:#010x}\n", m_self->padding3); header += fmt::format("padding3 ...........: {:#010x}\n", m_self.padding3);
return header; return header;
} }
std::string Elf::SELFSegHeader(u16 no) { std::string Elf::SELFSegHeader(u16 no) {
auto segment_header = m_self_segments[no]; const auto segment_header = m_self_segments[no];
std::string header = fmt::format("====== SEGMENT HEADER {} ========\n", no); std::string header = fmt::format("====== SEGMENT HEADER {} ========\n", no);
header += fmt::format("flags ............: {:#018x}\n", segment_header.flags); header += fmt::format("flags ............: {:#018x}\n", segment_header.flags);
header += fmt::format("file offset ......: {:#018x}\n", segment_header.file_offset); header += fmt::format("file offset ......: {:#018x}\n", segment_header.file_offset);
@ -320,65 +352,36 @@ std::string Elf::SELFSegHeader(u16 no) {
std::string Elf::ElfHeaderStr() { std::string Elf::ElfHeaderStr() {
std::string header = fmt::format("======= Elf header ===========\n"); std::string header = fmt::format("======= Elf header ===========\n");
header += fmt::format("ident ............: 0x"); header += fmt::format("ident ............: 0x");
for (auto i : m_elf_header->e_ident.magic) { for (auto i : m_elf_header.e_ident.magic) {
header += fmt::format("{:02X}", i); header += fmt::format("{:02X}", i);
} }
header += fmt::format("\n"); header += fmt::format("\n");
auto ident_class = magic_enum::enum_cast<ident_class_es>(m_elf_header->e_ident.ei_class); header += fmt::format("ident class.......: {}\n", getIdentClassName(m_elf_header.e_ident.ei_class));
if (ident_class.has_value()) { header += fmt::format("ident data .......: {}\n", getIdentEndianName(m_elf_header.e_ident.ei_data));
header += fmt::format("ident class.......: {}\n", magic_enum::enum_name(ident_class.value())); header += fmt::format("ident version.....: {}\n", getIdentVersionName(m_elf_header.e_ident.ei_version));
} header += fmt::format("ident osabi .....: {}\n", getIdentOsabiName(m_elf_header.e_ident.ei_osabi));
header += fmt::format("ident abiversion..: {}\n", getIdentAbiversionName(m_elf_header.e_ident.ei_abiversion));
auto ident_data = magic_enum::enum_cast<ident_endian_es>(m_elf_header->e_ident.ei_data);
if (ident_data.has_value()) {
header += fmt::format("ident data .......: {}\n", magic_enum::enum_name(ident_data.value()));
}
auto ident_version = magic_enum::enum_cast<ident_version_es>(m_elf_header->e_ident.ei_version);
if (ident_version.has_value()) {
header += fmt::format("ident version.....: {}\n", magic_enum::enum_name(ident_version.value()));
}
auto ident_osabi = magic_enum::enum_cast<ident_osabi_es>(m_elf_header->e_ident.ei_osabi);
if (ident_osabi.has_value()) {
header += fmt::format("ident osabi .....: {}\n", magic_enum::enum_name(ident_osabi.value()));
}
auto ident_abiversion = magic_enum::enum_cast<ident_abiversion_es>(m_elf_header->e_ident.ei_abiversion);
if (ident_abiversion.has_value()) {
header += fmt::format("ident abiversion..: {}\n", magic_enum::enum_name(ident_abiversion.value()));
}
header += fmt::format("ident UNK ........: 0x"); header += fmt::format("ident UNK ........: 0x");
for (auto i : m_elf_header->e_ident.pad) { for (auto i : m_elf_header.e_ident.pad) {
header += fmt::format("{:02X}", i); header += fmt::format("{:02X}", i);
} }
header += fmt::format("\n"); header += fmt::format("\n");
auto type = magic_enum::enum_cast<e_type_s>(m_elf_header->e_type); header += fmt::format("type ............: {}\n", static_cast<u32>(m_elf_header.e_type));
if (type.has_value()) { header += fmt::format("machine ..........: {}\n", static_cast<u32>(m_elf_header.e_machine));
header += fmt::format("type ............: {}\n", magic_enum::enum_name(type.value())); header += fmt::format("version ..........: {}\n", static_cast<u32>(m_elf_header.e_version));
} header += fmt::format("entry ............: {:#018x}\n", m_elf_header.e_entry);
header += fmt::format("phoff ............: {:#018x}\n", m_elf_header.e_phoff);
auto machine = magic_enum::enum_cast<e_machine_es>(m_elf_header->e_machine); header += fmt::format("shoff ............: {:#018x}\n", m_elf_header.e_shoff);
if (machine.has_value()) { header += fmt::format("flags ............: {:#010x}\n", m_elf_header.e_flags);
header += fmt::format("machine ..........: {}\n", magic_enum::enum_name(machine.value())); header += fmt::format("ehsize ...........: {}\n", m_elf_header.e_ehsize);
} header += fmt::format("phentsize ........: {}\n", m_elf_header.e_phentsize);
auto version = magic_enum::enum_cast<e_version_es>(m_elf_header->e_version); header += fmt::format("phnum ............: {}\n", m_elf_header.e_phnum);
if (version.has_value()) { header += fmt::format("shentsize ........: {}\n", m_elf_header.e_shentsize);
header += fmt::format("version ..........: {}\n", magic_enum::enum_name(version.value())); header += fmt::format("shnum ............: {}\n", m_elf_header.e_shnum);
} header += fmt::format("shstrndx .........: {}\n", m_elf_header.e_shstrndx);
header += fmt::format("entry ............: {:#018x}\n", m_elf_header->e_entry);
header += fmt::format("phoff ............: {:#018x}\n", m_elf_header->e_phoff);
header += fmt::format("shoff ............: {:#018x}\n", m_elf_header->e_shoff);
header += fmt::format("flags ............: {:#010x}\n", m_elf_header->e_flags);
header += fmt::format("ehsize ...........: {}\n", m_elf_header->e_ehsize);
header += fmt::format("phentsize ........: {}\n", m_elf_header->e_phentsize);
header += fmt::format("phnum ............: {}\n", m_elf_header->e_phnum);
header += fmt::format("shentsize ........: {}\n", m_elf_header->e_shentsize);
header += fmt::format("shnum ............: {}\n", m_elf_header->e_shnum);
header += fmt::format("shstrndx .........: {}\n", m_elf_header->e_shstrndx);
return header; return header;
} }
@ -418,45 +421,39 @@ std::string Elf::ElfPheaderFlagsStr(u32 flags) {
std::string Elf::ElfPHeaderStr(u16 no) { std::string Elf::ElfPHeaderStr(u16 no) {
std::string header = fmt::format("====== PROGRAM HEADER {} ========\n", no); std::string header = fmt::format("====== PROGRAM HEADER {} ========\n", no);
header += fmt::format("p_type ....: {}\n", ElfPheaderTypeStr((m_elf_phdr + no)->p_type)); header += fmt::format("p_type ....: {}\n", ElfPheaderTypeStr(m_elf_phdr[no].p_type));
header += fmt::format("p_flags ...: {:#010x}\n", static_cast<u32>(m_elf_phdr[no].p_flags));
auto flags = magic_enum::enum_cast<elf_program_flags>((m_elf_phdr + no)->p_flags); header += fmt::format("p_offset ..: {:#018x}\n", m_elf_phdr[no].p_offset);
if (flags.has_value()) { header += fmt::format("p_vaddr ...: {:#018x}\n", m_elf_phdr[no].p_vaddr);
header += fmt::format("p_flags ...: {}\n", magic_enum::enum_name(flags.value())); header += fmt::format("p_paddr ...: {:#018x}\n", m_elf_phdr[no].p_paddr);
} header += fmt::format("p_filesz ..: {:#018x}\n", m_elf_phdr[no].p_filesz);
// header += fmt::format("p_flags ...: {:#010x}\n", (m_elf_phdr + no)->p_flags); header += fmt::format("p_memsz ...: {:#018x}\n", m_elf_phdr[no].p_memsz);
header += fmt::format("p_offset ..: {:#018x}\n", (m_elf_phdr + no)->p_offset); header += fmt::format("p_align ...: {:#018x}\n", m_elf_phdr[no].p_align);
header += fmt::format("p_vaddr ...: {:#018x}\n", (m_elf_phdr + no)->p_vaddr);
header += fmt::format("p_paddr ...: {:#018x}\n", (m_elf_phdr + no)->p_paddr);
header += fmt::format("p_filesz ..: {:#018x}\n", (m_elf_phdr + no)->p_filesz);
header += fmt::format("p_memsz ...: {:#018x}\n", (m_elf_phdr + no)->p_memsz);
header += fmt::format("p_align ...: {:#018x}\n", (m_elf_phdr + no)->p_align);
return header; return header;
} }
void Elf::LoadSegment(u64 virtual_addr, u64 file_offset, u64 size) { void Elf::LoadSegment(u64 virtual_addr, u64 file_offset, u64 size) {
if (m_self != nullptr) { if (!is_self) {
for (uint16_t i = 0; i < m_self->segment_count; i++) { // It's elf file
const auto& seg = m_self_segments[i]; m_f.seek(file_offset, Common::FS::SeekMode::Set);
m_f.read(reinterpret_cast<void*>(static_cast<uintptr_t>(virtual_addr)), size);
return;
}
if (seg.IsBlocked()) { for (uint16_t i = 0; i < m_self.segment_count; i++) {
auto phdr_id = seg.GetId(); const auto& seg = m_self_segments[i];
const auto& phdr = m_elf_phdr[phdr_id];
if (file_offset >= phdr.p_offset && file_offset < phdr.p_offset + phdr.p_filesz) { if (seg.IsBlocked()) {
auto offset = file_offset - phdr.p_offset; auto phdr_id = seg.GetId();
m_f->Seek(offset + seg.file_offset, fsSeekMode::fsSeekSet); const auto& phdr = m_elf_phdr[phdr_id];
m_f->Read(reinterpret_cast<void*>(static_cast<uintptr_t>(virtual_addr)), size);
return; if (file_offset >= phdr.p_offset && file_offset < phdr.p_offset + phdr.p_filesz) {
} auto offset = file_offset - phdr.p_offset;
m_f.seek(offset + seg.file_offset, Common::FS::SeekMode::Set);
m_f.read(reinterpret_cast<void*>(static_cast<uintptr_t>(virtual_addr)), size);
return;
} }
} }
BREAKPOINT(); // hmm we didn't return something...
} else {
// it's elf file
m_f->Seek(file_offset, fsSeekMode::fsSeekSet);
m_f->Read(reinterpret_cast<void*>(static_cast<uintptr_t>(virtual_addr)), size);
} }
BREAKPOINT(); // Hmm we didn't return something...
} }
u64 Elf::GetElfEntry() { return m_elf_header->e_entry; }

View File

@ -1,6 +1,10 @@
#pragma once #pragma once
#include <string> #include <string>
#include <inttypes.h> #include <cinttypes>
#include <span>
#include <vector>
#include "../../../types.h" #include "../../../types.h"
#include "../../FsFile.h" #include "../../FsFile.h"
@ -188,7 +192,7 @@ typedef enum :u32 {
typedef enum : u08 { typedef enum : u08 {
ELF_CLASS_NONE =0x0, ELF_CLASS_NONE =0x0,
ELF_CLASS_32 =0x1, ELF_CLASS_32 =0x1,
ELF_CLASS_64 =0x2, ELF_CLASS_64 =0x2,
ELF_CLASS_NUM =0x3 ELF_CLASS_NUM =0x3
} ident_class_es; } ident_class_es;
@ -446,9 +450,8 @@ constexpr u32 R_X86_64_64 = 1; // Direct 64 bit
constexpr u32 R_X86_64_JUMP_SLOT = 7; // Create PLT entry constexpr u32 R_X86_64_JUMP_SLOT = 7; // Create PLT entry
constexpr u32 R_X86_64_RELATIVE = 8; // Adjust by program base constexpr u32 R_X86_64_RELATIVE = 8; // Adjust by program base
class Elf class Elf {
{ public:
public:
Elf() = default; Elf() = default;
virtual ~Elf(); virtual ~Elf();
@ -456,29 +459,46 @@ public:
bool isSelfFile() const; bool isSelfFile() const;
bool isElfFile() const; bool isElfFile() const;
void DebugDump(); void DebugDump();
[[nodiscard]] const self_header* GetSElfHeader() const { return m_self; }
[[nodiscard]] const elf_header* GetElfHeader() const { return m_elf_header; } [[nodiscard]] self_header GetSElfHeader() const {
[[nodiscard]] const elf_program_header* GetProgramHeader() const { return m_elf_phdr; } return m_self;
[[nodiscard]] const self_segment_header* GetSegmentHeader() const { return m_self_segments; } }
[[nodiscard]] elf_header GetElfHeader() const {
return m_elf_header;
}
[[nodiscard]] std::span<const elf_program_header> GetProgramHeader() const {
return m_elf_phdr;
}
[[nodiscard]] std::span<const self_segment_header> GetSegmentHeader() const {
return m_self_segments;
}
[[nodiscard]] u64 GetElfEntry() const {
return m_elf_header.e_entry;
}
std::string SElfHeaderStr(); std::string SElfHeaderStr();
std::string SELFSegHeader(u16 no); std::string SELFSegHeader(u16 no);
std::string ElfHeaderStr(); std::string ElfHeaderStr();
std::string ElfPHeaderStr(u16 no); std::string ElfPHeaderStr(u16 no);
std::string ElfPheaderTypeStr(u32 type); std::string ElfPheaderTypeStr(u32 type);
std::string ElfPheaderFlagsStr(u32 flags); std::string ElfPheaderFlagsStr(u32 flags);
void LoadSegment(u64 virtual_addr, u64 file_offset, u64 size); void LoadSegment(u64 virtual_addr, u64 file_offset, u64 size);
u64 GetElfEntry();
private:
private:
void Reset(); void Reset();
FsFile* m_f = nullptr; private:
self_header* m_self = nullptr; Common::FS::File m_f{};
self_segment_header* m_self_segments = nullptr; bool is_self{};
elf_header* m_elf_header = nullptr; self_header m_self{};
elf_program_header* m_elf_phdr = nullptr; std::vector<self_segment_header> m_self_segments;
elf_section_header* m_elf_shdr = nullptr; elf_header m_elf_header{};
elf_program_id_header* m_self_id_header = nullptr; std::vector<elf_program_header> m_elf_phdr;
std::vector<elf_section_header> m_elf_shdr;
elf_program_id_header m_self_id_header{};
}; };

View File

@ -30,8 +30,8 @@ void ElfViewer::display(bool enabled)
if (ImGui::TreeNode("Self Segment Header")) if (ImGui::TreeNode("Self Segment Header"))
{ {
const auto* self = elf->GetSElfHeader(); const auto self = elf->GetSElfHeader();
for (u16 i = 0; i < self->segment_count; i++) for (u16 i = 0; i < self.segment_count; i++)
{ {
if (ImGui::TreeNodeEx((void*)(intptr_t)i, ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen, "%d", i)) if (ImGui::TreeNodeEx((void*)(intptr_t)i, ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen, "%d", i))
{ {
@ -47,7 +47,7 @@ void ElfViewer::display(bool enabled)
} }
if (ImGui::TreeNode("Elf")) if (ImGui::TreeNode("Elf"))
{ {
const auto* elf_header = elf->GetElfHeader(); const auto elf_header = elf->GetElfHeader();
if (ImGui::TreeNodeEx("Elf Header", ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen, "Elf Header")) if (ImGui::TreeNodeEx("Elf Header", ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen, "Elf Header"))
{ {
if (ImGui::IsItemClicked()) if (ImGui::IsItemClicked())
@ -55,10 +55,10 @@ void ElfViewer::display(bool enabled)
} }
if (ImGui::TreeNode("Elf Program Headers")) if (ImGui::TreeNode("Elf Program Headers"))
{ {
for (u16 i = 0; i < elf_header->e_phnum; i++) const auto pheader = elf->GetProgramHeader();
for (u16 i = 0; i < elf_header.e_phnum; i++)
{ {
const auto* pheader = elf->GetProgramHeader(); std::string ProgramInfo = elf->ElfPheaderFlagsStr(pheader[i].p_flags) + " " + elf->ElfPheaderTypeStr(pheader[i].p_type);
std::string ProgramInfo = elf->ElfPheaderFlagsStr((pheader + i)->p_flags) + " " + elf->ElfPheaderTypeStr((pheader + i)->p_type);
if (ImGui::TreeNodeEx((void*)(intptr_t)i,ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen, "%d - %s", i,ProgramInfo.c_str())) if (ImGui::TreeNodeEx((void*)(intptr_t)i,ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen, "%d - %s", i,ProgramInfo.c_str()))
{ {
if (ImGui::IsItemClicked()) if (ImGui::IsItemClicked())
@ -67,7 +67,7 @@ void ElfViewer::display(bool enabled)
} }
ImGui::TreePop(); ImGui::TreePop();
} }
if (elf_header->e_shnum != 0) if (elf_header.e_shnum != 0)
{ {
if (ImGui::TreeNode("Elf Section Headers")) if (ImGui::TreeNode("Elf Section Headers"))
{ {
@ -82,18 +82,18 @@ void ElfViewer::display(bool enabled)
ImGui::BeginChild("Table View", ImVec2(0, -ImGui::GetFrameHeightWithSpacing())); // Leave room for 1 line below us ImGui::BeginChild("Table View", ImVec2(0, -ImGui::GetFrameHeightWithSpacing())); // Leave room for 1 line below us
if (selected == SELF_HEADER) { if (selected == SELF_HEADER) {
ImGui::TextWrapped(elf->SElfHeaderStr().c_str()); ImGui::TextWrapped("%s", elf->SElfHeaderStr().c_str());
} }
if (selected >= 100 && selected < 200) if (selected >= 100 && selected < 200)
{ {
ImGui::TextWrapped(elf->SELFSegHeader(selected-100).c_str()); ImGui::TextWrapped("%s", elf->SELFSegHeader(selected-100).c_str());
} }
if (selected == ELF_HEADER) { if (selected == ELF_HEADER) {
ImGui::TextWrapped(elf->ElfHeaderStr().c_str()); ImGui::TextWrapped("%s", elf->ElfHeaderStr().c_str());
} }
if (selected >= 200 && selected < 300) if (selected >= 200 && selected < 300)
{ {
ImGui::TextWrapped(elf->ElfPHeaderStr(selected - 200).c_str()); ImGui::TextWrapped("%s", elf->ElfPHeaderStr(selected - 200).c_str());
} }
ImGui::EndChild(); ImGui::EndChild();
ImGui::End(); ImGui::End();