GDB Debugging Essentials and usage examples

Source: Internet
Author: User
Tags signal handler stack trace terminates

A: List of listed files

1. List

(GDB) List Line1,line2

Second: Execution procedure

To run a program that is ready for debugging, you can use the Run command, followed by any parameters that are sent to the program, including standard input and standard output specifiers (< and >) and Shell wildcard characters (*,? , [,]).

If you use the Run command without parameters, GDB uses the arguments you gave the previous run command again, which is useful.

The Set args command allows you to modify the parameters that are sent to the program, and you can use the show args command to view a list of its default parameters.

(GDB) Set args–b–x

(GDB) Show args

The BackTrace command provides a backward tracking function for the stack.

The BackTrace command produces a list of valid processes and parameters that have been invoked since the most recent process.

Three: Display the data

Use the Print command to check the values of individual variables.

(gdb) Print p (p is the variable name)

The Whatis command can display the type of a variable

(GDB) Whatis p

type = int *

Print is a powerful command of GDB that can display any valid expression in the language being debugged. In addition to the variables in your program, an expression can contain the following:

L CALL the function in the program

(gdb) Print find_entry (1,0)

L Data structures and other complex objects

(gdb) Print *table_start

$8={e=reference= ' \000 ', location=0x0,next=0x0}

The historical component of the L value

(GDB) print $ (A history variable, which can be referenced directly at a later time)

L-person for an array

A human array provides a way to display the contents of a memory block (an array section or a dynamically allocated storage area). The early debugger did not have a good way to replace arbitrary pointers with an array. As with parameters, let's look at the 10 integers in memory after the variable h, and the syntax for a dynamic array is as follows:

[email protected]

Therefore, to display the 10 elements behind H, you can use [email protected]:

(gdb) Print [email protected]

$13= ( -1,345,23,-234,0,0,0,98,345,10)

Four: Breakpoint (breakpoint)

The break command (which can be abbreviated as B) can be used to set breakpoints in a debugged program, which has the following four forms:

L Break Line-number The program to stop just before executing a given line.

The break Function-name causes the program to stop exactly before it enters the specified function.

L Break Line-or-function if condition if the condition (condition) is true, the program stops when it reaches the specified line or function.

L Break Routine-name set breakpoints at the entrance of the specified routine

If the program is made up of many original files, you can set breakpoints in each of the original files instead of setting breakpoints in the current original file, with the following methods:

(GDB) Break Filename:line-number

(GDB) Break Filename:function-name

To set a conditional breakpoint, you can take advantage of the break if command, as follows:

(GDB) Break line-or-function if expr

Cases:

(GDB) Break if testsize==100

To continue running from a breakpoint: countinue command

Five Management of breakpoints

1. Displays the breakpoint information for the current GDB:

(GDB) Info break

He will display all the breakpoint information in the following form:

Num Type Disp Enb Address What

1 breakpoint Keep y 0x000028bc in Init_random at qsort2.c:155

2 Breakpoint Keep Y 0x0000291c in Init_organ at qsort2.c:168

(GDB)

2. Delete the specified breakpoint:

(GDB) Delete Breakpoint 1

This command will delete the breakpoint numbered 1, and all breakpoints will be removed if no number argument is taken

(GDB) Delete Breakpoint

3. Disable the use of a breakpoint

(gdb) Disable Breakpoint 1

This command disables breakpoint 1, and the (ENB) field of the breakpoint information becomes n

4. Allow a breakpoint to be used

(GDB) Enable breakpoint 1

The command will allow Breakpoint 1, and the (ENB) field of the breakpoint information will change to Y

5. Clears all breakpoints on a line of code in the original file

(GDB) Clean number

Note: number is the line of a line of code for the original file

Six Checking and assignment of variables

L Whatis: Identifying types of arrays or variables

L PType: More powerful than Whatis, he can provide a definition of the structure

L Set Variable: assigns a value to a variable

L print can also be used to assign values in addition to the value of a variable

Seven Single Step execution

L Next

Do not enter the single step execution

L Step

Stepping into a single step

If you have entered a function and want to exit the function to return to its calling function, you can use the command finish

Eight Call to function

L Call name calls and executes a function

(GDB) Call Gen_and_sork (1234,1,0)

(GDB) Call printf ("ABCD")

$1=4

L finish finishes executing the current function, displaying its return value (if any)

Nine Machine Language Tools

There is a dedicated set of GDB variables that can be used to inspect and modify the computer's universal registers, and GDB provides the standard names of the 4 registers currently in use on each computer:

L $PC: Program counter

L $FP: Frame pointer (current stack frame)

L $SP: Stack pointer

L $PS: Processor status

Ten Signal

GDB can usually capture most of the signals sent to it, and by capturing the signal it can decide what to do with the running process. For example, by pressing CTRL-C to send the interrupt signal to GDB, GDB is usually terminated. But you may not want to interrupt gdb, and the real goal is to break the program that GDB is running, so GDB grabs the signal and stops the program it is running so that it can perform some debugging operations.

The handle command controls the processing of the signal, he has two parameters, one is the signal name, and the other is what to do when the signal is received. Several possible parameters are:

L Nostop receive the signal, do not send it to the program, do not stop the program.

L STOP the execution of the program when it receives the signal, which allows the program to debug; Displays a message indicating that the signal has been received (except for prohibited messages)

L Print a message when it receives the signal

L Noprint do not display the message when the signal is received (and implies that the program does not stop running)

L Pass sends the signal to the program, allowing your program to process it, stop it, or take other actions.

L NoPass Stop the program from running, but do not send the signal to the program.

For example, suppose you intercept a sigpipe signal to prevent the program being debugged from receiving the signal and, as soon as the signal arrives, ask the program to stop and notify you. To accomplish this, you can use the following command:

(GDB) handle Sigpipe stop Print

Note that UNIX's signal names are always capitalized! You can replace the signal name with a signal number.

If your program is going to perform any signal processing, you need to be able to test its signal handlers, and for that, you need an easy way to send the signal to the program, which is the task of the Signal command. The argument to the command is a number or a name, such as SIGINT. Suppose your program has a dedicated SIGINT (keyboard input, or ctrl-c; signal 2) signal handler set to take a cleanup action, to test the signal handler, you can set a breakpoint and use the following command:

(GDB) Signal 2

Continuing with Signal SIGINT (2)

The program continues to execute, but transmits the signal immediately, and the handler begins to run.

Eleven. Search for original files

Search text: This command displays the next line containing the text string in the current file.

Reverse-search text: The command can display the previous line that contains text.

Twelve. Unix interface

The shell command launches the Unix shell, ctrl-d exits the shell, and returns to GDB.

13. History of the Order

To allow historical commands, use the Set history expansion command

(GDB) Set history expansion on

Summary: Common GDB commands

BackTrace displays the current position in the program and the stack trace that represents how to get to the current location (synonyms: where)

Breakpoint setting a breakpoint in the program

CD changes the current working directory

Clear delete the breakpoint that you just stopped at

When you commands a breakpoint, list the commands that will be executed

Continue continue execution from breakpoint

Delete Deletes a breakpoint or a monitoring point, or it can be used with other commands

Displays variables and expressions when the display program is stopped

Down moves the stack frame so that another function becomes the current function

Frame Select frames for next continue command

Info displays various information related to the program

Jump starts running another point in the source program

Kill abnormally terminates a program that runs under GDB control

List lists the contents of the original file corresponding to the program being executed

Next executes the next source line to execute a function in its entirety

Print displays the value of a variable or an expression

PWD Displays the current working directory

Pype Displays the contents of a data structure, such as a struct or C + + class

Quit Quit GDB

Reverse-search reverse lookup of regular expressions in source files

Run to execute the program

Search searches the source file for regular expressions

Set variable assigning a value to a variable

Signal sending a signal to a running process

Step executes the next source line and enters the next function if necessary

Undisplay Display Command Anti-command, do not show expression

Until end current loop

Up moves the stack frame so that another function becomes the current function

Watch set a monitoring point (i.e. data breakpoint) in the program

Whatis display variable or function type

****************************************************

The GNU debugger is called GDB, and the program is an interactive tool that works in character mode. In the X Window system, there is a gdb front-end graphical tool called Xxgdb. GDB is a powerful debug program that can perform the following debugging tasks:

* Set breakpoints;

* Monitor the value of program variables;

* Single Step execution of the program;

* Modify the value of the variable.

Before you can use GDB to debug a program, you must compile the source file with the-G option. The CFLAGS variable can be defined as follows in Makefile:

CFLAGS = g

The following commands are commonly used when running GDB debuggers:

GDB Progname

Typing help at the GDB prompt will list the categories of commands, the main categories are:

* Aliases: Command alias

* Breakpoints: Breakpoint definition;

* Data: view;

* Files: Specify and view the file;

* Internals: Maintenance command;

* Running: Program execution;

* Stack: Call stack view;

* Statu: Status View;

* TRACEPOINTS: Tracking program execution.

Type the category name of the help followed by the command to get a detailed list of the commands.

Common commands for GDB

Command explanation

Break NUM sets a breakpoint on the specified line.

BT displays all the call stack frames. This command can be used to display the order in which functions are called.

Clear removes breakpoints that are set on a specific source file, on a specific line. Its usage is clear filename:num

Continue continue to execute the program being debugged. This command is used when the program stops running because of processing a signal or a breakpoint.

Display EXPR Displays the value of an expression every time the program stops. An expression consists of a variable defined by a program.

The file file loads the specified executable file for debugging.

Help NAME displays assistance information for the specified command.

Info break Displays the list of current breakpoints, including the number of times the breakpoint was reached.

Info files Displays detailed information about the files being debugged.

Info func Displays all the function names.

Info Local Displays the local variable information in the function.

Info prog shows the execution state of the program being debugged.

Info var displays all the global and static variable names.

Kill terminates the program that is being debugged.

The list displays the source code snippet.

Make to run the Make tool without exiting GDB.

Next executes a line of source code forward without stepping into other functions.

Print expr Displays the value of the expression expr.

GDB uses example ************************
List an error C source program BUGGING.C code:
1 #i nclude
2
3 static char buff [256];
4 static char* string;
5 int Main ()
6 {
7 printf ("Please input a string:");
8 gets (string);
9 printf ("\nyour string is:%s\n", string);
10}

The above program is very simple, its purpose is to accept the user's input, and then print out the user's input. The program uses a string address that has not been initialized, so the segment Fault error occurs after compiling and running:

$ gcc-o bugging-g bugging.c

$./bugging

Please input a STRING:ASFD

Segmentation fault (core dumped)

In order to find the problem in this program, we use GDB and follow the steps below:

1. Run the GDB bugging command and load the bugging executable file;

2. Execute the loaded bugging command run;

3. Use the where command to see where the program went wrong;

4. Use the list command to see the code near the call to the gets function;

5. The only factor that can cause the get function to go wrong is the variable string. Use the Print command to view the value of string;

6. In GdB, we can directly modify the value of the variable, as long as the string takes a valid pointer value can be, for this, we set the breakpoint at line 8th break 8;

7. The program re-runs to stop at line 8th, at which point we can modify the value of string with the set variable command;

8. Then continue running and you will see the correct program running results.

GDB Debugging Essentials and usage examples

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.