Linux GDB and Unix DBX debugging tools

Source: Internet
Author: User
Tags dbx valgrind

 

C/C ++ development in Unix-like environments,CodeDebugging is troublesome. the most primitive addition, tracking, and debugging are very time-consuming. Especially for a large project, debugging is very difficult when the number of lines of code is very large, it is not easy to locate core dump. Here we will introduce several common tools: GDB, DBX debugging tool, and valgrind memory check tool (Linux ).

GDB (GNU Debugger) is the GNU Debugger, which is usually used with GCC. Use GDB for debugging and compilationProgram-G or-ggdb compilation options must be specified. For example, GCC-G main. c

GDB command: F (File): Specifies the executable file, L (list) lists the source files, R (run) runs the executable file, can contain the executable parameter, B (break) sets the breakpoint, C (CONTINUE) continues to be interrupted until the next breakpoint or program ends. P (print) outputs the value of the variable, such as p aa; n (next, when the S (STEP) program is executed to a breakpoint, the execution is interrupted. You can use the S command to perform one-step execution to enter a function. Q (quit) exits.

If you want to run shell commands during GDB, you do not have to exit. Run shell to switch to shell mode and run shell commands.

GDB can process any signal when you debug the program. You can tell GDB which signal to process. You can ask GDB to immediately stop the running program when receiving the signal you specified for debugging. You can use the gdb handle command to complete this function. Handle <signal> <keywords...>

Define a signal processing in GDB. Signal <signal> can start with or not with sig, you can define a range of signals to be processed (such as: SIGIO-SIGKILL, signal processing from sigio signal to sigkill, it includes sigio, sigiot, and sigkill signals. You can also use the keyword "all" to indicate all signals to be processed. Once the debugged program receives a signal, the running program will be immediately stopped by GDB for debugging. Its <keywords> can be one or more of the following keywords. Nostop does not stop running, only the display signal is output, stop: stop the program, print displays a message, noprint when the program to be debugged receives the signal, GDB will not tell you to receive the signal information, noignore when the program to be debugged receives a signal, GDB does not process the signal. This indicates that GDB will hand over the signal to the debugged program for processing. Nopass, ignore when the program to be debugged receives a signal, GDB will not let the program to be debugged to process this signal.

View the core file: run the gdb execution file core file to load the core file, and use where to view the coredump location. If the system does not generate a core file, you can run the ulimit-C 2048 command to generate the file.

Multi-process debugging: after our test program fork the parent process, the sub-process calls sleep for 60 seconds. This is the key. This sleep should not have existed in the sub-process code. Instead, it was added to use GDB for debugging. Why should we let the sub-process start sleep as soon as it was just running? Because we need to get the process ID of a sub-process by using shell commands during sleep, and then attach the external process to the process ID by using GDB to debug the process.

Debug the dynamic library and run the execution program to load the dynamic library for debugging.

/*************************************** ********************************/

Dbx (Sun Studio) debugging tool: In the use of DBX to programSource code-G option must be used before debugging.

Start: DBX program_name load the program to be debugged, debug the Java program DBX program_name.class |. jar, you can specify the process ID to connect to the running process for debugging.

You can also load the debugging program when DBX is running: (DBX) debug program_name

Run the debugging program: Run [running parameters]

View the core file: You can use DBX program_name core or DBX-core to display stack traces and locate the crash location.

Set the breakpoint: Stop in function; stop at file: line; you can also set the current file through file-name, list function to view the source file, and determine the number of lines to set the breakpoint. In C ++, you can set breakpoints for keywords (inmember, inclass, infunction, or inobject) in classes, member functions, and objects. Stop change variable can be set to stop when the variable changes. Conditional stop breakpoint: Stop cond condition. In addition, in the dynamic library, you can set breakpoints in the Linked Library when the program starts.

List all breakpoints: Status

Delete breakpoint: delete breakpoint number

One-step execution: Step, next, step command step into the function, and next command step through the function. Step up will be executed until the current function controls the function that is returned to call it.

Continue execution: cont

View the call Stack: The where call stack represents all the active routines that have been called but have not yet returned their respective calls. In the stack, functions and their parameters are stored in the calling order. Stack tracing displays the stop position of the Program Stream execution and how the execution reaches this point. It provides a brief description of the program status.

Check variable: Print variable name

Exit: Quit

Connect a running process: attach PID

Detach a connected process: Detach PID

Search Symbol: whereis symbol prints a list of all the specific values of the specified symbol

Declaration of the output identifier whatis to be printed

You can use the attach sub-process ID to connect to the sub-process for debugging.

To display information about all threads of the current process: Execute thread, switch to the specified Thread: thread thr_id

Signal Processing:

Cont-Sig signal forwards signals to processes; catch displays the list of currently captured signals; ignore displays the list of signals ignored by programs

Shell mode switch: Sh

---------------------------- Common sub-commands for DBX debugging Tracing

Dbx is a program debugger Based on the command line interface in UNIX. Dbx performs debugging through interactive execution of DBX sub-commands. Before debugging a program, you must include the-G option in the compilation information to compile and generate a file with debugging information, that is, CC-O filename-G file. C. To access DBX, you only need to enter "dbx filename". filename is the name of the executable program to be debugged. After DBX is loaded, a prompt is displayed: (DBX). You can enter the DBX sub-command for debugging.

Syntax:
Dbx [-A processid] [-C commandfile] [-D nestingdepth] [-I Directory] [-e debugenvironment] [-P oldpath = newpath :... | pathfile] [-K] [-u] [-F] [-R] [-x] [objectfile [corefile]

-A processid
Connect the debugging program to a running process. To connect to the debugging program, you must have the permission to use the kill command for the process. Use the ps command to determine the process ID. If you are licensed, the DBX program interrupts the process, determines the full name of the object file, reads the symbol information, and prompts you to enter the command.

-C commandfile
Run the DBX sub-command in the file before reading standard input. The specified file in the $ home directory will be processed first, and then the file in the current directory will be processed. The command file in the current directory overwrites the command file in the $ home directory. If the specified file does not exist in the $ home directory or the current directory, a warning message is displayed.SourceSub-commands can be used after the DBX program runs.

-D nestingdepth
Set the nesting limit of the program block. The default nested depth limit is 25.

-E debugenvironment
Specifies the environment variables of the debugging program.

-P oldpath = newpath:... | pathfile
Specify the path of the replaced library when checking the core file in the format of oldpath = newpath. Oldpath specifies the value to be replaced (stored in the core file), while newpath specifies the new value to be replaced. These may be full or partial, absolute or relative paths. You can specify several replicas, which are separated by colons. On the contrary, the-P Flag can specify the file name and map the format of the previously read description. Only one ing can be read from the file in each row.

-F can be used to disable the slow reading mode and enable the DBX command to read all symbols at startup. By default, the slow reading mode is Enabled: It reads the expected symbol table information during DBX Session Initialization .. In this mode, DBX does not read the variables and types whose symbolic information has not been read. Therefore, commands such as whereis I do not list all instances of variable I in all functions.

-I directory
(Uppercase I) include the directory specified by the Directory variable in the list of directories in the source file. The default directory for searching source files is:

    • The directory where the source file is located during file compilation. The directory can be searched only when the compiler sets the Source Path of the object.
    • Current directory.
    • The directory where the current program is located.

-K ing the memory address, which is very useful for kernel debugging.

-R: run the object file immediately. If it ends successfully, the DBX debugging program will exit. Otherwise, the program will be debugged and the cause of the interruption will be reported.

Note: Unless-R is specified, the DBX command will prompt the user and wait for the command to be entered.

-U prefix the DBX command with @ (AT) for the file name. This flag reduces the possibility of mixed Symbol names.

-X prevents DBX commands from skipping the _ (underline) characters from the Fortran source code. This symbol allows DBX to distinguish between symbols which are the same except for the underline, for exampleXxxAndXxx _.

Below are some common sub-commands for DBX:

1. Basic operation commands
Run arg1 arg2...: run the existing process with the parameters of arg1, arg2.
R: run the existing process again with the parameters used last time.
Source filename: Read the DBX sub-command from the file named filename and execute it.
Return: returns the result after the current process is executed.
Sh command: run an operating system shell command without exiting DBX.
SH: Enter the shell status temporarily.
Quit: Exit DBX. If the program is not completed, it is terminated.

2. breakpoint and tracking command
stop VaR at N: breakpoint command. When the variable VAR in the nth line changes, the program is suspended.
stop var In Proc: sets the breakpoint command. When the VaR variable of Proc changes, the program is suspended.
stop at N: indicates the breakpoint command. The program is suspended when the nth line is executed.
stop In Proc: the breakpoint command. When the proc process is executed, the program is suspended.
trace VaR at N: Specifies the trace point command. When the variable VAR in the nth line changes, the trace information is displayed.
trace var In Proc: Set the trace point command. When the VaR variable of Proc changes, the trace information is displayed.
trace N: trace point command. The trace information is displayed when the nth row is executed.
trace proc: The trace point command. The trace information is displayed when the proc process is executed.
trace expr at N: Specifies the trace point command. The value of VaR is displayed when the nth row is executed.
Delete n | all: delete all breakpoints and tracking points in the nth row.

3. debug commands
Cont at N: run until row n.
Print var: print the value of the variable VAR.
Printf "string", expr,...: printed in C format.
Where: prints the current debugging status, including information about the current process.
FUNC: view the name of the currently running process.
Func proc: Move to the parent process that calls the proc process.
Whatis name: Type of the variable or process name.
Step [N]: One or n lines are executed in one step. When a thread is called, the thread is called.
Next [N]: One or n lines are executed in a single step. In case of a thread call, the thread is denied to be called.
Skip [N]: skip one or N breakpoints and continue to execute
Dump [proc] [>; file]: displays the names and values of all variables in the current or proc process.
Assign Var = expr: Assign the value of the expression expr to the variable VAR

4. Read the commands of the program to be debugged
List: lists source programs of several lines starting from the current row.
List n, m: list the source code from row n to Row M.
/String: Search for the string at the end of the file
? String: search for a string in the header.
File filename: Switch the file to the file filename.

(DBX) run -- run executable binary files
(DBX) list -- list Code
(DBX) next -- jump to the next step
(DBX) print <variable name> -- print the output value
(DBX) Stop at <FILENAME: line N> -- set a breakpoint
(DBX) Stop at <funcname: line N>
(DBX) cont -- continue execution
(DBX) cont at <line N> -- continue to execute the specified row
(DBX) Call -- call func ()
(DBX) delete <breakpoint number> -- delete a breakpoint
(DBX) Quit -- exit execution

Example1:

$ CC-g-o Test test. c
$ DBX Test
(DBX) Stop at main

Example2:

$ CC-G logoff. C-o Logoff

 
$ PS-u userid
 
PID tty Time Command
68 console 0: 04 sh
467 lft3 Logoff
 
$ DBX-A 467
 
Attached in main at line 5
5 For (I = 0; I <10 ;);
(DBX)

For more commands, refer:Http://publib16.boulder.ibm.com/doc_link/zh_CN/a_doc_lib/cmds/aixcmds2/dbx.htm

Linux GDB debugging

GDB is one of the most widely known free and open source software. It is used by a large number of GNU software projects and a number of third-party software that are not associated with GNU but want to have a high-quality debugger. In fact, many third-party tools merge GDB and use it as the basis for their debugging functions, even if they build graphical abstraction at all levels on top of GDB. You may have encountered GDB-but you may not be aware of it.

GDB is built on the basic concept that any debugger has two components. First, the underlying processing of GDB starts and closes individual processes or threads, tracks code execution, and inserts and deletes breakpoints in the running code. GDB supports a large number of different platforms and mechanisms to implement these (seemingly simple) operations in various architectures. Its specific functions may be affected by the underlying hardware functions and occasionally changed.

$ Gcc-O hello-G hello. c

$ GDB./Hello

(GDB) Help

(GDB) Break main (or B Main)

(GDB) Run

(GDB) Next (or next I, not in the function)

(GDB) Step (or step I, inside the function)

(GDB) print argv [1]

(GDB) BT (or backtrace, view all the stack frames before the program runs to the current position)

/*************************************** **************************************** */

Valgrind is a memory debugging tool in Linux (x86) environment. It runs programs to check memory usage and automatically detects memory leaks and memory management bugs, make your program more robust.

1. Valgrind installation ::Www.Valgrind. OrgThe installation is very simple. Execute configure, make, make install

2. Valgrind tool set:

Memcheck: detects memory management bugs in programs. All write/read operations and malloc/free operations are intercepted.

Cachegrind: cache analyzer, which simulates the level-1 cache I1, D1, and L2 level-2 cache in the CPU, and can accurately point out the cache loss and hit in the program.

Callgrind: Same as cachegrind, but it can trace the call and return relationships of functions and select a simulated cache.

Massif: Stack analyzer that can detect programs in the stackUseMemory size, heap block, heap management block, and stack size. This helps reduce the memory usage of programs.

Helgrind: detects the problem of multi-threaded synchronization using POSIX pthread.

3. Valgrind command format:

Valgrind [valgrind-options] Your-Prog [Your-prog-options]

Valgrind-options:

-- Tool = <Name> [default = memcheck] Select a tool

-H -- Help help

-- Display version

-Q -- quiet only displays errors

-V -- verbose more display

-D: displays debugging information of valgrind.

-- Trace-Children = <Yes | NO> [Default: No] traces sub-processes that are called through the exec system. The default value is no.

-- Child-silent-after-fork = <Yes | NO> [Default: No]?

-- Track-FDS = <Yes | NO> [Default: No] the list of all open file descriptors is displayed when you exit.

-- Time-stamp = <Yes | NO> [Default: No] running Timestamp

-- Log-FD = <number> [Default: 2, stderr] Output log to descriptor File

-- Log-file = <FILENAME> specify the log file

-- Log-socket = <IP-Address: Port-number> logs are output to the specified IP port through socket

Error-related options:

-- Xml = <Yes | NO> [Default: No] outputs Information in XML format. Only memcheck is available.

-- Num-callers = <number> [Default: 12] The default valgrind displays 12-level function calls to help identify program Positioning

-- Error-Limit = <Yes | NO> [Default: Yes] if the total number of errors exceeds 1000, or different errors exceed, stop displaying new errors.

-- Error-exitcode = <number> [Default: 0] indicates the error code returned when an error is detected during runtime.

-- Show-below-Main = <Yes | NO> [Default: No] by default, the stack trace reports function errors at the lower level of main.

-- DB-Attach = <Yes | NO> [Default: No] when it is set to yes, valgrind will suspend prompting whether to transfer to the debugging tool

-- DB-command = <command> [Default: GDB-NW % F % P] specifies that the default debugging tool is GDB.

-- Leak-check = <no | summary | Yes | full> [Default: Summary] detailed memory leakage information is provided during memory detection.

-- Show-reachable = <Yes | NO> [Default: No] display of reachable pointers during memory Detection

Other options are not frequently used. Some of them are not very understandable. This is omitted here.

Before detection, make sure to use the-G option to compile your program so that you can report the number of wrong lines.

4. Example of valgrind Error Report:

Memcheck

Illegal read/write access, array out of bounds

Invalid read of size 4 at 0x40f6bbcc:

(Within/usr/lib/LibPNG. so.2.1.0.9) by 0x40f6b804:

(Within/usr/lib/LibPNG. so.2.1.0.9) by 0x40b07ff4: read_png_image (qimageio *)

(Kernel/qpngio. By 0x40ac751b: qimageio: Read ()

(Kernel/qimage. cpp: 3621) Address 0xbffff0e0 is not stack 'd, malloc 'd or free 'd

Use uninitialized pointer

Conditional jump or move depends on uninitialised value (s) at 0x402dfa94:

_ Io_vfprintf (_ ITOA. h: 49) by 0x402e8476:

_ Io_printf (printf. C: 36) by 0x8048472: Main (tests/manuel1.c: 8)

Illegal release

Invalid Free () at 0x4004ffdf: Free (vg_clientmalloc.c: 577) by 0x80484c7:

Main (tests/doublefree. C: 10) Address 0x00007f7b4 is 0 bytes

Inside a block of size 177 free 'd at 0x4004ffdf: Free (vg_clientmalloc.c: 577) by 0x80484c7:

Main (tests/doublefree. C: 10)

Inappropriate release

Mismatched free ()/delete/Delete [] at 0x40043249: Free (vg_clientfuncs.c: 171) by 0x00002bb4e:

Qgarray ::~ Qgarray (void) (tools/qgarray. cpp: 149) by 0x4c261c41:

Pptdoc ::~ Pptdoc (void) (include/qmemarray. h: 60) by 0x4c261f0e:

Pptxml ::~ Pptxml (void) (pptxml. CC: 44) Address 0x4bb292a8 is 0 bytes

Inside a block of size 64 alloc 'd at 0x4004318c:

Operator new [] (unsigned INT) (vg_clientfuncs.c: 152) by 0x4c21bc15: klaola ::

Readsbstream (INT) const (klaola. CC: 314) by 0x4c21c155: klaola ::

Stream (klaola: olenode const *) (klaola. CC: 416) by 0x4c21788f:

Olefilter: Convert (qcstring const &) (olefilter. CC: 272)

Overlapping source and target Blocks

= 27492 = source and destination overlap in memcpy (0xbffff294, 0xbffff280, 21)

= 27492 = at 0x40026cdc: memcpy (mc_replace_strmem.c: 71)

= 27492 = by 0x804865a: Main (overlap. C: 40)

Default output report file name: Tool Name. Out. PID

Helgrind thread bug detection tool: It can report some common problems of thread usage. For example:

Release an invalid mutex, release unlocked mutex, release a mutex held by other threads, destroy an invalid or locked mutex, recursively lock a non-recursive lock, and release the memory containing the lock must handle the error code returned when the pthread function fails to be used, and the lock is still held when the thread exits, when pthread_cond_wait is called, the unapplied mutex or a mutex locked by other threads is used.

The error report is as follows:

Thread #1 unlocked a not-locked lock at 0x7fefffa90 at 0x4c2408d: Random (hg_intercepts.c: 492) by 0x40073a: nearly_main (Bytes: 27) by 0x40079b: Main (Bytes: 50) lock at 0x7fefffa90 was first observed at 0x4c25d01: pthread_mutex_init (hg_intercepts.c: 326) by 0x40071f: nearly_main (cost: 23) by 0x40079b: Main (cost: 50)

Memcheck and helgrind tools are commonly used. Valgrind is often used to make your program more perfect.

 

Reprinted statement:This article from http://blog.csdn.net/cation/archive/2009/08/10/4431143.aspx

========================================================== ======================================

Reference recommendations:

Dbx debugging method

GDB debugging essence and Examples

 

 

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.