Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiently scanning memory of a process

Tags:

c#

memory

editing

Recently I've put together a C# class that can read and write bytes in another processes memory using API calls etc. as I'm sure you've all seen before.

My question however relates to how I can efficiently scan the memory of another process? I know the basic method of testing each group of 4 bytes until you reach Int32.MaxValue, but I've found it is (as you may imagine) incredibly time and resource consuming.

From what I've read, there is a way to determine the allocated addresses of a process by doing a "HeapWalk". Can anyone provide me with some code examples and/or information about this and what would be the best way of going about it?

like image 708
Luke Joshua Park Avatar asked Dec 02 '12 03:12

Luke Joshua Park


1 Answers

What you are looking for is the list of memory regions, which is basically a list of pair of memory address / region size.

What you must do is :

  • get a handle to the target process using it's process ID (PID) using OpenProcess
  • call the VirtualQueryEx function until you reach the end of the memory space (i.e. while the result of the method is greater than 0)
  • close the process handle you opened

Start VirtualQueryEx with lpAddress as 0x0. This will return a MEMORY_BASIC_INFORMATION structure that contains both BaseAddress and RegionSize properties (this represents a memory space you can read). Then increment the lpAdress parameter with the RegionSize value, so next call of VirtualQueryEx will return the next region...etc.

Google OpenProcess, CloseHandle, VirtualQueryEx and MEMORY_BASIC_INFORMATION so you can find the different P/Invoke declarations to use, so you can call those Win32 functions from C#.

like image 81
ken2k Avatar answered Oct 20 '22 09:10

ken2k