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