2008年7月31日 星期四

如何使用gdb追蹤call stack

參考來源:

1. http://www.study-area.org/cyril/opentools/opentools/x1253.html
2. http://www.cs.umbc.edu/~chang/cs313.s02/stack.shtml
3. http://www.lslnet.com/linux/f/docs1/i03/big5120063.htm

1. trace對象

int test(int i)
{
int a;
a=i;
return a;
}

int main()
{
test(1);
}

2. trace對象gdb下的"disas main"輸出:

Dump of assembler code for function main:
0x08048355 : lea 0x4(%esp),%ecx
0x08048359 : and $0xfffffff0,%esp
0x0804835c : pushl -0x4(%ecx)
0x0804835f : push %ebp
0x08048360 : mov %esp,%ebp
0x08048362 : push %ecx
0x08048363 : sub $0x4,%esp
0x08048366 : movl $0x1,(%esp)
0x0804836d : call 0x8048344
0x08048372 : add $0x4,%esp
0x08048375 : pop %ecx
0x08048376 : pop %ebp
0x08048377 : lea -0x4(%ecx),%esp
0x0804837a : ret
End of assembler dump.


3.trace對象gdb下的"disas test"輸出:

Dump of assembler code for function test:
0x08048344 : push %ebp
0x08048345 : mov %esp,%ebp
0x08048347 : sub $0x10,%esp
0x0804834a : mov 0x8(%ebp),%eax
0x0804834d : mov %eax,-0x4(%ebp)
0x08048350 : mov -0x4(%ebp),%eax
0x08048353 : leave
0x08048354 : ret
End of assembler dump.

4. 函式test() call stack trace 情形
(在gdb下可以執行以下指令去執行trace task:
(1) gdb test
(2) >b main
(3) >r
(4) > stepi
(5)> info reg
(6)>p/x *(0xXXXXXXXX)
)

call 0x8048344

esp 0xbfaaf16c 0xbfaaf16c
ebp 0xbfaaf178 0xbfaaf178

;; 當執行完"call 0x8048344 ", eip=0x08048344
;; [esp]=test函式返回main的位置=0x8048372

[esp]=0x8048372
[ebp]=0xbfaaf1e8

push %ebp;; %esp=%esp-4, [%esp]=%ebp

esp 0xbfaaf168 0xbfaaf168
ebp 0xbfaaf178 0xbfaaf178

[esp]=0xbfaaf178
[ebp]=0xbfaaf1e8

mov %esp,%ebp;; %ebp=%esp

esp 0xbfaaf168 0xbfaaf168
ebp 0xbfaaf168 0xbfaaf168

[esp]=0xbfaaf178
[ebp]=0xbfaaf178

sub $0x10,%esp

esp 0xbfaaf158 0xbfaaf158
ebp 0xbfaaf168 0xbfaaf168


mov 0x8(%ebp),%eax; %eax=[0x8(%ebp)] 取parameter值

esp 0xbfaaf158 0xbfaaf158
ebp 0xbfaaf168 0xbfaaf168

[0x8(%ebp)]=0x1
[%eax]=0x1

mov %eax,-0x4(%ebp); [-0x4%ebp]=%eax;; 將parameter i設定給local 變數a

esp 0xbfaaf158 0xbfaaf158
ebp 0xbfaaf168 0xbfaaf168

[-0x4(%ebp)]=0x1
[%eax]=0x1

leave ;;該指令相當於:(1) mov %ebp,%esp // %esp=%ebp
(2)pop %ebp // %ebp=[%esp],%esp=%esp+4

esp 0xbfaaf16c 0xbfaaf16c
ebp 0xbfaaf178 0xbfaaf178

[esp]=0x8048372//return address
[ebp]=0xbfaaf1e8


ret;; 該指令相當於 pop %eip //%eip=[%esp],%esp+4

esp 0xbfaaf170 0xbfaaf170
ebp 0xbfaaf178 0xbfaaf178
[esp]=0x1//parameter value
[ebp]=0xbfaaf1e8

沒有留言: