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