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