xref: /DragonOS/kernel/src/syscall/mod.rs (revision e92d02281005bac31fe80e9070ac4a2a6cef0419)
1 use core::{
2     ffi::{c_char, c_int, c_void, CStr},
3     sync::atomic::{AtomicBool, Ordering},
4 };
5 
6 use num_traits::{FromPrimitive, ToPrimitive};
7 
8 use crate::{
9     arch::{cpu::cpu_reset, MMArch},
10     filesystem::vfs::{
11         fcntl::FcntlCommand,
12         file::FileMode,
13         syscall::{PosixKstat, SEEK_CUR, SEEK_END, SEEK_MAX, SEEK_SET},
14         MAX_PATHLEN,
15     },
16     include::bindings::bindings::{pid_t, PAGE_2M_SIZE, PAGE_4K_SIZE},
17     io::SeekFrom,
18     kinfo,
19     libs::align::page_align_up,
20     mm::{verify_area, MemoryManagementArch, VirtAddr},
21     net::syscall::SockAddr,
22     time::{
23         syscall::{PosixTimeZone, PosixTimeval},
24         TimeSpec,
25     },
26 };
27 
28 use self::user_access::UserBufferWriter;
29 
30 pub mod user_access;
31 
32 #[repr(i32)]
33 #[derive(Debug, FromPrimitive, ToPrimitive, PartialEq, Eq, Clone)]
34 #[allow(dead_code, non_camel_case_types)]
35 pub enum SystemError {
36     EPERM = 1,
37     /// 没有指定的文件或目录 No such file or directory.
38     ENOENT = 2,
39     /// 没有这样的进程 No such process.
40     ESRCH = 3,
41     /// 被中断的函数 Interrupted function.
42     EINTR = 4,
43     /// I/O错误 I/O error.
44     EIO = 5,
45     /// 没有这样的设备或地址 No such device or address.
46     ENXIO = 6,
47     /// 参数列表过长,或者在输出buffer中缺少空间 或者参数比系统内建的最大值要大 Argument list too long.
48     E2BIG = 7,
49     /// 可执行文件格式错误 Executable file format error
50     ENOEXEC = 8,
51     /// 错误的文件描述符 Bad file descriptor.
52     EBADF = 9,
53     /// 没有子进程 No child processes.
54     ECHILD = 10,
55     /// 资源不可用,请重试。 Resource unavailable, try again.(may be the same value as [EWOULDBLOCK])
56     ///
57     /// 操作将被禁止 Operation would block.(may be the same value as [EAGAIN]).
58     EAGAIN_OR_EWOULDBLOCK = 11,
59     /// 没有足够的空间 Not enough space.
60     ENOMEM = 12,
61     /// 访问被拒绝 Permission denied
62     EACCES = 13,
63     /// 错误的地址 Bad address
64     EFAULT = 14,
65     /// 需要块设备 Block device required
66     ENOTBLK = 15,
67     /// 设备或资源忙 Device or resource busy.
68     EBUSY = 16,
69     /// 文件已存在 File exists.
70     EEXIST = 17,
71     /// 跨设备连接 Cross-device link.
72     EXDEV = 18,
73     /// 没有指定的设备 No such device.
74     ENODEV = 19,
75     /// 不是目录 Not a directory.
76     ENOTDIR = 20,
77     /// 是一个目录 Is a directory
78     EISDIR = 21,
79     /// 不可用的参数 Invalid argument.
80     EINVAL = 22,
81     /// 系统中打开的文件过多 Too many files open in system.
82     ENFILE = 23,
83     /// 文件描述符的值过大 File descriptor value too large.
84     EMFILE = 24,
85     /// 不正确的I/O控制操作 Inappropriate I/O control operation.
86     ENOTTY = 25,
87     /// 文本文件忙 Text file busy.
88     ETXTBSY = 26,
89     /// 文件太大 File too large.
90     EFBIG = 27,
91     /// 设备上没有空间 No space left on device.
92     ENOSPC = 28,
93     /// 错误的寻道.当前文件是pipe,不允许seek请求  Invalid seek.
94     ESPIPE = 29,
95     /// 只读的文件系统 Read-only file system.
96     EROFS = 30,
97     /// 链接数过多 Too many links.
98     EMLINK = 31,
99     /// 断开的管道 Broken pipe.
100     EPIPE = 32,
101     /// 数学参数超出作用域 Mathematics argument out of domain of function.
102     EDOM = 33,
103     /// 结果过大 Result too large.
104     ERANGE = 34,
105     /// 资源死锁将要发生 Resource deadlock would occur.
106     EDEADLK = 35,
107     /// 文件名过长 Filename too long.
108     ENAMETOOLONG = 36,
109     /// 没有可用的锁 No locks available.
110     ENOLCK = 37,
111     /// 功能不支持 Function not supported.
112     ENOSYS = 38,
113     /// 目录非空 Directory not empty.
114     ENOTEMPTY = 39,
115     /// 符号链接级别过多 Too many levels of symbolic links.
116     ELOOP = 40,
117     /// 没有期待类型的消息 No message of the desired type.
118     ENOMSG = 41,
119     /// 标志符被移除 Identifier removed.
120     EIDRM = 42,
121     /// 通道号超出范围 Channel number out of range
122     ECHRNG = 43,
123     /// 二级不同步 Level 2 not synchronized
124     EL2NSYNC = 44,
125     /// 三级暂停 Level 3 halted
126     EL3HLT = 45,
127     /// 三级重置 Level 3 reset
128     EL3RST = 46,
129     /// 链接号超出范围 Link number out of range
130     ELNRNG = 47,
131     /// 未连接协议驱动程序 Protocol driver not attached
132     EUNATCH = 48,
133     /// 没有可用的CSI结构 No CSI structure available
134     ENOCSI = 49,
135     /// 二级暂停 Level 2 halted
136     EL2HLT = 50,
137     /// 无效交换 Invalid exchange
138     EBADE = 51,
139     /// 无效的请求描述符 Invalid request descriptor
140     EBADR = 52,
141     /// 交换满 Exchange full
142     EXFULL = 53,
143     /// 无阳极 No anode
144     ENOANO = 54,
145     /// 请求码无效 Invalid request code
146     EBADRQC = 55,
147     /// 无效插槽 Invalid slot
148     EBADSLT = 56,
149     /// 资源死锁 Resource deadlock would occur
150     EDEADLOCK = 57,
151     /// 错误的字体文件格式 Bad font file format
152     EBFONT = 58,
153     /// 不是STREAM Not a STREAM
154     ENOSTR = 59,
155     /// 队列头没有可读取的消息 No message is available on the STREAM head read queue.
156     ENODATA = 60,
157     /// 流式ioctl()超时 Stream ioctl() timeout
158     ETIME = 61,
159     /// 没有STREAM资源  No STREAM resources.
160     ENOSR = 62,
161     /// 机器不在网络上 Machine is not on the network
162     ENONET = 63,
163     /// 未安装软件包 Package not installed
164     ENOPKG = 64,
165     /// 远程对象 Object is remote
166     EREMOTE = 65,
167     /// 保留 Reserved.
168     ENOLINK = 66,
169     /// 外设错误 Advertise error.
170     EADV = 67,
171     /// 安装错误 Srmount error
172     ESRMNT = 68,
173     /// 发送时发生通信错误 Communication error on send
174     ECOMM = 69,
175     /// 协议错误 Protocol error.
176     EPROTO = 70,
177     /// 保留使用 Reserved.
178     EMULTIHOP = 71,
179     /// RFS特定错误 RFS specific error
180     EDOTDOT = 72,
181     /// 错误的消息 Bad message.
182     EBADMSG = 73,
183     /// 数值过大,产生溢出 Value too large to be stored in data type.
184     EOVERFLOW = 74,
185     /// 名称在网络上不是唯一的 Name not unique on network
186     ENOTUNIQ = 75,
187     /// 处于不良状态的文件描述符 File descriptor in bad state
188     EBADFD = 76,
189     /// 远程地址已更改 Remote address changed
190     EREMCHG = 77,
191     /// 无法访问所需的共享库 Can not access a needed shared library
192     ELIBACC = 78,
193     /// 访问损坏的共享库 Accessing a corrupted shared library
194     ELIBBAD = 79,
195     /// a. out中的.lib部分已损坏 .lib section in a.out corrupted
196     ELIBSCN = 80,
197     /// 尝试链接太多共享库 Attempting to link in too many shared libraries
198     ELIBMAX = 81,
199     /// 无法直接执行共享库 Cannot exec a shared library directly
200     ELIBEXEC = 82,
201     /// 不合法的字符序列 Illegal byte sequence.
202     EILSEQ = 83,
203     /// 中断的系统调用应该重新启动 Interrupted system call should be restarted
204     ERESTART = 84,
205     /// 流管道错误 Streams pipe error
206     ESTRPIPE = 85,
207     /// 用户太多 Too many users
208     EUSERS = 86,
209     /// 不是一个套接字 Not a socket.
210     ENOTSOCK = 87,
211     /// 需要目标地址 Destination address required.
212     EDESTADDRREQ = 88,
213     /// 消息过大 Message too large.
214     EMSGSIZE = 89,
215     /// 对于套接字而言,错误的协议 Protocol wrong type for socket.
216     EPROTOTYPE = 90,
217     /// 协议不可用 Protocol not available.
218     ENOPROTOOPT = 91,
219     /// 协议不被支持 Protocol not supported.
220     EPROTONOSUPPORT = 92,
221     /// 不支持套接字类型 Socket type not supported
222     ESOCKTNOSUPPORT = 93,
223     /// 套接字不支持该操作 Operation not supported on socket (may be the same value as [ENOTSUP]).
224     ///
225     /// 不被支持 Not supported (may be the same value as [EOPNOTSUPP]).
226     EOPNOTSUPP_OR_ENOTSUP = 94,
227     /// 不支持协议系列 Protocol family not supported
228     EPFNOSUPPORT = 95,
229     /// 地址family不支持 Address family not supported.
230     EAFNOSUPPORT = 96,
231     /// 地址正在被使用 Address in use.
232     EADDRINUSE = 97,
233     /// 地址不可用 Address  not available.
234     EADDRNOTAVAIL = 98,
235     /// 网络已关闭 Network is down.
236     ENETDOWN = 99,
237     /// 网络不可达 Network unreachable.
238     ENETUNREACH = 100,
239     /// 网络连接已断开 Connection aborted by network.
240     ENETRESET = 101,
241     /// 连接已断开 Connection aborted.
242     ECONNABORTED = 102,
243     /// 连接被重置 Connection reset.
244     ECONNRESET = 103,
245     /// 缓冲区空间不足 No buffer space available.
246     ENOBUFS = 104,
247     /// 套接字已连接 Socket is connected.
248     EISCONN = 105,
249     /// 套接字未连接 The socket is not connected.
250     ENOTCONN = 106,
251     /// 传输端点关闭后无法发送 Cannot send after transport endpoint shutdown
252     ESHUTDOWN = 107,
253     /// 引用太多:无法拼接 Too many references: cannot splice
254     ETOOMANYREFS = 108,
255     /// 连接超时 Connection timed out.
256     ETIMEDOUT = 109,
257     /// 连接被拒绝 Connection refused.
258     ECONNREFUSED = 110,
259     /// 主机已关闭 Host is down
260     EHOSTDOWN = 111,
261     /// 主机不可达 Host is unreachable.
262     EHOSTUNREACH = 112,
263     /// 连接已经在处理 Connection already in progress.
264     EALREADY = 113,
265     /// 操作正在处理 Operation in progress.
266     EINPROGRESS = 114,
267     /// 保留 Reserved.
268     ESTALE = 115,
269     /// 结构需要清理 Structure needs cleaning
270     EUCLEAN = 116,
271     /// 不是XENIX命名类型文件 Not a XENIX named type file
272     ENOTNAM = 117,
273     /// 没有可用的XENIX信号量 No XENIX semaphores available
274     ENAVAIL = 118,
275     /// 是命名类型文件 Is a named type file
276     EISNAM = 119,
277     /// 远程I/O错误 Remote I/O error
278     EREMOTEIO = 120,
279     /// 保留使用 Reserved
280     EDQUOT = 121,
281     /// 没有找到媒介 No medium found
282     ENOMEDIUM = 122,
283     /// 介质类型错误 Wrong medium type
284     EMEDIUMTYPE = 123,
285     /// 操作被取消 Operation canceled.
286     ECANCELED = 124,
287     /// 所需的密钥不可用 Required key not available
288     ENOKEY = 125,
289     /// 密钥已过期 Key has expired
290     EKEYEXPIRED = 126,
291     /// 密钥已被撤销 Key has been revoked
292     EKEYREVOKED = 127,
293     /// 密钥被服务拒绝 Key has been revoked
294     EKEYREJECTED = 128,
295     /// 之前的拥有者挂了 Previous owner died.
296     EOWNERDEAD = 129,
297     /// 状态不可恢复 State not recoverable.
298     ENOTRECOVERABLE = 130,
299 }
300 
301 impl SystemError {
302     /// @brief 把posix错误码转换为系统错误枚举类型。
303     pub fn from_posix_errno(errno: i32) -> Option<SystemError> {
304         // posix 错误码是小于0的
305         if errno >= 0 {
306             return None;
307         }
308         return <Self as FromPrimitive>::from_i32(-errno);
309     }
310 
311     /// @brief 把系统错误枚举类型转换为负数posix错误码。
312     pub fn to_posix_errno(&self) -> i32 {
313         return -<Self as ToPrimitive>::to_i32(self).unwrap();
314     }
315 }
316 
317 // 定义系统调用号
318 pub const SYS_PUT_STRING: usize = 1;
319 pub const SYS_OPEN: usize = 2;
320 pub const SYS_CLOSE: usize = 3;
321 pub const SYS_READ: usize = 4;
322 pub const SYS_WRITE: usize = 5;
323 pub const SYS_LSEEK: usize = 6;
324 pub const SYS_FORK: usize = 7;
325 pub const SYS_VFORK: usize = 8;
326 pub const SYS_BRK: usize = 9;
327 pub const SYS_SBRK: usize = 10;
328 
329 pub const SYS_REBOOT: usize = 11;
330 pub const SYS_CHDIR: usize = 12;
331 pub const SYS_GET_DENTS: usize = 13;
332 pub const SYS_EXECVE: usize = 14;
333 pub const SYS_WAIT4: usize = 15;
334 pub const SYS_EXIT: usize = 16;
335 pub const SYS_MKDIR: usize = 17;
336 pub const SYS_NANOSLEEP: usize = 18;
337 /// todo: 该系统调用与Linux不一致,将来需要删除该系统调用!!! 删的时候记得改C版本的libc
338 pub const SYS_CLOCK: usize = 19;
339 pub const SYS_PIPE: usize = 20;
340 /// 系统调用21曾经是SYS_MSTAT,但是现在已经废弃
341 pub const __NOT_USED: usize = 21;
342 pub const SYS_UNLINK_AT: usize = 22;
343 pub const SYS_KILL: usize = 23;
344 pub const SYS_SIGACTION: usize = 24;
345 pub const SYS_RT_SIGRETURN: usize = 25;
346 pub const SYS_GETPID: usize = 26;
347 pub const SYS_SCHED: usize = 27;
348 pub const SYS_DUP: usize = 28;
349 pub const SYS_DUP2: usize = 29;
350 pub const SYS_SOCKET: usize = 30;
351 
352 pub const SYS_SETSOCKOPT: usize = 31;
353 pub const SYS_GETSOCKOPT: usize = 32;
354 pub const SYS_CONNECT: usize = 33;
355 pub const SYS_BIND: usize = 34;
356 pub const SYS_SENDTO: usize = 35;
357 pub const SYS_RECVFROM: usize = 36;
358 pub const SYS_RECVMSG: usize = 37;
359 pub const SYS_LISTEN: usize = 38;
360 pub const SYS_SHUTDOWN: usize = 39;
361 pub const SYS_ACCEPT: usize = 40;
362 
363 pub const SYS_GETSOCKNAME: usize = 41;
364 pub const SYS_GETPEERNAME: usize = 42;
365 pub const SYS_GETTIMEOFDAY: usize = 43;
366 pub const SYS_MMAP: usize = 44;
367 pub const SYS_MUNMAP: usize = 45;
368 
369 pub const SYS_MPROTECT: usize = 46;
370 pub const SYS_FSTAT: usize = 47;
371 #[allow(dead_code)]
372 pub const SYS_GETCWD: usize = 48;
373 #[allow(dead_code)]
374 pub const SYS_GETPPID: usize = 49;
375 #[allow(dead_code)]
376 pub const SYS_GETPGID: usize = 50;
377 
378 pub const SYS_FCNTL: usize = 51;
379 pub const SYS_FTRUNCATE: usize = 52;
380 
381 #[derive(Debug)]
382 pub struct Syscall;
383 
384 extern "C" {
385     fn do_put_string(s: *const u8, front_color: u32, back_color: u32) -> usize;
386 }
387 
388 #[no_mangle]
389 pub extern "C" fn syscall_init() -> i32 {
390     kinfo!("Initializing syscall...");
391     Syscall::init().expect("syscall init failed");
392     kinfo!("Syscall init successfully!");
393     return 0;
394 }
395 
396 impl Syscall {
397     /// 初始化系统调用
398     pub fn init() -> Result<(), SystemError> {
399         static INIT_FLAG: AtomicBool = AtomicBool::new(false);
400         let prev = INIT_FLAG.swap(true, Ordering::SeqCst);
401         if prev {
402             panic!("Cannot initialize syscall more than once!");
403         }
404         return crate::arch::syscall::arch_syscall_init();
405     }
406     /// @brief 系统调用分发器,用于分发系统调用。
407     ///
408     /// 这个函数内,需要根据系统调用号,调用对应的系统调用处理函数。
409     /// 并且,对于用户态传入的指针参数,需要在本函数内进行越界检查,防止访问到内核空间。
410     pub fn handle(syscall_num: usize, args: &[usize], from_user: bool) -> usize {
411         let r = match syscall_num {
412             SYS_PUT_STRING => {
413                 Self::put_string(args[0] as *const u8, args[1] as u32, args[2] as u32)
414             }
415             SYS_OPEN => {
416                 let path: &CStr = unsafe { CStr::from_ptr(args[0] as *const c_char) };
417                 let path: Result<&str, core::str::Utf8Error> = path.to_str();
418                 let res = if path.is_err() {
419                     Err(SystemError::EINVAL)
420                 } else {
421                     let path: &str = path.unwrap();
422                     let flags = args[1];
423                     let open_flags: FileMode = FileMode::from_bits_truncate(flags as u32);
424 
425                     Self::open(path, open_flags)
426                 };
427 
428                 res
429             }
430             SYS_CLOSE => {
431                 let fd = args[0];
432                 Self::close(fd)
433             }
434             SYS_READ => {
435                 let fd = args[0] as i32;
436                 let buf_vaddr = args[1];
437                 let len = args[2];
438                 let virt_addr = VirtAddr::new(buf_vaddr);
439                 // 判断缓冲区是否来自用户态,进行权限校验
440                 let res = if from_user && verify_area(virt_addr, len as usize).is_err() {
441                     // 来自用户态,而buffer在内核态,这样的操作不被允许
442                     Err(SystemError::EPERM)
443                 } else {
444                     let buf: &mut [u8] = unsafe {
445                         core::slice::from_raw_parts_mut::<'static, u8>(buf_vaddr as *mut u8, len)
446                     };
447 
448                     Self::read(fd, buf)
449                 };
450                 // kdebug!("sys read, fd: {}, len: {}, res: {:?}", fd, len, res);
451                 res
452             }
453             SYS_WRITE => {
454                 let fd = args[0] as i32;
455                 let buf_vaddr = args[1];
456                 let len = args[2];
457                 let virt_addr = VirtAddr::new(buf_vaddr);
458                 // 判断缓冲区是否来自用户态,进行权限校验
459                 let res = if from_user && verify_area(virt_addr, len as usize).is_err() {
460                     // 来自用户态,而buffer在内核态,这样的操作不被允许
461                     Err(SystemError::EPERM)
462                 } else {
463                     let buf: &[u8] = unsafe {
464                         core::slice::from_raw_parts::<'static, u8>(buf_vaddr as *const u8, len)
465                     };
466 
467                     Self::write(fd, buf)
468                 };
469 
470                 // kdebug!("sys write, fd: {}, len: {}, res: {:?}", fd, len, res);
471 
472                 res
473             }
474 
475             SYS_LSEEK => {
476                 let fd = args[0] as i32;
477                 let offset = args[1] as i64;
478                 let whence = args[2] as u32;
479 
480                 let w = match whence {
481                     SEEK_SET => Ok(SeekFrom::SeekSet(offset)),
482                     SEEK_CUR => Ok(SeekFrom::SeekCurrent(offset)),
483                     SEEK_END => Ok(SeekFrom::SeekEnd(offset)),
484                     SEEK_MAX => Ok(SeekFrom::SeekEnd(0)),
485                     _ => Err(SystemError::EINVAL),
486                 };
487 
488                 let res = if w.is_err() {
489                     Err(w.unwrap_err())
490                 } else {
491                     let w = w.unwrap();
492                     Self::lseek(fd, w)
493                 };
494                 // kdebug!("sys lseek, fd: {}, offset: {}, whence: {}, res: {:?}", fd, offset, whence, res);
495 
496                 res
497             }
498 
499             SYS_BRK => {
500                 let new_brk = VirtAddr::new(args[0]);
501                 Self::brk(new_brk).map(|vaddr| vaddr.data())
502             }
503 
504             SYS_SBRK => {
505                 let increment = args[0] as isize;
506                 Self::sbrk(increment).map(|vaddr| vaddr.data())
507             }
508 
509             SYS_REBOOT => Self::reboot(),
510 
511             SYS_CHDIR => {
512                 // Closure for checking arguments
513                 let chdir_check = |arg0: usize| {
514                     if arg0 == 0 {
515                         return Err(SystemError::EFAULT);
516                     }
517                     let path_ptr = arg0 as *const c_char;
518                     let virt_addr = VirtAddr::new(path_ptr as usize);
519                     // 权限校验
520                     if path_ptr.is_null()
521                         || (from_user && verify_area(virt_addr, PAGE_2M_SIZE as usize).is_err())
522                     {
523                         return Err(SystemError::EINVAL);
524                     }
525                     let dest_path: &CStr = unsafe { CStr::from_ptr(path_ptr) };
526                     let dest_path: &str = dest_path.to_str().map_err(|_| SystemError::EINVAL)?;
527                     if dest_path.len() == 0 {
528                         return Err(SystemError::EINVAL);
529                     } else if dest_path.len() > PAGE_4K_SIZE as usize {
530                         return Err(SystemError::ENAMETOOLONG);
531                     }
532 
533                     return Ok(dest_path);
534                 };
535 
536                 let r: Result<&str, SystemError> = chdir_check(args[0]);
537                 if r.is_err() {
538                     Err(r.unwrap_err())
539                 } else {
540                     Self::chdir(r.unwrap())
541                 }
542             }
543 
544             SYS_GET_DENTS => {
545                 let fd = args[0] as i32;
546                 let buf_vaddr = args[1];
547                 let len = args[2];
548                 let virt_addr = VirtAddr::new(buf_vaddr);
549                 // 判断缓冲区是否来自用户态,进行权限校验
550                 let res = if from_user && verify_area(virt_addr, len as usize).is_err() {
551                     // 来自用户态,而buffer在内核态,这样的操作不被允许
552                     Err(SystemError::EPERM)
553                 } else if buf_vaddr == 0 {
554                     Err(SystemError::EFAULT)
555                 } else {
556                     let buf: &mut [u8] = unsafe {
557                         core::slice::from_raw_parts_mut::<'static, u8>(buf_vaddr as *mut u8, len)
558                     };
559                     Self::getdents(fd, buf)
560                 };
561 
562                 res
563             }
564 
565             SYS_EXECVE => {
566                 let path_ptr = args[0];
567                 let argv_ptr = args[1];
568                 let env_ptr = args[2];
569                 let virt_path_ptr = VirtAddr::new(path_ptr);
570                 let virt_argv_ptr = VirtAddr::new(argv_ptr);
571                 let virt_env_ptr = VirtAddr::new(env_ptr);
572                 // 权限校验
573                 if from_user
574                     && (verify_area(virt_path_ptr, PAGE_4K_SIZE as usize).is_err()
575                         || verify_area(virt_argv_ptr, PAGE_4K_SIZE as usize).is_err())
576                     || verify_area(virt_env_ptr, PAGE_4K_SIZE as usize).is_err()
577                 {
578                     Err(SystemError::EFAULT)
579                 } else {
580                     Self::execve(
581                         path_ptr as *const c_void,
582                         argv_ptr as *const *const c_void,
583                         env_ptr as *const *const c_void,
584                     )
585                 }
586             }
587             SYS_WAIT4 => {
588                 let pid = args[0] as pid_t;
589                 let wstatus = args[1] as *mut c_int;
590                 let options = args[2] as c_int;
591                 let rusage = args[3] as *mut c_void;
592                 let virt_wstatus = VirtAddr::new(wstatus as usize);
593                 let virt_rusage = VirtAddr::new(rusage as usize);
594                 // 权限校验
595                 // todo: 引入rusage之后,更正以下权限校验代码中,rusage的大小
596                 if from_user
597                     && (verify_area(virt_wstatus, core::mem::size_of::<c_int>() as usize).is_err()
598                         || verify_area(virt_rusage, PAGE_4K_SIZE as usize).is_err())
599                 {
600                     Err(SystemError::EFAULT)
601                 } else {
602                     Self::wait4(pid, wstatus, options, rusage)
603                 }
604             }
605 
606             SYS_EXIT => {
607                 let exit_code = args[0];
608                 Self::exit(exit_code)
609             }
610             SYS_MKDIR => {
611                 let path_ptr = args[0] as *const c_char;
612                 let mode = args[1];
613                 let virt_path_ptr = VirtAddr::new(path_ptr as usize);
614                 let security_check = || {
615                     if path_ptr.is_null()
616                         || (from_user && verify_area(virt_path_ptr, PAGE_2M_SIZE as usize).is_err())
617                     {
618                         return Err(SystemError::EINVAL);
619                     }
620                     let path: &CStr = unsafe { CStr::from_ptr(path_ptr) };
621                     let path: &str = path.to_str().map_err(|_| SystemError::EINVAL)?.trim();
622 
623                     if path == "" {
624                         return Err(SystemError::EINVAL);
625                     }
626                     return Ok(path);
627                 };
628 
629                 let path = security_check();
630                 if path.is_err() {
631                     Err(path.unwrap_err())
632                 } else {
633                     Self::mkdir(path.unwrap(), mode)
634                 }
635             }
636 
637             SYS_NANOSLEEP => {
638                 let req = args[0] as *const TimeSpec;
639                 let rem = args[1] as *mut TimeSpec;
640                 let virt_req = VirtAddr::new(req as usize);
641                 let virt_rem = VirtAddr::new(rem as usize);
642                 if from_user
643                     && (verify_area(virt_req, core::mem::size_of::<TimeSpec>() as usize).is_err()
644                         || verify_area(virt_rem, core::mem::size_of::<TimeSpec>() as usize)
645                             .is_err())
646                 {
647                     Err(SystemError::EFAULT)
648                 } else {
649                     Self::nanosleep(req, rem)
650                 }
651             }
652 
653             SYS_CLOCK => Self::clock(),
654             SYS_PIPE => {
655                 let pipefd = args[0] as *mut c_int;
656                 match UserBufferWriter::new(
657                     pipefd,
658                     core::mem::size_of::<[c_int; 2]>() as usize,
659                     from_user,
660                 ) {
661                     Err(e) => Err(e),
662                     Ok(mut user_buffer) => match user_buffer.buffer::<i32>(0) {
663                         Err(e) => Err(e),
664                         Ok(pipefd) => Self::pipe(pipefd),
665                     },
666                 }
667             }
668 
669             SYS_UNLINK_AT => {
670                 let dirfd = args[0] as i32;
671                 let pathname = args[1] as *const c_char;
672                 let flags = args[2] as u32;
673                 let virt_pathname = VirtAddr::new(pathname as usize);
674                 if from_user && verify_area(virt_pathname, PAGE_4K_SIZE as usize).is_err() {
675                     Err(SystemError::EFAULT)
676                 } else if pathname.is_null() {
677                     Err(SystemError::EFAULT)
678                 } else {
679                     let get_path = || {
680                         let pathname: &CStr = unsafe { CStr::from_ptr(pathname) };
681 
682                         let pathname: &str = pathname.to_str().map_err(|_| SystemError::EINVAL)?;
683                         if pathname.len() >= MAX_PATHLEN {
684                             return Err(SystemError::ENAMETOOLONG);
685                         }
686                         return Ok(pathname.trim());
687                     };
688                     let pathname = get_path();
689                     if pathname.is_err() {
690                         Err(pathname.unwrap_err())
691                     } else {
692                         // kdebug!("sys unlinkat: dirfd: {}, pathname: {}", dirfd, pathname.as_ref().unwrap());
693                         Self::unlinkat(dirfd, pathname.unwrap(), flags)
694                     }
695                 }
696             }
697             SYS_KILL => {
698                 let pid = args[0] as pid_t;
699                 let sig = args[1] as c_int;
700 
701                 Self::kill(pid, sig)
702             }
703 
704             SYS_SIGACTION => {
705                 let sig = args[0] as c_int;
706                 let act = args[1];
707                 let old_act = args[2];
708                 Self::sigaction(sig, act, old_act, from_user)
709             }
710 
711             SYS_RT_SIGRETURN => {
712                 // 由于目前signal机制的实现,与x86_64强关联,因此暂时在arch/x86_64/syscall.rs中调用
713                 // todo: 未来需要将signal机制与平台解耦
714                 todo!()
715             }
716 
717             SYS_GETPID => Self::getpid(),
718 
719             SYS_SCHED => Self::sched(from_user),
720             SYS_DUP => {
721                 let oldfd: i32 = args[0] as c_int;
722                 Self::dup(oldfd)
723             }
724             SYS_DUP2 => {
725                 let oldfd: i32 = args[0] as c_int;
726                 let newfd: i32 = args[1] as c_int;
727                 Self::dup2(oldfd, newfd)
728             }
729 
730             SYS_SOCKET => Self::socket(args[0], args[1], args[2]),
731             SYS_SETSOCKOPT => {
732                 let optval = args[3] as *const u8;
733                 let optlen = args[4] as usize;
734                 let virt_optval = VirtAddr::new(optval as usize);
735                 // 验证optval的地址是否合法
736                 if verify_area(virt_optval, optlen as usize).is_err() {
737                     // 地址空间超出了用户空间的范围,不合法
738                     Err(SystemError::EFAULT)
739                 } else {
740                     let data: &[u8] = unsafe { core::slice::from_raw_parts(optval, optlen) };
741                     Self::setsockopt(args[0], args[1], args[2], data)
742                 }
743             }
744             SYS_GETSOCKOPT => {
745                 let optval = args[3] as *mut u8;
746                 let optlen = args[4] as *mut usize;
747                 let virt_optval = VirtAddr::new(optval as usize);
748                 let virt_optlen = VirtAddr::new(optlen as usize);
749                 let security_check = || {
750                     // 验证optval的地址是否合法
751                     if verify_area(virt_optval, PAGE_4K_SIZE as usize).is_err() {
752                         // 地址空间超出了用户空间的范围,不合法
753                         return Err(SystemError::EFAULT);
754                     }
755 
756                     // 验证optlen的地址是否合法
757                     if verify_area(virt_optlen, core::mem::size_of::<u32>() as usize).is_err() {
758                         // 地址空间超出了用户空间的范围,不合法
759                         return Err(SystemError::EFAULT);
760                     }
761                     return Ok(());
762                 };
763                 let r = security_check();
764                 if r.is_err() {
765                     Err(r.unwrap_err())
766                 } else {
767                     Self::getsockopt(args[0], args[1], args[2], optval, optlen as *mut u32)
768                 }
769             }
770 
771             SYS_CONNECT => {
772                 let addr = args[1] as *const SockAddr;
773                 let addrlen = args[2] as usize;
774                 let virt_addr = VirtAddr::new(addr as usize);
775                 // 验证addr的地址是否合法
776                 if verify_area(virt_addr, addrlen as usize).is_err() {
777                     // 地址空间超出了用户空间的范围,不合法
778                     Err(SystemError::EFAULT)
779                 } else {
780                     Self::connect(args[0], addr, addrlen)
781                 }
782             }
783             SYS_BIND => {
784                 let addr = args[1] as *const SockAddr;
785                 let addrlen = args[2] as usize;
786                 let virt_addr = VirtAddr::new(addr as usize);
787                 // 验证addr的地址是否合法
788                 if verify_area(virt_addr, addrlen as usize).is_err() {
789                     // 地址空间超出了用户空间的范围,不合法
790                     Err(SystemError::EFAULT)
791                 } else {
792                     Self::bind(args[0], addr, addrlen)
793                 }
794             }
795 
796             SYS_SENDTO => {
797                 let buf = args[1] as *const u8;
798                 let len = args[2] as usize;
799                 let flags = args[3] as u32;
800                 let addr = args[4] as *const SockAddr;
801                 let addrlen = args[5] as usize;
802                 let virt_buf = VirtAddr::new(buf as usize);
803                 let virt_addr = VirtAddr::new(addr as usize);
804                 // 验证buf的地址是否合法
805                 if verify_area(virt_buf, len as usize).is_err() {
806                     // 地址空间超出了用户空间的范围,不合法
807                     Err(SystemError::EFAULT)
808                 } else if verify_area(virt_addr, addrlen as usize).is_err() {
809                     // 地址空间超出了用户空间的范围,不合法
810                     Err(SystemError::EFAULT)
811                 } else {
812                     let data: &[u8] = unsafe { core::slice::from_raw_parts(buf, len) };
813                     Self::sendto(args[0], data, flags, addr, addrlen)
814                 }
815             }
816 
817             SYS_RECVFROM => {
818                 let buf = args[1] as *mut u8;
819                 let len = args[2] as usize;
820                 let flags = args[3] as u32;
821                 let addr = args[4] as *mut SockAddr;
822                 let addrlen = args[5] as *mut usize;
823                 let virt_buf = VirtAddr::new(buf as usize);
824                 let virt_addrlen = VirtAddr::new(addrlen as usize);
825                 let virt_addr = VirtAddr::new(addr as usize);
826                 let security_check = || {
827                     // 验证buf的地址是否合法
828                     if verify_area(virt_buf, len as usize).is_err() {
829                         // 地址空间超出了用户空间的范围,不合法
830                         return Err(SystemError::EFAULT);
831                     }
832 
833                     // 验证addrlen的地址是否合法
834                     if verify_area(virt_addrlen, core::mem::size_of::<u32>() as usize).is_err() {
835                         // 地址空间超出了用户空间的范围,不合法
836                         return Err(SystemError::EFAULT);
837                     }
838 
839                     if verify_area(virt_addr, core::mem::size_of::<SockAddr>() as usize).is_err() {
840                         // 地址空间超出了用户空间的范围,不合法
841                         return Err(SystemError::EFAULT);
842                     }
843                     return Ok(());
844                 };
845                 let r = security_check();
846                 if r.is_err() {
847                     Err(r.unwrap_err())
848                 } else {
849                     let buf = unsafe { core::slice::from_raw_parts_mut(buf, len) };
850                     Self::recvfrom(args[0], buf, flags, addr, addrlen as *mut u32)
851                 }
852             }
853 
854             SYS_RECVMSG => {
855                 let msg = args[1] as *mut crate::net::syscall::MsgHdr;
856                 let flags = args[2] as u32;
857                 match UserBufferWriter::new(
858                     msg,
859                     core::mem::size_of::<crate::net::syscall::MsgHdr>(),
860                     true,
861                 ) {
862                     Err(e) => Err(e),
863                     Ok(mut user_buffer_writer) => {
864                         match user_buffer_writer.buffer::<crate::net::syscall::MsgHdr>(0) {
865                             Err(e) => Err(e),
866                             Ok(buffer) => {
867                                 let msg = &mut buffer[0];
868                                 Self::recvmsg(args[0], msg, flags)
869                             }
870                         }
871                     }
872                 }
873             }
874 
875             SYS_LISTEN => Self::listen(args[0], args[1]),
876             SYS_SHUTDOWN => Self::shutdown(args[0], args[1]),
877             SYS_ACCEPT => Self::accept(args[0], args[1] as *mut SockAddr, args[2] as *mut u32),
878             SYS_GETSOCKNAME => {
879                 Self::getsockname(args[0], args[1] as *mut SockAddr, args[2] as *mut u32)
880             }
881             SYS_GETPEERNAME => {
882                 Self::getpeername(args[0], args[1] as *mut SockAddr, args[2] as *mut u32)
883             }
884             SYS_GETTIMEOFDAY => {
885                 let timeval = args[0] as *mut PosixTimeval;
886                 let timezone_ptr = args[1] as *mut PosixTimeZone;
887                 match UserBufferWriter::new(timeval, core::mem::size_of::<PosixTimeval>(), true) {
888                     Err(e) => Err(e),
889                     Ok(_) => {
890                         match UserBufferWriter::new(
891                             timezone_ptr,
892                             core::mem::size_of::<PosixTimeZone>(),
893                             true,
894                         ) {
895                             Err(e) => Err(e),
896                             Ok(_) => {
897                                 if !timeval.is_null() {
898                                     Self::gettimeofday(timeval, timezone_ptr)
899                                 } else {
900                                     Err(SystemError::EFAULT)
901                                 }
902                             }
903                         }
904                     }
905                 }
906             }
907             SYS_MMAP => {
908                 let len = page_align_up(args[1]);
909                 let virt_addr = VirtAddr::new(args[0] as usize);
910                 if verify_area(virt_addr, len as usize).is_err() {
911                     Err(SystemError::EFAULT)
912                 } else {
913                     Self::mmap(
914                         VirtAddr::new(args[0]),
915                         len,
916                         args[2],
917                         args[3],
918                         args[4] as i32,
919                         args[5],
920                     )
921                 }
922             }
923             SYS_MUNMAP => {
924                 let addr = args[0];
925                 let len = page_align_up(args[1]);
926                 if addr & MMArch::PAGE_SIZE != 0 {
927                     // The addr argument is not a multiple of the page size
928                     Err(SystemError::EINVAL)
929                 } else {
930                     Self::munmap(VirtAddr::new(addr), len)
931                 }
932             }
933             SYS_MPROTECT => {
934                 let addr = args[0];
935                 let len = page_align_up(args[1]);
936                 if addr & MMArch::PAGE_SIZE != 0 {
937                     // The addr argument is not a multiple of the page size
938                     Err(SystemError::EINVAL)
939                 } else {
940                     Self::mprotect(VirtAddr::new(addr), len, args[2])
941                 }
942             }
943 
944             SYS_FSTAT => {
945                 let fd = args[0] as i32;
946                 let kstat = args[1] as *mut PosixKstat;
947                 let vaddr = VirtAddr::new(kstat as usize);
948                 // FIXME 由于c中的verify_area与rust中的verify_area重名,所以在引入时加了前缀区分
949                 // TODO 应该将用了c版本的verify_area都改为rust的verify_area
950                 match verify_area(vaddr, core::mem::size_of::<PosixKstat>()) {
951                     Ok(_) => Self::fstat(fd, kstat),
952                     Err(e) => Err(e),
953                 }
954             }
955 
956             SYS_FCNTL => {
957                 let fd = args[0] as i32;
958                 let cmd: Option<FcntlCommand> =
959                     <FcntlCommand as FromPrimitive>::from_u32(args[1] as u32);
960                 let arg = args[2] as i32;
961                 let res = if let Some(cmd) = cmd {
962                     Self::fcntl(fd, cmd, arg)
963                 } else {
964                     Err(SystemError::EINVAL)
965                 };
966 
967                 // kdebug!("FCNTL: fd: {}, cmd: {:?}, arg: {}, res: {:?}", fd, cmd, arg, res);
968                 res
969             }
970 
971             SYS_FTRUNCATE => {
972                 let fd = args[0] as i32;
973                 let len = args[1] as usize;
974                 let res = Self::ftruncate(fd, len);
975                 // kdebug!("FTRUNCATE: fd: {}, len: {}, res: {:?}", fd, len, res);
976                 res
977             }
978 
979             _ => panic!("Unsupported syscall ID: {}", syscall_num),
980         };
981 
982         let r = r.unwrap_or_else(|e| e.to_posix_errno() as usize);
983         return r;
984     }
985 
986     pub fn put_string(
987         s: *const u8,
988         front_color: u32,
989         back_color: u32,
990     ) -> Result<usize, SystemError> {
991         return Ok(unsafe { do_put_string(s, front_color, back_color) });
992     }
993 
994     pub fn reboot() -> Result<usize, SystemError> {
995         cpu_reset();
996     }
997 }
998