Vento
Vento

Reputation: 215

How to push arguments onto stack using MASM x64?

I know the x64 calling convention, first four arguments are in rcx, rdx, r8, r9, rest are on the stack. But my question is how push these arguments?

call_func PROC
    push rbp
    mov rbp, rsp

    mov rbx, rcx ; move C function address to rbx

    mov rcx, 1   ; some dummy value
    mov rdx, 2   ; some dummy value
    mov r8,  3   ; some dummy value
    mov r9,  4   ; some dummy value

    ; and now I want to push fifth argument, but how?

    call rbx     ; call the function

    mov rsp, rbp
    pop rbp

    ret
call_func ENDP

I have tried mov QWORD PTR [rsp + 20h], 1 but when returning form this asm function the RIP register is set to weird value, like 0x0000000000000001. I know that the RIP register is instruction pointer, but why it is modifying it?
I have tried one more thing, let the function take 6 arguments and when I pass sixth argument like mov QWORD PTR [rsp + 28h], 1 the app is fine, sixth argument is passed, fifth has weird value.

Upvotes: 1

Views: 916

Answers (1)

Vento
Vento

Reputation: 215

As Jester said, before pushing arguments I need to allocate space for these arguments including shadow space.
Final working code:

call_func PROC
    push rbp
    mov rbp, rsp
    sub rsp, 32  ; allocate shadow space 'padding'
    sub rsp, 16  ; allocate space for fifth and sixth argument

    mov r11, rcx ; move C function address to r11

    mov rcx, 1   ; some dummy value
    mov rdx, 2   ; some dummy value
    mov r8,  3   ; some dummy value
    mov r9,  4   ; some dummy value

    mov QWORD PTR [rsp + 20h], 5  ; push fifth argument
    mov QWORD PTR [rsp + 28h], 6  ; push sixth argument

    call r11     ; call the function

    mov rsp, rbp
    pop rbp

    ret
call_func ENDP

Upvotes: 1

Related Questions