GDB debugging program

xiaoxiao2021-03-06  69

GDB debugging program

GDB overview ----

GDB is a powerful UNIX published by GNU open source organization. Perhaps, you prefer the graphical interface method, like the debugging of IDE, etc., but if you are software under the UNIX platform, you will find that the GDB debugging tool has a graphic debugger than VC, BCB. powerful functions. The so-called "inch is a long, the ruler is short" is this truth.

In general, GDB mainly helps you complete the following four features:

1. Start your program, you can run the program as you want to follow your custom requirements. 2. Allow the debugged program to stop at the breakpoint you specified. (Breakpoint can be conditional expression) 3, when the program is stopped, you can check what happened in your program. 4. Dynamic changes your program's execution environment.

From above, GDB and general debugging tools have no two, basically complete these features, but in detail, you will find the power of the debugging tool of GDB, everyone may be used to the graphical debugging tool, but there is At the time, the debug tool of the command line has the function that cannot be completed. Let us look in one by one.

A debug example ------

Source: tst.c

1 #include 2 3 int fullc (int N) 4 {5 int sum = 0, i; 6 for (i = 0; i

Compilation Generation Document: (under Linux) HCHEN / TEST> CC -G TST.C -O TST

Use GDB debugging:

HCHEN / TEST> GDB TST <---------- Starting GDBGNU GDB 5.1.1Copyright 2002 Free Software Foundation, Inc.gdb is Free Software, Covered by The gnu general public liclecense, and you arewelcome to change IT and YOU / or distribute copies of it under certain conditions.Type "show copying" to see the conditions.There is absolutely no warranty for GDB. Type "show warranty" for details.This GDB was configured as "i386-suse-linux" .. (GDB) L <------------------ l Commands is equivalent to List, and the original code is started from the first line. 1 #include 23 int fullc (int N) 4 {5 int sum = 0, i; 6 for (i = 0; i

Breakpoint 1, Main () at tst.c: 17 <---------- Announced at the breakpoint. 17 Long Result = 0; (GDB) N <-------------------- Single statement execution, next command is short. 18 for (i = 1; i <= 100; i ) (gdb) N20 results = I; (GDB) N18 for (i = 1; i <= 100; i ) (GDB) N20 results = i; GDB) c <--------------------- Continue to run the program, and the contractue command is short. Continuing.Result [1-100] = 5050 <---------- Program Output. Breakpoint 2, Func (n = 250) at tst.c: 55 int sum = 0, i; (gdb) N6 for (i = 1; i <= n; i ) (GDB) PI <------ --------------- Print the value of the variable I, the print command is short. $ 1 = 134513808 (GDB) N8 SUM = I; (GDB) N6 for (i = 1; i <= n; i ) (GDB) P Sum $ 2 = 1 (GDB) N8 SUM = I; (GDB) PI $ 3 = 2 (GDB) N6 for (i = 1; i <= n; i ) (GDB) P Sum $ 4 = 3 (GDB) BT <----------------- - View function stack. # 0 func (n = 250) At tst.c: 5 # 1 0x080484e4 in main () at tst.c: 24 # 2 0x400409ed in __libc_start_main () from /lib/libc.so.6(gdb) Finish <- ------------------ exit function. Run Till Exit from # 0 func (n = 250) at Tst.c: 50x080484e4 in main () at tst.c: 2424 Printf ("Result [1-250] =% D / N", FUNC (250)); Value Returned IS $ 6 = 31375 (GDB) C <-------------------- Continue to run. Continuing.Result [1-250] = 31375 <---------- Program Output.

Program evted with code 027. <-------- Program exits, the debugging ends. (GDB) Q <-------------------- exits GDB. HCHEN / TEST>

Ok, has the above feelings, or let us systematically meet GDB.

Use GDB ----

Generally, GDB mainly debugging is a program of C / C . To debug the C / C program, first in compile, we must add debug information to the executable. This can be done using the -g parameter using the compiler (CC / GCC / G ). Such as:> cc -g hello.c -o hello> g -g hello.cpp -o hello

If there is no -g, you will see the function name, variable name, which instead, all of which is the memory address of the runtime. When you use -g to join the debug information, then successfully compile the target code, let's take a look at how to use GDB to debug him.

There are several ways to start GDB:

1, GDB Program is also your executable, generally under the directory.

2, GDB Core uses GDB to simultaneously debug a running program and core file, and Core is the file generated after the program is illegally executed.

3, GDB If your program is a service, you can specify the process ID of this service run. GDB will automatically go up to Attach and debug him. Program should be searched in the PATH environment variable.

When GDB is started, you can add some GDB launch switches. Detailed switches can be viewed with GDB -HELP. I only exemplified some commonly used parameters:

-Symbols -s Read symbol tables from the specified file.

-SE file reads symbolic table information from the specified file and uses him in the executable.

-core -c debugging the core file of Core Dump.

-directory -d Add a search path for a source file. The default search path is the path defined in the environment variable.

GDB command outline -------

After starting the GDB, you can use the GDB command to start the debugger using the GDB command, and the gdb command can use the HELP command to view, as shown below:

/ Home / hchen> gdb GNU gdb 5.1.1 Copyright 2002 Free Software Foundation, Inc. GDB is free software, covered by the GNU General Public License, and you are welcome to change it and / or distribute copies of it under certain conditions. Type "Show Copying" to see the conditions. There is absolutely no warranty for gdb. Type "Show Warranty" for details. This GDB WAS Configured AS "i386-suse-linux". (GDB) Help List of classs of Commands:

aliases - Aliases of other commands breakpoints - Making program stop at certain points data - Examining data files - Specifying and examining files internals - Maintenance commands obscure - Obscure features running - Running the program stack - Examining the stack status - Status inquiries support - Support facilities tracepoints - Tracing of program execution without stopping the program user-defined -. User-defined commandsType "help" followed by a class name for a list of commands in that class Type "help Followed by Command Name for Full Documentation. Command Name Abbreviations Are Allowed if Unambiguous. (GDB)

There are a lot of GDB commands, and GDB is divided into many types. The HELP command is just a command type of GDB. If you want to see the command in the species, you can use the help command, such as: Help Breakpoints, view all commands for setting breakpoints. You can also directly help to view the help of the command.

In the GDB, when entering the command, you can use the first few characters that only use the command, of course, the first few characters of the command should mark a unique command, under Linux, you can knock The full name of the Tab key to make up the command, if there is repetitive, then GDB will come out. Example 1: Set a breakpoint when entering the function FUNC. Can be knocked into Break func, or is directly b func breakpoint 1 at 0x8048458: file hello.c, line 10. Example 2: Typing B Press twice Tab keys, you will see all B heads Command: (GDB) B Backtrace Break BT (GDB)

Example Three: just remember the prefix function, it can be: (gdb) b make_ (once again press the TAB key, you'll see :) make_a_section_from_file make_environ make_abs_section make_function_type make_blockvector make_pointer_type make_cleanup make_reference_type make_command make_symbol_completion_list (gdb) b Make_ GDB All the functions starting with all the makers will be viewed.

Example 4: When debugging the C program, there is a function name. Such as: (GDB) b 'Bubble (INT, INT) B' BUBBLE (You can see all overload functions and parameters in C . (Note: m -? And "Pressing the Tab button" Is a meaning) When you exit GDB, you only use the quit or command to refer to Q.

Running UNIX in GDB ------------

In the GDB environment, you can execute the unix shell command, complete using the gdb's shell command:

Shell Call Unix's shell to perform , UNIX's shell defined in the environment variable shell will be used to perform if shell is not defined, then using UNIX standard shell: / BIN / SH. (Using Command.com or cmd.exe in Windows)

Another GDB command is make: make You can execute your Make command in GDB to re-build your own program. This order is equivalent to "shell make ".

Run out in GDB --------

When GDB is started in GDB , the GDB searches for the source files of in the Path path and the current directory. To confirm if the GDB reads the source file, you can use the L or List command to see if the GDB can list the source code.

In GDB, run the program using R or the run command. The operation of the program, you may need to set the following four aspects.

1, the program runs the parameters. Set Args Specifies the runtime parameter. (, Such as: SET ARGS 10 20 30 40 50) The show args command can view the setup run parameters.

2, the operating environment. Path

can set the running path of the program. Show paths View the runtime path of the program. Set Environment VarName [= value] Set the environment variable. Such as: set env user = hchen show environment [varName] View environment variables.

3, work catalog. CD

is equivalent to the CD command of the shell. The PWD displays the current directory.

4, the input and output of the program. INFO TERMINAL displays the mode of the terminal you use. Use the redirection control program to output. Such as: run> outfile tty command can write the terminal device input and output. Such as: TTY / DEV / TTYB

Debugging the running program --------

Two methods: 1. View the PID (process ID) of the running program with PS under UNIX, and then mount the running program with GDB PID format. 2, first use GDB to associate upward upward upward up, GDB, use the attach command in GDB to hook the PID of the process. And use DETACH to cancel the process.

Pause / recovery program run ---------

In the debugger, the suspension program is required, and GDB can easily pause the operation of the program. You can set the program where you have stopped, stop under what conditions, or stop when you receive a signal. To allow you to view runtime variables, as well as runtime processes. When the process is parked by GDB, you can use Info Program to see if the program is running, the process number, and is suspended.

In GDB, we can have the following pauses: breakpoint, watchpoint, catchpoint, signal (Signals), thread stops. If you want to recover the program, you can use C or the Continue command.

First, set breakpoints, we use the break command to set the breakpoint. There are several ways to set breakpoints on the front: BREAK Announced when entering the specified function. You can specify the function name using the Class :: function or function (type, type, type) format in C .

Break Announced in the specified line number.

Break Offset Break -offset Announces the offset line in front of the current line number. OFFSET is natural number.

Break FileName: Linenum Announced on the Linenum line of the source file filename.

Break filename: Function is stopped at the entrance to the function function of the source file filename.

Break * address stops at the memory address running.

When the BREAK BREAK command does not have a parameter, it is said to stop at the next instruction.

Break ... if ... can be the above parameters, Condition represents the condition, stop when the condition is set up. For example, in the circulatory body, Break if i = 100 can be set, indicating that the program is stopped when I is 100.

When you check the breakpoint, you can use the info command, as shown below: (Note: n) Info Breakpoints [N] Info Break [N]

Second, setting the WatchPoint observation point General to observe if a certain expression (variable is also an expression) value varies, if there is a change, stop the program immediately. We have the following ways to set the observation point: Watch sets an observation point (variable) EXPR. When the one-volume expression value changes, the program is stopped immediately. RWATCH When the expression (variable) expr is read, the program is stopped. AWATCH stops the program when the value of the expression (variable) is read or written. INFO WATCHPOINTS lists all the observation points currently set.

Third, set the capture point (CatchPoint)

You can set the capture point to make some events at runtime. Such as: Load shared library (dynamic link library) or C exception. Set the format of the capture point to: catch When Event occurs, stop the program. Event can be below: 1. Throw a C throw an exception. (Throw is key) 2, Catch a C capture exception. (CATCH is key) 3, the Exec call system calls EXEC. (EXEC is keyword, currently this feature is only useful under HP-UX) 4. When the Fork call system calls fork. (Fork is keyword, this feature is currently useful under HP-UX) 5, when the VFORK call system calls vfork. (Vfork is keyword, this feature is currently useful under HP-UX) 6, LOAD or LOAD When loading a shared library (dynamic link library). (LOAD is keyword, this function is currently useful under HP-UX) 7, unload or unload When you uninstall the shared library (dynamic link library). (Unload is keyword, this feature is currently useful in HP-UX) Tcatch only sets only one capture point, and after the program is stopped, the should be automatically deleted.

Fourth, maintain the stop point

The above mentioned how to set the stop point of the program, the stop point in the GDB is the three classes described above. In GDB, if you feel that the defined stop point is not used, you can use the delete, clear, disable, and enable, these commands to maintain.

Clear clears all defined stoppoints.

Clear Clear Clear all stop points on the function.

Clear Clear Clear all the stop points set on the specified line.

Delete [BreakPoints] [Range ...] Deletes the specified breakpoint, BreakPoints is a breakpoint. If the break point is not specified, it means deleting all breakpoints. Range represents the range of breakpoints (such as: 3-7). Its shorthand command is D.

A better way to delete is the disable stop point. The stop point of Disable, the GDB will not be deleted. When you need it, Enable is as follows.

Disable [BreakPoints] [Range ...] Disable, the stop point specified by Disable, BreakPoints is the stop point number. If nothing is specified, it means all stop points for Disable. The shorthand command is DIS.

Enable [Breakpoints] [Range ...] Enable The stoppoint specified, Breakpoints is the stop point number.

Enable [BreakPoints] Once Range ... Enable The stop point specified once, when the program is stopped, the stop point is automatically disabled by GDB.

Enable [BreakPoints] delete Range ... Enable The stop point specified once, when the program is stopped, the stop point is automatically deleted by GDB. 5. Stop condition maintenance

As mentioned earlier, when we mentioned the breakpoint, we mentioned that you can set a condition. When the conditions are set up, the program is automatically stopped. This is a very powerful function. Here, I want to tell the relevant maintenance commands for this condition. In general, set a condition for breakpoints, we use the IF keyword, followed by its breakpoint conditions. Moreover, after the condition is set, we can use the construct command to modify the conditions of the breakpoint. (Only Break and Watch Commands Support IF, Catch does not currently support IF)

Condition Modify the stop condition for BNUM for Expression.

Condition Clears the stop condition of BNUM.

There is also a particularly special maintenance command ignore, you can specify the program run, ignore the stop condition a few times.

Ignore means that the stop condition COUNT that ignores the breakpoint of BNUM.

6. Set the run command for the stop point

We can use the Command command provided by GDB to set the run command of the stop point. That is, when the running program is stopped, we can make it automatically run for some other commands, which is advantageous to automate debugging. GDB-based automation debugging is a powerful support.

Commands [BNUM] ... command-list ... End

Write a list of commands for the breakpoint BNUM. When the program is stopped by the breakpoint, the GDB will run the command in the command list.

E.g:

Break foo if x> 0 Commands Printf "x IS% D / N", X Continue End breakpoint is set in the function foo, the breakpoint condition is x> 0, if the program is broken, that is, once X In the FOO function is greater than 0, GDB automatically prints the value of X and continues to run the program.

If you want to clear the command sequence on the breakpoint, just make a commands command, and you will do it directly.

Seven, breakpoint menu

In C , you may repeat the function of the same name (function overload), in which case BREAK cannot tell GDB to stop in which function is to stop. Of course, you can use Break that is, tell GDB's parameter type of the function to specify a function. Otherwise, GDB will list a break menu for you to choose the breakpoint you need. You just need to enter the number in your menu list. Such as:

(GDB) B String :: after [0] Cancel [1] all [2] file: string.cc; line number: 867 [3] file: string.cc; line number: string.cc; line number: string.cc Line Number: 875 [5] file: string.cc; line number: 853 [6] file: string.cc; line number: 846 [7] file: string.cc; line number: 735> 2 4 6 Breakpoint 1 at 0xb26c: file String.cc, line 867. Breakpoint 2 at 0xb344: file String.cc, line 875. Breakpoint 3 at 0xafcc:. file String.cc, line 846. Multiple breakpoints were set Use the "delete" command to delete Unwanted breakpoints. (GDB), GDB lists all AFTER's overload function, you can choose the list number. 0 indicates that the setting breakpoint is given, and 1 means that all functions set breakpoints.

Eight, recovery procedures running and single-step debugging

When the program is stopped, you can use the Continue command to recover the run until the end of the program, or the next breakpoint. You can also use the STEP or NEXT command single-step tracker.

Continue [ignore-count] c [ignore-count] FG [ignore-count] recovery program runs until the program ends, or the next breakpoint arrival. Ignore-count indicates that the number of breakpoints is ignored. The three commands of Continue, C, and FG are the same meaning.

Step Single step tracking, if there is a function call, he will enter the function. The premise of entering the function is that this function is compiled with Debug information. Very like Step in in Tools such as VC. Behind COUNT can also not be added, do not add a strip execution, plus the COUNT section instruction to execute, and then stop.

Next The same single step tracking, if there is a function call, he will not enter the function. Very STEP over, such as the VC and other tools. Behind COUNT can also not be added, do not add a strip execution, plus the COUNT section instruction to execute, and then stop.

SET STEP-MODE SET STEP-MODE ON Open STEP-MODE mode, so that the program does not stop because there is no debug information when performing single-step tracking. This parameter is favorable to view the machine code.

Set Step-Mod Off Turns the Step-Mode mode.

Finish running procedure until the current function completes the return. And print functions returned to the stack address and return value and parameter value.

Until or u When you are tired of walking in a cyclic body, this command can run the program until the cyclic body is exited.

Stepi or Si nexti or Ni single step tracking one machine directive! A program code may be completed by several machine instructions, STEPI and NEXTI can perform machine instructions in a single step. As with the same function as the same function is "Display / I $ PC", after running this command, single-step tracking will play machine instructions while playing the program code (that is, assembly code)

Nine, signals (SIGNALS)

The signal is a soft interrupt, a method of processing an asynchronous event. In general, the operating system supports many signals. Especially UNIX, compare important applications generally process signals. Unix defines a number of signals, such as Sigint represents the interrupt character signal, that is, the signal of Ctrl C, Sigbus represents the signal of the hardware fault; SIGCHLD represents the signal of the child process; Sigkill indicates the signal of the termination program, and the like. Semicidal programming is a very important technology under UNIX.

GDB has the ability to deal with any signal when you debug the program, you can tell GDB which signal needs to process. You can ask GDB When you receive the signal you specified, you will stop running the program that is running for you to debug. You can use the GDB's handle command to complete this feature.

Handle defines a signal processing in GDB. Signal can be started with SIG or not starting with SIG, can be used to define a range to process signals (such as: sigio-sigkill, indicating processing from SIGIO signals to sigkill, including SIGIO, SIGIOT, SIGKILL three signals ), You can also use the keyword all to indicate all signals to process. Once the debugged program receives the signal, the running program will be immediately stopped by GDB for debug. Its can be one or more of the following keywords.

Nostop When the debugging program receives a signal, GDB does not stop the running of the program, but the message tells you that this signal is received. When the STOP receives the signal when the debugged program, GDB will stop your program. Print When the debugging program receives the signal, GDB will display a message. NOPRINT When the debugging program receives the signal, GDB will not tell you information about the signal. PASS NOIGNORE When the debugging program receives the signal, the GDB does not process the signal. This means that GDB will hand over this signal to the debugged program. When NOPASS IGNORE receives a signal when the debugged program receives the signal, the GDB will not let the debug program process this signal.

Info Signals Info Handle View which signals are in GDB detection.

Ten, thread stops

If your program is multi-thread, you can define if your breakpoint is on all threads or in a particular thread. GDB is easy to help you have completed this.

BREAK Thread BREAK Thread if ... Linespec Specifies the line number of the source program that is set in the breakpoint. Threadno Specifies the id's ID, note that this ID is GDB assignment, you can view thread information in the program through the "Info Threads" command. If you don't specify Thread , you indicate that your breakpoint is located on all threads. You can also specify a breakpoint condition for a thread. Such as: (GDB) Break Frik.c: 13 Thread 28 IF Bartab> Lim

When your program is parked by GDB, all running threads will be stopped. This makes it easy you to view the overall situation of the running program. And all threads are still running when you are running in your recovery program. It is afraid that the main process is in a single step of debugging. View Stack Information -----

When the program is stopped, the first thing you need to do is to check where to stop. When your program calls a function, the address, function parameters, and the local variables in the function will be pressed into the "stack". You can use the GDB command to see the information in the current stack.

Here is some GDB commands for viewing the function call stack information:

Backtrace BT prints all information about the current function call stack. Such as: (gdb) BT # 0 func (n = 250) at tst.c: 6 # 1 0x08048524 in main (argc = 1, argv = 0xBfffff674) At TST.C: 30 # 2 0x400409ed in __libc_start_main () from / lib / lib / lib / lib / lib / lib / lib / lib / lib / /Libc.so.6 can be seen from the function of the call stack information: __ libc_start_main -> main () -> func () backtrace bt n is a positive integer, indicating that only the top of the stack Stack information of the N layer.

BackTrace <-n> bt <-n> -n table a negative integer, indicating that only the stack information of the N layer under the stack. If you want to see a layer of information, you need to switch the current stack, in general, the program is stopped, the top of the stack is the current stack, if you want to check the details of the stack, first you want to do it first. Switch the current stack.

Frame f n is an integer starting from 0 and is a layer number in the stack. For example: frame 0, represents the top of the stack, FRAME 1, indicating the second layer of the stack. Up indicates that the upper surface of the stack moves the N layer, and may not be hit N, indicating that the upward moves. Down indicates that the n layer is moved below, and may not beat N, indicating a downward movement.

The above command will print out information of the moving stack layer. If you don't want it to make it. You can use these three commands: SELECT-FRAME corresponds to the frame command. Up-Silently corresponds to the UP command. Down-Silently corresponds to the Down command.

View the current stack of information, you can use the following GDB command:

Frame or F will print this information: the stack layer number, the current function name, the function parameter value, the file in the file and the line number, the function executed by the function. Info frame info f This command prints more detailed information of the current stack layer, but most is the internal address of the runtime. For example, the function address, the address of the call function, the address called function, the current function is written by, the function parameter address, the value, the address, and the like of local variables, etc. Such as: (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 0xBffFFF5D8 INFO ARGS Prints the parameter name and its value of the current function. INFO LOCALS prints all local variables and their values ​​in the current function. INFO CATCH prints an exception handling information in the current function. View Source ----- First, Display Source Codes

GDB can print out the source code of the debugprue, of course, be sure to add -g parameters when compiling, and compile the source program information into the execution file. Otherwise, you can't see the source program. When the program stops, the GDB will report that the program stopped on the first few lines of the file. You can use the list command to print the source code of the program. Let's take a look at the GDB command to view the source code. List Displays the source program around the Linenum line of the program. List Displays the source program of a function called function name FUNCTION. List displays the source program behind the current line. List - Displays the source program in front of the current row.

Generally, print the top 5 rows of the current row, if the display function is on the top 2 line 8 line, the default is 10 lines, of course, you can customize the range of display, use the following command to set a display source program The number of rows.

Set listsize Sets the number of rows that displays the source code. Show ListSize looks at the current ListSize settings.

The List command has the following usage:

List , Displays the source code between the first line to the LAST line. List, Displays the source code from the current line to the LAST line. List displays the source code.

Generally speaking, you can follow the following parameters after List:

line number. < Offset> The positive offset of the current line number. <-Offset> The negative shift of the current line number. Which file is of which file. Function Name. which function in which file is. <* Address> The address of the statement of the program runs in memory. Second, search source code

Not only that, GDB also provides commands for source code search:

Forward-Search search Search to the front.

REVERSE-Search All Searches. Among them, is the regular expression, and the main string matching mode, about the regular expression, I will not talk about it here, please check the relevant information.

Third, the path to specify the source file

At some point, in the execution program compiled with -g, just includes the name of the source file, no path name. GDB provides commands that allow you to specify the path to the source file to search for GDB.

Directory DIR Add a source file path to the current path. If you want to specify multiple paths, you can use ":", you can use ":" and Windows. Directory clears all custom source file search path information. Show Directories Displays the defined source file search path.

Fourth, the memory of the source code

You can use the Info Line command to view the address of the source code in memory. Info Line, you can follow the "Row", "Function Name", "File Name", "File Name: Function Name", this command prints the memory address of the specified source code at runtime, such as:

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

There is also a command that you can view the current execution of the source program, this command will take the command dump in the current memory. As shown below, the assembly code of the function FUNC is viewed.

(Gdb) disassemble func Dump of assembler code for function func: 0x8048450 : push% ebp 0x8048451 : mov% esp,% ebp 0x8048453 : sub $ 0x18,% esp 0x8048456 : MOVL $ 0x0 ,0xffffffc (% EBP) 0x804845d : MOVL $ 0x1, 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff. (% EBP) 0x8048464 : MOV 0xFffffFf8 (% EBP),% EAX 0x8048467 : CMP 0x8 (% EBP),% EAX 0x804846A : jle 0x8048470 0x804846c : JMP 0x8048480 0x804846e : MOV% ESI, % ESI 0X8048470 : MOV 0xfffffffff8 (% EBP),% EAX 0x8048473 : add% EAX, 0xffffffffc (% EBP) 0x8048476 : INCL 0xFFFFFFFF8 (% EBP) 0x8048479 : JMP 0x8048464 0x804847B : NOP 0x804847C : LEA 0x0 (% ESI, 1),% ESI 0x8048480 : MOV 0xFffFFFFC (% EBP) % EDX 0 x8048483 : MOV% EDX,% EAX 0x8048485 : JMP 0x8048487 0x8048487 : MOV% EBP,% ESP 0x8048489 : POP% EBP 0x804848a : Ret end of assemer dump.

View runtime data ------ When you debug the program, when the program is parked, you can use the print command (the shortup command is p), or syncing the command inspect to view the current program running data. The format of the print command is: Print Print / is an expression, is the expression of the language you debugging (GDB can debug multiple programming languages), is Output format, for example, if you want to output an expression in the format of the 16-in-1, then / x. First, the expression print and many gdb commands, you can accept an expression, and the GDB calculates this expression based on the data running in the current program. Since it is an expression, it can be a constant constant in the current program run. Variables, functions, etc. Unfortunately, GDB can't use the macro you defined in the program. The expression of the expression should be the syntax of the language currently debugged, since C / C is a public type of language, so the examples in this article are about C / C . (About the chapter of the other language with GDB, I will introduce later) in the expression, there are several gdb supported operators, which can be used in any language. @ Is an operator related to an array, which will have a more detailed description. :: Specify a variable in a file or a function. {} represents an object that pointing to the memory address type Type. Second, 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 variables (current file visible) 3, local variables (current scope visible) if your part Variables and global variables have conflicts (which are heavy), in general, local variables hide global variables, that is, if a global variable and local variable in a function are the same name, if the current stop point is in the function, The value of the variable displayed with Print is the value of the local variable in the function. If you want to view the value of global variables, you can use the "::" operator: File :: variable function :: variable can specify the variable you want to view, which file is in or Which function is in. For example, view the value of the global variable x in file f2.c: GDB) P 'f2.c' :: x Of course, "::" Operations and C conflicts, GDB can automatically identify "::" Whether the operator of C , so you don't have to worry that there will be exceptions when debug C programs. In addition, it is important to note that if your program is compiled, the optimized option is turned on, then some variables may not be accessed when using GDB to be optimized, or the value of the value is incorrect. This is normal, because the optimizer will delete your program, organize your program's order, eliminate some meaningless variables, so when you debug this program, the runtime instruction and you write instructions. Different, there will be no results you think. When this is done, it is necessary to turn the compilation optimization when the compiler is compiled. In general, almost all compilers support compilation optimized switches, for example, GNU's C / C compiler GCC, you can use the "-gstabs" option to solve this problem. For parameters for the compiler, please check the instructions documentation for the compiler. Third, array

Sometimes you need to see a value of a continuous memory space. For example, a parameter of an array or the size of the data that is dynamically allocated. You can use the "@" operator, "@" operator, "@" is the value of the first memory address, "@", you want to see the length of memory. For example, there is such a statement in your program: int * array = (int *) malloc (len * sizeof (int)); then, in the GDB debugging process, you can display this dynamic array with the following command. :

P * array @ le

@ 的 边 边 数 地址 内容 内容 是 是 是 是 是 是 是 是 是 是 是 中 中 中 中 中 中 中 中 中 中 中 中 中 中 中 中 中 中 的 的 的 的 的 中 的 的 的 的 的 的Array @ le $ 1 = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 34, 36, 38, 40}

If it is a static array, you can display all the contents of all the data in the array can be displayed directly with the Print array name.

Fourth, output format

In general, GDB outputs the value of variables according to the type of variable. But you can also customize the format of the output of GDB. For example, you want to output an integer hexadecimal, or binary to view the situation in this integer variable. To do this, you can use GDB data display format: x Press hexadecimal format to display variables. D Display variables by decimal format. U Display unsigned integer in the hexadecimal format. O Display variables in eight-en-binary format. T Press binary format to display variables. A Display variables in hexadecimal format. C Press the character format display variable. F Display variables in floating point. (GDB) P / $ 22 = 0x65 (GDB) P / CI $ 23 = 101 'E' (GDB) P / Fi $ 24 = 1.41531145E-43 (GDB) P / Xi $ 25 = 0x65 ( GDB) P / Ti $ 26 = 1100101

Five, check the memory

You can use the examine command (short-write Yes x) to see the value in the memory address. The syntax of the x command is as follows: X / n, f, u is an optional parameter. N is a positive integer that represents the length of the memory, that is, the content of several addresses from the current address. F represents the format displayed, see above. If the address refers to a string, the format can be s, if the ten is the command address, then the format can be i. U Represents the number of bytes requested from the current address, if not specified, the GDB defaults to 4 Bytes. u Parameters can be replaced with the following characters, b represents a single byte, h represents double bytes, w represents four bytes, g represents eight bytes. When we specify the length of the byte length, the GDB will start from the memory address, read and write the specified byte, and take it as a value. represents a memory address.

The three parameters of n / f / u can be used together. For example: command: x / 3uh 0x54320 is represented, from the memory address 0x54320 read content, H is indicated by a double-byte as one unit, 3 represents three units, u means that pressing hexadecimal display. Six, automatic display

You can set some of the automatically displayed variables, or when the program is stopped, or when you are single-step tracking, these variables are automatically displayed. The associated GDB command is Display. Display Display / display / expr is an expression, FMT represents the format of the display, and addr represents the memory address, when you set up one or more expressions in DISPLAY After the style, as long as your program is stopped, GDB will automatically display the values ​​of these expressions you set. Format 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 address of the instruction, and / i indicates the output format of the machine command code, which is compilation. So when the program is stopped, the source code and the machine command code correspond to the case, which is a very interesting feature. Here is some GDB commands related to Display: undisplay Delete Display Delete automatically displayed, DNUMS means the set automatic explicit number. If you want to delete a few, the number can be separated by space. If you want to delete a range, you can use a minus sign (eg 2-5) Disable display enable display Disable and ENALBE do not delete automatic display settings, but just make it fails and recovered. Info Display View automatic display of Display settings. GDB will play a form and report how many automatic display settings set in the debug, which includes, set numbers, expressions, whether eNABLE. 7. Set display options

There are more options on the display in GDB. Here I will only exist of most common options.

Set Print Address Set Print Address ON Open Address Output, when the program displays the function information, GDB will display the parameter address of the function. The system defaults to open, such as: (GDB) F # 0 set_quotes (lq = 0x34c78 "<<", RQ = 0x34c88 ">>") AT INPUT.C: 530 530 IF (LQUOTE! = Def_lquote)

Set Print Address Off Parameter Address Display, such as: (GDB) Set Print Addr Off (GDB) F # 0 set_quotes (lq = "<<", RQ = ">>") AT INPUT.C: 530 530 IF (LQUOTE! = Def_lquote)

Show Print Address View whether the current address display option is open. Set Print Array Set Print Array ON ON ON Display, when the array is turned, each element occupies a row, if not open, each element is separated by a comma. This option is closed by default. The two commands related to it are as follows, I will not say more. Set Print Array Off Show Print ArraySet Print Elements This option is primarily set, if your array is too big, you can specify a to specify the maximum data display. Length, when the length is reached, GDB is no longer displayed down. If set to 0, it is not limited. Show Print Elements View the option information for Print Elements. Set print null-stop If this option is opened, the end is displayed when the string is displayed. This option defaults to OFF. Set Print Pretty On If you open the PrintF pretty this option, it is more beautiful when the GDB displays the structure. Such as:

$ 1 = {Next = 0x0, Flags = {SWEET = 1, Sour = 1}, meat = 0x54 "pork"}

Set Print Pretty Off Close the Printf Pretty this option, the GDB displays the structure as follows: $ 1 = {Next = 0x0, Flags = {SWEET = 1, SOUR = 1}, meat = 0x54 "Pork"} show print Pretty View GDB How to display structures. Set print sevenbit-strings Settings the character display, press "/ nn" format display, if the string or character data is displayed / NNN, such as "/ 065". Show Print Sevenbit-Strings View the character display switch is open. Set Print Union Set whether or not the consortium within the display structure is explicit. For example, the following data structure: 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 think = {Tree, {acorn}}; When this switch is turned on, after executing the P foo command, it will be displayed as follows: $ 1 = {it = Tree, form = {Tree = acorn, bug = Cocoon}} When the P foo command is executed, the P foo command is executed as follows: $ 1 = {it = Tree, form = {...}}

Show Print Union Display Methods SET Print Object In C , if an object pointer points to its partial class, if you open this option, GDB will automatically display the output according to the rule called by the virtual method, if closed If this option, GDB does not have a virtual function table. This option is OFF by default. Show Print Object View the setting of the object option. Set print static-members This option indicates whether the content in a C object is to display the static data member. The default is ON. Show Print Static-Members View Static Data Members Options Settings. Set Print VTBL When this option is turned on, GDB will display the virtual function table with a comparison format. Its default is closed. Show Print VTBL View options for virtual functions display format. 8. History When you use the GDB's Print to view the data running data, you will be recorded by GDB. GDB will make every print command for your way in a way in $ 1, $ 2, $ 3 ...... Thus, you can use this number to access the previous expressions, such as $ 1. The benefits of this feature are that if you have previously entered a relatively long expression, if you want to view the value of this expression, you can use history to access, save your duplicate input. Nine, GDB environment variables

You can define your own variables in the GDB debug environment to save running data in some debuggers. To define a variable of a GDB is simple. Use the GDB's set command. GDB's environment variables are the same as UNIX, is also a head. For example: SET $ foo = * Object_ptr When using environment variables, GDB will create this variable when you first use, and in later use, it assigns it directly. Environment variables have no type, you can define any type to the environment variable. Includes structures and arrays. Show convenience This command views all the environment variables currently set. This is a relatively powerful function, environmental variable, and program variable interaction, which will make program debugging and convenient. For example: SET $ I = 0 Print Bar [$ I ] -> Contents, when you don't have to, Print Bar [0] -> Contents, Print Bar [1] -> Contents Enter commands. After entering such a command, only the knock back, repeat the previous statement, the environment variable will be automatically accumulated, thereby completing the function of outputting one by one. Ten, check the register

To view the value of the register, it is easy, you can use the following command: Info Registers to view the register. (In addition to floating point registers) Info all-registers to view all registers. (Including floating point registers) Info registers View the situation of the specified register. The program is placed in the register, such as the currently running instruction address (IP), the current stack address (SP) of the program, and the like. You can also use the print command to access the register, just add a $ symbol before the register name. Such as: p $ EIP. Change the execution of the program -------

Once you use the GDB to hang up the debugger, when the program runs, you can dynamically change the current debugger running line or the value of its variable according to your own debugging ideas, this powerful function can make you Better debugging your program, for example, you can run all the branches of the program in the program. First, modify the variable value

Modify the variable value when the debugger is running, it is easy to implement in GDB, and you can complete it using GDB's print command. Such as: (GDB) Print X = 4 x = 4 This expression is the syntax of C / C , meaning modified to 4 values ​​of the variable x, if your current debug language is PASCAL, then you can use PASCAL syntax: x: = 4. At some point, it is very likely that your variables and parameters in GDB conflicts, such as: (GDB) Width Type = Double (GDB) P Width $ 4 = 13 (GDB) set width = 47 Invalid Syntax in Expression.

Because set width is the command of GDB, "Invalid Syntax In Expression" appears error, at this time, 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, some cases, GDB does not report such an error, so the insurance starts, it is best to use the set var format when you change the program variable.

Second, jump execution

In general, the debugging procedure will be executed in accordance with the running order of the program code. GDB provides the function of chaos, that is, GDB can modify the execution order of the program, allowing the program to execute cashed. This feature can be over the jump command of GDB: Jump Specifies the operating point of the next statement. can be the line number of the file, which can be file: line format, which can be NUM's offset format. The table is the next operational statement where to start. JUMP

The
is the memory address of the code line. Note that the jump command will not change the content in the current program stack, so when you jump from a function to another, the function will have errors when the function runs back, and the possible results are still very strange. Even generation of program core dump. So it is best to jump in the same function. People who are familiar with assembly know that when the program is run, there is a register to save the memory address where the current code is located. Therefore, the JUMP command is also changing the value in this register. Thus, you can use the "SET $ PC" to change the address of the jump execution. Such as: set $ pc = 0x485 three, generating semaphors

Use the Singal command to generate a signal to be debugged. Such as: Interrupt Signal Ctrl C. This is very convenient for debugging of the program, setting breakpoints in any position running, and generating a semaphore in this breakpoint, which accurately generates a debugging of the signal at some point. The syntax is: Signal , UNIX system semaphore usually from 1 to 15. So is also in this range. Different Single Commands and Shell's Kill commands, when the system's kill command signals to the debugged program, it is intercepted by GDB, and a signal from the SINGLE command is sent directly to the debugged program.

Fourth, the mandatory function returns

If your debug break is in a function, and there is still a statement that is not executed. You can use the return command to force the function ignore the statements that have not yet been executed and return. Return Return Use the return command to cancel the execution of the current function and return immediately, if is specified, the value of the expression is recognized as the return value of the function. V. Forced call functions

The Call can be a function to achieve the purpose of the forced call function. And display the return value of the function, if the function returns the value is Void, then it is not displayed. Another similar command can also complete this feature --Print, which can be followed by the expression, so it can also be used to call the function, the varint, and call are different. If the function returns Void, Call does not display, Print The display function returns the value and stores the value into historical data.

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

GDB supports the following languages: C, C , Fortran, Pascal, Java, Chill, Assembly, and Modula-2. Generally speaking, GDB will determine the debug language according to the program you debug, such as: Discovering the file name suffix ".c", GDB will consider a C program. The file name suffix is ​​".c, .cc, .cp, .cpp, .cxx, .c ", GDB will consider a C program. The suffix is ​​".f, .f", GDB will consider the Fortran program, and if the suffix is ​​".s, .s" will consider the assembly language. That is, GDB will set their own language environment based on the language of the program you debug, and let GDB's commands change to change the language environment. For example, some GDB commands require expression or variables, the syntax of these expressions or variables is completely changed according to the current locale. For example, the syntax of the pointer in C / C is * P, and in the modula-2 is P ^. Also, if your current program is compiled by several different languages, the GDB can automatically switch the locale according to different languages ​​during the debugging. This function of changing the language environment is really a design of the developer.

Here are a few commands related to the GDB locale:

Show Language Views the current locale. If GDB does not know the programming language you debug, then the C language is considered a default environment. Info frame is a program language of the current function. Info Source is a program language for the current file. If the GDB does not detect the current programming, you can also manually set the current program language. Use the set language command to do.

When the set language command is not followed, you can view the language type supported by 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 so you can keep up is listed in the set language Program language names come to set up the current locale.

postscript--

转载请注明原文地址:https://www.9cbs.com/read-119788.html

New Post(0)