1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
|
#include "Memory.h"
#include <psapi.h>
#include <tlhelp32.h>
#include <iostream>
#undef PROCESSENTRY32
#undef Process32Next
Memory::Memory(const std::string& processName) {
// First, get the handle of the process
PROCESSENTRY32 entry;
entry.dwSize = sizeof(entry);
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
while (Process32Next(snapshot, &entry)) {
if (processName == entry.szExeFile) {
_handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID);
if (!_handle) {
std::cerr << "Couldn't find " << processName.c_str() << ". Is it open?" << std::endl;
exit(EXIT_FAILURE);
}
break;
}
}
// Next, get the process base address
DWORD numModules;
std::vector<HMODULE> moduleList(1024);
EnumProcessModulesEx(_handle, &moduleList[0], static_cast<DWORD>(moduleList.size()), &numModules, 3);
std::string name(64, 0);
for (DWORD i = 0; i < numModules / sizeof(HMODULE); i++) {
GetModuleBaseNameA(_handle, moduleList[i], &name[0], sizeof(name));
// TODO: Filling with 0s still yeilds name.size() == 64...
if (strcmp(processName.c_str(), name.c_str()) == 0) {
_baseAddress = (uintptr_t)moduleList[i];
break;
}
}
if (_baseAddress == 0) {
std::cerr << "Couldn't find base address!" << std::endl;
exit(EXIT_FAILURE);
}
}
Memory::~Memory() {
CloseHandle(_handle);
}
// Private methods:
void Memory::ThrowError() {
wchar_t message[256];
FormatMessageW(4096, NULL, GetLastError(), 1024, message, 256, NULL);
std::cerr << message << std::endl;
exit(EXIT_FAILURE);
}
uintptr_t Memory::ComputeOffset(std::vector<int> offsets)
{
uintptr_t cumulativeAddress = _baseAddress;
// Leave off the last offset, since it will be either read/write, and may not be of type unitptr_t.
int final_offset = offsets.back();
offsets.pop_back();
for (int offset : offsets) {
cumulativeAddress += offset;
if (!ReadProcessMemory(_handle, (LPVOID)cumulativeAddress, &cumulativeAddress, sizeof(uintptr_t), NULL)) {
ThrowError();
}
}
return cumulativeAddress + final_offset;
}
|