x64的ABI在Unix(Linux,Mac OS)上和Windows上是不同的,调用约定有区别。
wikipedia上对调用约定的解释
调用约定的不同(寄存器传参部分)
Unix:
The first six integer arguments (from the left) are passed in RDI, RSI, RDX, RCX, R8, and R9, in that order.
Additional integer arguments are passed on the stack. These registers, plus RAX, R10 and R11 are destroyed
by function calls, and thus are available for use by the function without saving.
Windows:
The first four integer arguments are passed in RCX, RDX, R8 and R9, in that order. Additional integer
arguments are passed on the stack. These registers, plus RAX, R10 and R11 are destroyed by function calls,
and thus are available for use by the function without saving.
需要注意的是,Windows上用register传参的同时,还需要需要分配栈空间,并且需要16字节对齐。
The x64 Application Binary Interface (ABI) is a 4 register fast-call calling convention, with stack-backing for those registers.
代码示例
----------------------------------------------------------------------
; Allocate stack memory
; ---------------------------------------------------------------------
sub rsp,8*7
; Allocated 8*7 bytes:
; 8*4 from them are defaut parameters for all functions.
; 8*3 from them are those extra three parameters on stack.
; Total allocated space for seven parameters.
; 4x Default parameters are passed via registers.
; Those 3x extra parameters are passed via stack.
; !!! Always allocate stack space => odd number * 8,
; like now is just like we need => 8*7, doing like this will
; balance stack and make it aligned on 16 byte boundary.
; ---------------------------------------------------------------------
; Call printf with seven parameters
; 4x of them are assigned to registers.
; 3x of them are assigned to stack spaces.
; ---------------------------------------------------------------------
; #3x# ; Stack parameters
mov rax,qword [param6]
mov qword [rsp+48],rax
mov rax,qword [param5]
mov qword [rsp+40],rax
mov rax,qword [param4]
mov qword [rsp+32],rax
; ---------------------------
; #4x# ; Register parameters
mov r9,qword [param3]
mov r8,qword [param2]
mov rdx,qword [param1]
mov rcx,qword txt_format
; ---------------------------
call printf
; ---------------------------
; ---------------------------------------------------------------------
; Release stack memory
; ---------------------------------------------------------------------
add rsp,8*7