Debug a program with GDB

Source: Internet
Author: User
Tags aliases switches

Turn from: http://blog.csdn.net/haoahua/article/details/2056854


the original text is from the Chenhao column (http://blog.csdn.net/haoel/), thanks to the author for publishing such a good article.

Debug a program with GDB

Debug the program with GDB (i)

GDB Overview
————

GDB is a powerful UNIX program debugging tool released by the GNU Open source organization. Perhaps, you like the graphical interface, such as VC, BCB debugging IDE, but if you are in the UNIX platform to do the software, you will find that the debugging tool GDB is more than VC, BCB graphics debugger more powerful features. The so-called "inch, the ruler has short" is this truth.

In general, GDB mainly helps you complete the following four aspects of the function:

1, start your program, you can follow your custom requirements of the arbitrary operation of the program.
2. You can let the program being debugged stop at the breakpoint where you specify the adjustment. (A breakpoint can be a conditional expression)
3. When the program is stopped, you can check what happens in your program at this time.
4, dynamic changes in the execution of your program environment.

From the above, GDB is no different from the usual debugging tools, basically complete these functions, but in detail, you will find GDB this debugging tool is powerful, you may be more accustomed to the graphical debugging tools, but sometimes, the command line debugging tools are not completed by the graphical tools. Let's see it all.


A debugging example
——————

SOURCE program: TST.C

1 #include <stdio.h>
2
3 int func (int n)
4 {
5 int sum=0,i;
6 for (i=0; i<n; i++)
7 {
8 sum+=i;
9}
return sum;
11}
12
13
Main ()
15 {
int i;
Long result = 0;
for (I=1; i<=100; i++)
19 {
result = i;
21}
22
printf ("result[1-100] =%d/n", result);
printf ("result[1-250] =%d/n", func (250));
25}

Compile Build Execution file: (under Linux)
hchen/test> cc-g Tst.c-o TST

Debugging with GDB:

hchen/test> gdb TST <----------start GDB
GNU gdb 5.1.1
Copyright 2002 Free Software Foundation, Inc.
The GDB is free software, covered by the GNU general public License, and your are
Welcome to change it and/or distribute copies of it under certain conditions.
Type ' show copying ' to the conditions.
There is absolutely no warranty for GDB. Type ' show warranty ' for details.
This is GDB was configured as "I386-suse-linux" ...
(GDB) L <--------------------l command is equivalent to the list, starting with the first line of the original code.
1 #include <stdio.h>
2
3 int func (int n)
4 {
5 int sum=0,i;
6 for (i=0; i<n; i++)
7 {
8 sum+=i;
9}
return sum;
(GDB) <--------------------Direct carriage return, repeat the last command
11}
12
13
Main ()
15 {
int i;
Long result = 0;
for (I=1; i<=100; i++)
19 {
result = i;
(GDB) Break <--------------------set breakpoints at the 16th line of the source program.
Breakpoint 1 at 0x8048496:file tst.c, line 16.
(GDB) Break Func <--------------------set a breakpoint at the func () entrance of the function.
Breakpoint 2 at 0x8048456:file tst.c, line 5.
(GDB) Info Break <--------------------view breakpoint information.
Num Type Disp ENB address What
1 breakpoint Keep Y 0x08048496 in main at tst.c:16
2 Breakpoint Keep Y 0x08048456 in func at Tst.c:5
(GDB) R <---------------------running programs, Run command shorthand
Starting program:/HOME/HCHEN/TEST/TST

Breakpoint 1, Main () at Tst.c:17 <----------stop at the breakpoint.
Long result = 0;
(GDB) n <---------------------A single statement is executed, and the next command is abbreviated.
for (I=1; i<=100; i++)
(GDB) n
result = i;
(GDB) n
for (I=1; i<=100; i++)
(GDB) n
result = i;
(GDB) C <---------------------continue to run the program, continue command shorthand.
Continuing.
RESULT[1-100] = 5050 <----------program output.

Breakpoint 2, func (n=250) at Tst.c:5
5 int sum=0,i;
(GDB) n
6 for (i=1; i<=n; i++)
(GDB) P i <---------------------the value of the print variable i and the Print command is abbreviated.
$ = 134513808
(GDB) n
8 sum+=i;
(GDB) n
6 for (i=1; i<=n; i++)
(GDB) P sum
$ = 1
(GDB) n
8 sum+=i;
(GDB) P I
$ = 2
(GDB) n
6 for (i=1; i<=n; i++)
(GDB) P sum
$ = 3
(GDB) bt <---------------------view the function stack.
#0 func (n=250) at Tst.c:5
#1 0x080484e4 in Main () 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:5
0x080484e4 in Main () at tst.c:24
printf ("result[1-250] =%d/n", func (250));
Value returned is $ = 31375
(GDB) C <---------------------continue to run.
Continuing.
RESULT[1-250] = 31375 <----------program output.

Program exited with code 027. <--------program exits and debugging ends.
(GDB) Q <---------------------exit gdb.
Hchen/test>

Well, with the above perceptual knowledge, or let us have a systematic understanding of GDB bar.


Using GDB
————

In general, GDB is primarily debugging C + + programs. To debug a C + + program, first at compile time, we have to add debug information to the executable file. You can do this with the-g parameter of the compiler (cc/gcc/g++). Such as:

> cc-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 all the run-time memory address. When you add the debug information with-G and successfully compile the target code, let's see how to debug it with GDB.

There are several ways to start gdb:

1, GDB <program>
Program is your executable file, usually in the course of the directory.

2. GDB <program> Core
Using GDB to debug both a running program and a core file, the core is the file that was generated after the program was illegally executed after the core dump.

3, GDB <program> <PID>
If your program is a service program, then you can specify the process ID of the service program at run time. GDB will automatically attach up and debug him. program should be searched for in the PATH environment variable.

When GDB starts, you can add some gdb startup switches, and the detailed switches can be viewed with gdb-help. I'll just cite some of the more commonly used parameters below:

-symbols <file>
-S <file>
Reads the symbol table from the specified file.

-se file
Reads the symbol table information from the specified file and uses it in the executable file.

-core <file>
-C <file>
Core dump core file when debugging.

-directory <directory>
-D <directory>
Add a search path to a source file. The default search path is the path defined by path in the environment variable.

Debug the program with GDB (ii)

After you start GDB, you are brought into the GDB debugging environment, you can use the GDB command to start the debugger, GDB commands can use the Help command to view, as follows:

   /home/hchen> gdb
    GNU gdb 5.1.1
    Copyright 2002 Fre E Software Foundation, Inc.
    GDB is free Software, covered by the GNU general public License, and Yo U are
    Welcome to change it and/or distribute copies of it under certain.
Conditions ;  Type ' show copying ' to the conditions.
    There is absolutely no warranty for gdb.  Type ' show warranty ' for details.
    This GDB is configured as "I386-suse-linux".
    (gdb) help
    List of classes of commands:

    Aliases--aliases of other commands
    breakpoints--making program stop at C Ertain points
    data--examining data
    files--Specifying and examining files
    Internals--Maintenance commands
    obscure--obscure features
&NBSP;&N bsp;  running--running the program
    Stack--examining the stack
    statu S--Status inquiries
    Support--support facilities
    tracepoints--Tracing O F program execution without stopping
    user-defined--user-defined commands

Type ' help ' followed by the A class name for a list of the commands in that class.
Type ' help ' followed by the command name for the full documentation.
Command name abbreviations are allowed if unambiguous.
(GDB)

GDB has a lot of commands, and gdb divides it into many categories. The help command is just an example of the GDB command type, and if you want to see the commands in the category, you can use the helps <class> command, such as the breakpoints, to see all the commands that set breakpoints. You can also help <command> directly to view the commands.

In


gdb, enter the command, you can not play the full command, only the first few characters of the command can be, of course, the first few characters of the command should mark a unique command, in Linux, you can tap two times tab to complete the full name of the command, if there is duplication, Then GDB will take it out.
&NBSP;&NBSP;&NBSP;&NBSP
    Example one: When you enter a function func, set a breakpoint. You can either typing a break func, or directly to B func
    (gdb) b func
    breakpoint 1 at 0x8048458:file Hel LO.C, line 10.
&NBSP
    example two: typing B press two times the TAB key, you will see all the B-First commands:
    (gdb) b
    backtrace  break      BT
    (GDB)

    Example Three: Only remember the prefix of the function, you can do this:
    (gdb) b make_ < Press the TAB key
    (Press the TAB key again and you will 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 examples of functions that start with make are shown to you.

Example four: When you debug a C + + program, you have the same function name. Such as:
(gdb) b ' bubble (M-?
Bubble (double,double) Bubble (int,int)
(gdb) b ' Bubble (
You can view all of the overloaded functions and parameters in C + +. (Note: M-and "Press two tab" is a meaning)

To exit GDB, just use the Quit or command abbreviation Q.

Shell program running UNIX in GDB
————————————

In the GDB environment, you can execute the UNIX shell command, using the GDB shell command to complete:

Shell <command string>
Invoke the Unix shell to execute <command string> the UNIX shell defined in the environment variable shell will be used to execute the <command string>, if the shell is not defined, Then use the UNIX standard shell:/bin/sh. (Use Command.com or cmd.exe in Windows)

Another GDB command is make:
Make <make-args>
You can perform the make command in GDB to rebuild your program. This command is equivalent to "shell make <make-args>".


Running programs in GDB
————————

When GDB is started with gdb <program>, GDB searches for the <program> source files in the path path and in the current directory. To verify that GDB is reading the source file, use the L or List command to see if GDB can list the source code.

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

1. Operating parameters of the program.
Set args can specify Run-time parameters. (such as: Set args 10 20 30 40 50)
Show args command to see the set of run parameters.

2, the operating environment.
Path <dir> can set the running paths of programs.
Show paths view the running path of the program.
Set environment VarName [=value] Sets the environment variable. such as: Set env User=hchen
Show environment [varname] View environment variables.

3, working directory.
CD <dir> equivalent to Shell's CD command.
PWD Displays the current directory.

4, the program input and output.
Info Terminal shows the mode of the terminal used by your program.
Use the redirect Control program output. such as: Run > outfile
A TTY command can refer to a terminal device that writes input and output. such as: Tty/dev/ttyb


To debug a program that is already running
————————

Two ways:
1, under the UNIX with PS view the running of the program's PID (process ID), and then use the GDB <program> PID format to hook up the running program.
2, first with GDB <program> Association on the source code, and GDB, in gdb with the attach command to hook up the process of PID. Use detach to cancel the hook process.

Suspend/Redo program run
—————————

In the debugger, pausing a program to run is necessary, and GDB can easily suspend the operation of the program. You can set the program to stop in which line, under what conditions to stop, in the receipt of what signal to stop and so on. To make it easier for you to see the run-time variables and the run-time process.

When the process is stopped by GDB, you can use the Info program to see if the application is running, the process number, and why it was paused.

In GdB, we can have several pauses: breakpoints (breakpoint), Observation points (Watchpoint), capture points (Catchpoint), signals (signals), thread stops (threads Stops). If you want to restore the program to run, you can use the C or Continue command.


One, set breakpoints (breakpoint)

We use the break command to set the breakpoint. There are several ways to set breakpoints on the front:

Break <function>
Stop when you enter the specified function. In C + +, you can use the class::function or function (type,type) format to specify the functions name.

Break <linenum>
Stop at the specified line number.

Break +offset
Break-offset
Stop at the offset line either before or after the current line number. Offiset is the natural number.

Break Filename:linenum
Stop at the LineNum line at the source file filename.

Break Filename:function
Stop at the entrance of the function function of filename file.

Break *address
Stop at the memory address where the program is running.

Break
When the break command has no parameters, it means to stop at the next command.

Break ... if <condition>
... Can be the above parameters, condition to express conditions, when the condition is established to stop. For example, in an ambient body, you can set the break if i=100, which means stopping the program when I is 100.

When viewing breakpoints, you can use the info command as follows: (Note: n indicates a breakpoint number)
info breakpoints [n]
Info break [n]

Ii. Setting up observation points (Watchpoint)

Observation points are generally observed to see whether the value of an expression (a variable is also an expression) has changed, and if there is a change, stop the program immediately. We have the following methods to set the observation point:

Watch <expr>
Sets an observation point for expression (variable) expr. Stop the program as soon as the value of the expression changes.

Rwatch <expr>
Stops the program when the expression (variable) expr is read.

Awatch <expr>
Stops a program when the value of an expression (variable) is read or written.

Info watchpoints
Lists all the observed points that are currently set.


third, set the capture Point (Catchpoint)

    You can set up capture points to catch some events while the program is running. such as: Load a shared library (dynamic link library) or C + + exception. Set the capture point in the format:
    
    catch <event>
         Stop the program when event occurs. The event can be the following:
        1, throw an exception thrown by a C + +. (throw keyword)
        2, catch an exception caught by a C + +. (catch is the keyword)
        3, exec calls the system call exec. (exec is the keyword, this feature is only useful under HP-UX)
        4, fork calls the system call fork. (Fork is the keyword, this feature is currently only useful under HP-UX)
        5, Vfork calls the system call Vfork. (Vfork is the keyword, this feature is only useful at HP-UX)
        6, load or load <libname> When you load a shared library (a dynamic-link library). (load is the keyword, this feature is currently only

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.