Alibaba-AndFix Bug熱修復框架原理及原始碼解析

我是喬同學發表於2015-11-13

這裡寫圖片描述
小憩之後,繼續為你解讀AndFix熱修復框架,呵呵。

上一篇Alibaba-AndFix Bug熱修復框架的使用已經介紹了AndFix的使用,這篇主要介紹AndFix原理以及原始碼解析。

AndFix原理

AndFix的原理就是方法的替換,把有bug的方法替換成補丁檔案中的方法。
這裡寫圖片描述

注:在Native層使用指標替換的方式替換bug方法,已達到修復bug的目的。

使用AndFix修復熱修復的整體流程:

這裡寫圖片描述

方法替換過程:

這裡寫圖片描述

原始碼解析

解析原始碼從使用的方法一一解析。

在自定義Application中初始化PatchManger:

PatchManager mPatchManager = new PatchManager();

直接例項化了一個PatchManger例項物件,接下看PatchManager類原始碼:

public PatchManager(Context context) {
        mContext = context;
        mAndFixManager = new AndFixManager(mContext);//初始化AndFixManager
        mPatchDir = new File(mContext.getFilesDir(), DIR);//初始化存放patch補丁檔案的資料夾
        mPatchs = new ConcurrentSkipListSet<Patch>();//初始化存在Patch類的集合,此類適合大併發
        mLoaders = new ConcurrentHashMap<String, ClassLoader>();//初始化存放類對應的類載入器集合
}

然後看AndFixManager的初始化:

public AndFixManager(Context context) {
        mContext = context;
        mSupport = Compat.isSupport();//判斷Android機型是否適支援AndFix
        if (mSupport) {
            mSecurityChecker = new SecurityChecker(mContext);//初始化簽名判斷類
            mOptDir = new File(mContext.getFilesDir(), DIR);//初始化patch檔案存放的資料夾
            if (!mOptDir.exists() && !mOptDir.mkdirs()) {// make directory fail
                mSupport = false;
                Log.e(TAG, "opt dir create error.");
            } else if (!mOptDir.isDirectory()) {// not directory
                mOptDir.delete();//如果不是檔案目錄就刪除
                mSupport = false;
            }
        }
}
public static synchronized boolean isSupport() {//此處加了同步鎖機制
        if (isChecked)
            return isSupport;

        isChecked = true;
        // not support alibaba's YunOs
        boolean isYunOs = isYunOS();//判斷系統是否是YunOs系統,YunOs系統是阿里巴巴的系統
        boolean setup  =AndFix.setup();//判斷是Dalvik還是Art虛擬機器,來註冊Native方法
        boolean isSupportSDKVersion = isSupportSDKVersion();//根據sdk版本判斷是否支援
        if (!isYunOs && setup && isSupportSDKVersion) {//根據上面三個boolean值判斷是否支援
            isSupport = true;
        }

        if (inBlackList()) {
            isSupport = false;
        }
        return isSupport;
}
private static boolean isSupportSDKVersion() {
        if (android.os.Build.VERSION.SDK_INT >= 8
                && android.os.Build.VERSION.SDK_INT <= 23) {
            return true;
        }
        return false;
}
public static boolean setup() {
        try {
            final String vmVersion = System.getProperty("java.vm.version");
            boolean isArt = vmVersion != null && vmVersion.startsWith("2");
            int apilevel = Build.VERSION.SDK_INT;
            return setup(isArt, apilevel);
        } catch (Exception e) {
            Log.e(TAG, "setup", e);
            return false;
        }
}
//簽名機制的初始化過程
public SecurityChecker(Context context) {
        mContext = context;
        init(mContext);
}
//主要是獲取當前應用的簽名及其他資訊,為了判斷與patch檔案的簽名是否一致
private void init(Context context) {
        try {
            PackageManager pm = context.getPackageManager();
            String packageName = context.getPackageName();

            PackageInfo packageInfo = pm.getPackageInfo(packageName,
                    PackageManager.GET_SIGNATURES);
            CertificateFactory certFactory = CertificateFactory
                    .getInstance("X.509");
            ByteArrayInputStream stream = new ByteArrayInputStream(
                    packageInfo.signatures[0].toByteArray());
            X509Certificate cert = (X509Certificate) certFactory
                    .generateCertificate(stream);
            mDebuggable = cert.getSubjectX500Principal().equals(DEBUG_DN);
            mPublicKey = cert.getPublicKey();
        } catch (NameNotFoundException e) {
            Log.e(TAG, "init", e);
        } catch (CertificateException e) {
            Log.e(TAG, "init", e);
    }
}

接下,看一下版本的初始化:

mPatchManager.init("version")

init方法原始碼:

public void init(String appVersion) {
        if (!mPatchDir.exists() && !mPatchDir.mkdirs()) {// make directory fail
            Log.e(TAG, "patch dir create error.");
            return;
        } else if (!mPatchDir.isDirectory()) {// not directory
            mPatchDir.delete();
            return;
        }
        SharedPreferences sp = mContext.getSharedPreferences(SP_NAME,
                Context.MODE_PRIVATE);//儲存關於patch檔案的資訊
        //根據你傳入的版本號和之前的對比,做不同的處理
        String ver = sp.getString(SP_VERSION, null);
        if (ver == null || !ver.equalsIgnoreCase(appVersion)) {
            cleanPatch();//刪除本地patch檔案
            sp.edit().putString(SP_VERSION, appVersion).commit();//並把傳入的版本號儲存
        } else {
            initPatchs();//初始化patch列表,把本地的patch檔案載入到記憶體
    }
}

private void cleanPatch() {
        File[] files = mPatchDir.listFiles();
        for (File file : files) {
            mAndFixManager.removeOptFile(file);//刪除所有的本地快取patch檔案
            if (!FileUtil.deleteFile(file)) {
                Log.e(TAG, file.getName() + " delete error.");
        }
    }
}
private void initPatchs() {
        File[] files = mPatchDir.listFiles();
        for (File file : files) {
            addPatch(file);//載入Patch檔案
        }
}
private Patch addPatch(File file) {
        Patch patch = null;
        if (file.getName().endsWith(SUFFIX)) {
            try {
                patch = new Patch(file);//例項化Patch物件
                mPatchs.add(patch);//把patch例項儲存到記憶體的集合中,在PatchManager例項化集合
            } catch (IOException e) {
                Log.e(TAG, "addPatch", e);
            }
        }
        return patch;
}

Patch檔案的載入

public Patch(File file) throws IOException {
        mFile = file;
        init();
}

@SuppressWarnings("deprecation")
private void init() throws IOException {
        JarFile jarFile = null;
        InputStream inputStream = null;
        try {
            jarFile = new JarFile(mFile);//使用JarFile讀取Patch檔案
            JarEntry entry = jarFile.getJarEntry(ENTRY_NAME);//獲取META-INF/PATCH.MF檔案
            inputStream = jarFile.getInputStream(entry);
            Manifest manifest = new Manifest(inputStream);
            Attributes main = manifest.getMainAttributes();
            mName = main.getValue(PATCH_NAME);//獲取PATCH.MF屬性Patch-Name
            mTime = new Date(main.getValue(CREATED_TIME));//獲取PATCH.MF屬性Created-Time

            mClassesMap = new HashMap<String, List<String>>();
            Attributes.Name attrName;
            String name;
            List<String> strings;
            for (Iterator<?> it = main.keySet().iterator(); it.hasNext();) {
                attrName = (Attributes.Name) it.next();
                name = attrName.toString();
                //判斷name的字尾是否是-Classes,並把name對應的值加入到集合中,對應的值就是class類名的列表
                if (name.endsWith(CLASSES)) {
                    strings = Arrays.asList(main.getValue(attrName).split(","));
                    if (name.equalsIgnoreCase(PATCH_CLASSES)) {
                        mClassesMap.put(mName, strings);
                    } else {
                        mClassesMap.put(
                                name.trim().substring(0, name.length() - 8),// remove
                                                                            // "-Classes"
                                strings);
                    }
                }
            }
        } finally {
            if (jarFile != null) {
                jarFile.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        }

}

loadPatch方法原始碼

mPatchManager.loadPatch();

loadPatch原始碼:

public void loadPatch() {
        mLoaders.put("*", mContext.getClassLoader());// wildcard
        Set<String> patchNames;
        List<String> classes;
        for (Patch patch : mPatchs) {
            patchNames = patch.getPatchNames();
            for (String patchName : patchNames) {
                classes = patch.getClasses(patchName);//獲取patch對用的class類的集合List
                mAndFixManager.fix(patch.getFile(), mContext.getClassLoader(),
                        classes);//修復bug方法
            }
    }
}

fix bug

public synchronized void fix(File file, ClassLoader classLoader,
            List<String> classes) {
        if (!mSupport) {
            return;
        }
        //判斷patch檔案的簽名
        if (!mSecurityChecker.verifyApk(file)) {// security check fail
            return;
        }

        try {
            File optfile = new File(mOptDir, file.getName());
            boolean saveFingerprint = true;
            if (optfile.exists()) {
                // need to verify fingerprint when the optimize file exist,
                // prevent someone attack on jailbreak device with
                // Vulnerability-Parasyte.
                // btw:exaggerated android Vulnerability-Parasyte
                // http://secauo.com/Exaggerated-Android-Vulnerability-Parasyte.html
                if (mSecurityChecker.verifyOpt(optfile)) {
                    saveFingerprint = false;
                } else if (!optfile.delete()) {
                    return;
                }
            }
            //載入patch檔案中的dex
            final DexFile dexFile = DexFile.loadDex(file.getAbsolutePath(),
                    optfile.getAbsolutePath(), Context.MODE_PRIVATE);

            if (saveFingerprint) {
                mSecurityChecker.saveOptSig(optfile);
            }

            ClassLoader patchClassLoader = new ClassLoader(classLoader) {
                @Override
                protected Class<?> findClass(String className)
                        throws ClassNotFoundException {//重寫ClasLoader的findClass方法
                    Class<?> clazz = dexFile.loadClass(className, this);
                    if (clazz == null
                            && className.startsWith("com.alipay.euler.andfix")) {
                        return Class.forName(className);// annotation’s class
                                                        // not found
                    }
                    if (clazz == null) {
                        throw new ClassNotFoundException(className);
                    }
                    return clazz;
                }
            };
            Enumeration<String> entrys = dexFile.entries();
            Class<?> clazz = null;
            while (entrys.hasMoreElements()) {
                String entry = entrys.nextElement();
                if (classes != null && !classes.contains(entry)) {
                    continue;// skip, not need fix
                }
                clazz = dexFile.loadClass(entry, patchClassLoader);//獲取有bug的類檔案
                if (clazz != null) {
                    fixClass(clazz, classLoader);// next code
                }
            }
        } catch (IOException e) {
            Log.e(TAG, "pacth", e);
    }
}
private void fixClass(Class<?> clazz, ClassLoader classLoader) {
        Method[] methods = clazz.getDeclaredMethods();
        MethodReplace methodReplace;
        String clz;
        String meth;
        for (Method method : methods) {
            //獲取此方法的註解,因為有bug的方法在生成的patch的類中的方法都是有註解的,下面會給圖進行展示
            methodReplace = method.getAnnotation(MethodReplace.class);
            if (methodReplace == null)
                continue;
            clz = methodReplace.clazz();//獲取註解中clazz的值
            meth = methodReplace.method();//獲取註解中method的值
            if (!isEmpty(clz) && !isEmpty(meth)) {
                replaceMethod(classLoader, clz, meth, method);//next code
            }
    }
}
private void replaceMethod(ClassLoader classLoader, String clz,
            String meth, Method method) {
        try {
            String key = clz + "@" + classLoader.toString();
            Class<?> clazz = mFixedClass.get(key);//判斷此類是否被fix
            if (clazz == null) {// class not load
                Class<?> clzz = classLoader.loadClass(clz);
                // initialize target class
                clazz = AndFix.initTargetClass(clzz);//初始化class
            }
            if (clazz != null) {// initialize class OK
                mFixedClass.put(key, clazz);
                Method src = clazz.getDeclaredMethod(meth,
                        method.getParameterTypes());//根據反射獲取到有bug的類的方法(有bug的apk)
                AndFix.addReplaceMethod(src, method);//src是有bug的方法,method是補丁方法
            }
        } catch (Exception e) {
            Log.e(TAG, "replaceMethod", e);
    }
}
public static void addReplaceMethod(Method src, Method dest) {
        try {
            replaceMethod(src, dest);//呼叫了native方法,next code
            initFields(dest.getDeclaringClass());
        } catch (Throwable e) {
            Log.e(TAG, "addReplaceMethod", e);
        }
}
private static native void replaceMethod(Method dest, Method src);

由於Android4.4後才用的Art虛擬機器,之前的系統都是Dalvik虛擬機器,因此Natice層寫了2個方法,對不同的系統做不同的處理方式。

extern void dalvik_replaceMethod(JNIEnv* env, jobject src, jobject dest);//Dalvik
extern void art_replaceMethod(JNIEnv* env, jobject src, jobject dest);//Art

Dalvik replaceMethod的實現:

extern void __attribute__ ((visibility ("hidden"))) dalvik_replaceMethod(
        JNIEnv* env, jobject src, jobject dest) {
    jobject clazz = env->CallObjectMethod(dest, jClassMethod);
    ClassObject* clz = (ClassObject*) dvmDecodeIndirectRef_fnPtr(
            dvmThreadSelf_fnPtr(), clazz);
    clz->status = CLASS_INITIALIZED;

    Method* meth = (Method*) env->FromReflectedMethod(src);
    Method* target = (Method*) env->FromReflectedMethod(dest);
    LOGD("dalvikMethod: %s", meth->name);

    meth->jniArgInfo = 0x80000000;
    meth->accessFlags |= ACC_NATIVE;//把Method的屬性設定成Native方法

    int argsSize = dvmComputeMethodArgsSize_fnPtr(meth);
    if (!dvmIsStaticMethod(meth))
        argsSize++;
    meth->registersSize = meth->insSize = argsSize;
    meth->insns = (void*) target;

    meth->nativeFunc = dalvik_dispatcher;//把方法的實現替換成native方法
}

Art replaceMethod的實現:

//不同的art系統版本不同處理也不同
extern void __attribute__ ((visibility ("hidden"))) art_replaceMethod(
        JNIEnv* env, jobject src, jobject dest) {
    if (apilevel > 22) {
        replace_6_0(env, src, dest);
    } else if (apilevel > 21) {
        replace_5_1(env, src, dest);
    } else {
        replace_5_0(env, src, dest);
    }
}
//以5.0為例:
void replace_5_0(JNIEnv* env, jobject src, jobject dest) {
    art::mirror::ArtMethod* smeth =
            (art::mirror::ArtMethod*) env->FromReflectedMethod(src);

    art::mirror::ArtMethod* dmeth =
            (art::mirror::ArtMethod*) env->FromReflectedMethod(dest);

    dmeth->declaring_class_->class_loader_ =
            smeth->declaring_class_->class_loader_; //for plugin classloader
    dmeth->declaring_class_->clinit_thread_id_ =
            smeth->declaring_class_->clinit_thread_id_;
    dmeth->declaring_class_->status_ = (void *)((int)smeth->declaring_class_->status_-1);
    //把一些引數的指標給補丁方法
    smeth->declaring_class_ = dmeth->declaring_class_;
    smeth->access_flags_ = dmeth->access_flags_;
    smeth->frame_size_in_bytes_ = dmeth->frame_size_in_bytes_;
    smeth->dex_cache_initialized_static_storage_ =
            dmeth->dex_cache_initialized_static_storage_;
    smeth->dex_cache_resolved_types_ = dmeth->dex_cache_resolved_types_;
    smeth->dex_cache_resolved_methods_ = dmeth->dex_cache_resolved_methods_;
    smeth->vmap_table_ = dmeth->vmap_table_;
    smeth->core_spill_mask_ = dmeth->core_spill_mask_;
    smeth->fp_spill_mask_ = dmeth->fp_spill_mask_;
    smeth->mapping_table_ = dmeth->mapping_table_;
    smeth->code_item_offset_ = dmeth->code_item_offset_;
    smeth->entry_point_from_compiled_code_ =
            dmeth->entry_point_from_compiled_code_;

    smeth->entry_point_from_interpreter_ = dmeth->entry_point_from_interpreter_;
    smeth->native_method_ = dmeth->native_method_;//把補丁方法替換掉
    smeth->method_index_ = dmeth->method_index_;
    smeth->method_dex_index_ = dmeth->method_dex_index_;

    LOGD("replace_5_0: %d , %d", smeth->entry_point_from_compiled_code_,
            dmeth->entry_point_from_compiled_code_);

}

新增Patch

mPatchManager.addPatch(path)

原始碼:

public void addPatch(String path) throws IOException {
        File src = new File(path);
        File dest = new File(mPatchDir, src.getName());
        if (!src.exists()) {
            throw new FileNotFoundException(path);
        }
        if (dest.exists()) {
            Log.d(TAG, "patch [" + path + "] has be loaded.");
            return;
        }
        FileUtil.copyFile(src, dest);// copy to patch's directory
        Patch patch = addPatch(dest);//同loadPatch中的addPatch一樣的操作
        if (patch != null) {
            loadPatch(patch);//載入pach,同上loadPatch
        }
    }

移除Patch

mPatchManager.removeAllPatch();

原始碼:

public void removeAllPatch() {
        cleanPatch();//刪除本地快取的patch檔案列表
        SharedPreferences sp = mContext.getSharedPreferences(SP_NAME,
                Context.MODE_PRIVATE);
        sp.edit().clear().commit();//把關於patch的資料進行清空
    }

到此原始碼就解析結束。

反編譯Patch dex檔案程式碼

patch檔案中.dex檔案反編譯後,看到原始碼效果如下:
這裡寫圖片描述
紅框標註的部分,就是補丁方法。方法的註解部分寫了clazz和method的值,對應著apk包中的類名和方法名稱。

相關文章