Catching fatal exceptions thrown from unmanaged code - c#

Currently, there is no way (at least I did not find a way) to catch fatal exceptions (such as Stack Overflow, Segfault, ..) with try-catch block.
I already started issue at .net core repository so for more details you can read there (https://github.com/dotnet/core/issues/4228)
What I'm trying to do is to make the application not crash when there is any segfault/stack overflow/any fatal exception in loaded unmanaged code. what happens now is that .NET CLR kills my application if any fatal error occurs.
Example:
In c# managed code loaded external c++ dll via kernel LoadLibrary function.
Assume the dll is intentionally created for robustness testing therefore when a specific function is called it triggers segfault (e.g. trying to get data from outside of array bounds).
When this error happens this gets caught by .net CLR and immediately kills the calling managed c# code(application).
What I would like is just report that this happens instead of dying silently.
I did some research and found out there is the reasoning behind that which is described in the issue above.

Related

System.AccessViolationException break on thrown

I am trying to resolve a AccessViolationException that is created when returning from native to managed code. Visual studio 2015 / .Net 4.0. I went into the Exception Settings and selected to Break when thrown for AccessViolationException. However that does not appear to occur. I read that there are new behaviors for this exception here.
https://msdn.microsoft.com/en-us/library/system.accessviolationexception(v=vs.110).aspx
Would that prevent the debugger from breaking on the throw?
More details, and maybe you are right the VS simply cannot give me more. The native code returns a struct to the managed code. The struct is defined in managed so that the marshaling can occur. I can step through the native code and the method completes. The debugger ends up on the managed method which was pinvoked. I was hoping the debugger would stop at a point that would allow me to identify the offending memory component

Microsoft Visual C++ Runtime Library Exception in c#

I am using a fingerprint capture device in my c# application, this device has c# wrapper class for a c++ SDK dll.
Sometimes i get a c++ exception message (see image) and then the application close, the problem is that I can't catch this exception and can't keep application running after this exception.
The Question is: How Can I Catch This Exception in C#?
How Can I Catch This Exception in C#?
You cannot. An unmanaged C++ exception cannot be caught by managed code. You need to catch unmanaged exceptions in unmanaged code. You cannot let unmanaged exceptions propagate outside the unmanaged module.
However, the error dialog suggests that you have a more serious problem. One that cannot be dealt with simply by catching an exception. You will need to work out why your program is terminating the runtime in this catastrophic way, and stop that happening. That error dialog suggests that your program is calling abort(), which is terminal.
In other words you need to prevent this error from happening in the first place, rather than attempting to recover from it. This is not an error that you can hope to recover from.

Can I prevent StackOverflowException from crashing my debuggee in Visual Studio?

I'm debugging a 3rd party library that is littered with properties that occasionally throw StackOverFlowException.
Whenever I look at objects from this library in the Watch window, I end up getting the error message "Function evaluation was aborted" and the app I'm debugging crashes.
I wrote an example of a property that reproduces this (when trying to evaluate it in the Watch window):
private static int CausesStackoverflow
{
get { return CausesStackoverflow; }
}
Is there any way to evaluate properties in the Watch window without risking my app crashing due to a Stackoverflow?
You should prevent (using counters or other tricks) and not catch StackOverflowExceptions.
Since this is 3rd party code (so I suppose it can't be changed) you can try this:
Starting with 2.0 a StackOverflow Exception can only be caught in the following circumstances.
The CLR is being run in a hosted environment where the host specifically allows for StackOverflow exceptions to be handled
The stackoverflow exception is thrown by user code and not due to an actual stack overflow situation (Reference)
From MSDN StackOverflowException page:
In prior versions of the .NET
Framework, your application could
catch a StackOverflowException object
(for example, to recover from
unbounded recursion). However, that
practice is currently discouraged
because significant additional code is
required to reliably catch a stack
overflow exception and continue
program execution.
Starting with the .NET Framework
version 2.0, a StackOverflowException
object cannot be caught by a try-catch
block and the corresponding process is
terminated by default. Consequently,
users are advised to write their code
to detect and prevent a stack
overflow. For example, if your
application depends on recursion, use
a counter or a state condition to
terminate the recursive loop. Note
that an application that hosts the
common language runtime (CLR) can
specify that the CLR unload the
application domain where the stack
overflow exception occurs and let the
corresponding process continue. For
more information, see
ICLRPolicyManager Interface and
Hosting the Common Language Runtime.

try/catch not working inside UnhandledException handler

I've got a weird symptom in an application, where try/catches inside the handler for UnhandledExceptions don't work: (that is a breakpoint inside the catch does not get hit, even if the breakpoint inside the try does).
Obviously searching for 'exception unhandled inside UnhandledException' is not working very well for me.
I've tried doing a mini proof-of-concept, and unfortunately that one works.
So while I'm trying to track down the root of the problem, if anyone here has any ideas where to look I'd be greatful.
(We recently changed from XP to Windows7, and .Net 4.5 from 4.0 - I'm pretty certain that previously this worked).
EDIT: Looks like it's provoked by a call down to a (managed) C++ library which is throwing a System.AccessViolationException. Strangely, if I replace the call with a throw new AccessViolationException, it does do what I want...
You wrote, "We recently changed ... .Net 4.5 from 4.0 - I'm pretty certain that previously this worked." but the following seems worth adding, because pretty sure really means not certain :-)
I read somewhere that AccessViolationException cannot occur in managed code, but may be trapped by the runtime for unmanaged code. Maybe the C++ library calls into unmanaged code?
In .NET 4+ the process will terminate after AccessViolationException. Your exception handler will be ignored. This is among a group of exception types considered unrecoverable: Corrupted State Exceptions. In .NET 4+ you will need to customise the app config to override this behaviour.
Be sure that you try to catch System.AccessViolationException and not native Access Violation error.
When you do throw new AccessViolationException it throws System.AccAccessViolationException.
If library that you calls is native it can throw native Access Violation error, but .NET catch block normally can catch only managed exceptions.
try this:
i think we can't handle Unhandeled exception and have to exit application in finally.
http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx

application level global exception handler didn't get hit

My .net application has a global exception handler by subscribing to AppDomain.Current.Domain UnhandledException event. On a few occassions i have seen that my application crashes but this global exception handler never gets hit. Not sure if its help but application is doing some COM interop.
My understanding is that as long as I don't have any local catch blocks swallowing the exception, this global exception handler should always be hit. Any ideas on what I might be missing causing this handler never been invoked?
Is this the cause of your problem?
AppDomain.CurrentDomain.UnhandledException not firing without debugging
The CLR is not all-powerful to catch every exception that unmanaged code can cause. Typically an AccessViolationException btw. It can only catch them when the unmanaged code is called from managed code. The scenario that's not supported is the unmanaged code spinning up its own thread and this thread causing a crash. Not terribly unlikely when you work with a COM component.
Since .NET 4.0, a Fatal Execution Engine exception no longer causes the UnhandledException event to fire. The exception was deemed too nasty to allow any more managed code to run. It is. And traditionally, a StackOverflowException causes an immediate abort.
You can diagnose this somewhat from the ExitCode of the process. It contains the exception code of the exception that terminated the process. 0x8013yyyy is an exception caused by managed code. 0xc0000005 is an access violation. Etcetera. You can use adplus, available from the Debugging Tools For Windows download to capture a minidump of the process. Since this is likely to be caused by the COM component, working with the vendor is likely to be important to get this resolved.
Since you are doing COM interop I do strongly suspect that some unmanaged code was running in another thread which did cause an unhandled exception. This will lead to application exit without a call to your unhandled exception handler.
Besides this with .NET 4.0 the policy did get stronger when the application is shut down without further notice.
Under the following conditions your application is shut down without further notice (Environmnt.FailFast).
Pre .NET 4:
StackOverFlowException
.NET 4:
StackoverFlowException
AccessViolationException
You can override the behaviour in .NET 4 by decorating a method with the HandleProcessCorruptedStateExceptionsAttribute or you can add the legacyCorruptedStateExceptionsPolicy tag to your App.config.
If your problem is an uncatched exception in unmanaged code you can either run your application under a debugger or you let it crash und collect a memory dump for post mortem debugging. Debugging crash dumps is usualy done with WindDbg.
After you have downloaded Windbg you have adplus (a vbs script located under Programm Files\Debugging Tools for Windows) which you can attach to your running process to trigger a crash dump when the process terminates due to an exception.
adplus -crash -p yourprocessid
Then you have a much better chance to find out what was going on when your process did terminate. Windows can also be configured to take a crash dump for you via DrWatson on older Windows Versions (Windows Error Reporting)
Crash Dump Generation
Hard core programmers will insist to create their own dump generation tool which basically uses the AEDebug registry key. When this key has a value which points to an existing executable it will be called when an application crashes which can e.g. show the Visual Studio Debugger Chooser Dialog or it can trigger the dump generation for your process.
Suspend Threads
An often overlooked thing is when you create a crash dump with an external tool (it is better to rely on external tools since you do not know how bad your process is corrupted and if it is out memory you are already in a bad situation) that you should suspend all threads from the crashed process before you take the dump.
When you take a big full memory dump it can take several minutes depending on the allocated memory of the faulted process. During this time the application threads can continue to wreak havoc on your application state leaving you with a dump which contains an inconsistent process state which did change during dump generation.
This would happen if your handler throws an exception.
It would also happen if you call Environment.FailFast or if you Abort the UI thread.

Categories

Resources