简单的C++程序 汇编分析
//源代码
#include "iostream"
using namespace std;
class Student
{
private:
int num;
int score;
public:
void setdata(int p1, int p2)
{
int test = 0;
num = p1;
score = p2;
}
};
int main(void)
{
Student S;
S.setdata(1, 80);
return 0;
}
//汇编分析
main 函数
堆栈:
栈顶
...
S.num← 对象S的地址 [ebp-8]
S.score
ebp
...
栈底
19: int main(void)
20: {
00401030 push ebp
00401031 mov ebp,esp
00401033 sub esp,48h
00401036 push ebx
00401037 push esi
00401038 push edi
00401039 lea edi,[ebp-48h]
0040103C mov ecx,12h
00401041 mov eax,0CCCCCCCCh
00401046 rep stos dword ptr [edi]
21: Student S;
22: S.setdata(1, 80);
00401048 push 50h //压入参数80
0040104A push 1 //压入参数1
0040104C lea ecx,[ebp-8] //S的地址放入ecx: 将this指针存入ecx中
0040104F call @ILT+15(Student::setdata) (00401014) //调用setdata函数
23: return 0;
00401054 xor eax,eax
24: }
00401056 pop edi
00401057 pop esi
00401058 pop ebx
00401059 add esp,48h
0040105C cmp ebp,esp
0040105E call __chkesp (004081a0)
00401063 mov esp,ebp
00401065 pop ebp
00401066 ret
//main 函数 通过 call 00401014 调用setdata函数
@ILT+15(?setdata@Student@@QAEXHH@Z):
00401014 jmp Student::setdata (00401080) //00401080 是setdata函数的入口地址
setdata函数(ecx中存放调用该函数的对象的地址:相当于this指针)
堆栈:
栈顶
...
test ← test变量:ebp-8
this指针← 通过ecx压栈: ebp-4
ebp
Eip ← 返回地址:ebp+4
p2 ← 参数p2: ebp+8
p1 ← 参数p1: ebp+0C
...
栈底
11: void setdata(int p1, int p2)
12: {
00401080 push ebp
00401081 mov ebp,esp
00401083 sub esp,48h
00401086 push ebx
00401087 push esi
00401088 push edi
00401089 push ecx
0040108A lea edi,[ebp-48h]
0040108D mov ecx,12h
00401092 mov eax,0CCCCCCCCh
00401097 rep stos dword ptr [edi]
00401099 pop ecx
0040109A mov dword ptr [ebp-4],ecx //将this指针存入栈中
13: int test = 0;
0040109D mov dword ptr [ebp-8],0 //test = 0;
14: num = p1;
004010A4 mov eax,dword ptr [ebp-4] //this指针→eax
004010A7 mov ecx,dword ptr [ebp+8] //p1→ecx
004010AA mov dword ptr [eax],ecx //this->num = p1;
15: score = p2;
004010AC mov edx,dword ptr [ebp-4] //this指针→eax
004010AF mov eax,dword ptr [ebp+0Ch] //p2→eax
004010B2 mov dword ptr [edx+4],eax //this->score = p2;
16: }
004010B5 pop edi
004010B6 pop esi
004010B7 pop ebx
004010B8 mov esp,ebp
004010BA pop ebp
004010BB ret 8