linux assembly: how to call syscall?

assembly, linux, system-calls, x86-64

Solution

To make a system call in 64-bit Linux, place the system call number in rax, and its arguments, in order, in rdi, rsi, rdx, r10, r8, and r9, then invoke syscall.

Note that 64-bit call numbers are different from 32-bit call numbers.

Here is an example in GAS syntax. NASM syntax for putting an address in a register is `lea rsi, [rel message]` using a RIP-relative LEA.

        .global _start

        .text
_start:
        # write(1, message, 13)
        mov     $1, %rax                # system call 1 is write
        mov     $1, %rdi                # file handle 1 is stdout
        lea     message(%rip), %rsi     # address of string to output
        mov     $13, %rdx               # number of bytes
        syscall

        # exit(0)
        mov     $60, %rax               # system call 60 is exit
        xor     %rdi, %rdi              # return code 0
        syscall

.section .rodata           # read-only data section
message:
        .ascii  "Hello, World\n"

See also What happens if you use the 32-bit int 0x80 Linux ABI in 64-bit code?

Problem

I want to call a syscall in assembly. The problem is I can't `mov ecx,rsp`. `rsp` is 64-bit register, `ecx` is a 32-bit register. I want to pass the buffer addr as a parameter of this syscall. What can I do? Thanks. ``` section .data s0: db "Largest basic function number supported:%s\n",0 s0len: equ $-s0 section .text global main extern write main: sub rsp, 16 xor eax, eax cpuid mov [rsp], ebx mov [rsp+4], edx mov [rsp+8], ecx mov [rsp+12], word 0x0 mov eax, 4 mov ebx, 1 mov ecx, rsp mov edx, 4 int 80h mov eax, 4 mov ebx, 1 mov ecx, s0 mov edx, s0len int 80h mov eax, 1 int 80h ```

Original source

Related problems