How to simulate a corrupt state exception in .NET

2019-01-15 00:14发布

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"?

3条回答
小情绪 Triste *
2楼-- · 2019-01-15 00:59

Just dereference a random number:

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

or overflow the stack:

    private static void StackOverflow()
    {
        StackOverflow();
    }
查看更多
Luminary・发光体
3楼-- · 2019-01-15 01:08

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);
    }
}
查看更多
仙女界的扛把子
4楼-- · 2019-01-15 01:09

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
  }
}
查看更多
登录 后发表回答