Android热修复基本原理
热修复的原理主要有两种技术,一是不需要启动APP就能实现修复,在 Native 层实现的。一种是需要启动 App,在JAVA层实现的。 本文会介绍 Android 热修复的最基本原理( Java 层实现的,需要重启 App),那就是通过 ClassLoader 的机制,通过反射先加载补丁包的类,从而替换掉存在 BUG 的类,达到修复的目的。
JVM与Dalvik
Android应用程序运行在 Dalvik/ART 虚拟机,并且每一个应用程序对应有一个单独的 Dalvik 虚拟机实例。Dalvik 虚拟机实则也算是一个 Java 虚拟机,只不过它执行的不是 class 文件,而是 dex 文件。class 文件有很多冗余信息,dex文件会做去冗余信息的优化。
Dalvik 虚拟机与 Java 虚拟机共享有差不多的特性,差别在于两者执行的指令集是不一样的,前者的指令集是基本寄存器的,而后者的指令集是基于堆栈的。
基于栈的虚拟机
对于基于栈的虚拟机来说,每一个运行时的线程,都有一个独立的栈。栈中记录了方法调用的历史,每有一次方法调用,栈中便会多一个栈桢。最顶部的栈桢称作当前栈桢,其代表着当前执行的方法。基于栈的虚拟机通过操作数栈进行所有操作。
JVM是基于栈的指令会很紧凑,比如一个方法体的执行,需要经过一连串的指令来完成,JVM指令集是没有任何变量的,执行过程中,结合局部变量表,完成方法体指令的执行,过程中实际上需要和内存空间进行不断交互,这也是为什么一个 java 程序跑起来后,会占用很大的内存的原因。JVM使用的指令只占一个字节,因而称为字节码。
ICONST_1 : 将int类型常量1压入操作数栈;
ISTORE 0 : 将栈顶int类型值存入局部变量0;
IADD : 执行int类型的加法 ;
基于寄存器的虚拟机
Dalvik是基于寄存器的虚拟机,其指令集需要指定源地址和目标地址(理解为变量声明),因此需要更多的指令空间。Dalvik的某些指令需要占用两个字节。
基于栈和基于寄存器的指令集,各有优势,一般来说,执行同样的功能,基于栈需要更多的指令(主要是load和store),而基于寄存器需要更多的指令空间。
基于寄存器的虚拟机中没有操作数栈,但是有很多虚拟寄存器。其实和操作数栈相同,这些寄存器也存放在运行时栈中,本质上就是一个数组。与JVM相似,在Dalvik VM中每个线程都有自己的PC和调用栈,方法调用的活动记录以帧为单位保存在调用栈上。
而且 Dalvik 版程序的指令数明显减少了,数据移动次数也明显减少了。基于寄存器的虚拟机虽然比基于堆栈的虚拟机在硬件通用性上要差一些,但是它的代码执行效率却更好。 显然,后者最大的好处在于可以根据硬件实现更大的优化,这更适合移动设备的特点。
ART与Dalvik
Dalvik虚拟机执行的是dex字节码,解释执行。从Android 2.2版本开始,支持JIT即时编译(Just In Time),即在程序运行的过程中进行选择热点代码(经常执行的代码)进行编译或者优化。
而ART(Android Runtime) 是在 Android 4.4 中引入的一个开发者选项,也是 Android 5.0 及更高版本的默认 Android 运行时。ART虚拟机执行的是本地机器码。Android的运行时从Dalvik虚拟机替换成ART虚拟机,并不要求开发者将自己的应用直接编译成目标机器码,APK仍然是一个包含dex字节码的文件。
那么,ART虚拟机执行的本地机器码是从哪里来?
Dalvik下应用在安装的过程,会执行一次优化,将dex字节码进行优化生成odex文件。而Art下将应用的dex字节码翻译成本地机器码的最恰当AOT时机也就发生在应用安装的时候。ART 引入了预先编译机制(Ahead Of Time),在安装时,ART 使用设备自带的 dex2oat 工具来编译应用,dex中的字节码将被编译成本地机器码。
简单来说在应用程序安装的过程中,ART就已经将所有的字节码重新编译成了机器码。应用程序运行过程中无需进行实时的编译工作,只需要进行直接调用。因此,ART极大的提高了应用程序的运行效率,但是这样会导致应用的安装速度会变慢,所以谷歌在Android N引入了混编机制。
Android N 的运作方式
ART 使用预先 (AOT) 编译,并且从 Android N混合使用 AOT 编译,解释和 JIT 。
1、最初安装应用时不进行任何 AOT 编译(安装又快了),运行过程中解释执行,对经常执行的方法进行 JIT,经过 JIT 编译的方法将会记录到 Profile 配置文件中。
2、当设备闲置和充电时,编译守护进程会运行,根据 Profile 文件对常用代码进行 AOT 编译。待下次运行时直接使用编译好的机器码。
ClassLoader
先回顾下 Java 中的 ClassLoader
BootstrapClassLoader 负责加载 JVM 运行时的核心类,比如 JAVA_HOME/lib/rt.jar
等等
ExtensionClassLoader 负责加载 JVM 的扩展类,比如 JAVA_HOME/lib/ext
下面的 jar 包
AppClassLoader 负责加载 classpath 里的 jar 包和目录
双亲委派机制
某个类加载器在加载类时,首先将加载任务委托给父类加载器,依次递归,如果父类加载器可以完成类加载任务,就成功返回;只有父类加载器无法完成此加载任务或者没有父类加载器时,才自己去加载。
1、避免重复加载,当父加载器已经加载了该类的时候,就没有必要子 ClassLoader 再加载一次。
2、安全性考虑,防止核心API库被随意篡改。
public abstract class ClassLoader {
public Class<?> loadClass(String className) throws ClassNotFoundException {
return loadClass(className, false);
}
protected Class<?> loadClass(String className, boolean resolve) throws ClassNotFoundException {
// 判断当前类加载器是否已经加载过指定类,若已加载则直接返回
Class<?> clazz = findLoadedClass(className);
if (clazz == null) {
// 如果没有加载过,则调用parent的类加载递归加载该类,若已加载则直接返回
clazz = parent.loadClass(className, false);
if (clazz == null) {
// 还没加载,则调用当前类加载器来加载[见小节3.2]
clazz = findClass(className);
}
}
return clazz;
}
}
Android 中的 ClassLoader:
可以看看各个类的ClassLoader是不是和上图一致:
Log.d(TAG, "String: " + String.class.getClassLoader());
Log.d(TAG, "Activity: " + Activity.class.getClassLoader());
Log.d(TAG, "AppCompatActivity: " + AppCompatActivity.class.getClassLoader());
Log.d(TAG, "getClassLoader: " + getClassLoader());
Log.d(TAG, "AppCompatActivity getParent: " + AppCompatActivity.class.getClassLoader().getParent());
Log.d(TAG, "Application: " + Application.class.getClassLoader());
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
Log.d(TAG, "getSystemClassLoader: " + classLoader);
可以看到 BootClassLoader 加载了 AndroidFramework层以及 rt.jar 里面的类,Jar包和自己的代码类由 PathClassLoader 来完成加载。主要来看看 PathClassLoader,DexClassLoader,BaseDexClassLoader,BootClassLoader,ClassLoader 这5个类加载器:
PathClassLoader
public class PathClassLoader extends BaseDexClassLoader {
public PathClassLoader(String dexPath, ClassLoader parent) {
super((String)null, (File)null, (String)null, (ClassLoader)null);
throw new RuntimeException("Stub!");
}
public PathClassLoader(String dexPath, String librarySearchPath, ClassLoader parent) {
super((String)null, (File)null, (String)null, (ClassLoader)null);
throw new RuntimeException("Stub!");
}
}
PathClassLoader 比较简单, 继承于 BaseDexClassLoader.
DexClassLoader
public class DexClassLoader extends BaseDexClassLoader {
public DexClassLoader(String dexPath, String optimizedDirectory, String librarySearchPath, ClassLoader parent) {
super((String)null, (File)null, (String)null, (ClassLoader)null);
throw new RuntimeException("Stub!");
}
}
DexClassLoader也同样,只是简单地封装了BaseDexClassLoader对象
BaseDexClassLoader
public class BaseDexClassLoader extends ClassLoader {
public BaseDexClassLoader(String dexPath, File optimizedDirectory, String librarySearchPath, ClassLoader parent) {
throw new RuntimeException("Stub!");
}
}
BaseDexClassLoader 构造函数,有一个非常重要的过程,那就是初始化 DexPathList 对象。
另外该构造函数的参数说明:
- dexPath: 包含目标类或资源的
apk/jar
列表;当有多个路径则采用:
分割; - optimizedDirectory: 优化后 dex 文件存在的目录,可以为 null;
- libraryPath: native库所在路径列表;当有多个路径则采用
:
分割; - ClassLoader:父类的类加载器;
ClassLoader
public abstract class ClassLoader {
private ClassLoader parent; // 记录父类加载器
protected ClassLoader() {
this(getSystemClassLoader(), false); // 见下文
}
protected ClassLoader(ClassLoader parentLoader) {
this(parentLoader, false);
}
ClassLoader(ClassLoader parentLoader, boolean nullAllowed) {
if (parentLoader == null && !nullAllowed) {
// 父类的类加载器为空,则抛出异常
throw new NullPointerException("parentLoader == null && !nullAllowed");
}
parent = parentLoader;
}
}
BootClassLoader
class BootClassLoader extends ClassLoader {
private static BootClassLoader instance;
public static synchronized BootClassLoader getInstance() {
if (instance == null) {
instance = new BootClassLoader();
}
return instance;
}
public BootClassLoader() {
super(null, true);
}
}
以上所有的 ClassLoader 都直接或间接着继承于抽象类 ClassLoader。
DexPathList
BaseDexClassLoader 里 DexPathList 属性主要就是记录了 dex 文件的列表:
final class DexPathList {
private Element[] dexElements;
private final List<File> nativeLibraryDirectories;
private final List<File> systemNativeLibraryDirectories;
final class DexPathList {
public DexPathList(ClassLoader definingContext, String dexPath,
String libraryPath, File optimizedDirectory) {
...
this.definingContext = definingContext;
ArrayList<IOException> suppressedExceptions = new ArrayList<IOException>();
// 记录所有的 dexFile 文件
this.dexElements = makePathElements(splitDexPath(dexPath), optimizedDirectory, suppressedExceptions);
// app 目录的 native 库
this.nativeLibraryDirectories = splitPaths(libraryPath, false);
// 系统目录的 native 库
this.systemNativeLibraryDirectories = splitPaths(System.getProperty("java.library.path"), true);
List<File> allNativeLibraryDirectories = new ArrayList<>(nativeLibraryDirectories);
allNativeLibraryDirectories.addAll(systemNativeLibraryDirectories);
// 记录所有的 native 动态库
this.nativeLibraryPathElements = makePathElements(allNativeLibraryDirectories, null, suppressedExceptions);
...
}
}
DexPathList初始化过程,主要功能是收集以下两个变量信息:
1、dexElements: 根据多路径的分隔符 :
将dexPath转换成File列表,记录所有的dexFile
2、nativeLibraryPathElements: 记录所有的 Native 动态库,包括app 目录的 native 库和系统目录的 native 库。
makeDexElements 方法用于 dexFile 转为 Element 数组
private static Element[] makeDexElements(List<File> files, File optimizedDirectory,
List<IOException> suppressedExceptions, ClassLoader loader) {
return makeDexElements(files, optimizedDirectory, suppressedExceptions, loader, false);
}
private static Element[] makeDexElements(List<File> files, File optimizedDirectory,
List<IOException> suppressedExceptions, ClassLoader loader, boolean isTrusted) {
Element[] elements = new Element[files.size()]; // 获取文件个数
int elementsPos = 0;
for (File file : files) {
if (file.isDirectory()) {
elements[elementsPos++] = new Element(file);
} else if (file.isFile()) {
String name = file.getName();
DexFile dex = null;
// 匹配以.dex为后缀的文件
if (name.endsWith(DEX_SUFFIX)) {
dex = loadDexFile(file, optimizedDirectory, loader, elements);
if (dex != null) {
elements[elementsPos++] = new Element(dex, null);
}
} else {
dex = loadDexFile(file, optimizedDirectory, loader, elements);
if (dex == null) {
elements[elementsPos++] = new Element(file);
} else {
elements[elementsPos++] = new Element(dex, file);
}
}
if (dex != null && isTrusted) {
dex.setTrusted();
}
} else {
System.logW("ClassLoader referenced unknown path: " + file);
}
}
if (elementsPos != elements.length) {
elements = Arrays.copyOf(elements, elementsPos);
}
return elements;
}
DexPathList.findClass 方法就是热修复基本原理的核心逻辑了
public Class findClass(String name, List<Throwable> suppressed) {
for (Element element : dexElements) {
DexFile dex = element.dexFile;
if (dex != null) {
// 找到目标类,则直接返回
Class clazz = dex.loadClassBinaryName(name, definingContext, suppressed);
if (clazz != null) {
return clazz;
}
}
}
return null;
}
- PathClassLoader: 主要用于系统和 app 的类加载器,其中 optimizedDirectory 为 null ,采用默认目录
/data/dalvik-cache/
- DexClassLoader: 可以从包含 classes.dex 的 jar 或者 apk 中,加载类的类加载器,可用于执行动态加载,但必须是app私有可写目录来缓存 odex 文件。能够加载系统没有安装的 apk 或者 jar 文件,因此很多插件化方案都是采用 DexClassLoader;
- BaseDexClassLoader: 比较基础的类加载器,PathClassLoader 和 DexClassLoader 都只是在构造函数上对其简单封装而已;
- BootClassLoader: 作为父类的类构造器。
热修复核心逻辑:在DexPathList.findClass() 过程,一个 Classloader 可以包含多个 dex 文件,每个 dex 文件被封装到一个 Element 对象,这些 Element 对象排列成有序的数组 dexElements 。当查找某个类时,会遍历所有的 dex 文件,如果找到则直接返回,不再继续遍历 dexElements。也就是说当两个类不同的 dex 中出现,会优先处理排在前面的 dex 文件,这便是热修复的核心精髓,将需要修复的类所打包的 dex 文件插入到 dexElements 前面。通过反射就可以很方便的添加我们修复后的 dex 到 DexPathList 中,这样错误的类就不会被加载了!
热修复代码实现
假设现有 Activity onCreate 内代码崩溃:
public class Test {
public static void hypothesisError(){
throw new UnsupportedOperationException("some error!");
}
}
...
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Test.hypothesisError();
}
}
HotFixApplication 作为自定义 Application,执行热修复
public class HotFixApplication extends Application {
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
// 执行热修复,插入补丁 dex
Hotfix.installPatch(this, new File("/sdcard/patch.dex"));
}
}
/sdcard/patch.dex
是提前准备好的 dex 文件,里面也只有 Test 类,但是去掉了 Exception。下面是生成 dex 文件的命令,当然也可以是用 jar 包生成:
C:\Android\SDK\build-tools\30.0.3\dx --dex --output=patch.dex cn/tim/dalvik_test/Test.class
Hotfix 实现的热修复流程:
package cn.tim.dalvik_test;
import android.app.Application;
import android.os.Build;
import android.util.Log;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
public class Hotfix {
private static final String TAG = "Hotfix";
public static void installPatch(Application application, File patch){
// 获取当前应用的 ClassLoader PathClassLoader
ClassLoader classLoader = application.getClassLoader();
Log.d(TAG, "installPatch: classLoader = " + classLoader);
List<File> files = new ArrayList<>();
if (patch.exists()) {
files.add(patch);
}
File dexOptDir = application.getCacheDir();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
try {
NewClassLoaderInjector.inject(application, classLoader, files);
} catch (Throwable throwable) {
throwable.printStackTrace();
}
} else {
try {
//23 6.0及以上
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// V23.install(classLoader, files, dexOptDir);
install(classLoader, files, dexOptDir);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
V19.install(classLoader, files, dexOptDir); //4.4以上
} else { // >= 14
V14.install(classLoader, files, dexOptDir);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
// V23
private static void install(ClassLoader loader, List<File> additionalClassPathEntities,
File optimizeDir) throws NoSuchFieldException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, IOException {
// 1、反射获取 DexPathList 属性对象 pathList
Field pathListField = ShareReflectUtil.findField(loader, "pathList");
Object dexPathList = pathListField.get(loader);
ArrayList<IOException> suppressedExceptions = new ArrayList<>();
// 2、反射修改 pathList 的 DexElements
Object[] patchElements = makePathElements(dexPathList, additionalClassPathEntities, optimizeDir, suppressedExceptions);
// 3、将原本的 dexElements 与 makePathElements生成的数组合并
ShareReflectUtil.expandFieldArray(dexPathList, "dexElements", patchElements);
if (suppressedExceptions.size() > 0) {
for (IOException e : suppressedExceptions) {
Log.w(TAG, "Exception in makePathElement", e);
throw e;
}
}
}
/**
* V23 dexFile 转为 Element数组
*/
private static Object[] makePathElements(Object dexPathList, List<File> files, File optimizeDir,
List<IOException> suppressedException)
throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
// android 6 7 8 9均存在 makePathElements 方法
Method makePathElementsM = ShareReflectUtil.findMethod(dexPathList, "makePathElements",
List.class, File.class, List.class);
return (Object[]) makePathElementsM.invoke(dexPathList, files, optimizeDir, suppressedException);
}
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;
}
}
}
private static Object[] makeDexElements(
Object dexPathList, ArrayList<File> files, File optimizedDirectory,
ArrayList<IOException> suppressedExceptions)
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
Method makeDexElements = ShareReflectUtil.findMethod(dexPathList, "makeDexElements",
ArrayList.class, File.class,
ArrayList.class);
return (Object[]) makeDexElements.invoke(dexPathList, files, optimizedDirectory,
suppressedExceptions);
}
}
/**
* 14, 15, 16, 17, 18.
*/
private static final class V14 {
private static void install(ClassLoader loader, List<File> additionalClassPathEntries,
File optimizedDirectory)
throws IllegalArgumentException, IllegalAccessException,
NoSuchFieldException, InvocationTargetException, NoSuchMethodException {
Field pathListField = ShareReflectUtil.findField(loader, "pathList");
Object dexPathList = pathListField.get(loader);
ShareReflectUtil.expandFieldArray(dexPathList, "dexElements",
makeDexElements(dexPathList,
new ArrayList<File>(additionalClassPathEntries), optimizedDirectory));
}
private static Object[] makeDexElements(
Object dexPathList, ArrayList<File> files, File optimizedDirectory)
throws IllegalAccessException, InvocationTargetException,
NoSuchMethodException {
Method makeDexElements =
ShareReflectUtil.findMethod(dexPathList, "makeDexElements", ArrayList.class,
File.class);
return (Object[]) makeDexElements.invoke(dexPathList, files, optimizedDirectory);
}
}
}
需要注意的是,Android 各个版本实现代码细微不一致,这是由于 Android 不同版本的虚拟机导致的,但是核心逻辑都是一致的。如果是在 Android N,需要自定义 ClassLoader 通过反射替换系统创建的 PathClassLoader,这块可以参考 Tinker 的逻辑实现。
反射工具类 ShareReflectUtil:
package cn.tim.dalvik_test;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
public class ShareReflectUtil {
/**
* 从 instance 到其父类 找 name 属性
*
* @param instance
* @param name
* @return
* @throws NoSuchFieldException
*/
public static Field findField(Object instance, String name) throws NoSuchFieldException {
for (Class<?> clazz = instance.getClass(); clazz != null; clazz = clazz.getSuperclass()) {
try {
//查找当前类的 属性(不包括父类)
Field field = clazz.getDeclaredField(name);
if (!field.isAccessible()) {
field.setAccessible(true);
}
return field;
} catch (NoSuchFieldException e) {
// ignore and search next
}
}
throw new NoSuchFieldException("Field " + name + " not found in " + instance.getClass());
}
/**
* 从 instance 到其父类 找 name 方法
*
* @param instance
* @param name
* @return
* @throws NoSuchFieldException
*/
public static Method findMethod(Object instance, String name, Class<?>... parameterTypes)
throws NoSuchMethodException {
for (Class<?> clazz = instance.getClass(); clazz != null; clazz = clazz.getSuperclass()) {
try {
Method method = clazz.getDeclaredMethod(name, parameterTypes);
if (!method.isAccessible()) {
method.setAccessible(true);
}
return method;
} catch (NoSuchMethodException e) {
// ignore and search next
}
}
throw new NoSuchMethodException("Method "
+ name
+ " with parameters "
+ Arrays.asList(parameterTypes)
+ " not found in " + instance.getClass());
}
/**
* @param instance
* @param fieldName
* @param patchElements 补丁的Element数组
* @throws NoSuchFieldException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public static void expandFieldArray(Object instance, String fieldName, Object[] patchElements)
throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
//拿到 classloader中的dexelements 数组
Field dexElementsField = findField(instance, fieldName);
//old Element[]
Object[] dexElements = (Object[]) dexElementsField.get(instance);
//合并后的数组
Object[] newElements = (Object[]) Array.newInstance(dexElements.getClass().getComponentType(),
dexElements.length + patchElements.length);
// 先拷贝新数组
System.arraycopy(patchElements, 0, newElements, 0, patchElements.length);
System.arraycopy(dexElements, 0, newElements, patchElements.length, dexElements.length);
//修改 classLoader中 pathList的 dexelements
dexElementsField.set(instance, newElements);
}
}
NewClassLoaderInjector.java
package cn.tim.dalvik_test;
import android.app.Application;
import android.content.Context;
import android.content.res.Resources;
import android.os.Build;
import java.io.File;
import java.lang.reflect.Field;
import java.util.List;
import dalvik.system.DexFile;
import dalvik.system.PathClassLoader;
public class NewClassLoaderInjector {
private static final class DispatchClassLoader extends ClassLoader {
private final String mApplicationClassName;
private final ClassLoader mOldClassLoader;
private ClassLoader mNewClassLoader;
private final ThreadLocal<Boolean> mCallFindClassOfLeafDirectly = new ThreadLocal<Boolean>() {
@Override
protected Boolean initialValue() {
return false;
}
};
DispatchClassLoader(String applicationClassName, ClassLoader oldClassLoader) {
super(ClassLoader.getSystemClassLoader());
mApplicationClassName = applicationClassName;
mOldClassLoader = oldClassLoader;
}
void setNewClassLoader(ClassLoader classLoader) {
mNewClassLoader = classLoader;
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
System.out.println("find:" + name);
if (mCallFindClassOfLeafDirectly.get()) {
return null;
}
// 1、Application类不需要修复,使用原本的类加载器获得
if (name.equals(mApplicationClassName)) {
return findClass(mOldClassLoader, name);
}
// 2、加载热修复框架的类 因为不需要修复,就用原本的类加载器获得
if (name.startsWith("com.enjoy.patch.")) {
return findClass(mOldClassLoader, name);
}
try {
return findClass(mNewClassLoader, name);
} catch (ClassNotFoundException ignored) {
return findClass(mOldClassLoader, name);
}
}
private Class<?> findClass(ClassLoader classLoader, String name) throws ClassNotFoundException {
try {
//双亲委托,所以可能会stackoverflow死循环,防止这个情况
mCallFindClassOfLeafDirectly.set(true);
return classLoader.loadClass(name);
} finally {
mCallFindClassOfLeafDirectly.set(false);
}
}
}
public static ClassLoader inject(Application app, ClassLoader oldClassLoader,List<File> patchs) throws Throwable {
// 分发加载任务的加载器,作为我们自己的加载器的父加载器
DispatchClassLoader dispatchClassLoader
= new DispatchClassLoader(app.getClass().getName(), oldClassLoader);
//创建我们自己的加载器
ClassLoader newClassLoader
= createNewClassLoader(app, oldClassLoader, dispatchClassLoader,patchs);
dispatchClassLoader.setNewClassLoader(newClassLoader);
doInject(app, newClassLoader);
return newClassLoader;
}
private static ClassLoader createNewClassLoader(Context context, ClassLoader oldClassLoader,
ClassLoader dispatchClassLoader,List<File> patchs) throws Throwable {
//得到pathList
Field pathListField = ShareReflectUtil.findField(oldClassLoader, "pathList");
Object oldPathList = pathListField.get(oldClassLoader);
//dexElements
Field dexElementsField = ShareReflectUtil.findField(oldPathList, "dexElements");
Object[] oldDexElements = (Object[]) dexElementsField.get(oldPathList);
//从Element上得到 dexFile
Field dexFileField = ShareReflectUtil.findField(oldDexElements[0], "dexFile");
// 获得原始的dexPath用于构造classloader
StringBuilder dexPathBuilder = new StringBuilder();
String packageName = context.getPackageName();
boolean isFirstItem = true;
for (File patch : patchs) {
if (isFirstItem) {
isFirstItem = false;
} else {
dexPathBuilder.append(File.pathSeparator);
}
dexPathBuilder.append(patch.getAbsolutePath());
}
for (Object oldDexElement : oldDexElements) {
String dexPath = null;
DexFile dexFile = (DexFile) dexFileField.get(oldDexElement);
if (dexFile != null) {
dexPath = dexFile.getName();
}
if (dexPath == null || dexPath.isEmpty()) {
continue;
}
if (!dexPath.contains("/" + packageName)) {
continue;
}
if (isFirstItem) {
isFirstItem = false;
} else {
dexPathBuilder.append(File.pathSeparator);
}
dexPathBuilder.append(dexPath);
}
final String combinedDexPath = dexPathBuilder.toString();
// app的native库(so) 文件目录 用于构造classloader
Field nativeLibraryDirectoriesField = ShareReflectUtil.findField(oldPathList, "nativeLibraryDirectories");
List<File> oldNativeLibraryDirectories = (List<File>) nativeLibraryDirectoriesField.get(oldPathList);
StringBuilder libraryPathBuilder = new StringBuilder();
isFirstItem = true;
for (File libDir : oldNativeLibraryDirectories) {
if (libDir == null) {
continue;
}
if (isFirstItem) {
isFirstItem = false;
} else {
libraryPathBuilder.append(File.pathSeparator);
}
libraryPathBuilder.append(libDir.getAbsolutePath());
}
String combinedLibraryPath = libraryPathBuilder.toString();
//创建自己的类加载器
ClassLoader result = new PathClassLoader(combinedDexPath, combinedLibraryPath, dispatchClassLoader);
ShareReflectUtil.findField(oldPathList, "definingContext").set(oldPathList, result);
ShareReflectUtil.findField(result, "parent").set(result, dispatchClassLoader);
return result;
}
private static void doInject(Application app, ClassLoader classLoader) throws Throwable {
Thread.currentThread().setContextClassLoader(classLoader);
Context baseContext = (Context) ShareReflectUtil.findField(app, "mBase").get(app);
Object basePackageInfo = ShareReflectUtil.findField(baseContext, "mPackageInfo").get(baseContext);
ShareReflectUtil.findField(basePackageInfo, "mClassLoader").set(basePackageInfo, classLoader);
if (Build.VERSION.SDK_INT < 27) {
Resources res = app.getResources();
try {
ShareReflectUtil.findField(res, "mClassLoader").set(res, classLoader);
final Object drawableInflater = ShareReflectUtil.findField(res, "mDrawableInflater").get(res);
if (drawableInflater != null) {
ShareReflectUtil.findField(drawableInflater, "mClassLoader").set(drawableInflater, classLoader);
}
} catch (Throwable ignored) {
// Ignored.
}
}
}
}
可以看到已经修复了崩溃!
最近简单热修复的基本原理就已经结束了,如果要实现真正的热修复框架,那么就需要Gradle开发:字节码插桩 + 自动生成Dex 的方式以及其他的考虑点了。