runtime: Allow ignoring unhandled exceptions in UnhandledException event handler

Background and Motivation

Scenarios like designers or REPLs that host user provided code are not able to handle unhandled exceptions thrown by the user provided code. Unhandled exceptions on finalizer thread, threadpool threads or user created threads will take down the whole process. This is not desirable experience for these type of scenarios.

The discussion that lead to this proposal is in https://github.com/dotnet/runtime/issues/39587

Proposed API

Allow ignoring unhandled exceptions on threads created by the runtime from managed UnhandledException handler:

 namespace System
 {
     public class UnhandledExceptionEventArgs
     {
         // Existing property. Always true in .NET Core today. The behavior will be changed to:
+        // - `false` for exceptions that can be ignored (ie thread was created by the runtime)
+        // - `true` for exceptions that cannot be ignored (ie foreign thread or other situations when it is not reasonably possible to continue execution)
         // This behavior is close to .NET Framework 1.x behavior of this property.
         public bool IsTerminating { get; }

+        // The default value is false. The event handlers can set it to true to make
+        // runtime ignore the exception. It has effect only when IsTerminating is false.
+        // The documentation will come with usual disclaimer for bad consequences of ignoring exceptions
+        public bool Ignore { get; set; }
     }
 }

Usage Examples

AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
{
    if (DesignMode && !e.IsTerminating)
    {
        DisplayException(e.ExceptionObject);
        e.Ignore = true;
    }
};

Alternative Designs

Unmanaged hosting API that enables this behavior. (CoreCLR has poorly documented and poorly tested configuration option for this today.)

Similar prior art:

Risks

This API can be abused to ignore unhandled exceptions in scenarios where it is not warranted.

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 14
  • Comments: 89 (80 by maintainers)

Most upvoted comments

It seems this issue is also blocking an important plugin for Unreal Engine ( https://github.com/nxrighthere/UnrealCLR/issues/33 ) while this was moved to the Future milestone, I’d like to push this to be taken into consideration for .NET 6 or even .NET 7. It’s kinda discouraging to see it stuck in that milestone that only god-knows-when will be done.

Considering the positive impact that project is making in the UE community as a whole, I think it’s important to look at.

Excluding the UE topic, this issue is pretty valid to me in some apps I’ve developed in the past, too. Haven’t needed it, but it would’ve been a good addition to some workarounds I’ve had to implement.

We need this functionality.

I would create a new small header file for this. It can live in https://github.com/dotnet/runtime/tree/main/src/native/public. I would not worry about shipping it - just tell people to copy it over from the repo if they need it.

(We have header files for debugger, profiler or hosting. Each of these are handled differently, there is not much consistency.)

There must be a way to fetch a pointer to a native function from managed code. Perhaps more than one.

  • Create a helper method in the native library that returns the function pointer, DllImport the helper method, and call it to get the function pointer. I think this is the best option.
  • NativeLibrary.Load + NativeLibrary.GetExport. It does not work with static linking

Although I kind of wonder if we need to encode the native method signature in the API, or whether it is a function at all.

https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.objectivec.objectivecmarshal.initialize?view=net-8.0 is recently added API with similar shape. It has the function pointers in the signature.

I think either way, we can say that once UnhandledExceptionHandler returns true, this is no longer an unhandled case so CurrentDomain.UnhandledException is not called, regardless of the runtime.

  • Add to AppDomain vs. introduce a new type under ExceptionServices

I’d prefer ExceptionServices. This can be seen as orthogonal to CurrentDomain.UnhandledException, thus does not need to live near it.

  • Event vs. a single shot delegate

I think I might prefer a single shot delegate (the DllImportResolver style). Solves the problem with multiple handlers. Or at least moves it to the user, who still can build something pluggable or flow this into an event.

But I’d like to hear from the likely users.

Yeah, let’s try to get this done for .NET 9.

I don’t like Ignorable \ Ignore. Whoever handle the unhandled exception may not necessarily ignore it, maybe they will choose to not just take down the current process, but the whole OS as well. Or they could choose to ignore the unhandled exception. Point is, we only know that someone handled it. We don’t know how they handled it. Ignoring it is just one way of handling it.

Better names: bool CanBeHandled; bool Handled;

Video

  • Looks good as proposed
namespace System
{
    public partial class UnhandledExceptionEventArgs : EventArgs
    {
        // Existing property.
        // public bool IsTerminating { get; }
        
        public bool Ignore { get; set; }
    }
}

The combined proposal is at https://github.com/dotnet/runtime/issues/101560

@jkotas @AaronRobinsonMSFT - huge thanks for helping with this!!

LGTM

Nit: The example has GetFatalErrorHandler on the managed side, but it does not show it on the unmanaged side.

I have applied all the suggestions. I think this is ready to be put in one proposal (together with managed handler part) and send to API review.

The latest iteration that should capture all the suggestions so far. Let me know if I missed/misunderstood something or there are some additional thoughts.

The API definition:

Managed API to set up the handler

public static class ExceptionHandling
{
    /// <summary>
    /// .NET runtime is going to call `fatalErrorHandler` set by this method before its own
    /// fatal error handling (creating .NET runtime-specific crash dump, etc.).
    /// </summary>
    /// <exception cref="ArgumentNullException">If fatalErrorHandler is null</exception>
    /// <exception cref="InvalidOperationException">If a handler is already set</exception>
    public static void SetFatalErrorHandler(delegate* unmanaged<uint, void*, int> fatalErrorHandler);
}

The shape of the FatalErrorHandler, if implemented in c++ (the default calling convention for the given platform is used)

// expected signature of the handler
FatalErrorHandlerResult FatalErrorHandler(int32_t hresult, struct FatalErrorInfo* data);

With FatalErrorHandlerResult and FatalErrorInfo defined in “TBD.h” as:

enum FatalErrorHandlerResult : int32_t
{
    RunDefaultHandler = 0,
    SkipDefaultHandler = 1,
};

struct FatalErrorInfo
{
    size_t size;    // size of the FatalErrorInfo instance
    void*  address; // code location correlated with the failure (i.e. location where FailFast was called)

    // exception/signal information, if available
    void* info;     // Cast to PEXCEPTION_RECORD on Windows or siginfo_t* on non-Windows.
    void* context;  // Cast to PCONTEXT on Windows or ucontext_t* on non-Windows.

    // UTF-16 strings with additional information as appropriate
    char16_t* errorSource;     // example: "Assertion Failed"
    char16_t* message;         // error message. For example the one passed to "FailFast(message)"
    char16_t* detailMessage;   // detailMessage that was passed to "Assert(condition, message, detailMessage)"
    char16_t* exceptionString; // for unhandled managed exceptions the result of "ex.ToString()"
};

Typical use:

Setting up the handler for the app (C# code in the actual app):

internal unsafe class Program
{
    [DllImport("myCustomCrashHandler.dll")]
    public static extern delegate* unmanaged<uint, void*, int> GetFatalErrorHandler();

    static void Main(string[] args)
    {
        ExceptionHandling.SetFatalErrorHandler(GetFatalErrorHandler());

        RunMyProgram();
    }
}

The handler. (c++ in myCustomCrashHandler.dll)

#include "TBD.h"

static FatalErrorHandlerResult FatalErrorHandler(int32_t hresult, struct FatalErrorInfo* data)
{
    // this is a special handler that analyzes OOM crashes
    if (hresult != COR_E_OUTOFMEMORY)
    {
        return FatalErrorHandlerResult::RunDefaultHandler;
    }

    DoSomeCustomProcessingOfOOM(data);

    // no need for a huge crash dump after an OOM.
    return FatalErrorHandlerResult::SkipDefaultHandler;
}

extern "C" DLL_EXPORT void* GetFatalErrorHandler()
{
    return &FatalErrorHandler;
}

If the fail-fast is originating as Environment.FailFast, I do not have concerns about collecting the stacktrace upfront like we do that today.

I have concerns about computing the stacktrace automatically for failfasts that are e.g. crashes in the middle of GC. We do print the managed stacktrace to console for these today, but it is not clear whether it is a good idea. We have seen situations where it caused secondary crashes and made the original crash undiagnosable.

I think the managed stacktrace needs to be optional and only computed if the handler wants it given that computing it is a very complex operation. I do not have a strong opinion about how it should be formatted.

hard to get in other ways

This may change as we make progress on cDAC.

I don’t think this is a good idea. The hosting APIs have very different UX and rules. The hosting APIs are expecting strings that are created by the user and provided. This API is entirely in the domain of runtime provided strings, so we should not introduce any additional munging in that space and provide what we have. char16_t is far more preferable to yet another set of PAL definitions that users will need to manage.

Makes sense. I did notice that unlike hosting, the strings go in a different direction (from runtime to the handler).

By char16_t - do you mean on both Windows and Unix? Any thoughts about encoding?

I would call it int32_t hresult then (to match Exception.HResult that is the same kind of error code).

int32_t error_code

What kind of error_code is this?

Cast to PEXCEPTION_POINTERS on Windows or ucontext_t* on non-Windows.

EXCEPTION_POINTERS is bundle of EXCEPTION_RECORD and CONTEXT. It corresponds to siginfo_t* and ucontext_t*. We may want to split it into two fields like this:

struct ExceptionData
{
...
    void* info; // Cast to PEXCEPTION_RECORD on Windows or siginfo_t* on non-Windows.
    void* ucontext; // Cast to PCONTEXT on Windows or ucontext_t* on non-Windows.
...
};

ExceptionData

We should call it FatalErrorData (or FatalErrorInfo) to match SetFatalErrorHandler.

Is that about PEXCEPTION_POINTERS? I think it would be ok on Windows.

I agree, but then the declarations become muddled and we end up requiring people to define complex structures. If we instead make the data structures simple the declarations are easy to copy/paste and users can simply cast in the implementation if needed. One could imagine something akin to the following:

struct ExceptionData
{
    size_t size;
    void* Context; // Cast to PEXCEPTION_POINTERS on Windows or ucontext_t* on non-Windows.
    // Define other fields and how they should be used.
};

So the signature could be:

// returns false if default handler is not desired.
extern "C" DLL_EXPORT BOOL __cdecl FatalErrorHandler(int32_t error_code, struct ExceptionData* data);

Now we need to settle on how ExceptionData looks like

I am not sure if exceptions thrown in reverse pinvokes have a defined behavior today

On Windows CoreCLR, exceptions escaping from reverse PInvokes are converted to Windows SEH exceptions. Exceptions escaping from reverse PInvokes are treated as unhandled exceptions everywhere else.

we would prefer to be able to handle as many cases as possible versus crashing the process.

To handle unhandled exception in reverse PInvoke, we would have to return something to the unmanaged code that called the reverse PInvoke. What would that be? Returning random values and hope for the best does not sound like a good plan.

For the semantics of unhandled exception handler I think we can follow the model of imaginary

try { UserCode(); } catch (Exception ex) when handler(ex){};

in places where the above will not lead to process termination regardless of what handler() returns.

  • only exceptions that can be caught and ignored will cause the handler to be invoked. (i.e. stack overflow will not)
  • an unhandled exception thrown in a handler will not invoke the handler, but will be treated as returning false.
  • when an exception is handled via a handler in a user-started thread, the thread will still exit (but not escalate to process termination)
  • when an exception is handled in a task-pumping scenario (thread pool, finalizer queue, anything else?), the pumping will continue. (we do not need to commit to what happens to the thread, but the process should be able to proceed)
  • a reverse pinvoke will not install the try/catch like above.
  • main() will not install the try/catch like above

Any other interesting scenario or a corner case?

How does that work with multiple listeners? The last wins?

The first one wins. It is how AssemblyResolve and similar events work today. One example from many: https://github.com/dotnet/runtime/blob/aee49579769188d0ff7cf3ca872d2126e5bb3c70/src/libraries/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.cs#L811-L821

Still not a great name.

Proposed API

Allow ignoring unhandled exceptions on threads created by the runtime from new managed UnhandledExceptionThrowing handler:

namespace System
{
    public class AppDomain
    {
        public event UnhandledExceptionThrowingEventHandler? UnhandledExceptionThrowing;
    }

    public delegate void UnhandledExceptionThrowingEventHandler(object sender, UnhandledExceptionThrowingEventArgs e);

    public class UnhandledExceptionThrowingEventArgs : EventArgs
    {
        public object ExceptionObject { get; }

        // - `true` for exceptions that can be ignored (ie thread was created by the runtime)
        // - `false` for exceptions that cannot be ignored (ie foreign thread or other situations when it is not reasonably possible to continue execution)
        public bool Ignorable { get; }

        // The default value is false. The event handlers can set it to true to make
        // runtime ignore the exception. It has effect only when Ignorable is false.
        // The documentation will come with usual disclaimer for bad consequences of ignoring exceptions
        public bool Ignore { get; set; }
    }
}

The exception will be reported in existing UnhandledException event, whether it’s ignored or not. UnhandledExceptionEventArgs.IsTerminating will be false if the exception was ignorable and ignored.

Usage Examples

AppDomain.CurrentDomain.UnhandledExceptionThrowing += (sender, e) =>
{
    if (DesignMode && e.Ignorable)
    {
        DisplayException(e.ExceptionObject);
        e.Ignore = true;
    }
};