Mono.Cecil: Log方法的入口和出口点

Mono.Cecil: Log method's entry and exit point

我正在编写一个程序,可以将目标程序的 IL 更改为记录方法的入口点和出口点。 我正在使用 Mono.Cecil 我想让这个程序在目标方法的开头和结尾插入日志语句。

我尝试了一个基本程序作为示例。

public class Target
{
    // My target method. 
    public void Run()
    {
        Console.WriteLine("Run method body");
    }

    // This is my log method, which i want to call in begining of Run() method. 
    public void LogEntry()
    {
        System.Console.WriteLine("******Entered in RUN method.***********");
    }
}

源程序。

public class Sample 
{
    private readonly string _targetFileName;
    private readonly ModuleDefinition _module;

    public ModuleDefinition TargetModule { get { return _module; } }

    public Sample(string targetFileName)
    {
        _targetFileName = targetFileName;

        // Read the module with default parameters
        _module = ModuleDefinition.ReadModule(_targetFileName);
    }

    public void Run()
    {

        // Retrive the target class. 
        var targetType = _module.Types.Single(t => t.Name == "Target");

        // Retrieve the target method.
        var runMethod = targetType.Methods.Single(m => m.Name == "Run");

        // Get a ILProcessor for the Run method
        var processor = runMethod.Body.GetILProcessor();

        // get log entry method ref to create instruction
        var logEntryMethodReference = targetType.Methods.Single(m => m.Name == "LogEntry");

        var newInstruction = processor.Create(OpCodes.Call, logEntryMethodReference);

        var firstInstruction = runMethod.Body.Instructions[0];

        processor.InsertBefore(firstInstruction, newInstruction);

        // Write the module with default parameters
        _module.Write(_targetFileName);
    }
}

当我运行我的源程序改变目标程序的IL时, 我收到以下错误消息。

System.InvalidProgramException: 公共语言运行库检测到无效程序。 在 CecilDemoTarget.Target.Run() 在 CecilDemoTarget.Program.Main(String[] args).

我认为问题在于您在调用实例方法时未指定 this

要解决此问题,您有两种选择:

  • 制作 LogEntry static.
  • 通过在 call 之前添加 ldarg.0 指令,将 this 加载到计算堆栈上。

要验证我所说的是否正确并在将来诊断类似问题,您可以 运行 在修改后的程序集上进行 Peverify。