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