-
Notifications
You must be signed in to change notification settings - Fork 2
/
DirectMemoryTools.cpp
386 lines (343 loc) · 12.5 KB
/
DirectMemoryTools.cpp
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
#ifdef _WIN32 // Windows
#include "DirectMemoryTools.h"
#include <winsock2.h>
#include <windows.h>
#include <cstdio>
#include <future>
#include <psapi.h>
#include <string>
#include <TlHelp32.h>
#define DMA_DEBUG false
HANDLE hProcess;
mulong DirectMemoryTools::memRead(void *buff, mulong len, Addr addr, offset off) {
if (buff == nullptr || len == 0) return 0;
// 检查内存是否有效再读取
MEMORY_BASIC_INFORMATION mbi;
if (VirtualQueryEx(hProcess, reinterpret_cast<LPCVOID>(addr + off), &mbi, sizeof(mbi))) {
if (mbi.State == MEM_COMMIT && (mbi.Protect & (
PAGE_READONLY | PAGE_READWRITE | PAGE_EXECUTE_READ |
PAGE_EXECUTE_READWRITE))) {
return ReadProcessMemory(hProcess, (LPVOID) (addr + off), buff, len, nullptr);
} else {
logDebug("Error: Memory not writable or not committed\n");
}
} else {
logDebug("Error: VirtualQueryEx failed\n");
}
return 0;
}
mulong DirectMemoryTools::memWrite(void *buff, mulong len, Addr addr, offset off) {
// 检查内存是否有效再写入
MEMORY_BASIC_INFORMATION mbi;
if (VirtualQueryEx(hProcess, reinterpret_cast<LPCVOID>(addr + off), &mbi, sizeof(mbi))) {
if (mbi.State == MEM_COMMIT && (mbi.Protect & (PAGE_READWRITE | PAGE_EXECUTE_READWRITE))) {
return WriteProcessMemory(hProcess, (LPVOID) (addr + off), buff, len, nullptr);
} else {
logDebug("Error: Memory not writable or not committed\n");
}
} else {
logDebug("Error: VirtualQueryEx failed\n");
}
return 0;
}
DirectMemoryTools::~DirectMemoryTools() {
DirectMemoryTools::close();
}
bool DirectMemoryTools::init(std::string bm) {
MemoryToolsBase::init();
int pid = this->getPID(bm);
if (pid > 0) {
hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, pid);
processID = pid;
processName = bm;
initModuleRegions();
initMemoryRegions();
baseModule = getModule(bm);
return true;
}
return false;
}
void DirectMemoryTools::close() {
CloseHandle(hProcess);
}
std::vector<PProcess> DirectMemoryTools::getProcessList() {
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnapshot == INVALID_HANDLE_VALUE) {
logDebug("Failed to CreateToolhelp32Snapshot\n");
return {};
}
PROCESSENTRY32 processEntry;
processEntry.dwSize = sizeof(PROCESSENTRY32);
std::vector<PProcess> processes;
// 遍历进程列表
if (Process32First(hSnapshot, &processEntry)) {
do {
PProcess process;
strcpy(process.processName, processEntry.szExeFile);
process.processID = processEntry.th32ProcessID;
process.processID = processEntry.th32ParentProcessID;
processes.push_back(process);
} while (Process32Next(hSnapshot, &processEntry));
}
CloseHandle(hSnapshot);
return processes;
}
DirectMemoryTools::DirectMemoryTools() = default;
int DirectMemoryTools::getPID(std::string bm) {
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnapshot == INVALID_HANDLE_VALUE) {
logDebug("Failed to CreateToolhelp32Snapshot\n");
return -1;
}
PROCESSENTRY32 processEntry;
processEntry.dwSize = sizeof(PROCESSENTRY32);
// 遍历进程列表
if (Process32First(hSnapshot, &processEntry)) {
do {
std::string processName = processEntry.szExeFile;
if (processName == bm) {
CloseHandle(hSnapshot);
return processEntry.th32ProcessID;
}
} while (Process32Next(hSnapshot, &processEntry));
}
CloseHandle(hSnapshot);
return -1;
}
void DirectMemoryTools::initModuleRegions() {
HMODULE hMods[1024];
DWORD cbNeeded;
if (EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded)) {
for (unsigned int i = 0; i < (cbNeeded / sizeof(HMODULE)); i++) {
MODULEINFO modInfo;
char szModName[MAX_PATH] = {0};
if (!GetModuleInformation(hProcess, hMods[i], &modInfo, sizeof(modInfo))) {
continue;
}
if (!GetModuleBaseName(hProcess, hMods[i], szModName, sizeof(szModName) / sizeof(TCHAR))) {
continue;
}
MModule mModule;
mModule.baseAddress = (Addr) modInfo.lpBaseOfDll;
mModule.baseSize = modInfo.SizeOfImage;
strcpy(mModule.moduleName, szModName);
moduleRegions.push_back(mModule);
}
}
}
void DirectMemoryTools::initMemoryRegions() {
// 遍历整个虚拟地址空间
Addr address = 0;
MEMORY_BASIC_INFORMATION mbi;
while (VirtualQueryEx(hProcess, reinterpret_cast<LPCVOID>(address), &mbi, sizeof(mbi))) {
bool isModuleRegion = false;
// 检查该内存区域是否属于任何模块
for (const auto &moduleRegion: moduleRegions) {
if (reinterpret_cast<Addr>(mbi.BaseAddress) >= moduleRegion.baseAddress &&
reinterpret_cast<Addr>(mbi.BaseAddress) < moduleRegion.baseAddress + moduleRegion.baseSize) {
isModuleRegion = true;
break;
}
}
// 如果不属于任何模块,则将其添加到非模块区域列表中
if (!isModuleRegion && mbi.State == MEM_COMMIT) {
memoryRegions.push_back({"", (Addr) mbi.BaseAddress, mbi.RegionSize});
}
// 移动到下一个内存区域
address = reinterpret_cast<Addr>(mbi.BaseAddress) + mbi.RegionSize;
}
}
Handle DirectMemoryTools::createScatter() {
return nullptr;
}
void DirectMemoryTools::addScatterReadV(Handle handle, void *buff, mulong len, Addr addr) {
readV(buff, len, addr);
}
void DirectMemoryTools::addScatterReadV(Handle handle, void *buff, mulong len, Addr addr, offset off) {
readV(buff, len, addr, off);
}
void DirectMemoryTools::executeReadScatter(Handle handle) {
}
void DirectMemoryTools::closeScatterHandle(Handle handle) {
}
void DirectMemoryTools::execAndCloseScatterHandle(Handle handle) {
}
#else // Linux
#include <fstream>
#include <sstream>
#include "DirectMemoryTools.h"
#include <unistd.h>
#include <sys/uio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <cstdio>
#include <future>
#include <dirent.h>
#include <cstring>
#include <sys/ptrace.h>
#include <sys/wait.h>
#include <vector>
#define DMA_DEBUG false
pid_t hProcess;
std::string trimAndGetModuleName(const std::string& str) {
size_t first = str.find_first_not_of(' ');
if (first == std::string::npos) return ""; // No content
size_t last = str.find_last_not_of(' ');
std::string trimmed = str.substr(first, (last - first + 1));
size_t lastSlash = trimmed.find_last_of('/');
if (lastSlash != std::string::npos) {
return trimmed.substr(lastSlash + 1);
}
return trimmed;
}
mulong DirectMemoryTools::memRead(void *buff, mulong len, Addr addr, offset off) {
memset(buff, 0, len);
Addr lastAddr = addr + off;
iovec iov_ReadBuffer{}, iov_ReadOffset{};
iov_ReadBuffer.iov_base = buff;
iov_ReadBuffer.iov_len = len;
iov_ReadOffset.iov_base = (void *) lastAddr;
iov_ReadOffset.iov_len = len;
long int size = syscall(SYS_process_vm_readv, processID, &iov_ReadBuffer, 1, &iov_ReadOffset, 1, 0);
return size == -1 ? 0 : size;
}
mulong DirectMemoryTools::memWrite(void *buff, mulong len, Addr addr, offset off) {
iovec iov_WriteBuffer{}, iov_WriteOffset{};
iov_WriteBuffer.iov_base = buff;
iov_WriteBuffer.iov_len = len;
iov_WriteOffset.iov_base = (void *) (addr + off);
iov_WriteOffset.iov_len = len;
// 大小
long int size = syscall(SYS_process_vm_writev, processID, &iov_WriteBuffer, 1, &iov_WriteOffset, 1, 0);
return size == -1 ? 0 : size;
}
DirectMemoryTools::~DirectMemoryTools() {
DirectMemoryTools::close();
}
bool DirectMemoryTools::init(std::string bm) {
MemoryToolsBase::init();
int pid = this->getPID(bm);
if (pid > 0) {
hProcess = pid;
processID = pid;
processName = bm;
initModuleRegions();
initMemoryRegions();
baseModule = getModule(bm);
return true;
}
return false;
}
void DirectMemoryTools::close() {
}
std::vector<PProcess> DirectMemoryTools::getProcessList() {
std::vector<PProcess> processes;
DIR *dir = opendir("/proc");
if (dir == nullptr) {
return processes;
}
dirent *entry;
while ((entry = readdir(dir)) != nullptr) {
if (entry->d_type == DT_DIR) {
int pid = atoi(entry->d_name);
if (pid > 0) {
std::string cmdline_path = "/proc/" + std::string(entry->d_name) + "/cmdline";
std::ifstream cmdline_file(cmdline_path);
if (!cmdline_file.is_open()) {
continue;
}
std::string process_name;
std::getline(cmdline_file, process_name, '\0');
if (!process_name.empty()) {
size_t param_pos = process_name.find(' ');
if (param_pos != std::string::npos) {
process_name = process_name.substr(0, param_pos);
}
size_t last_slash_pos = process_name.find_last_of('/');
if (last_slash_pos != std::string::npos) {
process_name = process_name.substr(last_slash_pos + 1);
}
// printf("process_name: %s\n",process_name.c_str());
PProcess process;
strncpy(process.processName, process_name.c_str(), sizeof(process.processName) - 1);
process.processName[sizeof(process.processName) - 1] = '\0';
process.processID = pid;
processes.push_back(process);
}
}
}
}
closedir(dir);
return processes;
}
DirectMemoryTools::DirectMemoryTools() = default;
int DirectMemoryTools::getPID(std::string bm) {
std::vector<PProcess> processes = getProcessList();
for (const auto &process : processes) {
if (process.processName == bm) {
return process.processID;
}
}
return -1;
}
void DirectMemoryTools::initModuleRegions() {
std::string maps_path = std::string("/proc/") + std::to_string(hProcess) + "/maps";
std::ifstream maps_file(maps_path);
std::string line;
while (std::getline(maps_file, line)) {
Addr start, end;
std::istringstream lineStream(line);
std::string addresses, permissions, offset, dev, inode, moduleName;
lineStream >> addresses >> permissions >> offset >> dev >> inode;
std::getline(lineStream, moduleName);
std::istringstream addressStream(addresses);
std::string startAddressStr, endAddressStr;
std::getline(addressStream, startAddressStr, '-');
std::getline(addressStream, endAddressStr, '-');
start = std::stoul(startAddressStr, nullptr, 16);
end = std::stoul(endAddressStr, nullptr, 16);
if(!moduleName.empty()) {
moduleName = trimAndGetModuleName(moduleName);
}
if (permissions.find('r') != std::string::npos) {
MModule mModule;
mModule.baseAddress = start;
mModule.baseSize = end - start;
strcpy(mModule.moduleName,moduleName.c_str());
moduleRegions.push_back(mModule);
}
}
}
void DirectMemoryTools::initMemoryRegions() {
// std::string maps_path = std::string("/proc/") + std::to_string(hProcess) + "/maps";
// std::ifstream maps_file(maps_path);
// std::string line;
// while (std::getline(maps_file, line)) {
// std::istringstream iss(line);
// Addr start, end;
// char dash;
// iss >> std::hex >> start >> dash >> end;
// std::string perms;
// iss >> perms;
// if (perms.find('r') != std::string::npos) {
// memoryRegions.push_back({"", start, end - start});
// }
// }
}
Handle DirectMemoryTools::createScatter() {
return nullptr;
}
void DirectMemoryTools::addScatterReadV(Handle handle, void *buff, mulong len, Addr addr){
readV(buff, len, addr);
}
void DirectMemoryTools::addScatterReadV(Handle handle, void *buff, mulong len, Addr addr, offset off) {
readV(buff, len, addr, off);
}
void DirectMemoryTools::executeReadScatter(Handle handle) {
}
void DirectMemoryTools::closeScatterHandle(Handle handle) {
}
void DirectMemoryTools::execAndCloseScatterHandle(Handle handle){
}
#endif