GDB is a powerful UNIX published by GNU open source organization. Perhaps, you prefer the graphical interface method, like the debugging of IDE, etc., but if you are software under the UNIX platform, you will find that the GDB debugging tool has a graphic debugger than VC, BCB. powerful functions. The so-called "inch is a long, the ruler is short" is this truth.
In general, GDB mainly helps you complete the following four features:
1. Start your program, you can run the program as you want to follow your custom requirements.
2. Allow the debugged program to stop at the breakpoint you specified. (The breakpoint can be conditional expression)
3. When the program is parked, you can check what happened in your program.
4. Dynamic changes your program's execution environment.
From above, GDB and general debugging tools have no two, basically complete these features, but in detail, you will find the power of the debugging tool of GDB, everyone may be used to the graphical debugging tool, but there is At the time, the debug tool of the command line has the function that cannot be completed. Let us look in one by one.
A debug sample
--------
Source: tst.c
1 #include
2
3 int func (INT N)
4 {
5 int sum = 0, i;
6 for (i = 0; i
7 {
8 sum = i;
9 }
10 returnium;
11}
12
13
14 main ()
15 {
16 INT I;
17 long result = 0;
18 for (i = 1; i <= 100; i )
19 {
20 Result = i;
twenty one }
twenty two
23 Printf ("Result [1-100] =% D", Result);
24 Printf ("Result [1-250] =% D", FUNC (250));
25}
Compile generation execution file: (linux)
HCHEN / TEST> CC -G TST.C -O TST
Use GDB debugging:
HCHEN / TEST> GDB TST <---------- Start GDB
GNU GDB 5.1.1
CopyRight 2002 Free Software Foundation, Inc.
GDB IS Free Software, Covered by the gnu general public license, and you are
Welcome to change IT and / or or distribute copies of it under certain conditions.
Type "Show Copying" to see the conditions.
There Is Absolutely No Warranty for GDB. Type "Show Warranty" for Details.
THIS GDB WAS Configured AS "I386-SUSE-Linux" ...
(GDB) L <------------------ L command is equivalent to the list, and the original code is started from the first line.
1 #include
2
3 int func (INT N)
4 {
5 int sum = 0, i;
6 for (i = 0; i
7 {
8 sum = i;
9 }
10 returnium;
(GDB) <-------------------- direct carriage return, repeat the last order
11} 12
13
14 main ()
15 {
16 INT I;
17 long result = 0;
18 for (i = 1; i <= 100; i )
19 {
20 Result = i;
(GDB) BREAK 16 <------------------ Set breakpoints, in the 16th line of the source program.
Breakpoint 1 at 0x8048496: File Tst.c, Line 16.
(GDB) BREAK FUNC <------------------ Set the breakpoint, at the entrance to the function func ().
Breakpoint 2 at 0x8048456: File Tst.c, Line 5.
(GDB) Info Break <-------------------- View the breakpoint information.
Num Type DINB Address What
1 BreakPoint Keep Y 0x08048496 in main at tst.c: 16
2 BreakPoint Keep Y 0x08048456 in Func At TST.C: 5
(GDB) R <-------------------- running the program, Run command is short
Starting Program: / HOME / HCHEN / TEST / TST
Breakpoint 1, Main () at tst.c: 17 <---------- Announced at the breakpoint.
17 long result = 0;
(GDB) N <------------------- Single statement execution, Next command is short.
18 for (i = 1; i <= 100; i )
(GDB) N
20 Result = i;
(GDB) N
18 for (i = 1; i <= 100; i )
(GDB) N
20 Result = i;
(GDB) C <-------------------- Continue to run the program, and the contractue command is short.
Continuing.
Result [1-100] = 5050 <---------- Program Output.
Breakpoint 2, Func (n = 250) at tst.c: 5
5 int sum = 0, i;
(GDB) N
6 for (i = 1; i <= n; i )
(GDB) P i <------------------- Print the value of the variable I, the print command is short.
$ 1 = 134513808
(GDB) N
8 sum = i;
(GDB) N
6 for (i = 1; i <= n; i )
(GDB) P SUM
$ 2 = 1
(GDB) N
8 sum = i;
(GDB) P i
$ 3 = 2
(GDB) N
6 for (i = 1; i <= n; i )
(GDB) P SUM
$ 4 = 3
(GDB) BT <-------------------- View the function stack.
# 0 func (n = 250) at tst.c: 5
# 1 0x080484e4 in main () at tst.c: 24
# 2 0x400409ed in __libc_start_main () from /lib/libc.so.6
(GDB) Finish <-------------------- exits the function.
Run Till Exit from # 0 func (n = 250) at Tst.c: 50x080484e4 in main () at tst.c: 24
24 Printf ("Result [1-250] =% D", FUNC (250));
Value Returned IS $ 6 = 31375
(GDB) c <-------------------- Continue to run.
Continuing.
Result [1-250] = 31375 <---------- Program Output.
Program evted with code 027. <-------- Program exits, the debugging ends.
(GDB) Q <-------------------- exits GDB.
HCHEN / TEST>
Ok, has the above feelings, or let us systematically meet GDB.
Use GDB
----
Generally, GDB mainly debugging is a program of C / C . To debug the C / C program, first in compile, we must add debug information to the executable. This can be done using the -g parameter using the compiler (CC / GCC / G ). Such as:
> cc -g hello.c -o hello
> g -g hello.cpp -o hello
If there is no -g, you will see the function name, variable name, which instead, all of which is the memory address of the runtime. When you use -g to join the debug information, then successfully compile the target code, let's take a look at how to use GDB to debug him.
There are several ways to start GDB:
1, GDB
Program is also your executable file, usually under the directory.
2, GDB
core
Use GDB to debug a running program and core file, and Core is the file generated after the process of core dump after the program is illegally executed.
3, GDB
If your program is a service, you can specify the process ID of this service run. GDB will automatically go up to Attach and debug him. Program should be searched in the PATH environment variable.
When GDB is started, you can add some GDB launch switches. Detailed switches can be viewed with GDB -HELP. I only exemplified some commonly used parameters:
-symbols
-S
Read the symbol table from the specified file.
-Se file
Read the symbol table information from the specified file and use him in the executable.
-CORE
-C
Combatch the core file of Core Dump.
-Directory
-d
Add a source file search path. The default search path is the path defined in the environment variable.
GDB command profile
-------
After starting the GDB, you can use the GDB command to start the debugger using the GDB command, and the gdb command can use the HELP command to view, as shown below:
/ homen / hchen> GDB
GNU GDB 5.1.1
CopyRight 2002 Free Software Foundation, Inc.
GDB IS Free Software, Covered by the gnu general public license, and you are
Welcome to change IT and / or or distribute copies of it under certain conditions.
Type "Show Copying" to see the conditions.
There Is Absolutely No Warranty for GDB. Type "Show Warranty" for Details.This GDB WAS Configured AS "i386-suse-linux".
(GDB) Help
List of classes of commists:
Aliases - Aliases of Other Commands
Breakpoints - Making Program Stop At Certain Points
Data - Examing Data
FILES - Specifying and Examing Files
INTERNALS - Maintenance CommANDS
Obscure - Obscure Features
Running - Running the Program
Stack - EXAMININININING THE Stack
Status - Status Inquiries
Support - Support facilities
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 commists in what class.
Type "Help" Followed by Command Name for Full Documentation.
Command name abbreviations are allowed if unambiguous.
(GDB)
There are a lot of GDB commands, and GDB is divided into many types. The HELP command is just a command type of GDB. If you want to see the command in the species, you can use the help command, such as: Help Breakpoints, check all the commands to set the breakpoint. You can also directly Help to view the help of the command.
In the GDB, when entering the command, you can use the first few characters that only use the command, of course, the first few characters of the command should mark a unique command, under Linux, you can knock The full name of the Tab key to make up the command, if there is repetitive, then GDB will come out.
Example 1: Set a breakpoint when entering the function FUNC. Can be knocked into Break Func, or it is directly B FUNC
(GDB) B FUNC
Breakpoint 1 at 0x8048458: file hello.c, line 10.
Example 2: Typing B Press twice Tab keys, you will see all B head command:
(GDB) B
Backtrace BREAK BT
(GDB)
Example 3: Remember only the prefix of the function, you can:
(GDB) B Make_
(Press the next Tab button, you will see :)
Make_a_section_from_file make_environ
Make_abs_section make_function_type
Make_blockvector make_pointer_type
Make_cleanup make_reference_type
Make_command make_symbol_completion_list
(GDB) B Make_
GDB will come out to you through all the functions of all makers.
Example 4: When debugging the C program, there is a function name. Such as: (GDB) B 'BUBBLE (M-?
Bubble (Double, Double) Bubble (INT, INT)
(GDB) B 'BUBBLE
You can check all overload functions and parameters in C . (Note: M-? And "pressing the Tab key")
When you want to quit GDB, just send quit or command to Q.
SHELL program running Unix in GDB
----------------
In the GDB environment, you can execute the unix shell command, complete using the gdb's shell command:
shell
Calling UNIX's shell is executed, UNIX's shell defined in the environment variable shell will be used to execute, if the shell is not defined, then the standard shell: / bin / SH of UNIX. (Using Command.com or cmd.exe in Windows)
Another GDB command is make:
Make
You can execute the make command in GDB to re-build your own program. This command is equivalent to "shell make".
Run the program in GDB
------------
When GDB is started in a GDB, GDB will search for the source files searched in the Path path and the current directory. To confirm if the GDB reads the source file, you can use the L or List command to see if the GDB can list the source code.
In GDB, run the program using R or the run command. The operation of the program, you may need to set the following four aspects.
1, the program runs the parameters.
Set Args Specifies the runtime parameter. (Such as: set Args 10 20 30 40 50)
The show args command can view the setup run parameters.
2, the operating environment.
Path
The program's run path can be set.
Show paths View the runtime path of the program.
Set Environment VarName [= value] Set the environment variable. Such as: set env user = hchen
Show Environment [VarName] View environment variable.
3, work catalog.
CD
The CD command equivalent to the shell.
The PWD displays the current directory.
4, the input and output of the program.
INFO TERMINAL displays the mode of the terminal you use.
Use the redirection control program to output. Such as: Run> Outfile
The TTY command can be written to the terminal device input and output. Such as: TTY / DEV / TTYB
Debugging the running program
------------
Two methods:
1. View the PID (process ID) of the running program with PS under UNIX, and then hook the running program in GDB PID format.
2, first use the GDB to associate the upper source code, and perform GDB, use the attach command in GDB to hook the PID of the process. And use DETACH to cancel the process.
Pause / recovery procedure
---------
In the debugger, the suspension program is required, and GDB can easily pause the operation of the program. You can set the program where you have stopped, stop under what conditions, or stop when you receive a signal. To allow you to view runtime variables, as well as runtime processes.
When the process is parked by GDB, you can use Info Program to see if the program is running, the process number, and is suspended.
In GDB, we can have the following pauses: breakpoint, watchpoint, catchpoint, signal (Signals), thread stops. If you want to recover the program, you can use C or the Continue command. First, set breakpoints (BREAKPOINT)
We use the break command to set breakpoints. There are several ways to set breakpoints in front:
Break
Announced when entering the specified function. You can specify the function name using the Class :: function or function (type, type, type) format in C .
Break
Announced at the specified line number.
Break offset
BREAK -OFFSET
An offset line in front or behind the current line number. OFFSET is natural number.
Break filename: LINENUM
Announced on the Linenum line of the source file filename.
Break filename: Function
Announced at the entrance of the FUNCTION function of the source file filename.
Break * address
Announced in the memory address running.
Break
When the BREAK command does not have a parameter, it is indicated when the next instruction is stopped.
Break ... if
... can be the above parameters, Condition represents the condition, stops when the conditions are set up. For example, in the circulatory body, Break if i = 100 can be set, indicating that the program is stopped when I is 100.
When you check the breakpoint, you can use the info command, as shown below: (Note: n means breakout number)
Info Breakpoints [N]
Info Break [N]
Second, set the observation point (WatchPoint)
Watching points generally observe whether an expression (variable is also an expression) value varies, if there is a change, stop the program immediately. We have several ways to set the observation point:
Watch
Set an observation point for expression (variable) expr. When the one-volume expression value changes, the program is stopped immediately.
RWATCH
When the expression (variable) expr is read, the program is stopped.
awatch
When the value of the expression (variable) is read or written, the program is stopped.
INFO WATCHPOINTS
List all currently set observations.
Third, set the capture point (CatchPoint)
You can set the capture point to make some events at runtime. Such as: Load shared library (dynamic link library) or C exception. Set the format of the capture point:
Catch
When Event occurs, stop the program. Event can be the following:
1. Throw a C throw an exception. (Throw is key)
2, catch a C capture exception. (Catch is keyword)
3, when Calling EXEC calls system. (EXEC is keyword, currently this function is only useful under HP-UX)
4. When the Fork call system calls fork. (Fork is keyword, this feature is currently useful under HP-UX)
5, the VFORK call system calls vfork. (Vfork is keyword, this feature is currently useful under HP-UX)
6, when LOAD or LOAD loads the shared library (dynamic link library). (LOAD is keyword, this function is currently useful under HP-UX) 7, unload or unload to uninstall the shared library (dynamic link library). (Unload is keyword, currently this function is only useful under HP-UX)
Tcatch
Only one capture point is set. After the program is stopped, the should be automatically deleted.
Fourth, maintain the stop point
The above mentioned how to set the stop point of the program, the stop point in the GDB is the three classes described above. In GDB, if you feel that the defined stop point is not used, you can use the delete, clear, disable, and enable, these commands to maintain.
Clear
Clear all defined stop points.
Clear
Clear
Clear all stop points on the function.
Clear
Clear
Clear all stop points on the specified line.
Delete [BreakPoints] [Range ...]
Delete the specified breakpoint, BreakPoints is a breakpoint. If the break point is not specified, it means deleting all breakpoints. Range represents the range of breakpoints (such as: 3-7). Its shorthand command is D.
A better way to delete is the disable stop point. The stop point of Disable, the GDB will not be deleted. When you need it, Enable is as follows.
Disable [BreakPoints] [Range ...]
The stop point specified by disable, BreakPoints is the stop point number. If nothing is specified, it means all stop points for Disable. The shorthand command is DIS.
Enable [BreakPoints] [Range ...]
The stop point specified by Enable, BreakPoints is the stop point number.
Enable [BreakPoints] onCE Range ...
The stop point specified by Enable is once, and the stop point is immediately automatically disable by GDB after the program is stopped.
Enable [BreakPoints] delete Range ...
The stop point specified by Enable once, when the program is stopped, the stop point is automatically deleted by GDB.
5. Stop condition maintenance
As mentioned earlier, when we mentioned the breakpoint, we mentioned that you can set a condition. When the conditions are set up, the program is automatically stopped. This is a very powerful function. Here, I want to tell the relevant maintenance commands for this condition. In general, set a condition for breakpoints, we use the IF keyword, followed by its breakpoint conditions. Moreover, after the condition is set, we can use the construct command to modify the conditions of the breakpoint. (Only Break and Watch Commands Support IF, Catch does not currently support IF)
Condition
Modify the break condition of the BNUM to Expression.
Condition
Clear the break condition of BNUM.
There is also a particularly special maintenance command ignore, you can specify the program run, ignore the stop condition a few times.
Ignore
Indicates that the stop condition COUNT is ignored by the broken point number BNUM.
6. Set the run command for the stop point
We can use the Command command provided by GDB to set the run command of the stop point. That is, when the running program is stopped, we can make it automatically run for some other commands, which is advantageous to automate debugging. GDB-based automation debugging is a powerful support.
Commands [BNUM]
... Command-List ...
end
Write a list of commands for the breakpoint BNUM. When the program is stopped by the breakpoint, the GDB will run the command in the command list. E.g:
Break foo if x> 0
Commands
Printf "x is% d", x
Continue
end
The breakpoint is set in the function foo, the breakpoint condition is X> 0, if the program is broken, that is, once the value is greater than 0 in the foo function, GDB automatically prints the value of X and continues the program .
If you want to clear the command sequence on the breakpoint, just make a commands command, and you will do it directly.
Seven, breakpoint menu
In C , you may repeated a function of the same name (function overload), in which case Break
Can't tell GDB to stop in which function is in the entrance. Of course, you can use Break
That is to tell GDB parameter type of the function to specify a function. Otherwise, GDB will list a break menu for you to choose the breakpoint you need. You just need to enter the number in your menu list. Such as:
(GDB) B String :: after
[0] CANCEL
[1] all
[2] File: string.cc; line number: 867
[3] File: string.cc; line number: 860
[4] File: string.cc; line number: 875
[5] File: string.cc; line number: 853
[6] File: string.cc; line number: 846
[7] File: string.cc; line number: 735
> 2 4 6
BreakPoint 1 at 0xB26C: File string.cc, line 867.
BreakPoint 2 at 0xB344: File string.cc, line 875.
BreakPoint 3 at 0xAFCC: File string.cc, line 846.
Multiple Breakpoints Were Set.
Use the "delete" Command to Delete Unwanted
Breakpoints.
(GDB)
It can be seen that GDB lists all After's overloaded functions, you can choose the list number. 0 indicates that the setting breakpoint is given, and 1 means that all functions set breakpoints.
Eight, recovery procedures running and single-step debugging
When the program is stopped, you can use the Continue command to recover the run until the end of the program, or the next breakpoint. You can also use the STEP or NEXT command single-step tracker.
Continue [ignore-count]
c [ignore-count]
FG [ignore-count]
The recovery program is running until the program ends, or the next breakpoint arrives. Ignore-count indicates that the number of breakpoints is ignored. The three commands of Continue, C, and FG are the same meaning.
STEP
Single step tracking, if there is a function call, he will enter the function. The premise of entering the function is that this function is compiled with Debug information. Very like Step in in Tools such as VC. Behind COUNT can also not be added, do not add a strip execution, plus the COUNT section instruction to execute, and then stop.
NEXT
Also single step tracking, if there is a function call, he will not enter the function. Very STEP over, such as the VC and other tools. Behind COUNT can also not be added, do not add a strip execution, plus the COUNT section instruction to execute, and then stop.
Set step-modeset step-mode on
Open STEP-MODE mode, so, the program does not stop because there is no DEBUG information when performing single-step tracking. This parameter is favorable to view the machine code.
Set Step-mod OFF
Turn off Step-Mode mode.
Finish
Run the program until the current function completes the return. And print functions returned to the stack address and return value and parameter value.
Until or U
When you are tired of walking in a cyclic body, this command can run the program until the cyclic body is exited.
Stepi or Si
Nexti or Ni
Single step tracking a machine directive! A program code may be completed by several machine instructions, STEPI and NEXTI can perform machine instructions in a single step. As with the same function as the same function is "Display / I $ PC", after running this command, single-step tracking will play machine instructions while playing the program code (that is, assembly code)
Nine, signals (SIGNALs)
The signal is a soft interrupt, a method of processing an asynchronous event. In general, the operating system supports many signals. Especially UNIX, compare important applications generally process signals. Unix defines a number of signals, such as Sigint represents the interrupt character signal, that is, the signal of Ctrl C, Sigbus represents the signal of the hardware fault; SIGCHLD represents the signal of the child process; Sigkill indicates the signal of the termination program, and the like. Semicidal programming is a very important technology under UNIX.
GDB has the ability to deal with any signal when you debug the program, you can tell GDB which signal needs to process. You can ask GDB When you receive the signal you specified, you will stop running the program that is running for you to debug. You can use the GDB's handle command to complete this feature.
Handle
Define a signal processing in GDB. signal
You can use the SIG or not starting with SIG, you can use the range to process the signal (such as: sigio-sigkill, indicating processing from the SIGIO signal to Sigkill, including SIGIO, SIGIOT, SIGKILL three signals), or Use the keyword all to indicate all signals to process. Once the debugged program receives the signal, the running program will be immediately stopped by GDB for debug. its
It can be one or more of the following keywords.
Nostop
When the debugging program receives the signal, GDB does not stop the running of the program, but the message will tell you that this signal is received.
STOP
When the debugging program receives the signal, GDB will stop your program.
When the debugging program receives the signal, GDB will display a message.
Noprint
When the debugged program receives the signal, GDB will not tell you information about the signal.
PASS
NoIgnore
When the debugging program receives the signal, the GDB does not process the signal. This means that GDB will hand over this signal to the debugged program.
NOPASS
Ignore
When the debugged program receives the signal, GDB does not allow the debugger to process this signal.
INFO SIGNALS
Info Handle
See what signal is in GDB detection.
Ten, thread stops
If your program is multi-thread, you can define if your breakpoint is on all threads or in a particular thread. GDB is easy to help you have completed this.
Break
Thread
Break
Thread
IF ...
LINESPEC specifies the line number of the source program that breakpoints set. Threadno Specifies the id's ID, note that this ID is GDB assignment, you can view thread information in the program through the "Info Threads" command. If you don't specify Thread, you indicate that your breakpoint is located on all threads. You can also specify a breakpoint condition for a thread. Such as:
(GDB) Break frik.c: 13 Thread 28 If Bartab> Lim
When your program is parked by GDB, all running threads will be stopped. This makes it easy you to view the overall situation of the running program. And all threads are still running when you are running in your recovery program. It is afraid that the main process is in a single step of debugging.
View stack information
-----
When the program is stopped, the first thing you need to do is to check where to stop. When your program calls a function, the address, function parameters, and the local variables in the function will be pressed into the "stack". You can use the GDB command to see the information in the current stack.
Here is some GDB commands for viewing the function call stack information:
Backtrace
BT
Print all the information of the current function call stack. Such as:
(GDB) BT
# 0 func (n = 250) At tst.c: 6
# 1 0x08048524 in main (argc = 1, argv = 0xBfffff674) At tst.c: 30
# 2 0x400409ed in __libc_start_main () from /lib/libc.so.6
From the above you can see the call stack information of the function: __ libc_start_main -> main () -> func ()
Backtrace
BT
n is a positive integer that means that only the stack information of the N layer on the top of the stack.
Backtrace <-n>
BT <-n>
-n table a negative integer, indicating that only the stack information of the N layer under the stack.
If you want to see a layer of information, you need to switch the current stack, in general, the program is stopped, the top of the stack is the current stack, if you want to check the details of the stack, first you want to do it first. Switch the current stack.
Frame
fly
n is an integer starting from 0 and is a layer number in the stack. For example: frame 0, represents the top of the stack, FRAME 1, indicating the second layer of the stack.
UP
Indicates that the upper surface of the stack moves the N layer, and may not be hit N, indicating that the upward movement is moved.
Down
Indicates that the N layer is moved to the stack, and may not beat N, indicating a downward movement.
The above command will print out information of the moving stack layer. If you don't want it to make it. You can use these three commands:
SELECT-FRAME
Corresponds to the frame command.
Up-Silently
Corresponds to the UP command.
Down-Silently
Corresponds to the Down command.
View the current stack of information, you can use the following GDB command:
Frame or F
This information will be printed: The stack layer number, the current function name, the function parameter value, the file and the line number where the function is located, the function being executed.
INFO FRAME
Info f
This command prints the information of more detailed current stack layers, but most of them are within the internal address of the runtime. For example, the function address, the address of the call function, the address called function, the current function is written by, the function parameter address, the value, the address, and the like of local variables, etc. Such as:
(GDB) Info F
Stack level 0, frame at 0xBffff5d4:
EIP = 0x804845d in func (tst.c: 6); saved eip 0x8048524called by frame at 0xBfff 10c
Source Language C.
Arglist at 0xBfffFf5D4, Args: n = 250
Locals AT 0xBfffff5D4, Previous Frame's SP IS 0x0
Saved registers:
EBP AT 0XBFFFF5D4, EIP AT 0xBffff5D8
Info args
Print the parameter name and its value of the current function.
Info locals
Print all local variables and their values in the current function.
INFO CATCH
Print an exception handling information in the current function.
View the source program
-----
First, display source code
GDB can print out the source code of the debugprue, of course, be sure to add -g parameters when compiling, and compile the source program information into the execution file. Otherwise, you can't see the source program. When the program stops, the GDB will report that the program stopped on the first few lines of the file. You can use the list command to print the source code of the program. Let's take a look at the GDB command to view the source code.
List
Displays the source program around the Linenum line.
List
Displays the source program of the function called function name FUNCTION.
List
Displays the source program behind the current line.
List -
Displays the source program in front of the current row.
Generally, print the top 5 rows of the current row, if the display function is on the top 2 line 8 line, the default is 10 lines, of course, you can customize the range of display, use the following command to set a display source program The number of rows.
Set listsize
Set the number of rows that displays the source code.
Show Listsize
View the current ListSize settings.
The List command has the following usage:
List
,
Displays the source code between the first line to the LAST line.
List,
Displays the source code from the current line to the LAST line.
List
The source code is displayed later.
Generally speaking, you can follow the following parameters after List:
Line number.
< Offset> The positive offset of the current line number.
<-offset> The negative shift of the current line number.
Which file is of which file.
Function name.
Which function in which file is in.
<* Address> The address of the statement of the program runs in memory.
Second, search source code
Not only that, GDB also provides commands for source code search:
Forward-Search
Search
Search in front.
Reverse-Search
All search.
among them,
It is the regular expression, and the main string matching mode, about the regular expression, I will not talk about it here, please check the relevant information.
Third, the path to specify the source file
At some point, in the execution program compiled with -g, just includes the name of the source file, no path name. GDB provides commands that allow you to specify the path to the source file to search for GDB.
Directory
DIR
Add a source file path to the front of the current path. If you want to specify multiple paths, you can use ":", you can use ":" and Windows.
Directory
Clear all custom source file search path information.
Show Directories
Displays the defined source file search path.
Fourth, the memory of the source code
You can use the Info Line command to view the address of the source code in memory. Info Line, you can follow the "Row", "Function Name", "File Name", "File Name: Function Name", this command prints the memory address of the specified source code at runtime, such as:
(GDB) Info line tst.c: func
Line 5 of "TST.C" Starts At Address 0x8048456and Ends AT 0x804845D
.
There is also a command that you can view the current execution of the source program, this command will take the command dump in the current memory. As shown below, the assembly code of the function FUNC is viewed.
(GDB) Disassemble Func
Dump of assembler code for function func:
0x8048450
: PUSH% EBP
0x8048451
: MOV% ESP,% EBP
0x8048453
: SUB $ 0x18,% ESP
0x8048456
: MOVL $ 0x0, 0xfffffffc (% EBP)
0x804845d
: MOVL $ 0x1, 0xffffffff8 (% EBP)
0x8048464
: MOV 0xfffffff8 (% EBP),% EAX
0x8048467
: CMP 0x8 (% EBP),% EAX
0x804846A
: jle 0x8048470
0x804846C
: JMP 0x8048480
0x804846e
: MOV% ESI,% ESI
0x8048470
: MOV 0xfffffff8 (% EBP),% EAX
0x8048473
: Add% EAX, 0xfffffffc (% EBP)
0x8048476
: INCL 0xFFFFFFF8 (% EBP)
0x8048479
: JMP 0x8048464
0x804847B
: NOP
0x804847c
: LEA 0x0 (% ESI, 1),% ESI
0x8048480
: MOV 0xFffffFfc (% EBP),% EDX
0x8048483
: MOV% EDX,% EAX
0x8048485
: JMP 0x8048487
0x8048487
: MOV% EBP,% ESP
0x8048489
: POP% EBP
0x804848A
: RET
End of assembler dump.
View runtime data
-------
When you debug the program, when the program is stopped, you can use the print command (the shortup command is P), or syncing the command inspect to view the current program running data. The format of the print command is:
PRINT /
It is an expression, which is the language of the language you debugging (GDB can debug multiple programming languages).
It is the format of the output, for example, if you want to output the expression in the format of the 16-in-1, then / x.
First, expressions
PRINT and many GDB commands, you can accept an expression, and GDB calculates this expression according to the data running in the current program. Since it is an expression, it can be a CONST constant, variable, function, etc. in the current program. content. Unfortunately, GDB can't use the macro you defined in the program.
The expression of the expression should be the syntax of the language currently debugged, since C / C is a public type of language, so the examples in this article are about C / C . (And I will introduce later, I will introduce later)
In the expression, there are several operators supported by GDB, which can be used in any language.
@
It is an operator related to the array that will be described in more detail later.
::
Specify a variable in a file or a function.
{
}
Represents a pointing memory address
Type of Type.
Second, program variables
In GDB, you can view the values of the following three variables at any time:
1. Global variables (visible all files)
2, static global variable (visible to the current document)
3, local variable (current Scope visible)
If your local variables and global variables have collisions (which is the reintegration), the local variable hides the global variable, that is, if a global variable and the local variable in a function, if the current stop point In the function, the value of the variable displayed with PRINT is the value of the local variable in the function. If you want to view the value of global variables, you can use the "::" operator:
FILE :: Variable
Function :: Variable
You can specify the variable you want to view in this form, which file is in or in the function. For example, check the value of the global variable X in the file f2.c:
GDB) P 'f2.c' :: x
Of course, "::" Operations and C conflicts, GDB can automatically identify "::" whether C operators, so you don't have to worry that there will be exceptions when debugging C programs.
In addition, it is important to note that if your program is compiled, the optimized option is turned on, then some variables may not be accessed when using GDB to be optimized, or the value of the value is incorrect. This is normal, because the optimizer will delete your program, organize your program's order, eliminate some meaningless variables, so when you debug this program, the runtime instruction and you write instructions. Different, there will be no results you think. When this is done, it is necessary to turn the compilation optimization when the compiler is compiled. In general, almost all compilers support compilation optimized switches, for example, GNU's C / C compiler GCC, you can use the "-gstabs" option to solve this problem. For parameters for the compiler, please check the instructions documentation for the compiler.
Third, array
Sometimes you need to see a value of a continuous memory space. For example, a parameter of an array or the size of the data that is dynamically allocated. You can use the "@" operator, "@" operator, "@" is the value of the first memory address, "@", you want to see the length of memory. For example, there is such a statement in your program:
INT * Array = (int *) Malloc (len * sizeof (int));
So, during the GDB debugging process, you can display this dynamic array with the following command:
P * array @ le
@ 的 边 The value of the first address of the array is the content pointed to by the variable Array. The right side is the length of the data, which is saved in the variable LEN, its output result, about the following:
(GDB) P * array @ le
$ 1 = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40}
If it is a static array, you can display all the contents of all the data in the array can be displayed directly with the Print array name.
Fourth, output format
In general, GDB outputs the value of variables according to the type of variable. But you can also customize the format of the output of GDB. For example, you want to output an integer hexadecimal, or binary to view the situation in this integer variable. To do this, you can use GDB data display format:
x Display variables in hexadecimal format.
d Display variables by decimal format.
u Display unsigned integer in the hexadecimal format.
o Display variables in eight-en-binary format.
t Press binary format to display variables.
a Display variables in hexadecimal format. c Press the character format display variable.
f Display variables in floating point.
(GDB) P i
$ 21 = 101
(GDB) P / A i
$ 22 = 0x65
(GDB) P / C i
$ 23 = 101 'e'
(GDB) P / F i
$ 24 = 1.41531145E-43
(GDB) P / x i
$ 25 = 0x65
(GDB) P / T i
$ 26 = 1100101
Five, check the memory
You can use the examine command (short-write Yes x) to see the value in the memory address. The syntax of the x command is as follows:
X /
n, f, u is an optional parameter.
n is a positive integer that represents the length of the memory, that is, the content of several addresses from the current address.
f represents the format displayed, see above. If the address refers to a string, the format can be s, if the ten is the command address, then the format can be i.
u Represents the number of bytes requested from the current address, if not specified, the GDB defaults to 4 Bytes. u Parameters can be replaced with the following characters, b represents a single byte, h represents double bytes, w represents four bytes, g represents eight bytes. When we specify the length of the byte length, the GDB will start from the memory address, read and write the specified byte, and take it as a value.
Represents a memory address.
The three parameters of n / f / u can be used together. E.g:
Command: x / 3uh 0x54320 is represented, from the memory address 0x54320 read content, H indicates that the double-byte is one unit, and 3 represents three units, u means that it is displayed in hexadecimal display.
Six, automatic display
You can set some of the automatically displayed variables, or when the program is stopped, or when you are single-step tracking, these variables are automatically displayed. The associated GDB command is Display.
DISPLAY
DISPLAY /
DISPLAY /
EXPR is an expression, FMT represents the format of the display, and addr represents the memory address. When you set one or more expressions with Display, as long as your program is stopped, GDB will automatically display these these The value of the expression.
Format I and S are also supported by Display, a very useful command is:
Display / i $ PC
$ PC is a gdb environment variable, indicating the address of the command, / i indicates the output format as the machine instruction code, which is compilation. So when the program is stopped, the source code and the machine command code correspond to the case, which is a very interesting feature.
Here are some GDB commands related to Display:
Undisplay
DELETE DISPLAY
Delete automatic display, DNUMS means the set automatic explicit number. If you are deleted at the same time, the number can be separated by a space. If you want to delete a range number, you can use the minus sign (eg 2-5)
Disable display
Enable display
Disable and ENALBE do not delete automatic display settings, but just make it fails and recovered.
Info Display
View the automatic display of Display settings. GDB will play a form and report how many automatic display settings set in the debug, which includes, set numbers, expressions, whether eNABLE.
7. Set display options
There are more options on the display in GDB. Here I will only exist of most common options.
Set Print Address
Set Print Address ON
Open the address and output, when the program displays the function information, GDB will display the parameter address of the function. The system defaults to open, such as: (GDB) f
# 0 set_quotes (lq = 0x34c78 "<<", rq = 0x34c88 ">>")
AT INPUT.C: 530
530 if (LQUOTE! = Def_lquote)
Set Print Address Off
Close the parameter address of the function display, such as:
(GDB) Set Print Addr OFF
(GDB) F
# 0 set_quotes (lq = "<<", rq = ">>") at input.c: 530
530 if (LQUOTE! = Def_lquote)
Show Print Address
Check if the current address display option is open.
Set Print Array
Set Print Array ON
Open the array display, when the array is turned on, each element occupies a row, if it is not opened, each element is separated by a comma. This option is closed by default. The two commands related to it are as follows, I will not say more.
Set Print Array Off
Show Print Array
Set Print Elements
This option is mainly setting array. If your array is too big, then you can specify a
To specify the maximum length of the data display, when the length is reached, GDB will no longer be displayed down. If set to 0, it is not limited.
Show Print Elements
Check the option information for Print Elements.
Set Print Null-Stop
If this option is turned on, then when the string is displayed, the end is displayed. This option defaults to OFF.
Set Print Pretty on
If you open the PrintF pretty option, then it is more beautiful when the GDB displays the structure. Such as:
$ 1 = {
NEXT = 0x0,
Flags = {
Sweet = 1,
Sour = 1
}
MEAT = 0x54 "PORK"
}
Set Print Pretty OFF
Turn off the Printf Pretty this option, the GDB displays the structure as follows:
$ 1 = {Next = 0x0, Flags = {SWEET = 1, Sour = 1}, meat = 0x54 "pork"}
Show Print Pretty
View how GDB displays structures.
Set print sevenbit-strings
Set the character display, press "NN" format display, if the string or character data is displayed by Nn, such as "65"
Show print sevenbit-strings
View the character display switch is open.
Set Print Union
When the display structure is displayed, it is explicitly in which the consortium data is displayed. For example, there are the following data structure:
Typedef enum {tree, bug} species;
Typedef enum {BIG_TREE, Acorn, Seedling} Tree_Forms
Typedef enum {catterpillar, cocoon, butterfly}
Bug_Forms;
Struct thing {
Species it;
Union {
Tree_Forms Tree;
Bug_Forms bug;} form;
}
Struct thing foo = {Tree, {acorn}};
When this switch is turned on, after executing the P foo command, it will be displayed as follows:
$ 1 = {It = Tree, Form = {Tree = acorn, bug = cocoon}}}
When the switch is turned off, then the P foo command is executed, it will be displayed as follows:
$ 1 = {It = Tree, Form = {...}}
Show Print Union
Viewing the display of the consortium data
Set Print Object
In C , if an object pointer points to its partial class, if the option is opened, the GDB will automatically display the output according to the rule called by the virtual method. If this option is turned off, GDB regards the virtual function table. This option is OFF by default.
Show Print Object
View the settings for the object option.
Set Print Static-Members
This option indicates that when the content in a C object is to display the static data member. The default is ON.
Show print static-members
Check the static data member option settings.
Set Print VTBL
When this option is opened, GDB will display the virtual function table with a comparison format. Its default is closed.
Show Print VTBL
View the options for virtual functions display format.
Eight, history
When you use the GDB's print to view the data running data, you will be recorded by GDB. GDB will make every print command for your way in a way in $ 1, $ 2, $ 3 ...... Thus, you can use this number to access the previous expressions, such as $ 1. The benefits of this feature are that if you have previously entered a relatively long expression, if you want to view the value of this expression, you can use history to access, save your duplicate input.
Nine, GDB environment variables
You can define your own variables in the GDB debug environment to save running data in some debuggers. To define a variable of a GDB is simple. Use the GDB's set command. GDB's environment variables are the same as UNIX, is also a head. Such as:
SET $ foo = * Object_ptr
When using environment variables, GDB creates this variable when you first use, and in later use, it assigns it directly. Environment variables have no type, you can define any type to the environment variable. Includes structures and arrays.
SHOW Convenience
This command views all environment variables currently set.
This is a relatively powerful function, environmental variable, and program variable interaction, which will make program debugging and convenient. E.g:
Set $ i = 0
Print Bar [$ I ] -> Contents
So, when you don't have to, Print Bar [0] -> Contents, Print Bar [1] -> Contents Enter the command. After entering such a command, only the knock back, repeat the previous statement, the environment variable will be automatically accumulated, thereby completing the function of outputting one by one.
Ten, check the register
To view the value of the register, it is easy, you can use the following command:
Info registers
View the situation of the register. (Except floating point registers)
Info all-registers
View all registers. (Including floating point registers)
Info registers
View the situation of the specified register.
The program is placed in the register, such as the currently running instruction address (IP), the current stack address (SP) of the program, and the like. You can also use the print command to access the register, just add a $ symbol before the register name. Such as: p $ EIP. Change the execution of the program
-------
Once you use the GDB to hang up the debugger, when the program runs, you can dynamically change the current debugger running line or the value of its variable according to your own debugging ideas, this powerful function can make you Better debugging your program, for example, you can run all the branches of the program in the program.
First, modify the variable value
Modify the variable value when the debugger is running, it is easy to implement in GDB, and you can complete it using GDB's print command. Such as:
(GDB) Print x = 4
X = 4 This expression is the syntax of C / C , meaning that the value of the variable x is modified to 4, if your current debugging is Pascal, then you can use Pascal's grammar: x: = 4.
At some point, it is very likely that your variables and parameters in GDB conflicts, such as:
(GDB) WHATIS WIDTH
TYPE = DOUBLE
(GDB) P Width
$ 4 = 13
(GDB) set width = 47
Invalid Syntax in Expression.
Because set width is the command of GDB, "Invalid Syntax In Expression" appears error, at this time, you can use the set var command to tell GDB, Width is not your GDB parameter, but the program's variable name, Such as:
(GDB) set var width = 47
In addition, there may be some cases, GDB does not report such an error, so the insurance starts, preferably when you change the program variable, it is best to use the set var format GDB command.
Second, jump execution
In general, the debugging procedure will be executed in accordance with the running order of the program code. GDB provides the function of chaos, that is, GDB can modify the execution order of the program, allowing the program to execute cashed. This feature can be over the jump command of GDB:
Jump (Linespec)
Specifies the operating point of the next statement. (linesPCE) can be the line number of the file, which can be file: line format, which can be Num this offset format. The table is the next operational statement where to start.
Jump (address)
Here (address) is the memory address of the code line.
Note that the jump command will not change the content in the current program stack, so when you jump from a function to another, the function will have errors when the function runs back, and the possible results are still very strange. Even generation of program core dump. So it is best to jump in the same function.
People who are familiar with assembly know that when the program is run, there is a register to save the memory address where the current code is located. Therefore, the JUMP command is also changing the value in this register. Thus, you can use the "SET $ PC" to change the address of the jump execution. Such as:
SET $ PC = 0x485
Third, generate semaphore
Use the Singal command to generate a signal to be debugged. Such as: Interrupt Signal Ctrl C. This is very convenient for debugging of the program, setting breakpoints in any position running, and generating a semaphore in this breakpoint, which accurately generates a debugging of the signal at some point. Syntax is: Signal
The system seminated system seminated in Unix is usually from 1 to 15. and so
The value is also in this range.
Different Single Commands and Shell's Kill commands, when the system's kill command signals to the debugged program, it is intercepted by GDB, and a signal from the SINGLE command is sent directly to the debugged program.
Fourth, the mandatory function returns
If your debug break is in a function, and there is still a statement that is not executed. You can use the return command to force the function ignore the statements that have not yet been executed and return.
Return
Return
Use the return command to cancel the execution of the current function and return it now, if specified
Then, the value of the expression is recognized as the return value of the function.
V. Forced call functions
Call
The expression can be a function in the expression to achieve the purpose of the forced call function. And display the return value of the function, if the function returns the value is Void, then it is not displayed.
Another similar command can also complete this feature --Print, which can be followed by the expression, so it can also be used to call the function, the varint, and call are different. If the function returns Void, Call does not display, Print The display function returns the value and stores the value into historical data.
Use GDB in different languages
------------
GDB supports the following languages: C, C , Fortran, Pascal, Java, Chill, Assembly, and Modula-2. Generally speaking, GDB will determine the debug language according to the program you debug, such as: Discovering the file name suffix ".c", GDB will consider a C program. The file name suffix is ".c, .cc, .cp, .cpp, .cxx, .c ", GDB will consider a C program. The suffix is ".f, .f", GDB will consider the Fortran program, and if the suffix is ".s, .s" will consider the assembly language.
That is, GDB will set their own language environment based on the language of the program you debug, and let GDB's commands change to change the language environment. For example, some GDB commands require expression or variables, the syntax of these expressions or variables is completely changed according to the current locale. For example, the syntax of the pointer in C / C is * P, and in the modula-2 is P ^. Also, if your current program is compiled by several different languages, the GDB can automatically switch the locale according to different languages during the debugging. This function of changing the language environment is really a design of the developer.
Here are a few commands related to the GDB locale:
SHOW LANGUAGE
View the current locale. If GDB does not know the programming language you debug, then the C language is considered a default environment.
INFO FRAME
View the program language of the current function.
Info Source
View the program language of the current file.
If the GDB does not detect the current programming, you can also manually set the current program language. Use the set language command to do.
When you don't follow the set language command, you can view the language type supported by GDB:
(GDB) Set Language
The Currently Understood Settings Are:
Local or Auto Automatic Setting Based on Source Filec Use the C Language
C Use THE C Language
ASM Use the asm language
Chill Use the Chill Language
Fortran Use the fortran language
Java Use the Java Language
MODULA-2 Use The Modula-2 Language
Pascal Use the Pascal Language
Scheme Use the scheme language
So you can keep up with the list of quilted programs that are listed after Set Language to set the current locale.
postscript
-
GDB is a powerful command line debugging tool. Everyone knows the power of the command line that it can form a sequence to form a script. The software under UNIX is the command line. This gives the program development for great convenience, the advantage of the command line software is that they can be very easy to integrate, using a few simple tools, You can make a very powerful feature.
So the software under UNIX is more organically combined than the software under Windows, and each exerts each of the strengths and combines a stronger function. The graphics software under Windows is basically the camp, which cannot be called, which is very disadvantageous for the integration of various software. It is not what comparable to Windows, the so-called "inch", the feature is short ", the graphics tool is still a place that is not as good as the command line. (When you see this sentence, I hope that you will never think that I am "despise the graphical interface", and I raise my bar)
I am writing this article based on the version 5.1.1, so some functions have been modified, or there is a more powerful feature. Moreover, I wrote very rush, it is more written, and I have seen many of the wrong words (I use five, so the wrong word makes you can't understand), so I am here to express my mistake in my text. Apologize.
When the function of the GDB in the text, I just collected some of the commands and usage methods of GDB, in fact, I only explain the features of all GDBs, more documents, or see it, please check GDB's help and use manual, perhaps, after a while, if I have time, I will write a GDB's advanced use.
I personally like the function of automatic debugging of GDB. This feature is really powerful. I am really powerful. I write a script under UNIX, let the script automatically compile my program, automatically debug, and report the results, debugging, automatic Checkin source code library. A order, compile with commissioning with Checkin, more cool. Just GDB is not very mature for automated debugging, only semi-automated, and sincerely expects the maturity of GDB automation debugging.