腾讯面试合集:热修复连环炮(热修复是什么-有接触过tinker吗,tinker原理是什么)

###5.Tinker原理
先上github官方首页的图

BaseApk就是我们的基准包,也就是渠道上线的包。

NewApk就是我们的hotfix包,包括修复的代码资源以及so文件。

Tinker做了对应的DexDiff、ResDiff、BsDiff来产出一个patch.apk,里面具体内容也是由lib、res和dex文件组成,assets中还有对应的dex、res和so信息

然后Tinker通过找到基准包data/app/packagename/base.apk通过DexPatch合成新的dex,并且合成一个tinker_classN.apk(其实就是包含了所有合成dex的zip包)接着在运行时通过反射把这个合成dex文件插入到PathClassLoader中的dexElements数组的前面,保证类加载时优先加载补丁dex中的class。

接下来我们就从加载patch和合成patch来弄清Tinker的整个工作流程。
###6.Tinker源码分析之加载补丁Patch流程
默认情况如果使用了Tinker注解产生Application可以看到它继承了TinkerApplication

/**
*

  • Generated application for tinker life cycle

*/
public class Application extends TinkerApplication {

public Application() {
super(7, “com.jiuyan.infashion.ApplicationLike”, “com.tencent.tinker.loader.TinkerLoader”, false);
}

}

跟踪到TinkerApplication在方法attachBaseContext中找到最终会调用loadTinker方法来,最后反射调用了变量loaderClassName定义类中的tryLoad方法,默认是com.tencent.tinker.loader.TinkerLoader这个类中的tryLoad方法。该方法调用tryLoadPatchFilesInternal来执行相关代码逻辑。

private void tryLoadPatchFilesInternal(TinkerApplication app, Intent resultIntent) {
//…省略一大段校验相关逻辑代码

//now we can load patch jar
if (isEnabledForDex) {
boolean loadTinkerJars = TinkerDexLoader.loadTinkerJars(app, patchVersionDirectory, oatDex, resultIntent, isSystemOTA);
if (isSystemOTA) {
// update fingerprint after load success
patchInfo.fingerPrint = Build.FINGERPRINT;
patchInfo.oatDir = loadTinkerJars ? ShareConstants.INTERPRET_DEX_OPTIMIZE_PATH : ShareConstants.DEFAULT_DEX_OPTIMIZE_PATH;
// reset to false
oatModeChanged = false;

if (!SharePatchInfo.rewritePatchInfoFileWithLock(patchInfoFile, patchInfo, patchInfoLockFile)) {
ShareIntentUtil.setIntentReturnCode(resultIntent, ShareConstants.ERROR_LOAD_PATCH_REWRITE_PATCH_INFO_FAIL);
Log.w(TAG, “tryLoadPatchFiles:onReWritePatchInfoCorrupted”);
return;
}
// update oat dir
resultIntent.putExtra(ShareIntentUtil.INTENT_PATCH_OAT_DIR, patchInfo.oatDir);
}
if (!loadTinkerJars) {
Log.w(TAG, “tryLoadPatchFiles:onPatchLoadDexesFail”);
return;
}
}

//now we can load patch resource
if (isEnabledForResource) {
boolean loadTinkerResources = TinkerResourceLoader.loadTinkerResources(app, patchVersionDirectory, resultIntent);
if (!loadTinkerResources) {
Log.w(TAG, “tryLoadPatchFiles:onPatchLoadResourcesFail”);
return;
}
}
// kill all other process if oat mode change
if (oatModeChanged) {
ShareTinkerInternals.killAllOtherProcess(app);
Log.i(TAG, “tryLoadPatchFiles:oatModeChanged, try to kill all other process”);
}
//all is ok!
ShareIntentUtil.setIntentReturnCode(resultIntent, ShareConstants.ERROR_LOAD_OK);
Log.i(TAG, “tryLoadPatchFiles: load end, ok!”);
return;
}

这里省略了非常多的Tinker校验,一共有包括tinker自身enable属性以及md5和文件存在等相关检查。

先看加载dex部分,TinkerDexLoader.loadTinkerJars传入四个参数,分别为application,patchVersionDirectory当前patch文件目录,oatDir当前patch的oat文件目录,intent,当前patch是否需要进行oat(由于系统OTA更新需要dex oat重新生成缓存)。

/**

  • Load tinker JARs and add them to
  • the Application ClassLoader.
  • @param application The application.
    */
    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    public static boolean loadTinkerJars(final TinkerApplication application, String directory, String oatDir, Intent intentResult, boolean isSystemOTA) {
    if (loadDexList.isEmpty() && classNDexInfo.isEmpty()) {
    Log.w(TAG, “there is no dex to load”);
    return true;
    }

PathClassLoader classLoader = (PathClassLoader) TinkerDexLoader.class.getClassLoader();
if (classLoader != null) {
Log.i(TAG, "classloader: " + classLoader.toString());
} else {
Log.e(TAG, “classloader is null”);
ShareIntentUtil.setIntentReturnCode(intentResult, ShareConstants.ERROR_LOAD_PATCH_VERSION_DEX_CLASSLOADER_NULL);
return false;
}
String dexPath = directory + “/” + DEX_PATH + “/”;

ArrayList legalFiles = new ArrayList<>();

for (ShareDexDiffPatchInfo info : loadDexList) {
//for dalvik, ignore art support dex
if (isJustArtSupportDex(info)) {
continue;
}

String path = dexPath + info.realName;
File file = new File(path);

//…check md5
legalFiles.add(file);
}
//… verify merge classN.apk

File optimizeDir = new File(directory + “/” + oatDir);

if (isSystemOTA) {
final boolean[] parallelOTAResult = {true};
final Throwable[] parallelOTAThrowable = new Throwable[1];
String targetISA;
try {
targetISA = ShareTinkerInternals.getCurrentInstructionSet();
} catch (Throwable throwable) {
Log.i(TAG, “getCurrentInstructionSet fail:” + throwable);
// try {
// targetISA = ShareOatUtil.getOatFileInstructionSet(testOptDexFile);
// } catch (Throwable throwable) {
// don’t ota on the front
deleteOutOfDateOATFile(directory);

intentResult.putExtra(ShareIntentUtil.INTENT_PATCH_INTERPRET_EXCEPTION, throwable);
ShareIntentUtil.setIntentReturnCode(intentResult, ShareConstants.ERROR_LOAD_PATCH_GET_OTA_INSTRUCTION_SET_EXCEPTION);
return false;
// }
}

deleteOutOfDateOATFile(directory);

Log.w(TAG, “systemOTA, try parallel oat dexes, targetISA:” + targetISA);
// change dir
optimizeDir = new File(directory + “/” + INTERPRET_DEX_OPTIMIZE_PATH);

TinkerDexOptimizer.optimizeAll(
legalFiles, optimizeDir, true, targetISA,
new TinkerDexOptimizer.ResultCallback() {
//… callback
}
);

if (!parallelOTAResult[0]) {
Log.e(TAG, “parallel oat dexes failed”);
intentResult.putExtra(ShareIntentUtil.INTENT_PATCH_INTERPRET_EXCEPTION, parallelOTAThrowable[0]);
ShareIntentUtil.setIntentReturnCode(intentResult, ShareConstants.ERROR_LOAD_PATCH_OTA_INTERPRET_ONLY_EXCEPTION);
return false;
}
}
try {
SystemClassLoaderAdder.installDexes(application, classLoader, optimizeDir, legalFiles);
} catch (Throwable e) {
Log.e(TAG, “install dexes failed”);
// e.printStackTrace();
intentResult.putExtra(ShareIntentUtil.INTENT_PATCH_EXCEPTION, e);
ShareIntentUtil.setIntentReturnCode(intentResult, ShareConstants.ERROR_LOAD_PATCH_VERSION_DEX_LOAD_EXCEPTION);
return false;
}

return true;
}

省略了几处md5校验代码,首先获取到PathClassLoader并且通过判断系统是否art过滤出对应legalFiles,如果发现系统进行过OTA升级则通过ProcessBuilder命令行执行dex2oat进行并行的oat优化dex,最后调用installDexes来安装dex。

@SuppressLint(“NewApi”)
public static void installDexes(Application application, PathClassLoader loader, File dexOptDir, List files)
throws Throwable {
Log.i(TAG, "installDexes dexOptDir: " + dexOptDir.getAbsolutePath() + “, dex size:” + files.size());

if (!files.isEmpty()) {
files = createSortedAdditionalPathEntries(files);
ClassLoader classLoader = loader;
if (Build.VERSION.SDK_INT >= 24 && !checkIsProtectedApp(files)) {
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);
}
}
}

针对不同的Android版本需要对DexPathList中的dexElements生成方法makeDexElements进行适配。

主要做的事情就是获取当前app运行时PathClassLoader的父类BaseDexClassLoader中的pathList对象,通过反射它的makePathElements方法传入对应的path参数构造出Element[]数组对象,然后拿到pathList中的Element[]数组对象dexElements两者进行合并排序,把patch的相关dex信息放在数组前端,最后合并数组结果赋值给pathList保证classloader优先到patch中查找加载。

###7.Tinker源码分析之合成补丁Patch流程
合并代码入口

Tinker.with(context).getPatchListener().onPatchReceived(patchLocation);

传入patch文件所在位置即可,推荐通过服务端下发下载到对应的/data/data/应用目录下防止被三方软件清理,onPatchReceived方法在DefaultPatchListener.java中。

@Override
public int onPatchReceived(String path) {
File patchFile = new File(path);

int returnCode = patchCheck(path, SharePatchFileUtil.getMD5(patchFile));

if (returnCode == ShareConstants.ERROR_PATCH_OK) {
TinkerPatchService.runPatchService(context, path);
} else {
Tinker.with(context).getLoadReporter().onLoadPatchListenerReceiveFail(new File(path), returnCode);
}
return returnCode;
}

先进行tinker的一些初始化配置检查还有patch文件的md5校验。如果check通过returnCode为0则执行runPatchService启动一个IntentService的子类TinkerPatchService来处理patch的合成。接下来看Service执行任务代码:

@Override
protected void onHandleIntent(Intent intent) {
final Context context = getApplicationContext();
Tinker tinker = Tinker.with(context);
tinker.getPatchReporter().onPatchServiceStart(intent);

if (intent == null) {
TinkerLog.e(TAG, “TinkerPatchService received a null intent, ignoring.”);
return;
}
String path = getPatchPathExtra(intent);
if (path == null) {
TinkerLog.e(TAG, “TinkerPatchService can’t get the path extra, ignoring.”);
return;
}
File patchFile = new File(path);

long begin = SystemClock.elapsedRealtime();
boolean result;
long cost;
Throwable e = null;

increasingPriority();
PatchResult patchResult = new PatchResult();
try {
if (upgradePatchProcessor == null) {
throw new TinkerRuntimeException(“upgradePatchProcessor is null.”);
}
result = upgradePatchProcessor.tryPatch(context, path, patchResult);
} catch (Throwable throwable) {
e = throwable;
result = false;
tinker.getPatchReporter().onPatchException(patchFile, e);
}

cost = SystemClock.elapsedRealtime() - begin;
tinker.getPatchReporter().
onPatchResult(patchFile, result, cost);

patchResult.isSuccess = result;
patchResult.rawPatchFilePath = path;
patchResult.costTime = cost;
patchResult.e = e;

AbstractResultService.runResultService(context, patchResult, getPatchResultExtra(intent));

}

回调PatchReporter接口的onPatchServiceStart方法,然后取到patch文件同时调用increasingPriority启动一个不可见前台Service保活这个TinkerPatchService,最后开始合成patchupgradePatchProcessor.tryPatch。同样省略一些常规check代码:

@Override
public boolean tryPatch(Context context, String tempPatchPath, PatchResult patchResult) {
Tinker manager = Tinker.with(context);
final File patchFile = new File(tempPatchPath);
//…省略

//check ok, we can real recover a new patch
final String patchDirectory = manager.getPatchDirectory().getAbsolutePath();

File patchInfoLockFile = SharePatchFileUtil.getPatchInfoLockFile(patchDirectory);
File patchInfoFile = SharePatchFileUtil.getPatchInfoFile(patchDirectory);

SharePatchInfo oldInfo = SharePatchInfo.readAndCheckPropertyWithLock(patchInfoFile, patchInfoLockFile);

//it is a new patch, so we should not find a exist
SharePatchInfo newInfo;

//already have patch
if (oldInfo != null) {
if (oldInfo.oldVersion == null || oldInfo.newVersion == null || oldInfo.oatDir == null) {
TinkerLog.e(TAG, “UpgradePatch tryPatch:onPatchInfoCorrupted”);
manager.getPatchReporter().onPatchInfoCorrupted(patchFile, oldInfo.oldVersion, oldInfo.newVersion);
return false;
}

if (!SharePatchFileUtil.checkIfMd5Valid(patchMd5)) {
TinkerLog.e(TAG, “UpgradePatch tryPatch:onPatchVersionCheckFail md5 %s is valid”, patchMd5);
manager.getPatchReporter().onPatchVersionCheckFail(patchFile, oldInfo, patchMd5);
return false;
}
// if it is interpret now, use changing flag to wait main process
final String finalOatDir = oldInfo.oatDir.equals(ShareConstants.INTERPRET_DEX_OPTIMIZE_PATH)
? ShareConstants.CHANING_DEX_OPTIMIZE_PATH : oldInfo.oatDir;
newInfo = new SharePatchInfo(oldInfo.oldVersion, patchMd5, Build.FINGERPRINT, finalOatDir);
} else {
newInfo = new SharePatchInfo(“”, patchMd5, Build.FINGERPRINT, ShareConstants.DEFAULT_DEX_OPTIMIZE_PATH);
}

//it is a new patch, we first delete if there is any files
//don’t delete dir for faster retry
// SharePatchFileUtil.deleteDir(patchVersionDirectory);
final String patchName = SharePatchFileUtil.getPatchVersionDirectory(patchMd5);

final String patchVersionDirectory = patchDirectory + “/” + patchName;

TinkerLog.i(TAG, “UpgradePatch tryPatch:patchVersionDirectory:%s”, patchVersionDirectory);

//copy file
File destPatchFile = new File(patchVersionDirectory + “/” + SharePatchFileUtil.getPatchVersionFile(patchMd5));

//…省略

if (!DexDiffPatchInternal.tryRecoverDexFiles(manager, signatureCheck, context, patchVersionDirectory, destPatchFile)) {
TinkerLog.e(TAG, “UpgradePatch tryPatch:new patch recover, try patch dex failed”);
return false;
}

if (!BsDiffPatchInternal.tryRecoverLibraryFiles(manager, signatureCheck, context, patchVersionDirectory, destPatchFile)) {
TinkerLog.e(TAG, “UpgradePatch tryPatch:new patch recover, try patch library failed”);
return false;
}

if (!ResDiffPatchInternal.tryRecoverResourceFiles(manager, signatureCheck, context, patchVersionDirectory, destPatchFile)) {
TinkerLog.e(TAG, “UpgradePatch tryPatch:new patch recover, try patch resource failed”);
return false;
}

//…省略
}

1.检查是否有之前的patch信息oldInfo,查看旧补丁是否正在执行oat过程,后续会等待主进程oat执行完毕。 2.拷贝new patch到app的data目录的tinker目录下,防止被三方软件删除。 3.分别判断执行tryRecoverDexFiles合成dex,tryRecoverLibraryFiles合成so以及tryRecoverResourceFiles合成资源。

主要看下dex合成过程,这也是我们最关心的地方。

protected static boolean tryRecoverDexFiles(Tinker manager, ShareSecurityCheck checker, Context context,
String patchVersionDirectory, File patchFile) {
if (!manager.isEnabledForDex()) {
TinkerLog.w(TAG, “patch recover, dex is not enabled”);
return true;
}
String dexMeta = checker.getMetaContentMap().get(DEX_META_FILE);

if (dexMeta == null) {
TinkerLog.w(TAG, “patch recover, dex is not contained”);
return true;
}

long begin = SystemClock.elapsedRealtime();
boolean result = patchDexExtractViaDexDiff(context, patchVersionDirectory, dexMeta, patchFile);
long cost = SystemClock.elapsedRealtime() - begin;
TinkerLog.i(TAG, “recover dex result:%b, cost:%d”, result, cost);
return result;
}

读取patch包assets/dex_meta.txt信息转换成String,进入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;
}

File dexFiles = new File(dir);
File[] files = dexFiles.listFiles();
List dexList = files != null ? Arrays.asList(files) : null;

final String optimizeDexDirectory = patchVersionDirectory + “/” + DEX_OPTIMIZE_PATH + “/”;
return dexOptimizeDexFiles(context, dexList, optimizeDexDirectory, patchFile);

}

首先执行方法extractDexDiffInternals传入了合成后dex路径,前面读取的dex_meta信息,patch文件以及type类型dex。为了节约篇幅只提取了主要的代码,详细代码参考github。

private static boolean extractDexDiffInternals(Context context, String dir, String meta, File patchFile, int type) {
//parse
patchList.clear();
ShareDexDiffPatchInfo.parseDexDiffPatchInfo(meta, patchList);
//获取base.apk
String apkPath = applicationInfo.sourceDir;
apk = new ZipFile(apkPath);
patch = new ZipFile(patchFile);
for (ShareDexDiffPatchInfo info : patchList) {
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);
}

最后

下面是辛苦给大家整理的学习路线


《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》点击传送门,即可获取!
extractedFile = new File(dir + info.realName);
//…省略

ZipEntry patchFileEntry = patch.getEntry(patchRealPath);
ZipEntry rawApkFileEntry = apk.getEntry(patchRealPath);

patchDexFile(apk, patch, rawApkFileEntry, patchFileEntry, info, extractedFile);
}

最后

下面是辛苦给大家整理的学习路线

[外链图片转存中…(img-mDUjuXMo-1715362422878)]
《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》点击传送门,即可获取!

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值