如何在x86中返回registervalues

时间:2013-02-12 12:28:30

标签: c assembly x86

编写x86汇编函数的正确语法是什么,该函数将一个寄存器值返回给C中的调用函数?是否涉及一些堆栈操作,如果是这样,之后如何清理?我会感谢一个简单的例子。先感谢您。

3 个答案:

答案 0 :(得分: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

序列“push ebp / mov ebp,esp”可以通过“enter”提供,“mov esp,ebp”可以通过“leave”提供,但我更喜欢使它更容易理解,并且使用显式指令更快平台。

答案 1 :(得分:1)

使用gcc,您可以使用内联汇编,而不必过多担心堆栈。

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

这使用了一个没有指令的汇编部分,其输出约束表明eax的值应放在名为eax的变量中。

我使用unsigned int作为寄存器,这不是非常便携,但内联汇编无论如何都不是非常便携。变量必须是寄存器的大小。

答案 2 :(得分:0)

在Linux中,如果返回一个int,则返回eax,一个long(仅限64位模式)返回rax。