1. 查看函數對應的匯編代碼
gdb -batch -ex "disas /m <function-name>" "./<binary-name>"
作用:查看<binary-name>程序里<function-name>函數對應的匯編代碼,"/m"修飾符同時顯示源代碼。
當然,你也可以選擇用objdump;相比之下,我更喜歡gdb,因為我通常只是對某一個函數的匯編代碼感興趣。
2. 關閉new thread / thread exited消息
調試多線程程序時,經常會被new thread / thread exited的消息刷屏,分散調試者的注意力。
可以通過修改gdb配置文件(一般是"~/.gdbinit"文件),關閉此信息。
set print thread-events off
3. 屏蔽gdb signal信息
gdb調試有時會遇到“Program received signal SIGSEGV, Segmentation fault.”的中斷,執行continue之后,很快又會斷住。
解決方法是忽略相應信號,在gdb中輸入如下指令
# 查看SIGSEGV信號狀態 handle SIGSEGV # 關閉print handle SIGSEGV noprint
參考:https://blog.csdn.net/ma100/article/details/62424408
4. 斷點命令列表
當gdb遇到斷點時,幾乎總是要查看某個變量。如果反復遇到同一個斷點,將反復查看相同的變量。
如果能讓gdb在每次到達某個斷點時,自動執行一組命令,豈不完美。斷點命令列表就是用來做這件事的。
(gdb) break main.cc:13 # 此時,你會獲得一個斷點號<breakpoint-number> (gdb) commands <breakpoint-number> >silent >print <var-name> >continue >end
(gdb)
需要額外解釋的一點,silent命令經常是命令列表的第一條命令,以使gdb更安靜地觸發斷點。
5. 調度器鎖
按說在gdb里是可以通過 print 或 call 來達到調用函數的目的的,但在真實生產環境中(多線程程序的調試),往往會遇到下面的錯誤:
"The program stopped in another thread while making a function call from GDB."
出現這個錯誤的原因是,你在斷點處調用函數的同時,其他線程也跟着運行起來了,並且有一個線程遇到了這個斷點。解決的方法很簡單,gdb里有一個叫做scheduler-locking的東西,在 print 或 call 之前置為“on”,打印完之后再恢復即可。
我在.gdbinit里增加了一個擴展的打印宏,幫助我完成這個事情。
define pp if $argc != 1 help pp else set scheduler-locking on print $arg0 set scheduler-locking step end end
補充一點,gdb默認的scheduler-locking模式是step,所以要記得恢復默認值。
關於scheduler-locking,gdb官方文檔是這么介紹的
set scheduler-locking mode
Set the scheduler locking mode. It applies to normal execution, record mode,
and replay mode. If it is off, then there is no locking and any thread may
run at any time. If on, then only the current thread may run when the inferior
is resumed. The step mode optimizes for single-stepping; it prevents other
threads from preempting the current thread while you are stepping, so that the
focus of debugging does not change unexpectedly.show scheduler-locking
Display the current scheduler locking mode.
6. 我的簡易版gdb配置樣例
set print thread-events off define pac if $argc != 1 help pac else print $arg0 continue end end document pac Print And Continue usage: pac <var> end define pp if $argc != 1 help pp else set scheduler-locking on print $arg0 set scheduler-locking step end end document pp Print in scheduler-locking mode usage: pp <var> end
7. 臨時向文件輸出信息
這種情況往往是因為輸出信息較多,刷屏了,或者怎樣。
比如,要用到info functions輸出所有函數,結果往往一屏顯示不了,可以將其輸出到文件。
(gdb) set logging file <file name> (gdb) set logging on (gdb) info functions (gdb) set logging off
8. 設置動態鏈接庫搜索路徑
(gdb) set solib-search-path <path>
(gdb) show solib-search-path
后續,還有一塊比較大的內容是pretty-printer,有機會可以單獨寫一篇來介紹相關內容。