栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

Linux 知:gdb

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Linux 知:gdb

文章目录
  • 前言
  • 帮助
    • help 参数
    • help 命令
  • 详解
    • 简单示例
    • 自动补全
    • 运行shell程序
    • 调试程序
      • 调试未运行的程序
      • 调试已运行的程序
  • 拓展
  • 后语
  • 参考

前言

gdb - The GNU Debugger(GNU 调试器)

官方文档 | 官方手册 | 在线中文手册

帮助 help 参数

详情如下:

This is the GNU debugger.  Usage: 这是 GNU 调试器。用法:

    gdb [options] [executable-file [core-file or process-id]]
    gdb [options] --args executable-file [inferior-arguments ...]

Selection of debuggee and its files: 调试对象及其文件的选择:

  --args             Arguments after executable-file are passed to inferior 
                     可执行文件后的参数传递给 inferior
  --core=COREFILE    Analyze the core dump COREFILE. 分析核心转储 COREFILE。
  --exec=EXECFILE    Use EXECFILE as the executable. 使用 EXECFILE 作为可执行文件。
  --pid=PID          Attach to running process PID. 附加到正在运行的进程 PID。
  --directory=DIR    Search for source files in DIR. 在 DIR 中搜索源文件。
  --se=FILE          Use FILE as symbol file and executable file. 
                     使用 FILE 作为符号文件和可执行文件。
  --symbols=SYMFILE  Read symbols from SYMFILE. 从 SYMFILE 读取符号。
  --readnow          Fully read symbol files on first access. 首次访问时完全读取符号文件。
  --readnever        Do not read symbol files. 不读取符号文件。
  --write            Set writing into executable and core files. 
                     设置写入可执行文件和核心文件。

Initial commands and command files: 初始命令和命令文件:

  --command=FILE, -x Execute GDB commands from FILE. 从 FILE 执行 GDB 命令。
  --init-command=FILE, -ix
                     Like -x but execute commands before loading inferior. 
                     类似于 -x 但在加载inferior之前执行命令。
  --eval-command=COMMAND, -ex
                     Execute a single GDB command. 执行单个 GDB 命令。
                     May be used multiple times and in conjunction with --command. 
                     可以多次使用并与 --command 结合使用。
  --init-eval-command=COMMAND, -iex
                     Like -ex but before loading inferior. 像 -ex 但在加载inferior之前。
  --nh               Do not read ~/.gdbinit. 不读取 ~/.gdbinit。
  --nx               Do not read any .gdbinit files in any directory. 
                     不要读取任何目录中的任何 .gdbinit 文件。

Output and user interface control: 输出和用户界面控制:

  --fullname         Output information used by emacs-GDB interface. 
                     输出 emacs-GDB 接口使用的信息。
  --interpreter=INTERP
                     Select a specific interpreter / user interface 
                     选择特定的解释器/用户界面
  --tty=TTY          Use TTY for input/output by the program being debugged. 
                     将 TTY 用于正在调试的程序的输入/输出。
  -w                 Use the GUI interface. 使用 GUI 界面。
  --nw               Do not use the GUI interface. 不要使用 GUI 界面。
  --tui              Use a terminal user interface. 使用终端用户界面。
  --dbx              DBX compatibility mode.
  -q, --quiet, --silent
                     Do not print version number on startup. 不要在启动时打印版本号。

Operating modes: 操作模式:

  --batch            Exit after processing options. 处理选项后退出。
  --batch-silent     Like --batch, but suppress all gdb stdout output. 
                     与 --batch 类似,但禁止所有 gdb stdout 输出。
  --return-child-result
                     GDB exit code will be the child's exit code. 
                     GDB 退出代码将是孩子的退出代码。
  --configuration    Print details about GDB configuration and then exit. 
                     打印有关 GDB 配置的详细信息,然后退出。
  --help             Print this message and then exit. 打印此消息然后退出。
  --version          Print version information and then exit. 打印版本信息然后退出。

Remote debugging options: 远程调试选项:

  -b BAUDRATE        Set serial port baud rate used for remote debugging. 
                     设置用于远程调试的串口波特率。
  -l TIMEOUT         Set timeout in seconds for remote debugging.  
                     设置远程调试的超时时间(以秒为单位)。

Other options: 其他选项:

  --cd=DIR           Change current directory to DIR. 将当前目录更改为 DIR。
  --data-directory=DIR, -D
                     Set GDB's data-directory to DIR. 将 GDB 的数据目录设置为 DIR。

At startup, GDB reads the following init files and executes their commands:
在启动时,GDB 读取以下 init 文件并执行它们的命令:
   * system-wide init files: /etc/gdbinit 系统范围的初始化文件:/etc/gdbinit

For more information, type "help" from within GDB, or consult the 
有关更多信息,请在 GDB 中键入“help”,或查阅
GDB manual (available as on-line info or a printed manual). 
GDB 手册(可作为在线信息或印刷手册获得)。

Report bugs to .

You can ask GDB-related questions on the GDB users mailing list
(gdb@sourceware.org) or on GDB's IRC channel (#gdb on Freenode).
help 命令

启动gdb,然后输入help命令可以查看gdb中提供的调试命令信息,如下所示:

详情如下:

maminjie@fedora ~> gdb
GNU gdb (GDB) Fedora 10.1-13.fc34
Copyright (C) 2020 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later 
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".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
.
Find the GDB manual and other documentation resources online at:
    .

For help, type "help". 如需帮助,请键入"help"
Type "apropos word" to search for commands related to "word".
输入“apropos word”以搜索与“word”相关的命令。
(gdb) help
List of classes of commands: 命令类列表:

aliases -- User-defined aliases of other commands. 其他命令的用户定义别名
breakpoints -- Making program stop at certain points. 程序在某些点停止
data -- Examining data. 检查数据
files -- Specifying and examining files. 指定和检查文件
internals -- Maintenance commands. 维护命令
obscure -- Obscure features. 晦涩的特征
running -- Running the program. 运行程序
stack -- Examining the stack. 检查栈
status -- Status inquiries. 状态查询
support -- Support facilities. 支持设施
text-user-interface -- TUI is the GDB text based interface.
tracepoints -- Tracing of program execution without stopping the program.
               在不停止程序的情况下跟踪程序执行
user-defined -- User-defined commands. 用户定义的命令

Type "help" followed by a class name for a list of commands in that class.
键入“help”,后跟类名以获取该类中的命令列表
Type "help all" for the list of all commands.
键入“help all”,获取所有命令的列表
Type "help" followed by command name for full documentation.
输入“apropos word”以搜索与“word”相关的命令
Type "apropos word" to search for commands related to "word".
输入“apropos word”以搜索与“word”相关的命令
Type "apropos -v word" for full documentation of commands related to "word".
键入“apropos -v word”以获取与“word”相关的命令的完整文档。
Command name abbreviations are allowed if unambiguous.
如果没有歧义,则允许使用命令名称缩写
(gdb)

gdb中的命令很多,gdb把它们分成许多种类。help命令只是例出gdb的命令种类,如果要看种类中的命令,可以使用help 命令,如:help breakpoints,查看设置断点的所有命令。也可以直接 help 来查看命令的帮助。另外,这些命令同时还有很多缩写的别名。

  • help breakpoints
    (gdb) h breakpoints
    Making program stop at certain points.
    
    List of commands:
    
    awatch -- Set a watchpoint for an expression.
    break, brea, bre, br, b -- Set breakpoint at specified location.
    break-range -- Set a breakpoint for an address range.
    catch -- Set catchpoints to catch events.
    catch assert -- Catch failed Ada assertions, when raised.
    catch catch -- Catch an exception, when caught.
    catch exception -- Catch Ada exceptions, when raised.
    catch exec -- Catch calls to exec.
    catch fork -- Catch calls to fork.
    catch handlers -- Catch Ada exceptions, when handled.
    catch load -- Catch loads of shared libraries.
    catch rethrow -- Catch an exception, when rethrown.
    catch signal -- Catch signals by their names and/or numbers.
    catch syscall -- Catch system calls by their names, groups and/or numbers.
    catch throw -- Catch an exception, when thrown.
    catch unload -- Catch unloads of shared libraries.
    catch vfork -- Catch calls to vfork.
    clear, cl -- Clear breakpoint at specified location.
    commands -- Set commands to be executed when the given breakpoints are hit.
    condition -- Specify breakpoint number N to break only if COND is true.
    ...
    
  • help break
    (gdb) h break
    break, brea, bre, br, b
    Set breakpoint at specified location.
    break [PROBE_MODIFIER] [LOCATION] [thread THREADNUM] [if CONDITION]
    PROBE_MODIFIER shall be present if the command is to be placed in a
    probe point.  Accepted values are `-probe' (for a generic, automatically
    guessed probe type), `-probe-stap' (for a SystemTap probe) or
    `-probe-dtrace' (for a DTrace probe).
    LOCATION may be a linespec, address, or explicit location as described
    below.
    
    With no LOCATION, uses current execution address of the selected
    stack frame.  This is useful for breaking on return to a stack frame.
    
    THREADNUM is the number from "info threads".
    ConDITION is a boolean expression.
    ...
    
详解

调试器(例如 GDB)的目的是让您看到另一个程序在执行时“内部”发生了什么——或者另一个程序在它崩溃时正在做什么。

GDB 可以做四种主要的事情(加上其他支持这些的事情)来帮助你在行为中发现错误:

  • 启动您的程序,指定可能影响其行为的任何内容。
  • 使您的程序在指定条件下停止。
  • 当您的程序停止时,检查发生了什么。
  • 更改程序中的内容,以便您可以尝试纠正一个错误的影响并继续了解另一个错误。

您可以使用 GDB 调试用 C、C++、Fortran 和 Modula-2 编写的程序。

GDB 是用 shell 命令“gdb”调用的。启动后,它会从终端读取命令,直到您告诉它使用 GDB 命令“quit”退出。您可以使用命令“help”从 GDB 本身获得在线帮助。

你可以不带参数或选项运行“gdb”;但是启动 GDB 的最常用方法是使用一两个参数,指定一个可执行程序作为参数:

gdb program

您还可以从指定的可执行程序和核心文件开始:

gdb program core

相反,如果要调试正在运行的进程,您可以指定进程 ID 作为第二个参数或使用选项“-p”:

gdb program 1234
gdb -p 1234

会将 GDB 附加到进程 1234。使用选项 -p 可以省略程序文件名。

以下是一些最常用的 GDB 命令:

  • break [file:]function
    在函数(在文件中)设置断点。

  • run [arglist]
    启动您的程序(使用 arglist,如果指定)。

  • bt
    Backtrace:显示程序调用栈。

  • print expr
    显示表达式的值。

  • c
    继续运行您的程序(停止后,例如在断点处)。

  • next
    执行下一个程序行(停止后);跳过该行中的任何函数调用。

  • edit [file:]function
    查看当前停止的程序行。

  • list [file:]function
    在当前停止的位置附近键入程序的文本。

  • step
    执行下一个程序行(停止后);进入该行中的任何函数调用。

  • help [name]
    显示有关 GDB 命令名称的信息,或有关使用 GDB 的一般信息。

  • quit
    从 GDB 退出。

简单示例

源程序:test.c

#include 

int add(int a, int b)
{
    return a + b;
}

int main(void)
{
    int sum = 0;

    sum = add(100, 200);
    printf("%dn", sum);

    sum = add(1000, 2000);
    printf("%dn", sum);

    return 0;
}

编译生成执行文件:

$ gcc -g test.c -o test

编译时加入-g选项,可以将调试信息加到可执行程序中,方便后续gdb更好的调试。

使用GDB调试:

$ gdb test
gdb test
GNU gdb (Ubuntu 8.1-0ubuntu3.2) 8.1.0.20180409-git
Copyright (C) 2018 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later 
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-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
.
Find the GDB manual and other documentation resources online at:
.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from test...done.
(gdb) l        <-------------------- l命令相当于list,列出源码
1       #include 
2
3       int add(int a, int b)
4       {
5           return a + b;
6       }
7
8       int main(void)
9       {
10          int sum = 0;
(gdb)         <-------------------- 直接回车,表示重复上一次命令
11
12          sum = add(100, 200);
13          printf("%dn", sum);
14
15          sum = add(1000, 2000);
16          printf("%dn", sum);
17
18          return 0;
19      }
20
(gdb) break 10     <-------------------- 设置断点,在源程序第10行处
Breakpoint 1 at 0x666: file test.c, line 10.
(gdb) b add        <-------------------- 设置断点,在函数add()入口处
Breakpoint 2 at 0x654: file test.c, line 5.
(gdb) info break
Num     Type           Disp Enb Address            What
1       breakpoint     keep y   0x0000000000000666 in main at test.c:10
2       breakpoint     keep y   0x0000000000000654 in add at test.c:5
(gdb) r        <--------------------- 运行程序,run命令简写
Starting program: /home/canpool/work/gdb/test

Breakpoint 1, main () at test.c:10    <---------- 在断点处停住
10          int sum = 0;
(gdb) n        <--------------------- 单条语句执行,next命令简写
12          sum = add(100, 200);
(gdb) p sum    <--------------------- 打印变量sum的值,print命令简写
$1 = 0
(gdb) n

Breakpoint 2, add (a=100, b=200) at test.c:5
5           return a + b;
(gdb)
6       }
(gdb) p sum
No symbol "sum" in current context.
(gdb) n
main () at test.c:13
13          printf("%dn", sum);
(gdb) p sum
$2 = 300
(gdb) n
300
15          sum = add(1000, 2000);
(gdb) bt
#0  main () at test.c:15
(gdb) c       <--------------------- 继续运行程序,continue命令简写
Continuing.

Breakpoint 2, add (a=1000, b=2000) at test.c:5
5           return a + b;
(gdb) bt      <--------------------- 查看函数调用栈
#0  add (a=1000, b=2000) at test.c:5
#1  0x00000000080006a4 in main () at test.c:15
(gdb) c
Continuing.
3000
[Inferior 1 (process 400) exited normally]    <--------程序退出,调试结束
(gdb) q       <--------------------- 退出gdb
自动补全

gdb中,输入命令时,可以不用打全命令,只用打命令的前几个字符就可以了,当然,命令的前几个字符应该要标志着一个唯一的命令,在Linux下,你可以敲击两次TAB键来补齐命令的全称,如果有重复的,那么gdb会把其例出来。

  • 命令补全
    敲入b按两次TAB键,会看到所有b打头的命令
    (gdb) b
    backtrace    bookmark     break        break-range  bt
    (gdb) b
    
  • 函数补全
    只记得函数的前缀的话,输入前缀按两次TAB键,会看到所有签注的函数
    (gdb) b wait
    wait_builtin                   wait_for_background_pids.cold  wait_sigint_handler
    wait_for                       wait_for_job                   waitchld.constprop
    wait_for_any_job               wait_for_job.cold              waitpid
    wait_for_any_job.cold          wait_for_single_pid            waitpid@plt
    wait_for_background_pids       wait_sigint_cleanup
    (gdb) b wait
    
运行shell程序

在gdb环境中,你可以执行UNIX的shell的命令,shell命令的帮助信息如下:

(gdb) h shell
shell, !
Execute the rest of the line as a shell command.
With no arguments, run an inferior shell.

1)交互shell
shell命令不带参数的话,将进入交互模式:

(gdb) shell
[maminjie@fedora gdb]$ ls
test  test.c
[maminjie@fedora gdb]$ exit
exit
(gdb)

2)执行shell程序
可以通过下面的方式来执行shell程序:

shell 

调用UNIX的shell来执行 ,环境变量SHELL中定义的UNIX的shell将会被用来执行,如果SHELL没有定义,那就使用UNIX的标准shell:/bin/sh(在Windows中使用Command.com或 cmd.exe)

(gdb) shell echo $SHELL
/bin/bash
(gdb) shell pwd
/home/maminjie/work/gdb
(gdb) !ls
test  test.c
(gdb)

3)执行make命令

(gdb) h make
Run the ``make'' program using the rest of the line as arguments.

可以在gdb中执行make命令来重新build自己的程序,如下所示:

make 

这个命令等价于:“shell make ”。

调试程序 调试未运行的程序

几种方法如下:
1)以 gdb 方式启动gdb并加载程序
2)启动 gdb,然后以 file 方式加载程序
gdb会在PATH路径和当前目录中搜索 程序。
如要确认gdb是否读到程序,可使用l或list命令,看看gdb是否能列出源代码。

在gdb中,运行程序使用r或是run命令。程序的运行,你有可能需要设置下面四方面的事:
1)程序运行参数
set args 可指定运行时参数(如:set args 10 20 30 40 50)
show args 命令可以查看设置好的运行参数
2)运行环境
path

可设定程序的运行路径
show paths 查看程序的运行路径
set environment varname [=value] 设置环境变量。如:set env USER=canpool
show environment [varname] 查看环境变量
3)工作目录
cd 相当于shell的cd命令
pwd 显示当前的所在目录
4)程序的输入输出
info terminal 显示你程序用到的终端的模式。
使用重定向控制程序输出。如:run > outfile
tty命令可以指写输入输出的终端设备。如:tty /dev/ttyb

测试如下:

maminjie@fedora ~/w/gdb> gdb
...
For help, type "help".
Type "apropos word" to search for commands related to "word".
(gdb) l
No symbol table is loaded.  Use the "file" command.
(gdb) file test
Reading symbols from test...
(gdb) l
1       #include 
2
3       int add(int a, int b)
4       {
5           return a + b;
6       }
7
8       int main(void)
9       {
10          int sum = 0;
(gdb) q
maminjie@fedora ~/w/gdb> gdb test
...
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from test...
(gdb) l
1       #include 
2
3       int add(int a, int b)
4       {
5           return a + b;
6       }
7
8       int main(void)
9       {
10          int sum = 0;
(gdb)
调试已运行的程序

几种方法:
1)用ps查看正在运行的程序的PID(进程ID),然后用如下格式挂接正在运行的程序。

gdb  PID
gdb -p PID

2)先用 gdb 关联上程序,在gdb中用 attach PID 来挂接进程,并用 detach 来取消挂接的进程。

测试如下:

maminjie@fedora ~/w/gdb> ps
    PID TTY          TIME CMD
  16962 pts/1    00:00:00 bash
  16987 pts/1    00:00:00 fish
  18660 pts/1    00:00:00 ps
maminjie@fedora ~/w/gdb> gdb -p 16962
...
For help, type "help".
Type "apropos word" to search for commands related to "word".
Attaching to process 16962
Reading symbols from /usr/bin/bash...
Reading symbols from .gnu_debugdata for /usr/bin/bash...
(No debugging symbols found in .gnu_debugdata for /usr/bin/bash)
Reading symbols from /lib64/libtinfo.so.6...
Reading symbols from .gnu_debugdata for /lib64/libtinfo.so.6...
(No debugging symbols found in .gnu_debugdata for /lib64/libtinfo.so.6)
Reading symbols from /lib64/libdl.so.2...
(No debugging symbols found in /lib64/libdl.so.2)
Reading symbols from /lib64/libc.so.6...
(No debugging symbols found in /lib64/libc.so.6)
Reading symbols from /lib64/ld-linux-x86-64.so.2...
(No debugging symbols found in /lib64/ld-linux-x86-64.so.2)
Reading symbols from /lib64/libnss_sss.so.2...
Reading symbols from .gnu_debugdata for /lib64/libnss_sss.so.2...
(No debugging symbols found in .gnu_debugdata for /lib64/libnss_sss.so.2)
0x00007f9a5dc16dda in wait4 () from /lib64/libc.so.6
Missing separate debuginfos, use: dnf debuginfo-install bash-5.1.0-2.fc34.x86_64
(gdb) bt
#0  0x00007f9a5dc16dda in wait4 () from /lib64/libc.so.6
#1  0x000055a2111370bd in waitchld.constprop ()
#2  0x000055a21109b8ea in wait_for ()
#3  0x000055a211083d1e in execute_command_internal ()
#4  0x000055a211084578 in execute_command ()
#5  0x000055a211075f49 in reader_loop ()
#6  0x000055a21106791e in main ()
(gdb) q
A debugging session is active.

        Inferior 1 [process 16962] will be detached.

Quit anyway? (y or n) y
Detaching from program: /usr/bin/bash, process 16962
[Inferior 1 (process 16962) detached]
maminjie@fedora ~/w/gdb> gdb bash
...
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from bash...
Reading symbols from .gnu_debugdata for /usr/bin/bash...
(No debugging symbols found in .gnu_debugdata for /usr/bin/bash)
Missing separate debuginfos, use: dnf debuginfo-install bash-5.1.0-2.fc34.x86_64
(gdb) attach 16962
Attaching to program: /usr/bin/bash, process 16962
Reading symbols from /lib64/libtinfo.so.6...
Reading symbols from .gnu_debugdata for /lib64/libtinfo.so.6...
(No debugging symbols found in .gnu_debugdata for /lib64/libtinfo.so.6)
Reading symbols from /lib64/libdl.so.2...
(No debugging symbols found in /lib64/libdl.so.2)
Reading symbols from /lib64/libc.so.6...
(No debugging symbols found in /lib64/libc.so.6)
Reading symbols from /lib64/ld-linux-x86-64.so.2...
(No debugging symbols found in /lib64/ld-linux-x86-64.so.2)
Reading symbols from /lib64/libnss_sss.so.2...
Reading symbols from .gnu_debugdata for /lib64/libnss_sss.so.2...
(No debugging symbols found in .gnu_debugdata for /lib64/libnss_sss.so.2)
0x00007f9a5dc16dda in wait4 () from /lib64/libc.so.6
(gdb) bt
#0  0x00007f9a5dc16dda in wait4 () from /lib64/libc.so.6
#1  0x000055a2111370bd in waitchld.constprop ()
#2  0x000055a21109b8ea in wait_for ()
#3  0x000055a211083d1e in execute_command_internal ()
#4  0x000055a211084578 in execute_command ()
#5  0x000055a211075f49 in reader_loop ()
#6  0x000055a21106791e in main ()
(gdb) detach
Detaching from program: /usr/bin/bash, process 16962
[Inferior 1 (process 16962) detached]
(gdb)
拓展 后语 参考
  • GDB调试程序(完全手册)
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/308043.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号