command-line debugging tools in a UNIX environment: GDB

Source: Internet
Author: User
Tags gdb debugger

command-line debugging tools in a UNIX environment: gdb

If you need to use the GDB debugger, add the-G option to GCC.

The following command section is a simplified version, such as using L instead of list and so on.

1. Basic Commands

1) Enter GDB #gdb test

Test is the program to debug, generated by GCC test.c-g-o test. Enter the post prompt into (GDB).

2) View Source (GDB) L

Source code will be a line number hint.

If you need to see the functions defined in other files, add the function name to the definition of the functions and view the other sources nearby. Or: Use a breakpoint or a single-step operation to enter this function by using s at a function.

3) Set Breakpoint (GDB) b 6

This will stop running to the 6th line of the source code, you can see the value of the variable, stack conditions, etc., this line number is GDB's row number.

4) View breakpoint information (GDB) Info b

You can type "info B" to see the situation at the breakpoint, you can set multiple breakpoints;

5) Run code (GDB) r

6) Display variable value (GDB) p n

When the program pauses, type "p variable name" (print);

GDB displays the value of the variable with the "$N" tag before the corresponding value, which is the reference mark of the current variable value, and if you want to refer to the variable again, you can write "$N" without having to write a lengthy variable name;

7) Watch variable (GDB) watch n

In a loop, often want to be able to observe the change of a variable, then you can type the command "watch" to observe the change of variables, GDB set the Observer point "n";

8) Single Step operation (GDB) n

9) program continues to run (GDB) c

Keep the program running down until the breakpoint is encountered again or the program ends;

10) Exit GDB (GDB) Q

2. Breakpoint Debugging

Command Format example function

Break + Sets the line number of a breakpoint break n sets a breakpoint at n rows

Tbreak + line number or function name Tbreak N/func set a temporary breakpoint that is automatically deleted when it arrives

Break + filename + line number breaks Main.c:10 used to set breakpoints on the specified file corresponding line

Break + <0x...> Break 0x3400a used to pause at a certain location in memory

Break + line number + if + condition breaks if i==3 is used to set conditional breakpoints and is very convenient to use in loops

Info breakpoints/watchpoints [n] info break n denotes breakpoint number, view breakpoint/Observer point condition

Clear + Breakpoint line number to be cleared clear 10 is used to clear the breakpoint of the corresponding line, to give the line number of the breakpoint, when cleared, GDB gives a hint

Delete + breakpoint number to clear delete 3 The command to clear the breakpoint and automatically display the expression, to give the breakpoint number, when cleared, GDB will not give any hint

Disable/enable + Breakpoint Number Disable 3 Let the breakpoint temporarily fail/enable, if you want to disable/enable multiple numbers at the breakpoint, you can separate the numbers with a space

Awatch/watch + variable Awatch/watch I sets an observer, and the program is paused when the variable is read out or written.

Rwatch + variable Rwatch I sets an observer, and when the variable is read out, the program is paused

Catch sets the snap point to catch some events while the program is running. such as: Loading shared libraries (dynamic link libraries) or C + + exceptions

Tcatch only once the snap point is set, when the program stops, it should be deleted automatically.

3. Data Commands

Display + expression Displays the value of the expression, which displays the value of the expression whenever the program runs to a breakpoint

Info display is used to show all current expressions to display values

Delete + Display number Delete 3 is used to delete an expression to display the value, the deleted expression will not be displayed

Disable/enable + display number disable/enable 3 temporarily invalidate/enable an expression to display a value

Undisplay + Display number Undisplay 3 is used to finish displaying the value of an expression

Whatis + variable Whatis I shows the data type of an expression

Print (p) + variable/expression p n is used for printing the value of a variable or an expression

Set + variable = variable value set i = 3 change the value of a variable in the program

When you use the Print command, you can output the variable in the specified format, with a command format of print/variable name + format

The commonly used variable format: x: hexadecimal, D: decimal, U: unsigned number, O: octal, C: Character format, F: floating-point.

4. Debug run environment-related commands

Set args set args arg1 arg2 setting run parameters

Show args show args see Run parameters

Set width + number set width 70 set GdB's line width

CD + working directory CD: /Switch Working directory

Run R/run program starts execution

Step (s) s enter (will go into the called sub-function) Step into the function, the premise is that this function is compiled with debug information

Next (n) n non-entry (does not go into the called child function) stepping

Finish finish runs until the function returns and prints information such as the stack address and return value and parameter values when the function returns

Until + rows U 3 run to a line of functions

Continue (c) C executes to the next breakpoint or program end

Return < return value > return 5 changes the program flow, ends the current function directly, and returns the specified value

Call + Function-the function to run at the current location

5. Stack-related commands

BACKTRACE/BT BT is used to print the stack frame pointer, you can also add the number of stack frame pointers to be printed, to see what functions call the program at this point, the program "Call stack" is the list of all called functions before the current function (including the current function). Each function and its variables are assigned a "frame", the most recently called function in frame No. 0 ("bottom" frame)

Frame frame 1 is used to print the specified stack frame

Info reg info reg Check Register usage

Info stack info Stack view stack usage

Up/down Up/down jumps to the previous layer/next layer function

6. Jump Execution

Jump specifies the run point of the next statement. This can be the line number of the file, which can be the File:line format, which can be the +num offset format. The table is where the next run statement starts. Equivalent to changing the contents of the PC register, the stack content has not changed, cross function jumps prone to errors.

7. Signal Command

Signal signal sigxxx produces XXX signals, such as SIGINT. A method for fast searching Linux query signals: # KILL-L

Handle defines a signal processing in GDB. The signal can start with the sig or not start with the sig, you can define a range to process the signal (such as: Sigio-sigkill, which represents the processing of signals from the SIGIO signal to SIGKILL, including Sigio,sigiot,sigkill three signals), You can also use the keyword all to indicate that you want to process all the signals. Once the program being debugged receives the signal, the running program is immediately stopped by GDB for debugging. It can be one or more of the following keywords:
When the program being debugged receives a signal, GDB does not stop the program from running, but will print a message telling you that you received the signal/GDB will stop your program.
When the program being debugged receives a signal, GDB displays a message that/GDB will not tell you about the signal received.
When the program being debugged receives a signal, GDB does not process the signal. This means that GDB will give this signal to the debug program to handle.
When the program being debugged receives a signal, GDB does not let the debugger process the signal.
Info signals
Info handle
You can see which signals are processed by GDB, and you can see the default processing methods

Unlike the kill command of the shell, the kill command of the system is intercepted by GDB when signaled to the debug program, and a signal issued by the single command is sent directly to the debugged program.

8. Run the shell command

Like (gdb) shell ls to run LS.

9. More program run options and commissioning

1, program operation parameters.
Set args can specify runtime parameters. (Example: Set args 10 20 30 40 50)
The show args command can view the set run parameters.
2, the operating environment.
Path sets the path of the program to run.
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 is equivalent to the Shell's CD command.

The PWD displays the current directory.
4, the input and output of the program.
Info terminal shows you the terminal mode used by your program.
Use redirection control program output. such as: Run > outfile
A TTY command can refer to an end device that writes input and output. such as: Tty/dev/ttyb

5. Debugging a Running Program

Two methods:
(1) Under UNIX, use PS to view the running program's PID (process ID), and then use the GDB PID format to hook up the running program.
(2) using GDB to associate the source code, and GDB, in gdb with the attach command to hook up the process PID. Use the detach to cancel the hook process.

6. Pause/Resume program run when the process is stopped by GDB, you can use info program to see if it is running, the process number, and why it was paused. In gdb, we can pause in the following ways: Breakpoints (breakpoint), Observation points (watchpoint), Snap points (catchpoint), signal (signals), Thread stops (thread Stops), if you want to restore the program to run, You can use the C or Continue command.

7. Threads (thread Stops)

If the program is multi-threaded, you can define whether the breakpoint is on all threads, or on a particular thread.
Break thread
Break Thread If ...
LINESPEC Specifies the line number of the source program to which the breakpoint is set. THREADNO Specifies the ID of the thread, note that this ID is assigned by GDB and can be viewed through the "Info Threads" command to view the thread information in the running program. If you do not specify thread, the breakpoint is set above all threads. You can also specify a breakpoint condition for a thread. Such as:
(gdb) Break frik.c:13 thread Bartab > Lim
When your program is stopped by GDB, all running threads will be stopped. This makes it easy to see the overall situation of the running program. And when you resume the program, all the threads will be restored to run.

10. Debug the Core file

Core Dump:core means memory, and dump means to throw it out and heap it out. When developing and using UNIX programs, sometimes the program is inexplicably down, without any hint (sometimes prompting core dumped), At this time, you can look at the shape of the core. Process number of the file generation, this file is the operating system to drop the memory content of the program is generated, it can be used as a reference for debugging programs

(1) Creating a core file

By default, the size of the core file is set to 0 so that the system does not dump the core file. Modified before the core file can be generated.

Ulimit-c Unlimited
Ulimit Unlimited

These need to have root permission, each time you reopen interrupts under Ubuntu, you need to re-enter the first command above to set the core size to infinity

Core file Generation Path: Enter the executable file under the same path where the command is run. If the system-generated core file does not have any other extension names, it is all named Core. The new core file generation will overwrite the original core file.

1)/proc/sys/kernel/core_uses_pid can control whether a PID is added as an extension in the file name of the core file. The file content is 1, which means adding a PID as the extension, the resulting core file format is core.xxxx, and 0 means that the resulting core file is named Core.
You can modify this file by using the following command:
echo "1" >/proc/sys/kernel/core_uses_pid

2) Proc/sys/kernel/core_pattern can control the core file save location and file name format.
You can modify this file by using the following command:
echo "/corefile/core-%e-%p-%t" > Core_pattern, the core file can be generated uniformly into the/corefile directory, resulting in a file named core-command name-pid-timestamp
The following is a list of parameters:
%p-insert pid into filename add PID
%u-insert current UID to filename to add the present UID
%g-insert current GID into filename to add an existing GID
%s-insert signal that caused the coredump into the filename adds a signal that causes the core to be generated
%t-insert Unix time, the coredump occurred into filename when you add a core file when you build Unix
%h-insert hostname where the coredump happened into filename adds host name
%e-insert coredumping executable name into filename add command name

(2) View core files with GDB

After core dump occurs, use GDB to view the contents of the core file to locate the row in the file that raised the core dump.
GDB [exec file] [core file]
Such as:
GdB./test Core

or GDB./a.out
Core-file core.xxxx
After GDB, use the BT command backtrace or where to see where the program is running to locate the file-and-line of core dump.

Executable file to be debugged, need to add-g,core file at compile time to display error message correctly

1) gdb-core=core.xxxx
2) Gdb-c core.xxxx

(3) Observing a process crash information in real time with GDB

Start process
Gdb-p PID
Run the process to crash
GDB will display crash information

(Transferred from:

command-line debugging tools in a UNIX environment: GDB

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