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