From 5f0b15e2fa1aa4dec7f45519ffa55d9c7163d0ff Mon Sep 17 00:00:00 2001 From: georgemoralis Date: Wed, 17 May 2023 19:29:05 +0300 Subject: [PATCH] draft work on memory allocation --- CMakeLists.txt | 2 +- src/Core/Memory.cpp | 50 +++++++++++++++++++++++++++++++++++++++++++++ src/Core/Memory.h | 11 ++++++++++ 3 files changed, 62 insertions(+), 1 deletion(-) create mode 100644 src/Core/Memory.cpp create mode 100644 src/Core/Memory.h diff --git a/CMakeLists.txt b/CMakeLists.txt index acdeb680..3b08cb04 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -26,7 +26,7 @@ add_executable(shadps4 src/Loader/Elf.cpp src/Loader/Elf.h src/GUI/ElfViewer.cpp - src/GUI/ElfViewer.h "src/Util/Log.h" "src/Util/Log.cpp") + src/GUI/ElfViewer.h "src/Util/Log.h" "src/Util/Log.cpp" "src/Core/Memory.cpp" "src/Core/Memory.h") find_package(OpenGL REQUIRED) diff --git a/src/Core/Memory.cpp b/src/Core/Memory.cpp new file mode 100644 index 00000000..1420f0db --- /dev/null +++ b/src/Core/Memory.cpp @@ -0,0 +1,50 @@ +#include "../Loader/Elf.h" +#include +#include "../Util/Log.h" + +namespace Memory +{ + + 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; + } + + namespace VirtualMemory { + + u64 memory_alloc(u64 address, u64 size) + { + //TODO it supports only execute_read_write mode + auto ptr = reinterpret_cast(VirtualAlloc(reinterpret_cast(static_cast(address)), + size, + static_cast(MEM_COMMIT) | static_cast(MEM_RESERVE), + PAGE_EXECUTE_READWRITE)); + + if (ptr == 0) + { + auto err = static_cast(GetLastError()); + LOG_ERROR_IF(true,"VirtualAlloc() failed: 0x{:X}\n", err); + } + return ptr; + } + } + +} \ No newline at end of file diff --git a/src/Core/Memory.h b/src/Core/Memory.h new file mode 100644 index 00000000..961415c5 --- /dev/null +++ b/src/Core/Memory.h @@ -0,0 +1,11 @@ +#pragma once + +namespace Memory +{ + static u64 get_aligned_size(const elf_program_header* phdr); + static u64 calculate_base_size(const elf_header* ehdr, const elf_program_header* phdr); + + namespace VirtualMemory { + u64 memory_alloc(u64 address, u64 size); + } +} \ No newline at end of file