Attaching a debugger at startup

Sometimes you need to debug a process, and you need to attach the debugger right away, but you cannot launch the process under the debugger. For example, if the process you need to debug is a Windows Service, the Windows Service Manager must launch the process. How can you debug it?

Here are the two easiest solutions:

#1: Windows includes registry settings under the ‘Image File Execution Options’ key that can help you debug this. I blogged about this before back in February of 2005 (https://blogs.msdn.com/greggm/archive/2005/02/21/377663.aspx). Most of the information is that blog is still correct. A few updates worth mentioning though:

  • Visual Studio 2008 can support session 0 processes on Vista or Server 2008.
  • Visual Studio 2008 can support 64-bit operating systems. The only remaining 64-bit restriction is that 64-bit managed processes cannot be debugged this way since the .NET Framework does not support managed+native debugging of 64-bit processes.
  • Visual Studio 2005 does not support this feature on Windows Vista or Server 2008. You will need to upgrade to 2008 for these operating systems.

#2: You can add code to your app to cause it to pause waiting for a debugger to attach. I am attaching an example header file for making this work. We ship several executables that embed similar code for this reason. Just call ‘RuntimeDiagnostics::CheckPauseOnStartupOption()’ as the first line of code in your main routine. You can do something verify similar for managed code as well. Just call ‘System.Diagnostics.Debugger.IsAttached’ instead of IsDebuggerPresent.

int _tmain(int argc, _TCHAR* argv[])

{

    RuntimeDiagnostics::CheckPauseOnStartupOption();

    return 0;

}

Then set this registy key if you need your app to pause:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\sample.exe]
"PauseOnStartup"=dword:00000001

 

RuntimeDiagnostics.h

Comments

  • Anonymous
    September 12, 2008
    PingBack from http://hoursfunnywallpaper.cn/?p=5949

  • Anonymous
    September 16, 2008
    I recently had to deal with this situation on Windows 2000 and wondering if there is a solution to the following: My .NET services run using a domain account I need to attach a debugger at start up but the debugger can’t interact with the desktop I don’t want to use Local System because the problem may be security related If there isn’t a work around for this on 2000, what about the newer operating systems? Thanks, Dave

  • Anonymous
    September 16, 2008
    Hi Dave, You would need to use approach #2 in this scenario. As I mentioned above, you would need to covert my sample code to C#, but that should be pretty easy to do. Gregg