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