From 9cf7f6976a5625359f8b43dd495b2215b7935bb1 Mon Sep 17 00:00:00 2001 From: Brady Date: Mon, 30 Sep 2024 13:38:39 -0500 Subject: [PATCH] Use unicode API to get module handle --- include/libhat/Process.hpp | 3 +-- src/os/win32/Process.cpp | 20 +++++++++++++++----- 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/include/libhat/Process.hpp b/include/libhat/Process.hpp index 3553c33..0fa6b4e 100644 --- a/include/libhat/Process.hpp +++ b/include/libhat/Process.hpp @@ -2,7 +2,6 @@ #include #include -#include #include namespace hat::process { @@ -15,7 +14,7 @@ namespace hat::process { /// Returns an optional containing the module with the given name in the current process /// If the module is not found, std::nullopt is returned instead - [[nodiscard]] std::optional get_module(const std::string& name); + [[nodiscard]] std::optional get_module(std::string_view name); /// Returns the module located at the specified base address. Optionally, a size may be provided to indicate /// the size of the allocation pointed to by address, preventing a potential out-of-bounds read. diff --git a/src/os/win32/Process.cpp b/src/os/win32/Process.cpp index 7cb2860..0aa88b8 100644 --- a/src/os/win32/Process.cpp +++ b/src/os/win32/Process.cpp @@ -42,17 +42,27 @@ namespace hat::process { } module_t get_process_module() { - return module_t{reinterpret_cast(GetModuleHandleA(nullptr))}; + return module_t{reinterpret_cast(GetModuleHandleW(nullptr))}; } - std::optional get_module(const std::string& name) { - if (const auto module = GetModuleHandleA(name.c_str()); module) { + std::optional get_module(const std::string_view name) { + const int size = MultiByteToWideChar(CP_UTF8, 0, name.data(), static_cast(name.size()), nullptr, 0); + if (!size) { + return {}; + } + + std::wstring str; + str.resize(size); + + MultiByteToWideChar(CP_UTF8, 0, name.data(), static_cast(name.size()), str.data(), size); + + if (const auto module = GetModuleHandleW(str.c_str()); module) { return module_t{std::bit_cast(module)}; } return {}; } - std::optional module_at(void* address, std::optional size) { + std::optional module_at(void* address, const std::optional size) { if (isValidModule(address, size)) { return module_t{std::bit_cast(address)}; } @@ -72,7 +82,7 @@ namespace hat::process { const auto maxChars = std::min(name.size(), 8); const auto* sectionHeader = IMAGE_FIRST_SECTION(&ntHeaders); - for (int i = 0; i < ntHeaders.FileHeader.NumberOfSections; i++, sectionHeader++) { + for (DWORD i = 0; i < ntHeaders.OptionalHeader.NumberOfRvaAndSizes; i++, sectionHeader++) { if (strncmp(name.data(), reinterpret_cast(sectionHeader->Name), maxChars) == 0) { return { bytes + sectionHeader->VirtualAddress,