Search code examples
c#.netcilmono.cecil

.NET CIL manipulation of evaluation stack


I have this sequence of CIL codes which I injected through the use of Mono.Cecil. However, the modified .NET C# application will not run.

Objective: Manually load and pop values from stack to display in Console.WriteLine

 for (int i = 0; i < 3; i++)
        {
            int z = some value popped manually from stack;                 
            Console.WriteLine(z);
        }

This is the simple main() program I modified:

.method private hidebysig static void Main(string[] args) cil managed
{

    .entrypoint
    .maxstack 5
    .locals init (
        [0] int32 num,
        [1] int32 num2)
    L_0000: ldc.i4.6 //manually push value 6 to stack
    L_0001: ldc.i4.5 //manually push value 5 to stack
    L_0002: ldc.i4.4 //manually push value 4 to stack
    L_0003: ldc.i4.0 //push int i initial value 0 to stack 
    L_0004: stloc.0 //pop and store to int i variable to variable num
    L_0005: br.s L_0013
    L_0007: nop 
    L_0008: stloc.1 //pop the pushed values 6,5 and 4 to variable num2
    L_0009: ldloc.1 //load value of num2 to stack
    L_000a: call void [mscorlib]System.Console::WriteLine(int32) //pop value of num2 and print
    L_000f: ldloc.0 //load previous value in variable num to stack
    L_0010: ldc.i4.1 //load incremental value 1 to stack
    L_0011: add //pop and add the top 2 values, result is pushed to stack
    L_0012: stloc.0 //store the new result to variable num. (int i)
    L_0013: ldloc.0 //push int i variable value to stack
    L_0014: ldc.i4.3 //push value 3 to stack as number of times to loop
    L_0015: blt.s L_0007 //branch less than (pop and cmp the top 2 values in stack)
    L_0017: ret 
}

However, the above code cannnot run. I tried changing blt.s to clt and br_true.s but it doesn't work either. Does anyone know if it is possible to attain my objective? Thanks.

EDIT: According to ECMA-335, III.1.7.5, there might be a backward branch constraint. Not sure if this is the case.

In particular, if that single-pass analysis arrives at an instruction, call it location X, that immediately follows an unconditional branch, and where X is not the target of an earlier branch instruction, then the state of the evaluation stack at X, clearly, cannot be derived from existing information. In this case, the CLI demands that the evaluation stack at X be empty.


Solution

  • You IL-Code looks ok, but i think the CLR might not be able to check if the stack is corrupted after the method completes. When something is pushed onto the stack, the CLR checks if the value are also popped from the stack.

    So if you push 3 values onto the stack the CLR not might be able to check if your loop is running three times, so the CLR doesn't know if there are still values onto the stack when the method is returning.