|
| 1 | +//! Load file support protocols. |
| 2 | +
|
| 3 | +#[cfg(feature = "alloc")] |
| 4 | +use alloc::vec::Vec; |
| 5 | + |
| 6 | +use crate::proto::device_path::{FfiDevicePath, DevicePath}; |
| 7 | +use crate::proto::unsafe_protocol; |
| 8 | +use crate::{Result, Status}; |
| 9 | +use core::ffi::c_void; |
| 10 | +use core::ptr; |
| 11 | + |
| 12 | +/// The UEFI LoadFile2 protocol. |
| 13 | +/// |
| 14 | +/// This protocol has a single method to load a file according to some |
| 15 | +/// device path. |
| 16 | +/// |
| 17 | +/// This interface is implemented by many devices, e.g. network and filesystems. |
| 18 | +#[derive(Debug)] |
| 19 | +#[repr(transparent)] |
| 20 | +#[unsafe_protocol(uefi_raw::protocol::media::LoadFile2::GUID)] |
| 21 | +pub struct LoadFile2(uefi_raw::protocol::media::LoadFile2); |
| 22 | + |
| 23 | +impl LoadFile2 { |
| 24 | + /// Load file addressed by provided device path |
| 25 | + pub fn load_file(&mut self, |
| 26 | + file_path: &DevicePath, |
| 27 | + buffer: &mut [u8] |
| 28 | + ) -> Result<(), usize> { |
| 29 | + let mut buffer_size = buffer.len(); |
| 30 | + unsafe { |
| 31 | + (self.0.load_file)(self, |
| 32 | + file_path, |
| 33 | + false, |
| 34 | + buffer_size, |
| 35 | + buffer.as_mut_ptr() |
| 36 | + ) |
| 37 | + }.to_result_with( |
| 38 | + || debug_assert_eq!(buffer_size, buffer.len()), |
| 39 | + |_| buffer_size |
| 40 | + ) |
| 41 | + } |
| 42 | + |
| 43 | + #[cfg(feature = "alloc")] |
| 44 | + /// Load file addressed by the provided device path. |
| 45 | + pub fn load_file_to_vec(&mut self, |
| 46 | + file_path: &DevicePath, |
| 47 | + ) -> Result<Vec<u8>> { |
| 48 | + let mut buffer_size: usize = 0; |
| 49 | + let mut status: Status; |
| 50 | + unsafe { |
| 51 | + status = (self.0.load_file)(self, |
| 52 | + file_path.as_ffi_ptr(), |
| 53 | + false, |
| 54 | + ptr::addr_of_mut!(buffer_size), |
| 55 | + ptr::null_mut() |
| 56 | + ); |
| 57 | + } |
| 58 | + |
| 59 | + if status.is_error() { |
| 60 | + return Err(status.into()); |
| 61 | + } |
| 62 | + |
| 63 | + let mut buffer: Vec<u8> = Vec::with_capacity(buffer_size); |
| 64 | + unsafe { |
| 65 | + status = (self.0.load_file)(self, |
| 66 | + file_path.as_ffi_ptr(), |
| 67 | + false, |
| 68 | + ptr::addr_of_mut!(buffer_size), |
| 69 | + buffer.as_mut_ptr() as *mut c_void |
| 70 | + ); |
| 71 | + } |
| 72 | + |
| 73 | + if status.is_error() { |
| 74 | + return Err(status.into()); |
| 75 | + } |
| 76 | + |
| 77 | + Ok(buffer) |
| 78 | + } |
| 79 | +} |
0 commit comments