Common debugging methods (GDB) for C/C + + programs under Linux

Source: Internet
Author: User


 whether in the process of development or operation, debugging to ensure the normal operation of the most basic means, familiar with these debugging methods, so that we quickly locate the problem of the program, improve development efficiency. a program to run normal debugging(1) using GDB directlyThe most common way in the development process, we can in its process to add breakpoints, monitoring and other auxiliary means to monitor its behavior is consistent with our design, such as:          
(2) The program is already running and is attached to the process via attach          





two debugging after program interruptionlet's start with a brief introduction to the Linux signal:a soft interrupt signal (signal, also referred to as a signal) is used to notify the process that an asynchronous event has occurred. Processes can send soft interrupt signals to each other through system call kill. The kernel can also send a signal to the process because of an internal event, notifying the process that an event has occurred.     Note that the signal is only used to notify a process of what has happened and does not pass any data to the process. The process of receiving signals has different processing methods for various signals. The processing method can be divided into three categories: the first is similar to the interrupt handler, for the signal to be processed, the process can specify a handler function, which is handled by the function. The second method is to ignore a signal and do nothing about it, as if it had not happened. The third method is that the processing of the signal retains the default value of the system, and the default operation for most signals is to cause the process to terminate. The process calls signal through the system to specify the processing behavior of a process for a signal. we are using the signal mechanism of Linux as the first method to deal with it. take SIGSEGV For example, other similar. The most fundamental reason for triggering this signal is to attempt to access unallocated memory, or to attempt to write data to an address that does not have write permission. (1) Call stack via backtrace,backtrace_symbols output function;
void dump (int __signal) {const int __max_stack_flow = 20;void* __array[__max_stack_flow];char** __strings;size_t __size = BackTrace (__array,__max_stack_flow);p rintf ("BackTrace () returned%d addresses\n", (int) __size); __strings = BackTrace _symbols (__array,__size); if (NULL = = __strings) {perror ("Backtrace_symbols"); exit (exit_failure);} fprintf (stderr, "obtained%ZD stack frames.nm", __size); for (size_t __i = 0; __i < __size; ++__i) {printf ("%s\n", __stri Ngs[__i]);} This __strings was malloc (3) Ed by Backtrace_symbols (), and must be freed Herefree (__strings);    Exit (0);}

    · For example, we need to deal with SIGSEGV, then only need to call signal (SIGSEGV, dump), then when the SIGSEGV interrupt is generated, the dump call is triggered, the stack is printed, the default setting maximum number of stacks is 20, if the actual stack is greater than 20, Show only the last 20 layers. Test Code:
void Segv_fun () {unsigned char* __ptr = 0x00; *__ptr = 0x00;} void register_signal (int __signal) {signal (__signal, dump);} void Testdump::test_signal_segv () {printf ("testdump::test_signal sigsegv\n"); register_signal (SIGSEGV); Segv_fun ();}
Run Output:

from the running results can be seen, the program SIGSEGV interrupt triggered the dump function, dump print 6 frames, First frame:/easy_main (_z4dumpi+0x26) [0x402896] is executing dump; Second frame:/lib64/libc.so.6 () [0x332ae329a0] is a library function that calls libc; frame three:./easy_main (_zn8testdump5myrunepkcb+0x5f) [0x402d2f], this looks a bit strange, this string seems to be able to see some information, testdump? cannot be positioned quickly. Don't worry, if this appears, let's see, we can use Addr2line to convert the address to the number of lines that correspond to the file.
then look at the source code file,
void Segv_fun () {unsigned char* __ptr = 0x00;*__ptr = 0x00;}

Now you know where the problem lies! Nth Frame ......
(2) Analyzing core filesIf there is no takeover of the information, then a core file is generated after the program is interrupted, and the core file is a mirror image of the memory at the time of the program interruption, which can be used to restore the scene. If you do not produce a core file, check the ulimit parameters, such as my settings,        
then you need to set it too small, in blocks, generally 1 blocks = 1k, which is 1024bytes.        
now that I have set it to 1M, if the program takes up less than 1M of memory, the core file is a full memory image, and more than 1M will retain the closest 1M memory information.         
It is shown from the output that the core dump (segmentation fault core dumped) was generated when the first execution did not generate the core and set the Ulimit value.Next we use the core file to locate the error message.     Obviously, the result shows the detailed code that generated the interrupt and the number of rows in the file, which is more convenient!
(3) combine (1), start gdb Debug when interrupted,change the code slightly, capture the signal, get the parameters of the current process, and execute the command line.         
void dump_for_gdb (int __signal) {const int __max_buf_size = 512;char __buf[__max_buf_size] = {};char __cmd[__max_buf_size ] = {}; file* __file;snprintf (__buf, sizeof (__BUF), "/proc/%d/cmdline", Getpid ()); __file = fopen (__buf, "R")) {exit (0);} Fclose (__file); if (__buf[strlen (__BUF)-1] = = ' \ n ')//warning:multi-character character constant [-wmultichar]{__buf[ Strlen (__BUF)-1] = ' + ';//warning:multi-character character constant [-wmultichar]}snprintf (__cmd, sizeof (__cmd), " GdB%s%d ", __buf, Getpid ()); system (__cmd); exit (0);}
void register_signal_for_gdb (int __signal) {signal (__signal, dump_for_gdb);}
void Testdump::test_dump_for_gdb () {printf ("testdump::test_dump_for_gdb sigsegv\n"); Register_signal_for_gdb ( SIGSEGV); segv_fun2 ();}
Output Results

of course, we can integrate these things, for example, after the project is finally online, we hope this operation is more simple, because in the operational phase, the operator may not be a developer, but the OPS, we want to use a simpler, direct way to extract this information, it will need to further work. Our previous approach was to write the dump stack information in a file and then use the shell to read the stack information, using Addr2line to convert to a specific number of file rows or functions and save the final file. In this way, the OPS staff only need to give the final document to the developer, so they can analyze the positioning problem. This is what is commonly used, and if there is a better way, welcome to the supplement.
Reference Code: [email protected]: Yuyunliuhen/easy.git Https://github.com/yuyunliuhen/easy/blob/master/src/base/easy_dump.h https://github.com/yuyunliuhen/easy/blob/master/src/test/easy_test_dump.cc

Reference:
Linux signal Signal processing mechanism The reason and debugging method of segment error under Linux get process-related information, such as CmdLine



Common debugging methods (GDB) for C/C + + programs under Linux

Related Article

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.