Saturday, August 4, 2007

Why you should not trust CreateProcess' PROCESS_INFORMATION

At GreenBorder I was working on a complex multi-process application with a lot of interactions between the processes through IPC and DuplicateHandle. The processes were created with CreateProcess. This call returns a PROCESS_INFORMATION structure containing the process ID of the newly created process, the thread ID of the main thread along with their handles.

I was using the structure to initialize my IPC and was using the process handle to duplicate some others handles into this new process.

Everything sounds good right? Wrong!

The problems started happening the first time I had to debug a complex bug. Since this is a multi-process architecture, the easiest/best solution to debug the child processes is to set the Image File Execution for the process to start your favorite debugger (Windbg in this case) automatically. Unfortunately it turned out to be a lot worse. After a little while I discovered that the PROCESS_INFORMATION structure returned by CreateProcess was not containing the information about my process... but the information about the debugger! All calls to DuplicateHandle were in fact duplicating handles into Windbg.

I can see how I could have refactored the code to not depend on the hProcess, but my case was not that simple. I was in fact calling CreateProcessAsUser with a restricted token. Too restricted for Windbg to be able to run properly!

To solution was to change the way I debug child processes. I'm now using the "Debug Child Processes Also" option in windbg. Oh, and if you don't control the creation of the parent process, you can still attach to it and type the command ".childdbg 1".

Note: While I was writing this post I looked on the web for some references and I found a post about this exact same issue from Raymond Chen posted only 1 month ago. My blog should also be called "The old new thing" :)

No comments: