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