xref: /DragonOS/kernel/src/syscall/mod.rs (revision d14e28a8a9b023ee8df7c2e8eee43e523134dbb2)
1 use core::{
2     ffi::{c_char, c_int, c_void, CStr},
3     sync::atomic::{AtomicBool, Ordering},
4 };
5 
6 use crate::{
7     arch::{ipc::signal::SigSet, syscall::nr::*},
8     driver::base::device::device_number::DeviceNumber,
9     libs::{futex::constant::FutexFlag, rand::GRandFlags},
10     process::{
11         fork::KernelCloneArgs,
12         resource::{RLimit64, RUsage},
13     },
14 };
15 
16 use num_traits::FromPrimitive;
17 use system_error::SystemError;
18 
19 use crate::{
20     arch::{cpu::cpu_reset, interrupt::TrapFrame, MMArch},
21     driver::base::block::SeekFrom,
22     filesystem::vfs::{
23         fcntl::FcntlCommand,
24         file::FileMode,
25         syscall::{ModeType, PosixKstat, SEEK_CUR, SEEK_END, SEEK_MAX, SEEK_SET},
26         MAX_PATHLEN,
27     },
28     include::bindings::bindings::{PAGE_2M_SIZE, PAGE_4K_SIZE},
29     kinfo,
30     libs::align::page_align_up,
31     mm::{verify_area, MemoryManagementArch, VirtAddr},
32     net::syscall::SockAddr,
33     process::{fork::CloneFlags, Pid},
34     time::{
35         syscall::{PosixTimeZone, PosixTimeval},
36         TimeSpec,
37     },
38 };
39 
40 use self::{
41     misc::SysInfo,
42     user_access::{UserBufferReader, UserBufferWriter},
43 };
44 
45 pub mod misc;
46 pub mod user_access;
47 
48 // 与linux不一致的调用,在linux基础上累加
49 pub const SYS_PUT_STRING: usize = 100000;
50 pub const SYS_SBRK: usize = 100001;
51 /// todo: 该系统调用与Linux不一致,将来需要删除该系统调用!!! 删的时候记得改C版本的libc
52 pub const SYS_CLOCK: usize = 100002;
53 pub const SYS_SCHED: usize = 100003;
54 
55 #[derive(Debug)]
56 pub struct Syscall;
57 
58 extern "C" {
59     fn do_put_string(s: *const u8, front_color: u32, back_color: u32) -> usize;
60 }
61 
62 impl Syscall {
63     /// 初始化系统调用
64     #[inline(never)]
65     pub fn init() -> Result<(), SystemError> {
66         static INIT_FLAG: AtomicBool = AtomicBool::new(false);
67         let prev = INIT_FLAG.swap(true, Ordering::SeqCst);
68         if prev {
69             panic!("Cannot initialize syscall more than once!");
70         }
71         kinfo!("Initializing syscall...");
72         let r = crate::arch::syscall::arch_syscall_init();
73         kinfo!("Syscall init successfully!");
74 
75         return r;
76     }
77     /// @brief 系统调用分发器,用于分发系统调用。
78     ///
79     /// 这个函数内,需要根据系统调用号,调用对应的系统调用处理函数。
80     /// 并且,对于用户态传入的指针参数,需要在本函数内进行越界检查,防止访问到内核空间。
81     #[inline(never)]
82     pub fn handle(
83         syscall_num: usize,
84         args: &[usize],
85         frame: &mut TrapFrame,
86     ) -> Result<usize, SystemError> {
87         let r = match syscall_num {
88             SYS_PUT_STRING => {
89                 Self::put_string(args[0] as *const u8, args[1] as u32, args[2] as u32)
90             }
91             #[cfg(target_arch = "x86_64")]
92             SYS_OPEN => {
93                 let path: &CStr = unsafe { CStr::from_ptr(args[0] as *const c_char) };
94                 let path: Result<&str, core::str::Utf8Error> = path.to_str();
95                 let res = if path.is_err() {
96                     Err(SystemError::EINVAL)
97                 } else {
98                     let path: &str = path.unwrap();
99 
100                     let flags = args[1];
101                     let mode = args[2];
102 
103                     let open_flags: FileMode = FileMode::from_bits_truncate(flags as u32);
104                     let mode = ModeType::from_bits(mode as u32).ok_or(SystemError::EINVAL)?;
105                     Self::open(path, open_flags, mode, true)
106                 };
107                 res
108             }
109 
110             SYS_OPENAT => {
111                 let dirfd = args[0] as i32;
112                 let path: &CStr = unsafe { CStr::from_ptr(args[1] as *const c_char) };
113                 let flags = args[2];
114                 let mode = args[3];
115 
116                 let path: Result<&str, core::str::Utf8Error> = path.to_str();
117                 let res = if path.is_err() {
118                     Err(SystemError::EINVAL)
119                 } else {
120                     let path: &str = path.unwrap();
121 
122                     let open_flags: FileMode =
123                         FileMode::from_bits(flags as u32).ok_or(SystemError::EINVAL)?;
124                     let mode = ModeType::from_bits(mode as u32).ok_or(SystemError::EINVAL)?;
125                     Self::openat(dirfd, path, open_flags, mode, true)
126                 };
127                 res
128             }
129             SYS_CLOSE => {
130                 let fd = args[0];
131 
132                 let res = Self::close(fd);
133 
134                 res
135             }
136             SYS_READ => {
137                 let fd = args[0] as i32;
138                 let buf_vaddr = args[1];
139                 let len = args[2];
140                 let from_user = frame.from_user();
141                 let mut user_buffer_writer =
142                     UserBufferWriter::new(buf_vaddr as *mut u8, len, from_user)?;
143 
144                 let user_buf = user_buffer_writer.buffer(0)?;
145                 let res = Self::read(fd, user_buf);
146                 res
147             }
148             SYS_WRITE => {
149                 let fd = args[0] as i32;
150                 let buf_vaddr = args[1];
151                 let len = args[2];
152                 let from_user = frame.from_user();
153                 let user_buffer_reader =
154                     UserBufferReader::new(buf_vaddr as *const u8, len, from_user)?;
155 
156                 let user_buf = user_buffer_reader.read_from_user(0)?;
157                 let res = Self::write(fd, user_buf);
158                 res
159             }
160 
161             SYS_LSEEK => {
162                 let fd = args[0] as i32;
163                 let offset = args[1] as i64;
164                 let whence = args[2] as u32;
165 
166                 let w = match whence {
167                     SEEK_SET => Ok(SeekFrom::SeekSet(offset)),
168                     SEEK_CUR => Ok(SeekFrom::SeekCurrent(offset)),
169                     SEEK_END => Ok(SeekFrom::SeekEnd(offset)),
170                     SEEK_MAX => Ok(SeekFrom::SeekEnd(0)),
171                     _ => Err(SystemError::EINVAL),
172                 }?;
173 
174                 Self::lseek(fd, w)
175             }
176             SYS_IOCTL => {
177                 let fd = args[0];
178                 let cmd = args[1];
179                 let data = args[2];
180                 Self::ioctl(fd, cmd as u32, data)
181             }
182 
183             #[cfg(target_arch = "x86_64")]
184             SYS_FORK => Self::fork(frame),
185             #[cfg(target_arch = "x86_64")]
186             SYS_VFORK => Self::vfork(frame),
187 
188             SYS_BRK => {
189                 let new_brk = VirtAddr::new(args[0]);
190                 Self::brk(new_brk).map(|vaddr| vaddr.data())
191             }
192 
193             SYS_SBRK => {
194                 let increment = args[0] as isize;
195                 Self::sbrk(increment).map(|vaddr: VirtAddr| vaddr.data())
196             }
197 
198             SYS_REBOOT => Self::reboot(),
199 
200             SYS_CHDIR => {
201                 // Closure for checking arguments
202                 let chdir_check = |arg0: usize| {
203                     if arg0 == 0 {
204                         return Err(SystemError::EFAULT);
205                     }
206                     let path_ptr = arg0 as *const c_char;
207                     let virt_addr = VirtAddr::new(path_ptr as usize);
208                     // 权限校验
209                     if path_ptr.is_null()
210                         || (frame.from_user()
211                             && verify_area(virt_addr, PAGE_2M_SIZE as usize).is_err())
212                     {
213                         return Err(SystemError::EINVAL);
214                     }
215                     let dest_path: &CStr = unsafe { CStr::from_ptr(path_ptr) };
216                     let dest_path: &str = dest_path.to_str().map_err(|_| SystemError::EINVAL)?;
217                     if dest_path.len() == 0 {
218                         return Err(SystemError::EINVAL);
219                     } else if dest_path.len() > MAX_PATHLEN as usize {
220                         return Err(SystemError::ENAMETOOLONG);
221                     }
222 
223                     return Ok(dest_path);
224                 };
225 
226                 let r = chdir_check(args[0])?;
227                 Self::chdir(r)
228             }
229 
230             #[allow(unreachable_patterns)]
231             SYS_GETDENTS64 | SYS_GETDENTS => {
232                 let fd = args[0] as i32;
233 
234                 let buf_vaddr = args[1];
235                 let len = args[2];
236                 let virt_addr: VirtAddr = VirtAddr::new(buf_vaddr);
237                 // 判断缓冲区是否来自用户态,进行权限校验
238                 let res = if frame.from_user() && verify_area(virt_addr, len as usize).is_err() {
239                     // 来自用户态,而buffer在内核态,这样的操作不被允许
240                     Err(SystemError::EPERM)
241                 } else if buf_vaddr == 0 {
242                     Err(SystemError::EFAULT)
243                 } else {
244                     let buf: &mut [u8] = unsafe {
245                         core::slice::from_raw_parts_mut::<'static, u8>(buf_vaddr as *mut u8, len)
246                     };
247                     Self::getdents(fd, buf)
248                 };
249 
250                 res
251             }
252 
253             SYS_EXECVE => {
254                 let path_ptr = args[0];
255                 let argv_ptr = args[1];
256                 let env_ptr = args[2];
257                 let virt_path_ptr = VirtAddr::new(path_ptr);
258                 let virt_argv_ptr = VirtAddr::new(argv_ptr);
259                 let virt_env_ptr = VirtAddr::new(env_ptr);
260                 // 权限校验
261                 if frame.from_user()
262                     && (verify_area(virt_path_ptr, MAX_PATHLEN as usize).is_err()
263                         || verify_area(virt_argv_ptr, PAGE_4K_SIZE as usize).is_err())
264                     || verify_area(virt_env_ptr, PAGE_4K_SIZE as usize).is_err()
265                 {
266                     Err(SystemError::EFAULT)
267                 } else {
268                     Self::execve(
269                         path_ptr as *const u8,
270                         argv_ptr as *const *const u8,
271                         env_ptr as *const *const u8,
272                         frame,
273                     )
274                     .map(|_| 0)
275                 }
276             }
277             SYS_WAIT4 => {
278                 let pid = args[0] as i32;
279                 let wstatus = args[1] as *mut i32;
280                 let options = args[2] as c_int;
281                 let rusage = args[3] as *mut c_void;
282                 // 权限校验
283                 // todo: 引入rusage之后,更正以下权限校验代码中,rusage的大小
284                 Self::wait4(pid.into(), wstatus, options, rusage)
285             }
286 
287             SYS_EXIT => {
288                 let exit_code = args[0];
289                 Self::exit(exit_code)
290             }
291             #[cfg(target_arch = "x86_64")]
292             SYS_MKDIR => {
293                 let path_ptr = args[0] as *const c_char;
294                 let mode = args[1];
295                 let virt_path_ptr = VirtAddr::new(path_ptr as usize);
296                 let security_check = || {
297                     if path_ptr.is_null()
298                         || (frame.from_user()
299                             && verify_area(virt_path_ptr, PAGE_2M_SIZE as usize).is_err())
300                     {
301                         return Err(SystemError::EINVAL);
302                     }
303                     let path: &CStr = unsafe { CStr::from_ptr(path_ptr) };
304                     let path: &str = path.to_str().map_err(|_| SystemError::EINVAL)?.trim();
305 
306                     if path == "" {
307                         return Err(SystemError::EINVAL);
308                     }
309                     return Ok(path);
310                 };
311 
312                 let path = security_check();
313                 if path.is_err() {
314                     Err(path.unwrap_err())
315                 } else {
316                     Self::mkdir(path.unwrap(), mode)
317                 }
318             }
319 
320             SYS_NANOSLEEP => {
321                 let req = args[0] as *const TimeSpec;
322                 let rem = args[1] as *mut TimeSpec;
323                 let virt_req = VirtAddr::new(req as usize);
324                 let virt_rem = VirtAddr::new(rem as usize);
325                 if frame.from_user()
326                     && (verify_area(virt_req, core::mem::size_of::<TimeSpec>() as usize).is_err()
327                         || verify_area(virt_rem, core::mem::size_of::<TimeSpec>() as usize)
328                             .is_err())
329                 {
330                     Err(SystemError::EFAULT)
331                 } else {
332                     Self::nanosleep(req, rem)
333                 }
334             }
335 
336             SYS_CLOCK => Self::clock(),
337             #[cfg(target_arch = "x86_64")]
338             SYS_PIPE => {
339                 let pipefd: *mut i32 = args[0] as *mut c_int;
340                 if pipefd.is_null() {
341                     Err(SystemError::EFAULT)
342                 } else {
343                     Self::pipe2(pipefd, FileMode::empty())
344                 }
345             }
346             SYS_PIPE2 => {
347                 let pipefd: *mut i32 = args[0] as *mut c_int;
348                 let arg1 = args[1];
349                 if pipefd.is_null() {
350                     Err(SystemError::EFAULT)
351                 } else {
352                     let flags = FileMode::from_bits_truncate(arg1 as u32);
353                     Self::pipe2(pipefd, flags)
354                 }
355             }
356 
357             SYS_UNLINKAT => {
358                 let dirfd = args[0] as i32;
359                 let pathname = args[1] as *const c_char;
360                 let flags = args[2] as u32;
361                 let virt_pathname = VirtAddr::new(pathname as usize);
362                 if frame.from_user() && verify_area(virt_pathname, PAGE_4K_SIZE as usize).is_err() {
363                     Err(SystemError::EFAULT)
364                 } else if pathname.is_null() {
365                     Err(SystemError::EFAULT)
366                 } else {
367                     let get_path = || {
368                         let pathname: &CStr = unsafe { CStr::from_ptr(pathname) };
369 
370                         let pathname: &str = pathname.to_str().map_err(|_| SystemError::EINVAL)?;
371                         if pathname.len() >= MAX_PATHLEN {
372                             return Err(SystemError::ENAMETOOLONG);
373                         }
374                         return Ok(pathname.trim());
375                     };
376                     let pathname = get_path();
377                     if pathname.is_err() {
378                         Err(pathname.unwrap_err())
379                     } else {
380                         // kdebug!("sys unlinkat: dirfd: {}, pathname: {}", dirfd, pathname.as_ref().unwrap());
381                         Self::unlinkat(dirfd, pathname.unwrap(), flags)
382                     }
383                 }
384             }
385 
386             #[cfg(target_arch = "x86_64")]
387             SYS_UNLINK => {
388                 let pathname = args[0] as *const u8;
389                 Self::unlink(pathname)
390             }
391             SYS_KILL => {
392                 let pid = Pid::new(args[0]);
393                 let sig = args[1] as c_int;
394                 // kdebug!("KILL SYSCALL RECEIVED");
395                 Self::kill(pid, sig)
396             }
397 
398             SYS_RT_SIGACTION => {
399                 let sig = args[0] as c_int;
400                 let act = args[1];
401                 let old_act = args[2];
402                 Self::sigaction(sig, act, old_act, frame.from_user())
403             }
404 
405             SYS_GETPID => Self::getpid().map(|pid| pid.into()),
406 
407             SYS_SCHED => Self::sched(frame.from_user()),
408             SYS_DUP => {
409                 let oldfd: i32 = args[0] as c_int;
410                 Self::dup(oldfd)
411             }
412 
413             #[cfg(target_arch = "x86_64")]
414             SYS_DUP2 => {
415                 let oldfd: i32 = args[0] as c_int;
416                 let newfd: i32 = args[1] as c_int;
417                 Self::dup2(oldfd, newfd)
418             }
419 
420             SYS_SOCKET => Self::socket(args[0], args[1], args[2]),
421             SYS_SETSOCKOPT => {
422                 let optval = args[3] as *const u8;
423                 let optlen = args[4] as usize;
424                 let virt_optval = VirtAddr::new(optval as usize);
425                 // 验证optval的地址是否合法
426                 if verify_area(virt_optval, optlen as usize).is_err() {
427                     // 地址空间超出了用户空间的范围,不合法
428                     Err(SystemError::EFAULT)
429                 } else {
430                     let data: &[u8] = unsafe { core::slice::from_raw_parts(optval, optlen) };
431                     Self::setsockopt(args[0], args[1], args[2], data)
432                 }
433             }
434             SYS_GETSOCKOPT => {
435                 let optval = args[3] as *mut u8;
436                 let optlen = args[4] as *mut usize;
437                 let virt_optval = VirtAddr::new(optval as usize);
438                 let virt_optlen = VirtAddr::new(optlen as usize);
439                 let security_check = || {
440                     // 验证optval的地址是否合法
441                     if verify_area(virt_optval, PAGE_4K_SIZE as usize).is_err() {
442                         // 地址空间超出了用户空间的范围,不合法
443                         return Err(SystemError::EFAULT);
444                     }
445 
446                     // 验证optlen的地址是否合法
447                     if verify_area(virt_optlen, core::mem::size_of::<u32>() as usize).is_err() {
448                         // 地址空间超出了用户空间的范围,不合法
449                         return Err(SystemError::EFAULT);
450                     }
451                     return Ok(());
452                 };
453                 let r = security_check();
454                 if r.is_err() {
455                     Err(r.unwrap_err())
456                 } else {
457                     Self::getsockopt(args[0], args[1], args[2], optval, optlen as *mut u32)
458                 }
459             }
460 
461             SYS_CONNECT => {
462                 let addr = args[1] as *const SockAddr;
463                 let addrlen = args[2] as usize;
464                 let virt_addr = VirtAddr::new(addr as usize);
465                 // 验证addr的地址是否合法
466                 if verify_area(virt_addr, addrlen as usize).is_err() {
467                     // 地址空间超出了用户空间的范围,不合法
468                     Err(SystemError::EFAULT)
469                 } else {
470                     Self::connect(args[0], addr, addrlen)
471                 }
472             }
473             SYS_BIND => {
474                 let addr = args[1] as *const SockAddr;
475                 let addrlen = args[2] as usize;
476                 let virt_addr = VirtAddr::new(addr as usize);
477                 // 验证addr的地址是否合法
478                 if verify_area(virt_addr, addrlen as usize).is_err() {
479                     // 地址空间超出了用户空间的范围,不合法
480                     Err(SystemError::EFAULT)
481                 } else {
482                     Self::bind(args[0], addr, addrlen)
483                 }
484             }
485 
486             SYS_SENDTO => {
487                 let buf = args[1] as *const u8;
488                 let len = args[2] as usize;
489                 let flags = args[3] as u32;
490                 let addr = args[4] as *const SockAddr;
491                 let addrlen = args[5] as usize;
492                 let virt_buf = VirtAddr::new(buf as usize);
493                 let virt_addr = VirtAddr::new(addr as usize);
494                 // 验证buf的地址是否合法
495                 if verify_area(virt_buf, len as usize).is_err() {
496                     // 地址空间超出了用户空间的范围,不合法
497                     Err(SystemError::EFAULT)
498                 } else if verify_area(virt_addr, addrlen as usize).is_err() {
499                     // 地址空间超出了用户空间的范围,不合法
500                     Err(SystemError::EFAULT)
501                 } else {
502                     let data: &[u8] = unsafe { core::slice::from_raw_parts(buf, len) };
503                     Self::sendto(args[0], data, flags, addr, addrlen)
504                 }
505             }
506 
507             SYS_RECVFROM => {
508                 let buf = args[1] as *mut u8;
509                 let len = args[2] as usize;
510                 let flags = args[3] as u32;
511                 let addr = args[4] as *mut SockAddr;
512                 let addrlen = args[5] as *mut usize;
513                 let virt_buf = VirtAddr::new(buf as usize);
514                 let virt_addrlen = VirtAddr::new(addrlen as usize);
515                 let virt_addr = VirtAddr::new(addr as usize);
516                 let security_check = || {
517                     // 验证buf的地址是否合法
518                     if verify_area(virt_buf, len as usize).is_err() {
519                         // 地址空间超出了用户空间的范围,不合法
520                         return Err(SystemError::EFAULT);
521                     }
522 
523                     // 验证addrlen的地址是否合法
524                     if verify_area(virt_addrlen, core::mem::size_of::<u32>() as usize).is_err() {
525                         // 地址空间超出了用户空间的范围,不合法
526                         return Err(SystemError::EFAULT);
527                     }
528 
529                     if verify_area(virt_addr, core::mem::size_of::<SockAddr>() as usize).is_err() {
530                         // 地址空间超出了用户空间的范围,不合法
531                         return Err(SystemError::EFAULT);
532                     }
533                     return Ok(());
534                 };
535                 let r = security_check();
536                 if r.is_err() {
537                     Err(r.unwrap_err())
538                 } else {
539                     let buf = unsafe { core::slice::from_raw_parts_mut(buf, len) };
540                     Self::recvfrom(args[0], buf, flags, addr, addrlen as *mut u32)
541                 }
542             }
543 
544             SYS_RECVMSG => {
545                 let msg = args[1] as *mut crate::net::syscall::MsgHdr;
546                 let flags = args[2] as u32;
547                 match UserBufferWriter::new(
548                     msg,
549                     core::mem::size_of::<crate::net::syscall::MsgHdr>(),
550                     true,
551                 ) {
552                     Err(e) => Err(e),
553                     Ok(mut user_buffer_writer) => {
554                         match user_buffer_writer.buffer::<crate::net::syscall::MsgHdr>(0) {
555                             Err(e) => Err(e),
556                             Ok(buffer) => {
557                                 let msg = &mut buffer[0];
558                                 Self::recvmsg(args[0], msg, flags)
559                             }
560                         }
561                     }
562                 }
563             }
564 
565             SYS_LISTEN => Self::listen(args[0], args[1]),
566             SYS_SHUTDOWN => Self::shutdown(args[0], args[1]),
567             SYS_ACCEPT => Self::accept(args[0], args[1] as *mut SockAddr, args[2] as *mut u32),
568             SYS_ACCEPT4 => Self::accept4(
569                 args[0],
570                 args[1] as *mut SockAddr,
571                 args[2] as *mut u32,
572                 args[3] as u32,
573             ),
574             SYS_GETSOCKNAME => {
575                 Self::getsockname(args[0], args[1] as *mut SockAddr, args[2] as *mut u32)
576             }
577             SYS_GETPEERNAME => {
578                 Self::getpeername(args[0], args[1] as *mut SockAddr, args[2] as *mut u32)
579             }
580             SYS_GETTIMEOFDAY => {
581                 let timeval = args[0] as *mut PosixTimeval;
582                 let timezone_ptr = args[1] as *mut PosixTimeZone;
583                 Self::gettimeofday(timeval, timezone_ptr)
584             }
585             SYS_MMAP => {
586                 let len = page_align_up(args[1]);
587                 let virt_addr = VirtAddr::new(args[0] as usize);
588                 if verify_area(virt_addr, len as usize).is_err() {
589                     Err(SystemError::EFAULT)
590                 } else {
591                     Self::mmap(
592                         VirtAddr::new(args[0]),
593                         len,
594                         args[2],
595                         args[3],
596                         args[4] as i32,
597                         args[5],
598                     )
599                 }
600             }
601             SYS_MUNMAP => {
602                 let addr = args[0];
603                 let len = page_align_up(args[1]);
604                 if addr & (MMArch::PAGE_SIZE - 1) != 0 {
605                     // The addr argument is not a multiple of the page size
606                     Err(SystemError::EINVAL)
607                 } else {
608                     Self::munmap(VirtAddr::new(addr), len)
609                 }
610             }
611             SYS_MPROTECT => {
612                 let addr = args[0];
613                 let len = page_align_up(args[1]);
614                 if addr & (MMArch::PAGE_SIZE - 1) != 0 {
615                     // The addr argument is not a multiple of the page size
616                     Err(SystemError::EINVAL)
617                 } else {
618                     Self::mprotect(VirtAddr::new(addr), len, args[2])
619                 }
620             }
621 
622             SYS_GETCWD => {
623                 let buf = args[0] as *mut u8;
624                 let size = args[1] as usize;
625                 let security_check = || {
626                     verify_area(VirtAddr::new(buf as usize), size)?;
627                     return Ok(());
628                 };
629                 let r = security_check();
630                 if r.is_err() {
631                     Err(r.unwrap_err())
632                 } else {
633                     let buf = unsafe { core::slice::from_raw_parts_mut(buf, size) };
634                     Self::getcwd(buf).map(|ptr| ptr.data())
635                 }
636             }
637 
638             SYS_GETPGID => Self::getpgid(Pid::new(args[0])).map(|pid| pid.into()),
639 
640             SYS_GETPPID => Self::getppid().map(|pid| pid.into()),
641             SYS_FSTAT => {
642                 let fd = args[0] as i32;
643                 let kstat = args[1] as *mut PosixKstat;
644                 let vaddr = VirtAddr::new(kstat as usize);
645                 // FIXME 由于c中的verify_area与rust中的verify_area重名,所以在引入时加了前缀区分
646                 // TODO 应该将用了c版本的verify_area都改为rust的verify_area
647                 match verify_area(vaddr, core::mem::size_of::<PosixKstat>()) {
648                     Ok(_) => Self::fstat(fd, kstat),
649                     Err(e) => Err(e),
650                 }
651             }
652 
653             SYS_FCNTL => {
654                 let fd = args[0] as i32;
655                 let cmd: Option<FcntlCommand> =
656                     <FcntlCommand as FromPrimitive>::from_u32(args[1] as u32);
657                 let arg = args[2] as i32;
658                 let res = if let Some(cmd) = cmd {
659                     Self::fcntl(fd, cmd, arg)
660                 } else {
661                     Err(SystemError::EINVAL)
662                 };
663 
664                 // kdebug!("FCNTL: fd: {}, cmd: {:?}, arg: {}, res: {:?}", fd, cmd, arg, res);
665                 res
666             }
667 
668             SYS_FTRUNCATE => {
669                 let fd = args[0] as i32;
670                 let len = args[1] as usize;
671                 let res = Self::ftruncate(fd, len);
672                 // kdebug!("FTRUNCATE: fd: {}, len: {}, res: {:?}", fd, len, res);
673                 res
674             }
675 
676             #[cfg(target_arch = "x86_64")]
677             SYS_MKNOD => {
678                 let path = args[0];
679                 let flags = args[1];
680                 let dev_t = args[2];
681                 let flags: ModeType = ModeType::from_bits_truncate(flags as u32);
682                 Self::mknod(path as *const i8, flags, DeviceNumber::from(dev_t as u32))
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                 verify_area(uaddr, core::mem::size_of::<u32>())?;
711                 verify_area(uaddr2, core::mem::size_of::<u32>())?;
712 
713                 let mut timespec = None;
714                 if utime != 0 && operation.contains(FutexFlag::FLAGS_HAS_TIMEOUT) {
715                     let reader = UserBufferReader::new(
716                         utime as *const TimeSpec,
717                         core::mem::size_of::<TimeSpec>(),
718                         true,
719                     )?;
720 
721                     timespec = Some(reader.read_one_from_user::<TimeSpec>(0)?.clone());
722                 }
723 
724                 Self::do_futex(uaddr, operation, val, timespec, uaddr2, utime as u32, val3)
725             }
726 
727             SYS_READV => Self::readv(args[0] as i32, args[1], args[2]),
728             SYS_WRITEV => Self::writev(args[0] as i32, args[1], args[2]),
729 
730             SYS_SET_TID_ADDRESS => Self::set_tid_address(args[0]),
731 
732             #[cfg(target_arch = "x86_64")]
733             SYS_LSTAT => {
734                 let path: &CStr = unsafe { CStr::from_ptr(args[0] as *const c_char) };
735                 let path: Result<&str, core::str::Utf8Error> = path.to_str();
736                 let res = if path.is_err() {
737                     Err(SystemError::EINVAL)
738                 } else {
739                     let path: &str = path.unwrap();
740                     let kstat = args[1] as *mut PosixKstat;
741                     let vaddr = VirtAddr::new(kstat as usize);
742                     match verify_area(vaddr, core::mem::size_of::<PosixKstat>()) {
743                         Ok(_) => Self::lstat(path, kstat),
744                         Err(e) => Err(e),
745                     }
746                 };
747 
748                 res
749             }
750 
751             #[cfg(target_arch = "x86_64")]
752             SYS_STAT => {
753                 let path: &CStr = unsafe { CStr::from_ptr(args[0] as *const c_char) };
754                 let path: Result<&str, core::str::Utf8Error> = path.to_str();
755                 let res = if path.is_err() {
756                     Err(SystemError::EINVAL)
757                 } else {
758                     let path: &str = path.unwrap();
759                     let kstat = args[1] as *mut PosixKstat;
760                     let vaddr = VirtAddr::new(kstat as usize);
761                     match verify_area(vaddr, core::mem::size_of::<PosixKstat>()) {
762                         Ok(_) => Self::stat(path, kstat),
763                         Err(e) => Err(e),
764                     }
765                 };
766 
767                 res
768             }
769 
770             SYS_EPOLL_CREATE => Self::epoll_create(args[0] as i32),
771             SYS_EPOLL_CREATE1 => Self::epoll_create1(args[0]),
772 
773             SYS_EPOLL_CTL => Self::epoll_ctl(
774                 args[0] as i32,
775                 args[1],
776                 args[2] as i32,
777                 VirtAddr::new(args[3]),
778             ),
779 
780             SYS_EPOLL_WAIT => Self::epoll_wait(
781                 args[0] as i32,
782                 VirtAddr::new(args[1]),
783                 args[2] as i32,
784                 args[3] as i32,
785             ),
786 
787             SYS_EPOLL_PWAIT => {
788                 let epfd = args[0] as i32;
789                 let epoll_event = VirtAddr::new(args[1]);
790                 let max_events = args[2] as i32;
791                 let timespec = args[3] as i32;
792                 let sigmask_addr = args[4] as *mut SigSet;
793 
794                 if sigmask_addr.is_null() {
795                     return Self::epoll_wait(epfd, epoll_event, max_events, timespec);
796                 }
797                 let sigmask_reader =
798                     UserBufferReader::new(sigmask_addr, core::mem::size_of::<SigSet>(), true)?;
799                 let mut sigmask = sigmask_reader.read_one_from_user::<SigSet>(0)?.clone();
800 
801                 Self::epoll_pwait(
802                     args[0] as i32,
803                     VirtAddr::new(args[1]),
804                     args[2] as i32,
805                     args[3] as i32,
806                     &mut sigmask,
807                 )
808             }
809 
810             // 目前为了适配musl-libc,以下系统调用先这样写着
811             SYS_GETRANDOM => {
812                 let flags = GRandFlags::from_bits(args[2] as u8).ok_or(SystemError::EINVAL)?;
813                 Self::get_random(args[0] as *mut u8, args[1], flags)
814             }
815 
816             SYS_SOCKETPAIR => {
817                 unimplemented!()
818             }
819 
820             #[cfg(target_arch = "x86_64")]
821             SYS_POLL => {
822                 kwarn!("SYS_POLL has not yet been implemented");
823                 Ok(0)
824             }
825 
826             SYS_RT_SIGPROCMASK => {
827                 kwarn!("SYS_RT_SIGPROCMASK has not yet been implemented");
828                 Ok(0)
829             }
830 
831             SYS_TKILL => {
832                 kwarn!("SYS_TKILL has not yet been implemented");
833                 Ok(0)
834             }
835 
836             SYS_SIGALTSTACK => {
837                 kwarn!("SYS_SIGALTSTACK has not yet been implemented");
838                 Ok(0)
839             }
840 
841             SYS_EXIT_GROUP => {
842                 kwarn!("SYS_EXIT_GROUP has not yet been implemented");
843                 Ok(0)
844             }
845 
846             SYS_MADVISE => {
847                 // 这个太吵了,总是打印,先注释掉
848                 // kwarn!("SYS_MADVISE has not yet been implemented");
849                 Ok(0)
850             }
851             SYS_GETTID => Self::gettid().map(|tid| tid.into()),
852             SYS_GETUID => Self::getuid().map(|uid| uid.into()),
853 
854             SYS_SYSLOG => {
855                 let syslog_action_type = args[0] as usize;
856                 let buf_vaddr = args[1];
857                 let len = args[2];
858                 let from_user = frame.from_user();
859                 let mut user_buffer_writer =
860                     UserBufferWriter::new(buf_vaddr as *mut u8, len, from_user)?;
861 
862                 let user_buf = user_buffer_writer.buffer(0)?;
863                 let res = Self::do_syslog(syslog_action_type, user_buf, len);
864                 res
865             }
866 
867             SYS_GETGID => Self::getgid().map(|gid| gid.into()),
868             SYS_SETUID => {
869                 kwarn!("SYS_SETUID has not yet been implemented");
870                 Ok(0)
871             }
872             SYS_SETGID => {
873                 kwarn!("SYS_SETGID has not yet been implemented");
874                 Ok(0)
875             }
876             SYS_GETEUID => Self::geteuid().map(|euid| euid.into()),
877             SYS_GETEGID => Self::getegid().map(|egid| egid.into()),
878             SYS_GETRUSAGE => {
879                 let who = args[0] as c_int;
880                 let rusage = args[1] as *mut RUsage;
881                 Self::get_rusage(who, rusage)
882             }
883 
884             #[cfg(target_arch = "x86_64")]
885             SYS_READLINK => {
886                 let path = args[0] as *const u8;
887                 let buf = args[1] as *mut u8;
888                 let bufsiz = args[2] as usize;
889                 Self::readlink(path, buf, bufsiz)
890             }
891 
892             SYS_READLINKAT => {
893                 let dirfd = args[0] as i32;
894                 let pathname = args[1] as *const u8;
895                 let buf = args[2] as *mut u8;
896                 let bufsiz = args[3] as usize;
897                 Self::readlink_at(dirfd, pathname, buf, bufsiz)
898             }
899 
900             SYS_PRLIMIT64 => {
901                 let pid = args[0];
902                 let pid = Pid::new(pid);
903                 let resource = args[1];
904                 let new_limit = args[2] as *const RLimit64;
905                 let old_limit = args[3] as *mut RLimit64;
906 
907                 Self::prlimit64(pid, resource, new_limit, old_limit)
908             }
909 
910             #[cfg(target_arch = "x86_64")]
911             SYS_ACCESS => {
912                 let pathname = args[0] as *const u8;
913                 let mode = args[1] as u32;
914                 Self::access(pathname, mode)
915             }
916 
917             SYS_FACCESSAT => {
918                 let dirfd = args[0] as i32;
919                 let pathname = args[1] as *const u8;
920                 let mode = args[2] as u32;
921                 Self::faccessat2(dirfd, pathname, mode, 0)
922             }
923 
924             SYS_FACCESSAT2 => {
925                 let dirfd = args[0] as i32;
926                 let pathname = args[1] as *const u8;
927                 let mode = args[2] as u32;
928                 let flags = args[3] as u32;
929                 Self::faccessat2(dirfd, pathname, mode, flags)
930             }
931 
932             SYS_CLOCK_GETTIME => {
933                 let clockid = args[0] as i32;
934                 let timespec = args[1] as *mut TimeSpec;
935                 Self::clock_gettime(clockid, timespec)
936             }
937 
938             SYS_SYSINFO => {
939                 let info = args[0] as *mut SysInfo;
940                 Self::sysinfo(info)
941             }
942 
943             SYS_UMASK => {
944                 let mask = args[0] as u32;
945                 Self::umask(mask)
946             }
947 
948             #[cfg(target_arch = "x86_64")]
949             SYS_CHMOD => {
950                 let pathname = args[0] as *const u8;
951                 let mode = args[1] as u32;
952                 Self::chmod(pathname, mode)
953             }
954             SYS_FCHMOD => {
955                 let fd = args[0] as i32;
956                 let mode = args[1] as u32;
957                 Self::fchmod(fd, mode)
958             }
959             SYS_FCHMODAT => {
960                 let dirfd = args[0] as i32;
961                 let pathname = args[1] as *const u8;
962                 let mode = args[2] as u32;
963                 Self::fchmodat(dirfd, pathname, mode)
964             }
965 
966             SYS_SCHED_GETAFFINITY => {
967                 // todo: 这个系统调用还没有实现
968 
969                 Err(SystemError::ENOSYS)
970             }
971 
972             SYS_SCHED_YIELD => Self::sched_yield(),
973 
974             _ => panic!("Unsupported syscall ID: {}", syscall_num),
975         };
976 
977         return r;
978     }
979 
980     pub fn put_string(
981         s: *const u8,
982         front_color: u32,
983         back_color: u32,
984     ) -> Result<usize, SystemError> {
985         return Ok(unsafe { do_put_string(s, front_color, back_color) });
986     }
987 
988     pub fn reboot() -> Result<usize, SystemError> {
989         unsafe { cpu_reset() };
990     }
991 }
992