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