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