Hi Koren, Looks like it may be related to a farily common issue: Cecil doesn't turn short forms of OpCodes (like br_s to br) if they argument overflow.
You can easily fix it by using two extensions methods: using Mono.Cecil.Rocks; method.Body.SimplifyMacros(); // do the insert method.Body.OptimzieMacros(); Let us know if it helps, Jb On Sat, Jan 23, 2016 at 5:18 AM, Koren Shoval <[email protected]> wrote: > Hi, > > very new to Emit and Cecil. > looking to insert method calls into my code. > in this example, i am trying to add calls, on each branch statement, inside > my Demo.Do() method > > getting very weird results... depends on the instructions i add probes to > --- > NullReferenceException from IL Spy, > corrupt assembly when running, > stack size mismatch. > > if the code below the right way to inject these calls? what am i doing > wrong? > > Thanks, > Koren > > here's the code. > > // target assembly > class Demo { > void Do() { > //... > } > } > > class Probe { > void Invoke(string, string, string, int, double) { //... } > } > > // in my cecil emitting assembly, > // _module = target assembly > > var staticMethod = _module.Types.First(x => > x.Name.Equals("Probe")).Methods.First(x => x.Name.Equals("Invoke")); > var method = _module.Types.First(x => > x.Name.Equals("Demo")).Methods.First(x=>x.Name.Equals("Do")); > > // get Demo.Do() body > var il = method.Body.GetILProcessor(); > > // get a collection of branch instructions, i want to invoke the Probe at. > (i.e. if (x>10) { probe(); // ... } else { probe(); //... } ) > // i am getting the next nop after the branch statement to avoid splitting > up related il lines > var instructions = method.Body.Instructions > .Where(x => x.OpCode.FlowControl == FlowControl.Cond_Branch) > .Where(x => x.Next != null && x.Next.OpCode.Code == > Code.Nop) > .Select(x => x.Next) > .ToList(); > > // loop on relevant instructions, emit the call to Probe > for (int i = 0; i < instructions.Count; i++) > { > var target = instructions[i]; > > var block = new[] { > il.Create(OpCodes.Ldstr, "p1"), > il.Create(OpCodes.Ldstr, "p2"), > il.Create(OpCodes.Ldstr, "p3"), > il.Create(OpCodes.Ldc_I4, i), > il.Create(OpCodes.Ldc_R8, 0), > il.Create(OpCodes.Call, staticMethod), > il.Create(OpCodes.Nop) > }; > > for (int b = 0; b < block.Length; b++) > { > il.InsertAfter(target, block[b]); > target = block[b]; > } > } > > -- > -- > -- > 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.
