簡體   English   中英

基指針和堆棧指針

[英]Base pointer and stack pointer

鑒於這段代碼:

       swap:

            push ebp ; back up the base pointer,
            mov ebp, esp
            ; push the context of the registers on the stack

            push eax
            push ebx
            push ecx
            push edx

            mov eax, [ebp+8] ; address of the first parameter
            mov ebx, [ebp+12] ; address of the second parameter
            mov dl, [eax]
            mov cl, [ebx]

            mov [eax], cl

            mov [ebx], dl

            ; restore the context of the registers from the stack

            pop edx
            pop ecx  
            pop ebx
            pop eax
            ; restore the ebp
            pop ebp
            ret

(這只是方法。之前我們在堆棧上推送了第一個和第二個參數。)

我的問題是:為什么我們將8添加到Base Pointer以獲取第一個參數的地址,然后是12?

我得到的事實是他們是dword,所以他們每個都是4個字節..所以從ebp + 8到ebp + 12,它讓人感覺很好。 但為什么第一個是ebp + 8? 因為如果ESP指向堆棧的頂部,那么mov ebp,esp意味着EBP指向堆棧的TOP。 然后我們在堆棧上推送4個值:eax,ebx,ecx和edx。 為什么EBP + 8指向第一個參數?

調用該函數時,堆棧如下所示:

+-------------+
| Parameter 2 |
+-------------+
| Parameter 1 |
+-------------+
| Return Addr |  <-- esp
+-------------+    

然后在“堆棧幀”設置后:

+-------------+
| Parameter 2 | <-- [ebp + 12]
+-------------+
| Parameter 1 | <-- [ebp + 8]
+-------------+
| Return Addr |  
+-------------+    
| saved ebp   | <-- ebp
+-------------+ <-- esp

現在保存上下文:

+-------------+
| Parameter 2 | <-- [ebp + 12]
+-------------+
| Parameter 1 | <-- [ebp + 8]
+-------------+
| Return Addr |  
+-------------+    
| saved ebp   | <-- ebp
+-------------+ 
| saved eax   |  
+-------------+    
| saved ebx   |  
+-------------+    
| saved ecx   |  
+-------------+    
| saved edx   | <-- esp
+-------------+    

不要忘記,在許多系統上,堆棧向下增長(這對於x86系列來說確實如此),因此堆棧的頂部將具有最低的內存地址。

因為堆棧上還有另外兩個項目; 你在這個例程的開頭推送的前一個ebp,以及通過調用例程放在堆棧上的返回地址。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM