編輯:Android 資訊
上一篇文章講了 Tinker 的接入與源碼輪廓。把 Tinker 的代碼按職責切開,其實是三塊:應用內對補丁的合併與加載(上一篇已講)、dex 的 diff / patch 算法(本篇)、以及 gradle 插件(另有專文)。
Tinker 最大的亮點之一,就是自研了一套 dex 差分算法。要讀懂它,前提是先對 dex 的內部格式有基本認識,否則面對一臉的 offset 和 section 只會一頭霧水。所以本文的節奏是:先看懂 dex 檔長什麼樣,再用一個最小案例推演 diff 的思路,最後進源碼。
反編譯 apk 時都見過一到多個 *.dex,我們寫的代碼就在裡面。jar 本質上是 class 檔的壓縮包,解壓就能看到一個個 class;dex 卻無法用解壓的方式還原出 class,說明它有自己的一套格式:
dex 對 Java 類檔重新排列,把所有類檔中的常量池分解、消除冗餘,重新組合成一個共享常量池,讓相同字串與常量在 dex 中只出現一次,從而顯著縮小檔案體積。
要分析一個檔的組成,最好的辦法是自己造一個最小的樣本。
public class Hello{ public static void main(String[] args){ System.out.println("hello dex!"); } }
javac -source 1.7 -target 1.7 Hello.java
dx --dex --output=Hello.dex Hello.class
dx 位於
Android-sdk/build-tools/版本號/dx,命令無法識別時記得加入 PATH 或直接使用絕對路徑。
先看一張整體結構示意圖:

光靠一張圖遠遠不夠——後續要研究 diff,我們需要精確到「哪個位元組是什麼含義」。純靠記憶不現實,好在有工具:010 Editor(官網)。安裝後打開 dex,它會引導你裝上 dex 的解析模板,於是十六進位內容與各區塊結構就能左右對照著看,點擊下方任一區塊即可定位到對應的位元組。

想更深入的話,可以配合《DEX 文件格式分析》《Android 逆向之旅—解析編譯之後的 Dex 文件格式》一起看。本文只做最小必要的格式說明。

從欄位構成就能猜出 header 的職責:既承載校驗資訊,也記錄整個檔各區塊的分布(off 均為偏移量)。這樣虛擬機只需讀 header,就能掌握全局佈局,並順帶驗證格式是否合法、檔是否被改篡。
magic 證明這是 dex;checksum 與 signature 負責完整性校驗file_size 為檔大小,head_size 為頭部大小endian_tag 固定 0x12345678,表示採用小端序其餘幾乎都是成對出現的 size 與 off。舉例:string_ids_off = 112 表示從偏移 112 開始是 string_ids 區;string_ids_size = 14 表示該區有 14 個 string_id_item。其餘同理,配合 010 Editor 逐項對照即可。

開頭是 map_item_list 的數量,隨後是每個條目的描述:

每個 map_list_item 由四部分組成:一個枚舉型別、一個兩位元組的保留欄位、一個 size(該型別的個數)、一個 offset(該型別的起始偏移)。以本例說明:
TYPE_HEADER_ITEM,size = 1,offset = 0;TYPE_STRING_ID_ITEM,size = 14,offset = 112(header 長度正好 112,緊接其後)。由此可見,map_list 的價值在於把整個 dex 切成若干已知區塊(本例 13 個),並告訴你每個區塊從哪裡開始、裡面裝了多少個什麼結構。拿到起點,再依型別按對應的數據結構去讀,就完整了。
手上有一份 old dex 和一份 new dex,目標是生成一個 patch,使得 patch + old dex → new dex。
把 dex 粗略看成三部分:header、各區塊、map_list。
那麼單個區塊怎麼辦?假設有個字串區:
old dex:Hello、World、zhy
new dex:Android、World、zhy
差異就是刪掉 Hello、加入 Android,patch 中針對該區只需記錄「del Hello, add Android」(落地時自然是二進位形式)。
而應用端可以直接讀出 old dex,因此它知道該區原本是 Hello、World、zhy,再疊上 patch 的三條指令,就能推算出 Android、World、zhy。
這就是 Tinker 差分思路的骨架:不傳全量,只傳「哪些索引被刪、哪些索引新增、哪些索引被替換」,其餘部分沿用舊檔。真實實現比這個模型複雜,但大方向一致。
讀這類大型代碼庫有個技巧:先從輸入輸出反推入口。diff 的簽名很明確——輸入 old dex 與 new dex,輸出 patch 檔,那麼必然存在一個類承擔這件事,它就是 DexPatchGenerator(位於 tinker-build 的 tinker-patch-lib 下):
@Test public void testDiff() throws IOException { File oldFile = new File("Hello.dex"); File newFile = new File("Hello-World.dex"); File patchFile = new File("patch.dex"); DexPatchGenerator dexPatchGenerator = new DexPatchGenerator(oldFile, newFile); dexPatchGenerator.executeAndSaveTo(patchFile); }
三行代碼就是完整的 diff 調用。別在 gradle 插件那邊糾結,直接從這裡切進去。
public DexPatchGenerator(File oldDexFile, File newDexFile) throws IOException { this(new Dex(oldDexFile), new Dex(newDexFile)); }
public Dex(File file) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(file)); loadFrom(in, (int) file.length()); } private void loadFrom(InputStream in, int initSize) throws IOException { byte[] rawData = FileUtils.readStream(in, initSize); this.data = ByteBuffer.wrap(rawData); this.data.order(ByteOrder.LITTLE_ENDIAN); this.tableOfContents.readFrom(this); }
整個檔被讀成 byte[](這一步相當吃記憶體),由 ByteBuffer 包裝並設為小端,然後交給 TableOfContents.readFrom:
#TableOfContents public void readFrom(Dex dex) throws IOException { readHeader(dex.openSection(header)); // special case, since mapList.byteCount is available only after // computeSizesFromOffsets() was invoked, so here we can't use // dex.openSection(mapList) to get dex section. readMap(dex.openSection(mapList.off)); computeSizesFromOffsets(); }
readHeader 就是按 header 的欄位順序逐個讀值賦給成員,並順帶做合法性校驗(magic、header_size、endian_tag、mapList.off 不能為 0 等):
private void readHeader(Dex.Section headerIn) throws UnsupportedEncodingException { byte[] magic = headerIn.readByteArray(8); int apiTarget = DexFormat.magicToApi(magic); if (apiTarget != DexFormat.API_NO_EXTENDED_OPCODES) { throw new DexException("Unexpected magic: " + Arrays.toString(magic)); } checksum = headerIn.readInt(); signature = headerIn.readByteArray(20); fileSize = headerIn.readInt(); int headerSize = headerIn.readInt(); if (headerSize != SizeOf.HEADER_ITEM) { throw new DexException("Unexpected header: 0x" + Integer.toHexString(headerSize)); } int endianTag = headerIn.readInt(); if (endianTag != DexFormat.ENDIAN_TAG) { throw new DexException("Unexpected endian tag: 0x" + Integer.toHexString(endianTag)); } linkSize = headerIn.readInt(); linkOff = headerIn.readInt(); mapList.off = headerIn.readInt(); if (mapList.off == 0) { throw new DexException("Cannot merge dex files that do not contain a map"); } stringIds.size = headerIn.readInt(); stringIds.off = headerIn.readInt(); typeIds.size = headerIn.readInt(); typeIds.off = headerIn.readInt(); protoIds.size = headerIn.readInt(); protoIds.off = headerIn.readInt(); fieldIds.size = headerIn.readInt(); fieldIds.off = headerIn.readInt(); methodIds.size = headerIn.readInt(); methodIds.off = headerIn.readInt(); classDefs.size = headerIn.readInt(); classDefs.off = headerIn.readInt(); dataSize = headerIn.readInt(); dataOff = headerIn.readInt(); }
readMap 則從 header 已知的 mapList.off 處起讀:先取條目數,再逐條讀 type / unused / size / offset,對應到 TableContents.Section 對象:
private void readMap(Dex.Section in) throws IOException { int mapSize = in.readInt(); Section previous = null; for (int i = 0; i < mapSize; i++) { short type = in.readShort(); in.readShort(); // unused Section section = getSection(type); int size = in.readInt(); int offset = in.readInt(); section.size = size; section.off = offset; previous = section; } header.off = 0; Arrays.sort(sections); // Skip header section, since its offset must be zero. for (int i = 1; i < sections.length; ++i) { if (sections[i].off == Section.UNDEF_OFFSET) { sections[i].off = sections[i - 1].off; } } }
最後 computeSizesFromOffsets() 根據相鄰 offset 反推每個 section 的 byteCount。至此 dex 檔已完整映射為內存中的 Dex 對象。
public DexPatchGenerator(Dex oldDex, Dex newDex) { this.oldDex = oldDex; this.newDex = newDex; SparseIndexMap oldToNewIndexMap = new SparseIndexMap(); SparseIndexMap oldToPatchedIndexMap = new SparseIndexMap(); SparseIndexMap newToPatchedIndexMap = new SparseIndexMap(); SparseIndexMap selfIndexMapForSkip = new SparseIndexMap(); additionalRemovingClassPatternSet = new HashSet<>(); this.stringDataSectionDiffAlg = new StringDataSectionDiffAlgorithm( oldDex, newDex, oldToNewIndexMap, oldToPatchedIndexMap, newToPatchedIndexMap, selfIndexMapForSkip ); this.typeIdSectionDiffAlg = ... this.protoIdSectionDiffAlg = ... this.fieldIdSectionDiffAlg = ... this.methodIdSectionDiffAlg = ... this.classDefSectionDiffAlg = ... this.typeListSectionDiffAlg = ... this.annotationSetRefListSectionDiffAlg = ... this.annotationSetSectionDiffAlg = ... this.classDataSectionDiffAlg = ... this.codeSectionDiffAlg = ... this.debugInfoSectionDiffAlg = ... this.annotationSectionDiffAlg = ... this.encodedArraySectionDiffAlg = ... this.annotationsDirectorySectionDiffAlg = ... }
構造階段一口氣初始化了 15 個算法,每個對應一個區塊,目標都一樣:算出「刪了什麼、加了什麼、換了什麼」。
public void executeAndSaveTo(OutputStream out) throws IOException { int patchedheaderSize = SizeOf.HEADER_ITEM; int patchedStringIdsSize = newDex.getTableOfContents().stringIds.size * SizeOf.STRING_ID_ITEM; int patchedTypeIdsSize = newDex.getTableOfContents().typeIds.size * SizeOf.TYPE_ID_ITEM; int patchedProtoIdsSize = newDex.getTableOfContents().protoIds.size * SizeOf.PROTO_ID_ITEM; int patchedFieldIdsSize = newDex.getTableOfContents().fieldIds.size * SizeOf.MEMBER_ID_ITEM; int patchedMethodIdsSize = newDex.getTableOfContents().methodIds.size * SizeOf.MEMBER_ID_ITEM; int patchedClassDefsSize = newDex.getTableOfContents().classDefs.size * SizeOf.CLASS_DEF_ITEM; int patchedIdSectionSize = patchedStringIdsSize + patchedTypeIdsSize + patchedProtoIdsSize + patchedFieldIdsSize + patchedMethodIdsSize + patchedClassDefsSize; this.patchedHeaderOffset = 0; this.patchedStringIdsOffset = patchedHeaderOffset + patchedheaderSize; this.stringDataSectionDiffAlg.execute(); this.patchedStringDataItemsOffset = patchedheaderSize + patchedIdSectionSize; this.stringDataSectionDiffAlg.simulatePatchOperation(this.patchedStringDataItemsOffset); // 省略了其余14個算法的一堆代碼 this.patchedDexSize = this.patchedMapListOffset + patchedMapListSize; writeResultToStream(out); }
15 個區塊的處理是串行且有順序依賴的(後面的 offset 取決於前面算出的 size),所以這段代碼很長。下面只挑 stringData 這條算法看透,其餘同構。
public void execute() { this.patchOperationList.clear(); // 1. 拿到oldDex和newDex的itemList this.adjustedOldIndexedItemsWithOrigOrder = collectSectionItems(this.oldDex, true); this.oldItemCount = this.adjustedOldIndexedItemsWithOrigOrder.length; AbstractMap.SimpleEntry<Integer, T>[] adjustedOldIndexedItems = new AbstractMap.SimpleEntry[this.oldItemCount]; System.arraycopy(this.adjustedOldIndexedItemsWithOrigOrder, 0, adjustedOldIndexedItems, 0, this.oldItemCount); Arrays.sort(adjustedOldIndexedItems, this.comparatorForItemDiff); AbstractMap.SimpleEntry<Integer, T>[] adjustedNewIndexedItems = collectSectionItems(this.newDex, false); this.newItemCount = adjustedNewIndexedItems.length; Arrays.sort(adjustedNewIndexedItems, this.comparatorForItemDiff); int oldCursor = 0; int newCursor = 0; // 2.遍歷,對比,收集patch操作 while (oldCursor < this.oldItemCount || newCursor < this.newItemCount) { if (oldCursor >= this.oldItemCount) { // 剩下的全是newItem,做ADD } else if (newCursor >= newItemCount) { // 剩下的全是oldItem,做DEL } else { AbstractMap.SimpleEntry<Integer, T> oldIndexedItem = adjustedOldIndexedItems[oldCursor]; AbstractMap.SimpleEntry<Integer, T> newIndexedItem = adjustedNewIndexedItems[newCursor]; int cmpRes = oldIndexedItem.getValue().compareTo(newIndexedItem.getValue()); if (cmpRes < 0) { int deletedIndex = oldIndexedItem.getKey(); int deletedOffset = getItemOffsetOrIndex(deletedIndex, oldIndexedItem.getValue()); this.patchOperationList.add(new PatchOperation<T>(PatchOperation.OP_DEL, deletedIndex)); markDeletedIndexOrOffset(this.oldToPatchedIndexMap, deletedIndex, deletedOffset); ++oldCursor; } else if (cmpRes > 0) { this.patchOperationList.add(new PatchOperation<>(PatchOperation.OP_ADD, newIndexedItem.getKey(), newIndexedItem.getValue())); ++newCursor; } else { int oldIndex = oldIndexedItem.getKey(); int newIndex = newIndexedItem.getKey(); int oldOffset = getItemOffsetOrIndex(oldIndexedItem.getKey(), oldIndexedItem.getValue()); int newOffset = getItemOffsetOrIndex(newIndexedItem.getKey(), newIndexedItem.getValue()); if (oldIndex != newIndex) { this.oldIndexToNewIndexMap.put(oldIndex, newIndex); } if (oldOffset != newOffset) { this.oldOffsetToNewOffsetMap.put(oldOffset, newOffset); } ++oldCursor; ++newCursor; } } } }
做法類似一次有序歸併:兩邊各自按內容排序後雙指針前進,比 value——
OP_DEL;OP_ADD;接著還有一段後處理:
public void execute() { // 接上... // 根據index排序,如果index一樣,則先DEL後ADD Collections.sort(this.patchOperationList, comparatorForPatchOperationOpt); Iterator<PatchOperation<T>> patchOperationIt = this.patchOperationList.iterator(); PatchOperation<T> prevPatchOperation = null; while (patchOperationIt.hasNext()) { PatchOperation<T> patchOperation = patchOperationIt.next(); if (prevPatchOperation != null && prevPatchOperation.op == PatchOperation.OP_DEL && patchOperation.op == PatchOperation.OP_ADD ) { if (prevPatchOperation.index == patchOperation.index) { prevPatchOperation.op = PatchOperation.OP_REPLACE; prevPatchOperation.newItem = patchOperation.newItem; patchOperationIt.remove(); prevPatchOperation = null; } else { prevPatchOperation = patchOperation; } } else { prevPatchOperation = patchOperation; } } // Finally we record some information for the final calculations. patchOperationIt = this.patchOperationList.iterator(); while (patchOperationIt.hasNext()) { PatchOperation<T> patchOperation = patchOperationIt.next(); switch (patchOperation.op) { case PatchOperation.OP_DEL: { indexToDelOperationMap.put(patchOperation.index, patchOperation); break; } case PatchOperation.OP_ADD: { indexToAddOperationMap.put(patchOperation.index, patchOperation); break; } case PatchOperation.OP_REPLACE: { indexToReplaceOperationMap.put(patchOperation.index, patchOperation); break; } } } }
三步:按 index 排序(同 index 時 DEL 在 ADD 之前);把「同一 index 上相鄰的 DEL + ADD」合併成更緊湊的 OP_REPLACE;最後攤平成三個 Map,分別記錄待刪、待增、待替換。
execute 的產物就是這三個 Map。
public void simulatePatchOperation(int baseOffset) { int oldIndex = 0; int patchedIndex = 0; int patchedOffset = baseOffset; while (oldIndex < this.oldItemCount || patchedIndex < this.newItemCount) { if (this.indexToAddOperationMap.containsKey(patchedIndex)) { T newItem = patchOperation.newItem; int itemSize = getItemSize(newItem); ++patchedIndex; patchedOffset += itemSize; } else if (this.indexToReplaceOperationMap.containsKey(patchedIndex)) { T newItem = patchOperation.newItem; int itemSize = getItemSize(newItem); ++patchedIndex; patchedOffset += itemSize; } else if (this.indexToDelOperationMap.containsKey(oldIndex)) { ++oldIndex; } else if (this.indexToReplaceOperationMap.containsKey(oldIndex)) { ++oldIndex; } else if (oldIndex < this.oldItemCount) { ++oldIndex; ++patchedIndex; patchedOffset += itemSize; } } this.patchedSectionSize = SizeOf.roundToTimesOfFour(patchedOffset - baseOffset); }
它在模擬一遍「重建新區塊」的過程,只為得到 patchedSectionSize。會讓指針前移並累加 size 的情形有三種:命中待新增、命中待替換、以及既沒被刪也沒被替換的 old item。三者相加恰好就是 new dex 該區的 item 全集——這也從另一側驗證了 diff 結果的自洽性。
所有算法跑完,我們手上有:每個區的 PatchOperationList,以及每個區的 size(累加即可得到各區 offset)。
private void writeResultToStream(OutputStream os) throws IOException { DexDataBuffer buffer = new DexDataBuffer(); buffer.write(DexPatchFile.MAGIC); // DEXDIFF buffer.writeShort(DexPatchFile.CURRENT_VERSION); buffer.writeInt(this.patchedDexSize); // we will return here to write firstChunkOffset later. int posOfFirstChunkOffsetField = buffer.position(); buffer.writeInt(0); buffer.writeInt(this.patchedStringIdsOffset); buffer.writeInt(this.patchedTypeIdsOffset); buffer.writeInt(this.patchedProtoIdsOffset); buffer.writeInt(this.patchedFieldIdsOffset); buffer.writeInt(this.patchedMethodIdsOffset); buffer.writeInt(this.patchedClassDefsOffset); buffer.writeInt(this.patchedMapListOffset); buffer.writeInt(this.patchedTypeListsOffset); buffer.writeInt(this.patchedAnnotationSetRefListItemsOffset); buffer.writeInt(this.patchedAnnotationSetItemsOffset); buffer.writeInt(this.patchedClassDataItemsOffset); buffer.writeInt(this.patchedCodeItemsOffset); buffer.writeInt(this.patchedStringDataItemsOffset); buffer.writeInt(this.patchedDebugInfoItemsOffset); buffer.writeInt(this.patchedAnnotationItemsOffset); buffer.writeInt(this.patchedEncodedArrayItemsOffset); buffer.writeInt(this.patchedAnnotationsDirectoryItemsOffset); buffer.write(this.oldDex.computeSignature(false)); int firstChunkOffset = buffer.position(); buffer.position(posOfFirstChunkOffsetField); buffer.writeInt(firstChunkOffset); buffer.position(firstChunkOffset); writePatchOperations(buffer, this.stringDataSectionDiffAlg.getPatchOperationList()); // 省略其他14個writePatch... byte[] bufferData = buffer.array(); os.write(bufferData); os.flush(); }
檔頭依次是 MAGIC 與版本號(供讀取時校驗這是一個合法的 Tinker 補丁)、補丁後的 dex 總大小,以及各區 offset。注意第四個 int 先寫 0 佔位,等所有 offset 寫完再回填——它記錄的是數據區起點,讀取時靠它一步跳到正題。
private <T extends Comparable<T>> void writePatchOperations( DexDataBuffer buffer, List<PatchOperation<T>> patchOperationList ) { List<Integer> delOpIndexList = new ArrayList<>(patchOperationList.size()); List<Integer> addOpIndexList = new ArrayList<>(patchOperationList.size()); List<Integer> replaceOpIndexList = new ArrayList<>(patchOperationList.size()); List<T> newItemList = new ArrayList<>(patchOperationList.size()); for (PatchOperation<T> patchOperation : patchOperationList) { switch (patchOperation.op) { case PatchOperation.OP_DEL: { delOpIndexList.add(patchOperation.index); break; } case PatchOperation.OP_ADD: { addOpIndexList.add(patchOperation.index); newItemList.add(patchOperation.newItem); break; } case PatchOperation.OP_REPLACE: { replaceOpIndexList.add(patchOperation.index); newItemList.add(patchOperation.newItem); break; } } } buffer.writeUleb128(delOpIndexList.size()); int lastIndex = 0; for (Integer index : delOpIndexList) { buffer.writeSleb128(index - lastIndex); lastIndex = index; } buffer.writeUleb128(addOpIndexList.size()); lastIndex = 0; for (Integer index : addOpIndexList) { buffer.writeSleb128(index - lastIndex); lastIndex = index; } buffer.writeUleb128(replaceOpIndexList.size()); lastIndex = 0; for (Integer index : replaceOpIndexList) { buffer.writeSleb128(index - lastIndex); lastIndex = index; } for (T newItem : newItemList) { if (newItem instanceof StringData) { buffer.writeStringData((StringData) newItem); } } }
先按 DEL / ADD / REPLACE 分成三組索引,新值統一進 newItemList;寫入順序是「刪的個數 + 各個索引」「增的個數 + 各個索引」「換的個數 + 各個索引」「所有新值」。索引採用差值編碼(index - lastIndex)配合 ULEB128 / SLEB128,這是壓縮補丁體積的關鍵一筆。
於是我們可以反推 patch 的重建公式:某區在 new dex 中的內容等於
oldItems - del - replace + addItems + replaceItems
同樣從簽名反推:輸入 old dex 與 patch,輸出 new dex,對應的類是 DexPatchApplier(在 tinker-commons 中)。別被安全校驗和解壓邏輯帶跑。
@Test public void testPatch() throws IOException { File oldFile = new File("Hello.dex"); File patchFile = new File("patch.dex"); File newFile = new File("new.dex"); DexPatchApplier dexPatchGenerator = new DexPatchApplier(oldFile, patchFile); dexPatchGenerator.executeAndSaveTo(newFile); }
public DexPatchApplier(File oldDexIn, File patchFileIn) throws IOException { this(new Dex(oldDexIn), new DexPatchFile(patchFileIn)); }
public DexPatchFile(File file) throws IOException { this.buffer = new DexDataBuffer(ByteBuffer.wrap(FileUtils.readFile(file))); init(); }
private void init() { byte[] magic = this.buffer.readByteArray(MAGIC.length); if (CompareUtils.uArrCompare(magic, MAGIC) != 0) { throw new IllegalStateException("bad dex patch file magic: " + Arrays.toString(magic)); } this.version = this.buffer.readShort(); if (CompareUtils.uCompare(this.version, CURRENT_VERSION) != 0) { throw new IllegalStateException("bad dex patch file version: " + this.version + ", expected: " + CURRENT_VERSION); } this.patchedDexSize = this.buffer.readInt(); this.firstChunkOffset = this.buffer.readInt(); this.patchedStringIdSectionOffset = this.buffer.readInt(); this.patchedTypeIdSectionOffset = this.buffer.readInt(); this.patchedProtoIdSectionOffset = this.buffer.readInt(); this.patchedFieldIdSectionOffset = this.buffer.readInt(); this.patchedMethodIdSectionOffset = this.buffer.readInt(); this.patchedClassDefSectionOffset = this.buffer.readInt(); this.patchedMapListSectionOffset = this.buffer.readInt(); this.patchedTypeListSectionOffset = this.buffer.readInt(); this.patchedAnnotationSetRefListSectionOffset = this.buffer.readInt(); this.patchedAnnotationSetSectionOffset = this.buffer.readInt(); this.patchedClassDataSectionOffset = this.buffer.readInt(); this.patchedCodeSectionOffset = this.buffer.readInt(); this.patchedStringDataSectionOffset = this.buffer.readInt(); this.patchedDebugInfoSectionOffset = this.buffer.readInt(); this.patchedAnnotationSectionOffset = this.buffer.readInt(); this.patchedEncodedArraySectionOffset = this.buffer.readInt(); this.patchedAnnotationsDirectorySectionOffset = this.buffer.readInt(); this.oldDexSignature = this.buffer.readByteArray(SizeOf.SIGNATURE); this.buffer.position(firstChunkOffset); }
讀取順序與寫入嚴格對應:校驗 magic 與版本,讀出 patchedDexSize 與全部 offset,最後一步跳到 firstChunkOffset 進入數據區。
public DexPatchApplier( Dex oldDexIn, DexPatchFile patchFileIn) { this.oldDex = oldDexIn; this.patchFile = patchFileIn; this.patchedDex = new Dex(patchFileIn.getPatchedDexSize()); this.oldToPatchedIndexMap = new SparseIndexMap(); }
這裡預先按 patchedDexSize 開好了輸出的 Dex 對象,各區內容將直接寫入其中。
第一段,用 patch 檔裡的 offset 為輸出 dex 的 TableOfContents 賦值:
public void executeAndSaveTo(OutputStream out) throws IOException { TableOfContents patchedToc = this.patchedDex.getTableOfContents(); patchedToc.header.off = 0; patchedToc.header.size = 1; patchedToc.mapList.size = 1; patchedToc.stringIds.off = this.patchFile.getPatchedStringIdSectionOffset(); patchedToc.typeIds.off = this.patchFile.getPatchedTypeIdSectionOffset(); patchedToc.typeLists.off = this.patchFile.getPatchedTypeListSectionOffset(); patchedToc.protoIds.off = this.patchFile.getPatchedProtoIdSectionOffset(); patchedToc.fieldIds.off = this.patchFile.getPatchedFieldIdSectionOffset(); patchedToc.methodIds.off = this.patchFile.getPatchedMethodIdSectionOffset(); patchedToc.classDefs.off = this.patchFile.getPatchedClassDefSectionOffset(); patchedToc.mapList.off = this.patchFile.getPatchedMapListSectionOffset(); patchedToc.stringDatas.off = this.patchFile.getPatchedStringDataSectionOffset(); patchedToc.annotations.off = this.patchFile.getPatchedAnnotationSectionOffset(); patchedToc.annotationSets.off = this.patchFile.getPatchedAnnotationSetSectionOffset(); patchedToc.annotationSetRefLists.off = this.patchFile.getPatchedAnnotationSetRefListSectionOffset(); patchedToc.annotationsDirectories.off = this.patchFile.getPatchedAnnotationsDirectorySectionOffset(); patchedToc.encodedArrays.off = this.patchFile.getPatchedEncodedArraySectionOffset(); patchedToc.debugInfos.off = this.patchFile.getPatchedDebugInfoSectionOffset(); patchedToc.codes.off = this.patchFile.getPatchedCodeSectionOffset(); patchedToc.classDatas.off = this.patchFile.getPatchedClassDataSectionOffset(); patchedToc.fileSize = this.patchFile.getPatchedDexSize(); Arrays.sort(patchedToc.sections); patchedToc.computeSizesFromOffsets(); }
排序並算出各區 byteCount 後,佈局就確定了。
第二段,按依賴順序執行 15 個 patch 算法。注意執行順序與 diff 時的宣告順序不同——這裡是拓撲排序的結果,被引用的區必須先還原:
public void executeAndSaveTo(OutputStream out) throws IOException { // 第二段 this.stringDataSectionPatchAlg = new StringDataSectionPatchAlgorithm( patchFile, oldDex, patchedDex, oldToPatchedIndexMap ); this.typeIdSectionPatchAlg = new TypeIdSectionPatchAlgorithm(...); this.protoIdSectionPatchAlg = new ProtoIdSectionPatchAlgorithm(...); this.fieldIdSectionPatchAlg = new FieldIdSectionPatchAlgorithm(...); this.methodIdSectionPatchAlg = new MethodIdSectionPatchAlgorithm(...); this.classDefSectionPatchAlg = new ClassDefSectionPatchAlgorithm(...); this.typeListSectionPatchAlg = new TypeListSectionPatchAlgorithm(...); this.annotationSetRefListSectionPatchAlg = new AnnotationSetRefListSectionPatchAlgorithm(...); this.annotationSetSectionPatchAlg = new AnnotationSetSectionPatchAlgorithm(...); this.classDataSectionPatchAlg = new ClassDataSectionPatchAlgorithm(...); this.codeSectionPatchAlg = new CodeSectionPatchAlgorithm(...); this.debugInfoSectionPatchAlg = new DebugInfoItemSectionPatchAlgorithm(...); this.annotationSectionPatchAlg = new AnnotationSectionPatchAlgorithm(...); this.encodedArraySectionPatchAlg = new StaticValueSectionPatchAlgorithm(...); this.annotationsDirectorySectionPatchAlg = new AnnotationsDirectorySectionPatchAlgorithm(...); this.stringDataSectionPatchAlg.execute(); this.typeIdSectionPatchAlg.execute(); this.typeListSectionPatchAlg.execute(); this.protoIdSectionPatchAlg.execute(); this.fieldIdSectionPatchAlg.execute(); this.methodIdSectionPatchAlg.execute(); this.annotationSectionPatchAlg.execute(); this.annotationSetSectionPatchAlg.execute(); this.annotationSetRefListSectionPatchAlg.execute(); this.annotationsDirectorySectionPatchAlg.execute(); this.debugInfoSectionPatchAlg.execute(); this.codeSectionPatchAlg.execute(); this.classDataSectionPatchAlg.execute(); this.encodedArraySectionPatchAlg.execute(); this.classDefSectionPatchAlg.execute(); }
以 stringData 為例:
public void execute() { final int deletedItemCount = patchFile.getBuffer().readUleb128(); final int[] deletedIndices = readDeltaIndiciesOrOffsets(deletedItemCount); final int addedItemCount = patchFile.getBuffer().readUleb128(); final int[] addedIndices = readDeltaIndiciesOrOffsets(addedItemCount); final int replacedItemCount = patchFile.getBuffer().readUleb128(); final int[] replacedIndices = readDeltaIndiciesOrOffsets(replacedItemCount); final TableOfContents.Section tocSec = getTocSection(this.oldDex); Dex.Section oldSection = null; int oldItemCount = 0; if (tocSec.exists()) { oldSection = this.oldDex.openSection(tocSec); oldItemCount = tocSec.size; } doFullPatch( oldSection, oldItemCount, deletedIndices, addedIndices, replacedIndices ); }
讀取順序與寫入完全一致:刪的數量與索引、增的數量與索引、換的數量與索引,然後拿到 old dex 對應區的指針與 item 數。四項齊備,進入 doFullPatch:
private void doFullPatch( Dex.Section oldSection, int oldItemCount, int[] deletedIndices, int[] addedIndices, int[] replacedIndices) { int deletedItemCount = deletedIndices.length; int addedItemCount = addedIndices.length; int replacedItemCount = replacedIndices.length; int newItemCount = oldItemCount + addedItemCount - deletedItemCount; int deletedItemCounter = 0; int addActionCursor = 0; int replaceActionCursor = 0; int oldIndex = 0; int patchedIndex = 0; while (oldIndex < oldItemCount || patchedIndex < newItemCount) { if (addActionCursor < addedItemCount && addedIndices[addActionCursor] == patchedIndex) { T addedItem = nextItem(patchFile.getBuffer()); int patchedOffset = writePatchedItem(addedItem); ++addActionCursor; ++patchedIndex; } else if (replaceActionCursor < replacedItemCount && replacedIndices[replaceActionCursor] == patchedIndex) { T replacedItem = nextItem(patchFile.getBuffer()); int patchedOffset = writePatchedItem(replacedItem); ++replaceActionCursor; ++patchedIndex; } else if (Arrays.binarySearch(deletedIndices, oldIndex) >= 0) { T skippedOldItem = nextItem(oldSection); ++oldIndex; ++deletedItemCounter; } else if (Arrays.binarySearch(replacedIndices, oldIndex) >= 0) { T skippedOldItem = nextItem(oldSection); ++oldIndex; } else if (oldIndex < oldItemCount) { T oldItem = adjustItem(this.oldToPatchedIndexMap, nextItem(oldSection)); int patchedOffset = writePatchedItem(oldItem); ++oldIndex; ++patchedIndex; } } }
先算出 newItemCount = oldItemCount + addCount - delCount,然後按 patchedIndex 從 0 走到 newItemCount,每個位置四選一:命中待新增就從 patch 檔讀新值寫入;命中待替換同理;oldIndex 落在待刪或待替換集合則跳過舊值;否則把舊值寫入(注意這裡經過 adjustItem,因為被引用的 index / offset 可能已經變了)。
值得欣賞的是它的 IO 模式:新增與替換的值在 patch 檔中是按 patchedIndex 順序緊密排列的,所以只需一個流式讀指針配合三組索引,就能一遍完成重建,不需要隨讀定位。
其餘 14 個算法的 execute 邏輯都寫在父類裡,差異只在於 item 的讀寫方式。
第三段,所有區塊還原完畢,收尾寫 header 與 map_list:
public void executeAndSaveTo(OutputStream out) throws IOException { // 1. offset賦值 // 2. 各區patch算法 Dex.Section headerOut = this.patchedDex.openSection(patchedToc.header.off); patchedToc.writeHeader(headerOut); Dex.Section mapListOut = this.patchedDex.openSection(patchedToc.mapList.off); patchedToc.writeMap(mapListOut); this.patchedDex.writeHashes(); this.patchedDex.writeTo(out); }
writeHashes() 計算 signature 與 checksum——這兩項依賴整個檔的最終內容,因此必須放在 map_list 之後。最後把內存中的 Dex 整體落檔,重建完成。
public class World{ public static void main(String[] args){ System.out.println("nani World"); } }
javac -source 1.7 -target 1.7 World.java dx --dex --output=World.dex World.class
用 010 Editor 分別打開兩個 dex,只看 string_id_item:

兩邊各 13 個字串,按前述算法雙指針比對,得到的操作序列是:
del 1 add 1 LWorld; del 2 add 8 World.java del 10 add 11 naniWorld
按索引排序後順序不變;接著把「同索引相鄰的 DEL + ADD」摺疊成 REPLACE:
replace 1 LWorld del 2 add 8 World.java del 10 add 11 naniWorld
寫檔前再按 DEL / ADD / REPLACE 分組,新值依序進 newItemList:
del ops: del 2 del 10 add ops: add 8 add 11 replace ops: replace 1
LWorld //replace 1 World.java //add 8 naniWorld //add 11
那麼最終寫入的字節序列應該是:
2 //del size 2 8 // index - lastIndex 2 // add size 8 3 // index - lastIndex 1 //replace size 1 LWorld World.java naniWorld
在 writeResultToStream 的對應位置加上日誌驗證:
buffer.writeUleb128(delOpIndexList.size()); System.out.println("del size = " + delOpIndexList.size()); int lastIndex = 0; for (Integer index : delOpIndexList) { buffer.writeSleb128(index - lastIndex); System.out.println("del index = " + (index - lastIndex)); lastIndex = index; } buffer.writeUleb128(addOpIndexList.size()); System.out.println("add size = " + addOpIndexList.size()); lastIndex = 0; for (Integer index : addOpIndexList) { buffer.writeSleb128(index - lastIndex); System.out.println("add index = " + (index - lastIndex)); lastIndex = index; } buffer.writeUleb128(replaceOpIndexList.size()); System.out.println("replace size = " + replaceOpIndexList.size()); lastIndex = 0; for (Integer index : replaceOpIndexList) { buffer.writeSleb128(index - lastIndex); System.out.println("replace index = " + (index - lastIndex)); lastIndex = index; } for (T newItem : newItemList) { if (newItem instanceof StringData) { buffer.writeStringData((StringData) newItem); System.out.println("stringdata = " + ((StringData) newItem).value); } }
實際輸出:
del size = 2 del index = 2 del index = 8 add size = 2 add index = 8 add index = 3 replace size = 1 replace index = 1 stringdata = LWorld; stringdata = World.java stringdata = nani World
與手推結果完全一致。其他區塊可以用同樣的方式驗證,patch 側的推導也類似,這裡不再重複。
如何反編譯 Android 5.0 framework
在 Android 平台上,對於與硬件交互相關的模塊——比如對應雙卡的 Telephony、對應拍照的 Camera,以及 Bluetooth 等等——不同廠商會不同程度
invisible 和 gone 差在哪?Android 可見性屬性完整對比
Android 裡幾乎每個 View 都有 visibility 屬性,取值只有三個:visible、invisible、gone。看起來都是「顯示 / 不顯示」,但 i
從 Java 到 Kernel:一次讀懂 Android Binder 的跨進程通信全程
本文以 Android 6.0 原始碼為基礎,沿著 startService 這條主線,把 Binder 的 IPC 過程從 Java framework 一路追到 Na
iOS 與 Android 究竟哪個平台更賺錢?
一直有個幾乎所有手機愛好者都認同的說法:Android 是全球用戶數最多的操作系統,市場份額十分驚人。無論你問表哥表姐還是弟弟妹妹,哪怕他們不太關注移動領域、不太懂手機,