12dbef785SGnoCiYeH use core::ffi::CStr; 22dbef785SGnoCiYeH 31496ba7bSLoGin use alloc::{ 41496ba7bSLoGin string::{String, ToString}, 51496ba7bSLoGin sync::Arc, 61496ba7bSLoGin vec::Vec, 71496ba7bSLoGin }; 8004e86ffSlogin 9004e86ffSlogin use crate::{ 102dbef785SGnoCiYeH driver::base::{block::SeekFrom, device::DeviceNumber}, 112b771e32SGou Ngai filesystem::vfs::file::FileDescriptorVec, 122dbef785SGnoCiYeH include::bindings::bindings::{verify_area, AT_REMOVEDIR, PROC_MAX_FD_NUM}, 132b771e32SGou Ngai kerror, 141496ba7bSLoGin libs::rwlock::RwLockWriteGuard, 151496ba7bSLoGin mm::VirtAddr, 161496ba7bSLoGin process::ProcessManager, 172dbef785SGnoCiYeH syscall::{user_access::UserBufferReader, Syscall, SystemError}, 1867b48188Shoumkh time::TimeSpec, 19004e86ffSlogin }; 20004e86ffSlogin 21004e86ffSlogin use super::{ 22ab5c8ca4Slogin core::{do_mkdir, do_remove_dir, do_unlink_at}, 236d81180bSLoGin fcntl::{FcntlCommand, FD_CLOEXEC}, 24004e86ffSlogin file::{File, FileMode}, 25ab5c8ca4Slogin utils::rsplit_path, 26a03c4f9dSLoGin Dirent, FileType, IndexNode, MAX_PATHLEN, ROOT_INODE, VFS_MAX_FOLLOW_SYMLINK_TIMES, 27004e86ffSlogin }; 2840314b30SXiaoye Zheng // use crate::kdebug; 29004e86ffSlogin 30ab5c8ca4Slogin pub const SEEK_SET: u32 = 0; 31ab5c8ca4Slogin pub const SEEK_CUR: u32 = 1; 32ab5c8ca4Slogin pub const SEEK_END: u32 = 2; 33ab5c8ca4Slogin pub const SEEK_MAX: u32 = 3; 34004e86ffSlogin 3567b48188Shoumkh bitflags! { 3667b48188Shoumkh /// 文件类型和权限 376b4e7a29SLoGin #[repr(C)] 3867b48188Shoumkh pub struct ModeType: u32 { 3967b48188Shoumkh /// 掩码 4067b48188Shoumkh const S_IFMT = 0o0_170_000; 4167b48188Shoumkh /// 文件类型 4267b48188Shoumkh const S_IFSOCK = 0o140000; 4367b48188Shoumkh const S_IFLNK = 0o120000; 4467b48188Shoumkh const S_IFREG = 0o100000; 4567b48188Shoumkh const S_IFBLK = 0o060000; 4667b48188Shoumkh const S_IFDIR = 0o040000; 4767b48188Shoumkh const S_IFCHR = 0o020000; 4867b48188Shoumkh const S_IFIFO = 0o010000; 4967b48188Shoumkh 5067b48188Shoumkh const S_ISUID = 0o004000; 5167b48188Shoumkh const S_ISGID = 0o002000; 5267b48188Shoumkh const S_ISVTX = 0o001000; 5367b48188Shoumkh /// 文件用户权限 5467b48188Shoumkh const S_IRWXU = 0o0700; 5567b48188Shoumkh const S_IRUSR = 0o0400; 5667b48188Shoumkh const S_IWUSR = 0o0200; 5767b48188Shoumkh const S_IXUSR = 0o0100; 5867b48188Shoumkh /// 文件组权限 5967b48188Shoumkh const S_IRWXG = 0o0070; 6067b48188Shoumkh const S_IRGRP = 0o0040; 6167b48188Shoumkh const S_IWGRP = 0o0020; 6267b48188Shoumkh const S_IXGRP = 0o0010; 6367b48188Shoumkh /// 文件其他用户权限 6467b48188Shoumkh const S_IRWXO = 0o0007; 6567b48188Shoumkh const S_IROTH = 0o0004; 6667b48188Shoumkh const S_IWOTH = 0o0002; 6767b48188Shoumkh const S_IXOTH = 0o0001; 6806d5e247SLoGin 6906d5e247SLoGin /// 0o777 7006d5e247SLoGin const S_IRWXUGO = Self::S_IRWXU.bits | Self::S_IRWXG.bits | Self::S_IRWXO.bits; 7106d5e247SLoGin /// 0o7777 7206d5e247SLoGin const S_IALLUGO = Self::S_ISUID.bits | Self::S_ISGID.bits | Self::S_ISVTX.bits| Self::S_IRWXUGO.bits; 7306d5e247SLoGin /// 0o444 7406d5e247SLoGin const S_IRUGO = Self::S_IRUSR.bits | Self::S_IRGRP.bits | Self::S_IROTH.bits; 7506d5e247SLoGin /// 0o222 7606d5e247SLoGin const S_IWUGO = Self::S_IWUSR.bits | Self::S_IWGRP.bits | Self::S_IWOTH.bits; 7706d5e247SLoGin /// 0o111 7806d5e247SLoGin const S_IXUGO = Self::S_IXUSR.bits | Self::S_IXGRP.bits | Self::S_IXOTH.bits; 7906d5e247SLoGin 8006d5e247SLoGin 8167b48188Shoumkh } 8267b48188Shoumkh } 8367b48188Shoumkh 8467b48188Shoumkh #[repr(C)] 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 } 145ab5c8ca4Slogin impl Syscall { 146ab5c8ca4Slogin /// @brief 为当前进程打开一个文件 147ab5c8ca4Slogin /// 148ab5c8ca4Slogin /// @param path 文件路径 149ab5c8ca4Slogin /// @param o_flags 打开文件的标志位 150ab5c8ca4Slogin /// 151ab5c8ca4Slogin /// @return 文件描述符编号,或者是错误码 152ab5c8ca4Slogin pub fn open(path: &str, mode: FileMode) -> Result<usize, SystemError> { 1536d81180bSLoGin // kdebug!("open: path: {}, mode: {:?}", path, mode); 154ab5c8ca4Slogin // 文件名过长 1552dbef785SGnoCiYeH if path.len() > MAX_PATHLEN as usize { 156ab5c8ca4Slogin return Err(SystemError::ENAMETOOLONG); 157ab5c8ca4Slogin } 158ab5c8ca4Slogin 159a03c4f9dSLoGin let inode: Result<Arc<dyn IndexNode>, SystemError> = 160a03c4f9dSLoGin ROOT_INODE().lookup_follow_symlink(path, VFS_MAX_FOLLOW_SYMLINK_TIMES); 161ab5c8ca4Slogin 162ab5c8ca4Slogin let inode: Arc<dyn IndexNode> = if inode.is_err() { 163ab5c8ca4Slogin let errno = inode.unwrap_err(); 164ab5c8ca4Slogin // 文件不存在,且需要创建 165ab5c8ca4Slogin if mode.contains(FileMode::O_CREAT) 166ab5c8ca4Slogin && !mode.contains(FileMode::O_DIRECTORY) 167ab5c8ca4Slogin && errno == SystemError::ENOENT 168ab5c8ca4Slogin { 169ab5c8ca4Slogin let (filename, parent_path) = rsplit_path(path); 170ab5c8ca4Slogin // 查找父目录 171ab5c8ca4Slogin let parent_inode: Arc<dyn IndexNode> = 172ab5c8ca4Slogin ROOT_INODE().lookup(parent_path.unwrap_or("/"))?; 173ab5c8ca4Slogin // 创建文件 1746b4e7a29SLoGin let inode: Arc<dyn IndexNode> = parent_inode.create( 1756b4e7a29SLoGin filename, 1766b4e7a29SLoGin FileType::File, 1776b4e7a29SLoGin ModeType::from_bits_truncate(0o755), 1786b4e7a29SLoGin )?; 179ab5c8ca4Slogin inode 180004e86ffSlogin } else { 181ab5c8ca4Slogin // 不需要创建文件,因此返回错误码 182ab5c8ca4Slogin return Err(errno); 183004e86ffSlogin } 184004e86ffSlogin } else { 185ab5c8ca4Slogin inode.unwrap() 186004e86ffSlogin }; 187004e86ffSlogin 188ab5c8ca4Slogin let file_type: FileType = inode.metadata()?.file_type; 189ab5c8ca4Slogin // 如果要打开的是文件夹,而目标不是文件夹 190ab5c8ca4Slogin if mode.contains(FileMode::O_DIRECTORY) && file_type != FileType::Dir { 191ab5c8ca4Slogin return Err(SystemError::ENOTDIR); 192004e86ffSlogin } 193ab5c8ca4Slogin 194ab5c8ca4Slogin // 如果O_TRUNC,并且,打开模式包含O_RDWR或O_WRONLY,清空文件 195ab5c8ca4Slogin if mode.contains(FileMode::O_TRUNC) 196ab5c8ca4Slogin && (mode.contains(FileMode::O_RDWR) || mode.contains(FileMode::O_WRONLY)) 197ab5c8ca4Slogin && file_type == FileType::File 198ab5c8ca4Slogin { 199ab5c8ca4Slogin inode.truncate(0)?; 200ab5c8ca4Slogin } 201ab5c8ca4Slogin 202ab5c8ca4Slogin // 创建文件对象 20334e6d6c8Syuyi2439 204ab5c8ca4Slogin let mut file: File = File::new(inode, mode)?; 205ab5c8ca4Slogin 206ab5c8ca4Slogin // 打开模式为“追加” 207ab5c8ca4Slogin if mode.contains(FileMode::O_APPEND) { 208ab5c8ca4Slogin file.lseek(SeekFrom::SeekEnd(0))?; 209ab5c8ca4Slogin } 210ab5c8ca4Slogin // 把文件对象存入pcb 2111496ba7bSLoGin let r = ProcessManager::current_pcb() 2121496ba7bSLoGin .fd_table() 2131496ba7bSLoGin .write() 2141496ba7bSLoGin .alloc_fd(file, None) 2151496ba7bSLoGin .map(|fd| fd as usize); 2161496ba7bSLoGin 2176d81180bSLoGin return r; 218ab5c8ca4Slogin } 219ab5c8ca4Slogin 220ab5c8ca4Slogin /// @brief 关闭文件 221ab5c8ca4Slogin /// 222ab5c8ca4Slogin /// @param fd 文件描述符编号 223ab5c8ca4Slogin /// 224ab5c8ca4Slogin /// @return 成功返回0,失败返回错误码 225ab5c8ca4Slogin pub fn close(fd: usize) -> Result<usize, SystemError> { 2261496ba7bSLoGin let binding = ProcessManager::current_pcb().fd_table(); 2271496ba7bSLoGin let mut fd_table_guard = binding.write(); 2281496ba7bSLoGin 22934e6d6c8Syuyi2439 let res = fd_table_guard.drop_fd(fd as i32).map(|_| 0); 23034e6d6c8Syuyi2439 23134e6d6c8Syuyi2439 return res; 232ab5c8ca4Slogin } 233ab5c8ca4Slogin 23440314b30SXiaoye Zheng /// @brief 发送命令到文件描述符对应的设备, 23540314b30SXiaoye Zheng /// 23640314b30SXiaoye Zheng /// @param fd 文件描述符编号 23740314b30SXiaoye Zheng /// @param cmd 设备相关的请求类型 23840314b30SXiaoye Zheng /// 23940314b30SXiaoye Zheng /// @return Ok(usize) 成功返回0 24040314b30SXiaoye Zheng /// @return Err(SystemError) 读取失败,返回posix错误码 24140314b30SXiaoye Zheng pub fn ioctl(fd: usize, cmd: u32, data: usize) -> Result<usize, SystemError> { 24240314b30SXiaoye Zheng let binding = ProcessManager::current_pcb().fd_table(); 24340314b30SXiaoye Zheng let fd_table_guard = binding.read(); 24440314b30SXiaoye Zheng 24540314b30SXiaoye Zheng let file = fd_table_guard 24640314b30SXiaoye Zheng .get_file_by_fd(fd as i32) 24740314b30SXiaoye Zheng .ok_or(SystemError::EBADF)?; 24840314b30SXiaoye Zheng 24940314b30SXiaoye Zheng // drop guard 以避免无法调度的问题 25040314b30SXiaoye Zheng drop(fd_table_guard); 25140314b30SXiaoye Zheng let r = file.lock_no_preempt().inode().ioctl(cmd, data); 25240314b30SXiaoye Zheng return r; 25340314b30SXiaoye Zheng } 25440314b30SXiaoye Zheng 255ab5c8ca4Slogin /// @brief 根据文件描述符,读取文件数据。尝试读取的数据长度与buf的长度相同。 256ab5c8ca4Slogin /// 257ab5c8ca4Slogin /// @param fd 文件描述符编号 258ab5c8ca4Slogin /// @param buf 输出缓冲区。 259ab5c8ca4Slogin /// 260ab5c8ca4Slogin /// @return Ok(usize) 成功读取的数据的字节数 261ab5c8ca4Slogin /// @return Err(SystemError) 读取失败,返回posix错误码 262ab5c8ca4Slogin pub fn read(fd: i32, buf: &mut [u8]) -> Result<usize, SystemError> { 2631496ba7bSLoGin let binding = ProcessManager::current_pcb().fd_table(); 2641496ba7bSLoGin let fd_table_guard = binding.read(); 2651496ba7bSLoGin 2661496ba7bSLoGin let file = fd_table_guard.get_file_by_fd(fd); 267ab5c8ca4Slogin if file.is_none() { 268ab5c8ca4Slogin return Err(SystemError::EBADF); 269ab5c8ca4Slogin } 2701496ba7bSLoGin // drop guard 以避免无法调度的问题 2711496ba7bSLoGin drop(fd_table_guard); 2721496ba7bSLoGin let file = file.unwrap(); 273ab5c8ca4Slogin 2741496ba7bSLoGin return file.lock_no_preempt().read(buf.len(), buf); 275ab5c8ca4Slogin } 276ab5c8ca4Slogin 277ab5c8ca4Slogin /// @brief 根据文件描述符,向文件写入数据。尝试写入的数据长度与buf的长度相同。 278ab5c8ca4Slogin /// 279ab5c8ca4Slogin /// @param fd 文件描述符编号 280ab5c8ca4Slogin /// @param buf 输入缓冲区。 281ab5c8ca4Slogin /// 282ab5c8ca4Slogin /// @return Ok(usize) 成功写入的数据的字节数 283ab5c8ca4Slogin /// @return Err(SystemError) 写入失败,返回posix错误码 284ab5c8ca4Slogin pub fn write(fd: i32, buf: &[u8]) -> Result<usize, SystemError> { 2851496ba7bSLoGin let binding = ProcessManager::current_pcb().fd_table(); 2861496ba7bSLoGin let fd_table_guard = binding.read(); 287ab5c8ca4Slogin 2881496ba7bSLoGin let file = fd_table_guard 2891496ba7bSLoGin .get_file_by_fd(fd) 2901496ba7bSLoGin .ok_or(SystemError::EBADF)?; 2911496ba7bSLoGin 2921496ba7bSLoGin // drop guard 以避免无法调度的问题 2931496ba7bSLoGin drop(fd_table_guard); 2941496ba7bSLoGin return file.lock_no_preempt().write(buf.len(), buf); 295ab5c8ca4Slogin } 296ab5c8ca4Slogin 297ab5c8ca4Slogin /// @brief 调整文件操作指针的位置 298ab5c8ca4Slogin /// 299ab5c8ca4Slogin /// @param fd 文件描述符编号 300ab5c8ca4Slogin /// @param seek 调整的方式 301ab5c8ca4Slogin /// 302ab5c8ca4Slogin /// @return Ok(usize) 调整后,文件访问指针相对于文件头部的偏移量 303ab5c8ca4Slogin /// @return Err(SystemError) 调整失败,返回posix错误码 304ab5c8ca4Slogin pub fn lseek(fd: i32, seek: SeekFrom) -> Result<usize, SystemError> { 3051496ba7bSLoGin let binding = ProcessManager::current_pcb().fd_table(); 3061496ba7bSLoGin let fd_table_guard = binding.read(); 3071496ba7bSLoGin let file = fd_table_guard 3081496ba7bSLoGin .get_file_by_fd(fd) 3091496ba7bSLoGin .ok_or(SystemError::EBADF)?; 3101496ba7bSLoGin 3111496ba7bSLoGin // drop guard 以避免无法调度的问题 3121496ba7bSLoGin drop(fd_table_guard); 3131496ba7bSLoGin return file.lock_no_preempt().lseek(seek); 314004e86ffSlogin } 315004e86ffSlogin 316004e86ffSlogin /// @brief 切换工作目录 317004e86ffSlogin /// 318004e86ffSlogin /// @param dest_path 目标路径 319004e86ffSlogin /// 320004e86ffSlogin /// @return 返回码 描述 321004e86ffSlogin /// 0 | 成功 322004e86ffSlogin /// 323004e86ffSlogin /// EACCESS | 权限不足 324004e86ffSlogin /// 325004e86ffSlogin /// ELOOP | 解析path时遇到路径循环 326004e86ffSlogin /// 327004e86ffSlogin /// ENAMETOOLONG | 路径名过长 328004e86ffSlogin /// 329004e86ffSlogin /// ENOENT | 目标文件或目录不存在 330004e86ffSlogin /// 331004e86ffSlogin /// ENODIR | 检索期间发现非目录项 332004e86ffSlogin /// 333004e86ffSlogin /// ENOMEM | 系统内存不足 334004e86ffSlogin /// 335004e86ffSlogin /// EFAULT | 错误的地址 336004e86ffSlogin /// 337004e86ffSlogin /// ENAMETOOLONG | 路径过长 338ab5c8ca4Slogin pub fn chdir(dest_path: &str) -> Result<usize, SystemError> { 3391496ba7bSLoGin let proc = ProcessManager::current_pcb(); 340ab5c8ca4Slogin // Copy path to kernel space to avoid some security issues 3411496ba7bSLoGin let path = dest_path.to_string(); 3421496ba7bSLoGin let mut new_path = String::from(""); 3431496ba7bSLoGin if path.len() > 0 { 3441496ba7bSLoGin let cwd = match path.as_bytes()[0] { 3451496ba7bSLoGin b'/' => String::from("/"), 3461496ba7bSLoGin _ => proc.basic().cwd(), 3471496ba7bSLoGin }; 3481496ba7bSLoGin let mut cwd_vec: Vec<_> = cwd.split("/").filter(|&x| x != "").collect(); 3491496ba7bSLoGin let path_split = path.split("/").filter(|&x| x != ""); 3501496ba7bSLoGin for seg in path_split { 3511496ba7bSLoGin if seg == ".." { 3521496ba7bSLoGin cwd_vec.pop(); 3531496ba7bSLoGin } else if seg == "." { 3541496ba7bSLoGin // 当前目录 3551496ba7bSLoGin } else { 3561496ba7bSLoGin cwd_vec.push(seg); 3571496ba7bSLoGin } 3581496ba7bSLoGin } 3591496ba7bSLoGin //proc.basic().set_path(String::from("")); 3601496ba7bSLoGin for seg in cwd_vec { 3611496ba7bSLoGin new_path.push_str("/"); 3621496ba7bSLoGin new_path.push_str(seg); 3631496ba7bSLoGin } 3641496ba7bSLoGin if new_path == "" { 3651496ba7bSLoGin new_path = String::from("/"); 3661496ba7bSLoGin } 3671496ba7bSLoGin } 368a03c4f9dSLoGin let inode = 369a03c4f9dSLoGin match ROOT_INODE().lookup_follow_symlink(&new_path, VFS_MAX_FOLLOW_SYMLINK_TIMES) { 370004e86ffSlogin Err(e) => { 371676b8ef6SMork kerror!("Change Directory Failed, Error = {:?}", e); 372ab5c8ca4Slogin return Err(SystemError::ENOENT); 373004e86ffSlogin } 374004e86ffSlogin Ok(i) => i, 375004e86ffSlogin }; 3761496ba7bSLoGin let metadata = inode.metadata()?; 3771496ba7bSLoGin if metadata.file_type == FileType::Dir { 3781496ba7bSLoGin proc.basic_mut().set_cwd(String::from(new_path)); 379ab5c8ca4Slogin return Ok(0); 380004e86ffSlogin } else { 381ab5c8ca4Slogin return Err(SystemError::ENOTDIR); 382004e86ffSlogin } 383004e86ffSlogin } 3841496ba7bSLoGin 3851496ba7bSLoGin /// @brief 获取当前进程的工作目录路径 3861496ba7bSLoGin /// 3871496ba7bSLoGin /// @param buf 指向缓冲区的指针 3881496ba7bSLoGin /// @param size 缓冲区的大小 3891496ba7bSLoGin /// 3901496ba7bSLoGin /// @return 成功,返回的指针指向包含工作目录路径的字符串 3911496ba7bSLoGin /// @return 错误,没有足够的空间 3921496ba7bSLoGin pub fn getcwd(buf: &mut [u8]) -> Result<VirtAddr, SystemError> { 3931496ba7bSLoGin let proc = ProcessManager::current_pcb(); 3941496ba7bSLoGin let cwd = proc.basic().cwd(); 3951496ba7bSLoGin 3961496ba7bSLoGin let cwd_bytes = cwd.as_bytes(); 3971496ba7bSLoGin let cwd_len = cwd_bytes.len(); 3981496ba7bSLoGin if cwd_len + 1 > buf.len() { 3991496ba7bSLoGin return Err(SystemError::ENOMEM); 400004e86ffSlogin } 4011496ba7bSLoGin buf[..cwd_len].copy_from_slice(cwd_bytes); 4021496ba7bSLoGin buf[cwd_len] = 0; 4031496ba7bSLoGin 4041496ba7bSLoGin return Ok(VirtAddr::new(buf.as_ptr() as usize)); 405004e86ffSlogin } 406004e86ffSlogin 407004e86ffSlogin /// @brief 获取目录中的数据 408004e86ffSlogin /// 409ab5c8ca4Slogin /// TODO: 这个函数的语义与Linux不一致,需要修改!!! 410ab5c8ca4Slogin /// 411004e86ffSlogin /// @param fd 文件描述符号 412ab5c8ca4Slogin /// @param buf 输出缓冲区 413ab5c8ca4Slogin /// 414ab5c8ca4Slogin /// @return 成功返回读取的字节数,失败返回错误码 415ab5c8ca4Slogin pub fn getdents(fd: i32, buf: &mut [u8]) -> Result<usize, SystemError> { 416ab5c8ca4Slogin let dirent = 417ab5c8ca4Slogin unsafe { (buf.as_mut_ptr() as *mut Dirent).as_mut() }.ok_or(SystemError::EFAULT)?; 418004e86ffSlogin 419004e86ffSlogin if fd < 0 || fd as u32 > PROC_MAX_FD_NUM { 420ab5c8ca4Slogin return Err(SystemError::EBADF); 421004e86ffSlogin } 422004e86ffSlogin 423004e86ffSlogin // 获取fd 4241496ba7bSLoGin let binding = ProcessManager::current_pcb().fd_table(); 4251496ba7bSLoGin let fd_table_guard = binding.read(); 4261496ba7bSLoGin let file = fd_table_guard 4271496ba7bSLoGin .get_file_by_fd(fd) 4281496ba7bSLoGin .ok_or(SystemError::EBADF)?; 429004e86ffSlogin 4301496ba7bSLoGin // drop guard 以避免无法调度的问题 4311496ba7bSLoGin drop(fd_table_guard); 43234e6d6c8Syuyi2439 43334e6d6c8Syuyi2439 let res = file.lock_no_preempt().readdir(dirent).map(|x| x as usize); 43434e6d6c8Syuyi2439 43534e6d6c8Syuyi2439 return res; 436004e86ffSlogin } 437004e86ffSlogin 438004e86ffSlogin /// @brief 创建文件夹 439004e86ffSlogin /// 440004e86ffSlogin /// @param path(r8) 路径 / mode(r9) 模式 441004e86ffSlogin /// 442004e86ffSlogin /// @return uint64_t 负数错误码 / 0表示成功 443ab5c8ca4Slogin pub fn mkdir(path: &str, mode: usize) -> Result<usize, SystemError> { 444ab5c8ca4Slogin return do_mkdir(path, FileMode::from_bits_truncate(mode as u32)).map(|x| x as usize); 445004e86ffSlogin } 446004e86ffSlogin 447ab5c8ca4Slogin /// **删除文件夹、取消文件的链接、删除文件的系统调用** 448004e86ffSlogin /// 449ab5c8ca4Slogin /// ## 参数 450004e86ffSlogin /// 451ab5c8ca4Slogin /// - `dirfd`:文件夹的文件描述符.目前暂未实现 452ab5c8ca4Slogin /// - `pathname`:文件夹的路径 453ab5c8ca4Slogin /// - `flags`:标志位 454004e86ffSlogin /// 455004e86ffSlogin /// 456ab5c8ca4Slogin pub fn unlinkat(_dirfd: i32, pathname: &str, flags: u32) -> Result<usize, SystemError> { 457004e86ffSlogin // kdebug!("sys_unlink_at={path:?}"); 458ab5c8ca4Slogin if (flags & (!AT_REMOVEDIR)) != 0 { 459ab5c8ca4Slogin return Err(SystemError::EINVAL); 460004e86ffSlogin } 461004e86ffSlogin 462ab5c8ca4Slogin if (flags & AT_REMOVEDIR) > 0 { 463004e86ffSlogin // kdebug!("rmdir"); 464ab5c8ca4Slogin match do_remove_dir(&pathname) { 465004e86ffSlogin Err(err) => { 466676b8ef6SMork kerror!("Failed to Remove Directory, Error Code = {:?}", err); 467ab5c8ca4Slogin return Err(err); 468004e86ffSlogin } 469004e86ffSlogin Ok(_) => { 470ab5c8ca4Slogin return Ok(0); 471004e86ffSlogin } 472004e86ffSlogin } 473004e86ffSlogin } 474004e86ffSlogin 475ab5c8ca4Slogin match do_unlink_at(&pathname, FileMode::from_bits_truncate(flags as u32)) { 476004e86ffSlogin Err(err) => { 477676b8ef6SMork kerror!("Failed to Remove Directory, Error Code = {:?}", err); 478ab5c8ca4Slogin return Err(err); 479004e86ffSlogin } 480004e86ffSlogin Ok(_) => { 481ab5c8ca4Slogin return Ok(0); 482004e86ffSlogin } 483004e86ffSlogin } 484004e86ffSlogin } 4852b771e32SGou Ngai 486ab5c8ca4Slogin /// @brief 根据提供的文件描述符的fd,复制对应的文件结构体,并返回新复制的文件结构体对应的fd 487ab5c8ca4Slogin pub fn dup(oldfd: i32) -> Result<usize, SystemError> { 4881496ba7bSLoGin let binding = ProcessManager::current_pcb().fd_table(); 4891496ba7bSLoGin let mut fd_table_guard = binding.write(); 490ab5c8ca4Slogin 4911496ba7bSLoGin let old_file = fd_table_guard 4921496ba7bSLoGin .get_file_by_fd(oldfd) 4931496ba7bSLoGin .ok_or(SystemError::EBADF)?; 4941496ba7bSLoGin 4951496ba7bSLoGin let new_file = old_file 4961496ba7bSLoGin .lock_no_preempt() 4971496ba7bSLoGin .try_clone() 4981496ba7bSLoGin .ok_or(SystemError::EBADF)?; 4992b771e32SGou Ngai // 申请文件描述符,并把文件对象存入其中 5001496ba7bSLoGin let res = fd_table_guard.alloc_fd(new_file, None).map(|x| x as usize); 5012b771e32SGou Ngai return res; 5022b771e32SGou Ngai } 5032b771e32SGou Ngai 504ab5c8ca4Slogin /// 根据提供的文件描述符的fd,和指定新fd,复制对应的文件结构体, 505ab5c8ca4Slogin /// 并返回新复制的文件结构体对应的fd. 506ab5c8ca4Slogin /// 如果新fd已经打开,则会先关闭新fd. 507ab5c8ca4Slogin /// 508ab5c8ca4Slogin /// ## 参数 509ab5c8ca4Slogin /// 510ab5c8ca4Slogin /// - `oldfd`:旧文件描述符 511ab5c8ca4Slogin /// - `newfd`:新文件描述符 512ab5c8ca4Slogin /// 513ab5c8ca4Slogin /// ## 返回值 514ab5c8ca4Slogin /// 515ab5c8ca4Slogin /// - 成功:新文件描述符 516ab5c8ca4Slogin /// - 失败:错误码 517ab5c8ca4Slogin pub fn dup2(oldfd: i32, newfd: i32) -> Result<usize, SystemError> { 5181496ba7bSLoGin let binding = ProcessManager::current_pcb().fd_table(); 5191496ba7bSLoGin let mut fd_table_guard = binding.write(); 5201496ba7bSLoGin return Self::do_dup2(oldfd, newfd, &mut fd_table_guard); 5211496ba7bSLoGin } 5221496ba7bSLoGin 5231496ba7bSLoGin fn do_dup2( 5241496ba7bSLoGin oldfd: i32, 5251496ba7bSLoGin newfd: i32, 5261496ba7bSLoGin fd_table_guard: &mut RwLockWriteGuard<'_, FileDescriptorVec>, 5271496ba7bSLoGin ) -> Result<usize, SystemError> { 5282b771e32SGou Ngai // 确认oldfd, newid是否有效 5291496ba7bSLoGin if !(FileDescriptorVec::validate_fd(oldfd) && FileDescriptorVec::validate_fd(newfd)) { 5301496ba7bSLoGin return Err(SystemError::EBADF); 5311496ba7bSLoGin } 5321496ba7bSLoGin 5332b771e32SGou Ngai if oldfd == newfd { 5342b771e32SGou Ngai // 若oldfd与newfd相等 535ab5c8ca4Slogin return Ok(newfd as usize); 5362b771e32SGou Ngai } 5371496ba7bSLoGin let new_exists = fd_table_guard.get_file_by_fd(newfd).is_some(); 5381496ba7bSLoGin if new_exists { 5392b771e32SGou Ngai // close newfd 5401496ba7bSLoGin if let Err(_) = fd_table_guard.drop_fd(newfd) { 5412b771e32SGou Ngai // An I/O error occurred while attempting to close fildes2. 5422b771e32SGou Ngai return Err(SystemError::EIO); 5432b771e32SGou Ngai } 5442b771e32SGou Ngai } 5452b771e32SGou Ngai 5461496ba7bSLoGin let old_file = fd_table_guard 5471496ba7bSLoGin .get_file_by_fd(oldfd) 5481496ba7bSLoGin .ok_or(SystemError::EBADF)?; 5491496ba7bSLoGin let new_file = old_file 5501496ba7bSLoGin .lock_no_preempt() 5511496ba7bSLoGin .try_clone() 5521496ba7bSLoGin .ok_or(SystemError::EBADF)?; 5532b771e32SGou Ngai // 申请文件描述符,并把文件对象存入其中 5541496ba7bSLoGin let res = fd_table_guard 5551496ba7bSLoGin .alloc_fd(new_file, Some(newfd)) 556ab5c8ca4Slogin .map(|x| x as usize); 5572b771e32SGou Ngai return res; 5582b771e32SGou Ngai } 5596d81180bSLoGin 5606d81180bSLoGin /// # fcntl 5616d81180bSLoGin /// 5626d81180bSLoGin /// ## 参数 5636d81180bSLoGin /// 5646d81180bSLoGin /// - `fd`:文件描述符 5656d81180bSLoGin /// - `cmd`:命令 5666d81180bSLoGin /// - `arg`:参数 5676d81180bSLoGin pub fn fcntl(fd: i32, cmd: FcntlCommand, arg: i32) -> Result<usize, SystemError> { 5686d81180bSLoGin match cmd { 5696d81180bSLoGin FcntlCommand::DupFd => { 5706d81180bSLoGin if arg < 0 || arg as usize >= FileDescriptorVec::PROCESS_MAX_FD { 5716d81180bSLoGin return Err(SystemError::EBADF); 5726d81180bSLoGin } 5736d81180bSLoGin let arg = arg as usize; 5746d81180bSLoGin for i in arg..FileDescriptorVec::PROCESS_MAX_FD { 5751496ba7bSLoGin let binding = ProcessManager::current_pcb().fd_table(); 5761496ba7bSLoGin let mut fd_table_guard = binding.write(); 5771496ba7bSLoGin if fd_table_guard.get_file_by_fd(fd).is_none() { 5781496ba7bSLoGin return Self::do_dup2(fd, i as i32, &mut fd_table_guard); 5796d81180bSLoGin } 5806d81180bSLoGin } 5816d81180bSLoGin return Err(SystemError::EMFILE); 5826d81180bSLoGin } 5836d81180bSLoGin FcntlCommand::GetFd => { 5846d81180bSLoGin // Get file descriptor flags. 5851496ba7bSLoGin let binding = ProcessManager::current_pcb().fd_table(); 5861496ba7bSLoGin let fd_table_guard = binding.read(); 5871496ba7bSLoGin if let Some(file) = fd_table_guard.get_file_by_fd(fd) { 5881496ba7bSLoGin // drop guard 以避免无法调度的问题 5891496ba7bSLoGin drop(fd_table_guard); 5906d81180bSLoGin 5911496ba7bSLoGin if file.lock().close_on_exec() { 5926d81180bSLoGin return Ok(FD_CLOEXEC as usize); 5936d81180bSLoGin } 5946d81180bSLoGin } 5956d81180bSLoGin return Err(SystemError::EBADF); 5966d81180bSLoGin } 5976d81180bSLoGin FcntlCommand::SetFd => { 5986d81180bSLoGin // Set file descriptor flags. 5991496ba7bSLoGin let binding = ProcessManager::current_pcb().fd_table(); 6001496ba7bSLoGin let fd_table_guard = binding.write(); 6011496ba7bSLoGin 6021496ba7bSLoGin if let Some(file) = fd_table_guard.get_file_by_fd(fd) { 6031496ba7bSLoGin // drop guard 以避免无法调度的问题 6041496ba7bSLoGin drop(fd_table_guard); 6056d81180bSLoGin let arg = arg as u32; 6066d81180bSLoGin if arg & FD_CLOEXEC != 0 { 6071496ba7bSLoGin file.lock().set_close_on_exec(true); 6086d81180bSLoGin } else { 6091496ba7bSLoGin file.lock().set_close_on_exec(false); 6106d81180bSLoGin } 6116d81180bSLoGin return Ok(0); 6126d81180bSLoGin } 6136d81180bSLoGin return Err(SystemError::EBADF); 6146d81180bSLoGin } 6156d81180bSLoGin 6166d81180bSLoGin FcntlCommand::GetFlags => { 6176d81180bSLoGin // Get file status flags. 6181496ba7bSLoGin let binding = ProcessManager::current_pcb().fd_table(); 6191496ba7bSLoGin let fd_table_guard = binding.read(); 6201496ba7bSLoGin 6211496ba7bSLoGin if let Some(file) = fd_table_guard.get_file_by_fd(fd) { 6221496ba7bSLoGin // drop guard 以避免无法调度的问题 6231496ba7bSLoGin drop(fd_table_guard); 6241496ba7bSLoGin return Ok(file.lock_no_preempt().mode().bits() as usize); 6256d81180bSLoGin } 6261496ba7bSLoGin 6276d81180bSLoGin return Err(SystemError::EBADF); 6286d81180bSLoGin } 6296d81180bSLoGin FcntlCommand::SetFlags => { 6306d81180bSLoGin // Set file status flags. 6311496ba7bSLoGin let binding = ProcessManager::current_pcb().fd_table(); 6321496ba7bSLoGin let fd_table_guard = binding.write(); 6331496ba7bSLoGin 6341496ba7bSLoGin if let Some(file) = fd_table_guard.get_file_by_fd(fd) { 6356d81180bSLoGin let arg = arg as u32; 6366d81180bSLoGin let mode = FileMode::from_bits(arg).ok_or(SystemError::EINVAL)?; 6371496ba7bSLoGin // drop guard 以避免无法调度的问题 6381496ba7bSLoGin drop(fd_table_guard); 6391496ba7bSLoGin file.lock_no_preempt().set_mode(mode)?; 6406d81180bSLoGin return Ok(0); 6416d81180bSLoGin } 6421496ba7bSLoGin 6436d81180bSLoGin return Err(SystemError::EBADF); 6446d81180bSLoGin } 6456d81180bSLoGin _ => { 6466d81180bSLoGin // TODO: unimplemented 6476d81180bSLoGin // 未实现的命令,返回0,不报错。 6486d81180bSLoGin 6496d81180bSLoGin // kwarn!("fcntl: unimplemented command: {:?}, defaults to 0.", cmd); 6506d81180bSLoGin return Ok(0); 6516d81180bSLoGin } 6526d81180bSLoGin } 6536d81180bSLoGin } 6546d81180bSLoGin 6556d81180bSLoGin /// # ftruncate 6566d81180bSLoGin /// 6576d81180bSLoGin /// ## 描述 6586d81180bSLoGin /// 6596d81180bSLoGin /// 改变文件大小. 6606d81180bSLoGin /// 如果文件大小大于原来的大小,那么文件的内容将会被扩展到指定的大小,新的空间将会用0填充. 6616d81180bSLoGin /// 如果文件大小小于原来的大小,那么文件的内容将会被截断到指定的大小. 6626d81180bSLoGin /// 6636d81180bSLoGin /// ## 参数 6646d81180bSLoGin /// 6656d81180bSLoGin /// - `fd`:文件描述符 6666d81180bSLoGin /// - `len`:文件大小 6676d81180bSLoGin /// 6686d81180bSLoGin /// ## 返回值 6696d81180bSLoGin /// 6706d81180bSLoGin /// 如果成功,返回0,否则返回错误码. 6716d81180bSLoGin pub fn ftruncate(fd: i32, len: usize) -> Result<usize, SystemError> { 6721496ba7bSLoGin let binding = ProcessManager::current_pcb().fd_table(); 6731496ba7bSLoGin let fd_table_guard = binding.read(); 6741496ba7bSLoGin 6751496ba7bSLoGin if let Some(file) = fd_table_guard.get_file_by_fd(fd) { 6761496ba7bSLoGin // drop guard 以避免无法调度的问题 6771496ba7bSLoGin drop(fd_table_guard); 6781496ba7bSLoGin let r = file.lock_no_preempt().ftruncate(len).map(|_| 0); 6796d81180bSLoGin return r; 6806d81180bSLoGin } 6811496ba7bSLoGin 6826d81180bSLoGin return Err(SystemError::EBADF); 6836d81180bSLoGin } 6841496ba7bSLoGin 68567b48188Shoumkh fn do_fstat(fd: i32) -> Result<PosixKstat, SystemError> { 6861496ba7bSLoGin let binding = ProcessManager::current_pcb().fd_table(); 6871496ba7bSLoGin let fd_table_guard = binding.read(); 6881496ba7bSLoGin let file = fd_table_guard 6891496ba7bSLoGin .get_file_by_fd(fd) 6901496ba7bSLoGin .ok_or(SystemError::EBADF)?; 6911496ba7bSLoGin // drop guard 以避免无法调度的问题 6921496ba7bSLoGin drop(fd_table_guard); 6931496ba7bSLoGin 69467b48188Shoumkh let mut kstat = PosixKstat::new(); 69567b48188Shoumkh // 获取文件信息 6961496ba7bSLoGin let metadata = file.lock().metadata()?; 69767b48188Shoumkh kstat.size = metadata.size as i64; 69867b48188Shoumkh kstat.dev_id = metadata.dev_id as u64; 6996b4e7a29SLoGin kstat.inode = metadata.inode_id.into() as u64; 70067b48188Shoumkh kstat.blcok_size = metadata.blk_size as i64; 70167b48188Shoumkh kstat.blocks = metadata.blocks as u64; 70267b48188Shoumkh 70367b48188Shoumkh kstat.atime.tv_sec = metadata.atime.tv_sec; 70467b48188Shoumkh kstat.atime.tv_nsec = metadata.atime.tv_nsec; 70567b48188Shoumkh kstat.mtime.tv_sec = metadata.mtime.tv_sec; 70667b48188Shoumkh kstat.mtime.tv_nsec = metadata.mtime.tv_nsec; 70767b48188Shoumkh kstat.ctime.tv_sec = metadata.ctime.tv_sec; 70867b48188Shoumkh kstat.ctime.tv_nsec = metadata.ctime.tv_nsec; 70967b48188Shoumkh 71067b48188Shoumkh kstat.nlink = metadata.nlinks as u64; 71167b48188Shoumkh kstat.uid = metadata.uid as i32; 71267b48188Shoumkh kstat.gid = metadata.gid as i32; 71367b48188Shoumkh kstat.rdev = metadata.raw_dev as i64; 7146b4e7a29SLoGin kstat.mode = metadata.mode; 7151496ba7bSLoGin match file.lock().file_type() { 7167eda31b2SLoGin FileType::File => kstat.mode.insert(ModeType::S_IFREG), 71767b48188Shoumkh FileType::Dir => kstat.mode.insert(ModeType::S_IFDIR), 71867b48188Shoumkh FileType::BlockDevice => kstat.mode.insert(ModeType::S_IFBLK), 71967b48188Shoumkh FileType::CharDevice => kstat.mode.insert(ModeType::S_IFCHR), 72067b48188Shoumkh FileType::SymLink => kstat.mode.insert(ModeType::S_IFLNK), 72167b48188Shoumkh FileType::Socket => kstat.mode.insert(ModeType::S_IFSOCK), 72267b48188Shoumkh FileType::Pipe => kstat.mode.insert(ModeType::S_IFIFO), 72340314b30SXiaoye Zheng FileType::KvmDevice => kstat.mode.insert(ModeType::S_IFCHR), 72467b48188Shoumkh } 72567b48188Shoumkh 72667b48188Shoumkh return Ok(kstat); 72767b48188Shoumkh } 7281496ba7bSLoGin 729*971462beSGnoCiYeH fn do_stat(path: &str) -> Result<PosixKstat, SystemError> { 730*971462beSGnoCiYeH let fd = Self::open(path, FileMode::O_RDONLY)?; 731*971462beSGnoCiYeH let ret = Self::do_fstat(fd as i32); 732*971462beSGnoCiYeH Self::close(fd)?; 733*971462beSGnoCiYeH ret 734*971462beSGnoCiYeH } 735*971462beSGnoCiYeH 73667b48188Shoumkh pub fn fstat(fd: i32, usr_kstat: *mut PosixKstat) -> Result<usize, SystemError> { 7371496ba7bSLoGin let kstat = Self::do_fstat(fd)?; 73867b48188Shoumkh if usr_kstat.is_null() { 73967b48188Shoumkh return Err(SystemError::EFAULT); 74067b48188Shoumkh } 74167b48188Shoumkh unsafe { 74267b48188Shoumkh *usr_kstat = kstat; 74367b48188Shoumkh } 74467b48188Shoumkh return Ok(0); 74567b48188Shoumkh } 7462dbef785SGnoCiYeH 747*971462beSGnoCiYeH pub fn stat(path: &str, user_kstat: *mut PosixKstat) -> Result<usize, SystemError> { 748*971462beSGnoCiYeH let fd = Self::open(path, FileMode::O_RDONLY)?; 749*971462beSGnoCiYeH Self::fstat(fd as i32, user_kstat).map_err(|e| { 750*971462beSGnoCiYeH Self::close(fd).ok(); 751*971462beSGnoCiYeH e 752*971462beSGnoCiYeH }) 753*971462beSGnoCiYeH } 754*971462beSGnoCiYeH 7552dbef785SGnoCiYeH pub fn mknod( 7562dbef785SGnoCiYeH path_ptr: *const i8, 7572dbef785SGnoCiYeH mode: ModeType, 7582dbef785SGnoCiYeH dev_t: DeviceNumber, 7592dbef785SGnoCiYeH ) -> Result<usize, SystemError> { 7602dbef785SGnoCiYeH // 安全检验 7612dbef785SGnoCiYeH let len = unsafe { CStr::from_ptr(path_ptr).to_bytes().len() }; 7622dbef785SGnoCiYeH let user_buffer = UserBufferReader::new(path_ptr, len, true)?; 7632dbef785SGnoCiYeH let buf = user_buffer.read_from_user::<u8>(0)?; 7642dbef785SGnoCiYeH let path = core::str::from_utf8(buf).map_err(|_| SystemError::EINVAL)?; 7652dbef785SGnoCiYeH 7662dbef785SGnoCiYeH // 文件名过长 7672dbef785SGnoCiYeH if path.len() > MAX_PATHLEN as usize { 7682dbef785SGnoCiYeH return Err(SystemError::ENAMETOOLONG); 7692dbef785SGnoCiYeH } 7702dbef785SGnoCiYeH 771a03c4f9dSLoGin let inode: Result<Arc<dyn IndexNode>, SystemError> = 772a03c4f9dSLoGin ROOT_INODE().lookup_follow_symlink(path, VFS_MAX_FOLLOW_SYMLINK_TIMES); 7732dbef785SGnoCiYeH 7742dbef785SGnoCiYeH if inode.is_ok() { 7752dbef785SGnoCiYeH return Err(SystemError::EEXIST); 7762dbef785SGnoCiYeH } 7772dbef785SGnoCiYeH 7782dbef785SGnoCiYeH let (filename, parent_path) = rsplit_path(path); 7792dbef785SGnoCiYeH 7802dbef785SGnoCiYeH // 查找父目录 781a03c4f9dSLoGin let parent_inode: Arc<dyn IndexNode> = ROOT_INODE() 782a03c4f9dSLoGin .lookup_follow_symlink(parent_path.unwrap_or("/"), VFS_MAX_FOLLOW_SYMLINK_TIMES)?; 7832dbef785SGnoCiYeH // 创建nod 7842dbef785SGnoCiYeH parent_inode.mknod(filename, mode, dev_t)?; 7852dbef785SGnoCiYeH 7862dbef785SGnoCiYeH return Ok(0); 7872dbef785SGnoCiYeH } 788*971462beSGnoCiYeH 789*971462beSGnoCiYeH pub fn writev(fd: i32, iov: usize, count: usize) -> Result<usize, SystemError> { 790*971462beSGnoCiYeH // IoVecs会进行用户态检验 791*971462beSGnoCiYeH let iovecs = unsafe { IoVecs::from_user(iov as *const IoVec, count, false) }?; 792*971462beSGnoCiYeH 793*971462beSGnoCiYeH let data = iovecs.gather(); 794*971462beSGnoCiYeH 795*971462beSGnoCiYeH Self::write(fd, &data) 796*971462beSGnoCiYeH } 79767b48188Shoumkh } 798cde5492fSlogin #[repr(C)] 799cde5492fSlogin #[derive(Debug, Clone, Copy)] 800cde5492fSlogin pub struct IoVec { 801cde5492fSlogin /// 缓冲区的起始地址 802cde5492fSlogin pub iov_base: *mut u8, 803cde5492fSlogin /// 缓冲区的长度 804cde5492fSlogin pub iov_len: usize, 805cde5492fSlogin } 806cde5492fSlogin 807cde5492fSlogin /// 用于存储多个来自用户空间的IoVec 808cde5492fSlogin /// 809cde5492fSlogin /// 由于目前内核中的文件系统还不支持分散读写,所以暂时只支持将用户空间的IoVec聚合成一个缓冲区,然后进行操作。 810cde5492fSlogin /// TODO:支持分散读写 811cde5492fSlogin #[derive(Debug)] 812cde5492fSlogin pub struct IoVecs(Vec<&'static mut [u8]>); 813cde5492fSlogin 814cde5492fSlogin impl IoVecs { 815cde5492fSlogin /// 从用户空间的IoVec中构造IoVecs 816cde5492fSlogin /// 817cde5492fSlogin /// @param iov 用户空间的IoVec 818cde5492fSlogin /// @param iovcnt 用户空间的IoVec的数量 819cde5492fSlogin /// @param readv 是否为readv系统调用 820cde5492fSlogin /// 821cde5492fSlogin /// @return 构造成功返回IoVecs,否则返回错误码 822cde5492fSlogin pub unsafe fn from_user( 823cde5492fSlogin iov: *const IoVec, 824cde5492fSlogin iovcnt: usize, 825cde5492fSlogin _readv: bool, 826cde5492fSlogin ) -> Result<Self, SystemError> { 827cde5492fSlogin // 检查iov指针所在空间是否合法 828cde5492fSlogin if !verify_area( 829cde5492fSlogin iov as usize as u64, 830cde5492fSlogin (iovcnt * core::mem::size_of::<IoVec>()) as u64, 831cde5492fSlogin ) { 832cde5492fSlogin return Err(SystemError::EFAULT); 833cde5492fSlogin } 834cde5492fSlogin 835cde5492fSlogin // 将用户空间的IoVec转换为引用(注意:这里的引用是静态的,因为用户空间的IoVec不会被释放) 836cde5492fSlogin let iovs: &[IoVec] = core::slice::from_raw_parts(iov, iovcnt); 837cde5492fSlogin 838cde5492fSlogin let mut slices: Vec<&mut [u8]> = vec![]; 839cde5492fSlogin slices.reserve(iovs.len()); 840cde5492fSlogin 841cde5492fSlogin for iov in iovs.iter() { 842cde5492fSlogin if iov.iov_len == 0 { 843cde5492fSlogin continue; 844cde5492fSlogin } 845cde5492fSlogin 846cde5492fSlogin if !verify_area(iov.iov_base as usize as u64, iov.iov_len as u64) { 847cde5492fSlogin return Err(SystemError::EFAULT); 848cde5492fSlogin } 849cde5492fSlogin 850cde5492fSlogin slices.push(core::slice::from_raw_parts_mut(iov.iov_base, iov.iov_len)); 851cde5492fSlogin } 852cde5492fSlogin 853cde5492fSlogin return Ok(Self(slices)); 854cde5492fSlogin } 855cde5492fSlogin 856cde5492fSlogin /// @brief 将IoVecs中的数据聚合到一个缓冲区中 857cde5492fSlogin /// 858cde5492fSlogin /// @return 返回聚合后的缓冲区 859cde5492fSlogin pub fn gather(&self) -> Vec<u8> { 860cde5492fSlogin let mut buf = Vec::new(); 861cde5492fSlogin for slice in self.0.iter() { 862cde5492fSlogin buf.extend_from_slice(slice); 863cde5492fSlogin } 864cde5492fSlogin return buf; 865cde5492fSlogin } 866cde5492fSlogin 867cde5492fSlogin /// @brief 将给定的数据分散写入到IoVecs中 868cde5492fSlogin pub fn scatter(&mut self, data: &[u8]) { 869cde5492fSlogin let mut data: &[u8] = data; 870cde5492fSlogin for slice in self.0.iter_mut() { 871cde5492fSlogin let len = core::cmp::min(slice.len(), data.len()); 872cde5492fSlogin if len == 0 { 873cde5492fSlogin continue; 874cde5492fSlogin } 875cde5492fSlogin 876cde5492fSlogin slice[..len].copy_from_slice(&data[..len]); 877cde5492fSlogin data = &data[len..]; 878cde5492fSlogin } 879cde5492fSlogin } 880cde5492fSlogin 881cde5492fSlogin /// @brief 创建与IoVecs等长的缓冲区 882cde5492fSlogin /// 883cde5492fSlogin /// @param set_len 是否设置返回的Vec的len。 884cde5492fSlogin /// 如果为true,则返回的Vec的len为所有IoVec的长度之和; 885cde5492fSlogin /// 否则返回的Vec的len为0,capacity为所有IoVec的长度之和. 886cde5492fSlogin /// 887cde5492fSlogin /// @return 返回创建的缓冲区 888cde5492fSlogin pub fn new_buf(&self, set_len: bool) -> Vec<u8> { 889cde5492fSlogin let total_len: usize = self.0.iter().map(|slice| slice.len()).sum(); 890cde5492fSlogin let mut buf: Vec<u8> = Vec::with_capacity(total_len); 891cde5492fSlogin 892cde5492fSlogin if set_len { 8937ae679ddSLoGin buf.resize(total_len, 0); 894cde5492fSlogin } 895cde5492fSlogin return buf; 896cde5492fSlogin } 897cde5492fSlogin } 898