Code demonstrating the importance of a Constrained Execution Region

前端 未结 5 2211
耶瑟儿~
耶瑟儿~ 2020-12-23 00:04

Could anyone create a short sample that breaks, unless the [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] is applied?

5条回答
  •  被撕碎了的回忆
    2020-12-23 00:29

    using System;
    using System.Runtime.CompilerServices;
    using System.Runtime.ConstrainedExecution;
    
    class Program {
        static bool cerWorked;
    
        static void Main( string[] args ) {
            try {
                cerWorked = true;
                MyFn();
            }
            catch( OutOfMemoryException ) {
                Console.WriteLine( cerWorked );
            }
            Console.ReadLine();
        }
    
        unsafe struct Big {
            public fixed byte Bytes[int.MaxValue];
        }
    
        //results depends on the existance of this attribute
        [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] 
        unsafe static void StackOverflow() {
            Big big;
            big.Bytes[ int.MaxValue - 1 ] = 1;
        }
    
        static void MyFn() {
            RuntimeHelpers.PrepareConstrainedRegions();
            try {
                cerWorked = false;
            }
            finally {
                StackOverflow();
            }
        }
    }
    

    When MyFn is jitted, it tries to create a ConstrainedRegion from the finally block.

    • In the case without the ReliabilityContract, no proper ConstrainedRegion could be formed, so a regular code is emitted. The stack overflow exception is thrown on the call to Stackoverflow (after the try block is executed).

    • In the case with the ReliabilityContract, a ConstrainedRegion could be formed and the stack requirements of methods in the finally block could be lifted into MyFn. The stack overflow exception is now thrown on the call to MyFn (before the try block is ever executed).

提交回复
热议问题