Skip to content
systemcoding.dev
Assembly

Pass the fifth and sixth arguments in r8 and r9

The System V AMD64 ABI passes integer arguments five and six in r8 and r9; a six-argument NASM 2.16.03 function and its caller.

1 min read
Summarize in AI

The first six integer or pointer arguments go in registers under the System V AMD64 ABI, in this order: rdi, rsi, rdx, rcx, r8, r9. The fifth and sixth are the ones people forget, because r8 and r9 have no letter in their names to hint at their job. The function below adds all six, and _start calls it with 1 to 6 using NASM 2.16.03 on Linux.

sum6.asmnasm
global _start
section .text

sum6:                       ; long sum6(a, b, c, d, e, f)
    lea  rax, [rdi + rsi]
    add  rax, rdx
    add  rax, rcx
    add  rax, r8            ; fifth argument
    add  rax, r9            ; sixth argument
    ret

_start:
    mov  edi, 1
    mov  esi, 2
    mov  edx, 3
    mov  ecx, 4
    mov  r8d, 5
    mov  r9d, 6
    call sum6
    mov  edi, eax
    mov  eax, 60
    syscall
Text
$ ./sum6; echo $?
21

Writing mov r8d, 5 zero-extends into all of r8, the same as any 32-bit write, so the shorter encoding is safe for small constants. Note that rcx carries the fourth argument for ordinary function calls but the syscall instruction uses r10 there, because syscall overwrites rcx with the return address. That is why a libc wrapper for a four-argument system call first copies rcx to r10. A seventh argument no longer fits in a register and goes on the stack.

Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.