GDB Debug commands in a detailed

Source: Internet
Author: User
Tags semaphore
Basic Usage 1. Introduction

GDB (GNU Debugger) is a debugging tool for GCC. Its powerful, now described as follows:
GDB is the main help you complete the following four aspects of the function:
1. Start your program, you can follow your custom requirements to run the program at will.
2. Allow the program being debugged to stop at the breakpoint you have specified for the reset. (Breakpoint can be a conditional expression)
3. When the program is stopped, you can check what happens in your program at this time.
4. Dynamically change the execution environment of your program. 2 generating Debug information

In general, GDB is mainly debugging the C + + program. In order to debug a C + + program, first at compile time, we have to add debug information to the executable file. This can be done using the-g parameter of the compiler (cc/gcc/g++). Such as:

Gcc-g hello.c-o Hello
g++-G hello.cpp-o Hello

Without-G, you will not see the program's function name, variable name, instead of the memory address of the runtime. After you have added the debug information with-G and successfully compiled the target code, let's look at how to debug it with GDB. 3 How to start gdb 1. GDB Program

Program is your execution file, typically in the current directory. 2. GDB Program Core

Using GDB to debug a running program and core file at the same time, the core is the file generated after core dump is executed illegally. 3. GDB Program 1234

If your program is a service program, you can specify the process ID at which the service program runs. GDB will automatically attach up and debug him. The program should be searched in the PATH environment variable. 4 program Run context 4.1 program Run parameters

Set args can specify runtime parameters. (Example: Set args 10 20 30 40 50)
The show args command can view the set run parameters.
Run (r) Startup program
Do not specify a run parameter R
Specify operating parameters r 4.2 working directory

CD is equivalent to the Shell's CD command.
The PWD displays the current directory. 4.3 input and output of the program

Info terminal shows you the terminal mode used by your program.
Use redirection control program output. such as: Run > outfile
The TTY command can be used to set the terminal device for input and output. Example: Tty/dev/tty1 5 Set Breakpoint 5.1 Simple Breakpoint

Break sets a breakpoint that can be abbreviated to B
B 10 Set breakpoints in line 10th of the source program
b func set breakpoint, at the entrance of Func function more than 5.2 files set breakpoints

Stop when entering the specified function:
In C + + you can use
The Class::function or function (type,type) format to specify the name of the functions. If there is a namespace, you can use the namespace::class::function or function (type,type) format to specify the functions name.
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 class::function or function (Type,type)
Stop at the entrance to the function function of class
Break Namespace::class::function
Stop 5.3 at the entrance to the function function of class classes where the namespace is namespace to query all breakpoints

Info B 6 observation point

Watch sets an observer point for the expression (variable) expr. When the expression value changes, stop the program immediately.
Rwatch expression (variable) when expr is read, stops the program.
Awatch the value of an expression (variable) is read or written, the program is stopped.
Info watchpoints Lists all the observed points that are currently set. 7 Conditional Breakpoints

Generally, to set a condition for a breakpoint, we use the IF keyword followed by its breakpoint condition. And, when the conditions are set, we can use the condition command to modify the condition of the breakpoint. And, when the conditions are set, we can use the condition command to modify the condition of the breakpoint. (Only the break and watch command support If,catch currently does not support if).
Set a conditional breakpoint
b test.c:8 if intvalue = = 5
Condition is similar to break if, except that condition can only be used on existing breakpoints
Change the stop condition of the breakpoint number to Bnum as expression
Condition Bnum Expression
Clear stop condition with breakpoint number Bnum
Condition Bnum
Ignore ignore stop condition several times
Represents a stop condition that ignores a breakpoint number of bnum count times
Ignore bnum Count8 Maintenance Stop PointClear clears all defined stop points. The clear function clears all stops that are set on the function. Clear LineNum clears all stops that are set on the specified line. Clear Filename:linenum clears all settings in the specified file: The stop point on the specified line. delete [breakpoints] [range ...] Deletes the specified breakpoint, breakpoints the breakpoint number. If you do not specify a breakpoint number, all breakpoints are deleted. Range represents the range of breakpoint numbers (for example: 3-7). Its shorthand command is D. A better way than delete is disable stop point, disable the stop point, GDB will not delete, when you need, enable, just like the Recycle Bin. disable [breakpoints] [range ...] disable the stop point specified, breakpoints is the stop number. If nothing is specified, all disable stops are indicated. The shorthand command is dis. Enable [breakpoints] [range ...] The stop point specified by enable, breakpoints is the stop number. Enable [breakpoints] once range...enable the stop point specified once, when the program stops, the stop is automatically disable by GDB. Enable [breakpoints] Delete range...enable The stop point specified once, when the program stops, the stop is automatically deleted by GDB.9 Set the Run command for the stop point

We can use the command command provided by GDB to set the run of the stop point. In other words, when the running program is stopped, we can let it run some other commands automatically, which is very advantageous for automated debugging. is a powerful support for GDB-based automated debugging.

commands [Bnum]
... command-list
... End

Write a list of commands for the breakpoint number bnum. When the program is stopped by the breakpoint, GDB runs the command in the command list in turn.
For example:

Break foo if x>0
commands
printf "x is%d", x
continue
End

Breakpoint set in function foo, the breakpoint condition is x>0, if the program is broken, that is, once the value of x in the Foo function is greater than 0,GDB will automatically print out the value of X, and continue to run the program.
If you want to clear a sequence of commands on a breakpoint, simply execute the commands command and just hit the end of the line. 10 Debug Code Run program, can be abbreviated to r next single step tracking, function call as a simple statement execution, can be abbreviated to n step single step tracking, function calls into the called function body, can be abbreviated as S-finish exit function until in a circular body single-step tracking , this command runs the program until it exits the loop body, which can be shortened to U. Continue continue to run the program, can be abbreviated to C Stepi or Si, Nexti or ni step-tracking a machine instruction, a program code may be completed by a number of machine instructions, STEPI and Nexti can step into the machine instructions. Info program to see if the application is running, the process number, and why it was paused. 11 View run-time data print the values of a variable, string, expression, and so on, abbreviated to p p count prints the value of Count p cou1+cou2+cou3 Print expression value prints accept an expression, GDB calculates the expression based on the data currently running by the program, which can be const constants, variables, functions, and so on in the current program. However, GDB cannot use macros defined in the program. 12 Program Variables

In GdB, you can view the values of the following three variables at any time:
1. Global variables (all files visible)
2. Static global variable (current file is visible)
3. Local variables (visible at current scope)
If you have a local variable that conflicts with a global variable (that is, a duplicate name), a local variable typically hides the global variable, that is, if a global variable and a local variable in a function have the same names, if the current stop is in the function, the value of the variable shown in print is the value of the local variable in the function. If you want to see the value of a global variable at this point, you can use the "::" Operator:
File::variable
Function::variable
You can specify the variables you want to see in this form, in which file or in which function. For example, view the value of global variable x in file f2.c:

P ' f2.c ':: X

Of course, the "::" operator will conflict with C + +, and GDB will automatically recognize "::" Whether it is a C + + operator, so you don't have to worry about exceptions when debugging C + + programs.
4. Array variables
Sometimes you need to look at the value of a contiguous amount of memory space. For example, a paragraph of an array, or the size of dynamically allocated data. You can use GDB's "@" operator, the left side of "@" is the value of the address of the first memory, and the right side of "@" you want to see the length of the memory. For example, there is a statement in your program that says:

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

So, during GDB debugging, you can display the value of this dynamic array as follows:

P *array@len

The left side of @ is the value of the array's first address, which is what the variable array points to, and the length of the data on the right, which is stored in the variable len. 13 Automatic Display

You can set up some automatically displayed variables that are automatically displayed when the program stops, or when you step through the tracks. The associated GDB command is display.

Display expr
display/fmt expr
display/fmt addr

Expr is an expression, FMT represents the format shown, addr represents a memory address, and when you set up one or more expressions with display, GDB automatically displays the values of the expressions you set as long as your program is stopped.

Info display

View the information displayed automatically for display settings.

Undisplay dnums
... Delete Display Dnums ...

Delete auto-display, dnums means the automatic explicit number that is set up. If you want to delete several, the number can be separated by a space, if you want to delete a range of numbers, you can use a minus sign (for example: 2-5)

Disable Display dnums
... Enable Display Dnums ...

Disable and Enalbe do not remove the settings that are automatically displayed, but just let them fail and resume. 14 historical records

When you use GDB's print to view the data that the program is running on, each print will be recorded by GDB. GDB will be numbered 1, 1, 2, 3 ... in this way for each of your print commands. So, you can use this number to access the previous expression, such as 3 .... This way, make a number for each of your print commands. You can then use this number to access the previous expression, such as 1. The benefit of this feature is that if you have previously entered a long expression, if you want to see the value of the expression, you can use the history to access it, eliminating the need for duplicate input.

(GDB) Show Values
Print the last ten values in the their item numbers. This
was like ' P $$9 ' repeated ten times, except that show values does not a change of the history
.

(GDB) Show values n
Print Ten history values centered on the history item number n.

(GDB) Show values +
Print Ten history values just after the values last printed. If no more values
is available, show values + produces no display.
15 Changing the execution of the program

Once you use GDB to hang up the debugger, when the program is running, you can change the running line of the currently debugged program or the value of its variable dynamically in GDB according to your debugging idea, this powerful function can let you debug your program better, for example, You can go through all the branches of the program in one run of the program. 15.1 modifying variable values

Modifying the values of variables that are run by the debugger is easy to implement in GDB and is done using GDB's Print command. Such as:

(gdb) Print x=4

X=4 This expression is the syntax for C/s + +, meaning to change the value of variable x to 4, if your current debugging language is Pascal, then you can use Pascal's syntax: X:=4.
At some point, it is possible that your variables conflict with the arguments in gdb, such as:

(gdb) whatis width
type = Double
(gdb) p width
$4 =
(gdb) set width=47
Invalid syntax in expression .

Because the set width is a gdb command, there is a "Invalid syntax in expression" setting error, 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 situations where GDB does not report this error, so it is safe to use the GDB command in the set var format when you change the value of the program variable. 15.2 Jump Execution

In general, the debugger executes sequentially in the order in which the program code is run. GDB provides the ability to execute in a disorderly order, that is, GDB can modify the order in which the program executes, allowing the program to perform random jumps. This feature can be done by GDB's Jump command:

Jump Linespec

Specifies the run point of the next statement. This can be the line number of the file, which can be the File:line format, which can be the +num offset format. Indicates where the next run statement starts.

Jump *address

Here 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 when you skip from one function to another, it is inevitable that an error will occur when the function is returned with a stack operation, and the result may be very strange, even if the program core Dump is generated. So it's best to jump in the same function.
People familiar with the Assembly know that when the program runs, the EIP register is used to hold the memory address where the current code resides. So, the jump command changes the value in this register. You can then use set $PC to change the address of the jump execution. Such as:

Set $pc = 0x485
15.3 generating the semaphore

Using the Singal command, you can generate a semaphore to the program being debugged. Such as: Interrupt signal CTRL + C. This is very convenient for debugging the program, you can set the breakpoint at any point in the program run, and in this breakpoint with GDB to produce a semaphore, this precisely in a place to produce a signal very advantageous to the program debugging.
The syntax is:

Signal Signal

UNIX's system semaphores are usually from 1 to 15. So the value is also in this range.
Unlike the kill command of the shell, the kill command of the system is intercepted by GDB when signaled to the debug program, and a signal issued by the single command is sent directly to the debugged program. 15.4 Force function return

If your debug breakpoint is in a function, and the statement is not finished. You can use the return command to force the function to ignore statements that have not yet been executed and return.

return
return expression

Use the return command to cancel the execution of the current function and return immediately, and if specified, the value of the expression is considered to be the return value of the function. 15.5 Force Call Function

Call Expr

A function can be used in an expression to achieve the purpose of forcing the function to be called. and displays the return value of the function, if the function return value is void, then it is not displayed.

Print expr

Another similar command can also be done with this function--print,print can be followed by the expression, so you can also use him to invoke the function, print and call is different, if the function returned Void,call is not displayed, print shows the function return value, And the value is stored in the historical data. 16 Show Source code

GDB can print out the source code of the program being debugged, of course, at the time of compiling the program must add –g parameters, the source program information compiled into the execution file. Otherwise you will not see the source program. When the program stops, GDB reports that the program is parked on the first line of the file. You can use the List command to print the program's source code. Print 10 rows By default, or take a look at the GDB command that looks at the source code.

(GDB) List linenum
Print lines centered around line number linenum in the current source file.
(GDB) List function

Displays the source program for a function named function.

List

Displays the source program after the current line.

List-

Displays the source program in front of the current line.
In general, the current line is printed on the top 5 rows and the next 5 lines, if the display function is 2 rows below 8 lines, the default is 10 rows, of course, you can also customize the display of the range, using the following command can be set to display the source program number of lines.

Set Listsize count

Sets the number of lines to display the source code at a time. (unless the list argument explicitly specifies some other number)

Show Listsize

View the settings for the current listsize. 17 Debugging a running process

Two methods:
1. Under UNIX, use PS to view the running program's PID (process ID), and then use the GDB PID process-id format to hook up the running program.
2, the first with GDB associated with the source code, and GDB, in gdb with the Attach Process-id command to hook up the process PID. Use the detach to cancel the hook process. 18 Threads

If your program is multithreaded, you can define whether your breakpoint is on all threads, or on a particular thread. GDB is easy to help you with this work.

Break Linespec thread Threadno break
linespec thread Threadno If ...

LINESPEC Specifies the line number of the source program to which the breakpoint is set. THREADNO Specifies the ID of the thread, note that this ID is assigned by GDB, and you can view the thread information in the running program through the "Info Threads" command. If you do not specify ' thread Threadno ', then your breakpoint is set on all threads. You can also specify a breakpoint condition for a thread. Such as:

(gdb) Break frik.c:13 thread Bartab > Lim

When your program is stopped by GDB, all running threads will be stopped. This facilitates you to view the overall situation of the running program. And when you resume the program, all the threads will be restored to run. That is even when the main process is being debugged. 19 viewing stack information

When the program is stopped, the first thing you need to do is to see where the program is parked. When your program calls a function, the address of the function, the function arguments, the local variables within the function are pressed into the stack. You can use the GDB command to view the information in the current stack.
Here are some GDB commands to view the function call stack information:
Breacktrace, referred to as BT
Prints all the information for the current function call stack. Such as:

(GDB) bt
#0 func (n=250) at Tst.c:6
#1 0x08048524 in Main (Argc=1, argv=0xbffff674) at tst.c:30
#2 0x400409ed In __libc_start_main () from/lib/libc.so.6

The function's call stack information can be seen from the:__libc_start_main–> main () –> func ()

BackTrace N
bt N

n is a positive integer that represents only the stack information for the top n-tier of the stack.

Backtrace-n
Bt-n

The-n table is a negative integer that prints only the stack information for the n-tier below the stack.

If you want to view a layer of information, you need to switch the current stack, generally speaking, when the program stops, the topmost stack is the current stack, if you want to see the stack below the details of the layer, the first thing to do is to switch the current stack.

Frame n

N is an integer starting from 0, which is the layer number in the stack. For example: Frame 0, representing the top of the stack, frame 1, represents the second layer of the stack.

(GDB) frame addr
F addr Select the frame at address addr. This is useful mainly if the chaining of stack frames have been damaged by a bug, making it impossible for GDB to Assign
  numbers properly to all frames. In addition, this can is useful when the your program has multiple stacks and switches between them.

(GDB) up n

Moves the n layer to the top of the stack without hitting N, which means moving up one layer.

Down n

Moves the n layer below the stack, without hitting N, to move down one layer.
The above command will print out the information of the stack layer that is moved to. If you don't want it to be a message. You can use these three commands:
The select-frame corresponds to the frame command.
up-silently n corresponds to the UP command.
down-silently n corresponds to the down command.
To view the information for the current stack, you can use the following GDB command:

Frame or F

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.