View stack information by GDB

Source: Internet
Author: User
Tags print object

View stack information
-----

When the program is stopped, the first thing you need to do is to check where the program stops. When your program
When a function is called, the address, parameters, and local variables in the function are pushed in.
"Stack. You can use the gdb command to view information in the current stack.

The following are some gdb commands for viewing the stack information of function calls:

Backtrace
BT
Print all information about the current function call stack. For example:

(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

From the above we can see the call stack information of the function: __libc_start_main --> main () --> func ()

Backtrace
BT
N is a positive integer, indicating that only stack information of N layers on top of the stack is printed.

Backtrace <-N>
BT <-N>
-N indicates that only stack information of N layers under the stack is printed.

If you want to view the information of a certain layer, you need to switch the current stack. Generally, when the program stops
The stack of the layer is the current stack. To view the details of the layer below the stack, you must first switch the current stack.

Frame
F
N is an integer starting from 0 and a layer number in the stack. For example, frame 0 indicates the top of the stack, frame 1 indicates the second layer of the stack.

Up
It indicates moving N layers to the top of the stack. If n is not required, it indicates moving up a layer.

Down
It indicates moving N layers to the bottom of the stack. If n is not used, it indicates moving down a layer.

The above command will print the information to be moved to the stack layer. If you do not want them to output information. You can use these three commands:

Select-frame corresponds to the frame command.
Up-silently corresponds to the up command.
The down-silently command corresponds to the down command.

To view information about the current stack layer, run the following GDB command:

Frame or F
The following information is printed: the stack layer number, the current function name, function parameter value, the file and row number of the function, and the statement executed by the function.

Info Frame
Info F

This command prints more detailed information about the current stack layer, except that most of the information is in the runtime
Address. For example, the function address, the address of the called function, and the address of the called function. What is the current function?
Program language, function parameter address and value, local variable address, and so on. For example:

(GDB) info F
Stack level 0, frame at 0xbffff5d4:
EIP = 0x804845d in func (TST. C: 6); saved EIP 0x8048524
Called by frame at 0xbffff60c
Source Language C.
Arglist at 0xbffff5d4, argS: N = 250
Locals at 0xbffff5d4, previous frame's SP is 0x0
Saved registers:
EBP at 0xbffff5d4, EIP at 0xbffff5d8

Info ARGs
Print the parameter name and value of the current function.

Info locals
Print all local variables and their values in the current function.

Info catch
Print the exception handling information in the current function.

View Source program
-----

1. display source code

GDB can print the source code of the program to be debugged. Of course, the-G parameter must be added during program compilation
Compile the source program information to the execution file. Otherwise, you will not be able to see the source program. When the program stops,
GDB will report the row on which the program stops. You can use the LIST command to print the program's source code.
. Let's take a look at the source code's GDB command.

List
Displays the source code around the linenum line of the program.

List
Displays the source program of the function named function.

List
Displays the source code behind the current row.

List-
Displays the source code before the current row.

It is usually used to print the top 5 rows and the next 5 rows of the current row. If the display function is the top 2 and the next 8 rows, the default value is 10.
You can also customize the display range. You can use the following command to set the number of lines to display the source program at a time.

Set listsize
Set the number of lines for displaying source code at a time.

Show listsize
View the current listsize settings.

The list command also has the following usage:

List,
Displays the source code from the first row to the last row.

List,
Displays the source code from the current row to the last row.

List +
The source code is displayed later.

Generally, the following parameters can be followed after the list:

The row number.
<+ Offset> the positive offset of the current row number.
<-Offset> the negative offset of the current row number.
The row of the file.
Function name.
The function in the file.
<* Address> the address of the statement in the memory when the program runs.

2. Search source code

Besides, GDB provides the following source code search commands:

Forward-search
Search
Search forward.

Reverse-search
Search all.

Here, it is a regular expression and also the matching mode of the Main string. I will not talk about the regular expression here. Please check the relevant information.

3. Specify the source file path

In some cases, the execution program compiled with-G only contains the name of the source file without a path name. GDB provides commands that allow you to specify the path of the source file for GDB to search.

Directory
Dir
Add a source file path to the front of the current path. If you want to specify multiple paths, you can use ":" in UNIX, and ";" in windows.
Directory
Clear all custom source file search paths.

Show Directories
Displays the defined source file search path.

4. Source Code memory

You can use the info line command to view the address of the source code in the memory. Info line can be followed
"Line number", "function name", "File Name: line number", and "File Name: Function Name". This command prints the specified
The memory address of the source code at runtime, such:

(GDB) info line TST. C: func
Line 5 of "TST. c" starts at address 0x8048456 and ends at 0x804845d.

There is also a command (disassemble) You can view the machine code of the current execution of the source program, this command
Dump the commands in the current memory. The following example shows the assembly code of the function func.

(GDB) disassemble func
Dump of worker er code for function FUNC:
0x8048450: Push % EBP
0x8048451: mov % ESP, % EBP
0x8048453: Sub $0x18, % ESP
0x8048456: movl $0x0, 0 xfffffffc (% EBP)
0x804845d: movl $0x1, 0xfffffff8 (% EBP)
0x8048464: mov 0xfffffff8 (% EBP), % eax
0x8048467: CMP 0x8 (% EBP), % eax
0x804846a: jle 0x8048470
0x804846c: JMP 0x8048480
0x804846e: mov % ESI, % ESI
0x8048470: mov 0xfffffff8 (% EBP), % eax
0x8048473: Add % eax, 0 xfffffffc (% EBP)
0x8048476: incl 0xfffffff8 (% EBP)
0x8048479: JMP 0x8048464
0x804847b: NOP
0x804847c: Lea 0x0 (% ESI, 1), % ESI
0x8048480: mov 0 xfffffffc (% EBP), % edX
0x8048483: mov % edX, % eax
0x8048485: JMP 0x8048487
0x8048487: mov % EBP, % ESP
0x8048489: Pop % EBP
0x804848a: Ret
End of worker er dump.

View runtime data
-------

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

Print
Print/
Is an expression, is the language expression of the program you debug (GDB can debug multiple programming languages), is the output format, for example, if you want to output the expression in hexadecimal format, it is/X.

I. Expressions

Like many gdb commands, print can accept an expression.
Since it is an expression, it can be a const constant in the current program running,
Variables, functions, and so on. Unfortunately, GDB cannot use the macros you define in the program.

The expression syntax should be the syntax of the language currently being debugged. Since C/C ++ is a popular language
The examples in this article are about C/C ++. (For more information about how to debug other languages using GDB
Description)

In expressions, there are several operators supported by GDB that can be used in any language.

@
Is an array-related operator, which will be described in more detail later.

::
Specifies a variable in a file or function.

{}
Indicates an object pointing to the memory address type.

Ii. program variables

In GDB, you can view the values of the following three variables at any time:
1. Global variables (visible to all files)
2. Static global variables (visible to the current file)
3. Local variables (visible to the current scope)

If your local variables conflict with global variables (that is, duplicate names ),
If a global variable and a local variable in a function have the same name
The previous stop point is in the function. The value of the variable displayed with print will be the value of the local variable in the function. If
To view the global variable value, you can use the ":" OPERATOR:

File: Variable
Function: Variable
You can specify the variable you want to view in this form, which file or function is used. For example, to view the value of global variable X in file f2.c:

GDB) P 'f2. C': x

Of course, the ":" operator will conflict with the c ++ operator. GDB can automatically identify whether the ":" operator is a C ++ operator, so you don't have to worry about exceptions when debugging C ++ programs.

In addition, if optimization options are enabled during program compilation
Some variables may be inaccessible or the value error code may occur when the program is modified. This is very
Normally, the optimization program will delete and modify your program, sort out the statement order of your program, and remove meaningless
Variable, so when you debug a program like GDB, the running commands are different from the ones you write.
The unexpected results will appear. To deal with this situation, you need to disable compilation optimization during program compilation.
Generally, almost all compilers support Compilation optimization. For example, the gnu c/C ++ Compiler
GCC, you can use the "-gstabs" option to solve this problem. For more information about compiler parameters, see compile
The usage instructions of the interpreter.

3. Array

Sometimes you need to view the value of a continuous memory space. For example, an array segment or dynamically allocated
Data size. You can use the "@" operator of GDB. The left side of "@" is the address of the first memory.
Value, and you want to view the Memory Length on the right. For example, your program has the following statement:

Int * array = (int *) malloc (LEN * sizeof (INT ));

Therefore, during GDB debugging, you can use the following command to display the value of this dynamic array:

P * array @ Len

The left side of @ is the value of the first address of the array, that is, the content pointed to by the variable array, and the right side is the length of the data. It is saved in the variable Len and the output result is, it looks like this:

(GDB) p * array @ Len
$1 = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40}

If it is a static array, you can directly use the print array name to display all the data in the array.

Iv. Output Format

Generally, GDB outputs the value of a variable based on the type of the variable. However, you can also customize the output lattice of GDB.
. For example, you want to output a hexadecimal integer or a binary string to view
Bit. To do this, you can use the gdb data display format:

X displays variables in hexadecimal format.
D. Display variables in decimal format.
U displays unsigned integers in hexadecimal format.
O display variables in octal format.
T display variables in binary format.
A displays variables in hexadecimal format.
C. Display variables in character format.
F. Display variables in floating point format.

(GDB) p I
$21 = 101

(GDB) P/A I
$22 = 0x65

(GDB) P/C I
$23 = 101 'E'

(GDB) P/F I
$24 = 1.20.31145e-43

(GDB) P/x I
$25 = 0x65

(GDB) P/T I
$26 = 1100101

5. view memory

You can use the EXAMINE command (abbreviated as X) to view the value in the memory address. The syntax of the X command is as follows:

X/

N, f, and u are optional parameters.

N is a positive integer that shows the memory length, that is, the content of several addresses is displayed from the current address to the back.
F indicates the display format. See the preceding figure. If the address refers to a string, the format can be S. If location 10 is the instruction address, the format can be I.
U indicates the number of bytes requested from the current address. If not specified, GDB defaults to four bytes.
 

The U parameter can be replaced by the following characters. B represents a single byte, H represents a double byte, W represents a four byte, and G represents an octal node.
  When we specify the byte length, GDB reads and writes the specified byte starting from the memory address specified by the memory and takes it as a value.

Indicates a memory address.

The n/f/U parameters can be used together. For example:

Command: X/3uh 0x54320 indicates that the content is read from the memory address 0x54320, h indicates that the two bytes are used as a unit, 3 indicates three units, and the u table is displayed in hexadecimal format.

6. Automatic Display

You can set variables that are automatically displayed when the program stops or when you track them in a single step. The relevant GDB command is display.

Display
Display/
Display/

Expr is an expression. FMT indicates the display format. ADDR indicates the memory address. After you set one or more expressions using display, as long as your program is stopped, GDB automatically displays the values of these expressions.

Formats I and S are also supported by display. A very useful command is:

Display/I $ PC

$ PC is the environment variable of GDB, indicating the instruction address./I indicates that the output format is machine instruction code, that is, assembly. When the program is stopped, the source code corresponds to the machine script code. This is a very interesting function.

The following are some display-related gdb commands:

Undisplay
Delete display
Delete automatic display. dnums indicates the automatically displayed number. If you want to delete multiple numbers at the same time, they can be separated by spaces. If you want to delete numbers within a range, you can use a minus sign (for example, 2-5)

Disable display
Enable display
Disable and enalbe do not delete automatically displayed settings, but only make them invalid and restored.

Info display
View the automatic display information set for display. GDB generates a table and reports to you how many automatic display settings are set in debugging, including the number, expression, and enable.

7. Set display options

There are many display options in GDB. Here I will only list most of the commonly used options.

Set print address
Set print address on
Open the address output. When the program displays the function information, GDB displays the function parameter address. The system is enabled by default, such:

(GDB) f
#0 set_quotes (SCSI = 0x34c78 "<", RQ = 0x34c88 "> ")
At input. C: 530
530 if (lquote! = Def_lquote)

Set print address off
Disable function parameter address display, for example:

(GDB) set print ADDR off
(GDB) f
#0 set_quotes (SCSI = "<", RQ = ">") at input. C: 530
530 if (lquote! = Def_lquote)

Show print address
Check whether the current address display option is enabled.

Set print Array
Set print array on
Open the array display. When the array is displayed, each element occupies one row. If it is not opened, each element is separated by a comma. This option is disabled by default. The two related commands are as follows.

Set print array off
Show print Array

Set print Elements
This option is mainly used to set an array. If your array is too large, you can specify a maximum length for data display. When this length is reached, GDB is no longer displayed. If it is set to 0, it indicates no restriction.

Show print Elements
View the options of print elements.

Set print null-stop
If this option is enabled, when the string is displayed, the end character is displayed. This option is off by default.

Set print pretty on
If you enable the printf pretty option, it looks pretty when GDB displays the struct. For example:

$1 = {
Next = 0x0,
Flags = {
Sweet = 1,
Sour = 1
},
Meat = 0x54 "pork"
}

Set print pretty off
Disable the printf pretty option. GDB displays the struct as follows:

$1 = {next = 0x0, flags = {sweet = 1, sour = 1}, meat = 0x54 "pork "}

Show print pretty
View how GDB displays struct.

Set print sevenbit-strings
Set whether to display characters in \ NNN format. If yes, the string or character data is displayed in \ NNN format, for example, \ 065 ".

Show print sevenbit-strings
Check whether the character display switch is enabled.

Set print Union
Sets whether to explicitly display the consortium data in the struct. For example, the following data structure is available:

Typedef Enum {tree, bug} species;
Typedef Enum {big_tree, Acorn, seedling} tree_forms;
Typedef Enum {Caterpillar, cocoon, butterfly}
Bug_forms;

Struct thing {
Species it;
Union {
Tree_forms tree;
Bug_forms bug;
} Form;
};

Struct thing Foo = {tree, {acorn }};

When this switch is enabled, the following information is displayed after the P Foo command is executed:
$1 = {It = tree, form = {tree = Acorn, bug = cocoon }}

When the P Foo command is executed, the following information is displayed:
$1 = {It = tree, form = {...}}

Show print Union
View the display mode of the consortium data

Set Print Object
In C ++, if an object pointer points to its derived class, if this option is enabled, GDB will automatically display the output according to the rules of the virtual method call. If this option is disabled, GDB does not care about the virtual function table. This option is off by default.

Show Print Object
View the settings of object options.

Set print static-members
This option indicates whether static data members are displayed when the content of a C ++ object is displayed. The default value is on.

Show print static-members
View the static data member option settings.

Set print vtbl
When this option is enabled, GDB will display the virtual function table in a more regular format. It is disabled by default.

Show print vtbl
View the options of the virtual function display format.

VIII. History

When you use GDB print to view the data when the program runs, each print will be recorded by GDB.
GDB will compile the numbers for each print command in the form of $1, $2, $3. So you can
Use this number to access previous expressions, such as $1. The benefit of this function is that
A long expression is entered. If you want to view the value of this expression, you can use the history record.
To access, saving Repeated input.

IX. GDB Environment Variables

You can define your own variables in the debugging environment of GDB to save running data in some debugging programs. It is easy to define a GDB variable. Use the SET command of GDB. The environment variable of GDB is the same as that of UNIX, and starts with $. For example:

Set $ Foo = * object_ptr

When using environment variables, GDB will create this variable when you use it for the first time. In future use, it will directly swap its values. The environment variable has no type. You can define any type for the environment variable. Including struct and array.

Show convenience
This command is used to view all the environment variables currently set.

This is a powerful function. The interaction between environment variables and program variables makes program debugging more flexible and convenient. For example:

Set $ I = 0
Print bar [$ I ++]-> Contents

Therefore, you do not need to input the command in print bar [0]-> contents, printbar [1]-> contents. After you enter such a command, you only need to press enter to repeat the previous statement and the environment variables will be automatically accumulated to complete the output-by-one function.

10. View registers

To view the register value, run the following command:

Info registers
View the register information. (Except floating-point registers)

Info all-registers
View All registers. (Including floating-point registers)

Info registers
View the status of the specified register.

The register contains the data when the program is running, such as the instruction address (IP) currently running the program
Front stack address (SP) and so on. You can also use the print command to access the register.
Add a $ symbol before the register name. For example, p $ EIP.

Change Program Execution
-------

Once you use GDB to mount the program to be debugged, after the program runs, you can follow your own debugging ideas.
Change the running line or variable value of the program to be debugged in GDB. This powerful function can
It is enough for you to better debug your program. For example, you can go through all the points of the program in one run of the program.
.

1. Modify the variable value

It is easy to modify the variable value when the debugged program runs in GDB. You can use the print command of GDB to complete the modification. For example:

(GDB) print x = 4

The expression x = 4 is the C/C ++ syntax, 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.

In some cases, your variables may conflict with the parameters in GDB, for example:

(GDB) whatis width
Type = double
(GDB) P width
$4 = 13
(GDB) Set width = 47
Invalid Syntax in expression.

Because Set width is the gdb command, the "invalid syntax inexpression" setting error occurs. At this time, you can use the setvar command to tell GDB that width is not your GDB parameter, it is the variable name of the program, such:

(GDB) set var width = 47

In addition, in some cases, GDB does not report such errors. Therefore, it is best to use the gdb command in setvar format when you change the value of program variables.

Ii. Redirect execution

In general, the program to be debugged is executed in sequence according to the running sequence of the program code. GDB provides the unordered execution function, that is, GDB can modify the execution sequence of the program and allow the program to jump freely. This function can be completed by the jump command of GDB:

Jump
Specifies the running point of the next statement. It can be the row number of the file, it can be in file: line format, it can be in the offset format of + num. Table-based where the next running statement starts.

Jump

Here
Is the memory address of the code line.

Note that the jump command does not change the content in the current program stack, so when you jump from one function to another
When a function is returned after it is run, an error occurs when the stack operation is performed.
Strangely, it even produces the program core dump. So it is best to jump in the same function.

Anyone familiar with Assembly knows that when the program is running, there is a register used to save the memory location where the current code is located.
Address. Therefore, the jump command changes the value in this register. Therefore, you can use
$ PC to change the jump execution address. For example:

Set $ Pc = 0x485

3. Generate semaphores

Use the singal command to generate a semaphore for the program to be debugged. For example, CTRL + C. This
It is very convenient for program debugging. You can set a breakpoint anywhere in the program running, and use GDB
Generate a semaphore, which accurately generates signals somewhere and is very advantageous for program debugging.

Syntax: signal. UNIX system semaphores usually start from 1 to 15. So the value is in this range.

The single command is different from the Shell kill command. When the system's kill command sends a signal to the program to be debugged
GDB intercepts, while a single command sends a signal directly to the program to be debugged.

4. force function return

If your debugging breakpoint is in a function and other statements are not executed. You can use the return command to force the function to ignore unexecuted statements and return them.

Return
Return
Use the return command to cancel the execution of the current function and return immediately. If the return value is specified, the value of this expression will be recognized as the return value of the function.

5. Force call a function

Call

The expression can be a function to forcibly call the function. And display the return value of the function, as shown in figure
If the return value of the function is void, it is not displayed.

Another similar command can also complete this function-print, print can be followed by expressions, so
You can use it to call the function. The difference between print and call is that if the function returns void, the call is not displayed.
Print: the return value of the function is displayed, and the value is stored in historical data.

Use GDB in different languages
----------

GDB supports the following languages: C, C ++, Fortran, Pascal, Java, chill, assembly, and
Modula-2. Generally, GDB determines the debugging language based on the program you are debugging. For example
If the current file name is suffixed with ". c", GDB considers it a C program. The file name suffix is ". C,. CC,. CP,
. Cpp,. cxx,. c ++ ", GDB will regard it as a C ++ program. While the suffix is ". F,. F", GDB will think it is
The FORTRAN program. If it is suffixed with ". S,. s", it will be considered as an assembly language.

That is to say, GDB will set up its own language environment based on the language of the program you are debugging, And let GDB's life
The language environment changes. For example, when some gdb commands require expressions or variables
The syntax of expressions or variables is completely changed according to the current language environment. For example, in C/C ++
The syntax is * P, while in the Modula-2 is P ^. And, if your current program is composed of several different languages
Together, GDB can automatically switch the language environment according to different languages during the debugging process.
This kind of functionality changed along with the language environment is really considerate for developers.

The following are some commands related to the gdb language environment:

Show Language
View the current language environment. If GDB cannot identify the programming language you are debugging, C is considered as the default environment.

Info Frame
View the language of the current function.

Info Source
View the program language of the current file.

If GDB does not detect the current program language, you can also manually set the current program language. Use the set language command.

After the set language command, you can view the supported language types of GDB:

(GDB) set language
The currently understood settings are:

Local or auto automatic setting based on source file
C use the C Language
C ++ use the C ++ Language
ASM use the ASM Language
Chill use the chill Language
FORTRAN use the Fortran language
Java use the Java language
Modula-2 use the Modula-2 Language
Pascal use the PASCAL Language
Scheme use the scheme Language

You can set the current language environment by keeping up with the listed language name after set language.

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.