1 use core::ffi::CStr; 2 3 use alloc::{ 4 string::{String, ToString}, 5 sync::Arc, 6 vec::Vec, 7 }; 8 use system_error::SystemError; 9 10 use crate::{ 11 driver::base::{block::SeekFrom, device::device_number::DeviceNumber}, 12 filesystem::vfs::file::FileDescriptorVec, 13 kerror, 14 libs::rwlock::RwLockWriteGuard, 15 mm::{verify_area, VirtAddr}, 16 process::ProcessManager, 17 syscall::{ 18 user_access::{check_and_clone_cstr, UserBufferReader, UserBufferWriter}, 19 Syscall, 20 }, 21 time::TimeSpec, 22 }; 23 24 use super::{ 25 core::{do_mkdir, do_remove_dir, do_unlink_at}, 26 fcntl::{AtFlags, FcntlCommand, FD_CLOEXEC}, 27 file::{File, FileMode}, 28 open::{do_faccessat, do_fchmodat, do_sys_open}, 29 utils::{rsplit_path, user_path_at}, 30 Dirent, FileType, IndexNode, MAX_PATHLEN, ROOT_INODE, VFS_MAX_FOLLOW_SYMLINK_TIMES, 31 }; 32 // use crate::kdebug; 33 34 pub const SEEK_SET: u32 = 0; 35 pub const SEEK_CUR: u32 = 1; 36 pub const SEEK_END: u32 = 2; 37 pub const SEEK_MAX: u32 = 3; 38 39 bitflags! { 40 /// 文件类型和权限 41 #[repr(C)] 42 pub struct ModeType: u32 { 43 /// 掩码 44 const S_IFMT = 0o0_170_000; 45 /// 文件类型 46 const S_IFSOCK = 0o140000; 47 const S_IFLNK = 0o120000; 48 const S_IFREG = 0o100000; 49 const S_IFBLK = 0o060000; 50 const S_IFDIR = 0o040000; 51 const S_IFCHR = 0o020000; 52 const S_IFIFO = 0o010000; 53 54 const S_ISUID = 0o004000; 55 const S_ISGID = 0o002000; 56 const S_ISVTX = 0o001000; 57 /// 文件用户权限 58 const S_IRWXU = 0o0700; 59 const S_IRUSR = 0o0400; 60 const S_IWUSR = 0o0200; 61 const S_IXUSR = 0o0100; 62 /// 文件组权限 63 const S_IRWXG = 0o0070; 64 const S_IRGRP = 0o0040; 65 const S_IWGRP = 0o0020; 66 const S_IXGRP = 0o0010; 67 /// 文件其他用户权限 68 const S_IRWXO = 0o0007; 69 const S_IROTH = 0o0004; 70 const S_IWOTH = 0o0002; 71 const S_IXOTH = 0o0001; 72 73 /// 0o777 74 const S_IRWXUGO = Self::S_IRWXU.bits | Self::S_IRWXG.bits | Self::S_IRWXO.bits; 75 /// 0o7777 76 const S_IALLUGO = Self::S_ISUID.bits | Self::S_ISGID.bits | Self::S_ISVTX.bits| Self::S_IRWXUGO.bits; 77 /// 0o444 78 const S_IRUGO = Self::S_IRUSR.bits | Self::S_IRGRP.bits | Self::S_IROTH.bits; 79 /// 0o222 80 const S_IWUGO = Self::S_IWUSR.bits | Self::S_IWGRP.bits | Self::S_IWOTH.bits; 81 /// 0o111 82 const S_IXUGO = Self::S_IXUSR.bits | Self::S_IXGRP.bits | Self::S_IXOTH.bits; 83 84 85 } 86 } 87 88 #[repr(C)] 89 /// # 文件信息结构体 90 pub struct PosixKstat { 91 /// 硬件设备ID 92 dev_id: u64, 93 /// inode号 94 inode: u64, 95 /// 硬链接数 96 nlink: u64, 97 /// 文件权限 98 mode: ModeType, 99 /// 所有者用户ID 100 uid: i32, 101 /// 所有者组ID 102 gid: i32, 103 /// 设备ID 104 rdev: i64, 105 /// 文件大小 106 size: i64, 107 /// 文件系统块大小 108 blcok_size: i64, 109 /// 分配的512B块数 110 blocks: u64, 111 /// 最后访问时间 112 atime: TimeSpec, 113 /// 最后修改时间 114 mtime: TimeSpec, 115 /// 最后状态变化时间 116 ctime: TimeSpec, 117 /// 用于填充结构体大小的空白数据 118 pub _pad: [i8; 24], 119 } 120 impl PosixKstat { 121 fn new() -> Self { 122 Self { 123 inode: 0, 124 dev_id: 0, 125 mode: ModeType { bits: 0 }, 126 nlink: 0, 127 uid: 0, 128 gid: 0, 129 rdev: 0, 130 size: 0, 131 atime: TimeSpec { 132 tv_sec: 0, 133 tv_nsec: 0, 134 }, 135 mtime: TimeSpec { 136 tv_sec: 0, 137 tv_nsec: 0, 138 }, 139 ctime: TimeSpec { 140 tv_sec: 0, 141 tv_nsec: 0, 142 }, 143 blcok_size: 0, 144 blocks: 0, 145 _pad: Default::default(), 146 } 147 } 148 } 149 150 /// 151 /// Arguments for how openat2(2) should open the target path. If only @flags and 152 /// @mode are non-zero, then openat2(2) operates very similarly to openat(2). 153 /// 154 /// However, unlike openat(2), unknown or invalid bits in @flags result in 155 /// -EINVAL rather than being silently ignored. @mode must be zero unless one of 156 /// {O_CREAT, O_TMPFILE} are set. 157 /// 158 /// ## 成员变量 159 /// 160 /// - flags: O_* flags. 161 /// - mode: O_CREAT/O_TMPFILE file mode. 162 /// - resolve: RESOLVE_* flags. 163 #[derive(Debug, Clone, Copy)] 164 #[repr(C)] 165 pub struct PosixOpenHow { 166 pub flags: u64, 167 pub mode: u64, 168 pub resolve: u64, 169 } 170 171 impl PosixOpenHow { 172 #[allow(dead_code)] 173 pub fn new(flags: u64, mode: u64, resolve: u64) -> Self { 174 Self { 175 flags, 176 mode, 177 resolve, 178 } 179 } 180 } 181 182 #[derive(Debug, Clone, Copy)] 183 pub struct OpenHow { 184 pub o_flags: FileMode, 185 pub mode: ModeType, 186 pub resolve: OpenHowResolve, 187 } 188 189 impl OpenHow { 190 pub fn new(mut o_flags: FileMode, mut mode: ModeType, resolve: OpenHowResolve) -> Self { 191 if !o_flags.contains(FileMode::O_CREAT) { 192 mode = ModeType::empty(); 193 } 194 195 if o_flags.contains(FileMode::O_PATH) { 196 o_flags = o_flags.intersection(FileMode::O_PATH_FLAGS); 197 } 198 199 Self { 200 o_flags, 201 mode, 202 resolve, 203 } 204 } 205 } 206 207 impl From<PosixOpenHow> for OpenHow { 208 fn from(posix_open_how: PosixOpenHow) -> Self { 209 let o_flags = FileMode::from_bits_truncate(posix_open_how.flags as u32); 210 let mode = ModeType::from_bits_truncate(posix_open_how.mode as u32); 211 let resolve = OpenHowResolve::from_bits_truncate(posix_open_how.resolve as u64); 212 return Self::new(o_flags, mode, resolve); 213 } 214 } 215 216 bitflags! { 217 pub struct OpenHowResolve: u64{ 218 /// Block mount-point crossings 219 /// (including bind-mounts). 220 const RESOLVE_NO_XDEV = 0x01; 221 222 /// Block traversal through procfs-style 223 /// "magic-links" 224 const RESOLVE_NO_MAGICLINKS = 0x02; 225 226 /// Block traversal through all symlinks 227 /// (implies OEXT_NO_MAGICLINKS) 228 const RESOLVE_NO_SYMLINKS = 0x04; 229 /// Block "lexical" trickery like 230 /// "..", symlinks, and absolute 231 const RESOLVE_BENEATH = 0x08; 232 /// Make all jumps to "/" and ".." 233 /// be scoped inside the dirfd 234 /// (similar to chroot(2)). 235 const RESOLVE_IN_ROOT = 0x10; 236 // Only complete if resolution can be 237 // completed through cached lookup. May 238 // return -EAGAIN if that's not 239 // possible. 240 const RESOLVE_CACHED = 0x20; 241 } 242 } 243 impl Syscall { 244 /// @brief 为当前进程打开一个文件 245 /// 246 /// @param path 文件路径 247 /// @param o_flags 打开文件的标志位 248 /// 249 /// @return 文件描述符编号,或者是错误码 250 pub fn open( 251 path: &str, 252 flags: FileMode, 253 mode: ModeType, 254 follow_symlink: bool, 255 ) -> Result<usize, SystemError> { 256 return do_sys_open(AtFlags::AT_FDCWD.bits(), path, flags, mode, follow_symlink); 257 } 258 259 pub fn openat( 260 dirfd: i32, 261 path: &str, 262 o_flags: FileMode, 263 mode: ModeType, 264 follow_symlink: bool, 265 ) -> Result<usize, SystemError> { 266 return do_sys_open(dirfd, path, o_flags, mode, follow_symlink); 267 } 268 269 /// @brief 关闭文件 270 /// 271 /// @param fd 文件描述符编号 272 /// 273 /// @return 成功返回0,失败返回错误码 274 pub fn close(fd: usize) -> Result<usize, SystemError> { 275 let binding = ProcessManager::current_pcb().fd_table(); 276 let mut fd_table_guard = binding.write(); 277 278 let res = fd_table_guard.drop_fd(fd as i32).map(|_| 0); 279 280 return res; 281 } 282 283 /// @brief 发送命令到文件描述符对应的设备, 284 /// 285 /// @param fd 文件描述符编号 286 /// @param cmd 设备相关的请求类型 287 /// 288 /// @return Ok(usize) 成功返回0 289 /// @return Err(SystemError) 读取失败,返回posix错误码 290 pub fn ioctl(fd: usize, cmd: u32, data: usize) -> Result<usize, SystemError> { 291 let binding = ProcessManager::current_pcb().fd_table(); 292 let fd_table_guard = binding.read(); 293 294 let file = fd_table_guard 295 .get_file_by_fd(fd as i32) 296 .ok_or(SystemError::EBADF)?; 297 298 // drop guard 以避免无法调度的问题 299 drop(fd_table_guard); 300 let r = file.lock_no_preempt().inode().ioctl(cmd, data); 301 return r; 302 } 303 304 /// @brief 根据文件描述符,读取文件数据。尝试读取的数据长度与buf的长度相同。 305 /// 306 /// @param fd 文件描述符编号 307 /// @param buf 输出缓冲区。 308 /// 309 /// @return Ok(usize) 成功读取的数据的字节数 310 /// @return Err(SystemError) 读取失败,返回posix错误码 311 pub fn read(fd: i32, buf: &mut [u8]) -> Result<usize, SystemError> { 312 let binding = ProcessManager::current_pcb().fd_table(); 313 let fd_table_guard = binding.read(); 314 315 let file = fd_table_guard.get_file_by_fd(fd); 316 if file.is_none() { 317 return Err(SystemError::EBADF); 318 } 319 // drop guard 以避免无法调度的问题 320 drop(fd_table_guard); 321 let file = file.unwrap(); 322 323 return file.lock_no_preempt().read(buf.len(), buf); 324 } 325 326 /// @brief 根据文件描述符,向文件写入数据。尝试写入的数据长度与buf的长度相同。 327 /// 328 /// @param fd 文件描述符编号 329 /// @param buf 输入缓冲区。 330 /// 331 /// @return Ok(usize) 成功写入的数据的字节数 332 /// @return Err(SystemError) 写入失败,返回posix错误码 333 pub fn write(fd: i32, buf: &[u8]) -> Result<usize, SystemError> { 334 let binding = ProcessManager::current_pcb().fd_table(); 335 let fd_table_guard = binding.read(); 336 337 let file = fd_table_guard 338 .get_file_by_fd(fd) 339 .ok_or(SystemError::EBADF)?; 340 341 // drop guard 以避免无法调度的问题 342 drop(fd_table_guard); 343 return file.lock_no_preempt().write(buf.len(), buf); 344 } 345 346 /// @brief 调整文件操作指针的位置 347 /// 348 /// @param fd 文件描述符编号 349 /// @param seek 调整的方式 350 /// 351 /// @return Ok(usize) 调整后,文件访问指针相对于文件头部的偏移量 352 /// @return Err(SystemError) 调整失败,返回posix错误码 353 pub fn lseek(fd: i32, seek: SeekFrom) -> Result<usize, SystemError> { 354 let binding = ProcessManager::current_pcb().fd_table(); 355 let fd_table_guard = binding.read(); 356 let file = fd_table_guard 357 .get_file_by_fd(fd) 358 .ok_or(SystemError::EBADF)?; 359 360 // drop guard 以避免无法调度的问题 361 drop(fd_table_guard); 362 return file.lock_no_preempt().lseek(seek); 363 } 364 365 /// @brief 切换工作目录 366 /// 367 /// @param dest_path 目标路径 368 /// 369 /// @return 返回码 描述 370 /// 0 | 成功 371 /// 372 /// EACCESS | 权限不足 373 /// 374 /// ELOOP | 解析path时遇到路径循环 375 /// 376 /// ENAMETOOLONG | 路径名过长 377 /// 378 /// ENOENT | 目标文件或目录不存在 379 /// 380 /// ENODIR | 检索期间发现非目录项 381 /// 382 /// ENOMEM | 系统内存不足 383 /// 384 /// EFAULT | 错误的地址 385 /// 386 /// ENAMETOOLONG | 路径过长 387 pub fn chdir(dest_path: &str) -> Result<usize, SystemError> { 388 let proc = ProcessManager::current_pcb(); 389 // Copy path to kernel space to avoid some security issues 390 let path = dest_path.to_string(); 391 let mut new_path = String::from(""); 392 if path.len() > 0 { 393 let cwd = match path.as_bytes()[0] { 394 b'/' => String::from("/"), 395 _ => proc.basic().cwd(), 396 }; 397 let mut cwd_vec: Vec<_> = cwd.split("/").filter(|&x| x != "").collect(); 398 let path_split = path.split("/").filter(|&x| x != ""); 399 for seg in path_split { 400 if seg == ".." { 401 cwd_vec.pop(); 402 } else if seg == "." { 403 // 当前目录 404 } else { 405 cwd_vec.push(seg); 406 } 407 } 408 //proc.basic().set_path(String::from("")); 409 for seg in cwd_vec { 410 new_path.push_str("/"); 411 new_path.push_str(seg); 412 } 413 if new_path == "" { 414 new_path = String::from("/"); 415 } 416 } 417 let inode = 418 match ROOT_INODE().lookup_follow_symlink(&new_path, VFS_MAX_FOLLOW_SYMLINK_TIMES) { 419 Err(e) => { 420 kerror!("Change Directory Failed, Error = {:?}", e); 421 return Err(SystemError::ENOENT); 422 } 423 Ok(i) => i, 424 }; 425 let metadata = inode.metadata()?; 426 if metadata.file_type == FileType::Dir { 427 proc.basic_mut().set_cwd(String::from(new_path)); 428 return Ok(0); 429 } else { 430 return Err(SystemError::ENOTDIR); 431 } 432 } 433 434 /// @brief 获取当前进程的工作目录路径 435 /// 436 /// @param buf 指向缓冲区的指针 437 /// @param size 缓冲区的大小 438 /// 439 /// @return 成功,返回的指针指向包含工作目录路径的字符串 440 /// @return 错误,没有足够的空间 441 pub fn getcwd(buf: &mut [u8]) -> Result<VirtAddr, SystemError> { 442 let proc = ProcessManager::current_pcb(); 443 let cwd = proc.basic().cwd(); 444 445 let cwd_bytes = cwd.as_bytes(); 446 let cwd_len = cwd_bytes.len(); 447 if cwd_len + 1 > buf.len() { 448 return Err(SystemError::ENOMEM); 449 } 450 buf[..cwd_len].copy_from_slice(cwd_bytes); 451 buf[cwd_len] = 0; 452 453 return Ok(VirtAddr::new(buf.as_ptr() as usize)); 454 } 455 456 /// @brief 获取目录中的数据 457 /// 458 /// TODO: 这个函数的语义与Linux不一致,需要修改!!! 459 /// 460 /// @param fd 文件描述符号 461 /// @param buf 输出缓冲区 462 /// 463 /// @return 成功返回读取的字节数,失败返回错误码 464 pub fn getdents(fd: i32, buf: &mut [u8]) -> Result<usize, SystemError> { 465 let dirent = 466 unsafe { (buf.as_mut_ptr() as *mut Dirent).as_mut() }.ok_or(SystemError::EFAULT)?; 467 468 if fd < 0 || fd as usize > FileDescriptorVec::PROCESS_MAX_FD { 469 return Err(SystemError::EBADF); 470 } 471 472 // 获取fd 473 let binding = ProcessManager::current_pcb().fd_table(); 474 let fd_table_guard = binding.read(); 475 let file = fd_table_guard 476 .get_file_by_fd(fd) 477 .ok_or(SystemError::EBADF)?; 478 479 // drop guard 以避免无法调度的问题 480 drop(fd_table_guard); 481 482 let res = file.lock_no_preempt().readdir(dirent).map(|x| x as usize); 483 484 return res; 485 } 486 487 /// @brief 创建文件夹 488 /// 489 /// @param path(r8) 路径 / mode(r9) 模式 490 /// 491 /// @return uint64_t 负数错误码 / 0表示成功 492 pub fn mkdir(path: &str, mode: usize) -> Result<usize, SystemError> { 493 return do_mkdir(path, FileMode::from_bits_truncate(mode as u32)).map(|x| x as usize); 494 } 495 496 /// **删除文件夹、取消文件的链接、删除文件的系统调用** 497 /// 498 /// ## 参数 499 /// 500 /// - `dirfd`:文件夹的文件描述符.目前暂未实现 501 /// - `pathname`:文件夹的路径 502 /// - `flags`:标志位 503 /// 504 /// 505 pub fn unlinkat(dirfd: i32, pathname: &str, flags: u32) -> Result<usize, SystemError> { 506 let flags = AtFlags::from_bits(flags as i32).ok_or(SystemError::EINVAL)?; 507 508 if flags.contains(AtFlags::AT_REMOVEDIR) { 509 // kdebug!("rmdir"); 510 match do_remove_dir(dirfd, &pathname) { 511 Err(err) => { 512 kerror!("Failed to Remove Directory, Error Code = {:?}", err); 513 return Err(err); 514 } 515 Ok(_) => { 516 return Ok(0); 517 } 518 } 519 } 520 521 match do_unlink_at(dirfd, &pathname) { 522 Err(err) => { 523 kerror!("Failed to Remove Directory, Error Code = {:?}", err); 524 return Err(err); 525 } 526 Ok(_) => { 527 return Ok(0); 528 } 529 } 530 } 531 532 pub fn unlink(pathname: *const u8) -> Result<usize, SystemError> { 533 if pathname.is_null() { 534 return Err(SystemError::EFAULT); 535 } 536 let ureader = UserBufferReader::new(pathname, MAX_PATHLEN, true)?; 537 538 let buf: &[u8] = ureader.buffer(0).unwrap(); 539 540 let pathname: &CStr = CStr::from_bytes_until_nul(buf).map_err(|_| SystemError::EINVAL)?; 541 542 let pathname: &str = pathname.to_str().map_err(|_| SystemError::EINVAL)?; 543 if pathname.len() >= MAX_PATHLEN { 544 return Err(SystemError::ENAMETOOLONG); 545 } 546 let pathname = pathname.trim(); 547 548 return do_unlink_at(AtFlags::AT_FDCWD.bits(), pathname).map(|v| v as usize); 549 } 550 551 /// @brief 根据提供的文件描述符的fd,复制对应的文件结构体,并返回新复制的文件结构体对应的fd 552 pub fn dup(oldfd: i32) -> Result<usize, SystemError> { 553 let binding = ProcessManager::current_pcb().fd_table(); 554 let mut fd_table_guard = binding.write(); 555 556 let old_file = fd_table_guard 557 .get_file_by_fd(oldfd) 558 .ok_or(SystemError::EBADF)?; 559 560 let new_file = old_file 561 .lock_no_preempt() 562 .try_clone() 563 .ok_or(SystemError::EBADF)?; 564 // 申请文件描述符,并把文件对象存入其中 565 let res = fd_table_guard.alloc_fd(new_file, None).map(|x| x as usize); 566 return res; 567 } 568 569 /// 根据提供的文件描述符的fd,和指定新fd,复制对应的文件结构体, 570 /// 并返回新复制的文件结构体对应的fd. 571 /// 如果新fd已经打开,则会先关闭新fd. 572 /// 573 /// ## 参数 574 /// 575 /// - `oldfd`:旧文件描述符 576 /// - `newfd`:新文件描述符 577 /// 578 /// ## 返回值 579 /// 580 /// - 成功:新文件描述符 581 /// - 失败:错误码 582 pub fn dup2(oldfd: i32, newfd: i32) -> Result<usize, SystemError> { 583 let binding = ProcessManager::current_pcb().fd_table(); 584 let mut fd_table_guard = binding.write(); 585 return Self::do_dup2(oldfd, newfd, &mut fd_table_guard); 586 } 587 588 fn do_dup2( 589 oldfd: i32, 590 newfd: i32, 591 fd_table_guard: &mut RwLockWriteGuard<'_, FileDescriptorVec>, 592 ) -> Result<usize, SystemError> { 593 // 确认oldfd, newid是否有效 594 if !(FileDescriptorVec::validate_fd(oldfd) && FileDescriptorVec::validate_fd(newfd)) { 595 return Err(SystemError::EBADF); 596 } 597 598 if oldfd == newfd { 599 // 若oldfd与newfd相等 600 return Ok(newfd as usize); 601 } 602 let new_exists = fd_table_guard.get_file_by_fd(newfd).is_some(); 603 if new_exists { 604 // close newfd 605 if let Err(_) = fd_table_guard.drop_fd(newfd) { 606 // An I/O error occurred while attempting to close fildes2. 607 return Err(SystemError::EIO); 608 } 609 } 610 611 let old_file = fd_table_guard 612 .get_file_by_fd(oldfd) 613 .ok_or(SystemError::EBADF)?; 614 let new_file = old_file 615 .lock_no_preempt() 616 .try_clone() 617 .ok_or(SystemError::EBADF)?; 618 // 申请文件描述符,并把文件对象存入其中 619 let res = fd_table_guard 620 .alloc_fd(new_file, Some(newfd)) 621 .map(|x| x as usize); 622 return res; 623 } 624 625 /// # fcntl 626 /// 627 /// ## 参数 628 /// 629 /// - `fd`:文件描述符 630 /// - `cmd`:命令 631 /// - `arg`:参数 632 pub fn fcntl(fd: i32, cmd: FcntlCommand, arg: i32) -> Result<usize, SystemError> { 633 match cmd { 634 FcntlCommand::DupFd => { 635 if arg < 0 || arg as usize >= FileDescriptorVec::PROCESS_MAX_FD { 636 return Err(SystemError::EBADF); 637 } 638 let arg = arg as usize; 639 for i in arg..FileDescriptorVec::PROCESS_MAX_FD { 640 let binding = ProcessManager::current_pcb().fd_table(); 641 let mut fd_table_guard = binding.write(); 642 if fd_table_guard.get_file_by_fd(fd).is_none() { 643 return Self::do_dup2(fd, i as i32, &mut fd_table_guard); 644 } 645 } 646 return Err(SystemError::EMFILE); 647 } 648 FcntlCommand::GetFd => { 649 // Get file descriptor flags. 650 let binding = ProcessManager::current_pcb().fd_table(); 651 let fd_table_guard = binding.read(); 652 if let Some(file) = fd_table_guard.get_file_by_fd(fd) { 653 // drop guard 以避免无法调度的问题 654 drop(fd_table_guard); 655 656 if file.lock().close_on_exec() { 657 return Ok(FD_CLOEXEC as usize); 658 } 659 } 660 return Err(SystemError::EBADF); 661 } 662 FcntlCommand::SetFd => { 663 // Set file descriptor flags. 664 let binding = ProcessManager::current_pcb().fd_table(); 665 let fd_table_guard = binding.write(); 666 667 if let Some(file) = fd_table_guard.get_file_by_fd(fd) { 668 // drop guard 以避免无法调度的问题 669 drop(fd_table_guard); 670 let arg = arg as u32; 671 if arg & FD_CLOEXEC != 0 { 672 file.lock().set_close_on_exec(true); 673 } else { 674 file.lock().set_close_on_exec(false); 675 } 676 return Ok(0); 677 } 678 return Err(SystemError::EBADF); 679 } 680 681 FcntlCommand::GetFlags => { 682 // Get file status flags. 683 let binding = ProcessManager::current_pcb().fd_table(); 684 let fd_table_guard = binding.read(); 685 686 if let Some(file) = fd_table_guard.get_file_by_fd(fd) { 687 // drop guard 以避免无法调度的问题 688 drop(fd_table_guard); 689 return Ok(file.lock_no_preempt().mode().bits() as usize); 690 } 691 692 return Err(SystemError::EBADF); 693 } 694 FcntlCommand::SetFlags => { 695 // Set file status flags. 696 let binding = ProcessManager::current_pcb().fd_table(); 697 let fd_table_guard = binding.write(); 698 699 if let Some(file) = fd_table_guard.get_file_by_fd(fd) { 700 let arg = arg as u32; 701 let mode = FileMode::from_bits(arg).ok_or(SystemError::EINVAL)?; 702 // drop guard 以避免无法调度的问题 703 drop(fd_table_guard); 704 file.lock_no_preempt().set_mode(mode)?; 705 return Ok(0); 706 } 707 708 return Err(SystemError::EBADF); 709 } 710 _ => { 711 // TODO: unimplemented 712 // 未实现的命令,返回0,不报错。 713 714 // kwarn!("fcntl: unimplemented command: {:?}, defaults to 0.", cmd); 715 return Ok(0); 716 } 717 } 718 } 719 720 /// # ftruncate 721 /// 722 /// ## 描述 723 /// 724 /// 改变文件大小. 725 /// 如果文件大小大于原来的大小,那么文件的内容将会被扩展到指定的大小,新的空间将会用0填充. 726 /// 如果文件大小小于原来的大小,那么文件的内容将会被截断到指定的大小. 727 /// 728 /// ## 参数 729 /// 730 /// - `fd`:文件描述符 731 /// - `len`:文件大小 732 /// 733 /// ## 返回值 734 /// 735 /// 如果成功,返回0,否则返回错误码. 736 pub fn ftruncate(fd: i32, len: usize) -> Result<usize, SystemError> { 737 let binding = ProcessManager::current_pcb().fd_table(); 738 let fd_table_guard = binding.read(); 739 740 if let Some(file) = fd_table_guard.get_file_by_fd(fd) { 741 // drop guard 以避免无法调度的问题 742 drop(fd_table_guard); 743 let r = file.lock_no_preempt().ftruncate(len).map(|_| 0); 744 return r; 745 } 746 747 return Err(SystemError::EBADF); 748 } 749 750 fn do_fstat(fd: i32) -> Result<PosixKstat, SystemError> { 751 let binding = ProcessManager::current_pcb().fd_table(); 752 let fd_table_guard = binding.read(); 753 let file = fd_table_guard 754 .get_file_by_fd(fd) 755 .ok_or(SystemError::EBADF)?; 756 // drop guard 以避免无法调度的问题 757 drop(fd_table_guard); 758 759 let mut kstat = PosixKstat::new(); 760 // 获取文件信息 761 let metadata = file.lock().metadata()?; 762 kstat.size = metadata.size as i64; 763 kstat.dev_id = metadata.dev_id as u64; 764 kstat.inode = metadata.inode_id.into() as u64; 765 kstat.blcok_size = metadata.blk_size as i64; 766 kstat.blocks = metadata.blocks as u64; 767 768 kstat.atime.tv_sec = metadata.atime.tv_sec; 769 kstat.atime.tv_nsec = metadata.atime.tv_nsec; 770 kstat.mtime.tv_sec = metadata.mtime.tv_sec; 771 kstat.mtime.tv_nsec = metadata.mtime.tv_nsec; 772 kstat.ctime.tv_sec = metadata.ctime.tv_sec; 773 kstat.ctime.tv_nsec = metadata.ctime.tv_nsec; 774 775 kstat.nlink = metadata.nlinks as u64; 776 kstat.uid = metadata.uid as i32; 777 kstat.gid = metadata.gid as i32; 778 kstat.rdev = metadata.raw_dev as i64; 779 kstat.mode = metadata.mode; 780 match file.lock().file_type() { 781 FileType::File => kstat.mode.insert(ModeType::S_IFREG), 782 FileType::Dir => kstat.mode.insert(ModeType::S_IFDIR), 783 FileType::BlockDevice => kstat.mode.insert(ModeType::S_IFBLK), 784 FileType::CharDevice => kstat.mode.insert(ModeType::S_IFCHR), 785 FileType::SymLink => kstat.mode.insert(ModeType::S_IFLNK), 786 FileType::Socket => kstat.mode.insert(ModeType::S_IFSOCK), 787 FileType::Pipe => kstat.mode.insert(ModeType::S_IFIFO), 788 FileType::KvmDevice => kstat.mode.insert(ModeType::S_IFCHR), 789 } 790 791 return Ok(kstat); 792 } 793 794 pub fn fstat(fd: i32, usr_kstat: *mut PosixKstat) -> Result<usize, SystemError> { 795 let kstat = Self::do_fstat(fd)?; 796 if usr_kstat.is_null() { 797 return Err(SystemError::EFAULT); 798 } 799 unsafe { 800 *usr_kstat = kstat; 801 } 802 return Ok(0); 803 } 804 805 pub fn stat(path: &str, user_kstat: *mut PosixKstat) -> Result<usize, SystemError> { 806 let fd = Self::open(path, FileMode::O_RDONLY, ModeType::empty(), true)?; 807 let r = Self::fstat(fd as i32, user_kstat); 808 Self::close(fd).ok(); 809 return r; 810 } 811 812 pub fn lstat(path: &str, user_kstat: *mut PosixKstat) -> Result<usize, SystemError> { 813 let fd = Self::open(path, FileMode::O_RDONLY, ModeType::empty(), false)?; 814 let r = Self::fstat(fd as i32, user_kstat); 815 Self::close(fd).ok(); 816 return r; 817 } 818 819 pub fn mknod( 820 path_ptr: *const i8, 821 mode: ModeType, 822 dev_t: DeviceNumber, 823 ) -> Result<usize, SystemError> { 824 // 安全检验 825 let len = unsafe { CStr::from_ptr(path_ptr).to_bytes().len() }; 826 let user_buffer = UserBufferReader::new(path_ptr, len, true)?; 827 let buf = user_buffer.read_from_user::<u8>(0)?; 828 let path = core::str::from_utf8(buf).map_err(|_| SystemError::EINVAL)?; 829 830 // 文件名过长 831 if path.len() > MAX_PATHLEN as usize { 832 return Err(SystemError::ENAMETOOLONG); 833 } 834 835 let inode: Result<Arc<dyn IndexNode>, SystemError> = 836 ROOT_INODE().lookup_follow_symlink(path, VFS_MAX_FOLLOW_SYMLINK_TIMES); 837 838 if inode.is_ok() { 839 return Err(SystemError::EEXIST); 840 } 841 842 let (filename, parent_path) = rsplit_path(path); 843 844 // 查找父目录 845 let parent_inode: Arc<dyn IndexNode> = ROOT_INODE() 846 .lookup_follow_symlink(parent_path.unwrap_or("/"), VFS_MAX_FOLLOW_SYMLINK_TIMES)?; 847 // 创建nod 848 parent_inode.mknod(filename, mode, dev_t)?; 849 850 return Ok(0); 851 } 852 853 pub fn writev(fd: i32, iov: usize, count: usize) -> Result<usize, SystemError> { 854 // IoVecs会进行用户态检验 855 let iovecs = unsafe { IoVecs::from_user(iov as *const IoVec, count, false) }?; 856 857 let data = iovecs.gather(); 858 859 Self::write(fd, &data) 860 } 861 862 pub fn readv(fd: i32, iov: usize, count: usize) -> Result<usize, SystemError> { 863 // IoVecs会进行用户态检验 864 let mut iovecs = unsafe { IoVecs::from_user(iov as *const IoVec, count, true) }?; 865 866 let mut data = Vec::new(); 867 data.resize(iovecs.0.iter().map(|x| x.len()).sum(), 0); 868 869 let len = Self::read(fd, &mut data)?; 870 871 iovecs.scatter(&data[..len]); 872 873 return Ok(len); 874 } 875 876 pub fn readlink_at( 877 dirfd: i32, 878 path: *const u8, 879 user_buf: *mut u8, 880 buf_size: usize, 881 ) -> Result<usize, SystemError> { 882 let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?; 883 let mut user_buf = UserBufferWriter::new(user_buf, buf_size, true)?; 884 885 if path.len() == 0 { 886 return Err(SystemError::EINVAL); 887 } 888 889 let (inode, path) = user_path_at(&ProcessManager::current_pcb(), dirfd, &path)?; 890 891 let inode = inode.lookup(path.as_str())?; 892 if inode.metadata()?.file_type != FileType::SymLink { 893 return Err(SystemError::EINVAL); 894 } 895 896 let ubuf = user_buf.buffer::<u8>(0).unwrap(); 897 898 let mut file = File::new(inode, FileMode::O_RDONLY)?; 899 900 let len = file.read(buf_size, ubuf)?; 901 902 return Ok(len); 903 } 904 905 pub fn readlink( 906 path: *const u8, 907 user_buf: *mut u8, 908 buf_size: usize, 909 ) -> Result<usize, SystemError> { 910 return Self::readlink_at(AtFlags::AT_FDCWD.bits(), path, user_buf, buf_size); 911 } 912 913 pub fn access(pathname: *const u8, mode: u32) -> Result<usize, SystemError> { 914 return do_faccessat( 915 AtFlags::AT_FDCWD.bits(), 916 pathname, 917 ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?, 918 0, 919 ); 920 } 921 922 pub fn faccessat2( 923 dirfd: i32, 924 pathname: *const u8, 925 mode: u32, 926 flags: u32, 927 ) -> Result<usize, SystemError> { 928 return do_faccessat( 929 dirfd, 930 pathname, 931 ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?, 932 flags, 933 ); 934 } 935 936 pub fn chmod(pathname: *const u8, mode: u32) -> Result<usize, SystemError> { 937 return do_fchmodat( 938 AtFlags::AT_FDCWD.bits(), 939 pathname, 940 ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?, 941 ); 942 } 943 944 pub fn fchmodat(dirfd: i32, pathname: *const u8, mode: u32) -> Result<usize, SystemError> { 945 return do_fchmodat( 946 dirfd, 947 pathname, 948 ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?, 949 ); 950 } 951 952 pub fn fchmod(fd: i32, mode: u32) -> Result<usize, SystemError> { 953 let _mode = ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?; 954 let binding = ProcessManager::current_pcb().fd_table(); 955 let fd_table_guard = binding.read(); 956 let _file = fd_table_guard 957 .get_file_by_fd(fd) 958 .ok_or(SystemError::EBADF)?; 959 960 // fchmod没完全实现,因此不修改文件的权限 961 // todo: 实现fchmod 962 kwarn!("fchmod not fully implemented"); 963 return Ok(0); 964 } 965 } 966 967 #[repr(C)] 968 #[derive(Debug, Clone, Copy)] 969 pub struct IoVec { 970 /// 缓冲区的起始地址 971 pub iov_base: *mut u8, 972 /// 缓冲区的长度 973 pub iov_len: usize, 974 } 975 976 /// 用于存储多个来自用户空间的IoVec 977 /// 978 /// 由于目前内核中的文件系统还不支持分散读写,所以暂时只支持将用户空间的IoVec聚合成一个缓冲区,然后进行操作。 979 /// TODO:支持分散读写 980 #[derive(Debug)] 981 pub struct IoVecs(Vec<&'static mut [u8]>); 982 983 impl IoVecs { 984 /// 从用户空间的IoVec中构造IoVecs 985 /// 986 /// @param iov 用户空间的IoVec 987 /// @param iovcnt 用户空间的IoVec的数量 988 /// @param readv 是否为readv系统调用 989 /// 990 /// @return 构造成功返回IoVecs,否则返回错误码 991 pub unsafe fn from_user( 992 iov: *const IoVec, 993 iovcnt: usize, 994 _readv: bool, 995 ) -> Result<Self, SystemError> { 996 // 检查iov指针所在空间是否合法 997 verify_area( 998 VirtAddr::new(iov as usize), 999 iovcnt * core::mem::size_of::<IoVec>(), 1000 ) 1001 .map_err(|_| SystemError::EFAULT)?; 1002 1003 // 将用户空间的IoVec转换为引用(注意:这里的引用是静态的,因为用户空间的IoVec不会被释放) 1004 let iovs: &[IoVec] = core::slice::from_raw_parts(iov, iovcnt); 1005 1006 let mut slices: Vec<&mut [u8]> = vec![]; 1007 slices.reserve(iovs.len()); 1008 1009 for iov in iovs.iter() { 1010 if iov.iov_len == 0 { 1011 continue; 1012 } 1013 1014 verify_area( 1015 VirtAddr::new(iov.iov_base as usize), 1016 iovcnt * core::mem::size_of::<IoVec>(), 1017 ) 1018 .map_err(|_| SystemError::EFAULT)?; 1019 1020 slices.push(core::slice::from_raw_parts_mut(iov.iov_base, iov.iov_len)); 1021 } 1022 1023 return Ok(Self(slices)); 1024 } 1025 1026 /// @brief 将IoVecs中的数据聚合到一个缓冲区中 1027 /// 1028 /// @return 返回聚合后的缓冲区 1029 pub fn gather(&self) -> Vec<u8> { 1030 let mut buf = Vec::new(); 1031 for slice in self.0.iter() { 1032 buf.extend_from_slice(slice); 1033 } 1034 return buf; 1035 } 1036 1037 /// @brief 将给定的数据分散写入到IoVecs中 1038 pub fn scatter(&mut self, data: &[u8]) { 1039 let mut data: &[u8] = data; 1040 for slice in self.0.iter_mut() { 1041 let len = core::cmp::min(slice.len(), data.len()); 1042 if len == 0 { 1043 continue; 1044 } 1045 1046 slice[..len].copy_from_slice(&data[..len]); 1047 data = &data[len..]; 1048 } 1049 } 1050 1051 /// @brief 创建与IoVecs等长的缓冲区 1052 /// 1053 /// @param set_len 是否设置返回的Vec的len。 1054 /// 如果为true,则返回的Vec的len为所有IoVec的长度之和; 1055 /// 否则返回的Vec的len为0,capacity为所有IoVec的长度之和. 1056 /// 1057 /// @return 返回创建的缓冲区 1058 pub fn new_buf(&self, set_len: bool) -> Vec<u8> { 1059 let total_len: usize = self.0.iter().map(|slice| slice.len()).sum(); 1060 let mut buf: Vec<u8> = Vec::with_capacity(total_len); 1061 1062 if set_len { 1063 buf.resize(total_len, 0); 1064 } 1065 return buf; 1066 } 1067 } 1068