Linux C program segment Error Analysis

Source: Internet
Author: User
Tags signal handler
Linux C program segment Error Analysis
(16:50:57)

Tags: it
 
Category: C/C ++

Fopen ("/var/spool/cron/tmp", "W + ");
/////////////////////////////////////////
# Include <sys/types. h>
# Include <sys/STAT. h>
# Include <fcntl. h>
# Include <unistd. h>
# Include <stdio. h>
# Include <string. h>
# Include <stdlib. h>

Int main (){
Int ret =-1;
Printf ("************************************* **
Delpolicy
**************************************** * **********/N ");
File * F;
F = fopen ("var/spool/cron/tmp", "W ");
If (F = NULL)
{
Printf ("Open TMP failed! /N ");
Fclose (f );
Return-1;
}
Printf ("open two files
Successfully !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ");
Fclose (f );
Ret = 0;
Printf ("************************************* **
Delpolicy
**************************************** * **********/N ");
Return ret;
}

The following error occurs:

Cause: 1: "/var/spool/cron/tmp" is incorrectly written as "var/spool/cron/tmp"


2: The file name cannot be the TMP keyword. It can be mytmp.

A segment error occurs when you access the wrong memory segment. Generally, you do not have the permission or the corresponding physical memory exists, especially when you access the 0 address.

Generally, a segment error means that the accessed memory exceeds the memory space of the program provided by the system. Generally, this value is saved by GDTR and is a 48-bit register,
The 32-bit table stores the gdt table pointed to by it, and the last 13 BITs are saved to the corresponding gdt subscript, the last three digits include whether the program is in the memory and the running level of the program in the CPU,

The gdt is a table with 64-bit as the unit. In this table, the code segment for running the program and the starting address of the data segment are saved, and the corresponding segment limitation and page exchange are also saved,

Information such as the program running level and memory granularity. Once a program is accessed out of bounds, the CPU will generate corresponding exception protection, so Segmentation
Fault appears.

In programming, the following methods may easily cause segment errors, which are basically caused by incorrect pointer usage.

1) access the system data zone, especially
The most common way to write data to memory addresses protected by the system is to give a pointer A 0 address
2) memory out of bounds (array out of bounds, variable types inconsistent, etc.) access to areas not in your memory

Solution

When we write programs in C/C ++, most of the work of memory management needs to be done.
How to quickly locate these "segment errors" statements

1 dummy_function (void)

2 {

3
Unsigned char * PTR = 0x00;

4
* PTR = 0x00;

5}

6

7 int main (void)

8 {

9
Dummy_function ();
10

11
Return 0;

12}
 
An error occurred while trying to operate on the memory area with the address 0, which is usually inaccessible. Compile and run:
$./A. Out
Segment Error

1. Use GDB to gradually find the segment error:
You need an executable program with debugging information
-Rdynamic "parameters are compiled, and then the newly compiled program is debugged using GDB. The specific steps are as follows:
$ Gcc-g-rdynamic d. c
$ GDB./A. Out
Gnu gdb 6.5
Copyright (c) 2006 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License,
And you are
Welcome to change it and/or distribute copies of it under certain
Conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB. Type
"Show warranty" for details.
This GDB was configured as "i686-pc-linux-gnu"... using host
Libthread_db library "/lib/libthread_db.so.1 ".

(GDB) r
Starting program:/a. Out

Program received signal SIGSEGV, segmentation fault.
0x08048524 in dummy_function () at D. C: 4
4
* PTR = 0x00;
(GDB)

 
You do not need to perform step-by-step debugging to find the 4th line of the error location d. c file.
The process ended after receiving the SIGSEGV signal. For more information, see man 7 signal ),
The default handler action of SIGSEGV is to print the error message of "segment error" and generate the core file. method 2 is generated.
2. Analyze the core file:
What is a core file?
The default action of certain signals is to cause
A process to terminate and produce a core dump file,
A disk file containing an image of the process's
Memory at the time
Termination.
A list of the signals which cause a process to dump core can be
Found in signal (7 ).
This document is taken from man page (MAN 5 core ). Sometimes the generation of core files is disabled to gradually reduce the number of pull files on the system,
Limit the core file size to kb.
$ Ulimit-C 0
$ Ulimit-C 1000
$ Ulimit-C 1000
$./A. Out
Segment error (core dumped)
$ Ls
A. out core
D. c F. c g. C
Pango. c test_iconv.c
Test_regex.c
 
The core file is finally generated. GDB debugging:
$ GDB./A. out core
Gnu gdb 6.5
Copyright (c) 2006 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License,
And you are
Welcome to change it and/or distribute copies of it under certain
Conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB. Type
"Show warranty" for details.
This GDB was configured as "i686-pc-linux-gnu"... using host
Libthread_db library "/lib/libthread_db.so.1 ".

Warning: Can't read pathname for load map: input/output error.
Reading symbols from/lib/libc. so.6...... done.
Loaded symbols for/lib/libc. so.6
Reading symbols from/lib/ld-linux.so.2... done.
Loaded symbols for/lib/ld-linux.so.2
Core was generated by './A. out '.
Program terminated with signal 11, segmentation fault.
#0 0x08048524 in dummy_function () at D. C: 4
4
* PTR = 0x00;

For IE in windows, sometimes some web pages may encounter "runtime errors". If your computer is installed with a Windows compiler,

It will pop up a dialog box asking if you want to debug it. If you choose yes, the compiler will be opened and enter the debugging status to start debugging.
How can we achieve this in Linux? Let it call GDB in the handler of SIGSEGV, so the third method was born again:
3. Start debugging when a segment error occurs:
# Include <stdio. h>
# Include <stdlib. h>
# Include <signal. h>
# Include <string. h>

Void dump (INT signo)
{

Char Buf [1024];

Char cmd [1024];

File * FH;


Snprintf (BUF, sizeof (BUF), "/proc/% d/define line", getpid ());

If (! (FH = fopen (BUF, "R ")))

Exit (0 );

If (! Fgets (BUF, sizeof (BUF), FH ))

Exit (0 );

Fclose (FH );

If (BUF [strlen (BUF)-1] = '/N ')

Buf [strlen (BUF)-1] = '/0 ';

Snprintf (CMD, sizeof (CMD), "GDB % S % d", Buf, getpid ());

System (CMD );


Exit (0 );
}


Void
Dummy_function (void)
{

Unsigned char * PTR = 0x00;

* PTR = 0x00;
}


Int
Main (void)
{

Signal (SIGSEGV, & dump );

Dummy_function ();


Return 0;
}
 
The compilation and running effect is as follows:
$ Gcc-g-rdynamic F. C
$./A. Out
Gnu gdb 6.5
Copyright (c) 2006 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License,
And you are
Welcome to change it and/or distribute copies of it under certain
Conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB. Type
"Show warranty" for details.
This GDB was configured as "i686-pc-linux-gnu"... using host
Libthread_db library "/lib/libthread_db.so.1 ".

Attaching to program:/home/xiaosuo/test/a. Out, Process
9563
Reading symbols from/lib/libc. so.6...... done.
Loaded symbols for/lib/libc. so.6
Reading symbols from/lib/ld-linux.so.2... done.
Loaded symbols for/lib/ld-linux.so.2
0xffffe410 in _ kernel_vsyscall ()
(GDB) BT
#0 0xffffe410 in _ kernel_vsyscall ()
#1 0xb7ee4b53 in waitpid () from
/Lib/libc. so.6
#2 0xb7e925c9 in strtold_l () from
/Lib/libc. so.6
#3 0x08048830 in dump (signo = 11) at F. C: 22
#4 <signal handler
Called>
#5 0x0804884c in dummy_function ()
F. C: 31
#6 0x08048886 in main () at F. C: 38
 
The above methods are implemented on the premise that GDB is available on the system. If not, what should I do? Actually, glibc provides such function clusters that can dump stack content,
For details, see/usr/include/execinfo. H (none of these functions provide man
Page.
4. Use backtrace and objdump for analysis:
The rewrite code is as follows:
# Include <execinfo. h>
# Include <stdio. h>
# Include <stdlib. h>
# Include <signal. h>


Void
Dummy_function (void)
{

Unsigned char * PTR = 0x00;

* PTR = 0x00;
}

Void dump (INT signo)
{

Void * array [10];

Size_t size;

Char ** strings;

Size_t I;


Size = backtrace (array, 10 );

Strings = backtrace_symbols (array, size );


Printf ("obtained % ZD stack frames./N", size );


For (I = 0; I <size; I ++)

Printf ("% s/n", strings [I]);


Free (strings );


Exit (0 );
}


Int
Main (void)
{

Signal (SIGSEGV, & dump );

Dummy_function ();


Return 0;
}
 
The compilation and running results are as follows:
$ Gcc-g-rdynamic G. C
$./A. Out
Obtained 5 stack frames.
./A. Out (dump + 0x19) [0x80486c2]
[0xffffe420]
./A. Out (main + 0x35) [0x802136f]
/Lib/libc. so.6 (_ libc_start_main + 0xe6) [0xb7e02866]
./A. out [0x8048601]
 
Use the objdump disassembly program to find the code location corresponding to address 0x802136f:
$ Objdump-d a. Out
8048765:
E8 02 Fe FF
FF
Call 804856c
<Signal @ PLT
>
80100006a:
E8 25 FF
FF
Call 8048694
<Dummy_function>
803666f:
B8 00 00 00
00
MoV
$0x0, % eax
8048774:
C9
Leav

----- The following content is taken from the Internet

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.