Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

深入AndFix熱修復(二):apkpatch補丁生成工具的源碼全解

編輯:關於 Android 程式設計

前面我們知道了,要生成.patch補丁文件,需要借助apkpatch這個工具。本章我們就來看看它內部的實現原理。apkpatch是一個並未開源的jar包,但借助JD-GUI或procyon反編譯,我們依然能讀到它的源碼(以1.0.3版本為例)。

在動手之前,有幾個「坑」必須先講清楚:

  • 工具只提取了classes.dex,因此原生並不支持multidex。如果開啟了multidex,且待修復的類不在同一個dex中,補丁就不會生效。這與作者在issue中宣稱支持multidex並不一致,不過我們可以借助JavaAssist修改這個jar包來補上這一能力。
  • AndFix不支援新增成員變量,但支援在新方法內部新增局部變量,也不支援修改成員變量。
  • 在對比方法時,會比對兩個dex中同時存在的方法:實現不同則記錄為「修改過的方法」,方法名不同則記錄為「新增的方法」——也就是說AndFix支援新增方法,這一點已被測試證實。

一、入口:找到Main.class

位於com.euler.patch包下,一切從Main()方法開始。

public static void main(String[] args) {
    CommandLineParser parser = new PosixParser();
    CommandLine commandLine = null;
    option();
    try {
        commandLine = parser.parse(allOptions, args);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        usage(commandLine);
        return;
    }
    //第一部分:校驗必填參數
    if ((!commandLine.hasOption('k')) && (!commandLine.hasOption("keystore"))) { usage(commandLine); return; }
    if ((!commandLine.hasOption('p')) && (!commandLine.hasOption("kpassword"))) { usage(commandLine); return; }
    if ((!commandLine.hasOption('a')) && (!commandLine.hasOption("alias"))) { usage(commandLine); return; }
    if ((!commandLine.hasOption('e')) && (!commandLine.hasOption("epassword"))) { usage(commandLine); return; }
    File out = null;
    if ((!commandLine.hasOption('o')) && (!commandLine.hasOption("out"))) out = new File("");
    else out = new File(commandLine.getOptionValue('o'));
    //第二部分:讀取簽名相關參數
    String keystore = commandLine.getOptionValue('k');
    String password = commandLine.getOptionValue('p');
    String alias = commandLine.getOptionValue('a');
    String entry = commandLine.getOptionValue('e');
    String name = "main";
    if ((commandLine.hasOption('n')) || (commandLine.hasOption("name"))) {
        name = commandLine.getOptionValue('n');
    }
    if ((commandLine.hasOption('m')) || (commandLine.hasOption("merge"))) {
        //合併多個補丁的分支
        String[] merges = commandLine.getOptionValues('m');
        File[] files = new File[merges.length];
        for (int i = 0; i < merges.length; i++) {
            files[i] = new File(merges[i]);
        }
        MergePatch mergePatch = new MergePatch(files, name, out, keystore, password, alias, entry);
        mergePatch.doMerge();
    } else {
        //常規打補丁分支
        if ((!commandLine.hasOption('f')) && (!commandLine.hasOption("from"))) { usage(commandLine); return; }
        if ((!commandLine.hasOption('t')) && (!commandLine.hasOption("to"))) { usage(commandLine); return; }
        File from = new File(commandLine.getOptionValue("f"));
        File to = new File(commandLine.getOptionValue('t'));
        if ((!commandLine.hasOption('n')) && (!commandLine.hasOption("name"))) {
            name = from.getName().split("\\.")[0];
        }
        //第三部分:構建ApkPatch並執行
        ApkPatch apkPatch = new ApkPatch(from, to, name, out, keystore, password, alias, entry);
        apkPatch.doPatch();
    }
}

這段代碼可以切成幾塊來看:第一部分檢查命令行必填參數,缺參數就打印用法提示;第二部分讀取正式打包時用到的keystore、password、alias、entry等參數;第三部分把這些參數交給ApkPatch構造函數初始化,最後調用doPatch()開工。

二、ApkPatch核心邏輯

2.1 構造函數

public ApkPatch(File from, File to, String name, File out, String keystore, String password, String alias, String entry) {
    super(name, out, keystore, password, alias, entry);
    this.from = from;
    this.to = to;
}

它調用了父類Build的構造函數,做的事很簡單——給變量賦值。若out不存在,父類會自動創建這個輸出目錄。

protected static final String SUFFIX = ".apatch";
protected String name;
private String keystore;
private String password;
private String alias;
private String entry;
protected File out;

public Build(String name, File out, String keystore, String password, String alias, String entry) {
    this.name = name;
    this.out = out;
    this.keystore = keystore;
    this.password = password;
    this.alias = alias;
    this.entry = entry;
    if (!out.exists()) out.mkdirs();
    else if (!out.isDirectory()) throw new RuntimeException("output path must be directory.");
}

2.2 doPatch方法

一句話概括就是兩步:先對比兩個apk拿到差異,再把結果打包成apatch文件。

public void doPatch() {
    try {
        final File smaliDir = new File(this.out, "smali");
        if (!smaliDir.exists()) smaliDir.mkdir();
        final File dexFile = new File(this.out, "diff.dex");
        final File outFile = new File(this.out, "diff.apatch");
        //第一步:對比兩個apk,差異寫入DiffInfo
        final DiffInfo info = new DexDiffer().diff(this.from, this.to);
        //第二步:把差異寫成smali,再打包成dex
        this.classes = buildCode(smaliDir, dexFile, info);
        //第三步:把dex寫入jar並簽名,生成diff.apatch
        this.build(outFile, dexFile);
        //第四步:重命名收尾
        this.release(this.out, dexFile, outFile);
    } catch (Exception e2) {
        e2.printStackTrace();
    }
}

2.2.1 第一步:對比並記錄差異(DexDiffer.diff)

public DiffInfo diff(final File newFile, final File oldFile) throws IOException {
    final DexBackedDexFile newDexFile = DexFileFactory.loadDexFile(newFile, 19, true);
    final DexBackedDexFile oldDexFile = DexFileFactory.loadDexFile(oldFile, 19, true);
    final DiffInfo info = DiffInfo.getInstance();
    boolean contains = false;
    for (final DexBackedClassDef newClazz : newDexFile.getClasses()) {//遍歷新apk所有類
        final Set<? extends DexBackedClassDef> oldclasses = oldDexFile.getClasses();
        for (final DexBackedClassDef oldClazz : oldclasses) {//遍歷舊apk所有類
            if (newClazz.equals(oldClazz)) {//同名類,記錄修改
                this.compareField(newClazz, oldClazz, info);
                this.compareMethod(newClazz, oldClazz, info);
                contains = true;
                break;
            }
        }
        if (!contains) {//否則記錄為新增類
            info.addAddedClasses(newClazz);
        }
    }
    return info;
}

其中提取dex的地方在DexFileFactory類裡。可以看到它只取出了classes.dex,這正是原生工具不支持multidex的根源。

public static DexBackedDexFile loadDexFile(File dexFile, int api, boolean experimental) throws IOException {
    return loadDexFile(dexFile, "classes.dex", new Opcodes(api, experimental));
}

對比變量的compareField——再次印證了AndFix不支持新增或修改成員變量:

public void compareField(DexBackedField object, Iterable<? extends DexBackedField> olds, DiffInfo info) {
    for (DexBackedField reference : olds) {
        if (reference.equals(object)) {
            if ((reference.getInitialValue() == null) && (object.getInitialValue() != null)) { info.addModifiedFields(object); return; }
            if ((reference.getInitialValue() != null) && (object.getInitialValue() == null)) { info.addModifiedFields(object); return; }
            if ((reference.getInitialValue() == null) && (object.getInitialValue() == null)) { return; }
            if (reference.getInitialValue().compareTo(object.getInitialValue()) != 0) { info.addModifiedFields(object); return; }
            return;
        }
    }
    info.addAddedFields(object);
}

對比方法的compareMethod——同名不同實現記錄為修改,名字不同記錄為新增:

public void compareMethod(DexBackedMethod object, Iterable<? extends DexBackedMethod> olds, DiffInfo info) {
    for (DexBackedMethod reference : olds) {
        if (reference.equals(object)) {
            if ((reference.getImplementation() == null) && (object.getImplementation() != null)) { info.addModifiedMethods(object); return; }
            if ((reference.getImplementation() != null) && (object.getImplementation() == null)) { info.addModifiedMethods(object); return; }
            if ((reference.getImplementation() == null) && (object.getImplementation() == null)) { return; }
            if (!reference.getImplementation().equals(object.getImplementation())) { info.addModifiedMethods(object); return; }
            return;
        }
    }
    info.addAddedMethods(object);
}

2.2.2 第二步:寫入smali並打包成dex(buildCode)

把上一步的diff信息寫成smali文件,並生成diff.dex。smali文件以_CF.smali結尾,並在修改處用自定義註解MethodReplace標注,供替換階段查找待修復的變量或方法。

private static Set buildCode(final File smaliDir, final File dexFile, final DiffInfo info) throws IOException, RecognitionException, FileNotFoundException {
    final ClassFileNameHandler outFileNameHandler = new ClassFileNameHandler(smaliDir, ".smali");
    final ClassFileNameHandler inFileNameHandler = new ClassFileNameHandler(smaliDir, ".smali");
    final DexBuilder dexBuilder = DexBuilder.makeDexBuilder();
    for (final DexBackedClassDef classDef : list) {
        final String className = classDef.getType();
        baksmali.disassembleClass(classDef, outFileNameHandler, options);
        final File smaliFile = inFileNameHandler.getUniqueFilenameForClass(TypeGenUtil.newType(className));
        classes.add(TypeGenUtil.newType(className).substring(1, TypeGenUtil.newType(className).length() - 1).replace('/', '.'));
        SmaliMod.assembleSmaliFile(smaliFile, dexBuilder, true, true);
    }
    dexBuilder.writeTo(new FileDataStore(dexFile));
    return classes;
}

2.2.3 第三步:打包簽名生成diff.apatch(build)

先從keystore取到應用簽名,實例化PatchBuilder並調用writeMeta(getMeta()),把Manifest寫入META-INF/PATCH.MF,再通過sealPatch把dex與簽名信息封入其中。

protected void build(File outFile, File dexFile) throws KeyStoreException, FileNotFoundException, IOException, NoSuchAlgorithmException, CertificateException, UnrecoverableEntryException {
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    KeyStore.PrivateKeyEntry privateKeyEntry = null;
    InputStream is = new FileInputStream(this.keystore);
    keyStore.load(is, this.password.toCharArray());
    privateKeyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(this.alias, new KeyStore.PasswordProtection(this.entry.toCharArray()));
    PatchBuilder builder = new PatchBuilder(outFile, dexFile, privateKeyEntry, System.out);
    builder.writeMeta(getMeta());
    builder.sealPatch();
}

getMeta()負責組裝寫入清單的內容:

protected Manifest getMeta() {
    Manifest manifest = new Manifest();
    Attributes main = manifest.getMainAttributes();
    main.putValue("Manifest-Version", "1.0");
    main.putValue("Created-By", "1.0 (ApkPatch)");
    main.putValue("Created-Time", new Date(System.currentTimeMillis()).toGMTString());
    main.putValue("From-File", this.from.getName());
    main.putValue("To-File", this.to.getName());
    main.putValue("Patch-Name", this.name);
    main.putValue("Patch-Classes", Formater.dotStringList(this.classes));
    return manifest;
}

2.2.4 第四步:dex轉.apatch(release)

最後一步,對dexFile做MD5,再把outFile重命名為帶MD5的.apatch文件。看到「.apatch」有沒有很激動?我們的補丁包就是這樣誕生的。

protected void release(File outDir, File dexFile, File outFile) throws NoSuchAlgorithmException, FileNotFoundException, IOException {
    MessageDigest messageDigest = MessageDigest.getInstance("md5");
    FileInputStream fileInputStream = new FileInputStream(dexFile);
    byte[] buffer = new byte[8192];
    int len = 0;
    while ((len = fileInputStream.read(buffer)) > 0) {
        messageDigest.update(buffer, 0, len);
    }
    String md5 = HexUtil.hex(messageDigest.digest());
    fileInputStream.close();
    outFile.renameTo(new File(outDir, this.name + "-" + md5 + ".apatch"));
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved