Dynamically altering another program’s flow

I’ve been asked by a friend of mine for sample code on debugging APIs. The code starts and debugs the Minesweeper game that comes with Windows 7, using breakpoints and single steps. When the user clicks a bomb, the instruction pointer is moved so that it doesn’t explode.

Updates
14/04/2012: fixed a bug

Downloads
Source code (x86 and x64 compatible)

Application monitoring

I’ve been asked if there’s a way to programmatically determine if an application crashed in order to restart it; the answer is, of course, yes. To accomplish this task, you have to create the process with a launcher that acts like a debugger; your application only needs to check the exit code of the process whenever it receives an EXIT_PROCESS_DEBUG_EVENT event (you can also check for unrecoverable exceptions).

Here’s the pseudo-code:

DEBUG_EVENT deDebugEvent;
...
WaitForDebugEvent(..);
...
// Check the event type
switch(deDebugEvent.dwDebugEventCode)
{
	...
	case EXIT_PROCESS_DEBUG_EVENT:
	{
		// We assume that if the program exited with a nonzero code, it crashed
		if (deDebugEvent.u.ExitProcess.dwExitCode)
		{
			// The program crashed
			DebugActiveProcessStop(...);
			CreateProcess(...);
			...
		}

		// Clean exit
		ExitProcess(0);
	}
	...
}

Source code: http://www.insanedevelopers.net/downloads/Sources/ApplicationMonitor.zip