10

Well, in .NET 4 Microsoft added the HandleProcessCorruptedStateExceptions attribute:

HandleProcessCorruptedStateExceptionsAttribute Class

I want to test this feature. How can I bring my application to a "corrupt state"?

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
  • 2
    Lets say you catch it. What are you going to do with it? –  Jun 01 '10 at 13:37
  • 4
    Log it. We have a production crash with no logs whatsoever. This new log will help us. –  Jun 01 '10 at 14:00

3 Answers3

14

Screwing up the garbage collected heap is always a good way:

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
  }
}
Hans Passant
  • 873,011
  • 131
  • 1,552
  • 2,371
13

Just dereference a random number:

    private static unsafe void AccessViolation()
    {
        byte b = *(byte*) (8762765876);
    }

or overflow the stack:

    private static void StackOverflow()
    {
        StackOverflow();
    }
Roman Starkov
  • 52,420
  • 33
  • 225
  • 300
  • 4
    According to Microsoft, StackOverflowException is not a CSE (Corrupted State Exception) and cannot be caught as one: http://dotnetslackers.com/articles/net/All-about-Corrupted-State-Exceptions-in-NET4.aspx#s4-corrupted-state-exceptions-cses-in-net4 – Abel Nov 29 '13 at 01:38
0

Test HandleProcessCorruptedStateExceptions feature:

using System.Diagnostics;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
...

[HandleProcessCorruptedStateExceptions]
public void HandleCorruptedStateException()
{
    try
    {
        var ptr = new IntPtr(42);
        Marshal.StructureToPtr(42, ptr, true);
    }
    catch(Exception ex)
    {
         Debug.WriteLine(ex.Message);
    }
}
Andrei Krasutski
  • 3,487
  • 1
  • 21
  • 33