热修复系列一:原理篇

比较 Tinker QZone AndFix Robust
类替换
So替换
资源替换
全平台替换
即时生效
性能损耗 ⬇️ ⬆️ ⬇️ ⬇️

Class 加载过程

image.png

PathClassLoader只是个包装类,不会加载文件。

在Android中, Dalvik能执行的文件之一是dex文件。我们编写的.java文件会被编译为class文件然后打包成dex文件。Dalvik就是将会将所有的dex文件以Element的方式存放在DexPathList中。
当加载一个class文件时,Dalvik会从DexPathList中去遍历每一个dex寻找其中的class文件,找到对应的立即返回,如果所有的dex文件中均不含这个class文件,就会返回ClassNotFoundException。

源码

/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package dalvik.system;

/**
 * Provides a simple {@link ClassLoader} implementation that operates on a list
 * of files and directories in the local file system, but does not attempt to
 * load classes from the network. Android uses this class for its system class
 * loader and for its application class loader(s).
 */
public class PathClassLoader extends BaseDexClassLoader {
    /**
     * Creates a {@code PathClassLoader} that operates on a given list of files
     * and directories. This method is equivalent to calling
     * {@link #PathClassLoader(String, String, ClassLoader)} with a
     * {@code null} value for the second argument (see description there).
     *
     * @param dexPath the list of jar/apk files containing classes and
     * resources, delimited by {@code File.pathSeparator}, which
     * defaults to {@code ":"} on Android
     * @param parent the parent class loader
     */
    public PathClassLoader(String dexPath, ClassLoader parent) {
        super(dexPath, null, null, parent);
    }

    /**
     * Creates a {@code PathClassLoader} that operates on two given
     * lists of files and directories. The entries of the first list
     * should be one of the following:
     *
     * <ul>
     * <li>JAR/ZIP/APK files, possibly containing a "classes.dex" file as
     * well as arbitrary resources.
     * <li>Raw ".dex" files (not inside a zip file).
     * </ul>
     *
     * The entries of the second list should be directories containing
     * native library files.
     *
     * @param dexPath the list of jar/apk files containing classes and
     * resources, delimited by {@code File.pathSeparator}, which
     * defaults to {@code ":"} on Android
     * @param librarySearchPath the list of directories containing native
     * libraries, delimited by {@code File.pathSeparator}; may be
     * {@code null}
     * @param parent the parent class loader
     */
    public PathClassLoader(String dexPath, String librarySearchPath, ClassLoader parent) {
        super(dexPath, null, librarySearchPath, parent);
    }
}


BaseDexClassLoader.java



public class BaseDexClassLoader extends ClassLoader {
    //内部包装所有的Dex文件
    private final DexPathList pathList;

    /**
     * Constructs an instance.
     *
     * @param dexPath the list of jar/apk files containing classes and
     * resources, delimited by {@code File.pathSeparator}, which
     * defaults to {@code ":"} on Android
     * @param optimizedDirectory directory where optimized dex files
     * should be written; may be {@code null}
     * @param librarySearchPath the list of directories containing native
     * libraries, delimited by {@code File.pathSeparator}; may be
     * {@code null}
     * @param parent the parent class loader
     */
    public BaseDexClassLoader(String dexPath, File optimizedDirectory,
            String librarySearchPath, ClassLoader parent) {
        super(parent);
        this.pathList = new DexPathList(this, dexPath, librarySearchPath, optimizedDirectory);
    }

    //加载class文件
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        List<Throwable> suppressedExceptions = new ArrayList<Throwable>();
        //调用pathList的findClass
        Class c = pathList.findClass(name, suppressedExceptions);
        if (c == null) {
            ClassNotFoundException cnfe = new ClassNotFoundException("Didn't find class \"" + name + "\" on path: " + pathList);
            for (Throwable t : suppressedExceptions) {
                cnfe.addSuppressed(t);
            }
            throw cnfe;
        }
        return c;
    }
        .......省略其他代码...........
}


DexPathList


final class DexPathList {
    private static final String DEX_SUFFIX = ".dex";
    private static final String zipSeparator = "!/";

    /** class definition context */
    private final ClassLoader definingContext;

    /** 存放所有的dex文件
     * List of dex/resource (class path) elements.
     * Should be called pathElements, but the Facebook app uses reflection
     * to modify 'dexElements' (http://b/7726934).
     */
    private Element[] dexElements;

  

    /**
    Element用来包装dex文件
     * Finds the named class in one of the dex files pointed at by
     * this instance. This will find the one in the earliest listed
     * path element. If the class is found but has not yet been
     * defined, then this method will define it in the defining
     * context that this instance was constructed with.
     *
     * @param name of class to find
     * @param suppressed exceptions encountered whilst finding the class
     * @return the named class or {@code null} if the class is not
     * found in any of the dex files
     */
    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;
                }
            }
        }
        if (dexElementsSuppressedExceptions != null) {
            suppressed.addAll(Arrays.asList(dexElementsSuppressedExceptions));
        }
        return null;
    }
 

        .....省略其他代码.....
}


修复方案

到这里我们已经知道了,加载class的流程是通过BaseDexClassLoader调用findClass(String name),进而调用DexPathListfindClass(String name),而这个方法又是通过遍历包装了dex文件对应的包装类ElementdexElements来完成的。

那么我们只需要将修复好的class文件编译打包成dex文件,然后通过反射变更系统的dexElements,将这个fixBug.dex解析提取出dexElements然后跟系统的dexElements进行合并,并且放到第一位置。那么在加载class文件时,findClass在第一位置找到了class文件后,不再理会后面的class文件。这样即完成了修复。

出问题了

我们假定出问题的文件如下:

package com.example.myapplication;

import android.widget.Toast;

public class TestBug {
    public void test(MainActivity mainActivity) {
        Toast.makeText(mainActivity, "This is bug file", Toast.LENGTH_LONG).show();
    }
}


而正确的文件如下


package com.example.myapplication;

import android.widget.Toast;

public class TestBug {
    public void test(MainActivity mainActivity) {
        Toast.makeText(mainActivity, "This is  file", Toast.LENGTH_LONG).show();
    }
}

生成dex文件

进入到修复的class文件目录下,不要进入到包名目录下(com里面是包名)

dx --dex --output [你要输出的文件] [要编译的文件或者目录]

class文件位置

dex文件copy到 data/user/package name/app_odex

修复后的文件打包的dex,反编译后确认无误。


image.png

将fixbug.dex文件复制到手机的SD卡目录下。

热修复核心代码以及注解

package com.example.myapplication;


import android.content.Context;
import android.os.Environment;
import android.widget.Toast;
import dalvik.system.DexClassLoader;
import dalvik.system.PathClassLoader;

import java.io.*;
import java.lang.reflect.Array;
import java.lang.reflect.Field;

public class DexUtils {


    /**
     * 将dex包复制到/data/user/包名之下
     * @param context
     */
    public static void copyFixDex2Data(Context context){
        File odex = context.getDir("odex", Context.MODE_PRIVATE);
        String filePath = new File(odex, "fixbug.dex").getAbsolutePath();
        File fixBugDexFile = new File(filePath);
        if (fixBugDexFile.exists()) {
            fixBugDexFile.delete();
        }
        InputStream is = null;
        FileOutputStream os = null;
        try {
            is = new FileInputStream(new File(Environment.getExternalStorageDirectory(), "fixbug.dex"));
            os = new FileOutputStream(filePath);
            int len = 0;
            byte[] buffer = new byte[1024];
            while ((len = is.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
            File f = new File(filePath);
            if (f.exists()) {
                Toast.makeText(context, "dex overwrite", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void loadDex(Context context) {
        File fileDir = context.getDir("odex", Context.MODE_PRIVATE);
        //优化后的缓存路径
        String optimizedDirectory = fileDir.getAbsolutePath() + File.separator + "opt_dex";
        File[] listFiles = fileDir.listFiles();
        for (File file : listFiles) {
            if (file.getName().startsWith("classes") || file.getName().endsWith(".dex")) {
                String dexPath = file.getAbsolutePath();
                //dex中的lib路径
                String librarySearchPath = null;


                //APP中真正运行的加载dex的loader,我们的目的是吧dexClassLoader中的Element"合并"到pathClassLoader的Element[]中


                //BaseDexClassLoader->pathList(DexPathList)->dexElements(Element[])

                try {
                    //-------step1-----------反射到系统的Element[]---------------------
                    //拿到系统的ClassLoader
                    Class baseDexClassLoader = Class.forName("dalvik.system.BaseDexClassLoader");
                    Field pathListField = baseDexClassLoader.getDeclaredField("pathList");
                    pathListField.setAccessible(true);
                    //APP中真正运行的加载dex的loader
                    PathClassLoader pathClassLoader = (PathClassLoader) context.getClassLoader();
                    Object pathListObj = pathListField.get(pathClassLoader);

                    Class<?> pathListObjClass = pathListObj.getClass();
                    Field dexElementsField = pathListObjClass.getDeclaredField("dexElements");
                    dexElementsField.setAccessible(true);
                    //private Element[] dexElements;
                    Object systemElements = dexElementsField.get(pathListObj);


                    //--------step2----------反射到自己的Element[]---------------------
                    Class myBaseDexClassLoader = Class.forName("dalvik.system.BaseDexClassLoader");
                    Field myPathListField = myBaseDexClassLoader.getDeclaredField("pathList");
                    myPathListField.setAccessible(true);
                    //我们的dex包中的
                    DexClassLoader
                            dexClassLoader = new DexClassLoader(dexPath, optimizedDirectory, librarySearchPath, context.getClassLoader());
                    Object myPathListObj = myPathListField.get(dexClassLoader);

                    Class<?> myPathListObjClass = myPathListObj.getClass();
                    Field myDexElementsField = myPathListObjClass.getDeclaredField("dexElements");
                    myDexElementsField.setAccessible(true);
                    //private Element[] dexElements;
                    Object myElements = myDexElementsField.get(myPathListObj);

                    //----------step3-------------自己的Element合并到System的Element中-------------------------------
                    //Element的类型反射拿到
                    Class elementType = systemElements.getClass().getComponentType();
                    int sysDexLength = Array.getLength(systemElements);
                    int myDexLength = Array.getLength(myElements);
                    int newElementsAryLength = myDexLength + sysDexLength;

                    Object newElements = Array.newInstance(elementType, newElementsAryLength);

                    //-----------核心----将fixDex放到最前面----------
                    for (int i = 0; i < newElementsAryLength; i++) {
                        if (i < myDexLength) {
                            Array.set(newElements, i, Array.get(myElements, i));
                        } else {
                            Array.set(newElements, i, Array.get(systemElements, i - myDexLength));
                        }
                    }

                    Field elements = pathListObj.getClass().getDeclaredField("dexElements");
                    elements.setAccessible(true);
                    elements.set(pathListObj, newElements);//合并完毕!!!!!!!

                    System.out.println("fix finish");

                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (Exception e){
                    e.printStackTrace();
                }

            }
        }

    }
}


BaseApplication


package com.example.myapplication;

import android.app.Application;
import android.content.Context;
import android.support.multidex.MultiDex;

public class BaseApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    protected void attachBaseContext(Context base) {
        MultiDex.install(this);
        
        DexUtils.copyFixDex2Data(this)
        DexUtils.loadDex(base);
        super.attachBaseContext(base);

    }

}

36tz7-ckdwq.gif

代码https://github.com/kaina404/hotfix

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,324评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,303评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,192评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,555评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,569评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,566评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,927评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,583评论 0 257
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,827评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,590评论 2 320
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,669评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,365评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,941评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,928评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,159评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,880评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,399评论 2 342