I get a corrupted state exception (CSE) in my application using the framework .NET 4.5.1. This exception taken from the event viewer is:
Framework Version: v4.0.30319
Description: The process was terminated due to an internal error in the .NET Runtime at IP 000007FEEB8F75CB (000007FEEB7B0000) with exit code 80131506.
I get the same exception into the event viewer by using the following code from the issue How to simulate a corrupt state exception in .NET 4?:
using System;
using System.Runtime.InteropServices;
class Program {
unsafe static void Main(string[] args)
{
var obj = new byte[1];
var pin = GCHandle.Alloc(obj, GCHandleType.Pinned);
byte* p = (byte*)pin.AddrOfPinnedObject();
for (int ix = 0; ix < 256; ++ix) *p-- = 0;
GC.Collect(); // kaboom
}
}
I use the attributes HandleProcessCorruptedStateExceptions and SecurityCritical on the handler of event UnhandledException as discussed in the haindl's response for the issue Gracefully handling corrupted state exceptions.
But I cannot catch this error with it. Why ?
That works with a access violation generated with:
private static unsafe void AccessViolation()
{
byte b = *(byte*) (8762765876);
}
The code of the handler where I log the error message is executed but of course, I don't get the same error as in my application.
UPDATE:
I attempt to catch the CSE by reproducing the 3 steps described in this issue:
Recompile as a .NET 3.5 assembly and run it in .NET 4.0.
Add a line to your application's config file under the configuration/runtime element:
Decorate the methods you want to catch these exceptions in with the HandleProcessCorruptedStateExceptions attribute. See http://msdn.microsoft.com/en-us/magazine/dd419661.aspx#id0070035 for details.
But that does not work for me !
My code is:
using System;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Security;
namespace Test
{
class Program
{
[HandleProcessCorruptedStateExceptions]
[SecurityCritical]
static void Main(string[] args)
{
while (true)
{
try
{
PerformException();
}
catch (Exception ex)
{
Console.WriteLine("Error");
}
}
}
[HandleProcessCorruptedStateExceptions]
[SecurityCritical]
unsafe static void PerformException()
{
var obj = new byte[1];
var pin = GCHandle.Alloc(obj, GCHandleType.Pinned);
byte* p = (byte*)pin.AddrOfPinnedObject();
for (int ix = 0; ix < 256; ++ix) *p-- = 0;
GC.Collect(); // CSE occurs here.
}
}
}
My app.config file is:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<runtime>
<legacyCorruptedStateExceptionsPolicy enabled="true"/>
</runtime>
</configuration>
Why is the CSE not caught ?
Note I must allow the code to build with the unsafe mode because it is required by the following line code:
byte* p = (byte*)pin.AddrOfPinnedObject();
I repeat it's only for debugging. The goal is to find the code part which occurs this error type in a greater application in order to bring a fix.