Mono.Cecil能:登录方法的进入和退出点

问题描述:

我写一个程序,可以改变目标程序的IL记录方法的进入和退出点。 我使用Mono.Cecil能 我想这个程序插入到目标方法的开始和结束日志语句。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(字串[] args)。

我认为问题是,我们在调用实例方法不指定this

为了解决这个问题,你有两个选择:

  • LogEntrystatic
  • 评价栈的装入thiscall之前添加ldarg.0指令。

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

+0

完成。谢谢@svick – Krishnan