作業系統›Ch3 System Call 與虛擬機器第 3 題/共 10 題
3. System Call、syscall、x86_64、sys_write
#OS-03-003中System Callsyscallx86_64sys_write
On x86_64 systems, the Linux system calls are made using the syscall instruction with the following calling conventions
- RAX: Contains the system call number.
- RDI, RSI, RDX, R10, R8, and R9: Are used to pass up to six arguments to the system call.
- RCX and R11: Are clobbered after the syscall instruction.
- Return Value: The return value of the system call is placed in the RAX register.
The implementation of the sys_write (write) system call in the Linux kernel is as follows.
/ fs / read_write.c
...
642
643 return ret;
644 }
645
646 SYSCALL_DEFINE3(write, unsigned int, fd, const char __user *,
647 size_t, count)
648 {
649 return ksys_write(fd, buf, count);
650 }
And, the man pages description for sys_write is as follows.
write(2) System Calls Manual write(2)
NAME
write - write to a file descriptor
LIBRARY
Standard C library (libc, -lc)
SYNOPSIS
#include <unistd.h>
ssize_t write(int fd, const void buf[.count], size_t count);
DESCRIPTION
write() writes up to count bytes from the buffer starting at buf
to the file referred to by the file descriptor fd.
The number of bytes written may be less than count if, for
example, there is insufficient space on the underlying physical
medium, or the RLIMIT_FSIZE resource limit is encountered (see
setrlimit(2)), or the call was interrupted by a signal handler
after having written less than count bytes. (See also pipe(7).)
Which of the following statement(s) is true for invoking the sys_write system call?
參考答案與解析
(a) 錯誤:RAX放的是syscall number(此處為write的編號),fd應放在RDI(第一個參數)。(b) 正確:依calling convention,第二個參數buf的位址要放在RSI。(c) 正確:man page明確指出實際寫入的bytes數可能小於count。(d) 錯誤:使用者只能透過事先定義好、有對應syscall number的system call進入核心,無法任意呼叫核心中的任何函式。
📄 交大113
▤完整推導請見《WH 資工筆記 · 作業系統》Ch3 System Call 與虛擬機器