使用反射查看方法是否在方法内被调用

10

我正在使用反射(reflection)并且正在使用一个MethodBody。如何检查特定方法是否在MethodBody中被调用?

Assembly assembly = Assembly.Load("Module1");
Type type = assembly.GetType("Module1.ModuleInit");
MethodInfo mi = type.GetMethod("Initialize");
MethodBody mb = mi.GetMethodBody();

1
使用反射无法直接完成此操作。之前有人发布了一个类似的问题,您可能需要查看这些答案,看看是否有帮助您实现所需功能的方法。 - Can Gencer
5
请问您能否对您试图解决的问题进行更详细的说明?我倾向于发现,当我试图解决一个看起来非常困难的问题时,往往是因为我采用了错误的方法。反思主要是为了发现一个对象的“形状”,而不是它的实现方式。 - Lazarus
1
这是一个复杂的情况,但我正在构建一个Blend插件。该插件必须能够生成一些C#代码(调用方法的代码)。在生成代码之前,它必须检查代码是否已经存在。 - Peter
1
@Lazurus:当它存在时,我在我的插件中显示类名。 - Peter
1
@Guffa:我不想调用一个方法。如果在MethodBody中没有对特定方法的调用,我想在MethodBody内部生成C#代码。 - Peter
显示剩余4条评论
3个回答

20
使用Mono.Cecil。它是一个单独的程序集,适用于Microsoft .NET和Mono。(我认为我在编写以下代码时使用了0.6或类似版本)。
假设您有多个程序集。
IEnumerable<AssemblyDefinition> assemblies;

使用AssemblyFactory获取它们(加载一个?)

以下代码片段将枚举所有这些程序集中类型的所有方法的用法

methodUsages = assemblies
            .SelectMany(assembly => assembly.MainModule.Types.Cast<TypeDefinition>())
            .SelectMany(type => type.Methods.Cast<MethodDefinition>())
            .Where(method => null != method.Body) // allow abstracts and generics
            .SelectMany(method => method.Body.Instructions.Cast<Instruction>())
            .Select(instr => instr.Operand)
            .OfType<MethodReference>();

这将返回所有方法引用(包括在反射中使用或构建可能执行或不执行的表达式)。因此,除了向您展示Cecil API可以轻松完成的操作外,这可能没有太多用处:)
请注意,此示例假定较旧版本的Cecil(主流mono版本中的版本)。新版本:
- 更加简洁(通过使用强类型泛型集合) - 更快
当然,在您的情况下,您可以有一个单个方法引用作为起点。比如说,您想检测' mytargetmethod '何时可以直接在'startingpoint'内调用:
MethodReference startingpoint; // get it somewhere using Cecil
MethodReference mytargetmethod; // what you are looking for

bool isCalled = startingpoint    
    .GetOriginalMethod() // jump to original (for generics e.g.)
    .Resolve()           // get the definition from the IL image
    .Body.Instructions.Cast<Instruction>()
    .Any(i => i.OpCode == OpCodes.Callvirt && i.Operand == (mytargetmethod));

调用树搜索

这是一个有效的代码片段,可以让您递归地搜索相互调用(间接)的方法。

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Mono.Cecil;
using Mono.Cecil.Cil;

namespace StackOverflow
{
    /*
     * breadth-first lazy search across a subset of the call tree rooting in startingPoint
     * 
     * methodSelect selects the methods to recurse into
     * resultGen generates the result objects to be returned by the enumerator
     * 
     */
    class CallTreeSearch<T> : BaseCodeVisitor, IEnumerable<T> where T : class
    {
        private readonly Func<MethodReference, bool> _methodSelect;
        private readonly Func<Instruction, Stack<MethodReference>, T> _transform;

        private readonly IEnumerable<MethodDefinition> _startingPoints;
        private readonly IDictionary<MethodDefinition, Stack<MethodReference>> _chain = new Dictionary<MethodDefinition, Stack<MethodReference>>();
        private readonly ICollection<MethodDefinition> _seen = new HashSet<MethodDefinition>(new CompareMembers<MethodDefinition>());
        private readonly ICollection<T> _results = new HashSet<T>();
        private Stack<MethodReference> _currentStack;

        private const int InfiniteRecursion = -1;
        private readonly int _maxrecursiondepth;
        private bool _busy;

        public CallTreeSearch(IEnumerable<MethodDefinition> startingPoints,
                              Func<MethodReference, bool> methodSelect,
                              Func<Instruction, Stack<MethodReference>, T> resultGen)
            : this(startingPoints, methodSelect, resultGen, InfiniteRecursion)
        {

        }

        public CallTreeSearch(IEnumerable<MethodDefinition> startingPoints,
                              Func<MethodReference, bool> methodSelect,
                              Func<Instruction, Stack<MethodReference>, T> resultGen,
                              int maxrecursiondepth)
        {
            _startingPoints = startingPoints.ToList();

            _methodSelect = methodSelect;
            _maxrecursiondepth = maxrecursiondepth;
            _transform = resultGen;
        }

        public override void VisitMethodBody(MethodBody body)
        {
            _seen.Add(body.Method); // avoid infinite recursion
            base.VisitMethodBody(body);
        }

        public override void VisitInstructionCollection(InstructionCollection instructions)
        {
            foreach (Instruction instr in instructions)
                VisitInstruction(instr);

            base.VisitInstructionCollection(instructions);
        }

        public override void VisitInstruction(Instruction instr)
        {
            T result = _transform(instr, _currentStack);
            if (result != null)
                _results.Add(result);

            var methodRef = instr.Operand as MethodReference; // TODO select calls only?
            if (methodRef != null && _methodSelect(methodRef))
            {
                var resolve = methodRef.Resolve();
                if (null != resolve && !(_chain.ContainsKey(resolve) || _seen.Contains(resolve)))
                    _chain.Add(resolve, new Stack<MethodReference>(_currentStack.Reverse()));
            }

            base.VisitInstruction(instr);
        }

        public IEnumerator<T> GetEnumerator()
        {
            lock (this) // not multithread safe
            {
                if (_busy)
                    throw new InvalidOperationException("CallTreeSearch enumerator is not reentrant");
                _busy = true;

                try
                {
                    int recursionLevel = 0;
                    ResetToStartingPoints();

                    while (_chain.Count > 0 &&
                           ((InfiniteRecursion == _maxrecursiondepth) || recursionLevel++ <= _maxrecursiondepth))
                    {

                        // swapout the collection because Visitor will modify
                        var clone = new Dictionary<MethodDefinition, Stack<MethodReference>>(_chain);
                        _chain.Clear();

                        foreach (var call in clone.Where(call => HasBody(call.Key)))
                        {
//                          Console.Error.Write("\rCallTreeSearch: level #{0}, scanning {1,-20}\r", recursionLevel, call.Key.Name + new string(' ',21));
                            _currentStack = call.Value;
                            _currentStack.Push(call.Key);
                            try
                            {
                                _results.Clear();
                                call.Key.Body.Accept(this); // grows _chain and _results
                            }
                            finally
                            {
                                _currentStack.Pop();
                            }
                            _currentStack = null;

                            foreach (var result in _results)
                                yield return result;
                        }
                    }
                }
                finally
                {
                    _busy = false;
                }
            }
        }

        private void ResetToStartingPoints()
        {
            _chain.Clear();
            _seen.Clear();
            foreach (var startingPoint in _startingPoints)
            {
                _chain.Add(startingPoint, new Stack<MethodReference>());
                _seen.Add(startingPoint);
            }
        }

        private static bool HasBody(MethodDefinition methodDefinition)
        {
            return !(methodDefinition.IsAbstract || methodDefinition.Body == null);
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }

    internal class CompareMembers<T> : IComparer<T>, IEqualityComparer<T>
        where T: class, IMemberReference
    {
        public int Compare(T x, T y)
        { return StringComparer.InvariantCultureIgnoreCase.Compare(KeyFor(x), KeyFor(y)); }

        public bool Equals(T x, T y)
        { return KeyFor(x).Equals(KeyFor(y)); }

        private static string KeyFor(T mr)
        { return null == mr ? "" : String.Format("{0}::{1}", mr.DeclaringType.FullName, mr.Name); }

        public int GetHashCode(T obj)
        { return KeyFor(obj).GetHashCode(); }
    }
}

注意事项

  • Resolve()方法中进行一些错误处理(我有一个扩展方法TryResolve()可供使用)
  • 可选地仅选择调用操作中的MethodReferences用法(call、calli、callvirt...)(请参见//TODO

典型用法:

public static IEnumerable<T> SearchCallTree<T>(this TypeDefinition startingClass,
                                               Func<MethodReference, bool> methodSelect,
                                               Func<Instruction, Stack<MethodReference>, T> resultFunc,
                                               int maxdepth)
    where T : class
{
    return new CallTreeSearch<T>(startingClass.Methods.Cast<MethodDefinition>(), methodSelect, resultFunc, maxdepth);
}

public static IEnumerable<T> SearchCallTree<T>(this MethodDefinition startingMethod,
                                               Func<MethodReference, bool> methodSelect,
                                               Func<Instruction, Stack<MethodReference>, T> resultFunc,
                                               int maxdepth)
    where T : class
{
    return new CallTreeSearch<T>(new[] { startingMethod }, methodSelect, resultFunc, maxdepth); 
}

// Actual usage:
private static IEnumerable<TypeUsage> SearchMessages(TypeDefinition uiType, bool onlyConstructions)
{
    return uiType.SearchCallTree(IsBusinessCall,
           (instruction, stack) => DetectRequestUsage(instruction, stack, onlyConstructions));
}

请注意,像DetectRequestUsage这样的函数的完善完全取决于您自己(编辑:但是请参见此处)。您可以做任何您想要的事情,并且不要忘记:您将拥有完整的静态分析调用栈,因此实际上可以使用所有这些信息来完成非常棒的事情


我找不到BaseCodeVisitor类,你能告诉我在哪个程序集中可以找到它吗? - Peter
1
你需要使用Mono.Cecil。它是一个单独的程序集,可以在Microsoft .NET和Mono上运行。(我写这段代码时使用的版本大约是0.6左右) - sehe
我知道这是一个旧的线程,但我刚刚尝试了这段代码,也找不到BaseCodeVisitor类。我已经引用了Mono.Cecil,并导入了命名空间。我查看了DLL本身(使用反编译器),并没有这个名称的类。我有最新的Momo.Cecil.dll,版本为0.9.5.0。有什么想法吗?谢谢。 - Avrohom Yisroel
1
@AvrohomYisroel 我想象界面已经改变了。我没有时间去找出具体的改变,但我想象它不会有太大的变化。(我知道所有的集合类型都已经进行了重构以使用 .NET 泛型) - sehe
你有使用的DLL二进制文件副本吗?我尝试从GitHub获取0.6版本,但是我的源代码控制理解可能有问题,或者该网站很糟糕。我无法弄清楚如何下载特定版本。我只需要一个可以与此处代码配合使用的二进制文件。如果您有,请发送电子邮件至mryossu@hotmail.com - 谢谢 :) - Avrohom Yisroel

1
在生成代码之前,必须检查它是否已经存在。
有几种情况下捕获异常比防止生成异常要便宜得多。这是一个典型的例子。您可以获取方法体的IL,但反射不是反汇编器。反汇编器也不是真正的解决方案,您需要反汇编整个调用树来实现所需的行为。毕竟,方法体中的方法调用本身可能会调用一个方法,等等。捕获Jitter编译IL时抛出的异常要简单得多。

-1
可以使用StackTrace类:
System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace();
System.Diagnostics.StackFrame sf = st.GetFrame(1); 
Console.Out.Write(sf.GetMethod().ReflectedType.Name + "." + sf.GetMethod().Name); 

1 可以调整,确定您感兴趣的帧数。


1
我曾经尝试过这个,结果被咬了一口 - 在调试和发布版本中,帧数可能会不同,花了我一段时间才弄清楚。 (可以通过使用属性关闭此优化,但这可能会导致性能下降)。 - takrl

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接