C语言函数调用分析
代码:
- #include
- typedef struct{
- doubled;
- float f;
- inti;
- char c;
- }return_value;
- return_value my_test_pass(return_value pass)
- {
- return_value rv;
- rv.d=pass.d;
- rv.f=pass.f;
- rv.i=pass.i;
- rv.c=pass.c;
- return rv;
- }
- return_value my_test_of_return()
- {
- return_value rv;
- rv.d=12.56;
- rv.f=3.1;
- rv.i=10;
- rv.c=a;
- return rv;
- }
- intmain()
- {
- return_value local=my_test_of_return();
- return_value local1=my_test_pass(local);
- return 0;
- }
编译和反汇编过程:
[gong@Gong-Computer deeplearn]$ gcc -g structpass.c -o structpass
[gong@Gong-Computer deeplearn]$ objdump -S -d structpass > structpass_s
[gong@Gong-Computer deeplearn]$ objdump -S -d structpass > structpass_s
- ...
- int main()
- {
- 804841d: 8d 4c 24 04 lea 0x4(%esp),%ecx
- 8048421: 83 e4 f8 and $0xfffffff8,%esp
- 8048424: ff 71 fc pushl -0x4(%ecx)
- 8048427: 55 push %ebp
- 8048428: 89 e5 mov %esp,%ebp
- 804842a: 51 push %ecx
- 804842b: 83 ec 4c sub $0x4c,%esp
- return_value local = my_test_of_return();
- 804842e: 8d 45 e0 lea -0x20(%ebp),%eax
- 8048431: 89 04 24 mov %eax,(%esp)
- 8048434: e8 9e ff ff ff call 80483d7
- 8048439: 83 ec 04 sub $0x4,%esp
- return_value local1 = my_test_pass(local);
- 804843c: 8d 45 c8 lea -0x38(%ebp),%eax
- 804843f: 8b 55 e0 mov -0x20(%ebp),%edx
- 8048442: 89 54 24 04 mov %edx,0x4(%esp)
- 8048446: 8b 55 e4 mov -0x1c(%ebp),%edx
- 8048449: 89 54 24 08 mov %edx,0x8(%esp)
- 804844d: 8b 55 e8 mov -0x18(%ebp),%edx
- 8048450: 89 54 24 0c mov %edx,0xc(%esp)
- 8048454: 8b 55 ec mov -0x14(%ebp),%edx
- 8048457: 89 54 24 10 mov %edx,0x10(%esp)
- 804845b: 8b 55 f0 mov -0x10(%ebp),%edx
- 804845e: 89 54 24 14 mov %edx,0x14(%esp)
- 8048462: 89 04 24 mov %eax,(%esp)
- 8048465: e8 2a ff ff ffcall8048394
- 804846a: 83 ec 04 sub $0x4,%esp
- return 0;
- 804846d: b8 00 00 00 00 mov $0x0,%eax
- }
由上面的反汇编代码可以知道结构体的传递参数是依据堆栈实现的。这也说明了多参数的传递过程并不是按着固定的模式实现的,这也是我们需要注意的问题。参数的传递需要根据实际情况分析。
总结:
函数的调用是有一定的方式的,各个函数都有一定的堆栈空间,而且每一个堆栈空间的分布情况也是类似的,但是大小要根据实际的情况分析。一般一个函数的堆栈空间中包含下面几个部分:1、栈帧(用来表示该堆栈空间的栈底,也就是指开始的地址EBP),局部变量的空间,下一个被调用函数的参数传递,最后是返回地址(实质上也是一个EBP)。就是依据EBP和相对位置就能知道每一个函数的基本分布,而ESP就能知道堆栈空间的大小。
被调用参数的获取主要是依据EBP指针的相对位置获得,因为被调用函数的堆栈空间上一个堆栈空间就是调用函数的堆栈空间。根据函数的栈帧指针(EBP)和相对位置(-4,-8等)找到对应的参数,但是相对位置也是不固定的,这需要考虑结构体的对齐等方式,具体的要在实际中计算。
返回值一般都是采用EAX返回的,但是对于结构体等则是采用堆栈的方式一个元算一个元素的返回的,但是还是运用了EAX的特性。
函数调用的分布打开如下:
评论