How to get to Exception object in .NET when native code calls it

How to get to Exception object in .NET when native code calls it

Few day ago, I did investigate crash dump where .NET code raised some exception. Some .NET code called from native host using COM interface. .NET wraps such calls in try catch and return proper HRESULT to caller in native code in case of exception. In my case that .NET method failed and return failed HRESULT. Then due to unforeseen design issues, native code crashed and as result Windows created crash dump and terminated process.

Normally in most native languages when exception is raised, exception object of some kind is created and when exception handled somewhere, this object is destroyed and after that there is no way to get it. In my case as soon as executed left COM method, exception would be destroyed. But because .NET is managed language there are high chance that exception object is not collected yet. All we need to do, is to dump all heap objects.

But before that I had to load .NET support into WinDbg using following command:
.cordll -ve -u -l

Then I had to dump all exceptions using following command:
!dumpheap -type Exception

Unfortunately, list could be quite long and could take quite a lot of time to investigate, specially if you are not familiar with all code.

Fortunately, in my case I know type of exception and I used this command:
!dumpheap -type ReflectionTypeLoadException

And bingo I had only one exception. Then I did click on address of that object and WinDbg printed nice exception for me. You can check exception message and other fields of that object. But because it is ReflectionTypeLoadException I know that I had to examine LoaderExceptions property which is actually _exceptions field of that object. I clicked on value to the left from _exceptions and WinDbg printed array of exceptions. Then I checked them one by one and found why assembly failed to load. Quite easy.

I hope it helped someone.