Merge pull request #62 from GPUCode/new-elf

code: Rework elf loader and general cleanup
This commit is contained in:
georgemoralis 2023-10-27 09:44:30 +03:00 committed by GitHub
commit b3cc2efdb2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
20 changed files with 829 additions and 1073 deletions

View File

@ -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<const u08> 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

View File

@ -1,62 +1,87 @@
#pragma once
#include <bit>
#include <cstdio>
#include <string>
#include <span>
#include <vector>
#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<const u08> data);
bool seek(s64 offset, SeekMode mode);
u64 getFileSize();
u64 tell() const;
return "r";
}
template <typename T>
bool read(T& data) const {
return read(&data, sizeof(T));
}
const int getSeekMode(fsSeekMode mode)
{
switch (mode) {
case fsSeekSet: return SEEK_SET;
case fsSeekCur: return SEEK_CUR;
case fsSeekEnd: return SEEK_END;
}
template <typename T>
bool read(std::vector<T>& 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

View File

@ -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<void*>(*virtual_addr), width, height, neo);
Graphics::Vulkan::vulkanFillImage(ctx, vk_obj, tempbuff, *size, pitch, static_cast<uint64_t>(VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL));
delete[] tempbuff;
std::vector<u08> tempbuff(*size);
GPU::convertTileToLinear(tempbuff.data(), reinterpret_cast<void*>(*virtual_addr), width, height, neo);
Graphics::Vulkan::vulkanFillImage(ctx, vk_obj, tempbuff.data(), *size, pitch, static_cast<u64>(VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL));
} else {
Graphics::Vulkan::vulkanFillImage(ctx, vk_obj, reinterpret_cast<void*>(*virtual_addr), *size, pitch,
static_cast<uint64_t>(VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL));
static_cast<u64>(VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL));
}
}

View File

@ -1,6 +1,7 @@
#pragma once
#include <types.h>
#include <vector>
#include <vulkan/vulkan_core.h>
#include <mutex>
@ -9,15 +10,15 @@ 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<VkCommandBuffer> buffers;
std::vector<VkFence> fences;
std::vector<VkSemaphore> semaphores;
std::vector<bool> busy;
u32 buffers_count = 0;
};
struct VulkanQueueInfo {
std::mutex* mutex = nullptr;
std::unique_ptr<std::mutex> mutex{};
u32 family = static_cast<u32>(-1);
u32 index = static_cast<u32>(-1);
VkQueue vk_queue = nullptr;

View File

@ -1,5 +1,5 @@
#include "graphics_render.h"
#include <fmt/core.h>
#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);
}
}
@ -130,48 +130,46 @@ void GPU::CommandPool::createPool(int id) {
auto* render_ctx = singleton<RenderCtx>::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) {
printf("pool is 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) {
printf("Can't allocate command buffers\n");
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) {
printf("Can't create fence\n");
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,8 +178,8 @@ 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) {
printf("Can't create semas\n");
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);
}
}
}

View File

@ -1,4 +1,6 @@
#pragma once
#include <array>
#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<HLE::Libs::Graphics::VulkanCommandPool, 11> m_pool{};
};
class CommandBuffer {
public:
@ -48,14 +50,14 @@ 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;
};

View File

@ -1,7 +1,8 @@
#include "Linker.h"
#include "../virtual_memory.h"
#include <Util/log.h>
#include "../../Util/Disassembler.h"
#include <fmt/core.h>
#include "Zydis.h"
#include <Util/string_util.h>
#include "Util/aerolib.h"
#include "Loader/SymbolsResolver.h"
@ -12,103 +13,92 @@ constexpr bool debug_loader = true;
static u64 g_load_addr = SYSTEM_RESERVED + CODE_BASE_OFFSET;
Linker::Linker()
static u64 get_aligned_size(const elf_program_header& phdr)
{
m_HLEsymbols = new SymbolsResolver;
return (phdr.p_align != 0 ? (phdr.p_memsz + (phdr.p_align - 1)) & ~(phdr.p_align - 1) : phdr.p_memsz);
}
Linker::~Linker()
static u64 calculate_base_size(const elf_header& ehdr, std::span<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);
}
static u64 calculate_base_size(const elf_header* ehdr, const elf_program_header* phdr)
{
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))
{
auto phdrh = phdr + i;
u64 last_addr = phdr[i].p_vaddr + get_aligned_size(phdrh);
if (last_addr > base_size)
{
base_size = last_addr;
}
}
}
return base_size;
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))
{
u64 last_addr = phdr[i].p_vaddr + get_aligned_size(phdr[i]);
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<u16>(nVal >> 6u) & 0x3fu];
enc += pCodes[nVal & 0x3fu];
}
else
{
enc += pCodes[static_cast<u16>(nVal >> 12u) & 0x3fu];
enc += pCodes[static_cast<u16>(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<u16>(nVal >> 6u) & 0x3fu];
enc += pCodes[nVal & 0x3fu];
}
else
{
enc += pCodes[static_cast<u16>(nVal >> 12u) & 0x3fu];
enc += pCodes[static_cast<u16>(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 = new Elf;
m->elf->Open(elf_name);//load elf
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)
{
//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<u64>(0x1000) - 1)) + 0x1000;//align base size to 0x1000 block size (TODO is that the default block size or it can be changed?
@ -120,9 +110,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 +120,51 @@ 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<u64>(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<u64>(m->m_dynamic.data()), elf_pheader[i].p_offset, elf_pheader[i].p_filesz);
}
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<u64>(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<u64>(m->m_dynamic_data.data()), elf_pheader[i].p_offset, elf_pheader[i].p_filesz);
}
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<uint8_t*>(m->elf->GetElfEntry() + m->base_virtual_addr);
ZyanU64 runtime_address = m->elf->GetElfEntry() + m->base_virtual_addr;
auto* rt1 = reinterpret_cast<uint8_t*>(m->elf.GetElfEntry() + m->base_virtual_addr);
ZyanU64 runtime_address = m->elf.GetElfEntry() + m->base_virtual_addr;
// Loop over the instructions in our buffer.
ZyanUSize offset = 0;
@ -188,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;
}
@ -196,107 +184,105 @@ void Linker::LoadModuleToMemory(Module* m)
void Linker::LoadDynamicInfo(Module* m)
{
m->dynamic_info = new DynamicModuleInfo;
for (const auto* dyn = static_cast<elf_dynamic*>(m->m_dynamic); dyn->d_tag != DT_NULL; dyn++)
for (const auto* dyn = reinterpret_cast<elf_dynamic*>(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<void*>(static_cast<uint8_t*>(m->m_dynamic_data) + dyn->d_un.d_ptr);
m->dynamic_info.hash_table = reinterpret_cast<void*>(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<char*>(static_cast<uint8_t*>(m->m_dynamic_data) + dyn->d_un.d_ptr);
m->dynamic_info.str_table = reinterpret_cast<char*>(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<elf_symbol*>(static_cast<uint8_t*>(m->m_dynamic_data) + dyn->d_un.d_ptr);
m->dynamic_info.symbol_table = reinterpret_cast<elf_symbol*>(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<elf_relocation*>(static_cast<uint8_t*>(m->m_dynamic_data) + dyn->d_un.d_ptr);
m->dynamic_info.jmp_relocation_table = reinterpret_cast<elf_relocation*>(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<elf_relocation*>(static_cast<uint8_t*>(m->m_dynamic_data) + dyn->d_un.d_ptr);
m->dynamic_info.relocation_table = reinterpret_cast<elf_relocation*>(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
{
@ -307,18 +293,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:
@ -332,15 +318,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:
@ -351,9 +337,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:
@ -365,9 +351,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)
{
@ -375,9 +361,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)
{
@ -390,9 +376,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)
{
@ -400,9 +386,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)
{
@ -415,19 +401,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<uint8_t*>(sym) < reinterpret_cast<uint8_t*>(m->dynamic_info->symbol_table) + m->dynamic_info->symbol_table_total_size;
for (auto* sym = m->dynamic_info.symbol_table;
reinterpret_cast<uint8_t*>(sym) < reinterpret_cast<uint8_t*>(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
{
@ -491,11 +475,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);
}
@ -508,8 +492,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;
@ -517,7 +501,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:
@ -548,7 +531,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;
@ -582,12 +564,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<u08*>(rel) < reinterpret_cast<u08*>(m->dynamic_info->relocation_table) + m->dynamic_info->relocation_table_size; rel++, idx++)
for (auto* rel = m->dynamic_info.relocation_table; reinterpret_cast<u08*>(rel) < reinterpret_cast<u08*>(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<u08*>(rel) < reinterpret_cast<u08*>(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<u08*>(rel) < reinterpret_cast<u08*>(m->dynamic_info.jmp_relocation_table) + m->dynamic_info.jmp_relocation_table_size; rel++, idx++)
{
relocate(idx, rel, m, true);
}
@ -612,10 +594,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 {
@ -646,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) {
@ -681,6 +660,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);
}

View File

@ -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 = nullptr;
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<const char*> needed;
std::vector<ModuleInfo> import_modules;
std::vector<ModuleInfo> export_modules;
std::vector<LibraryInfo> import_libs;
std::vector<LibraryInfo> export_libs;
std::string filename;//filename with absolute path
std::vector<const char*> needed;
std::vector<ModuleInfo> import_modules;
std::vector<ModuleInfo> export_modules;
std::vector<LibraryInfo> import_libs;
std::vector<LibraryInfo> 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<u08> m_dynamic;
std::vector<u08> 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<Module*> m_modules;
SymbolsResolver* m_HLEsymbols = nullptr;
std::vector<Module> m_modules;
SymbolsResolver m_hle_symbols{};
std::mutex m_mutex;
};

View File

@ -1,139 +1,188 @@
#include "Elf.h"
#include <Util/log.h>
#include <debug.h>
#include <bit>
#include <fmt/core.h>
#include <spdlog/pattern_formatter.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <spdlog/sinks/basic_file_sink.h>
#include <spdlog/spdlog.h>
#include <magic_enum.hpp>
#include <debug.h>
#include "Elf.h"
#include "spdlog/sinks/basic_file_sink.h"
#include "spdlog/spdlog.h"
constexpr bool debug_elf = true;
template <>
struct magic_enum::customize::enum_range<e_type_s> {
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]<typename T>(std::vector<T>& 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<u32>(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<u32>(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<u32>(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<u32>(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<u32>(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<u32>(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<u32>(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<u32>(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<u32>(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<program_type_es>(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<ident_class_es>(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<ident_endian_es>(m_elf_header->e_ident.ei_data);
if (ident_data.has_value()) {
header += fmt::format("ident data .......: {}\n", magic_enum::enum_name(ident_data.value()));
}
auto ident_version = magic_enum::enum_cast<ident_version_es>(m_elf_header->e_ident.ei_version);
if (ident_version.has_value()) {
header += fmt::format("ident version.....: {}\n", magic_enum::enum_name(ident_version.value()));
}
auto ident_osabi = magic_enum::enum_cast<ident_osabi_es>(m_elf_header->e_ident.ei_osabi);
if (ident_osabi.has_value()) {
header += fmt::format("ident osabi .....: {}\n", magic_enum::enum_name(ident_osabi.value()));
}
auto ident_abiversion = magic_enum::enum_cast<ident_abiversion_es>(m_elf_header->e_ident.ei_abiversion);
if (ident_abiversion.has_value()) {
header += fmt::format("ident abiversion..: {}\n", magic_enum::enum_name(ident_abiversion.value()));
}
header += fmt::format("ident 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<e_type_s>(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<e_machine_es>(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<e_version_es>(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<u32>(m_elf_header.e_type));
header += fmt::format("machine ..........: {}\n", static_cast<u32>(m_elf_header.e_machine));
header += fmt::format("version ..........: {}\n", static_cast<u32>(m_elf_header.e_version));
header += fmt::format("entry ............: {:#018x}\n", m_elf_header.e_entry);
header += fmt::format("phoff ............: {:#018x}\n", m_elf_header.e_phoff);
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<elf_program_flags>((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<u32>(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<void*>(static_cast<uintptr_t>(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<void*>(static_cast<uintptr_t>(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<void*>(static_cast<uintptr_t>(virtual_addr)), size);
return;
}
}
BREAKPOINT(); // hmm we didn't return something...
} else {
// it's elf file
m_f->Seek(file_offset, fsSeekMode::fsSeekSet);
m_f->Read(reinterpret_cast<void*>(static_cast<uintptr_t>(virtual_addr)), size);
}
BREAKPOINT(); // Hmm we didn't return something...
}
u64 Elf::GetElfEntry() { return m_elf_header->e_entry; }

View File

@ -1,6 +1,10 @@
#pragma once
#include <string>
#include <inttypes.h>
#include <cinttypes>
#include <span>
#include <vector>
#include "../../../types.h"
#include "../../FsFile.h"
@ -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;
@ -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<const elf_program_header> GetProgramHeader() const {
return m_elf_phdr;
}
[[nodiscard]] std::span<const self_segment_header> GetSegmentHeader() const {
return m_self_segments;
}
[[nodiscard]] u64 GetElfEntry() const {
return m_elf_header.e_entry;
}
std::string SElfHeaderStr();
std::string 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<self_segment_header> m_self_segments;
elf_header m_elf_header{};
std::vector<elf_program_header> m_elf_phdr;
std::vector<elf_section_header> m_elf_shdr;
elf_program_id_header m_self_id_header{};
};

View File

@ -2,7 +2,6 @@
#include "SymbolsResolver.h"
#include <Util/log.h>
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;
}

View File

@ -1,24 +1,21 @@
#pragma once
#include <cstdlib>
#include <new>
#include <memory>
template <class T>
class singleton {
public:
public:
static T* instance() {
if (!m_instance) {
m_instance = static_cast<T*>(std::malloc(sizeof(T)));
new (m_instance) T;
m_instance = std::make_unique<T>();
}
return m_instance;
return m_instance.get();
}
protected:
protected:
singleton();
~singleton();
private:
static inline T* m_instance = nullptr;
private:
static inline std::unique_ptr<T> m_instance{};
};

View File

@ -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,7 +47,7 @@ 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())
@ -55,10 +55,10 @@ void ElfViewer::display(bool enabled)
}
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,18 +82,18 @@ 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();

View File

@ -1,6 +1,5 @@
#include "Disassembler.h"
#include <stdio.h>
#include <fmt/format.h>
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);
fmt::print("instruction: {}\n", szBuffer);
}

View File

@ -2,6 +2,7 @@
#include <fstream>
#include <string>
#include <fmt/core.h>
#include <toml11/toml.hpp>
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<toml::preserve_comments>(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;

View File

@ -1,5 +1,5 @@
#include "emulator.h"
#include <fmt/core.h>
#include <Core/PS4/HLE/Graphics/graphics_render.h>
#include <Emulator/Host/controller.h>
#include "Emulator/Util/singleton.h"
@ -33,7 +33,7 @@ static void CreateSdlWindow(WindowCtx* ctx) {
int height = static_cast<int>(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);
}
@ -109,39 +109,35 @@ void DrawBuffer(HLE::Libs::Graphics::VideoOutVulkanImage* image) {
window_ctx->is_window_hidden = false;
}
window_ctx->swapchain->current_index = static_cast<u32>(-1);
window_ctx->swapchain.current_index = static_cast<u32>(-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) {
printf("Can't aquireNextImage\n");
fmt::print("Can't aquireNextImage\n");
std::exit(0);
}
if (window_ctx->swapchain->current_index == static_cast<u32>(-1)) {
printf("Unsupported:swapchain current index is -1\n");
if (window_ctx->swapchain.current_index == static_cast<u32>(-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) {
printf("vkWaitForFences is not success\n");
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) {
printf("blt_src_image is null\n");
std::exit(0);
}
if (blt_dst_image == nullptr) {
printf("blt_dst_image is null\n");
fmt::print("blt_src_image is null\n");
std::exit(0);
}
@ -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;
@ -187,13 +183,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);
}
}

View File

@ -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<VkImage> swapchain_images;
std::vector<VkImageView> 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,6 +78,7 @@ struct EmuPrivate {
u32 m_screen_width = {0};
u32 m_screen_height = {0};
};
void emuInit(u32 width, u32 height);
void emuRun();
void checkAndWaitForGraphicsInit();

View File

@ -1,38 +1,14 @@
// 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 <SDL3/SDL.h>
#include <stdio.h>
#include "imgui.h"
#include "imgui_impl_opengl3.h"
#include "imgui_impl_sdl3.h"
#if defined(IMGUI_IMPL_OPENGL_ES2)
#include <SDL3/SDL_opengles2.h>
#else
#include <SDL3/SDL_opengl.h>
#endif
#include <Util/log.h>
#include "GUI/ElfViewer.h"
#include "spdlog/spdlog.h"
#include <cstdio>
#include <fmt/core.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 "Util/log.h"
#include <Core/PS4/HLE/Graphics/video_out.h>
#include <Util/config.h>
#include <Zydis/Zydis.h>
#include <emulator.h>
#include <inttypes.h>
#include <stdio.h>
#include <cinttypes>
#include <thread>
#include "Core/PS4/HLE/Libs.h"
#include "Core/PS4/Linker.h"
#include "Emulator/Util\singleton.h"
@ -41,7 +17,7 @@
// Main code
int main(int argc, char* argv[]) {
if (argc == 1) {
printf("Usage: %s <elf or eboot.bin path>\n", argv[0]);
fmt::print("Usage: {} <elf or eboot.bin path>\n", argv[0]);
return -1;
}
Config::load("config.toml");
@ -53,9 +29,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<Linker>::instance();
HLE::Libs::Init_HLE_Libs(linker->getHLESymbols());
auto* module = linker->LoadModule(path); // load main executable
auto linker = singleton<Linker>::instance();
HLE::Libs::Init_HLE_Libs(&linker->getHLESymbols());
linker->LoadModule(path); // Load main executable
std::jthread mainthread(
[](std::stop_token stop_token, void*) {
auto* linker = singleton<Linker>::instance();
@ -67,187 +43,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<Linker>::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;
}

View File

@ -1,5 +1,5 @@
#include "vulkan_util.h"
#include <fmt/core.h>
#include <Core/PS4/GPU/gpu_memory.h>
#include <SDL_vulkan.h>
#include <Emulator/Util/singleton.h>
@ -53,10 +53,9 @@ void Graphics::Vulkan::vulkanCreate(Emu::WindowCtx* ctx) {
std::vector<const char*> 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<Emu::WindowCtx>::instance();
auto* s = new Emu::VulkanSwapchain;
Emu::VulkanSwapchain Graphics::Vulkan::vulkanCreateSwapchain(HLE::Libs::Graphics::GraphicCtx* ctx, u32 image_count) {
auto window_ctx = singleton<Emu::WindowCtx>::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<uint32_t>(-1);
s.current_index = static_cast<uint32_t>(-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<std::mutex>();
}
};
@ -588,7 +586,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);

View File

@ -19,13 +19,6 @@ constexpr int VULKAN_QUEUE_GFX = 8;
constexpr int VULKAN_QUEUE_UTIL = 9;
constexpr int VULKAN_QUEUE_PRESENT = 10;
template <typename T>
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<const char*>& 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);