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