2013-02-12 45 views
0

寫一個x86彙編函數返回一個寄存器值到C中的調用函數的正確語法是什麼?是否存在一些堆棧操作,如果是這樣,那麼這個清理過程怎麼樣?我會感謝一個簡單的例子。先謝謝你。如何在x86中返回寄存器值

+0

研究編譯器的調用約定。 – 2013-02-12 12:31:47

+0

這取決於您的代碼使用的其他調用約定;請參閱http://en.wikipedia.org/wiki/X86_calling_conventions。 – 2013-02-12 12:34:03

+0

@alexey。嗯。。好。我正在使用gcc。 – stian 2013-02-12 12:35:28

回答

1

作爲一項規則,以下頁眉和頁腳是用於32位程序:

MyProc: 
; prologue 
    push ebp 
    mov ebp, esp 

    sub esp, sizeof_local_variables ; this is optional, if your procedure 
             ; needs some local variables. 

; here write your code. 
; The arguments are accessible on addresses [ebp+8+some_const] 
; The local variables are on addresses [ebp-some_const] 
; where some_const must be less than sizeof_local_variables of course. 

; Return the result in EAX register if you want to return it to C/C++ or other HLL. 

; epilogue 
    mov esp, ebp  ; restores the stack pointer as it was on the entry 
    retn n    ; returns to the caller. If you are using CCALL convention 
         ; (usualy in C code) you have to omit "n" constant. 
         ; n is the count of bytes of the pushed arguments. 
         ; in 32bit environment it must be multiply of 4 

序列 「推EBP/MOV EBP,尤指」 可以通過instrunction 「進入」 和「MOV ESP提供, ebp「by」leave「,但我更願意讓它更易於理解,並且在大多數平臺上使用明確的指令會更快。

+0

事後清理很有意思。謝謝。 – stian 2013-02-12 12:52:16

0

在Linux中,如果你返回一個int,返回eax,一個long(僅在64位模式下)以rax返回。

1

使用gcc,您可以使用內聯彙編,而不用擔心堆棧太多。

unsigned int get_eax(void) { 
    unsigned int eax; 
    asm("" : "=a" (eax)); 
    return eax; 
} 

它使用與它沒有任何指令的組件部分,與說EAX的值應放在一個名爲eax變量的輸出限制。

我使用unsigned int作爲寄存器,它不是非常便攜,但內聯彙編不是很便攜。變量需要是寄存器的大小。