From ca564b928ce5203f83978b2a0ad2279404e12956 Mon Sep 17 00:00:00 2001 From: GPUCode Date: Thu, 26 Oct 2023 22:55:13 +0300 Subject: [PATCH 1/7] core: Rework elf loader --- src/Core/FsFile.cpp | 173 +++++------ src/Core/FsFile.h | 121 +++++--- src/Core/PS4/Linker.cpp | 54 ++-- src/Core/PS4/Linker.h | 14 +- src/Core/PS4/Loader/Elf.cpp | 563 ++++++++++++++++++------------------ src/Core/PS4/Loader/Elf.h | 66 +++-- src/GUI/ElfViewer.cpp | 26 +- 7 files changed, 514 insertions(+), 503 deletions(-) diff --git a/src/Core/FsFile.cpp b/src/Core/FsFile.cpp index 7f23ad17..3e73c9af 100644 --- a/src/Core/FsFile.cpp +++ b/src/Core/FsFile.cpp @@ -1,122 +1,93 @@ #include "FsFile.h" -FsFile::FsFile() -{ - m_file = nullptr; +namespace Common::FS { + +File::File() = default; + +File::File(const std::string& path, OpenMode mode) { + open(path, mode); } -FsFile::FsFile(const std::string& path, fsOpenMode mode) -{ - Open(path, mode); +File::~File() { + close(); } -bool FsFile::Open(const std::string& path, fsOpenMode mode) -{ - Close(); - #ifdef _WIN64 - fopen_s(&m_file, path.c_str(), getOpenMode(mode)); - #else - m_file = std::fopen(path.c_str(), getOpenMode(mode)); - #endif - return IsOpen(); +bool File::open(const std::string& path, OpenMode mode) { + close(); +#ifdef _WIN64 + fopen_s(&m_file, path.c_str(), getOpenMode(mode)); +#else + m_file = std::fopen(path.c_str(), getOpenMode(mode)); +#endif + return isOpen(); } -bool FsFile::Close() -{ - if (!IsOpen() || std::fclose(m_file) != 0) { - m_file = nullptr; - return false; - } +bool File::close() { + if (!isOpen() || std::fclose(m_file) != 0) [[unlikely]] { + m_file = nullptr; + return false; + } - m_file = nullptr; - return true; + m_file = nullptr; + return true; } -FsFile::~FsFile() -{ - Close(); +bool File::write(std::span data) { + return isOpen() && std::fwrite(data.data(), 1, data.size(), m_file) == data.size(); } -bool FsFile::Write(const void* src, u64 size) -{ - if (!IsOpen() || std::fwrite(src, 1, size, m_file) != size) { - return false; - } - return true; +bool File::read(void* data, u64 size) const { + return isOpen() && std::fread(data, 1, size, m_file) == size; } -bool FsFile::Read(void* dst, u64 size) -{ - if (!IsOpen() || std::fread(dst, 1, size, m_file) != size) { - return false; - } - return true; +bool File::seek(s64 offset, SeekMode mode) { +#ifdef _WIN64 + if (!isOpen() || _fseeki64(m_file, offset, getSeekMode(mode)) != 0) { + return false; + } +#else + if (!isOpen() || fseeko64(m_file, offset, getSeekMode(mode)) != 0) { + return false; + } +#endif + return true; } -u32 FsFile::ReadBytes(void* dst, u64 size) -{ - return std::fread(dst, 1, size, m_file); +u64 File::tell() const { + if (isOpen()) [[likely]] { +#ifdef _WIN64 + return _ftelli64(m_file); +#else + return ftello64(m_file); +#endif + } + + return -1; } -bool FsFile::Seek(s64 offset, fsSeekMode mode) -{ - #ifdef _WIN64 - if (!IsOpen() || _fseeki64(m_file, offset, getSeekMode(mode)) != 0) { - return false; - } - #else - if (!IsOpen() || fseeko64(m_file, offset, getSeekMode(mode)) != 0) { - return false; - } - #endif - return true; -} - -u64 FsFile::Tell() const -{ - if (IsOpen()) { - #ifdef _WIN64 - return _ftelli64(m_file); - #else - return ftello64(m_file); - #endif - } - 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; +u64 File::getFileSize() { +#ifdef _WIN64 + const u64 pos = _ftelli64(m_file); + if (_fseeki64(m_file, 0, SEEK_END) != 0) { + return 0; + } + + const u64 size = _ftelli64(m_file); + if (_fseeki64(m_file, pos, SEEK_SET) != 0) { + return 0; + } +#else + const u64 pos = ftello64(m_file); + if (fseeko64(m_file, 0, SEEK_END) != 0) { + return 0; + } + + const u64 size = ftello64(m_file); + if (fseeko64(m_file, pos, SEEK_SET) != 0) { + return 0; + } +#endif + return size; } +} // namespace Common::FS diff --git a/src/Core/FsFile.h b/src/Core/FsFile.h index 8bc019da..a00d00dc 100644 --- a/src/Core/FsFile.h +++ b/src/Core/FsFile.h @@ -1,62 +1,87 @@ #pragma once + +#include #include #include +#include +#include + #include "../types.h" -enum fsOpenMode -{ - fsRead = 0x1, - fsWrite = 0x2, - fsReadWrite = fsRead | fsWrite +namespace Common::FS { + +enum class OpenMode : u32 { + Read = 0x1, + Write = 0x2, + ReadWrite = Read | Write }; -enum fsSeekMode -{ - fsSeekSet, - fsSeekCur, - fsSeekEnd, +enum class SeekMode : u32 { + Set, + Cur, + End, }; -class FsFile -{ - std::FILE* m_file; -public: - FsFile(); - 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(); +class File { + public: + File(); + explicit File(const std::string& path, OpenMode mode = OpenMode::Read); + ~File(); - const char* getOpenMode(fsOpenMode mode) - { - switch (mode) { - case fsRead: return "rb"; - case fsWrite: return "wb"; - case fsReadWrite: return "r+b"; - } + bool open(const std::string& path, OpenMode mode = OpenMode::Read); + bool close(); + bool read(void* data, u64 size) const; + bool write(std::span data); + bool seek(s64 offset, SeekMode mode); + u64 getFileSize(); + u64 tell() const; - return "r"; - } + template + bool read(T& data) const { + return read(&data, sizeof(T)); + } - const int getSeekMode(fsSeekMode mode) - { - switch (mode) { - case fsSeekSet: return SEEK_SET; - case fsSeekCur: return SEEK_CUR; - case fsSeekEnd: return SEEK_END; - } + template + bool read(std::vector& data) const { + return read(data.data(), data.size() * sizeof(T)); + } - return SEEK_SET; - } - std::FILE* fileDescr() - { - return m_file; - } + bool isOpen() const { + return m_file != nullptr; + } + + 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 diff --git a/src/Core/PS4/Linker.cpp b/src/Core/PS4/Linker.cpp index 0748fdd0..e795b906 100644 --- a/src/Core/PS4/Linker.cpp +++ b/src/Core/PS4/Linker.cpp @@ -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 phdr) { 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)) { - auto phdrh = phdr + i; - u64 last_addr = phdr[i].p_vaddr + get_aligned_size(phdrh); + u64 last_addr = phdr[i].p_vaddr + get_aligned_size(phdr[i]); if (last_addr > base_size) { base_size = last_addr; @@ -73,10 +72,9 @@ Module* Linker::LoadModule(const std::string& elf_name) std::scoped_lock lock{m_mutex}; auto* m = new Module; m->linker = this; - m->elf = new Elf; - m->elf->Open(elf_name);//load elf + m->elf.Open(elf_name); - if (m->elf->isElfFile()) + if (m->elf.isElfFile()) { LoadModuleToMemory(m); LoadDynamicInfo(m); @@ -107,8 +105,8 @@ Module* Linker::FindModule(/*u32 id*/) void Linker::LoadModuleToMemory(Module* m) { //get elf header, program header - auto* elf_header = m->elf->GetElfHeader(); - auto* elf_pheader = m->elf->GetProgramHeader(); + const auto elf_header = m->elf.GetElfHeader(); + const auto elf_pheader = m->elf.GetProgramHeader(); u64 base_size = calculate_base_size(elf_header, elf_pheader); m->aligned_base_size = (base_size & ~(static_cast(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, "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_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_file_size = elf_pheader[i].p_filesz; - u64 segment_memory_size = get_aligned_size(elf_pheader + i); - 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)); + u64 segment_memory_size = get_aligned_size(elf_pheader[i]); + 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, "segment_addr ..........: {:#018x}\n", segment_addr); 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_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 { - 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; case PT_DYNAMIC: if (elf_pheader[i].p_filesz != 0) { void* dynamic = new u08[elf_pheader[i].p_filesz]; - m->elf->LoadSegment(reinterpret_cast(dynamic), elf_pheader[i].p_offset, elf_pheader[i].p_filesz); + m->elf.LoadSegment(reinterpret_cast(dynamic), elf_pheader[i].p_offset, elf_pheader[i].p_filesz); m->m_dynamic = dynamic; } 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; case PT_SCE_DYNLIBDATA: if (elf_pheader[i].p_filesz != 0) { void* dynamic = new u08[elf_pheader[i].p_filesz]; - m->elf->LoadSegment(reinterpret_cast(dynamic), elf_pheader[i].p_offset, elf_pheader[i].p_filesz); + m->elf.LoadSegment(reinterpret_cast(dynamic), elf_pheader[i].p_offset, elf_pheader[i].p_filesz); m->m_dynamic_data = dynamic; } 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; 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(m->elf->GetElfEntry() + m->base_virtual_addr); - ZyanU64 runtime_address = m->elf->GetElfEntry() + m->base_virtual_addr; + auto* rt1 = reinterpret_cast(m->elf.GetElfEntry() + m->base_virtual_addr); + ZyanU64 runtime_address = m->elf.GetElfEntry() + m->base_virtual_addr; // Loop over the instructions in our buffer. ZyanUSize offset = 0; @@ -681,6 +679,6 @@ void Linker::Execute() p.argc = 1; 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); -} \ No newline at end of file +} diff --git a/src/Core/PS4/Linker.h b/src/Core/PS4/Linker.h index e777d61b..596a9af7 100644 --- a/src/Core/PS4/Linker.h +++ b/src/Core/PS4/Linker.h @@ -14,17 +14,17 @@ struct EntryParams { 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 { - Elf* elf = nullptr; + Elf elf; 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_data = nullptr; + void* m_dynamic = nullptr; + void* m_dynamic_data = nullptr; DynamicModuleInfo* dynamic_info = nullptr; SymbolsResolver* export_sym = nullptr; @@ -131,4 +131,4 @@ public: std::vector m_modules; SymbolsResolver* m_HLEsymbols = nullptr; std::mutex m_mutex; -}; \ No newline at end of file +}; diff --git a/src/Core/PS4/Loader/Elf.cpp b/src/Core/PS4/Loader/Elf.cpp index d9112707..a9b7f17e 100644 --- a/src/Core/PS4/Loader/Elf.cpp +++ b/src/Core/PS4/Loader/Elf.cpp @@ -1,139 +1,188 @@ -#include "Elf.h" - -#include -#include +#include #include #include #include +#include +#include -#include +#include +#include "Elf.h" -#include "spdlog/sinks/basic_file_sink.h" -#include "spdlog/spdlog.h" - -constexpr bool debug_elf = true; - -template <> -struct magic_enum::customize::enum_range { - static constexpr int min = 0xfe00; - static constexpr int max = 0xfe18; - // (max - min) must be less than UINT16_MAX. -}; - -Elf::~Elf() { Reset(); } - -static self_header* load_self(FsFile& f) { - // read self header - auto* self = new self_header; - f.Read(self, sizeof(self_header)); - return self; -} - -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; +static std::string_view getProgramTypeName(program_type_es type) { + switch (type) { + case PT_FAKE: + return "PT_FAKE"; + case PT_NPDRM_EXEC: + return "PT_NPDRM_EXEC"; + case PT_NPDRM_DYNLIB: + return "PT_NPDRM_DYNLIB"; + case PT_SYSTEM_EXEC: + return "PT_SYSTEM_EXEC"; + case PT_SYSTEM_DYNLIB: + return "PT_SYSTEM_DYNLIB"; + case PT_HOST_KERNEL: + return "PT_HOST_KERNEL"; + case PT_SECURE_MODULE: + return "PT_SECURE_MODULE"; + case PT_SECURE_KERNEL: + return "PT_SECURE_KERNEL"; + default: + return "INVALID"; } - - 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 -{ - if (m_f != nullptr) { - m_f->Close(); - delete m_f; +static std::string_view getIdentClassName(ident_class_es elf_class) { + switch (elf_class) { + case ELF_CLASS_NONE: + return "ELF_CLASS_NONE"; + 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; - m_self_segments = nullptr; - m_elf_header = nullptr; - m_elf_phdr = nullptr; - m_elf_shdr = nullptr; - m_self_id_header = nullptr; +static std::string_view getIdentEndianName(ident_endian_es endian) { + switch (endian) { + case ELF_DATA_NONE: + return "ELF_DATA_NONE"; + case ELF_DATA_2LSB: + 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) { - Reset(); // reset all variables + Reset(); - m_f = new FsFile; - m_f->Open(file_name, fsOpenMode::fsRead); + m_f.open(file_name, Common::FS::OpenMode::Read); + m_f.read(m_self); - m_self = load_self(*m_f); - - 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 + if (is_self = isSelfFile(); !is_self) { + m_f.seek(0, Common::FS::SeekMode::Set); } 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 - - m_elf_header = load_elf_header(*m_f); - + const u64 elf_header_pos = m_f.tell(); + m_f.read(m_elf_header); if (!isElfFile()) { - delete m_elf_header; - m_elf_header = nullptr; + return; } - if (m_elf_header != nullptr) { - m_elf_phdr = load_program_header(*m_f, elfheader_pos + m_elf_header->e_phoff, m_elf_header->e_phnum); - m_elf_shdr = load_section_header(*m_f, elfheader_pos + m_elf_header->e_shoff, m_elf_header->e_shnum); - } - if (isself && m_elf_header != nullptr) { + const auto load_headers = [this](std::vector& out, u64 offset, u16 num) { + if (!num) { + return; + } + + 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; 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 += 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_phnum * m_elf_header.e_phentsize; + header_size += m_elf_header.e_shnum * m_elf_header.e_shentsize; header_size += 15; - header_size &= ~15; // align + header_size &= ~15; // Align - if (m_elf_header->e_ehsize - header_size >= sizeof(elf_program_id_header)) { - m_f->Seek(header_size, fsSeekMode::fsSeekSet); - - m_self_id_header = new elf_program_id_header; - m_f->Read(m_self_id_header, sizeof(elf_program_id_header)); + if (m_elf_header.e_ehsize - header_size >= sizeof(elf_program_id_header)) { + m_f.seek(header_size, Common::FS::SeekMode::Set); + m_f.read(m_self_id_header); } } @@ -141,26 +190,19 @@ void Elf::Open(const std::string& file_name) { } 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; } - if (m_self == nullptr) { - return false; // if we can't load self header return false - } - - 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); + if (m_self.version != 0x00 || m_self.mode != 0x01 || m_self.endian != 0x01 || m_self.attributes != 0x12) [[unlikely]] { + fmt::print("Unknown SELF file\n"); return false; } - if (m_self->version != 0x00 || m_self->mode != 0x01 || m_self->endian != 0x01 || m_self->attributes != 0x12) { - printf("Unknown SELF file\n"); - return false; - } - - if (m_self->category != 0x01 || m_self->program_type != 0x01) { - printf("Unknown SELF file\n"); + if (m_self.category != 0x01 || m_self.program_type != 0x01) [[unlikely]] { + fmt::print("Unknown SELF file\n"); return false; } @@ -168,68 +210,60 @@ bool Elf::isSelfFile() 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(m_elf_header.e_ident.ei_class)); 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(m_elf_header.e_ident.ei_data)); return false; } - 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) { - 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); + if (m_elf_header.e_ident.ei_version != ELF_VERSION_CURRENT) { + fmt::print("ERROR:e_ident[EI_VERSION] expected 0x01 is ({:#x})\n", static_cast(m_elf_header.e_ident.ei_version)); return false; } - if (m_elf_header->e_ident.ei_data != ELF_DATA_2LSB) { - printf("ERROR:e_ident[EI_DATA] expected 0x01 is (0x%x)\n", m_elf_header->e_ident.ei_data); + if (m_elf_header.e_ident.ei_osabi != ELF_OSABI_FREEBSD) { + fmt::print("ERROR:e_ident[EI_OSABI] expected 0x09 is ({:#x})\n", static_cast(m_elf_header.e_ident.ei_osabi)); return false; } - if (m_elf_header->e_ident.ei_version != ELF_VERSION_CURRENT) { - printf("ERROR:e_ident[EI_VERSION] expected 0x01 is (0x%x)\n", m_elf_header->e_ident.ei_version); + if (m_elf_header.e_ident.ei_abiversion != ELF_ABI_VERSION_AMDGPU_HSA_V2) { + fmt::print("ERROR:e_ident[EI_ABIVERSION] expected 0x00 is ({:#x})\n", static_cast(m_elf_header.e_ident.ei_abiversion)); return false; } - if (m_elf_header->e_ident.ei_osabi != ELF_OSABI_FREEBSD) { - printf("ERROR:e_ident[EI_OSABI] expected 0x09 is (0x%x)\n", m_elf_header->e_ident.ei_osabi); + 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) { + fmt::print("ERROR:e_type expected 0xFE10 OR 0xFE18 OR 0xfe00 is ({:#x})\n", static_cast(m_elf_header.e_type)); return false; } - if (m_elf_header->e_ident.ei_abiversion != ELF_ABI_VERSION_AMDGPU_HSA_V2) { - printf("ERROR:e_ident[EI_ABIVERSION] expected 0x00 is (0x%x)\n", m_elf_header->e_ident.ei_abiversion); + if (m_elf_header.e_machine != EM_X86_64) { + fmt::print("ERROR:e_machine expected 0x3E is ({:#x})\n", static_cast(m_elf_header.e_machine)); 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) { - printf("ERROR:e_type expected 0xFE10 OR 0xFE18 OR 0xfe00 is (%04x)\n", m_elf_header->e_type); + if (m_elf_header.e_version != EV_CURRENT) { + fmt::print("ERROR:m_elf_header.e_version expected 0x01 is ({:#x})\n", static_cast(m_elf_header.e_version)); return false; } - if (m_elf_header->e_machine != EM_X86_64) { - printf("ERROR:e_machine expected 0x3E is (%04x)\n", m_elf_header->e_machine); + if (m_elf_header.e_phentsize != sizeof(elf_program_header)) { + fmt::print("ERROR:e_phentsize ({}) != sizeof(elf_program_header)\n", static_cast(m_elf_header.e_phentsize)); return false; } - if (m_elf_header->e_version != EV_CURRENT) { - printf("ERROR:m_elf_header->e_version expected 0x01 is (0x%x)\n", m_elf_header->e_version); - 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 + 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; } @@ -237,10 +271,10 @@ bool Elf::isElfFile() const { } 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("\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("\n"); @@ -248,67 +282,65 @@ void Elf::DebugDump() { spdlog::info(ElfHeaderStr()); - if (m_elf_header->e_phentsize > 0) { + if (m_elf_header.e_phentsize > 0) { 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)); } } - if (m_elf_header->e_shentsize > 0) { + if (m_elf_header.e_shentsize > 0) { 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("sh_name ........: {}\n", (m_elf_shdr + i)->sh_name); - 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_addr ........: {:#018x}\n", (m_elf_shdr + i)->sh_addr); - 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_link ........: {:#010x}\n", (m_elf_shdr + i)->sh_link); - 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_entsize .....: {:#018x}\n", (m_elf_shdr + i)->sh_entsize); + 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_flags .......: {:#018x}\n", m_elf_shdr[i].sh_flags); + 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_size ........: {:#018x}\n", m_elf_shdr[i].sh_size); + 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_addralign ...: {:#018x}\n", m_elf_shdr[i].sh_addralign); + 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("auth id ............: {:#018x}\n", m_self_id_header->authid); - auto program_type = magic_enum::enum_cast(m_self_id_header->program_type); - if (program_type.has_value()) { - spdlog::info("program type .......: {}\n", magic_enum::enum_name(program_type.value())); - } 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); + spdlog::info("auth id ............: {:#018x}\n", m_self_id_header.authid); + spdlog::info("program type .......: {}\n", getProgramTypeName(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; - 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); } } std::string Elf::SElfHeaderStr() { - std::string header = fmt::format("======= SELF HEADER =========\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("mode ...............: {:#04x}\n", m_self->mode); - header += fmt::format("endian .............: {}\n", m_self->endian); - header += fmt::format("attributes .........: {:#04x}\n", m_self->attributes); - header += fmt::format("category ...........: {:#04x}\n", m_self->category); - header += fmt::format("program_type........: {:#04x}\n", m_self->program_type); - header += fmt::format("padding1 ...........: {:#06x}\n", m_self->padding1); - header += fmt::format("header size ........: {}\n", m_self->header_size); - header += fmt::format("meta size ..........: {}\n", m_self->meta_size); - header += fmt::format("file size ..........: {}\n", m_self->file_size); - header += fmt::format("padding2 ...........: {:#010x}\n", m_self->padding2); - header += fmt::format("segment count ......: {}\n", m_self->segment_count); - header += fmt::format("unknown 1A .........: {:#06x}\n", m_self->unknown1A); - header += fmt::format("padding3 ...........: {:#010x}\n", m_self->padding3); + std::string header = fmt::format("======= SELF HEADER =========\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("mode ...............: {:#04x}\n", m_self.mode); + header += fmt::format("endian .............: {}\n", m_self.endian); + header += fmt::format("attributes .........: {:#04x}\n", m_self.attributes); + header += fmt::format("category ...........: {:#04x}\n", m_self.category); + header += fmt::format("program_type........: {:#04x}\n", m_self.program_type); + header += fmt::format("padding1 ...........: {:#06x}\n", m_self.padding1); + header += fmt::format("header size ........: {}\n", m_self.header_size); + header += fmt::format("meta size ..........: {}\n", m_self.meta_size); + header += fmt::format("file size ..........: {}\n", m_self.file_size); + header += fmt::format("padding2 ...........: {:#010x}\n", m_self.padding2); + header += fmt::format("segment count ......: {}\n", m_self.segment_count); + header += fmt::format("unknown 1A .........: {:#06x}\n", m_self.unknown1A); + header += fmt::format("padding3 ...........: {:#010x}\n", m_self.padding3); return header; } 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); header += fmt::format("flags ............: {:#018x}\n", segment_header.flags); 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 header = fmt::format("======= Elf header ===========\n"); 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("\n"); - auto ident_class = magic_enum::enum_cast(m_elf_header->e_ident.ei_class); - if (ident_class.has_value()) { - header += fmt::format("ident class.......: {}\n", magic_enum::enum_name(ident_class.value())); - } - - auto ident_data = magic_enum::enum_cast(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(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(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(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 class.......: {}\n", getIdentClassName(m_elf_header.e_ident.ei_class)); + header += fmt::format("ident data .......: {}\n", getIdentEndianName(m_elf_header.e_ident.ei_data)); + 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)); 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("\n"); - auto type = magic_enum::enum_cast(m_elf_header->e_type); - if (type.has_value()) { - header += fmt::format("type ............: {}\n", magic_enum::enum_name(type.value())); - } - - auto machine = magic_enum::enum_cast(m_elf_header->e_machine); - if (machine.has_value()) { - header += fmt::format("machine ..........: {}\n", magic_enum::enum_name(machine.value())); - } - auto version = magic_enum::enum_cast(m_elf_header->e_version); - if (version.has_value()) { - header += fmt::format("version ..........: {}\n", magic_enum::enum_name(version.value())); - } - 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); + header += fmt::format("type ............: {}\n", static_cast(m_elf_header.e_type)); + header += fmt::format("machine ..........: {}\n", static_cast(m_elf_header.e_machine)); + header += fmt::format("version ..........: {}\n", static_cast(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); + 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; } @@ -418,45 +421,39 @@ std::string Elf::ElfPheaderFlagsStr(u32 flags) { std::string Elf::ElfPHeaderStr(u16 no) { std::string header = fmt::format("====== PROGRAM HEADER {} ========\n", no); - header += fmt::format("p_type ....: {}\n", ElfPheaderTypeStr((m_elf_phdr + no)->p_type)); - - auto flags = magic_enum::enum_cast((m_elf_phdr + no)->p_flags); - if (flags.has_value()) { - header += fmt::format("p_flags ...: {}\n", magic_enum::enum_name(flags.value())); - } - // header += fmt::format("p_flags ...: {:#010x}\n", (m_elf_phdr + no)->p_flags); - header += fmt::format("p_offset ..: {:#018x}\n", (m_elf_phdr + no)->p_offset); - 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); + header += fmt::format("p_type ....: {}\n", ElfPheaderTypeStr(m_elf_phdr[no].p_type)); + header += fmt::format("p_flags ...: {:#010x}\n", static_cast(m_elf_phdr[no].p_flags)); + header += fmt::format("p_offset ..: {:#018x}\n", m_elf_phdr[no].p_offset); + 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; } void Elf::LoadSegment(u64 virtual_addr, u64 file_offset, u64 size) { - if (m_self != nullptr) { - for (uint16_t i = 0; i < m_self->segment_count; i++) { - const auto& seg = m_self_segments[i]; + if (!is_self) { + // It's elf file + m_f.seek(file_offset, Common::FS::SeekMode::Set); + m_f.read(reinterpret_cast(static_cast(virtual_addr)), size); + return; + } - if (seg.IsBlocked()) { - auto phdr_id = seg.GetId(); - const auto& phdr = m_elf_phdr[phdr_id]; + for (uint16_t i = 0; i < m_self.segment_count; i++) { + const auto& seg = m_self_segments[i]; - 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, fsSeekMode::fsSeekSet); - m_f->Read(reinterpret_cast(static_cast(virtual_addr)), size); - return; - } + if (seg.IsBlocked()) { + auto phdr_id = seg.GetId(); + const auto& phdr = m_elf_phdr[phdr_id]; + + 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(static_cast(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(static_cast(virtual_addr)), size); } + BREAKPOINT(); // Hmm we didn't return something... } - -u64 Elf::GetElfEntry() { return m_elf_header->e_entry; } diff --git a/src/Core/PS4/Loader/Elf.h b/src/Core/PS4/Loader/Elf.h index b04625f0..45bf3156 100644 --- a/src/Core/PS4/Loader/Elf.h +++ b/src/Core/PS4/Loader/Elf.h @@ -1,6 +1,10 @@ #pragma once + #include -#include +#include +#include +#include + #include "../../../types.h" #include "../../FsFile.h" @@ -54,7 +58,7 @@ struct self_segment_header u64 flags; u64 file_offset; u64 file_size; - u64 memory_size; + u64 memory_size; }; @@ -188,7 +192,7 @@ typedef enum :u32 { typedef enum : u08 { ELF_CLASS_NONE =0x0, ELF_CLASS_32 =0x1, - ELF_CLASS_64 =0x2, + ELF_CLASS_64 =0x2, ELF_CLASS_NUM =0x3 } ident_class_es; @@ -302,7 +306,7 @@ typedef enum : u32 { PF_READ_WRITE_EXEC = 0x7 } elf_program_flags; -struct elf_program_header +struct elf_program_header { elf_program_type p_type; /* Type of segment */ elf_program_flags p_flags; /* Segment attributes */ @@ -386,7 +390,7 @@ constexpr s64 DT_SCE_SYMTAB = 0x61000039; constexpr s64 DT_SCE_SYMTABSZ = 0x6100003f; -struct elf_dynamic +struct elf_dynamic { s64 d_tag; union @@ -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_RELATIVE = 8; // Adjust by program base -class Elf -{ -public: +class Elf { + public: Elf() = default; virtual ~Elf(); @@ -456,29 +459,46 @@ public: bool isSelfFile() const; bool isElfFile() const; void DebugDump(); - [[nodiscard]] const self_header* GetSElfHeader() const { return m_self; } - [[nodiscard]] const elf_header* GetElfHeader() const { return m_elf_header; } - [[nodiscard]] const elf_program_header* GetProgramHeader() const { return m_elf_phdr; } - [[nodiscard]] const self_segment_header* GetSegmentHeader() const { return m_self_segments; } + + [[nodiscard]] self_header GetSElfHeader() const { + return m_self; + } + + [[nodiscard]] elf_header GetElfHeader() const { + return m_elf_header; + } + + [[nodiscard]] std::span GetProgramHeader() const { + return m_elf_phdr; + } + + [[nodiscard]] std::span GetSegmentHeader() const { + return m_self_segments; + } + + [[nodiscard]] u64 GetElfEntry() const { + return m_elf_header.e_entry; + } + std::string SElfHeaderStr(); std::string SELFSegHeader(u16 no); std::string ElfHeaderStr(); std::string ElfPHeaderStr(u16 no); std::string ElfPheaderTypeStr(u32 type); std::string ElfPheaderFlagsStr(u32 flags); + void LoadSegment(u64 virtual_addr, u64 file_offset, u64 size); - u64 GetElfEntry(); - -private: + private: void Reset(); - FsFile* m_f = nullptr; - self_header* m_self = nullptr; - self_segment_header* m_self_segments = nullptr; - elf_header* m_elf_header = nullptr; - elf_program_header* m_elf_phdr = nullptr; - elf_section_header* m_elf_shdr = nullptr; - elf_program_id_header* m_self_id_header = nullptr; + private: + Common::FS::File m_f{}; + bool is_self{}; + self_header m_self{}; + std::vector m_self_segments; + elf_header m_elf_header{}; + std::vector m_elf_phdr; + std::vector m_elf_shdr; + elf_program_id_header m_self_id_header{}; }; - diff --git a/src/GUI/ElfViewer.cpp b/src/GUI/ElfViewer.cpp index e698d853..fdb1fc07 100644 --- a/src/GUI/ElfViewer.cpp +++ b/src/GUI/ElfViewer.cpp @@ -30,8 +30,8 @@ void ElfViewer::display(bool enabled) if (ImGui::TreeNode("Self Segment Header")) { - const auto* self = elf->GetSElfHeader(); - for (u16 i = 0; i < self->segment_count; i++) + const auto self = elf->GetSElfHeader(); + for (u16 i = 0; i < self.segment_count; i++) { if (ImGui::TreeNodeEx((void*)(intptr_t)i, ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen, "%d", i)) { @@ -47,18 +47,18 @@ void ElfViewer::display(bool enabled) } 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::IsItemClicked()) selected = ELF_HEADER; } 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::IsItemClicked()) @@ -67,7 +67,7 @@ void ElfViewer::display(bool enabled) } ImGui::TreePop(); } - if (elf_header->e_shnum != 0) + if (elf_header.e_shnum != 0) { if (ImGui::TreeNode("Elf Section Headers")) { @@ -82,20 +82,20 @@ void ElfViewer::display(bool enabled) ImGui::BeginChild("Table View", ImVec2(0, -ImGui::GetFrameHeightWithSpacing())); // Leave room for 1 line below us if (selected == SELF_HEADER) { - ImGui::TextWrapped(elf->SElfHeaderStr().c_str()); + ImGui::TextWrapped("%s", elf->SElfHeaderStr().c_str()); } 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) { - ImGui::TextWrapped(elf->ElfHeaderStr().c_str()); + ImGui::TextWrapped("%s", elf->ElfHeaderStr().c_str()); } 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::End(); -} \ No newline at end of file +} From 7cbe7c762ae2cddb341cd15db1cd745118a62d0b Mon Sep 17 00:00:00 2001 From: GPUCode Date: Thu, 26 Oct 2023 23:07:15 +0300 Subject: [PATCH 2/7] linker: Eliminate orphan news * Most of these can just be on the stack, with the rest being std::vectors --- src/Core/PS4/Linker.cpp | 263 +++++++++++++++++++--------------------- src/Core/PS4/Linker.h | 106 ++++++++-------- 2 files changed, 175 insertions(+), 194 deletions(-) diff --git a/src/Core/PS4/Linker.cpp b/src/Core/PS4/Linker.cpp index e795b906..a4e00cc6 100644 --- a/src/Core/PS4/Linker.cpp +++ b/src/Core/PS4/Linker.cpp @@ -1,7 +1,7 @@ #include "Linker.h" #include "../virtual_memory.h" #include -#include "../../Util/Disassembler.h" +#include "Zydis.h" #include #include "Util/aerolib.h" #include "Loader/SymbolsResolver.h" @@ -12,15 +12,6 @@ constexpr bool debug_loader = true; static u64 g_load_addr = SYSTEM_RESERVED + CODE_BASE_OFFSET; -Linker::Linker() -{ - m_HLEsymbols = new SymbolsResolver; -} - -Linker::~Linker() -{ -} - 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); @@ -28,78 +19,78 @@ static u64 get_aligned_size(const elf_program_header& phdr) static u64 calculate_base_size(const elf_header& ehdr, std::span phdr) { - u64 base_size = 0; + u64 base_size = 0; 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)) + { u64 last_addr = phdr[i].p_vaddr + get_aligned_size(phdr[i]); - if (last_addr > base_size) - { - base_size = last_addr; - } - } - } - return base_size; + if (last_addr > base_size) + { + base_size = last_addr; + } + } + } + return base_size; } static std::string encodeId(u64 nVal) { - std::string enc; - const char pCodes[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-"; - if (nVal < 0x40u) - { - enc += pCodes[nVal]; - } - else - { - if (nVal < 0x1000u) - { - enc += pCodes[static_cast(nVal >> 6u) & 0x3fu]; - enc += pCodes[nVal & 0x3fu]; - } - else - { - enc += pCodes[static_cast(nVal >> 12u) & 0x3fu]; - enc += pCodes[static_cast(nVal >> 6u) & 0x3fu]; - enc += pCodes[nVal & 0x3fu]; - } - } - return enc; + std::string enc; + const char pCodes[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-"; + if (nVal < 0x40u) + { + enc += pCodes[nVal]; + } + else + { + if (nVal < 0x1000u) + { + enc += pCodes[static_cast(nVal >> 6u) & 0x3fu]; + enc += pCodes[nVal & 0x3fu]; + } + else + { + enc += pCodes[static_cast(nVal >> 12u) & 0x3fu]; + enc += pCodes[static_cast(nVal >> 6u) & 0x3fu]; + enc += pCodes[nVal & 0x3fu]; + } + } + return enc; } + +Linker::Linker() = default; + +Linker::~Linker() = default; + Module* Linker::LoadModule(const std::string& elf_name) { std::scoped_lock lock{m_mutex}; - auto* m = new Module; - m->linker = this; - m->elf.Open(elf_name); - if (m->elf.isElfFile()) - { - LoadModuleToMemory(m); - LoadDynamicInfo(m); - LoadSymbols(m); - Relocate(m); - } - else - { - return nullptr;//it is not a valid elf file //TODO check it why! - } - m_modules.push_back(m);//added it to load modules + auto& m = m_modules.emplace_back(); + m.linker = this; + m.elf.Open(elf_name); - return m; + if (m.elf.isElfFile()) { + LoadModuleToMemory(&m); + LoadDynamicInfo(&m); + LoadSymbols(&m); + Relocate(&m); + } else { + m_modules.pop_back(); + return nullptr; // It is not a valid elf file //TODO check it why! + } + + return &m; } Module* Linker::FindModule(/*u32 id*/) { - //find module . TODO atm we only have 1 module so we don't need to iterate on vector - Module* m = m_modules.at(0); - - if (m) - { - return m; - } - return nullptr; + // TODO atm we only have 1 module so we don't need to iterate on vector + if (m_modules.empty()) [[unlikely]] { + return nullptr; + } + return &m_modules[0]; } void Linker::LoadModuleToMemory(Module* m) @@ -146,9 +137,8 @@ void Linker::LoadModuleToMemory(Module* m) case PT_DYNAMIC: if (elf_pheader[i].p_filesz != 0) { - void* dynamic = new u08[elf_pheader[i].p_filesz]; - m->elf.LoadSegment(reinterpret_cast(dynamic), elf_pheader[i].p_offset, elf_pheader[i].p_filesz); - m->m_dynamic = dynamic; + m->m_dynamic.resize(elf_pheader[i].p_filesz); + m->elf.LoadSegment(reinterpret_cast(m->m_dynamic.data()), elf_pheader[i].p_offset, elf_pheader[i].p_filesz); } else { @@ -158,9 +148,8 @@ void Linker::LoadModuleToMemory(Module* m) case PT_SCE_DYNLIBDATA: if (elf_pheader[i].p_filesz != 0) { - void* dynamic = new u08[elf_pheader[i].p_filesz]; - m->elf.LoadSegment(reinterpret_cast(dynamic), elf_pheader[i].p_offset, elf_pheader[i].p_filesz); - m->m_dynamic_data = dynamic; + m->m_dynamic_data.resize(elf_pheader[i].p_filesz); + m->elf.LoadSegment(reinterpret_cast(m->m_dynamic_data.data()), elf_pheader[i].p_offset, elf_pheader[i].p_filesz); } else { @@ -194,107 +183,105 @@ void Linker::LoadModuleToMemory(Module* m) void Linker::LoadDynamicInfo(Module* m) { - m->dynamic_info = new DynamicModuleInfo; - - for (const auto* dyn = static_cast(m->m_dynamic); dyn->d_tag != DT_NULL; dyn++) + for (const auto* dyn = reinterpret_cast(m->m_dynamic.data()); dyn->d_tag != DT_NULL; dyn++) { switch (dyn->d_tag) { case DT_SCE_HASH: //Offset of the hash table. - m->dynamic_info->hash_table = reinterpret_cast(static_cast(m->m_dynamic_data) + dyn->d_un.d_ptr); + m->dynamic_info.hash_table = reinterpret_cast(m->m_dynamic_data.data() + dyn->d_un.d_ptr); break; case DT_SCE_HASHSZ: //Size of the hash table - m->dynamic_info->hash_table_size = dyn->d_un.d_val; + m->dynamic_info.hash_table_size = dyn->d_un.d_val; break; case DT_SCE_STRTAB://Offset of the string table. - m->dynamic_info->str_table = reinterpret_cast(static_cast(m->m_dynamic_data) + dyn->d_un.d_ptr); + m->dynamic_info.str_table = reinterpret_cast(m->m_dynamic_data.data() + dyn->d_un.d_ptr); break; case DT_SCE_STRSZ: //Size of the string table. - m->dynamic_info->str_table_size = dyn->d_un.d_val; + m->dynamic_info.str_table_size = dyn->d_un.d_val; break; case DT_SCE_SYMTAB://Offset of the symbol table. - m->dynamic_info->symbol_table = reinterpret_cast(static_cast(m->m_dynamic_data) + dyn->d_un.d_ptr); + m->dynamic_info.symbol_table = reinterpret_cast(m->m_dynamic_data.data() + dyn->d_un.d_ptr); break; case DT_SCE_SYMTABSZ://Size of the symbol table. - m->dynamic_info->symbol_table_total_size = dyn->d_un.d_val; + m->dynamic_info.symbol_table_total_size = dyn->d_un.d_val; break; case DT_INIT: - m->dynamic_info->init_virtual_addr = dyn->d_un.d_ptr; + m->dynamic_info.init_virtual_addr = dyn->d_un.d_ptr; break; case DT_FINI: - m->dynamic_info->fini_virtual_addr = dyn->d_un.d_ptr; + m->dynamic_info.fini_virtual_addr = dyn->d_un.d_ptr; break; case DT_SCE_PLTGOT: //Offset of the global offset table. - m->dynamic_info->pltgot_virtual_addr = dyn->d_un.d_ptr; + m->dynamic_info.pltgot_virtual_addr = dyn->d_un.d_ptr; break; case DT_SCE_JMPREL: //Offset of the table containing jump slots. - m->dynamic_info->jmp_relocation_table = reinterpret_cast(static_cast(m->m_dynamic_data) + dyn->d_un.d_ptr); + m->dynamic_info.jmp_relocation_table = reinterpret_cast(m->m_dynamic_data.data() + dyn->d_un.d_ptr); break; case DT_SCE_PLTRELSZ: //Size of the global offset table. - m->dynamic_info->jmp_relocation_table_size = dyn->d_un.d_val; + m->dynamic_info.jmp_relocation_table_size = dyn->d_un.d_val; break; case DT_SCE_PLTREL: //The type of relocations in the relocation table. Should be DT_RELA - m->dynamic_info->jmp_relocation_type = dyn->d_un.d_val; - if (m->dynamic_info->jmp_relocation_type != DT_RELA) + m->dynamic_info.jmp_relocation_type = dyn->d_un.d_val; + if (m->dynamic_info.jmp_relocation_type != DT_RELA) { LOG_WARN_IF(debug_loader, "DT_SCE_PLTREL is NOT DT_RELA should check!"); } break; case DT_SCE_RELA: //Offset of the relocation table. - m->dynamic_info->relocation_table = reinterpret_cast(static_cast(m->m_dynamic_data) + dyn->d_un.d_ptr); + m->dynamic_info.relocation_table = reinterpret_cast(m->m_dynamic_data.data() + dyn->d_un.d_ptr); break; case DT_SCE_RELASZ: //Size of the relocation table. - m->dynamic_info->relocation_table_size = dyn->d_un.d_val; + m->dynamic_info.relocation_table_size = dyn->d_un.d_val; break; case DT_SCE_RELAENT : //The size of relocation table entries. - m->dynamic_info->relocation_table_entries_size = dyn->d_un.d_val; - if (m->dynamic_info->relocation_table_entries_size != 0x18) //this value should always be 0x18 + m->dynamic_info.relocation_table_entries_size = dyn->d_un.d_val; + if (m->dynamic_info.relocation_table_entries_size != 0x18) //this value should always be 0x18 { LOG_WARN_IF(debug_loader, "DT_SCE_RELAENT is NOT 0x18 should check!"); } break; case DT_INIT_ARRAY:// Address of the array of pointers to initialization functions - m->dynamic_info->init_array_virtual_addr = dyn->d_un.d_ptr; + m->dynamic_info.init_array_virtual_addr = dyn->d_un.d_ptr; break; case DT_FINI_ARRAY: // Address of the array of pointers to termination functions - m->dynamic_info->fini_array_virtual_addr = dyn->d_un.d_ptr; + m->dynamic_info.fini_array_virtual_addr = dyn->d_un.d_ptr; break; case DT_INIT_ARRAYSZ://Size in bytes of the array of initialization functions - m->dynamic_info->init_array_size = dyn->d_un.d_val; + m->dynamic_info.init_array_size = dyn->d_un.d_val; break; case DT_FINI_ARRAYSZ://Size in bytes of the array of terminationfunctions - m->dynamic_info->fini_array_size = dyn->d_un.d_val; + m->dynamic_info.fini_array_size = dyn->d_un.d_val; break; case DT_PREINIT_ARRAY://Address of the array of pointers to pre - initialization functions - m->dynamic_info->preinit_array_virtual_addr = dyn->d_un.d_ptr; + m->dynamic_info.preinit_array_virtual_addr = dyn->d_un.d_ptr; break; case DT_PREINIT_ARRAYSZ://Size in bytes of the array of pre - initialization functions - m->dynamic_info->preinit_array_size = dyn->d_un.d_val; + m->dynamic_info.preinit_array_size = dyn->d_un.d_val; break; case DT_SCE_SYMENT: //The size of symbol table entries - m->dynamic_info->symbol_table_entries_size = dyn->d_un.d_val; - if (m->dynamic_info->symbol_table_entries_size != 0x18) //this value should always be 0x18 + m->dynamic_info.symbol_table_entries_size = dyn->d_un.d_val; + if (m->dynamic_info.symbol_table_entries_size != 0x18) //this value should always be 0x18 { LOG_WARN_IF(debug_loader, "DT_SCE_SYMENT is NOT 0x18 should check!"); } break; case DT_DEBUG: - m->dynamic_info->debug = dyn->d_un.d_val; + m->dynamic_info.debug = dyn->d_un.d_val; break; case DT_TEXTREL: - m->dynamic_info->textrel = dyn->d_un.d_val; + m->dynamic_info.textrel = dyn->d_un.d_val; break; case DT_FLAGS: - m->dynamic_info->flags = dyn->d_un.d_val; - if (m->dynamic_info->flags != 0x04) //this value should always be DF_TEXTREL (0x04) + m->dynamic_info.flags = dyn->d_un.d_val; + if (m->dynamic_info.flags != 0x04) //this value should always be DF_TEXTREL (0x04) { LOG_WARN_IF(debug_loader, "DT_FLAGS is NOT 0x04 should check!"); } break; case DT_NEEDED://Offset of the library string in the string table to be linked in. - if (m->dynamic_info->str_table != nullptr)//in theory this should already be filled from about just make a test case + if (m->dynamic_info.str_table != nullptr)//in theory this should already be filled from about just make a test case { - m->dynamic_info->needed.push_back(m->dynamic_info->str_table + dyn->d_un.d_val); + m->dynamic_info.needed.push_back(m->dynamic_info.str_table + dyn->d_un.d_val); } else { @@ -305,18 +292,18 @@ void Linker::LoadDynamicInfo(Module* m) { ModuleInfo info{}; info.value = dyn->d_un.d_val; - info.name = m->dynamic_info->str_table + info.name_offset; + info.name = m->dynamic_info.str_table + info.name_offset; info.enc_id = encodeId(info.id); - m->dynamic_info->import_modules.push_back(info); + m->dynamic_info.import_modules.push_back(info); } break; case DT_SCE_IMPORT_LIB: { LibraryInfo info{}; info.value = dyn->d_un.d_val; - info.name = m->dynamic_info->str_table + info.name_offset; + info.name = m->dynamic_info.str_table + info.name_offset; info.enc_id = encodeId(info.id); - m->dynamic_info->import_libs.push_back(info); + m->dynamic_info.import_libs.push_back(info); } break; case DT_SCE_FINGERPRINT: @@ -330,15 +317,15 @@ void Linker::LoadDynamicInfo(Module* m) LOG_INFO_IF(debug_loader, "unsupported DT_SCE_IMPORT_LIB_ATTR value = ..........: {:#018x}\n", dyn->d_un.d_val); break; case DT_SCE_ORIGINAL_FILENAME: - m->dynamic_info->filename = m->dynamic_info->str_table + dyn->d_un.d_val; + m->dynamic_info.filename = m->dynamic_info.str_table + dyn->d_un.d_val; break; case DT_SCE_MODULE_INFO://probably only useable in shared modules { ModuleInfo info{}; info.value = dyn->d_un.d_val; - info.name = m->dynamic_info->str_table + info.name_offset; + info.name = m->dynamic_info.str_table + info.name_offset; info.enc_id = encodeId(info.id); - m->dynamic_info->export_modules.push_back(info); + m->dynamic_info.export_modules.push_back(info); } break; case DT_SCE_MODULE_ATTR: @@ -349,9 +336,9 @@ void Linker::LoadDynamicInfo(Module* m) { LibraryInfo info{}; info.value = dyn->d_un.d_val; - info.name = m->dynamic_info->str_table + info.name_offset; + info.name = m->dynamic_info.str_table + info.name_offset; info.enc_id = encodeId(info.id); - m->dynamic_info->export_libs.push_back(info); + m->dynamic_info.export_libs.push_back(info); } break; default: @@ -363,9 +350,9 @@ void Linker::LoadDynamicInfo(Module* m) const ModuleInfo* Linker::FindModule(const Module& m, const std::string& id) { - const auto& import_modules = m.dynamic_info->import_modules; + const auto& import_modules = m.dynamic_info.import_modules; int index = 0; - for (auto mod : import_modules) + for (const auto& mod : import_modules) { if (mod.enc_id.compare(id) == 0) { @@ -373,9 +360,9 @@ const ModuleInfo* Linker::FindModule(const Module& m, const std::string& id) } index++; } - const auto& export_modules = m.dynamic_info->export_modules; + const auto& export_modules = m.dynamic_info.export_modules; index = 0; - for (auto mod : export_modules) + for (const auto& mod : export_modules) { if (mod.enc_id.compare(id) == 0) { @@ -388,9 +375,9 @@ const ModuleInfo* Linker::FindModule(const Module& m, const std::string& id) const LibraryInfo* Linker::FindLibrary(const Module& m, const std::string& id) { - const auto& import_libs = m.dynamic_info->import_libs; + const auto& import_libs = m.dynamic_info.import_libs; int index = 0; - for (auto lib : import_libs) + for (const auto& lib : import_libs) { if (lib.enc_id.compare(id) == 0) { @@ -398,9 +385,9 @@ const LibraryInfo* Linker::FindLibrary(const Module& m, const std::string& id) } index++; } - const auto& export_libs = m.dynamic_info->export_libs; + const auto& export_libs = m.dynamic_info.export_libs; index = 0; - for (auto lib : export_libs) + for (const auto& lib : export_libs) { if (lib.enc_id.compare(id) == 0) { @@ -413,19 +400,17 @@ const LibraryInfo* Linker::FindLibrary(const Module& m, const std::string& id) void Linker::LoadSymbols(Module* m) { - if (m->dynamic_info->symbol_table == nullptr || m->dynamic_info->str_table == nullptr || m->dynamic_info->symbol_table_total_size==0) + if (m->dynamic_info.symbol_table == nullptr || m->dynamic_info.str_table == nullptr || m->dynamic_info.symbol_table_total_size==0) { LOG_INFO_IF(debug_loader, "Symbol table not found!\n"); return; } - m->export_sym = new SymbolsResolver; - m->import_sym = new SymbolsResolver; - for (auto* sym = m->dynamic_info->symbol_table; - reinterpret_cast(sym) < reinterpret_cast(m->dynamic_info->symbol_table) + m->dynamic_info->symbol_table_total_size; + for (auto* sym = m->dynamic_info.symbol_table; + reinterpret_cast(sym) < reinterpret_cast(m->dynamic_info.symbol_table) + m->dynamic_info.symbol_table_total_size; sym++) { - std::string id = std::string(m->dynamic_info->str_table + sym->st_name); + std::string id = std::string(m->dynamic_info.str_table + sym->st_name); auto ids = StringUtil::split_string(id, '#'); if (ids.size() == 3)//symbols are 3 parts name , library , module { @@ -489,11 +474,11 @@ void Linker::LoadSymbols(Module* m) if (is_sym_export) { - m->export_sym->AddSymbol(sym_r, sym->st_value + m->base_virtual_addr); + m->export_sym.AddSymbol(sym_r, sym->st_value + m->base_virtual_addr); } else { - m->import_sym->AddSymbol(sym_r,0); + m->import_sym.AddSymbol(sym_r,0); } @@ -506,8 +491,8 @@ static void relocate(u32 idx, elf_relocation* rel, Module* m, bool isJmpRel) { auto type = rel->GetType(); auto symbol = rel->GetSymbol(); auto addend = rel->rel_addend; - auto* symbolsTlb = m->dynamic_info->symbol_table; - auto* namesTlb = m->dynamic_info->str_table; + auto* symbolsTlb = m->dynamic_info.symbol_table; + auto* namesTlb = m->dynamic_info.str_table; u64 rel_value = 0; u64 rel_base_virtual_addr = m->base_virtual_addr; @@ -580,12 +565,12 @@ static void relocate(u32 idx, elf_relocation* rel, Module* m, bool isJmpRel) { void Linker::Relocate(Module* m) { u32 idx = 0; - for (auto* rel = m->dynamic_info->relocation_table; reinterpret_cast(rel) < reinterpret_cast(m->dynamic_info->relocation_table) + m->dynamic_info->relocation_table_size; rel++, idx++) + for (auto* rel = m->dynamic_info.relocation_table; reinterpret_cast(rel) < reinterpret_cast(m->dynamic_info.relocation_table) + m->dynamic_info.relocation_table_size; rel++, idx++) { relocate(idx, rel, m, false); } idx = 0; - for (auto* rel = m->dynamic_info->jmp_relocation_table; reinterpret_cast(rel) < reinterpret_cast(m->dynamic_info->jmp_relocation_table) + m->dynamic_info->jmp_relocation_table_size; rel++, idx++) + for (auto* rel = m->dynamic_info.jmp_relocation_table; reinterpret_cast(rel) < reinterpret_cast(m->dynamic_info.jmp_relocation_table) + m->dynamic_info.jmp_relocation_table_size; rel++, idx++) { relocate(idx, rel, m, true); } @@ -610,10 +595,8 @@ void Linker::Resolve(const std::string& name, int Symtype, Module* m, SymbolReco sr.type = Symtype; const SymbolRecord* rec = nullptr; + rec = m_hle_symbols.FindSymbol(sr); - if (m_HLEsymbols != nullptr) { - rec = m_HLEsymbols->FindSymbol(sr); - } if (rec != nullptr) { *return_info = *rec; } else { @@ -679,6 +662,6 @@ void Linker::Execute() p.argc = 1; 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); - + const auto& module = m_modules.at(0); + run_main_entry(module.elf.GetElfEntry() + module.base_virtual_addr, &p, ProgramExitFunc); } diff --git a/src/Core/PS4/Linker.h b/src/Core/PS4/Linker.h index 596a9af7..b9872995 100644 --- a/src/Core/PS4/Linker.h +++ b/src/Core/PS4/Linker.h @@ -14,23 +14,6 @@ struct EntryParams { const char* argv[3]; }; -// This struct keeps neccesary info about loaded modules. Main executeable is included too as well -struct Module -{ - Elf elf; - u64 aligned_base_size = 0; - u64 base_virtual_addr = 0; // Base virtual address - - Linker* linker = nullptr; - - void* m_dynamic = nullptr; - void* m_dynamic_data = nullptr; - DynamicModuleInfo* dynamic_info = nullptr; - - SymbolsResolver* export_sym = nullptr; - SymbolsResolver* import_sym = nullptr; -}; - struct ModuleInfo { std::string name; @@ -66,50 +49,65 @@ struct LibraryInfo struct DynamicModuleInfo { - void* hash_table = nullptr; - u64 hash_table_size = 0; + void* hash_table = nullptr; + u64 hash_table_size = 0; - char* str_table = nullptr; - u64 str_table_size = 0; + char* str_table = nullptr; + u64 str_table_size = 0; - elf_symbol* symbol_table = nullptr; - u64 symbol_table_total_size = 0; - u64 symbol_table_entries_size = 0; + elf_symbol* symbol_table = nullptr; + u64 symbol_table_total_size = 0; + u64 symbol_table_entries_size = 0; - u64 init_virtual_addr = 0; - u64 fini_virtual_addr = 0; - u64 pltgot_virtual_addr = 0; - u64 init_array_virtual_addr = 0; - u64 fini_array_virtual_addr = 0; - u64 preinit_array_virtual_addr = 0; - u64 init_array_size = 0; - u64 fini_array_size = 0; - u64 preinit_array_size = 0; + u64 init_virtual_addr = 0; + u64 fini_virtual_addr = 0; + u64 pltgot_virtual_addr = 0; + u64 init_array_virtual_addr = 0; + u64 fini_array_virtual_addr = 0; + u64 preinit_array_virtual_addr = 0; + u64 init_array_size = 0; + u64 fini_array_size = 0; + u64 preinit_array_size = 0; - elf_relocation* jmp_relocation_table = nullptr; - u64 jmp_relocation_table_size = 0; - s64 jmp_relocation_type = 0; + elf_relocation* jmp_relocation_table = nullptr; + u64 jmp_relocation_table_size = 0; + s64 jmp_relocation_type = 0; - elf_relocation* relocation_table = nullptr; - u64 relocation_table_size = 0; - u64 relocation_table_entries_size = 0; + elf_relocation* relocation_table = nullptr; + u64 relocation_table_size = 0; + u64 relocation_table_entries_size = 0; - u64 debug = 0; - u64 textrel = 0; - u64 flags = 0; + u64 debug = 0; + u64 textrel = 0; + u64 flags = 0; - std::vector needed; - std::vector import_modules; - std::vector export_modules; - std::vector import_libs; - std::vector export_libs; - - std::string filename;//filename with absolute path + std::vector needed; + std::vector import_modules; + std::vector export_modules; + std::vector import_libs; + std::vector export_libs; + std::string filename; // Filename with absolute path }; -class Linker +// This struct keeps neccesary info about loaded modules. Main executeable is included too as well +struct Module { + Elf elf; + u64 aligned_base_size = 0; + u64 base_virtual_addr = 0; // Base virtual address + + Linker* linker = nullptr; + + std::vector m_dynamic; + std::vector m_dynamic_data; + DynamicModuleInfo dynamic_info{}; + + SymbolsResolver export_sym; + SymbolsResolver import_sym; +}; + +class Linker { public: Linker(); virtual ~Linker(); @@ -119,16 +117,16 @@ public: void LoadModuleToMemory(Module* m); void LoadDynamicInfo(Module* m); void LoadSymbols(Module* m); - SymbolsResolver* getHLESymbols() { return m_HLEsymbols; } + SymbolsResolver& getHLESymbols() { return m_hle_symbols; } void Relocate(Module* m); void Resolve(const std::string& name, int Symtype, Module* m, SymbolRecord* return_info); void Execute(); - private: +private: const ModuleInfo* FindModule(const Module& m, const std::string& id); const LibraryInfo* FindLibrary(const Module& program, const std::string& id); - std::vector m_modules; - SymbolsResolver* m_HLEsymbols = nullptr; + std::vector m_modules; + SymbolsResolver m_hle_symbols{}; std::mutex m_mutex; }; From f3504b2d25bbb5fb76479cc5cfbe960a7405f6be Mon Sep 17 00:00:00 2001 From: GPUCode Date: Thu, 26 Oct 2023 23:13:07 +0300 Subject: [PATCH 3/7] singleton: Use unique_ptr --- src/Core/PS4/Linker.cpp | 2 -- src/Emulator/Util/singleton.h | 17 +++++++---------- src/main.cpp | 2 +- 3 files changed, 8 insertions(+), 13 deletions(-) diff --git a/src/Core/PS4/Linker.cpp b/src/Core/PS4/Linker.cpp index a4e00cc6..76e4a6b3 100644 --- a/src/Core/PS4/Linker.cpp +++ b/src/Core/PS4/Linker.cpp @@ -500,7 +500,6 @@ static void relocate(u32 idx, elf_relocation* rel, Module* m, bool isJmpRel) { bool rel_isResolved = false; u08 rel_sym_type = 0; std::string rel_name; - u08 rel_bind_type = -1; //-1 means it didn't resolve switch (type) { case R_X86_64_RELATIVE: @@ -531,7 +530,6 @@ static void relocate(u32 idx, elf_relocation* rel, Module* m, bool isJmpRel) { } switch (sym_bind) { case STB_GLOBAL: - rel_bind_type = STB_GLOBAL; rel_name = namesTlb + sym.st_name; m->linker->Resolve(rel_name, rel_sym_type, m, &symrec); symbol_vitrual_addr = symrec.virtual_address; diff --git a/src/Emulator/Util/singleton.h b/src/Emulator/Util/singleton.h index a401a380..d5086133 100644 --- a/src/Emulator/Util/singleton.h +++ b/src/Emulator/Util/singleton.h @@ -1,24 +1,21 @@ #pragma once -#include -#include +#include template class singleton { - public: +public: static T* instance() { if (!m_instance) { - m_instance = static_cast(std::malloc(sizeof(T))); - new (m_instance) T; + m_instance = std::make_unique(); } - return m_instance; } - protected: +protected: singleton(); ~singleton(); - private: - static inline T* m_instance = nullptr; -}; \ No newline at end of file +private: + static inline std::unique_ptr m_instance{}; +}; diff --git a/src/main.cpp b/src/main.cpp index 172ede3a..022a4c30 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -54,7 +54,7 @@ int main(int argc, char* argv[]) { const char* const path = argv[1]; // argument 1 is the path of self file to boot auto* linker = singleton::instance(); - HLE::Libs::Init_HLE_Libs(linker->getHLESymbols()); + HLE::Libs::Init_HLE_Libs(&linker->getHLESymbols()); auto* module = linker->LoadModule(path); // load main executable std::jthread mainthread( [](std::stop_token stop_token, void*) { From 33729d634e2048f6ebdea481033b158ad63d8d7a Mon Sep 17 00:00:00 2001 From: GPUCode Date: Thu, 26 Oct 2023 23:15:11 +0300 Subject: [PATCH 4/7] main: Remove remnants of imgui example --- src/main.cpp | 214 +-------------------------------------------------- 1 file changed, 4 insertions(+), 210 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 022a4c30..bb9aed7d 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,38 +1,13 @@ -// Dear ImGui: standalone example application for SDL3 + OpenGL -// (SDL is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.) -// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. -// Read online: https://github.com/ocornut/imgui/tree/master/docs - #include -#include - -#include "imgui.h" -#include "imgui_impl_opengl3.h" -#include "imgui_impl_sdl3.h" -#if defined(IMGUI_IMPL_OPENGL_ES2) -#include -#else -#include -#endif - +#include #include - -#include "GUI/ElfViewer.h" -#include "spdlog/spdlog.h" #include "types.h" - -// This example can also compile and run with Emscripten! See 'Makefile.emscripten' for details. -#ifdef __EMSCRIPTEN__ -#include "../libs/emscripten/emscripten_mainloop_stub.h" -#endif #include #include #include #include -#include -#include +#include #include - #include "Core/PS4/HLE/Libs.h" #include "Core/PS4/Linker.h" #include "Emulator/Util\singleton.h" @@ -53,9 +28,9 @@ int main(int argc, char* argv[]) { const char* const path = argv[1]; // argument 1 is the path of self file to boot - auto* linker = singleton::instance(); + auto linker = singleton::instance(); HLE::Libs::Init_HLE_Libs(&linker->getHLESymbols()); - auto* module = linker->LoadModule(path); // load main executable + linker->LoadModule(path); // Load main executable std::jthread mainthread( [](std::stop_token stop_token, void*) { auto* linker = singleton::instance(); @@ -67,187 +42,6 @@ int main(int argc, char* argv[]) { discordRPC.update(Discord::RPCStatus::Idling, ""); Emu::emuRun(); -#if 0 - // Setup SDL - if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_GAMEPAD) != 0) - { - printf("Error: SDL_Init(): %s\n", SDL_GetError()); - return -1; - } - - // Decide GL+GLSL versions -#if defined(IMGUI_IMPL_OPENGL_ES2) - // GL ES 2.0 + GLSL 100 - const char* glsl_version = "#version 100"; - SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, 0); - SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); - SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); - SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); -#elif defined(__APPLE__) - // GL 3.2 Core + GLSL 150 - const char* glsl_version = "#version 150"; - SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG); // Always required on Mac - SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); - SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); - SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); -#else - // GL 3.0 + GLSL 130 - const char* glsl_version = "#version 130"; - SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, 0); - SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); - SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); - SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); -#endif - - // Enable native IME. - SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1"); - - // Create window with graphics context - SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); - SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); - SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); - SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIDDEN); - SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL3+OpenGL3 example", 1280, 720, window_flags); - if (window == nullptr) - { - printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); - return -1; - } - SDL_SetWindowPosition(window, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED); - SDL_GLContext gl_context = SDL_GL_CreateContext(window); - SDL_GL_MakeCurrent(window, gl_context); - SDL_GL_SetSwapInterval(1); // Enable vsync - SDL_ShowWindow(window); - - // Setup Dear ImGui context - IMGUI_CHECKVERSION(); - ImGui::CreateContext(); - ImGuiIO& io = ImGui::GetIO(); (void)io; - io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls - io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls - - // Setup Dear ImGui style - ImGui::StyleColorsDark(); - //ImGui::StyleColorsLight(); - - // Setup Platform/Renderer backends - ImGui_ImplSDL3_InitForOpenGL(window, gl_context); - ImGui_ImplOpenGL3_Init(glsl_version); - - // Load Fonts - // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. - // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. - // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. - // - Read 'docs/FONTS.md' for more instructions and details. - // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! - // - Our Emscripten build process allows embedding fonts to be accessible at runtime from the "fonts/" folder. See Makefile.emscripten for details. - //io.Fonts->AddFontDefault(); - //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); - //IM_ASSERT(font != nullptr); - - // Our state - bool show_demo_window = true; - bool show_another_window = false; - ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); - - // Main loop - bool done = false; -#ifdef __EMSCRIPTEN__ - // For an Emscripten build we are disabling file-system access, so let's not attempt to do a fopen() of the imgui.ini file. - // You may manually call LoadIniSettingsFromMemory() to load settings from your own storage. - io.IniFilename = nullptr; - EMSCRIPTEN_MAINLOOP_BEGIN -#else - while (!done) -#endif - { - // Poll and handle events (inputs, window resize, etc.) - // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. - // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. - // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. - // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. - SDL_Event event; - while (SDL_PollEvent(&event)) - { - ImGui_ImplSDL3_ProcessEvent(&event); - if (event.type == SDL_EVENT_QUIT) - done = true; - if (event.type == SDL_EVENT_WINDOW_CLOSE_REQUESTED && event.window.windowID == SDL_GetWindowID(window)) - done = true; - } - - // Start the Dear ImGui frame - ImGui_ImplOpenGL3_NewFrame(); - ImGui_ImplSDL3_NewFrame(); - ImGui::NewFrame(); - - // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!). - if (show_demo_window) - ImGui::ShowDemoWindow(&show_demo_window); - - // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window. - { - static float f = 0.0f; - static int counter = 0; - - ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it. - - ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too) - ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state - ImGui::Checkbox("Another Window", &show_another_window); - - ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f - ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color - - if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated) - counter++; - ImGui::SameLine(); - ImGui::Text("counter = %d", counter); - - ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); - ImGui::End(); - } - - // 3. Show another simple window. - if (show_another_window) - { - ImGui::Begin("Another Window", &show_another_window); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked) - ImGui::Text("Hello from another window!"); - if (ImGui::Button("Close Me")) - show_another_window = false; - ImGui::End(); - } - auto* linker = Singleton::Instance(); - ElfViewer elfview(linker->FindModule()->elf); - elfview.display(show_another_window); - // Rendering - ImGui::Render(); - glViewport(0, 0, (int)io.DisplaySize.x, (int)io.DisplaySize.y); - glClearColor(clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w); - glClear(GL_COLOR_BUFFER_BIT); - ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); - SDL_GL_SwapWindow(window); - } -#ifdef __EMSCRIPTEN__ - EMSCRIPTEN_MAINLOOP_END; -#endif - - // Cleanup - ImGui_ImplOpenGL3_Shutdown(); - ImGui_ImplSDL3_Shutdown(); - ImGui::DestroyContext(); - - SDL_GL_DeleteContext(gl_context); - SDL_DestroyWindow(window); - SDL_Quit(); -#endif - discordRPC.stop(); return 0; } From 28819dede14b2159092ad50f83b7ecf1aaac9f64 Mon Sep 17 00:00:00 2001 From: GPUCode Date: Thu, 26 Oct 2023 23:29:05 +0300 Subject: [PATCH 5/7] code: Replace printf/scanf with type safe fmt --- src/Core/PS4/HLE/Graphics/graphics_render.cpp | 18 +++++++-------- src/Core/PS4/Linker.cpp | 6 ++--- src/Core/PS4/Loader/SymbolsResolver.cpp | 23 ++++++++----------- src/Emulator/Util/singleton.h | 2 +- src/Util/Disassembler.cpp | 15 ++++++------ src/Util/config.cpp | 9 ++++---- src/emulator.cpp | 20 ++++++++-------- src/main.cpp | 5 ++-- src/vulkan_util.cpp | 4 ++-- 9 files changed, 50 insertions(+), 52 deletions(-) diff --git a/src/Core/PS4/HLE/Graphics/graphics_render.cpp b/src/Core/PS4/HLE/Graphics/graphics_render.cpp index e51e3721..22829e7c 100644 --- a/src/Core/PS4/HLE/Graphics/graphics_render.cpp +++ b/src/Core/PS4/HLE/Graphics/graphics_render.cpp @@ -1,5 +1,5 @@ #include "graphics_render.h" - +#include #include "Emulator/Util/singleton.h" #include "emulator.h" @@ -60,7 +60,7 @@ void GPU::CommandBuffer::begin() const { auto result = vkBeginCommandBuffer(buffer, &begin_info); if (result != VK_SUCCESS) { - printf("vkBeginCommandBuffer failed\n"); + fmt::print("vkBeginCommandBuffer failed\n"); std::exit(0); } } @@ -70,7 +70,7 @@ void GPU::CommandBuffer::end() const { auto result = vkEndCommandBuffer(buffer); if (result != VK_SUCCESS) { - printf("vkEndCommandBuffer failed\n"); + fmt::print("vkEndCommandBuffer failed\n"); std::exit(0); } } @@ -96,7 +96,7 @@ void GPU::CommandBuffer::executeWithSemaphore() { m_execute = true; if (result != VK_SUCCESS) { - printf("vkQueueSubmit failed\n"); + fmt::print("vkQueueSubmit failed\n"); std::exit(0); } } @@ -122,7 +122,7 @@ void GPU::CommandBuffer::execute() { m_execute = true; if (result != VK_SUCCESS) { - printf("vkQueueSubmit failed\n"); + fmt::print("vkQueueSubmit failed\n"); std::exit(0); } } @@ -141,7 +141,7 @@ void GPU::CommandPool::createPool(int id) { vkCreateCommandPool(ctx->m_device, &pool_info, nullptr, &m_pool[id]->pool); if (m_pool[id]->pool == nullptr) { - printf("pool is nullptr"); + fmt::print("pool is nullptr"); std::exit(0); } @@ -158,7 +158,7 @@ void GPU::CommandPool::createPool(int id) { alloc_info.commandBufferCount = m_pool[id]->buffers_count; if (vkAllocateCommandBuffers(ctx->m_device, &alloc_info, m_pool[id]->buffers) != VK_SUCCESS) { - printf("Can't allocate command buffers\n"); + fmt::print("Can't allocate command buffers\n"); std::exit(0); } @@ -171,7 +171,7 @@ void GPU::CommandPool::createPool(int id) { fence_info.flags = 0; if (vkCreateFence(ctx->m_device, &fence_info, nullptr, &m_pool[id]->fences[i]) != VK_SUCCESS) { - printf("Can't create fence\n"); + fmt::print("Can't create fence\n"); std::exit(0); } @@ -181,7 +181,7 @@ void GPU::CommandPool::createPool(int id) { semaphore_info.flags = 0; if (vkCreateSemaphore(ctx->m_device, &semaphore_info, nullptr, &m_pool[id]->semaphores[i]) != VK_SUCCESS) { - printf("Can't create semas\n"); + fmt::print("Can't create semas\n"); std::exit(0); } } diff --git a/src/Core/PS4/Linker.cpp b/src/Core/PS4/Linker.cpp index 76e4a6b3..14367dc5 100644 --- a/src/Core/PS4/Linker.cpp +++ b/src/Core/PS4/Linker.cpp @@ -1,6 +1,7 @@ #include "Linker.h" #include "../virtual_memory.h" #include +#include #include "Zydis.h" #include #include "Util/aerolib.h" @@ -175,7 +176,7 @@ void Linker::LoadModuleToMemory(Module* m) /* length: */ sizeof(rt1) - offset, /* instruction: */ &instruction ))) { - printf("%016" PRIX64 " %s\n", runtime_address, instruction.text); + fmt::print("{:#x}" PRIX64 " {}\n", runtime_address, instruction.text); offset += instruction.info.length; runtime_address += instruction.info.length; } @@ -625,8 +626,7 @@ using exit_func_t = PS4_SYSV_ABI void (*)(); using entry_func_t = PS4_SYSV_ABI void (*)(EntryParams* params, exit_func_t atexit_func); static PS4_SYSV_ABI void ProgramExitFunc() { - - printf("exit function called\n"); + fmt::print("exit function called\n"); } static void run_main_entry(u64 addr, EntryParams* params, exit_func_t exit_func) { diff --git a/src/Core/PS4/Loader/SymbolsResolver.cpp b/src/Core/PS4/Loader/SymbolsResolver.cpp index b8740836..c0e56d53 100644 --- a/src/Core/PS4/Loader/SymbolsResolver.cpp +++ b/src/Core/PS4/Loader/SymbolsResolver.cpp @@ -2,7 +2,6 @@ #include "SymbolsResolver.h" #include - void SymbolsResolver::AddSymbol(const SymbolRes& s, u64 virtual_addr) { SymbolRecord r{}; @@ -12,21 +11,19 @@ void SymbolsResolver::AddSymbol(const SymbolRes& s, u64 virtual_addr) } std::string SymbolsResolver::GenerateName(const SymbolRes& s) { - char str[256]; - sprintf(str, "%s lib[%s_v%d]mod[%s_v%d.%d]", s.name.c_str(),s.library.c_str(), s.library_version, s.module.c_str(), - s.module_version_major, s.module_version_minor); - return std::string(str); + return fmt::format("{} lib[{}_v{}]mod[{}_v{}.{}]", + s.name, s.library, s.library_version, + s.module, s.module_version_major, s.module_version_minor); } const SymbolRecord* SymbolsResolver::FindSymbol(const SymbolRes& s) const { - std::string name = GenerateName(s); - int index = 0; - for (auto symbol : m_symbols) { - if (symbol.name.compare(name) == 0) { - return &m_symbols.at(index); + const std::string name = GenerateName(s); + for (u32 i = 0; i < m_symbols.size(); i++) { + if (m_symbols[i].name.compare(name) == 0) { + return &m_symbols[i]; } - index++; } - LOG_INFO_IF(true, "unresolved! {}\n", name); + + LOG_INFO("Unresolved! {}\n", name); return nullptr; -} \ No newline at end of file +} diff --git a/src/Emulator/Util/singleton.h b/src/Emulator/Util/singleton.h index d5086133..01b3751b 100644 --- a/src/Emulator/Util/singleton.h +++ b/src/Emulator/Util/singleton.h @@ -9,7 +9,7 @@ public: if (!m_instance) { m_instance = std::make_unique(); } - return m_instance; + return m_instance.get(); } protected: diff --git a/src/Util/Disassembler.cpp b/src/Util/Disassembler.cpp index 83b9289f..e1af76bb 100644 --- a/src/Util/Disassembler.cpp +++ b/src/Util/Disassembler.cpp @@ -1,6 +1,5 @@ #include "Disassembler.h" -#include - +#include Disassembler::Disassembler() { @@ -15,11 +14,11 @@ Disassembler::~Disassembler() void Disassembler::printInstruction(void* code,u64 address)//print a single instruction { ZydisDecodedInstruction instruction; - ZydisDecodedOperand operands[ZYDIS_MAX_OPERAND_COUNT_VISIBLE]; - ZyanStatus status = ZydisDecoderDecodeFull(&m_decoder, code, sizeof(code), &instruction, operands); + ZydisDecodedOperand operands[ZYDIS_MAX_OPERAND_COUNT_VISIBLE]; + ZyanStatus status = ZydisDecoderDecodeFull(&m_decoder, code, sizeof(code), &instruction, operands); if (!ZYAN_SUCCESS(status)) { - printf("decode instruction failed at %p\n", code); + fmt::print("decode instruction failed at {}\n", fmt::ptr(code)); } else { @@ -30,7 +29,7 @@ void Disassembler::printInstruction(void* code,u64 address)//print a single inst void Disassembler::printInst(ZydisDecodedInstruction& inst, ZydisDecodedOperand* operands,u64 address) { const int bufLen = 256; - char szBuffer[bufLen]; + char szBuffer[bufLen]; ZydisFormatterFormatInstruction(&m_formatter, &inst, operands,inst.operand_count_visible, szBuffer, sizeof(szBuffer), address, ZYAN_NULL); - printf("instruction: %s\n", szBuffer); -} \ No newline at end of file + fmt::print("instruction: {}\n", szBuffer); +} diff --git a/src/Util/config.cpp b/src/Util/config.cpp index aa5ff8a4..ab4eaf02 100644 --- a/src/Util/config.cpp +++ b/src/Util/config.cpp @@ -2,6 +2,7 @@ #include #include +#include #include namespace Config { @@ -29,7 +30,7 @@ void load(const std::filesystem::path& path) { try { data = toml::parse(path); } catch (std::exception& ex) { - printf("Got exception trying to load config file. Exception: %s\n", ex.what()); + fmt::print("Got exception trying to load config file. Exception: {}\n", ex.what()); return; } @@ -61,14 +62,14 @@ void save(const std::filesystem::path& path) { try { data = toml::parse(path); } catch (const std::exception& ex) { - printf("Exception trying to parse config file. Exception: %s\n", ex.what()); + fmt::print("Exception trying to parse config file. Exception: {}\n", ex.what()); return; } } else { if (error) { - printf("Filesystem error accessing %s (error: %s)\n", path.string().c_str(), error.message().c_str()); + fmt::print("Filesystem error accessing {} (error: {})\n", path.string(), error.message().c_str()); } - printf("Saving new configuration file %s\n", path.string().c_str()); + fmt::print("Saving new configuration file {}\n", path.string()); } data["General"]["isPS4Pro"] = isNeo; diff --git a/src/emulator.cpp b/src/emulator.cpp index 7e67849d..b489b39a 100644 --- a/src/emulator.cpp +++ b/src/emulator.cpp @@ -1,5 +1,5 @@ #include "emulator.h" - +#include #include #include #include "Emulator/Util/singleton.h" @@ -33,7 +33,7 @@ static void CreateSdlWindow(WindowCtx* ctx) { int height = static_cast(ctx->m_graphic_ctx.screen_height); if (SDL_Init(SDL_INIT_VIDEO) < 0) { - printf("%s\n", SDL_GetError()); + fmt::print("{}\n", SDL_GetError()); std::exit(0); } std::string title = "shadps4 v" + std::string(Emulator::VERSION); @@ -43,7 +43,7 @@ static void CreateSdlWindow(WindowCtx* ctx) { ctx->is_window_hidden = true; // hide window until we need to show something (should draw something in buffers) if (ctx->m_window == nullptr) { - printf("%s\n", SDL_GetError()); + fmt::print("{}\n", SDL_GetError()); std::exit(0); } @@ -115,11 +115,11 @@ void DrawBuffer(HLE::Libs::Graphics::VideoOutVulkanImage* image) { window_ctx->swapchain->present_complete_fence, &window_ctx->swapchain->current_index); if (result != VK_SUCCESS) { - printf("Can't aquireNextImage\n"); + fmt::print("Can't aquireNextImage\n"); std::exit(0); } if (window_ctx->swapchain->current_index == static_cast(-1)) { - printf("Unsupported:swapchain current index is -1\n"); + fmt::print("Unsupported:swapchain current index is -1\n"); std::exit(0); } @@ -127,7 +127,7 @@ void DrawBuffer(HLE::Libs::Graphics::VideoOutVulkanImage* image) { result = vkWaitForFences(window_ctx->m_graphic_ctx.m_device, 1, &window_ctx->swapchain->present_complete_fence, VK_TRUE, 100000000); } while (result == VK_TIMEOUT); if (result != VK_SUCCESS) { - printf("vkWaitForFences is not success\n"); + fmt::print("vkWaitForFences is not success\n"); std::exit(0); } @@ -137,11 +137,11 @@ void DrawBuffer(HLE::Libs::Graphics::VideoOutVulkanImage* image) { auto* blt_dst_image = window_ctx->swapchain; if (blt_src_image == nullptr) { - printf("blt_src_image is null\n"); + fmt::print("blt_src_image is null\n"); std::exit(0); } if (blt_dst_image == nullptr) { - printf("blt_dst_image is null\n"); + fmt::print("blt_dst_image is null\n"); std::exit(0); } @@ -187,13 +187,13 @@ void DrawBuffer(HLE::Libs::Graphics::VideoOutVulkanImage* image) { const auto& queue = window_ctx->m_graphic_ctx.queues[10]; if (queue.mutex != nullptr) { - printf("queue.mutexe is null\n"); + fmt::print("queue.mutexe is null\n"); std::exit(0); } result = vkQueuePresentKHR(queue.vk_queue, &present); if (result != VK_SUCCESS) { - printf("vkQueuePresentKHR failed\n"); + fmt::print("vkQueuePresentKHR failed\n"); std::exit(0); } } diff --git a/src/main.cpp b/src/main.cpp index bb9aed7d..97cfc909 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,7 +1,8 @@ #include #include -#include +#include #include "types.h" +#include "Util/log.h" #include #include #include @@ -16,7 +17,7 @@ // Main code int main(int argc, char* argv[]) { if (argc == 1) { - printf("Usage: %s \n", argv[0]); + fmt::print("Usage: {} \n", argv[0]); return -1; } Config::load("config.toml"); diff --git a/src/vulkan_util.cpp b/src/vulkan_util.cpp index f414a7f0..39f5305b 100644 --- a/src/vulkan_util.cpp +++ b/src/vulkan_util.cpp @@ -1,5 +1,5 @@ #include "vulkan_util.h" - +#include #include #include #include @@ -588,7 +588,7 @@ void Graphics::Vulkan::vulkanCreateBuffer(HLE::Libs::Graphics::GraphicCtx* ctx, bool allocated = GPU::vulkanAllocateMemory(ctx, &buffer->memory); if (!allocated) { - printf("Can't allocate vulkan\n"); + fmt::print("Can't allocate vulkan\n"); std::exit(0); } vkBindBufferMemory(ctx->m_device, buffer->buffer, buffer->memory.memory, buffer->memory.offset); From e196e356695df40763e246f6293bb6b39fc819b2 Mon Sep 17 00:00:00 2001 From: GPUCode Date: Thu, 26 Oct 2023 23:38:37 +0300 Subject: [PATCH 6/7] vulkan: Remove orphan new part 1 --- src/Core/PS4/HLE/Graphics/graphics_ctx.h | 4 +- src/emulator.cpp | 30 +++++------ src/emulator.h | 11 ++-- src/vulkan_util.cpp | 64 ++++++++++++------------ src/vulkan_util.h | 11 +--- 5 files changed, 54 insertions(+), 66 deletions(-) diff --git a/src/Core/PS4/HLE/Graphics/graphics_ctx.h b/src/Core/PS4/HLE/Graphics/graphics_ctx.h index 051949b5..4496b5ea 100644 --- a/src/Core/PS4/HLE/Graphics/graphics_ctx.h +++ b/src/Core/PS4/HLE/Graphics/graphics_ctx.h @@ -17,7 +17,7 @@ struct VulkanCommandPool { }; struct VulkanQueueInfo { - std::mutex* mutex = nullptr; + std::unique_ptr mutex{}; u32 family = static_cast(-1); u32 index = static_cast(-1); VkQueue vk_queue = nullptr; @@ -69,4 +69,4 @@ struct VideoOutVulkanImage : public VulkanImage { VideoOutVulkanImage() : VulkanImage(VulkanImageType::VideoOut) {} }; -} // namespace HLE::Libs::Graphics \ No newline at end of file +} // namespace HLE::Libs::Graphics diff --git a/src/emulator.cpp b/src/emulator.cpp index b489b39a..44e69683 100644 --- a/src/emulator.cpp +++ b/src/emulator.cpp @@ -109,41 +109,37 @@ void DrawBuffer(HLE::Libs::Graphics::VideoOutVulkanImage* image) { window_ctx->is_window_hidden = false; } - window_ctx->swapchain->current_index = static_cast(-1); + window_ctx->swapchain.current_index = static_cast(-1); - auto result = vkAcquireNextImageKHR(window_ctx->m_graphic_ctx.m_device, window_ctx->swapchain->swapchain, UINT64_MAX, nullptr, - window_ctx->swapchain->present_complete_fence, &window_ctx->swapchain->current_index); + auto result = vkAcquireNextImageKHR(window_ctx->m_graphic_ctx.m_device, window_ctx->swapchain.swapchain, UINT64_MAX, nullptr, + window_ctx->swapchain.present_complete_fence, &window_ctx->swapchain.current_index); if (result != VK_SUCCESS) { fmt::print("Can't aquireNextImage\n"); std::exit(0); } - if (window_ctx->swapchain->current_index == static_cast(-1)) { + if (window_ctx->swapchain.current_index == static_cast(-1)) { fmt::print("Unsupported:swapchain current index is -1\n"); std::exit(0); } do { - result = vkWaitForFences(window_ctx->m_graphic_ctx.m_device, 1, &window_ctx->swapchain->present_complete_fence, VK_TRUE, 100000000); + result = vkWaitForFences(window_ctx->m_graphic_ctx.m_device, 1, &window_ctx->swapchain.present_complete_fence, VK_TRUE, 100000000); } while (result == VK_TIMEOUT); if (result != VK_SUCCESS) { fmt::print("vkWaitForFences is not success\n"); std::exit(0); } - vkResetFences(window_ctx->m_graphic_ctx.m_device, 1, &window_ctx->swapchain->present_complete_fence); + vkResetFences(window_ctx->m_graphic_ctx.m_device, 1, &window_ctx->swapchain.present_complete_fence); - auto* blt_src_image = image; - auto* blt_dst_image = window_ctx->swapchain; + auto blt_src_image = image; + auto blt_dst_image = window_ctx->swapchain; if (blt_src_image == nullptr) { fmt::print("blt_src_image is null\n"); std::exit(0); } - if (blt_dst_image == nullptr) { - fmt::print("blt_dst_image is null\n"); - std::exit(0); - } GPU::CommandBuffer buffer(10); @@ -151,7 +147,7 @@ void DrawBuffer(HLE::Libs::Graphics::VideoOutVulkanImage* image) { buffer.begin(); - Graphics::Vulkan::vulkanBlitImage(&buffer, blt_src_image, blt_dst_image); + Graphics::Vulkan::vulkanBlitImage(&buffer, blt_src_image, &blt_dst_image); VkImageMemoryBarrier pre_present_barrier{}; pre_present_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; @@ -167,7 +163,7 @@ void DrawBuffer(HLE::Libs::Graphics::VideoOutVulkanImage* image) { pre_present_barrier.subresourceRange.levelCount = 1; pre_present_barrier.subresourceRange.baseArrayLayer = 0; pre_present_barrier.subresourceRange.layerCount = 1; - pre_present_barrier.image = window_ctx->swapchain->swapchain_images[window_ctx->swapchain->current_index]; + pre_present_barrier.image = window_ctx->swapchain.swapchain_images[window_ctx->swapchain.current_index]; vkCmdPipelineBarrier(vk_buffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, nullptr, 0, nullptr, 1, &pre_present_barrier); @@ -178,8 +174,8 @@ void DrawBuffer(HLE::Libs::Graphics::VideoOutVulkanImage* image) { present.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; present.pNext = nullptr; present.swapchainCount = 1; - present.pSwapchains = &window_ctx->swapchain->swapchain; - present.pImageIndices = &window_ctx->swapchain->current_index; + present.pSwapchains = &window_ctx->swapchain.swapchain; + present.pImageIndices = &window_ctx->swapchain.current_index; present.pWaitSemaphores = &buffer.getPool()->semaphores[buffer.getIndex()]; present.waitSemaphoreCount = 1; present.pResults = nullptr; @@ -223,4 +219,4 @@ void keyboardEvent(SDL_Event* event) { } } -} // namespace Emu \ No newline at end of file +} // namespace Emu diff --git a/src/emulator.h b/src/emulator.h index 7842faae..0e9f938d 100644 --- a/src/emulator.h +++ b/src/emulator.h @@ -49,8 +49,8 @@ struct VulkanSwapchain { VkSwapchainKHR swapchain = nullptr; VkFormat swapchain_format = VK_FORMAT_UNDEFINED; VkExtent2D swapchain_extent = {}; - VkImage* swapchain_images = nullptr; - VkImageView* swapchain_image_views = nullptr; + std::vector swapchain_images; + std::vector swapchain_image_views; u32 swapchain_images_count = 0; VkSemaphore present_complete_semaphore = nullptr; VkFence present_complete_fence = nullptr; @@ -65,8 +65,8 @@ struct WindowCtx { SDL_Window* m_window = nullptr; bool is_window_hidden = true; VkSurfaceKHR m_surface = nullptr; - VulkanSurfaceCapabilities* m_surface_capabilities = nullptr; - VulkanSwapchain* swapchain = nullptr; + VulkanSurfaceCapabilities m_surface_capabilities; + VulkanSwapchain swapchain; }; struct EmuPrivate { @@ -78,10 +78,11 @@ struct EmuPrivate { u32 m_screen_width = {0}; u32 m_screen_height = {0}; }; + void emuInit(u32 width, u32 height); void emuRun(); void checkAndWaitForGraphicsInit(); HLE::Libs::Graphics::GraphicCtx* getGraphicCtx(); void DrawBuffer(HLE::Libs::Graphics::VideoOutVulkanImage* image); void keyboardEvent(SDL_Event* event); -} // namespace Emulator \ No newline at end of file +} // namespace Emulator diff --git a/src/vulkan_util.cpp b/src/vulkan_util.cpp index 39f5305b..5821944d 100644 --- a/src/vulkan_util.cpp +++ b/src/vulkan_util.cpp @@ -53,10 +53,9 @@ void Graphics::Vulkan::vulkanCreate(Emu::WindowCtx* ctx) { std::vector device_extensions = {VK_KHR_SWAPCHAIN_EXTENSION_NAME, VK_EXT_DEPTH_CLIP_ENABLE_EXTENSION_NAME, VK_EXT_COLOR_WRITE_ENABLE_EXTENSION_NAME, "VK_KHR_maintenance1"}; - ctx->m_surface_capabilities = new Emu::VulkanSurfaceCapabilities{}; Emu::VulkanQueues queues; - vulkanFindCompatiblePhysicalDevice(ctx->m_graphic_ctx.m_instance, ctx->m_surface, device_extensions, ctx->m_surface_capabilities, + vulkanFindCompatiblePhysicalDevice(ctx->m_graphic_ctx.m_instance, ctx->m_surface, device_extensions, &ctx->m_surface_capabilities, &ctx->m_graphic_ctx.m_physical_device, &queues); if (ctx->m_graphic_ctx.m_physical_device == nullptr) { @@ -79,18 +78,17 @@ void Graphics::Vulkan::vulkanCreate(Emu::WindowCtx* ctx) { ctx->swapchain = vulkanCreateSwapchain(&ctx->m_graphic_ctx, 2); } -Emu::VulkanSwapchain* Graphics::Vulkan::vulkanCreateSwapchain(HLE::Libs::Graphics::GraphicCtx* ctx, u32 image_count) { - auto* window_ctx = singleton::instance(); - auto* s = new Emu::VulkanSwapchain; +Emu::VulkanSwapchain Graphics::Vulkan::vulkanCreateSwapchain(HLE::Libs::Graphics::GraphicCtx* ctx, u32 image_count) { + auto window_ctx = singleton::instance(); + const auto& capabilities = window_ctx->m_surface_capabilities.capabilities; + Emu::VulkanSwapchain s{}; VkExtent2D extent{}; - extent.width = clamp(ctx->screen_width, window_ctx->m_surface_capabilities->capabilities.minImageExtent.width, - window_ctx->m_surface_capabilities->capabilities.maxImageExtent.width); - extent.height = clamp(ctx->screen_height, window_ctx->m_surface_capabilities->capabilities.minImageExtent.height, - window_ctx->m_surface_capabilities->capabilities.maxImageExtent.height); - - image_count = clamp(image_count, window_ctx->m_surface_capabilities->capabilities.minImageCount, - window_ctx->m_surface_capabilities->capabilities.maxImageCount); + extent.width = std::clamp(ctx->screen_width, capabilities.minImageExtent.width, + capabilities.maxImageExtent.width); + extent.height = std::clamp(ctx->screen_height, capabilities.minImageExtent.height, + capabilities.maxImageExtent.height); + image_count = std::clamp(image_count, capabilities.minImageCount, capabilities.maxImageCount); VkSwapchainCreateInfoKHR create_info{}; create_info.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; @@ -99,15 +97,15 @@ Emu::VulkanSwapchain* Graphics::Vulkan::vulkanCreateSwapchain(HLE::Libs::Graphic create_info.surface = window_ctx->m_surface; create_info.minImageCount = image_count; - if (window_ctx->m_surface_capabilities->is_format_unorm_bgra32) { + if (window_ctx->m_surface_capabilities.is_format_unorm_bgra32) { create_info.imageFormat = VK_FORMAT_B8G8R8A8_UNORM; create_info.imageColorSpace = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR; - } else if (window_ctx->m_surface_capabilities->is_format_srgb_bgra32) { + } else if (window_ctx->m_surface_capabilities.is_format_srgb_bgra32) { create_info.imageFormat = VK_FORMAT_B8G8R8A8_SRGB; create_info.imageColorSpace = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR; } else { - create_info.imageFormat = window_ctx->m_surface_capabilities->formats.at(0).format; - create_info.imageColorSpace = window_ctx->m_surface_capabilities->formats.at(0).colorSpace; + create_info.imageFormat = window_ctx->m_surface_capabilities.formats.at(0).format; + create_info.imageColorSpace = window_ctx->m_surface_capabilities.formats.at(0).colorSpace; } create_info.imageExtent = extent; @@ -116,31 +114,31 @@ Emu::VulkanSwapchain* Graphics::Vulkan::vulkanCreateSwapchain(HLE::Libs::Graphic create_info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; create_info.queueFamilyIndexCount = 0; create_info.pQueueFamilyIndices = nullptr; - create_info.preTransform = window_ctx->m_surface_capabilities->capabilities.currentTransform; + create_info.preTransform = window_ctx->m_surface_capabilities.capabilities.currentTransform; create_info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; create_info.presentMode = VK_PRESENT_MODE_FIFO_KHR; create_info.clipped = VK_TRUE; create_info.oldSwapchain = nullptr; - s->swapchain_format = create_info.imageFormat; - s->swapchain_extent = extent; + s.swapchain_format = create_info.imageFormat; + s.swapchain_extent = extent; - vkCreateSwapchainKHR(ctx->m_device, &create_info, nullptr, &s->swapchain); + vkCreateSwapchainKHR(ctx->m_device, &create_info, nullptr, &s.swapchain); - vkGetSwapchainImagesKHR(ctx->m_device, s->swapchain, &s->swapchain_images_count, nullptr); + vkGetSwapchainImagesKHR(ctx->m_device, s.swapchain, &s.swapchain_images_count, nullptr); - s->swapchain_images = new VkImage[s->swapchain_images_count]; - vkGetSwapchainImagesKHR(ctx->m_device, s->swapchain, &s->swapchain_images_count, s->swapchain_images); + s.swapchain_images.resize(s.swapchain_images_count); + vkGetSwapchainImagesKHR(ctx->m_device, s.swapchain, &s.swapchain_images_count, s.swapchain_images.data()); - s->swapchain_image_views = new VkImageView[s->swapchain_images_count]; - for (uint32_t i = 0; i < s->swapchain_images_count; i++) { + s.swapchain_image_views.resize(s.swapchain_images_count); + for (uint32_t i = 0; i < s.swapchain_images_count; i++) { VkImageViewCreateInfo create_info{}; create_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; create_info.pNext = nullptr; create_info.flags = 0; - create_info.image = (s->swapchain_images)[i]; + create_info.image = s.swapchain_images[i]; create_info.viewType = VK_IMAGE_VIEW_TYPE_2D; - create_info.format = s->swapchain_format; + create_info.format = s.swapchain_format; create_info.components.r = VK_COMPONENT_SWIZZLE_IDENTITY; create_info.components.g = VK_COMPONENT_SWIZZLE_IDENTITY; create_info.components.b = VK_COMPONENT_SWIZZLE_IDENTITY; @@ -151,28 +149,28 @@ Emu::VulkanSwapchain* Graphics::Vulkan::vulkanCreateSwapchain(HLE::Libs::Graphic create_info.subresourceRange.layerCount = 1; create_info.subresourceRange.levelCount = 1; - vkCreateImageView(ctx->m_device, &create_info, nullptr, &((s->swapchain_image_views)[i])); + vkCreateImageView(ctx->m_device, &create_info, nullptr, &s.swapchain_image_views[i]); } - if (s->swapchain == nullptr) { + if (s.swapchain == nullptr) { LOG_CRITICAL_IF(log_file_vulkanutil, "Could not create swapchain\n"); std::exit(0); } - s->current_index = static_cast(-1); + s.current_index = static_cast(-1); VkSemaphoreCreateInfo present_complete_info{}; present_complete_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; present_complete_info.pNext = nullptr; present_complete_info.flags = 0; - auto result = vkCreateSemaphore(ctx->m_device, &present_complete_info, nullptr, &s->present_complete_semaphore); + auto result = vkCreateSemaphore(ctx->m_device, &present_complete_info, nullptr, &s.present_complete_semaphore); VkFenceCreateInfo fence_info{}; fence_info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; fence_info.pNext = nullptr; fence_info.flags = 0; - result = vkCreateFence(ctx->m_device, &fence_info, nullptr, &s->present_complete_fence); + result = vkCreateFence(ctx->m_device, &fence_info, nullptr, &s.present_complete_fence); if (result != VK_SUCCESS) { LOG_CRITICAL_IF(log_file_vulkanutil, "Can't create vulkan fence\n"); std::exit(0); @@ -187,7 +185,7 @@ void Graphics::Vulkan::vulkanCreateQueues(HLE::Libs::Graphics::GraphicCtx* ctx, ctx->queues[id].index = info.index; vkGetDeviceQueue(ctx->m_device, ctx->queues[id].family, ctx->queues[id].index, &ctx->queues[id].vk_queue); if (with_mutex) { - ctx->queues[id].mutex = new std::mutex; + ctx->queues[id].mutex = std::make_unique(); } }; diff --git a/src/vulkan_util.h b/src/vulkan_util.h index 6230e76b..bd1fdda8 100644 --- a/src/vulkan_util.h +++ b/src/vulkan_util.h @@ -19,13 +19,6 @@ constexpr int VULKAN_QUEUE_GFX = 8; constexpr int VULKAN_QUEUE_UTIL = 9; constexpr int VULKAN_QUEUE_PRESENT = 10; -template -const T& clamp(const T& x, const T& min, const T& max) { - if (x < min) return min; - if (x > max) return max; - return x; -} - void vulkanCreate(Emu::WindowCtx* ctx); void vulkanGetInstanceExtensions(Emu::VulkanExt* ext); void vulkanFindCompatiblePhysicalDevice(VkInstance instance, VkSurfaceKHR surface, const std::vector& device_extensions, @@ -36,7 +29,7 @@ VkDevice vulkanCreateDevice(VkPhysicalDevice physical_device, VkSurfaceKHR surfa Emu::VulkanQueues vulkanFindQueues(VkPhysicalDevice device, VkSurfaceKHR surface); void vulkanGetSurfaceCapabilities(VkPhysicalDevice physical_device, VkSurfaceKHR surface, Emu::VulkanSurfaceCapabilities* surfaceCap); void vulkanCreateQueues(HLE::Libs::Graphics::GraphicCtx* ctx, const Emu::VulkanQueues& queues); -Emu::VulkanSwapchain* vulkanCreateSwapchain(HLE::Libs::Graphics::GraphicCtx* ctx, u32 image_count); +Emu::VulkanSwapchain vulkanCreateSwapchain(HLE::Libs::Graphics::GraphicCtx* ctx, u32 image_count); void vulkanBlitImage(GPU::CommandBuffer* buffer, HLE::Libs::Graphics::VulkanImage* src_image, Emu::VulkanSwapchain* dst_swapchain); void vulkanFillImage(HLE::Libs::Graphics::GraphicCtx* ctx, HLE::Libs::Graphics::VulkanImage* dst_image, const void* src_data, u64 size, u32 src_pitch, u64 dst_layout); @@ -44,4 +37,4 @@ void vulkanBufferToImage(GPU::CommandBuffer* buffer, HLE::Libs::Graphics::Vulkan HLE::Libs::Graphics::VulkanImage* dst_image, u64 dst_layout); void vulkanCreateBuffer(HLE::Libs::Graphics::GraphicCtx* ctx, u64 size, HLE::Libs::Graphics::VulkanBuffer* buffer); void vulkanDeleteBuffer(HLE::Libs::Graphics::GraphicCtx* ctx, HLE::Libs::Graphics::VulkanBuffer* buffer); -}; // namespace Graphics::Vulkan \ No newline at end of file +}; // namespace Graphics::Vulkan From 0021e68aab95b8b916244466b3168c8b87821132 Mon Sep 17 00:00:00 2001 From: GPUCode Date: Thu, 26 Oct 2023 23:46:05 +0300 Subject: [PATCH 7/7] vulkan: Remove orphan new part 2 --- src/Core/PS4/GPU/video_out_buffer.cpp | 9 ++-- src/Core/PS4/HLE/Graphics/graphics_ctx.h | 9 ++-- src/Core/PS4/HLE/Graphics/graphics_render.cpp | 51 +++++++------------ src/Core/PS4/HLE/Graphics/graphics_render.h | 14 ++--- 4 files changed, 36 insertions(+), 47 deletions(-) diff --git a/src/Core/PS4/GPU/video_out_buffer.cpp b/src/Core/PS4/GPU/video_out_buffer.cpp index 21d825b9..339b5960 100644 --- a/src/Core/PS4/GPU/video_out_buffer.cpp +++ b/src/Core/PS4/GPU/video_out_buffer.cpp @@ -23,13 +23,12 @@ static void update_func(HLE::Libs::Graphics::GraphicCtx* ctx, const u64* params, if (tiled) { - auto* tempbuff = new u08[*size]; - GPU::convertTileToLinear(tempbuff, reinterpret_cast(*virtual_addr), width, height, neo); - Graphics::Vulkan::vulkanFillImage(ctx, vk_obj, tempbuff, *size, pitch, static_cast(VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL)); - delete[] tempbuff; + std::vector tempbuff(*size); + GPU::convertTileToLinear(tempbuff.data(), reinterpret_cast(*virtual_addr), width, height, neo); + Graphics::Vulkan::vulkanFillImage(ctx, vk_obj, tempbuff.data(), *size, pitch, static_cast(VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL)); } else { Graphics::Vulkan::vulkanFillImage(ctx, vk_obj, reinterpret_cast(*virtual_addr), *size, pitch, - static_cast(VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL)); + static_cast(VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL)); } } diff --git a/src/Core/PS4/HLE/Graphics/graphics_ctx.h b/src/Core/PS4/HLE/Graphics/graphics_ctx.h index 4496b5ea..1196d0b0 100644 --- a/src/Core/PS4/HLE/Graphics/graphics_ctx.h +++ b/src/Core/PS4/HLE/Graphics/graphics_ctx.h @@ -1,6 +1,7 @@ #pragma once #include +#include #include #include @@ -9,10 +10,10 @@ namespace HLE::Libs::Graphics { struct VulkanCommandPool { std::mutex mutex; VkCommandPool pool = nullptr; - VkCommandBuffer* buffers = nullptr; - VkFence* fences = nullptr; - VkSemaphore* semaphores = nullptr; - bool* busy = nullptr; + std::vector buffers; + std::vector fences; + std::vector semaphores; + std::vector busy; u32 buffers_count = 0; }; diff --git a/src/Core/PS4/HLE/Graphics/graphics_render.cpp b/src/Core/PS4/HLE/Graphics/graphics_render.cpp index 22829e7c..63e68f3a 100644 --- a/src/Core/PS4/HLE/Graphics/graphics_render.cpp +++ b/src/Core/PS4/HLE/Graphics/graphics_render.cpp @@ -130,47 +130,45 @@ void GPU::CommandPool::createPool(int id) { auto* render_ctx = singleton::instance(); auto* ctx = render_ctx->getGraphicCtx(); - m_pool[id] = new HLE::Libs::Graphics::VulkanCommandPool; - VkCommandPoolCreateInfo pool_info{}; pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; pool_info.pNext = nullptr; pool_info.queueFamilyIndex = ctx->queues[id].family; pool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; - vkCreateCommandPool(ctx->m_device, &pool_info, nullptr, &m_pool[id]->pool); + vkCreateCommandPool(ctx->m_device, &pool_info, nullptr, &m_pool[id].pool); - if (m_pool[id]->pool == nullptr) { + if (!m_pool[id].pool) { fmt::print("pool is nullptr"); std::exit(0); } - m_pool[id]->buffers_count = 4; - m_pool[id]->buffers = new VkCommandBuffer[m_pool[id]->buffers_count]; - m_pool[id]->fences = new VkFence[m_pool[id]->buffers_count]; - m_pool[id]->semaphores = new VkSemaphore[m_pool[id]->buffers_count]; - m_pool[id]->busy = new bool[m_pool[id]->buffers_count]; + m_pool[id].buffers_count = 4; + m_pool[id].buffers.resize(m_pool[id].buffers_count); + m_pool[id].fences.resize(m_pool[id].buffers_count); + m_pool[id].semaphores.resize(m_pool[id].buffers_count); + m_pool[id].busy.resize(m_pool[id].buffers_count); VkCommandBufferAllocateInfo alloc_info{}; alloc_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; - alloc_info.commandPool = m_pool[id]->pool; + alloc_info.commandPool = m_pool[id].pool; alloc_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; - alloc_info.commandBufferCount = m_pool[id]->buffers_count; + alloc_info.commandBufferCount = m_pool[id].buffers_count; - if (vkAllocateCommandBuffers(ctx->m_device, &alloc_info, m_pool[id]->buffers) != VK_SUCCESS) { + if (vkAllocateCommandBuffers(ctx->m_device, &alloc_info, m_pool[id].buffers.data()) != VK_SUCCESS) { fmt::print("Can't allocate command buffers\n"); std::exit(0); } - for (uint32_t i = 0; i < m_pool[id]->buffers_count; i++) { - m_pool[id]->busy[i] = false; + for (u32 i = 0; i < m_pool[id].buffers_count; i++) { + m_pool[id].busy[i] = false; VkFenceCreateInfo fence_info{}; fence_info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; fence_info.pNext = nullptr; fence_info.flags = 0; - if (vkCreateFence(ctx->m_device, &fence_info, nullptr, &m_pool[id]->fences[i]) != VK_SUCCESS) { + if (vkCreateFence(ctx->m_device, &fence_info, nullptr, &m_pool[id].fences[i]) != VK_SUCCESS) { fmt::print("Can't create fence\n"); std::exit(0); } @@ -180,7 +178,7 @@ void GPU::CommandPool::createPool(int id) { semaphore_info.pNext = nullptr; semaphore_info.flags = 0; - if (vkCreateSemaphore(ctx->m_device, &semaphore_info, nullptr, &m_pool[id]->semaphores[i]) != VK_SUCCESS) { + if (vkCreateSemaphore(ctx->m_device, &semaphore_info, nullptr, &m_pool[id].semaphores[i]) != VK_SUCCESS) { fmt::print("Can't create semas\n"); std::exit(0); } @@ -192,23 +190,12 @@ void GPU::CommandPool::deleteAllPool() { auto* ctx = render_ctx->getGraphicCtx(); for (auto& pool : m_pool) { - if (pool != nullptr) { - for (uint32_t i = 0; i < pool->buffers_count; i++) { - vkDestroySemaphore(ctx->m_device, pool->semaphores[i], nullptr); - vkDestroyFence(ctx->m_device, pool->fences[i], nullptr); + if (pool.pool) { + for (u32 i = 0; i < pool.buffers_count; i++) { + vkDestroySemaphore(ctx->m_device, pool.semaphores[i], nullptr); + vkDestroyFence(ctx->m_device, pool.fences[i], nullptr); } - - vkFreeCommandBuffers(ctx->m_device, pool->pool, pool->buffers_count, pool->buffers); - - vkDestroyCommandPool(ctx->m_device, pool->pool, nullptr); - - delete[] pool->semaphores; - delete[] pool->fences; - delete[] pool->buffers; - delete[] pool->busy; - - delete pool; - pool = nullptr; + vkDestroyCommandPool(ctx->m_device, pool.pool, nullptr); } } } diff --git a/src/Core/PS4/HLE/Graphics/graphics_render.h b/src/Core/PS4/HLE/Graphics/graphics_render.h index b98197de..c85f3948 100644 --- a/src/Core/PS4/HLE/Graphics/graphics_render.h +++ b/src/Core/PS4/HLE/Graphics/graphics_render.h @@ -1,4 +1,6 @@ #pragma once + +#include #include "graphics_ctx.h" namespace GPU { @@ -9,17 +11,17 @@ class CommandPool { ~CommandPool() {} HLE::Libs::Graphics::VulkanCommandPool* getPool(int id) { - if (m_pool[id] == nullptr) { + if (!m_pool[id].pool) { createPool(id); } - return m_pool[id]; + return &m_pool[id]; } private: void createPool(int id); void deleteAllPool(); - HLE::Libs::Graphics::VulkanCommandPool* m_pool[11] = {}; + std::array m_pool{}; }; class CommandBuffer { public: @@ -48,16 +50,16 @@ class Framebuffer { }; class RenderCtx { public: - RenderCtx() : m_framebuffer(new Framebuffer) {} + RenderCtx() = default; virtual ~RenderCtx() {} void setGraphicCtx(HLE::Libs::Graphics::GraphicCtx* ctx) { m_graphic_ctx = ctx; } HLE::Libs::Graphics::GraphicCtx* getGraphicCtx() { return m_graphic_ctx; } private: - Framebuffer* m_framebuffer = nullptr; + Framebuffer m_framebuffer{}; HLE::Libs::Graphics::GraphicCtx* m_graphic_ctx = nullptr; }; void renderCreateCtx(); -}; // namespace GPU \ No newline at end of file +}; // namespace GPU