System calls: crossing into the kernel
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
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.
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اقرأ الدرس خطوة بخطوة
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 errorLine 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: userPacking 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)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 numberLook 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)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 kernelThe 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)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 = 3Line 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)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 = -1Line 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 errorEvery 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)
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01When your C program calls write(), what code runs first?
write() is an ordinary function in the C library (libc). It puts the call number and the arguments in registers and then runs the trap instruction that enters the kernel.
02On x86-64 Linux, how does the kernel know which service the program wants?
The program only supplies a number (1 for write on x86-64 Linux). The kernel looks it up in its own table, so a program can only reach the services the kernel offers, never an address it picked.
03Why does the write handler check that file descriptor 1 is open and that the buffer is in the program's own memory?
Arguments come from user mode, so the kernel checks them all. A file descriptor that is not open gives EBADF; a buffer outside the program's memory gives EFAULT.
04write(9, "hi\n", 3) is called but file descriptor 9 is not open. What does the program see?
The Linux kernel answers -9 (minus EBADF). The C library wrapper sees a negative value, stores 9 in errno and returns -1, which is how C functions report failure.
05Which step of a system call switches the CPU from user mode to kernel mode?
Loading registers happens in user mode. The syscall instruction switches to kernel mode and jumps to the entry point the kernel chose at boot, in one move; sysret switches back.
المسرد
- System call
- A request from a program to the kernel for a service it may not do itself, such as writing to a device. It names the service by number.
- C library (libc)
- The standard library C programs call. Its wrapper functions, such as write(), turn a call into a system call.
- Register
- A small, fast storage slot inside the CPU. On x86-64 Linux a system call's number goes in rax and its first arguments in rdi, rsi and rdx.
- System call table
- The kernel's list of handlers in number order. The call number picks the entry; 1 is write on x86-64 Linux.
- Trap instruction
- The instruction that enters the kernel: it switches to kernel mode and jumps to a fixed entry point in one move. On x86-64 it is syscall; sysret goes back.
- File descriptor
- A small number naming one of a program's open files or devices. It is an index into that program's table of open files; 1 is standard output.
- errno
- A variable the C library sets to an error number when a call fails. It only means something right after a call that reported an error.
- EBADF
- The error number for a bad file descriptor: one that is not open, or not open for that use. It is 9 on Linux.
الملاحظات والمصادر
- The call number 1 for write, the registers rax, rdi, rsi and rdx, and the instructions syscall and sysret are for Linux on x86-64. Other systems use other numbers: on 64-bit ARM Linux write is 64, and xv6 on RISC-V puts the number in a7 and traps with ecall. The idea is the same everywhere.
- The table shows only the first three entries. Recent Linux kernels on x86-64 compile the table into a switch statement rather than looking it up in an array, but it does the same job: number in, handler out.
- The card shows the three lines of main() that matter; the whole program is real C99 with POSIX. Compiled and run, it prints hi on standard output and write: Bad file descriptor on standard error.
- The raw -9 is how the Linux kernel answers; the C library hides it and gives you -1 and errno = 9. On Linux and macOS EBADF is 9. errno is only meaningful right after a call that reported an error.
- The figure does not show the registers for perror's own write calls; they make the same trip as line 1, with fd 2.
- R. and A. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, ch. 6: Limited Direct Execution
- Berkeley CS162, Lecture 3 (dual-mode operation and system calls)
- R. Cox, F. Kaashoek, R. Morris, xv6: a simple, Unix-like teaching operating system (MIT 6.1810), ch. 4
- MIT 6.1810 (2024), lecture notes: System call entry/exit
- Linux man-pages: intro(2)
- Linux man-pages: syscall(2)
- Linux man-pages: write(2)
- Linux man-pages: open(2)
- Linux man-pages: errno(3)
- Linux man-pages: perror(3)
- Linux source: x86-64 system call table
- Linux source: x86-64 system call dispatch (syscall_64.c)
- Python documentation: os.write
اختبار يتاح بعد الخطوة الأخيرة.