xref: /DragonOS/kernel/src/syscall/mod.rs (revision b4eb05a17f0f65668f69e7979660874ef8e01a2e)
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::PosixStatx,
11     libs::{futex::constant::FutexFlag, rand::GRandFlags},
12     mm::syscall::MremapFlags,
13     net::syscall::MsgHdr,
14     process::{
15         fork::KernelCloneArgs,
16         resource::{RLimit64, RUsage},
17         ProcessManager,
18     },
19     syscall::user_access::check_and_clone_cstr,
20 };
21 
22 use num_traits::FromPrimitive;
23 use system_error::SystemError;
24 use uefi::proto::debug;
25 
26 use crate::{
27     arch::{cpu::cpu_reset, interrupt::TrapFrame, MMArch},
28     filesystem::vfs::{
29         fcntl::{AtFlags, FcntlCommand},
30         file::FileMode,
31         syscall::{ModeType, PosixKstat},
32         MAX_PATHLEN,
33     },
34     include::bindings::bindings::PAGE_4K_SIZE,
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         TimeSpec,
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             SYS_RENAME => {
103                 let oldname: *const u8 = args[0] as *const u8;
104                 let newname: *const u8 = args[1] as *const u8;
105                 Self::do_renameat2(
106                     AtFlags::AT_FDCWD.bits(),
107                     oldname,
108                     AtFlags::AT_FDCWD.bits(),
109                     newname,
110                     0,
111                 )
112             }
113 
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                 let path = args[0];
641                 let flags = args[1];
642                 let dev_t = args[2];
643                 let flags: ModeType = ModeType::from_bits_truncate(flags as u32);
644                 Self::mknod(path as *const u8, flags, DeviceNumber::from(dev_t as u32))
645             }
646 
647             SYS_CLONE => {
648                 let parent_tid = VirtAddr::new(args[2]);
649                 let child_tid = VirtAddr::new(args[3]);
650 
651                 // 地址校验
652                 verify_area(parent_tid, core::mem::size_of::<i32>())?;
653                 verify_area(child_tid, core::mem::size_of::<i32>())?;
654 
655                 let mut clone_args = KernelCloneArgs::new();
656                 clone_args.flags = CloneFlags::from_bits_truncate(args[0] as u64);
657                 clone_args.stack = args[1];
658                 clone_args.parent_tid = parent_tid;
659                 clone_args.child_tid = child_tid;
660                 clone_args.tls = args[4];
661                 Self::clone(frame, clone_args)
662             }
663 
664             SYS_FUTEX => {
665                 let uaddr = VirtAddr::new(args[0]);
666                 let operation = FutexFlag::from_bits(args[1] as u32).ok_or(SystemError::ENOSYS)?;
667                 let val = args[2] as u32;
668                 let utime = args[3];
669                 let uaddr2 = VirtAddr::new(args[4]);
670                 let val3 = args[5] as u32;
671 
672                 verify_area(uaddr, core::mem::size_of::<u32>())?;
673                 verify_area(uaddr2, core::mem::size_of::<u32>())?;
674 
675                 let mut timespec = None;
676                 if utime != 0 && operation.contains(FutexFlag::FLAGS_HAS_TIMEOUT) {
677                     let reader = UserBufferReader::new(
678                         utime as *const TimeSpec,
679                         core::mem::size_of::<TimeSpec>(),
680                         true,
681                     )?;
682 
683                     timespec = Some(*reader.read_one_from_user::<TimeSpec>(0)?);
684                 }
685 
686                 Self::do_futex(uaddr, operation, val, timespec, uaddr2, utime as u32, val3)
687             }
688 
689             SYS_READV => Self::readv(args[0] as i32, args[1], args[2]),
690             SYS_WRITEV => Self::writev(args[0] as i32, args[1], args[2]),
691 
692             SYS_SET_TID_ADDRESS => Self::set_tid_address(args[0]),
693 
694             #[cfg(target_arch = "x86_64")]
695             SYS_LSTAT => {
696                 let path = args[0] as *const u8;
697                 let kstat = args[1] as *mut PosixKstat;
698                 Self::lstat(path, kstat)
699             }
700 
701             #[cfg(target_arch = "x86_64")]
702             SYS_STAT => {
703                 let path = args[0] as *const u8;
704                 let kstat = args[1] as *mut PosixKstat;
705                 Self::stat(path, kstat)
706             }
707 
708             SYS_STATX => {
709                 let fd = args[0] as i32;
710                 let path = args[1] as *const u8;
711                 let flags = args[2] as u32;
712                 let mask = args[3] as u32;
713                 let kstat = args[4] as *mut PosixStatx;
714 
715                 Self::do_statx(fd, path, flags, mask, kstat)
716             }
717 
718             SYS_EPOLL_CREATE => Self::epoll_create(args[0] as i32),
719             SYS_EPOLL_CREATE1 => Self::epoll_create1(args[0]),
720 
721             SYS_EPOLL_CTL => Self::epoll_ctl(
722                 args[0] as i32,
723                 args[1],
724                 args[2] as i32,
725                 VirtAddr::new(args[3]),
726             ),
727 
728             SYS_EPOLL_WAIT => Self::epoll_wait(
729                 args[0] as i32,
730                 VirtAddr::new(args[1]),
731                 args[2] as i32,
732                 args[3] as i32,
733             ),
734 
735             SYS_EPOLL_PWAIT => {
736                 let epfd = args[0] as i32;
737                 let epoll_event = VirtAddr::new(args[1]);
738                 let max_events = args[2] as i32;
739                 let timespec = args[3] as i32;
740                 let sigmask_addr = args[4] as *mut SigSet;
741 
742                 if sigmask_addr.is_null() {
743                     return Self::epoll_wait(epfd, epoll_event, max_events, timespec);
744                 }
745                 let sigmask_reader =
746                     UserBufferReader::new(sigmask_addr, core::mem::size_of::<SigSet>(), true)?;
747                 let mut sigmask = *sigmask_reader.read_one_from_user::<SigSet>(0)?;
748 
749                 Self::epoll_pwait(
750                     args[0] as i32,
751                     VirtAddr::new(args[1]),
752                     args[2] as i32,
753                     args[3] as i32,
754                     &mut sigmask,
755                 )
756             }
757 
758             // 目前为了适配musl-libc,以下系统调用先这样写着
759             SYS_GETRANDOM => {
760                 let flags = GRandFlags::from_bits(args[2] as u8).ok_or(SystemError::EINVAL)?;
761                 Self::get_random(args[0] as *mut u8, args[1], flags)
762             }
763 
764             SYS_SOCKETPAIR => {
765                 let mut user_buffer_writer = UserBufferWriter::new(
766                     args[3] as *mut c_int,
767                     core::mem::size_of::<[c_int; 2]>(),
768                     frame.from_user(),
769                 )?;
770                 let fds = user_buffer_writer.buffer::<i32>(0)?;
771                 Self::socketpair(args[0], args[1], args[2], fds)
772             }
773 
774             #[cfg(target_arch = "x86_64")]
775             SYS_POLL => {
776                 kwarn!("SYS_POLL has not yet been implemented");
777                 Ok(0)
778             }
779 
780             SYS_SETPGID => {
781                 kwarn!("SYS_SETPGID has not yet been implemented");
782                 Ok(0)
783             }
784 
785             SYS_RT_SIGPROCMASK => {
786                 kwarn!("SYS_RT_SIGPROCMASK has not yet been implemented");
787                 Ok(0)
788             }
789 
790             SYS_TKILL => {
791                 kwarn!("SYS_TKILL has not yet been implemented");
792                 Ok(0)
793             }
794 
795             SYS_SIGALTSTACK => {
796                 kwarn!("SYS_SIGALTSTACK has not yet been implemented");
797                 Ok(0)
798             }
799 
800             SYS_EXIT_GROUP => {
801                 kwarn!("SYS_EXIT_GROUP has not yet been implemented");
802                 Ok(0)
803             }
804 
805             SYS_MADVISE => {
806                 // 这个太吵了,总是打印,先注释掉
807                 // kwarn!("SYS_MADVISE has not yet been implemented");
808                 Ok(0)
809             }
810             SYS_GETTID => Self::gettid().map(|tid| tid.into()),
811             SYS_GETUID => Self::getuid(),
812 
813             SYS_SYSLOG => {
814                 let syslog_action_type = args[0];
815                 let buf_vaddr = args[1];
816                 let len = args[2];
817                 let from_user = frame.from_user();
818                 let mut user_buffer_writer =
819                     UserBufferWriter::new(buf_vaddr as *mut u8, len, from_user)?;
820 
821                 let user_buf = user_buffer_writer.buffer(0)?;
822                 Self::do_syslog(syslog_action_type, user_buf, len)
823             }
824 
825             SYS_GETGID => Self::getgid(),
826             SYS_SETUID => {
827                 kwarn!("SYS_SETUID has not yet been implemented");
828                 Ok(0)
829             }
830             SYS_SETGID => {
831                 kwarn!("SYS_SETGID has not yet been implemented");
832                 Ok(0)
833             }
834             SYS_GETEUID => Self::geteuid(),
835             SYS_GETEGID => Self::getegid(),
836             SYS_GETRUSAGE => {
837                 let who = args[0] as c_int;
838                 let rusage = args[1] as *mut RUsage;
839                 Self::get_rusage(who, rusage)
840             }
841 
842             #[cfg(target_arch = "x86_64")]
843             SYS_READLINK => {
844                 let path = args[0] as *const u8;
845                 let buf = args[1] as *mut u8;
846                 let bufsiz = args[2];
847                 Self::readlink(path, buf, bufsiz)
848             }
849 
850             SYS_READLINKAT => {
851                 let dirfd = args[0] as i32;
852                 let path = args[1] as *const u8;
853                 let buf = args[2] as *mut u8;
854                 let bufsiz = args[3];
855                 Self::readlink_at(dirfd, path, buf, bufsiz)
856             }
857 
858             SYS_PRLIMIT64 => {
859                 let pid = args[0];
860                 let pid = Pid::new(pid);
861                 let resource = args[1];
862                 let new_limit = args[2] as *const RLimit64;
863                 let old_limit = args[3] as *mut RLimit64;
864 
865                 Self::prlimit64(pid, resource, new_limit, old_limit)
866             }
867 
868             #[cfg(target_arch = "x86_64")]
869             SYS_ACCESS => {
870                 let pathname = args[0] as *const u8;
871                 let mode = args[1] as u32;
872                 Self::access(pathname, mode)
873             }
874 
875             SYS_FACCESSAT => {
876                 let dirfd = args[0] as i32;
877                 let pathname = args[1] as *const u8;
878                 let mode = args[2] as u32;
879                 Self::faccessat2(dirfd, pathname, mode, 0)
880             }
881 
882             SYS_FACCESSAT2 => {
883                 let dirfd = args[0] as i32;
884                 let pathname = args[1] as *const u8;
885                 let mode = args[2] as u32;
886                 let flags = args[3] as u32;
887                 Self::faccessat2(dirfd, pathname, mode, flags)
888             }
889 
890             SYS_CLOCK_GETTIME => {
891                 let clockid = args[0] as i32;
892                 let timespec = args[1] as *mut TimeSpec;
893                 Self::clock_gettime(clockid, timespec)
894             }
895 
896             SYS_SYSINFO => {
897                 let info = args[0] as *mut SysInfo;
898                 Self::sysinfo(info)
899             }
900 
901             SYS_UMASK => {
902                 let mask = args[0] as u32;
903                 Self::umask(mask)
904             }
905 
906             SYS_FCHOWN => {
907                 kwarn!("SYS_FCHOWN has not yet been implemented");
908                 Ok(0)
909             }
910 
911             SYS_FSYNC => {
912                 kwarn!("SYS_FSYNC has not yet been implemented");
913                 Ok(0)
914             }
915 
916             #[cfg(target_arch = "x86_64")]
917             SYS_CHMOD => {
918                 let pathname = args[0] as *const u8;
919                 let mode = args[1] as u32;
920                 Self::chmod(pathname, mode)
921             }
922             SYS_FCHMOD => {
923                 let fd = args[0] as i32;
924                 let mode = args[1] as u32;
925                 Self::fchmod(fd, mode)
926             }
927             SYS_FCHMODAT => {
928                 let dirfd = args[0] as i32;
929                 let pathname = args[1] as *const u8;
930                 let mode = args[2] as u32;
931                 Self::fchmodat(dirfd, pathname, mode)
932             }
933 
934             SYS_SCHED_GETAFFINITY => {
935                 // todo: 这个系统调用还没有实现
936 
937                 Err(SystemError::ENOSYS)
938             }
939 
940             #[cfg(target_arch = "x86_64")]
941             SYS_GETRLIMIT => {
942                 let resource = args[0];
943                 let rlimit = args[1] as *mut RLimit64;
944 
945                 Self::prlimit64(
946                     ProcessManager::current_pcb().pid(),
947                     resource,
948                     core::ptr::null::<RLimit64>(),
949                     rlimit,
950                 )
951             }
952 
953             SYS_FADVISE64 => {
954                 // todo: 这个系统调用还没有实现
955 
956                 Err(SystemError::ENOSYS)
957             }
958 
959             SYS_MOUNT => {
960                 let source = args[0] as *const u8;
961                 let target = args[1] as *const u8;
962                 let filesystemtype = args[2] as *const u8;
963                 return Self::mount(source, target, filesystemtype, 0, null());
964             }
965             SYS_NEWFSTATAT => {
966                 // todo: 这个系统调用还没有实现
967 
968                 Err(SystemError::ENOSYS)
969             }
970 
971             SYS_SCHED_YIELD => Self::sched_yield(),
972             SYS_UNAME => {
973                 let name = args[0] as *mut PosixOldUtsName;
974                 Self::uname(name)
975             }
976 
977             _ => panic!("Unsupported syscall ID: {}", syscall_num),
978         };
979 
980         return r;
981     }
982 
983     pub fn put_string(
984         s: *const u8,
985         front_color: u32,
986         back_color: u32,
987     ) -> Result<usize, SystemError> {
988         // todo: 删除这个系统调用
989         let s = check_and_clone_cstr(s, Some(4096))?;
990         let fr = (front_color & 0x00ff0000) >> 16;
991         let fg = (front_color & 0x0000ff00) >> 8;
992         let fb = front_color & 0x000000ff;
993         let br = (back_color & 0x00ff0000) >> 16;
994         let bg = (back_color & 0x0000ff00) >> 8;
995         let bb = back_color & 0x000000ff;
996         print!("\x1B[38;2;{fr};{fg};{fb};48;2;{br};{bg};{bb}m{s}\x1B[0m");
997         return Ok(s.len());
998     }
999 
1000     pub fn reboot() -> Result<usize, SystemError> {
1001         unsafe { cpu_reset() };
1002     }
1003 }
1004