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