C++ - 读取进程内存到缓冲区,写入进程内存(同一缓冲区上的新值)将缓冲区恢复为旧值

C++ - ReadProcessMemory to buffer, WriteProcessMemory (with new value on same buffer) reverts buffer to old value

本文关键字:缓冲区 内存 新值 恢复 取进程 读取 C++ 进程      更新时间:2023-10-16

我不知道为什么会这样,我很好奇。 我已经设法在不使用 WriteProcessMemory 上的缓冲区的情况下成功写入/读取,但我想知道为什么会发生这种情况。

这就是它的工作原理。你扔测试

目标.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;
}

主体.cpp(读取和写入地址)。从主开始。

#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;
}

这里发生了什么。

  • 要缓冲的读取内存
  • 缓冲区 = 5
  • 使缓冲区 = 20
  • 将缓冲区写入内存。
  • 缓冲区 = 5;<- ¿为什么?

如果有人能向我解释这一点,我将不胜感激!

几件事。

DWORD Address = 0x28ff28;

你怎么得到这个,你只是从上面的程序告诉你的地址是什么?

如果您从上述地址获取地址,则需要找到程序的入口点并将0x28ff28添加到该号码中。

编辑:如果你使用内存查看器,你可以看到程序吐出的地址不指向那个整数,我说的偏移量也不指向那个整数。您需要找出它相对于程序起始路径的存储位置。我错误的假设是,您可以使用上面程序吐出的数字。

窗口的设计方式是出于安全原因,它将在不同的地址随机启动程序,并且您看到的地址与程序启动的位置相差。

您应该能够从nModule.modBaseAddr找到基址,但如果以 64 位运行程序,则可能需要将其强制转换为uint64_t

我希望这有所帮助。

编辑: 您也可以执行此操作,而不是遍历快照

hWnd_ = FindWindow(nullptr, processName.c_str());
GetWindowThreadProcessId(hWnd_, &pid_);

还要确保您以管理员身份运行。