interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / vendor / uefi / src / proto / media / file / mod.rs

500 lines · 16607 bytes Raw Blame History
1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3//! This module provides the [`FileHandle`] structure as well as the more
4//! specific [`RegularFile`] and [`Directory`] structures.
5//!
6//! This module also provides the [`File`] trait for opening, querying,
7//! creating, reading, and writing files.
8//!
9//! Usually a file system implementation will return a "root" directory, representing
10//! `/` on that volume. With that directory, it is possible to enumerate and open
11//! all the other files on that volume.
12
13mod dir;
14mod info;
15mod regular;
16
17use crate::{CStr16, Result, Status, StatusExt};
18use core::ffi::c_void;
19use core::fmt::Debug;
20use core::{mem, ptr};
21use uefi_raw::protocol::file_system::{FileMode as RawFileMode, FileProtocolV1};
22
23#[cfg(feature = "alloc")]
24use {crate::mem::make_boxed, alloc::boxed::Box};
25
26pub use dir::Directory;
27pub use info::{
28 FileInfo, FileInfoCreationError, FileProtocolInfo, FileSystemInfo, FileSystemVolumeLabel,
29 FromUefi,
30};
31pub use regular::RegularFile;
32pub use uefi_raw::protocol::file_system::FileAttribute;
33
34/// Common interface to `FileHandle`, `RegularFile`, and `Directory`.
35///
36/// `File` contains all functionality that is safe to perform on any type of
37/// file handle.
38pub trait File: Sized {
39 /// Access the underlying file handle.
40 #[doc(hidden)]
41 fn handle(&mut self) -> &mut FileHandle;
42
43 /// Try to open a file relative to this file.
44 ///
45 /// # Arguments
46 /// * `filename` Path of file to open, relative to this file
47 /// * `open_mode` The mode to open the file with
48 /// * `attributes` Only valid when `FILE_MODE_CREATE` is used as a mode
49 ///
50 /// # Errors
51 ///
52 /// See section `EFI_FILE_PROTOCOL.Open()` in the UEFI Specification for more details.
53 /// Note that [`INVALID_PARAMETER`] is not listed in the specification as one of the
54 /// errors returned by this function, but some implementations (such as EDK2) perform
55 /// additional validation and may return that status for invalid inputs.
56 ///
57 /// [`INVALID_PARAMETER`]: Status::INVALID_PARAMETER
58 ///
59 /// * [`Status::INVALID_PARAMETER`]
60 /// * [`Status::NOT_FOUND`]
61 /// * [`Status::NO_MEDIA`]
62 /// * [`Status::MEDIA_CHANGED`]
63 /// * [`Status::DEVICE_ERROR`]
64 /// * [`Status::VOLUME_CORRUPTED`]
65 /// * [`Status::WRITE_PROTECTED`]
66 /// * [`Status::ACCESS_DENIED`]
67 /// * [`Status::OUT_OF_RESOURCES`]
68 /// * [`Status::VOLUME_FULL`]
69 fn open(
70 &mut self,
71 filename: &CStr16,
72 open_mode: FileMode,
73 attributes: FileAttribute,
74 ) -> Result<FileHandle> {
75 let mut ptr = ptr::null_mut();
76
77 // SAFETY: The memory is valid.
78 unsafe {
79 (self.imp().open)(
80 self.imp(),
81 &mut ptr,
82 filename.as_ptr().cast(),
83 RawFileMode::from_bits_truncate(open_mode as u64),
84 attributes,
85 )
86 }
87 // SAFETY: The memory is valid.
88 .to_result_with_val(|| unsafe { FileHandle::new(ptr) })
89 }
90
91 /// Close this file handle. Same as dropping this structure.
92 fn close(self) {}
93
94 /// Closes and deletes this file
95 ///
96 /// # Warnings
97 ///
98 /// See section `EFI_FILE_PROTOCOL.Delete()` in the UEFI Specification for more details.
99 ///
100 /// * [`Status::WARN_DELETE_FAILURE`]
101 fn delete(mut self) -> Result {
102 // SAFETY: The memory is valid.
103 let result = unsafe { (self.imp().delete)(self.imp()) }.to_result();
104 mem::forget(self);
105 result
106 }
107
108 /// Queries some information about a file
109 ///
110 /// The information will be written into a user-provided buffer.
111 /// If the buffer is too small, the required buffer size will be returned as part of the error.
112 /// That size includes the trailing padding of `Info`, so it may be larger than what the
113 /// firmware reports.
114 ///
115 /// The buffer must be aligned on an `<Info as Align>::alignment()` boundary.
116 ///
117 /// # Arguments
118 /// * `buffer` Buffer that the information should be written into
119 ///
120 /// # Errors
121 ///
122 /// See section `EFI_FILE_PROTOCOL.GetInfo()` in the UEFI Specification for more details.
123 ///
124 /// * [`Status::UNSUPPORTED`]
125 /// * [`Status::NO_MEDIA`]
126 /// * [`Status::DEVICE_ERROR`]
127 /// * [`Status::VOLUME_CORRUPTED`]
128 /// * [`Status::BUFFER_TOO_SMALL`]
129 /// * [`Status::BAD_BUFFER_SIZE`] if the firmware returned an incomplete structure. See
130 /// [`FromUefi::from_uefi`].
131 fn get_info<'buf, Info: FileProtocolInfo + ?Sized>(
132 &mut self,
133 buffer: &'buf mut [u8],
134 ) -> Result<&'buf mut Info, Option<usize>> {
135 let mut buffer_size = buffer.len();
136 Info::assert_aligned(buffer);
137 // SAFETY: The memory is valid.
138 unsafe {
139 (self.imp().get_info)(
140 self.imp(),
141 &Info::GUID,
142 &mut buffer_size,
143 buffer.as_mut_ptr().cast(),
144 )
145 }
146 .to_result_with_err(|s| {
147 if s == Status::BUFFER_TOO_SMALL {
148 // Account for the trailing padding of the Rust type, so that
149 // a buffer of the reported size is accepted by `from_uefi`.
150 Some(Info::round_up_to_alignment(buffer_size))
151 } else {
152 None
153 }
154 })?;
155 Info::from_uefi(buffer, buffer_size)
156 }
157
158 /// Sets some information about a file
159 ///
160 /// There are various restrictions on the information that may be modified using this method.
161 /// The simplest one is that it is usually not possible to call it on read-only media. Further
162 /// restrictions specific to a given information type are described in the corresponding
163 /// `FileProtocolInfo` type documentation.
164 ///
165 /// # Arguments
166 /// * `info` Info that should be set for the file
167 ///
168 /// # Errors
169 ///
170 /// See section `EFI_FILE_PROTOCOL.SetInfo()` in the UEFI Specification for more details.
171 ///
172 /// * [`Status::UNSUPPORTED`]
173 /// * [`Status::NO_MEDIA`]
174 /// * [`Status::DEVICE_ERROR`]
175 /// * [`Status::VOLUME_CORRUPTED`]
176 /// * [`Status::WRITE_PROTECTED`]
177 /// * [`Status::ACCESS_DENIED`]
178 /// * [`Status::VOLUME_FULL`]
179 /// * [`Status::BAD_BUFFER_SIZE`]
180 fn set_info<Info: FileProtocolInfo + ?Sized>(&mut self, info: &Info) -> Result {
181 let info_ptr = ptr::from_ref(info).cast::<c_void>();
182 let info_size = size_of_val(info);
183 // SAFETY: The memory is valid.
184 unsafe { (self.imp().set_info)(self.imp(), &Info::GUID, info_size, info_ptr).to_result() }
185 }
186
187 /// Flushes all modified data associated with the file handle to the device
188 ///
189 /// # Errors
190 ///
191 /// See section `EFI_FILE_PROTOCOL.Flush()` in the UEFI Specification for more details.
192 ///
193 /// * [`Status::NO_MEDIA`]
194 /// * [`Status::DEVICE_ERROR`]
195 /// * [`Status::VOLUME_CORRUPTED`]
196 /// * [`Status::WRITE_PROTECTED`]
197 /// * [`Status::ACCESS_DENIED`]
198 /// * [`Status::VOLUME_FULL`]
199 fn flush(&mut self) -> Result {
200 // SAFETY: The memory is valid.
201 unsafe { (self.imp().flush)(self.imp()) }.to_result()
202 }
203
204 /// Read the dynamically allocated info for a file.
205 #[cfg(feature = "alloc")]
206 fn get_boxed_info<Info: FileProtocolInfo + ?Sized + Debug>(&mut self) -> Result<Box<Info>> {
207 let fetch_data_fn = |buf| self.get_info::<Info>(buf);
208 let file_info = make_boxed::<Info, _>(fetch_data_fn)?;
209 Ok(file_info)
210 }
211
212 /// Returns if the underlying file is a regular file.
213 /// The result is an error if the underlying file was already closed or deleted.
214 ///
215 /// UEFI file system protocol only knows "regular files" and "directories".
216 fn is_regular_file(&self) -> Result<bool>;
217
218 /// Returns if the underlying file is a directory.
219 /// The result is an error if the underlying file was already closed or deleted.
220 ///
221 /// UEFI file system protocol only knows "regular files" and "directories".
222 fn is_directory(&self) -> Result<bool>;
223}
224
225// Internal File helper methods to access the function pointer table.
226trait FileInternal: File {
227 fn imp(&mut self) -> &mut FileProtocolV1 {
228 // SAFETY: The pointer is not null, aligned, and initialized.
229 unsafe { &mut *self.handle().0 }
230 }
231}
232
233impl<T: File> FileInternal for T {}
234
235/// An opaque handle to some contiguous block of data on a volume.
236///
237/// A `FileHandle` is just a wrapper around a UEFI file handle. Under the hood, it can either be a
238/// `RegularFile` or a `Directory`; use the `into_type()` or the unsafe
239/// `{RegularFile, Directory}::new()` methods to perform the conversion.
240///
241/// Dropping this structure will result in the file handle being closed.
242#[repr(transparent)]
243#[derive(Debug)]
244pub struct FileHandle(*mut FileProtocolV1);
245
246impl FileHandle {
247 pub(super) const unsafe fn new(ptr: *mut FileProtocolV1) -> Self {
248 Self(ptr)
249 }
250
251 /// Converts `File` into a more specific subtype based on if it is a
252 /// directory or not. Wrapper around [Self::is_regular_file].
253 pub fn into_type(self) -> Result<FileType> {
254 use FileType::*;
255
256 self.is_regular_file().map(|is_file| {
257 if is_file {
258 // SAFETY: The memory is valid.
259 unsafe { Regular(RegularFile::new(self)) }
260 } else {
261 // SAFETY: The memory is valid.
262 unsafe { Dir(Directory::new(self)) }
263 }
264 })
265 }
266
267 /// If the handle represents a directory, convert it into a
268 /// [`Directory`]. Otherwise returns `None`.
269 #[must_use]
270 pub fn into_directory(self) -> Option<Directory> {
271 if let Ok(FileType::Dir(dir)) = self.into_type() {
272 Some(dir)
273 } else {
274 None
275 }
276 }
277
278 /// If the handle represents a regular file, convert it into a
279 /// [`RegularFile`]. Otherwise returns `None`.
280 #[must_use]
281 pub fn into_regular_file(self) -> Option<RegularFile> {
282 if let Ok(FileType::Regular(regular)) = self.into_type() {
283 Some(regular)
284 } else {
285 None
286 }
287 }
288}
289
290impl File for FileHandle {
291 #[inline]
292 fn handle(&mut self) -> &mut FileHandle {
293 self
294 }
295
296 fn is_regular_file(&self) -> Result<bool> {
297 // SAFETY: The pointer was checked for null just above.
298 let this = unsafe { self.0.as_mut().unwrap() };
299
300 // - get_position fails with EFI_UNSUPPORTED on directories
301 // - result is an error if the underlying file was already closed or deleted.
302 let mut pos = 0;
303 // SAFETY: The memory is valid.
304 match unsafe { (this.get_position)(this, &mut pos) } {
305 Status::SUCCESS => Ok(true),
306 Status::UNSUPPORTED => Ok(false),
307 s => Err(s.into()),
308 }
309 }
310
311 fn is_directory(&self) -> Result<bool> {
312 self.is_regular_file().map(|b| !b)
313 }
314}
315
316impl Drop for FileHandle {
317 fn drop(&mut self) {
318 // SAFETY: The memory is valid.
319 let result: Result = unsafe { (self.imp().close)(self.imp()) }.to_result();
320 // The spec says this always succeeds. Let's not panic in a drop for
321 // higher reliability.
322 if let Err(err) = result {
323 log::error!("Failed to close file: {err:?}");
324 }
325 }
326}
327
328/// Disambiguate the file type. Returned by `File::into_type()`.
329#[derive(Debug)]
330pub enum FileType {
331 /// The file was a regular (data) file.
332 Regular(RegularFile),
333 /// The file was a directory.
334 Dir(Directory),
335}
336
337/// Usage flags describing what is possible to do with the file.
338///
339/// SAFETY: Using a repr(C) enum is safe here because this type is only sent to
340/// the UEFI implementation, and never received from it.
341#[derive(Debug, Copy, Clone, Eq, PartialEq)]
342#[repr(u64)]
343pub enum FileMode {
344 /// The file can be read from
345 Read = 1,
346
347 /// The file can be read from and written to
348 ReadWrite = 2 | 1,
349
350 /// The file can be read, written, and will be created if it does not exist
351 CreateReadWrite = (1 << 63) | 2 | 1,
352}
353
354#[cfg(test)]
355mod tests {
356 use super::*;
357 use crate::runtime::Time;
358 use crate::{CString16, Guid, Identify};
359 use ::alloc::vec;
360 use uefi_raw::protocol::file_system::FileProtocolRevision;
361
362 // Test `get_boxed_info` by setting up a fake file, which is mostly
363 // just function pointers. Most of the functions can be empty, only
364 // get_info is actually implemented to return useful data.
365 #[test]
366 fn test_get_boxed_info() {
367 let mut file_impl = FileProtocolV1 {
368 revision: FileProtocolRevision::REVISION_1,
369 open: stub_open,
370 close: stub_close,
371 delete: stub_delete,
372 read: stub_read,
373 write: stub_write,
374 get_position: stub_get_position,
375 set_position: stub_set_position,
376 get_info: stub_get_info,
377 set_info: stub_set_info,
378 flush: stub_flush,
379 };
380 let file_handle = FileHandle(&mut file_impl);
381
382 // SAFETY: The memory is valid.
383 let mut file = unsafe { RegularFile::new(file_handle) };
384 let info = file.get_boxed_info::<FileInfo>().unwrap();
385 assert_eq!(info.file_size(), 123);
386 assert_eq!(info.file_name(), CString16::try_from("test_file").unwrap());
387 }
388
389 unsafe extern "efiapi" fn stub_get_info(
390 _this: *mut FileProtocolV1,
391 information_type: *const Guid,
392 buffer_size: *mut usize,
393 buffer: *mut c_void,
394 ) -> Status {
395 // SAFETY: The memory is valid.
396 assert_eq!(unsafe { *information_type }, FileInfo::GUID);
397
398 // Use a temporary buffer to get some file info, then copy that
399 // data to the output buffer.
400 let mut tmp = vec![0; 128];
401 let file_size = 123;
402 let physical_size = 456;
403 let time = Time::invalid();
404 let info = FileInfo::new(
405 &mut tmp,
406 file_size,
407 physical_size,
408 time,
409 time,
410 time,
411 FileAttribute::empty(),
412 &CString16::try_from("test_file").unwrap(),
413 )
414 .unwrap();
415 let required_size = size_of_val(info);
416 // SAFETY: The memory is valid.
417 if unsafe { *buffer_size } < required_size {
418 // SAFETY: The memory is valid.
419 unsafe {
420 *buffer_size = required_size;
421 }
422 Status::BUFFER_TOO_SMALL
423 } else {
424 // SAFETY: The memory is valid.
425 unsafe {
426 ptr::copy_nonoverlapping(
427 ptr::from_ref::<FileInfo>(info).cast(),
428 buffer,
429 required_size,
430 );
431 }
432 // SAFETY: The memory is valid.
433 unsafe {
434 *buffer_size = required_size;
435 }
436 Status::SUCCESS
437 }
438 }
439
440 const extern "efiapi" fn stub_open(
441 _this: *mut FileProtocolV1,
442 _new_handle: *mut *mut FileProtocolV1,
443 _filename: *const uefi_raw::Char16,
444 _open_mode: RawFileMode,
445 _attributes: FileAttribute,
446 ) -> Status {
447 Status::UNSUPPORTED
448 }
449
450 const extern "efiapi" fn stub_close(_this: *mut FileProtocolV1) -> Status {
451 Status::SUCCESS
452 }
453
454 const extern "efiapi" fn stub_delete(_this: *mut FileProtocolV1) -> Status {
455 Status::UNSUPPORTED
456 }
457
458 const extern "efiapi" fn stub_read(
459 _this: *mut FileProtocolV1,
460 _buffer_size: *mut usize,
461 _buffer: *mut c_void,
462 ) -> Status {
463 Status::UNSUPPORTED
464 }
465
466 const extern "efiapi" fn stub_write(
467 _this: *mut FileProtocolV1,
468 _buffer_size: *mut usize,
469 _buffer: *const c_void,
470 ) -> Status {
471 Status::UNSUPPORTED
472 }
473
474 const extern "efiapi" fn stub_get_position(
475 _this: *const FileProtocolV1,
476 _position: *mut u64,
477 ) -> Status {
478 Status::UNSUPPORTED
479 }
480
481 const extern "efiapi" fn stub_set_position(
482 _this: *mut FileProtocolV1,
483 _position: u64,
484 ) -> Status {
485 Status::UNSUPPORTED
486 }
487
488 const extern "efiapi" fn stub_set_info(
489 _this: *mut FileProtocolV1,
490 _information_type: *const Guid,
491 _buffer_size: usize,
492 _buffer: *const c_void,
493 ) -> Status {
494 Status::UNSUPPORTED
495 }
496
497 const extern "efiapi" fn stub_flush(_this: *mut FileProtocolV1) -> Status {
498 Status::UNSUPPORTED
499 }
500}