aienux
Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.
Brought by drakestapleton
aienux / vendor / uefi / src / fs / file_system / fs.rs
| 1 | // SPDX-License-Identifier: MIT OR Apache-2.0 |
| 2 | |
| 3 | //! Module for [`FileSystem`]. |
| 4 | |
| 5 | use crate::Status; |
| 6 | use crate::fs::*; |
| 7 | use alloc::boxed::Box; |
| 8 | use alloc::string::String; |
| 9 | use alloc::vec; |
| 10 | use alloc::vec::Vec; |
| 11 | use core::fmt; |
| 12 | use core::fmt::{Debug, Formatter}; |
| 13 | use uefi::boot::ScopedProtocol; |
| 14 | |
| 15 | /// Return type for public [`FileSystem`] operations. |
| 16 | pub type FileSystemResult<T> = Result<T, Error>; |
| 17 | |
| 18 | /// High-level file-system abstraction for UEFI volumes with an API that is |
| 19 | /// close to `std::fs`. It acts as convenient accessor around the |
| 20 | /// [`SimpleFileSystemProtocol`]. |
| 21 | /// |
| 22 | /// Please refer to the [module documentation] for more information. |
| 23 | /// |
| 24 | /// [module documentation]: uefi::fs |
| 25 | pub struct FileSystem(ScopedProtocol<SimpleFileSystemProtocol>); |
| 26 | |
| 27 | impl FileSystem { |
| 28 | /// Constructor. |
| 29 | #[must_use] |
| 30 | pub fn new(proto: impl Into<Self>) -> Self { |
| 31 | proto.into() |
| 32 | } |
| 33 | |
| 34 | /// Returns `Ok(true)` if the path points at an existing file. |
| 35 | /// |
| 36 | /// If the file does not exist, `Ok(false)` is returned. If it cannot be |
| 37 | /// determined whether the file exists or not, an error is returned. |
| 38 | pub fn try_exists(&mut self, path: impl AsRef<Path>) -> FileSystemResult<bool> { |
| 39 | match self.open(path.as_ref(), UefiFileMode::Read, false) { |
| 40 | Ok(_) => Ok(true), |
| 41 | Err(Error::Io(err)) => { |
| 42 | if err.uefi_error.status() == Status::NOT_FOUND { |
| 43 | Ok(false) |
| 44 | } else { |
| 45 | Err(Error::Io(err)) |
| 46 | } |
| 47 | } |
| 48 | Err(err) => Err(err), |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | /// Copies the contents of one file to another. Creates the destination file |
| 53 | /// if it doesn't exist and overwrites any content, if it exists. |
| 54 | pub fn copy( |
| 55 | &mut self, |
| 56 | src_path: impl AsRef<Path>, |
| 57 | dest_path: impl AsRef<Path>, |
| 58 | ) -> FileSystemResult<()> { |
| 59 | let src_path = src_path.as_ref(); |
| 60 | let dest_path = dest_path.as_ref(); |
| 61 | |
| 62 | // Open the source file for reading. |
| 63 | let mut src = self |
| 64 | .open(src_path, UefiFileMode::Read, false)? |
| 65 | .into_regular_file() |
| 66 | .ok_or_else(|| { |
| 67 | Error::Io(IoError { |
| 68 | path: src_path.to_path_buf(), |
| 69 | context: IoErrorContext::NotAFile, |
| 70 | uefi_error: Status::INVALID_PARAMETER.into(), |
| 71 | }) |
| 72 | })?; |
| 73 | |
| 74 | // Get the source file's size in bytes. |
| 75 | let src_size = { |
| 76 | let src_info = src.get_boxed_info::<UefiFileInfo>().map_err(|err| { |
| 77 | Error::Io(IoError { |
| 78 | path: src_path.to_path_buf(), |
| 79 | context: IoErrorContext::Metadata, |
| 80 | uefi_error: err, |
| 81 | }) |
| 82 | })?; |
| 83 | src_info.file_size() |
| 84 | }; |
| 85 | |
| 86 | // Try to delete the destination file in case it already exists. Allow |
| 87 | // this to fail, since it might not exist. Or it might exist, but be a |
| 88 | // directory, in which case the error will be caught when trying to |
| 89 | // create the file. |
| 90 | let _ = self.remove_file(dest_path); |
| 91 | |
| 92 | // Create and open the destination file. |
| 93 | let mut dest = self |
| 94 | .open(dest_path, UefiFileMode::CreateReadWrite, false)? |
| 95 | .into_regular_file() |
| 96 | .ok_or_else(|| { |
| 97 | Error::Io(IoError { |
| 98 | path: dest_path.to_path_buf(), |
| 99 | context: IoErrorContext::OpenError, |
| 100 | uefi_error: Status::INVALID_PARAMETER.into(), |
| 101 | }) |
| 102 | })?; |
| 103 | |
| 104 | // 1 MiB copy buffer. |
| 105 | let mut chunk = vec![0; 1024 * 1024]; |
| 106 | |
| 107 | // Read chunks from the source file and write to the destination file. |
| 108 | let mut remaining_size = src_size; |
| 109 | while remaining_size > 0 { |
| 110 | // Read one chunk. |
| 111 | let num_bytes_read = src.read(&mut chunk).map_err(|err| { |
| 112 | Error::Io(IoError { |
| 113 | path: src_path.to_path_buf(), |
| 114 | context: IoErrorContext::ReadFailure, |
| 115 | uefi_error: err.to_err_without_payload(), |
| 116 | }) |
| 117 | })?; |
| 118 | |
| 119 | // If the read returned no bytes, but `remaining_size > 0`, return |
| 120 | // an error. |
| 121 | if num_bytes_read == 0 { |
| 122 | return Err(Error::Io(IoError { |
| 123 | path: src_path.to_path_buf(), |
| 124 | context: IoErrorContext::ReadFailure, |
| 125 | uefi_error: Status::ABORTED.into(), |
| 126 | })); |
| 127 | } |
| 128 | |
| 129 | // Copy the bytes read out to the destination file. |
| 130 | dest.write(&chunk[..num_bytes_read]).map_err(|err| { |
| 131 | Error::Io(IoError { |
| 132 | path: dest_path.to_path_buf(), |
| 133 | context: IoErrorContext::WriteFailure, |
| 134 | uefi_error: err.to_err_without_payload(), |
| 135 | }) |
| 136 | })?; |
| 137 | |
| 138 | remaining_size -= u64::try_from(num_bytes_read).unwrap(); |
| 139 | } |
| 140 | |
| 141 | dest.flush().map_err(|err| { |
| 142 | Error::Io(IoError { |
| 143 | path: dest_path.to_path_buf(), |
| 144 | context: IoErrorContext::FlushFailure, |
| 145 | uefi_error: err, |
| 146 | }) |
| 147 | })?; |
| 148 | |
| 149 | Ok(()) |
| 150 | } |
| 151 | |
| 152 | /// Creates a new, empty directory at the provided path |
| 153 | pub fn create_dir(&mut self, path: impl AsRef<Path>) -> FileSystemResult<()> { |
| 154 | let path = path.as_ref(); |
| 155 | self.open(path, UefiFileMode::CreateReadWrite, true) |
| 156 | .map(|_| ()) |
| 157 | } |
| 158 | |
| 159 | /// Recursively create a directory and all of its parent components if they |
| 160 | /// are missing. |
| 161 | pub fn create_dir_all(&mut self, path: impl AsRef<Path>) -> FileSystemResult<()> { |
| 162 | let path = path.as_ref(); |
| 163 | |
| 164 | // Collect all relevant sub paths in a vector. |
| 165 | let mut dirs_to_create = vec![path.to_path_buf()]; |
| 166 | while let Some(parent) = dirs_to_create.last().unwrap().parent() { |
| 167 | dirs_to_create.push(parent) |
| 168 | } |
| 169 | // Now reverse, so that we have something like this: |
| 170 | // - a |
| 171 | // - a\\b |
| 172 | // - a\\b\\c |
| 173 | dirs_to_create.reverse(); |
| 174 | |
| 175 | for parent in dirs_to_create { |
| 176 | if !self.try_exists(&parent)? { |
| 177 | self.create_dir(parent)?; |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | Ok(()) |
| 182 | } |
| 183 | |
| 184 | /// Given a path, query the file system to get information about a file, |
| 185 | /// directory, etc. Returns [`UefiFileInfo`]. |
| 186 | pub fn metadata(&mut self, path: impl AsRef<Path>) -> FileSystemResult<Box<UefiFileInfo>> { |
| 187 | let path = path.as_ref(); |
| 188 | let mut file = self.open(path, UefiFileMode::Read, false)?; |
| 189 | file.get_boxed_info().map_err(|err| { |
| 190 | Error::Io(IoError { |
| 191 | path: path.to_path_buf(), |
| 192 | context: IoErrorContext::Metadata, |
| 193 | uefi_error: err, |
| 194 | }) |
| 195 | }) |
| 196 | } |
| 197 | |
| 198 | /// Read the entire contents of a file into a bytes vector. |
| 199 | pub fn read(&mut self, path: impl AsRef<Path>) -> FileSystemResult<Vec<u8>> { |
| 200 | let path = path.as_ref(); |
| 201 | |
| 202 | let mut file = self |
| 203 | .open(path, UefiFileMode::Read, false)? |
| 204 | .into_regular_file() |
| 205 | .ok_or_else(|| { |
| 206 | Error::Io(IoError { |
| 207 | path: path.to_path_buf(), |
| 208 | context: IoErrorContext::NotAFile, |
| 209 | // We do not have a real UEFI error here as we have a logical |
| 210 | // problem. |
| 211 | uefi_error: Status::INVALID_PARAMETER.into(), |
| 212 | }) |
| 213 | })?; |
| 214 | |
| 215 | let info = file.get_boxed_info::<UefiFileInfo>().map_err(|err| { |
| 216 | Error::Io(IoError { |
| 217 | path: path.to_path_buf(), |
| 218 | context: IoErrorContext::Metadata, |
| 219 | uefi_error: err, |
| 220 | }) |
| 221 | })?; |
| 222 | |
| 223 | let mut vec = vec![0; info.file_size() as usize]; |
| 224 | let read_bytes = file.read(vec.as_mut_slice()).map_err(|err| { |
| 225 | Error::Io(IoError { |
| 226 | path: path.to_path_buf(), |
| 227 | context: IoErrorContext::ReadFailure, |
| 228 | uefi_error: err.to_err_without_payload(), |
| 229 | }) |
| 230 | })?; |
| 231 | |
| 232 | // we read the whole file at once! |
| 233 | if read_bytes != info.file_size() as usize { |
| 234 | log::error!("Did only read {}/{} bytes", info.file_size(), read_bytes); |
| 235 | } |
| 236 | |
| 237 | Ok(vec) |
| 238 | } |
| 239 | |
| 240 | /// Returns an iterator over the entries within a directory. |
| 241 | pub fn read_dir(&mut self, path: impl AsRef<Path>) -> FileSystemResult<UefiDirectoryIter> { |
| 242 | let path = path.as_ref(); |
| 243 | let dir = self |
| 244 | .open(path, UefiFileMode::Read, false)? |
| 245 | .into_directory() |
| 246 | .ok_or_else(|| { |
| 247 | Error::Io(IoError { |
| 248 | path: path.to_path_buf(), |
| 249 | context: IoErrorContext::NotADirectory, |
| 250 | // We do not have a real UEFI error here as we have a logical |
| 251 | // problem. |
| 252 | uefi_error: Status::INVALID_PARAMETER.into(), |
| 253 | }) |
| 254 | })?; |
| 255 | Ok(UefiDirectoryIter::new(dir)) |
| 256 | } |
| 257 | |
| 258 | /// Read the entire contents of a file into a Rust string. |
| 259 | pub fn read_to_string(&mut self, path: impl AsRef<Path>) -> FileSystemResult<String> { |
| 260 | String::from_utf8(self.read(path)?).map_err(Error::Utf8Encoding) |
| 261 | } |
| 262 | |
| 263 | /// Removes an empty directory. |
| 264 | pub fn remove_dir(&mut self, path: impl AsRef<Path>) -> FileSystemResult<()> { |
| 265 | let path = path.as_ref(); |
| 266 | |
| 267 | let file = self |
| 268 | .open(path, UefiFileMode::ReadWrite, false)? |
| 269 | .into_type() |
| 270 | .unwrap(); |
| 271 | |
| 272 | match file { |
| 273 | UefiFileType::Dir(dir) => dir.delete().map_err(|err| { |
| 274 | Error::Io(IoError { |
| 275 | path: path.to_path_buf(), |
| 276 | context: IoErrorContext::CantDeleteDirectory, |
| 277 | uefi_error: err, |
| 278 | }) |
| 279 | }), |
| 280 | UefiFileType::Regular(_) => { |
| 281 | Err(Error::Io(IoError { |
| 282 | path: path.to_path_buf(), |
| 283 | context: IoErrorContext::NotADirectory, |
| 284 | // We do not have a real UEFI error here as we have a logical |
| 285 | // problem. |
| 286 | uefi_error: Status::INVALID_PARAMETER.into(), |
| 287 | })) |
| 288 | } |
| 289 | } |
| 290 | } |
| 291 | |
| 292 | /// Removes a directory at this path, after removing all its contents. Use |
| 293 | /// carefully! |
| 294 | pub fn remove_dir_all(&mut self, path: impl AsRef<Path>) -> FileSystemResult<()> { |
| 295 | let path = path.as_ref(); |
| 296 | for file_info in self |
| 297 | .read_dir(path)? |
| 298 | .filter_map(|file_info_result| file_info_result.ok()) |
| 299 | { |
| 300 | if COMMON_SKIP_DIRS.contains(&file_info.file_name()) { |
| 301 | continue; |
| 302 | } |
| 303 | |
| 304 | let mut abs_entry_path = PathBuf::new(); |
| 305 | abs_entry_path.push(path); |
| 306 | abs_entry_path.push(file_info.file_name()); |
| 307 | if file_info.is_directory() { |
| 308 | // delete all inner files |
| 309 | // This recursion is fine as there are no links in UEFI/FAT file |
| 310 | // systems. No cycles possible. |
| 311 | self.remove_dir_all(&abs_entry_path)?; |
| 312 | } else { |
| 313 | self.remove_file(abs_entry_path)?; |
| 314 | } |
| 315 | } |
| 316 | // Now that the dir is empty, we delete it as final step. |
| 317 | self.remove_dir(path)?; |
| 318 | Ok(()) |
| 319 | } |
| 320 | |
| 321 | /// Removes a file from the filesystem. |
| 322 | pub fn remove_file(&mut self, path: impl AsRef<Path>) -> FileSystemResult<()> { |
| 323 | let path = path.as_ref(); |
| 324 | |
| 325 | let file = self |
| 326 | .open(path, UefiFileMode::ReadWrite, false)? |
| 327 | .into_type() |
| 328 | .unwrap(); |
| 329 | |
| 330 | match file { |
| 331 | UefiFileType::Regular(file) => file.delete().map_err(|err| { |
| 332 | Error::Io(IoError { |
| 333 | path: path.to_path_buf(), |
| 334 | context: IoErrorContext::CantDeleteFile, |
| 335 | uefi_error: err, |
| 336 | }) |
| 337 | }), |
| 338 | UefiFileType::Dir(_) => Err(Error::Io(IoError { |
| 339 | path: path.to_path_buf(), |
| 340 | context: IoErrorContext::NotAFile, |
| 341 | // We do not have a real UEFI error here as we have a logical |
| 342 | // problem. |
| 343 | uefi_error: Status::INVALID_PARAMETER.into(), |
| 344 | })), |
| 345 | } |
| 346 | } |
| 347 | |
| 348 | /// Rename a file or directory to a new name, replacing the original file if |
| 349 | /// it already exists. |
| 350 | pub fn rename( |
| 351 | &mut self, |
| 352 | src_path: impl AsRef<Path>, |
| 353 | dest_path: impl AsRef<Path>, |
| 354 | ) -> FileSystemResult<()> { |
| 355 | self.copy(&src_path, dest_path)?; |
| 356 | self.remove_file(src_path) |
| 357 | } |
| 358 | |
| 359 | /// Write a slice as the entire contents of a file. This function will |
| 360 | /// create a file if it does not exist, and will entirely replace its |
| 361 | /// contents if it does. |
| 362 | pub fn write( |
| 363 | &mut self, |
| 364 | path: impl AsRef<Path>, |
| 365 | content: impl AsRef<[u8]>, |
| 366 | ) -> FileSystemResult<()> { |
| 367 | let path = path.as_ref(); |
| 368 | |
| 369 | // since there is no .truncate() in UEFI, we delete the file first it it |
| 370 | // exists. |
| 371 | if self.try_exists(path)? { |
| 372 | self.remove_file(path)?; |
| 373 | } |
| 374 | |
| 375 | let mut handle = self |
| 376 | .open(path, UefiFileMode::CreateReadWrite, false)? |
| 377 | .into_regular_file() |
| 378 | .unwrap(); |
| 379 | |
| 380 | handle.write(content.as_ref()).map_err(|err| { |
| 381 | Error::Io(IoError { |
| 382 | path: path.to_path_buf(), |
| 383 | context: IoErrorContext::WriteFailure, |
| 384 | uefi_error: err.to_err_without_payload(), |
| 385 | }) |
| 386 | })?; |
| 387 | handle.flush().map_err(|err| { |
| 388 | Error::Io(IoError { |
| 389 | path: path.to_path_buf(), |
| 390 | context: IoErrorContext::FlushFailure, |
| 391 | uefi_error: err, |
| 392 | }) |
| 393 | })?; |
| 394 | Ok(()) |
| 395 | } |
| 396 | |
| 397 | /// Opens a fresh handle to the root directory of the volume. |
| 398 | fn open_root(&mut self) -> FileSystemResult<UefiDirectoryHandle> { |
| 399 | self.0.open_volume().map_err(|err| { |
| 400 | Error::Io(IoError { |
| 401 | path: { |
| 402 | let mut path = PathBuf::new(); |
| 403 | path.push(SEPARATOR_STR); |
| 404 | path |
| 405 | }, |
| 406 | context: IoErrorContext::CantOpenVolume, |
| 407 | uefi_error: err, |
| 408 | }) |
| 409 | }) |
| 410 | } |
| 411 | |
| 412 | /// Wrapper around [`Self::open_root`] that opens the provided path as |
| 413 | /// absolute path. |
| 414 | /// |
| 415 | /// May create a file if [`UefiFileMode::CreateReadWrite`] is set. May |
| 416 | /// create a directory if [`UefiFileMode::CreateReadWrite`] and `create_dir` |
| 417 | /// is set. The parameter `create_dir` is ignored otherwise. |
| 418 | fn open( |
| 419 | &mut self, |
| 420 | path: &Path, |
| 421 | mode: UefiFileMode, |
| 422 | create_dir: bool, |
| 423 | ) -> FileSystemResult<UefiFileHandle> { |
| 424 | validate_path(path)?; |
| 425 | |
| 426 | let attr = if mode == UefiFileMode::CreateReadWrite && create_dir { |
| 427 | UefiFileAttribute::DIRECTORY |
| 428 | } else { |
| 429 | UefiFileAttribute::empty() |
| 430 | }; |
| 431 | |
| 432 | self.open_root()? |
| 433 | .open(path.to_cstr16(), mode, attr) |
| 434 | .map_err(|err| { |
| 435 | Error::Io(IoError { |
| 436 | path: path.to_path_buf(), |
| 437 | context: IoErrorContext::OpenError, |
| 438 | uefi_error: err, |
| 439 | }) |
| 440 | }) |
| 441 | } |
| 442 | } |
| 443 | |
| 444 | impl Debug for FileSystem { |
| 445 | fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { |
| 446 | let ptr: *const _ = &self.0; |
| 447 | f.debug_tuple("FileSystem").field(&ptr).finish() |
| 448 | } |
| 449 | } |
| 450 | |
| 451 | impl From<ScopedProtocol<SimpleFileSystemProtocol>> for FileSystem { |
| 452 | fn from(proto: ScopedProtocol<SimpleFileSystemProtocol>) -> Self { |
| 453 | Self(proto) |
| 454 | } |
| 455 | } |