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

后端 未结 3 1844
春和景丽
春和景丽 2020-12-06 06:45

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

HandleProcessCorruptedStateExceptionsAttribute Class

I want to test this

相关标签:
3条回答
  • 2020-12-06 07:06

    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);
        }
    }
    
    0 讨论(0)
  • Just dereference a random number:

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

    or overflow the stack:

        private static void StackOverflow()
        {
            StackOverflow();
        }
    
    0 讨论(0)
  • 2020-12-06 07:17

    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
      }
    }
    
    0 讨论(0)
提交回复
热议问题