xref: /DragonOS/kernel/src/syscall/mod.rs (revision 4f8f484930ed3c09ecf4b5b05b1dea14f7b05d8b)
1 use core::{
2     ffi::{c_char, c_int, c_void, CStr},
3     sync::atomic::{AtomicBool, Ordering},
4 };
5 
6 use crate::{
7     arch::{ipc::signal::SigSet, syscall::nr::*},
8     driver::base::device::device_number::DeviceNumber,
9     libs::{futex::constant::FutexFlag, rand::GRandFlags},
10     mm::syscall::MremapFlags,
11     net::syscall::MsgHdr,
12     process::{
13         fork::KernelCloneArgs,
14         resource::{RLimit64, RUsage},
15         ProcessManager,
16     },
17     syscall::user_access::check_and_clone_cstr,
18 };
19 
20 use num_traits::FromPrimitive;
21 use system_error::SystemError;
22 
23 use crate::{
24     arch::{cpu::cpu_reset, interrupt::TrapFrame, MMArch},
25     driver::base::block::SeekFrom,
26     filesystem::vfs::{
27         fcntl::FcntlCommand,
28         file::FileMode,
29         syscall::{ModeType, PosixKstat, SEEK_CUR, SEEK_END, SEEK_MAX, SEEK_SET},
30         MAX_PATHLEN,
31     },
32     include::bindings::bindings::{PAGE_2M_SIZE, PAGE_4K_SIZE},
33     kinfo,
34     libs::align::page_align_up,
35     mm::{verify_area, MemoryManagementArch, VirtAddr},
36     net::syscall::SockAddr,
37     process::{fork::CloneFlags, Pid},
38     time::{
39         syscall::{PosixTimeZone, PosixTimeval},
40         TimeSpec,
41     },
42 };
43 
44 use self::{
45     misc::SysInfo,
46     user_access::{UserBufferReader, UserBufferWriter},
47 };
48 
49 pub mod misc;
50 pub mod user_access;
51 
52 // 与linux不一致的调用,在linux基础上累加
53 pub const SYS_PUT_STRING: usize = 100000;
54 pub const SYS_SBRK: usize = 100001;
55 /// todo: 该系统调用与Linux不一致,将来需要删除该系统调用!!! 删的时候记得改C版本的libc
56 pub const SYS_CLOCK: usize = 100002;
57 pub const SYS_SCHED: usize = 100003;
58 
59 #[derive(Debug)]
60 pub struct Syscall;
61 
62 impl Syscall {
63     /// 初始化系统调用
64     #[inline(never)]
65     pub fn init() -> Result<(), SystemError> {
66         static INIT_FLAG: AtomicBool = AtomicBool::new(false);
67         let prev = INIT_FLAG.swap(true, Ordering::SeqCst);
68         if prev {
69             panic!("Cannot initialize syscall more than once!");
70         }
71         kinfo!("Initializing syscall...");
72         let r = crate::arch::syscall::arch_syscall_init();
73         kinfo!("Syscall init successfully!");
74 
75         return r;
76     }
77     /// @brief 系统调用分发器,用于分发系统调用。
78     ///
79     /// 这个函数内,需要根据系统调用号,调用对应的系统调用处理函数。
80     /// 并且,对于用户态传入的指针参数,需要在本函数内进行越界检查,防止访问到内核空间。
81     #[inline(never)]
82     pub fn handle(
83         syscall_num: usize,
84         args: &[usize],
85         frame: &mut TrapFrame,
86     ) -> Result<usize, SystemError> {
87         let r = match syscall_num {
88             SYS_PUT_STRING => {
89                 Self::put_string(args[0] as *const u8, args[1] as u32, args[2] as u32)
90             }
91             #[cfg(target_arch = "x86_64")]
92             SYS_OPEN => {
93                 let path: &CStr = unsafe { CStr::from_ptr(args[0] as *const c_char) };
94                 let path: Result<&str, core::str::Utf8Error> = path.to_str();
95                 let res = if path.is_err() {
96                     Err(SystemError::EINVAL)
97                 } else {
98                     let path: &str = path.unwrap();
99 
100                     let flags = args[1];
101                     let mode = args[2];
102 
103                     let open_flags: FileMode = FileMode::from_bits_truncate(flags as u32);
104                     let mode = ModeType::from_bits(mode as u32).ok_or(SystemError::EINVAL)?;
105                     Self::open(path, open_flags, mode, true)
106                 };
107                 res
108             }
109 
110             SYS_OPENAT => {
111                 let dirfd = args[0] as i32;
112                 let path: &CStr = unsafe { CStr::from_ptr(args[1] as *const c_char) };
113                 let flags = args[2];
114                 let mode = args[3];
115 
116                 let path: Result<&str, core::str::Utf8Error> = path.to_str();
117                 let res = if path.is_err() {
118                     Err(SystemError::EINVAL)
119                 } else {
120                     let path: &str = path.unwrap();
121 
122                     let open_flags: FileMode =
123                         FileMode::from_bits(flags as u32).ok_or(SystemError::EINVAL)?;
124                     let mode = ModeType::from_bits(mode as u32).ok_or(SystemError::EINVAL)?;
125                     Self::openat(dirfd, path, open_flags, mode, true)
126                 };
127                 res
128             }
129             SYS_CLOSE => {
130                 let fd = args[0];
131                 Self::close(fd)
132             }
133             SYS_READ => {
134                 let fd = args[0] as i32;
135                 let buf_vaddr = args[1];
136                 let len = args[2];
137                 let from_user = frame.from_user();
138                 let mut user_buffer_writer =
139                     UserBufferWriter::new(buf_vaddr as *mut u8, len, from_user)?;
140 
141                 let user_buf = user_buffer_writer.buffer(0)?;
142                 Self::read(fd, user_buf)
143             }
144             SYS_WRITE => {
145                 let fd = args[0] as i32;
146                 let buf_vaddr = args[1];
147                 let len = args[2];
148                 let from_user = frame.from_user();
149                 let user_buffer_reader =
150                     UserBufferReader::new(buf_vaddr as *const u8, len, from_user)?;
151 
152                 let user_buf = user_buffer_reader.read_from_user(0)?;
153                 Self::write(fd, user_buf)
154             }
155 
156             SYS_LSEEK => {
157                 let fd = args[0] as i32;
158                 let offset = args[1] as i64;
159                 let whence = args[2] as u32;
160 
161                 let w = match whence {
162                     SEEK_SET => Ok(SeekFrom::SeekSet(offset)),
163                     SEEK_CUR => Ok(SeekFrom::SeekCurrent(offset)),
164                     SEEK_END => Ok(SeekFrom::SeekEnd(offset)),
165                     SEEK_MAX => Ok(SeekFrom::SeekEnd(0)),
166                     _ => Err(SystemError::EINVAL),
167                 }?;
168 
169                 Self::lseek(fd, w)
170             }
171 
172             SYS_PREAD64 => {
173                 let fd = args[0] as i32;
174                 let buf_vaddr = args[1];
175                 let len = args[2];
176                 let offset = args[3];
177 
178                 let mut user_buffer_writer =
179                     UserBufferWriter::new(buf_vaddr as *mut u8, len, frame.from_user())?;
180                 let buf = user_buffer_writer.buffer(0)?;
181                 Self::pread(fd, buf, len, offset)
182             }
183 
184             SYS_PWRITE64 => {
185                 let fd = args[0] as i32;
186                 let buf_vaddr = args[1];
187                 let len = args[2];
188                 let offset = args[3];
189 
190                 let user_buffer_reader =
191                     UserBufferReader::new(buf_vaddr as *const u8, len, frame.from_user())?;
192 
193                 let buf = user_buffer_reader.read_from_user(0)?;
194                 Self::pwrite(fd, buf, len, offset)
195             }
196 
197             SYS_IOCTL => {
198                 let fd = args[0];
199                 let cmd = args[1];
200                 let data = args[2];
201                 Self::ioctl(fd, cmd as u32, data)
202             }
203 
204             #[cfg(target_arch = "x86_64")]
205             SYS_FORK => Self::fork(frame),
206             #[cfg(target_arch = "x86_64")]
207             SYS_VFORK => Self::vfork(frame),
208 
209             SYS_BRK => {
210                 let new_brk = VirtAddr::new(args[0]);
211                 Self::brk(new_brk).map(|vaddr| vaddr.data())
212             }
213 
214             SYS_SBRK => {
215                 let increment = args[0] as isize;
216                 Self::sbrk(increment).map(|vaddr: VirtAddr| vaddr.data())
217             }
218 
219             SYS_REBOOT => Self::reboot(),
220 
221             SYS_CHDIR => {
222                 // Closure for checking arguments
223                 let chdir_check = |arg0: usize| {
224                     if arg0 == 0 {
225                         return Err(SystemError::EFAULT);
226                     }
227                     let path_ptr = arg0 as *const c_char;
228                     let virt_addr = VirtAddr::new(path_ptr as usize);
229                     // 权限校验
230                     if path_ptr.is_null()
231                         || (frame.from_user()
232                             && verify_area(virt_addr, PAGE_2M_SIZE as usize).is_err())
233                     {
234                         return Err(SystemError::EINVAL);
235                     }
236                     let dest_path: &CStr = unsafe { CStr::from_ptr(path_ptr) };
237                     let dest_path: &str = dest_path.to_str().map_err(|_| SystemError::EINVAL)?;
238                     if dest_path.len() == 0 {
239                         return Err(SystemError::EINVAL);
240                     } else if dest_path.len() > MAX_PATHLEN as usize {
241                         return Err(SystemError::ENAMETOOLONG);
242                     }
243 
244                     return Ok(dest_path);
245                 };
246 
247                 let r = chdir_check(args[0])?;
248                 Self::chdir(r)
249             }
250 
251             #[allow(unreachable_patterns)]
252             SYS_GETDENTS64 | SYS_GETDENTS => {
253                 let fd = args[0] as i32;
254 
255                 let buf_vaddr = args[1];
256                 let len = args[2];
257                 let virt_addr: VirtAddr = VirtAddr::new(buf_vaddr);
258                 // 判断缓冲区是否来自用户态,进行权限校验
259                 let res = if frame.from_user() && verify_area(virt_addr, len as usize).is_err() {
260                     // 来自用户态,而buffer在内核态,这样的操作不被允许
261                     Err(SystemError::EPERM)
262                 } else if buf_vaddr == 0 {
263                     Err(SystemError::EFAULT)
264                 } else {
265                     let buf: &mut [u8] = unsafe {
266                         core::slice::from_raw_parts_mut::<'static, u8>(buf_vaddr as *mut u8, len)
267                     };
268                     Self::getdents(fd, buf)
269                 };
270 
271                 res
272             }
273 
274             SYS_EXECVE => {
275                 let path_ptr = args[0];
276                 let argv_ptr = args[1];
277                 let env_ptr = args[2];
278                 let virt_path_ptr = VirtAddr::new(path_ptr);
279                 let virt_argv_ptr = VirtAddr::new(argv_ptr);
280                 let virt_env_ptr = VirtAddr::new(env_ptr);
281                 // 权限校验
282                 if frame.from_user()
283                     && (verify_area(virt_path_ptr, MAX_PATHLEN as usize).is_err()
284                         || verify_area(virt_argv_ptr, PAGE_4K_SIZE as usize).is_err())
285                     || verify_area(virt_env_ptr, PAGE_4K_SIZE as usize).is_err()
286                 {
287                     Err(SystemError::EFAULT)
288                 } else {
289                     Self::execve(
290                         path_ptr as *const u8,
291                         argv_ptr as *const *const u8,
292                         env_ptr as *const *const u8,
293                         frame,
294                     )
295                     .map(|_| 0)
296                 }
297             }
298             SYS_WAIT4 => {
299                 let pid = args[0] as i32;
300                 let wstatus = args[1] as *mut i32;
301                 let options = args[2] as c_int;
302                 let rusage = args[3] as *mut c_void;
303                 // 权限校验
304                 // todo: 引入rusage之后,更正以下权限校验代码中,rusage的大小
305                 Self::wait4(pid.into(), wstatus, options, rusage)
306             }
307 
308             SYS_EXIT => {
309                 let exit_code = args[0];
310                 Self::exit(exit_code)
311             }
312             #[cfg(target_arch = "x86_64")]
313             SYS_MKDIR => {
314                 let path_ptr = args[0] as *const c_char;
315                 let mode = args[1];
316                 let virt_path_ptr = VirtAddr::new(path_ptr as usize);
317                 let security_check = || {
318                     if path_ptr.is_null()
319                         || (frame.from_user()
320                             && verify_area(virt_path_ptr, PAGE_2M_SIZE as usize).is_err())
321                     {
322                         return Err(SystemError::EINVAL);
323                     }
324                     let path: &CStr = unsafe { CStr::from_ptr(path_ptr) };
325                     let path: &str = path.to_str().map_err(|_| SystemError::EINVAL)?.trim();
326 
327                     if path == "" {
328                         return Err(SystemError::EINVAL);
329                     }
330                     return Ok(path);
331                 };
332 
333                 let path = security_check();
334                 if path.is_err() {
335                     Err(path.unwrap_err())
336                 } else {
337                     Self::mkdir(path.unwrap(), mode)
338                 }
339             }
340 
341             SYS_NANOSLEEP => {
342                 let req = args[0] as *const TimeSpec;
343                 let rem = args[1] as *mut TimeSpec;
344                 let virt_req = VirtAddr::new(req as usize);
345                 let virt_rem = VirtAddr::new(rem as usize);
346                 if frame.from_user()
347                     && (verify_area(virt_req, core::mem::size_of::<TimeSpec>() as usize).is_err()
348                         || verify_area(virt_rem, core::mem::size_of::<TimeSpec>() as usize)
349                             .is_err())
350                 {
351                     Err(SystemError::EFAULT)
352                 } else {
353                     Self::nanosleep(req, rem)
354                 }
355             }
356 
357             SYS_CLOCK => Self::clock(),
358             #[cfg(target_arch = "x86_64")]
359             SYS_PIPE => {
360                 let pipefd: *mut i32 = args[0] as *mut c_int;
361                 if pipefd.is_null() {
362                     Err(SystemError::EFAULT)
363                 } else {
364                     Self::pipe2(pipefd, FileMode::empty())
365                 }
366             }
367 
368             SYS_PIPE2 => {
369                 let pipefd: *mut i32 = args[0] as *mut c_int;
370                 let arg1 = args[1];
371                 if pipefd.is_null() {
372                     Err(SystemError::EFAULT)
373                 } else {
374                     let flags = FileMode::from_bits_truncate(arg1 as u32);
375                     Self::pipe2(pipefd, flags)
376                 }
377             }
378 
379             SYS_UNLINKAT => {
380                 let dirfd = args[0] as i32;
381                 let pathname = args[1] as *const c_char;
382                 let flags = args[2] as u32;
383                 let virt_pathname = VirtAddr::new(pathname as usize);
384                 if frame.from_user() && verify_area(virt_pathname, PAGE_4K_SIZE as usize).is_err() {
385                     Err(SystemError::EFAULT)
386                 } else if pathname.is_null() {
387                     Err(SystemError::EFAULT)
388                 } else {
389                     let get_path = || {
390                         let pathname: &CStr = unsafe { CStr::from_ptr(pathname) };
391 
392                         let pathname: &str = pathname.to_str().map_err(|_| SystemError::EINVAL)?;
393                         if pathname.len() >= MAX_PATHLEN {
394                             return Err(SystemError::ENAMETOOLONG);
395                         }
396                         return Ok(pathname.trim());
397                     };
398                     let pathname = get_path();
399                     if pathname.is_err() {
400                         Err(pathname.unwrap_err())
401                     } else {
402                         // kdebug!("sys unlinkat: dirfd: {}, pathname: {}", dirfd, pathname.as_ref().unwrap());
403                         Self::unlinkat(dirfd, pathname.unwrap(), flags)
404                     }
405                 }
406             }
407 
408             #[cfg(target_arch = "x86_64")]
409             SYS_RMDIR => {
410                 let pathname = args[0] as *const u8;
411                 Self::rmdir(pathname)
412             }
413 
414             #[cfg(target_arch = "x86_64")]
415             SYS_UNLINK => {
416                 let pathname = args[0] as *const u8;
417                 Self::unlink(pathname)
418             }
419             SYS_KILL => {
420                 let pid = Pid::new(args[0]);
421                 let sig = args[1] as c_int;
422                 // kdebug!("KILL SYSCALL RECEIVED");
423                 Self::kill(pid, sig)
424             }
425 
426             SYS_RT_SIGACTION => {
427                 let sig = args[0] as c_int;
428                 let act = args[1];
429                 let old_act = args[2];
430                 Self::sigaction(sig, act, old_act, frame.from_user())
431             }
432 
433             SYS_GETPID => Self::getpid().map(|pid| pid.into()),
434 
435             SYS_SCHED => Self::sched(frame.from_user()),
436             SYS_DUP => {
437                 let oldfd: i32 = args[0] as c_int;
438                 Self::dup(oldfd)
439             }
440 
441             #[cfg(target_arch = "x86_64")]
442             SYS_DUP2 => {
443                 let oldfd: i32 = args[0] as c_int;
444                 let newfd: i32 = args[1] as c_int;
445                 Self::dup2(oldfd, newfd)
446             }
447 
448             SYS_SOCKET => Self::socket(args[0], args[1], args[2]),
449             SYS_SETSOCKOPT => {
450                 let optval = args[3] as *const u8;
451                 let optlen = args[4] as usize;
452                 let virt_optval = VirtAddr::new(optval as usize);
453                 // 验证optval的地址是否合法
454                 if verify_area(virt_optval, optlen as usize).is_err() {
455                     // 地址空间超出了用户空间的范围,不合法
456                     Err(SystemError::EFAULT)
457                 } else {
458                     let data: &[u8] = unsafe { core::slice::from_raw_parts(optval, optlen) };
459                     Self::setsockopt(args[0], args[1], args[2], data)
460                 }
461             }
462             SYS_GETSOCKOPT => {
463                 let optval = args[3] as *mut u8;
464                 let optlen = args[4] as *mut usize;
465                 let virt_optval = VirtAddr::new(optval as usize);
466                 let virt_optlen = VirtAddr::new(optlen as usize);
467                 let security_check = || {
468                     // 验证optval的地址是否合法
469                     if verify_area(virt_optval, PAGE_4K_SIZE as usize).is_err() {
470                         // 地址空间超出了用户空间的范围,不合法
471                         return Err(SystemError::EFAULT);
472                     }
473 
474                     // 验证optlen的地址是否合法
475                     if verify_area(virt_optlen, core::mem::size_of::<u32>() as usize).is_err() {
476                         // 地址空间超出了用户空间的范围,不合法
477                         return Err(SystemError::EFAULT);
478                     }
479                     return Ok(());
480                 };
481                 let r = security_check();
482                 if r.is_err() {
483                     Err(r.unwrap_err())
484                 } else {
485                     Self::getsockopt(args[0], args[1], args[2], optval, optlen as *mut u32)
486                 }
487             }
488 
489             SYS_CONNECT => {
490                 let addr = args[1] as *const SockAddr;
491                 let addrlen = args[2] as usize;
492                 let virt_addr = VirtAddr::new(addr as usize);
493                 // 验证addr的地址是否合法
494                 if verify_area(virt_addr, addrlen as usize).is_err() {
495                     // 地址空间超出了用户空间的范围,不合法
496                     Err(SystemError::EFAULT)
497                 } else {
498                     Self::connect(args[0], addr, addrlen)
499                 }
500             }
501             SYS_BIND => {
502                 let addr = args[1] as *const SockAddr;
503                 let addrlen = args[2] as usize;
504                 let virt_addr = VirtAddr::new(addr as usize);
505                 // 验证addr的地址是否合法
506                 if verify_area(virt_addr, addrlen as usize).is_err() {
507                     // 地址空间超出了用户空间的范围,不合法
508                     Err(SystemError::EFAULT)
509                 } else {
510                     Self::bind(args[0], addr, addrlen)
511                 }
512             }
513 
514             SYS_SENDTO => {
515                 let buf = args[1] as *const u8;
516                 let len = args[2] as usize;
517                 let flags = args[3] as u32;
518                 let addr = args[4] as *const SockAddr;
519                 let addrlen = args[5] as usize;
520                 let virt_buf = VirtAddr::new(buf as usize);
521                 let virt_addr = VirtAddr::new(addr as usize);
522                 // 验证buf的地址是否合法
523                 if verify_area(virt_buf, len as usize).is_err() {
524                     // 地址空间超出了用户空间的范围,不合法
525                     Err(SystemError::EFAULT)
526                 } else if verify_area(virt_addr, addrlen as usize).is_err() {
527                     // 地址空间超出了用户空间的范围,不合法
528                     Err(SystemError::EFAULT)
529                 } else {
530                     let data: &[u8] = unsafe { core::slice::from_raw_parts(buf, len) };
531                     Self::sendto(args[0], data, flags, addr, addrlen)
532                 }
533             }
534 
535             SYS_RECVFROM => {
536                 let buf = args[1] as *mut u8;
537                 let len = args[2] as usize;
538                 let flags = args[3] as u32;
539                 let addr = args[4] as *mut SockAddr;
540                 let addrlen = args[5] as *mut usize;
541                 let virt_buf = VirtAddr::new(buf as usize);
542                 let virt_addrlen = VirtAddr::new(addrlen as usize);
543                 let virt_addr = VirtAddr::new(addr as usize);
544                 let security_check = || {
545                     // 验证buf的地址是否合法
546                     if verify_area(virt_buf, len as usize).is_err() {
547                         // 地址空间超出了用户空间的范围,不合法
548                         return Err(SystemError::EFAULT);
549                     }
550 
551                     // 验证addrlen的地址是否合法
552                     if verify_area(virt_addrlen, core::mem::size_of::<u32>() as usize).is_err() {
553                         // 地址空间超出了用户空间的范围,不合法
554                         return Err(SystemError::EFAULT);
555                     }
556 
557                     if verify_area(virt_addr, core::mem::size_of::<SockAddr>() as usize).is_err() {
558                         // 地址空间超出了用户空间的范围,不合法
559                         return Err(SystemError::EFAULT);
560                     }
561                     return Ok(());
562                 };
563                 let r = security_check();
564                 if r.is_err() {
565                     Err(r.unwrap_err())
566                 } else {
567                     let buf = unsafe { core::slice::from_raw_parts_mut(buf, len) };
568                     Self::recvfrom(args[0], buf, flags, addr, addrlen as *mut u32)
569                 }
570             }
571 
572             SYS_RECVMSG => {
573                 let msg = args[1] as *mut MsgHdr;
574                 let flags = args[2] as u32;
575 
576                 let mut user_buffer_writer =
577                     UserBufferWriter::new(msg, core::mem::size_of::<MsgHdr>(), frame.from_user())?;
578                 let buffer = user_buffer_writer.buffer::<MsgHdr>(0)?;
579 
580                 let msg = &mut buffer[0];
581                 Self::recvmsg(args[0], msg, flags)
582             }
583 
584             SYS_LISTEN => Self::listen(args[0], args[1]),
585             SYS_SHUTDOWN => Self::shutdown(args[0], args[1]),
586             SYS_ACCEPT => Self::accept(args[0], args[1] as *mut SockAddr, args[2] as *mut u32),
587             SYS_ACCEPT4 => Self::accept4(
588                 args[0],
589                 args[1] as *mut SockAddr,
590                 args[2] as *mut u32,
591                 args[3] as u32,
592             ),
593             SYS_GETSOCKNAME => {
594                 Self::getsockname(args[0], args[1] as *mut SockAddr, args[2] as *mut u32)
595             }
596             SYS_GETPEERNAME => {
597                 Self::getpeername(args[0], args[1] as *mut SockAddr, args[2] as *mut u32)
598             }
599             SYS_GETTIMEOFDAY => {
600                 let timeval = args[0] as *mut PosixTimeval;
601                 let timezone_ptr = args[1] as *mut PosixTimeZone;
602                 Self::gettimeofday(timeval, timezone_ptr)
603             }
604             SYS_MMAP => {
605                 let len = page_align_up(args[1]);
606                 let virt_addr = VirtAddr::new(args[0] as usize);
607                 if verify_area(virt_addr, len as usize).is_err() {
608                     Err(SystemError::EFAULT)
609                 } else {
610                     Self::mmap(
611                         VirtAddr::new(args[0]),
612                         len,
613                         args[2],
614                         args[3],
615                         args[4] as i32,
616                         args[5],
617                     )
618                 }
619             }
620             SYS_MREMAP => {
621                 let old_vaddr = VirtAddr::new(args[0]);
622                 let old_len = args[1];
623                 let new_len = args[2];
624                 let mremap_flags = MremapFlags::from_bits_truncate(args[3] as u8);
625                 let new_vaddr = VirtAddr::new(args[4]);
626 
627                 Self::mremap(old_vaddr, old_len, new_len, mremap_flags, new_vaddr)
628             }
629             SYS_MUNMAP => {
630                 let addr = args[0];
631                 let len = page_align_up(args[1]);
632                 if addr & (MMArch::PAGE_SIZE - 1) != 0 {
633                     // The addr argument is not a multiple of the page size
634                     Err(SystemError::EINVAL)
635                 } else {
636                     Self::munmap(VirtAddr::new(addr), len)
637                 }
638             }
639             SYS_MPROTECT => {
640                 let addr = args[0];
641                 let len = page_align_up(args[1]);
642                 if addr & (MMArch::PAGE_SIZE - 1) != 0 {
643                     // The addr argument is not a multiple of the page size
644                     Err(SystemError::EINVAL)
645                 } else {
646                     Self::mprotect(VirtAddr::new(addr), len, args[2])
647                 }
648             }
649 
650             SYS_GETCWD => {
651                 let buf = args[0] as *mut u8;
652                 let size = args[1] as usize;
653                 let security_check = || {
654                     verify_area(VirtAddr::new(buf as usize), size)?;
655                     return Ok(());
656                 };
657                 let r = security_check();
658                 if r.is_err() {
659                     Err(r.unwrap_err())
660                 } else {
661                     let buf = unsafe { core::slice::from_raw_parts_mut(buf, size) };
662                     Self::getcwd(buf).map(|ptr| ptr.data())
663                 }
664             }
665 
666             SYS_GETPGID => Self::getpgid(Pid::new(args[0])).map(|pid| pid.into()),
667 
668             SYS_GETPPID => Self::getppid().map(|pid| pid.into()),
669             SYS_FSTAT => {
670                 let fd = args[0] as i32;
671                 let kstat = args[1] as *mut PosixKstat;
672                 let vaddr = VirtAddr::new(kstat as usize);
673                 // FIXME 由于c中的verify_area与rust中的verify_area重名,所以在引入时加了前缀区分
674                 // TODO 应该将用了c版本的verify_area都改为rust的verify_area
675                 match verify_area(vaddr, core::mem::size_of::<PosixKstat>()) {
676                     Ok(_) => Self::fstat(fd, kstat),
677                     Err(e) => Err(e),
678                 }
679             }
680 
681             SYS_FCNTL => {
682                 let fd = args[0] as i32;
683                 let cmd: Option<FcntlCommand> =
684                     <FcntlCommand as FromPrimitive>::from_u32(args[1] as u32);
685                 let arg = args[2] as i32;
686                 let res = if let Some(cmd) = cmd {
687                     Self::fcntl(fd, cmd, arg)
688                 } else {
689                     Err(SystemError::EINVAL)
690                 };
691 
692                 // kdebug!("FCNTL: fd: {}, cmd: {:?}, arg: {}, res: {:?}", fd, cmd, arg, res);
693                 res
694             }
695 
696             SYS_FTRUNCATE => {
697                 let fd = args[0] as i32;
698                 let len = args[1] as usize;
699                 let res = Self::ftruncate(fd, len);
700                 // kdebug!("FTRUNCATE: fd: {}, len: {}, res: {:?}", fd, len, res);
701                 res
702             }
703 
704             #[cfg(target_arch = "x86_64")]
705             SYS_MKNOD => {
706                 let path = args[0];
707                 let flags = args[1];
708                 let dev_t = args[2];
709                 let flags: ModeType = ModeType::from_bits_truncate(flags as u32);
710                 Self::mknod(path as *const i8, flags, DeviceNumber::from(dev_t as u32))
711             }
712 
713             SYS_CLONE => {
714                 let parent_tid = VirtAddr::new(args[2]);
715                 let child_tid = VirtAddr::new(args[3]);
716 
717                 // 地址校验
718                 verify_area(parent_tid, core::mem::size_of::<i32>())?;
719                 verify_area(child_tid, core::mem::size_of::<i32>())?;
720 
721                 let mut clone_args = KernelCloneArgs::new();
722                 clone_args.flags = CloneFlags::from_bits_truncate(args[0] as u64);
723                 clone_args.stack = args[1];
724                 clone_args.parent_tid = parent_tid;
725                 clone_args.child_tid = child_tid;
726                 clone_args.tls = args[4];
727                 Self::clone(frame, clone_args)
728             }
729 
730             SYS_FUTEX => {
731                 let uaddr = VirtAddr::new(args[0]);
732                 let operation = FutexFlag::from_bits(args[1] as u32).ok_or(SystemError::ENOSYS)?;
733                 let val = args[2] as u32;
734                 let utime = args[3];
735                 let uaddr2 = VirtAddr::new(args[4]);
736                 let val3 = args[5] as u32;
737 
738                 verify_area(uaddr, core::mem::size_of::<u32>())?;
739                 verify_area(uaddr2, core::mem::size_of::<u32>())?;
740 
741                 let mut timespec = None;
742                 if utime != 0 && operation.contains(FutexFlag::FLAGS_HAS_TIMEOUT) {
743                     let reader = UserBufferReader::new(
744                         utime as *const TimeSpec,
745                         core::mem::size_of::<TimeSpec>(),
746                         true,
747                     )?;
748 
749                     timespec = Some(reader.read_one_from_user::<TimeSpec>(0)?.clone());
750                 }
751 
752                 Self::do_futex(uaddr, operation, val, timespec, uaddr2, utime as u32, val3)
753             }
754 
755             SYS_READV => Self::readv(args[0] as i32, args[1], args[2]),
756             SYS_WRITEV => Self::writev(args[0] as i32, args[1], args[2]),
757 
758             SYS_SET_TID_ADDRESS => Self::set_tid_address(args[0]),
759 
760             #[cfg(target_arch = "x86_64")]
761             SYS_LSTAT => {
762                 let path: &CStr = unsafe { CStr::from_ptr(args[0] as *const c_char) };
763                 let path: Result<&str, core::str::Utf8Error> = path.to_str();
764                 let res = if path.is_err() {
765                     Err(SystemError::EINVAL)
766                 } else {
767                     let path: &str = path.unwrap();
768                     let kstat = args[1] as *mut PosixKstat;
769                     let vaddr = VirtAddr::new(kstat as usize);
770                     match verify_area(vaddr, core::mem::size_of::<PosixKstat>()) {
771                         Ok(_) => Self::lstat(path, kstat),
772                         Err(e) => Err(e),
773                     }
774                 };
775 
776                 res
777             }
778 
779             #[cfg(target_arch = "x86_64")]
780             SYS_STAT => {
781                 let path: &CStr = unsafe { CStr::from_ptr(args[0] as *const c_char) };
782                 let path: Result<&str, core::str::Utf8Error> = path.to_str();
783                 let res = if path.is_err() {
784                     Err(SystemError::EINVAL)
785                 } else {
786                     let path: &str = path.unwrap();
787                     let kstat = args[1] as *mut PosixKstat;
788                     let vaddr = VirtAddr::new(kstat as usize);
789                     match verify_area(vaddr, core::mem::size_of::<PosixKstat>()) {
790                         Ok(_) => Self::stat(path, kstat),
791                         Err(e) => Err(e),
792                     }
793                 };
794 
795                 res
796             }
797 
798             SYS_EPOLL_CREATE => Self::epoll_create(args[0] as i32),
799             SYS_EPOLL_CREATE1 => Self::epoll_create1(args[0]),
800 
801             SYS_EPOLL_CTL => Self::epoll_ctl(
802                 args[0] as i32,
803                 args[1],
804                 args[2] as i32,
805                 VirtAddr::new(args[3]),
806             ),
807 
808             SYS_EPOLL_WAIT => Self::epoll_wait(
809                 args[0] as i32,
810                 VirtAddr::new(args[1]),
811                 args[2] as i32,
812                 args[3] as i32,
813             ),
814 
815             SYS_EPOLL_PWAIT => {
816                 let epfd = args[0] as i32;
817                 let epoll_event = VirtAddr::new(args[1]);
818                 let max_events = args[2] as i32;
819                 let timespec = args[3] as i32;
820                 let sigmask_addr = args[4] as *mut SigSet;
821 
822                 if sigmask_addr.is_null() {
823                     return Self::epoll_wait(epfd, epoll_event, max_events, timespec);
824                 }
825                 let sigmask_reader =
826                     UserBufferReader::new(sigmask_addr, core::mem::size_of::<SigSet>(), true)?;
827                 let mut sigmask = sigmask_reader.read_one_from_user::<SigSet>(0)?.clone();
828 
829                 Self::epoll_pwait(
830                     args[0] as i32,
831                     VirtAddr::new(args[1]),
832                     args[2] as i32,
833                     args[3] as i32,
834                     &mut sigmask,
835                 )
836             }
837 
838             // 目前为了适配musl-libc,以下系统调用先这样写着
839             SYS_GETRANDOM => {
840                 let flags = GRandFlags::from_bits(args[2] as u8).ok_or(SystemError::EINVAL)?;
841                 Self::get_random(args[0] as *mut u8, args[1], flags)
842             }
843 
844             SYS_SOCKETPAIR => {
845                 let mut user_buffer_writer = UserBufferWriter::new(
846                     args[3] as *mut c_int,
847                     core::mem::size_of::<[c_int; 2]>(),
848                     frame.from_user(),
849                 )?;
850                 let fds = user_buffer_writer.buffer::<i32>(0)?;
851                 Self::socketpair(args[0], args[1], args[2], fds)
852             }
853 
854             #[cfg(target_arch = "x86_64")]
855             SYS_POLL => {
856                 kwarn!("SYS_POLL has not yet been implemented");
857                 Ok(0)
858             }
859 
860             SYS_SETPGID => {
861                 kwarn!("SYS_SETPGID has not yet been implemented");
862                 Ok(0)
863             }
864 
865             SYS_RT_SIGPROCMASK => {
866                 kwarn!("SYS_RT_SIGPROCMASK has not yet been implemented");
867                 Ok(0)
868             }
869 
870             SYS_TKILL => {
871                 kwarn!("SYS_TKILL has not yet been implemented");
872                 Ok(0)
873             }
874 
875             SYS_SIGALTSTACK => {
876                 kwarn!("SYS_SIGALTSTACK has not yet been implemented");
877                 Ok(0)
878             }
879 
880             SYS_EXIT_GROUP => {
881                 kwarn!("SYS_EXIT_GROUP has not yet been implemented");
882                 Ok(0)
883             }
884 
885             SYS_MADVISE => {
886                 // 这个太吵了,总是打印,先注释掉
887                 // kwarn!("SYS_MADVISE has not yet been implemented");
888                 Ok(0)
889             }
890             SYS_GETTID => Self::gettid().map(|tid| tid.into()),
891             SYS_GETUID => Self::getuid().map(|uid| uid.into()),
892 
893             SYS_SYSLOG => {
894                 let syslog_action_type = args[0] as usize;
895                 let buf_vaddr = args[1];
896                 let len = args[2];
897                 let from_user = frame.from_user();
898                 let mut user_buffer_writer =
899                     UserBufferWriter::new(buf_vaddr as *mut u8, len, from_user)?;
900 
901                 let user_buf = user_buffer_writer.buffer(0)?;
902                 let res = Self::do_syslog(syslog_action_type, user_buf, len);
903                 res
904             }
905 
906             SYS_GETGID => Self::getgid().map(|gid| gid.into()),
907             SYS_SETUID => {
908                 kwarn!("SYS_SETUID has not yet been implemented");
909                 Ok(0)
910             }
911             SYS_SETGID => {
912                 kwarn!("SYS_SETGID has not yet been implemented");
913                 Ok(0)
914             }
915             SYS_GETEUID => Self::geteuid().map(|euid| euid.into()),
916             SYS_GETEGID => Self::getegid().map(|egid| egid.into()),
917             SYS_GETRUSAGE => {
918                 let who = args[0] as c_int;
919                 let rusage = args[1] as *mut RUsage;
920                 Self::get_rusage(who, rusage)
921             }
922 
923             #[cfg(target_arch = "x86_64")]
924             SYS_READLINK => {
925                 let path = args[0] as *const u8;
926                 let buf = args[1] as *mut u8;
927                 let bufsiz = args[2] as usize;
928                 Self::readlink(path, buf, bufsiz)
929             }
930 
931             SYS_READLINKAT => {
932                 let dirfd = args[0] as i32;
933                 let pathname = args[1] as *const u8;
934                 let buf = args[2] as *mut u8;
935                 let bufsiz = args[3] as usize;
936                 Self::readlink_at(dirfd, pathname, buf, bufsiz)
937             }
938 
939             SYS_PRLIMIT64 => {
940                 let pid = args[0];
941                 let pid = Pid::new(pid);
942                 let resource = args[1];
943                 let new_limit = args[2] as *const RLimit64;
944                 let old_limit = args[3] as *mut RLimit64;
945 
946                 Self::prlimit64(pid, resource, new_limit, old_limit)
947             }
948 
949             #[cfg(target_arch = "x86_64")]
950             SYS_ACCESS => {
951                 let pathname = args[0] as *const u8;
952                 let mode = args[1] as u32;
953                 Self::access(pathname, mode)
954             }
955 
956             SYS_FACCESSAT => {
957                 let dirfd = args[0] as i32;
958                 let pathname = args[1] as *const u8;
959                 let mode = args[2] as u32;
960                 Self::faccessat2(dirfd, pathname, mode, 0)
961             }
962 
963             SYS_FACCESSAT2 => {
964                 let dirfd = args[0] as i32;
965                 let pathname = args[1] as *const u8;
966                 let mode = args[2] as u32;
967                 let flags = args[3] as u32;
968                 Self::faccessat2(dirfd, pathname, mode, flags)
969             }
970 
971             SYS_CLOCK_GETTIME => {
972                 let clockid = args[0] as i32;
973                 let timespec = args[1] as *mut TimeSpec;
974                 Self::clock_gettime(clockid, timespec)
975             }
976 
977             SYS_SYSINFO => {
978                 let info = args[0] as *mut SysInfo;
979                 Self::sysinfo(info)
980             }
981 
982             SYS_UMASK => {
983                 let mask = args[0] as u32;
984                 Self::umask(mask)
985             }
986 
987             SYS_FCHOWN => {
988                 kwarn!("SYS_FCHOWN has not yet been implemented");
989                 Ok(0)
990             }
991 
992             SYS_FSYNC => {
993                 kwarn!("SYS_FSYNC has not yet been implemented");
994                 Ok(0)
995             }
996 
997             #[cfg(target_arch = "x86_64")]
998             SYS_CHMOD => {
999                 let pathname = args[0] as *const u8;
1000                 let mode = args[1] as u32;
1001                 Self::chmod(pathname, mode)
1002             }
1003             SYS_FCHMOD => {
1004                 let fd = args[0] as i32;
1005                 let mode = args[1] as u32;
1006                 Self::fchmod(fd, mode)
1007             }
1008             SYS_FCHMODAT => {
1009                 let dirfd = args[0] as i32;
1010                 let pathname = args[1] as *const u8;
1011                 let mode = args[2] as u32;
1012                 Self::fchmodat(dirfd, pathname, mode)
1013             }
1014 
1015             SYS_SCHED_GETAFFINITY => {
1016                 // todo: 这个系统调用还没有实现
1017 
1018                 Err(SystemError::ENOSYS)
1019             }
1020 
1021             #[cfg(target_arch = "x86_64")]
1022             SYS_GETRLIMIT => {
1023                 let resource = args[0];
1024                 let rlimit = args[1] as *mut RLimit64;
1025 
1026                 Self::prlimit64(
1027                     ProcessManager::current_pcb().pid(),
1028                     resource,
1029                     0 as *const RLimit64,
1030                     rlimit,
1031                 )
1032             }
1033 
1034             SYS_SCHED_YIELD => Self::sched_yield(),
1035 
1036             _ => panic!("Unsupported syscall ID: {}", syscall_num),
1037         };
1038 
1039         return r;
1040     }
1041 
1042     pub fn put_string(
1043         s: *const u8,
1044         front_color: u32,
1045         back_color: u32,
1046     ) -> Result<usize, SystemError> {
1047         // todo: 删除这个系统调用
1048         let s = check_and_clone_cstr(s, Some(4096))?;
1049         let fr = (front_color & 0x00ff0000) >> 16;
1050         let fg = (front_color & 0x0000ff00) >> 8;
1051         let fb = front_color & 0x000000ff;
1052         let br = (back_color & 0x00ff0000) >> 16;
1053         let bg = (back_color & 0x0000ff00) >> 8;
1054         let bb = back_color & 0x000000ff;
1055         print!("\x1B[38;2;{fr};{fg};{fb};48;2;{br};{bg};{bb}m{s}\x1B[0m");
1056         return Ok(s.len());
1057     }
1058 
1059     pub fn reboot() -> Result<usize, SystemError> {
1060         unsafe { cpu_reset() };
1061     }
1062 }
1063