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