From 36dba82c4506119a4e065d5ad7724edf3d6dca1e Mon Sep 17 00:00:00 2001 From: momo5502 Date: Mon, 19 Aug 2024 19:50:48 +0200 Subject: [PATCH] Allocate virtual memory --- src/emulator/main.cpp | 2 +- src/emulator/syscalls.cpp | 51 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) diff --git a/src/emulator/main.cpp b/src/emulator/main.cpp index b766500f..185ca083 100644 --- a/src/emulator/main.cpp +++ b/src/emulator/main.cpp @@ -11,8 +11,8 @@ #define IA32_GS_BASE_MSR 0xC0000101 -#define STACK_ADDRESS 0x7ffffffde000 #define STACK_SIZE 0x40000 +#define STACK_ADDRESS (0x800000000000 - STACK_SIZE) #define KUSD_ADDRESS 0x7ffe0000 diff --git a/src/emulator/syscalls.cpp b/src/emulator/syscalls.cpp index 317490ad..ed30011f 100644 --- a/src/emulator/syscalls.cpp +++ b/src/emulator/syscalls.cpp @@ -242,6 +242,54 @@ namespace uc.reg(UC_X86_REG_RAX, STATUS_SUCCESS); } + + void handle_NtAllocateVirtualMemoryEx(const unicorn& uc) + { + const auto process_handle = uc.reg(UC_X86_REG_R10); + const unicorn_object base_address{uc, uc.reg(UC_X86_REG_RDX)}; + const unicorn_object bytes_to_allocate{uc, uc.reg(UC_X86_REG_R8)}; + //const auto allocation_type = uc.reg(UC_X86_REG_R9D); + const auto page_protection = static_cast(uc.read_stack(5)); + + if (process_handle != ~0ULL) + { + uc.reg(UC_X86_REG_RAX, STATUS_NOT_IMPLEMENTED); + return; + } + + constexpr auto allocation_granularity = 0x10000; + auto allocation_bytes = bytes_to_allocate.read(); + allocation_bytes = align_up(allocation_bytes, allocation_granularity); + bytes_to_allocate.write(allocation_bytes); + + const auto protection = map_nt_to_unicorn_protection(page_protection); + + auto allocate_anywhere = false; + auto allocation_base = base_address.read(); + if (!allocation_base) + { + allocate_anywhere = true; + allocation_base = allocation_granularity; + } + + bool succeeded = false; + + while (true) + { + succeeded = uc_mem_map(uc, allocation_base, allocation_bytes, protection) == UC_ERR_OK; + if (succeeded || !allocate_anywhere) + { + break; + } + + allocation_base += allocation_granularity; + } + + uc.reg(UC_X86_REG_RAX, succeeded + ? STATUS_SUCCESS + : STATUS_NOT_SUPPORTED // No idea what the correct code is + ); + } } void handle_syscall(const unicorn& uc, process_context& context) @@ -276,6 +324,9 @@ void handle_syscall(const unicorn& uc, process_context& context) case 0x50: handle_NtProtectVirtualMemory(uc); break; + case 0x78: + handle_NtAllocateVirtualMemoryEx(uc); + break; case 0x11A: handle_NtManageHotPatch(uc); break;