Debug a .NET EXE file that crashes immediately

空扰寡人 提交于 2019-11-30 10:24:44
Michael Stum

If you have WinDbg installed, use menu FileOpen Executable to open the application directly under the debugger and automatically break immediately.

You can then use the commands under Debug (i.e., Go) to execute it normally and debug it. Also load the SOS Extensions. Not as nice as Visual Studio, but useful if you only have the EXE (and hopefully the PDB, although that's optional) and no source.

Example: This is my source code, which we assume is unavailable:

    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        int x = 10 - 10;
        int i = 2000/x;

        Application.Run(new Form1());
    }

This crashes immediately, with no chance for you to attach a debugger in time. This is the WinDbg output after hitting "Run":

Removed dead ImageShack link - Freehand circles by me

After loading SOS.dll, you can use !DumpStack to see where the Exception was thrown:

Removed dead ImageShack link - No Freehand Circles, sorry!

Note that JIT or compiler optimizations may cause methods to be inlined which may make the StackTrace not 100% reliable, but for a quick overview it works.

WinDbg is a bit arcane, but once you got some basics done it's awesome and at least helps finding the root of the issue.

Harper Shelby

One additional option not mentioned above is to insert a

Debugger.Break();

statement at the very beginning of the program - perhaps wrapped in a #ifdef DEBUG to make it easier to skip over when its time to build for release. I've used this technique to debug Windows services that were crashing early on.

Immediate crash?

I'd use ildasm just to make sure I've got a valid (looking) managed executable.

Also, I've been bitten a few times by having the .exe on a networked drive, and not having the permissions set correctly.

One common reason for this is if an exception is thrown in the constructor of whatever object is creating when calling Application.Run... as in:

Application.Run(new MyForm());

If the MyForm constructor throws an exception, it will usually just crash.

Also consider using Assembly Binding Log Viewer to determine if you are missing a required assembly, or have a versioning issue.

Johannes Rudolph

Start it within the debugger (F5 or Ctrl + Shift + B). You should be able to set an arbitrary breakpoint (like in the main function) and single step your way through.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!