I am experimenting with parsing IL in order to emit a method. I have gotten the IL code of a method in a string[] where each string is an IL instruction. I am looping over this array and adding OpCodes using an ILGenerator:
foreach (string ins in instructions) //string representations of IL
{
string opCode = ins.Split(':').ElementAt(1);
// other conditions omitted
if (opCode.Contains("br.s"))
{
Label targetInstruction = ilGenerator.DefineLabel();
ilGenerator.MarkLabel(targetInstruction);
ilGenerator.Emit(OpCodes.Br_S, targetInstruction);
}
Here is the IL that I need to reproduce:
Source IL:
IL_0000: nop
IL_0001: ldstr "Hello, World!"
IL_0006: stloc.0
IL_0007: br.s IL_0009
IL_0009: ldloc.0
IL_000a: ret
And here is what I am getting as output:
Target IL:
IL_0000: nop
IL_0001: ldstr "Hello, World!"
IL_0006: stloc.0
IL_0007: br.s IL_0007 // this is wrong -- needs to point to IL_0009
IL_0009: ldloc.0
IL_000a: ret
As you can see the br.s call is pointing to itself which of course causes an infinite loop. How do I get it to point to the following instruction as in the source? This has to do with using Reflection.Emit.Label but I'm not sure how it works.
EDIT By the way the IL seen above is for this simple method,
public string HelloWorld()
{
return "Hello, World!";
}
This code:
ilGenerator.MarkLabel(targetInstruction);
ilGenerator.Emit(OpCodes.Br_S, targetInstruction);
clearly says "mark the label here" and then you add the instruction at the point where you marked the label.
If this is not what you want, why are you doing it?
MarkLabel marks the current position, which means the position of the next instruction you output, as the target of the label.
In this case, to get "what you want", simply reverse those two lines, output the branch instruction before marking the label.
I placed "what you want" in quotes since I don't understand the point of that branch instruction. The machine will happily "move" to the next instruction all by itself, there is no need to add "branch to the next instruction" instructions for this to happen.