Udostępnij za pośrednictwem


MSIL Verification Notes - 3

Below code tries to return a ByRef object which points on a stack location.

CLR rule considers this kind of ByRef object is not safe to return to the caller.

.method public instance int32& modopt([Microsoft.VisualC]Microsoft.VisualC.IsCXXPointerModifier)
          retLocalByref() cil managed
  {
    // Code size       30 (0x1e)
    .maxstack  2
    .locals init (int32 V_0)
    IL_0000:  ldstr      "Returning local byref"
    IL_0005:  ldloc.0
    IL_0006:  box        [mscorlib]System.Int32
    IL_000b:  call       void [mscorlib]System.Console::WriteLine(string,
                                                                  object)
                                                                 
    ldloca 0
                                                                     
    IL_001d:  ret
  }

This actually makes sense. When a method call returns the stack will be reused by other methods. If a dangling pointer randomly points to a stack location, it could do possibly anything to break type safety.

Here is the Peverify result.

 [IL]: Error: [xxx.dll : C::retLocalByref][mdToken=0x6000003][offset 0x00000014] Return type is
ByRef, TypedReference, ArgHandle, or ArgIterator.(Error: 0x80131870) 

The equivalent C# code looks like below.

     ()   (){     V_0;    .(, );     (  ()) &;}
 

Comments