Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienux/blob/main/vendor/uefi/src/proto/media/file/regular.rs # aienux Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aienux / vendor / uefi / src / proto / media / file / regular.rs` 303 lines ยท 10445 bytes Raw Blame History 1 // SPDX-License-Identifier: MIT OR Apache-2.0 2 3 use super::{File, FileHandle, FileInternal}; 4 use crate::{Error, Result, Status, StatusExt}; 5 6 /// A `FileHandle` that is also a regular (data) file. 7 /// 8 /// Use `FileHandle::into_type` or `RegularFile::new` to create a `RegularFile`. 9 /// In addition to supporting the normal `File` operations, `RegularFile` 10 /// supports direct reading and writing. 11 #[repr(transparent)] 12 #[derive(Debug)] 13 pub struct RegularFile(FileHandle); 14 15 impl RegularFile { 16 /// A special position used to seek to the end of a file with `set_position()`. 17 pub const END_OF_FILE: u64 = u64::MAX; 18 19 /// Coverts a `FileHandle` into a `RegularFile` without checking the file kind. 20 /// # Safety 21 /// This function should only be called on handles which ARE NOT directories, 22 /// doing otherwise is unsafe. 23 #[must_use] 24 pub const unsafe fn new(handle: FileHandle) -> Self { 25 Self(handle) 26 } 27 28 /// Read data from file. 29 /// 30 /// Try to read as much as possible into `buffer`. Returns the number of bytes that were 31 /// actually read. 32 /// 33 /// # Arguments 34 /// * `buffer` The target buffer of the read operation 35 /// 36 /// # Errors 37 /// 38 /// See section `EFI_FILE_PROTOCOL.Read()` in the UEFI Specification for more details. 39 /// 40 /// * [`Status::NO_MEDIA`] 41 /// * [`Status::DEVICE_ERROR`] 42 /// * [`Status::VOLUME_CORRUPTED`] 43 /// 44 /// # Quirks 45 /// 46 /// Some UEFI implementations have a bug where large reads will incorrectly 47 /// return an error. This function avoids that bug by reading in chunks of 48 /// no more than 1 MiB. This is handled internally within the function; 49 /// callers can safely pass in a buffer of any size. See 50 /// for more information. 51 pub fn read(&mut self, buffer: &mut [u8]) -> Result { 52 let chunk_size = 1024 * 1024; 53 54 // SAFETY: The memory is valid. 55 read_chunked(buffer, chunk_size, |buf, buf_size| unsafe { 56 (self.imp().read)(self.imp(), buf_size, buf.cast()) 57 }) 58 } 59 60 /// Internal method for reading without chunking. This is used to implement 61 /// `Directory::read_entry`. 62 pub(super) fn read_unchunked(&mut self, buffer: &mut [u8]) -> Result> { 63 let mut buffer_size = buffer.len(); 64 let status = 65 // SAFETY: The memory is valid. 66 unsafe { (self.imp().read)(self.imp(), &mut buffer_size, buffer.as_mut_ptr().cast()) }; 67 68 status.to_result_with( 69 || buffer_size, 70 |s| { 71 if s == Status::BUFFER_TOO_SMALL { 72 // `buffer_size` was updated to the required buffer size by the underlying read 73 // function. 74 Some(buffer_size) 75 } else { 76 None 77 } 78 }, 79 ) 80 } 81 82 /// Write data to file 83 /// 84 /// Write `buffer` to file, increment the file pointer. 85 /// 86 /// If an error occurs, returns the number of bytes that were actually written. If no error 87 /// occurred, the entire buffer is guaranteed to have been written successfully. 88 /// 89 /// # Arguments 90 /// * `buffer` Buffer to write to file 91 /// 92 /// # Errors 93 /// 94 /// See section `EFI_FILE_PROTOCOL.Write()` in the UEFI Specification for more details. 95 /// 96 /// * [`Status::NO_MEDIA`] 97 /// * [`Status::DEVICE_ERROR`] 98 /// * [`Status::VOLUME_CORRUPTED`] 99 /// * [`Status::WRITE_PROTECTED`] 100 /// * [`Status::ACCESS_DENIED`] 101 /// * [`Status::VOLUME_FULL`] 102 pub fn write(&mut self, buffer: &[u8]) -> Result<(), usize> { 103 let mut buffer_size = buffer.len(); 104 // SAFETY: The memory is valid. 105 unsafe { (self.imp().write)(self.imp(), &mut buffer_size, buffer.as_ptr().cast()) } 106 .to_result_with_err(|_| buffer_size) 107 } 108 109 /// Get the file's current position 110 /// 111 /// # Errors 112 /// 113 /// See section `EFI_FILE_PROTOCOL.GetPosition()` in the UEFI Specification for more details. 114 /// 115 /// * [`Status::DEVICE_ERROR`] 116 pub fn get_position(&mut self) -> Result { 117 let mut pos = 0u64; 118 // SAFETY: The memory is valid. 119 unsafe { (self.imp().get_position)(self.imp(), &mut pos) }.to_result_with_val(|| pos) 120 } 121 122 /// Sets the file's current position 123 /// 124 /// Set the position of this file handle to the absolute position specified by `position`. 125 /// 126 /// Seeking past the end of the file is allowed, it will trigger file growth on the next write. 127 /// Using a position of RegularFile::END_OF_FILE will seek to the end of the file. 128 /// 129 /// # Arguments 130 /// * `position` The new absolution position of the file handle 131 /// 132 /// # Errors 133 /// 134 /// See section `EFI_FILE_PROTOCOL.SetPosition()` in the UEFI Specification for more details. 135 /// 136 /// * [`Status::DEVICE_ERROR`] 137 pub fn set_position(&mut self, position: u64) -> Result { 138 // SAFETY: The memory is valid. 139 unsafe { (self.imp().set_position)(self.imp(), position) }.to_result() 140 } 141 } 142 143 impl File for RegularFile { 144 #[inline] 145 fn handle(&mut self) -> &mut FileHandle { 146 &mut self.0 147 } 148 149 fn is_regular_file(&self) -> Result { 150 Ok(true) 151 } 152 153 fn is_directory(&self) -> Result { 154 Ok(false) 155 } 156 } 157 158 /// Read data into `buffer` in chunks of `chunk_size`. Reading is done by 159 /// calling `read`, which takes a pointer to a byte buffer and the buffer's 160 /// size. 161 /// 162 /// See [`RegularFile::read`] for details of why reading in chunks is needed. 163 /// 164 /// This separate function exists for easier unit testing. 165 fn read_chunked(buffer: &mut [u8], chunk_size: usize, mut read: F) -> Result 166 where 167 F: FnMut(*mut u8, &mut usize) -> Status, 168 { 169 let mut remaining_size = buffer.len(); 170 let mut total_read_size = 0; 171 let mut output_ptr = buffer.as_mut_ptr(); 172 173 while remaining_size > 0 { 174 let requested_read_size = remaining_size.min(chunk_size); 175 176 let mut read_size = requested_read_size; 177 let status = read(output_ptr, &mut read_size); 178 179 if status.is_success() { 180 // Never trust a firmware-reported length larger than what we 181 // requested; otherwise the pointer/size arithmetic below would 182 // run out of bounds. 183 let read_size = read_size.min(requested_read_size); 184 total_read_size += read_size; 185 remaining_size -= read_size; 186 // SAFETY: The memory is valid. 187 output_ptr = unsafe { output_ptr.add(read_size) }; 188 189 // Exit the loop if there's nothing left to read. 190 if read_size < requested_read_size { 191 break; 192 } 193 } else { 194 return Err(Error::new(status, ())); 195 } 196 } 197 198 Ok(total_read_size) 199 } 200 201 #[cfg(test)] 202 mod tests { 203 use super::*; 204 use alloc::rc::Rc; 205 use alloc::vec; 206 use alloc::vec::Vec; 207 use core::cell::RefCell; 208 209 #[derive(Default)] 210 struct TestFile { 211 // Use `Rc` so that we can modify via an immutable ref, makes 212 // the test simpler to implement. 213 data: Rc>>, 214 offset: Rc>, 215 } 216 217 impl TestFile { 218 fn read(&self, buffer: *mut u8, buffer_size: &mut usize) -> Status { 219 let mut offset = self.offset.borrow_mut(); 220 let data = self.data.borrow(); 221 222 let remaining_data_size = data.len() - *offset; 223 let size_to_read = remaining_data_size.min(*buffer_size); 224 // SAFETY: The memory is valid. 225 unsafe { buffer.copy_from(data.as_ptr().add(*offset), size_to_read) }; 226 *offset += size_to_read; 227 *buffer_size = size_to_read; 228 Status::SUCCESS 229 } 230 231 fn reset(&self) { 232 *self.data.borrow_mut() = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 233 *self.offset.borrow_mut() = 0; 234 } 235 } 236 237 /// Test reading a regular file. 238 #[test] 239 fn test_file_read_chunked() { 240 let file = TestFile::default(); 241 let read = |buf, buf_size: &mut usize| file.read(buf, buf_size); 242 243 // Chunk size equal to the data size. 244 file.reset(); 245 let mut buffer = [0; 10]; 246 assert_eq!(read_chunked(&mut buffer, 10, read), Ok(10)); 247 assert_eq!(buffer.as_slice(), *file.data.borrow()); 248 249 // Chunk size smaller than the data size. 250 file.reset(); 251 let mut buffer = [0; 10]; 252 assert_eq!(read_chunked(&mut buffer, 2, read), Ok(10)); 253 assert_eq!(buffer.as_slice(), *file.data.borrow()); 254 255 // Chunk size bigger than the data size. 256 file.reset(); 257 let mut buffer = [0; 10]; 258 assert_eq!(read_chunked(&mut buffer, 20, read), Ok(10)); 259 assert_eq!(buffer.as_slice(), *file.data.borrow()); 260 261 // Buffer smaller than the full file. 262 file.reset(); 263 let mut buffer = [0; 4]; 264 assert_eq!(read_chunked(&mut buffer, 10, read), Ok(4)); 265 assert_eq!(buffer.as_slice(), [1, 2, 3, 4]); 266 267 // Buffer bigger than the full file. 268 file.reset(); 269 let mut buffer = [0; 20]; 270 assert_eq!(read_chunked(&mut buffer, 10, read), Ok(10)); 271 assert_eq!( 272 buffer, 273 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 274 ); 275 276 // Empty buffer. 277 file.reset(); 278 let mut buffer = []; 279 assert_eq!(read_chunked(&mut buffer, 10, read), Ok(0)); 280 assert_eq!(buffer, []); 281 282 // Empty file. 283 file.reset(); 284 file.data.borrow_mut().clear(); 285 let mut buffer = [0; 10]; 286 assert_eq!(read_chunked(&mut buffer, 10, read), Ok(0)); 287 assert_eq!(buffer, [0; 10]); 288 } 289 290 // Regression test: a callback (i.e. firmware) reporting a read length 291 // larger than requested must not cause `remaining_size` to underflow or 292 // `output_ptr` to walk out of bounds. The over-reported length is clamped. 293 #[test] 294 fn test_file_read_chunked_over_report() { 295 // A misbehaving read that always reports 2 bytes more than requested. 296 let read = |_buf: *mut u8, buf_size: &mut usize| { 297 *buf_size += 2; 298 Status::SUCCESS 299 }; 300 let mut buffer = [0u8; 8]; 301 assert_eq!(read_chunked(&mut buffer, 4, read), Ok(8)); 302 } 303 }