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