【发布时间】:2018-04-05 17:17:15
【问题描述】:
我不知道为什么会这样,我很好奇。 我已经成功地写入/读取,而不是使用 WriteProcessMemory 上的缓冲区,但我想知道为什么会发生这种情况。
这就是它的工作原理。你扔测试
target.cpp(将变量地址输出到读/写的进程)
#include <iostream>
#include <string>
using namespace std;
int main(){
int test = 5;
string pero = "hola";
cout << sizeof(test);
cout<<"Address of test is :" <<&test <<endl; //Address to put on Principal.cpp
cin.get(); //Wait that other process writes then I manually continue.
cout << "Value of test is: " << test<<endl; //Outputs 5, should output 20.
cin.get();
return 0;
}
Principal.cpp(读取和写入地址)。从 main 开始。
#include <windows.h>
#include <tlhelp32.h>
#include <iostream> // For STL i/o
#include <ctime> // For std::chrono
#include <thread> // For std::this_thread
using namespace std;
DWORD FindProcessId(const char *name)
{
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnapshot == INVALID_HANDLE_VALUE)
return 0;
PROCESSENTRY32 ProcEntry;
ProcEntry.dwSize = sizeof(PROCESSENTRY32);
if (Process32First(hSnapshot, &ProcEntry))
{
{
if (stricmp(ProcEntry.szExeFile, name) == 0)
return ProcEntry.th32ProcessID;
while (Process32Next(hSnapshot, &ProcEntry))
if (stricmp(ProcEntry.szExeFile, name) == 0)
{
return ProcEntry.th32ProcessID;
}
}
}
}
// IMPORTANT PART STARTS HERE.
int main()
{
int buffer;
DWORD Address = 0x28ff28; //Address of int test.
DWORD ProcessId = FindProcessId("test.exe");
if (ProcessId == 0)
cout << "Doesn't exist.";
else
cout << "Process Id is : " << ProcessId << endl;
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, 0, ProcessId);
if (hProcess == INVALID_HANDLE_VALUE)
{
cout << "Error in HANDLE";
}
if (ReadProcessMemory(hProcess, (LPCVOID)Address, (LPVOID)&buffer, sizeof(buffer), 0) == 0)
{
DWORD error = GetLastError();
cout << "Error is " << error << endl;
}
cout << "Buffer is: " << buffer << endl; //Outputs 5
buffer = 20; // Want to write 20 and then read variable on test.exe.
if (WriteProcessMemory(hProcess, (LPVOID)Address, (LPCVOID)&buffer, sizeof(buffer), 0) == 0)
{
DWORD error = GetLastError();
cout << "Error is " << error << endl;
}
cout << "Buffer is: " << buffer << endl; //Outputs 5, should output 20.
CloseHandle(hProcess);
return 0;
}
这里发生了什么。
- ReadMemory 到缓冲区
- 缓冲区 = 5
- 使缓冲区 = 20
- 将缓冲区写入内存。
- 缓冲区 = 5;
如果有人能向我解释这一点,我将不胜感激!
【问题讨论】:
-
如果没有找到目标进程,
FindProcessId的返回值是不确定的。如果搜索循环退出但未找到匹配项,则需要return 0语句。它还泄漏了CreateToolhelp32Snapshot返回的句柄。而main的错误处理也不是很好。 -
"buffer = 5; " - 您是否声称在调用
WriteProcessMemory后buffer内部的principal.cpp已恢复为5?或者target.cpp内部的test永远不会更新到20? -
您的编译器发出了警告。不要忽视它。
-
你好@RemyLebeau,principal.cpp 中的缓冲区恢复到 5。
-
@HeTheMan 鉴于您显示的代码,这根本不可能
标签: c++ winapi buffer readprocessmemory