[备忘] 重温十年前的C基础 - 函数调用与栈

参考文章: http://www.cnblogs.com/DylanWind/archive/2008/12/08/1349822.html

C代码:

#include 

long test(int a,int b)
{
     a = a + 3;
     b = b + 5;
     return a + b;
}

int main(int argc, char* argv[])
{
    printf("%d",test(10,90));
    return 0;
}

反汇编后的main

16:   int main(int argc, char* argv[])
17:   {
00401070   push        ebp
00401071   mov         ebp,esp
00401073   sub         esp,40h
00401076   push        ebx
00401077   push        esi
00401078   push        edi
00401079   lea         edi,[ebp-40h]
0040107C   mov         ecx,10h
00401081   mov         eax,0CCCCCCCCh
00401086   rep stos    dword ptr [edi]
18:       printf("%d",test(10,90));
00401088   push        5Ah
0040108A   push        0Ah
0040108C   call        @ILT+0(test) (00401005)
00401091   add         esp,8
00401094   push        eax
00401095   push        offset string "%d" (0042201c)
0040109A   call        printf (004010d0)
0040109F   add         esp,8
19:       return 0;
004010A2   xor         eax,eax
20:   }

反汇编后的test

8:    long test(int a,int b)
9:    {
00401020   push        ebp
00401021   mov         ebp,esp           
00401023   sub         esp,40h
00401026   push        ebx
00401027   push        esi
00401028   push        edi
00401029   lea         edi,[ebp-40h]
0040102C   mov         ecx,10h
00401031   mov         eax,0CCCCCCCCh
00401036   rep stos    dword ptr [edi]       //这些和上面一样
10:        a = a + 3;                                    
00401038   mov         eax,dword ptr [ebp+8] //ebp=0x12FF24 加8 [0x12FF30]即取到了参数10
0040103B   add         eax,3
0040103E   mov         dword ptr [ebp+8],eax
11:        b = b + 5;
00401041   mov         ecx,dword ptr [ebp+0Ch]
00401044   add         ecx,5
00401047   mov         dword ptr [ebp+0Ch],ecx
12:        return a + b;
0040104A   mov         eax,dword ptr [ebp+8]
0040104D   add         eax,dword ptr [ebp+0Ch]  //最后的结果保存在eax, 结果得以返回
13:   }
00401050   pop         edi                 
00401051   pop         esi
00401052   pop         ebx
00401053   mov         esp,ebp  //esp指向0x12FF24, test函数的堆栈空间被放弃,从当前函数栈顶返回到栈底
00401055   pop         ebp       //此时ebp=0x12FF80, 恢复现场  esp=0x12FF28
00401056   ret       //ret负责栈顶0x12FF28之值00401091弹出到指令寄存器中,esp=0x12FF30

我自己分析的PPT

smithfox | Thursday 31 March 2011 at 5:31 pm | | system