Dynamically attaching a debugger

Sometimes something goes wrong with your program and you want to investigate why. You can start Visual Studio, choose Debug->Attach to Process and choose the process you want to debug. (The dialog also allows remote debugging and choosing Native, Managed, Mixed, Script, T_SQL, and Auto.)

Perhaps this may not work: your process launched other processes and you’re not sure to which one to attach. Sometimes it’s too late: you want to attach before a particular line of code has been executed. Perhaps the process starts and finishes too quickly.

In native code, like C or C++, you can add a call to the DebugBreak() function. If a debugger is attached, this causes a breakpoint. If not, you get a dialog to attach a debugger. You can also add an Int 3 assembly language call (0xcc) directly inline like this C++ code:

      int x=4;

      _asm int 3

With native code, I prefer using int 3 vs DebugBreak, because the int 3 occurs right in the same stack frame and module as the code in question, whereas DebugBreak occurs one level down in another DLL, as shown in this callstack:

            ntdll.dll!_DbgBreakPoint@0() Line 44 Asm

  CLRHost.exe!foobar() Line 20 + 0x8 bytes C++

In VB.Net you want behavior similar to the Stop statement (I believe the documentation for Stop is not quite correct: it seems to be ignored when running the EXE via Ctrl-F5 (which starts the EXE without debugging), but causes a breakpoint when reached while running under the debugger.

Try adding a line of code before the code in question:

System.Diagnostics.Debugger.Launch()

When it’s executed not under a debugger, a dialog will come up asking if you want to launch the debugger. Choose VS as your JIT (Just In Time) debugger and VS will start and you can single step or inspect your program’s execution at that line.

In Foxpro, you can say SUSPEND which suspends the program execution, and you can use the command window or activate the debugger to inspect or change your program’s execution. Or you can insert the command SET STEP ON, which will bring up the debugger.

 (For JIT, if you don’t have a debugger installed, I believe Dr. Watson will show up).

Be sure to remove any debug lines before deploying your program! (One way is to use a preprocessor definition which evaluates to DebugBreak for debug builds, and nothing for retail builds.)

For more about attaching a debugger, see also Is a process hijacking your machine?