1 use core::mem::MaybeUninit; 2 3 use alloc::{boxed::Box, string::String, sync::Arc, vec::Vec}; 4 5 use crate::{ 6 arch::asm::current::current_pcb, 7 filesystem::procfs::ProcfsFilePrivateData, 8 include::bindings::bindings::{ 9 process_control_block, EINVAL, ENOBUFS, EOVERFLOW, EPERM, ESPIPE, 10 }, 11 io::SeekFrom, 12 kerror, 13 }; 14 15 use super::{Dirent, FileType, IndexNode, Metadata}; 16 17 /// 文件私有信息的枚举类型 18 #[derive(Debug, Clone)] 19 pub enum FilePrivateData { 20 // procfs文件私有信息 21 Procfs(ProcfsFilePrivateData), 22 // 不需要文件私有信息 23 Unused, 24 } 25 26 impl Default for FilePrivateData { 27 fn default() -> Self { 28 return Self::Unused; 29 } 30 } 31 32 bitflags! { 33 /// @brief 文件打开模式 34 /// 其中,低2bit组合而成的数字的值,用于表示访问权限。其他的bit,才支持通过按位或的方式来表示参数 35 /// 36 /// 与Linux 5.19.10的uapi/asm-generic/fcntl.h相同 37 /// https://opengrok.ringotek.cn/xref/linux-5.19.10/tools/include/uapi/asm-generic/fcntl.h#19 38 pub struct FileMode: u32{ 39 /* File access modes for `open' and `fcntl'. */ 40 /// Open Read-only 41 const O_RDONLY = 0o0; 42 /// Open Write-only 43 const O_WRONLY = 0o1; 44 /// Open read/write 45 const O_RDWR = 0o2; 46 /// Mask for file access modes 47 const O_ACCMODE = 0o00000003; 48 49 /* Bits OR'd into the second argument to open. */ 50 /// Create file if it does not exist 51 const O_CREAT = 0o00000100; 52 /// Fail if file already exists 53 const O_EXCL = 0o00000200; 54 /// Do not assign controlling terminal 55 const O_NOCTTY = 0o00000400; 56 /// 文件存在且是普通文件,并以O_RDWR或O_WRONLY打开,则它会被清空 57 const O_TRUNC = 0o00001000; 58 /// 文件指针会被移动到文件末尾 59 const O_APPEND = 0o00002000; 60 /// 非阻塞式IO模式 61 const O_NONBLOCK = 0o00004000; 62 /// used to be O_SYNC, see below 63 const O_DSYNC = 0o00010000; 64 /// fcntl, for BSD compatibility 65 const FASYNC = 0o00020000; 66 /* direct disk access hint */ 67 const O_DIRECT = 0o00040000; 68 const O_LARGEFILE = 0o00100000; 69 /// 打开的必须是一个目录 70 const O_DIRECTORY = 0o00200000; 71 /// Do not follow symbolic links 72 const O_NOFOLLOW = 0o00400000; 73 const O_NOATIME = 0o01000000; 74 /// set close_on_exec 75 const O_CLOEXEC = 0o02000000; 76 } 77 } 78 79 /// @brief 抽象文件结构体 80 #[derive(Debug, Clone)] 81 pub struct File { 82 inode: Arc<dyn IndexNode>, 83 /// 对于文件,表示字节偏移量;对于文件夹,表示当前操作的子目录项偏移量 84 offset: usize, 85 /// 文件的打开模式 86 mode: FileMode, 87 /// 文件类型 88 file_type: FileType, 89 /// readdir时候用的,暂存的本次循环中,所有子目录项的名字的数组 90 readdir_subdirs_name: Vec<String>, 91 pub private_data: FilePrivateData, 92 } 93 94 impl File { 95 /// @brief 创建一个新的文件对象 96 /// 97 /// @param inode 文件对象对应的inode 98 /// @param mode 文件的打开模式 99 pub fn new(inode: Arc<dyn IndexNode>, mode: FileMode) -> Result<Self, i32> { 100 let file_type: FileType = inode.metadata()?.file_type; 101 let mut f = File { 102 inode, 103 offset: 0, 104 mode, 105 file_type, 106 readdir_subdirs_name: Vec::new(), 107 private_data: FilePrivateData::default(), 108 }; 109 // kdebug!("inode:{:?}",f.inode); 110 f.inode.open(&mut f.private_data)?; 111 return Ok(f); 112 } 113 114 /// @brief 从文件中读取指定的字节数到buffer中 115 /// 116 /// @param len 要读取的字节数 117 /// @param buf 目标buffer 118 /// 119 /// @return Ok(usize) 成功读取的字节数 120 /// @return Err(i32) 错误码 121 pub fn read(&mut self, len: usize, buf: &mut [u8]) -> Result<usize, i32> { 122 // 先检查本文件在权限等规则下,是否可读取。 123 self.readable()?; 124 125 if buf.len() < len { 126 return Err(-(ENOBUFS as i32)); 127 } 128 129 let len = self 130 .inode 131 .read_at(self.offset, len, buf, &mut self.private_data)?; 132 self.offset += len; 133 return Ok(len); 134 } 135 136 /// @brief 从buffer向文件写入指定的字节数的数据 137 /// 138 /// @param len 要写入的字节数 139 /// @param buf 源数据buffer 140 /// 141 /// @return Ok(usize) 成功写入的字节数 142 /// @return Err(i32) 错误码 143 pub fn write(&mut self, len: usize, buf: &[u8]) -> Result<usize, i32> { 144 // 先检查本文件在权限等规则下,是否可写入。 145 self.writeable()?; 146 if buf.len() < len { 147 return Err(-(ENOBUFS as i32)); 148 } 149 let len = self 150 .inode 151 .write_at(self.offset, len, buf, &mut FilePrivateData::Unused)?; 152 self.offset += len; 153 return Ok(len); 154 } 155 156 /// @brief 获取文件的元数据 157 pub fn metadata(&self) -> Result<Metadata, i32> { 158 return self.inode.metadata(); 159 } 160 161 /// @brief 根据inode号获取子目录项的名字 162 pub fn get_entry_name(&self, ino: usize) -> Result<String, i32> { 163 return self.inode.get_entry_name(ino); 164 } 165 166 /// @brief 调整文件操作指针的位置 167 /// 168 /// @param origin 调整的起始位置 169 pub fn lseek(&mut self, origin: SeekFrom) -> Result<usize, i32> { 170 if self.inode.metadata().unwrap().file_type == FileType::Pipe { 171 return Err(-(ESPIPE as i32)); 172 } 173 let pos: i64; 174 match origin { 175 SeekFrom::SeekSet(offset) => { 176 pos = offset; 177 } 178 SeekFrom::SeekCurrent(offset) => { 179 pos = self.offset as i64 + offset; 180 } 181 SeekFrom::SeekEnd(offset) => { 182 let metadata = self.metadata()?; 183 pos = metadata.size + offset; 184 } 185 SeekFrom::Invalid => { 186 return Err(-(EINVAL as i32)); 187 } 188 } 189 190 if pos < 0 || pos > self.metadata()?.size { 191 return Err(-(EOVERFLOW as i32)); 192 } 193 self.offset = pos as usize; 194 return Ok(self.offset); 195 } 196 197 /// @brief 判断当前文件是否可读 198 #[inline] 199 pub fn readable(&self) -> Result<(), i32> { 200 // 暂时认为只要不是write only, 就可读 201 if self.mode == FileMode::O_WRONLY { 202 return Err(-(EPERM as i32)); 203 } 204 205 return Ok(()); 206 } 207 208 /// @brief 判断当前文件是否可写 209 #[inline] 210 pub fn writeable(&self) -> Result<(), i32> { 211 // 暂时认为只要不是read only, 就可写 212 if self.mode == FileMode::O_RDONLY { 213 return Err(-(EPERM as i32)); 214 } 215 216 return Ok(()); 217 } 218 219 /// @biref 充填dirent结构体 220 /// @return 返回dirent结构体的大小 221 pub fn readdir(&mut self, dirent: &mut Dirent) -> Result<u64, i32> { 222 let inode: &Arc<dyn IndexNode> = &self.inode; 223 224 // 如果偏移量为0 225 if self.offset == 0 { 226 self.readdir_subdirs_name = inode.list()?; 227 self.readdir_subdirs_name.sort(); 228 } 229 230 // kdebug!("sub_entries={sub_entries:?}"); 231 if self.readdir_subdirs_name.is_empty() { 232 self.offset = 0; 233 return Ok(0); 234 } 235 let name: String = self.readdir_subdirs_name.remove(0); 236 let sub_inode: Arc<dyn IndexNode> = match inode.find(&name) { 237 Ok(i) => i, 238 Err(e) => { 239 kerror!("Readdir error: Failed to find sub inode, file={self:?}"); 240 return Err(e); 241 } 242 }; 243 244 let name_bytes: &[u8] = name.as_bytes(); 245 246 self.offset += 1; 247 dirent.d_ino = sub_inode.metadata().unwrap().inode_id as u64; 248 dirent.d_off = 0; 249 dirent.d_reclen = 0; 250 dirent.d_type = sub_inode.metadata().unwrap().file_type.get_file_type_num() as u8; 251 // 根据posix的规定,dirent中的d_name是一个不定长的数组,因此需要unsafe来拷贝数据 252 unsafe { 253 let ptr = &mut dirent.d_name as *mut u8; 254 let buf: &mut [u8] = 255 ::core::slice::from_raw_parts_mut::<'static, u8>(ptr, name_bytes.len()); 256 buf.copy_from_slice(name_bytes); 257 } 258 259 // 计算dirent结构体的大小 260 return Ok((name_bytes.len() + ::core::mem::size_of::<Dirent>() 261 - ::core::mem::size_of_val(&dirent.d_name)) as u64); 262 } 263 pub fn inode(&self) -> Arc<dyn IndexNode> { 264 return self.inode.clone(); 265 } 266 } 267 268 impl Drop for File { 269 fn drop(&mut self) { 270 let r: Result<(), i32> = self.inode.close(&mut self.private_data); 271 // 打印错误信息 272 if r.is_err() { 273 kerror!( 274 "pid: {} failed to close file: {:?}, errno={}", 275 current_pcb().pid, 276 self, 277 r.unwrap_err() 278 ); 279 } 280 } 281 } 282 283 /// @brief pcb里面的文件描述符数组 284 #[derive(Debug, Clone)] 285 pub struct FileDescriptorVec { 286 /// 当前进程打开的文件描述符 287 pub fds: [Option<Box<File>>; FileDescriptorVec::PROCESS_MAX_FD], 288 } 289 290 impl FileDescriptorVec { 291 pub const PROCESS_MAX_FD: usize = 32; 292 293 pub fn new() -> Box<FileDescriptorVec> { 294 // 先声明一个未初始化的数组 295 let mut data: [MaybeUninit<Option<Box<File>>>; FileDescriptorVec::PROCESS_MAX_FD] = 296 unsafe { MaybeUninit::uninit().assume_init() }; 297 298 // 逐个把每个元素初始化为None 299 for i in 0..FileDescriptorVec::PROCESS_MAX_FD { 300 data[i] = MaybeUninit::new(None); 301 } 302 // 由于一切都初始化完毕,因此将未初始化的类型强制转换为已经初始化的类型 303 let data: [Option<Box<File>>; FileDescriptorVec::PROCESS_MAX_FD] = unsafe { 304 core::mem::transmute::<_, [Option<Box<File>>; FileDescriptorVec::PROCESS_MAX_FD]>(data) 305 }; 306 307 // 初始化文件描述符数组结构体 308 return Box::new(FileDescriptorVec { fds: data }); 309 } 310 311 /// @brief 从pcb的fds字段,获取文件描述符数组的可变引用 312 #[inline] 313 pub fn from_pcb(pcb: &'static process_control_block) -> Option<&'static mut FileDescriptorVec> { 314 return unsafe { (pcb.fds as usize as *mut FileDescriptorVec).as_mut() }; 315 } 316 317 /// @brief 判断文件描述符序号是否合法 318 /// 319 /// @return true 合法 320 /// 321 /// @return false 不合法 322 #[inline] 323 pub fn validate_fd(fd: i32) -> bool { 324 if fd < 0 || fd as usize > FileDescriptorVec::PROCESS_MAX_FD { 325 return false; 326 } else { 327 return true; 328 } 329 } 330 } 331