xref: /DragonOS/kernel/src/syscall/mod.rs (revision 70f159a3988eab656ea1d2b204fde87948526ecf)
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::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.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.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.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.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.from_user() && verify_area(virt_addr, len as usize).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.from_user()
260                     && (verify_area(virt_path_ptr, MAX_PATHLEN as usize).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.from_user()
303                     && (verify_area(virt_req, core::mem::size_of::<TimeSpec>() as usize).is_err()
304                         || verify_area(virt_rem, core::mem::size_of::<TimeSpec>() as usize)
305                             .is_err())
306                 {
307                     Err(SystemError::EFAULT)
308                 } else {
309                     Self::nanosleep(req, rem)
310                 }
311             }
312 
313             SYS_CLOCK => Self::clock(),
314             #[cfg(target_arch = "x86_64")]
315             SYS_PIPE => {
316                 let pipefd: *mut i32 = args[0] as *mut c_int;
317                 if pipefd.is_null() {
318                     Err(SystemError::EFAULT)
319                 } else {
320                     Self::pipe2(pipefd, FileMode::empty())
321                 }
322             }
323 
324             SYS_PIPE2 => {
325                 let pipefd: *mut i32 = args[0] as *mut c_int;
326                 let arg1 = args[1];
327                 if pipefd.is_null() {
328                     Err(SystemError::EFAULT)
329                 } else {
330                     let flags = FileMode::from_bits_truncate(arg1 as u32);
331                     Self::pipe2(pipefd, flags)
332                 }
333             }
334 
335             SYS_UNLINKAT => {
336                 let dirfd = args[0] as i32;
337                 let path = args[1] as *const u8;
338                 let flags = args[2] as u32;
339                 Self::unlinkat(dirfd, path, flags)
340             }
341 
342             #[cfg(target_arch = "x86_64")]
343             SYS_RMDIR => {
344                 let path = args[0] as *const u8;
345                 Self::rmdir(path)
346             }
347 
348             #[cfg(target_arch = "x86_64")]
349             SYS_UNLINK => {
350                 let path = args[0] as *const u8;
351                 Self::unlink(path)
352             }
353             SYS_KILL => {
354                 let pid = Pid::new(args[0]);
355                 let sig = args[1] as c_int;
356                 // kdebug!("KILL SYSCALL RECEIVED");
357                 Self::kill(pid, sig)
358             }
359 
360             SYS_RT_SIGACTION => {
361                 let sig = args[0] as c_int;
362                 let act = args[1];
363                 let old_act = args[2];
364                 Self::sigaction(sig, act, old_act, frame.from_user())
365             }
366 
367             SYS_GETPID => Self::getpid().map(|pid| pid.into()),
368 
369             SYS_SCHED => Self::sched(frame.from_user()),
370             SYS_DUP => {
371                 let oldfd: i32 = args[0] as c_int;
372                 Self::dup(oldfd)
373             }
374 
375             #[cfg(target_arch = "x86_64")]
376             SYS_DUP2 => {
377                 let oldfd: i32 = args[0] as c_int;
378                 let newfd: i32 = args[1] as c_int;
379                 Self::dup2(oldfd, newfd)
380             }
381 
382             SYS_SOCKET => Self::socket(args[0], args[1], args[2]),
383             SYS_SETSOCKOPT => {
384                 let optval = args[3] as *const u8;
385                 let optlen = args[4] as usize;
386                 let virt_optval = VirtAddr::new(optval as usize);
387                 // 验证optval的地址是否合法
388                 if verify_area(virt_optval, optlen as usize).is_err() {
389                     // 地址空间超出了用户空间的范围,不合法
390                     Err(SystemError::EFAULT)
391                 } else {
392                     let data: &[u8] = unsafe { core::slice::from_raw_parts(optval, optlen) };
393                     Self::setsockopt(args[0], args[1], args[2], data)
394                 }
395             }
396             SYS_GETSOCKOPT => {
397                 let optval = args[3] as *mut u8;
398                 let optlen = args[4] as *mut usize;
399                 let virt_optval = VirtAddr::new(optval as usize);
400                 let virt_optlen = VirtAddr::new(optlen as usize);
401                 let security_check = || {
402                     // 验证optval的地址是否合法
403                     if verify_area(virt_optval, PAGE_4K_SIZE as usize).is_err() {
404                         // 地址空间超出了用户空间的范围,不合法
405                         return Err(SystemError::EFAULT);
406                     }
407 
408                     // 验证optlen的地址是否合法
409                     if verify_area(virt_optlen, core::mem::size_of::<u32>() as usize).is_err() {
410                         // 地址空间超出了用户空间的范围,不合法
411                         return Err(SystemError::EFAULT);
412                     }
413                     return Ok(());
414                 };
415                 let r = security_check();
416                 if r.is_err() {
417                     Err(r.unwrap_err())
418                 } else {
419                     Self::getsockopt(args[0], args[1], args[2], optval, optlen as *mut u32)
420                 }
421             }
422 
423             SYS_CONNECT => {
424                 let addr = args[1] as *const SockAddr;
425                 let addrlen = args[2] as usize;
426                 let virt_addr = VirtAddr::new(addr as usize);
427                 // 验证addr的地址是否合法
428                 if verify_area(virt_addr, addrlen as usize).is_err() {
429                     // 地址空间超出了用户空间的范围,不合法
430                     Err(SystemError::EFAULT)
431                 } else {
432                     Self::connect(args[0], addr, addrlen)
433                 }
434             }
435             SYS_BIND => {
436                 let addr = args[1] as *const SockAddr;
437                 let addrlen = args[2] as usize;
438                 let virt_addr = VirtAddr::new(addr as usize);
439                 // 验证addr的地址是否合法
440                 if verify_area(virt_addr, addrlen as usize).is_err() {
441                     // 地址空间超出了用户空间的范围,不合法
442                     Err(SystemError::EFAULT)
443                 } else {
444                     Self::bind(args[0], addr, addrlen)
445                 }
446             }
447 
448             SYS_SENDTO => {
449                 let buf = args[1] as *const u8;
450                 let len = args[2] as usize;
451                 let flags = args[3] as u32;
452                 let addr = args[4] as *const SockAddr;
453                 let addrlen = args[5] as usize;
454                 let virt_buf = VirtAddr::new(buf as usize);
455                 let virt_addr = VirtAddr::new(addr as usize);
456                 // 验证buf的地址是否合法
457                 if verify_area(virt_buf, len as usize).is_err() {
458                     // 地址空间超出了用户空间的范围,不合法
459                     Err(SystemError::EFAULT)
460                 } else if verify_area(virt_addr, addrlen as usize).is_err() {
461                     // 地址空间超出了用户空间的范围,不合法
462                     Err(SystemError::EFAULT)
463                 } else {
464                     let data: &[u8] = unsafe { core::slice::from_raw_parts(buf, len) };
465                     Self::sendto(args[0], data, flags, addr, addrlen)
466                 }
467             }
468 
469             SYS_RECVFROM => {
470                 let buf = args[1] as *mut u8;
471                 let len = args[2] as usize;
472                 let flags = args[3] as u32;
473                 let addr = args[4] as *mut SockAddr;
474                 let addrlen = args[5] as *mut usize;
475                 let virt_buf = VirtAddr::new(buf as usize);
476                 let virt_addrlen = VirtAddr::new(addrlen as usize);
477                 let virt_addr = VirtAddr::new(addr as usize);
478                 let security_check = || {
479                     // 验证buf的地址是否合法
480                     if verify_area(virt_buf, len).is_err() {
481                         // 地址空间超出了用户空间的范围,不合法
482                         return Err(SystemError::EFAULT);
483                     }
484 
485                     // 验证addrlen的地址是否合法
486                     if verify_area(virt_addrlen, core::mem::size_of::<u32>()).is_err() {
487                         // 地址空间超出了用户空间的范围,不合法
488                         return Err(SystemError::EFAULT);
489                     }
490 
491                     if verify_area(virt_addr, core::mem::size_of::<SockAddr>()).is_err() {
492                         // 地址空间超出了用户空间的范围,不合法
493                         return Err(SystemError::EFAULT);
494                     }
495                     return Ok(());
496                 };
497                 let r = security_check();
498                 if r.is_err() {
499                     Err(r.unwrap_err())
500                 } else {
501                     let buf = unsafe { core::slice::from_raw_parts_mut(buf, len) };
502                     Self::recvfrom(args[0], buf, flags, addr, addrlen as *mut u32)
503                 }
504             }
505 
506             SYS_RECVMSG => {
507                 let msg = args[1] as *mut MsgHdr;
508                 let flags = args[2] as u32;
509 
510                 let mut user_buffer_writer =
511                     UserBufferWriter::new(msg, core::mem::size_of::<MsgHdr>(), frame.from_user())?;
512                 let buffer = user_buffer_writer.buffer::<MsgHdr>(0)?;
513 
514                 let msg = &mut buffer[0];
515                 Self::recvmsg(args[0], msg, flags)
516             }
517 
518             SYS_LISTEN => Self::listen(args[0], args[1]),
519             SYS_SHUTDOWN => Self::shutdown(args[0], args[1]),
520             SYS_ACCEPT => Self::accept(args[0], args[1] as *mut SockAddr, args[2] as *mut u32),
521             SYS_ACCEPT4 => Self::accept4(
522                 args[0],
523                 args[1] as *mut SockAddr,
524                 args[2] as *mut u32,
525                 args[3] as u32,
526             ),
527             SYS_GETSOCKNAME => {
528                 Self::getsockname(args[0], args[1] as *mut SockAddr, args[2] as *mut u32)
529             }
530             SYS_GETPEERNAME => {
531                 Self::getpeername(args[0], args[1] as *mut SockAddr, args[2] as *mut u32)
532             }
533             SYS_GETTIMEOFDAY => {
534                 let timeval = args[0] as *mut PosixTimeval;
535                 let timezone_ptr = args[1] as *mut PosixTimeZone;
536                 Self::gettimeofday(timeval, timezone_ptr)
537             }
538             SYS_MMAP => {
539                 let len = page_align_up(args[1]);
540                 let virt_addr = VirtAddr::new(args[0]);
541                 if verify_area(virt_addr, len).is_err() {
542                     Err(SystemError::EFAULT)
543                 } else {
544                     Self::mmap(
545                         VirtAddr::new(args[0]),
546                         len,
547                         args[2],
548                         args[3],
549                         args[4] as i32,
550                         args[5],
551                     )
552                 }
553             }
554             SYS_MREMAP => {
555                 let old_vaddr = VirtAddr::new(args[0]);
556                 let old_len = args[1];
557                 let new_len = args[2];
558                 let mremap_flags = MremapFlags::from_bits_truncate(args[3] as u8);
559                 let new_vaddr = VirtAddr::new(args[4]);
560 
561                 Self::mremap(old_vaddr, old_len, new_len, mremap_flags, new_vaddr)
562             }
563             SYS_MUNMAP => {
564                 let addr = args[0];
565                 let len = page_align_up(args[1]);
566                 if addr & (MMArch::PAGE_SIZE - 1) != 0 {
567                     // The addr argument is not a multiple of the page size
568                     Err(SystemError::EINVAL)
569                 } else {
570                     Self::munmap(VirtAddr::new(addr), len)
571                 }
572             }
573             SYS_MPROTECT => {
574                 let addr = args[0];
575                 let len = page_align_up(args[1]);
576                 if addr & (MMArch::PAGE_SIZE - 1) != 0 {
577                     // The addr argument is not a multiple of the page size
578                     Err(SystemError::EINVAL)
579                 } else {
580                     Self::mprotect(VirtAddr::new(addr), len, args[2])
581                 }
582             }
583 
584             SYS_GETCWD => {
585                 let buf = args[0] as *mut u8;
586                 let size = args[1];
587                 let security_check = || {
588                     verify_area(VirtAddr::new(buf as usize), size)?;
589                     return Ok(());
590                 };
591                 let r = security_check();
592                 if r.is_err() {
593                     Err(r.unwrap_err())
594                 } else {
595                     let buf = unsafe { core::slice::from_raw_parts_mut(buf, size) };
596                     Self::getcwd(buf).map(|ptr| ptr.data())
597                 }
598             }
599 
600             SYS_GETPGID => Self::getpgid(Pid::new(args[0])).map(|pid| pid.into()),
601 
602             SYS_GETPPID => Self::getppid().map(|pid| pid.into()),
603             SYS_FSTAT => {
604                 let fd = args[0] as i32;
605                 let kstat = args[1] as *mut PosixKstat;
606                 let vaddr = VirtAddr::new(kstat as usize);
607                 // FIXME 由于c中的verify_area与rust中的verify_area重名,所以在引入时加了前缀区分
608                 // TODO 应该将用了c版本的verify_area都改为rust的verify_area
609                 match verify_area(vaddr, core::mem::size_of::<PosixKstat>()) {
610                     Ok(_) => Self::fstat(fd, kstat),
611                     Err(e) => Err(e),
612                 }
613             }
614 
615             SYS_FCNTL => {
616                 let fd = args[0] as i32;
617                 let cmd: Option<FcntlCommand> =
618                     <FcntlCommand as FromPrimitive>::from_u32(args[1] as u32);
619                 let arg = args[2] as i32;
620                 let res = if let Some(cmd) = cmd {
621                     Self::fcntl(fd, cmd, arg)
622                 } else {
623                     Err(SystemError::EINVAL)
624                 };
625 
626                 // kdebug!("FCNTL: fd: {}, cmd: {:?}, arg: {}, res: {:?}", fd, cmd, arg, res);
627                 res
628             }
629 
630             SYS_FTRUNCATE => {
631                 let fd = args[0] as i32;
632                 let len = args[1];
633                 let res = Self::ftruncate(fd, len);
634                 // kdebug!("FTRUNCATE: fd: {}, len: {}, res: {:?}", fd, len, res);
635                 res
636             }
637 
638             #[cfg(target_arch = "x86_64")]
639             SYS_MKNOD => {
640                 use crate::driver::base::device::device_number::DeviceNumber;
641 
642                 let path = args[0];
643                 let flags = args[1];
644                 let dev_t = args[2];
645                 let flags: ModeType = ModeType::from_bits_truncate(flags as u32);
646                 Self::mknod(path as *const u8, flags, DeviceNumber::from(dev_t as u32))
647             }
648 
649             SYS_CLONE => {
650                 let parent_tid = VirtAddr::new(args[2]);
651                 let child_tid = VirtAddr::new(args[3]);
652 
653                 // 地址校验
654                 verify_area(parent_tid, core::mem::size_of::<i32>())?;
655                 verify_area(child_tid, core::mem::size_of::<i32>())?;
656 
657                 let mut clone_args = KernelCloneArgs::new();
658                 clone_args.flags = CloneFlags::from_bits_truncate(args[0] as u64);
659                 clone_args.stack = args[1];
660                 clone_args.parent_tid = parent_tid;
661                 clone_args.child_tid = child_tid;
662                 clone_args.tls = args[4];
663                 Self::clone(frame, clone_args)
664             }
665 
666             SYS_FUTEX => {
667                 let uaddr = VirtAddr::new(args[0]);
668                 let operation = FutexFlag::from_bits(args[1] as u32).ok_or(SystemError::ENOSYS)?;
669                 let val = args[2] as u32;
670                 let utime = args[3];
671                 let uaddr2 = VirtAddr::new(args[4]);
672                 let val3 = args[5] as u32;
673 
674                 verify_area(uaddr, core::mem::size_of::<u32>())?;
675                 verify_area(uaddr2, core::mem::size_of::<u32>())?;
676 
677                 let mut timespec = None;
678                 if utime != 0 && operation.contains(FutexFlag::FLAGS_HAS_TIMEOUT) {
679                     let reader = UserBufferReader::new(
680                         utime as *const TimeSpec,
681                         core::mem::size_of::<TimeSpec>(),
682                         true,
683                     )?;
684 
685                     timespec = Some(*reader.read_one_from_user::<TimeSpec>(0)?);
686                 }
687 
688                 Self::do_futex(uaddr, operation, val, timespec, uaddr2, utime as u32, val3)
689             }
690 
691             SYS_READV => Self::readv(args[0] as i32, args[1], args[2]),
692             SYS_WRITEV => Self::writev(args[0] as i32, args[1], args[2]),
693 
694             SYS_SET_TID_ADDRESS => Self::set_tid_address(args[0]),
695 
696             #[cfg(target_arch = "x86_64")]
697             SYS_LSTAT => {
698                 let path = args[0] as *const u8;
699                 let kstat = args[1] as *mut PosixKstat;
700                 Self::lstat(path, kstat)
701             }
702 
703             #[cfg(target_arch = "x86_64")]
704             SYS_STAT => {
705                 let path = args[0] as *const u8;
706                 let kstat = args[1] as *mut PosixKstat;
707                 Self::stat(path, kstat)
708             }
709 
710             SYS_STATX => {
711                 let fd = args[0] as i32;
712                 let path = args[1] as *const u8;
713                 let flags = args[2] as u32;
714                 let mask = args[3] as u32;
715                 let kstat = args[4] as *mut PosixStatx;
716 
717                 Self::do_statx(fd, path, flags, mask, kstat)
718             }
719 
720             #[cfg(target_arch = "x86_64")]
721             SYS_EPOLL_CREATE => Self::epoll_create(args[0] as i32),
722             SYS_EPOLL_CREATE1 => Self::epoll_create1(args[0]),
723 
724             SYS_EPOLL_CTL => Self::epoll_ctl(
725                 args[0] as i32,
726                 args[1],
727                 args[2] as i32,
728                 VirtAddr::new(args[3]),
729             ),
730 
731             #[cfg(target_arch = "x86_64")]
732             SYS_EPOLL_WAIT => Self::epoll_wait(
733                 args[0] as i32,
734                 VirtAddr::new(args[1]),
735                 args[2] as i32,
736                 args[3] as i32,
737             ),
738 
739             SYS_EPOLL_PWAIT => {
740                 let epfd = args[0] as i32;
741                 let epoll_event = VirtAddr::new(args[1]);
742                 let max_events = args[2] as i32;
743                 let timespec = args[3] as i32;
744                 let sigmask_addr = args[4] as *mut SigSet;
745 
746                 if sigmask_addr.is_null() {
747                     return Self::epoll_wait(epfd, epoll_event, max_events, timespec);
748                 }
749                 let sigmask_reader =
750                     UserBufferReader::new(sigmask_addr, core::mem::size_of::<SigSet>(), true)?;
751                 let mut sigmask = *sigmask_reader.read_one_from_user::<SigSet>(0)?;
752 
753                 Self::epoll_pwait(
754                     args[0] as i32,
755                     VirtAddr::new(args[1]),
756                     args[2] as i32,
757                     args[3] as i32,
758                     &mut sigmask,
759                 )
760             }
761 
762             // 目前为了适配musl-libc,以下系统调用先这样写着
763             SYS_GETRANDOM => {
764                 let flags = GRandFlags::from_bits(args[2] as u8).ok_or(SystemError::EINVAL)?;
765                 Self::get_random(args[0] as *mut u8, args[1], flags)
766             }
767 
768             SYS_SOCKETPAIR => {
769                 let mut user_buffer_writer = UserBufferWriter::new(
770                     args[3] as *mut c_int,
771                     core::mem::size_of::<[c_int; 2]>(),
772                     frame.from_user(),
773                 )?;
774                 let fds = user_buffer_writer.buffer::<i32>(0)?;
775                 Self::socketpair(args[0], args[1], args[2], fds)
776             }
777 
778             #[cfg(target_arch = "x86_64")]
779             SYS_POLL => {
780                 kwarn!("SYS_POLL has not yet been implemented");
781                 Ok(0)
782             }
783 
784             SYS_SETPGID => {
785                 kwarn!("SYS_SETPGID has not yet been implemented");
786                 Ok(0)
787             }
788 
789             SYS_RT_SIGPROCMASK => {
790                 kwarn!("SYS_RT_SIGPROCMASK has not yet been implemented");
791                 Ok(0)
792             }
793 
794             SYS_TKILL => {
795                 kwarn!("SYS_TKILL has not yet been implemented");
796                 Ok(0)
797             }
798 
799             SYS_SIGALTSTACK => {
800                 kwarn!("SYS_SIGALTSTACK has not yet been implemented");
801                 Ok(0)
802             }
803 
804             SYS_EXIT_GROUP => {
805                 kwarn!("SYS_EXIT_GROUP has not yet been implemented");
806                 Ok(0)
807             }
808 
809             SYS_MADVISE => {
810                 // 这个太吵了,总是打印,先注释掉
811                 // kwarn!("SYS_MADVISE has not yet been implemented");
812                 Ok(0)
813             }
814             SYS_GETTID => Self::gettid().map(|tid| tid.into()),
815             SYS_GETUID => Self::getuid(),
816 
817             SYS_SYSLOG => {
818                 let syslog_action_type = args[0];
819                 let buf_vaddr = args[1];
820                 let len = args[2];
821                 let from_user = frame.from_user();
822                 let mut user_buffer_writer =
823                     UserBufferWriter::new(buf_vaddr as *mut u8, len, from_user)?;
824 
825                 let user_buf = user_buffer_writer.buffer(0)?;
826                 Self::do_syslog(syslog_action_type, user_buf, len)
827             }
828 
829             SYS_GETGID => Self::getgid(),
830             SYS_SETUID => {
831                 kwarn!("SYS_SETUID has not yet been implemented");
832                 Ok(0)
833             }
834             SYS_SETGID => {
835                 kwarn!("SYS_SETGID has not yet been implemented");
836                 Ok(0)
837             }
838             SYS_GETEUID => Self::geteuid(),
839             SYS_GETEGID => Self::getegid(),
840             SYS_GETRUSAGE => {
841                 let who = args[0] as c_int;
842                 let rusage = args[1] as *mut RUsage;
843                 Self::get_rusage(who, rusage)
844             }
845 
846             #[cfg(target_arch = "x86_64")]
847             SYS_READLINK => {
848                 let path = args[0] as *const u8;
849                 let buf = args[1] as *mut u8;
850                 let bufsiz = args[2];
851                 Self::readlink(path, buf, bufsiz)
852             }
853 
854             SYS_READLINKAT => {
855                 let dirfd = args[0] as i32;
856                 let path = args[1] as *const u8;
857                 let buf = args[2] as *mut u8;
858                 let bufsiz = args[3];
859                 Self::readlink_at(dirfd, path, buf, bufsiz)
860             }
861 
862             SYS_PRLIMIT64 => {
863                 let pid = args[0];
864                 let pid = Pid::new(pid);
865                 let resource = args[1];
866                 let new_limit = args[2] as *const RLimit64;
867                 let old_limit = args[3] as *mut RLimit64;
868 
869                 Self::prlimit64(pid, resource, new_limit, old_limit)
870             }
871 
872             #[cfg(target_arch = "x86_64")]
873             SYS_ACCESS => {
874                 let pathname = args[0] as *const u8;
875                 let mode = args[1] as u32;
876                 Self::access(pathname, mode)
877             }
878 
879             SYS_FACCESSAT => {
880                 let dirfd = args[0] as i32;
881                 let pathname = args[1] as *const u8;
882                 let mode = args[2] as u32;
883                 Self::faccessat2(dirfd, pathname, mode, 0)
884             }
885 
886             SYS_FACCESSAT2 => {
887                 let dirfd = args[0] as i32;
888                 let pathname = args[1] as *const u8;
889                 let mode = args[2] as u32;
890                 let flags = args[3] as u32;
891                 Self::faccessat2(dirfd, pathname, mode, flags)
892             }
893 
894             SYS_CLOCK_GETTIME => {
895                 let clockid = args[0] as i32;
896                 let timespec = args[1] as *mut TimeSpec;
897                 Self::clock_gettime(clockid, timespec)
898             }
899 
900             SYS_SYSINFO => {
901                 let info = args[0] as *mut SysInfo;
902                 Self::sysinfo(info)
903             }
904 
905             SYS_UMASK => {
906                 let mask = args[0] as u32;
907                 Self::umask(mask)
908             }
909 
910             SYS_FCHOWN => {
911                 kwarn!("SYS_FCHOWN has not yet been implemented");
912                 Ok(0)
913             }
914 
915             SYS_FSYNC => {
916                 kwarn!("SYS_FSYNC has not yet been implemented");
917                 Ok(0)
918             }
919 
920             #[cfg(target_arch = "x86_64")]
921             SYS_CHMOD => {
922                 let pathname = args[0] as *const u8;
923                 let mode = args[1] as u32;
924                 Self::chmod(pathname, mode)
925             }
926             SYS_FCHMOD => {
927                 let fd = args[0] as i32;
928                 let mode = args[1] as u32;
929                 Self::fchmod(fd, mode)
930             }
931             SYS_FCHMODAT => {
932                 let dirfd = args[0] as i32;
933                 let pathname = args[1] as *const u8;
934                 let mode = args[2] as u32;
935                 Self::fchmodat(dirfd, pathname, mode)
936             }
937 
938             SYS_SCHED_GETAFFINITY => {
939                 // todo: 这个系统调用还没有实现
940 
941                 Err(SystemError::ENOSYS)
942             }
943 
944             #[cfg(target_arch = "x86_64")]
945             SYS_GETRLIMIT => {
946                 let resource = args[0];
947                 let rlimit = args[1] as *mut RLimit64;
948 
949                 Self::prlimit64(
950                     ProcessManager::current_pcb().pid(),
951                     resource,
952                     core::ptr::null::<RLimit64>(),
953                     rlimit,
954                 )
955             }
956 
957             SYS_FADVISE64 => {
958                 // todo: 这个系统调用还没有实现
959 
960                 Err(SystemError::ENOSYS)
961             }
962 
963             SYS_MOUNT => {
964                 let source = args[0] as *const u8;
965                 let target = args[1] as *const u8;
966                 let filesystemtype = args[2] as *const u8;
967                 return Self::mount(source, target, filesystemtype, 0, null());
968             }
969             SYS_NEWFSTATAT => {
970                 // todo: 这个系统调用还没有实现
971 
972                 Err(SystemError::ENOSYS)
973             }
974 
975             SYS_SCHED_YIELD => Self::sched_yield(),
976             SYS_UNAME => {
977                 let name = args[0] as *mut PosixOldUtsName;
978                 Self::uname(name)
979             }
980 
981             _ => panic!("Unsupported syscall ID: {}", syscall_num),
982         };
983 
984         return r;
985     }
986 
987     pub fn put_string(
988         s: *const u8,
989         front_color: u32,
990         back_color: u32,
991     ) -> Result<usize, SystemError> {
992         // todo: 删除这个系统调用
993         let s = check_and_clone_cstr(s, Some(4096))?;
994         let fr = (front_color & 0x00ff0000) >> 16;
995         let fg = (front_color & 0x0000ff00) >> 8;
996         let fb = front_color & 0x000000ff;
997         let br = (back_color & 0x00ff0000) >> 16;
998         let bg = (back_color & 0x0000ff00) >> 8;
999         let bb = back_color & 0x000000ff;
1000         print!("\x1B[38;2;{fr};{fg};{fb};48;2;{br};{bg};{bb}m{s}\x1B[0m");
1001         return Ok(s.len());
1002     }
1003 
1004     pub fn reboot() -> Result<usize, SystemError> {
1005         unsafe { cpu_reset() };
1006     }
1007 }
1008