簡體   English   中英

Mono.Cecil:日志方法的入口和出口點

[英]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.Program.Main(String [] args)處的CecilDemoTarget.Target.Run()處。

我認為問題在於您在不指定this情況下調用實例方法。

要解決此問題,您有兩種選擇:

  • 使LogEntry static
  • 加載this通過將計算堆棧上ldarg.0的前指令call

為了驗證我所說的是正確的並在將來診斷出類似的問題,可以在修改后的程序集上運行Peverify。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM