您的位置:首页 > 其它

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

2012-09-21 07:02 337 查看
如果你想记录一个方法的开始和结束,那么该怎么做呢?

最简单的方法:

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:

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();
}
[/code]

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

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





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

methodlogger.zip

methodlogger_src.zip

my_methodlogger.zip
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: