Full parsing of the Linux gdb debugger usage

Source: Internet
Author: User
Tags semaphore gdb debugger

GDB is a powerful UNIX program debugging tool released by the GNU Open Source organization, and GDB can help engineers with the following 4 functions:

    • Start the program, you can follow the requirements of the engineer custom run the program.
    • Let the debugged program stop at the breakpoint specified by the engineer, and the breakpoint can be a conditional expression.
    • When the program is stopped, you can check what is happening in the program at this time and recover from the above.
    • Dynamically change the execution environment of the program.

Whether you are debugging Linux kernel space drivers or debugging user-space applications, it is necessary to master GDB's usage. Also, the GDB command used to debug the kernel and debug the application is exactly the same, as illustrated in the example of the application of the GDB debugger, as shown in code 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;13   int array1[10] =15   {     48, 56, 77 , 226, 544, 9017   };18   int array2[10] =19   {     393, 11, 1, 2, 3, 0x199., 421<, C22/>};22 for   (i = 0; i <, i++) (     sum[i] = Add (Array1[i], array2[i]);   }27}

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

[[email protected] driver_study]# gdb gdb_examplegnu gdb Red Hat Linux (5.3POST-0.20021129.18RH) Copyright 2003 free Softwa  Re Foundation, Inc.gdb is free software, covered by the GNU general public License, and your arewelcome to change it and/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 is configured as "I386-redhat-linux-gnu" ... (GDB)
1. List command

Run the List command (abbreviated L) in GDB to list the code, including:

list <linenum> shows the source program around line linenum, such as:

(GDB) List 1510        one        int array1[10] =12 {$, A, a, a, a, a, a, 226, 544, a, 9014};15        int Arra Y2[10] =16        {          2, 1, 3, 418};19, 0x199, 393        

list <function> shows the source of a function named function, such as:

(GDB) List main2       {3         return a + b;4       }56       Main () 7       {8         int sum[10];9         int i;10        one        int ARRAY1[10] =

The list displays the source program after the current line.

List- displays the source program in front of the current line.

The following shows the process of using the run (abbreviated R), break (abbreviated B), next (abbreviated N) command of the control program in GDB, and printing the variable sum in the program using the print (abbreviation P) command:

(GDB) Break Addbreakpoint 1 at 0x80482f7:file gdb_example.c, line 3. (GDB) Run  starting program:/driver_study/gdb_example Breakpoint 1, add (a=48, b=85) at Gdb_example.c:3warning:sour Ce file is more recent than executable.3         return a + B; (gdb) Next4       } (GDB) Nextmain () at gdb_example.c:2323        for (i = 0; i < i++) (GDB) Next25          sum[i] = Add (Array1[i], array2[i]);(gdb) Print sum$1 = {133, 0, 0, 0, 0, 0, 0 , 0, 0, 0}
2. Run command

In GDB, run the program using the Run command. Before the program runs, we can set up the following 4 aspects of the working environment:

Program Run parameters

  Set args can specify runtime parameters, such asset args.

The show args   command can view the set run parameters.

Operating Environment

Path <dir>   can set the running paths of the program;

  How paths can see 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 CD commands;

  The pwd displays the directory where you are currently located.

Program input and output

  Info Terminal is used to display the terminal mode used by the program;

GDB can also use redirection control program output, such as run > outfile;

  The TTY command can specify an end device for the input and output, such as:tty/dev/ttys1.

3. Break command

To set breakpoints in gdb with the break command, the methods for setting breakpoints include:

Break <function>

When entering a specified function, the function name can be specified in C + + using the Class::function or functions (type, type) format.

Break <linenum>

Stops at the specified line number.

Break +offset/break-offset

The offset line before or after the current line number is stopped, Offiset is the natural number.

Break Filename:linenum

Stop at the LineNum line of the source file filename.

Break Filename:function

Stop at the entrance of the function function of the source file filename.

Break *address

Stop at the memory address where the program is running.

Break

The break command stops at the next instruction when there are no arguments.

Break ... if <condition>

"..." can be a parameter in the break <linenum>and break+offset/break–offset above, condition represents the condition and stops when the condition is set. For example, in the loop body, you can set the break if i=100, which means that when I is 100, the program is stopped.

Info

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

4. Single Step Command

During the debugging process, the next command is used for stepping, similar to step over in VC + +. The next step does not enter the inside of the function, and the step (s) command corresponding to next will enter its interior, similar to the step into in VC + +, when stepping into a function. The following shows the execution of the step command, which executes step at the Add () function Call of line 23 to enter its internal "return a+b;" Statement:

(GDB) Break 25Breakpoint 1 at 0x8048362:file gdb_example.c, line 25. (GDB) runstarting Program:/driver_study/gdb_example Breakpoint 1, Main () at gdb_example.c:2525          sum[i] = Add (array1[ I], array2[i]);(gdb) Stepadd (a=48, b=85) at Gdb_example.c:33         return a + B;

More complex uses of stepping include:

Step <count>

Single-step tracking, if there is a function call, enter the function (the premise of entering the function is that this function is compiled with debug information). The step is not followed by count to indicate the execution of a line, plus the following count instructions, and then stop.

Next <count>

Single-step tracking, if there is a function call, it does not enter the function. Similarly, next, without count, indicates the execution of a line, plus the subsequent count instruction, and then the stop.

Set Step-mode

Set Step-mode on is used to open the Step-mode mode, so that in the case of single-step tracking, the program does not stop because there is no debug information, the setting of this parameter is easy to view the machine code. Set Step-mod off is used to turn off Step-mode mode.

Finish

Runs the program until the current function finishes returning, and prints information such as the stack address and return value and parameter values when the function returns.

until (abbreviation u)

Always in the loop to perform a single step, can not get out is an annoying thing, until command to run the program until you exit the loop body.

Stepi (abbreviation SI) and nexti (abbreviation NI)

Stepi and Nexti are used to step through a single machine instruction, a program code may be completed by a number of machine instructions, STEPI and Nexti can step into the machine instructions. In addition, after running the "display/i $pc" command, single-step tracking will shoot the program code while typing the machine instructions, that is, assembly code.

5. Continue command

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

Continue [Ignore-count]c [IGNORE-COUNT]FG [Ignore-count]

Ignore-count indicates how many breakpoints are ignored. Assuming we set the function breakpoint Add ()and watch I, during the continue process, each time the add () function or I changes, the program stops, such as:

(gdb) continuecontinuing.hardware watchpoint 3:iold value = 2New value = 30x0804838d in Main () at gdb_example.c:2323
   
    for (i = 0; i < i++) (GDB) Continuecontinuing.breakpoint 1, Main () at gdb_example.c:2525          sum[i] = Add (array1[i ], Array2[i]);(gdb) continuecontinuing.hardware watchpoint 3:iold value = 3New value = 40x0804838d in Main () at Gdb_exam ple.c:2323 for        (i = 0; i < ten; i++)
   
6. Print command

When you debug a program, you can use the Print command (abbreviated p) or the inspect command to view the current program's running data when the program is stopped. The format of the Print command is:

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

<expr> is the expression that is the expression in the program being debugged,

<f> is the format of the output, for example, if you want to output the expression in 16-in-one format, then the/ x. In the expression, there are several operators supported by GDB, which can be used in any language where"@" is an array-related operator,"::" to specify a variable in a file or function,"{<type>} <addr> " represents an object of type that points to memory address <addr> .

The following demonstrates the process of viewing the value of an sum[] array:

    (GDB) print sum $      = {133, 155, 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 see the value of a contiguous amount of memory space, you can use GDB's "@" operator,"@ " to the left is the first memory address,"@" to the right is to see the length of memory. For example, the following dynamically requested memory:

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

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

P *[email Protected]

The output formats for print include:

    • x Displays the variable in hexadecimal format.
    • D Displays the variable in decimal format.
    • u displays unsigned integers in hexadecimal format.
    • o Displays the variable in octal format.
    • T displays the variable in binary format.
    • A displays the variable in hexadecimal format.
    • C Displays the variable in character format.
    • F Displays the variable in floating-point number format.

We can use the display command to set some automatically displayed variables, which are automatically displayed when the program is stopped, or when a single step is tracked. If you want to modify the value of a variable, such as x, you can use the following command:

Print x=4

When you use GDB's print to view data from a program running, each print is recorded by GDB. GDB will be $1,$2,$3 ... This way is numbered for each print command. We can use this number to access previous expressions, such as $ $.

7. Watch Command

Watch generally observes whether the value of an expression (a variable is an expression) has changed, and if so, stops the program immediately.

We have the following methods to set the observation point:

  Watch <expr>: Set an observer point for the expression (variable) expr. Once the expression value has changed, stop the program immediately.

  Rwatch <expr>: When the expression (variable) expr is read, stop the program.

  Awatch <expr>: When the value of an expression (variable) is read or written, stop the program.

  Info watchpoints: Lists all the observed points that are currently set. The following shows the process by which I is shown when I is observed and when I is found in continuous running next:

(gdb) Watch Ihardware watchpoint 3:i (gdb) next23 for        (i = 0; i < i++) (GDB) Nexthardware Watchpoint 3:iold val  UE = 0NEW value = 10x0804838d in main () @ gdb_example.c:2323        for (i = 0; i < i++) (GDB) Nextbreakpoint 1, Main () at gdb_example.c:2525          sum[i] = Add (Array1[i], array2[i]);(gdb) next23 for        (i = 0; i < i++) (GDB) Nexthar Dware watchpoint 3:iold value = 1New value = 20x0804838d in Main () at gdb_example.c:2323 for        (i = 0; i <; i++)
8. Examine command

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

X/<n/f/u> <addr>

<addr> represents a memory address. "x/" after the N, F, u are optional parameters, n is a positive integer, indicating the length of the display memory, that is, from the current address to display the contents of several addresses; F indicates the format of the display, if the address refers to a string, then the format can be S, if the address is an instruction address, The format can be i;u to indicate the number of bytes requested from the current address, and if not specified, gdb defaults to 4 bytes. The u parameter can be substituted by some characters: b for single byte, h for Double Byte, W for four bytes, and G for eight bytes. When we specify a byte length, GDB starts with the specified memory address, reads and writes the specified byte, and takes it as a value. The 3 parameters of N, F, and u 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), 16 binary mode (U) starting from memory address 0x54320. ==

For example:

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

We are

char *c = "Hello World";

After you set the breakpoint on the following line:

(GDB) L1    Main () 2    {3        char *c = "Hello World"; 4        printf ("%s\n", c); 5    } (GDB) b 4Breakpoint 1 at 0x100000f 17:file Main.c, line 4. (GDB) rstarting program:/users/songbarry/mainreading symbols for shared libraries +. Donebreakpoint 1, Main () at main.c:44        printf ("%s\n", c);

There are several ways to see the string C points to:

Method 1:

(GDB) P c$1 = 0x100000f2e "Hello World"

Method 2:

(GDB) x/s 0x100000f2e0x100000f2e:     "Hello World"

Method 3:

(GDB) p (char *) 0x100000f2e$3 = 0x100000f2e "Hello World"

Change the first character to uppercase:

(GDB) p * (char *) 0x100000f2e= ' h ' $4 = ' h '

And look at C:

(GDB) P c$5 = 0x100000f2e "Hello World"
9. Set command

To modify a register:

To modify Memory:

(GDB) set {unsigned int}0x8048a51=0x0

For example, for the 8th section:

(GDB) set {unsigned int}0x100000f2e=0x0       (gdb) X/10CB 0x100000f2e0x100000f2e:    0 ' + '    0 '    0 '    0 ' 111 '    o '    119 ' W '    111 ' o ' 0x100000f36:    ' r '    108 ' l ' (gdb) p c$10 = 0x100000f2e ""
10. Jump Command

In general, the debugger executes sequentially in the order in which the program code is run, but GDB also provides the ability to execute in a disorderly order, that is, GDB can modify the order in which the program executes, thus allowing the program to jump randomly. This feature can be used by GDB's jump command: Jump<linespec> to specify the run point of the next statement. The <linespec> can be the line number of the file, either the file:line format or the +num offset format, which indicates where the next run statement starts. 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 program stack, so if jumping from one function to another, when jumping to a function that returns, there will inevitably be an error in the stack operation, which can lead to unexpected results, So it's best to jump in the same function only with jumps.

11. Signal Command

Using the Singal command, you can generate a semaphore to the program being debugged, such as the interrupt signal "CTRL + C". This is very convenient for the debugging of the program, you can set the breakpoint at any point in the program run, and in this breakpoint with GDB to generate a semaphore, this precisely in a way to generate a signal is very beneficial to the debugging of the program. The syntax for the Signal command is:signal <signal>, Unix's system semaphore is usually from 1 to 15, so the <signal> value is also in this range.

12. Return command

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 and return.

Returnreturn <expression>

The return command above is used to cancel the execution of the current function and return immediately, and if <expression>is specified, the value of the expression will be used 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 to achieve the purpose of forcing the calling function, which displays the function's return value (if the function return value is not void). In fact, the Print command described earlier also completes the function of forcing the function to be called.

14. Info command

The info command can be used to view information such as registers, breakpoints, observers, and signals during debugging.

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 (see all registers, including floating-point registers)

  Info Registers <regname ...> (view the specified register)

  Info Break View breakpoint Information

  Info watchpoints Lists all of the currently set observer points,

INFO signals info handle See what signals are being detected by GDB,

Info Line command to see the source code in memory address.

Info threads can look at multiple threads.

Info line can be followed by a row number, function name, file name: line number, file name: function name, and many other forms, 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 are executed, which is the default value.
On only the currently debugged program will execute.
Step in a single step, in addition to the next function of the case, only when the front-line will be executed.

The commands related to 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
Set breakpoints on the corresponding lines in all threads
Thread Apply ID1 ID2 command
Have one or more threads execute GDB command commands.
Thread Apply all command
Let all the debugged threads execute the 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 current in-memory instructions. The following example is used to view the assembly code for function func:

(GDB) disassemble funcdump of assembler code for function func:0x8048450 <func>:       push   %ebp0x8048451 < Func+1>:     mov    %esp,%ebp0x8048453 <func+3>:     Sub    $0x18,%esp0x8048456 <func+6>:     MOVL   $0X0,0XFFFFFFFC (%EBP) ... End of assembler dump.

This article was reproduced from: http://blog.csdn.net/21cnbao/article/details/7385161

Full parsing of the Linux gdb debugger usage

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.