12dbef785SGnoCiYeH use core::ffi::CStr; 22dbef785SGnoCiYeH 31496ba7bSLoGin use alloc::{ 41496ba7bSLoGin string::{String, ToString}, 51496ba7bSLoGin sync::Arc, 61496ba7bSLoGin vec::Vec, 71496ba7bSLoGin }; 891e9d4abSLoGin use system_error::SystemError; 9004e86ffSlogin 10004e86ffSlogin use crate::{ 11*c566df45SLoGin driver::base::{block::SeekFrom, device::device_number::DeviceNumber}, 122b771e32SGou Ngai filesystem::vfs::file::FileDescriptorVec, 132b771e32SGou Ngai kerror, 141496ba7bSLoGin libs::rwlock::RwLockWriteGuard, 154fda81ceSLoGin mm::{verify_area, VirtAddr}, 161496ba7bSLoGin process::ProcessManager, 17709498caSLoGin syscall::{ 18709498caSLoGin user_access::{check_and_clone_cstr, UserBufferReader, UserBufferWriter}, 1991e9d4abSLoGin Syscall, 20709498caSLoGin }, 2167b48188Shoumkh time::TimeSpec, 22004e86ffSlogin }; 23004e86ffSlogin 24004e86ffSlogin use super::{ 25ab5c8ca4Slogin core::{do_mkdir, do_remove_dir, do_unlink_at}, 26709498caSLoGin fcntl::{AtFlags, FcntlCommand, FD_CLOEXEC}, 27004e86ffSlogin file::{File, FileMode}, 280fb515b0SLoGin open::{do_faccessat, do_fchmodat, do_sys_open}, 299b0abe6dSLoGin utils::{rsplit_path, user_path_at}, 30a03c4f9dSLoGin Dirent, FileType, IndexNode, MAX_PATHLEN, ROOT_INODE, VFS_MAX_FOLLOW_SYMLINK_TIMES, 31004e86ffSlogin }; 3240314b30SXiaoye Zheng // use crate::kdebug; 33004e86ffSlogin 34ab5c8ca4Slogin pub const SEEK_SET: u32 = 0; 35ab5c8ca4Slogin pub const SEEK_CUR: u32 = 1; 36ab5c8ca4Slogin pub const SEEK_END: u32 = 2; 37ab5c8ca4Slogin pub const SEEK_MAX: u32 = 3; 38004e86ffSlogin 3967b48188Shoumkh bitflags! { 4067b48188Shoumkh /// 文件类型和权限 416b4e7a29SLoGin #[repr(C)] 4267b48188Shoumkh pub struct ModeType: u32 { 4367b48188Shoumkh /// 掩码 4467b48188Shoumkh const S_IFMT = 0o0_170_000; 4567b48188Shoumkh /// 文件类型 4667b48188Shoumkh const S_IFSOCK = 0o140000; 4767b48188Shoumkh const S_IFLNK = 0o120000; 4867b48188Shoumkh const S_IFREG = 0o100000; 4967b48188Shoumkh const S_IFBLK = 0o060000; 5067b48188Shoumkh const S_IFDIR = 0o040000; 5167b48188Shoumkh const S_IFCHR = 0o020000; 5267b48188Shoumkh const S_IFIFO = 0o010000; 5367b48188Shoumkh 5467b48188Shoumkh const S_ISUID = 0o004000; 5567b48188Shoumkh const S_ISGID = 0o002000; 5667b48188Shoumkh const S_ISVTX = 0o001000; 5767b48188Shoumkh /// 文件用户权限 5867b48188Shoumkh const S_IRWXU = 0o0700; 5967b48188Shoumkh const S_IRUSR = 0o0400; 6067b48188Shoumkh const S_IWUSR = 0o0200; 6167b48188Shoumkh const S_IXUSR = 0o0100; 6267b48188Shoumkh /// 文件组权限 6367b48188Shoumkh const S_IRWXG = 0o0070; 6467b48188Shoumkh const S_IRGRP = 0o0040; 6567b48188Shoumkh const S_IWGRP = 0o0020; 6667b48188Shoumkh const S_IXGRP = 0o0010; 6767b48188Shoumkh /// 文件其他用户权限 6867b48188Shoumkh const S_IRWXO = 0o0007; 6967b48188Shoumkh const S_IROTH = 0o0004; 7067b48188Shoumkh const S_IWOTH = 0o0002; 7167b48188Shoumkh const S_IXOTH = 0o0001; 7206d5e247SLoGin 7306d5e247SLoGin /// 0o777 7406d5e247SLoGin const S_IRWXUGO = Self::S_IRWXU.bits | Self::S_IRWXG.bits | Self::S_IRWXO.bits; 7506d5e247SLoGin /// 0o7777 7606d5e247SLoGin const S_IALLUGO = Self::S_ISUID.bits | Self::S_ISGID.bits | Self::S_ISVTX.bits| Self::S_IRWXUGO.bits; 7706d5e247SLoGin /// 0o444 7806d5e247SLoGin const S_IRUGO = Self::S_IRUSR.bits | Self::S_IRGRP.bits | Self::S_IROTH.bits; 7906d5e247SLoGin /// 0o222 8006d5e247SLoGin const S_IWUGO = Self::S_IWUSR.bits | Self::S_IWGRP.bits | Self::S_IWOTH.bits; 8106d5e247SLoGin /// 0o111 8206d5e247SLoGin const S_IXUGO = Self::S_IXUSR.bits | Self::S_IXGRP.bits | Self::S_IXOTH.bits; 8306d5e247SLoGin 8406d5e247SLoGin 8567b48188Shoumkh } 8667b48188Shoumkh } 8767b48188Shoumkh 8867b48188Shoumkh #[repr(C)] 8967b48188Shoumkh /// # 文件信息结构体 9067b48188Shoumkh pub struct PosixKstat { 9167b48188Shoumkh /// 硬件设备ID 9267b48188Shoumkh dev_id: u64, 9367b48188Shoumkh /// inode号 9467b48188Shoumkh inode: u64, 9567b48188Shoumkh /// 硬链接数 9667b48188Shoumkh nlink: u64, 9767b48188Shoumkh /// 文件权限 9867b48188Shoumkh mode: ModeType, 9967b48188Shoumkh /// 所有者用户ID 10067b48188Shoumkh uid: i32, 10167b48188Shoumkh /// 所有者组ID 10267b48188Shoumkh gid: i32, 10367b48188Shoumkh /// 设备ID 10467b48188Shoumkh rdev: i64, 10567b48188Shoumkh /// 文件大小 10667b48188Shoumkh size: i64, 10767b48188Shoumkh /// 文件系统块大小 10867b48188Shoumkh blcok_size: i64, 10967b48188Shoumkh /// 分配的512B块数 11067b48188Shoumkh blocks: u64, 11167b48188Shoumkh /// 最后访问时间 11267b48188Shoumkh atime: TimeSpec, 11367b48188Shoumkh /// 最后修改时间 11467b48188Shoumkh mtime: TimeSpec, 11567b48188Shoumkh /// 最后状态变化时间 11667b48188Shoumkh ctime: TimeSpec, 11767b48188Shoumkh /// 用于填充结构体大小的空白数据 11867b48188Shoumkh pub _pad: [i8; 24], 11967b48188Shoumkh } 12067b48188Shoumkh impl PosixKstat { 12167b48188Shoumkh fn new() -> Self { 12267b48188Shoumkh Self { 12367b48188Shoumkh inode: 0, 12467b48188Shoumkh dev_id: 0, 12567b48188Shoumkh mode: ModeType { bits: 0 }, 12667b48188Shoumkh nlink: 0, 12767b48188Shoumkh uid: 0, 12867b48188Shoumkh gid: 0, 12967b48188Shoumkh rdev: 0, 13067b48188Shoumkh size: 0, 13167b48188Shoumkh atime: TimeSpec { 13267b48188Shoumkh tv_sec: 0, 13367b48188Shoumkh tv_nsec: 0, 13467b48188Shoumkh }, 13567b48188Shoumkh mtime: TimeSpec { 13667b48188Shoumkh tv_sec: 0, 13767b48188Shoumkh tv_nsec: 0, 13867b48188Shoumkh }, 13967b48188Shoumkh ctime: TimeSpec { 14067b48188Shoumkh tv_sec: 0, 14167b48188Shoumkh tv_nsec: 0, 14267b48188Shoumkh }, 14367b48188Shoumkh blcok_size: 0, 14467b48188Shoumkh blocks: 0, 14567b48188Shoumkh _pad: Default::default(), 14667b48188Shoumkh } 14767b48188Shoumkh } 14867b48188Shoumkh } 1490fb515b0SLoGin 1500fb515b0SLoGin /// 1510fb515b0SLoGin /// Arguments for how openat2(2) should open the target path. If only @flags and 1520fb515b0SLoGin /// @mode are non-zero, then openat2(2) operates very similarly to openat(2). 1530fb515b0SLoGin /// 1540fb515b0SLoGin /// However, unlike openat(2), unknown or invalid bits in @flags result in 1550fb515b0SLoGin /// -EINVAL rather than being silently ignored. @mode must be zero unless one of 1560fb515b0SLoGin /// {O_CREAT, O_TMPFILE} are set. 1570fb515b0SLoGin /// 1580fb515b0SLoGin /// ## 成员变量 1590fb515b0SLoGin /// 1600fb515b0SLoGin /// - flags: O_* flags. 1610fb515b0SLoGin /// - mode: O_CREAT/O_TMPFILE file mode. 1620fb515b0SLoGin /// - resolve: RESOLVE_* flags. 1630fb515b0SLoGin #[derive(Debug, Clone, Copy)] 1640fb515b0SLoGin #[repr(C)] 1650fb515b0SLoGin pub struct PosixOpenHow { 1660fb515b0SLoGin pub flags: u64, 1670fb515b0SLoGin pub mode: u64, 1680fb515b0SLoGin pub resolve: u64, 1690fb515b0SLoGin } 1700fb515b0SLoGin 1710fb515b0SLoGin impl PosixOpenHow { 1720fb515b0SLoGin #[allow(dead_code)] 1730fb515b0SLoGin pub fn new(flags: u64, mode: u64, resolve: u64) -> Self { 1740fb515b0SLoGin Self { 1750fb515b0SLoGin flags, 1760fb515b0SLoGin mode, 1770fb515b0SLoGin resolve, 1780fb515b0SLoGin } 1790fb515b0SLoGin } 1800fb515b0SLoGin } 1810fb515b0SLoGin 1820fb515b0SLoGin #[derive(Debug, Clone, Copy)] 1830fb515b0SLoGin pub struct OpenHow { 1840fb515b0SLoGin pub o_flags: FileMode, 1850fb515b0SLoGin pub mode: ModeType, 1860fb515b0SLoGin pub resolve: OpenHowResolve, 1870fb515b0SLoGin } 1880fb515b0SLoGin 1890fb515b0SLoGin impl OpenHow { 1900fb515b0SLoGin pub fn new(mut o_flags: FileMode, mut mode: ModeType, resolve: OpenHowResolve) -> Self { 1910fb515b0SLoGin if !o_flags.contains(FileMode::O_CREAT) { 1920fb515b0SLoGin mode = ModeType::empty(); 1930fb515b0SLoGin } 1940fb515b0SLoGin 1950fb515b0SLoGin if o_flags.contains(FileMode::O_PATH) { 1960fb515b0SLoGin o_flags = o_flags.intersection(FileMode::O_PATH_FLAGS); 1970fb515b0SLoGin } 1980fb515b0SLoGin 1990fb515b0SLoGin Self { 2000fb515b0SLoGin o_flags, 2010fb515b0SLoGin mode, 2020fb515b0SLoGin resolve, 2030fb515b0SLoGin } 2040fb515b0SLoGin } 2050fb515b0SLoGin } 2060fb515b0SLoGin 2070fb515b0SLoGin impl From<PosixOpenHow> for OpenHow { 2080fb515b0SLoGin fn from(posix_open_how: PosixOpenHow) -> Self { 2090fb515b0SLoGin let o_flags = FileMode::from_bits_truncate(posix_open_how.flags as u32); 2100fb515b0SLoGin let mode = ModeType::from_bits_truncate(posix_open_how.mode as u32); 2110fb515b0SLoGin let resolve = OpenHowResolve::from_bits_truncate(posix_open_how.resolve as u64); 2120fb515b0SLoGin return Self::new(o_flags, mode, resolve); 2130fb515b0SLoGin } 2140fb515b0SLoGin } 2150fb515b0SLoGin 2160fb515b0SLoGin bitflags! { 2170fb515b0SLoGin pub struct OpenHowResolve: u64{ 2180fb515b0SLoGin /// Block mount-point crossings 2190fb515b0SLoGin /// (including bind-mounts). 2200fb515b0SLoGin const RESOLVE_NO_XDEV = 0x01; 2210fb515b0SLoGin 2220fb515b0SLoGin /// Block traversal through procfs-style 2230fb515b0SLoGin /// "magic-links" 2240fb515b0SLoGin const RESOLVE_NO_MAGICLINKS = 0x02; 2250fb515b0SLoGin 2260fb515b0SLoGin /// Block traversal through all symlinks 2270fb515b0SLoGin /// (implies OEXT_NO_MAGICLINKS) 2280fb515b0SLoGin const RESOLVE_NO_SYMLINKS = 0x04; 2290fb515b0SLoGin /// Block "lexical" trickery like 2300fb515b0SLoGin /// "..", symlinks, and absolute 2310fb515b0SLoGin const RESOLVE_BENEATH = 0x08; 2320fb515b0SLoGin /// Make all jumps to "/" and ".." 2330fb515b0SLoGin /// be scoped inside the dirfd 2340fb515b0SLoGin /// (similar to chroot(2)). 2350fb515b0SLoGin const RESOLVE_IN_ROOT = 0x10; 2360fb515b0SLoGin // Only complete if resolution can be 2370fb515b0SLoGin // completed through cached lookup. May 2380fb515b0SLoGin // return -EAGAIN if that's not 2390fb515b0SLoGin // possible. 2400fb515b0SLoGin const RESOLVE_CACHED = 0x20; 2410fb515b0SLoGin } 2420fb515b0SLoGin } 243ab5c8ca4Slogin impl Syscall { 244ab5c8ca4Slogin /// @brief 为当前进程打开一个文件 245ab5c8ca4Slogin /// 246ab5c8ca4Slogin /// @param path 文件路径 247ab5c8ca4Slogin /// @param o_flags 打开文件的标志位 248ab5c8ca4Slogin /// 249ab5c8ca4Slogin /// @return 文件描述符编号,或者是错误码 2500fb515b0SLoGin pub fn open( 2510fb515b0SLoGin path: &str, 2520fb515b0SLoGin flags: FileMode, 2530fb515b0SLoGin mode: ModeType, 2540fb515b0SLoGin follow_symlink: bool, 2550fb515b0SLoGin ) -> Result<usize, SystemError> { 2560fb515b0SLoGin return do_sys_open(AtFlags::AT_FDCWD.bits(), path, flags, mode, follow_symlink); 257ab5c8ca4Slogin } 258ab5c8ca4Slogin 2590fb515b0SLoGin pub fn openat( 2600fb515b0SLoGin dirfd: i32, 2610fb515b0SLoGin path: &str, 2620fb515b0SLoGin o_flags: FileMode, 2630fb515b0SLoGin mode: ModeType, 2640fb515b0SLoGin follow_symlink: bool, 2650fb515b0SLoGin ) -> Result<usize, SystemError> { 2660fb515b0SLoGin return do_sys_open(dirfd, path, o_flags, mode, follow_symlink); 267ab5c8ca4Slogin } 268ab5c8ca4Slogin 269ab5c8ca4Slogin /// @brief 关闭文件 270ab5c8ca4Slogin /// 271ab5c8ca4Slogin /// @param fd 文件描述符编号 272ab5c8ca4Slogin /// 273ab5c8ca4Slogin /// @return 成功返回0,失败返回错误码 274ab5c8ca4Slogin pub fn close(fd: usize) -> Result<usize, SystemError> { 2751496ba7bSLoGin let binding = ProcessManager::current_pcb().fd_table(); 2761496ba7bSLoGin let mut fd_table_guard = binding.write(); 2771496ba7bSLoGin 27834e6d6c8Syuyi2439 let res = fd_table_guard.drop_fd(fd as i32).map(|_| 0); 27934e6d6c8Syuyi2439 28034e6d6c8Syuyi2439 return res; 281ab5c8ca4Slogin } 282ab5c8ca4Slogin 28340314b30SXiaoye Zheng /// @brief 发送命令到文件描述符对应的设备, 28440314b30SXiaoye Zheng /// 28540314b30SXiaoye Zheng /// @param fd 文件描述符编号 28640314b30SXiaoye Zheng /// @param cmd 设备相关的请求类型 28740314b30SXiaoye Zheng /// 28840314b30SXiaoye Zheng /// @return Ok(usize) 成功返回0 28940314b30SXiaoye Zheng /// @return Err(SystemError) 读取失败,返回posix错误码 29040314b30SXiaoye Zheng pub fn ioctl(fd: usize, cmd: u32, data: usize) -> Result<usize, SystemError> { 29140314b30SXiaoye Zheng let binding = ProcessManager::current_pcb().fd_table(); 29240314b30SXiaoye Zheng let fd_table_guard = binding.read(); 29340314b30SXiaoye Zheng 29440314b30SXiaoye Zheng let file = fd_table_guard 29540314b30SXiaoye Zheng .get_file_by_fd(fd as i32) 29640314b30SXiaoye Zheng .ok_or(SystemError::EBADF)?; 29740314b30SXiaoye Zheng 29840314b30SXiaoye Zheng // drop guard 以避免无法调度的问题 29940314b30SXiaoye Zheng drop(fd_table_guard); 30040314b30SXiaoye Zheng let r = file.lock_no_preempt().inode().ioctl(cmd, data); 30140314b30SXiaoye Zheng return r; 30240314b30SXiaoye Zheng } 30340314b30SXiaoye Zheng 304ab5c8ca4Slogin /// @brief 根据文件描述符,读取文件数据。尝试读取的数据长度与buf的长度相同。 305ab5c8ca4Slogin /// 306ab5c8ca4Slogin /// @param fd 文件描述符编号 307ab5c8ca4Slogin /// @param buf 输出缓冲区。 308ab5c8ca4Slogin /// 309ab5c8ca4Slogin /// @return Ok(usize) 成功读取的数据的字节数 310ab5c8ca4Slogin /// @return Err(SystemError) 读取失败,返回posix错误码 311ab5c8ca4Slogin pub fn read(fd: i32, buf: &mut [u8]) -> Result<usize, SystemError> { 3121496ba7bSLoGin let binding = ProcessManager::current_pcb().fd_table(); 3131496ba7bSLoGin let fd_table_guard = binding.read(); 3141496ba7bSLoGin 3151496ba7bSLoGin let file = fd_table_guard.get_file_by_fd(fd); 316ab5c8ca4Slogin if file.is_none() { 317ab5c8ca4Slogin return Err(SystemError::EBADF); 318ab5c8ca4Slogin } 3191496ba7bSLoGin // drop guard 以避免无法调度的问题 3201496ba7bSLoGin drop(fd_table_guard); 3211496ba7bSLoGin let file = file.unwrap(); 322ab5c8ca4Slogin 3231496ba7bSLoGin return file.lock_no_preempt().read(buf.len(), buf); 324ab5c8ca4Slogin } 325ab5c8ca4Slogin 326ab5c8ca4Slogin /// @brief 根据文件描述符,向文件写入数据。尝试写入的数据长度与buf的长度相同。 327ab5c8ca4Slogin /// 328ab5c8ca4Slogin /// @param fd 文件描述符编号 329ab5c8ca4Slogin /// @param buf 输入缓冲区。 330ab5c8ca4Slogin /// 331ab5c8ca4Slogin /// @return Ok(usize) 成功写入的数据的字节数 332ab5c8ca4Slogin /// @return Err(SystemError) 写入失败,返回posix错误码 333ab5c8ca4Slogin pub fn write(fd: i32, buf: &[u8]) -> Result<usize, SystemError> { 3341496ba7bSLoGin let binding = ProcessManager::current_pcb().fd_table(); 3351496ba7bSLoGin let fd_table_guard = binding.read(); 336ab5c8ca4Slogin 3371496ba7bSLoGin let file = fd_table_guard 3381496ba7bSLoGin .get_file_by_fd(fd) 3391496ba7bSLoGin .ok_or(SystemError::EBADF)?; 3401496ba7bSLoGin 3411496ba7bSLoGin // drop guard 以避免无法调度的问题 3421496ba7bSLoGin drop(fd_table_guard); 3431496ba7bSLoGin return file.lock_no_preempt().write(buf.len(), buf); 344ab5c8ca4Slogin } 345ab5c8ca4Slogin 346ab5c8ca4Slogin /// @brief 调整文件操作指针的位置 347ab5c8ca4Slogin /// 348ab5c8ca4Slogin /// @param fd 文件描述符编号 349ab5c8ca4Slogin /// @param seek 调整的方式 350ab5c8ca4Slogin /// 351ab5c8ca4Slogin /// @return Ok(usize) 调整后,文件访问指针相对于文件头部的偏移量 352ab5c8ca4Slogin /// @return Err(SystemError) 调整失败,返回posix错误码 353ab5c8ca4Slogin pub fn lseek(fd: i32, seek: SeekFrom) -> Result<usize, SystemError> { 3541496ba7bSLoGin let binding = ProcessManager::current_pcb().fd_table(); 3551496ba7bSLoGin let fd_table_guard = binding.read(); 3561496ba7bSLoGin let file = fd_table_guard 3571496ba7bSLoGin .get_file_by_fd(fd) 3581496ba7bSLoGin .ok_or(SystemError::EBADF)?; 3591496ba7bSLoGin 3601496ba7bSLoGin // drop guard 以避免无法调度的问题 3611496ba7bSLoGin drop(fd_table_guard); 3621496ba7bSLoGin return file.lock_no_preempt().lseek(seek); 363004e86ffSlogin } 364004e86ffSlogin 365004e86ffSlogin /// @brief 切换工作目录 366004e86ffSlogin /// 367004e86ffSlogin /// @param dest_path 目标路径 368004e86ffSlogin /// 369004e86ffSlogin /// @return 返回码 描述 370004e86ffSlogin /// 0 | 成功 371004e86ffSlogin /// 372004e86ffSlogin /// EACCESS | 权限不足 373004e86ffSlogin /// 374004e86ffSlogin /// ELOOP | 解析path时遇到路径循环 375004e86ffSlogin /// 376004e86ffSlogin /// ENAMETOOLONG | 路径名过长 377004e86ffSlogin /// 378004e86ffSlogin /// ENOENT | 目标文件或目录不存在 379004e86ffSlogin /// 380004e86ffSlogin /// ENODIR | 检索期间发现非目录项 381004e86ffSlogin /// 382004e86ffSlogin /// ENOMEM | 系统内存不足 383004e86ffSlogin /// 384004e86ffSlogin /// EFAULT | 错误的地址 385004e86ffSlogin /// 386004e86ffSlogin /// ENAMETOOLONG | 路径过长 387ab5c8ca4Slogin pub fn chdir(dest_path: &str) -> Result<usize, SystemError> { 3881496ba7bSLoGin let proc = ProcessManager::current_pcb(); 389ab5c8ca4Slogin // Copy path to kernel space to avoid some security issues 3901496ba7bSLoGin let path = dest_path.to_string(); 3911496ba7bSLoGin let mut new_path = String::from(""); 3921496ba7bSLoGin if path.len() > 0 { 3931496ba7bSLoGin let cwd = match path.as_bytes()[0] { 3941496ba7bSLoGin b'/' => String::from("/"), 3951496ba7bSLoGin _ => proc.basic().cwd(), 3961496ba7bSLoGin }; 3971496ba7bSLoGin let mut cwd_vec: Vec<_> = cwd.split("/").filter(|&x| x != "").collect(); 3981496ba7bSLoGin let path_split = path.split("/").filter(|&x| x != ""); 3991496ba7bSLoGin for seg in path_split { 4001496ba7bSLoGin if seg == ".." { 4011496ba7bSLoGin cwd_vec.pop(); 4021496ba7bSLoGin } else if seg == "." { 4031496ba7bSLoGin // 当前目录 4041496ba7bSLoGin } else { 4051496ba7bSLoGin cwd_vec.push(seg); 4061496ba7bSLoGin } 4071496ba7bSLoGin } 4081496ba7bSLoGin //proc.basic().set_path(String::from("")); 4091496ba7bSLoGin for seg in cwd_vec { 4101496ba7bSLoGin new_path.push_str("/"); 4111496ba7bSLoGin new_path.push_str(seg); 4121496ba7bSLoGin } 4131496ba7bSLoGin if new_path == "" { 4141496ba7bSLoGin new_path = String::from("/"); 4151496ba7bSLoGin } 4161496ba7bSLoGin } 417a03c4f9dSLoGin let inode = 418a03c4f9dSLoGin match ROOT_INODE().lookup_follow_symlink(&new_path, VFS_MAX_FOLLOW_SYMLINK_TIMES) { 419004e86ffSlogin Err(e) => { 420676b8ef6SMork kerror!("Change Directory Failed, Error = {:?}", e); 421ab5c8ca4Slogin return Err(SystemError::ENOENT); 422004e86ffSlogin } 423004e86ffSlogin Ok(i) => i, 424004e86ffSlogin }; 4251496ba7bSLoGin let metadata = inode.metadata()?; 4261496ba7bSLoGin if metadata.file_type == FileType::Dir { 4271496ba7bSLoGin proc.basic_mut().set_cwd(String::from(new_path)); 428ab5c8ca4Slogin return Ok(0); 429004e86ffSlogin } else { 430ab5c8ca4Slogin return Err(SystemError::ENOTDIR); 431004e86ffSlogin } 432004e86ffSlogin } 4331496ba7bSLoGin 4341496ba7bSLoGin /// @brief 获取当前进程的工作目录路径 4351496ba7bSLoGin /// 4361496ba7bSLoGin /// @param buf 指向缓冲区的指针 4371496ba7bSLoGin /// @param size 缓冲区的大小 4381496ba7bSLoGin /// 4391496ba7bSLoGin /// @return 成功,返回的指针指向包含工作目录路径的字符串 4401496ba7bSLoGin /// @return 错误,没有足够的空间 4411496ba7bSLoGin pub fn getcwd(buf: &mut [u8]) -> Result<VirtAddr, SystemError> { 4421496ba7bSLoGin let proc = ProcessManager::current_pcb(); 4431496ba7bSLoGin let cwd = proc.basic().cwd(); 4441496ba7bSLoGin 4451496ba7bSLoGin let cwd_bytes = cwd.as_bytes(); 4461496ba7bSLoGin let cwd_len = cwd_bytes.len(); 4471496ba7bSLoGin if cwd_len + 1 > buf.len() { 4481496ba7bSLoGin return Err(SystemError::ENOMEM); 449004e86ffSlogin } 4501496ba7bSLoGin buf[..cwd_len].copy_from_slice(cwd_bytes); 4511496ba7bSLoGin buf[cwd_len] = 0; 4521496ba7bSLoGin 4531496ba7bSLoGin return Ok(VirtAddr::new(buf.as_ptr() as usize)); 454004e86ffSlogin } 455004e86ffSlogin 456004e86ffSlogin /// @brief 获取目录中的数据 457004e86ffSlogin /// 458ab5c8ca4Slogin /// TODO: 这个函数的语义与Linux不一致,需要修改!!! 459ab5c8ca4Slogin /// 460004e86ffSlogin /// @param fd 文件描述符号 461ab5c8ca4Slogin /// @param buf 输出缓冲区 462ab5c8ca4Slogin /// 463ab5c8ca4Slogin /// @return 成功返回读取的字节数,失败返回错误码 464ab5c8ca4Slogin pub fn getdents(fd: i32, buf: &mut [u8]) -> Result<usize, SystemError> { 465ab5c8ca4Slogin let dirent = 466ab5c8ca4Slogin unsafe { (buf.as_mut_ptr() as *mut Dirent).as_mut() }.ok_or(SystemError::EFAULT)?; 467004e86ffSlogin 46846e234aeSLoGin if fd < 0 || fd as usize > FileDescriptorVec::PROCESS_MAX_FD { 469ab5c8ca4Slogin return Err(SystemError::EBADF); 470004e86ffSlogin } 471004e86ffSlogin 472004e86ffSlogin // 获取fd 4731496ba7bSLoGin let binding = ProcessManager::current_pcb().fd_table(); 4741496ba7bSLoGin let fd_table_guard = binding.read(); 4751496ba7bSLoGin let file = fd_table_guard 4761496ba7bSLoGin .get_file_by_fd(fd) 4771496ba7bSLoGin .ok_or(SystemError::EBADF)?; 478004e86ffSlogin 4791496ba7bSLoGin // drop guard 以避免无法调度的问题 4801496ba7bSLoGin drop(fd_table_guard); 48134e6d6c8Syuyi2439 48234e6d6c8Syuyi2439 let res = file.lock_no_preempt().readdir(dirent).map(|x| x as usize); 48334e6d6c8Syuyi2439 48434e6d6c8Syuyi2439 return res; 485004e86ffSlogin } 486004e86ffSlogin 487004e86ffSlogin /// @brief 创建文件夹 488004e86ffSlogin /// 489004e86ffSlogin /// @param path(r8) 路径 / mode(r9) 模式 490004e86ffSlogin /// 491004e86ffSlogin /// @return uint64_t 负数错误码 / 0表示成功 492ab5c8ca4Slogin pub fn mkdir(path: &str, mode: usize) -> Result<usize, SystemError> { 493ab5c8ca4Slogin return do_mkdir(path, FileMode::from_bits_truncate(mode as u32)).map(|x| x as usize); 494004e86ffSlogin } 495004e86ffSlogin 496ab5c8ca4Slogin /// **删除文件夹、取消文件的链接、删除文件的系统调用** 497004e86ffSlogin /// 498ab5c8ca4Slogin /// ## 参数 499004e86ffSlogin /// 500ab5c8ca4Slogin /// - `dirfd`:文件夹的文件描述符.目前暂未实现 501ab5c8ca4Slogin /// - `pathname`:文件夹的路径 502ab5c8ca4Slogin /// - `flags`:标志位 503004e86ffSlogin /// 504004e86ffSlogin /// 505bf4a4899SLoGin pub fn unlinkat(dirfd: i32, pathname: &str, flags: u32) -> Result<usize, SystemError> { 506bf4a4899SLoGin let flags = AtFlags::from_bits(flags as i32).ok_or(SystemError::EINVAL)?; 507004e86ffSlogin 508bf4a4899SLoGin if flags.contains(AtFlags::AT_REMOVEDIR) { 509004e86ffSlogin // kdebug!("rmdir"); 510bf4a4899SLoGin match do_remove_dir(dirfd, &pathname) { 511004e86ffSlogin Err(err) => { 512676b8ef6SMork kerror!("Failed to Remove Directory, Error Code = {:?}", err); 513ab5c8ca4Slogin return Err(err); 514004e86ffSlogin } 515004e86ffSlogin Ok(_) => { 516ab5c8ca4Slogin return Ok(0); 517004e86ffSlogin } 518004e86ffSlogin } 519004e86ffSlogin } 520004e86ffSlogin 521bf4a4899SLoGin match do_unlink_at(dirfd, &pathname) { 522004e86ffSlogin Err(err) => { 523676b8ef6SMork kerror!("Failed to Remove Directory, Error Code = {:?}", err); 524ab5c8ca4Slogin return Err(err); 525004e86ffSlogin } 526004e86ffSlogin Ok(_) => { 527ab5c8ca4Slogin return Ok(0); 528004e86ffSlogin } 529004e86ffSlogin } 530004e86ffSlogin } 5312b771e32SGou Ngai 532bf4a4899SLoGin pub fn unlink(pathname: *const u8) -> Result<usize, SystemError> { 533bf4a4899SLoGin if pathname.is_null() { 534bf4a4899SLoGin return Err(SystemError::EFAULT); 535bf4a4899SLoGin } 536bf4a4899SLoGin let ureader = UserBufferReader::new(pathname, MAX_PATHLEN, true)?; 537bf4a4899SLoGin 538bf4a4899SLoGin let buf: &[u8] = ureader.buffer(0).unwrap(); 539bf4a4899SLoGin 540bf4a4899SLoGin let pathname: &CStr = CStr::from_bytes_until_nul(buf).map_err(|_| SystemError::EINVAL)?; 541bf4a4899SLoGin 542bf4a4899SLoGin let pathname: &str = pathname.to_str().map_err(|_| SystemError::EINVAL)?; 543bf4a4899SLoGin if pathname.len() >= MAX_PATHLEN { 544bf4a4899SLoGin return Err(SystemError::ENAMETOOLONG); 545bf4a4899SLoGin } 546bf4a4899SLoGin let pathname = pathname.trim(); 547bf4a4899SLoGin 548bf4a4899SLoGin return do_unlink_at(AtFlags::AT_FDCWD.bits(), pathname).map(|v| v as usize); 549bf4a4899SLoGin } 550bf4a4899SLoGin 551ab5c8ca4Slogin /// @brief 根据提供的文件描述符的fd,复制对应的文件结构体,并返回新复制的文件结构体对应的fd 552ab5c8ca4Slogin pub fn dup(oldfd: i32) -> Result<usize, SystemError> { 5531496ba7bSLoGin let binding = ProcessManager::current_pcb().fd_table(); 5541496ba7bSLoGin let mut fd_table_guard = binding.write(); 555ab5c8ca4Slogin 5561496ba7bSLoGin let old_file = fd_table_guard 5571496ba7bSLoGin .get_file_by_fd(oldfd) 5581496ba7bSLoGin .ok_or(SystemError::EBADF)?; 5591496ba7bSLoGin 5601496ba7bSLoGin let new_file = old_file 5611496ba7bSLoGin .lock_no_preempt() 5621496ba7bSLoGin .try_clone() 5631496ba7bSLoGin .ok_or(SystemError::EBADF)?; 5642b771e32SGou Ngai // 申请文件描述符,并把文件对象存入其中 5651496ba7bSLoGin let res = fd_table_guard.alloc_fd(new_file, None).map(|x| x as usize); 5662b771e32SGou Ngai return res; 5672b771e32SGou Ngai } 5682b771e32SGou Ngai 569ab5c8ca4Slogin /// 根据提供的文件描述符的fd,和指定新fd,复制对应的文件结构体, 570ab5c8ca4Slogin /// 并返回新复制的文件结构体对应的fd. 571ab5c8ca4Slogin /// 如果新fd已经打开,则会先关闭新fd. 572ab5c8ca4Slogin /// 573ab5c8ca4Slogin /// ## 参数 574ab5c8ca4Slogin /// 575ab5c8ca4Slogin /// - `oldfd`:旧文件描述符 576ab5c8ca4Slogin /// - `newfd`:新文件描述符 577ab5c8ca4Slogin /// 578ab5c8ca4Slogin /// ## 返回值 579ab5c8ca4Slogin /// 580ab5c8ca4Slogin /// - 成功:新文件描述符 581ab5c8ca4Slogin /// - 失败:错误码 582ab5c8ca4Slogin pub fn dup2(oldfd: i32, newfd: i32) -> Result<usize, SystemError> { 5831496ba7bSLoGin let binding = ProcessManager::current_pcb().fd_table(); 5841496ba7bSLoGin let mut fd_table_guard = binding.write(); 5851496ba7bSLoGin return Self::do_dup2(oldfd, newfd, &mut fd_table_guard); 5861496ba7bSLoGin } 5871496ba7bSLoGin 5881496ba7bSLoGin fn do_dup2( 5891496ba7bSLoGin oldfd: i32, 5901496ba7bSLoGin newfd: i32, 5911496ba7bSLoGin fd_table_guard: &mut RwLockWriteGuard<'_, FileDescriptorVec>, 5921496ba7bSLoGin ) -> Result<usize, SystemError> { 5932b771e32SGou Ngai // 确认oldfd, newid是否有效 5941496ba7bSLoGin if !(FileDescriptorVec::validate_fd(oldfd) && FileDescriptorVec::validate_fd(newfd)) { 5951496ba7bSLoGin return Err(SystemError::EBADF); 5961496ba7bSLoGin } 5971496ba7bSLoGin 5982b771e32SGou Ngai if oldfd == newfd { 5992b771e32SGou Ngai // 若oldfd与newfd相等 600ab5c8ca4Slogin return Ok(newfd as usize); 6012b771e32SGou Ngai } 6021496ba7bSLoGin let new_exists = fd_table_guard.get_file_by_fd(newfd).is_some(); 6031496ba7bSLoGin if new_exists { 6042b771e32SGou Ngai // close newfd 6051496ba7bSLoGin if let Err(_) = fd_table_guard.drop_fd(newfd) { 6062b771e32SGou Ngai // An I/O error occurred while attempting to close fildes2. 6072b771e32SGou Ngai return Err(SystemError::EIO); 6082b771e32SGou Ngai } 6092b771e32SGou Ngai } 6102b771e32SGou Ngai 6111496ba7bSLoGin let old_file = fd_table_guard 6121496ba7bSLoGin .get_file_by_fd(oldfd) 6131496ba7bSLoGin .ok_or(SystemError::EBADF)?; 6141496ba7bSLoGin let new_file = old_file 6151496ba7bSLoGin .lock_no_preempt() 6161496ba7bSLoGin .try_clone() 6171496ba7bSLoGin .ok_or(SystemError::EBADF)?; 6182b771e32SGou Ngai // 申请文件描述符,并把文件对象存入其中 6191496ba7bSLoGin let res = fd_table_guard 6201496ba7bSLoGin .alloc_fd(new_file, Some(newfd)) 621ab5c8ca4Slogin .map(|x| x as usize); 6222b771e32SGou Ngai return res; 6232b771e32SGou Ngai } 6246d81180bSLoGin 6256d81180bSLoGin /// # fcntl 6266d81180bSLoGin /// 6276d81180bSLoGin /// ## 参数 6286d81180bSLoGin /// 6296d81180bSLoGin /// - `fd`:文件描述符 6306d81180bSLoGin /// - `cmd`:命令 6316d81180bSLoGin /// - `arg`:参数 6326d81180bSLoGin pub fn fcntl(fd: i32, cmd: FcntlCommand, arg: i32) -> Result<usize, SystemError> { 6336d81180bSLoGin match cmd { 6346d81180bSLoGin FcntlCommand::DupFd => { 6356d81180bSLoGin if arg < 0 || arg as usize >= FileDescriptorVec::PROCESS_MAX_FD { 6366d81180bSLoGin return Err(SystemError::EBADF); 6376d81180bSLoGin } 6386d81180bSLoGin let arg = arg as usize; 6396d81180bSLoGin for i in arg..FileDescriptorVec::PROCESS_MAX_FD { 6401496ba7bSLoGin let binding = ProcessManager::current_pcb().fd_table(); 6411496ba7bSLoGin let mut fd_table_guard = binding.write(); 6421496ba7bSLoGin if fd_table_guard.get_file_by_fd(fd).is_none() { 6431496ba7bSLoGin return Self::do_dup2(fd, i as i32, &mut fd_table_guard); 6446d81180bSLoGin } 6456d81180bSLoGin } 6466d81180bSLoGin return Err(SystemError::EMFILE); 6476d81180bSLoGin } 6486d81180bSLoGin FcntlCommand::GetFd => { 6496d81180bSLoGin // Get file descriptor flags. 6501496ba7bSLoGin let binding = ProcessManager::current_pcb().fd_table(); 6511496ba7bSLoGin let fd_table_guard = binding.read(); 6521496ba7bSLoGin if let Some(file) = fd_table_guard.get_file_by_fd(fd) { 6531496ba7bSLoGin // drop guard 以避免无法调度的问题 6541496ba7bSLoGin drop(fd_table_guard); 6556d81180bSLoGin 6561496ba7bSLoGin if file.lock().close_on_exec() { 6576d81180bSLoGin return Ok(FD_CLOEXEC as usize); 6586d81180bSLoGin } 6596d81180bSLoGin } 6606d81180bSLoGin return Err(SystemError::EBADF); 6616d81180bSLoGin } 6626d81180bSLoGin FcntlCommand::SetFd => { 6636d81180bSLoGin // Set file descriptor flags. 6641496ba7bSLoGin let binding = ProcessManager::current_pcb().fd_table(); 6651496ba7bSLoGin let fd_table_guard = binding.write(); 6661496ba7bSLoGin 6671496ba7bSLoGin if let Some(file) = fd_table_guard.get_file_by_fd(fd) { 6681496ba7bSLoGin // drop guard 以避免无法调度的问题 6691496ba7bSLoGin drop(fd_table_guard); 6706d81180bSLoGin let arg = arg as u32; 6716d81180bSLoGin if arg & FD_CLOEXEC != 0 { 6721496ba7bSLoGin file.lock().set_close_on_exec(true); 6736d81180bSLoGin } else { 6741496ba7bSLoGin file.lock().set_close_on_exec(false); 6756d81180bSLoGin } 6766d81180bSLoGin return Ok(0); 6776d81180bSLoGin } 6786d81180bSLoGin return Err(SystemError::EBADF); 6796d81180bSLoGin } 6806d81180bSLoGin 6816d81180bSLoGin FcntlCommand::GetFlags => { 6826d81180bSLoGin // Get file status flags. 6831496ba7bSLoGin let binding = ProcessManager::current_pcb().fd_table(); 6841496ba7bSLoGin let fd_table_guard = binding.read(); 6851496ba7bSLoGin 6861496ba7bSLoGin if let Some(file) = fd_table_guard.get_file_by_fd(fd) { 6871496ba7bSLoGin // drop guard 以避免无法调度的问题 6881496ba7bSLoGin drop(fd_table_guard); 6891496ba7bSLoGin return Ok(file.lock_no_preempt().mode().bits() as usize); 6906d81180bSLoGin } 6911496ba7bSLoGin 6926d81180bSLoGin return Err(SystemError::EBADF); 6936d81180bSLoGin } 6946d81180bSLoGin FcntlCommand::SetFlags => { 6956d81180bSLoGin // Set file status flags. 6961496ba7bSLoGin let binding = ProcessManager::current_pcb().fd_table(); 6971496ba7bSLoGin let fd_table_guard = binding.write(); 6981496ba7bSLoGin 6991496ba7bSLoGin if let Some(file) = fd_table_guard.get_file_by_fd(fd) { 7006d81180bSLoGin let arg = arg as u32; 7016d81180bSLoGin let mode = FileMode::from_bits(arg).ok_or(SystemError::EINVAL)?; 7021496ba7bSLoGin // drop guard 以避免无法调度的问题 7031496ba7bSLoGin drop(fd_table_guard); 7041496ba7bSLoGin file.lock_no_preempt().set_mode(mode)?; 7056d81180bSLoGin return Ok(0); 7066d81180bSLoGin } 7071496ba7bSLoGin 7086d81180bSLoGin return Err(SystemError::EBADF); 7096d81180bSLoGin } 7106d81180bSLoGin _ => { 7116d81180bSLoGin // TODO: unimplemented 7126d81180bSLoGin // 未实现的命令,返回0,不报错。 7136d81180bSLoGin 7146d81180bSLoGin // kwarn!("fcntl: unimplemented command: {:?}, defaults to 0.", cmd); 7156d81180bSLoGin return Ok(0); 7166d81180bSLoGin } 7176d81180bSLoGin } 7186d81180bSLoGin } 7196d81180bSLoGin 7206d81180bSLoGin /// # ftruncate 7216d81180bSLoGin /// 7226d81180bSLoGin /// ## 描述 7236d81180bSLoGin /// 7246d81180bSLoGin /// 改变文件大小. 7256d81180bSLoGin /// 如果文件大小大于原来的大小,那么文件的内容将会被扩展到指定的大小,新的空间将会用0填充. 7266d81180bSLoGin /// 如果文件大小小于原来的大小,那么文件的内容将会被截断到指定的大小. 7276d81180bSLoGin /// 7286d81180bSLoGin /// ## 参数 7296d81180bSLoGin /// 7306d81180bSLoGin /// - `fd`:文件描述符 7316d81180bSLoGin /// - `len`:文件大小 7326d81180bSLoGin /// 7336d81180bSLoGin /// ## 返回值 7346d81180bSLoGin /// 7356d81180bSLoGin /// 如果成功,返回0,否则返回错误码. 7366d81180bSLoGin pub fn ftruncate(fd: i32, len: usize) -> Result<usize, SystemError> { 7371496ba7bSLoGin let binding = ProcessManager::current_pcb().fd_table(); 7381496ba7bSLoGin let fd_table_guard = binding.read(); 7391496ba7bSLoGin 7401496ba7bSLoGin if let Some(file) = fd_table_guard.get_file_by_fd(fd) { 7411496ba7bSLoGin // drop guard 以避免无法调度的问题 7421496ba7bSLoGin drop(fd_table_guard); 7431496ba7bSLoGin let r = file.lock_no_preempt().ftruncate(len).map(|_| 0); 7446d81180bSLoGin return r; 7456d81180bSLoGin } 7461496ba7bSLoGin 7476d81180bSLoGin return Err(SystemError::EBADF); 7486d81180bSLoGin } 7491496ba7bSLoGin 75067b48188Shoumkh fn do_fstat(fd: i32) -> Result<PosixKstat, SystemError> { 7511496ba7bSLoGin let binding = ProcessManager::current_pcb().fd_table(); 7521496ba7bSLoGin let fd_table_guard = binding.read(); 7531496ba7bSLoGin let file = fd_table_guard 7541496ba7bSLoGin .get_file_by_fd(fd) 7551496ba7bSLoGin .ok_or(SystemError::EBADF)?; 7561496ba7bSLoGin // drop guard 以避免无法调度的问题 7571496ba7bSLoGin drop(fd_table_guard); 7581496ba7bSLoGin 75967b48188Shoumkh let mut kstat = PosixKstat::new(); 76067b48188Shoumkh // 获取文件信息 7611496ba7bSLoGin let metadata = file.lock().metadata()?; 76267b48188Shoumkh kstat.size = metadata.size as i64; 76367b48188Shoumkh kstat.dev_id = metadata.dev_id as u64; 7646b4e7a29SLoGin kstat.inode = metadata.inode_id.into() as u64; 76567b48188Shoumkh kstat.blcok_size = metadata.blk_size as i64; 76667b48188Shoumkh kstat.blocks = metadata.blocks as u64; 76767b48188Shoumkh 76867b48188Shoumkh kstat.atime.tv_sec = metadata.atime.tv_sec; 76967b48188Shoumkh kstat.atime.tv_nsec = metadata.atime.tv_nsec; 77067b48188Shoumkh kstat.mtime.tv_sec = metadata.mtime.tv_sec; 77167b48188Shoumkh kstat.mtime.tv_nsec = metadata.mtime.tv_nsec; 77267b48188Shoumkh kstat.ctime.tv_sec = metadata.ctime.tv_sec; 77367b48188Shoumkh kstat.ctime.tv_nsec = metadata.ctime.tv_nsec; 77467b48188Shoumkh 77567b48188Shoumkh kstat.nlink = metadata.nlinks as u64; 77667b48188Shoumkh kstat.uid = metadata.uid as i32; 77767b48188Shoumkh kstat.gid = metadata.gid as i32; 77867b48188Shoumkh kstat.rdev = metadata.raw_dev as i64; 7796b4e7a29SLoGin kstat.mode = metadata.mode; 7801496ba7bSLoGin match file.lock().file_type() { 7817eda31b2SLoGin FileType::File => kstat.mode.insert(ModeType::S_IFREG), 78267b48188Shoumkh FileType::Dir => kstat.mode.insert(ModeType::S_IFDIR), 78367b48188Shoumkh FileType::BlockDevice => kstat.mode.insert(ModeType::S_IFBLK), 78467b48188Shoumkh FileType::CharDevice => kstat.mode.insert(ModeType::S_IFCHR), 78567b48188Shoumkh FileType::SymLink => kstat.mode.insert(ModeType::S_IFLNK), 78667b48188Shoumkh FileType::Socket => kstat.mode.insert(ModeType::S_IFSOCK), 78767b48188Shoumkh FileType::Pipe => kstat.mode.insert(ModeType::S_IFIFO), 78840314b30SXiaoye Zheng FileType::KvmDevice => kstat.mode.insert(ModeType::S_IFCHR), 78967b48188Shoumkh } 79067b48188Shoumkh 79167b48188Shoumkh return Ok(kstat); 79267b48188Shoumkh } 7931496ba7bSLoGin 79467b48188Shoumkh pub fn fstat(fd: i32, usr_kstat: *mut PosixKstat) -> Result<usize, SystemError> { 7951496ba7bSLoGin let kstat = Self::do_fstat(fd)?; 79667b48188Shoumkh if usr_kstat.is_null() { 79767b48188Shoumkh return Err(SystemError::EFAULT); 79867b48188Shoumkh } 79967b48188Shoumkh unsafe { 80067b48188Shoumkh *usr_kstat = kstat; 80167b48188Shoumkh } 80267b48188Shoumkh return Ok(0); 80367b48188Shoumkh } 8042dbef785SGnoCiYeH 805971462beSGnoCiYeH pub fn stat(path: &str, user_kstat: *mut PosixKstat) -> Result<usize, SystemError> { 8060fb515b0SLoGin let fd = Self::open(path, FileMode::O_RDONLY, ModeType::empty(), true)?; 807bf4a4899SLoGin let r = Self::fstat(fd as i32, user_kstat); 808971462beSGnoCiYeH Self::close(fd).ok(); 809bf4a4899SLoGin return r; 810bf4a4899SLoGin } 811bf4a4899SLoGin 812bf4a4899SLoGin pub fn lstat(path: &str, user_kstat: *mut PosixKstat) -> Result<usize, SystemError> { 8130fb515b0SLoGin let fd = Self::open(path, FileMode::O_RDONLY, ModeType::empty(), false)?; 814bf4a4899SLoGin let r = Self::fstat(fd as i32, user_kstat); 815bf4a4899SLoGin Self::close(fd).ok(); 816bf4a4899SLoGin return r; 817971462beSGnoCiYeH } 818971462beSGnoCiYeH 8192dbef785SGnoCiYeH pub fn mknod( 8202dbef785SGnoCiYeH path_ptr: *const i8, 8212dbef785SGnoCiYeH mode: ModeType, 8222dbef785SGnoCiYeH dev_t: DeviceNumber, 8232dbef785SGnoCiYeH ) -> Result<usize, SystemError> { 8242dbef785SGnoCiYeH // 安全检验 8252dbef785SGnoCiYeH let len = unsafe { CStr::from_ptr(path_ptr).to_bytes().len() }; 8262dbef785SGnoCiYeH let user_buffer = UserBufferReader::new(path_ptr, len, true)?; 8272dbef785SGnoCiYeH let buf = user_buffer.read_from_user::<u8>(0)?; 8282dbef785SGnoCiYeH let path = core::str::from_utf8(buf).map_err(|_| SystemError::EINVAL)?; 8292dbef785SGnoCiYeH 8302dbef785SGnoCiYeH // 文件名过长 8312dbef785SGnoCiYeH if path.len() > MAX_PATHLEN as usize { 8322dbef785SGnoCiYeH return Err(SystemError::ENAMETOOLONG); 8332dbef785SGnoCiYeH } 8342dbef785SGnoCiYeH 835a03c4f9dSLoGin let inode: Result<Arc<dyn IndexNode>, SystemError> = 836a03c4f9dSLoGin ROOT_INODE().lookup_follow_symlink(path, VFS_MAX_FOLLOW_SYMLINK_TIMES); 8372dbef785SGnoCiYeH 8382dbef785SGnoCiYeH if inode.is_ok() { 8392dbef785SGnoCiYeH return Err(SystemError::EEXIST); 8402dbef785SGnoCiYeH } 8412dbef785SGnoCiYeH 8422dbef785SGnoCiYeH let (filename, parent_path) = rsplit_path(path); 8432dbef785SGnoCiYeH 8442dbef785SGnoCiYeH // 查找父目录 845a03c4f9dSLoGin let parent_inode: Arc<dyn IndexNode> = ROOT_INODE() 846a03c4f9dSLoGin .lookup_follow_symlink(parent_path.unwrap_or("/"), VFS_MAX_FOLLOW_SYMLINK_TIMES)?; 8472dbef785SGnoCiYeH // 创建nod 8482dbef785SGnoCiYeH parent_inode.mknod(filename, mode, dev_t)?; 8492dbef785SGnoCiYeH 8502dbef785SGnoCiYeH return Ok(0); 8512dbef785SGnoCiYeH } 852971462beSGnoCiYeH 853971462beSGnoCiYeH pub fn writev(fd: i32, iov: usize, count: usize) -> Result<usize, SystemError> { 854971462beSGnoCiYeH // IoVecs会进行用户态检验 855971462beSGnoCiYeH let iovecs = unsafe { IoVecs::from_user(iov as *const IoVec, count, false) }?; 856971462beSGnoCiYeH 857971462beSGnoCiYeH let data = iovecs.gather(); 858971462beSGnoCiYeH 859971462beSGnoCiYeH Self::write(fd, &data) 860971462beSGnoCiYeH } 861709498caSLoGin 862bf4a4899SLoGin pub fn readv(fd: i32, iov: usize, count: usize) -> Result<usize, SystemError> { 863bf4a4899SLoGin // IoVecs会进行用户态检验 864bf4a4899SLoGin let mut iovecs = unsafe { IoVecs::from_user(iov as *const IoVec, count, true) }?; 865bf4a4899SLoGin 866bf4a4899SLoGin let mut data = Vec::new(); 867bf4a4899SLoGin data.resize(iovecs.0.iter().map(|x| x.len()).sum(), 0); 868bf4a4899SLoGin 869bf4a4899SLoGin let len = Self::read(fd, &mut data)?; 870bf4a4899SLoGin 871bf4a4899SLoGin iovecs.scatter(&data[..len]); 872bf4a4899SLoGin 873bf4a4899SLoGin return Ok(len); 874bf4a4899SLoGin } 875bf4a4899SLoGin 876709498caSLoGin pub fn readlink_at( 877709498caSLoGin dirfd: i32, 878709498caSLoGin path: *const u8, 879709498caSLoGin user_buf: *mut u8, 880709498caSLoGin buf_size: usize, 881709498caSLoGin ) -> Result<usize, SystemError> { 8829b0abe6dSLoGin let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?; 883709498caSLoGin let mut user_buf = UserBufferWriter::new(user_buf, buf_size, true)?; 884709498caSLoGin 885709498caSLoGin if path.len() == 0 { 886709498caSLoGin return Err(SystemError::EINVAL); 88767b48188Shoumkh } 888709498caSLoGin 8890fb515b0SLoGin let (inode, path) = user_path_at(&ProcessManager::current_pcb(), dirfd, &path)?; 890709498caSLoGin 891709498caSLoGin let inode = inode.lookup(path.as_str())?; 892709498caSLoGin if inode.metadata()?.file_type != FileType::SymLink { 893709498caSLoGin return Err(SystemError::EINVAL); 894709498caSLoGin } 895709498caSLoGin 896709498caSLoGin let ubuf = user_buf.buffer::<u8>(0).unwrap(); 897709498caSLoGin 898709498caSLoGin let mut file = File::new(inode, FileMode::O_RDONLY)?; 899709498caSLoGin 900709498caSLoGin let len = file.read(buf_size, ubuf)?; 901709498caSLoGin 902709498caSLoGin return Ok(len); 903709498caSLoGin } 904709498caSLoGin 905709498caSLoGin pub fn readlink( 906709498caSLoGin path: *const u8, 907709498caSLoGin user_buf: *mut u8, 908709498caSLoGin buf_size: usize, 909709498caSLoGin ) -> Result<usize, SystemError> { 9109b0abe6dSLoGin return Self::readlink_at(AtFlags::AT_FDCWD.bits(), path, user_buf, buf_size); 9119b0abe6dSLoGin } 9129b0abe6dSLoGin 9139b0abe6dSLoGin pub fn access(pathname: *const u8, mode: u32) -> Result<usize, SystemError> { 9149b0abe6dSLoGin return do_faccessat( 9159b0abe6dSLoGin AtFlags::AT_FDCWD.bits(), 9169b0abe6dSLoGin pathname, 917bf4a4899SLoGin ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?, 9189b0abe6dSLoGin 0, 9199b0abe6dSLoGin ); 9209b0abe6dSLoGin } 9219b0abe6dSLoGin 9229b0abe6dSLoGin pub fn faccessat2( 9239b0abe6dSLoGin dirfd: i32, 9249b0abe6dSLoGin pathname: *const u8, 9259b0abe6dSLoGin mode: u32, 9269b0abe6dSLoGin flags: u32, 9279b0abe6dSLoGin ) -> Result<usize, SystemError> { 928bf4a4899SLoGin return do_faccessat( 929bf4a4899SLoGin dirfd, 930bf4a4899SLoGin pathname, 931bf4a4899SLoGin ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?, 932bf4a4899SLoGin flags, 933bf4a4899SLoGin ); 934bf4a4899SLoGin } 935bf4a4899SLoGin 936bf4a4899SLoGin pub fn chmod(pathname: *const u8, mode: u32) -> Result<usize, SystemError> { 937bf4a4899SLoGin return do_fchmodat( 938bf4a4899SLoGin AtFlags::AT_FDCWD.bits(), 939bf4a4899SLoGin pathname, 940bf4a4899SLoGin ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?, 941bf4a4899SLoGin ); 942bf4a4899SLoGin } 943bf4a4899SLoGin 944bf4a4899SLoGin pub fn fchmodat(dirfd: i32, pathname: *const u8, mode: u32) -> Result<usize, SystemError> { 945bf4a4899SLoGin return do_fchmodat( 946bf4a4899SLoGin dirfd, 947bf4a4899SLoGin pathname, 948bf4a4899SLoGin ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?, 949bf4a4899SLoGin ); 950bf4a4899SLoGin } 951bf4a4899SLoGin 952bf4a4899SLoGin pub fn fchmod(fd: i32, mode: u32) -> Result<usize, SystemError> { 953bf4a4899SLoGin let _mode = ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?; 954bf4a4899SLoGin let binding = ProcessManager::current_pcb().fd_table(); 955bf4a4899SLoGin let fd_table_guard = binding.read(); 956bf4a4899SLoGin let _file = fd_table_guard 957bf4a4899SLoGin .get_file_by_fd(fd) 958bf4a4899SLoGin .ok_or(SystemError::EBADF)?; 959bf4a4899SLoGin 960bf4a4899SLoGin // fchmod没完全实现,因此不修改文件的权限 961bf4a4899SLoGin // todo: 实现fchmod 962bf4a4899SLoGin kwarn!("fchmod not fully implemented"); 963bf4a4899SLoGin return Ok(0); 964709498caSLoGin } 965709498caSLoGin } 966709498caSLoGin 967cde5492fSlogin #[repr(C)] 968cde5492fSlogin #[derive(Debug, Clone, Copy)] 969cde5492fSlogin pub struct IoVec { 970cde5492fSlogin /// 缓冲区的起始地址 971cde5492fSlogin pub iov_base: *mut u8, 972cde5492fSlogin /// 缓冲区的长度 973cde5492fSlogin pub iov_len: usize, 974cde5492fSlogin } 975cde5492fSlogin 976cde5492fSlogin /// 用于存储多个来自用户空间的IoVec 977cde5492fSlogin /// 978cde5492fSlogin /// 由于目前内核中的文件系统还不支持分散读写,所以暂时只支持将用户空间的IoVec聚合成一个缓冲区,然后进行操作。 979cde5492fSlogin /// TODO:支持分散读写 980cde5492fSlogin #[derive(Debug)] 981cde5492fSlogin pub struct IoVecs(Vec<&'static mut [u8]>); 982cde5492fSlogin 983cde5492fSlogin impl IoVecs { 984cde5492fSlogin /// 从用户空间的IoVec中构造IoVecs 985cde5492fSlogin /// 986cde5492fSlogin /// @param iov 用户空间的IoVec 987cde5492fSlogin /// @param iovcnt 用户空间的IoVec的数量 988cde5492fSlogin /// @param readv 是否为readv系统调用 989cde5492fSlogin /// 990cde5492fSlogin /// @return 构造成功返回IoVecs,否则返回错误码 991cde5492fSlogin pub unsafe fn from_user( 992cde5492fSlogin iov: *const IoVec, 993cde5492fSlogin iovcnt: usize, 994cde5492fSlogin _readv: bool, 995cde5492fSlogin ) -> Result<Self, SystemError> { 996cde5492fSlogin // 检查iov指针所在空间是否合法 9974fda81ceSLoGin verify_area( 9984fda81ceSLoGin VirtAddr::new(iov as usize), 9994fda81ceSLoGin iovcnt * core::mem::size_of::<IoVec>(), 10004fda81ceSLoGin ) 10014fda81ceSLoGin .map_err(|_| SystemError::EFAULT)?; 1002cde5492fSlogin 1003cde5492fSlogin // 将用户空间的IoVec转换为引用(注意:这里的引用是静态的,因为用户空间的IoVec不会被释放) 1004cde5492fSlogin let iovs: &[IoVec] = core::slice::from_raw_parts(iov, iovcnt); 1005cde5492fSlogin 1006cde5492fSlogin let mut slices: Vec<&mut [u8]> = vec![]; 1007cde5492fSlogin slices.reserve(iovs.len()); 1008cde5492fSlogin 1009cde5492fSlogin for iov in iovs.iter() { 1010cde5492fSlogin if iov.iov_len == 0 { 1011cde5492fSlogin continue; 1012cde5492fSlogin } 1013cde5492fSlogin 10144fda81ceSLoGin verify_area( 10154fda81ceSLoGin VirtAddr::new(iov.iov_base as usize), 10164fda81ceSLoGin iovcnt * core::mem::size_of::<IoVec>(), 10174fda81ceSLoGin ) 10184fda81ceSLoGin .map_err(|_| SystemError::EFAULT)?; 1019cde5492fSlogin 1020cde5492fSlogin slices.push(core::slice::from_raw_parts_mut(iov.iov_base, iov.iov_len)); 1021cde5492fSlogin } 1022cde5492fSlogin 1023cde5492fSlogin return Ok(Self(slices)); 1024cde5492fSlogin } 1025cde5492fSlogin 1026cde5492fSlogin /// @brief 将IoVecs中的数据聚合到一个缓冲区中 1027cde5492fSlogin /// 1028cde5492fSlogin /// @return 返回聚合后的缓冲区 1029cde5492fSlogin pub fn gather(&self) -> Vec<u8> { 1030cde5492fSlogin let mut buf = Vec::new(); 1031cde5492fSlogin for slice in self.0.iter() { 1032cde5492fSlogin buf.extend_from_slice(slice); 1033cde5492fSlogin } 1034cde5492fSlogin return buf; 1035cde5492fSlogin } 1036cde5492fSlogin 1037cde5492fSlogin /// @brief 将给定的数据分散写入到IoVecs中 1038cde5492fSlogin pub fn scatter(&mut self, data: &[u8]) { 1039cde5492fSlogin let mut data: &[u8] = data; 1040cde5492fSlogin for slice in self.0.iter_mut() { 1041cde5492fSlogin let len = core::cmp::min(slice.len(), data.len()); 1042cde5492fSlogin if len == 0 { 1043cde5492fSlogin continue; 1044cde5492fSlogin } 1045cde5492fSlogin 1046cde5492fSlogin slice[..len].copy_from_slice(&data[..len]); 1047cde5492fSlogin data = &data[len..]; 1048cde5492fSlogin } 1049cde5492fSlogin } 1050cde5492fSlogin 1051cde5492fSlogin /// @brief 创建与IoVecs等长的缓冲区 1052cde5492fSlogin /// 1053cde5492fSlogin /// @param set_len 是否设置返回的Vec的len。 1054cde5492fSlogin /// 如果为true,则返回的Vec的len为所有IoVec的长度之和; 1055cde5492fSlogin /// 否则返回的Vec的len为0,capacity为所有IoVec的长度之和. 1056cde5492fSlogin /// 1057cde5492fSlogin /// @return 返回创建的缓冲区 1058cde5492fSlogin pub fn new_buf(&self, set_len: bool) -> Vec<u8> { 1059cde5492fSlogin let total_len: usize = self.0.iter().map(|slice| slice.len()).sum(); 1060cde5492fSlogin let mut buf: Vec<u8> = Vec::with_capacity(total_len); 1061cde5492fSlogin 1062cde5492fSlogin if set_len { 10637ae679ddSLoGin buf.resize(total_len, 0); 1064cde5492fSlogin } 1065cde5492fSlogin return buf; 1066cde5492fSlogin } 1067cde5492fSlogin } 1068