0. 前言
热修复这项技术,基本上已经成为android项目比较重要的模块了。主要因为项目在上线之后,都难免会有各种问题,而依靠发版去修复问题,成本太高了。
现在热修复的技术基本上有阿里的andfix、qzone的方案、美团提出的思想方案以及腾讯的tinker等。
其中andfix可能接入是最简单的一个(和tinker命令行接入方式差不多),不过andfix兼容性有一定的问题,qzone方案对性能会有一定的影响,且在art模式下出现内存错乱的问题,美团提出的思想方案主要是基于instant run的原理,目前尚未开源,兼容性较好。
这么看来,如果选择开源方案,tinker目前是最佳的选择,下面来看看tinker的大致的原理分析。
1. 原理概述
tinker将old.apk和new.apk做了diff,拿到patch.dex后将其与本机中apk的classes.dex做了合并,生成新的classes.dex,运行时通过反射将合并后的dex文件放置在加载的dexelements数组的前面。
运行时替代的原理,其实和qzone的方案差不多,都是去反射修改dexelements。两者的差异是:qzone是直接将patch.dex插到数组的前面;而tinker是合并后的全量dex插在数组的前面。因为qzone方案中提到的class_ispreverified的解决方案存在问题。
android的classloader体系中加载类一般使用的是pathclassloader和dexclassloader,大家只需要明白,android使用pathclassloader作为其类加载器,dexclassloader可以从.jar和.apk类型的文件内部加载classes.dex文件就好了。对于加载类,无非是给个classname,然后去findclass,pathclassloader和dexclassloader都继承自basedexclassloader。在basedexclassloader中有如下源码:
#basedexclassloader
@override
protected class<?> findclass(string name) throws classnotfoundexception {
class clazz = pathlist.findclass(name);
if (clazz == null) {
throw new classnotfoundexception(name);
}
return clazz;
}
#dexpathlist
public class findclass(string name) {
for (element element : dexelements) {
dexfile dex = element.dexfile;
if (dex != null) {
class clazz = dex.loadclassbinaryname(name, definingcontext);
if (clazz != null) {
return clazz;
}
}
}
return null;
}
#dexfile
public class loadclassbinaryname(string name, classloader loader) {
return defineclass(name, loader, mcookie);
}
private native static class defineclass(string name, classloader loader, int cookie);
可以看出basedexclassloader中有个pathlist对象,pathlist中包含一个dexfile的集合dexelements,而对于类加载就是遍历这个集合,通过dexfile去寻找。
通俗点说,一个classloader可以包含多个dex文件,每个dex文件是一个element,多个dex文件排列成一个有序的数组dexelements,当找类的时候,会按顺序遍历dex文件,然后从当前遍历的dex文件中找类,如果找类则返回,如果找不到从下一个dex文件继续查找。那么这样的话,我们可以在这个数组的第一个元素放置我们的patch.jar,里面包含修复过的类,这样的话,当遍历findclass的时候,我们修复的类就会被查找到,从而替代有bug的类。
本片文章tinker源码分析的两条线:
(1)应用启动时,从默认目录加载合并后的classes.dex
(2)patch下发后,合成classes.dex至目标目录
2.源码浅析
2.1 加载patch
加载的代码实际上在生成的application中调用的,其父类为tinkerapplication,在其attachbasecontext中辗转会调用到loadtinker()方法,在该方法内部,反射调用了tinkerloader的tryload方法。继而调用了tryloadpatchfilesinternal方法。
@override
public 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;
}
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的实现:
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;
}
}
}
}
(1)找到pathclassloader(basedexclassloader)对象中的pathlist对象
(2)根据pathlist对象找到其中的makedexelements方法,传入patch相关的对应的实参,返回element[]对象
(3)拿到pathlist对象中原本的dexelements方法
(4)步骤2与步骤3中的element[]数组进行合并,将patch相关的dex放在数组的前面
(5)最后将合并后的数组,设置给pathlist
2.2 合成patch
入口为onreceiveupgradepatch()方法:
tinkerinstaller.onreceiveupgradepatch(getapplicationcontext(),
environment.getexternalstoragedirectory().getabsolutepath() + "/patch_signed.apk");
上述代码会调用defaultpatchlistener中的onpatchreceived方法:
# defaultpatchlistener
@override
public 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即可。
@override
protected 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。这里有个有意思的地方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
@override
public 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比较核心的地方,感兴趣可以参考这篇文章!
以上就是android开发— 热修复tinker源码的简单介绍的详细内容。