MethodLogger 修改dll 记录方法的开始和结束(Hook into a method)

如果你想记录一个方法的开始和结束,那么该怎么做呢?

最简单的方法:

public class MyClass
{
    public void MyMethod()
    {
        Log.EnterMethod();
        Console.WriteLine("MyMethod");
        Log.ExitMethod();
    }
}

 

可是,如果已经有了一个程序集,想在每个方法的开始和结束记录方法的执行,那么该如何做呢

在CodeProject 上有篇文章就介绍了如何处理这种情况:

MethodLogger - Hook into method calls in .NET binaries

本文不打算做翻译,只是随便介绍下:How to hook into a method.

打开原文的project:

image

TestAppLib 主要是注入的方法:

namespace TestAppLib
{
    public class MethodExecutionLogger
    {
        public static void MethodStarted(string typeName, string methodName, string args)
        {
            Console.WriteLine("Start of" + typeName + "." + methodName + "(" + args + ")");
        }

        public static void MethodCompleted(string typeName, string methodName, string args)
        {
            Console.WriteLine("End of" + typeName + "." + methodName + "(" + args + ")");
        }
    }
}

可以看到主要是记录typeName,methodName,args,当然如果你记录了时间的话,那么做为性能分析也未尝不可.

原文有一个缺陷,就是Winform程序使用console,如果想要看到控制台消息的话,那么应该修改下:

image

运行程序,点击按钮可以看到效果:

image

 

打开src里面的项目

image

,修改命令行参数:

image

其中路径可能需要修改下自己的TestApp.exe对应的路径:

运行后,再次运行TestApp.exe,可以看到结果如下:

image

 

MyClass,MyMethod 的IL如下:

MyClass.MyMethod.method public hidebysig instance void  MyMethod() cil managed
{
  // 代码大小       53 (0x35)
  .maxstack  3
  IL_0000:  ldstr      "MyClass"
  IL_0005:  ldstr      "MyMethod"
  IL_000a:  ldstr      ""
  IL_000f:  call       void [TestAppLib]TestAppLib.MethodExecutionLogger::MethodStarted(string,
                                                                                        string,
                                                                                        string)
  .try
  {
    IL_0014:  nop
    IL_0015:  ldstr      "MyMethod"
    IL_001a:  call       void [mscorlib]System.Console::WriteLine(string)
    IL_001f:  nop
  }  // end .try
  finally
  {
    IL_0020:  ldstr      "MyClass"
    IL_0025:  ldstr      "MyMethod"
    IL_002a:  ldstr      ""
    IL_002f:  call       void [TestAppLib]TestAppLib.MethodExecutionLogger::MethodCompleted(string,
                                                                                            string,
                                                                                            string)
  }  // end handler
  IL_0034:  ret
} // end of method MyClass::MyMethod

有的同学觉得很神奇,其实这也比较简单,这就是所谓的元数据编程?,通过修改IL 来实现一些特殊的需要。

通过上面的IL可以看到,MethodLogger 通过修改IL的方式实现了方法的注入。

作者使用的修改IL的库是:PERWAPI (PE Read Write API)

 

最主要的一个方法是这个方法:

ModifyCode        static void ModifyCode(ClassDef classDef, MethodDef methodDef, Method startLogMethod, Method endLogMethod)
        {
            string classNameString = MethodLoggerUtil.GetQualifiedClassName(classDef);
            string methodNameString = methodDef.Name();
            string paramsString = MethodLoggerUtil.GetParamsAsString(methodDef.GetParams());

            Param[] parms = methodDef.GetParams();

            // We'll be pushing typeName, methodName and parameters as string parameters, so set max stack size to 3.
            if (methodDef.GetMaxStack() < 3)
            {
                methodDef.SetMaxStack(3);
            }

            CILInstructions instructions = methodDef.GetCodeBuffer();

            instructions.StartInsert();
            instructions.ldstr(classNameString);
            instructions.ldstr(methodNameString);
            instructions.ldstr(paramsString);
            instructions.MethInst(MethodOp.call, startLogMethod);

            instructions.StartBlock();
            
            instructions.EndInsert();


            while (instructions.GetNextInstruction().GetPos() < instructions.NumInstructions() - 2) ;

            instructions.StartInsert();

            TryBlock tryBlock = instructions.EndTryBlock();
            instructions.StartBlock();
            instructions.ldstr(classNameString);
            instructions.ldstr(methodNameString);
            instructions.ldstr(paramsString);
            instructions.MethInst(MethodOp.call, endLogMethod);
            instructions.EndFinallyBlock(tryBlock);

            instructions.EndInsert();
        }

主要也是使用PERWAPI 来读写IL,然后在每个方法中写如BeginMethod和EndMethod。

修改后的MyClass.MyMethod() 大致是这个样子的:

image

 

个人建议:如果可以用第一种方法的话,就使用第一种方法,后面的修改IL的方式在某些情况下也很有用,如果有需要的同学,可以参考原文。

 

methodlogger.zip

methodlogger_src.zip

my_methodlogger.zip 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值