Linux GDB Debugger Usage Complete parsing __linux

Source: Internet
Author: User
Tags semaphore gdb debugger

GDB is the GNU Open source organization released a powerful UNIX program debugging tools, GDB can help engineers to complete the following 4 aspects of the function: Start the program, can be customized according to the requirements of the engineer to run the program. Let the program being debugged stop at the breakpoint specified by the engineer, the breakpoint can be a conditional expression. When the program is stopped, you can check what happened in the procedure and trace it. Dynamically changing the execution environment of the program. Whether you are debugging a Linux kernel space driver or debugging a user-space application, it is essential to master GDB's usage. Also, the GDB command used to debug the kernel and debug the application is exactly the same, and the following example demonstrates the use of the GDB debugger in listing 22.2.

1  int Add (int a, int b)
2  {
3 return    a + b;
4  }
5  
6  Main ()
7  {
8    int sum[10] = 
9    {     0, 0, 0, 0, 0, 0, 0, 0, 0, 0     
one   }  ;   int i;   array1[10 int] = (in)-------------     544   />18   int array2[10] =   {
1,     2, 3, 4}, 0x199, 393   ;
For   (i = 0; i < i++)   {     sum[i] = Add (array1[i), array2[i]);   }
27}

Using the command gcc–g gdb_example.c–o gdb_example compile the above program, get the binary file containing debugging information example, execute the GDB gdb_example command into the debug state:

[Root@localhost driver_study]# gdb gdb_example
GNU gdb Red Hat Linux (5.3POST-0.20021129.18RH)
Copyright 2003 Free Software Foundation, Inc.
GDB is free software, covered by the GNU general public License, and your are
welcome to change it and/or distribute Co Pies of it under certain conditions.
Type ' show copying ' to the conditions.
There is absolutely no warranty for GDB.  Type ' show warranty ' for details.
This is GDB was configured as "I386-redhat-linux-gnu"
... (GDB)

1. List command

Running the List command (abbreviated L) in GDB allows you to list the code, in the form of List <linenum>, which shows the source program around the LineNum line, such as:

(GDB) List        int array1[10] =          ---------------------------------------- 21/>14        };        int array2[10] =        {1,          2, 3, 4}, 0x199, 393
, all; 19
list <function>, displaying the source program for functions called function functions, such as:
 List To display the source program after the current line. List-, displays the source program before the current line. 

The following is a procedure that uses the run (abbreviation R), break (abbreviated B), next (abbreviation N) command control program in GDB, and prints the variable sum in the program using the print (abbreviation P) command:

   
2. Run command

In GDB, run the program using the Run command. Before the program runs, we can set the following 4 aspects of the Working environment: The program run parameter set args can specify Run-time parameters, such as: Set args 50;show args command to see the set of running parameters. Operating Environment

Path <dir> programmable running paths; how paths can view the running path of the program; set environment VarName [=value] is used to set environment variables, such as set env User=baohua;

Show environment [VarName] is used to view environment variables. Working directory CD <dir> equivalent to Shell's CD command; pwd displays the current directory. The input and output of the program

Info terminal is used to display the mode of the terminal used by the program, and the redirection control program output can also be used in gdb, such as Run > outfile;

The TTY command can specify terminal devices for input and output, such as: Tty/dev/ttys1. 3. Break command

Use the break command in GDB to set breakpoints, including: Break <function> stop while entering the specified function, class::function or function (type, type) can be used in C + +. Format to specify the function name. Break <linenum> stop at the specified line number. The break +offset/break-offset stops at the offset line before or after the current line number, Offiset to the natural number. Break Filename:linenum stops at the LineNum line at the source file filename. Break filename:function stops at the entrance to the function function of the source file filename. Break *address stops at the memory address where the program is running. The break-break command stops at the next command when there are no parameters. Break ... if <condition>

"..." can be the condition of the above break <linenum> and break +offset/break–offset, and the condition is stopped when the condition is set up. For example, in the loop body, you can set the break if i=100 to stop the program when I is 100.

When viewing breakpoints, you can use the Info command, such as info breakpoints [n], info break [n] (n = breakpoint number). 4, one step command

During the debugging process, the next command is used for stepping, similar to VC + + step over. Next step does not go inside the function, and the step (abbreviated s) command that corresponds to next moves into the interior of a function, similar to that in VC + +. The following shows the execution of the step command, which executes the step into its internal "return A+b" at the Add () function call at line 23. Statement:

(GDB)
breakpoint 1 at 0x8048362:file gdb_example.c.
(GDB) Run
starting program:/driver_study/gdb_example 

Breakpoint 1, Main () at gdb_example.c:25          sum [I] = Add (Array1[i], array2[i]);
(GDB) Step
Add (a=48, b=85) at Gdb_example.c:3
3 return         A + b;
more complex uses for stepping in include:

Step <count>

Step-tracking, if there is a function call, enter the function (the prerequisite for entering the function is that the function is compiled with debug information). Follow the step without count to indicate the execution, plus the execution of the following Count bar, and then stop. Next <count> single-step Tracking, if there is a function call, it will not enter the function. In the same way, after next, no count represents the execution, plus the execution of the following count-bar instructions, and then stops. Set Step-mode set Step-mode on is used to open Step-mode mode so that the program does not stop because there is no debug information, and the setting of this parameter makes it easy to view machine code. Set Step-mod off is used to turn off Step-mode mode. Finish runs the program until the current function completes and prints the information such as the stack address and return value and parameter values when the function returns. until (abbreviation u) has been in the loop to perform a single step, it is annoying to retreat, until command can run the program until the body of the loop exit. Stepi (abbreviated SI) and Nexti (abbreviated NI) Stepi and Nexti are used to step through a machine instruction, a program code may be completed by several machine instructions, STEPI and Nexti can step through the machine instructions. In addition, after running the "display/i $pc" command, Single-step tracking will play out the machine instructions, the assembly code, while the program code is being played. 5, continue command

When the program is stopped, you can use the Continue command (abbreviated C,FG command with the Continue command) to restore the program to the end of the program, or to the next breakpoint, the command format:

Continue [Ignore-count]
c [Ignore-count]
FG [Ignore-count]
Ignore-count indicates how many breakpoints have been ignored thereafter. If we set the function breakpoint Add () and watch I, then in the continue process, every time you encounter the Add () function or I change, the program will stop, such as:

(GDB) Continue
continuing.
Hardware watchpoint 3:i old

value = 2
New value = 3
0x0804838d in Main () at gdb_example.c:23        (i = 0; i < i++)
(GDB) Continue
continuing.

Breakpoint 1, Main () at gdb_example.c:25          sum[i] = Add (array1[i), array2[i]);
(GDB) Continue
continuing.
Hardware watchpoint 3:i old

value = 3
New value = 4
0x0804838d into main () at gdb_example.c:23
23
   
    for (i = 0; i < i++)
   

6. Print command

When you debug a program, you can use the Print command (abbreviated as P) or the synonymous command inspect to view the running data of the current program when the program is stopped. The Print command is in the following format:

Print <expr>
 print/<f> <expr>

<expr> is an expression, is an expression in the program being debugged, <f> is the output format, for example, if you want to output the expression in 16 format, then it is/x. In an expression, there are several operators supported by GDB that can be used in any language, and "@" is an array of operators, "::" Specify a variable in a file or function, "{&LT;TYPE&GT} <addr>" indicates a point to memory address <addr> is an object of type.

The following shows the procedure for viewing the values of the sum[] array:

(gdb) print sum
$ = {0, 0, 0, 0, 0, 0, 0, 0}
(gdb) Next

Breakpoint 1, Main () at gdb_example.c:25
   25          Sum[i] = Add (Array1[i], array2[i]);
(GDB) Next
for        (i = 0; i < i++)
(gdb) print sum
$ = {133, 155, 143, 0, 0, 0, 0, 0, 0, 0}
When you need to view the value of a contiguous memory space, you can use the GDB "@" operator, the left of which is the first memory address, and the right of the @ to see the length of memory. For example, the following dynamically requested memory:

int *array = (int *) malloc (len * sizeof (int));

This displays the value of this dynamic array during the GDB debugging process:

P *array@len

The output format for print includes: x displays variables in hexadecimal format. D displays variables in decimal format. U displays the unsigned integer in hexadecimal format. o Display variables in octal format. T displays variables in binary format. A the variable is displayed in hexadecimal format. C displays variables in character format. F displays variables in floating-point format. We can use the display command to set some variables that are automatically displayed, and when the program stops, or when you step through it, these variables are automatically displayed. If you want to modify a variable, such as the value of x, you can use the following command:

Print x=4

When you use GDB's print to view the Run-time data of the program, each print is logged by GDB. GDB will use $1,$2,$3 ... This is the way to number each print command. We can use this number to access previous expressions, such as $. 7, watch command

Watch General to observe whether an expression (variable is also an expression) of the value has changed, if there is a change, immediately stop the program. We have the following methods to set the observation point: Watch <expr>: Set an observation point for expression (variable) expr. Stop the program as soon as the value of the expression changes. Rwatch <expr>: When the expression (variable) expr is read, stop the program. Awatch <expr>: Stops a program when the value of an expression (variable) is read or written. Info watchpoints: Lists all the observed points that are currently set. The following shows the process of observing I and once I change when I run next, I will show you the value of I:

(GDB) Watch i
hardware watchpoint 3:i
(gdb) Next
for        (i = 0; i < i++)
(gdb) Next
Hardwa  Re watchpoint 3:i old

value = 0
New value = 1
0x0804838d in Main () at gdb_example.c:23        (i = 0; I < 10; i++)
(gdb) Next

Breakpoint 1, Main () at gdb_example.c:25          sum[i] = Add (array1[i), Array2[i] c16/> (GDB) Next
for        (i = 0, i < i++)
(gdb) Next
hardware watchpoint 3:i old

value = 1< C22/>new value = 2
0x0804838d in Main () at gdb_example.c:23        (i = 0; i < i++)

8, examine command

We can use the Examine command (abbreviated to x) to view the values in the memory address. The syntax for the examine command is as follows:

<addr> represents a memory address. N, F, and U after "x/" are optional parameters, n is a positive integer indicating the length of the display memory, that is, displaying the contents of several addresses backwards from the current address; F indicates the format to display, if the address refers to a string, then the format can be S, if the address is the instruction address, then the format can be i;u Represents the number of bytes requested from the current address and, if not specified, gdb defaults to 4 bytes. The u parameter can be replaced by some characters: B for Single-byte, H for Double-byte, W for four bytes, and G for eight bytes. When we specify the byte length, GDB starts with the specified memory address, reads and writes the specified byte, and takes it out as a value. N, F, and u these 3 parameters can be used together, for example, the command "X/3uh 0x54320" indicates that 3 units (3) of memory are displayed in Double-byte 1 units (h) and 16 (U) from the memory address 0x54320. ==

For instance, the following example:

Main ()
{
        char *c = "Hello World";
        printf ("%s\n", c);
}

We are
char *c = "Hello World";
After setting a breakpoint on the next line:
(GDB) L
1    Main ()
2    {
3        char *c = "Hello World";
4        printf ("%s\n", c);
5    }
(GDB) b 4
breakpoint 1 at 0x100000f17:file main.c, line 4.
(GDB) r
starting program:/users/songbarry/main
Reading symbols for shared libraries +. Done

Breakpoint 1 , Main () at Main.c:4
4        printf ("%s\n", c);
You can see the string that C points to in a variety of ways:

Method 1:

(GDB) p C
$ = 0x100000f2e "Hello World"
Method 2:
(gdb) x/s 0x100000f2e
0x100000f2e:	 "Hello World"
Method 3:
(GDB) p (char *) 0x100000f2e
$ = 0x100000f2e "Hello World"
Change the first character to uppercase:
(GDB) p * (char *) 0x100000f2e= ' h '
$ = ' h '
Then look at c:
(GDB) p C
$ = 0x100000f2e "Hello World"

9, set command

Modify Registers:

(GDB) Set $v 0 = 0x004000000

To modify Memory:

(GDB) set {unsigned int}0x8048a51=0x0
For example, for the 8th section:

(GDB) set {unsigned int}0x100000f2e=0x0       
(gdb) X/10CB 0x100000f2e
0x100000f2e:	0 ' 0 '	0 '	0 ' 119 ' ' O ' '	0x100000f36 ' W '	o '
:	114 ' R '	108 ' l '
(GDB) p c< c16/>$10 = 0x100000f2e ""

10, jump command

In general, the debugger is executed in accordance with the order in which the program code is run, but GDB also provides the function of disorderly execution, that is, GDB can modify the order of execution of the program, so that the program jumps randomly. This feature can be specified by the GDB jump command: Jump <linespec> To specify the operation point of the next statement. <linespec> can be the line number of a file, either in file:line format or +num, which indicates where the next run statement will begin. Jump <address> Here <address> is the memory address of the line of code. Note that the jump command does not change the contents of the current stack, so if you use jump to jump from one function to another, when the function you jump to returns, the stack operation will inevitably occur, which can lead to unexpected results. So it's best to use jump to jump in the same function. 11, Signal command

using the Singal command, you can produce a semaphore to the program being debugged, such as interrupt signal "CTRL + C". This is very convenient for the debugging of the program, you can set breakpoints anywhere in the program running, and in the breakpoint with GDB to generate a semaphore, the precise way to generate a signal at a certain point is very conducive to the debugging of the program. The syntax for the signal command is: Signal <signal>,unix's system semaphores typically range from 1 to 15, so the value of <signal> is also in this scope. 12. Return Order

If you set a debug breakpoint in a function, and the statement does not finish after the breakpoint, we can use the return command to force the function to ignore the statement that has not yet been executed.

return return
<expression>
The return command above is used to cancel execution of the current function and returns immediately, and if <EXPRESSION> is specified, the value of the expression is taken as the return value of the function.

13. Call command

The call command is used to force the invocation of a function: The call <expr> expression can be a function in order to invoke the function, and it will display the return value of the function (if the function return value is not void). In fact, the Print command described earlier also completes the ability to force calls to functions. 14. Info Order

The info command can be used during debugging to view information such as registers, breakpoints, observation points, and signals. To view the value of a register, you can use the following command: Info registers (view registers other than floating-point registers) info All-registers (view all registers, including floating-point registers) info registers <regname ... > (View specified registers) to view breakpoint information, you can use the following command: Info break lists all the currently set observation points, using the following command: info watchpoints See what signals are being detected by GDB, using the following command: info Signals info handle can also use the Info Line command to view the address of the source code in memory. Info threads can look at multiple threads. Info line can be followed by row number, function name, FileName: line number, FileName: function name, etc., such as the following command will print out the specified source code at runtime memory address:

Info Line Tst.c:func

15, set scheduler-locking off|on|step

Off does not lock any threads, that is, all threads execute, which is the default value.
On only the currently debugged program will execute.
Step when stepping, except for the case where next has a function, only when the thread executes.

The commands associated with multithreaded debugging also include:

Thread ID
Toggles the thread of the currently debugged thread to the specified ID.

Break thread_test.c:123 thread All
To set a breakpoint on the corresponding line in all threads

Thread Apply ID1 ID2 command
Let one or more threads execute the GDB command.

Thread Apply all command
Let all debugged threads execute GDB command.
16, disassemble

The disassemble command is used for disassembly, which can be used to view the machine code of the source code at the time of execution, which actually simply dumps the instructions in the current memory. The following example looks at the assembly code for the function func:

(GDB) disassemble func
Dump of assembler code for function func:
0x8048450 <func>:       push   %EBP
0x8048451 <func+1>:     mov    %esp,%ebp
0x8048453 <func+3>:     Sub    $0x18,%esp
0x8048456 <func+6>:     movl   $0X0,0XFFFFFFFC (%EBP)
... End of assembler dump.
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.