获取MemberRef元数据令牌的字段是指

时间:2013-10-07 02:56:03

标签: c# .net reflection cil

公平警告,这可能有点深奥和棘手。

鉴于从CIL流中提取的MemberRef(下面有更多解释),你如何确定它指向的字段(如果有的话)(并获得FieldInfo)?

这是我到目前为止所知道的

根据ECMA 335 standard,MemberRef是一个元数据标记,基本上是表中的查找,可以指向字段元数据标记或方法元数据标记。从0x0A开始的任何元数据标记都是MemberRef。

enter image description here

之前我没有遇到其中的一个,但它们似乎并不罕见。我能够通过在方法中使用以下匿名类型来生成一个:

new
{
    A = new DateTime(1234, 5, 6, 7, 8, 9, DateTimeKind.Utc),
    B = (DateTime?)null
}

当我通过反射获取方法体时(获取PropertyInfo,获取GetMethod,获取MethodBody,然后获取get the ILA'获取方法是:

[2, 123, 79, 0, 0, 10, 42]

转换为:

ldarg.0
ldfld 0x0A00004F
ret

如果我反思并获得支持字段(依靠名称相似性来选择<A>i__Field,则无算法)我发现MetadataToken0x04000056

请注意,生成的令牌可能因编辑而异。

以0x04开头的令牌是一个字段: enter image description here

大多数情况下(对于我的有限测试中的所有非匿名对象,实际上)IL包含字段元数据令牌。这很容易变成FieldInfo通过Module.ResolveField(int),弄清楚如何处理会员资料让我失望。

循环使用Module上的其他ResolveXXX方法,唯一可以对MemberRef执行任何操作的方法是ResolveSignature。在上面的MemberRef上运行时,它返回一个[6, 19, 0]数组。我真的不知道该怎么做。

我正在处理的代码尚未完成,但公开。运行this test可以看到错误,导致this line上的字段查找失败时抛出异常。请注意,测试本身尚未完成,预计它不会成功,但也不应该死在那里。

任何人都知道如何制作该签名,或者从MemberRef获取字段的元数据令牌(以及它的FieldInfo)的其他方式?

这是一个重现问题的LINQPad程序脚本。它非常大,有很多样板。

void Main()
{
    Init();

    var obj = 
        new
        {
            A = new DateTime(1234, 5, 6, 7, 8, 9, DateTimeKind.Utc),
            B = (DateTime?)null
        };

    var usage = PropertyFieldUsage(obj.GetType());
    usage.Dump();
}

private static Dictionary<int, System.Reflection.Emit.OpCode> OneByteOps;
private static Dictionary<int, System.Reflection.Emit.OpCode> TwoByteOps;

public static Dictionary<PropertyInfo, List<FieldInfo>> PropertyFieldUsage(Type t)
{
  var ret = new Dictionary<PropertyInfo, List<FieldInfo>>();

  var props = t.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic).Where(p => p.GetMethod != null);

  var module = t.Module;

  foreach (var prop in props)
  {
      var getMtd = prop.GetMethod;
      var mtdBody = getMtd.GetMethodBody();
      var il = mtdBody.GetILAsByteArray();

      var fieldHandles = _GetFieldHandles(il);

      var fieldInfos = 
          fieldHandles
              .Select(
                  f => module.ResolveField(f)
              ).ToList();

      ret[prop] = fieldInfos;
  }

  return ret;
}

// Define other methods and classes here
private static List<int> _GetFieldHandles(byte[] cil)
{
  var ret = new List<int>();

  int i = 0;
  while (i < cil.Length)
  {
      int? fieldHandle;
      System.Reflection.Emit.OpCode ignored;
      var startsAt = i;
      i += _ReadOp(cil, i, out fieldHandle, out ignored);

      if (fieldHandle.HasValue)
      {
          ret.Add(fieldHandle.Value);
      }
  }

  return ret;
}

private static int _ReadOp(byte[] cil, int ix, out int? fieldHandle, out System.Reflection.Emit.OpCode opcode)
{
  const byte ContinueOpcode = 0xFE;

  int advance = 0;

  byte first = cil[ix];

  if (first == ContinueOpcode)
  {
      var next = cil[ix + 1];

      opcode = TwoByteOps[next];
      advance += 2;
  }
  else
  {
      opcode = OneByteOps[first];
      advance++;
  }

  fieldHandle = _ReadFieldOperands(opcode, cil, ix, ix + advance, ref advance);

  return advance;
}

private static int? _ReadFieldOperands(System.Reflection.Emit.OpCode op, byte[] cil, int instrStart, int operandStart, ref int advance)
{
  Func<int, int> readInt = (at) => cil[at] | (cil[at + 1] << 8) | (cil[at + 2] << 16) | (cil[at + 3] << 24);

  switch (op.OperandType)
  {
      case System.Reflection.Emit.OperandType.InlineBrTarget:
          advance += 4;
          return null;

      case System.Reflection.Emit.OperandType.InlineSwitch:
          advance += 4;
          var len = readInt(operandStart);
          var offset1 = instrStart + len * 4;
          for (var i = 0; i < len; i++)
          {
              advance += 4;
          }
          return null;

      case System.Reflection.Emit.OperandType.ShortInlineBrTarget:
          advance += 1;
          return null;

      case System.Reflection.Emit.OperandType.InlineField:
          advance += 4;
          var field = readInt(operandStart);
          return field;

      case System.Reflection.Emit.OperandType.InlineTok:
      case System.Reflection.Emit.OperandType.InlineType:
      case System.Reflection.Emit.OperandType.InlineMethod:
          advance += 4;
          return null;

      case System.Reflection.Emit.OperandType.InlineI:
          advance += 4;
          return null;

      case System.Reflection.Emit.OperandType.InlineI8:
          advance += 8;
          return null;

      case System.Reflection.Emit.OperandType.InlineNone:
          return null;

      case System.Reflection.Emit.OperandType.InlineR:
          advance += 8;
          return null;

      case System.Reflection.Emit.OperandType.InlineSig:
          advance += 4;
          return null;

      case System.Reflection.Emit.OperandType.InlineString:
          advance += 4;
          return null;

      case System.Reflection.Emit.OperandType.InlineVar:
          advance += 2;
          return null;

      case System.Reflection.Emit.OperandType.ShortInlineI:
          advance += 1;
          return null;

      case System.Reflection.Emit.OperandType.ShortInlineR:
          advance += 4;
          return null;

      case System.Reflection.Emit.OperandType.ShortInlineVar:
          advance += 1;
          return null;

      default: throw new Exception("Unexpected operand type [" + op.OperandType + "]");
  }
}

static void Init()
{
  var oneByte = new List<System.Reflection.Emit.OpCode>();
  var twoByte = new List<System.Reflection.Emit.OpCode>();

  foreach (var field in typeof(System.Reflection.Emit.OpCodes).GetFields(BindingFlags.Public | BindingFlags.Static))
  {
      var op = (System.Reflection.Emit.OpCode)field.GetValue(null);

      if (op.Size == 1)
      {
          oneByte.Add(op);
          continue;
      }

      if (op.Size == 2)
      {
          twoByte.Add(op);
          continue;
      }

      throw new Exception("Unexpected op size for " + op);
  }

  OneByteOps = oneByte.ToDictionary(d => (int)d.Value, d => d);
  TwoByteOps = twoByte.ToDictionary(d => (int)(d.Value & 0xFF), d => d);
}

1 个答案:

答案 0 :(得分:23)

这里的技巧是它是一个泛型类型(ResolveField的第二个参数),我们知道getter 不是一个泛型方法({{{}的最后一个参数1}}),所以你需要像这样使用ResolveField

ResolveField

在更一般的情况下,你不太了解类型(即它可能是非泛型类型)和方法(尽管严格来说,属性访问器本身并不是通用的,但这表明用途广泛):

var obj = new
{
    A = new DateTime(1234, 5, 6, 7, 8, 9, DateTimeKind.Utc),
    B = (DateTime?)null
};

Parse(obj, "A");
Parse(obj, "B");

static void Parse(object obj, string property)
{
    var blob = obj.GetType().GetProperty(property).GetGetMethod()
       .GetMethodBody().GetILAsByteArray();
    // hard-code that we know the token is at offset 2
    int token = BitConverter.ToInt32(blob, 2);

    var field = obj.GetType().Module.ResolveField(token,
        obj.GetType().GetGenericArguments(), null);
    Console.WriteLine(field.Name);
    Console.WriteLine(field.MetadataToken);
}