#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)] = '\0')
buf[strlen(buf) - 1] = '\0';
snprintf(cmd, sizeof(cmd),
"gdb %s %d", buf, getpid());
system(cmd);
exit(0);
}//dump
void
dummy(void)
{
unsigned char* ptr = 0x00;
*ptr = 0x00;
}//dummy
int
main(void)
{
signal(SIGSEGV, &dump);
dummy();
return 0;
}//main
编译运行效果如下:
$ 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
#5 0x0804884c in dummy_ () 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进行分析:
重写的代码如下:
#i nclude
#i nclude
#i nclude
#i nclude
void
dummy_ (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 s.\n", size);
for (i = 0; i < size; i++)
printf ("%s\n", strings[i]);
free (strings);
exit(0);
}
int
main (void)
{
signal(SIGSEGV, &dump);
dummy_ ();
return 0;
}
编译运行结果如下:
$ gcc -g -rdynamic g.c
$ ./a.out
Obtained 5 stack s.
./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对应的代码位置:
$ 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 leav
原文:http://tech.diannaodian.com/dw/lin/2012/0604/180621.html