#include <Windows.h>
#include <TlHelp32.h>
#include <stdio.h>// Dump a process' memory to a filevoiddumpProcessMemory(DWORD pid,const char* filename){HANDLE hProcess =OpenProcess(PROCESS_ALL_ACCESS,FALSE, pid);if(hProcess ==NULL){printf("Failed to open process %d\n", pid);return;}// Get the process informationPROCESSENTRY32 pe ={0};
pe.dwSize =sizeof(pe);HANDLE hSnapshot =CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);if(Process32First(hSnapshot,&pe)){do{if(pe.th32ProcessID == pid){break;}}while(Process32Next(hSnapshot,&pe));}CloseHandle(hSnapshot);// Create the output fileFILE* fp =fopen(filename,"wb");if(fp ==NULL){printf("Failed to create file %s\n", filename);CloseHandle(hProcess);return;}// Loop through all memory regions in the process and write them to the fileMEMORY_BASIC_INFORMATION mbi;SIZE_T bytesRead;for(LPVOID address =NULL;VirtualQueryEx(hProcess, address,&mbi,sizeof(mbi))==sizeof(mbi); address =(LPBYTE)mbi.BaseAddress + mbi.RegionSize){if(mbi.State !=MEM_FREE){// Allocate a buffer for this memory region and read the data from the processLPVOID buffer =VirtualAlloc(NULL, mbi.RegionSize,MEM_COMMIT,PAGE_READWRITE);ReadProcessMemory(hProcess, mbi.BaseAddress, buffer, mbi.RegionSize,&bytesRead);// Write the memory contents to the filefwrite(buffer,1, mbi.RegionSize, fp);// Free the bufferVirtualFree(buffer,0,MEM_RELEASE);}}fclose(fp);CloseHandle(hProcess);printf("Dumped process %s (pid=%d) memory to file %s\n", pe.szExeFile, pid, filename);}
int main(int argc, char** argv){if(argc !=2){printf("Usage: dumpmem <pid>\n");return1;}DWORD pid =atoi(argv[1]);dumpProcessMemory(pid,"memory.bin");return0;}