我在汇编程序(nasm)中编写代码,我希望包含函数,目前我已经
function0:
code
jmp return0
通过跳转到function0调用该函数,返回链接到调用函数的下面的标签, 但是这只有在调用一次函数时才有效,有没有更好的方法呢?
答案 0 :(得分:7)
(假设NASM x86)
使用call
调用函数,ret
从函数返回。
键入call
时发生的情况是下一条指令的地址为push
进入堆栈。当ret
被点击时,它将pop
从堆栈中解析并jmp
到达它。
func:
xor eax, eax
mov eax, 10
add eax, 5
ret ;// essentially identical to: pop [register] -> jmp [register]
_start:
call func
mov ebx, eax ;// Address of this instruction is pushed onto the stack
;// ebx is now 15
调用约定规定EAX
寄存器应包含返回值。另请注意,__cdecl calling convention接受堆栈上的参数。请查看上述链接页面中的示例。 NASM功能将设置其堆栈帧并从堆栈中获取参数以便在函数中使用。该值存储在EAX
。
答案 1 :(得分:0)
这是在汇编中编写函数(具有许多返回值)的一种非常简单的新方法:
function:
sub esp, ( 4 * ret_count)
pushad
mov ebp, esp
;code
;acces first argument with ( dword[ebp + 32 + (4*ret_count) + (4*arg_num)]
;write first return value with ( mov dword[ebp + 36 + (4*ret_pointer)]
popad
add esp, ( 4 * ret_count)
ret
之后,您可以访问如下返回值:
call function
mov eax, dword[esp] ; 1st ret
mov ebx, dword[esp - 4] ; 2nd ret
; or you can just pop them :
pop eax
pop ebx