about
07/06/2024
CsBites - Execution
C# Bites - Execution
CIL, C# virtual machine, multi-phase translation
1.0 C# Program Code
2.0 C# Program Code Disassembly
3.0 CIL Processing
-
It starts by defining
maxstack , the length of the CIL stack forMain , presumably a fixed buffer based on program analysis. -
Then defines
locals , an array of local storage for the variablesa ,b , andc which will be accessed with indexes attached to CIL opcodes. -
A
nop presumably used for a debugger hook, which probably would not be there if the program was compiled in "Release" mode. -
A
ldstr "hello C# world" which pushes a reference to the literal string into the CIL stack. -
The call
void pops the literal string reference from the stack and passes it to the named method....Console:: WriteLine (string) -
ldc.i4.1 pushes ani32 int with literal value of1 onto the CIL stack. -
stloc.0 pops that value and stores it inlocals storage using index of 0. -
Repeats that process for
b . -
At this point the stack is empty and
locals holds values fora andb -
the next statements
ldloc.0 andldloc.1 push the local values fora andb onto the stack, callsadd which pops off the two locals, adds them, and pushes the result back onto the stack. -
stloc.2 pops the result and stores it into local storage at index 2. - A reference to the literal output format string is pushed onto the stack.
-
The next statements push local variable
a onto the stack, box the value by storing in the managed heap and replacinga with its boxed reference. -
That process is repeated for
b andc . -
At this point, the CIL stack has the three local variables and and output format string reference
on the heap, e.g., four items hence
maxstack has the value 4. -
finally,
System.Console:: is called that uses the stack contents as arguments and displays the result on the terminal.WriteLine (string, object, object, object) -
then
Main returns ending the program.
4.0 Conclusions
5.0 References:
Reference | Description |
---|---|
dotPeek - JetBrains decompiler | Tool for translating between assemblies <--> CIL <--> C# source |
C# Tutorial - w3shools | Simple tutorial with guided exercises |
Understanding CIL - Code Project | Clear introduction to the Common Intermediate Language |
Common Intermediate Language - Wikipedia | Quick summary |
List of CIL Instructions - Wikipedia | Extensive list, useful for reference |