MSIL: Simple custom Code says Invalid IL code - System.InvalidProgramException

643 views Asked by At

I'm trying to learn more about .NET MSIL and so I wanted to write my custom IL Assembly. I got stuck with the following example.

First I am on OSX, using Mono "Mono JIT compiler version 4.8.1 (mono-4.8.0-branch/22a39d7 Fri Apr 7 12:00:08 EDT 2017)" and my il assembly looks like. Full file:

.assembly extern mscorlib
{
  .ver 4:0:0:0
  .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
}
.assembly 'Application'
{
  .hash algorithm 0x00008004
  .ver  0:0:0:0
}
.module sample.exe // GUID = {B239DF75-1D4B-4A83-B8B6-99BDEFD7B8A6}


  .class public auto ansi MainType
    extends [mscorlib]System.Object
  {

    // method line 1
    .method public specialname rtspecialname
           instance default void '.ctor' ()  cil managed
    {
        // Method begins at RVA 0x20ec
    // Code size 7 (0x7)
    .maxstack 8
              ldarg.0
              call instance void object::'.ctor'()
              ret
    } // end of method MainType::.ctor

    // method line 2
    .method public static hidebysig
           default void Main (string[] A_0)  cil managed
    {
        // Method begins at RVA 0x20f4
        .entrypoint
        // Code size 87 (0x57)
        .maxstack 6
        .locals init (
          int32[]   V_0,
          int32 V_1)
                  // Allocating array of size 200
                  ldc.i4 200
                  newarr int32[]
                  stloc.0

                  // Pushing the numbers I want to output
                  ldc.i4 100
                  ldc.i4 101
                  ldc.i4 102

                  // 3 is the total number of previous pushed numbers
                  // it functions in this programm as a counter which
                  // will be decremented
                  ldc.i4 3
                  stloc.1      // storing the 3 in the temp variable V_1

                  ldloc.0      // push the array reference onto stack 
                  ldc.i4 0     // push the index onto the stack 
                  ldloc.1      // loading the 3 from the temp int32 var (V_1), push it onto the stack 
                  stelem.i4    // save the value into the array at index 0 (defined above aka pushed on the stack)

                  // when it enters first, on the top of the stack should
                  // be the value 102 which we want to print out:
           loop:  call void class [mscorlib]System.Console::WriteLine(int32) // the call should consume 102 from the stack and print it out

                  // loading the counter from array
                  ldloc.0
                  ldc.i4 0
                  ldelem.i4

                  ldc.i4 1   // pushing 1
                  sub        // subtract the counter by 1

                  // Storing the result which is on the stack
                  // in the array index 0 (our counter):
                  stloc.1
                  ldloc.0
                  ldc.i4 0
                  ldloc.1
                  stelem.i4

                  // Loading the counter value again onto stack to perform
                  // the check for branching:
                  ldloc.0
                  ldc.i4 0
                  ldelem.i4

                  ldc.i4 0 // pushing 0 to see if the counter is 0
                  ceq
                  brfalse loop // if its not yet 0 then we jump to the loop label; which means it should on the next call to WriteLine consume the next value which is on the stack, which should be 101

                  ret
    } // end of method MainType::Main

  } // end of class MainType

The interesting or the "problematic" part is here:

    .method public static hidebysig
           default void Main (string[] A_0)  cil managed
    {
        // Method begins at RVA 0x20f4
        .entrypoint
        // Code size 87 (0x57)
        .maxstack 6
        .locals init (
          int32[]   V_0,
          int32 V_1)
                  // Allocating array of size 200
                  ldc.i4 200
                  newarr int32[]
                  stloc.0

                  // Pushing the numbers I want to output
                  ldc.i4 100
                  ldc.i4 101
                  ldc.i4 102

                  // 3 is the total number of previous pushed numbers
                  // it functions in this programm as a counter which
                  // will be decremented
                  ldc.i4 3
                  stloc.1      // storing the 3 in the temp variable V_1

                  ldloc.0      // push the array reference onto stack 
                  ldc.i4 0     // push the index onto the stack 
                  ldloc.1      // loading the 3 from the temp int32 var (V_1), push it onto the stack 
                  stelem.i4    // save the value into the array at index 0 (defined above aka pushed on the stack)

                  // when it enters first, on the top of the stack should
                  // be the value 102 which we want to print out:
           loop:  call void class [mscorlib]System.Console::WriteLine(int32) // the call should consume 102 from the stack and print it out

                  // loading the counter from array
                  ldloc.0
                  ldc.i4 0
                  ldelem.i4

                  ldc.i4 1   // pushing 1
                  sub        // subtract the counter by 1

                  // Storing the result which is on the stack
                  // in the array index 0 (our counter):
                  stloc.1
                  ldloc.0
                  ldc.i4 0
                  ldloc.1
                  stelem.i4

                  // Loading the counter value again onto stack to perform
                  // the check for branching:
                  ldloc.0
                  ldc.i4 0
                  ldelem.i4

                  ldc.i4 0 // pushing 0 to see if the counter is 0
                  ceq
                  brfalse loop // if its not yet 0 then we jump to the loop label; which means it should on the next call to WriteLine consume the next value which is on the stack, which should be 101

                  ret
    } // end of method MainType::Main

The error I'm getting is the following:

Unhandled Exception:
System.InvalidProgramException: Invalid IL code in MainType:Main         (string[]): IL_0056: ret       


[ERROR] FATAL UNHANDLED EXCEPTION: System.InvalidProgramException:     Invalid IL code in MainType:Main (string[]): IL_0056: ret       

And the "IL_0056: ret" points to the line (when I disassemble the resulting executable):

IL_0044:  ldc.i4 0
IL_0049:  ldelem.i4 
IL_004a:  ldc.i4 0
IL_004f:  ceq 
IL_0051:  brfalse IL_0028

IL_0056:  ret   //// <<<< HERE
} // end of method MainType::Main

Some important notes: * When storing & assigning to the array it seems that I always make some unnecessary "dances". I do this because in the end I want to create a stack machine and which only works with values from the stack. That's also the reason why the code looks like this. Before writing it I wanted to see how I could do it in MSIL.

I would really appreciate if someone could tell me what is wrong here. Thank you very much.

It's my first question here and I hope I have provided all the necessary infos in order to help me :-)

PS: I also tried to use MonoDevelop with "Debug Application" but I couldn't really get any meaningful data out of it, neither has gdb worked for me well.

PPS: I was thinking that I still have values on the stack left but when I add a pop at the end (or more) then it simply tells me that the 'pop' is invalid.

EDIT:

I tried to print some sort of output to see what's going wrong and I figured out that in between the 'loop' label it does not pop the value from the stack correctly. I could not yet figure out why, but here is an example output which shows it clearly:

102
LOOP START
101
---
101
---
101
---
exit now
100

Even if I modify the il code further, so it prints more values:

LOOP START
102
101
100
---
102
101
100
---
102
101
100
---
exit now

it does not pop from the stack. For some strange reasons making a 'call WriteLine' does not pop the value, or as it seems it does backup & restore the stack but that's just my assumption. Has this to do anything with the: .NET CIL manipulation of evaluation stack ("Backward Branch Constraints", Link: http://jilc.sourceforge.net/ecma_p3_cil.shtml)

0

There are 0 answers