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