1 use core::ffi::c_void; 2 use core::mem::size_of; 3 4 use alloc::string::ToString; 5 use alloc::{string::String, sync::Arc, vec::Vec}; 6 use log::warn; 7 use system_error::SystemError; 8 9 use crate::producefs; 10 use crate::{ 11 driver::base::{block::SeekFrom, device::device_number::DeviceNumber}, 12 filesystem::vfs::{core as Vcore, file::FileDescriptorVec}, 13 libs::rwlock::RwLockWriteGuard, 14 mm::{verify_area, VirtAddr}, 15 process::ProcessManager, 16 syscall::{ 17 user_access::{self, check_and_clone_cstr, UserBufferWriter}, 18 Syscall, 19 }, 20 time::PosixTimeSpec, 21 }; 22 23 use super::{ 24 core::{do_mkdir_at, do_remove_dir, do_unlink_at}, 25 fcntl::{AtFlags, FcntlCommand, FD_CLOEXEC}, 26 file::{File, FileMode}, 27 open::{do_faccessat, do_fchmodat, do_sys_open}, 28 utils::{rsplit_path, user_path_at}, 29 Dirent, FileType, IndexNode, SuperBlock, FSMAKER, MAX_PATHLEN, ROOT_INODE, 30 VFS_MAX_FOLLOW_SYMLINK_TIMES, 31 }; 32 33 pub const SEEK_SET: u32 = 0; 34 pub const SEEK_CUR: u32 = 1; 35 pub const SEEK_END: u32 = 2; 36 pub const SEEK_MAX: u32 = 3; 37 38 bitflags! { 39 /// 文件类型和权限 40 #[repr(C)] 41 pub struct ModeType: u32 { 42 /// 掩码 43 const S_IFMT = 0o0_170_000; 44 /// 文件类型 45 const S_IFSOCK = 0o140000; 46 const S_IFLNK = 0o120000; 47 const S_IFREG = 0o100000; 48 const S_IFBLK = 0o060000; 49 const S_IFDIR = 0o040000; 50 const S_IFCHR = 0o020000; 51 const S_IFIFO = 0o010000; 52 53 const S_ISUID = 0o004000; 54 const S_ISGID = 0o002000; 55 const S_ISVTX = 0o001000; 56 /// 文件用户权限 57 const S_IRWXU = 0o0700; 58 const S_IRUSR = 0o0400; 59 const S_IWUSR = 0o0200; 60 const S_IXUSR = 0o0100; 61 /// 文件组权限 62 const S_IRWXG = 0o0070; 63 const S_IRGRP = 0o0040; 64 const S_IWGRP = 0o0020; 65 const S_IXGRP = 0o0010; 66 /// 文件其他用户权限 67 const S_IRWXO = 0o0007; 68 const S_IROTH = 0o0004; 69 const S_IWOTH = 0o0002; 70 const S_IXOTH = 0o0001; 71 72 /// 0o777 73 const S_IRWXUGO = Self::S_IRWXU.bits | Self::S_IRWXG.bits | Self::S_IRWXO.bits; 74 /// 0o7777 75 const S_IALLUGO = Self::S_ISUID.bits | Self::S_ISGID.bits | Self::S_ISVTX.bits| Self::S_IRWXUGO.bits; 76 /// 0o444 77 const S_IRUGO = Self::S_IRUSR.bits | Self::S_IRGRP.bits | Self::S_IROTH.bits; 78 /// 0o222 79 const S_IWUGO = Self::S_IWUSR.bits | Self::S_IWGRP.bits | Self::S_IWOTH.bits; 80 /// 0o111 81 const S_IXUGO = Self::S_IXUSR.bits | Self::S_IXGRP.bits | Self::S_IXOTH.bits; 82 83 84 } 85 } 86 87 #[repr(C)] 88 #[derive(Clone, Copy)] 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: PosixTimeSpec, 113 /// 最后修改时间 114 mtime: PosixTimeSpec, 115 /// 最后状态变化时间 116 ctime: PosixTimeSpec, 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: PosixTimeSpec { 132 tv_sec: 0, 133 tv_nsec: 0, 134 }, 135 mtime: PosixTimeSpec { 136 tv_sec: 0, 137 tv_nsec: 0, 138 }, 139 ctime: PosixTimeSpec { 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 #[repr(C)] 151 #[derive(Clone, Copy)] 152 /// # 文件信息结构体X 153 pub struct PosixStatx { 154 /* 0x00 */ 155 stx_mask: PosixStatxMask, 156 /// 文件系统块大小 157 stx_blksize: u32, 158 /// Flags conveying information about the file [uncond] 159 stx_attributes: StxAttributes, 160 /* 0x10 */ 161 /// 硬链接数 162 stx_nlink: u32, 163 /// 所有者用户ID 164 stx_uid: u32, 165 /// 所有者组ID 166 stx_gid: u32, 167 /// 文件权限 168 stx_mode: ModeType, 169 170 /* 0x20 */ 171 /// inode号 172 stx_inode: u64, 173 /// 文件大小 174 stx_size: i64, 175 /// 分配的512B块数 176 stx_blocks: u64, 177 /// Mask to show what's supported in stx_attributes 178 stx_attributes_mask: StxAttributes, 179 180 /* 0x40 */ 181 /// 最后访问时间 182 stx_atime: PosixTimeSpec, 183 /// 文件创建时间 184 stx_btime: PosixTimeSpec, 185 /// 最后状态变化时间 186 stx_ctime: PosixTimeSpec, 187 /// 最后修改时间 188 stx_mtime: PosixTimeSpec, 189 190 /* 0x80 */ 191 /// 主设备ID 192 stx_rdev_major: u32, 193 /// 次设备ID 194 stx_rdev_minor: u32, 195 /// 主硬件设备ID 196 stx_dev_major: u32, 197 /// 次硬件设备ID 198 stx_dev_minor: u32, 199 200 /* 0x90 */ 201 stx_mnt_id: u64, 202 stx_dio_mem_align: u32, 203 stx_dio_offset_align: u32, 204 } 205 impl PosixStatx { 206 fn new() -> Self { 207 Self { 208 stx_mask: PosixStatxMask::STATX_BASIC_STATS, 209 stx_blksize: 0, 210 stx_attributes: StxAttributes::STATX_ATTR_APPEND, 211 stx_nlink: 0, 212 stx_uid: 0, 213 stx_gid: 0, 214 stx_mode: ModeType { bits: 0 }, 215 stx_inode: 0, 216 stx_size: 0, 217 stx_blocks: 0, 218 stx_attributes_mask: StxAttributes::STATX_ATTR_APPEND, 219 stx_atime: PosixTimeSpec { 220 tv_sec: 0, 221 tv_nsec: 0, 222 }, 223 stx_btime: PosixTimeSpec { 224 tv_sec: 0, 225 tv_nsec: 0, 226 }, 227 stx_ctime: PosixTimeSpec { 228 tv_sec: 0, 229 tv_nsec: 0, 230 }, 231 stx_mtime: PosixTimeSpec { 232 tv_sec: 0, 233 tv_nsec: 0, 234 }, 235 stx_rdev_major: 0, 236 stx_rdev_minor: 0, 237 stx_dev_major: 0, 238 stx_dev_minor: 0, 239 stx_mnt_id: 0, 240 stx_dio_mem_align: 0, 241 stx_dio_offset_align: 0, 242 } 243 } 244 } 245 246 bitflags! { 247 pub struct PosixStatxMask: u32{ 248 /// Want stx_mode & S_IFMT 249 const STATX_TYPE = 0x00000001; 250 251 /// Want stx_mode & ~S_IFMT 252 const STATX_MODE = 0x00000002; 253 254 /// Want stx_nlink 255 const STATX_NLINK = 0x00000004; 256 257 /// Want stx_uid 258 const STATX_UID = 0x00000008; 259 260 /// Want stx_gid 261 const STATX_GID = 0x00000010; 262 263 /// Want stx_atime 264 const STATX_ATIME = 0x00000020; 265 266 /// Want stx_mtime 267 const STATX_MTIME = 0x00000040; 268 269 /// Want stx_ctime 270 const STATX_CTIME = 0x00000080; 271 272 /// Want stx_ino 273 const STATX_INO = 0x00000100; 274 275 /// Want stx_size 276 const STATX_SIZE = 0x00000200; 277 278 /// Want stx_blocks 279 const STATX_BLOCKS = 0x00000400; 280 281 /// [All of the above] 282 const STATX_BASIC_STATS = 0x000007ff; 283 284 /// Want stx_btime 285 const STATX_BTIME = 0x00000800; 286 287 /// The same as STATX_BASIC_STATS | STATX_BTIME. 288 /// It is deprecated and should not be used. 289 const STATX_ALL = 0x00000fff; 290 291 /// Want stx_mnt_id (since Linux 5.8) 292 const STATX_MNT_ID = 0x00001000; 293 294 /// Want stx_dio_mem_align and stx_dio_offset_align 295 /// (since Linux 6.1; support varies by filesystem) 296 const STATX_DIOALIGN = 0x00002000; 297 298 /// Reserved for future struct statx expansion 299 const STATX_RESERVED = 0x80000000; 300 } 301 } 302 303 bitflags! { 304 pub struct StxAttributes: u64 { 305 /// 文件被文件系统压缩 306 const STATX_ATTR_COMPRESSED = 0x00000004; 307 /// 文件被标记为不可修改 308 const STATX_ATTR_IMMUTABLE = 0x00000010; 309 /// 文件是只追加写入的 310 const STATX_ATTR_APPEND = 0x00000020; 311 /// 文件不会被备份 312 const STATX_ATTR_NODUMP = 0x00000040; 313 /// 文件需要密钥才能在文件系统中解密 314 const STATX_ATTR_ENCRYPTED = 0x00000800; 315 /// 目录是自动挂载触发器 316 const STATX_ATTR_AUTOMOUNT = 0x00001000; 317 /// 目录是挂载点的根目录 318 const STATX_ATTR_MOUNT_ROOT = 0x00002000; 319 /// 文件受到 Verity 保护 320 const STATX_ATTR_VERITY = 0x00100000; 321 /// 文件当前处于 DAX 状态 CPU直接访问 322 const STATX_ATTR_DAX = 0x00200000; 323 } 324 } 325 326 #[repr(C)] 327 #[derive(Debug, Clone, Copy)] 328 pub struct PosixStatfs { 329 f_type: u64, 330 f_bsize: u64, 331 f_blocks: u64, 332 f_bfree: u64, 333 f_bavail: u64, 334 f_files: u64, 335 f_ffree: u64, 336 f_fsid: u64, 337 f_namelen: u64, 338 f_frsize: u64, 339 f_flags: u64, 340 f_spare: [u64; 4], 341 } 342 343 impl From<SuperBlock> for PosixStatfs { 344 fn from(super_block: SuperBlock) -> Self { 345 Self { 346 f_type: super_block.magic.bits, 347 f_bsize: super_block.bsize, 348 f_blocks: super_block.blocks, 349 f_bfree: super_block.bfree, 350 f_bavail: super_block.bavail, 351 f_files: super_block.files, 352 f_ffree: super_block.ffree, 353 f_fsid: super_block.fsid, 354 f_namelen: super_block.namelen, 355 f_frsize: super_block.frsize, 356 f_flags: super_block.flags, 357 f_spare: [0u64; 4], 358 } 359 } 360 } 361 /// 362 /// Arguments for how openat2(2) should open the target path. If only @flags and 363 /// @mode are non-zero, then openat2(2) operates very similarly to openat(2). 364 /// 365 /// However, unlike openat(2), unknown or invalid bits in @flags result in 366 /// -EINVAL rather than being silently ignored. @mode must be zero unless one of 367 /// {O_CREAT, O_TMPFILE} are set. 368 /// 369 /// ## 成员变量 370 /// 371 /// - flags: O_* flags. 372 /// - mode: O_CREAT/O_TMPFILE file mode. 373 /// - resolve: RESOLVE_* flags. 374 #[derive(Debug, Clone, Copy)] 375 #[repr(C)] 376 pub struct PosixOpenHow { 377 pub flags: u64, 378 pub mode: u64, 379 pub resolve: u64, 380 } 381 382 impl PosixOpenHow { 383 #[allow(dead_code)] 384 pub fn new(flags: u64, mode: u64, resolve: u64) -> Self { 385 Self { 386 flags, 387 mode, 388 resolve, 389 } 390 } 391 } 392 393 #[derive(Debug, Clone, Copy)] 394 pub struct OpenHow { 395 pub o_flags: FileMode, 396 pub mode: ModeType, 397 pub resolve: OpenHowResolve, 398 } 399 400 impl OpenHow { 401 pub fn new(mut o_flags: FileMode, mut mode: ModeType, resolve: OpenHowResolve) -> Self { 402 if !o_flags.contains(FileMode::O_CREAT) { 403 mode = ModeType::empty(); 404 } 405 406 if o_flags.contains(FileMode::O_PATH) { 407 o_flags = o_flags.intersection(FileMode::O_PATH_FLAGS); 408 } 409 410 Self { 411 o_flags, 412 mode, 413 resolve, 414 } 415 } 416 } 417 418 impl From<PosixOpenHow> for OpenHow { 419 fn from(posix_open_how: PosixOpenHow) -> Self { 420 let o_flags = FileMode::from_bits_truncate(posix_open_how.flags as u32); 421 let mode = ModeType::from_bits_truncate(posix_open_how.mode as u32); 422 let resolve = OpenHowResolve::from_bits_truncate(posix_open_how.resolve); 423 return Self::new(o_flags, mode, resolve); 424 } 425 } 426 427 bitflags! { 428 pub struct OpenHowResolve: u64{ 429 /// Block mount-point crossings 430 /// (including bind-mounts). 431 const RESOLVE_NO_XDEV = 0x01; 432 433 /// Block traversal through procfs-style 434 /// "magic-links" 435 const RESOLVE_NO_MAGICLINKS = 0x02; 436 437 /// Block traversal through all symlinks 438 /// (implies OEXT_NO_MAGICLINKS) 439 const RESOLVE_NO_SYMLINKS = 0x04; 440 /// Block "lexical" trickery like 441 /// "..", symlinks, and absolute 442 const RESOLVE_BENEATH = 0x08; 443 /// Make all jumps to "/" and ".." 444 /// be scoped inside the dirfd 445 /// (similar to chroot(2)). 446 const RESOLVE_IN_ROOT = 0x10; 447 // Only complete if resolution can be 448 // completed through cached lookup. May 449 // return -EAGAIN if that's not 450 // possible. 451 const RESOLVE_CACHED = 0x20; 452 } 453 } 454 455 bitflags! { 456 pub struct UmountFlag: i32 { 457 const DEFAULT = 0; /* Default call to umount. */ 458 const MNT_FORCE = 1; /* Force unmounting. */ 459 const MNT_DETACH = 2; /* Just detach from the tree. */ 460 const MNT_EXPIRE = 4; /* Mark for expiry. */ 461 const UMOUNT_NOFOLLOW = 8; /* Don't follow symlink on umount. */ 462 } 463 } 464 465 impl Syscall { 466 /// @brief 为当前进程打开一个文件 467 /// 468 /// @param path 文件路径 469 /// @param o_flags 打开文件的标志位 470 /// 471 /// @return 文件描述符编号,或者是错误码 472 pub fn open( 473 path: *const u8, 474 o_flags: u32, 475 mode: u32, 476 follow_symlink: bool, 477 ) -> Result<usize, SystemError> { 478 let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?; 479 let open_flags: FileMode = FileMode::from_bits(o_flags).ok_or(SystemError::EINVAL)?; 480 let mode = ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?; 481 return do_sys_open( 482 AtFlags::AT_FDCWD.bits(), 483 &path, 484 open_flags, 485 mode, 486 follow_symlink, 487 ); 488 } 489 490 pub fn openat( 491 dirfd: i32, 492 path: *const u8, 493 o_flags: u32, 494 mode: u32, 495 follow_symlink: bool, 496 ) -> Result<usize, SystemError> { 497 let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?; 498 let open_flags: FileMode = FileMode::from_bits(o_flags).ok_or(SystemError::EINVAL)?; 499 let mode = ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?; 500 return do_sys_open(dirfd, &path, open_flags, mode, follow_symlink); 501 } 502 503 /// @brief 关闭文件 504 /// 505 /// @param fd 文件描述符编号 506 /// 507 /// @return 成功返回0,失败返回错误码 508 pub fn close(fd: usize) -> Result<usize, SystemError> { 509 let binding = ProcessManager::current_pcb().fd_table(); 510 let mut fd_table_guard = binding.write(); 511 512 fd_table_guard.drop_fd(fd as i32).map(|_| 0) 513 } 514 515 /// @brief 发送命令到文件描述符对应的设备, 516 /// 517 /// @param fd 文件描述符编号 518 /// @param cmd 设备相关的请求类型 519 /// 520 /// @return Ok(usize) 成功返回0 521 /// @return Err(SystemError) 读取失败,返回posix错误码 522 pub fn ioctl(fd: usize, cmd: u32, data: usize) -> Result<usize, SystemError> { 523 let binding = ProcessManager::current_pcb().fd_table(); 524 let fd_table_guard = binding.read(); 525 526 let file = fd_table_guard 527 .get_file_by_fd(fd as i32) 528 .ok_or(SystemError::EBADF)?; 529 530 // drop guard 以避免无法调度的问题 531 drop(fd_table_guard); 532 let r = file.inode().ioctl(cmd, data, &file.private_data.lock()); 533 return r; 534 } 535 536 /// @brief 根据文件描述符,读取文件数据。尝试读取的数据长度与buf的长度相同。 537 /// 538 /// @param fd 文件描述符编号 539 /// @param buf 输出缓冲区 540 /// 541 /// @return Ok(usize) 成功读取的数据的字节数 542 /// @return Err(SystemError) 读取失败,返回posix错误码 543 pub fn read(fd: i32, buf: &mut [u8]) -> Result<usize, SystemError> { 544 let binding = ProcessManager::current_pcb().fd_table(); 545 let fd_table_guard = binding.read(); 546 547 let file = fd_table_guard.get_file_by_fd(fd); 548 if file.is_none() { 549 return Err(SystemError::EBADF); 550 } 551 // drop guard 以避免无法调度的问题 552 drop(fd_table_guard); 553 let file = file.unwrap(); 554 555 return file.read(buf.len(), buf); 556 } 557 558 /// @brief 根据文件描述符,向文件写入数据。尝试写入的数据长度与buf的长度相同。 559 /// 560 /// @param fd 文件描述符编号 561 /// @param buf 输入缓冲区 562 /// 563 /// @return Ok(usize) 成功写入的数据的字节数 564 /// @return Err(SystemError) 写入失败,返回posix错误码 565 pub fn write(fd: i32, buf: &[u8]) -> Result<usize, SystemError> { 566 let binding = ProcessManager::current_pcb().fd_table(); 567 let fd_table_guard = binding.read(); 568 569 let file = fd_table_guard 570 .get_file_by_fd(fd) 571 .ok_or(SystemError::EBADF)?; 572 573 // drop guard 以避免无法调度的问题 574 drop(fd_table_guard); 575 return file.write(buf.len(), buf); 576 } 577 578 /// @brief 调整文件操作指针的位置 579 /// 580 /// @param fd 文件描述符编号 581 /// @param seek 调整的方式 582 /// 583 /// @return Ok(usize) 调整后,文件访问指针相对于文件头部的偏移量 584 /// @return Err(SystemError) 调整失败,返回posix错误码 585 pub fn lseek(fd: i32, offset: i64, seek: u32) -> Result<usize, SystemError> { 586 let seek = match seek { 587 SEEK_SET => Ok(SeekFrom::SeekSet(offset)), 588 SEEK_CUR => Ok(SeekFrom::SeekCurrent(offset)), 589 SEEK_END => Ok(SeekFrom::SeekEnd(offset)), 590 SEEK_MAX => Ok(SeekFrom::SeekEnd(0)), 591 _ => Err(SystemError::EINVAL), 592 }?; 593 594 let binding = ProcessManager::current_pcb().fd_table(); 595 let fd_table_guard = binding.read(); 596 let file = fd_table_guard 597 .get_file_by_fd(fd) 598 .ok_or(SystemError::EBADF)?; 599 600 // drop guard 以避免无法调度的问题 601 drop(fd_table_guard); 602 return file.lseek(seek); 603 } 604 605 /// # sys_pread64 系统调用的实际执行函数 606 /// 607 /// ## 参数 608 /// - `fd`: 文件描述符 609 /// - `buf`: 读出缓冲区 610 /// - `len`: 要读取的字节数 611 /// - `offset`: 文件偏移量 612 pub fn pread(fd: i32, buf: &mut [u8], len: usize, offset: usize) -> Result<usize, SystemError> { 613 let binding = ProcessManager::current_pcb().fd_table(); 614 let fd_table_guard = binding.read(); 615 616 let file = fd_table_guard.get_file_by_fd(fd); 617 if file.is_none() { 618 return Err(SystemError::EBADF); 619 } 620 // drop guard 以避免无法调度的问题 621 drop(fd_table_guard); 622 let file = file.unwrap(); 623 624 return file.pread(offset, len, buf); 625 } 626 627 /// # sys_pwrite64 系统调用的实际执行函数 628 /// 629 /// ## 参数 630 /// - `fd`: 文件描述符 631 /// - `buf`: 写入缓冲区 632 /// - `len`: 要写入的字节数 633 /// - `offset`: 文件偏移量 634 pub fn pwrite(fd: i32, buf: &[u8], len: usize, offset: usize) -> Result<usize, SystemError> { 635 let binding = ProcessManager::current_pcb().fd_table(); 636 let fd_table_guard = binding.read(); 637 638 let file = fd_table_guard.get_file_by_fd(fd); 639 if file.is_none() { 640 return Err(SystemError::EBADF); 641 } 642 // drop guard 以避免无法调度的问题 643 drop(fd_table_guard); 644 let file = file.unwrap(); 645 646 return file.pwrite(offset, len, buf); 647 } 648 649 /// @brief 切换工作目录 650 /// 651 /// @param dest_path 目标路径 652 /// 653 /// @return 返回码 描述 654 /// 0 | 成功 655 /// 656 /// EACCESS | 权限不足 657 /// 658 /// ELOOP | 解析path时遇到路径循环 659 /// 660 /// ENAMETOOLONG | 路径名过长 661 /// 662 /// ENOENT | 目标文件或目录不存在 663 /// 664 /// ENODIR | 检索期间发现非目录项 665 /// 666 /// ENOMEM | 系统内存不足 667 /// 668 /// EFAULT | 错误的地址 669 /// 670 /// ENAMETOOLONG | 路径过长 671 pub fn chdir(path: *const u8) -> Result<usize, SystemError> { 672 if path.is_null() { 673 return Err(SystemError::EFAULT); 674 } 675 676 let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?; 677 let proc = ProcessManager::current_pcb(); 678 // Copy path to kernel space to avoid some security issues 679 let mut new_path = String::from(""); 680 if !path.is_empty() { 681 let cwd = match path.as_bytes()[0] { 682 b'/' => String::from("/"), 683 _ => proc.basic().cwd(), 684 }; 685 let mut cwd_vec: Vec<_> = cwd.split('/').filter(|&x| !x.is_empty()).collect(); 686 let path_split = path.split('/').filter(|&x| !x.is_empty()); 687 for seg in path_split { 688 if seg == ".." { 689 cwd_vec.pop(); 690 } else if seg == "." { 691 // 当前目录 692 } else { 693 cwd_vec.push(seg); 694 } 695 } 696 //proc.basic().set_path(String::from("")); 697 for seg in cwd_vec { 698 new_path.push('/'); 699 new_path.push_str(seg); 700 } 701 if new_path.is_empty() { 702 new_path = String::from("/"); 703 } 704 } 705 let inode = 706 match ROOT_INODE().lookup_follow_symlink(&new_path, VFS_MAX_FOLLOW_SYMLINK_TIMES) { 707 Err(_) => { 708 return Err(SystemError::ENOENT); 709 } 710 Ok(i) => i, 711 }; 712 let metadata = inode.metadata()?; 713 if metadata.file_type == FileType::Dir { 714 proc.basic_mut().set_cwd(new_path); 715 return Ok(0); 716 } else { 717 return Err(SystemError::ENOTDIR); 718 } 719 } 720 721 /// @brief 获取当前进程的工作目录路径 722 /// 723 /// @param buf 指向缓冲区的指针 724 /// @param size 缓冲区的大小 725 /// 726 /// @return 成功,返回的指针指向包含工作目录路径的字符串 727 /// @return 错误,没有足够的空间 728 pub fn getcwd(buf: &mut [u8]) -> Result<VirtAddr, SystemError> { 729 let proc = ProcessManager::current_pcb(); 730 let cwd = proc.basic().cwd(); 731 732 let cwd_bytes = cwd.as_bytes(); 733 let cwd_len = cwd_bytes.len(); 734 if cwd_len + 1 > buf.len() { 735 return Err(SystemError::ENOMEM); 736 } 737 buf[..cwd_len].copy_from_slice(cwd_bytes); 738 buf[cwd_len] = 0; 739 740 return Ok(VirtAddr::new(buf.as_ptr() as usize)); 741 } 742 743 /// @brief 获取目录中的数据 744 /// 745 /// TODO: 这个函数的语义与Linux不一致,需要修改!!! 746 /// 747 /// @param fd 文件描述符号 748 /// @param buf 输出缓冲区 749 /// 750 /// @return 成功返回读取的字节数,失败返回错误码 751 pub fn getdents(fd: i32, buf: &mut [u8]) -> Result<usize, SystemError> { 752 let dirent = 753 unsafe { (buf.as_mut_ptr() as *mut Dirent).as_mut() }.ok_or(SystemError::EFAULT)?; 754 755 if fd < 0 || fd as usize > FileDescriptorVec::PROCESS_MAX_FD { 756 return Err(SystemError::EBADF); 757 } 758 759 // 获取fd 760 let binding = ProcessManager::current_pcb().fd_table(); 761 let fd_table_guard = binding.read(); 762 let file = fd_table_guard 763 .get_file_by_fd(fd) 764 .ok_or(SystemError::EBADF)?; 765 766 // drop guard 以避免无法调度的问题 767 drop(fd_table_guard); 768 769 let res = file.readdir(dirent).map(|x| x as usize); 770 771 return res; 772 } 773 774 /// @brief 创建文件夹 775 /// 776 /// @param path(r8) 路径 / mode(r9) 模式 777 /// 778 /// @return uint64_t 负数错误码 / 0表示成功 779 pub fn mkdir(path: *const u8, mode: usize) -> Result<usize, SystemError> { 780 let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?; 781 do_mkdir_at( 782 AtFlags::AT_FDCWD.bits(), 783 &path, 784 FileMode::from_bits_truncate(mode as u32), 785 )?; 786 return Ok(0); 787 } 788 789 /// **创建硬连接的系统调用** 790 /// 791 /// ## 参数 792 /// 793 /// - 'oldfd': 用于解析源文件路径的文件描述符 794 /// - 'old': 源文件路径 795 /// - 'newfd': 用于解析新文件路径的文件描述符 796 /// - 'new': 新文件将创建的路径 797 /// - 'flags': 标志位,仅以位或方式包含AT_EMPTY_PATH和AT_SYMLINK_FOLLOW 798 /// 799 /// 800 pub fn do_linkat( 801 oldfd: i32, 802 old: &str, 803 newfd: i32, 804 new: &str, 805 flags: AtFlags, 806 ) -> Result<usize, SystemError> { 807 // flag包含其他未规定值时返回EINVAL 808 if !(AtFlags::AT_EMPTY_PATH | AtFlags::AT_SYMLINK_FOLLOW).contains(flags) { 809 return Err(SystemError::EINVAL); 810 } 811 // TODO AT_EMPTY_PATH标志启用时,进行调用者CAP_DAC_READ_SEARCH或相似的检查 812 let symlink_times = if flags.contains(AtFlags::AT_SYMLINK_FOLLOW) { 813 0_usize 814 } else { 815 VFS_MAX_FOLLOW_SYMLINK_TIMES 816 }; 817 let pcb = ProcessManager::current_pcb(); 818 819 // 得到源路径的inode 820 let old_inode: Arc<dyn IndexNode> = if old.is_empty() { 821 if flags.contains(AtFlags::AT_EMPTY_PATH) { 822 // 在AT_EMPTY_PATH启用时,old可以为空,old_inode实际为oldfd所指文件,但该文件不能为目录。 823 let binding = pcb.fd_table(); 824 let fd_table_guard = binding.read(); 825 let file = fd_table_guard 826 .get_file_by_fd(oldfd) 827 .ok_or(SystemError::EBADF)?; 828 let old_inode = file.inode(); 829 old_inode 830 } else { 831 return Err(SystemError::ENONET); 832 } 833 } else { 834 let (old_begin_inode, old_remain_path) = user_path_at(&pcb, oldfd, old)?; 835 old_begin_inode.lookup_follow_symlink(&old_remain_path, symlink_times)? 836 }; 837 838 // old_inode为目录时返回EPERM 839 if old_inode.metadata().unwrap().file_type == FileType::Dir { 840 return Err(SystemError::EPERM); 841 } 842 843 // 得到新创建节点的父节点 844 let (new_begin_inode, new_remain_path) = user_path_at(&pcb, newfd, new)?; 845 let (new_name, new_parent_path) = rsplit_path(&new_remain_path); 846 let new_parent = 847 new_begin_inode.lookup_follow_symlink(new_parent_path.unwrap_or("/"), symlink_times)?; 848 849 // 被调用者利用downcast_ref判断两inode是否为同一文件系统 850 return new_parent.link(new_name, &old_inode).map(|_| 0); 851 } 852 853 pub fn link(old: *const u8, new: *const u8) -> Result<usize, SystemError> { 854 let get_path = |cstr: *const u8| -> Result<String, SystemError> { 855 let res = check_and_clone_cstr(cstr, Some(MAX_PATHLEN))?; 856 if res.len() >= MAX_PATHLEN { 857 return Err(SystemError::ENAMETOOLONG); 858 } 859 if res.is_empty() { 860 return Err(SystemError::ENOENT); 861 } 862 Ok(res) 863 }; 864 let old = get_path(old)?; 865 let new = get_path(new)?; 866 return Self::do_linkat( 867 AtFlags::AT_FDCWD.bits(), 868 &old, 869 AtFlags::AT_FDCWD.bits(), 870 &new, 871 AtFlags::empty(), 872 ); 873 } 874 875 pub fn linkat( 876 oldfd: i32, 877 old: *const u8, 878 newfd: i32, 879 new: *const u8, 880 flags: i32, 881 ) -> Result<usize, SystemError> { 882 let old = check_and_clone_cstr(old, Some(MAX_PATHLEN))?; 883 let new = check_and_clone_cstr(new, Some(MAX_PATHLEN))?; 884 if old.len() >= MAX_PATHLEN || new.len() >= MAX_PATHLEN { 885 return Err(SystemError::ENAMETOOLONG); 886 } 887 // old 根据flags & AtFlags::AT_EMPTY_PATH判空 888 if new.is_empty() { 889 return Err(SystemError::ENOENT); 890 } 891 let flags = AtFlags::from_bits(flags).ok_or(SystemError::EINVAL)?; 892 Self::do_linkat(oldfd, &old, newfd, &new, flags) 893 } 894 895 /// **删除文件夹、取消文件的链接、删除文件的系统调用** 896 /// 897 /// ## 参数 898 /// 899 /// - `dirfd`:文件夹的文件描述符.目前暂未实现 900 /// - `pathname`:文件夹的路径 901 /// - `flags`:标志位 902 /// 903 /// 904 pub fn unlinkat(dirfd: i32, path: *const u8, flags: u32) -> Result<usize, SystemError> { 905 let flags = AtFlags::from_bits(flags as i32).ok_or(SystemError::EINVAL)?; 906 907 let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?; 908 909 if flags.contains(AtFlags::AT_REMOVEDIR) { 910 // debug!("rmdir"); 911 match do_remove_dir(dirfd, &path) { 912 Err(err) => { 913 return Err(err); 914 } 915 Ok(_) => { 916 return Ok(0); 917 } 918 } 919 } 920 921 match do_unlink_at(dirfd, &path) { 922 Err(err) => { 923 return Err(err); 924 } 925 Ok(_) => { 926 return Ok(0); 927 } 928 } 929 } 930 931 pub fn rmdir(path: *const u8) -> Result<usize, SystemError> { 932 let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?; 933 return do_remove_dir(AtFlags::AT_FDCWD.bits(), &path).map(|v| v as usize); 934 } 935 936 pub fn unlink(path: *const u8) -> Result<usize, SystemError> { 937 let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?; 938 return do_unlink_at(AtFlags::AT_FDCWD.bits(), &path).map(|v| v as usize); 939 } 940 941 /// # 修改文件名 942 /// 943 /// 944 /// ## 参数 945 /// 946 /// - oldfd: 源文件夹文件描述符 947 /// - filename_from: 源文件路径 948 /// - newfd: 目标文件夹文件描述符 949 /// - filename_to: 目标文件路径 950 /// - flags: 标志位 951 /// 952 /// 953 /// ## 返回值 954 /// - Ok(返回值类型): 返回值的说明 955 /// - Err(错误值类型): 错误的说明 956 /// 957 pub fn do_renameat2( 958 oldfd: i32, 959 filename_from: *const u8, 960 newfd: i32, 961 filename_to: *const u8, 962 _flags: u32, 963 ) -> Result<usize, SystemError> { 964 let filename_from = check_and_clone_cstr(filename_from, Some(MAX_PATHLEN)).unwrap(); 965 let filename_to = check_and_clone_cstr(filename_to, Some(MAX_PATHLEN)).unwrap(); 966 // 文件名过长 967 if filename_from.len() > MAX_PATHLEN || filename_to.len() > MAX_PATHLEN { 968 return Err(SystemError::ENAMETOOLONG); 969 } 970 971 //获取pcb,文件节点 972 let pcb = ProcessManager::current_pcb(); 973 let (_old_inode_begin, old_remain_path) = user_path_at(&pcb, oldfd, &filename_from)?; 974 let (_new_inode_begin, new_remain_path) = user_path_at(&pcb, newfd, &filename_to)?; 975 //获取父目录 976 let (old_filename, old_parent_path) = rsplit_path(&old_remain_path); 977 let old_parent_inode = ROOT_INODE() 978 .lookup_follow_symlink(old_parent_path.unwrap_or("/"), VFS_MAX_FOLLOW_SYMLINK_TIMES)?; 979 let (new_filename, new_parent_path) = rsplit_path(&new_remain_path); 980 let new_parent_inode = ROOT_INODE() 981 .lookup_follow_symlink(new_parent_path.unwrap_or("/"), VFS_MAX_FOLLOW_SYMLINK_TIMES)?; 982 old_parent_inode.move_to(old_filename, &new_parent_inode, new_filename)?; 983 return Ok(0); 984 } 985 986 /// @brief 根据提供的文件描述符的fd,复制对应的文件结构体,并返回新复制的文件结构体对应的fd 987 pub fn dup(oldfd: i32) -> Result<usize, SystemError> { 988 let binding = ProcessManager::current_pcb().fd_table(); 989 let mut fd_table_guard = binding.write(); 990 991 let old_file = fd_table_guard 992 .get_file_by_fd(oldfd) 993 .ok_or(SystemError::EBADF)?; 994 995 let new_file = old_file.try_clone().ok_or(SystemError::EBADF)?; 996 // dup默认非cloexec 997 new_file.set_close_on_exec(false); 998 // 申请文件描述符,并把文件对象存入其中 999 let res = fd_table_guard.alloc_fd(new_file, None).map(|x| x as usize); 1000 return res; 1001 } 1002 1003 /// 根据提供的文件描述符的fd,和指定新fd,复制对应的文件结构体, 1004 /// 并返回新复制的文件结构体对应的fd. 1005 /// 如果新fd已经打开,则会先关闭新fd. 1006 /// 1007 /// ## 参数 1008 /// 1009 /// - `oldfd`:旧文件描述符 1010 /// - `newfd`:新文件描述符 1011 /// 1012 /// ## 返回值 1013 /// 1014 /// - 成功:新文件描述符 1015 /// - 失败:错误码 1016 pub fn dup2(oldfd: i32, newfd: i32) -> Result<usize, SystemError> { 1017 let binding = ProcessManager::current_pcb().fd_table(); 1018 let mut fd_table_guard = binding.write(); 1019 return Self::do_dup2(oldfd, newfd, &mut fd_table_guard); 1020 } 1021 1022 pub fn dup3(oldfd: i32, newfd: i32, flags: u32) -> Result<usize, SystemError> { 1023 let flags = FileMode::from_bits_truncate(flags); 1024 if (flags.bits() & !FileMode::O_CLOEXEC.bits()) != 0 { 1025 return Err(SystemError::EINVAL); 1026 } 1027 1028 if oldfd == newfd { 1029 return Err(SystemError::EINVAL); 1030 } 1031 1032 let binding = ProcessManager::current_pcb().fd_table(); 1033 let mut fd_table_guard = binding.write(); 1034 return Self::do_dup3(oldfd, newfd, flags, &mut fd_table_guard); 1035 } 1036 1037 fn do_dup2( 1038 oldfd: i32, 1039 newfd: i32, 1040 fd_table_guard: &mut RwLockWriteGuard<'_, FileDescriptorVec>, 1041 ) -> Result<usize, SystemError> { 1042 Self::do_dup3(oldfd, newfd, FileMode::empty(), fd_table_guard) 1043 } 1044 1045 fn do_dup3( 1046 oldfd: i32, 1047 newfd: i32, 1048 flags: FileMode, 1049 fd_table_guard: &mut RwLockWriteGuard<'_, FileDescriptorVec>, 1050 ) -> Result<usize, SystemError> { 1051 // 确认oldfd, newid是否有效 1052 if !(FileDescriptorVec::validate_fd(oldfd) && FileDescriptorVec::validate_fd(newfd)) { 1053 return Err(SystemError::EBADF); 1054 } 1055 1056 if oldfd == newfd { 1057 // 若oldfd与newfd相等 1058 return Ok(newfd as usize); 1059 } 1060 let new_exists = fd_table_guard.get_file_by_fd(newfd).is_some(); 1061 if new_exists { 1062 // close newfd 1063 if fd_table_guard.drop_fd(newfd).is_err() { 1064 // An I/O error occurred while attempting to close fildes2. 1065 return Err(SystemError::EIO); 1066 } 1067 } 1068 1069 let old_file = fd_table_guard 1070 .get_file_by_fd(oldfd) 1071 .ok_or(SystemError::EBADF)?; 1072 let new_file = old_file.try_clone().ok_or(SystemError::EBADF)?; 1073 1074 if flags.contains(FileMode::O_CLOEXEC) { 1075 new_file.set_close_on_exec(true); 1076 } else { 1077 new_file.set_close_on_exec(false); 1078 } 1079 // 申请文件描述符,并把文件对象存入其中 1080 let res = fd_table_guard 1081 .alloc_fd(new_file, Some(newfd)) 1082 .map(|x| x as usize); 1083 return res; 1084 } 1085 1086 /// # fcntl 1087 /// 1088 /// ## 参数 1089 /// 1090 /// - `fd`:文件描述符 1091 /// - `cmd`:命令 1092 /// - `arg`:参数 1093 pub fn fcntl(fd: i32, cmd: FcntlCommand, arg: i32) -> Result<usize, SystemError> { 1094 // debug!("fcntl ({cmd:?}) fd: {fd}, arg={arg}"); 1095 match cmd { 1096 FcntlCommand::DupFd | FcntlCommand::DupFdCloexec => { 1097 if arg < 0 || arg as usize >= FileDescriptorVec::PROCESS_MAX_FD { 1098 return Err(SystemError::EBADF); 1099 } 1100 let arg = arg as usize; 1101 for i in arg..FileDescriptorVec::PROCESS_MAX_FD { 1102 let binding = ProcessManager::current_pcb().fd_table(); 1103 let mut fd_table_guard = binding.write(); 1104 if fd_table_guard.get_file_by_fd(i as i32).is_none() { 1105 if cmd == FcntlCommand::DupFd { 1106 return Self::do_dup2(fd, i as i32, &mut fd_table_guard); 1107 } else { 1108 return Self::do_dup3( 1109 fd, 1110 i as i32, 1111 FileMode::O_CLOEXEC, 1112 &mut fd_table_guard, 1113 ); 1114 } 1115 } 1116 } 1117 return Err(SystemError::EMFILE); 1118 } 1119 FcntlCommand::GetFd => { 1120 // Get file descriptor flags. 1121 let binding = ProcessManager::current_pcb().fd_table(); 1122 let fd_table_guard = binding.read(); 1123 1124 if let Some(file) = fd_table_guard.get_file_by_fd(fd) { 1125 // drop guard 以避免无法调度的问题 1126 drop(fd_table_guard); 1127 1128 if file.close_on_exec() { 1129 return Ok(FD_CLOEXEC as usize); 1130 } else { 1131 return Ok(0); 1132 } 1133 } 1134 return Err(SystemError::EBADF); 1135 } 1136 FcntlCommand::SetFd => { 1137 // Set file descriptor flags. 1138 let binding = ProcessManager::current_pcb().fd_table(); 1139 let fd_table_guard = binding.write(); 1140 1141 if let Some(file) = fd_table_guard.get_file_by_fd(fd) { 1142 // drop guard 以避免无法调度的问题 1143 drop(fd_table_guard); 1144 let arg = arg as u32; 1145 if arg & FD_CLOEXEC != 0 { 1146 file.set_close_on_exec(true); 1147 } else { 1148 file.set_close_on_exec(false); 1149 } 1150 return Ok(0); 1151 } 1152 return Err(SystemError::EBADF); 1153 } 1154 1155 FcntlCommand::GetFlags => { 1156 // Get file status flags. 1157 let binding = ProcessManager::current_pcb().fd_table(); 1158 let fd_table_guard = binding.read(); 1159 1160 if let Some(file) = fd_table_guard.get_file_by_fd(fd) { 1161 // drop guard 以避免无法调度的问题 1162 drop(fd_table_guard); 1163 return Ok(file.mode().bits() as usize); 1164 } 1165 1166 return Err(SystemError::EBADF); 1167 } 1168 FcntlCommand::SetFlags => { 1169 // Set file status flags. 1170 let binding = ProcessManager::current_pcb().fd_table(); 1171 let fd_table_guard = binding.write(); 1172 1173 if let Some(file) = fd_table_guard.get_file_by_fd(fd) { 1174 let arg = arg as u32; 1175 let mode = FileMode::from_bits(arg).ok_or(SystemError::EINVAL)?; 1176 // drop guard 以避免无法调度的问题 1177 drop(fd_table_guard); 1178 file.set_mode(mode)?; 1179 return Ok(0); 1180 } 1181 1182 return Err(SystemError::EBADF); 1183 } 1184 _ => { 1185 // TODO: unimplemented 1186 // 未实现的命令,返回0,不报错。 1187 1188 warn!("fcntl: unimplemented command: {:?}, defaults to 0.", cmd); 1189 return Err(SystemError::ENOSYS); 1190 } 1191 } 1192 } 1193 1194 /// # ftruncate 1195 /// 1196 /// ## 描述 1197 /// 1198 /// 改变文件大小. 1199 /// 如果文件大小大于原来的大小,那么文件的内容将会被扩展到指定的大小,新的空间将会用0填充. 1200 /// 如果文件大小小于原来的大小,那么文件的内容将会被截断到指定的大小. 1201 /// 1202 /// ## 参数 1203 /// 1204 /// - `fd`:文件描述符 1205 /// - `len`:文件大小 1206 /// 1207 /// ## 返回值 1208 /// 1209 /// 如果成功,返回0,否则返回错误码. 1210 pub fn ftruncate(fd: i32, len: usize) -> Result<usize, SystemError> { 1211 let binding = ProcessManager::current_pcb().fd_table(); 1212 let fd_table_guard = binding.read(); 1213 1214 if let Some(file) = fd_table_guard.get_file_by_fd(fd) { 1215 // drop guard 以避免无法调度的问题 1216 drop(fd_table_guard); 1217 let r = file.ftruncate(len).map(|_| 0); 1218 return r; 1219 } 1220 1221 return Err(SystemError::EBADF); 1222 } 1223 1224 fn do_fstat(fd: i32) -> Result<PosixKstat, SystemError> { 1225 let binding = ProcessManager::current_pcb().fd_table(); 1226 let fd_table_guard = binding.read(); 1227 let file = fd_table_guard 1228 .get_file_by_fd(fd) 1229 .ok_or(SystemError::EBADF)?; 1230 // drop guard 以避免无法调度的问题 1231 drop(fd_table_guard); 1232 1233 let mut kstat = PosixKstat::new(); 1234 // 获取文件信息 1235 let metadata = file.metadata()?; 1236 kstat.size = metadata.size; 1237 kstat.dev_id = metadata.dev_id as u64; 1238 kstat.inode = metadata.inode_id.into() as u64; 1239 kstat.blcok_size = metadata.blk_size as i64; 1240 kstat.blocks = metadata.blocks as u64; 1241 1242 kstat.atime.tv_sec = metadata.atime.tv_sec; 1243 kstat.atime.tv_nsec = metadata.atime.tv_nsec; 1244 kstat.mtime.tv_sec = metadata.mtime.tv_sec; 1245 kstat.mtime.tv_nsec = metadata.mtime.tv_nsec; 1246 kstat.ctime.tv_sec = metadata.ctime.tv_sec; 1247 kstat.ctime.tv_nsec = metadata.ctime.tv_nsec; 1248 1249 kstat.nlink = metadata.nlinks as u64; 1250 kstat.uid = metadata.uid as i32; 1251 kstat.gid = metadata.gid as i32; 1252 kstat.rdev = metadata.raw_dev.data() as i64; 1253 kstat.mode = metadata.mode; 1254 match file.file_type() { 1255 FileType::File => kstat.mode.insert(ModeType::S_IFREG), 1256 FileType::Dir => kstat.mode.insert(ModeType::S_IFDIR), 1257 FileType::BlockDevice => kstat.mode.insert(ModeType::S_IFBLK), 1258 FileType::CharDevice => kstat.mode.insert(ModeType::S_IFCHR), 1259 FileType::SymLink => kstat.mode.insert(ModeType::S_IFLNK), 1260 FileType::Socket => kstat.mode.insert(ModeType::S_IFSOCK), 1261 FileType::Pipe => kstat.mode.insert(ModeType::S_IFIFO), 1262 FileType::KvmDevice => kstat.mode.insert(ModeType::S_IFCHR), 1263 FileType::FramebufferDevice => kstat.mode.insert(ModeType::S_IFCHR), 1264 } 1265 1266 return Ok(kstat); 1267 } 1268 1269 pub fn fstat(fd: i32, usr_kstat: *mut PosixKstat) -> Result<usize, SystemError> { 1270 let mut writer = UserBufferWriter::new(usr_kstat, size_of::<PosixKstat>(), true)?; 1271 let kstat = Self::do_fstat(fd)?; 1272 1273 writer.copy_one_to_user(&kstat, 0)?; 1274 return Ok(0); 1275 } 1276 1277 pub fn stat(path: *const u8, user_kstat: *mut PosixKstat) -> Result<usize, SystemError> { 1278 let fd = Self::open( 1279 path, 1280 FileMode::O_RDONLY.bits(), 1281 ModeType::empty().bits(), 1282 true, 1283 )?; 1284 let r = Self::fstat(fd as i32, user_kstat); 1285 Self::close(fd).ok(); 1286 return r; 1287 } 1288 1289 pub fn lstat(path: *const u8, user_kstat: *mut PosixKstat) -> Result<usize, SystemError> { 1290 let fd = Self::open( 1291 path, 1292 FileMode::O_RDONLY.bits(), 1293 ModeType::empty().bits(), 1294 false, 1295 )?; 1296 let r = Self::fstat(fd as i32, user_kstat); 1297 Self::close(fd).ok(); 1298 return r; 1299 } 1300 1301 pub fn statfs(path: *const u8, user_statfs: *mut PosixStatfs) -> Result<usize, SystemError> { 1302 let mut writer = UserBufferWriter::new(user_statfs, size_of::<PosixStatfs>(), true)?; 1303 let fd = Self::open( 1304 path, 1305 FileMode::O_RDONLY.bits(), 1306 ModeType::empty().bits(), 1307 true, 1308 )?; 1309 let path = check_and_clone_cstr(path, Some(MAX_PATHLEN)).unwrap(); 1310 let pcb = ProcessManager::current_pcb(); 1311 let (_inode_begin, remain_path) = user_path_at(&pcb, fd as i32, &path)?; 1312 let inode = ROOT_INODE().lookup_follow_symlink(&remain_path, MAX_PATHLEN)?; 1313 let statfs = PosixStatfs::from(inode.fs().super_block()); 1314 writer.copy_one_to_user(&statfs, 0)?; 1315 return Ok(0); 1316 } 1317 1318 pub fn fstatfs(fd: i32, user_statfs: *mut PosixStatfs) -> Result<usize, SystemError> { 1319 let mut writer = UserBufferWriter::new(user_statfs, size_of::<PosixStatfs>(), true)?; 1320 let binding = ProcessManager::current_pcb().fd_table(); 1321 let fd_table_guard = binding.read(); 1322 let file = fd_table_guard 1323 .get_file_by_fd(fd) 1324 .ok_or(SystemError::EBADF)?; 1325 drop(fd_table_guard); 1326 let statfs = PosixStatfs::from(file.inode().fs().super_block()); 1327 writer.copy_one_to_user(&statfs, 0)?; 1328 return Ok(0); 1329 } 1330 1331 pub fn do_statx( 1332 fd: i32, 1333 path: *const u8, 1334 flags: u32, 1335 mask: u32, 1336 usr_kstat: *mut PosixStatx, 1337 ) -> Result<usize, SystemError> { 1338 if usr_kstat.is_null() { 1339 return Err(SystemError::EFAULT); 1340 } 1341 1342 let mask = PosixStatxMask::from_bits_truncate(mask); 1343 1344 if mask.contains(PosixStatxMask::STATX_RESERVED) { 1345 return Err(SystemError::ENAVAIL); 1346 } 1347 1348 let flags = FileMode::from_bits_truncate(flags); 1349 let ofd = Self::open(path, flags.bits(), ModeType::empty().bits, true)?; 1350 1351 let binding = ProcessManager::current_pcb().fd_table(); 1352 let fd_table_guard = binding.read(); 1353 let file = fd_table_guard 1354 .get_file_by_fd(ofd as i32) 1355 .ok_or(SystemError::EBADF)?; 1356 // drop guard 以避免无法调度的问题 1357 drop(fd_table_guard); 1358 let mut writer = UserBufferWriter::new(usr_kstat, size_of::<PosixStatx>(), true)?; 1359 let mut tmp: PosixStatx = PosixStatx::new(); 1360 // 获取文件信息 1361 let metadata = file.metadata()?; 1362 1363 tmp.stx_mask |= PosixStatxMask::STATX_BASIC_STATS; 1364 tmp.stx_blksize = metadata.blk_size as u32; 1365 if mask.contains(PosixStatxMask::STATX_MODE) || mask.contains(PosixStatxMask::STATX_TYPE) { 1366 tmp.stx_mode = metadata.mode; 1367 } 1368 if mask.contains(PosixStatxMask::STATX_NLINK) { 1369 tmp.stx_nlink = metadata.nlinks as u32; 1370 } 1371 if mask.contains(PosixStatxMask::STATX_UID) { 1372 tmp.stx_uid = metadata.uid as u32; 1373 } 1374 if mask.contains(PosixStatxMask::STATX_GID) { 1375 tmp.stx_gid = metadata.gid as u32; 1376 } 1377 if mask.contains(PosixStatxMask::STATX_ATIME) { 1378 tmp.stx_atime.tv_sec = metadata.atime.tv_sec; 1379 tmp.stx_atime.tv_nsec = metadata.atime.tv_nsec; 1380 } 1381 if mask.contains(PosixStatxMask::STATX_MTIME) { 1382 tmp.stx_mtime.tv_sec = metadata.ctime.tv_sec; 1383 tmp.stx_mtime.tv_nsec = metadata.ctime.tv_nsec; 1384 } 1385 if mask.contains(PosixStatxMask::STATX_CTIME) { 1386 // ctime是文件上次修改状态的时间 1387 tmp.stx_ctime.tv_sec = metadata.mtime.tv_sec; 1388 tmp.stx_ctime.tv_nsec = metadata.mtime.tv_nsec; 1389 } 1390 if mask.contains(PosixStatxMask::STATX_INO) { 1391 tmp.stx_inode = metadata.inode_id.into() as u64; 1392 } 1393 if mask.contains(PosixStatxMask::STATX_SIZE) { 1394 tmp.stx_size = metadata.size; 1395 } 1396 if mask.contains(PosixStatxMask::STATX_BLOCKS) { 1397 tmp.stx_blocks = metadata.blocks as u64; 1398 } 1399 1400 if mask.contains(PosixStatxMask::STATX_BTIME) { 1401 // btime是文件创建时间 1402 tmp.stx_btime.tv_sec = metadata.ctime.tv_sec; 1403 tmp.stx_btime.tv_nsec = metadata.ctime.tv_nsec; 1404 } 1405 if mask.contains(PosixStatxMask::STATX_ALL) { 1406 tmp.stx_attributes = StxAttributes::STATX_ATTR_APPEND; 1407 tmp.stx_attributes_mask |= 1408 StxAttributes::STATX_ATTR_AUTOMOUNT | StxAttributes::STATX_ATTR_DAX; 1409 tmp.stx_dev_major = metadata.dev_id as u32; 1410 tmp.stx_dev_minor = metadata.dev_id as u32; // 1411 tmp.stx_rdev_major = metadata.raw_dev.data(); 1412 tmp.stx_rdev_minor = metadata.raw_dev.data(); 1413 } 1414 if mask.contains(PosixStatxMask::STATX_MNT_ID) { 1415 tmp.stx_mnt_id = 0; 1416 } 1417 if mask.contains(PosixStatxMask::STATX_DIOALIGN) { 1418 tmp.stx_dio_mem_align = 0; 1419 tmp.stx_dio_offset_align = 0; 1420 } 1421 1422 match file.file_type() { 1423 FileType::File => tmp.stx_mode.insert(ModeType::S_IFREG), 1424 FileType::Dir => tmp.stx_mode.insert(ModeType::S_IFDIR), 1425 FileType::BlockDevice => tmp.stx_mode.insert(ModeType::S_IFBLK), 1426 FileType::CharDevice => tmp.stx_mode.insert(ModeType::S_IFCHR), 1427 FileType::SymLink => tmp.stx_mode.insert(ModeType::S_IFLNK), 1428 FileType::Socket => tmp.stx_mode.insert(ModeType::S_IFSOCK), 1429 FileType::Pipe => tmp.stx_mode.insert(ModeType::S_IFIFO), 1430 FileType::KvmDevice => tmp.stx_mode.insert(ModeType::S_IFCHR), 1431 FileType::FramebufferDevice => tmp.stx_mode.insert(ModeType::S_IFCHR), 1432 } 1433 1434 writer.copy_one_to_user(&tmp, 0)?; 1435 Self::close(fd as usize).ok(); 1436 return Ok(0); 1437 } 1438 1439 pub fn mknod( 1440 path: *const u8, 1441 mode: ModeType, 1442 dev_t: DeviceNumber, 1443 ) -> Result<usize, SystemError> { 1444 let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?; 1445 let path = path.as_str().trim(); 1446 1447 let inode: Result<Arc<dyn IndexNode>, SystemError> = 1448 ROOT_INODE().lookup_follow_symlink(path, VFS_MAX_FOLLOW_SYMLINK_TIMES); 1449 1450 if inode.is_ok() { 1451 return Err(SystemError::EEXIST); 1452 } 1453 1454 let (filename, parent_path) = rsplit_path(path); 1455 1456 // 查找父目录 1457 let parent_inode: Arc<dyn IndexNode> = ROOT_INODE() 1458 .lookup_follow_symlink(parent_path.unwrap_or("/"), VFS_MAX_FOLLOW_SYMLINK_TIMES)?; 1459 // 创建nod 1460 parent_inode.mknod(filename, mode, dev_t)?; 1461 1462 return Ok(0); 1463 } 1464 1465 pub fn writev(fd: i32, iov: usize, count: usize) -> Result<usize, SystemError> { 1466 // IoVecs会进行用户态检验 1467 let iovecs = unsafe { IoVecs::from_user(iov as *const IoVec, count, false) }?; 1468 1469 let data = iovecs.gather(); 1470 1471 Self::write(fd, &data) 1472 } 1473 1474 pub fn readv(fd: i32, iov: usize, count: usize) -> Result<usize, SystemError> { 1475 // IoVecs会进行用户态检验 1476 let mut iovecs = unsafe { IoVecs::from_user(iov as *const IoVec, count, true) }?; 1477 1478 let mut data = vec![0; iovecs.0.iter().map(|x| x.len()).sum()]; 1479 1480 let len = Self::read(fd, &mut data)?; 1481 1482 iovecs.scatter(&data[..len]); 1483 1484 return Ok(len); 1485 } 1486 1487 pub fn readlink_at( 1488 dirfd: i32, 1489 path: *const u8, 1490 user_buf: *mut u8, 1491 buf_size: usize, 1492 ) -> Result<usize, SystemError> { 1493 let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?; 1494 let path = path.as_str().trim(); 1495 let mut user_buf = UserBufferWriter::new(user_buf, buf_size, true)?; 1496 1497 let (inode, path) = user_path_at(&ProcessManager::current_pcb(), dirfd, path)?; 1498 1499 let inode = inode.lookup(path.as_str())?; 1500 if inode.metadata()?.file_type != FileType::SymLink { 1501 return Err(SystemError::EINVAL); 1502 } 1503 1504 let ubuf = user_buf.buffer::<u8>(0).unwrap(); 1505 1506 let file = File::new(inode, FileMode::O_RDONLY)?; 1507 1508 let len = file.read(buf_size, ubuf)?; 1509 1510 return Ok(len); 1511 } 1512 1513 pub fn readlink( 1514 path: *const u8, 1515 user_buf: *mut u8, 1516 buf_size: usize, 1517 ) -> Result<usize, SystemError> { 1518 return Self::readlink_at(AtFlags::AT_FDCWD.bits(), path, user_buf, buf_size); 1519 } 1520 1521 pub fn access(pathname: *const u8, mode: u32) -> Result<usize, SystemError> { 1522 return do_faccessat( 1523 AtFlags::AT_FDCWD.bits(), 1524 pathname, 1525 ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?, 1526 0, 1527 ); 1528 } 1529 1530 pub fn faccessat2( 1531 dirfd: i32, 1532 pathname: *const u8, 1533 mode: u32, 1534 flags: u32, 1535 ) -> Result<usize, SystemError> { 1536 return do_faccessat( 1537 dirfd, 1538 pathname, 1539 ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?, 1540 flags, 1541 ); 1542 } 1543 1544 pub fn chmod(pathname: *const u8, mode: u32) -> Result<usize, SystemError> { 1545 return do_fchmodat( 1546 AtFlags::AT_FDCWD.bits(), 1547 pathname, 1548 ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?, 1549 ); 1550 } 1551 1552 pub fn fchmodat(dirfd: i32, pathname: *const u8, mode: u32) -> Result<usize, SystemError> { 1553 return do_fchmodat( 1554 dirfd, 1555 pathname, 1556 ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?, 1557 ); 1558 } 1559 1560 pub fn fchmod(fd: i32, mode: u32) -> Result<usize, SystemError> { 1561 let _mode = ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?; 1562 let binding = ProcessManager::current_pcb().fd_table(); 1563 let fd_table_guard = binding.read(); 1564 let _file = fd_table_guard 1565 .get_file_by_fd(fd) 1566 .ok_or(SystemError::EBADF)?; 1567 1568 // fchmod没完全实现,因此不修改文件的权限 1569 // todo: 实现fchmod 1570 warn!("fchmod not fully implemented"); 1571 return Ok(0); 1572 } 1573 /// #挂载文件系统 1574 /// 1575 /// 用于挂载文件系统,目前仅支持ramfs挂载 1576 /// 1577 /// ## 参数: 1578 /// 1579 /// - source 挂载设备(暂时不支持) 1580 /// - target 挂载目录 1581 /// - filesystemtype 文件系统 1582 /// - mountflags 挂载选项(暂未实现) 1583 /// - data 带数据挂载 1584 /// 1585 /// ## 返回值 1586 /// - Ok(0): 挂载成功 1587 /// - Err(SystemError) :挂载过程中出错 1588 pub fn mount( 1589 _source: *const u8, 1590 target: *const u8, 1591 filesystemtype: *const u8, 1592 _mountflags: usize, 1593 _data: *const c_void, 1594 ) -> Result<usize, SystemError> { 1595 let target = user_access::check_and_clone_cstr(target, Some(MAX_PATHLEN))?; 1596 1597 let filesystemtype = user_access::check_and_clone_cstr(filesystemtype, Some(MAX_PATHLEN))?; 1598 1599 let filesystemtype = producefs!(FSMAKER, filesystemtype)?; 1600 1601 Vcore::do_mount(filesystemtype, target.to_string().as_str())?; 1602 1603 return Ok(0); 1604 } 1605 1606 // 想法:可以在VFS中实现一个文件系统分发器,流程如下: 1607 // 1. 接受从上方传来的文件类型字符串 1608 // 2. 将传入值与启动时准备好的字符串数组逐个比较(probe) 1609 // 3. 直接在函数内调用构造方法并直接返回文件系统对象 1610 1611 /// src/linux/mount.c `umount` & `umount2` 1612 /// 1613 /// [umount(2) — Linux manual page](https://www.man7.org/linux/man-pages/man2/umount.2.html) 1614 pub fn umount2(target: *const u8, flags: i32) -> Result<(), SystemError> { 1615 let target = user_access::check_and_clone_cstr(target, Some(MAX_PATHLEN))?; 1616 Vcore::do_umount2( 1617 AtFlags::AT_FDCWD.bits(), 1618 &target, 1619 UmountFlag::from_bits(flags).ok_or(SystemError::EINVAL)?, 1620 )?; 1621 return Ok(()); 1622 } 1623 } 1624 1625 #[repr(C)] 1626 #[derive(Debug, Clone, Copy)] 1627 pub struct IoVec { 1628 /// 缓冲区的起始地址 1629 pub iov_base: *mut u8, 1630 /// 缓冲区的长度 1631 pub iov_len: usize, 1632 } 1633 1634 /// 用于存储多个来自用户空间的IoVec 1635 /// 1636 /// 由于目前内核中的文件系统还不支持分散读写,所以暂时只支持将用户空间的IoVec聚合成一个缓冲区,然后进行操作。 1637 /// TODO:支持分散读写 1638 #[derive(Debug)] 1639 pub struct IoVecs(Vec<&'static mut [u8]>); 1640 1641 impl IoVecs { 1642 /// 从用户空间的IoVec中构造IoVecs 1643 /// 1644 /// @param iov 用户空间的IoVec 1645 /// @param iovcnt 用户空间的IoVec的数量 1646 /// @param readv 是否为readv系统调用 1647 /// 1648 /// @return 构造成功返回IoVecs,否则返回错误码 1649 pub unsafe fn from_user( 1650 iov: *const IoVec, 1651 iovcnt: usize, 1652 _readv: bool, 1653 ) -> Result<Self, SystemError> { 1654 // 检查iov指针所在空间是否合法 1655 verify_area( 1656 VirtAddr::new(iov as usize), 1657 iovcnt * core::mem::size_of::<IoVec>(), 1658 ) 1659 .map_err(|_| SystemError::EFAULT)?; 1660 1661 // 将用户空间的IoVec转换为引用(注意:这里的引用是静态的,因为用户空间的IoVec不会被释放) 1662 let iovs: &[IoVec] = core::slice::from_raw_parts(iov, iovcnt); 1663 1664 let mut slices: Vec<&mut [u8]> = vec![]; 1665 slices.reserve(iovs.len()); 1666 1667 for iov in iovs.iter() { 1668 if iov.iov_len == 0 { 1669 continue; 1670 } 1671 1672 verify_area( 1673 VirtAddr::new(iov.iov_base as usize), 1674 iovcnt * core::mem::size_of::<IoVec>(), 1675 ) 1676 .map_err(|_| SystemError::EFAULT)?; 1677 1678 slices.push(core::slice::from_raw_parts_mut(iov.iov_base, iov.iov_len)); 1679 } 1680 1681 return Ok(Self(slices)); 1682 } 1683 1684 /// @brief 将IoVecs中的数据聚合到一个缓冲区中 1685 /// 1686 /// @return 返回聚合后的缓冲区 1687 pub fn gather(&self) -> Vec<u8> { 1688 let mut buf = Vec::new(); 1689 for slice in self.0.iter() { 1690 buf.extend_from_slice(slice); 1691 } 1692 return buf; 1693 } 1694 1695 /// @brief 将给定的数据分散写入到IoVecs中 1696 pub fn scatter(&mut self, data: &[u8]) { 1697 let mut data: &[u8] = data; 1698 for slice in self.0.iter_mut() { 1699 let len = core::cmp::min(slice.len(), data.len()); 1700 if len == 0 { 1701 continue; 1702 } 1703 1704 slice[..len].copy_from_slice(&data[..len]); 1705 data = &data[len..]; 1706 } 1707 } 1708 1709 /// @brief 创建与IoVecs等长的缓冲区 1710 /// 1711 /// @param set_len 是否设置返回的Vec的len。 1712 /// 如果为true,则返回的Vec的len为所有IoVec的长度之和; 1713 /// 否则返回的Vec的len为0,capacity为所有IoVec的长度之和. 1714 /// 1715 /// @return 返回创建的缓冲区 1716 pub fn new_buf(&self, set_len: bool) -> Vec<u8> { 1717 let total_len: usize = self.0.iter().map(|slice| slice.len()).sum(); 1718 let mut buf: Vec<u8> = Vec::with_capacity(total_len); 1719 1720 if set_len { 1721 buf.resize(total_len, 0); 1722 } 1723 return buf; 1724 } 1725 } 1726