banner
ekko

ekko's blog

时间不在于你拥有多少,而在于你怎样使用
github
xbox
email

gdb使用指南

image

进入调试#

调试本机程序#

gdb ./a.out

调试目标板程序#

gdb-mutliarch ./a.elf

使用串口方式则增加 - b 选项设置波特率:

gdb-multiarch -b 115200 ./a.elf

之后的步骤都是在 gdb 命令行内输入指令!

连接目标板#

调试本机程序不需要本步骤
使用网络连接目标板 /gdb 服务端:

target remote 192.0.2.1:4242

使用 USB 串口连接目标板 /gdb 服务端:

target remote /dev/ttyUSB0

常用调试命令#

后续命令都以 help 格式进行展示,格式为help+使用的命令,比如help load就是指当前命令为 load,下方有更完整的参数帮助信息。
下一行通常是该命令的别名,比如:

(gdb) help step
step, s

意思就是step命令还可以使用s命令,两者是等效的。
如果没有别名的话下一行就是该命令的功能说明,比如:

(gdb) help c
continue, fg, c
Continue program being debugged, after signal or breakpoint.

再往下的格式就是命令使用方法,比如:

Usage: step [N]

方括号 [] 内的参数为可选参数,再往下方就是各个参数的含义以及更详细的命令功能说明,为保证含义准确就都使用 help 的原始英文说明。

加载程序 / 文件#

(gdb) help load
Dynamically load FILE into the running program.
FILE symbols are recorded for access from GDB.
Usage: load [FILE] [OFFSET]
An optional load OFFSET may also be given as a literal address.
When OFFSET is provided, FILE must also be provided.  FILE can be provided
on its own.

概要:load 默认可加载启动 gdb 时通过命令行传入的 elf 文件,如果未通过 gdb 指定,则需要在 load 后增加文件路径

单步#

(gdb) help step
step, s
Step program until it reaches a different source line.
Usage: step [N]
Argument N means step N times (or till program stops for another reason).

概要:单步运行,有函数调用则进入函数

下一步#

(gdb) help n
next, n
Step program, proceeding through subroutine calls.
Usage: next [N]
Unlike "step", if the current source line calls a subroutine,
this command does not enter the subroutine, but instead steps over
the call, in effect treating it as a single source line.

概要:与单步运行不同的是,有函数调用会直接运行完该函数,不进入函数内部

继续#

(gdb) help c
continue, fg, c
Continue program being debugged, after signal or breakpoint.
Usage: continue [N]
If proceeding from breakpoint, a number N may be used as an argument,
which means to set the ignore count of that breakpoint to N - 1 (so that
the breakpoint won't break until the Nth time it is reached).

If non-stop mode is enabled, continue only the current thread,
otherwise all the threads in the program are continued.  To
continue all stopped threads in non-stop mode, use the -a option.
Specifying -a and an ignore count simultaneously is an error.

概要:继续运行程序,直到有信号打断,或者触发断点,或者触发观察点

完成#

(gdb) help finish
finish, fin
Execute until selected stack frame returns.
Usage: finish
Upon return, the value returned is printed and put in the value history.

概要:继续运行程序,直到当前函数返回

直到#

(gdb) help until
until, u
Execute until past the current line or past a LOCATION.
Execute until the program reaches a source line greater than the current
or a specified location (same args as break command) within the current frame.

概要:继续运行程序,直到循环体结束,可以在 until 后加行号,则表示运行到该行结束

函数调用#

(gdb) help call
Call a function in the program.
Usage: call EXP
The argument is the function name and arguments, in the notation of the
current working language.  The result is printed and saved in the value
history, if it is not void.

断点#

添加软件断点#

(gdb) help b
break, brea, bre, br, b
Set breakpoint at specified location.
break [PROBE_MODIFIER] [LOCATION] [thread THREADNUM]
        [-force-condition] [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.

With the "-force-condition" flag, the condition is defined even when
it is invalid for all current locations.

Linespecs are colon-separated lists of location parameters, such as
source filename, function name, label name, and line number.
Example: To specify the start of a label named "the_top" in the
function "fact" in the file "factorial.c", use
"factorial.c:fact:the_top".

Address locations begin with "*" and specify an exact address in the
program.  Example: To specify the fourth byte past the start function
"main", use "*main + 4".
--Type <RET> for more, q to quit, c to continue without paging--

Explicit locations are similar to linespecs but use an option/argument
syntax to specify location parameters.
Example: To specify the start of the label named "the_top" in the
function "fact" in the file "factorial.c", use "-source factorial.c
-function fact -label the_top".

By default, a specified function is matched against the program's
functions in all scopes.  For C++, this means in all namespaces and
classes.  For Ada, this means in all packages.  E.g., in C++,
"func()" matches "A::func()", "A::B::func()", etc.  The
"-qualified" flag overrides this behavior, making GDB interpret the
specified name as a complete fully-qualified name instead.

Multiple breakpoints at one place are permitted, and useful if their
conditions are different.

Do "help breakpoints" for info on other commands dealing with breakpoints.

概要:经常使用的方式为 b + 函数名称,b + 文件名:行号

添加硬件断点#

(gdb) help hb
Set a hardware assisted breakpoint.
Like "break" except the breakpoint requires hardware support,
some target hardware may not have this support.

hbreak [PROBE_MODIFIER] [LOCATION] [thread THREADNUM]
        [-force-condition] [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.

With the "-force-condition" flag, the condition is defined even when
it is invalid for all current locations.

Linespecs are colon-separated lists of location parameters, such as
source filename, function name, label name, and line number.
Example: To specify the start of a label named "the_top" in the
function "fact" in the file "factorial.c", use
"factorial.c:fact:the_top".

Address locations begin with "*" and specify an exact address in the
--Type <RET> for more, q to quit, c to continue without paging--
program.  Example: To specify the fourth byte past the start function
"main", use "*main + 4".

Explicit locations are similar to linespecs but use an option/argument
syntax to specify location parameters.
Example: To specify the start of the label named "the_top" in the
function "fact" in the file "factorial.c", use "-source factorial.c
-function fact -label the_top".

By default, a specified function is matched against the program's
functions in all scopes.  For C++, this means in all namespaces and
classes.  For Ada, this means in all packages.  E.g., in C++,
"func()" matches "A::func()", "A::B::func()", etc.  The
"-qualified" flag overrides this behavior, making GDB interpret the
specified name as a complete fully-qualified name instead.

Multiple breakpoints at one place are permitted, and useful if their
conditions are different.

Do "help breakpoints" for info on other commands dealing with breakpoints.

查看当前断点#

(gdb) help i b
info breakpoints, info b
Status of specified breakpoints (all user-settable breakpoints if no argument).
The "Type" column indicates one of:
        breakpoint     - normal breakpoint
        watchpoint     - watchpoint
The "Disp" column contains one of "keep", "del", or "dis" to indicate
the disposition of the breakpoint after it gets hit.  "dis" means that the
breakpoint will be disabled.  The "Address" and "What" columns indicate the
address and file/line number respectively.

Convenience variable "$_" and default examine address for "x"
are set to the address of the last breakpoint listed unless the command
is prefixed with "server ".

Convenience variable "$bpnum" contains the number of the last
breakpoint set.

概要:其中的 Num 可作为其他功能比如关闭断点的参数,其中的 Type 可以看出是软件断点 / 硬件断点 / 观察点

关闭断点#

(gdb) help disable
disable, disa, dis
Disable all or some breakpoints.
Usage: disable [BREAKPOINTNUM]...
Arguments are breakpoint numbers with spaces in between.
To disable all breakpoints, give no argument.
A disabled breakpoint is not forgotten, but has no effect until re-enabled.

List of disable subcommands:

disable breakpoints -- Disable all or some breakpoints.
disable display -- Disable some expressions to be displayed when program stops.
disable frame-filter -- GDB command to disable the specified frame-filter.
disable mem -- Disable memory region.
disable pretty-printer -- GDB command to disable the specified pretty-printer.
disable probes -- Disable probes.
disable type-printer -- GDB command to disable the specified type-printer.
disable unwinder -- GDB command to disable the specified unwinder.
disable xmethod -- GDB command to disable a specified (group of) xmethod(s).

Type "help disable" followed by disable subcommand name for full documentation.
Type "apropos word" to search for commands related to "word".
Type "apropos -v word" for full documentation of commands related to "word".
Command name abbreviations are allowed if unambiguous.

开启断点#

(gdb) help enable
enable, en
Enable all or some breakpoints.
Usage: enable [BREAKPOINTNUM]...
Give breakpoint numbers (separated by spaces) as arguments.
With no subcommand, breakpoints are enabled until you command otherwise.
This is used to cancel the effect of the "disable" command.
With a subcommand you can enable temporarily.

List of enable subcommands:

enable breakpoints -- Enable all or some breakpoints.
enable count -- Enable some breakpoints for COUNT hits.
enable delete -- Enable some breakpoints and delete when hit.
enable display -- Enable some expressions to be displayed when program stops.
enable frame-filter -- GDB command to enable the specified frame-filter.
enable mem -- Enable memory region.
enable once -- Enable some breakpoints for one hit.
enable pretty-printer -- GDB command to enable the specified pretty-printer.
enable probes -- Enable probes.
enable type-printer -- GDB command to enable the specified type printer.
enable unwinder -- GDB command to enable unwinders.
enable xmethod -- GDB command to enable a specified (group of) xmethod(s).

Type "help enable" followed by enable subcommand name for full documentation.
Type "apropos word" to search for commands related to "word".
Type "apropos -v word" for full documentation of commands related to "word".
Command name abbreviations are allowed if unambiguous.

删除断点#

(gdb) help del
delete, del, d
Delete all or some breakpoints.
Usage: delete [BREAKPOINTNUM]...
Arguments are breakpoint numbers with spaces in between.
To delete all breakpoints, give no argument.

Also a prefix command for deletion of other GDB objects.

观察点#

(gdb) help watch
Set a watchpoint for EXPRESSION.
Usage: watch [-location] EXPRESSION

Options:
  -location
    This evaluates EXPRESSION and watches the memory to which is refers.
    -l can be used as a short form of -location.

A watchpoint stops execution of your program whenever the value of
an expression changes.

概要:检测一个表达式的值,删除观察点与查看当前观察点都同之前断点操作

读写寄存器#

读取全部寄存器 / 单个寄存器#

(gdb) help info r
info registers, info r
List of integer registers and their contents, for selected stack frame.
One or more register names as argument means describe the given registers.
One or more register group names as argument means describe the registers
in the named register groups.

写寄存器#

举例写 pc 寄存器的值为 0x1111:

(gdb)set $pc=0x1111

读写内存#

读内存#

(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), s(string)
  and z(hex, zero padded on the left).
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.  If a negative number is specified, memory is
examined backward from the address.

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".

举例

1. 10进制显示1个字节(byte)的数据
   x/1bo 0x40000000
2. 16进制显示2个字(word)的数据
   x/2wx 0x40000000

写内存#

举例:

(gdb)set *((uint8_t*)0x40000000)=0x11
(gdb)set *((uint64_t*)0x40000000)=0x1111111111111111

查看栈回溯信息#

(gdb) help bt
backtrace, where, bt
Print backtrace of all stack frames, or innermost COUNT frames.
Usage: backtrace [OPTION]... [QUALIFIER]... [COUNT | -COUNT]

Options:
  -entry-values no|only|preferred|if-needed|both|compact|default
    Set printing of function arguments at function entry.
    GDB can sometimes determine the values of function arguments at entry,
    in addition to their current values.  This option tells GDB whether
    to print the current value, the value at entry (marked as val@entry),
    or both.  Note that one or both of these values may be <optimized out>.

  -frame-arguments all|scalars|none|presence
    Set printing of non-scalar frame arguments.

  -raw-frame-arguments [on|off]
    Set whether to print frame arguments in raw form.
    If set, frame arguments are printed in raw form, bypassing any
    pretty-printers for that value.

  -frame-info auto|source-line|location|source-and-location|location-and-address|short-location
    Set printing of frame information.

  -past-main [on|off]
    Set whether backtraces should continue past "main".
    Normally the caller of "main" is not of interest, so GDB will terminate
    the backtrace at "main".  Set this if you need to see the rest
    of the stack trace.

--Type <RET> for more, q to quit, c to continue without paging--
  -past-entry [on|off]
    Set whether backtraces should continue past the entry point of a program.
    Normally there are no callers beyond the entry point of a program, so GDB
    will terminate the backtrace there.  Set this if you need to see
    the rest of the stack trace.

  -full
    Print values of local variables.

  -no-filters
    Prohibit frame filters from executing on a backtrace.

  -hide
    Causes Python frame filter elided frames to not be printed.

For backward compatibility, the following qualifiers are supported:

   full       - same as -full option.
   no-filters - same as -no-filters option.
   hide       - same as -hide.

With a negative COUNT, print outermost -COUNT frames.

打印表达式#

(gdb) help print
print, inspect, p
Print value of expression EXP.
Usage: print [[OPTION]... --] [/FMT] [EXP]

Options:
  -address [on|off]
    Set printing of addresses.

  -array [on|off]
    Set pretty formatting of arrays.

  -array-indexes [on|off]
    Set printing of array indexes.

  -elements NUMBER|unlimited
    Set limit on string chars or array elements to print.
    "unlimited" causes there to be no limit.

  -max-depth NUMBER|unlimited
    Set maximum print depth for nested structures, unions and arrays.
    When structures, unions, or arrays are nested beyond this depth then they
    will be replaced with either '{...}' or '(...)' depending on the language.
    Use "unlimited" to print the complete structure.

  -memory-tag-violations [on|off]
    Set printing of memory tag violations for pointers.
    Issue a warning when the printed value is a pointer
    whose logical tag doesn't match the allocation tag of the memory
    location it points to.
--Type <RET> for more, q to quit, c to continue without paging--

  -null-stop [on|off]
    Set printing of char arrays to stop at first null char.

  -object [on|off]
    Set printing of C++ virtual function tables.

  -pretty [on|off]
    Set pretty formatting of structures.

  -raw-values [on|off]
    Set whether to print values in raw form.
    If set, values are printed in raw form, bypassing any
    pretty-printers for that value.

  -repeats NUMBER|unlimited
    Set threshold for repeated print elements.
    "unlimited" causes all elements to be individually printed.

  -static-members [on|off]
    Set printing of C++ static members.

  -symbol [on|off]
    Set printing of symbol names when printing pointers.

  -union [on|off]
    Set printing of unions interior to structures.

  -vtbl [on|off]
--Type <RET> for more, q to quit, c to continue without paging--
    Set printing of C++ virtual function tables.

Note: because this command accepts arbitrary expressions, if you
specify any command option, you must use a double dash ("--")
to mark the end of option processing.  E.g.: "print -o -- myobj".

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).

多线程#

查看线程信息#

(gdb) help i threads
Display currently known threads.
Usage: info threads [OPTION]... [ID]...
If ID is given, it is a space-separated list of IDs of threads to display.
Otherwise, all threads are displayed.

Options:
  -gid
    Show global thread IDs.

切换线程#

(gdb) help thread
thread, t
Use this command to switch between threads.
The new thread ID must be currently known.

List of thread subcommands:

thread apply -- Apply a command to a list of threads.
thread find -- Find threads that match a regular expression.
thread name -- Set the current thread's name.

Type "help thread" followed by thread subcommand name for full documentation.
Type "apropos word" to search for commands related to "word".
Type "apropos -v word" for full documentation of commands related to "word".
Command name abbreviations are allowed if unambiguous.

查看源码#

(gdb) help list
list, l
List specified function or line.
With no argument, lists ten more lines after or around previous listing.
"list -" lists the ten lines before a previous ten-line listing.
One argument specifies a line, and ten lines are listed around that line.
Two arguments with comma between specify starting and ending lines to list.
Lines can be specified in these ways:
  LINENUM, to list around that line in current file,
  FILE:LINENUM, to list around that line in that file,
  FUNCTION, to list around beginning of that function,
  FILE:FUNCTION, to distinguish among like-named static functions.
  *ADDRESS, to list around the line containing that address.
With two args, if one is empty, it stands for ten lines away from
the other arg.

By default, when a single location is given, display ten lines.
This can be changed using "set listsize", and the current value
can be shown using "show listsize".

反汇编#

(gdb) help disass
Disassemble a specified section of memory.
Usage: disassemble[/m|/r|/s] START [, END]
Default is the function surrounding the pc of the selected frame.

With a /s modifier, source lines are included (if available).
In this mode, the output is displayed in PC address order, and
file names and contents for all relevant source files are displayed.

With a /m modifier, source lines are included (if available).
This view is "source centric": the output is in source line order,
regardless of any optimization that is present.  Only the main source file
is displayed, not those of, e.g., any inlined functions.
This modifier hasn't proved useful in practice and is deprecated
in favor of /s.

With a /r modifier, raw instructions in hex are included.

With a single argument, the function surrounding that address is dumped.
Two arguments (separated by a comma) are taken as a range of memory to dump,
  in the form of "start,end", or "start,+length".

Note that the address is interpreted as an expression, not as a location
like in the "break" command.
So, for example, if you want to disassemble function bar in file foo.c
you must type "disassemble 'foo.c'::bar" and not "disassemble foo.c:bar".

其他#

未涉及到的其他用法可使用help,man等方式查询,也可官网查询Debugging with GDB (sourceware.org)

加载中...
此文章数据所有权由区块链加密技术和智能合约保障仅归创作者所有。