Skip to content

Commit

Permalink
Merge pull request #24 from nedavni/Fix_NullRef_LdElem
Browse files Browse the repository at this point in the history
Fixed NullReferenceException in scenario with branches & Ldelem
  • Loading branch information
Anton92nd authored Dec 25, 2020
2 parents f666e8f + ba23b76 commit d6bdb9d
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 1 deletion.
71 changes: 71 additions & 0 deletions GrEmit.Tests/Test.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.InteropServices;
using System.Text;

using GrEmit.Utils;

Expand All @@ -18,6 +19,76 @@ namespace GrEmit.Tests
[TestFixture]
public class Test
{
[Test]
public void Test_LdElem_OnClass_ShouldEmitType()
{
// private static string ClearAll(StringBuilder[] input)
// {
// string result = string.Empty;
//
// for (int i = 0; i < input.Length; ++i)
// {
// result = string.Concat(result, input[i]);
// }
// return result;
// }

var method = new DynamicMethod(nameof(Test_LdElem_OnClass_ShouldEmitType), typeof(string), new[] {typeof(StringBuilder[])}, typeof(Test));
using (var il = new GroboIL(method))
{
var index = il.DeclareLocal(typeof(int));
var result = il.DeclareLocal(typeof(string));

il.Ldc_I4(0);
il.Stloc(index);

il.Ldstr(string.Empty);
il.Stloc(result);

var start = il.DefineLabel("start");
var compare = il.DefineLabel("compare");

il.Br(compare);
il.MarkLabel(start);

il.Ldloc(result);

il.Ldarg(0);
il.Ldloc(index);
il.Ldelem(typeof(StringBuilder));
il.Call(typeof(object).GetMethod(nameof(ToString)));

il.Call(typeof(string).GetMethod(nameof(string.Concat), new[] {typeof(string), typeof(string)}));
il.Stloc(result);

il.Ldloc(index);
il.Ldc_I4(1);
il.Add();
il.Stloc(index);

il.MarkLabel(compare);
il.Ldloc(index);
il.Ldarg(0);
il.Ldlen();
il.Conv<int>();
il.Blt(start, false);

il.Ldloc(result);
il.Ret();
}

var check = "12345";

var inputs = new StringBuilder[check.Length];
for (var i = 0; i < check.Length; i++)
{
inputs[i] = new StringBuilder(check[i].ToString());
}

var func = (Func<StringBuilder[], string>)method.CreateDelegate(typeof(Func<StringBuilder[], string>));
Assert.That(func(inputs), Is.EqualTo(check));
}

[Test]
public void TestLocalloc()
{
Expand Down
2 changes: 1 addition & 1 deletion GrEmit/GroboIL.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2131,7 +2131,7 @@ private ILInstructionComment GetComment()

private void Emit(OpCode opCode, TypeILInstructionParameter parameter)
{
var lineNumber = ilCode.Append(opCode, new EmptyILInstructionComment());
var lineNumber = ilCode.Append(opCode, parameter, new EmptyILInstructionComment());
if (analyzeStack && stack != null)
MutateStack(opCode, parameter);
ilCode.SetComment(lineNumber, GetComment());
Expand Down

0 comments on commit d6bdb9d

Please sign in to comment.