Skip to content
Merged
Show file tree
Hide file tree
Changes from 9 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
12 changes: 11 additions & 1 deletion src/coreclr/System.Private.CoreLib/src/System/GC.CoreCLR.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Threading;
Expand Down Expand Up @@ -318,7 +319,16 @@ private static unsafe uint RunFinalizers()
void* fptr = GetNextFinalizeableObject(ObjectHandleOnStack.Create(ref target));
if (fptr == null)
break;
((delegate*<object, void>)fptr)(target!);

try
{
((delegate*<object, void>)fptr)(target!);
}
catch (Exception ex) when (ExceptionHandling.s_handler != null && ExceptionHandling.s_handler(ex))
Comment thread
jkotas marked this conversation as resolved.
Outdated
{
// the handler returned "true" means the exception is now "handled" and we should continue.
}

currentThread.ResetFinalizerThread();
count++;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using System;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;

//
Expand Down Expand Up @@ -63,10 +64,15 @@ private static unsafe uint DrainQueue()

finalizerCount++;

// Call the finalizer on the current target object. If the finalizer throws we'll fail
// fast via normal Redhawk exception semantics (since we don't attempt to catch
// anything).
((delegate*<object, void>)target.GetMethodTable()->FinalizerCode)(target);
try
{
// Call the finalizer on the current target object.
((delegate*<object, void>)target.GetMethodTable()->FinalizerCode)(target);
}
catch (Exception ex) when (ExceptionHandling.s_handler != null && ExceptionHandling.s_handler(ex))
{
// the handler returned "true" means the exception is now "handled" and we should continue.
}
Comment thread
jkotas marked this conversation as resolved.
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System.Globalization;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;

Expand Down Expand Up @@ -458,6 +459,10 @@ private static void StartThread(IntPtr parameter)

startHelper.Run();
}
catch (Exception ex) when (ExceptionHandling.s_handler != null && ExceptionHandling.s_handler(ex))
{
// the handler returned "true" means the exception is now "handled" and we should gracefully exit.
}
finally
{
thread.SetThreadStateBit(ThreadState.Stopped);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Threading;

namespace System.Runtime.ExceptionServices
{
public delegate bool UnhandledExceptionHandler(System.Exception exception);

public static class ExceptionHandling
{
internal static UnhandledExceptionHandler? s_handler;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,7 @@
<Compile Include="System\Runtime\CompilerServices\ClassConstructorRunner.cs" />
<Compile Include="System\Runtime\CompilerServices\InlineArrayAttribute.cs" />
<Compile Include="System\Runtime\CompilerServices\StaticClassConstructionContext.cs" />
<Compile Include="System\Runtime\ExceptionServices\ExceptionHandling.cs" />
<Compile Include="System\Runtime\InteropServices\InAttribute.cs" />
<Compile Include="System\Diagnostics\DebuggerStepThroughAttribute.cs" />
<Compile Include="System\Diagnostics\StackTraceHiddenAttribute.cs" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2572,6 +2572,9 @@
<data name="InvalidOperation_CannotRegisterSecondResolver" xml:space="preserve">
<value>A resolver is already set for the assembly.</value>
</data>
<data name="InvalidOperation_CannotRegisterSecondHandler" xml:space="preserve">
<value>A handler for unhandled exceptions 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
Expand Up @@ -917,6 +917,7 @@
<Compile Include="$(MSBuildThisFileDirectory)System\Runtime\ConstrainedExecution\PrePrepareMethodAttribute.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Runtime\ConstrainedExecution\ReliabilityContractAttribute.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Runtime\ExceptionServices\ExceptionDispatchInfo.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Runtime\ExceptionServices\ExceptionHandling.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Runtime\ExceptionServices\FirstChanceExceptionEventArgs.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Runtime\ExceptionServices\HandleProcessCorruptedStateExceptionsAttribute.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Runtime\GCFrameRegistration.cs" Condition="'$(FeatureMono)' != 'true'" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Threading;

namespace System.Runtime.ExceptionServices
{
public delegate bool UnhandledExceptionHandler(System.Exception exception);

@teo-tsirpanis teo-tsirpanis Nov 26, 2024

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@VSadov the approved API shape used Func<Exception, bool> instead of a custom delegate.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@VSadov the approved API shape used Func<Exception, bool> instead of a custom delegate.

@VSadov do you have plans to address this? We cannot check in new unapproved public APIs.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Opened #110254.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

do you have plans to address this? We cannot check in new unapproved public APIs.

Yes. It was an oversight.
The approved shape was the same as in proposal except for this part. I missed that there was a diff from the proposal.


public static class ExceptionHandling
{
internal static UnhandledExceptionHandler? s_handler;

/// <summary>
/// Sets a handler for unhandled exceptions.
/// </summary>
/// <exception cref="ArgumentNullException">If handler is null</exception>
/// <exception cref="InvalidOperationException">If a handler is already set</exception>
public static void SetUnhandledExceptionHandler(UnhandledExceptionHandler handler)
{
ArgumentNullException.ThrowIfNull(handler);

if (Interlocked.CompareExchange(ref s_handler, handler, null) != null)
{
throw new InvalidOperationException(SR.InvalidOperation_CannotRegisterSecondHandler);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.ExceptionServices;
using System.Runtime.Versioning;
using System.Security.Principal;

Expand Down Expand Up @@ -69,18 +70,25 @@ private void RunWorker()
AutoreleasePool.CreateAutoreleasePool();
#endif

if (start is ThreadStart threadStart)
try
{
threadStart();
}
else
{
ParameterizedThreadStart parameterizedThreadStart = (ParameterizedThreadStart)start;
if (start is ThreadStart threadStart)
{
threadStart();
}
else
{
ParameterizedThreadStart parameterizedThreadStart = (ParameterizedThreadStart)start;

object? startArg = _startArg;
_startArg = null;
object? startArg = _startArg;
_startArg = null;

parameterizedThreadStart(startArg);
parameterizedThreadStart(startArg);
}
}
catch (Exception ex) when (ExceptionHandling.s_handler != null && ExceptionHandling.s_handler(ex))
{
// the handler returned "true" means the exception is now "handled" and we should gracefully exit.
}

#if FEATURE_OBJCMARSHAL
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Tracing;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Threading.Tasks;
Expand Down Expand Up @@ -1187,12 +1188,21 @@ private static void DispatchWorkItem(object workItem, Thread currentThread)
{
if (workItem is Task task)
{
// Task workitems catch their exceptions for later observation
// We do not need to pass unhandled ones to ExceptionHandling.s_handler
task.ExecuteFromThreadPool(currentThread);
}
else
{
Debug.Assert(workItem is IThreadPoolWorkItem);
Unsafe.As<IThreadPoolWorkItem>(workItem).Execute();
try
{
Unsafe.As<IThreadPoolWorkItem>(workItem).Execute();
}
catch (Exception ex) when (ExceptionHandling.s_handler != null && ExceptionHandling.s_handler(ex))
{
// the handler returned "true" means the exception is now "handled" and we should continue.
}
}
}
}
Expand Down
5 changes: 5 additions & 0 deletions src/libraries/System.Runtime/ref/System.Runtime.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13955,6 +13955,11 @@ public sealed partial class HandleProcessCorruptedStateExceptionsAttribute : Sys
{
public HandleProcessCorruptedStateExceptionsAttribute() { }
}
public delegate bool UnhandledExceptionHandler(System.Exception exception);
public static partial class ExceptionHandling
{
public static void SetUnhandledExceptionHandler(UnhandledExceptionHandler handler) { throw null; }
Comment thread
jkotas marked this conversation as resolved.
Outdated
}
}
namespace System.Runtime.InteropServices
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
project (ForeignThreadRevPInvokeUnhandledNative)
Comment thread
jkotas marked this conversation as resolved.

include_directories(${INC_PLATFORM_DIR})

if(CLR_CMAKE_HOST_OSX)
# Enable non-POSIX pthreads APIs, which by default are not included in the pthreads header
add_definitions(-D_DARWIN_C_SOURCE)
endif(CLR_CMAKE_HOST_OSX)

set(SOURCES ForeignThreadRevPInvokeUnhandledNative.cpp)

if(NOT CLR_CMAKE_HOST_WIN32)
add_compile_options(-pthread)
endif()

# add the executable
add_library (ForeignThreadRevPInvokeUnhandledNative SHARED ${SOURCES})

# add the install targets
install (TARGETS ForeignThreadRevPInvokeUnhandledNative DESTINATION bin)
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
// 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.Threading;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using Xunit;

public delegate void MyCallback();

public class PInvokeRevPInvokeUnhandled
{
[DllImport("ForeignThreadRevPInvokeUnhandled")]
public static extern void InvokeCallback(MyCallback callback);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I cannot see this being used in this test

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I just copied the file between two tests. One uses InvokeCallback another uses InvokeCallbackOnNewThread. I can remove redundant ones.


[DllImport("ForeignThreadRevPInvokeUnhandled")]
public static extern void InvokeCallbackOnNewThread(MyCallback callback);

[ThreadStatic]
private static Exception lastEx;
private static bool expectUnhandledException = false;

private static bool Handler(Exception ex)
{
lastEx = ex;
return true;
}

private static void SetHandler()
{
System.Runtime.ExceptionServices.ExceptionHandling.SetUnhandledExceptionHandler(Handler);
}

// test-wide setup
static PInvokeRevPInvokeUnhandled()
{
AppDomain.CurrentDomain.UnhandledException += (_, _) =>
{
if (expectUnhandledException &&
lastEx == null)
{
Environment.Exit(100);
}
};

SetHandler();
}

public static void RunTest()
{
// sanity check, the handler should be working in a separate thread
Thread th = new Thread(() =>
{
try
{
lastEx = null;
throw new Exception("here is an unhandled exception1");
Assert.Fail();
}
finally
{
Assert.Equal("here is an unhandled exception1", lastEx.Message);
}
});

th.Start();
th.Join();

expectUnhandledException = true;
InvokeCallbackOnNewThread(() => {
try
{
lastEx = null;
throw new Exception("here is an unhandled exception2");
Assert.Fail();
}
finally
{
Assert.Null(lastEx);
}
});

Assert.Fail();
}

public static int Main()
{
RunTest();

// should not reach here
return 42;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<!-- Needed for CMakeProjectReference -->
<RequiresProcessIsolation>true</RequiresProcessIsolation>
<!-- Test requires EH-clean Main -->
<ReferenceXUnitWrapperGenerator>false</ReferenceXUnitWrapperGenerator>
<CLRTestPriority>0</CLRTestPriority>
<MonoAotIncompatible>true</MonoAotIncompatible>
</PropertyGroup>
<ItemGroup>
<Compile Include="ForeignThreadRevPInvokeUnhandled.cs" />
</ItemGroup>
<ItemGroup>
<CMakeProjectReference Include="CMakeLists.txt" />
</ItemGroup>
</Project>
Loading