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