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