Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code demonstrating the importance of a Constrained Execution Region

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

I just ran through this sample on MSDN and am unable to get it to break, even if I comment out the ReliabilityContract attribute. Finally seems to always get called.

like image 358
Sam Saffron Avatar asked Jul 08 '09 23:07

Sam Saffron


1 Answers

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).

like image 186
jyoung Avatar answered Oct 04 '22 13:10

jyoung