【问题标题】:Use Cecil to insert begin/end block around functions使用 Cecil 在函数周围插入开始/结束块
【发布时间】:2017-07-25 10:55:18
【问题描述】:

这个简单的代码可以正常工作,并允许在每个 Update/LateUpdate/FixedUpdate 函数周围添加一个 BeginSample/EndSample 调用。但是,它不考虑提前返回指令,例如作为条件的结果。你知道如何编写一个考虑提前返回的类似函数,以便在任何情况下都执行 EndSample 调用吗?

请注意,我不是 Cecil 专家,我现在只是在学习。在我看来,Cecil 会自动更新在调用 InsertBefore 和类似函数后提前返回的操作。因此,如果 BR 操作码先前跳转到特定指令地址,则在插入后将更新地址以跳转到原始指令。在大多数情况下这是可以的,但在我的情况下,这意味着 if 语句将跳过最后插入的操作,因为 BR 操作仍将直接指向最终的 Ret 指令。请注意,Update、LateUpdate 和 FixedUpdate 都是 void 函数。

foreach (var method in type.Methods)
{
    if ((method.Name == "Update" || method.Name == "LateUpdate" || method.Name == "FixedUpdate") &&
        method.HasParameters == false)
    {
        var beginMethod =
            module.ImportReference(typeof (Profiler).GetMethod("BeginSample",
                                                               new[] {typeof (string)}));
        var endMethod =
            module.ImportReference(typeof (Profiler).GetMethod("EndSample",
                                                               BindingFlags.Static |
                                                               BindingFlags.Public));

        Debug.Log(method.Name + " method found in class: " + type.Name);

        var ilProcessor = method.Body.GetILProcessor();

        var first = method.Body.Instructions[0];
        ilProcessor.InsertBefore(first,
                                 Instruction.Create(OpCodes.Ldstr,
                                                    type.FullName + "." + method.Name));
        ilProcessor.InsertBefore(first, Instruction.Create(OpCodes.Call, beginMethod));

        var lastRet = method.Body.Instructions[method.Body.Instructions.Count - 1];
        ilProcessor.InsertBefore(lastRet, Instruction.Create(OpCodes.Call, endMethod));

        changed = true;
    }
}

作为奖励,如果您能向我解释 Emit 和 Append 之间的区别,那么新创建的指令具有相同的操作数。 Append 是在后台执行 Emit 还是执行更多操作?

【问题讨论】:

  • 在对 Cecil 一无所知的情况下快速发表评论:如果您想保证无论内部控制流程如何总是发生某些事情,那么将其包装在 try .. finally 块中将是显而易见的事情,而不是追捕所有出口点。另一个明显的方法(与此相结合)是重命名原始函数并完全用一个包装器替换它begin() / function() / end()。最后但并非最不重要的一点是,您可以考虑使用分析器,而不是显然重新发明轮子。当然,并不是说你真的不需要自己的轮子。

标签: cil mono.cecil


【解决方案1】:

我可能已经找到了解决方案,至少显然它有效。我从这里遵循了用于解决类似问题的代码:

https://groups.google.com/forum/#!msg/mono-cecil/nE6JBjvEFCQ/MqV6tgDCB4AJ

我根据我的目的对其进行了调整,它似乎有效,尽管我可能会发现其他问题。这是完整的代码:

 static bool ProcessAssembly(AssemblyDefinition assembly)
 {
     var changed = false;

     var moduleG = assembly.MainModule;

     var attributeConstructor =
             moduleG.ImportReference(
                 typeof(RamjetProfilerPostProcessedAssemblyAttribute).GetConstructor(Type.EmptyTypes));
     var attribute = new CustomAttribute(attributeConstructor);
     var ramjet = moduleG.ImportReference(typeof(RamjetProfilerPostProcessedAssemblyAttribute));
     if (assembly.HasCustomAttributes)
     {
         var attributes = assembly.CustomAttributes;
         foreach (var attr in attributes)
         {
             if (attr.AttributeType.FullName == ramjet.FullName)
             {
                 Debug.LogWarning("<color=yellow>Skipping already-patched assembly:</color>  " + assembly.Name);
                 return false;
             }
         }
     }
     assembly.CustomAttributes.Add(attribute);

     foreach (var module in assembly.Modules)
     {
         foreach (var type in module.Types)
         {
             // Skip any classes related to the RamjetProfiler
             if (type.Name.Contains("AssemblyPostProcessor") || type.Name.Contains("RamjetProfiler"))
             {
                 // Todo: use actual type equals, not string matching
                 Debug.Log("Skipping self class : " + type.Name);
                 continue;
             }

             if (type.BaseType != null && type.BaseType.FullName.Contains("UnityEngine.MonoBehaviour"))
             {
                 foreach (var method in type.Methods)
                 {
                     if ((method.Name == "Update" || method.Name == "LateUpdate" || method.Name == "FixedUpdate") &&
                         method.HasParameters == false)
                     {
                         var beginMethod =
                             module.ImportReference(typeof(Profiler).GetMethod("BeginSample",
                                                                                new[] { typeof(string) }));
                         var endMethod =
                             module.ImportReference(typeof(Profiler).GetMethod("EndSample",
                                                                                BindingFlags.Static |
                                                                                BindingFlags.Public));

                         Debug.Log(method.Name + " method found in class: " + type.Name);

                         var ilProcessor = method.Body.GetILProcessor();

                         var first = method.Body.Instructions[0];
                         ilProcessor.InsertBefore(first,
                                                  Instruction.Create(OpCodes.Ldstr,
                                                                     type.FullName + "." + method.Name));
                         ilProcessor.InsertBefore(first, Instruction.Create(OpCodes.Call, beginMethod));

                         var lastcall = Instruction.Create(OpCodes.Call, endMethod);

                         FixReturns(method, lastcall);

                         changed = true;
                     }
                 }
             }
         }
     }

     return changed;
 }

 static void FixReturns(MethodDefinition med, Instruction lastcall)
 {
     MethodBody body = med.Body;

     var instructions = body.Instructions;
     Instruction formallyLastInstruction = instructions[instructions.Count - 1];
     Instruction lastLeaveInstruction = null;

     var lastRet = Instruction.Create(OpCodes.Ret);
     instructions.Add(lastcall);
     instructions.Add(lastRet);

     for (var index = 0; index < instructions.Count - 1; index++)
     {
         var instruction = instructions[index];
         if (instruction.OpCode == OpCodes.Ret)
         {
             Instruction leaveInstruction = Instruction.Create(OpCodes.Leave, lastcall);
             if (instruction == formallyLastInstruction)
             {
                 lastLeaveInstruction = leaveInstruction;
             }

             instructions[index] = leaveInstruction;
         }
     }

     FixBranchTargets(lastLeaveInstruction, formallyLastInstruction, body);
 }

 private static void FixBranchTargets(
     Instruction lastLeaveInstruction,
     Instruction formallyLastRetInstruction,
     MethodBody body)
 {
     for (var index = 0; index < body.Instructions.Count - 2; index++)
     {
         var instruction = body.Instructions[index];
         if (instruction.Operand != null && instruction.Operand == formallyLastRetInstruction)
         {
             instruction.Operand = lastLeaveInstruction;
         }
     }
 }

基本上它的作用是添加一个Ret 指令,然后用Leave 函数替换所有以前的Ret(通常是一个,为什么要超过一个?)这是什么意思 :) ),所以之前的所有跳转都保持有效。与原始代码不同,我在最后一个 Ret 之前使 Leave 指令指向 EndSample 调用

【讨论】:

  • 离开操作码只是分支 (br*),还可用于跳出受保护区域(try、catch、... - 块)
猜你喜欢
  • 1970-01-01
  • 2019-11-06
  • 1970-01-01
  • 2016-08-11
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
  • 2022-01-17
  • 2022-10-23
相关资源
最近更新 更多