Exit Syscall in Assembly

In x86-64 assembly on Linux, the exit system call is commonly used to terminate a program.

Exit has a syscall number of 60, and it takes a single argument – the exit code. As with other system calls, the number of the syscall is stored in the rax register, and the first argument is stored in rdi.

Check out our article on system calls to learn how to use them. It covers what syscalls are and how they work, how to look up the syscall numbers, how to research syscall, identify arguments, and more!

The Exit System Call

Here’s how the exit syscall looks:

mov rax, 60
mov rdi, 0
syscall

Wherever this code is placed, it will terminate the program at that point.

It is a good idea to use a procedure so that it can be called when needed. This also makes the code cleaner:

Exit:
    mov rax, 60
    mov rdi, 0
    syscall

Exit Syscall Example

Let’s see a complete example of how we can use the exit syscall to terminate a program, taking advantage of the procedure from the last example.

The following program adds two numbers. The flow of execution starts at the beginning of _start, and ends with the exit syscall.

section .text
    global _start

_start:
    call init_variables
    call add_numbers
    call Exit 

init_variables:
    mov rax, 5
    mov rbx, 10
    ret

add_numbers:
    add rax, rbx
    ret

Exit:
    mov rax, 60
    mov rdi, 0
    syscall

First the ‘init_variables’ procedure is called and returned from. Then the ‘add_numbers’ procedure adds the two numbers and stores the sum in the rax register. Finally, the ‘Exit’ procedure is called, which results in the termination of the program.