Mono.Cecil:注入try / finally?

时间:2012-10-07 14:31:42

标签: .net mono.cecil

Mono.Cecil was answered here中实现try / catch的良好概述,但他只是在完整的try / catch / finally之后停止。那么如何使用Mono.Cecil实现try / finally?

2 个答案:

答案 0 :(得分:9)

以下是注入finally的方法。

首先,您需要修复返回语句。你只想要一个。

Instruction FixReturns()
{
    if (Method.ReturnType == TypeSystem.Void)
    {
        var instructions = body.Instructions;
        var lastRet = Instruction.Create(OpCodes.Ret);
        instructions.Add(lastRet);

        for (var index = 0; index < instructions.Count - 1; index++)
        {
            var instruction = instructions[index];
            if (instruction.OpCode == OpCodes.Ret)
            {
                instructions[index] = Instruction.Create(OpCodes.Leave, lastRet);
            }
        }
        return lastRet;
    }
    else
    {
        var instructions = body.Instructions;
        var returnVariable = new VariableDefinition("methodTimerReturn", Method.ReturnType);
        body.Variables.Add(returnVariable);
        var lastLd = Instruction.Create(OpCodes.Ldloc, returnVariable);
        instructions.Add(lastLd);
        instructions.Add(Instruction.Create(OpCodes.Ret));

        for (var index = 0; index < instructions.Count - 2; index++)
        {
            var instruction = instructions[index];
            if (instruction.OpCode == OpCodes.Ret)
            {
                instructions[index] = Instruction.Create(OpCodes.Leave, lastLd);
                instructions.Insert(index, Instruction.Create(OpCodes.Stloc, returnVariable));
                index++;
            }
        }
        return lastLd;
    }
}

然后找到第一条指令。如果它是实例构造函数,则需要跳过2。

Instruction FirstInstructionSkipCtor()
{
    if (Method.IsConstructor && !Method.IsStatic)
    {
        return body.Instructions.Skip(2).First();
    }
    return body.Instructions.First();
}

然后将它拼接在一起

void InnerProcess()
{
    body = Method.Body;
    body.SimplifyMacros();
    ilProcessor = body.GetILProcessor();

    var returnInstruction = FixReturns();

    var firstInstruction = FirstInstructionSkipCtor();

    var beforeReturn = Instruction.Create(OpCodes.Nop);
    ilProcessor.InsertBefore(returnInstruction, beforeReturn);

    InjectIlForFinaly(returnInstruction);

    var handler = new ExceptionHandler(ExceptionHandlerType.Finally)
        {
            TryStart = firstInstruction,
            TryEnd = beforeReturn,
            HandlerStart = beforeReturn,
            HandlerEnd = returnInstruction,
        };

    body.ExceptionHandlers.Add(handler);
    body.InitLocals = true;
    body.OptimizeMacros();
}

答案 1 :(得分:1)

发现已检查的示例非常有用且非常有用。但是,在更复杂的条件下遇到了问题。在FixReturns()中,void和non-void返回范围,更改ret的方法 - &gt;通过创建新的说明孤儿原件离开。这可以将其他指令与孤儿作为操作数(例如,分支到原始ret)。结果代码最终无效。

我们只是更新了现有的ret指令的操作码/操作数对,而不是创建新的操作码,所有这些都很好。

干杯。