GDB Debug Parsing

Source: Internet
Author: User
Tags keywords list semaphore

GDB (GNU Debugger) is a powerful command-line debugging tool. You know the power of the command line is that it can form an execution sequence and form a script. The software under UNIX is full of command line, which gives the program development a great convenience, the advantage of the command line software is that they can be very easy to integrate together, using a few simple tools of the command, you can make a very powerful function.

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). Allows the program to be 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.

1 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.

2 How to start GDB

(1). GDB program //program is your execution file, typically in the current directory.

(2). GDB program Core //use GDB to debug a running program and core file at the same time, core is the file generated after core dump is executed illegally.

(3). GDB program SID //If your application 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.

3 Common operations

(1). When you do not remember the command, enter the command first letter press two times tab, you will see all the commands that begin with this letter
(GDB) b
BackTrace Break BT
(2). View code when the list is debugged

Set Listsize <count>//Set the number of lines to display the source code at a time
Show Listsize//view settings for current listsize
List <first>, <last>//Display source code from first line to last row
List, <last>//Display source code from current line to last row
List <linenum>//display source code before and after a specified line
List <+offset>//positive offset of current line number
List <-offset>//negative offset of the current line number
List <filename:linenum>//Displays the front and back code of the specified line for the specified file
List <function>//display function source code
List <filename:function>//shows which function's code in the file
List <*address>//The address of the statement in memory when the program runs

3. Debugging code

When you do not remember the command, enter the command first letter press two times tab, you will see all the commands that begin with this letter

Run program, can be abbreviated to r

Continue continue to run the program, can be abbreviated to C

BackTrace displays the current position in the program and the stack that reaches the current location

Next single-step tracking, function calls are executed as a simple statement, abbreviated as N

Step one-step tracking, function transfer into the called function body, abbreviated to S

Finish Exit Function, return call function

Until one-step tracking in a loop, this command runs the program until it exits the loop body, which can be shortened to U.

Stepi or Si, Nexti or ni steps 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.

Info program to see if the application is running, the process number, and why it was paused.

Whatis viewing variable types

Print view the value of a variable

4 Breakpoint operation

(1). Set breakpoints

Break [Filename:]line-number//Set a breakpoint on the Line-number line of the source file filename (no filename defaults to the current file)

Break [filename:]function-name//Set breakpoints at the entrance to the function function of the source file filename

Break +offset//offset offset line before or after the current line number set a breakpoint
Break-offset

Break *address//Set a breakpoint at the memory address where the program is running

Break//No parameter means set breakpoint at the next instruction

Break line-or-function if condition //condition is true, set a breakpoint at the set condition

Enable [breakpoints] once [range...] Breakpoints is enabled only once in the range specified by range , and is automatically set to disabled when the program is stopped
Enable [breakpoints] Delete [range...] Enable breakpoints within range specified, and after the program has stopped, these breakpoints are automatically deleted

(2). View Breakpoints

Info break [n]//n identify breakpoint number

(3). Delete Breakpoint

Delete break/breakpoints//Without breakpoint number, all breakpoints will be deleted

Delete break/breakpoints 1//delete Breakpoint # 1th

Disable break/breakpoints N//Set a breakpoint to be invalid, without a breakpoint number, and set all breakpoints Disale

Enable break/breakpoints N//Set a breakpoint to be valid, without a breakpoint, to enable all disable breakpoints

6 Observation points

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 Count

8 Maintenance Stop Point

Clear 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 and breakpoints is 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 by the breakpoints as the stop point 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.

11 Viewing run-time data

Print prints the values of variables, strings, expressions, and so on, which can be abbreviated to P
P count Prints the value of Count
P COU1+COU2+COU3 Print Expression values

Print accepts an expression, and gdb evaluates the expression based on the data that the current program is running, which can be const constants, variables, functions, and so on in the current program run. 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 *[email Protected]

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 use $, $, $ ... this way you can make a number for each of your print commands. You can then use this number to access the previous expression, such as $ $. 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.

Show values

Print the last ten values in the value of the history, with their item numbers. This is

Like ' P $$9 ' repeated ten times, except that show values does don't change the

History.

Show Values N

Print Ten history values centered on the history item number n.

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 = 13

(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.

List LineNum

Print lines centered around line number linenum in the current source file.

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.

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.

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

This information is printed out: the stack's layer number, the current function name, the function parameter value, the file and line number where the function is located, and the statement to which the function executes.

Info frame

Info F

20 Signal

A signal is a soft interrupt and is a method of handling asynchronous events. In general, the operating system supports many signals. In particular, UNIX, a more important application typically processes signals. UNIX defines a number of signals, such as SIGINT to interrupt the character signal, that is, the CTRL + C signal, Sigbus indicates a hardware failure signal, SIGCHLD indicates the child process status change signal, sigkill means to terminate the program running signal, and so on.

Process the signal when debugging the program:

Handle signal [keywords ...]

Signal can start with the sig or not start with the sig, you can define a range to process the signal (such as: Sigio-sigkill, the signal processing from the SIGIO signal to SIGKILL, including Sigio,sigiot,sigkill three signals), You can also use the keyword all to indicate that you want to process all the signals. Once the program being debugged receives the signal, the running program is immediately stopped by GDB for debugging.

The keywords list is as follows:

Nostop

When the program being debugged receives a signal, GDB does not stop the program from running, but it will give you a message telling you to receive the signal.

Stop

When the program being debugged receives a signal, GDB stops your program. This implies the Print keyword as well.

Print

When the program being debugged receives a signal, GDB shows a message.

Noprint

When the program being debugged receives a signal, GDB will not tell you the message that you received the signal. This implies the Nostop keyword as well.

Pass

Noignore

When the program being debugged receives a signal, GDB does not process the signal. This means that GDB will give this signal to the debug program to process or else it may terminate if the signal is fatal and not handled.

NoPass

Ignore

When the program being debugged receives a signal, GDB does not let the debugger process the signal.

Info signals

Info handle

See what signals are being detected by GDB.

21catch

When the event occurs, stop the program. The event can be something as follows:
1. Throw an exception thrown by C + +. (Throw is keyword)
2. Catch an exception caught by C + +. (Catch as keyword)

22 specifying the path to the source file

At some point, only the name of the source file is included in the Execute program that was compiled with-G, and there is no path name. GDB provides a command that lets you specify the path to the source file so that gdb can search.

Directory dirname ...

Dir dirname ...

Adds a source file path to the front of the current path. If you want to specify multiple paths, under Unix you can use ":", under windows you can use ";".

Directory

Clears all the custom source file search path information.

Show directories

Displays the defined source file search path.

GDB Debug Parsing

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.