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