flavour404
flavour404

Reputation: 6312

C ReadProcessMemory - how to examine the memory area associated with a process

I wans to read all of the memory associated with a particular process. I am aware of ReadProcessMemory, but as I have little experience of using it and I am fearful that I will just get a load of rubbish out (rubbish in...).

a) how do I work out, from the base pointer to the end) the total region that I can read b) what is the best way/safest to iterate over this area of memory and print it c) how do I print it given that I don't know what values it will contain so that I can look at it?

I would also like to be able to include the actual location of each piece of data from within memory in my output.

Thanks R.

Upvotes: 1

Views: 6279

Answers (4)

huseyin tugrul buyukisik
huseyin tugrul buyukisik

Reputation: 11910

Thank you Jerry Coffin. This is just i was looking for in winnt.h:

typedef struct _MEMORY_BASIC_INFORMATION {
PVOID BaseAddress;
PVOID AllocationBase;
DWORD AllocationProtect;
DWORD RegionSize;
DWORD State;
DWORD Protect;
DWORD Type;
} MEMORY_BASIC_INFORMATION, *PMEMORY_BASIC_INFORMATION;

in winbase.h:

VirtualQueryEx(
HANDLE hProcess,
LPCVOID lpAddress,
PMEMORY_BASIC_INFORMATION lpBuffer,
DWORD dwLength
);

Upvotes: 0

Jerry Coffin
Jerry Coffin

Reputation: 490088

There are a couple of things you generally need (or at least want) to use to make much use of ReadProcessMemory. For your first question, finding blocks of memory that can be read, you can use VirtualQueryEx to find the regions of memory in a process, and how the virtual memory manager has marked each region.

To find things like locations of individual variables, you normally need to use the debugging API -- specifically the Symbol part -- SymInitialize, SymGetSymFromName, and possibly SymEnumerateSymbols should get you a decent start. There are quite a few more though...

Upvotes: 1

John Knoeller
John Knoeller

Reputation: 34128

Start with VirtualQueryEx to determine what parts of the process's address space have pages backing them up, then once you know what is where, you can use ReadProcessMemory to look at the actual data.

Upvotes: 4

R Samuel Klatchko
R Samuel Klatchko

Reputation: 76531

Memory is accessible in units of pages (typically 4096 bytes). If you read each page individually, you can know that if the read fails, that page is not readable and you can skip it.

#define PAGESIZE 4096
char *base = (char *)0;
do {

    char buffer[PAGESIZE];

    if (ReadProcessMemory(handle, base, buffer, PAGESIZE, NULL) != 0)
    {
        // buffer is valid

        // the address of buffer[X] is base+X
    }

    base += PAGESIZE;

// keep looping going until we wrap back around to 0
} while (base != 0);   

Upvotes: 4

Related Questions