How to simulate a corrupt state exception in .NET 4?

♀尐吖头ヾ 提交于 2019-11-26 21:18:02

问题


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


回答1:


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
  }
}



回答2:


Just dereference a random number:

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

or overflow the stack:

    private static void StackOverflow()
    {
        StackOverflow();
    }



回答3:


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);
    }
}


来源:https://stackoverflow.com/questions/2950130/how-to-simulate-a-corrupt-state-exception-in-net-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!