system

System Calls in Assembly

System Calls in Assembly

System calls allow interaction with the operating system to perform tasks such as file operations, input/output, and process control.

Steps for Making a System Call

  1. Load the system call number into the rax register.
  2. Load arguments into specific registers (e.g., rdi, rsi, etc.).
  3. Trigger the system call using the syscall instruction.

Example: Writing to the Screen

section .data
    msg db 'Hello, World!', 0xA  ; Message to display
    len equ $ - msg              ; Calculate message length

section .text
    global _start

_start:
    mov rax, 1        ; System call: write
    mov rdi, 1        ; File descriptor: stdout
    mov rsi, msg      ; Address of the message
    mov rdx, len      ; Length of the message
    syscall           ; Perform the system call

    mov rax, 60       ; System call: exit
    xor rdi, rdi      ; Exit code: 0
    syscall
    

Example: Reading from the Keyboard

section .bss
    input resb 10      ; Reserve 10 bytes for input

section .text
    global _start

_start:
    mov rax, 0        ; System call: read
    mov rdi, 0        ; File descriptor: stdin
    mov rsi, input    ; Address to store input
    mov rdx, 10       ; Maximum number of bytes to read
    syscall           ; Perform the system call

    mov rax, 60       ; System call: exit
    xor rdi, rdi      ; Exit code: 0
    syscall
    

System calls are highly platform-dependent. The above examples are specific to Linux on x86-64 architecture.