Android熱修復(fù)技術(shù)——QQ空間補(bǔ)丁方案解析(3)

如前文所述,要想實(shí)現(xiàn)熱更新的目的,就必須在dex分包完成之后操作字節(jié)碼文件。比較常用的字節(jié)碼操作工具有ASM和javaassist。相比之下ASM提供一系列字節(jié)碼指令,效率更高但是要求使用者對(duì)字節(jié)碼操作有一定了解。而javaassist雖然效率差一些但是使用門檻較低,本文選擇使用javaassist。關(guān)于javaassist可以參考Java 編程的動(dòng)態(tài)性, 第四部分: 用 Javassist 進(jìn)行類轉(zhuǎn)換

正常App開(kāi)發(fā)過(guò)程中,編譯,打包過(guò)程都是Android Studio自動(dòng)完成。如無(wú)特殊需求無(wú)需人為干預(yù),但是要實(shí)現(xiàn)插樁就必須在Android Studio的自動(dòng)化打包流程中加入插樁的過(guò)程。

1. Gradle,Task,Transform,Plugin

Android Studio采用Gradle作為構(gòu)建工具,所有有必要了解一下Gradle構(gòu)建的基本概念和流程。如果不熟悉可以參考一下下列文章:

Gradle的構(gòu)建工程實(shí)質(zhì)上是通過(guò)一系列的Task完成的,所以在構(gòu)建apk的過(guò)程中就存在一個(gè)打包dex的任務(wù)。Gradle 1.5以上版本提供了一個(gè)新的API:Transform,官方文檔對(duì)于Transform的描述是:

The goal of this API is to simplify injecting custom class manipulations without having to deal with tasks, and to offer more flexibility on what is manipulated. The internal code processing (jacoco, progard, multi-dex) have all moved to this new mechanism already in 1.5.0-beta1.

    1. The Dex class is gone. You cannot access it anymore through the variant API (the getter is still there for now but will throw an exception)
    1. Transform can only be registered globally which applies them to all the variants. We'll improve this shortly.
    1. There's no way to control ordering of the transforms.

Transform任務(wù)一經(jīng)注冊(cè)就會(huì)被插入到任務(wù)執(zhí)行隊(duì)列中,并且其恰好在dex打包task之前。所以要想實(shí)現(xiàn)插樁就必須創(chuàng)建一個(gè)Transform類的Task。

1.1 Task

Gradle的執(zhí)行腳本就是由一系列的Task完成的。Task有一個(gè)重要的概念:input的output。每一個(gè)task需要有輸入input,然后對(duì)input進(jìn)行處理完成后在輸出output。

1.2 Plugin

Gradle的另外一個(gè)重要概念就是Plugin。整個(gè)Gradle的構(gòu)建體系都是有一個(gè)一個(gè)的plugin構(gòu)成的,實(shí)際Gradle只是一個(gè)框架,提供了基本task和指定標(biāo)準(zhǔn)。而具體每一個(gè)task的執(zhí)行邏輯都定義在一個(gè)個(gè)的plugin中。詳細(xì)的概念可以參考:Writing Custom Plugins
在Android開(kāi)發(fā)中我們經(jīng)常使用到的plugin有:"com.android.application","com.android.library","java"等等。
每一個(gè)Plugin包含了一系列的task,所以執(zhí)行g(shù)radle腳本的過(guò)程也就是執(zhí)行目標(biāo)腳本所apply的plugin所包含的task。

1.3 創(chuàng)建一個(gè)包含Transform任務(wù)的Plugin

    1. 新建一個(gè)module,選擇library module,module名字必須叫BuildSrc
    1. 刪除module下的所有文件,除了build.gradle,清空build.gradle中的內(nèi)容
    1. 然后新建以下目錄 src-main-groovy
    1. 修改build.gradle如下,同步
apply plugin: 'groovy'

repositories {
    jcenter()
}

dependencies {
    compile gradleApi()
    compile 'com.android.tools.build:gradle:1.5.0'
    compile 'org.javassist:javassist:3.20.0-GA'//javaassist依賴
}
    1. 像普通module一樣新建package和類,不過(guò)這里的類是以groovy結(jié)尾,新建類的時(shí)候選擇file,并且以.groovy作為后綴
    1. 自定義Plugin:
package com.hotpatch.plugin

import com.android.build.api.transform.*
import com.android.build.gradle.internal.pipeline.TransformManager
import org.apache.commons.codec.digest.DigestUtils
import org.apache.commons.io.FileUtils
import org.gradle.api.Project

public class PreDexTransform extends Transform {

    Project project;

    public PreDexTransform(Project project1) {
        this.project = project1;

        def libPath = project.project(":hack").buildDir.absolutePath.concat("/intermediates/classes/debug")
        println libPath
        Inject.appendClassPath(libPath)
        Inject.appendClassPath("/Users/liyazhou/Library/Android/sdk/platforms/android-24/android.jar")
    }
    @Override
    String getName() {
        return "preDex"
    }

    @Override
    Set<QualifiedContent.ContentType> getInputTypes() {
        return TransformManager.CONTENT_CLASS
    }

    @Override
    Set<QualifiedContent.Scope> getScopes() {
        return TransformManager.SCOPE_FULL_PROJECT
    }

    @Override
    boolean isIncremental() {
        return false
    }

    @Override
    void transform(Context context, Collection<TransformInput> inputs, Collection<TransformInput> referencedInputs, TransformOutputProvider outputProvider, boolean isIncremental) throws IOException, TransformException, InterruptedException {

        // 遍歷transfrom的inputs
        // inputs有兩種類型,一種是目錄,一種是jar,需要分別遍歷。
        inputs.each {TransformInput input ->
            input.directoryInputs.each {DirectoryInput directoryInput->

                //TODO 注入代碼
                Inject.injectDir(directoryInput.file.absolutePath)

                def dest = outputProvider.getContentLocation(directoryInput.name,
                        directoryInput.contentTypes, directoryInput.scopes, Format.DIRECTORY)
                // 將input的目錄復(fù)制到output指定目錄
                FileUtils.copyDirectory(directoryInput.file, dest)
            }

            input.jarInputs.each {JarInput jarInput->


                //TODO 注入代碼
                String jarPath = jarInput.file.absolutePath;
                String projectName = project.rootProject.name;
                if(jarPath.endsWith("classes.jar")
                        && jarPath.contains("exploded-aar/"+projectName)
                        // hotpatch module是用來(lái)加載dex,無(wú)需注入代碼
                        && !jarPath.contains("exploded-aar/"+projectName+"/hotpatch")) {
                    Inject.injectJar(jarPath)
                }

                // 重命名輸出文件(同目錄copyFile會(huì)沖突)
                def jarName = jarInput.name
                def md5Name = DigestUtils.md5Hex(jarInput.file.getAbsolutePath())
                if(jarName.endsWith(".jar")) {
                    jarName = jarName.substring(0,jarName.length()-4)
                }
                def dest = outputProvider.getContentLocation(jarName+md5Name, jarInput.contentTypes, jarInput.scopes, Format.JAR)
                FileUtils.copyFile(jarInput.file, dest)
            }
        }
    }
}
  • 8.Inject.groovy, JarZipUtil.groovy
package com.hotpatch.plugin

import javassist.ClassPool
import javassist.CtClass
import org.apache.commons.io.FileUtils

public class Inject {

    private static ClassPool pool = ClassPool.getDefault()

    /**
     * 添加classPath到ClassPool
     * @param libPath
     */
    public static void appendClassPath(String libPath) {
        pool.appendClassPath(libPath)
    }

    /**
     * 遍歷該目錄下的所有class,對(duì)所有class進(jìn)行代碼注入。
     * 其中以下class是不需要注入代碼的:
     * --- 1. R文件相關(guān)
     * --- 2. 配置文件相關(guān)(BuildConfig)
     * --- 3. Application
     * @param path 目錄的路徑
     */
    public static void injectDir(String path) {
        pool.appendClassPath(path)
        File dir = new File(path)
        if(dir.isDirectory()) {
            dir.eachFileRecurse { File file ->

                String filePath = file.absolutePath
                if (filePath.endsWith(".class")
                        && !filePath.contains('R$')
                        && !filePath.contains('R.class')
                        && !filePath.contains("BuildConfig.class")
                        // 這里是application的名字,可自行配置
                        && !filePath.contains("HotPatchApplication.class")) {
                    // 應(yīng)用程序包名,可自行配置
                    int index = filePath.indexOf("com/hotpatch/plugin")
                    if (index != -1) {
                        int end = filePath.length() - 6 // .class = 6
                        String className = filePath.substring(index, end).replace('\\', '.').replace('/','.')
                        injectClass(className, path)
                    }
                }
            }
        }
    }

    /**
     * 這里需要將jar包先解壓,注入代碼后再重新生成jar包
     * @path jar包的絕對(duì)路徑
     */
    public static void injectJar(String path) {
        if (path.endsWith(".jar")) {
            File jarFile = new File(path)


            // jar包解壓后的保存路徑
            String jarZipDir = jarFile.getParent() +"/"+jarFile.getName().replace('.jar','')

            // 解壓jar包, 返回jar包中所有class的完整類名的集合(帶.class后綴)
            List classNameList = JarZipUtil.unzipJar(path, jarZipDir)

            // 刪除原來(lái)的jar包
            jarFile.delete()

            // 注入代碼
            pool.appendClassPath(jarZipDir)
            for(String className : classNameList) {
                if (className.endsWith(".class")
                        && !className.contains('R$')
                        && !className.contains('R.class')
                        && !className.contains("BuildConfig.class")) {
                    className = className.substring(0, className.length()-6)
                    injectClass(className, jarZipDir)
                }
            }

            // 從新打包jar
            JarZipUtil.zipJar(jarZipDir, path)

            // 刪除目錄
            FileUtils.deleteDirectory(new File(jarZipDir))
        }
    }

    private static void injectClass(String className, String path) {
        CtClass c = pool.getCtClass(className)
        if (c.isFrozen()) {
            c.defrost()
        }
        def constructor = c.getConstructors()[0];
        constructor.insertAfter("System.out.println(com.hotpatch.hack.AntilazyLoad.class);")
        c.writeFile(path)
    }

}

package com.hotpatch.plugin

import java.util.jar.JarEntry
import java.util.jar.JarFile
import java.util.jar.JarOutputStream
import java.util.zip.ZipEntry

/**
 * Created by hp on 2016/4/13.
 */
public class JarZipUtil {

    /**
     * 將該jar包解壓到指定目錄
     * @param jarPath jar包的絕對(duì)路徑
     * @param destDirPath jar包解壓后的保存路徑
     * @return 返回該jar包中包含的所有class的完整類名類名集合,其中一條數(shù)據(jù)如:com.aitski.hotpatch.Xxxx.class
     */
    public static List unzipJar(String jarPath, String destDirPath) {

        List list = new ArrayList()
        if (jarPath.endsWith('.jar')) {

            JarFile jarFile = new JarFile(jarPath)
            Enumeration<JarEntry> jarEntrys = jarFile.entries()
            while (jarEntrys.hasMoreElements()) {
                JarEntry jarEntry = jarEntrys.nextElement()
                if (jarEntry.directory) {
                    continue
                }
                String entryName = jarEntry.getName()
                if (entryName.endsWith('.class')) {
                    String className = entryName.replace('\\', '.').replace('/', '.')
                    list.add(className)
                }
                String outFileName = destDirPath + "/" + entryName
                File outFile = new File(outFileName)
                outFile.getParentFile().mkdirs()
                InputStream inputStream = jarFile.getInputStream(jarEntry)
                FileOutputStream fileOutputStream = new FileOutputStream(outFile)
                fileOutputStream << inputStream
                fileOutputStream.close()
                inputStream.close()
            }
            jarFile.close()
        }
        return list
    }

    /**
     * 重新打包jar
     * @param packagePath 將這個(gè)目錄下的所有文件打包成jar
     * @param destPath 打包好的jar包的絕對(duì)路徑
     */
    public static void zipJar(String packagePath, String destPath) {

        File file = new File(packagePath)
        JarOutputStream outputStream = new JarOutputStream(new FileOutputStream(destPath))
        file.eachFileRecurse { File f ->
            String entryName = f.getAbsolutePath().substring(packagePath.length() + 1)
            outputStream.putNextEntry(new ZipEntry(entryName))
            if(!f.directory) {
                InputStream inputStream = new FileInputStream(f)
                outputStream << inputStream
                inputStream.close()
            }
        }
        outputStream.close()
    }
}

    1. 在app module下build.gradle文件中添加新插件:apply plugin: com.hotpatch.plugin.Register

2. 創(chuàng)建hack.jar

創(chuàng)建一個(gè)單獨(dú)的module,命名為com.hotpatch.plugin.AntilazyLoad:

package com.hotpatch.plugin
public class AntilazyLoad {
}

使用上一篇博客介紹的方法打包hack.jar。然后將hack.jar復(fù)制到app module下的assets目錄中。另外注意:app module不能依賴hack module。之所以要?jiǎng)?chuàng)建一個(gè)hack module,同時(shí)人為地在dex打包過(guò)程中插入對(duì)其他hack.jar中類的依賴,就是要讓apk文件在安裝的時(shí)候不被打上CLASS_ISPREVERIFIED標(biāo)記。
另外由于hack.jar位于assets中,所以必須要在加載patch_dex之前加載hack.jar。另外由于加載其他路徑的dex文件都是在Application.onCreate()方法中執(zhí)行的,此時(shí)還沒(méi)有加載hack.jar,所以這就是為什么在上一章節(jié)插樁的時(shí)候不能在Application中插樁的原因。

插樁的過(guò)程介紹完了,整個(gè)熱修復(fù)的過(guò)程也就差不多了,讀者可以參考完整的代碼進(jìn)行demo試用:Hotpatch Demo

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容