您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發基礎

調試實戰:跟隨一次 UIKit Bug 的完整修復過程

編輯:iOS 開發基礎

沒人能寫出完美無瑕的代碼,但調試代碼這件事,我們都應該有能力做好。比起給一堆零散的小建議,我更想帶你親歷一次真正的 bug 修復——這是一個 UIKit 的 bug,我會完整展示自己理解、隔離並最終解決它的思路與流程。

問題

我收到一份 bug 反饋:快速點擊一個按鈕,在彈出並關閉一個 popover 的同時,父視圖控制器也被一起關掉了。所幸報告附了截圖,所以第一步——重現 bug——已經有人幫我做好了:

我的第一個猜測是:我們的代碼裡可能有 dismiss 視圖控制器的邏輯,誤把父視圖控制器也 dismiss 了。然而用 Xcode 集成的視圖調試功能一看,很明顯有一個全局的 UIDimmingView 作為 first responder 在響應點擊事件:

蘋果在 Xcode 6 中加入了調試視圖層次結構的功能,這一步很可能靈感來自廣受好評的 Reveal 和 Spark Inspector。相比 Xcode,它們在許多方面做得更好、功能更全。

使用 LLDB

在可視化調試問世之前,最常用的做法是通過 LLDB 的 po [[UIWindow keyWindow] recursiveDescription] 來查看層次結構,它能以文本形式打印出完整的視圖層次。

類似的,我們也可以用 po [[[UIWindow keyWindow] rootViewController] _printHierarchy] 來查看視圖控制器。這是蘋果在 iOS 8 中悄悄為 UIViewController 加入的一個私有輔助方法。

(lldb) po [[[UIWindow keyWindow] rootViewController] _printHierarchy], state: disappeared, view:  not in the window       | , state: disappeared, view:  not in the window    + , state: appeared, view: , presented with:    |    | , state: appeared, view:    |    |    | , state: appeared, view:    |    + , state: appeared, view: , presented with:    |    |    | , state: appeared, view:    |    |    |    | , state: appeared, view:

LLDB 非常強大,還能寫腳本。Facebook 發布過一套名為 Chisel 的 Python 腳本集合,為日常調試提供了大量便利。其中的 pviews 和 pvc 分別等價於視圖和視圖控制器的層次打印。Chisel 的視圖控制器樹和上面的方法輸出很相似,但同時還會顯示視圖尺寸。

我常用它來檢查響應鏈——雖然你可以對感興趣的對象手動循環執行 nextResponder,或添加一個類別輔助方法,但直接輸入 presponder object 依然是迄今為止最快的方式。

添加斷點

我們首先要找出究竟是哪段代碼 dismiss 了視圖控制器。最直覺的做法是在 viewWillDisappear: 上打個斷點,看看調用棧:

(lldb) bt * thread #1: tid = 0x1039b3, 0x004fab75 PSPDFCatalog`-[PSPDFViewController viewWillDisappear:](self=0x7f354400, _cmd=0x03b817bf, animated='\x01') + 85 at PSPDFViewController.m:359, queue = 'com.apple.main-thread', stop reason = breakpoint 1.1   * frame #0: 0x004fab75 PSPDFCatalog`-[PSPDFViewController viewWillDisappear:](self=0x7f354400, _cmd=0x03b817bf, animated='\x01') + 85 at PSPDFViewController.m:359     frame #1: 0x033ac782 UIKit`-[UIViewController _setViewAppearState:isAnimating:] + 706     frame #2: 0x033acdf4 UIKit`-[UIViewController __viewWillDisappear:] + 106     frame #3: 0x033d9a62 UIKit`-[UINavigationController viewWillDisappear:] + 115     frame #4: 0x033ac782 UIKit`-[UIViewController _setViewAppearState:isAnimating:] + 706     frame #5: 0x033acdf4 UIKit`-[UIViewController __viewWillDisappear:] + 106     frame #6: 0x033c46a1 UIKit`-[UIViewController(UIContainerViewControllerProtectedMethods) beginAppearanceTransition:animated:] + 200     frame #7: 0x03380ad8 UIKit`__56-[UIPresentationController runTransitionForCurrentState]_block_invoke + 594     frame #8: 0x033b47ab UIKit`__40+[UIViewController _scheduleTransition:]_block_invoke + 18     frame #9: 0x0327a0ce UIKit`___afterCACommitHandler_block_invoke + 15     frame #10: 0x0327a079 UIKit`_applyBlockToCFArrayCopiedToStack + 415     frame #11: 0x03279e8e UIKit`_afterCACommitHandler + 545     frame #12: 0x060669de CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 30     frame #20: 0x032508b6 UIKit`UIApplicationMain + 1526     frame #21: 0x000a119d PSPDFCatalog`main(argc=1, argv=0xbffcd65c) + 141 at main.m:15 (lldb)

用 LLDB 的 bt 命令可以打印斷點處的調用棧;bt all 效果相同,但會打印所有線程的狀態,而不僅限當前線程。

看這個棧可以發現,視圖控制器已經在 dismiss 途中——因為該方法是在預定的動畫裡被調用的,所以我們需要把斷點打得更靠前一些。這裡我們關注的是對 -[UIViewController dismissViewControllerAnimated:completion:] 的調用。於是在 Xcode 的斷點列表裡加一個符號斷點,重新跑一遍示例。

Xcode 的斷點功能非常強大,能加條件、跳過計數,還能自定義動作(如播放音效、自動繼續等)。雖然它們能省下不少時間,但這裡用不上:

(lldb) bt * thread #1: tid = 0x1039b3, 0x033bb685 UIKit`-[UIViewController dismissViewControllerAnimated:completion:], queue = 'com.apple.main-thread', stop reason = breakpoint 7.1   * frame #0: 0x033bb685 UIKit`-[UIViewController dismissViewControllerAnimated:completion:]     frame #1: 0x03a7da2c UIKit`-[UIPopoverPresentationController dimmingViewWasTapped:] + 244     frame #2: 0x036153ed UIKit`-[UIDimmingView handleSingleTap:] + 118     frame #3: 0x03691287 UIKit`_UIGestureRecognizerSendActions + 327     frame #4: 0x0368fb04 UIKit`-[UIGestureRecognizer _updateGestureWithEvent:buttonEvent:] + 561     frame #5: 0x03691b4d UIKit`-[UIGestureRecognizer _delayedUpdateGesture] + 60     frame #6: 0x036954ca UIKit`___UIGestureRecognizerUpdate_block_invoke661 + 57     frame #7: 0x0369538d UIKit`_UIGestureRecognizerRemoveObjectsFromArrayAndApplyBlocks + 317     frame #8: 0x03689296 UIKit`_UIGestureRecognizerUpdate + 3720     frame #9: 0x032a226b UIKit`-[UIWindow _sendGesturesForEvent:] + 1356     frame #10: 0x032a30cf UIKit`-[UIWindow sendEvent:] + 769     frame #21: 0x032508b6 UIKit`UIApplicationMain + 1526     frame #22: 0x000a119d PSPDFCatalog`main(argc=1, argv=0xbffcd65c) + 141 at main.m:15

果然如我們所料!正如預期,全屏 UIDimmingView 收到了我們的觸摸,在 handleSingleTap: 中處理後,轉發到 UIPopoverPresentationController 的 dimmingViewWasTapped: 方法來 dismiss 視圖控制器(本該如此)。然而——當我們快速點擊時,這個斷點被命中了兩次。難道有第二個 dimming 視圖?還是說調用的是同一個實例?由於斷點停在只有匯編的狀態,調 po self 是行不通的。

調用約定入門

憑藉對匯編和函數調用約定的基礎知識,我們仍能拿到 self 的值。iOS ABI Function Call Guide 以及模擬器所用的 Mac OS X ABI Function Call Guide 都是極好的參考資料。

我們知道每個 Objective-C 方法都有兩個隱式參數:self 和 _cmd,所以我們要做的就是取棧上的第一個對象。在 32-bit 架構中,棧信息保存在 $esp 裡,因此在 Objective-C 方法中可以用 po *(int*)($esp+4) 取 self,用 p (SEL)*(int*)($esp+8) 取 _cmd。$esp 裡的第一個值是返回地址,隨後的變量依次保存在 $esp+12、$esp+16 等位置。

x86-64 架構(用於那些含 arm64 芯片的 iPhone 設備的模擬器)提供了更多寄存器,變量放在 $rdi、$rsi、$rdx、$rcx、$r8、$r9 中,其後的變量則在 $rbp 棧上,從 $rbp+16、$rbp+24 開始依次排列。

armv7 架構的變量通常放在 $r0、$r1、$r2、$r3 中,之後移到 $sp 棧上:

(lldb) po $r0 (lldb) p (SEL)$r1 (SEL) $1 = "dismissViewControllerAnimated:completion:"

arm64 與 armv7 類似,但因為寄存器更多,$x0 到 $x7 整個范圍都用來存放變量,之後才回到棧寄存器 $sp。

想更深入地了解 x86、x86-64 的棧布局,可以閱讀 AMD64 ABI Draft。

使用 Runtime

追蹤方法執行的另一種思路是重寫方法,在調用父類前插入日志。然而手動 swizzling 雖調試方便,從花費的時間上看其實效率不高。前陣子我寫了一個小巧的庫叫 Aspects,專門幹這件事。它可以用於生產代碼,但我大多數時候只拿它來調試和寫測試用例。(若你對 Aspects 感興趣,可以點此了解更多。)

#import "Aspects.h" [UIPopoverPresentationController aspect_hookSelector:NSSelectorFromString(@"dimmingViewWasTapped:")                                          withOptions:0                                            usingBlock:^(id  info, UIView *tappedView) {     NSLog(@"%@ dimmingViewWasTapped:%@", info.instance, tappedView); } error:NULL];

這裡我們為 dimmingViewWasTapped: 加了一個鉤子。它是私有方法,因此我們用 NSSelectorFromString。你可以驗證方法是否存在,並借助 iOS Runtime Headers 查到幾乎每個框架類的其他私有與公共方法。這個項目利用了一個事實:方法在運行時無法真正被隱藏,它會在所有類中查找方法,從而生成一份比蘋果官方更完整的頭文件。(當然,調用私有 API 並不是好主意——這裡只是為了弄清楚到底發生了什麼。)

在鉤子方法的日志中,我們得到:

PSPDFCatalog[84049:1079574]  dimmingViewWasTapped:   PSPDFCatalog[84049:1079574]  dimmingViewWasTapped:

可以看到對象地址完全相同,所以我們可憐的 dimming 視圖確實被調用了兩次。我們還能用 Aspects 看看究竟是哪個控制器被 dismiss:

[UIViewController aspect_hookSelector:@selector(dismissViewControllerAnimated:completion:)                          withOptions:0                           usingBlock:^(id  info) {     NSLog(@"%@ dismissed.", info.instance); } error:NULL];
2014-11-22 19:24:51.900 PSPDFCatalog[84210:1084883]  dismissed.   2014-11-22 19:24:52.209 PSPDFCatalog[84210:1084883]  dismissed.

兩次 dimming 視圖都調用了主導航控制器的 dismiss 方法。如果子視圖控制器存在,視圖控制器的 dismissViewControllerAnimated:completion: 會把 dismiss 請求轉發給子視圖控制器,否則就 dismiss 自己。所以第一次 dismiss 發生在 popover 上,而第二次,導航控制器本身被 dismiss 了。

尋找臨時方案

現在我們搞清楚了「發生了什麼」,接下來該追問「為何會發生」。UIKit 是閉源的,但我們可以借助 Hopper 這類反匯編工具來解讀 UIKit 的匯編,仔細看看 UIPopoverPresentationController 裡到底發生了什麼。你可以在 /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/System/Library/Frameworks/UIKit.framework 找到二進制文件,然後在 Hopper 裡用 File -> Read Executable to Disassemble... 讓它遍歷並符號化整個二進制。32-bit 的反匯編最成熟,選 32-bit 文件能拿到最好的結果。Hex-Rays 出品的 IDA 是另一款強大但昂貴的反匯編工具,通常能給出更好的結果:

具備一些匯編基礎知識對讀懂代碼很有幫助。不過你也可以用偽代碼視圖,得到類似 C 代碼的結果:

讀偽代碼讓人大開眼界。這裡有兩條代碼路徑:一條在 delegate 實現了 popoverPresentationControllerShouldDismissPopover: 時走,另一條在沒實現時走——兩條路徑其實相當不同。在 delegate 實現了該方法的那條路徑裡,含有 if (controller.presented && !controller.dismissing) 的判斷;而另一條路徑(也就是我們當前實際走進去的)卻沒有,並總是調用 dismiss。憑著這些內部信息,我們可以嘗試實現自己的 UIPopoverPresentationControllerDelegate 來繞開這個 bug:

- (BOOL)popoverPresentationControllerShouldDismissPopover:(UIPopoverPresentationController *)popoverPresentationController {     return YES; }

我第一次嘗試把創建 popover 的主視圖控制器設為 delegate,結果它把 UIPopoverController 弄壞了。雖然文檔沒提,但 popover 控制器會在 _setupPresentationController 中把自己設為 delegate,移掉它會造成破壞。之後,我改用一個 UIPopoverController 的子類,直接把上面那個方法加了進去。這兩個類之間的聯系並沒有文檔化,我們的方案依賴了這種未公開的行為;不過這個實現與默認行為一致,純粹是為了解決問題,因此是經得起時間考驗的。

反饋 Radar

現在別停下。我們通常會為這類繞過問題的方案寫點文檔,但還有件重要的事:給 Apple 提交一個 radar。這麼做有額外好處——它能幫你驗證自己是否真正理解這個 bug、代碼有沒有其他副作用;日後若放棄支持該 iOS 版本,你也能輕易回滾代碼,並測試這個 radar 是否已被修復。

// UIPopoverController 是它的 contentViewController,即 UIPopoverPresentationController 的默認 delegate // // 這裡有一個 bug:當雙擊 diming 視圖時,presentation 視圖控制器將調用兩次 // dismissViewControllerAnimated:completion:,並 dismiss 掉它的父控制器. // // 通過實現這個 delegate 可以讓代碼運行另一條正確地檢查了是否正在 dismiss 的代碼路徑 // rdar://problem/19067761 - (BOOL)popoverPresentationControllerShouldDismissPopover:(UIPopoverPresentationController *)popoverPresentationController {     return YES; }

寫一個 radar 其實是件頗有意思的挑戰,並不像你想的那麼耗時。附上一個示例,能幫那些忙碌的蘋果工程師省不少力;沒有示例,radar 很可能被推遲甚至直接忽略。我為這個問題寫了個約 50 行代碼的示例,還附上了一些說明與解決方案。單視圖模板通常是做示例最快的起點。

說實話,蘋果的 Radar 網頁並不好用,不過你可以繞開它。QuickRadar 是一款提交 radar 的優秀 Mac 前端,還會自動把副本提交到 OpenRadar,復制 radar 也極為方便。你應該馬上下載它;另外,如果你也覺得示例裡這樣的 bug 值得修復,可以復制 rdar://19067761。

並非所有問題都能靠簡單方案繞過,但這套步驟能幫你找到更好的解法,或至少幫助你理解「某些事情為何會發生」。

參考

iOS Debugging Magic (TN2239)
iOS Runtime Headers
Debugging Tips for iOS Developers
Hopper — a reverse engineering tool
IDA by Hex-Rays
Aspects — Delightful, simple library for aspect-oriented programming.
Building Aspects
Event Delivery: The Responder Chain
Chisel — a collection of LLDB commands to assist debugging iOS apps
Where the top of the stack is on x86
Stack frame layout on x86-64
AMD64 ABI draft
ARM 64-bit Architecture
Decompiling assembly: IDA vs Hopper

原文 Debugging: A Case Study

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved