From http://www.loveunix.net/bbs/index.php?showtopic=28564
------------------
Haoel (original)
QQ: 753640
MSN: haoel@hotmail.com
Transfer from 9CBS
---------------------------------(One)-------------- -------------------------
[GDB overview]
----
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
Code
?? 1 #include
? ? 2
? 3 int func (int N)
?? 4 {
?? 5??? Int sum = 0, i;
??????????????????????????????????????????????????????????????
?? 7??? {
???????????????????????????????? Sum = i;
? ? 9 ? ? ? ? }
?? 10???? Return Sum
?? 11}
?? 12
?? 13
?? 14 main ()
?? 15 {
?????? INT i;
?? 17??? Long result = 0;
????? For (i = 1; i <= 100; i )
?? 19??? {
???????? Y?
? ?twenty one ? ? ? ? }
? ?twenty two
?? 23??? Printf ("Result [1-100] =% D / N", Result);
?? 24??? Printf ("Result [1-250] =% D / N", FUNC (250));
?? 25}
Compile generation execution file: (linux)
HCHEN / TEST> CC -G TST.C -O TST
Use GDB debugging:
Code
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 '
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? <------------------- command is equivalent to 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???? Return Sum (GDB)? <-------------------- direct carriage return, repeat the last order 11?? 12 13 14?? Main () 15??? { 16??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????? 17???????????????? " 18???? FOR (i = 1; i <= 100; i ) 19???? { 20???? Y????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????? (GDB) BREAK 16? <------------------ Set breakpoint, in the 16th line of the source program. Breakpoint 1 at 0x8048496: File Tst.c, Line 16. (GDB) BREAK FUNC? <------------------ Set breakpoint, at the entrance to the function func (). Breakpoint 2 at 0x8048456: File Tst.c, Line 5. (GDB) Info Break? <-------------------- View breakpoint information. Num Type????? Disp Enb 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???? <--------------------- Run the program, run command Starting Program: / HOME / HCHEN / TEST / TST BreakPoint 1, Main () at tst.c: 17? <---------- Announced at the breakpoint. 17???????????????? " (GDB) n??? <--------------------- Single statement execution, Next command is short. 18???????????????????????????????????????????????????????????????,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ??????????? 20 result = i; (GDB) N 18???? FOR (i = 1; i <= 100; i ) (GDB) N ??????????? 20 result = i; (GDB) C??? <--------------------- Continue to run the program, 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 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? <------------------- Exit function. Run Till exit from # 0? Func (n = 250) at tst.c: 5 0x080484e4 in main () at tst.c: 24 24???? Printf ("Result [1-250] =% D / N", FUNC (250)); Value Returned IS $ 6 = 31375 (GDB) C? <--------------------- continued to run. Continuing. Result [1-250] = 31375? <---------- Program Output. Program evted with code 027. <-------- Program exits, the debugging ends. (GDB) Q? <--------------------- Exited 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 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: Code / 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 Commandsobscure - 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 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. Code 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. [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 to perform the Another GDB command is make: Make You can execute the make command in GDB to re-build your own program. This order is equivalent to "shell make [Running procedures in GDB] ------------ When GDB is started in GDB 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
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 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) that is running with PS under UNIX, and then hooks the running program with GDB
2, first use GDB
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. Code
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, load or load
7, unload or unload
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
In front of the setup breakpoint, we mentioned that you can set a condition. When the condition is established, the program is automatically stopped. This is a very powerful function. Here, I want to tell the relevant maintenance command of 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
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 / N", 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 repeat the function of the same name (function overload), in which case BREAK
(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 similar to Step over. 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-Mode
Set 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 and is 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
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
Break
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
(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.