Hi,

Yes that's a common issue.

Because it is common Cecil should probably do it for you, but in the
meantime I suggest you use the helper function in Mono.Cecil.Rocks to
transform all short forms into long forms before modifying the code,
and then optimize it again after the method body is final:

That would looks like:

using Mono.Cecil.Rocks;

MethodBody body = ...;

body.SimplifyMacros();

// modify body

body.OptimizeMacros();

Jb


On Fri, Jun 27, 2014 at 9:30 PM, Jonathan Piché <[email protected]> wrote:
> Hi,
>
> I noticed that most of the time, Cecil correctly updates branch offset
> targets when weaving in new IL instructions. For instance, adding a simple
> "ldstr" followed by a call to Console.WriteLine will correctly offset the
> branches below to the new instruction offsets.
>
>
> However, Cecil doesn't seem to correctly update offsets if the target
> instruction is changed.
>
> Consider a brtrue_s that points to the final instruction of a method. In
> order to wrap the method in a try/finally, I am adding a new final ret
> instruction, and then changing all previous returns into new leave
> instructions to the new final instruction (else you branch out of a try
> block, which is invalid).
>
> In the above case, the branch offset will remain what it was originally: no
> correction is made. Of course, the original instruction is no longer in the
> list of instructions; it was replaced with a new one.
>
>
> I tried with a direct assignation (Instructions[index] = newInstruction) and
> also with (ilProcessor.Replace(Instructions[index], newInstruction). Both
> will create the bug.
>
> The workaround is to change the instruction to ensure that the object
> reference is the same. so: Instructions[index].OpCode =
> newInstruction.OpCode; Instructions[index].Operand = newInstruction.Operand;
>
>
> My question is: Shouldn't this be what .Replace does? Is there another way
> to deal with this behavior?
>
>
> Thanks!
>
>
> Note: I included a text file with my weaving code and the problematic
> method. The problematic branch is the first one (brtrue.s IL_009b on my
> machine).
>
> --
> --
> --
> mono-cecil
> ---
> You received this message because you are subscribed to the Google Groups
> "mono-cecil" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to [email protected].
> For more options, visit https://groups.google.com/d/optout.

-- 
-- 
--
mono-cecil
--- 
You received this message because you are subscribed to the Google Groups 
"mono-cecil" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
For more options, visit https://groups.google.com/d/optout.

Reply via email to