1*82df0a13Shmt use core::mem::size_of; 22dbef785SGnoCiYeH 3*82df0a13Shmt use alloc::{string::String, sync::Arc, vec::Vec}; 491e9d4abSLoGin use system_error::SystemError; 5004e86ffSlogin 6004e86ffSlogin use crate::{ 7c566df45SLoGin driver::base::{block::SeekFrom, device::device_number::DeviceNumber}, 82b771e32SGou Ngai filesystem::vfs::file::FileDescriptorVec, 91496ba7bSLoGin libs::rwlock::RwLockWriteGuard, 104fda81ceSLoGin mm::{verify_area, VirtAddr}, 111496ba7bSLoGin process::ProcessManager, 12709498caSLoGin syscall::{ 13*82df0a13Shmt user_access::{check_and_clone_cstr, UserBufferWriter}, 1491e9d4abSLoGin Syscall, 15709498caSLoGin }, 1667b48188Shoumkh time::TimeSpec, 17004e86ffSlogin }; 18004e86ffSlogin 19004e86ffSlogin use super::{ 20ab5c8ca4Slogin core::{do_mkdir, do_remove_dir, do_unlink_at}, 21709498caSLoGin fcntl::{AtFlags, FcntlCommand, FD_CLOEXEC}, 22004e86ffSlogin file::{File, FileMode}, 230fb515b0SLoGin open::{do_faccessat, do_fchmodat, do_sys_open}, 249b0abe6dSLoGin utils::{rsplit_path, user_path_at}, 25a03c4f9dSLoGin Dirent, FileType, IndexNode, MAX_PATHLEN, ROOT_INODE, VFS_MAX_FOLLOW_SYMLINK_TIMES, 26004e86ffSlogin }; 2740314b30SXiaoye Zheng // use crate::kdebug; 28004e86ffSlogin 29ab5c8ca4Slogin pub const SEEK_SET: u32 = 0; 30ab5c8ca4Slogin pub const SEEK_CUR: u32 = 1; 31ab5c8ca4Slogin pub const SEEK_END: u32 = 2; 32ab5c8ca4Slogin pub const SEEK_MAX: u32 = 3; 33004e86ffSlogin 3467b48188Shoumkh bitflags! { 3567b48188Shoumkh /// 文件类型和权限 366b4e7a29SLoGin #[repr(C)] 3767b48188Shoumkh pub struct ModeType: u32 { 3867b48188Shoumkh /// 掩码 3967b48188Shoumkh const S_IFMT = 0o0_170_000; 4067b48188Shoumkh /// 文件类型 4167b48188Shoumkh const S_IFSOCK = 0o140000; 4267b48188Shoumkh const S_IFLNK = 0o120000; 4367b48188Shoumkh const S_IFREG = 0o100000; 4467b48188Shoumkh const S_IFBLK = 0o060000; 4567b48188Shoumkh const S_IFDIR = 0o040000; 4667b48188Shoumkh const S_IFCHR = 0o020000; 4767b48188Shoumkh const S_IFIFO = 0o010000; 4867b48188Shoumkh 4967b48188Shoumkh const S_ISUID = 0o004000; 5067b48188Shoumkh const S_ISGID = 0o002000; 5167b48188Shoumkh const S_ISVTX = 0o001000; 5267b48188Shoumkh /// 文件用户权限 5367b48188Shoumkh const S_IRWXU = 0o0700; 5467b48188Shoumkh const S_IRUSR = 0o0400; 5567b48188Shoumkh const S_IWUSR = 0o0200; 5667b48188Shoumkh const S_IXUSR = 0o0100; 5767b48188Shoumkh /// 文件组权限 5867b48188Shoumkh const S_IRWXG = 0o0070; 5967b48188Shoumkh const S_IRGRP = 0o0040; 6067b48188Shoumkh const S_IWGRP = 0o0020; 6167b48188Shoumkh const S_IXGRP = 0o0010; 6267b48188Shoumkh /// 文件其他用户权限 6367b48188Shoumkh const S_IRWXO = 0o0007; 6467b48188Shoumkh const S_IROTH = 0o0004; 6567b48188Shoumkh const S_IWOTH = 0o0002; 6667b48188Shoumkh const S_IXOTH = 0o0001; 6706d5e247SLoGin 6806d5e247SLoGin /// 0o777 6906d5e247SLoGin const S_IRWXUGO = Self::S_IRWXU.bits | Self::S_IRWXG.bits | Self::S_IRWXO.bits; 7006d5e247SLoGin /// 0o7777 7106d5e247SLoGin const S_IALLUGO = Self::S_ISUID.bits | Self::S_ISGID.bits | Self::S_ISVTX.bits| Self::S_IRWXUGO.bits; 7206d5e247SLoGin /// 0o444 7306d5e247SLoGin const S_IRUGO = Self::S_IRUSR.bits | Self::S_IRGRP.bits | Self::S_IROTH.bits; 7406d5e247SLoGin /// 0o222 7506d5e247SLoGin const S_IWUGO = Self::S_IWUSR.bits | Self::S_IWGRP.bits | Self::S_IWOTH.bits; 7606d5e247SLoGin /// 0o111 7706d5e247SLoGin const S_IXUGO = Self::S_IXUSR.bits | Self::S_IXGRP.bits | Self::S_IXOTH.bits; 7806d5e247SLoGin 7906d5e247SLoGin 8067b48188Shoumkh } 8167b48188Shoumkh } 8267b48188Shoumkh 8367b48188Shoumkh #[repr(C)] 84*82df0a13Shmt #[derive(Clone, Copy)] 8567b48188Shoumkh /// # 文件信息结构体 8667b48188Shoumkh pub struct PosixKstat { 8767b48188Shoumkh /// 硬件设备ID 8867b48188Shoumkh dev_id: u64, 8967b48188Shoumkh /// inode号 9067b48188Shoumkh inode: u64, 9167b48188Shoumkh /// 硬链接数 9267b48188Shoumkh nlink: u64, 9367b48188Shoumkh /// 文件权限 9467b48188Shoumkh mode: ModeType, 9567b48188Shoumkh /// 所有者用户ID 9667b48188Shoumkh uid: i32, 9767b48188Shoumkh /// 所有者组ID 9867b48188Shoumkh gid: i32, 9967b48188Shoumkh /// 设备ID 10067b48188Shoumkh rdev: i64, 10167b48188Shoumkh /// 文件大小 10267b48188Shoumkh size: i64, 10367b48188Shoumkh /// 文件系统块大小 10467b48188Shoumkh blcok_size: i64, 10567b48188Shoumkh /// 分配的512B块数 10667b48188Shoumkh blocks: u64, 10767b48188Shoumkh /// 最后访问时间 10867b48188Shoumkh atime: TimeSpec, 10967b48188Shoumkh /// 最后修改时间 11067b48188Shoumkh mtime: TimeSpec, 11167b48188Shoumkh /// 最后状态变化时间 11267b48188Shoumkh ctime: TimeSpec, 11367b48188Shoumkh /// 用于填充结构体大小的空白数据 11467b48188Shoumkh pub _pad: [i8; 24], 11567b48188Shoumkh } 11667b48188Shoumkh impl PosixKstat { 11767b48188Shoumkh fn new() -> Self { 11867b48188Shoumkh Self { 11967b48188Shoumkh inode: 0, 12067b48188Shoumkh dev_id: 0, 12167b48188Shoumkh mode: ModeType { bits: 0 }, 12267b48188Shoumkh nlink: 0, 12367b48188Shoumkh uid: 0, 12467b48188Shoumkh gid: 0, 12567b48188Shoumkh rdev: 0, 12667b48188Shoumkh size: 0, 12767b48188Shoumkh atime: TimeSpec { 12867b48188Shoumkh tv_sec: 0, 12967b48188Shoumkh tv_nsec: 0, 13067b48188Shoumkh }, 13167b48188Shoumkh mtime: TimeSpec { 13267b48188Shoumkh tv_sec: 0, 13367b48188Shoumkh tv_nsec: 0, 13467b48188Shoumkh }, 13567b48188Shoumkh ctime: TimeSpec { 13667b48188Shoumkh tv_sec: 0, 13767b48188Shoumkh tv_nsec: 0, 13867b48188Shoumkh }, 13967b48188Shoumkh blcok_size: 0, 14067b48188Shoumkh blocks: 0, 14167b48188Shoumkh _pad: Default::default(), 14267b48188Shoumkh } 14367b48188Shoumkh } 14467b48188Shoumkh } 1450fb515b0SLoGin 1460fb515b0SLoGin /// 1470fb515b0SLoGin /// Arguments for how openat2(2) should open the target path. If only @flags and 1480fb515b0SLoGin /// @mode are non-zero, then openat2(2) operates very similarly to openat(2). 1490fb515b0SLoGin /// 1500fb515b0SLoGin /// However, unlike openat(2), unknown or invalid bits in @flags result in 1510fb515b0SLoGin /// -EINVAL rather than being silently ignored. @mode must be zero unless one of 1520fb515b0SLoGin /// {O_CREAT, O_TMPFILE} are set. 1530fb515b0SLoGin /// 1540fb515b0SLoGin /// ## 成员变量 1550fb515b0SLoGin /// 1560fb515b0SLoGin /// - flags: O_* flags. 1570fb515b0SLoGin /// - mode: O_CREAT/O_TMPFILE file mode. 1580fb515b0SLoGin /// - resolve: RESOLVE_* flags. 1590fb515b0SLoGin #[derive(Debug, Clone, Copy)] 1600fb515b0SLoGin #[repr(C)] 1610fb515b0SLoGin pub struct PosixOpenHow { 1620fb515b0SLoGin pub flags: u64, 1630fb515b0SLoGin pub mode: u64, 1640fb515b0SLoGin pub resolve: u64, 1650fb515b0SLoGin } 1660fb515b0SLoGin 1670fb515b0SLoGin impl PosixOpenHow { 1680fb515b0SLoGin #[allow(dead_code)] 1690fb515b0SLoGin pub fn new(flags: u64, mode: u64, resolve: u64) -> Self { 1700fb515b0SLoGin Self { 1710fb515b0SLoGin flags, 1720fb515b0SLoGin mode, 1730fb515b0SLoGin resolve, 1740fb515b0SLoGin } 1750fb515b0SLoGin } 1760fb515b0SLoGin } 1770fb515b0SLoGin 1780fb515b0SLoGin #[derive(Debug, Clone, Copy)] 1790fb515b0SLoGin pub struct OpenHow { 1800fb515b0SLoGin pub o_flags: FileMode, 1810fb515b0SLoGin pub mode: ModeType, 1820fb515b0SLoGin pub resolve: OpenHowResolve, 1830fb515b0SLoGin } 1840fb515b0SLoGin 1850fb515b0SLoGin impl OpenHow { 1860fb515b0SLoGin pub fn new(mut o_flags: FileMode, mut mode: ModeType, resolve: OpenHowResolve) -> Self { 1870fb515b0SLoGin if !o_flags.contains(FileMode::O_CREAT) { 1880fb515b0SLoGin mode = ModeType::empty(); 1890fb515b0SLoGin } 1900fb515b0SLoGin 1910fb515b0SLoGin if o_flags.contains(FileMode::O_PATH) { 1920fb515b0SLoGin o_flags = o_flags.intersection(FileMode::O_PATH_FLAGS); 1930fb515b0SLoGin } 1940fb515b0SLoGin 1950fb515b0SLoGin Self { 1960fb515b0SLoGin o_flags, 1970fb515b0SLoGin mode, 1980fb515b0SLoGin resolve, 1990fb515b0SLoGin } 2000fb515b0SLoGin } 2010fb515b0SLoGin } 2020fb515b0SLoGin 2030fb515b0SLoGin impl From<PosixOpenHow> for OpenHow { 2040fb515b0SLoGin fn from(posix_open_how: PosixOpenHow) -> Self { 2050fb515b0SLoGin let o_flags = FileMode::from_bits_truncate(posix_open_how.flags as u32); 2060fb515b0SLoGin let mode = ModeType::from_bits_truncate(posix_open_how.mode as u32); 2070fb515b0SLoGin let resolve = OpenHowResolve::from_bits_truncate(posix_open_how.resolve as u64); 2080fb515b0SLoGin return Self::new(o_flags, mode, resolve); 2090fb515b0SLoGin } 2100fb515b0SLoGin } 2110fb515b0SLoGin 2120fb515b0SLoGin bitflags! { 2130fb515b0SLoGin pub struct OpenHowResolve: u64{ 2140fb515b0SLoGin /// Block mount-point crossings 2150fb515b0SLoGin /// (including bind-mounts). 2160fb515b0SLoGin const RESOLVE_NO_XDEV = 0x01; 2170fb515b0SLoGin 2180fb515b0SLoGin /// Block traversal through procfs-style 2190fb515b0SLoGin /// "magic-links" 2200fb515b0SLoGin const RESOLVE_NO_MAGICLINKS = 0x02; 2210fb515b0SLoGin 2220fb515b0SLoGin /// Block traversal through all symlinks 2230fb515b0SLoGin /// (implies OEXT_NO_MAGICLINKS) 2240fb515b0SLoGin const RESOLVE_NO_SYMLINKS = 0x04; 2250fb515b0SLoGin /// Block "lexical" trickery like 2260fb515b0SLoGin /// "..", symlinks, and absolute 2270fb515b0SLoGin const RESOLVE_BENEATH = 0x08; 2280fb515b0SLoGin /// Make all jumps to "/" and ".." 2290fb515b0SLoGin /// be scoped inside the dirfd 2300fb515b0SLoGin /// (similar to chroot(2)). 2310fb515b0SLoGin const RESOLVE_IN_ROOT = 0x10; 2320fb515b0SLoGin // Only complete if resolution can be 2330fb515b0SLoGin // completed through cached lookup. May 2340fb515b0SLoGin // return -EAGAIN if that's not 2350fb515b0SLoGin // possible. 2360fb515b0SLoGin const RESOLVE_CACHED = 0x20; 2370fb515b0SLoGin } 2380fb515b0SLoGin } 239ab5c8ca4Slogin impl Syscall { 240ab5c8ca4Slogin /// @brief 为当前进程打开一个文件 241ab5c8ca4Slogin /// 242ab5c8ca4Slogin /// @param path 文件路径 243ab5c8ca4Slogin /// @param o_flags 打开文件的标志位 244ab5c8ca4Slogin /// 245ab5c8ca4Slogin /// @return 文件描述符编号,或者是错误码 2460fb515b0SLoGin pub fn open( 247*82df0a13Shmt path: *const u8, 248*82df0a13Shmt o_flags: u32, 249*82df0a13Shmt mode: u32, 2500fb515b0SLoGin follow_symlink: bool, 2510fb515b0SLoGin ) -> Result<usize, SystemError> { 252*82df0a13Shmt let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?; 253*82df0a13Shmt let open_flags: FileMode = FileMode::from_bits(o_flags).ok_or(SystemError::EINVAL)?; 254*82df0a13Shmt let mode = ModeType::from_bits(mode as u32).ok_or(SystemError::EINVAL)?; 255*82df0a13Shmt return do_sys_open( 256*82df0a13Shmt AtFlags::AT_FDCWD.bits(), 257*82df0a13Shmt &path, 258*82df0a13Shmt open_flags, 259*82df0a13Shmt mode, 260*82df0a13Shmt follow_symlink, 261*82df0a13Shmt ); 262ab5c8ca4Slogin } 263ab5c8ca4Slogin 2640fb515b0SLoGin pub fn openat( 2650fb515b0SLoGin dirfd: i32, 266*82df0a13Shmt path: *const u8, 267*82df0a13Shmt o_flags: u32, 268*82df0a13Shmt mode: u32, 2690fb515b0SLoGin follow_symlink: bool, 2700fb515b0SLoGin ) -> Result<usize, SystemError> { 271*82df0a13Shmt let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?; 272*82df0a13Shmt let open_flags: FileMode = FileMode::from_bits(o_flags).ok_or(SystemError::EINVAL)?; 273*82df0a13Shmt let mode = ModeType::from_bits(mode as u32).ok_or(SystemError::EINVAL)?; 274*82df0a13Shmt return do_sys_open(dirfd, &path, open_flags, mode, follow_symlink); 275ab5c8ca4Slogin } 276ab5c8ca4Slogin 277ab5c8ca4Slogin /// @brief 关闭文件 278ab5c8ca4Slogin /// 279ab5c8ca4Slogin /// @param fd 文件描述符编号 280ab5c8ca4Slogin /// 281ab5c8ca4Slogin /// @return 成功返回0,失败返回错误码 282ab5c8ca4Slogin pub fn close(fd: usize) -> Result<usize, SystemError> { 2831496ba7bSLoGin let binding = ProcessManager::current_pcb().fd_table(); 2841496ba7bSLoGin let mut fd_table_guard = binding.write(); 2851496ba7bSLoGin 28634e6d6c8Syuyi2439 let res = fd_table_guard.drop_fd(fd as i32).map(|_| 0); 28734e6d6c8Syuyi2439 28834e6d6c8Syuyi2439 return res; 289ab5c8ca4Slogin } 290ab5c8ca4Slogin 29140314b30SXiaoye Zheng /// @brief 发送命令到文件描述符对应的设备, 29240314b30SXiaoye Zheng /// 29340314b30SXiaoye Zheng /// @param fd 文件描述符编号 29440314b30SXiaoye Zheng /// @param cmd 设备相关的请求类型 29540314b30SXiaoye Zheng /// 29640314b30SXiaoye Zheng /// @return Ok(usize) 成功返回0 29740314b30SXiaoye Zheng /// @return Err(SystemError) 读取失败,返回posix错误码 29840314b30SXiaoye Zheng pub fn ioctl(fd: usize, cmd: u32, data: usize) -> Result<usize, SystemError> { 29940314b30SXiaoye Zheng let binding = ProcessManager::current_pcb().fd_table(); 30040314b30SXiaoye Zheng let fd_table_guard = binding.read(); 30140314b30SXiaoye Zheng 30240314b30SXiaoye Zheng let file = fd_table_guard 30340314b30SXiaoye Zheng .get_file_by_fd(fd as i32) 30440314b30SXiaoye Zheng .ok_or(SystemError::EBADF)?; 30540314b30SXiaoye Zheng 30640314b30SXiaoye Zheng // drop guard 以避免无法调度的问题 30740314b30SXiaoye Zheng drop(fd_table_guard); 30852da9a59SGnoCiYeH let file = file.lock_no_preempt(); 30952da9a59SGnoCiYeH let r = file.inode().ioctl(cmd, data, &file.private_data); 31040314b30SXiaoye Zheng return r; 31140314b30SXiaoye Zheng } 31240314b30SXiaoye Zheng 313ab5c8ca4Slogin /// @brief 根据文件描述符,读取文件数据。尝试读取的数据长度与buf的长度相同。 314ab5c8ca4Slogin /// 315ab5c8ca4Slogin /// @param fd 文件描述符编号 31627b967a3S裕依 /// @param buf 输出缓冲区 317ab5c8ca4Slogin /// 318ab5c8ca4Slogin /// @return Ok(usize) 成功读取的数据的字节数 319ab5c8ca4Slogin /// @return Err(SystemError) 读取失败,返回posix错误码 320ab5c8ca4Slogin pub fn read(fd: i32, buf: &mut [u8]) -> Result<usize, SystemError> { 3211496ba7bSLoGin let binding = ProcessManager::current_pcb().fd_table(); 3221496ba7bSLoGin let fd_table_guard = binding.read(); 3231496ba7bSLoGin 3241496ba7bSLoGin let file = fd_table_guard.get_file_by_fd(fd); 325ab5c8ca4Slogin if file.is_none() { 326ab5c8ca4Slogin return Err(SystemError::EBADF); 327ab5c8ca4Slogin } 3281496ba7bSLoGin // drop guard 以避免无法调度的问题 3291496ba7bSLoGin drop(fd_table_guard); 3301496ba7bSLoGin let file = file.unwrap(); 331ab5c8ca4Slogin 3321496ba7bSLoGin return file.lock_no_preempt().read(buf.len(), buf); 333ab5c8ca4Slogin } 334ab5c8ca4Slogin 335ab5c8ca4Slogin /// @brief 根据文件描述符,向文件写入数据。尝试写入的数据长度与buf的长度相同。 336ab5c8ca4Slogin /// 337ab5c8ca4Slogin /// @param fd 文件描述符编号 33827b967a3S裕依 /// @param buf 输入缓冲区 339ab5c8ca4Slogin /// 340ab5c8ca4Slogin /// @return Ok(usize) 成功写入的数据的字节数 341ab5c8ca4Slogin /// @return Err(SystemError) 写入失败,返回posix错误码 342ab5c8ca4Slogin pub fn write(fd: i32, buf: &[u8]) -> Result<usize, SystemError> { 3431496ba7bSLoGin let binding = ProcessManager::current_pcb().fd_table(); 3441496ba7bSLoGin let fd_table_guard = binding.read(); 345ab5c8ca4Slogin 3461496ba7bSLoGin let file = fd_table_guard 3471496ba7bSLoGin .get_file_by_fd(fd) 3481496ba7bSLoGin .ok_or(SystemError::EBADF)?; 3491496ba7bSLoGin 3501496ba7bSLoGin // drop guard 以避免无法调度的问题 3511496ba7bSLoGin drop(fd_table_guard); 3521496ba7bSLoGin return file.lock_no_preempt().write(buf.len(), buf); 353ab5c8ca4Slogin } 354ab5c8ca4Slogin 355ab5c8ca4Slogin /// @brief 调整文件操作指针的位置 356ab5c8ca4Slogin /// 357ab5c8ca4Slogin /// @param fd 文件描述符编号 358ab5c8ca4Slogin /// @param seek 调整的方式 359ab5c8ca4Slogin /// 360ab5c8ca4Slogin /// @return Ok(usize) 调整后,文件访问指针相对于文件头部的偏移量 361ab5c8ca4Slogin /// @return Err(SystemError) 调整失败,返回posix错误码 362*82df0a13Shmt pub fn lseek(fd: i32, offset: i64, seek: u32) -> Result<usize, SystemError> { 363*82df0a13Shmt let seek = match seek { 364*82df0a13Shmt SEEK_SET => Ok(SeekFrom::SeekSet(offset)), 365*82df0a13Shmt SEEK_CUR => Ok(SeekFrom::SeekCurrent(offset)), 366*82df0a13Shmt SEEK_END => Ok(SeekFrom::SeekEnd(offset)), 367*82df0a13Shmt SEEK_MAX => Ok(SeekFrom::SeekEnd(0)), 368*82df0a13Shmt _ => Err(SystemError::EINVAL), 369*82df0a13Shmt }?; 370*82df0a13Shmt 3711496ba7bSLoGin let binding = ProcessManager::current_pcb().fd_table(); 3721496ba7bSLoGin let fd_table_guard = binding.read(); 3731496ba7bSLoGin let file = fd_table_guard 3741496ba7bSLoGin .get_file_by_fd(fd) 3751496ba7bSLoGin .ok_or(SystemError::EBADF)?; 3761496ba7bSLoGin 3771496ba7bSLoGin // drop guard 以避免无法调度的问题 3781496ba7bSLoGin drop(fd_table_guard); 3791496ba7bSLoGin return file.lock_no_preempt().lseek(seek); 380004e86ffSlogin } 381004e86ffSlogin 38227b967a3S裕依 /// # sys_pread64 系统调用的实际执行函数 38327b967a3S裕依 /// 38427b967a3S裕依 /// ## 参数 38527b967a3S裕依 /// - `fd`: 文件描述符 38627b967a3S裕依 /// - `buf`: 读出缓冲区 38727b967a3S裕依 /// - `len`: 要读取的字节数 38827b967a3S裕依 /// - `offset`: 文件偏移量 38927b967a3S裕依 pub fn pread(fd: i32, buf: &mut [u8], len: usize, offset: usize) -> Result<usize, SystemError> { 39027b967a3S裕依 let binding = ProcessManager::current_pcb().fd_table(); 39127b967a3S裕依 let fd_table_guard = binding.read(); 39227b967a3S裕依 39327b967a3S裕依 let file = fd_table_guard.get_file_by_fd(fd); 39427b967a3S裕依 if file.is_none() { 39527b967a3S裕依 return Err(SystemError::EBADF); 39627b967a3S裕依 } 39727b967a3S裕依 // drop guard 以避免无法调度的问题 39827b967a3S裕依 drop(fd_table_guard); 39927b967a3S裕依 let file = file.unwrap(); 40027b967a3S裕依 40127b967a3S裕依 return file.lock_no_preempt().pread(offset, len, buf); 40227b967a3S裕依 } 40327b967a3S裕依 40427b967a3S裕依 /// # sys_pwrite64 系统调用的实际执行函数 40527b967a3S裕依 /// 40627b967a3S裕依 /// ## 参数 40727b967a3S裕依 /// - `fd`: 文件描述符 40827b967a3S裕依 /// - `buf`: 写入缓冲区 40927b967a3S裕依 /// - `len`: 要写入的字节数 41027b967a3S裕依 /// - `offset`: 文件偏移量 41127b967a3S裕依 pub fn pwrite(fd: i32, buf: &[u8], len: usize, offset: usize) -> Result<usize, SystemError> { 41227b967a3S裕依 let binding = ProcessManager::current_pcb().fd_table(); 41327b967a3S裕依 let fd_table_guard = binding.read(); 41427b967a3S裕依 41527b967a3S裕依 let file = fd_table_guard.get_file_by_fd(fd); 41627b967a3S裕依 if file.is_none() { 41727b967a3S裕依 return Err(SystemError::EBADF); 41827b967a3S裕依 } 41927b967a3S裕依 // drop guard 以避免无法调度的问题 42027b967a3S裕依 drop(fd_table_guard); 42127b967a3S裕依 let file = file.unwrap(); 42227b967a3S裕依 42327b967a3S裕依 return file.lock_no_preempt().pwrite(offset, len, buf); 42427b967a3S裕依 } 42527b967a3S裕依 426004e86ffSlogin /// @brief 切换工作目录 427004e86ffSlogin /// 428004e86ffSlogin /// @param dest_path 目标路径 429004e86ffSlogin /// 430004e86ffSlogin /// @return 返回码 描述 431004e86ffSlogin /// 0 | 成功 432004e86ffSlogin /// 433004e86ffSlogin /// EACCESS | 权限不足 434004e86ffSlogin /// 435004e86ffSlogin /// ELOOP | 解析path时遇到路径循环 436004e86ffSlogin /// 437004e86ffSlogin /// ENAMETOOLONG | 路径名过长 438004e86ffSlogin /// 439004e86ffSlogin /// ENOENT | 目标文件或目录不存在 440004e86ffSlogin /// 441004e86ffSlogin /// ENODIR | 检索期间发现非目录项 442004e86ffSlogin /// 443004e86ffSlogin /// ENOMEM | 系统内存不足 444004e86ffSlogin /// 445004e86ffSlogin /// EFAULT | 错误的地址 446004e86ffSlogin /// 447004e86ffSlogin /// ENAMETOOLONG | 路径过长 448*82df0a13Shmt pub fn chdir(path: *const u8) -> Result<usize, SystemError> { 449*82df0a13Shmt if path.is_null() { 450*82df0a13Shmt return Err(SystemError::EFAULT); 451*82df0a13Shmt } 452*82df0a13Shmt 453*82df0a13Shmt let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?; 4541496ba7bSLoGin let proc = ProcessManager::current_pcb(); 455ab5c8ca4Slogin // Copy path to kernel space to avoid some security issues 4561496ba7bSLoGin let mut new_path = String::from(""); 4571496ba7bSLoGin if path.len() > 0 { 4581496ba7bSLoGin let cwd = match path.as_bytes()[0] { 4591496ba7bSLoGin b'/' => String::from("/"), 4601496ba7bSLoGin _ => proc.basic().cwd(), 4611496ba7bSLoGin }; 4621496ba7bSLoGin let mut cwd_vec: Vec<_> = cwd.split("/").filter(|&x| x != "").collect(); 4631496ba7bSLoGin let path_split = path.split("/").filter(|&x| x != ""); 4641496ba7bSLoGin for seg in path_split { 4651496ba7bSLoGin if seg == ".." { 4661496ba7bSLoGin cwd_vec.pop(); 4671496ba7bSLoGin } else if seg == "." { 4681496ba7bSLoGin // 当前目录 4691496ba7bSLoGin } else { 4701496ba7bSLoGin cwd_vec.push(seg); 4711496ba7bSLoGin } 4721496ba7bSLoGin } 4731496ba7bSLoGin //proc.basic().set_path(String::from("")); 4741496ba7bSLoGin for seg in cwd_vec { 4751496ba7bSLoGin new_path.push_str("/"); 4761496ba7bSLoGin new_path.push_str(seg); 4771496ba7bSLoGin } 4781496ba7bSLoGin if new_path == "" { 4791496ba7bSLoGin new_path = String::from("/"); 4801496ba7bSLoGin } 4811496ba7bSLoGin } 482a03c4f9dSLoGin let inode = 483a03c4f9dSLoGin match ROOT_INODE().lookup_follow_symlink(&new_path, VFS_MAX_FOLLOW_SYMLINK_TIMES) { 484*82df0a13Shmt Err(_) => { 485ab5c8ca4Slogin return Err(SystemError::ENOENT); 486004e86ffSlogin } 487004e86ffSlogin Ok(i) => i, 488004e86ffSlogin }; 4891496ba7bSLoGin let metadata = inode.metadata()?; 4901496ba7bSLoGin if metadata.file_type == FileType::Dir { 4911496ba7bSLoGin proc.basic_mut().set_cwd(String::from(new_path)); 492ab5c8ca4Slogin return Ok(0); 493004e86ffSlogin } else { 494ab5c8ca4Slogin return Err(SystemError::ENOTDIR); 495004e86ffSlogin } 496004e86ffSlogin } 4971496ba7bSLoGin 4981496ba7bSLoGin /// @brief 获取当前进程的工作目录路径 4991496ba7bSLoGin /// 5001496ba7bSLoGin /// @param buf 指向缓冲区的指针 5011496ba7bSLoGin /// @param size 缓冲区的大小 5021496ba7bSLoGin /// 5031496ba7bSLoGin /// @return 成功,返回的指针指向包含工作目录路径的字符串 5041496ba7bSLoGin /// @return 错误,没有足够的空间 5051496ba7bSLoGin pub fn getcwd(buf: &mut [u8]) -> Result<VirtAddr, SystemError> { 5061496ba7bSLoGin let proc = ProcessManager::current_pcb(); 5071496ba7bSLoGin let cwd = proc.basic().cwd(); 5081496ba7bSLoGin 5091496ba7bSLoGin let cwd_bytes = cwd.as_bytes(); 5101496ba7bSLoGin let cwd_len = cwd_bytes.len(); 5111496ba7bSLoGin if cwd_len + 1 > buf.len() { 5121496ba7bSLoGin return Err(SystemError::ENOMEM); 513004e86ffSlogin } 5141496ba7bSLoGin buf[..cwd_len].copy_from_slice(cwd_bytes); 5151496ba7bSLoGin buf[cwd_len] = 0; 5161496ba7bSLoGin 5171496ba7bSLoGin return Ok(VirtAddr::new(buf.as_ptr() as usize)); 518004e86ffSlogin } 519004e86ffSlogin 520004e86ffSlogin /// @brief 获取目录中的数据 521004e86ffSlogin /// 522ab5c8ca4Slogin /// TODO: 这个函数的语义与Linux不一致,需要修改!!! 523ab5c8ca4Slogin /// 524004e86ffSlogin /// @param fd 文件描述符号 525ab5c8ca4Slogin /// @param buf 输出缓冲区 526ab5c8ca4Slogin /// 527ab5c8ca4Slogin /// @return 成功返回读取的字节数,失败返回错误码 528ab5c8ca4Slogin pub fn getdents(fd: i32, buf: &mut [u8]) -> Result<usize, SystemError> { 529ab5c8ca4Slogin let dirent = 530ab5c8ca4Slogin unsafe { (buf.as_mut_ptr() as *mut Dirent).as_mut() }.ok_or(SystemError::EFAULT)?; 531004e86ffSlogin 53246e234aeSLoGin if fd < 0 || fd as usize > FileDescriptorVec::PROCESS_MAX_FD { 533ab5c8ca4Slogin return Err(SystemError::EBADF); 534004e86ffSlogin } 535004e86ffSlogin 536004e86ffSlogin // 获取fd 5371496ba7bSLoGin let binding = ProcessManager::current_pcb().fd_table(); 5381496ba7bSLoGin let fd_table_guard = binding.read(); 5391496ba7bSLoGin let file = fd_table_guard 5401496ba7bSLoGin .get_file_by_fd(fd) 5411496ba7bSLoGin .ok_or(SystemError::EBADF)?; 542004e86ffSlogin 5431496ba7bSLoGin // drop guard 以避免无法调度的问题 5441496ba7bSLoGin drop(fd_table_guard); 54534e6d6c8Syuyi2439 54634e6d6c8Syuyi2439 let res = file.lock_no_preempt().readdir(dirent).map(|x| x as usize); 54734e6d6c8Syuyi2439 54834e6d6c8Syuyi2439 return res; 549004e86ffSlogin } 550004e86ffSlogin 551004e86ffSlogin /// @brief 创建文件夹 552004e86ffSlogin /// 553004e86ffSlogin /// @param path(r8) 路径 / mode(r9) 模式 554004e86ffSlogin /// 555004e86ffSlogin /// @return uint64_t 负数错误码 / 0表示成功 556*82df0a13Shmt pub fn mkdir(path: *const u8, mode: usize) -> Result<usize, SystemError> { 557*82df0a13Shmt let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?; 558*82df0a13Shmt return do_mkdir(&path, FileMode::from_bits_truncate(mode as u32)).map(|x| x as usize); 559004e86ffSlogin } 560004e86ffSlogin 561ab5c8ca4Slogin /// **删除文件夹、取消文件的链接、删除文件的系统调用** 562004e86ffSlogin /// 563ab5c8ca4Slogin /// ## 参数 564004e86ffSlogin /// 565ab5c8ca4Slogin /// - `dirfd`:文件夹的文件描述符.目前暂未实现 566ab5c8ca4Slogin /// - `pathname`:文件夹的路径 567ab5c8ca4Slogin /// - `flags`:标志位 568004e86ffSlogin /// 569004e86ffSlogin /// 570*82df0a13Shmt pub fn unlinkat(dirfd: i32, path: *const u8, flags: u32) -> Result<usize, SystemError> { 571bf4a4899SLoGin let flags = AtFlags::from_bits(flags as i32).ok_or(SystemError::EINVAL)?; 572004e86ffSlogin 573*82df0a13Shmt let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?; 574*82df0a13Shmt 575bf4a4899SLoGin if flags.contains(AtFlags::AT_REMOVEDIR) { 576004e86ffSlogin // kdebug!("rmdir"); 577*82df0a13Shmt match do_remove_dir(dirfd, &path) { 578004e86ffSlogin Err(err) => { 579ab5c8ca4Slogin return Err(err); 580004e86ffSlogin } 581004e86ffSlogin Ok(_) => { 582ab5c8ca4Slogin return Ok(0); 583004e86ffSlogin } 584004e86ffSlogin } 585004e86ffSlogin } 586004e86ffSlogin 587*82df0a13Shmt match do_unlink_at(dirfd, &path) { 588004e86ffSlogin Err(err) => { 589ab5c8ca4Slogin return Err(err); 590004e86ffSlogin } 591004e86ffSlogin Ok(_) => { 592ab5c8ca4Slogin return Ok(0); 593004e86ffSlogin } 594004e86ffSlogin } 595004e86ffSlogin } 5962b771e32SGou Ngai 597*82df0a13Shmt pub fn rmdir(path: *const u8) -> Result<usize, SystemError> { 598*82df0a13Shmt let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?; 599*82df0a13Shmt return do_remove_dir(AtFlags::AT_FDCWD.bits(), &path).map(|v| v as usize); 6005eeefb8cSChenzx } 6015eeefb8cSChenzx 602*82df0a13Shmt pub fn unlink(path: *const u8) -> Result<usize, SystemError> { 603*82df0a13Shmt let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?; 604*82df0a13Shmt return do_unlink_at(AtFlags::AT_FDCWD.bits(), &path).map(|v| v as usize); 605bf4a4899SLoGin } 606bf4a4899SLoGin 6079e481b3bSTTaq /// # 修改文件名 6089e481b3bSTTaq /// 6099e481b3bSTTaq /// 6109e481b3bSTTaq /// ## 参数 6119e481b3bSTTaq /// 6129e481b3bSTTaq /// - oldfd: 源文件描述符 6139e481b3bSTTaq /// - filename_from: 源文件路径 6149e481b3bSTTaq /// - newfd: 目标文件描述符 6159e481b3bSTTaq /// - filename_to: 目标文件路径 6169e481b3bSTTaq /// - flags: 标志位 6179e481b3bSTTaq /// 6189e481b3bSTTaq /// 6199e481b3bSTTaq /// ## 返回值 6209e481b3bSTTaq /// - Ok(返回值类型): 返回值的说明 6219e481b3bSTTaq /// - Err(错误值类型): 错误的说明 6229e481b3bSTTaq /// 6239e481b3bSTTaq pub fn do_renameat2( 6249e481b3bSTTaq oldfd: i32, 6259e481b3bSTTaq filename_from: *const u8, 6269e481b3bSTTaq newfd: i32, 6279e481b3bSTTaq filename_to: *const u8, 6289e481b3bSTTaq _flags: u32, 6299e481b3bSTTaq ) -> Result<usize, SystemError> { 6309e481b3bSTTaq let filename_from = check_and_clone_cstr(filename_from, Some(MAX_PATHLEN)).unwrap(); 6319e481b3bSTTaq let filename_to = check_and_clone_cstr(filename_to, Some(MAX_PATHLEN)).unwrap(); 6329e481b3bSTTaq // 文件名过长 6339e481b3bSTTaq if filename_from.len() > MAX_PATHLEN as usize || filename_to.len() > MAX_PATHLEN as usize { 6349e481b3bSTTaq return Err(SystemError::ENAMETOOLONG); 6359e481b3bSTTaq } 6369e481b3bSTTaq 6379e481b3bSTTaq //获取pcb,文件节点 6389e481b3bSTTaq let pcb = ProcessManager::current_pcb(); 6399e481b3bSTTaq let (_old_inode_begin, old_remain_path) = user_path_at(&pcb, oldfd, &filename_from)?; 6409e481b3bSTTaq let (_new_inode_begin, new_remain_path) = user_path_at(&pcb, newfd, &filename_to)?; 6419e481b3bSTTaq //获取父目录 6429e481b3bSTTaq let (old_filename, old_parent_path) = rsplit_path(&old_remain_path); 6439e481b3bSTTaq let old_parent_inode = ROOT_INODE() 6449e481b3bSTTaq .lookup_follow_symlink(old_parent_path.unwrap_or("/"), VFS_MAX_FOLLOW_SYMLINK_TIMES)?; 6459e481b3bSTTaq let (new_filename, new_parent_path) = rsplit_path(&new_remain_path); 6469e481b3bSTTaq let new_parent_inode = ROOT_INODE() 6479e481b3bSTTaq .lookup_follow_symlink(new_parent_path.unwrap_or("/"), VFS_MAX_FOLLOW_SYMLINK_TIMES)?; 6489e481b3bSTTaq old_parent_inode.move_to(old_filename, &new_parent_inode, new_filename)?; 6499e481b3bSTTaq return Ok(0); 6509e481b3bSTTaq } 6519e481b3bSTTaq 652ab5c8ca4Slogin /// @brief 根据提供的文件描述符的fd,复制对应的文件结构体,并返回新复制的文件结构体对应的fd 653ab5c8ca4Slogin pub fn dup(oldfd: i32) -> Result<usize, SystemError> { 6541496ba7bSLoGin let binding = ProcessManager::current_pcb().fd_table(); 6551496ba7bSLoGin let mut fd_table_guard = binding.write(); 656ab5c8ca4Slogin 6571496ba7bSLoGin let old_file = fd_table_guard 6581496ba7bSLoGin .get_file_by_fd(oldfd) 6591496ba7bSLoGin .ok_or(SystemError::EBADF)?; 6601496ba7bSLoGin 6611496ba7bSLoGin let new_file = old_file 6621496ba7bSLoGin .lock_no_preempt() 6631496ba7bSLoGin .try_clone() 6641496ba7bSLoGin .ok_or(SystemError::EBADF)?; 6652b771e32SGou Ngai // 申请文件描述符,并把文件对象存入其中 6661496ba7bSLoGin let res = fd_table_guard.alloc_fd(new_file, None).map(|x| x as usize); 6672b771e32SGou Ngai return res; 6682b771e32SGou Ngai } 6692b771e32SGou Ngai 670ab5c8ca4Slogin /// 根据提供的文件描述符的fd,和指定新fd,复制对应的文件结构体, 671ab5c8ca4Slogin /// 并返回新复制的文件结构体对应的fd. 672ab5c8ca4Slogin /// 如果新fd已经打开,则会先关闭新fd. 673ab5c8ca4Slogin /// 674ab5c8ca4Slogin /// ## 参数 675ab5c8ca4Slogin /// 676ab5c8ca4Slogin /// - `oldfd`:旧文件描述符 677ab5c8ca4Slogin /// - `newfd`:新文件描述符 678ab5c8ca4Slogin /// 679ab5c8ca4Slogin /// ## 返回值 680ab5c8ca4Slogin /// 681ab5c8ca4Slogin /// - 成功:新文件描述符 682ab5c8ca4Slogin /// - 失败:错误码 683ab5c8ca4Slogin pub fn dup2(oldfd: i32, newfd: i32) -> Result<usize, SystemError> { 6841496ba7bSLoGin let binding = ProcessManager::current_pcb().fd_table(); 6851496ba7bSLoGin let mut fd_table_guard = binding.write(); 6861496ba7bSLoGin return Self::do_dup2(oldfd, newfd, &mut fd_table_guard); 6871496ba7bSLoGin } 6881496ba7bSLoGin 6891496ba7bSLoGin fn do_dup2( 6901496ba7bSLoGin oldfd: i32, 6911496ba7bSLoGin newfd: i32, 6921496ba7bSLoGin fd_table_guard: &mut RwLockWriteGuard<'_, FileDescriptorVec>, 6931496ba7bSLoGin ) -> Result<usize, SystemError> { 6942b771e32SGou Ngai // 确认oldfd, newid是否有效 6951496ba7bSLoGin if !(FileDescriptorVec::validate_fd(oldfd) && FileDescriptorVec::validate_fd(newfd)) { 6961496ba7bSLoGin return Err(SystemError::EBADF); 6971496ba7bSLoGin } 6981496ba7bSLoGin 6992b771e32SGou Ngai if oldfd == newfd { 7002b771e32SGou Ngai // 若oldfd与newfd相等 701ab5c8ca4Slogin return Ok(newfd as usize); 7022b771e32SGou Ngai } 7031496ba7bSLoGin let new_exists = fd_table_guard.get_file_by_fd(newfd).is_some(); 7041496ba7bSLoGin if new_exists { 7052b771e32SGou Ngai // close newfd 7061496ba7bSLoGin if let Err(_) = fd_table_guard.drop_fd(newfd) { 7072b771e32SGou Ngai // An I/O error occurred while attempting to close fildes2. 7082b771e32SGou Ngai return Err(SystemError::EIO); 7092b771e32SGou Ngai } 7102b771e32SGou Ngai } 7112b771e32SGou Ngai 7121496ba7bSLoGin let old_file = fd_table_guard 7131496ba7bSLoGin .get_file_by_fd(oldfd) 7141496ba7bSLoGin .ok_or(SystemError::EBADF)?; 7151496ba7bSLoGin let new_file = old_file 7161496ba7bSLoGin .lock_no_preempt() 7171496ba7bSLoGin .try_clone() 7181496ba7bSLoGin .ok_or(SystemError::EBADF)?; 7192b771e32SGou Ngai // 申请文件描述符,并把文件对象存入其中 7201496ba7bSLoGin let res = fd_table_guard 7211496ba7bSLoGin .alloc_fd(new_file, Some(newfd)) 722ab5c8ca4Slogin .map(|x| x as usize); 7232b771e32SGou Ngai return res; 7242b771e32SGou Ngai } 7256d81180bSLoGin 7266d81180bSLoGin /// # fcntl 7276d81180bSLoGin /// 7286d81180bSLoGin /// ## 参数 7296d81180bSLoGin /// 7306d81180bSLoGin /// - `fd`:文件描述符 7316d81180bSLoGin /// - `cmd`:命令 7326d81180bSLoGin /// - `arg`:参数 7336d81180bSLoGin pub fn fcntl(fd: i32, cmd: FcntlCommand, arg: i32) -> Result<usize, SystemError> { 7346d81180bSLoGin match cmd { 7356d81180bSLoGin FcntlCommand::DupFd => { 7366d81180bSLoGin if arg < 0 || arg as usize >= FileDescriptorVec::PROCESS_MAX_FD { 7376d81180bSLoGin return Err(SystemError::EBADF); 7386d81180bSLoGin } 7396d81180bSLoGin let arg = arg as usize; 7406d81180bSLoGin for i in arg..FileDescriptorVec::PROCESS_MAX_FD { 7411496ba7bSLoGin let binding = ProcessManager::current_pcb().fd_table(); 7421496ba7bSLoGin let mut fd_table_guard = binding.write(); 74352da9a59SGnoCiYeH if fd_table_guard.get_file_by_fd(i as i32).is_none() { 7441496ba7bSLoGin return Self::do_dup2(fd, i as i32, &mut fd_table_guard); 7456d81180bSLoGin } 7466d81180bSLoGin } 7476d81180bSLoGin return Err(SystemError::EMFILE); 7486d81180bSLoGin } 7496d81180bSLoGin FcntlCommand::GetFd => { 7506d81180bSLoGin // Get file descriptor flags. 7511496ba7bSLoGin let binding = ProcessManager::current_pcb().fd_table(); 7521496ba7bSLoGin let fd_table_guard = binding.read(); 7531496ba7bSLoGin if let Some(file) = fd_table_guard.get_file_by_fd(fd) { 7541496ba7bSLoGin // drop guard 以避免无法调度的问题 7551496ba7bSLoGin drop(fd_table_guard); 7566d81180bSLoGin 7571496ba7bSLoGin if file.lock().close_on_exec() { 7586d81180bSLoGin return Ok(FD_CLOEXEC as usize); 7596d81180bSLoGin } 7606d81180bSLoGin } 7616d81180bSLoGin return Err(SystemError::EBADF); 7626d81180bSLoGin } 7636d81180bSLoGin FcntlCommand::SetFd => { 7646d81180bSLoGin // Set file descriptor flags. 7651496ba7bSLoGin let binding = ProcessManager::current_pcb().fd_table(); 7661496ba7bSLoGin let fd_table_guard = binding.write(); 7671496ba7bSLoGin 7681496ba7bSLoGin if let Some(file) = fd_table_guard.get_file_by_fd(fd) { 7691496ba7bSLoGin // drop guard 以避免无法调度的问题 7701496ba7bSLoGin drop(fd_table_guard); 7716d81180bSLoGin let arg = arg as u32; 7726d81180bSLoGin if arg & FD_CLOEXEC != 0 { 7731496ba7bSLoGin file.lock().set_close_on_exec(true); 7746d81180bSLoGin } else { 7751496ba7bSLoGin file.lock().set_close_on_exec(false); 7766d81180bSLoGin } 7776d81180bSLoGin return Ok(0); 7786d81180bSLoGin } 7796d81180bSLoGin return Err(SystemError::EBADF); 7806d81180bSLoGin } 7816d81180bSLoGin 7826d81180bSLoGin FcntlCommand::GetFlags => { 7836d81180bSLoGin // Get file status flags. 7841496ba7bSLoGin let binding = ProcessManager::current_pcb().fd_table(); 7851496ba7bSLoGin let fd_table_guard = binding.read(); 7861496ba7bSLoGin 7871496ba7bSLoGin if let Some(file) = fd_table_guard.get_file_by_fd(fd) { 7881496ba7bSLoGin // drop guard 以避免无法调度的问题 7891496ba7bSLoGin drop(fd_table_guard); 7901496ba7bSLoGin return Ok(file.lock_no_preempt().mode().bits() as usize); 7916d81180bSLoGin } 7921496ba7bSLoGin 7936d81180bSLoGin return Err(SystemError::EBADF); 7946d81180bSLoGin } 7956d81180bSLoGin FcntlCommand::SetFlags => { 7966d81180bSLoGin // Set file status flags. 7971496ba7bSLoGin let binding = ProcessManager::current_pcb().fd_table(); 7981496ba7bSLoGin let fd_table_guard = binding.write(); 7991496ba7bSLoGin 8001496ba7bSLoGin if let Some(file) = fd_table_guard.get_file_by_fd(fd) { 8016d81180bSLoGin let arg = arg as u32; 8026d81180bSLoGin let mode = FileMode::from_bits(arg).ok_or(SystemError::EINVAL)?; 8031496ba7bSLoGin // drop guard 以避免无法调度的问题 8041496ba7bSLoGin drop(fd_table_guard); 8051496ba7bSLoGin file.lock_no_preempt().set_mode(mode)?; 8066d81180bSLoGin return Ok(0); 8076d81180bSLoGin } 8081496ba7bSLoGin 8096d81180bSLoGin return Err(SystemError::EBADF); 8106d81180bSLoGin } 8116d81180bSLoGin _ => { 8126d81180bSLoGin // TODO: unimplemented 8136d81180bSLoGin // 未实现的命令,返回0,不报错。 8146d81180bSLoGin 8156d81180bSLoGin // kwarn!("fcntl: unimplemented command: {:?}, defaults to 0.", cmd); 8166d81180bSLoGin return Ok(0); 8176d81180bSLoGin } 8186d81180bSLoGin } 8196d81180bSLoGin } 8206d81180bSLoGin 8216d81180bSLoGin /// # ftruncate 8226d81180bSLoGin /// 8236d81180bSLoGin /// ## 描述 8246d81180bSLoGin /// 8256d81180bSLoGin /// 改变文件大小. 8266d81180bSLoGin /// 如果文件大小大于原来的大小,那么文件的内容将会被扩展到指定的大小,新的空间将会用0填充. 8276d81180bSLoGin /// 如果文件大小小于原来的大小,那么文件的内容将会被截断到指定的大小. 8286d81180bSLoGin /// 8296d81180bSLoGin /// ## 参数 8306d81180bSLoGin /// 8316d81180bSLoGin /// - `fd`:文件描述符 8326d81180bSLoGin /// - `len`:文件大小 8336d81180bSLoGin /// 8346d81180bSLoGin /// ## 返回值 8356d81180bSLoGin /// 8366d81180bSLoGin /// 如果成功,返回0,否则返回错误码. 8376d81180bSLoGin pub fn ftruncate(fd: i32, len: usize) -> Result<usize, SystemError> { 8381496ba7bSLoGin let binding = ProcessManager::current_pcb().fd_table(); 8391496ba7bSLoGin let fd_table_guard = binding.read(); 8401496ba7bSLoGin 8411496ba7bSLoGin if let Some(file) = fd_table_guard.get_file_by_fd(fd) { 8421496ba7bSLoGin // drop guard 以避免无法调度的问题 8431496ba7bSLoGin drop(fd_table_guard); 8441496ba7bSLoGin let r = file.lock_no_preempt().ftruncate(len).map(|_| 0); 8456d81180bSLoGin return r; 8466d81180bSLoGin } 8471496ba7bSLoGin 8486d81180bSLoGin return Err(SystemError::EBADF); 8496d81180bSLoGin } 8501496ba7bSLoGin 85167b48188Shoumkh fn do_fstat(fd: i32) -> Result<PosixKstat, SystemError> { 8521496ba7bSLoGin let binding = ProcessManager::current_pcb().fd_table(); 8531496ba7bSLoGin let fd_table_guard = binding.read(); 8541496ba7bSLoGin let file = fd_table_guard 8551496ba7bSLoGin .get_file_by_fd(fd) 8561496ba7bSLoGin .ok_or(SystemError::EBADF)?; 8571496ba7bSLoGin // drop guard 以避免无法调度的问题 8581496ba7bSLoGin drop(fd_table_guard); 8591496ba7bSLoGin 86067b48188Shoumkh let mut kstat = PosixKstat::new(); 86167b48188Shoumkh // 获取文件信息 8621496ba7bSLoGin let metadata = file.lock().metadata()?; 86367b48188Shoumkh kstat.size = metadata.size as i64; 86467b48188Shoumkh kstat.dev_id = metadata.dev_id as u64; 8656b4e7a29SLoGin kstat.inode = metadata.inode_id.into() as u64; 86667b48188Shoumkh kstat.blcok_size = metadata.blk_size as i64; 86767b48188Shoumkh kstat.blocks = metadata.blocks as u64; 86867b48188Shoumkh 86967b48188Shoumkh kstat.atime.tv_sec = metadata.atime.tv_sec; 87067b48188Shoumkh kstat.atime.tv_nsec = metadata.atime.tv_nsec; 87167b48188Shoumkh kstat.mtime.tv_sec = metadata.mtime.tv_sec; 87267b48188Shoumkh kstat.mtime.tv_nsec = metadata.mtime.tv_nsec; 87367b48188Shoumkh kstat.ctime.tv_sec = metadata.ctime.tv_sec; 87467b48188Shoumkh kstat.ctime.tv_nsec = metadata.ctime.tv_nsec; 87567b48188Shoumkh 87667b48188Shoumkh kstat.nlink = metadata.nlinks as u64; 87767b48188Shoumkh kstat.uid = metadata.uid as i32; 87867b48188Shoumkh kstat.gid = metadata.gid as i32; 87902343d0bSLoGin kstat.rdev = metadata.raw_dev.data() as i64; 8806b4e7a29SLoGin kstat.mode = metadata.mode; 8811496ba7bSLoGin match file.lock().file_type() { 8827eda31b2SLoGin FileType::File => kstat.mode.insert(ModeType::S_IFREG), 88367b48188Shoumkh FileType::Dir => kstat.mode.insert(ModeType::S_IFDIR), 88467b48188Shoumkh FileType::BlockDevice => kstat.mode.insert(ModeType::S_IFBLK), 88567b48188Shoumkh FileType::CharDevice => kstat.mode.insert(ModeType::S_IFCHR), 88667b48188Shoumkh FileType::SymLink => kstat.mode.insert(ModeType::S_IFLNK), 88767b48188Shoumkh FileType::Socket => kstat.mode.insert(ModeType::S_IFSOCK), 88867b48188Shoumkh FileType::Pipe => kstat.mode.insert(ModeType::S_IFIFO), 88940314b30SXiaoye Zheng FileType::KvmDevice => kstat.mode.insert(ModeType::S_IFCHR), 89002343d0bSLoGin FileType::FramebufferDevice => kstat.mode.insert(ModeType::S_IFCHR), 89167b48188Shoumkh } 89267b48188Shoumkh 89367b48188Shoumkh return Ok(kstat); 89467b48188Shoumkh } 8951496ba7bSLoGin 89667b48188Shoumkh pub fn fstat(fd: i32, usr_kstat: *mut PosixKstat) -> Result<usize, SystemError> { 897*82df0a13Shmt let mut writer = UserBufferWriter::new(usr_kstat, size_of::<PosixKstat>(), true)?; 8981496ba7bSLoGin let kstat = Self::do_fstat(fd)?; 899*82df0a13Shmt 900*82df0a13Shmt writer.copy_one_to_user(&kstat, 0)?; 90167b48188Shoumkh return Ok(0); 90267b48188Shoumkh } 9032dbef785SGnoCiYeH 904*82df0a13Shmt pub fn stat(path: *const u8, user_kstat: *mut PosixKstat) -> Result<usize, SystemError> { 905*82df0a13Shmt let fd = Self::open( 906*82df0a13Shmt path, 907*82df0a13Shmt FileMode::O_RDONLY.bits(), 908*82df0a13Shmt ModeType::empty().bits(), 909*82df0a13Shmt true, 910*82df0a13Shmt )?; 911bf4a4899SLoGin let r = Self::fstat(fd as i32, user_kstat); 912971462beSGnoCiYeH Self::close(fd).ok(); 913bf4a4899SLoGin return r; 914bf4a4899SLoGin } 915bf4a4899SLoGin 916*82df0a13Shmt pub fn lstat(path: *const u8, user_kstat: *mut PosixKstat) -> Result<usize, SystemError> { 917*82df0a13Shmt let fd = Self::open( 918*82df0a13Shmt path, 919*82df0a13Shmt FileMode::O_RDONLY.bits(), 920*82df0a13Shmt ModeType::empty().bits(), 921*82df0a13Shmt false, 922*82df0a13Shmt )?; 923bf4a4899SLoGin let r = Self::fstat(fd as i32, user_kstat); 924bf4a4899SLoGin Self::close(fd).ok(); 925bf4a4899SLoGin return r; 926971462beSGnoCiYeH } 927971462beSGnoCiYeH 9282dbef785SGnoCiYeH pub fn mknod( 929*82df0a13Shmt path: *const u8, 9302dbef785SGnoCiYeH mode: ModeType, 9312dbef785SGnoCiYeH dev_t: DeviceNumber, 9322dbef785SGnoCiYeH ) -> Result<usize, SystemError> { 933*82df0a13Shmt let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?; 934*82df0a13Shmt let path = path.as_str().trim(); 9352dbef785SGnoCiYeH 936a03c4f9dSLoGin let inode: Result<Arc<dyn IndexNode>, SystemError> = 937a03c4f9dSLoGin ROOT_INODE().lookup_follow_symlink(path, VFS_MAX_FOLLOW_SYMLINK_TIMES); 9382dbef785SGnoCiYeH 9392dbef785SGnoCiYeH if inode.is_ok() { 9402dbef785SGnoCiYeH return Err(SystemError::EEXIST); 9412dbef785SGnoCiYeH } 9422dbef785SGnoCiYeH 9432dbef785SGnoCiYeH let (filename, parent_path) = rsplit_path(path); 9442dbef785SGnoCiYeH 9452dbef785SGnoCiYeH // 查找父目录 946a03c4f9dSLoGin let parent_inode: Arc<dyn IndexNode> = ROOT_INODE() 947a03c4f9dSLoGin .lookup_follow_symlink(parent_path.unwrap_or("/"), VFS_MAX_FOLLOW_SYMLINK_TIMES)?; 9482dbef785SGnoCiYeH // 创建nod 9492dbef785SGnoCiYeH parent_inode.mknod(filename, mode, dev_t)?; 9502dbef785SGnoCiYeH 9512dbef785SGnoCiYeH return Ok(0); 9522dbef785SGnoCiYeH } 953971462beSGnoCiYeH 954971462beSGnoCiYeH pub fn writev(fd: i32, iov: usize, count: usize) -> Result<usize, SystemError> { 955971462beSGnoCiYeH // IoVecs会进行用户态检验 956971462beSGnoCiYeH let iovecs = unsafe { IoVecs::from_user(iov as *const IoVec, count, false) }?; 957971462beSGnoCiYeH 958971462beSGnoCiYeH let data = iovecs.gather(); 959971462beSGnoCiYeH 960971462beSGnoCiYeH Self::write(fd, &data) 961971462beSGnoCiYeH } 962709498caSLoGin 963bf4a4899SLoGin pub fn readv(fd: i32, iov: usize, count: usize) -> Result<usize, SystemError> { 964bf4a4899SLoGin // IoVecs会进行用户态检验 965bf4a4899SLoGin let mut iovecs = unsafe { IoVecs::from_user(iov as *const IoVec, count, true) }?; 966bf4a4899SLoGin 967bf4a4899SLoGin let mut data = Vec::new(); 968bf4a4899SLoGin data.resize(iovecs.0.iter().map(|x| x.len()).sum(), 0); 969bf4a4899SLoGin 970bf4a4899SLoGin let len = Self::read(fd, &mut data)?; 971bf4a4899SLoGin 972bf4a4899SLoGin iovecs.scatter(&data[..len]); 973bf4a4899SLoGin 974bf4a4899SLoGin return Ok(len); 975bf4a4899SLoGin } 976bf4a4899SLoGin 977709498caSLoGin pub fn readlink_at( 978709498caSLoGin dirfd: i32, 979709498caSLoGin path: *const u8, 980709498caSLoGin user_buf: *mut u8, 981709498caSLoGin buf_size: usize, 982709498caSLoGin ) -> Result<usize, SystemError> { 9839b0abe6dSLoGin let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?; 984*82df0a13Shmt let path = path.as_str().trim(); 985709498caSLoGin let mut user_buf = UserBufferWriter::new(user_buf, buf_size, true)?; 986709498caSLoGin 9870fb515b0SLoGin let (inode, path) = user_path_at(&ProcessManager::current_pcb(), dirfd, &path)?; 988709498caSLoGin 989709498caSLoGin let inode = inode.lookup(path.as_str())?; 990709498caSLoGin if inode.metadata()?.file_type != FileType::SymLink { 991709498caSLoGin return Err(SystemError::EINVAL); 992709498caSLoGin } 993709498caSLoGin 994709498caSLoGin let ubuf = user_buf.buffer::<u8>(0).unwrap(); 995709498caSLoGin 996709498caSLoGin let mut file = File::new(inode, FileMode::O_RDONLY)?; 997709498caSLoGin 998709498caSLoGin let len = file.read(buf_size, ubuf)?; 999709498caSLoGin 1000709498caSLoGin return Ok(len); 1001709498caSLoGin } 1002709498caSLoGin 1003709498caSLoGin pub fn readlink( 1004709498caSLoGin path: *const u8, 1005709498caSLoGin user_buf: *mut u8, 1006709498caSLoGin buf_size: usize, 1007709498caSLoGin ) -> Result<usize, SystemError> { 10089b0abe6dSLoGin return Self::readlink_at(AtFlags::AT_FDCWD.bits(), path, user_buf, buf_size); 10099b0abe6dSLoGin } 10109b0abe6dSLoGin 10119b0abe6dSLoGin pub fn access(pathname: *const u8, mode: u32) -> Result<usize, SystemError> { 10129b0abe6dSLoGin return do_faccessat( 10139b0abe6dSLoGin AtFlags::AT_FDCWD.bits(), 10149b0abe6dSLoGin pathname, 1015bf4a4899SLoGin ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?, 10169b0abe6dSLoGin 0, 10179b0abe6dSLoGin ); 10189b0abe6dSLoGin } 10199b0abe6dSLoGin 10209b0abe6dSLoGin pub fn faccessat2( 10219b0abe6dSLoGin dirfd: i32, 10229b0abe6dSLoGin pathname: *const u8, 10239b0abe6dSLoGin mode: u32, 10249b0abe6dSLoGin flags: u32, 10259b0abe6dSLoGin ) -> Result<usize, SystemError> { 1026bf4a4899SLoGin return do_faccessat( 1027bf4a4899SLoGin dirfd, 1028bf4a4899SLoGin pathname, 1029bf4a4899SLoGin ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?, 1030bf4a4899SLoGin flags, 1031bf4a4899SLoGin ); 1032bf4a4899SLoGin } 1033bf4a4899SLoGin 1034bf4a4899SLoGin pub fn chmod(pathname: *const u8, mode: u32) -> Result<usize, SystemError> { 1035bf4a4899SLoGin return do_fchmodat( 1036bf4a4899SLoGin AtFlags::AT_FDCWD.bits(), 1037bf4a4899SLoGin pathname, 1038bf4a4899SLoGin ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?, 1039bf4a4899SLoGin ); 1040bf4a4899SLoGin } 1041bf4a4899SLoGin 1042bf4a4899SLoGin pub fn fchmodat(dirfd: i32, pathname: *const u8, mode: u32) -> Result<usize, SystemError> { 1043bf4a4899SLoGin return do_fchmodat( 1044bf4a4899SLoGin dirfd, 1045bf4a4899SLoGin pathname, 1046bf4a4899SLoGin ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?, 1047bf4a4899SLoGin ); 1048bf4a4899SLoGin } 1049bf4a4899SLoGin 1050bf4a4899SLoGin pub fn fchmod(fd: i32, mode: u32) -> Result<usize, SystemError> { 1051bf4a4899SLoGin let _mode = ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?; 1052bf4a4899SLoGin let binding = ProcessManager::current_pcb().fd_table(); 1053bf4a4899SLoGin let fd_table_guard = binding.read(); 1054bf4a4899SLoGin let _file = fd_table_guard 1055bf4a4899SLoGin .get_file_by_fd(fd) 1056bf4a4899SLoGin .ok_or(SystemError::EBADF)?; 1057bf4a4899SLoGin 1058bf4a4899SLoGin // fchmod没完全实现,因此不修改文件的权限 1059bf4a4899SLoGin // todo: 实现fchmod 1060bf4a4899SLoGin kwarn!("fchmod not fully implemented"); 1061bf4a4899SLoGin return Ok(0); 1062709498caSLoGin } 1063709498caSLoGin } 1064709498caSLoGin 1065cde5492fSlogin #[repr(C)] 1066cde5492fSlogin #[derive(Debug, Clone, Copy)] 1067cde5492fSlogin pub struct IoVec { 1068cde5492fSlogin /// 缓冲区的起始地址 1069cde5492fSlogin pub iov_base: *mut u8, 1070cde5492fSlogin /// 缓冲区的长度 1071cde5492fSlogin pub iov_len: usize, 1072cde5492fSlogin } 1073cde5492fSlogin 1074cde5492fSlogin /// 用于存储多个来自用户空间的IoVec 1075cde5492fSlogin /// 1076cde5492fSlogin /// 由于目前内核中的文件系统还不支持分散读写,所以暂时只支持将用户空间的IoVec聚合成一个缓冲区,然后进行操作。 1077cde5492fSlogin /// TODO:支持分散读写 1078cde5492fSlogin #[derive(Debug)] 1079cde5492fSlogin pub struct IoVecs(Vec<&'static mut [u8]>); 1080cde5492fSlogin 1081cde5492fSlogin impl IoVecs { 1082cde5492fSlogin /// 从用户空间的IoVec中构造IoVecs 1083cde5492fSlogin /// 1084cde5492fSlogin /// @param iov 用户空间的IoVec 1085cde5492fSlogin /// @param iovcnt 用户空间的IoVec的数量 1086cde5492fSlogin /// @param readv 是否为readv系统调用 1087cde5492fSlogin /// 1088cde5492fSlogin /// @return 构造成功返回IoVecs,否则返回错误码 1089cde5492fSlogin pub unsafe fn from_user( 1090cde5492fSlogin iov: *const IoVec, 1091cde5492fSlogin iovcnt: usize, 1092cde5492fSlogin _readv: bool, 1093cde5492fSlogin ) -> Result<Self, SystemError> { 1094cde5492fSlogin // 检查iov指针所在空间是否合法 10954fda81ceSLoGin verify_area( 10964fda81ceSLoGin VirtAddr::new(iov as usize), 10974fda81ceSLoGin iovcnt * core::mem::size_of::<IoVec>(), 10984fda81ceSLoGin ) 10994fda81ceSLoGin .map_err(|_| SystemError::EFAULT)?; 1100cde5492fSlogin 1101cde5492fSlogin // 将用户空间的IoVec转换为引用(注意:这里的引用是静态的,因为用户空间的IoVec不会被释放) 1102cde5492fSlogin let iovs: &[IoVec] = core::slice::from_raw_parts(iov, iovcnt); 1103cde5492fSlogin 1104cde5492fSlogin let mut slices: Vec<&mut [u8]> = vec![]; 1105cde5492fSlogin slices.reserve(iovs.len()); 1106cde5492fSlogin 1107cde5492fSlogin for iov in iovs.iter() { 1108cde5492fSlogin if iov.iov_len == 0 { 1109cde5492fSlogin continue; 1110cde5492fSlogin } 1111cde5492fSlogin 11124fda81ceSLoGin verify_area( 11134fda81ceSLoGin VirtAddr::new(iov.iov_base as usize), 11144fda81ceSLoGin iovcnt * core::mem::size_of::<IoVec>(), 11154fda81ceSLoGin ) 11164fda81ceSLoGin .map_err(|_| SystemError::EFAULT)?; 1117cde5492fSlogin 1118cde5492fSlogin slices.push(core::slice::from_raw_parts_mut(iov.iov_base, iov.iov_len)); 1119cde5492fSlogin } 1120cde5492fSlogin 1121cde5492fSlogin return Ok(Self(slices)); 1122cde5492fSlogin } 1123cde5492fSlogin 1124cde5492fSlogin /// @brief 将IoVecs中的数据聚合到一个缓冲区中 1125cde5492fSlogin /// 1126cde5492fSlogin /// @return 返回聚合后的缓冲区 1127cde5492fSlogin pub fn gather(&self) -> Vec<u8> { 1128cde5492fSlogin let mut buf = Vec::new(); 1129cde5492fSlogin for slice in self.0.iter() { 1130cde5492fSlogin buf.extend_from_slice(slice); 1131cde5492fSlogin } 1132cde5492fSlogin return buf; 1133cde5492fSlogin } 1134cde5492fSlogin 1135cde5492fSlogin /// @brief 将给定的数据分散写入到IoVecs中 1136cde5492fSlogin pub fn scatter(&mut self, data: &[u8]) { 1137cde5492fSlogin let mut data: &[u8] = data; 1138cde5492fSlogin for slice in self.0.iter_mut() { 1139cde5492fSlogin let len = core::cmp::min(slice.len(), data.len()); 1140cde5492fSlogin if len == 0 { 1141cde5492fSlogin continue; 1142cde5492fSlogin } 1143cde5492fSlogin 1144cde5492fSlogin slice[..len].copy_from_slice(&data[..len]); 1145cde5492fSlogin data = &data[len..]; 1146cde5492fSlogin } 1147cde5492fSlogin } 1148cde5492fSlogin 1149cde5492fSlogin /// @brief 创建与IoVecs等长的缓冲区 1150cde5492fSlogin /// 1151cde5492fSlogin /// @param set_len 是否设置返回的Vec的len。 1152cde5492fSlogin /// 如果为true,则返回的Vec的len为所有IoVec的长度之和; 1153cde5492fSlogin /// 否则返回的Vec的len为0,capacity为所有IoVec的长度之和. 1154cde5492fSlogin /// 1155cde5492fSlogin /// @return 返回创建的缓冲区 1156cde5492fSlogin pub fn new_buf(&self, set_len: bool) -> Vec<u8> { 1157cde5492fSlogin let total_len: usize = self.0.iter().map(|slice| slice.len()).sum(); 1158cde5492fSlogin let mut buf: Vec<u8> = Vec::with_capacity(total_len); 1159cde5492fSlogin 1160cde5492fSlogin if set_len { 11617ae679ddSLoGin buf.resize(total_len, 0); 1162cde5492fSlogin } 1163cde5492fSlogin return buf; 1164cde5492fSlogin } 1165cde5492fSlogin } 1166