banner
ekko

ekko's blog

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

gdb Usage Guide

image

Enter Debugging#

Debugging Local Program#

gdb ./a.out

Debugging Target Board Program#

gdb-multiarch ./a.elf

When using serial port, add the -b option to set the baud rate:

gdb-multiarch -b 115200 ./a.elf

The subsequent steps involve entering commands in the gdb command line!

Connect to Target Board#

This step is not needed for debugging local programs.
Use network to connect to target board/gdb server:

target remote 192.0.2.1:4242

Use USB serial to connect to target board/gdb server:

target remote /dev/ttyUSB0

Common Debugging Commands#

Subsequent commands are displayed in help format, with the format being help + command being used, for example, help load refers to the current command being load, with more complete parameter help information below.
The next line is usually the alias for that command, for example:

(gdb) help step
step, s

This means that the step command can also be used with the s command, both are equivalent.
If there is no alias, the next line is the function description of the command, for example:

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

The following format is the command usage method, for example:

Usage: step [N]

Parameters within square brackets [] are optional parameters, and further down are the meanings of various parameters and more detailed command function descriptions, using the original English descriptions from help to ensure accuracy.

Load Program/File#

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

Summary: load can load the elf file passed in through the command line when starting gdb by default. If not specified by gdb, the file path needs to be added after load.

Step#

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

Summary: Step execution, enters the function if there is a function call.

Next Step#

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

Summary: Unlike step execution, if there is a function call, it will directly run to the end of that function without entering the function.

Continue#

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

Summary: Continue running the program until interrupted by a signal, or a breakpoint, or a watchpoint.

Finish#

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

Summary: Continue running the program until the current function returns.

Until#

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

Summary: Continue running the program until the end of the loop body; you can add a line number after until to indicate running until that line ends.

Function Call#

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

Breakpoints#

Add Software Breakpoint#

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

Summary: A commonly used method is b + function name, b + filename: line number.

Add Hardware Breakpoint#

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

View Current 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.

Summary: The Num can be used as a parameter for other functions such as closing breakpoints, and the Type can indicate whether it is a software breakpoint/hardware breakpoint/watchpoint.

Disable Breakpoint#

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

Enable Breakpoint#

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

Delete Breakpoint#

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

Watchpoint#

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

Summary: Monitor the value of an expression, deleting a watchpoint and viewing current watchpoints are similar to previous breakpoint operations.

Read/Write Registers#

Read All Registers/Single Register#

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

Write Register#

For example, to write the value of the pc register as 0x1111:

(gdb)set $pc=0x1111

Read/Write Memory#

Read Memory#

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

Example

1. Display 1 byte of data in decimal
   x/1bo 0x40000000
2. Display 2 words of data in hexadecimal
   x/2wx 0x40000000

Write Memory#

Example:

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

View Stack Trace Information#

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

Print Expression#

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

Multithreading#

View Thread Information#

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

Switch Thread#

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

View Source Code#

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

Disassemble#

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

Others#

For other usages not covered, you can use help, man, etc., or check the official website Debugging with GDB (sourceware.org) for more information.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.