当前位置: 移动技术网 > 移动技术>移动开发>Android > Android热修复Tinker接入及源码解读

Android热修复Tinker接入及源码解读

2019年08月02日  | 移动技术网移动技术  | 我要评论

一、概述

热修复这项技术,基本上已经成为项目比较重要的模块了。主要因为项目在上线之后,都难免会有各种问题,而依靠发版去修复问题,成本太高了。

现在热修复的技术基本上有阿里的andfix、qzone的方案、美团提出的思想方案以及腾讯的tinker等。

其中andfix可能接入是最简单的一个(和tinker命令行接入方式差不多),不过兼容性还是是有一定的问题的;qzone方案对性能会有一定的影响,且在art模式下出现内存错乱的问题(其实这个问题我之前并不清楚,主要是tinker在mdcc上指出的);美团提出的思想方案主要是基于instant run的原理,目前尚未开源,不过这个方案我还是蛮喜欢的,主要是兼容性好。

这么看来,如果选择开源方案,tinker目前是最佳的选择,tinker的介绍有这么一句:

tinker已运行在微信的数亿android设备上,那么为什么你不使用tinker呢?

好了,说了这么多,下面来看看tinker如何接入,以及tinker的大致的原理分析。希望通过本文可以实现帮助大家更好的接入tinker,以及去了解tinker的一个大致的原理。

二、接入tinker

接入tinker目前给了两种方式,一种是基于命令行的方式,类似于andfix的接入方式;一种就是gradle的方式。

考虑早期使用andfix的app应该挺多的,以及很多人对gradle的相关配置还是觉得比较繁琐的,下面对两种方式都介绍下。

(1)命令行接入

接入之前我们先考虑下,接入的话,正常需要的前提(开启混淆的状态)。

对于api

一般来说,我们接入热修库,会在application#oncreate中进行一下初始化操作。然后在某个地方去调用类似loadpatch这样的api去加载patch文件。

对于patch的生成

简单的方式就是通过两个apk做对比然后生成;需要注意的是:两个apk做对比,需要的前提条件,第二次打包混淆所使用的mapping文件应该和线上apk是一致的。

最后就是看看这个项目有没有需要配置混淆;

有了大致的概念,我们就基本了解命令行接入tinker,大致需要哪些步骤了。

依赖引入

dependencies {
  // ...
  //可选,用于生成application类
  provided('com.tencent.tinker:tinker-android-anno:1.7.7')
  //tinker的核心库
  compile('com.tencent.tinker:tinker-android-lib:1.7.7')
}

顺便加一下签名的配置:

android{
 //...
  signingconfigs {
    release {      try {
        storefile file("release.keystore")
        storepassword "testres"
        keyalias "testres"
        keypassword "testres"
      } catch (ex) {
        throw new invaliduserdataexception(ex.tostring())
      }
    }
  }

  buildtypes {
    release {
      minifyenabled true
      signingconfig signingconfigs.release
      proguardfiles getdefaultproguardfile('proguard-android.txt'), 'proguard-rules.pro'
    }
    debug {
      debuggable true
      minifyenabled true
      signingconfig signingconfigs.release
      proguardfiles getdefaultproguardfile('proguard-android.txt'), 'proguard-rules.pro'
    }
  }
}

文末会有demo的下载地址,可以直接参考build.gradle文件,不用担心这些签名文件去哪找。

api引入

api主要就是初始化和loadpacth。

正常情况下,我们会考虑在application的oncreate中去初始化,不过tinker推荐下面的写法:

@defaultlifecycle(application = ".simpletinkerinapplication",
    flags = shareconstants.tinker_enable_all,
    loadverifyflag = false)public class simpletinkerinapplicationlike extends applicationlike {
  public simpletinkerinapplicationlike(application application, int tinkerflags, boolean tinkerloadverifyflag, long applicationstartelapsedtime, long applicationstartmillistime, intent tinkerresultintent) {    super(application, tinkerflags, tinkerloadverifyflag, applicationstartelapsedtime, applicationstartmillistime, tinkerresultintent);
  }  @override
  public void onbasecontextattached(context base) {    super.onbasecontextattached(base);
  }  @override
  public void oncreate() {    super.oncreate();
    tinkerinstaller.install(this);
  }
}

applicationlike通过名字你可能会猜,并非是application的子类,而是一个类似application的类。

tinker建议编写一个applicationlike的子类,你可以当成application去使用,注意顶部的注解:@defaultlifecycle,其application属性,会在编译期生成一个simpletinkerinapplication类。

所以,虽然我们这么写了,但是实际上application会在编译期生成,所以androidmanifest.xml中是这样的:

 <application
    android:name=".simpletinkerinapplication"
    .../>

 

编写如果报红,可以build下。

这样其实也能猜出来,这个注解背后有个annotation processor在做处理

通过该文会对一个编译时注解的运行流程和基本api有一定的掌握,文中也会对tinker该部分的源码做解析。

上述,就完成了tinker的初始化,那么调用loadpatch的时机,我们直接在activity中添加一个button设置:

public class mainactivity extends appcompatactivity {

  @override
  protected void oncreate(bundle savedinstancestate) {    super.oncreate(savedinstancestate);
    setcontentview(r.layout.activity_main);
  }  public void loadpatch(view view) {
    tinkerinstaller.onreceiveupgradepatch(getapplicationcontext(),
        environment.getexternalstoragedirectory().getabsolutepath() + "/patch_signed.apk");
  }
}

我们会将patch文件直接push到sdcard根目录;

所以一定要注意:添加sdcard权限,如果你是6.x以上的系统,自己添加上授权代码,或者手动在设置页面打开sdcard读写权限。

<uses-permission android:name="android.permission.write_external_storage" />

除以以外,有个特殊的地方就是tinker需要在androidmanifest.xml中指定tinker_id。

<application>
 <meta-data
      android:name="tinker_id"
      android:value="tinker_id_6235657" />
  //...</application>

到此api相关的就结束了,剩下的就是考虑patch如何生成。

patch生成

tinker提供了patch生成的工具,源码见:tinker-patch-cli,打成一个jar就可以使用,并且提供了命令行相关的参数以及文件。

命令行如下:

java -jar tinker-patch-cli-1.7.7.jar -old old.apk -new new.apk -config tinker_config.xml -out output

需要注意的就是tinker_config.xml,里面包含tinker的配置,例如签名文件等。

这里我们直接使用tinker提供的签名文件,所以不需要做修改,不过里面有个application的item修改为与本例一致:

<loader value="com.zhy.tinkersimplein.simpletinkerinapplication"/>

大致的文件结构如下:

可以在tinker-patch-cli中提取,或者直接下载文末的例子。

上述介绍了patch生成的命令,最后需要注意的就是,在第一次打出apk的时候,保留下生成的mapping文件,在/build/outputs/mapping/release/mapping.txt

可以copy到与proguard-rules.pro同目录,同时在第二次打修复包的时候,在proguard-rules.pro中添加上:

-applymapping mapping.txt

保证后续的打包与线上包使用的是同一个mapping文件。

tinker本身的混淆相关配置,可以参考:

如果,你对该部分描述不了解,可以直接查看源码即可。

测试

首先随便生成一个apk(api、混淆相关已经按照上述引入),安装到手机或者模拟器上。

然后,copy出mapping.txt文件,设置applymapping,修改代码,再次打包,生成new.apk。

两次的apk,可以通过命令行指令去生成patch文件。

如果你下载本例,命令需要在[该目录]下执行。

最终会在output文件夹中生成产物:

我们直接将patch_signed.apk push到sdcard,点击loadpatch,一定要观察命令行是否成功。

本例修改了title。

点击loadpatch,观察log,如果成功,应用默认为重启,然后再次启动即可达到修复效果。

到这里命令行的方式就介绍完了,和andfix的接入的方式基本上是一样的。

值得注意的是:该例仅展示了基本的接入,对于tinker的各种配置信息,还是需要去读tinker的文档(如果你确定要使用)tinker-wiki

(2)gradle接入

gradle接入的方式应该算是主流的方式,所以tinker也直接给出了例子,单独将该tinker-sample-android以project方式引入即可。

引入之后,可以查看其接入api的方式,以及相关配置。

在你每次build时,会在build/bakapk下生成本地打包的apk,r文件,以及mapping文件。

如果你需要生成patch文件,可以通过:

./gradlew tinkerpatchrelease // 或者 ./gradlew tinkerpatchdebug

生成。

生成目录为:build/outputs/tinkerpatch

需要注意的是,需要在app/build.gradle中设置相比较的apk(即old.apk,本次为new.apk),

ext {
  tinkerenabled = true
  //old apk file to build patch apk
  tinkeroldapkpath = "${bakpath}/old.apk"
  //proguard mapping file to build patch apk
  tinkerapplymappingpath = "${bakpath}/old-mapping.txt"}

提供的例子,基本上展示了tinker的自定义扩展的方式,具体还可以参考:

所以,如果你使用命令行方式接入,也不要忘了学习下其支持哪些扩展。

三、application是如何编译时生成的

从注释和命名上看:

//可选,用于生成application类provided('com.tencent.tinker:tinker-android-anno:1.7.7')

明显是该库,其结构如下:

典型的编译时注解的项目,源码见tinker-android-anno

入口为com.tencent.tinker.anno.annotationprocessor,可以在该services/javax.annotation.processing.processor文件中找到处理类全路径。

再次建议,如果你不了解,简单阅读下android 如何编写基于编译时注解的项目该文。

直接看annotationprocessor的process方法:

@overridepublic boolean process(set<? extends typeelement> annotations, roundenvironment roundenv) {
  processdefaultlifecycle(roundenv.getelementsannotatedwith(defaultlifecycle.class));  return true;
}

直接调用了processdefaultlifecycle:

private void processdefaultlifecycle(set<? extends element> elements) {    // 被注解defaultlifecycle标识的对象
    for (element e : elements) {     // 拿到defaultlifecycle注解对象
      defaultlifecycle ca = e.getannotation(defaultlifecycle.class);

      string lifecycleclassname = ((typeelement) e).getqualifiedname().tostring();
      string lifecyclepackagename = lifecycleclassname.substring(0, lifecycleclassname.lastindexof('.'));
      lifecycleclassname = lifecycleclassname.substring(lifecycleclassname.lastindexof('.') + 1);

      string applicationclassname = ca.application();      if (applicationclassname.startswith(".")) {
        applicationclassname = lifecyclepackagename + applicationclassname;
      }
      string applicationpackagename = applicationclassname.substring(0, applicationclassname.lastindexof('.'));
      applicationclassname = applicationclassname.substring(applicationclassname.lastindexof('.') + 1);

      string loaderclassname = ca.loaderclass();      if (loaderclassname.startswith(".")) {
        loaderclassname = lifecyclepackagename + loaderclassname;
      }       // /tinkerannoapplication.tmpl
      final inputstream is = annotationprocessor.class.getresourceasstream(application_template_path);      final scanner scanner = new scanner(is);      final string template = scanner.usedelimiter("\\a").next();      final string filecontent = template
        .replaceall("%package%", applicationpackagename)
        .replaceall("%application%", applicationclassname)
        .replaceall("%application_life_cycle%", lifecyclepackagename + "." + lifecycleclassname)
        .replaceall("%tinker_flags%", "" + ca.flags())
        .replaceall("%tinker_loader_class%", "" + loaderclassname)
        .replaceall("%tinker_load_verify_flag%", "" + ca.loadverifyflag());
        javafileobject fileobject = processingenv.getfiler().createsourcefile(applicationpackagename + "." + applicationclassname);
        processingenv.getmessager().printmessage(diagnostic.kind.note, "creating " + fileobject.touri());
     writer writer = fileobject.openwriter();
      printwriter pw = new printwriter(writer);
      pw.print(filecontent);
      pw.flush();
      writer.close();

    }
  }

代码比较简单,可以分三部分理解:

  • 步骤1:首先找到被defaultlifecycle标识的element(为类对象typeelement),得到该对象的包名,类名等信息,然后通过该对象,拿到@defaultlifecycle对象,获取该注解中声明属性的值。

  • 步骤2:读取一个模板文件,读取为字符串,将各个占位符通过步骤1中的值替代。

  • 步骤3:通过javafileobject将替换完成的字符串写文件,其实就是本例中的application对象。

我们看一眼模板文件:

package %package%;import com.tencent.tinker.loader.app.tinkerapplication;/**
 *
 * generated application for tinker life cycle
 *
 */public class %application% extends tinkerapplication {

  public %application%() {    super(%tinker_flags%, "%application_life_cycle%", "%tinker_loader_class%", %tinker_load_verify_flag%);
  }

}

对应我们的simpletinkerinapplicationlike

@defaultlifecycle(application = ".simpletinkerinapplication",
    flags = shareconstants.tinker_enable_all,
    loadverifyflag = false)public class simpletinkerinapplicationlike extends applicationlike {}

主要就几个占位符:

包名,如果application属性值以点开始,则同包;否则则截取

类名,application属性值中的类名

%tinker_flags%对应flags

%application_life_cycle%,编写的applicationlike的全路径

“%tinker_loader_class%”,这个值我们没有设置,实际上对应@defaultlifecycle的loaderclass属性,默认值为com.tencent.tinker.loader.tinkerloader

%tinker_load_verify_flag%对应loadverifyflag

于是最终生成的代码为:

/**
 *
 * generated application for tinker life cycle
 *
 */public class simpletinkerinapplication extends tinkerapplication {

  public simpletinkerinapplication() {    super(7, "com.zhy.tinkersimplein.simpletinkerinapplicationlike", "com.tencent.tinker.loader.tinkerloader", false);
  }

}

tinker这么做的目的,文档上是这么说的:

为了减少错误的出现,推荐使用annotation生成application类。

这样大致了解了application是如何生成的。

接下来我们大致看一下tinker的原理。

四、原理

来源于:https://github.com/tencent/tinker

tinker贴了一张大致的原理图。

可以看出:

tinker将old.apk和new.apk做了diff,拿到patch.dex,然后将patch.dex与本机中apk的classes.dex做了合并,生成新的classes.dex,运行时通过反射将合并后的dex文件放置在加载的dexelements数组的前面。

运行时替代的原理,其实和qzone的方案差不多,都是去反射修改dexelements。

两者的差异是:qzone是直接将patch.dex插到数组的前面;而tinker是将patch.dex与app中的classes.dex合并后的全量dex插在数组的前面。

tinker这么做的目的还是因为qzone方案中提到的class_ispreverified的解决方案存在问题;而tinker相当于换个思路解决了该问题。

接下来我们就从代码中去验证该原理。

本片文章源码分析的两条线:

应用启动时,从默认目录加载合并后的classes.dex

patch下发后,合成classes.dex至目标目录

五、源码分析

(1)加载patch

加载的代码实际上在生成的application中调用的,其父类为tinkerapplication,在其attachbasecontext中辗转会调用到loadtinker()方法,在该方法内部,反射调用了tinkerloader的tryload方法。

@overridepublic intent tryload(tinkerapplication app, int tinkerflag, boolean tinkerloadverifyflag) {
  intent resultintent = new intent();  long begin = systemclock.elapsedrealtime();
  tryloadpatchfilesinternal(app, tinkerflag, tinkerloadverifyflag, resultintent);  long cost = systemclock.elapsedrealtime() - begin;
  shareintentutil.setintentpatchcosttime(resultintent, cost);  return resultintent;
}

tryloadpatchfilesinternal中会调用到loadtinkerjars方法:

private void tryloadpatchfilesinternal(tinkerapplication app, int tinkerflag, boolean tinkerloadverifyflag, intent resultintent) {  // 省略大量安全性校验代码

  if (isenabledfordex) {    //tinker/patch.info/patch-641e634c/dex
    boolean dexcheck = tinkerdexloader.checkcomplete(patchversiondirectory, securitycheck, resultintent);    if (!dexcheck) {      //file not found, do not load patch
      log.w(tag, "tryloadpatchfiles:dex check fail");      return;
    }
  }  //now we can load patch jar
  if (isenabledfordex) {    boolean loadtinkerjars = tinkerdexloader.loadtinkerjars(app, tinkerloadverifyflag, patchversiondirectory, resultintent, issystemota);    if (!loadtinkerjars) {
      log.w(tag, "tryloadpatchfiles:onpatchloaddexesfail");      return;
    }
  }
}

tinkerdexloader.checkcomplete主要是用于检查下发的meta文件中记录的dex信息(meta文件,可以查看生成patch的产物,在assets/dex-meta.txt),检查meta文件中记录的dex文件信息对应的dex文件是否存在,并把值存在tinkerdexloader的静态变量dexlist中。

tinkerdexloader.loadtinkerjars传入四个参数,分别为application,tinkerloadverifyflag(注解上声明的值,传入为false),patchversiondirectory当前version的patch文件夹,intent,当前patch是否仅适用于art。

@targetapi(build.version_codes.ice_cream_sandwich)public static boolean loadtinkerjars(application application, boolean tinkerloadverifyflag, 
  string directory, intent intentresult, boolean issystemota) {
    pathclassloader classloader = (pathclassloader) tinkerdexloader.class.getclassloader();

    string dexpath = directory + "/" + dex_path + "/";
    file optimizedir = new file(directory + "/" + dex_optimize_path);

    arraylist<file> legalfiles = new arraylist<>();    final boolean isartplatform = sharetinkerinternals.isvmart();    for (sharedexdiffpatchinfo info : dexlist) {      //for dalvik, ignore art support dex
      if (isjustartsupportdex(info)) {        continue;
      }
      string path = dexpath + info.realname;
      file file = new file(path);

      legalfiles.add(file);
    }    // just for art
    if (issystemota) {
      parallelotaresult = true;
      parallelotathrowable = null;
      log.w(tag, "systemota, try parallel oat dexes!!!!!");

      tinkerparalleldexoptimizer.optimizeall(
        legalfiles, optimizedir,        new tinkerparalleldexoptimizer.resultcallback() {
        }
      );

    systemclassloaderadder.installdexes(application, classloader, optimizedir, legalfiles);    return true;
  }

找出仅支持art的dex,且当前patch是否仅适用于art时,并行去loaddex。

关键是最后的installdexes:

@suppresslint("newapi")public static void installdexes(application application, pathclassloader loader, file dexoptdir, list<file> files)  throws throwable {  if (!files.isempty()) {
    classloader classloader = loader;    if (build.version.sdk_int >= 24) {
      classloader = androidnclassloader.inject(loader, application);
    }    //because in dalvik, if inner class is not the same classloader with it wrapper class.
    //it won't fail at dex2opt
    if (build.version.sdk_int >= 23) {
      v23.install(classloader, files, dexoptdir);
    } else if (build.version.sdk_int >= 19) {
      v19.install(classloader, files, dexoptdir);
    } else if (build.version.sdk_int >= 14) {
      v14.install(classloader, files, dexoptdir);
    } else {
      v4.install(classloader, files, dexoptdir);
    }    //install done
    spatchdexcount = files.size();
    log.i(tag, "after loaded classloader: " + classloader + ", dex size:" + spatchdexcount);    if (!checkdexinstall(classloader)) {      //reset patch dex
      systemclassloaderadder.uninstallpatchdex(classloader);      throw new tinkerruntimeexception(shareconstants.check_dex_install_fail);
    }
  }
}

这里实际上就是根据不同的系统版本,去反射处理dexelements。

我们看一下v19的实现(主要我看了下本机只有个22的源码~):

private static final class v19 {

  private static void install(classloader loader, list<file> additionalclasspathentries,
                file optimizeddirectory)    throws illegalargumentexception, illegalaccessexception,
    nosuchfieldexception, invocationtargetexception, nosuchmethodexception, ioexception {

    field pathlistfield = sharereflectutil.findfield(loader, "pathlist");
    object dexpathlist = pathlistfield.get(loader);
    arraylist<ioexception> suppressedexceptions = new arraylist<ioexception>();
    sharereflectutil.expandfieldarray(dexpathlist, "dexelements", makedexelements(dexpathlist,      new arraylist<file>(additionalclasspathentries), optimizeddirectory,
      suppressedexceptions));    if (suppressedexceptions.size() > 0) {      for (ioexception e : suppressedexceptions) {
        log.w(tag, "exception in makedexelement", e);        throw e;
      }
    }
  }
}

找到pathclassloader(basedexclassloader)对象中的pathlist对象

根据pathlist对象找到其中的makedexelements方法,传入patch相关的对应的实参,返回element[]对象

拿到pathlist对象中原本的dexelements方法

步骤2与步骤3中的element[]数组进行合并,将patch相关的dex放在数组的前面

最后将合并后的数组,设置给pathlist

这里其实和qzone的提出的方案基本是一致的。如果你以前未了解过qzone的方案,可以参考此文:

android 热补丁动态修复框架小结

(2)合成patch

这里的入口为:

 tinkerinstaller.onreceiveupgradepatch(getapplicationcontext(),
        environment.getexternalstoragedirectory().getabsolutepath() + "/patch_signed.apk");

上述代码会调用defaultpatchlistener中的onpatchreceived方法:

# defaultpatchlistener@overridepublic int onpatchreceived(string path) {  int returncode = patchcheck(path);  if (returncode == shareconstants.error_patch_ok) {
    tinkerpatchservice.runpatchservice(context, path);
  } else {
    tinker.with(context).getloadreporter().onloadpatchlistenerreceivefail(new file(path), returncode);
  }  return returncode;

}

首先对tinker的相关配置(isenable)以及patch的合法性进行检测,如果合法,则调用tinkerpatchservice.runpatchservice(context, path);

public static void runpatchservice(context context, string path) {  try {
    intent intent = new intent(context, tinkerpatchservice.class);
    intent.putextra(patch_path_extra, path);
    intent.putextra(result_class_extra, resultserviceclass.getname());
    context.startservice(intent);
  } catch (throwable throwable) {
    tinkerlog.e(tag, "start patch service fail, exception:" + throwable);
  }
}

tinkerpatchservice是intentservice的子类,这里通过intent设置了两个参数,一个是patch的路径,一个是resultserviceclass,该值是调用tinker.install的时候设置的,默认为defaulttinkerresultservice.class。由于是intentservice,直接看onhandleintent即可,如果你对intentservice陌生

@overrideprotected void onhandleintent(intent intent) {  final context context = getapplicationcontext();
  tinker tinker = tinker.with(context);


  string path = getpatchpathextra(intent);

  file patchfile = new file(path);  boolean result;

  increasingpriority();
  patchresult patchresult = new patchresult();

  result = upgradepatchprocessor.trypatch(context, path, patchresult);

  patchresult.issuccess = result;
  patchresult.rawpatchfilepath = path;
  patchresult.costtime = cost;
  patchresult.e = e;

  abstractresultservice.runresultservice(context, patchresult, getpatchresultextra(intent));

}

比较清晰,主要关注upgradepatchprocessor.trypatch方法,调用的是upgradepatch.trypatch。ps:这里有个有意思的地方increasingpriority(),其内部实现为:

private void increasingpriority() {
  tinkerlog.i(tag, "try to increase patch process priority");  try {
    notification notification = new notification();    if (build.version.sdk_int < 18) {
      startforeground(notificationid, notification);
    } else {
      startforeground(notificationid, notification);      // start innerservice
      startservice(new intent(this, innerservice.class));
    }
  } catch (throwable e) {
    tinkerlog.i(tag, "try to increase patch process priority error:" + e);
  }
}

如果你对“保活”这个话题比较关注,那么对这段代码一定不陌生,主要是利用系统的一个漏洞来启动一个前台service。

下面继续回到trypatch方法:

# upgradepatch@overridepublic boolean trypatch(context context, string temppatchpath, patchresult patchresult) {
  tinker manager = tinker.with(context);  final file patchfile = new file(temppatchpath);  //it is a new patch, so we should not find a exist
  sharepatchinfo oldinfo = manager.gettinkerloadresultifpresent().patchinfo;
  string patchmd5 = sharepatchfileutil.getmd5(patchfile);  //use md5 as version
  patchresult.patchversion = patchmd5;
  sharepatchinfo newinfo;  //already have patch
  if (oldinfo != null) {
    newinfo = new sharepatchinfo(oldinfo.oldversion, patchmd5, build.fingerprint);
  } else {
    newinfo = new sharepatchinfo("", patchmd5, build.fingerprint);
  }  //check ok, we can real recover a new patch
  final string patchdirectory = manager.getpatchdirectory().getabsolutepath();  final string patchname = sharepatchfileutil.getpatchversiondirectory(patchmd5);  final string patchversiondirectory = patchdirectory + "/" + patchname;  //copy file
  file destpatchfile = new file(patchversiondirectory + "/" + sharepatchfileutil.getpatchversionfile(patchmd5));  // check md5 first
  if (!patchmd5.equals(sharepatchfileutil.getmd5(destpatchfile))) {
    sharepatchfileutil.copyfileusingstream(patchfile, destpatchfile);
  }  //we use destpatchfile instead of patchfile, because patchfile may be deleted during the patch process
  if (!dexdiffpatchinternal.tryrecoverdexfiles(manager, signaturecheck, context, patchversiondirectory, 
        destpatchfile)) {
    tinkerlog.e(tag, "upgradepatch trypatch:new patch recover, try patch dex failed");    return false;
  }  return true;
}

拷贝patch文件拷贝至私有目录,然后调用dexdiffpatchinternal.tryrecoverdexfiles

protected static boolean tryrecoverdexfiles(tinker manager, sharesecuritycheck checker, context context,
                        string patchversiondirectory, file patchfile) {
  string dexmeta = checker.getmetacontentmap().get(dex_meta_file);  boolean result = patchdexextractviadexdiff(context, patchversiondirectory, dexmeta, patchfile);  return result;
}

直接看patchdexextractviadexdiff

private static boolean patchdexextractviadexdiff(context context, string patchversiondirectory, string meta, final file patchfile) {
  string dir = patchversiondirectory + "/" + dex_path + "/";  if (!extractdexdiffinternals(context, dir, meta, patchfile, type_dex)) {
    tinkerlog.w(tag, "patch recover, extractdiffinternals fail");    return false;
  }  final tinker manager = tinker.with(context);

  file dexfiles = new file(dir);
  file[] files = dexfiles.listfiles();

  ...files遍历执行:dexfile.loaddex   return true;
}

核心代码主要在extractdexdiffinternals中:

private static boolean extractdexdiffinternals(context context, string dir, string meta, file patchfile, int type) {  //parse meta
  arraylist<sharedexdiffpatchinfo> patchlist = new arraylist<>();
  sharedexdiffpatchinfo.parsedexdiffpatchinfo(meta, patchlist);

  file directory = new file(dir);  //i think it is better to extract the raw files from apk
  tinker manager = tinker.with(context);
  zipfile apk = null;
  zipfile patch = null;

  applicationinfo applicationinfo = context.getapplicationinfo();

  string apkpath = applicationinfo.sourcedir; //base.apk
  apk = new zipfile(apkpath);
  patch = new zipfile(patchfile);  for (sharedexdiffpatchinfo info : patchlist) {    final string infopath = info.path;
    string patchrealpath;    if (infopath.equals("")) {
      patchrealpath = info.rawname;
    } else {
      patchrealpath = info.path + "/" + info.rawname;
    }

    file extractedfile = new file(dir + info.realname);

    zipentry patchfileentry = patch.getentry(patchrealpath);
    zipentry rawapkfileentry = apk.getentry(patchrealpath);

    patchdexfile(apk, patch, rawapkfileentry, patchfileentry, info, extractedfile);
  }  return true;
}

这里的代码比较关键了,可以看出首先解析了meta里面的信息,meta中包含了patch中每个dex的相关数据。然后通过application拿到sourcedir,其实就是本机apk的路径以及patch文件;根据mate中的信息开始遍历,其实就是取出对应的dex文件,最后通过patchdexfile对两个dex文件做合并。

private static void patchdexfile(
      zipfile baseapk, zipfile patchpkg, zipentry olddexentry, zipentry patchfileentry,
      sharedexdiffpatchinfo patchinfo, file patcheddexfile) throws ioexception {
  inputstream olddexstream = null;
  inputstream patchfilestream = null;

  olddexstream = new bufferedinputstream(baseapk.getinputstream(olddexentry));
  patchfilestream = (patchfileentry != null ? new bufferedinputstream(patchpkg.getinputstream(patchfileentry)) : null);  new dexpatchapplier(olddexstream, patchfilestream).executeandsaveto(patcheddexfile);

}

通过zipfile拿到其内部文件的inputstream,其实就是读取本地apk对应的dex文件,以及patch中对应dex文件,对二者的通过executeandsaveto方法进行合并至patcheddexfile,即patch的目标私有目录。

至于合并算法,这里其实才是tinker比较核心的地方,这个算法跟dex文件格式紧密关联,如果有机会,然后我又能看懂的话,后面会单独写篇博客介绍。此外dodola已经有篇博客进行了介绍:

tinker dexdiff算法解析

感兴趣的可以阅读下。

好了,到此我们就大致了解了tinker热修复的原理~~

测试demo地址:

https://github.com/wanandroid/tinkertest

当然这里只分析了代码了热修复,后续考虑分析资源以及so的热修、核心的diff算法、以及gradle插件等相关知识~

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网