編輯:Android 資訊
前面的文章已經把 Tinker 的 loader 流程、以及 dex diff / patch 的算法拆開講過了。整個體系如果少了「補丁是怎麼被打出來的」這一塊,理解鏈條其實是斷的,所以這一篇專門來看 tinker-patch-gradle-plugin。
(拖了將近兩個月才動手寫,再不記下來細節就真的忘乾淨了。)
本文對應的 Tinker 版本為 1.7.7。相關的前作是:
先拋一個問題:如果只給你一個 gradle 命令,執行完就吐出一個可以下發的 patch 檔,這個檔還能修代碼、修資源,你會怎麼設計?
最樸素的思路是:指定 oldApk,本地構建出 newApk,兩者做 diff,把差異數據用某種算法打包成補丁。方向沒錯,但魔鬼在細節裡:
回頭翻 build.gradle 就會發現,Tinker 要求我們填 oldApk 路徑、R.txt 路徑、mapping 路徑等等,卻從來沒有要求我們自己去寫 keep 規則、去改分包配置、去 apply mapping。這些髒活它全替你乾了。
本文就以這四個問題為線索,把 plugin 的代碼走一遍——順便說一句,這份 plugin 本身就是極好的 Gradle 學習材料。
把 Tinker 代碼庫拉下來導入,plugin 全部在 tinker-patch-gradle-plugin 模組下。但千萬不要一行一行硬啃,先找到入口。
入口其實很直白:打補丁時我們執行的是 tinkerPatchDebug(本文以 debug 為例)。執行日誌會長這樣:
:app:processDebugManifest :app:tinkerProcessDebugManifest(tinker) :app:tinkerProcessDebugResourceId (tinker) :app:processDebugResources :app:tinkerProguardConfigTask(tinker) :app:transformClassesAndResourcesWithProguard :app:tinkerProcessDebugMultidexKeep (tinker) :app:transformClassesWidthMultidexlistForDebug :app:assembleDebug :app:tinkerPatchDebug(tinker)
標了 (tinker) 的,就是插件自己塞進構建流程的 task。它們是怎麼混進去的?
接入 Tinker 之後,build.gradle 裡會有這麼一段:
if (buildWithTinker()) { apply plugin: 'com.tencent.tinker.patch' tinkerPatch {} // 各種參數 }
開關打開後 apply 了 com.tencent.tinker.patch,這個名字其實就是 properties 檔名,而該檔會映射到具體的插件類:

走進 TinkerPatchPlugin,apply 方法裡的核心邏輯大致如下:
// ... 省略了一堆代碼 TinkerPatchSchemaTask tinkerPatchBuildTask = project.tasks.create("tinkerPatch${variantName}", TinkerPatchSchemaTask) tinkerPatchBuildTask.dependsOn variant.assemble TinkerManifestTask manifestTask = project.tasks.create("tinkerProcess${variantName}Manifest", TinkerManifestTask) manifestTask.mustRunAfter variantOutput.processManifest variantOutput.processResources.dependsOn manifestTask TinkerResourceIdTask applyResourceTask = project.tasks.create("tinkerProcess${variantName}ResourceId", TinkerResourceIdTask) applyResourceTask.mustRunAfter manifestTask variantOutput.processResources.dependsOn applyResourceTask if (proguardEnable) { TinkerProguardConfigTask proguardConfigTask = project.tasks.create("tinkerProcess${variantName}Proguard", TinkerProguardConfigTask) proguardConfigTask.mustRunAfter manifestTask def proguardTask = getProguardTask(project, variantName) if (proguardTask != null) { proguardTask.dependsOn proguardConfigTask } } if (multiDexEnabled) { TinkerMultidexConfigTask multidexConfigTask = project.tasks.create("tinkerProcess${variantName}MultidexKeep", TinkerMultidexConfigTask) multidexConfigTask.mustRunAfter manifestTask def multidexTask = getMultiDexTask(project, variantName) if (multidexTask != null) { multidexTask.dependsOn multidexConfigTask } }
一目了然:通過 Gradle 的 Project API 創建了 5 個 task,再用 dependsOn 與 mustRunAfter 把它們縫進原有流程。例如這兩行:
TinkerManifestTask manifestTask = ... manifestTask.mustRunAfter variantOutput.processManifest variantOutput.processResources.dependsOn manifestTask
含義是 manifestTask 必須排在 processManifest 之後,而 processResources 又必須排在 manifestTask 之後,最終流程被改寫成:
processManifest-> manifestTask-> processResources
其餘幾個同理。理解了注入機制,接下來就是逐個看它們到底做了什麼。
順帶一提:如果你也有「在構建過程中插一脚」的需求,這套 task 編寫 + 依賴聲明的方式可以直接借鑑。

#TinkerManifestTask @TaskAction def updateManifest() { // Parse the AndroidManifest.xml String tinkerValue = project.extensions.tinkerPatch.buildConfig.tinkerId tinkerValue = TINKER_ID_PREFIX + tinkerValue;//"tinker_id_" // /build/intermediates/manifests/full/debug/AndroidManifest.xml writeManifestMeta(manifestPath, TINKER_ID, tinkerValue) addApplicationToLoaderPattern() File manifestFile = new File(manifestPath) if (manifestFile.exists()) { FileOperation.copyFileUsingStream(manifestFile, project.file(MANIFEST_XML)) } }
它只幹兩件事。
writeManifestMeta 解析 AndroidManifest.xml,在 <application> 節點內插入一條 meta-data,值就是拼好前綴的 tinkerValue:
<meta-data android:name="TINKER_ID" android:value="tinker_id_com.zhy.abc" />
(用 Groovy 操作 XML 實在是輕鬆,這裡就不展開了。)
addApplicationToLoaderPattern 則把自訂的 Application 類名,連同 com.tencent.tinker.loader.* 這批 loader 類,一併記錄到 project.extensions.tinkerPatch.dex.loader 中,供後續 task 使用。
最後把改好的 manifest 拷到 build/intermediates/tinker_intermediates/AndroidManifest.xml。
這裡值得停一下:文初列的四個問題裡並沒有 tinkerId,它憑什麼存在?微信的參數說明給了答案:
運行時需要校驗基準包的 tinkerId 是否等於補丁包的 tinkerId,這決定了補丁能應用到哪些基準包上。一般可以直接用 Git 版本號、versionName 之類的標識。
道理很樸素:非強制升級的場景下,線上同時存在各個版本的 App,而你的補丁只針對其中某一版。用 tinkerId 做配對,才能保證補丁不誤傷其他版本。
這正是為了解決文初第一個問題:打補丁時必須讓老資源的 ID 保持不變。手段是 public.xml 與 ids.xml。只要在 public.xml 裡提前固定:
<public type="id" name="search_button" id="0x7f0c0046" />
那麼後續構建中該資源的 ID 值就不會再變(檔名本身沒有硬性要求)。
很多人知道用 public.xml 固化資源,卻不清楚 ids.xml 存在的意義。有篇文章解釋得很清楚:
public.xml 是在 aapt 編譯時通過 -P 參數生成的,Gradle 插件 hook 掉相關 Task 無縫追加這個參數即可。需要注意的是,aapt 產出的 public.xml 不能直接用:裡面包含 id 類型的資源,應用到補丁構建時會報 resource is not defined。解法是把 id 類型資源單獨抽到 ids.xml 中,相當於一次聲明,編譯時和 public.xml 一起參與即可。
那具體怎麼保證 ID 不變?關鍵參數是 tinkerApplyResourcePath,它指向 oldApk 的 R.txt,裡面記錄了舊包所有資源對應的 int 值。
思路就出來了:把 R.txt 的內容翻譯成 public.xml,老資源的 ID 自然被鎖住。而 Tinker 做得更徹底——它不僅搬運老資源,還按照 ID 生成規則為新增資源也分配好 int 值並寫進 public.xml,等於把資源 ID 的分配權完全接管了。
第一步,把配置裡的 R.txt 讀進記憶體,拆成兩份結構:
第二步,遍歷當前工程的資源,分兩類處理。
values 目錄下的檔:遍歷 XML 節點,涵蓋 item、dimen、color、drawable、bool、integer、array、style、declare-styleable、attr、fraction 等類型,按類型歸入 rTypeResourceMap(key 為資源類型,value 為該類型的資源集合)。其中 declare-styleable 只取其內部的 attr 節點,按同樣規則處理。
res 下非 values 目錄:打開工程就能看到 layout、anim、color 等目錄,資源形式有兩種。一種是「檔即資源」,如 R.layout.xxx、R.drawable.xxx;另一種是 XML 中的 @+id/xxx 形式(@+android:id 除外),截取節點名作為資源名。同名同類型的直接複用舊值,否則分配新的 typeId 與 resourceId。
所有結果彙入 rTypeResourceMap,最後統一寫成 public.xml。以上即為這個 task 的全貌,下面的源碼只是把同樣的事做得更細。
@TaskAction def applyResourceId() { // 資源mapping文件 String resourceMappingFile = project.extensions.tinkerPatch.buildConfig.applyResourceMapping // resDir /build/intermediates/res/merged/debug String idsXml = resDir + "/values/ids.xml"; String publicXml = resDir + "/values/public.xml"; FileOperation.deleteFile(idsXml); FileOperation.deleteFile(publicXml); List<String> resourceDirectoryList = new ArrayList<String>(); // /build/intermediates/res/merged/debug resourceDirectoryList.add(resDir); project.logger.error("we build ${project.getName()} apk with apply resource mapping file ${resourceMappingFile}"); project.extensions.tinkerPatch.buildConfig.usingResourceMapping = true; // 收集所有的資源,以type->type,name,id,int/int[]存儲 Map<RDotTxtEntry.RType, Set<RDotTxtEntry>> rTypeResourceMap = PatchUtil.readRTxt(resourceMappingFile); AaptResourceCollector aaptResourceCollector = AaptUtil.collectResource(resourceDirectoryList, rTypeResourceMap); PatchUtil.generatePublicResourceXml(aaptResourceCollector, idsXml, publicXml); File publicFile = new File(publicXml); if (publicFile.exists()) { FileOperation.copyFileUsingStream(publicFile, project.file(RESOURCE_PUBLIC_XML)); project.logger.error("tinker gen resource public.xml in ${RESOURCE_PUBLIC_XML}"); } File idxFile = new File(idsXml); if (idxFile.exists()) { FileOperation.copyFileUsingStream(idxFile, project.file(RESOURCE_IDX_XML)); project.logger.error("tinker gen resource idx.xml in ${RESOURCE_IDX_XML}"); } }
先看輪廓:沒配 resource mapping 檔就直接跳過;最終產物是 public.xml 和 ids.xml;進入邏輯前會先清掉舊的同名檔。
隨後 PatchUtil.readRTxt 讀取 mapping 檔,其內容格式大致是:
int anim abc_slide_in_bottom 0x7f050006 int id useLogo 0x7f0b0012 int[] styleable AppCompatImageView { 0x01010119, 0x7f010027 } int styleable AppCompatImageView_android_src 0 int styleable AppCompatImageView_srcCompat 1
兩類記錄:普通 int 資源,以及 int[] 形式的 styleable(後面緊跟它的各個 item,寫過自訂 View 的應該很熟)。
readRTxt 的實現不長,用正則逐行匹配,每行拆成 idType、rType、name、idValue 四個欄位(對應 RDotTxtEntry 的成員)。idType 只有 INT 和 INT_ARRAY 兩種;rType 覆蓋:
ANIM, ANIMATOR, ARRAY, ATTR, BOOL, COLOR, DIMEN, DRAWABLE, FRACTION, ID, INTEGER, INTERPOLATOR, LAYOUT, MENU, MIPMAP, PLURALS, RAW, STRING, STYLE, STYLEABLE, TRANSITION, XML(參照 android.R 的定義)。這一步並沒有對 styleable 做特殊處理,只是按 rType 分組存進 Map。
接著看 AaptUtil.collectResource:
public static AaptResourceCollector collectResource(List<String> resourceDirectoryList, Map<RType, Set<RDotTxtEntry>> rTypeResourceMap) { AaptResourceCollector resourceCollector = new AaptResourceCollector(rTypeResourceMap); List<com.tencent.tinker.build.aapt.RDotTxtEntry> references = new ArrayList<com.tencent.tinker.build.aapt.RDotTxtEntry>(); for (String resourceDirectory : resourceDirectoryList) { try { collectResources(resourceDirectory, resourceCollector); } catch (Exception e) { throw new RuntimeException(e); } } for (String resourceDirectory : resourceDirectoryList) { try { processXmlFilesForIds(resourceDirectory, references, resourceCollector); } catch (Exception e) { throw new RuntimeException(e); } } return resourceCollector; }
它的構造方法先把舊資源表吃進來:
public AaptResourceCollector(Map<RType, Set<RDotTxtEntry>> rTypeResourceMap) { this(); if (rTypeResourceMap != null) { Iterator<Entry<RType, Set<RDotTxtEntry>>> iterator = rTypeResourceMap.entrySet().iterator(); while (iterator.hasNext()) { Entry<RType, Set<RDotTxtEntry>> entry = iterator.next(); RType rType = entry.getKey(); Set<RDotTxtEntry> set = entry.getValue(); for (RDotTxtEntry rDotTxtEntry : set) { originalResourceMap.put(rDotTxtEntry, rDotTxtEntry); ResourceIdEnumerator resourceIdEnumerator = null; // ARRAY主要是styleable if (!rDotTxtEntry.idType.equals(IdType.INT_ARRAY)) { // 獲得resourceId int resourceId = Integer.decode(rDotTxtEntry.idValue.trim()).intValue(); // 獲得typeId int typeId = ((resourceId & 0x00FF0000) / 0x00010000); if (typeId >= currentTypeId) { currentTypeId = typeId + 1; } // type -> id的映射 if (this.rTypeEnumeratorMap.containsKey(rType)) { resourceIdEnumerator = this.rTypeEnumeratorMap.get(rType); if (resourceIdEnumerator.currentId < resourceId) { resourceIdEnumerator.currentId = resourceId; } } else { resourceIdEnumerator = new ResourceIdEnumerator(); resourceIdEnumerator.currentId = resourceId; this.rTypeEnumeratorMap.put(rType, resourceIdEnumerator); } } } } } }
三件事:整條記錄塞進 originalResourceMap;對 int 型資源解出 typeId 並持續推進 currentTypeId(遍歷結束時它是最大值 +1);在 rTypeEnumeratorMap 中為每個 rType 維護「當前最大 resourceId」。
構造完成後依次執行 collectResources 與 processXmlFilesForIds。
collectResources:遍歷 res 目錄,values* 目錄交給 processValues,其他目錄交給 processFileNamesInDirectory。
private static void collectResources(String resourceDirectory, AaptResourceCollector resourceCollector) throws Exception { File resourceDirectoryFile = new File(resourceDirectory); File[] fileArray = resourceDirectoryFile.listFiles(); if (fileArray != null) { for (File file : fileArray) { if (file.isDirectory()) { String directoryName = file.getName(); if (directoryName.startsWith("values")) { if (!isAValuesDirectory(directoryName)) { throw new AaptUtilException("'" + directoryName + "' is not a valid values directory."); } processValues(file.getAbsolutePath(), resourceCollector); } else { processFileNamesInDirectory(file.getAbsolutePath(), resourceCollector); } } } } }
processValuesFile:values 下的檔基本都是 XML,逐個節點解析,按標籤名映射到 rType,並依類型取節點值:
public static void processValuesFile(String valuesFullFilename, AaptResourceCollector resourceCollector) throws Exception { Document document = JavaXmlUtil.parse(valuesFullFilename); String directoryName = new File(valuesFullFilename).getParentFile().getName(); Element root = document.getDocumentElement(); for (Node node = root.getFirstChild(); node != null; node = node.getNextSibling()) { if (node.getNodeType() != Node.ELEMENT_NODE) { continue; } String resourceType = node.getNodeName(); if (resourceType.equals(ITEM_TAG)) { resourceType = node.getAttributes().getNamedItem("type").getNodeValue(); if (resourceType.equals("id")) { resourceCollector.addIgnoreId(node.getAttributes().getNamedItem("name").getNodeValue()); } } if (IGNORED_TAGS.contains(resourceType)) { continue; } if (!RESOURCE_TYPES.containsKey(resourceType)) { throw new AaptUtilException("Invalid resource type <" + resourceType + "> in '" + valuesFullFilename + "'."); } RType rType = RESOURCE_TYPES.get(resourceType); String resourceValue = null; switch (rType) { case STRING: case COLOR: case DIMEN: case DRAWABLE: case BOOL: case INTEGER: resourceValue = node.getTextContent().trim(); break; case ARRAY://has sub item case PLURALS://has sub item case STYLE://has sub item case STYLEABLE://has sub item resourceValue = subNodeToString(node); break; case FRACTION://no sub item resourceValue = nodeToString(node, true); break; case ATTR://no sub item resourceValue = nodeToString(node, true); break; } try { addToResourceCollector(resourceCollector, new ResourceDirectory(directoryName, valuesFullFilename), node, rType, resourceValue); } catch (Exception e) { throw new AaptUtilException(e.getMessage() + ",Process file error:" + valuesFullFilename, e); } } }
順帶一提,這裡會把 <item type="id"> 聲明過的 id 記到 ignoreIdSet,最後寫 ids.xml 時會把它們過濾掉。
addToResourceCollector:非 styleable 直接取 name 註冊;styleable 則遍歷內部 attr 節點,跳過 android: 開頭的(系統屬性的 ID 不需要我們定),以 ATTR 類型註冊。
private static void addToResourceCollector(AaptResourceCollector resourceCollector, ResourceDirectory resourceDirectory, Node node, RType rType, String resourceValue) { String resourceName = sanitizeName(rType, resourceCollector, extractNameAttribute(node)); if (rType.equals(RType.STYLEABLE)) { int count = 0; for (Node attrNode = node.getFirstChild(); attrNode != null; attrNode = attrNode.getNextSibling()) { if (attrNode.getNodeType() != Node.ELEMENT_NODE || !attrNode.getNodeName().equals("attr")) { continue; } String rawAttrName = extractNameAttribute(attrNode); String attrName = sanitizeName(rType, resourceCollector, rawAttrName); if (!rawAttrName.startsWith("android:")) { resourceCollector.addIntResourceIfNotPresent(RType.ATTR, attrName); } } } else { resourceCollector.addIntResourceIfNotPresent(rType, resourceName); } }
核心分配邏輯在這裡:
public void addIntResourceIfNotPresent(RType rType, String name) { if (!rTypeEnumeratorMap.containsKey(rType)) { if (rType.equals(RType.ATTR)) { rTypeEnumeratorMap.put(rType, new ResourceIdEnumerator(1)); } else { rTypeEnumeratorMap.put(rType, new ResourceIdEnumerator(currentTypeId++)); } } RDotTxtEntry entry = new FakeRDotTxtEntry(IdType.INT, rType, name); Set<RDotTxtEntry> resourceSet = null; if (this.rTypeResourceMap.containsKey(rType)) { resourceSet = this.rTypeResourceMap.get(rType); } else { resourceSet = new HashSet<RDotTxtEntry>(); this.rTypeResourceMap.put(rType, resourceSet); } if (!resourceSet.contains(entry)) { String idValue = String.format("0x%08x", rTypeEnumeratorMap.get(rType).next()); addResource(rType, IdType.INT, name, idValue); } }
已存在同名同類型資源就什麼都不做;否則用 rTypeEnumeratorMap 裡記錄的該類型當前最大 ID 往後 +1。若這個類型是全新的,ATTR 固定從 1 開始,其他類型則用 currentTypeId 遞增出一個新 typeId。ID 拼好後交給 addResource:
public void addResource(RType rType, IdType idType, String name, String idValue) { Set<RDotTxtEntry> resourceSet = null; if (this.rTypeResourceMap.containsKey(rType)) { resourceSet = this.rTypeResourceMap.get(rType); } else { resourceSet = new HashSet<RDotTxtEntry>(); this.rTypeResourceMap.put(rType, resourceSet); } RDotTxtEntry rDotTxtEntry = new RDotTxtEntry(idType, rType, name, idValue); if (!resourceSet.contains(rDotTxtEntry)) { if (this.originalResourceMap.containsKey(rDotTxtEntry)) { this.rTypeEnumeratorMap.get(rType).previous(); rDotTxtEntry = this.originalResourceMap.get(rDotTxtEntry); } resourceSet.add(rDotTxtEntry); } }
contains 只比對 name 與 type。若命中 originalResourceMap,說明這條資源本來就在舊的 res map 裡,於是回退一次枚舉器(與前面的 next 配對),並直接複用舊實體——這一步正是「老資源 ID 不變」的落點。
processFileNamesInDirectory:處理 layout、anim 這類「檔名即資源名」的目錄,先從目錄名(如 drawable-xhpi)推出資源類型,再以檔名(去掉副檔名)作為資源名註冊。
public static void processFileNamesInDirectory(String resourceDirectory, AaptResourceCollector resourceCollector) throws IOException { File resourceDirectoryFile = new File(resourceDirectory); String directoryName = resourceDirectoryFile.getName(); int dashIndex = directoryName.indexOf('-'); if (dashIndex != -1) { directoryName = directoryName.substring(0, dashIndex); } if (!RESOURCE_TYPES.containsKey(directoryName)) { throw new AaptUtilException(resourceDirectoryFile.getAbsolutePath() + " is not a valid resource sub-directory."); } File[] fileArray = resourceDirectoryFile.listFiles(); if (fileArray != null) { for (File file : fileArray) { if (file.isHidden()) { continue; } String filename = file.getName(); int dotIndex = filename.indexOf('.'); String resourceName = dotIndex != -1 ? filename.substring(0, dotIndex) : filename; RType rType = RESOURCE_TYPES.get(directoryName); resourceCollector.addIntResourceIfNotPresent(rType, resourceName); System.out.println("rType = " + rType + " , resName = " + resourceName); ResourceDirectory resourceDirectoryBean = new ResourceDirectory(file.getParentFile().getName(), file.getAbsolutePath()); resourceCollector.addRTypeResourceName(rType, resourceName, null, resourceDirectoryBean); } } }
processXmlFilesForIds:跳過 values* 與 raw* 目錄,掃其餘 XML 中的自訂 id 節點。
public static void processXmlFilesForIds(String resourceDirectory, List<RDotTxtEntry> references, AaptResourceCollector resourceCollector) throws Exception { List<String> xmlFullFilenameList = FileUtil.findMatchFile(resourceDirectory, Constant.Symbol.DOT + Constant.File.XML); if (xmlFullFilenameList != null) { for (String xmlFullFilename : xmlFullFilenameList) { File xmlFile = new File(xmlFullFilename); String parentFullFilename = xmlFile.getParent(); File parentFile = new File(parentFullFilename); if (isAValuesDirectory(parentFile.getName()) || parentFile.getName().startsWith("raw")) { continue; } processXmlFile(xmlFullFilename, references, resourceCollector); } } }
public static void processXmlFile(String xmlFullFilename, List<RDotTxtEntry> references, AaptResourceCollector resourceCollector) throws IOException, XPathExpressionException { Document document = JavaXmlUtil.parse(xmlFullFilename); NodeList nodesWithIds = (NodeList) ANDROID_ID_DEFINITION.evaluate(document, XPathConstants.NODESET); for (int i = 0; i < nodesWithIds.getLength(); i++) { String resourceName = nodesWithIds.item(i).getNodeValue(); if (!resourceName.startsWith(ID_DEFINITION_PREFIX)) { throw new AaptUtilException("Invalid definition of a resource: '" + resourceName + "'"); } resourceCollector.addIntResourceIfNotPresent(RType.ID, resourceName.substring(ID_DEFINITION_PREFIX.length())); } }
也就是把 @+id/tv 中的 tv 取出來註冊為 ID 資源(@+android:id 除外)。至此資源收集完畢,剩下寫檔。
generatePublicResourceXml:遍歷 rTypeResourceMap,每條資源輸出為一行 public 標籤;若類型是 ID 且不在 ignoreSet 中,額外寫入 ids.xml。
public static void generatePublicResourceXml(AaptResourceCollector aaptResourceCollector, String outputIdsXmlFullFilename, String outputPublicXmlFullFilename) { if (aaptResourceCollector == null) { return; } FileUtil.createFile(outputIdsXmlFullFilename); FileUtil.createFile(outputPublicXmlFullFilename); PrintWriter idsWriter = null; PrintWriter publicWriter = null; try { idsWriter = new PrintWriter(new File(outputIdsXmlFullFilename), "UTF-8"); publicWriter = new PrintWriter(new File(outputPublicXmlFullFilename), "UTF-8"); idsWriter.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); publicWriter.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); idsWriter.println("<resources>"); publicWriter.println("<resources>"); Map<RType, Set<RDotTxtEntry>> map = aaptResourceCollector.getRTypeResourceMap(); Iterator<Entry<RType, Set<RDotTxtEntry>>> iterator = map.entrySet().iterator(); while (iterator.hasNext()) { Entry<RType, Set<RDotTxtEntry>> entry = iterator.next(); RType rType = entry.getKey(); if (!rType.equals(RType.STYLEABLE)) { Set<RDotTxtEntry> set = entry.getValue(); for (RDotTxtEntry rDotTxtEntry : set) { String rawName = aaptResourceCollector.getRawName(rType, rDotTxtEntry.name); if (StringUtil.isBlank(rawName)) { rawName = rDotTxtEntry.name; } publicWriter.println("<public type=\"" + rType + "\" name=\"" + rawName + "\" id=\"" + rDotTxtEntry.idValue.trim() + "\" />"); } Set<String> ignoreIdSet = aaptResourceCollector.getIgnoreIdSet(); for (RDotTxtEntry rDotTxtEntry : set) { if (rType.equals(RType.ID) && !ignoreIdSet.contains(rDotTxtEntry.name)) { idsWriter.println("<item type=\"" + rType + "\" name=\"" + rDotTxtEntry.name + "\"/>"); } } } idsWriter.flush(); publicWriter.flush(); } idsWriter.println("</resources>"); publicWriter.println("</resources>"); } catch (Exception e) { throw new PatchUtilException(e); } finally { if (idsWriter != null) { idsWriter.flush(); idsWriter.close(); } if (publicWriter != null) { publicWriter.flush(); publicWriter.close(); } } }
回應文初的問題二與問題四。開啟 proguard 時執行,做的事情很明確:套用 mapping 檔,並 keep 住一批關鍵類。順帶說明,把類釘在主 dex 的簡易做法之一,就是在混淆配置裡 keep 它,避免混淆改名導致 main dex 的 keep 規則失效。
@TaskAction def updateTinkerProguardConfig() { def file = project.file(PROGUARD_CONFIG_PATH) project.logger.error("try update tinker proguard file with ${file}") file.getParentFile().mkdirs() FileWriter fr = new FileWriter(file.path) String applyMappingFile = project.extensions.tinkerPatch.buildConfig.applyMapping if (shouldApplyMapping && FileOperation.isLegalFile(applyMappingFile)) { project.logger.error("try add applymapping ${applyMappingFile} to build the package") fr.write("-applymapping " + applyMappingFile) fr.write("\n") } else { project.logger.error("applymapping file ${applyMappingFile} is illegal, just ignore") } fr.write(PROGUARD_CONFIG_SETTINGS) fr.write("#your dex.loader patterns here\n") //they will removed when apply Iterable<String> loader = project.extensions.tinkerPatch.dex.loader for (String pattern : loader) { if (pattern.endsWith("*") && !pattern.endsWith("**")) { pattern += "*" } fr.write("-keep class " + pattern) fr.write("\n") } fr.close() applicationVariant.getBuildType().buildType.proguardFiles(file) def files = applicationVariant.getBuildType().buildType.getProguardFiles() project.logger.error("now proguard files is ${files}") }
先寫入 -applymapping,再寫入一批預設規則:
PROGUARD_CONFIG_SETTINGS = "-keepattributes *Annotation* \n" + "-dontwarn com.tencent.tinker.anno.AnnotationProcessor \n" + "-keep @com.tencent.tinker.anno.DefaultLifeCycle public class *\n" + "-keep public class * extends android.app.Application {\n" + " *;\n" + "}\n" + "\n" + "-keep public class com.tencent.tinker.loader.app.ApplicationLifeCycle {\n" + " *;\n" + "}\n" + "-keep public class * implements com.tencent.tinker.loader.app.ApplicationLifeCycle {\n" + " *;\n" + "}\n" + "\n" + "-keep public class com.tencent.tinker.loader.TinkerLoader {\n" + " *;\n" + "}\n" + "-keep public class * extends com.tencent.tinker.loader.TinkerLoader {\n" + " *;\n" + "}\n" + "-keep public class com.tencent.tinker.loader.TinkerTestDexLoad {\n" + " *;\n" + "}\n" + "\n"
最後再把 manifest task 記錄下來的 Application 與 com.tencent.tinker.loader.** 一併 keep 住,並把這個配置檔掛到 buildType 的 proguardFiles 上。
對應文初問題三。開啟 multiDexEnabled 時執行,本質上是生成一份 main dex keep 清單:
"-keep public class * implements com.tencent.tinker.loader.app.ApplicationLifeCycle {\n" + " *;\n" + "}\n" + "\n" + "-keep public class * extends com.tencent.tinker.loader.TinkerLoader {\n" + " *;\n" + "}\n" + "\n" + "-keep public class * extends android.app.Application {\n" + " *;\n" + "}\n"
Iterable<String> loader = project.extensions.tinkerPatch.dex.loader for (String pattern : loader) { if (pattern.endsWith("*")) { if (!pattern.endsWith("**")) { pattern += "*" } } lines.append("-keep class " + pattern + " {\n" + " *;\n" + "}\n") .append("\n") }
遍歷的 loader 集合,正是 TinkerManifestTask 當初寫入的那份名單——兩個 task 在這裡完成了呼應。
核心只有一句:調用 Runner.tinkerPatch。
protected void tinkerPatch() { try { //gen patch ApkDecoder decoder = new ApkDecoder(config); decoder.onAllPatchesStart(); decoder.patch(config.mOldApkFile, config.mNewApkFile); decoder.onAllPatchesEnd(); //gen meta file and version file PatchInfo info = new PatchInfo(config); info.gen(); //build patch PatchBuilder builder = new PatchBuilder(config); builder.buildPatch(); } catch (Throwable e) { e.printStackTrace(); goToError(); } }
拆成三段:生成各類 patch、生成 meta 檔與 version 檔(本質是往 assets 目錄寫一批鍵值對,包含 tinkerId 與 configField 相關資訊)、打包。
從 apk 的組成看,需要比對的對象大致是 dex、res、so 三類:
public boolean patch(File oldFile, File newFile) throws Exception { //check manifest change first manifestDecoder.patch(oldFile, newFile); unzipApkFiles(oldFile, newFile); Files.walkFileTree(mNewApkDir.toPath(), new ApkFilesVisitor(config, mNewApkDir.toPath(), mOldApkDir.toPath(), dexPatchDecoder, soPatchDecoder, resPatchDecoder)); soPatchDecoder.onAllPatchesEnd(); dexPatchDecoder.onAllPatchesEnd(); manifestDecoder.onAllPatchesEnd(); resPatchDecoder.onAllPatchesEnd(); //clean resources dexPatchDecoder.clean(); soPatchDecoder.clean(); resPatchDecoder.clean(); return true; }
仔細看會發現有四個 decoder,多出來的 manifestDecoder 並不是用來做 diff 的,而是校驗:目前 Tinker 不支持四大組件的新增,manifest 中不允许出現新組件;另外 minSdkVersion 低於 14 時只允許 dexMode 使用 jar 模式。manifest 的解析基於第三方庫 apk-parser。
接著解壓兩個 apk,目錄分別是 build/intermediates/outputs/old apk名稱/ 與 build/intermediates/outputs/app-debug/,然後以 newApk 的解壓目錄為基準逐檔比對:
Files.walkFileTree( mNewApkDir.toPath(), new ApkFilesVisitor( config, mNewApkDir.toPath(), mOldApkDir.toPath(), dexPatchDecoder, soPatchDecoder, resPatchDecoder));
@Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Path relativePath = newApkPath.relativize(file); // 在oldApkDir中找到該文件 Path oldPath = oldApkPath.resolve(relativePath); File oldFile = null; if (oldPath.toFile().exists()) { oldFile = oldPath.toFile(); } String patternKey = relativePath.toString().replace("\\", "/"); if (Utils.checkFileInPattern(config.mDexFilePattern, patternKey)) { dexDecoder.patch(oldFile, file.toFile()); } if (Utils.checkFileInPattern(config.mSoFilePattern, patternKey)) { soDecoder.patch(oldFile, file.toFile()); } if (Utils.checkFileInPattern(config.mResFilePattern, patternKey)) { resDecoder.patch(oldFile, file.toFile()); } return FileVisitResult.CONTINUE; }
在舊包裡找不到就是新增檔;找到了則比 md5,不一致就認為有改動,按類型分派給對應 decoder。各類檔的匹配規則都是可配置的。
public boolean patch(final File oldFile, final File newFile) { final String dexName = getRelativeDexName(oldFile, newFile); // 檢查loader class,省略了拋異常的一些代碼 excludedClassModifiedChecker.checkIfExcludedClassWasModifiedInNewDex(oldFile, newFile); File dexDiffOut = getOutputPath(newFile).toFile(); final String newMd5 = getRawOrWrappedDexMD5(newFile); if (oldFile == null || !oldFile.exists() || oldFile.length() == 0) { hasDexChanged = true; copyNewDexAndLogToDexMeta(newFile, newMd5, dexDiffOut); return true; } final String oldMd5 = getRawOrWrappedDexMD5(oldFile); if ((oldMd5 != null && !oldMd5.equals(newMd5)) || (oldMd5 == null && newMd5 != null)) { hasDexChanged = true; if (oldMd5 != null) { collectAddedOrDeletedClasses(oldFile, newFile); } } RelatedInfo relatedInfo = new RelatedInfo(); relatedInfo.oldMd5 = oldMd5; relatedInfo.newMd5 = newMd5; oldAndNewDexFilePairList.add(new AbstractMap.SimpleEntry<>(oldFile, newFile)); dexNameToRelatedInfoMap.put(dexName, relatedInfo); return true; }
開場那句 checkIfExcludedClassWasModifiedInNewDex 是硬性校驗:按 config.mDexLoaderPattern 過濾出 loader 相關類,要求 deletedClassInfos、addedClassInfos、changedClassInfosMap 三者全空——loader 類不允許新增、刪除、修改,且必須在主 dex。
之後:oldFile 不存在就当新增,直接拷到 build/intermediates/outputs/tinker_result/ 並記 log;存在則比 md5,不同就置 hasDexChanged 並收集增刪類資訊到 addedClassDescToDexNameMap 與 deletedClassDescToDexNameMap(後續會用到)。同時把這一對 dex 檔記進 oldAndNewDexFilePairList,並在 dexNameToRelatedInfoMap 裡存下 dexName 與 RelatedInfo 的映射。
值得注意:這個階段並沒有真正對有改動的 dex 做 diff,只拷了新增檔。真正的 diff 留到 onAllPatchesEnd。
soDecoder 實際上是 BsDiffDecoder:
@Override public boolean patch(File oldFile, File newFile) { String newMd5 = MD5.getMD5(newFile); File bsDiffFile = getOutputPath(newFile).toFile(); if (oldFile == null || !oldFile.exists()) { FileOperation.copyFileUsingStream(newFile, bsDiffFile); writeLogFiles(newFile, null, null, newMd5); return true; } String oldMd5 = MD5.getMD5(oldFile); if (oldMd5.equals(newMd5)) { return false; } if (!bsDiffFile.getParentFile().exists()) { bsDiffFile.getParentFile().mkdirs(); } BSDiff.bsdiff(oldFile, newFile, bsDiffFile); //超過80%,返回false if (Utils.checkBsDiffFileSize(bsDiffFile, newFile)) { writeLogFiles(newFile, oldFile, bsDiffFile, newMd5); } else { FileOperation.copyFileUsingStream(newFile, bsDiffFile); writeLogFiles(newFile, null, null, newMd5); } return true; }
新增檔直接拷貝;有改動則跑 bsdiff。有意思的是後面那個判斷:如果補丁檔已經超過新檔的 80%,說明差異實在太大,補丁沒有意義,於是直接把新檔拷過去覆蓋剛生成的 patch。所以 so 的三種結局是:新增→拷新檔;改動且補丁超過 80%→拷新檔;改動且補丁在 80% 以內→保留補丁。
@Override public boolean patch(File oldFile, File newFile) throws IOException, TinkerPatchException { String name = getRelativePathStringToNewFile(newFile); File outputFile = getOutputPath(newFile).toFile(); if (oldFile == null || !oldFile.exists()) { FileOperation.copyFileUsingStream(newFile, outputFile); addedSet.add(name); writeResLog(newFile, oldFile, TypedValue.ADD); return true; } String newMd5 = MD5.getMD5(newFile); String oldMd5 = MD5.getMD5(oldFile); if (oldMd5 != null && oldMd5.equals(newMd5)) { return false; } if (Utils.checkFileInPattern(config.mResIgnoreChangePattern, name)) { Logger.d("found modify resource: " + name + ", but it match ignore change pattern, just ignore!"); return false; } if (name.equals(TypedValue.RES_MANIFEST)) { Logger.d("found modify resource: " + name + ", but it is AndroidManifest.xml, just ignore!"); return false; } if (name.equals(TypedValue.RES_ARSC)) { if (AndroidParser.resourceTableLogicalChange(config)) { Logger.d("found modify resource: " + name + ", but it is logically the same as original new resources.arsc, just ignore!"); return false; } } dealWithModeFile(name, newMd5, oldFile, newFile, outputFile); return true; }
除了新增與 md5 相同兩種情況,還有幾類被刻意跳過:命中 ignoreChangePattern 的檔、AndroidManifest.xml,以及「邏輯上並未真正變化」的 resources.arsc(這一步的判斷很關鍵,因為前面資源 ID 固化的工作正是為了讓 arsc 保持穩定)。
private boolean dealWithModeFile(String name, String newMd5, File oldFile, File newFile, File outputFile) { if (checkLargeModFile(newFile)) { if (!outputFile.getParentFile().exists()) { outputFile.getParentFile().mkdirs(); } BSDiff.bsdiff(oldFile, newFile, outputFile); if (Utils.checkBsDiffFileSize(outputFile, newFile)) { LargeModeInfo largeModeInfo = new LargeModeInfo(); largeModeInfo.path = newFile; largeModeInfo.crc = FileOperation.getFileCrc32(newFile); largeModeInfo.md5 = newMd5; largeModifiedSet.add(name); largeModifiedMap.put(name, largeModeInfo); writeResLog(newFile, oldFile, TypedValue.LARGE_MOD); return true; } } modifiedSet.add(name); FileOperation.copyFileUsingStream(newFile, outputFile); writeResLog(newFile, oldFile, TypedValue.MOD); return false; }
先判斷是否為「大改檔」(預設 100K 以上,可配置)。非大檔直接拷新檔並記 MOD;大檔則走 bsdiff,同樣檢查 80% 門檻,超了就退回拷新檔。整體思路與 so 一致。
# DexDiffDecoder @Override public void onAllPatchesEnd() throws Exception { if (!hasDexChanged) { Logger.d("No dexes were changed, nothing needs to be done next."); return; } generatePatchInfoFile(); addTestDex(); }
private void generatePatchInfoFile() throws IOException { generatePatchedDexInfoFile(); logDexesToDexMeta(); checkCrossDexMovingClasses(); }
逐對處理之前記下的 dex:
private void generatePatchedDexInfoFile() { for (AbstractMap.SimpleEntry<File, File> oldAndNewDexFilePair : oldAndNewDexFilePairList) { File oldFile = oldAndNewDexFilePair.getKey(); File newFile = oldAndNewDexFilePair.getValue(); final String dexName = getRelativeDexName(oldFile, newFile); RelatedInfo relatedInfo = dexNameToRelatedInfoMap.get(dexName); if (!relatedInfo.oldMd5.equals(relatedInfo.newMd5)) { diffDexPairAndFillRelatedInfo(oldFile, newFile, relatedInfo); } else { relatedInfo.newOrFullPatchedFile = newFile; relatedInfo.newOrFullPatchedMd5 = relatedInfo.newMd5; } } }
private void diffDexPairAndFillRelatedInfo(File oldDexFile, File newDexFile, RelatedInfo relatedInfo) { File tempFullPatchDexPath = new File(config.mOutFolder + File.separator + TypedValue.DEX_TEMP_PATCH_DIR); final String dexName = getRelativeDexName(oldDexFile, newDexFile); File dexDiffOut = getOutputPath(newDexFile).toFile(); ensureDirectoryExist(dexDiffOut.getParentFile()); // dex diff , 去除loader classes DexPatchGenerator dexPatchGen = new DexPatchGenerator(oldDexFile, newDexFile); dexPatchGen.setAdditionalRemovingClassPatterns(config.mDexLoaderPattern); dexPatchGen.executeAndSaveTo(dexDiffOut); relatedInfo.dexDiffFile = dexDiffOut; relatedInfo.dexDiffMd5 = MD5.getMD5(dexDiffOut); File tempFullPatchedDexFile = new File(tempFullPatchDexPath, dexName); try { new DexPatchApplier(oldDexFile, dexDiffOut).executeAndSaveTo(tempFullPatchedDexFile); Logger.d(String.format("Verifying if patched new dex is logically the same as original new dex: %s ...", getRelativeStringBy(newDexFile, config.mTempUnzipNewDir))); Dex origNewDex = new Dex(newDexFile); Dex patchedNewDex = new Dex(tempFullPatchedDexFile); checkDexChange(origNewDex, patchedNewDex); relatedInfo.newOrFullPatchedFile = tempFullPatchedDexFile; relatedInfo.newOrFullPatchedMd5 = MD5.getMD5(tempFullPatchedDexFile); } catch (Exception e) { e.printStackTrace(); throw new TinkerPatchException("Failed to generate temporary patched dex, which makes MD5 generating procedure of new dex failed, either.", e); } if (!tempFullPatchedDexFile.exists()) { throw new TinkerPatchException("can not find the temporary full patched dex file:" + tempFullPatchedDexFile.getAbsolutePath()); } Logger.d("\nGen %s for dalvik full dex file:%s, size:%d, md5:%s", dexName, tempFullPatchedDexFile.getAbsolutePath(), tempFullPatchedDexFile.length(), relatedInfo.newOrFullPatchedMd5); }
這段值得細看:先做 dex diff 生成補丁,然後立刻在本地用 DexPatchApplier 把「old dex + 補丁」合併成一個臨時 dex——等於在構建期就模擬了一遍客戶端的補丁應用過程,再用 checkDexChange 做類級別比對,確認合併結果與新包邏輯一致。這是能在 CI 階段攔住「補丁打出來卻合不回新包」這類事故的一道防線。
最後 addTestDex 會把一個 test.dex 拷進產物目錄並寫入 meta,它來自 tinker-patch-lib 的 resources,用途是在真機上驗證補丁是否生效。
private void addTestDex() throws IOException { String dexMode = "jar"; if (config.mDexRaw) { dexMode = "raw"; } final InputStream is = DexDiffDecoder.class.getResourceAsStream("/" + TEST_DEX_NAME); String md5 = MD5.getMD5(is, 1024); is.close(); String meta = TEST_DEX_NAME + "," + "" + "," + md5 + "," + md5 + "," + 0 + "," + 0 + "," + dexMode; File dest = new File(config.mTempResultDir + "/" + TEST_DEX_NAME); FileOperation.copyResourceUsingStream(TEST_DEX_NAME, dest); metaWriter.writeLineToInfoFile(meta); }
public PatchBuilder(Configuration config) { this.config = config; this.unSignedApk = new File(config.mOutFolder, PATCH_NAME + "_unsigned.apk"); this.signedApk = new File(config.mOutFolder, PATCH_NAME + "_signed.apk"); this.signedWith7ZipApk = new File(config.mOutFolder, PATCH_NAME + "_signed_7zip.apk"); this.sevenZipOutPutDir = new File(config.mOutFolder, TypedValue.OUT_7ZIP_FILE_PATH); } public void buildPatch() throws Exception { final File resultDir = config.mTempResultDir; if (resultDir.listFiles().length == 0) { return; } generateUnsignedApk(unSignedApk); signApk(unSignedApk, signedApk); use7zApk(signedApk, signedWith7ZipApk, sevenZipOutPutDir); if (!signedApk.exists()) { Logger.e("Result: final unsigned patch result: %s, size=%d", unSignedApk.getAbsolutePath(), unSignedApk.length()); } else { long length = signedApk.length(); Logger.e("Result: final signed patch result: %s, size=%d", signedApk.getAbsolutePath(), length); if (signedWith7ZipApk.exists()) { long length7zip = signedWith7ZipApk.length(); Logger.e("Result: final signed with 7zip patch result: %s, size=%d", signedWith7ZipApk.getAbsolutePath(), length7zip); if (length7zip > length) { Logger.e("Warning: %s is bigger than %s %d byte, you should choose %s at these time!", signedWith7ZipApk.getName(), signedApk.getName(), (length7zip - length), signedApk.getName()); } } } }
三步:把 tinker_result 目錄壓成 unsigned apk、用 jarsigner 簽名、再把簽名包解壓重壓成 7zip 版本。三個產物中,7zip 版通常更小,但如果它反而比簽名包大,日誌會提示你直接用簽名包就好。
回頭看那四個問題:資源 ID 漂移由 TinkerResourceIdTask 接管,混淆不穩定由 TinkerProguardConfigTask 用 applymapping 解決,主 dex 約束由 TinkerMultidexConfigTask 加上 dex 階段的 excludedClass 校驗雙保險,而 TinkerManifestTask 用 tinkerId 保證補丁與基準包的精準配對。所有這些,使用者只需要在 gradle 裡填幾個路徑。
Tinker 裡可挖的東西很多,項目本身也有很強的工程價值,推薦順著讀一讀《Tinker:技術的初心與堅持》《微信 Android 熱補丁實踐演進之路》《Android N 混合編譯與對熱補丁影響解析》等文章。文中若有疏漏,歡迎直接指出。
Android NDK 開發 Crash 錯誤定位
前言 Android 中的崩潰大致可分為未捕獲例外、ANR 與原生層崩潰。Java 層例外通常可從 logcat 堆疊追蹤,但 NDK 造成的閃退往往較難定位。 NDK
Android 開發者的加密入門指南:6 個值得信賴的加密工具庫
行動應用已經成為黑客眼中的肥肉,被盯上的 App 數量每天都在增加。原因很直接:App 裡裝著他們想要的東西——使用者資料。硬編碼在原始碼中的固定金鑰、以純文字形式躺在
深入剖析 Android 編譯慢的根因與加速方案
對 Android 開發者來說,隨着工程規模不斷膨脹,編譯時間也會一路變長。哪怕只是加了一行代碼,也要乾等數十秒才能看到效果,這種割裂感會嚴重打斷編碼節奏。 以往能加速編
Android UI 元件系列:WebView 網路檢視
Android 的網路功能十分強大,WebView 元件能直接載入網頁,可將其視為一個內建的瀏覽器。要實現這個功能,具體步驟如下: 1、在版面配置檔中宣告 WebView