title: Runtime process memory patching for restoring state
body: <p>I'm looking for a method for storing the process memory, and restore it later at certain conditions.</p>
  
  <p>...</p>
  
  <p>Actually I've read questions about it... It seems a big challenge!</p>
  
  <p>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.</p>
  
  <p>The central server shall save its state by dumping its process memory, which should be restored later a certain conditions. (1)</p>
  
  <p>I known about <a href="http://msdn.microsoft.com/en-us/library/ms680553(VS.85).aspx" rel="noreferrer">ReadProcessMemory</a> and <a href="http://msdn.microsoft.com/en-us/library/ms681674(VS.85).aspx" rel="noreferrer">WriteProcessMemory</a> 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... <em>what addresses</em>? Many code I've read uses the address returned by <a href="http://msdn.microsoft.com/en-us/library/aa366887(VS.85).aspx" rel="noreferrer">VirtualAlloc</a>, but I don't known whether this could be useful to me.</p>
  
  <p>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.</p>
  
  <p>It remains the stack memory, and the heap memory, which are the memory segments what I'm interested in.</p>
  
  <p><em>Is it possible?</em></p>
  
  <p>(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.</p>
  
  <hr>
  
  <p>It came to my mind the <a href="http://msdn.microsoft.com/en-us/library/820k4tb8(v=VS.80).aspx" rel="noreferrer"><em>malloc</em> &amp; co. hook</a>. So I can track the memory allocated by the process. But actually I noticed the <a href="http://msdn.microsoft.com/en-us/library/wc28wkas(v=VS.80).aspx" rel="noreferrer">_CrtMemState</a> structure, but I don't known whether it could be useful to me.</p>