0Pricing
Assembly Language & x86 Low-Level Systems Programming · Урок

Системные вызовы Linux (syscalls)

Научитесь выполнять распространённые операции операционной системы, такие как ввод-вывод файлов, управление процессами и выделение памяти, используя системные вызовы Linux.

«Системные вызовы Linux (syscalls)» — бесплатный урок Assembly Language & x86 Low-Level Systems Programming на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Assembly Language & x86 Low-Level Systems Programming, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Assembly Language & x86 Low-Level Systems Programming содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

What are System Calls?

Welcome! In this lesson, we'll dive into Linux System Calls (syscalls). These are the fundamental way user-space programs request services from the operating system's kernel.

Think of them as a special set of functions that your program can call to do powerful things, like interacting with files, managing processes, or allocating memory.

User vs. Kernel Mode

Modern operating systems operate in different privilege levels. Typically, there's user mode (where your applications run) and kernel mode (where the OS core runs).

  • User Mode: Limited access to hardware and critical memory.
  • Kernel Mode: Full access, handles system resources securely.

System calls are the controlled gateway for user-mode programs to temporarily switch to kernel mode and ask the OS to perform privileged operations on their behalf.

Invoking Syscalls in x86-64

On x86-64 Linux, system calls are primarily invoked using the syscall instruction. Before calling syscall, you load specific registers with values:

  • RAX: Holds the system call number.
  • RDI, RSI, RDX, R10, R8, R9: Hold the system call arguments (up to 6).
  • The return value is placed back in RAX.

Finding Syscall Numbers

How do you know which number corresponds to which system call? You can look them up!

  • Use the man syscalls command in your terminal.
  • Consult header files like /usr/include/asm/unistd_64.h.

For example, sys_write is system call number 1, and sys_exit is number 60.

Basic File I/O: sys_write

One of the most common syscalls is sys_write, used to write data to a file descriptor. Its parameters are:

  • RDI: File descriptor (e.g., 1 for stdout).
  • RSI: Pointer to the buffer containing data.
  • RDX: Number of bytes to write.

Standard file descriptors are 0 (stdin), 1 (stdout), and 2 (stderr).

Hello, Syscall! Example

Let's write a simple program that prints "Hello, Syscall!" to the console using sys_write and then exits using sys_exit.

Try running this example:

section .data
    msg db "Hello, Syscall!", 0xa ; Our string + newline
    len equ $ - msg             ; Length of our string

section .text
    global _start

_start:
    ; sys_write(fd=1, buf=msg, count=len)
    mov rax, 1      ; syscall number for sys_write
    mov rdi, 1      ; fd=1 (stdout)
    mov rsi, msg    ; buffer (our string)
    mov rdx, len    ; count (length of string)
    syscall         ; Invoke kernel

    ; sys_exit(status=0)
    mov rax, 60     ; syscall number for sys_exit
    mov rdi, 0      ; exit status 0
    syscall         ; Invoke kernel

Basic File I/O: sys_read

The counterpart to sys_write is sys_read, which reads data from a file descriptor into a buffer. Its parameters are:

  • RDI: File descriptor (e.g., 0 for stdin).
  • RSI: Pointer to the buffer to store data.
  • RDX: Maximum number of bytes to read.

sys_read returns the number of bytes actually read, or an error code.

Echoing Input Example

Here's a program that reads up to 256 bytes from standard input (stdin) and then writes whatever it read back to standard output (stdout).

Try running this example:

section .bss
    buffer resb 256 ; A buffer to store input

section .text
    global _start

_start:
    ; sys_read(fd=0, buf=buffer, count=256)
    mov rax, 0      ; syscall number for sys_read
    mov rdi, 0      ; fd=0 (stdin)
    mov rsi, buffer ; buffer to store input
    mov rdx, 256    ; max bytes to read
    syscall         ; Invoke kernel
    mov rbp, rax    ; Store bytes read in rbp

    ; sys_write(fd=1, buf=buffer, count=rbp)
    mov rax, 1      ; syscall number for sys_write
    mov rdi, 1      ; fd=1 (stdout)
    mov rsi, buffer ; buffer (our read input)
    mov rdx, rbp    ; count (actual bytes read)
    syscall         ; Invoke kernel

    ; sys_exit(status=0)
    mov rax, 60     ; syscall number for sys_exit
    mov rdi, 0      ; exit status 0
    syscall         ; Invoke kernel

Syscall Arguments Check

Let's quickly check your understanding of how arguments are passed for x86-64 Linux system calls.

Recap: Linux System Calls

You've learned the basics of Linux system calls!

  • Syscalls are how user programs request kernel services.
  • The syscall instruction (x86-64) initiates the call.
  • RAX holds the syscall number, and RDI-R9 hold arguments.
  • We explored sys_write (to stdout), sys_read (from stdin), and sys_exit.

Mastering syscalls is key to understanding low-level Linux programming and operating system interaction.

Часто задаваемые вопросы

Урок «Системные вызовы Linux (syscalls)» бесплатный?

Да — полный текст урока «Системные вызовы Linux (syscalls)» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Assembly Language & x86 Low-Level Systems Programming, подпишись на CoddyKit PRO. Курс Assembly Language & x86 Low-Level Systems Programming содержит 4 уроков всего.

Чему я научусь в уроке «Системные вызовы Linux (syscalls)»?

Научитесь выполнять распространённые операции операционной системы, такие как ввод-вывод файлов, управление процессами и выделение памяти, используя системные вызовы Linux. Ты практикуешь Assembly Language & x86 Low-Level Systems Programming с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Assembly Language & x86 Low-Level Systems Programming?

Предыдущий опыт не требуется. Assembly Language & x86 Low-Level Systems Programming на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.

Сколько времени занимает урок «Системные вызовы Linux (syscalls)»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Assembly Language & x86 Low-Level Systems Programming?

Да. Каждый урок Assembly Language & x86 Low-Level Systems Programming включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Основы виртуальной памяти
  2. Системные вызовы Linux (syscalls)
  3. Взаимодействие с Windows API
  4. Динамическая память: выделение памяти в ассемблере
← Назад к Assembly Language & x86 Low-Level Systems Programming