http://linux.chinaitlab.com/administer/807513.html
在学习《程序员的自我修养》时,对其P172页图6-12 “Linux进程初始堆栈”内容的来路有点兴趣,遂花了点时间研究了下,茫然中居然试探出了条可以得到进程初始堆栈的途径……
[root@cxj /]# cat a.c
#include <stdlib.h>
#include <stdio.h>
int main()
{
printf("hello world\n");
return 0;
}
[root@cxj /]# readelf -a a.out | head -n 11
ELF Header:
Magic: 7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00
Class: ELF32
Data: 2's complement, little endian
Version: 1 (current)
OS/ABI: UNIX - System V
ABI Version: 0
Type: EXEC (Executable file)
Machine: Intel 80386
Version: 0x1
Entry point address: 0x80482f0 %获取入口地址
[root@cxj /]# gdb a.out %载入可执行文件
GNU gdb Red Hat Linux (6.6-35.fc8rh)
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 "i386-redhat-linux-gnu"...
Using host libthread_db library "/lib/libthread_db.so.1".
(gdb) b *0x80482f0 %将入口地址设为断点
Breakpoint 1 at 0x80482f0
(gdb) r %启动进程
Starting program: /a.out
warning: Missing the separate debug info file: /usr/lib/debug/.build-id/ac/2eeb206486bb7315d6ac4cd64de0cb50838ff6.debug
warning: Missing the separate debug info file: /usr/lib/debug/.build-id/ba/4ea1118691c826426e9410cafb798f25cefad5.debug
Breakpoint 1, 0x080482f0 in _start ()
(gdb) i r esp %查看栈顶指针(esp)
esp 0xbf8e5a40 0xbf8e5a40
(gdb) x/5570bw 0xbf8e5a40 %查看从esp所指位置开始足够远的存储区域内容,此处5570指查看从0xbf8e5a40开始的5570个“字”(此处为4字节)的内容
%此处取5570只是为了使往后查看的内容足够大。
%事实上我们可以从当前地址往后推最多0x3000个字节且以0x1000对齐的字节数。【经验,我并没有深究理论上的原因】
%比如 0xbf8e5a40 往后推最多0x3000个字节且保持 0x1000对齐的话将得到 0xbf8e8000
%这片区域包含的字节数换算成“字”数即为:(0xbf8e8000-0xbf8e5a40)/4 = 2416
%所以此处用比2416略大(为了得到错误)的值替换5570即可成功得到 Cannot access memory at address 0xXXXXXXXX 的错误消息(((不妨一试)))
%该错误消息可作为对当前进程的栈访问越界的标志。
%
%如果使用“ x/5570bw 0xbf8e5a40 ”命令无法得到如下所示的输出结构,不妨试试 “ x/5570x 0xbf8e5a40 ”