当前位置:网站首页>GDB usage details
GDB usage details
2022-07-21 18:17:00 【Chief prisoner】
Preface
- At work , Whether it's learning code flow or problem location ,GDB It's very important , Mastering more commands can improve our efficiency and problem-solving ability ;
- As I understand it , Yes GDB The degree of mastery can be divided into three kinds of people :
- Basic commands , Everybody knows
- Relatively higher order , A few people understand , After mastering it, you can improve the efficiency of debugging and solving problems
- Need to combine disassembly 、 Stack backtracking 、malloc Principle and structure of memory allocation 、elf File structure, etc , coordination GDB To solve some memory related occasional problems
This article combines work experience , It mainly describes the contents of the first two parts , The last part will be described in other topics . Master these commands , at work 、 Be more comfortable when you are familiar with code or debugging problems .
1、GDB Basic introduction
1.1 brief introduction
- gdb yes GNU A powerful Linux Program debugging tools under
- gdb Except support c/c++ Language support go、D、object-c、fortran Other languages
- GDB It mainly helps you complete the following four functions :
- Start your program , You can run the program according to your custom requirements .
- You can make the debugged program stop at the breakpoint you specified .( Breakpoints can be conditional expressions )
- When the program is stopped , You can check what's going on in your program at this point .
- You can change your program , Will a BUG The impact is corrected to test other BUG.
1.2 compile
gdb It's open source. , We can download open source code online , Then, according to our own cross compilation chain, this is not our focus , And there are many online materials , Don't expand
2、GDB Use
2.1 Usage mode
2.1.1 Local debugging
Run directly in the server or current embedded device environment , If gdb The procedure is gdb, The application is build, Then run the debugging and use the following commands :
~#gdb ./build
2.1.2 Remote debugging
Remote debugging requires two GDB Program , Run on remote devices (target) The program on is called gdbserver, Run on the local host host Upper gdb The program is a cross compiler , That is to say x86 Run on the platform arm Platform gdb Program , Write it down as gdb_client
1、 Embedded devices execute :
~#./gdbserver 192.168.10.2:1234 ./build
among 192.168.10.2 It means to allow from this IP Address login channel embedded device , In general, our PC Server address , Also omitted , Means to allow from any IP Link in ,:1234 Is the port number ,build For the application to be debugged .
2、PC End execution :
~#arm-linux-gdb ./build_Debug
handle SIGPIPE SIGUSR2 SIG32 nostop noprint
target remote 172.8.4.11:1234 // Establish an association with the server
among 172.8.4.11 For the current embedded device IP Address ,:1234 Bit port , It must be connected with the specified port when the embedded device is running , Both are required , Don't omit .
notes :
- There is no need to input build_Debug , Otherwise, loading will be very slow
- Due to the device side memory, etc , In general, we use remote debugging
2.1.3attach
In the actual cross compilation development process , Sometimes we run programs without loading gdb, But I found an occasional problem , need gdb To locate , This is the time to go attach analysis .
1、 Find the corresponding... Of the current executable program debug edition
2、ps, Check the process number of the current executable
3、 The device side executes
./gdbserver 192.168.10.2:1234 --attach 669 (669 Is a process pid)
4、PC End :
~#arm-linux-gdb ./build_Debug
handle SIGPIPE SIGUSR2 SIG32 nostop noprint
target remote 172.8.4.11:1234
5、detach You can quit gdb( After exiting, the program runs normally )
2.1.4core analysis
core The file is generated after the crash in order to restore the scene for analysis , More on that later , Here is just an introduction core File analysis :
~#arm-linux-gdb ./build_debug ./core.669
After loading successfully , Can directly bt View the thread that is currently dead , Yes core Document analysis .
notes :
- core The generated executable program should be consistent with core Used in parsing debug The version of the executable corresponds to , Otherwise, the exception will be parsed
- core There are many question marks when loading , You need to specify the path of the dynamic library
set solib-search-path ./libso/
set solib-absolute ./libso/
2.2 Common commands
1、 Basic commands
command | brief introduction | gdb function | Usage and remarks |
---|---|---|---|
run | r | function | Debugging begins |
break | b | To set breakpoints | b Breakpoint |
info | i | Check the information | View breakpoints i b, Wait for a detailed list later |
delete | d | Delete breakpoints | delete Breakpoint number |
disable | disable | Disable breakpoints | disable Breakpoint number |
backtrace | bt,where | View stack frame | bt N Show the beginning N Stack frame , bt -N Last N Stack frame |
p | Print variables | p argc Print variables , Detailed introduction later | |
x | x | Display memory | x 0x1234567, Detailed introduction later |
set | set | Change the value of the variable | set variable < Variable > = < expression >; such as set var test=3 |
next | n | Execute next line | n; Go to the next line , No matter how complicated the next line is |
step | s | Execute next line | s; If the next behavior function , Then it goes inside the function |
continue | c,cont | continue | c Is the number of times to continue , Omission , Means to continue once |
finish | finish | Execute to complete the current function | |
until | until | Execute complete code block |
2、 Print variable values
print Support format output , Command format :p/ Format Variable ; The format supported is as follows :
Format | explain |
---|---|
x | Is shown as 16 Base number |
d | Is shown as 10 Base number |
u | Display as unsigned 10 Base number |
o | Is shown as 8 Base number |
t | Is shown as 2 Hexadecimal number ,t Express two |
a | Address |
c | Display as characters |
f | Floating point decimal |
s | Display as string |
3、 Print memory
Format :x/NFU ADDR
N: Repeat after FU frequency
F:/x16 Base number /c character /s character string /a Address /d Decimal system /i assembly /t Binary system
U:b byte h(2 byte ) w(4 Byte default ) g(8 byte )
4、 Word wrap
(gdb)set height 0
Get rid of less The function of , Print all at once
5、 Print all thread stacks
(gdb)thread apply all bt
6、 Check the meaning of an address
(gdb)info line *0x00f43126 // The function name will be printed
Equivalent to :arm-linux-addr2line 0x00f43126 -e ./build_debug
7、 View the structure definition
(gdb)ptype pTimeVal
type = struct{
int32 i32tv;
int32 i32Usec;
}
8、 The printing format is beautiful
(gdb)set print pretty on
9、 Print array
(gdb)p *pstTmpStruct->[email protected]4
$35 = {
0x1, 0x2, 0x3, 0x4}
10、display
Print a value every time the breakpoint
11、 View instructions
info args: View the parameters and values of the current function
info line: View the address of the source code in memory , You can follow the line number 、 Function name
info locals: Displays the local variables of the current function
info symbol: Display global variable information
info function: Show all function names
info thread: View thread information
info registers: Enumerate register values
12、 Specify the dynamic library location
(gdb)set solib-search-patch ./libso/
(gdb)set solib-absolute-prefix ./libso/
13、 Print the current process map Information
location Memory Related crash problems are often used , Confirm the head and tail of the currently applied large memory
i proc map
2.3 Commonly used advanced
1、gdb Write a picture
In practical work, due to YUV Memory is usually directly from sdk Physical memory obtained from interface , Not mapped to virtual address , There is no way to read and write directly , So before writing, we usually need to copy to malloc In the memory , And then use gdb Put the data in memory dump To a file
(gdb)p/x malloc(1024)
$3 = 0x3593490
(gdb)p/x memcpy(0x3593490, address, 1024)
(gdb)dump memory ~/test.yuv 0x3593490 0x3593490+1024
2、 Automatically execute after the breakpoint
As shown below , When the breakpoint is executed , Automatic printing i Value , then bt Print stack , And then move on , Until the next breakpoint , repeat ; It is suitable for large projects , During debugging , Want to know the value of the variable at each breakpoint , You can use this command , There is no need to repeat every time .
3、 Multithreaded debugging
Step by step debugging n、s There's always a problem , An interface may be called by multiple threads ,n Executing one step may run to other threads , Cause inconvenience in debugging , So we can lock the thread before single step debugging , Can only execute to the current thread :
(gdb)set scheduler-locking on
(gdb)set scheduler-locking off
Sure OSA_getTimeOfDay For example, analyze
4、 Breakpoints lock a thread
Sometimes an interface , Such as getTimeOfDay When adding breakpoints , This interface is called by multiple threads , Not the thread we want to analyze , If you want to specify the call to a thread , You need to specify the thread number , For thread breakpoints :
(gdb)b getTimeOfDay thread 23
5、watch
6、 Disassembly :disassemble
disassemble /m
Assembly single step debugging :nexti、stepi
Assemble break points :b*main+4 #4 Represents the offset of the assembly instruction
The current function is selected by default , You can also specify that Disassembly Function of .
7、 Stack backtracking
stay gdb In the actual use of , There may be a situation that the stack is not printed due to the destruction of the stack , We can load the script to print the stack :
See : Stack backtracking tool and its usage
3、core dump
3.1 Introduce
The core dump file is a file in the process address space when the current process terminates unexpectedly ,core dump It can also be generated actively ( If in gdb in )
When the operating system has an exception in the program and the exception is not captured inside the city , Will put the current memory register state of the process 、 Run stack and other information dumps are stored in a
This file is also a binary file , have access to gdb、elfdump、objdump And so on .
core dump Recorded the crime scene , Through analysis core dump file , We can restore the situation when the system is abnormal , So as to find out the cause of the abnormality .
3.2core Generate
See if you can generate coredump You can enter commands at the terminal
~#ulimit -a
As shown in the figure ,corefile size by 0 Indicates that it is used to generate core The size of the file is 0, That is, it will not be generated core, modify core file size Commands available ulimit -c yoursize, among yousize The size specified for the user , If you don't want to limit the size , You can use the command directly :
~#ulimit -c unlimited
Setup completed core After the generated size, you need to set core Generated directory , Set up core The generated directory can be created by going to /proc/sys/kkernel/core_pattern Write parameters to set .
First check the default state /proc/sys/kkernel/core_pattern Value :
~#cat /proc/sys/kkernel/core_pattern
It means that by default, it will be generated in the current directory with the name core Of core file , We can use :
echo “/home/core-%e-%p-%s-%t” > /proc/sys/kernel/core_pattern
Use this command to modify core Directory of file generation and naming rules .
%e Out core Process pid
%u Out core Process UID
%s cause core Of signal Number
%t Out core Time for , from 1970-01-0100:00:00 Seconds to start
%e Out core Executable file name corresponding to the process
The specific meaning is as follows , And also notice that , since linux kernel 2.6.19 after ,core_pattern Pipeline commands are also supported , If the first character of the command is a pipe character ’l’,linux When the kernel captures the process crash information , It'll take root Permission to execute the program or script behind the pipeline . In this way , We can do some operations, such as core Compression, etc .
3.3core Use
The way of use has been described above , load core After the document , Debug commands and local or remote debugging gdb In the same way , It can be done by bt Command to view stack frames , Analyze possible errors , Disassemble if necessary , By looking at the value of the register , To restore the scene at that time . In the case of source code , You can also directly compare the elements to the location of the analysis error .
Even though core The file records the information when the error occurs , But if the stack frame is destroyed , For example, write data to a wrong address , It may cause data corruption on the stack frame , At this time, the information of stack frame cannot be viewed , Or the information on the stack frame becomes unreliable , The cause of the problem can only be found through other methods .
边栏推荐
- “为了买台手机,研究大半个月后仍然无从选择”
- Redis practice (I) login
- Web3流量聚合平台Starfish OS,给玩家元宇宙新范式体验
- H5 mobile game run rabbit source code download
- 【QT小记】在QThread的run()函数中使用定时器QTimer
- 漏洞挖掘-ThinkPHP6.0.12LTS反序列化
- 关于swing界面label和button的动态设置文字
- JS SVG cloud and love animation JS special effects
- Vulnerability statements of the sorted burp official website
- Mobilevit: challenge the end-to-side overlord of mobilenet
猜你喜欢
不知道 MySQL 咋学?刷完牛客这 50 道题就够了!(第八篇)
Creative paging style SVG animation JS special effects
冒號用法 視頻41 13.3. 目標檢測和邊界框 QA 13.4錨框
Web3.0 + Dao is the general trend, and safe creates a new world
Zdog漂浮旋转动画js特效代码
看懂RTK定位,这一篇就够啦!
IP协议号大全
堆栈的区别
iNFTnews | 元宇宙浪潮下,企业正通过AR和VR技术改善客户体验
Mobilevit: challenge the end-to-side overlord of mobilenet
随机推荐
Resume: smart cockpit series article 2: the vision of five interactive technologies behind it
19c搭建dg最后报错ORA-01275: Operation RENAME is not allowed if standby file management is automatic.
深潮财经解读USDD:穿过脱钩幻觉,寻找真实的稳定币
Zdog漂浮旋转动画js特效代码
Qdu summer training first week limited time training 1
Zdog floating rotation animation JS special effect code
Aijs add dotted line
h5手机游戏奔跑吧兔子源码下载
登录和注册页面扁平化设计
19c build DG and finally report error ora-01275: operation Rename is not allowed if standby file management is automatic
狂神redis笔记05
JS chart evaporation precipitation average temperature diagram display
Don't know how to learn MySQL? It's enough to finish the 50 questions of Niuke! (Part VII)
H5 mobile game run rabbit source code download
创意分页样式svg动画js特效
Raspberry pie 3B builds Flink cluster
In the available fields list of s/4hana extended fields, what should I do if I can't see the extended fields I created
iNFTnews | 元宇宙浪潮下,企业正通过AR和VR技术改善客户体验
NFS FTP PXE
2022-07-20:以下go语言代码是关于json 和 context的,输出什么?A:{};B:{“a“:“b“};C:{“Context“:0};D:不确定。 package main imp