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