您的位置:首页 > 运维架构 > Linux

Linux系统内存错误产生的原因及调试方法

2010-06-09 13:19 495 查看
来源:赛迪网 作者:kid

  而言之,产生段错误就是访问了错误的内存段,一般是你没有权限,或者根本就不存在对应的物理内存,尤其常见的是访问0地址.

  一般来说,段错误就是指访问的内存超出了系统所给这个程序的内存空间,通常这个值是由gdtr来保存的,他是一个48位的寄存器,其中的32位是保存由它指向的gdt表,后13位保存相应于gdt的下标,最后3位包括了程序是否在内存中以及程序的在cpu中的运行级别,指向的gdt是由以64位为一个单位的表,在这张表中就保存着程序运行的代码段以及数据段的起始地址以及与此相应的段限和页面交换还有程序运行级别还有内存粒度等等的信息。一旦一个程序发生了越界访问,cpu就会产生相应的异常保护,于是segmentation fault就出现了.

  在编程中以下几类做法容易导致段错误,基本是是错误地使用指针引起的

  1)访问系统数据区,尤其是往 系统保护的内存地址写数据

最常见就是给一个指针以0地址

  2)内存越界(数组越界,变量类型不一致等) 访问到不属于你的内存区域

  解决方法

  我们在用C/C++语言写程序的时侯,内存管理的绝大部分工作都是需要我们来做的。实际上,内存管理是一个比较繁琐的工作,无论你多高明,经验多丰富,难 免会在此处犯些小错误,而通常这些错误又是那么的浅显而易于消除。但是手工“除虫”(debug),往往是效率低下且让人厌烦的,本文将就"段错误"这个 内存访问越界的错误谈谈如何快速定位这些"段错误"的语句。

下面将就以下的一个存在段错误的程序介绍几种调试方法:

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 }
  作为一个熟练的C/C++程序员,以上代码的bug应该是很清楚的,因为它尝试操作地址为0的内存区域,而这个内存区域通常是不可访问的禁区,当然就会出错了。我们尝试编译运行它:

xiaosuo@gentux test $ ./a.out

段错误
  果然不出所料,它出错并退出了。

  1.利用gdb逐步查找段错误:

  这种方法也是被大众所熟知并广泛采用的方法,首先我们需要一个带有调试信息的可执行程序,所以我们加上“-g -rdynamic"的参数进行编译,然后用gdb调试运行这个新编译的程序,具体步骤如下:

xiaosuo@gentux test $ gcc -g -rdynamic d.c

xiaosuo@gentux test $ 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: /home/xiaosuo/test/a.out

Program received signal SIGSEGV, Segmentation fault.

0x08048524 in dummy_function () at d.c:4

4 *ptr = 0x00;

(gdb)
  好像不用一步步调试我们就找到了出错位置d.c文件的第4行,其实就是如此的简单。

  从这里我们还发现进程是由于收到了SIGSEGV信号而结束的。通过进一步的查阅文档(man 7 signal),我们知道SIGSEGV默认handler的动作是打印”段错误"的出错信息,并产生Core文件,由此我们又产生了方法二。

  2.分析Core文件:
程序在运行一段时间才出错,而且是内存错误。可能是指针访问错误。这种情况下,查找错误比较困难,可以使用core文件帮助查找错误。

Core文件是什么呢?

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 of termination. A list of the signals which cause a process to dump core can be found
in signal(7).
$ uname -a

Linux dev 2.4.21-9.30AXsmp #1 SMP Wed May 26 23:37:09 EDT 2004 i686 i686 i386 GNU/Linux

再看看默认的一些参数,注意core file size是个0,程序出错时不会产生core文件了。

$ ulimit -a

core file size (blocks, -c) 0

data seg size (kbytes, -d) unlimited

file size (blocks, -f) unlimited

max locked memory (kbytes, -l) 4

max memory size (kbytes, -m) unlimited

open files (-n) 2048

pipe size (512 bytes, -p) 8

stack size (kbytes, -s) 10240

cpu time (seconds, -t) unlimited

max user processes (-u) 7168

virtual memory (kbytes, -v) unlimited

不过奇怪了,我的系统上并没有找到core文件。后来,忆起为了渐少系统上的拉圾文件的数量(本人有些洁癖,这也是我喜欢Gentoo的原因 之一),禁止了core文件的生成,查看了以下果真如此,将系统的core文件的大小限制在512K大小,再试:

需要修改参数,才能使出错时产生core文件。

没有找到core文件,我们改改ulimit的设置,让它产生。1024是随便取的,要是core文件大于1024个块,就产生不出来了。

$ ulimit -c 1024

比较保险的做法是

$ ulimit -c unlimited

$ ulimit -a

core file size (blocks, -c) 1024

data seg size (kbytes, -d) unlimited

file size (blocks, -f) unlimited

max locked memory (kbytes, -l) 4

max memory size (kbytes, -m) unlimited

open files (-n) 2048

pipe size (512 bytes, -p) 8

stack size (kbytes, -s) 10240

cpu time (seconds, -t) unlimited

max user processes (-u) 7168

virtual memory (kbytes, -v) unlimited

设置Core Dump的核心转储文件目录和命名规则

/proc/sys/kernel/core_uses_pid可以控制产生的core文件的文件名中是否添加pid作为扩展,如果添加则文件内容为1,否则为0

/proc/sys/kernel/core_pattern可以设置格式化的core文件保存位置或文件名,比如原来文件内容是core-%e

可以这样修改:

echo "/corefile/core-%e-%p-%t" > /proc/sys/kernel/core_pattern

将会控制所产生的core文件会存放到/corefile目录下,产生的文件名为core-命令名-pid-时间戳

以下是参数列表:

%p - insert pid into filename 添加pid

%u - insert current uid into filename 添加当前uid

%g - insert current gid into filename 添加当前gid

%s - insert signal that caused the coredump into the filename 添加导致产生core的信号

%t - insert UNIX time that the coredump occurred into filename 添加core文件生成时的unix时间

%h - insert hostname where the coredump happened into filename 添加主机名

%e - insert coredumping executable name into filename 添加命令名

一个小方法来测试产生core文件

直接输入指令:

kill -s SIGSEGV $$

就可以在当前目录下面看到core文件了

产生core文件,可以使用gdb调试:

可执行程序是叫做bin(通常core文件就叫做bin.core),使用下面命令

1.gdb ./bin ./bin.core

2.使用bt命令看frames,假定在n

3.使用frame n调整frame

4.这个时候可以p任何argument或者local variable

调试p string这样的对象的值,可能由于过长,可以p string 的私有成员,如果p arg1.dat,这样可以通过p arg1.dat+100这样进行偏移。如:

xiaosuo@gentux test $ 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: 输入/输出错误.

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;

这样获得了这些数据以后,我们可以将这些数据取出来,构造core的条件,单步跟踪,今天我就用这样的方法找到了一个bug。

主要使用到第二条,就可以发现错误出现位置。在core文件内容中,显示的 第一个出现在某个文件的 行数,就为该行出现的错误。仔细查看该行。之后的一些信息就是函数调用的 逐行退出。而且每个都有位置标志。

Note:通过ulimit -c修改之后,只在当前shell起作用,如果要想对整个系统起作用可以将ulimit -c unlimited 加入/etc/profile里面;另外也可以修改/etc/security/limits.conf文件,加入* soft core unlimited即可。
手动产生core文件:通过gcore $pid命令直接导出相应进程的core文件,此命令运行后, 会恢复程序的执行, 不影响程序的运行

  Linux下如何做到这些呢?我的大脑飞速地旋转着,有了,让它在SIGSEGV的handler中调用gdb,于是第三个方法又诞生了:

  3.段错误时启动调试:

#include

#include

#include

#include

void dump(int signo)

{

char buf[1024];

char cmd[1024];

FILE *fh;

snprintf(buf, sizeof(buf), "/proc/%d/cmdline", 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] = '';

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;

}
  编译运行效果如下:

xiaosuo@gentux test $ gcc -g -rdynamic f.c

xiaosuo@gentux test $ ./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

#5 0x0804884c in dummy_function () at f.c:31

#6 0x08048886 in main () at f.c:38
  怎么样?是不是依旧很酷?

  以上方法都是在系统上有gdb的前提下进行的,如果没有呢?其实glibc为我们提供了此类能够dump栈内容的函数簇,详见/usr/include/execinfo.h(这些函数都没有提供man page,难怪我们找不到),另外你也可以通过gnu的手册进行学习。

  4.利用backtrace和objdump进行分析:

  重写的代码如下:

#include

#include

#include

#include

/* A dummy function to make the backtrace more interesting. */

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 ("%sn", strings[i]);

free (strings);

exit(0);

}

int

main (void)

{

signal(SIGSEGV, &dump);

dummy_function ();

return 0;

}
  编译运行结果如下:

xiaosuo@gentux test $ gcc -g -rdynamic g.c

xiaosuo@gentux test $ ./a.out

Obtained 5 stack frames.

./a.out(dump+0x19) [0x80486c2]

[0xffffe420]

./a.out(main+0x35) [0x804876f]

/lib/libc.so.6(__libc_start_main+0xe6) [0xb7e02866]

./a.out [0x8048601]
  这次你可能有些失望,似乎没能给出足够的信息来标示错误,不急,先看看能分析出来什么吧,用objdump反汇编程序,找到地址0x804876f对应的代码位置:

xiaosuo@gentux test $ objdump -d a.out
8048765: e8 02 fe ff ff call 804856c

804876a: e8 25 ff ff ff call 8048694

804876f: b8 00 00 00 00 mov $0x0,%eax

8048774: c9 leave
  我们还是找到了在哪个函数(dummy_function)中出错的,信息已然不是很完整,不过有总比没有好的啊!

  后记:

  本文给出了分析"段错误"的几种方法,不要认为这是与孔乙己先生的"回"字四种写法一样的哦,因为每种方法都有其自身的适用范围和适用环境,请酌情使用,或遵医嘱。

转自 http://tech.sina.com.cn/s/2007-08-24/09301696393.shtmlhttp://blog.csdn.net/yfw418/archive/2007/07/04/1679017.aspx
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

另外推荐一篇文章 走下神坛的内存调试器--定位多线程内存越界问题实践总结 http://wenku.baidu.com/view/5b1a6616b7360b4c2e3f64fd.html 用一个很好的例子讲解了寻找内存被修改导致程序crash的过程,使用了包括 MALLOC_CHECK, valgrind, electtric-fence,
dmalloc, mprotect 等工具和方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: