xref: /DragonOS/kernel/src/syscall/mod.rs (revision 6f189d2743e9b1ab790c58fc2d3a8d0c41cf61e1)
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             SYS_GETUID => Self::getuid(),
879 
880             SYS_SYSLOG => {
881                 let syslog_action_type = args[0];
882                 let buf_vaddr = args[1];
883                 let len = args[2];
884                 let from_user = frame.is_from_user();
885                 let mut user_buffer_writer =
886                     UserBufferWriter::new(buf_vaddr as *mut u8, len, from_user)?;
887 
888                 let user_buf = user_buffer_writer.buffer(0)?;
889                 Self::do_syslog(syslog_action_type, user_buf, len)
890             }
891 
892             SYS_GETGID => Self::getgid(),
893             SYS_SETUID => {
894                 warn!("SYS_SETUID has not yet been implemented");
895                 Ok(0)
896             }
897             SYS_SETGID => {
898                 warn!("SYS_SETGID has not yet been implemented");
899                 Ok(0)
900             }
901             SYS_SETSID => {
902                 warn!("SYS_SETSID has not yet been implemented");
903                 Ok(0)
904             }
905             SYS_GETEUID => Self::geteuid(),
906             SYS_GETEGID => Self::getegid(),
907             SYS_GETRUSAGE => {
908                 let who = args[0] as c_int;
909                 let rusage = args[1] as *mut RUsage;
910                 Self::get_rusage(who, rusage)
911             }
912 
913             #[cfg(target_arch = "x86_64")]
914             SYS_READLINK => {
915                 let path = args[0] as *const u8;
916                 let buf = args[1] as *mut u8;
917                 let bufsiz = args[2];
918                 Self::readlink(path, buf, bufsiz)
919             }
920 
921             SYS_READLINKAT => {
922                 let dirfd = args[0] as i32;
923                 let path = args[1] as *const u8;
924                 let buf = args[2] as *mut u8;
925                 let bufsiz = args[3];
926                 Self::readlink_at(dirfd, path, buf, bufsiz)
927             }
928 
929             SYS_PRLIMIT64 => {
930                 let pid = args[0];
931                 let pid = Pid::new(pid);
932                 let resource = args[1];
933                 let new_limit = args[2] as *const RLimit64;
934                 let old_limit = args[3] as *mut RLimit64;
935 
936                 Self::prlimit64(pid, resource, new_limit, old_limit)
937             }
938 
939             #[cfg(target_arch = "x86_64")]
940             SYS_ACCESS => {
941                 let pathname = args[0] as *const u8;
942                 let mode = args[1] as u32;
943                 Self::access(pathname, mode)
944             }
945 
946             SYS_FACCESSAT => {
947                 let dirfd = args[0] as i32;
948                 let pathname = args[1] as *const u8;
949                 let mode = args[2] as u32;
950                 Self::faccessat2(dirfd, pathname, mode, 0)
951             }
952 
953             SYS_FACCESSAT2 => {
954                 let dirfd = args[0] as i32;
955                 let pathname = args[1] as *const u8;
956                 let mode = args[2] as u32;
957                 let flags = args[3] as u32;
958                 Self::faccessat2(dirfd, pathname, mode, flags)
959             }
960 
961             SYS_CLOCK_GETTIME => {
962                 let clockid = args[0] as i32;
963                 let timespec = args[1] as *mut PosixTimeSpec;
964                 Self::clock_gettime(clockid, timespec)
965             }
966 
967             SYS_SYSINFO => {
968                 let info = args[0] as *mut SysInfo;
969                 Self::sysinfo(info)
970             }
971 
972             SYS_UMASK => {
973                 let mask = args[0] as u32;
974                 Self::umask(mask)
975             }
976 
977             SYS_FCHOWN => {
978                 warn!("SYS_FCHOWN has not yet been implemented");
979                 Ok(0)
980             }
981 
982             SYS_FSYNC => {
983                 warn!("SYS_FSYNC has not yet been implemented");
984                 Ok(0)
985             }
986 
987             SYS_RSEQ => {
988                 warn!("SYS_RSEQ has not yet been implemented");
989                 Ok(0)
990             }
991 
992             #[cfg(target_arch = "x86_64")]
993             SYS_CHMOD => {
994                 let pathname = args[0] as *const u8;
995                 let mode = args[1] as u32;
996                 Self::chmod(pathname, mode)
997             }
998             SYS_FCHMOD => {
999                 let fd = args[0] as i32;
1000                 let mode = args[1] as u32;
1001                 Self::fchmod(fd, mode)
1002             }
1003             SYS_FCHMODAT => {
1004                 let dirfd = args[0] as i32;
1005                 let pathname = args[1] as *const u8;
1006                 let mode = args[2] as u32;
1007                 Self::fchmodat(dirfd, pathname, mode)
1008             }
1009 
1010             SYS_SCHED_YIELD => Self::do_sched_yield(),
1011 
1012             SYS_SCHED_GETAFFINITY => {
1013                 let pid = args[0] as i32;
1014                 let size = args[1];
1015                 let set_vaddr = args[2];
1016 
1017                 let mut user_buffer_writer =
1018                     UserBufferWriter::new(set_vaddr as *mut u8, size, frame.is_from_user())?;
1019                 let set: &mut [u8] = user_buffer_writer.buffer(0)?;
1020 
1021                 Self::getaffinity(pid, set)
1022             }
1023 
1024             #[cfg(target_arch = "x86_64")]
1025             SYS_GETRLIMIT => {
1026                 let resource = args[0];
1027                 let rlimit = args[1] as *mut RLimit64;
1028 
1029                 Self::prlimit64(
1030                     ProcessManager::current_pcb().pid(),
1031                     resource,
1032                     core::ptr::null::<RLimit64>(),
1033                     rlimit,
1034                 )
1035             }
1036 
1037             SYS_FADVISE64 => {
1038                 // todo: 这个系统调用还没有实现
1039 
1040                 Err(SystemError::ENOSYS)
1041             }
1042 
1043             SYS_MOUNT => {
1044                 let source = args[0] as *const u8;
1045                 let target = args[1] as *const u8;
1046                 let filesystemtype = args[2] as *const u8;
1047                 return Self::mount(source, target, filesystemtype, 0, null());
1048             }
1049 
1050             SYS_UMOUNT2 => {
1051                 let target = args[0] as *const u8;
1052                 let flags = args[1] as i32;
1053                 Self::umount2(target, flags)?;
1054                 return Ok(0);
1055             }
1056 
1057             SYS_NEWFSTATAT => {
1058                 // todo: 这个系统调用还没有实现
1059 
1060                 Err(SystemError::ENOSYS)
1061             }
1062 
1063             // SYS_SCHED_YIELD => Self::sched_yield(),
1064             SYS_UNAME => {
1065                 let name = args[0] as *mut PosixOldUtsName;
1066                 Self::uname(name)
1067             }
1068             SYS_PRCTL => {
1069                 // todo: 这个系统调用还没有实现
1070 
1071                 Err(SystemError::EINVAL)
1072             }
1073 
1074             #[cfg(target_arch = "x86_64")]
1075             SYS_ALARM => {
1076                 let second = args[0] as u32;
1077                 Self::alarm(second)
1078             }
1079 
1080             SYS_SHMGET => {
1081                 let key = ShmKey::new(args[0]);
1082                 let size = args[1];
1083                 let shmflg = ShmFlags::from_bits_truncate(args[2] as u32);
1084 
1085                 Self::shmget(key, size, shmflg)
1086             }
1087             SYS_SHMAT => {
1088                 let id = ShmId::new(args[0]);
1089                 let vaddr = VirtAddr::new(args[1]);
1090                 let shmflg = ShmFlags::from_bits_truncate(args[2] as u32);
1091 
1092                 Self::shmat(id, vaddr, shmflg)
1093             }
1094             SYS_SHMDT => {
1095                 let vaddr = VirtAddr::new(args[0]);
1096                 Self::shmdt(vaddr)
1097             }
1098             SYS_SHMCTL => {
1099                 let id = ShmId::new(args[0]);
1100                 let cmd = ShmCtlCmd::from(args[1]);
1101                 let user_buf = args[2] as *const u8;
1102                 let from_user = frame.is_from_user();
1103 
1104                 Self::shmctl(id, cmd, user_buf, from_user)
1105             }
1106             SYS_UTIMENSAT => Self::sys_utimensat(
1107                 args[0] as i32,
1108                 args[1] as *const u8,
1109                 args[2] as *const PosixTimeSpec,
1110                 args[3] as u32,
1111             ),
1112             #[cfg(target_arch = "x86_64")]
1113             SYS_FUTIMESAT => {
1114                 let flags = UtimensFlags::empty();
1115                 Self::sys_utimensat(
1116                     args[0] as i32,
1117                     args[1] as *const u8,
1118                     args[2] as *const PosixTimeSpec,
1119                     flags.bits(),
1120                 )
1121             }
1122             #[cfg(target_arch = "x86_64")]
1123             SYS_UTIMES => Self::sys_utimes(args[0] as *const u8, args[1] as *const PosixTimeval),
1124             _ => panic!("Unsupported syscall ID: {}", syscall_num),
1125         };
1126 
1127         if ProcessManager::current_pcb()
1128             .flags()
1129             .contains(ProcessFlags::NEED_SCHEDULE)
1130         {
1131             schedule(SchedMode::SM_PREEMPT);
1132         }
1133 
1134         return r;
1135     }
1136 
1137     pub fn put_string(
1138         s: *const u8,
1139         front_color: u32,
1140         back_color: u32,
1141     ) -> Result<usize, SystemError> {
1142         // todo: 删除这个系统调用
1143         let s = check_and_clone_cstr(s, Some(4096))?;
1144         let fr = (front_color & 0x00ff0000) >> 16;
1145         let fg = (front_color & 0x0000ff00) >> 8;
1146         let fb = front_color & 0x000000ff;
1147         let br = (back_color & 0x00ff0000) >> 16;
1148         let bg = (back_color & 0x0000ff00) >> 8;
1149         let bb = back_color & 0x000000ff;
1150         print!("\x1B[38;2;{fr};{fg};{fb};48;2;{br};{bg};{bb}m{s}\x1B[0m");
1151         return Ok(s.len());
1152     }
1153 
1154     pub fn reboot() -> Result<usize, SystemError> {
1155         unsafe { cpu_reset() };
1156     }
1157 }
1158