ENع
→System calls
الدرس 02 · The kernel and system calls

System calls: crossing into the kernel

لم يُترجم بعد؛ يُعرض باللغة الإنجليزية

12 دقيقة12 خطوة5 أسئلةBeginner
عن هذا الدرس

A program cannot touch the screen, the disk or the network itself: it has to ask the kernel. That request is a system call. Follow one write() from a line of C into the C library, into the CPU's registers as a call number and three arguments, through the trap into kernel mode, through the kernel's system call table to the handler, and back with an answer. Then send a bad file descriptor and watch the kernel's -9 become -1 and errno. The lesson on user mode and kernel mode explains the two modes this builds on; the Software lesson on what an operating system does and the Hardware lesson on interrupts and I/O are good warm-ups.

ستتعلّم

حدّد ما تشعر بأنك أتقنته. هذا التقييم الذاتي لا يؤثر في درجة الدرس.

شكل 2 · تفاعلي
01 / 12

A request, not a jump

A program cannot run kernel code itself. Instead it makes a system call: a request that names a service by number, carries a few arguments, and enters the kernel through the system call entry point. The kernel does the work and sends back an answer.

the whole program (C99, POSIX):

#include <stdio.h>
#include <unistd.h>

int main(void) {
    ssize_t n, m;
    n = write(1, "hi\n", 3);
    m = write(9, "hi\n", 3);
    if (m < 0) perror("write");
    return n == 3 ? 0 : 1;
}

line 1   a write that works
line 2   the same write to a file descriptor that is not open
line 3   report the error
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. A request, not a jump

    A program cannot run kernel code itself. Instead it makes a system call: a request that names a service by number, carries a few arguments, and enters the kernel through the system call entry point. The kernel does the work and sends back an answer.

    the whole program (C99, POSIX):
    
    #include <stdio.h>
    #include <unistd.h>
    
    int main(void) {
        ssize_t n, m;
        n = write(1, "hi\n", 3);
        m = write(9, "hi\n", 3);
        if (m < 0) perror("write");
        return n == 3 ? 0 : 1;
    }
    
    line 1   a write that works
    line 2   the same write to a file descriptor that is not open
    line 3   report the error
  2. Line 1 calls the C library

    write() looks like any function, and it is one: a small function in the C library (libc), running in user mode. Its job is to turn your call into a request the kernel understands.

    line 1   n = write(1, "hi\n", 3);
             fd 1     standard output (the screen)
             "hi\n"   the bytes, in the program's memory
             3        how many bytes
    call     an ordinary call into libc   mode: user
  3. Packing the registers

    libc puts the request in CPU registers. rax gets 1, write's number on x86-64 Linux. rdi, rsi and rdx get the three arguments: file descriptor 1 (a small number naming an open file), where the bytes are, and 3. Only numbers cross over, never names.

    x86-64 Linux calling convention (syscall(2)):
      rax = 1     call number: write
      rdi = 1     argument 1: file descriptor
      rsi = buf   argument 2: address of "hi\n"
      rdx = 3     argument 3: byte count
      (r10, r8, r9 carry arguments 4 to 6)
  4. The trap instruction

    libc runs the syscall instruction. In one move the CPU switches to kernel mode and jumps to the entry point the kernel chose at boot. The entry code first saves the program's registers, so it can carry on later exactly where it was.

    syscall    mode user -> kernel
               jump to the kernel's system call entry
    entry      save the user registers
               (Linux: on the kernel stack; xv6: in the trap frame)
    the program cannot choose where it lands:
    it can only pick a number
  5. Look up the number

    The kernel reads rax, 1, and looks it up in its system call table, a list of handlers in number order. Entry 1 is write. A number with no entry is refused with an error, so a program can only reach real services.

    system call table (x86-64 Linux, first rows):
      0   read   -> sys_read
      1   write  -> sys_write
      2   open   -> sys_open
      ...
    rax = 1  ->  sys_write
    unknown number -> error (Linux: -ENOSYS; xv6: -1)
  6. Check the arguments

    The handler trusts nothing. Is file descriptor 1 in this program's table of open files? Yes, it is standard output. Is the buffer in the program's own memory? Yes, so the kernel copies the 3 bytes in safely.

    open files of this program:
      fd 0   in
      fd 1   out
      fd 2   err
    fd 1      open for writing?                 yes
    buf       inside the program's memory?      yes  (else EFAULT)
    copy      3 bytes from user memory into the kernel
  7. The kernel does the job

    Now the real work: the kernel hands h, i and a newline to the screen's driver, and hi appears. Only the kernel may touch the device, which is the whole reason the program had to ask.

    mode      kernel
    do        send 3 bytes: h  i  \n
    screen    hi
    result    3 (bytes written)
  8. The answer comes back

    The kernel writes the result, 3 bytes written, into the saved rax, restores the registers and runs sysret. The CPU drops back to user mode, after the syscall instruction. libc sees a number that is not negative and returns 3, so n = 3.

    rax       3
    sysret    mode kernel -> user
              back to the instruction after syscall
    libc      3 is not negative: return it
    line 1    n = 3
  9. Line 2: a bad request

    Line 2 makes the same call with file descriptor 9. The trip is the same: registers, trap, table, handler. But fd 9 is not in the table of open files, so the handler refuses before it does anything.

    line 2   m = write(9, "hi\n", 3);
             rax = 1   rdi = 9   rsi = buf   rdx = 3
    trap     mode user -> kernel, table entry 1: sys_write
    check    fd 9 open?   no
    answer   -EBADF = -9   (nothing is written)
  10. An error becomes errno

    The kernel returns a negative number, -9: minus EBADF, bad file descriptor. Back in user mode, libc sees it is negative. It stores 9 in the variable errno and returns -1, the C way of saying it failed. So m = -1.

    rax      -9   (= -EBADF)
    sysret   mode kernel -> user
    libc     negative, so:
               errno = 9    (EBADF, "Bad file descriptor")
               return -1
    line 2   m = -1
  11. Line 3 reports the error

    m is negative, so line 3 calls perror. It reads errno, 9, finds the message Bad file descriptor, and prints write: Bad file descriptor. To print, perror makes system calls of its own, to fd 2, standard error.

    line 3   if (m < 0) perror("write");
    errno    9  ->  "Bad file descriptor"
    prints   write: Bad file descriptor
             on fd 2, standard error (also the screen)
    errno only means something when the call reported an error
  12. Every program does this

    Every program talks to the kernel this way; in Python, os.write(1, b"hi\n") makes the same call. A number picks a handler from a table, the handler checks its arguments, and a negative answer becomes -1 plus errno.

    the path as a Python simulation:
    
    import errno
    
    open_fds = {0, 1, 2}               # this program's open files
    
    def sys_write(fd, data):           # the kernel's handler
        if fd not in open_fds:
            return -errno.EBADF        # a negative error number
        print(data, end="")            # the driver: bytes to the screen
        return len(data)
    
    table = {1: sys_write}             # the system call table (1 = write)
    
    def syscall(nr, *args):            # the trap: number -> handler
        return table[nr](*args)
    
    def write(fd, data):               # the C library wrapper
        r = syscall(1, fd, data)
        if r < 0:
            return -1, -r              # -1, and errno = -r
        return r, 0
    
    print(write(1, "hi\n"))
    print(write(9, "hi\n"))
    
    prints:
    hi
    (3, 0)
    (-1, 9)

اختبار يتاح بعد الخطوة الأخيرة.