Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the program flow when running under a debugger

Is there any way of detecting that a debugger is running in memory?

and here comes the on Form Load pseudocode.

if debugger.IsRunning then
Application.exit
end if

Edit: The original title was "Detecting an in memory debugger"

like image 922
OrElse Avatar asked Aug 25 '09 19:08

OrElse


People also ask

How do I change the code while debugging in IntelliJ?

From the main menu, select Run | Debugging Actions | Reload Changed Classes.

How do I run a program in debugger?

To run a program in a debuggerClick the Image File tab. In the Image box, type the name of an executable file or DLL, including the file name extension,and then press the TAB key. This activates the check boxes on the Image File tab. Click the Debugger check box to select it.


2 Answers

Try the following

if ( System.Diagnostics.Debugger.IsAttached ) {
  ...
}
like image 102
JaredPar Avatar answered Nov 15 '22 18:11

JaredPar


Two things to keep in mind before using this to close an application running in the debugger:

  1. I've used a debugger to pull a crash trace from a commercial .NET application and send it to the company where it was subsequently fixed with a thank you for making it easy and
  2. That check can be trivially defeated.

Now, to be of more use, here's how to use this detection to keep func eval in the debugger from changing your program state if you have a cache a lazily evaluated property for performance reasons.

private object _calculatedProperty;

public object SomeCalculatedProperty
{
    get
    {
        if (_calculatedProperty == null)
        {
            object property = /*calculate property*/;
            if (System.Diagnostics.Debugger.IsAttached)
                return property;

            _calculatedProperty = property;
        }

        return _calculatedProperty;
    }
}

I've also used this variant at times to ensure my debugger step-through doesn't skip the evaluation:

private object _calculatedProperty;

public object SomeCalculatedProperty
{
    get
    {
        bool debuggerAttached = System.Diagnostics.Debugger.IsAttached;

        if (_calculatedProperty == null || debuggerAttached)
        {
            object property = /*calculate property*/;
            if (debuggerAttached)
                return property;

            _calculatedProperty = property;
        }

        return _calculatedProperty;
    }
}
like image 21
Sam Harwell Avatar answered Nov 15 '22 18:11

Sam Harwell