進入調試#
調試本機程序#
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)