I'm looking for a method for storing the process memory, and restore it later at certain conditions.
...
Actually I've read questions about it... It seems a big challenge!
So, let's analyse: The application is a distributed one, but many processes are stateless (request their state to a centralized server). Processes uses network connections and shared memory for communicating with other processes.
The central server shall save its state by dumping its process memory, which should be restored later a certain conditions. (1)
I known about ReadProcessMemory and WriteProcessMemory functions, which allow the process to read itself and overwrite already allocated memory, isn't it? So, which I need is address where I start to read/write, and the number of bytes to read/write. So... what addresses? Many code I've read uses the address returned by VirtualAlloc, but I don't known whether this could be useful to me.
I assume that the process executable segments are not changing, so they do not need red/written. At restore time, I could also assume that all process threads are in the same execution position when the memory was read by the main thread.
It remains the stack memory, and the heap memory, which are the memory segments what I'm interested in.
Is it possible?
(1) It is perfectly legal to ask why I'm trying to do this. The reason is... complicated, as usual. However, say that the application has a very complicated state, that requires a too complex state saving algorithm. The another alternative (which is in subject of analysis) is the implementation of a logger/replay mechanism able to reproduce every event which has contributed to the modified state.
It came to my mind the malloc & co. hook. So I can track the memory allocated by the process. But actually I noticed the _CrtMemState structure, but I don't known whether it could be useful to me.
ReadProcessMemory is for reading the memory of another process. Inside of a process, it's unnecessary -- you can just dereference a pointer to read memory within the same process.
To find the blocks of memory in a process, you can use
VirtualQuery
. Each block will be tagged with a state, type, size, etc. Here's some code I wrote years ago to walk the block list for a specified process (usingVirtualQueryEx
). You useVirtualQuery
pretty much the same way, except that you don't have to specify a process, since it always walks the process in which its running.The process memory does not represent the entire state of the process. The operating system will be holding objects on behalf of your process (e.g., file handles, synchronization objects, etc.) in places like non-paged pool that are outside the scope of your process.
I think you'd be better off refactoring until you can serialize and deserialize the relevant state with a manageable effort.