jbevain / mono.reflection

Some useful reflection helpers, including an IL disassembler.
150 stars 50 forks source link

Non-standard IL code can crash the library #8

Closed xanatos closed 8 years ago

xanatos commented 9 years ago

Normally the this parameter is ldarg.0 . If you write "by hand" the IL code, it isn't illegal to use ldarg 0 or _ldargs 0 (where 0 in this case is the operand). This will break the Mono.Reflection at this line:

    ParameterInfo GetParameter (int index)
    {
        return parameters [method.IsStatic ? index : index - 1];
    }

in the MethodBodyReader.cs, because index will be 0, 0 - 1 == -1, parameters[-1] = IndexOutOfRangeException

jbevain commented 9 years ago

Yep. Not sure how to properly represent it with the SR object model though.

jbevain commented 9 years ago

One elegant way to fix it would be to explicitely check for ldarg 0 and return an instruction with ldarg.0.

xanatos commented 9 years ago

No, that would change the IL code... Better to return null...

jbevain commented 9 years ago

Yes, that's a much better solution.

xanatos commented 9 years ago

Or:

public class ThisParameter : ParameterInfo
{
    public ThisParameter(MemberInfo member)
    {
        NameImpl = "0";
        ClassImpl = member.DeclaringType;
        MemberImpl = member;
        PositionImpl = -1;
    }
}

private ParameterInfo thisParameter = null;

ParameterInfo GetParameter (int index)
{
    if (!method.IsStatic && index == 0)
    {
        return thisParameter ?? (thisParameter = new ThisParameter(method));
    }

    return parameters [method.IsStatic ? index : index - 1];
}

(made the parameter construction lazy, so that there is a single instance of it)

jbevain commented 8 years ago

Fixed in d157f3a6080681d56646ce2f14c736622921a11d.

Thanks!