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