dotnet / runtime

.NET is a cross-platform runtime for cloud, mobile, desktop, and IoT apps.
https://docs.microsoft.com/dotnet/core/
MIT License
15.29k stars 4.74k forks source link

SEHException after instantiating invalid ManualResetEvent #12158

Open corruptmem opened 5 years ago

corruptmem commented 5 years ago

Not sure if this counts as a bug, but it was unexpected behaviour for me.

Test case:

foreach (var _ in Enumerable.Range(1, 10000))
{            
    new ManualResetEvent(false) { Handle = new IntPtr(1234) };
    GC.Collect();
}

Run under the debugger (Windows, .NET Core 2.2) it will produce a SEHException from the GC finalizer thread:

System.Runtime.InteropServices.SEHException
  HResult=0x80004005
  Message=External component has thrown an exception.
  Stack Trace:
     Microsoft.Win32.Win32Native.CloseHandle(IntPtr handle) at
     System.Runtime.InteropServices.SafeHandle.InternalFinalize() at
     System.Runtime.InteropServices.SafeHandle.Finalize()

Although this is clearly an application code issue (in my case, it came from incorrectly serializing then subsequently deserializing a ManualResetEvent with JsonConvert), because the exception occurs on the finalizer thread some time after the incorrect code is called, it's very difficult to figure out where the code issue came from.

rkuiper1 commented 3 years ago

Hi,

I would like to +1 this issue and add that 'very difficult to figure out where the issue came from' is an understatement. Since about 2 weeks I get exactly this exception which basically makes it impossible to debug. Up until now I've been unsuccessful in finding any clues to what might cause this problem. My project has a modest 180.000 lines of code and I really have no idea what to look for. Debugging the live situation with VS2019 doesn't bring me any closer to understanding what happens nor does analyzing a dump file of the situation with windbg.

'Clearly being an application code issue' suggests that my lack of knowledge is the problem, which is probably true, but I dare to argue that the situation I currently find myself in is at least partially caused by design/security choices in the CLR, given that the code runs without problems when no debugger is attached.

Is there a way to approach this problem and find the problematic code?

cheers, RIchard