I hope someone can help me out with my problem. Currently I'm working with C# and use the library Mono.Cecil to add Instruction Code before a method exits. There is this one case, when a if statement is at the end of a method and I want to add TraceUtil.TraceMethodExit(b); at the end, it ends up in the if statement, but it should be outside at the end. I use exactly the same Instructions which the compiler? produces, when I would manualy would put the TraceUtil.TraceMethodExit(b); at the end. But still mine ends up in the if statement body.
but it should look like this:
Here are what the compiler? produces:
IL_0000: nop
IL_0001: ldarg.1
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: brfalse.s IL_0013
IL_0006: nop
IL_0007: ldstr "TEST"
IL_000c: call System.Void UnityEngine.Debug::Log(System.Object)
IL_0011: nop
IL_0012: nop
IL_0013: ldnull
IL_0014: call System.Void SEE.Utils.TraceUtil::TraceMethodExit(System.Object[])
IL_0019: nop
IL_001a: ret
Here are what will be the output when I add the instructions:
IL_0000: nop
IL_0001: ldarg.1
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: brfalse.s IL_001a
IL_0006: nop
IL_0007: ldstr "TEST"
IL_000c: call System.Void UnityEngine.Debug::Log(System.Object)
IL_0011: nop
IL_0012: nop
IL_0013: ldnull
IL_0014: call System.Void SEE.Utils.TraceUtil::TraceMethodExit(System.Object[])
IL_0019: nop
IL_001a: ret
Here is the Code/Method to add the additional instructions:
private static void TraceZeroParameterMethodExit(ILProcessor iLProc, Instruction instr, MethodReference mRef)
{
MethodBodyRocks.SimplifyMacros(iLProc.Body);
iLProc.InsertBefore(instr, Instruction.Create(OpCodes.Ldnull));
iLProc.InsertBefore(instr, Instruction.Create(OpCodes.Call, mRef));
iLProc.InsertBefore(instr, Instruction.Create(OpCodes.Nop));
MethodBodyRocks.OptimizeMacros(iLProc.Body);
}
Does anyone have a idea how this could be solved? Maybe it has to do with the Offset? Thanks for any help!
brfalse.s
is not updated and points out incorrectly.br/br.s
opcodes to point to your new opcode. I have a video on my channel where I'm showing how something similar can be done.ExceptionHandlers
- check what's insideilProcessor.Body.ExceptionHandlers