常用GDB指令

概述

GDB是一個由GNU開源組織發(fā)布的、UNIX/Linux操作系統(tǒng)下的、基于命令行的、功能強大的程序調(diào)試工具。

一般來說,GDB主要幫忙你完成下面四個方面的功能:

  1. 啟動你的程序,可以按照你的自定義的要求隨心所欲的運行程序。
  2. 可讓被調(diào)試的程序在你所指定的調(diào)置的斷點處停住。(斷點可以是條件表達式)
  3. 當程序被停住時,可以檢查此時你的程序中所發(fā)生的事。
  4. 動態(tài)的改變你程序的執(zhí)行環(huán)境。

雖然沒有像VC、Eclipse、IDEA、Xcode等IDE那樣的圖形化操作環(huán)境,但是借助于調(diào)試命令GDB可以完成幾乎所有你想要的功能,而且GDB的命令操控特性也特別適用于UNIX/Linux的命令行開發(fā)環(huán)境。

本文不介紹GCC編譯器的編譯選項和CoreDump的配置,僅介紹部分日常開發(fā)中的常用調(diào)試命令 。

常用命令

  1. file <文件名>
    加載被調(diào)試的可執(zhí)行程序文件。因為一般都在被調(diào)試程序所在目錄下執(zhí)行GDB,因而文本名不需要帶路徑。
(gdb) file file-name
  1. attach <PID>
    關(guān)聯(lián)指定進程。
(gdb) attach 1024 //關(guān)聯(lián)進程號為1024的進程進行調(diào)試
  1. l
    List的簡寫,列出當前位置之后的10行代碼;list line_number: 列出line_number之后的十行代碼。
(gdb) l
  1. r
    Run的簡寫,運行被調(diào)試的程序。如果此前沒有下過斷點,則執(zhí)行完整個程序;如果有斷點,則程序暫停在第一個可用斷點處。
(gdb) r
  1. c
    Continue的簡寫,繼續(xù)執(zhí)行被調(diào)試程序,直至下一個斷點或程序結(jié)束。
(gdb) c
  1. b <行號>
    b <函數(shù)名稱>
    b *<函數(shù)名稱>
    b *<代碼地址>
    d [編號]

    b是Breakpoint的簡寫,設置斷點。兩可以使用“行號”“函數(shù)名稱”“執(zhí)行地址”等方式指定斷點位置。
    其中在函數(shù)名稱前面加*符號表示將斷點設置在“由編譯器生成的prolog代碼處”。如果不了解匯編,可以不予理會此用法。
    break ... if ...:條件中斷。
    d是Delete breakpoint的簡寫,刪除指定編號的某個斷點,或刪除所有斷點。斷點編號從1開始遞增。
(gdb) b 8
(gdb) b main
(gdb) b *main
(gdb) b *0x804835c
(gdb) d
  1. bt
    backtrace的簡寫,列出調(diào)用棧。
(gdb) bt
  1. s
    執(zhí)行一行源程序代碼,如果此行代碼中有函數(shù)調(diào)用,則進入該函數(shù)。相當于其它調(diào)試器中的“Step Into (單步跟蹤進入)”。
    這個命令必須在有源代碼調(diào)試信息的情況下才可以使用(GCC編譯時使用“-g”參數(shù))。
(gdb) s
  1. n
    執(zhí)行一行源程序代碼,此行代碼中的函數(shù)調(diào)用也一并執(zhí)行。相當于其它調(diào)試器中的“Step Over (單步跟蹤)”。
    這個命令必須在有源代碼調(diào)試信息的情況下才可以使用(GCC編譯時使用“-g”參數(shù))。
(gdb) n
  1. si
    si命令類似于s命令,但針對匯編指令。
(gdb) si
  1. ni
    ni命令類似于n命令,但針對匯編指令。
(gdb) ni
  1. p <變量名稱>
    Print的簡寫,顯示指定變量(臨時變量或全局變量)的值。
(gdb) p i
(gdb) p nGlobalVar
  1. x
    和print命令需要指定變量不同,x命令需要指定內(nèi)存地址。
(gdb) help x
Examine memory: x/FMT ADDRESS.
ADDRESS is an expression for the memory address to examine.
FMT is a repeat count followed by a format letter and a size letter.
Format letters are o(octal), x(hex), d(decimal), u(unsigned decimal),
  t(binary), f(float), a(address), i(instruction), c(char) and s(string).
Size letters are b(byte), h(halfword), w(word), g(giant, 8 bytes).
The specified number of objects of the specified size are printed
according to the format.
Defaults for format and size letters are those previously used.
Default count is 1.  Default address is following last thing printed
with this command or "print".
(gdb) x /6cb 0x804835c //打印地址0x804835c起始的內(nèi)存內(nèi)容,連續(xù)6個字節(jié),以字符格式輸出。
  1. display ...
    undisplay <編號>

    display,設置程序中斷后欲顯示的數(shù)據(jù)及其格式。
    例如,如果希望每次程序中斷后可以看到即將被執(zhí)行的下一條匯編指令,可以使用命令display /i $pc,其中 $pc 代表當前匯編指令,/i 表示以十六進行顯示。當需要關(guān)心匯編代碼時,此命令相當有用。
    undispaly,取消先前的display設置,編號從1開始遞增。
(gdb) display /i $pc
(gdb) undisplay 1
  1. i
    Info的簡寫,用于顯示各類信息,詳情請查閱“help i”。
(gdb) help i
info address -- Describe where symbol SYM is stored
info all-registers -- List of all registers and their contents
info args -- Argument variables of current stack frame
info auto-load -- Print current status of auto-loaded files
info auto-load-scripts -- Print the list of automatically loaded Python scripts
info auxv -- Display the inferior's auxiliary vector
info bookmarks -- Status of user-settable bookmarks
info breakpoints -- Status of specified breakpoints (all user-settable breakpoints if no argument)
info checkpoints -- IDs of currently known checkpoints
info classes -- All Objective-C classes
info common -- Print out the values contained in a Fortran COMMON block
info copying -- Conditions for redistributing copies of GDB
info dcache -- Print information on the dcache performance
info display -- Expressions to display when program stops
info extensions -- All filename extensions associated with a source language
info files -- Names of targets and files being debugged
info float -- Print the status of the floating point unit
info frame -- All about selected stack frame
info frame-filter -- List all registered Python frame-filters
info functions -- All function names
info handle -- What debugger does when program gets various signals
info inferiors -- IDs of specified inferiors (all inferiors if no argument)
info line -- Core addresses of the code for a source line
info locals -- Local variables of current stack frame
info macro -- Show the definition of MACRO
info macros -- Show the definitions of all macros at LINESPEC
info mem -- Memory region attributes
info os -- Show OS data ARG
info pretty-printer -- GDB command to list all registered pretty-printers
info probes -- Show available static probes
info proc -- Show /proc process information about any running process
info program -- Execution status of the program
info record -- Info record options
info registers -- List of integer registers and their contents
info scope -- List the variables local to a scope
info selectors -- All Objective-C selectors
info set -- Show all GDB settings
info sharedlibrary -- Status of loaded shared object libraries
info signals -- What debugger does when program gets various signals
info skip -- Display the status of skips
info source -- Information about the current source file
info sources -- Source files in the program
info stack -- Backtrace of the stack
info static-tracepoint-markers -- List target static tracepoints markers
info symbol -- Describe what symbol is at location ADDR
info target -- Names of targets and files being debugged
info tasks -- Provide information about all known Ada tasks
info terminal -- Print inferior's saved terminal status
info threads -- Display currently known threads
info tracepoints -- Status of specified tracepoints (all tracepoints if no argument)
info tvariables -- Status of trace state variables and their values
info type-printers -- GDB command to list all registered type-printers
info types -- All type names
info variables -- All global and static variable names
info vector -- Print the status of the vector unit
info vtbl -- Show the virtual function table for a C++ object
info warranty -- Various kinds of warranty you do not have
info watchpoints -- Status of specified watchpoints (all watchpoints if no argument)
info win -- List of all displayed windows
(gdb) i r
  1. q
    Quit的簡寫,退出GDB調(diào)試環(huán)境。
(gdb) q
  1. help [命令名稱]
    GDB幫助命令,提供對GDB名種命令的解釋說明。
    如果指定了“命令名稱”參數(shù),則顯示該命令的詳細說明;如果沒有指定參數(shù),則分類顯示所有GDB命令,供用戶進一步瀏覽和查詢。
(gdb) help display

學會使用幫助文檔

上述的命令其實都有更復雜的使用方法,可以通過help命令查看幫助,比如我們使用help p查看print命令的詳細說明。

(gdb) help p
Print value of expression EXP.
Variables accessible are those of the lexical environment of the selected
stack frame, plus all those whose scope is global or an entire file.

$NUM gets previous value number NUM.  $ and $$ are the last two values.
$$NUM refers to NUM'th value back from the last one.
Names starting with $ refer to registers (with the values they would have
if the program were to return to the stack frame now selected, restoring
all registers saved by frames farther in) or else to debugger
"convenience" variables (any such name not a known register).
Use assignment expressions to give values to convenience variables.

{TYPE}ADREXP refers to a datum of data type TYPE, located at address ADREXP.
@ is a binary operator for treating consecutive data objects
anywhere in memory as an array.  FOO@NUM gives an array whose first
element is FOO, whose second element is stored in the space following
where FOO is stored, etc.  FOO must be an expression whose value
resides in memory.

EXP may be preceded with /FMT, where FMT is a format letter
but no count or size letter (see "x" command).

上述幫助文檔提到@參數(shù),這個參數(shù)可以讓你像查看數(shù)組內(nèi)容一樣打印連續(xù)內(nèi)存的數(shù)據(jù)對象。“@”的左邊是第一個內(nèi)存的地址的值,“@”的右邊則你你想查看內(nèi)存的長度。例如,你的程序中有這樣的語句:

int *array = (int *) malloc (len * sizeof (int));

于是,在GDB調(diào)試過程中,你可以以如下命令顯示出這個動態(tài)數(shù)組的取值:

(gdb) p *array@len

動手實踐

從網(wǎng)上隨便扒了一段代碼保存為main.c。

#include <stdio.h>

int g_var = 0;

static int _add(int a, int b) {
    printf("_add callad, a:%d, b:%d\n", a, b);
    return a+b;
}

int main(void) {
    int n = 1;
    
    printf("one n=%d, g_var=%d\n", n, g_var);
    ++n;
    --n;
    
    g_var += 20;
    g_var -= 10;
    n = _add(1, g_var);
    printf("two n=%d, g_var=%d\n", n, g_var);
    
    return 0;
}

編譯

記得加-g參數(shù)

gcc -g -Wall -o main main.c

執(zhí)行

結(jié)果如下:

./main
one n=1, g_var=0
_add callad, a:1, b:10
two n=11, g_var=10

開始調(diào)試

gdb main
GNU gdb (GDB) Red Hat Enterprise Linux 7.6.1-94.el7
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-redhat-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /media/sf_temp/gdb-sample/main...(no debugging symbols found)...done.
  1. l查看源碼
(gdb) l
2   
3   int g_var = 0;
4   
5   static int _add(int a, int b) {
6       printf("_add callad, a:%d, b:%d\n", a, b);
7       return a+b;
8   }
9   
10  int main(void) {
11      int n = 1;
  1. b下斷點
(gdb) b 17
Breakpoint 1 at 0x40058d: file main.c, line 17.
(gdb) info b
Num     Type           Disp Enb Address            What
1       breakpoint     keep y   0x000000000040058d in main at main.c:17
  1. r運行
 (gdb) r
 Starting program: /media/sf_temp/gdb-sample/main 
 one n=1, g_var=0

 Breakpoint 1, main () at main.c:17
 17     g_var += 20;

斷點生效了,也可以試試條件斷點

 (gdb) b 17 if n==1
 Breakpoint 1 at 0x40058d: file main.c, line 17.
 (gdb) info b
 Num     Type           Disp Enb Address            What
 1       breakpoint     keep y   0x000000000040058d in main at main.c:17
         stop only if n==1
 (gdb) r
 Starting program: /media/sf_temp/gdb-sample/main 
 one n=1, g_var=0

 Breakpoint 1, main () at main.c:17
 17     g_var += 20;
  1. 試試Continue命令
 (gdb) b 19
 Breakpoint 2 at 0x4005ab: file main.c, line 19.
 (gdb) info b
 Num     Type           Disp Enb Address            What
 1       breakpoint     keep y   0x000000000040058d in main at main.c:17
    breakpoint already hit 1 time
 2       breakpoint     keep y   0x00000000004005ab in main at main.c:19
 (gdb) c
 Continuing.

 Breakpoint 2, main () at main.c:19
 19     n = _add(1, g_var);
  1. s進入_add函數(shù)
(gdb) s
_add (a=1, b=10) at main.c:6
6       printf("_add callad, a:%d, b:%d\n", a, b);
  1. n單步執(zhí)行
(gdb) n
_add callad, a:1, b:10
7       return a+b;
  1. p打印變量值
(gdb) p a+b
$1 = 11
  1. bt打印調(diào)用棧
(gdb) bt
#0  _add (a=1, b=10) at main.c:7
#1  0x00000000004005bd in main () at main.c:19
  1. info打印詳細信息
(gdb) info f
Stack level 0, frame at 0x7fffffffe4c0:
 rip = 0x400552 in _add (main.c:7); saved rip 0x4005bd
 called by frame at 0x7fffffffe4e0
 source language c.
 Arglist at 0x7fffffffe4b0, args: a=1, b=10
 Locals at 0x7fffffffe4b0, Previous frame's sp is 0x7fffffffe4c0
 Saved registers:
  rbp at 0x7fffffffe4b0, rip at 0x7fffffffe4b8
(gdb) info b
Num     Type           Disp Enb Address            What
1       breakpoint     keep y   0x000000000040058d in main at main.c:17
    breakpoint already hit 1 time
2       breakpoint     keep y   0x00000000004005ab in main at main.c:19
    breakpoint already hit 1 time
(gdb) info args
a = 1
b = 10
(gdb) info registers
rax            0x17 23
rbx            0x0  0
rcx            0x7fffffe9   2147483625
rdx            0x7ffff7dd8a00   140737351879168
rsi            0x7ffff7ff8000   140737354104832
rdi            0x0  0
rbp            0x7fffffffe4b0   0x7fffffffe4b0
rsp            0x7fffffffe4a0   0x7fffffffe4a0
r8             0x7ffff7a64938   140737348258104
r9             0x16 22
r10            0x0  0
r11            0x246    582
r12            0x400440 4195392
r13            0x7fffffffe5b0   140737488348592
r14            0x0  0
r15            0x0  0
rip            0x400552 0x400552 <_add+37>
eflags         0x202    [ IF ]
cs             0x33 51
ss             0x2b 43
ds             0x0  0
es             0x0  0
fs             0x0  0
gs             0x0  0
  1. x打印內(nèi)存信息
(gdb) p a
$4 = 1
(gdb) p &a
$5 = (int *) 0x7fffffffe4ac
(gdb) x /1db 0x7fffffffe4ac
0x7fffffffe4ac: 1
  1. q退出調(diào)試
 (gdb) q
 A debugging session is active.

     Inferior 1 [process 2916] will be killed.

 Quit anyway? (y or n) y

gdbtui

單純使用l命令查看源碼在單步調(diào)試過程中十分不方便,所以官方提供了gdbtui這個工具,可以將調(diào)試界面分欄,實時顯示源碼。

其他

CoreDump的調(diào)試也是必備技能,但是使用的主要命令逃不開上述幾個例子,更多的是要依賴個人經(jīng)驗,結(jié)合寄存器數(shù)據(jù)和內(nèi)存數(shù)據(jù)進行分析。

至于GDB的多線程多進程調(diào)試實際開發(fā)中使用機會很少, 也就老鳥會用上些。這部分可以調(diào)試,不好調(diào)試,一般一調(diào)估計小半天就走了。
常用的命令如下:

info threads
thread id
set follow-thread-mode parent/child
set scheduler-locking on/off
attach pid

分別是查看、切換、設置同步調(diào)試和加載進程。

默認設置下,在調(diào)試多進程程序時GDB只會調(diào)試主進程。但是GDB(>V7.0)支持多進程的分別以及同時調(diào)試,換句話說,GDB可以同時調(diào)試多個程序。只需要設置follow-fork-mode(默認值:parent)和detach-on-fork(默認值:on)即可。

follow-fork-mode detach-on-fork 說明
parent on 只調(diào)試主進程(GDB默認)
child on 只調(diào)試子進程
parent off 同時調(diào)試兩個進程,gdb跟主進程,子進程block在fork位置
child off 同時調(diào)試兩個進程,gdb跟子進程,主進程block在fork位置

設置方法:set follow-fork-mode [parent|child] set detach-on-fork [on|off]
查詢正在調(diào)試的進程:info inferiors
切換調(diào)試的進程: inferior <infer number>
添加新的調(diào)試進程: add-inferior [-copies n] [-exec executable] ,可以用file executable來分配給inferior可執(zhí)行文件。
其他:remove-inferiors infno, detach inferior

我是咕咕雞,一個還在不停學習的全棧工程師。
熱愛生活,喜歡跑步,家庭是我不斷向前進步的動力。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容