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.data() 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 FileType::FramebufferDevice => kstat.mode.insert(ModeType::S_IFCHR), 790 } 791 792 return Ok(kstat); 793 } 794 795 pub fn fstat(fd: i32, usr_kstat: *mut PosixKstat) -> Result<usize, SystemError> { 796 let kstat = Self::do_fstat(fd)?; 797 if usr_kstat.is_null() { 798 return Err(SystemError::EFAULT); 799 } 800 unsafe { 801 *usr_kstat = kstat; 802 } 803 return Ok(0); 804 } 805 806 pub fn stat(path: &str, user_kstat: *mut PosixKstat) -> Result<usize, SystemError> { 807 let fd = Self::open(path, FileMode::O_RDONLY, ModeType::empty(), true)?; 808 let r = Self::fstat(fd as i32, user_kstat); 809 Self::close(fd).ok(); 810 return r; 811 } 812 813 pub fn lstat(path: &str, user_kstat: *mut PosixKstat) -> Result<usize, SystemError> { 814 let fd = Self::open(path, FileMode::O_RDONLY, ModeType::empty(), false)?; 815 let r = Self::fstat(fd as i32, user_kstat); 816 Self::close(fd).ok(); 817 return r; 818 } 819 820 pub fn mknod( 821 path_ptr: *const i8, 822 mode: ModeType, 823 dev_t: DeviceNumber, 824 ) -> Result<usize, SystemError> { 825 // 安全检验 826 let len = unsafe { CStr::from_ptr(path_ptr).to_bytes().len() }; 827 let user_buffer = UserBufferReader::new(path_ptr, len, true)?; 828 let buf = user_buffer.read_from_user::<u8>(0)?; 829 let path = core::str::from_utf8(buf).map_err(|_| SystemError::EINVAL)?; 830 831 // 文件名过长 832 if path.len() > MAX_PATHLEN as usize { 833 return Err(SystemError::ENAMETOOLONG); 834 } 835 836 let inode: Result<Arc<dyn IndexNode>, SystemError> = 837 ROOT_INODE().lookup_follow_symlink(path, VFS_MAX_FOLLOW_SYMLINK_TIMES); 838 839 if inode.is_ok() { 840 return Err(SystemError::EEXIST); 841 } 842 843 let (filename, parent_path) = rsplit_path(path); 844 845 // 查找父目录 846 let parent_inode: Arc<dyn IndexNode> = ROOT_INODE() 847 .lookup_follow_symlink(parent_path.unwrap_or("/"), VFS_MAX_FOLLOW_SYMLINK_TIMES)?; 848 // 创建nod 849 parent_inode.mknod(filename, mode, dev_t)?; 850 851 return Ok(0); 852 } 853 854 pub fn writev(fd: i32, iov: usize, count: usize) -> Result<usize, SystemError> { 855 // IoVecs会进行用户态检验 856 let iovecs = unsafe { IoVecs::from_user(iov as *const IoVec, count, false) }?; 857 858 let data = iovecs.gather(); 859 860 Self::write(fd, &data) 861 } 862 863 pub fn readv(fd: i32, iov: usize, count: usize) -> Result<usize, SystemError> { 864 // IoVecs会进行用户态检验 865 let mut iovecs = unsafe { IoVecs::from_user(iov as *const IoVec, count, true) }?; 866 867 let mut data = Vec::new(); 868 data.resize(iovecs.0.iter().map(|x| x.len()).sum(), 0); 869 870 let len = Self::read(fd, &mut data)?; 871 872 iovecs.scatter(&data[..len]); 873 874 return Ok(len); 875 } 876 877 pub fn readlink_at( 878 dirfd: i32, 879 path: *const u8, 880 user_buf: *mut u8, 881 buf_size: usize, 882 ) -> Result<usize, SystemError> { 883 let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?; 884 let mut user_buf = UserBufferWriter::new(user_buf, buf_size, true)?; 885 886 if path.len() == 0 { 887 return Err(SystemError::EINVAL); 888 } 889 890 let (inode, path) = user_path_at(&ProcessManager::current_pcb(), dirfd, &path)?; 891 892 let inode = inode.lookup(path.as_str())?; 893 if inode.metadata()?.file_type != FileType::SymLink { 894 return Err(SystemError::EINVAL); 895 } 896 897 let ubuf = user_buf.buffer::<u8>(0).unwrap(); 898 899 let mut file = File::new(inode, FileMode::O_RDONLY)?; 900 901 let len = file.read(buf_size, ubuf)?; 902 903 return Ok(len); 904 } 905 906 pub fn readlink( 907 path: *const u8, 908 user_buf: *mut u8, 909 buf_size: usize, 910 ) -> Result<usize, SystemError> { 911 return Self::readlink_at(AtFlags::AT_FDCWD.bits(), path, user_buf, buf_size); 912 } 913 914 pub fn access(pathname: *const u8, mode: u32) -> Result<usize, SystemError> { 915 return do_faccessat( 916 AtFlags::AT_FDCWD.bits(), 917 pathname, 918 ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?, 919 0, 920 ); 921 } 922 923 pub fn faccessat2( 924 dirfd: i32, 925 pathname: *const u8, 926 mode: u32, 927 flags: u32, 928 ) -> Result<usize, SystemError> { 929 return do_faccessat( 930 dirfd, 931 pathname, 932 ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?, 933 flags, 934 ); 935 } 936 937 pub fn chmod(pathname: *const u8, mode: u32) -> Result<usize, SystemError> { 938 return do_fchmodat( 939 AtFlags::AT_FDCWD.bits(), 940 pathname, 941 ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?, 942 ); 943 } 944 945 pub fn fchmodat(dirfd: i32, pathname: *const u8, mode: u32) -> Result<usize, SystemError> { 946 return do_fchmodat( 947 dirfd, 948 pathname, 949 ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?, 950 ); 951 } 952 953 pub fn fchmod(fd: i32, mode: u32) -> Result<usize, SystemError> { 954 let _mode = ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?; 955 let binding = ProcessManager::current_pcb().fd_table(); 956 let fd_table_guard = binding.read(); 957 let _file = fd_table_guard 958 .get_file_by_fd(fd) 959 .ok_or(SystemError::EBADF)?; 960 961 // fchmod没完全实现,因此不修改文件的权限 962 // todo: 实现fchmod 963 kwarn!("fchmod not fully implemented"); 964 return Ok(0); 965 } 966 } 967 968 #[repr(C)] 969 #[derive(Debug, Clone, Copy)] 970 pub struct IoVec { 971 /// 缓冲区的起始地址 972 pub iov_base: *mut u8, 973 /// 缓冲区的长度 974 pub iov_len: usize, 975 } 976 977 /// 用于存储多个来自用户空间的IoVec 978 /// 979 /// 由于目前内核中的文件系统还不支持分散读写,所以暂时只支持将用户空间的IoVec聚合成一个缓冲区,然后进行操作。 980 /// TODO:支持分散读写 981 #[derive(Debug)] 982 pub struct IoVecs(Vec<&'static mut [u8]>); 983 984 impl IoVecs { 985 /// 从用户空间的IoVec中构造IoVecs 986 /// 987 /// @param iov 用户空间的IoVec 988 /// @param iovcnt 用户空间的IoVec的数量 989 /// @param readv 是否为readv系统调用 990 /// 991 /// @return 构造成功返回IoVecs,否则返回错误码 992 pub unsafe fn from_user( 993 iov: *const IoVec, 994 iovcnt: usize, 995 _readv: bool, 996 ) -> Result<Self, SystemError> { 997 // 检查iov指针所在空间是否合法 998 verify_area( 999 VirtAddr::new(iov as usize), 1000 iovcnt * core::mem::size_of::<IoVec>(), 1001 ) 1002 .map_err(|_| SystemError::EFAULT)?; 1003 1004 // 将用户空间的IoVec转换为引用(注意:这里的引用是静态的,因为用户空间的IoVec不会被释放) 1005 let iovs: &[IoVec] = core::slice::from_raw_parts(iov, iovcnt); 1006 1007 let mut slices: Vec<&mut [u8]> = vec![]; 1008 slices.reserve(iovs.len()); 1009 1010 for iov in iovs.iter() { 1011 if iov.iov_len == 0 { 1012 continue; 1013 } 1014 1015 verify_area( 1016 VirtAddr::new(iov.iov_base as usize), 1017 iovcnt * core::mem::size_of::<IoVec>(), 1018 ) 1019 .map_err(|_| SystemError::EFAULT)?; 1020 1021 slices.push(core::slice::from_raw_parts_mut(iov.iov_base, iov.iov_len)); 1022 } 1023 1024 return Ok(Self(slices)); 1025 } 1026 1027 /// @brief 将IoVecs中的数据聚合到一个缓冲区中 1028 /// 1029 /// @return 返回聚合后的缓冲区 1030 pub fn gather(&self) -> Vec<u8> { 1031 let mut buf = Vec::new(); 1032 for slice in self.0.iter() { 1033 buf.extend_from_slice(slice); 1034 } 1035 return buf; 1036 } 1037 1038 /// @brief 将给定的数据分散写入到IoVecs中 1039 pub fn scatter(&mut self, data: &[u8]) { 1040 let mut data: &[u8] = data; 1041 for slice in self.0.iter_mut() { 1042 let len = core::cmp::min(slice.len(), data.len()); 1043 if len == 0 { 1044 continue; 1045 } 1046 1047 slice[..len].copy_from_slice(&data[..len]); 1048 data = &data[len..]; 1049 } 1050 } 1051 1052 /// @brief 创建与IoVecs等长的缓冲区 1053 /// 1054 /// @param set_len 是否设置返回的Vec的len。 1055 /// 如果为true,则返回的Vec的len为所有IoVec的长度之和; 1056 /// 否则返回的Vec的len为0,capacity为所有IoVec的长度之和. 1057 /// 1058 /// @return 返回创建的缓冲区 1059 pub fn new_buf(&self, set_len: bool) -> Vec<u8> { 1060 let total_len: usize = self.0.iter().map(|slice| slice.len()).sum(); 1061 let mut buf: Vec<u8> = Vec::with_capacity(total_len); 1062 1063 if set_len { 1064 buf.resize(total_len, 0); 1065 } 1066 return buf; 1067 } 1068 } 1069