【发布时间】:2010-12-04 13:42:25
【问题描述】:
我被要求分析一个汇编代码,该代码是从 Visual Studio IDE 中的以下 c++ 代码生成的:
这里是 c++ 代码:
int plus(int a,int b);
int main()
{
cout<<plus(2,4);
getchar();
return 0;
}
int plus(int a,int b)
{
static int t=2;
return a+b+t;
}
这里是汇编代码(简化形式):
_main PROC ; COMDAT
; 8 : {
push ebp
mov ebp, esp
sub esp, 192 ; 000000c0H
push ebx
push esi
push edi
lea edi, DWORD PTR [ebp-192]
mov ecx, 48 ; 00000030H
mov eax, -858993460 ; ccccccccH
rep stosd
; 9 : cout<<plus(2,4);
push 4
push 2
call ?plus@@YAHHH@Z ; plus
add esp, 8
mov esi, esp
push eax
mov ecx, DWORD PTR __imp_?cout@std@@3V?$basic_ostream@DU?$char_traits@D@std@@@1@A
call DWORD PTR __imp_??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QAEAAV01@H@Z
cmp esi, esp
call __RTC_CheckEsp
; 10 : getchar();
mov esi, esp
call DWORD PTR __imp__getchar
cmp esi, esp
call __RTC_CheckEsp
; 11 : return 0;
xor eax, eax
; 12 : }
pop edi
pop esi
pop ebx
add esp, 192 ; 000000c0H
cmp ebp, esp
call __RTC_CheckEsp
mov esp, ebp
pop ebp
ret 0
_main ENDP
; Function compile flags: /Odtp /RTCsu /ZI
_TEXT ENDS
; COMDAT ?plus@@YAHHH@Z
_TEXT SEGMENT
_a$ = 8 ; size = 4
_b$ = 12 ; size = 4
?plus@@YAHHH@Z PROC ; plus, COMDAT
; 15 : {
push ebp
mov ebp, esp
sub esp, 192 ; 000000c0H
push ebx
push esi
push edi
lea edi, DWORD PTR [ebp-192]
mov ecx, 48 ; 00000030H
mov eax, -858993460 ; ccccccccH
rep stosd
; 16 : static int t=2;
; 17 : return a+b+t;
mov eax, DWORD PTR _a$[ebp]
add eax, DWORD PTR _b$[ebp]
add eax, DWORD PTR ?t@?1??plus@@YAHHH@Z@4HA
; 18 : }
pop edi
pop esi
pop ebx
mov esp, ebp
pop ebp
ret 0
?plus@@YAHHH@Z ENDP ; plus
_TEXT ENDS
END
我必须找到代码如何处理堆栈以及如何存储和检索变量? 问候。
【问题讨论】:
-
代码是不言自明的。您有什么具体问题吗?
-
我想知道参数 a 和 b 以及静态 int t 的存储位置。找不到他们。
-
a 和 b 存储在堆栈中。由于这些是参数,您可以看到它们在此处使用 ebp 指针进行访问: mov eax, DWORD PTR _a$[ebp] add eax, DWORD PTR _b$[ebp] t 在此指令中直接指定为常量: add eax, DWORD PTR ?t@?1??plus@@YAHHH@Z@4H
-
还有static int t怎么样,控件是如何从plus方法返回的?
-
t 是一个常数,我已经在上面的回复中显示了。两个连续的加法指令是加 a+b+t 并将结果存储在 eax 指令中。 "ret 0" 是 plus 方法的返回指令。