Mono.Cecil weaver messed up branch targets
I'm trying to write a simple Cecil-based weaver that simply logs each seqeunce point. This is simple, I can iterate over all of the sequence points and insert an Ldstr to load the log text and a Call instruction to something like Console.WriteLine. To make sure that branch targets don't get missed out on this logging, I go through the instructions again, and patch each branch target to make sure that they now point to these preceding log instructions. The weaver code is attached because it's too big for discord (only 120 lines tho).
It works for loops, if-else statements, but for some reason when I use an if-else in a for loop, the jump targets get completely messed up. The smallest example I could find where it messes up is weaving this:
While some branch targets seem to be correct in the generated IL, the jump back at the very end points to an address higher than the last instruction (picture from ILSpy). Since loops and if-elses on their own work, I don't think it's particularly backwards jumps on their own that mess up the logic, but I could not figure out what it is. Anyone sees what the problem could be?
2 Replies
Ofc I have to dig up the cecil source code for this
So in case of short-form jumps, Cecil won't care to change it in case the jump target is too far away.
But they wrote a utility
Before patching, you call
method.Body.SimplifyMacros();
After you call method.Body.OptimizeMacros();
yeah wanted to say that, cecil breaks when you aren't careful with short branches
also for whatever reason it also breaks when you rename methods
not sure why it uses names and not metadata tokens for those