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