ITPub博客

首页 > > > 另类Unity热更新大法:代码注入式补丁热更新

另类Unity热更新大法:代码注入式补丁热更新

作者:u_453e1a12781dea 时间:2016-07-18 17:18:02 0 删除 编辑
作者:公的Kelly 
来源:简书网
眼看Unity引擎热火朝天,无数程序猿加入到了Unity开发的大本营。

一些老项目,当时ulua/slua还不如今天那样的成熟,因此他们选择了全c#开发;也有一些出于性能考虑,全c#开发;也有一些没有太丰富运营经验的开发团队,没有想太多,用全c#爽爽地开发。

用C#开发爽爽的日子一天一天的过去了,直到突然有一天,策划老大说:“我们得做个热更新模块!”;突然有一天,老板说:“别人游戏用Lua热更新,为什么我们不行?”;突然有一天,运营说:“线上游戏出了个bug,重新编译出包审核得几天啊!”——嗯,这时候,受伤的总是程序猿。

有没有亡羊补牢,临危受命的折衷方法?可以不用把C#改成Lua,可以不用区分平台(AndroidDLL重载IOS却不行),可以对任何代码做修复的方法?

有的,并且用很笨的一句代码来概括:
class Fucker {
    void Fucking() {
        if (PatchScript.HasPatchScript("Fucker.Fucking")) {                  // do patch fuck
           PatchScript.CallPatchScript("Fucker.Fucking");            return;
       }
        // do origin fuck
       Log.Info("I am a original fuck");
   }
}

往所有的函数注入代码,当存在补丁脚本时执行补丁脚本,不存在时执行原代码。

因此,本文的热更新等同于打补丁。

什么是热更新?

吐槽一点,虽然我们这个方法确实将热更新做成模块了,但这绝对是迫不得已的。 热更新绝对不是一个功能模块能实现,它是一个底层架构所决定的。要说一个项目不好,无法实现热更新,这归根到底是架构没想好、策划没坚持、程序没执着、运营懒得管等等各种各样复杂原因所导致的。

我心目中理想热更新是怎样?要热!:

  • 对任意部位的代码进行修改;
  • 运行时,自动下载更新代码,尔后无需重启;
  • 运行时,立即重载代码,并继续运行;
  • 兼顾开发环境与生产环境的简便性;

热更新在Web开发领域非常普遍,毕竟HTTP是无状态的;而游戏这种高实时性的开发相比,要想做好热更新就确实需要架构层的更多考虑了。怎么做好热更新,我们还是回到主题,接下来介绍方法,可以达到什么目的:

  • 对任意部位的方法体代码进行修改;
  • 运行时,立即重载代码,并继续运行
  • 语言无关:同样的思路可以应用在Java、C#、Go、C++等等
  • 使用起来不太方便
  • 亡羊补牢专用

代码注入补丁热更新大法流程

上面说了很多废话。接下直奔主题,要怎样做到:
class Fucker {
    void Fucking() {
        if (PatchScript.HasPatchScript("Fucker.Fucking")) {
            // do patch fuck
           PatchScript.CallPatchScript("Fucker.Fucking");            return;
       }
        // do origin fuck
       Log.Info("I am a original fuck");
   }
}

我们要针对Fucker类的Fucking方法进行更新,则新建Lua脚本Fucker.Fucking.lua
-- 文件名Fucker.Fucking.lua

function Func()
    print("I am a patch fuck!")
end

return Func

一个补丁脚本就此完成,当程序运行到Fucking函数时,实际上它执行的是Lua脚本,变相的实现了热更新的功能——改变代码的执行行为。

STEP 1:执行环境

本文针对Unity游戏开发,那么原语言,当然是C#了;而打补丁的语言,当时Lua了;

在这里我们使用SLua插件,它的高质量代码和强大的反射功能,非常适合代码注入补丁热更新。
class PatchScript 
{ 
   public bool HasPatchScript(string path)
    {
        return File.Exists("Script/" + path + ".lua");
   }

    public void CallScript(string path)
    {
        string scriptCode = File.ReadAllString(path);
        var luaFunc = this.luaState.doScript(scriptCode) as LuaFunction;
       luaFunc.call();
   }
}

STEP 2:代码注入

嗯,执行环境,非常的简单,不就是简单的if判断吗? 估计最令人迷惑的部分就是,如何往所有的C#函数体前部分插入代码了。

我们要做的,遍历所有的c#文件,取得class类名,然后再分析函数名,定位函数在代码中的起始位置、获取函数的参数列表、参数类型……等等。看起来很复杂,是不是要对c#做语法分析、词法分析了?感觉工作量很大啊。

幸好,轮子已经做好了。这里要用到一个重要的库——NRefactory。包括IDE MonoDevelop中的语法智能提示、重构都是基于这个库进行的。有了它,语法分析词法分析仅仅是API的调用而已。

我们要做的,就是使用NRefactory找出C#的方法体,并插入代码:
   using (var script = new DocumentScript(document, formattingOptions, options))
           {
               CSharpParser parser = new CSharpParser();
               SyntaxTree syntaxTree = parser.Parse(code, srcFilePath);                foreach (var classDec in syntaxTree.Descendants.OfType<TypeDeclaration>())
               {                    if (classDec.ClassType == ClassType.Class || classDec.ClassType == ClassType.Struct)
                   {                        var className = classDec.Name;                        foreach (var method in classDec.Children.OfType<MethodDeclaration>())
                       {                            var returnType = method.ReturnType.ToString();                            if (returnType.Contains("IEnumerator") || returnType.Contains("IEnumerable"))  // 暂不支持yield!
                               continue;                           // 。。。。这里找到了方法体! 开始进行插入!
                       }
                   }
               }
           }

我把使用NRefactory对C#方法体注入的代码,抽象成一个单独的类MethodInjector(C#),看文章底部。

STEP 3:编写Lua补丁

补丁的方法,在上文“代码注入补丁热更新大法流程”中已有提及:

对需要打补丁的函数,创建Lua脚本

如上文中要改变Fucker.Fucking函数的执行行为,则创建Fucker.Fucking.lua脚本文件,脚本末端返回一个Lua函数。

最后

本文着重提供了一种思路,而不提供完整的源代码,毕竟涉及到部分人的商业利益,遗憾点到即止。

使用下面的MethodInjector类,会把函数的参数值也进行解析、预编译指令引入、并且可以在Lua补丁中控制是否在执行补丁后,继续执行原C#代码,基本能达到大部分的需求了。

这里举例一个更好的方案:注入DLL的IL代码,而不是注入c#代码,来确保我们的c#代码不会被改动。

MethodInjector类
#region Copyright (c) 2015 KEngine / Kelly <http://github.com/mr-kelly>, All rights reserved.
// KEngine - Toolset and framework for Unity3D
// ===================================
// 
// Date:     2015/12/03
// Author:  Kelly
// Email: 23110388@qq.com
// Github: https://github.com/mr-kelly/KEngine
// 
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
// 
// You should have received a copy of the GNU Lesser General Public// License along with this library.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using ICSharpCode.NRefactory.CSharp;
using ICSharpCode.NRefactory.CSharp.Refactoring;
using ICSharpCode.NRefactory.Editor;

namespace CSharpMethodInjector
{
    /// <summary>
   /// 向C#代码块插入文字
   /// </summary>
   public class MethodInjector
   {
        public delegate string CSharpMethodInjectorDelegate(     
            string className,
            string methodName, string returnType, string[] parameters, string[] outParams);

        private CSharpMethodInjectorDelegate _afterInsert;
        private CSharpMethodInjectorDelegate _beforeInsert;
        private string[] _defineSymbols;

        private MethodInjector() {}
        public MethodInjector(CSharpMethodInjectorDelegate afterInsert, CSharpMethodInjectorDelegate beforeInsert = null, string[] defineSymbols = null)
        {
           _afterInsert = afterInsert;
           _beforeInsert = beforeInsert;
           _defineSymbols = defineSymbols;
       }
        /// <summary>
       /// 代码注入! GOGOGO
       /// </summary>
       /// <param name="srcFilePath"></param>
       /// <param name="outputFilePath"></param>
       public void Inject(string srcFilePath, string outputFilePath)        {
           UTF8Encoding utf8 = new UTF8Encoding(false);            var predefineSymbolsSb = new StringBuilder();
            if (_defineSymbols != null)
           {                foreach (var symbol in _defineSymbols)
               {
                   predefineSymbolsSb.AppendFormat("#define {0}\n", symbol);    
               }

           }

            var code = File.ReadAllText(srcFilePath, Encoding.UTF8);
           code = predefineSymbolsSb.ToString() + code;  // 加入宏

           var document = new StringBuilderDocument(code);
            var formattingOptions =FormattingOptionsFactory.CreateAllman();
            var options = new TextEditorOptions();
            using (var script = new DocumentScript(document, formattingOptions, options))
           {
               CSharpParser parser = new CSharpParser();
               SyntaxTree syntaxTree = parser.Parse(code, srcFilePath);
                foreach (var classDec in syntaxTree.Descendants.OfType<TypeDeclaration>())
               { 
                   if (classDec.ClassType == ClassType.Class || classDec.ClassType == ClassType.Struct)
                   { 
                       var className = classDec.Name;
                        foreach (var method in classDec.Children.OfType<MethodDeclaration>())
                       {
                            var returnType = method.ReturnType.ToString();
                           if (returnType.Contains("IEnumerator") || returnType.Contains("IEnumerable"))
// 暂不支持yield!
continue;
                            var methodSegment = script.GetSegment(method);
                            var methodOffset = methodSegment.Offset;  // 方法偏移

                           var paramsTypes = method.Parameters;//method.Children.OfType<ParameterDeclaration>();// typeName
                           var paramsTypesStrs = new List<string>(); // 参数
                           if (!method.HasModifier(Modifiers.Static))
                               paramsTypesStrs.Add("this"); // 非静态方法,加this

                           var paramsOutStrs = new List<string>(); // out 的参数
                           foreach (var paramsType in paramsTypes)
                           {
                               paramsTypesStrs.Add(paramsType.Name);                                if (paramsType.ParameterModifier == ParameterModifier.Out)
                               {
                                    // out 的参数
                                   paramsOutStrs.Add(string.Format("{0} = default({1});", paramsType.Name, paramsType.Type));
                               }
                           }
                            if (_beforeInsert != null)
                           {
                                var insertBeforeText = _beforeInsert(className, method.Name, returnType,
                                   paramsTypesStrs.ToArray(), paramsOutStrs.ToArray());
                                if (!string.IsNullOrEmpty(insertBeforeText))
                                   script.InsertText(methodOffset, insertBeforeText);
                           }
                            foreach (var blockStatement in method.Descendants.OfType<BlockStatement>())
                           {
                                int insertOffset; 
                               if (blockStatement.Statements.Count == 0) // 空函数
                               { 
                                  var segment = script.GetSegment(blockStatement);
                                   insertOffset = segment.Offset + 1; // 越过"/"
                               }
                                else
                               { 
                                   var firstChildStatement = blockStatement.Statements.First();
                                    var segment = script.GetSegment(firstChildStatement);
                                   insertOffset = segment.Offset;
                               }
                               script.InsertText(insertOffset, _afterInsert(className, method.Name, returnType, paramsTypesStrs.ToArray(), paramsOutStrs.ToArray()));                                break;
 // 仅对第一个方法包体(BlockStatement), 
其它不是方法进行处理
                           }
                       }
                   }
               }

           }
            var resultText = document.Text;

           resultText = resultText.Substring(predefineSymbolsSb.Length);
 // 移除宏定义
           File.WriteAllText(outputFilePath, resultText, utf8);
       }
   }
}
版权申明:内容来源网络,版权归原创者所有。除非无法确认,我们都会标明作者及出处,如有侵权烦请告知,我们会立即删除并表示歉意。谢谢。
只为一场完美的技术盛宴!
SACC2016
作为国内最受欢迎的架构师盛会,2016第八届中国系统架构师大会(SACC)将于2016年10月27日-29日在北京万达索菲特大酒店撼世来袭!

大会以"架构创新之路"为主题,共设置两个主场分享时段,24个技术交流专场时段;邀请来自互联网、电子商务、金融、电信、政府、行业协会等20多个领域,150多位技术专家及行业领袖来分享他们的经验;并将吸引4000多名系统运维、架构师、及各种企业的IT决策人士参会,为他们提供最具价值的交流平台。
最优折扣来袭!
7月28日前,订购SACC2016门票可立享6.8折优惠!团购更有折上折!
点击“阅读原文”立即购票!

原文作者:;如有侵权,请联系管理员删除。

请登录后发表评论 登录
全部评论

注册时间:2019-07-17

  • 博文量
    1982
  • 访问量
    17892