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