Skip to content

Overriding the default behavior in case of fatal errors #116050

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions src/coreclr/classlibnative/bcltype/system.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,17 @@

#include <minipal/cpuid.h>

extern "C" void QCALLTYPE ExceptionHandling_SetFatalErrorHandler(PVOID handler)
{
QCALL_CONTRACT;

BEGIN_QCALL;

EEPolicy::SetFatalErrorHandler(handler);

END_QCALL;
}

extern "C" VOID QCALLTYPE Environment_Exit(INT32 exitcode)
{
QCALL_CONTRACT;
Expand Down
2 changes: 2 additions & 0 deletions src/coreclr/classlibnative/bcltype/system.h
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ class SystemNative
static FCDECL0(FC_BOOL_RET, IsServerGC);
};

extern "C" void QCALLTYPE ExceptionHandling_SetFatalErrorHandler(PVOID handler);

extern "C" void QCALLTYPE Environment_Exit(INT32 exitcode);

extern "C" void QCALLTYPE Environment_FailFast(QCall::StackCrawlMarkHandle mark, PCWSTR message, QCall::ObjectHandleOnStack exception, PCWSTR errorSource);
Expand Down
37 changes: 37 additions & 0 deletions src/coreclr/vm/eepolicy.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,28 @@
#include "eventtrace.h"
#undef ExitProcess

#if __cplusplus < 202002L
#if defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wc++20-compat"
#endif

using char8_t = unsigned char;

#if defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
#endif

#include "../native/public/FatalErrorHandling.h"

FatalErrorHandlerResult (*g_fatalErrorHandler)(int32_t hresult, struct FatalErrorInfo* data);

void EEPolicy::SetFatalErrorHandler(PVOID handler)
{
g_fatalErrorHandler = (FatalErrorHandlerResult (*)(int32_t hresult, struct FatalErrorInfo* data))handler;
}

void SafeExitProcess(UINT exitCode, ShutdownCompleteAction sca = SCA_ExitProcessWhenShutdownComplete)
{
STRESS_LOG2(LF_SYNC, LL_INFO10, "SafeExitProcess: exitCode = %d sca = %d\n", exitCode, sca);
Expand Down Expand Up @@ -801,6 +823,21 @@ int NOINLINE EEPolicy::HandleFatalError(UINT exitCode, UINT_PTR address, LPCWSTR
{
WRAPPER_NO_CONTRACT;

// TODO: VS this is probably not the place where the handler needs to be called, or not the only one place.
// Also handler nees various data passed. Just test that the handler is called fro now.

// We are going to call a handler, if set up.
// We shoulb not be in COOP mode whan calling random native code.
GCX_PREEMP_NO_DTOR();

if (g_fatalErrorHandler != NULL)
{
if (g_fatalErrorHandler(exitCode, NULL) == SkipDefaultHandler)
{
return -1;
}
}

// All of the code from here on out is robust to any failures in any API's that are called.
FAULT_NOT_FATAL();

Expand Down
2 changes: 2 additions & 0 deletions src/coreclr/vm/eepolicy.h
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ class EEPolicy

static void DECLSPEC_NORETURN HandleFatalStackOverflow(EXCEPTION_POINTERS *pException, BOOL fSkipDebugger = FALSE);

static void SetFatalErrorHandler(PVOID handler);

private:
static void LogFatalError(UINT exitCode, UINT_PTR address, LPCWSTR pMessage, PEXCEPTION_POINTERS pExceptionInfo, LPCWSTR errorSource, LPCWSTR argExceptionString=NULL);
};
Expand Down
1 change: 1 addition & 0 deletions src/coreclr/vm/qcallentrypoints.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ static const Entry s_QCall[] =
DllImportEntry(Delegate_Construct)
DllImportEntry(Delegate_FindMethodHandle)
DllImportEntry(Delegate_InternalEqualMethodHandles)
DllImportEntry(ExceptionHandling_SetFatalErrorHandler)
DllImportEntry(Environment_Exit)
DllImportEntry(Environment_FailFast)
DllImportEntry(Environment_GetProcessorCount)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2581,6 +2581,9 @@
<data name="InvalidOperation_CannotRegisterSecondHandler" xml:space="preserve">
<value>A handler for unhandled exceptions is already set.</value>
</data>
<data name="InvalidOperation_CannotRegisterSecondFatalHandler" xml:space="preserve">
<value>A handler for fatal errors is already set.</value>
</data>
<data name="InvalidOperation_CannotRestoreUnsuppressedFlow" xml:space="preserve">
<value>Cannot restore context flow when it is not suppressed.</value>
</data>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,21 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;

namespace System.Runtime.ExceptionServices
{
public static class ExceptionHandling
public static partial class ExceptionHandling
{
private static Func<Exception, bool>? s_handler;

#if CORECLR
private static bool s_fatalHandlerSet;
#endif

internal static bool IsHandledByGlobalHandler(Exception ex)
{
return s_handler?.Invoke(ex) == true;
Expand Down Expand Up @@ -39,6 +46,34 @@ public static void SetUnhandledExceptionHandler(Func<Exception, bool> handler)
}
}

#if CORECLR
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "ExceptionHandling_SetFatalErrorHandler")]
private static unsafe partial void _SetFatalErrorHandler(delegate* unmanaged<int, void*, int> fatalErrorHandler);
#endif

/// <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>
[System.CLSCompliantAttribute(false)]
public static unsafe void SetFatalErrorHandler(delegate* unmanaged<int, void*, int> fatalErrorHandler)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would move this next to SetUnhandledExceptionHandler

{
#if CORECLR
ArgumentNullException.ThrowIfNull(fatalErrorHandler);

if (Interlocked.CompareExchange(ref s_fatalHandlerSet, true, false))
{
throw new InvalidOperationException(SR.InvalidOperation_CannotRegisterSecondFatalHandler);
}

_SetFatalErrorHandler(fatalErrorHandler);
#else
throw new PlatformNotSupportedException();
#endif
}

/// <summary>
/// Raises the <see cref="AppDomain.UnhandledException"/> event.
/// </summary>
Expand Down
2 changes: 2 additions & 0 deletions src/libraries/System.Runtime/ref/System.Runtime.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14133,6 +14133,8 @@ public static partial class ExceptionHandling
{
public static void SetUnhandledExceptionHandler(System.Func<System.Exception,bool> handler) { }
public static void RaiseAppDomainUnhandledExceptionEvent(object exception) { }
[System.CLSCompliantAttribute(false)]
public unsafe static void SetFatalErrorHandler(delegate* unmanaged<int, void*, int> fatalErrorHandler) { }
}
public partial class FirstChanceExceptionEventArgs : System.EventArgs
{
Expand Down
38 changes: 38 additions & 0 deletions src/native/public/FatalErrorHandling.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//

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

#if defined(_MSC_VER) && defined(_M_IX86)
#define DOTNET_CALLCONV __stdcall
#else
#define DOTNET_CALLCONV
#endif

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.

// An entry point for logging additional information about the crash.
// As runtime finds information suitable for logging, it will invoke pfnLogAction and pass the information in logString.
// The callback may be called multiple times.
// Combined, the logString will contain the same parts as in the console output of the default crash handler.
// The errorLog string will have UTF-8 encoding.
void (DOTNET_CALLCONV *pfnGetFatalErrorLog)(
FatalErrorInfo* errorData,
void (DOTNET_CALLCONV *pfnLogAction)(char8_t* logString, void *userContext),
void* userContext);

// More information can be exposed for querying in the future by adding
// entry points with similar pattern as in pfnGetFatalErrorLog
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Runtime.InteropServices;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using TestLibrary;
using Xunit;

unsafe public class UnhandledException
{
[UnmanagedCallersOnly]
static int Handler(int i, void* ptr)
{
Environment.Exit(100);

// unreachable
return 42;
}

public static int Main()
{
// set handler
ExceptionHandling.SetFatalErrorHandler((delegate* unmanaged<int, void*, int>)&Handler);

// throw
Environment.FailFast("hello");

return 42;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<!-- tests process-wide state -->
<RequiresProcessIsolation>true</RequiresProcessIsolation>
<!-- Test checks the behavior of Main -->
<ReferenceXUnitWrapperGenerator>false</ReferenceXUnitWrapperGenerator>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<CLRTestPriority>0</CLRTestPriority>
</PropertyGroup>
<ItemGroup>
<Compile Include="UnhandledException.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="$(TestSourceDir)Common/CoreCLRTestLibrary/CoreCLRTestLibrary.csproj" />
</ItemGroup>
</Project>
9 changes: 8 additions & 1 deletion src/tests/issues.targets
Original file line number Diff line number Diff line change
Expand Up @@ -1072,6 +1072,10 @@
<ExcludeList Include="$(XunitTestBinBase)/Loader/CustomAttributes/**">
<Issue>Dynamic code generation is not supported on this platform</Issue>
</ExcludeList>

<ExcludeList Include="$(XunitTestBinBase)/baseservices/exceptions/FatalErrorHandler/**">
<Issue>NYI on NativeAOT</Issue>
</ExcludeList>
</ItemGroup>

<!-- NativeAOT arm32 specific -->
Expand Down Expand Up @@ -1782,7 +1786,10 @@
<Issue>https://github.com/dotnet/runtime/issues/98628</Issue>
</ExcludeList>
<ExcludeList Include="$(XunitTestBinBase)/baseservices/exceptions/UnhandledExceptionHandler/**">
<Issue>NYI on Mono</Issue>
<Issue>NYI on Mono</Issue>
</ExcludeList>
<ExcludeList Include="$(XunitTestBinBase)/baseservices/exceptions/FatalErrorHandler/**">
<Issue>NYI on Mono</Issue>
</ExcludeList>
</ItemGroup>

Expand Down
Loading