Skip to content

Commit

Permalink
A minimum tactical fix for issue #697 (#698)
Browse files Browse the repository at this point in the history
* Provoke the issue

* Minimum fix

(cherry picked from commit 0f23047)

* Revert "Provoke the issue"

This reverts commit 1a2275b.

* Add unit test

(cherry picked from commit 185ba88)

* Use existing infrastructure

* Quick fix

Co-authored-by: Jb Evain <[email protected]>
  • Loading branch information
SteveGilham and jbevain authored Oct 15, 2020
1 parent 24c6ce4 commit 77f7bd1
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 2 deletions.
12 changes: 10 additions & 2 deletions Mono.Cecil.Cil/MethodBody.cs
Original file line number Diff line number Diff line change
Expand Up @@ -401,15 +401,23 @@ InstructionOffset ResolveInstructionOffset(InstructionOffset inputOffset, ref In
for (int i = cache.Index; i < items.Length; i++) {
cache.Index = i;
cache.Offset = size;
cache.Instruction = items [i];

var item = items [i];

// Allow for trailing null values in the case of
// instructions.Size < instructions.Capacity
if (item == null)
break;

cache.Instruction = item;

if (cache.Offset == offset)
return new InstructionOffset (cache.Instruction);

if (cache.Offset > offset)
return new InstructionOffset (items [i - 1]);

size += items [i].GetSize ();
size += item.GetSize ();
}

return new InstructionOffset ();
Expand Down
23 changes: 23 additions & 0 deletions Test/Mono.Cecil.Tests/ILProcessorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Cecil.Mdb;
using Mono.Cecil.Pdb;
using NUnit.Framework;

Expand Down Expand Up @@ -40,6 +41,28 @@ public void InsertBefore ()
AssertOpCodeSequence (new [] { OpCodes.Ldloc_0, OpCodes.Ldloc_1, OpCodes.Ldloc_2, OpCodes.Ldloc_3 }, method);
}

[Test]
public void InsertBeforeIssue697 ()
{
var parameters = new ReaderParameters { SymbolReaderProvider = new MdbReaderProvider () };
using (var module = GetResourceModule ("Issue697.dll", parameters))
{
var pathGetterDef = module.GetTypes ()
.SelectMany (t => t.Methods)
.First (m => m.Name.Equals ("get_Defer"));

var body = pathGetterDef.Body;
var worker = body.GetILProcessor ();
var initialBody = body.Instructions.ToList ();
var head = initialBody.First ();
var opcode = worker.Create (OpCodes.Ldc_I4_1);
worker.InsertBefore (head, opcode);
worker.InsertBefore (head, worker.Create (OpCodes.Ret));
initialBody.ForEach (worker.Remove);
AssertOpCodeSequence (new [] { OpCodes.Ldc_I4_1, OpCodes.Ret }, pathGetterDef.body);
}
}

[Test]
public void InsertAfter ()
{
Expand Down
Binary file added Test/Resources/assemblies/Issue697.dll
Binary file not shown.
Binary file added Test/Resources/assemblies/Issue697.dll.mdb
Binary file not shown.

0 comments on commit 77f7bd1

Please sign in to comment.