I wanted to make a really simple hack for "Enter The Gungeon" game. I tried getting BaseModuleAddress for it, so further on I can get some pointers and work with them. But my GetModuleBaseAddress() function not working properly as I wanted it to work. Note: The app is 64 bit.
A lot of times I've tried reworking the function, I didn't succeed though.
DWORD GetModuleBaseAddress(TCHAR* lpszModuleName, DWORD pID) { // Getting module base address
DWORD dwModuleBaseAddress = 0;
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, pID);
MODULEENTRY32 ModuleEntry32 = { 0 };
ModuleEntry32.dwSize = sizeof(MODULEENTRY32);
if (Module32First(hSnapshot, &ModuleEntry32))
{
do {
if (_tcscmp(ModuleEntry32.szModule, lpszModuleName) == 0)
{
dwModuleBaseAddress = (DWORD)ModuleEntry32.modBaseAddr;
break;
}
} while (Module32Next(hSnapshot, &ModuleEntry32));
}
CloseHandle(hSnapshot);
return dwModuleBaseAddress;
}
int main() {
char moduleName[] = "mono.dll";
HWND procHwnd = FindWindow(NULL, "Enter the Gungeon"); // Process stuff
DWORD pid;
GetWindowThreadProcessId(procHwnd, &pid);
HANDLE procHandle = OpenProcess(PROCESS_ALL_ACCESS, NULL, pid);
DWORD moduleAddress = GetModuleBaseAddress(_T(moduleName), pid);
DWORD b_moduleAddress;
ReadProcessMemory(procHandle, LPCVOID(moduleAddress), &b_moduleAddress, sizeof(b_moduleAddress), NULL); // Reading from module base address
std::cout << "Process id - " << pid << "\n" << " \n"; // Printing them all
std::cout << "ModuleBaseAddress - " << moduleAddress << "\n" << " \n";
std::cout << "ModuleBaseAddress Address - " << b_moduleAddress << "\n" << " \n";
std::cin.get();
}
I expect GetModuleBaseAddress working and giving me the correct base module address.
You are using DWORD to represent an address which is only 4 bytes, on x64 apps addresses need to be 8 bytes.
Your issue can be solved by using uintptr_t or other define/typedef which resolves to the correct pointer size based on the architecture you're building for.
Then if you're targeting a x64 process, then build for x64. If you're targeting x86, build your app in x86 and it will always work.
Here is the function I recommend which incorporates this
#include <windows.h>
#include <TlHelp32.h>
uintptr_t GetModuleBaseAddress(DWORD procId, const wchar_t* modName)
{
uintptr_t modBaseAddr = 0;
HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, procId);
if (hSnap != INVALID_HANDLE_VALUE)
{
MODULEENTRY32 modEntry;
modEntry.dwSize = sizeof(modEntry);
if (Module32First(hSnap, &modEntry))
{
do
{
if (!_wcsicmp(modEntry.szModule, modName))
{
modBaseAddr = (uintptr_t)modEntry.modBaseAddr;
break;
}
} while (Module32Next(hSnap, &modEntry));
}
}
CloseHandle(hSnap);
return modBaseAddr;
}