Master Linux debugging technology (1)

Source: Internet
Author: User

You can monitor the running user space program in various ways: You can run the debugger for it, debug the program in one step, add print statements, or add tools to analyze the program. This article describes several methods that can be used to debug programs running on Linux. We will review the four debugging problems, including segment errors, memory overflow and leakage, and suspension.
This article discusses four types of Linux program debugging. In the 1st cases, we used two sample programs with memory allocation problems, and used MEMWATCH and Yet Another Malloc DebuggerYAMD) tools to debug them. In the 2nd cases, we used the strace utility in Linux, which can track system calls and signals to find out where the program is wrong. In 3rd cases, we use the Oops function of the Linux kernel to solve program segment errors, and show you how to set the kernel source code-level debugger kernel source level debugger, kgdb ), use the GNU debugger, gdb) to solve the same problem. The kgdb program is a Linux kernel that uses a serial connection. In 4th cases, we use the magic key sequence provided on Linux to display information about components that cause suspension issues.
Common debugging methods
When your program contains errors, it is very likely that there is a condition somewhere in the code, you think it is true), but it is actually false ). The process of identifying an error is a process in which a certain condition is always believed to be true after an error is found.
The following examples are some types of conditions that you may be certain about:
Somewhere in the source code, a variable has a specific value.
A structure has been correctly set in a given place.
For the given if-then-else statement, the if part is the path to be executed.
When a subroutine is called, it receives its parameters correctly.
Identify the error, that is, determine whether all the above conditions exist. If you are sure that a variable should have a specific value when the subroutine is called, check whether this is the case. If you believe that the if structure will be executed, check whether this is the case. Generally, your assumptions are correct, but eventually you will find a situation that does not match the assumptions. Result, you will find out where an error occurs.
Debugging is a task that you cannot escape. There are many debugging methods, such as printing messages to the screen, using the debugger, or simply considering program execution and carefully figuring out the problem.
Before you fix the problem, you must find its source. For example, for a segment error, you need to know which line of the Code contains the segment error. Once you find an error line in the code, determine the value of the variable in the method, the method of calling the method, and the details about how the error occurs. Using the debugger makes it easy to find all this information. If no debugger is available, you can use other tools. Note that the debugger may not be provided in the product environment, and the Linux kernel does not have a built-in debugger .)
Practical memory and kernel tools
You can use the debugging tool on Linux to track user space and kernel problems in various ways. Use the following tools and technologies to build and debug your source code:
User space tools:
Memory tools: MEMWATCH and YAMD
Strace
GNU Debugger gdb)
Magic key sequence
Kernel tools:
Kernel source code-level debugger kgdb)
Built-in kernel debugger kdb)
Oops
This article will discuss a type of problem that is hard to find by manually checking the code, and this type of problem only exists in rare cases. Memory Errors usually occur in multiple cases at the same time, and sometimes you can only find Memory Errors After deploying the program.
1st cases: Memory debugging tools
As a standard programming language in Linux, C language gives us great control over dynamic memory allocation. However, such freedom may cause serious memory management problems that may cause program crashes or performance degradation over time.
Memory leakage means that there is a corresponding free () call in malloc () that will never be released after execution) and buffer overflow, for example, write operations on the memory previously allocated to an array) are some common problems that may be difficult to detect. This section will discuss several debugging tools that greatly simplify the process of detecting and identifying memory problems.
MEMWATCH
MEMWATCH, written by Johan Lindh, is an open-source C-language memory error detection tool. You can download it by yourself. See references later in this article ). After adding a header file in the Code and defining MEMWATCH in the gcc statement, you can track memory leaks and errors in the program. MEMWATCH supports ansi c. It provides results log records, detects double-free release), releases erroneous free by mistake, unfreed memory not released), overflows and underflow, and so on.
Listing 1. Memory sample test1.c)
# Include
# Include
# Include "memwatch. h"
Int main (void)
{
Char * ptr1;
Char * ptr2;
Ptr1. = malloc (512 );
Ptr2 = malloc (512 );
Ptr2 = ptr1;
Free (ptr2 );
Free (ptr1 );
}
The code in Listing 1 allocates two 512-byte memory blocks, and the pointer to the first memory block is set to point to the second memory block. As a result, the address of the second memory block is lost, resulting in Memory leakage.
Now let's compile memwatch. c In listing 1. The following is a makefile example:
Test1
Gcc-DMEMWATCH-DMW_STDIO test1.c memwatch
C-o test1
When you run the test1 program, it generates a report about the leaked memory. Listing 2 shows the sample memwatch. log output file.
Listing 2. test1 memwatch. log File
MEMWATCH 2.67 Copyright (C) 1992-1999 Johan Lindh
...
Double-free: <4> test1.c (15), 0x80517b4 was freed from test1.c (14)
...
Unfreed: <2> test1.c (11), 512 bytes at 0x80519e4
{FE ..............}
Memory usage statistics (global ):
N) umber of allocations made: 2
L) argest memory usage: 1024
T) otal of all alloc () cballs: 1024
U) nfreed bytes totals: 512
MEMWATCH shows you the rows that actually cause problems. If you release a released pointer, it will tell you. The same applies to memory that has not been released. The end of the log shows statistics, including the memory leaked, memory used, and total memory allocated.
YAMD
The YAMD software package is written by Nate Eldredge to find dynamic and memory-related problems in C and C ++. At the time of writing this article, YAMD's latest version is 0.32. Download the yamd-0.32.tar.gz, see references ). Run the make command to build the program. Then run the make install command to install the program and set the tool.
Once you download YAMD, use it on test1.c. Delete # include memwatch. h and make the following minor changes to makefile:
Use test1 of YAMD
Gcc-g test1.c-o test1
Listing 3 shows the output from YAMD on test1.
Listing 3. Using test1 output of YAMD
YAMD version 0.32
Executable:/usr/src/test/yamd-0.32/test1
...
INFO: Normal allocation of this block
Address 0x40025e00, size 512
...
INFO: Normal allocation of this block
Address 0x40028e00, size 512
...
INFO: Normal deallocation of this block
Address 0x40025e00, size 512
...
ERROR: Multiple freeing
Free of pointer already freed
Address 0x40025e00, size 512
...
WARNING: Memory leak
Address 0x40028e00, size 512
WARNING: Total memory leaks:
1 unfreed allocations totaling 512 bytes
* ** Finished at Tue... 10:07:15 2002
Allocated a grand total of 1024 bytes 2 allocations
Average of 512 bytes per allocation
Maxbytes allocated at one time: 1024
24 K alloced internally/12 K mapped now/8 K max
Virtual program size is 1416 K
End.
YAMD shows that we have released the memory and Memory leakage exists. Let's try YAMD on another sample program in Listing 4.
Listing 4. Memory code test2.c)
# Include
# Include
Int main (void)
{
Char * ptr1;
Char * ptr2;
Char * chptr;
Int I = 1;
Ptr1. = malloc (512 );
Ptr2 = malloc (512 );
Chptr = (char *) malloc (512 );
For (I; I <= 512; I ++ ){
Chptr ='s ';
}
Ptr2 = ptr1;
Free (ptr2 );
Free (ptr1 );
Free (chptr );
}
Run the following command to start YAMD:
./Run-yamd/usr/src/test/test2/test2
Listing 5 shows the output from the sample program test2 using YAMD. YAMD tells us that there is "out-of-bounds" in the for loop.
Listing 5. Use test2 output of YAMD
Running/usr/src/test/test2/test2
Temp output to/tmp/yamd-out.1243
*********
./Run-yamd: line 101: 1248 Segmentation fault (core dumped)
YAMD version 0.32
Starting run:/usr/src/test/test2/test2
Executable:/usr/src/test/test2/test2
Virtual program size is 1380 K
...
INFO: Normal allocation of this block
Address 0x40025e00, size 512
...
INFO: Normal allocation of this block
Address 0x40028e00, size 512
...
INFO: Normal allocation of this block
Address 0x4002be00, size 512
ERROR: Crash
...
Tried to write address 0x4002c000
Seems to be part of this block:
Address 0x4002be00, size 512
...
Address in question is at offset 512 (out of bounds)
Will dump core after checking heap.
Done.
MEMWATCH and YAMD are both very useful debugging tools, and their usage methods are different. For MEMWATCH, you need to add the file memwatch. h and enable two Compilation Time tags. For link) Statements, YAMD only needs the-g option.
Electric Fence
Most Linux distributions contain an Electric Fence package, but you can also download it. Electric Fence is a malloc () debugging library written by Bruce Perens. It allocates protected memory after you allocate the memory. If there is a fencepost error that exceeds running at the end of the array), the program will generate a protection error and end immediately. By combining Electric Fence and gdb, You can precisely track which row tries to access protected memory. Another feature of Electric Fence is its ability to detect memory leaks.
2nd cases: Use strace
The strace command is a powerful tool that displays all system calls sent by user space programs. Strace displays the parameters of these calls and Returns signed values. Strace receives information from the kernel, and does not need to build the kernel in any special way. It is useful to send tracing information to applications and kernel developers. In Listing 6, a partition format is incorrect. The List displays the starting part of strace, which is about calling and creating a file system to operate mkfs. Strace determines which call causes the problem.
Listing 6. Starting part of strace on mkfs
Execve ("/sbin/mkfs. jfs", ["mkfs. jfs", "-f", "/dev/test1"], &
...
Open ("/dev/test1", O_RDWR | O_LARGEFILE) = 4
Stat64 ("/dev/test1", {st_mode = &, st_rdev = makedev (63,255),...}) = 0
Ioctl (4, 0x40041271, 0xbfffe128) =-1 EINVAL (Invalid argument)
Write (2, "mkfs. jfs: warning-cannot setb"..., 98mkfs. jfs: warning-
Cannot set blocksize on block device/dev/test1: Invalid argument)
= 98
Stat64 ("/dev/test1", {st_mode = &, st_rdev = makedev (63,255),...}) = 0
Open ("/dev/test1", O_RDONLY | O_LARGEFILE) = 5
Ioctl (5, 0x80041272, 0xbfffe124) =-1 EINVAL (Invalid argument)
Write (2, "mkfs. jfs: can't determine device"...,... _ exit (1)
=?
Listing 6 shows that the mkfs program used to format partitions failed due to the call of ioctl. Ioctl BLKGETSIZE64 failed. The BLKGET-SIZE64 is defined in the source code that calls ioctl .) BLKGETSIZE64 ioctl will be added to all devices in Linux, which is not supported by logical volume manager. Therefore, if the BLKGETSIZE64 ioctl call fails, The mkfs code will call the earlier ioctl call, which makes mkfs suitable for the logical volume manager.


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.