diff --git a/CHANGELOG.md b/CHANGELOG.md index 63bc45a32..a7139be87 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,6 +30,11 @@ - `Image::get_image_file_system` now returns a `fs::FileSystem` instead of the protocol. - `CString16::default` now always contains a null character. +- Conversion from `Status` to `Result` has been reworked. The `into_with`, + `into_with_val`, and `into_with_err` methods have been removed from + `Status`. `impl From for Result` has also been removed. A new + `StatusExt` trait has been added that provides conversion methods to replace + the ones that have been removed. `StatusExt` has been added to the prelude. ## uefi-macros - [Unreleased] diff --git a/uefi-raw/src/lib.rs b/uefi-raw/src/lib.rs index 92021688d..4ab69dca3 100644 --- a/uefi-raw/src/lib.rs +++ b/uefi-raw/src/lib.rs @@ -16,3 +16,7 @@ #[macro_use] mod enums; + +mod status; + +pub use status::Status; diff --git a/uefi-raw/src/status.rs b/uefi-raw/src/status.rs new file mode 100644 index 000000000..531e0579a --- /dev/null +++ b/uefi-raw/src/status.rs @@ -0,0 +1,129 @@ +use core::fmt::Debug; + +newtype_enum! { +/// UEFI uses status codes in order to report successes, errors, and warnings. +/// +/// The spec allows implementation-specific status codes, so the `Status` +/// constants are not a comprehensive list of all possible values. +#[must_use] +pub enum Status: usize => { + /// The operation completed successfully. + SUCCESS = 0, + + /// The string contained characters that could not be rendered and were skipped. + WARN_UNKNOWN_GLYPH = 1, + /// The handle was closed, but the file was not deleted. + WARN_DELETE_FAILURE = 2, + /// The handle was closed, but the data to the file was not flushed properly. + WARN_WRITE_FAILURE = 3, + /// The resulting buffer was too small, and the data was truncated. + WARN_BUFFER_TOO_SMALL = 4, + /// The data has not been updated within the timeframe set by local policy. + WARN_STALE_DATA = 5, + /// The resulting buffer contains UEFI-compliant file system. + WARN_FILE_SYSTEM = 6, + /// The operation will be processed across a system reset. + WARN_RESET_REQUIRED = 7, + + /// The image failed to load. + LOAD_ERROR = Self::ERROR_BIT | 1, + /// A parameter was incorrect. + INVALID_PARAMETER = Self::ERROR_BIT | 2, + /// The operation is not supported. + UNSUPPORTED = Self::ERROR_BIT | 3, + /// The buffer was not the proper size for the request. + BAD_BUFFER_SIZE = Self::ERROR_BIT | 4, + /// The buffer is not large enough to hold the requested data. + /// The required buffer size is returned in the appropriate parameter. + BUFFER_TOO_SMALL = Self::ERROR_BIT | 5, + /// There is no data pending upon return. + NOT_READY = Self::ERROR_BIT | 6, + /// The physical device reported an error while attempting the operation. + DEVICE_ERROR = Self::ERROR_BIT | 7, + /// The device cannot be written to. + WRITE_PROTECTED = Self::ERROR_BIT | 8, + /// A resource has run out. + OUT_OF_RESOURCES = Self::ERROR_BIT | 9, + /// An inconstency was detected on the file system. + VOLUME_CORRUPTED = Self::ERROR_BIT | 10, + /// There is no more space on the file system. + VOLUME_FULL = Self::ERROR_BIT | 11, + /// The device does not contain any medium to perform the operation. + NO_MEDIA = Self::ERROR_BIT | 12, + /// The medium in the device has changed since the last access. + MEDIA_CHANGED = Self::ERROR_BIT | 13, + /// The item was not found. + NOT_FOUND = Self::ERROR_BIT | 14, + /// Access was denied. + ACCESS_DENIED = Self::ERROR_BIT | 15, + /// The server was not found or did not respond to the request. + NO_RESPONSE = Self::ERROR_BIT | 16, + /// A mapping to a device does not exist. + NO_MAPPING = Self::ERROR_BIT | 17, + /// The timeout time expired. + TIMEOUT = Self::ERROR_BIT | 18, + /// The protocol has not been started. + NOT_STARTED = Self::ERROR_BIT | 19, + /// The protocol has already been started. + ALREADY_STARTED = Self::ERROR_BIT | 20, + /// The operation was aborted. + ABORTED = Self::ERROR_BIT | 21, + /// An ICMP error occurred during the network operation. + ICMP_ERROR = Self::ERROR_BIT | 22, + /// A TFTP error occurred during the network operation. + TFTP_ERROR = Self::ERROR_BIT | 23, + /// A protocol error occurred during the network operation. + PROTOCOL_ERROR = Self::ERROR_BIT | 24, + /// The function encountered an internal version that was + /// incompatible with a version requested by the caller. + INCOMPATIBLE_VERSION = Self::ERROR_BIT | 25, + /// The function was not performed due to a security violation. + SECURITY_VIOLATION = Self::ERROR_BIT | 26, + /// A CRC error was detected. + CRC_ERROR = Self::ERROR_BIT | 27, + /// Beginning or end of media was reached + END_OF_MEDIA = Self::ERROR_BIT | 28, + /// The end of the file was reached. + END_OF_FILE = Self::ERROR_BIT | 31, + /// The language specified was invalid. + INVALID_LANGUAGE = Self::ERROR_BIT | 32, + /// The security status of the data is unknown or compromised and + /// the data must be updated or replaced to restore a valid security status. + COMPROMISED_DATA = Self::ERROR_BIT | 33, + /// There is an address conflict address allocation + IP_ADDRESS_CONFLICT = Self::ERROR_BIT | 34, + /// A HTTP error occurred during the network operation. + HTTP_ERROR = Self::ERROR_BIT | 35, +}} + +impl Status { + /// Bit indicating that an UEFI status code is an error. + pub const ERROR_BIT: usize = 1 << (core::mem::size_of::() * 8 - 1); + + /// Returns true if status code indicates success. + #[inline] + #[must_use] + pub fn is_success(self) -> bool { + self == Status::SUCCESS + } + + /// Returns true if status code indicates a warning. + #[inline] + #[must_use] + pub fn is_warning(self) -> bool { + (self != Status::SUCCESS) && (self.0 & Self::ERROR_BIT == 0) + } + + /// Returns true if the status code indicates an error. + #[inline] + #[must_use] + pub const fn is_error(self) -> bool { + self.0 & Self::ERROR_BIT != 0 + } +} + +impl core::fmt::Display for Status { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + Debug::fmt(self, f) + } +} diff --git a/uefi-services/src/lib.rs b/uefi-services/src/lib.rs index f1350935a..24c720974 100644 --- a/uefi-services/src/lib.rs +++ b/uefi-services/src/lib.rs @@ -82,7 +82,7 @@ pub fn init(st: &mut SystemTable) -> Result { unsafe { // Avoid double initialization. if SYSTEM_TABLE.is_some() { - return Status::SUCCESS.into(); + return Status::SUCCESS.to_result(); } // Setup the system table singleton diff --git a/uefi/src/lib.rs b/uefi/src/lib.rs index a1e637674..5f8f8d9ab 100644 --- a/uefi/src/lib.rs +++ b/uefi/src/lib.rs @@ -103,7 +103,7 @@ pub use self::data_types::{CStr16, CStr8, Char16, Char8, Event, Guid, Handle, Id pub use uefi_macros::{cstr16, cstr8, entry, guid}; mod result; -pub use self::result::{Error, Result, ResultExt, Status}; +pub use self::result::{Error, Result, ResultExt, Status, StatusExt}; pub mod table; diff --git a/uefi/src/mem.rs b/uefi/src/mem.rs index 939913335..bd6d3794a 100644 --- a/uefi/src/mem.rs +++ b/uefi/src/mem.rs @@ -108,7 +108,7 @@ pub(crate) fn make_boxed< #[cfg(test)] mod tests { use super::*; - use crate::ResultExt; + use crate::{ResultExt, StatusExt}; #[cfg(feature = "unstable")] use alloc::alloc::Global; use core::mem::{align_of, size_of}; @@ -146,7 +146,7 @@ mod tests { if buf.len() < required_size { // We can use an zero-length buffer to find the required size. - return Status::BUFFER_TOO_SMALL.into_with(|| panic!(), |_| Some(required_size)); + return Status::BUFFER_TOO_SMALL.to_result_with(|| panic!(), |_| Some(required_size)); }; // assert alignment diff --git a/uefi/src/prelude.rs b/uefi/src/prelude.rs index 3a5dac089..644acbe40 100644 --- a/uefi/src/prelude.rs +++ b/uefi/src/prelude.rs @@ -2,7 +2,7 @@ //! //! This includes the system table types, `Status` codes, etc. -pub use crate::{Handle, ResultExt, Status}; +pub use crate::{Handle, ResultExt, Status, StatusExt}; // Import the basic table types. pub use crate::table::boot::BootServices; diff --git a/uefi/src/proto/console/gop.rs b/uefi/src/proto/console/gop.rs index e12c7ddc0..7617324e2 100644 --- a/uefi/src/proto/console/gop.rs +++ b/uefi/src/proto/console/gop.rs @@ -52,7 +52,7 @@ use crate::proto::unsafe_protocol; use crate::util::usize_from_u32; -use crate::{Result, Status}; +use crate::{Result, Status, StatusExt}; use core::fmt::{Debug, Formatter}; use core::marker::PhantomData; use core::{mem, ptr}; @@ -94,7 +94,7 @@ impl GraphicsOutput { let mut info_sz = 0; let mut info = ptr::null(); - (self.query_mode)(self, index, &mut info_sz, &mut info).into_with_val(|| { + (self.query_mode)(self, index, &mut info_sz, &mut info).to_result_with_val(|| { let info = unsafe { *info }; Mode { index, @@ -119,7 +119,7 @@ impl GraphicsOutput { /// /// This function will invalidate the current framebuffer. pub fn set_mode(&mut self, mode: &Mode) -> Result { - (self.set_mode)(self, mode.index).into() + (self.set_mode)(self, mode.index).to_result() } /// Performs a blt (block transfer) operation on the frame buffer. @@ -147,7 +147,7 @@ impl GraphicsOutput { height, 0, ) - .into() + .to_result() } BltOp::VideoToBltBuffer { buffer, @@ -170,7 +170,7 @@ impl GraphicsOutput { height, 0, ) - .into(), + .to_result(), BltRegion::SubRectangle { coords: (dest_x, dest_y), px_stride, @@ -186,7 +186,7 @@ impl GraphicsOutput { height, px_stride * core::mem::size_of::(), ) - .into(), + .to_result(), } } BltOp::BufferToVideo { @@ -210,7 +210,7 @@ impl GraphicsOutput { height, 0, ) - .into(), + .to_result(), BltRegion::SubRectangle { coords: (src_x, src_y), px_stride, @@ -226,7 +226,7 @@ impl GraphicsOutput { height, px_stride * core::mem::size_of::(), ) - .into(), + .to_result(), } } BltOp::VideoToVideo { @@ -248,7 +248,7 @@ impl GraphicsOutput { height, 0, ) - .into() + .to_result() } } } diff --git a/uefi/src/proto/console/pointer/mod.rs b/uefi/src/proto/console/pointer/mod.rs index b15549c80..892b4cf6c 100644 --- a/uefi/src/proto/console/pointer/mod.rs +++ b/uefi/src/proto/console/pointer/mod.rs @@ -1,7 +1,7 @@ //! Pointer device access. use crate::proto::unsafe_protocol; -use crate::{Event, Result, Status}; +use crate::{Event, Result, Status, StatusExt}; use core::mem::MaybeUninit; /// Provides information about a pointer device. @@ -24,7 +24,7 @@ impl Pointer { /// /// - `DeviceError` if the device is malfunctioning and cannot be reset. pub fn reset(&mut self, extended_verification: bool) -> Result { - (self.reset)(self, extended_verification).into() + (self.reset)(self, extended_verification).to_result() } /// Retrieves the pointer device's current state, if a state change occurred @@ -40,7 +40,7 @@ impl Pointer { match (self.get_state)(self, pointer_state.as_mut_ptr()) { Status::NOT_READY => Ok(None), - other => other.into_with_val(|| unsafe { Some(pointer_state.assume_init()) }), + other => other.to_result_with_val(|| unsafe { Some(pointer_state.assume_init()) }), } } diff --git a/uefi/src/proto/console/serial.rs b/uefi/src/proto/console/serial.rs index dbb0b8cc9..b748e0618 100644 --- a/uefi/src/proto/console/serial.rs +++ b/uefi/src/proto/console/serial.rs @@ -3,7 +3,7 @@ use core::fmt::Write; use crate::proto::unsafe_protocol; -use crate::{Result, Status}; +use crate::{Result, Status, StatusExt}; use bitflags::bitflags; /// Provides access to a serial I/O device. @@ -39,7 +39,7 @@ pub struct Serial { impl Serial { /// Reset the device. pub fn reset(&mut self) -> Result { - (self.reset)(self).into() + (self.reset)(self).to_result() } /// Returns the current I/O mode. @@ -71,13 +71,13 @@ impl Serial { mode.data_bits as u8, mode.stop_bits, ) - .into() + .to_result() } /// Retrieve the device's current control bits. pub fn get_control_bits(&self) -> Result { let mut bits = ControlBits::empty(); - (self.get_control_bits)(self, &mut bits).into_with_val(|| bits) + (self.get_control_bits)(self, &mut bits).to_result_with_val(|| bits) } /// Sets the device's new control bits. @@ -85,7 +85,7 @@ impl Serial { /// Not all bits can be modified with this function. A mask of the allowed /// bits is stored in the [`ControlBits::SETTABLE`] constant. pub fn set_control_bits(&mut self, bits: ControlBits) -> Result { - (self.set_control_bits)(self, bits).into() + (self.set_control_bits)(self, bits).to_result() } /// Reads data from this device. @@ -95,7 +95,7 @@ impl Serial { /// bytes were actually read from the device. pub fn read(&mut self, data: &mut [u8]) -> Result<(), usize> { let mut buffer_size = data.len(); - unsafe { (self.read)(self, &mut buffer_size, data.as_mut_ptr()) }.into_with( + unsafe { (self.read)(self, &mut buffer_size, data.as_mut_ptr()) }.to_result_with( || debug_assert_eq!(buffer_size, data.len()), |_| buffer_size, ) @@ -108,7 +108,7 @@ impl Serial { /// were actually written to the device. pub fn write(&mut self, data: &[u8]) -> Result<(), usize> { let mut buffer_size = data.len(); - unsafe { (self.write)(self, &mut buffer_size, data.as_ptr()) }.into_with( + unsafe { (self.write)(self, &mut buffer_size, data.as_ptr()) }.to_result_with( || debug_assert_eq!(buffer_size, data.len()), |_| buffer_size, ) diff --git a/uefi/src/proto/console/text/input.rs b/uefi/src/proto/console/text/input.rs index 140096560..7888e9bff 100644 --- a/uefi/src/proto/console/text/input.rs +++ b/uefi/src/proto/console/text/input.rs @@ -1,5 +1,5 @@ use crate::proto::unsafe_protocol; -use crate::{Char16, Event, Result, Status}; +use crate::{Char16, Event, Result, Status, StatusExt}; use core::mem::MaybeUninit; /// Interface for text-based input devices. @@ -21,7 +21,7 @@ impl Input { /// /// - `DeviceError` if the device is malfunctioning and cannot be reset. pub fn reset(&mut self, extended_verification: bool) -> Result { - (self.reset)(self, extended_verification).into() + (self.reset)(self, extended_verification).to_result() } /// Reads the next keystroke from the input device, if any. @@ -77,7 +77,7 @@ impl Input { match (self.read_key_stroke)(self, key.as_mut_ptr()) { Status::NOT_READY => Ok(None), - other => other.into_with_val(|| Some(unsafe { key.assume_init() }.into())), + other => other.to_result_with_val(|| Some(unsafe { key.assume_init() }.into())), } } diff --git a/uefi/src/proto/console/text/output.rs b/uefi/src/proto/console/text/output.rs index c2b5a5f42..d07646278 100644 --- a/uefi/src/proto/console/text/output.rs +++ b/uefi/src/proto/console/text/output.rs @@ -1,5 +1,5 @@ use crate::proto::unsafe_protocol; -use crate::{CStr16, Char16, Result, ResultExt, Status}; +use crate::{CStr16, Char16, Result, ResultExt, Status, StatusExt}; use core::fmt; use core::fmt::{Debug, Formatter}; @@ -43,7 +43,7 @@ pub struct Output { impl Output { /// Resets and clears the text output device hardware. pub fn reset(&mut self, extended: bool) -> Result { - (self.reset)(self, extended).into() + (self.reset)(self, extended).to_result() } /// Clears the output screen. @@ -51,12 +51,12 @@ impl Output { /// The background is set to the current background color. /// The cursor is moved to (0, 0). pub fn clear(&mut self) -> Result { - (self.clear_screen)(self).into() + (self.clear_screen)(self).to_result() } /// Writes a string to the output device. pub fn output_string(&mut self, string: &CStr16) -> Result { - unsafe { (self.output_string)(self, string.as_ptr()) }.into() + unsafe { (self.output_string)(self, string.as_ptr()) }.to_result() } /// Writes a string to the output device. If the string contains @@ -79,7 +79,7 @@ impl Output { pub fn test_string(&mut self, string: &CStr16) -> Result { match unsafe { (self.test_string)(self, string.as_ptr()) } { Status::UNSUPPORTED => Ok(false), - other => other.into_with_val(|| true), + other => other.to_result_with_val(|| true), } } @@ -106,7 +106,8 @@ impl Output { /// alternative to this method. fn query_mode(&self, index: usize) -> Result<(usize, usize)> { let (mut columns, mut rows) = (0, 0); - (self.query_mode)(self, index, &mut columns, &mut rows).into_with_val(|| (columns, rows)) + (self.query_mode)(self, index, &mut columns, &mut rows) + .to_result_with_val(|| (columns, rows)) } /// Returns the current text mode. @@ -124,7 +125,7 @@ impl Output { /// Sets a mode as current. pub fn set_mode(&mut self, mode: OutputMode) -> Result { - (self.set_mode)(self, mode.index).into() + (self.set_mode)(self, mode.index).to_result() } /// Returns whether the cursor is currently shown or not. @@ -138,7 +139,7 @@ impl Output { /// The output device may not support this operation, in which case an /// `Unsupported` error will be returned. pub fn enable_cursor(&mut self, visible: bool) -> Result { - (self.enable_cursor)(self, visible).into() + (self.enable_cursor)(self, visible).to_result() } /// Returns the column and row of the cursor. @@ -153,7 +154,7 @@ impl Output { /// /// This function will fail if the cursor's new position would exceed the screen's bounds. pub fn set_cursor_position(&mut self, column: usize, row: usize) -> Result { - (self.set_cursor_position)(self, column, row).into() + (self.set_cursor_position)(self, column, row).to_result() } /// Sets the text and background colors for the console. @@ -167,7 +168,7 @@ impl Output { assert!(bgc < 8, "An invalid background color was requested"); let attr = ((bgc & 0x7) << 4) | (fgc & 0xF); - (self.set_attribute)(self, attr).into() + (self.set_attribute)(self, attr).to_result() } /// Get a reference to `OutputData`. The lifetime of the reference is tied diff --git a/uefi/src/proto/debug/mod.rs b/uefi/src/proto/debug/mod.rs index 22ad4983b..c9f3951df 100644 --- a/uefi/src/proto/debug/mod.rs +++ b/uefi/src/proto/debug/mod.rs @@ -12,7 +12,7 @@ use core::ffi::c_void; use crate::proto::unsafe_protocol; -use crate::{Result, Status}; +use crate::{Result, Status, StatusExt}; // re-export for ease of use pub use self::context::SystemContext; @@ -95,7 +95,7 @@ impl DebugSupport { } // Safety: As we've validated the `processor_index`, this should always be safe - (self.register_periodic_callback)(self, processor_index, callback).into() + (self.register_periodic_callback)(self, processor_index, callback).to_result() } /// Registers a function to be called when a given processor exception occurs. @@ -119,7 +119,8 @@ impl DebugSupport { } // Safety: As we've validated the `processor_index`, this should always be safe - (self.register_exception_callback)(self, processor_index, callback, exception_type).into() + (self.register_exception_callback)(self, processor_index, callback, exception_type) + .to_result() } /// Invalidates processor instruction cache for a memory range for a given `processor_index`. @@ -140,7 +141,7 @@ impl DebugSupport { // per the UEFI spec, this call should only return EFI_SUCCESS // Safety: As we've validated the `processor_index`, this should always be safe - (self.invalidate_instruction_cache)(self, processor_index, start, length).into() + (self.invalidate_instruction_cache)(self, processor_index, start, length).to_result() } } @@ -195,7 +196,7 @@ pub struct DebugPort { impl DebugPort { /// Resets the debugport device. pub fn reset(&self) -> Result { - (self.reset)(self).into() + (self.reset)(self).to_result() } /// Write data to the debugport device. @@ -210,7 +211,7 @@ impl DebugPort { &mut buffer_size, data.as_ptr().cast::(), ) - .into_with( + .to_result_with( || debug_assert_eq!(buffer_size, data.len()), |_| buffer_size, ) @@ -228,7 +229,7 @@ impl DebugPort { &mut buffer_size, data.as_mut_ptr().cast::(), ) - .into_with( + .to_result_with( || debug_assert_eq!(buffer_size, data.len()), |_| buffer_size, ) @@ -236,6 +237,6 @@ impl DebugPort { /// Check to see if any data is available to be read from the debugport device. pub fn poll(&self) -> Result { - (self.poll)(self).into() + (self.poll)(self).to_result() } } diff --git a/uefi/src/proto/driver/component_name.rs b/uefi/src/proto/driver/component_name.rs index 13fadffc4..0d4cbf991 100644 --- a/uefi/src/proto/driver/component_name.rs +++ b/uefi/src/proto/driver/component_name.rs @@ -6,7 +6,7 @@ use crate::proto::unsafe_protocol; use crate::table::boot::{BootServices, ScopedProtocol}; -use crate::{CStr16, Error, Handle, Result, Status}; +use crate::{CStr16, Error, Handle, Result, Status, StatusExt}; use core::fmt::{Debug, Formatter}; use core::{ptr, slice}; @@ -62,7 +62,7 @@ impl ComponentName1 { let language = language_to_cstr(language)?; let mut driver_name = ptr::null(); unsafe { (self.get_driver_name)(self, language.as_ptr(), &mut driver_name) } - .into_with_val(|| unsafe { CStr16::from_ptr(driver_name.cast()) }) + .to_result_with_val(|| unsafe { CStr16::from_ptr(driver_name.cast()) }) } /// Get the human-readable name of a controller in the given language. @@ -87,7 +87,7 @@ impl ComponentName1 { &mut driver_name, ) } - .into_with_val(|| unsafe { CStr16::from_ptr(driver_name.cast()) }) + .to_result_with_val(|| unsafe { CStr16::from_ptr(driver_name.cast()) }) } } @@ -142,7 +142,7 @@ impl ComponentName2 { let language = language_to_cstr(language)?; let mut driver_name = ptr::null(); unsafe { (self.get_driver_name)(self, language.as_ptr(), &mut driver_name) } - .into_with_val(|| unsafe { CStr16::from_ptr(driver_name.cast()) }) + .to_result_with_val(|| unsafe { CStr16::from_ptr(driver_name.cast()) }) } /// Get the human-readable name of a controller in the given language. @@ -167,7 +167,7 @@ impl ComponentName2 { &mut driver_name, ) } - .into_with_val(|| unsafe { CStr16::from_ptr(driver_name.cast()) }) + .to_result_with_val(|| unsafe { CStr16::from_ptr(driver_name.cast()) }) } } diff --git a/uefi/src/proto/media/block.rs b/uefi/src/proto/media/block.rs index 4d90deaa3..1fd8f98d2 100644 --- a/uefi/src/proto/media/block.rs +++ b/uefi/src/proto/media/block.rs @@ -1,7 +1,7 @@ //! Block I/O protocols. use crate::proto::unsafe_protocol; -use crate::{Result, Status}; +use crate::{Result, Status, StatusExt}; /// The Block I/O protocol. #[repr(C)] @@ -44,7 +44,7 @@ impl BlockIO { /// # Errors /// * `uefi::Status::DEVICE_ERROR` The block device is not functioning correctly and could not be reset. pub fn reset(&mut self, extended_verification: bool) -> Result { - (self.reset)(self, extended_verification).into() + (self.reset)(self, extended_verification).to_result() } /// Read the requested number of blocks from the device. @@ -65,7 +65,7 @@ impl BlockIO { /// proper alignment. pub fn read_blocks(&self, media_id: u32, lba: Lba, buffer: &mut [u8]) -> Result { let buffer_size = buffer.len(); - (self.read_blocks)(self, media_id, lba, buffer_size, buffer.as_mut_ptr()).into() + (self.read_blocks)(self, media_id, lba, buffer_size, buffer.as_mut_ptr()).to_result() } /// Writes the requested number of blocks to the device. @@ -87,7 +87,7 @@ impl BlockIO { /// on proper alignment. pub fn write_blocks(&mut self, media_id: u32, lba: Lba, buffer: &[u8]) -> Result { let buffer_size = buffer.len(); - (self.write_blocks)(self, media_id, lba, buffer_size, buffer.as_ptr()).into() + (self.write_blocks)(self, media_id, lba, buffer_size, buffer.as_ptr()).to_result() } /// Flushes all modified data to a physical block device. @@ -96,7 +96,7 @@ impl BlockIO { /// * `uefi::Status::DEVICE_ERROR` The device reported an error while attempting to write data. /// * `uefi::Status::NO_MEDIA` There is no media in the device. pub fn flush_blocks(&mut self) -> Result { - (self.flush_blocks)(self).into() + (self.flush_blocks)(self).to_result() } } diff --git a/uefi/src/proto/media/disk.rs b/uefi/src/proto/media/disk.rs index 2283d86b8..cf60784c2 100644 --- a/uefi/src/proto/media/disk.rs +++ b/uefi/src/proto/media/disk.rs @@ -1,7 +1,7 @@ //! Disk I/O protocols. use crate::proto::unsafe_protocol; -use crate::{Event, Result, Status}; +use crate::{Event, Result, Status, StatusExt}; use core::ptr::NonNull; /// The disk I/O protocol. @@ -46,7 +46,7 @@ impl DiskIo { /// * `uefi::status::NO_MEDIA` There is no medium in the device. /// * `uefi::status::MEDIA_CHANGED` `media_id` is not for the current medium. pub fn read_disk(&self, media_id: u32, offset: u64, buffer: &mut [u8]) -> Result { - (self.read_disk)(self, media_id, offset, buffer.len(), buffer.as_mut_ptr()).into() + (self.read_disk)(self, media_id, offset, buffer.len(), buffer.as_mut_ptr()).to_result() } /// Writes bytes to the disk device. @@ -65,7 +65,7 @@ impl DiskIo { /// * `uefi::status::MEDIA_CHANGED` `media_id` is not for the current medium. /// * `uefi::status::WRITE_PROTECTED` The device cannot be written to. pub fn write_disk(&mut self, media_id: u32, offset: u64, buffer: &[u8]) -> Result { - (self.write_disk)(self, media_id, offset, buffer.len(), buffer.as_ptr()).into() + (self.write_disk)(self, media_id, offset, buffer.len(), buffer.as_ptr()).to_result() } } @@ -115,7 +115,7 @@ impl DiskIo2 { /// * `uefi::status::DEVICE_ERROR` The device reported an error while performing /// the cancel operation. pub fn cancel(&mut self) -> Result { - (self.cancel)(self).into() + (self.cancel)(self).to_result() } /// Reads bytes from the disk device. @@ -149,7 +149,7 @@ impl DiskIo2 { len: usize, buffer: *mut u8, ) -> Result { - (self.read_disk_ex)(self, media_id, offset, token, len, buffer).into() + (self.read_disk_ex)(self, media_id, offset, token, len, buffer).to_result() } /// Writes bytes to the disk device. @@ -184,7 +184,7 @@ impl DiskIo2 { len: usize, buffer: *const u8, ) -> Result { - (self.write_disk_ex)(self, media_id, offset, token, len, buffer).into() + (self.write_disk_ex)(self, media_id, offset, token, len, buffer).to_result() } /// Flushes all modified data to the physical device. @@ -202,6 +202,6 @@ impl DiskIo2 { /// the flush operation. /// * `uefi::status::WRITE_PROTECTED` The device cannot be written to. pub fn flush_disk(&mut self, token: Option>) -> Result { - (self.flush_disk_ex)(self, token).into() + (self.flush_disk_ex)(self, token).to_result() } } diff --git a/uefi/src/proto/media/file/mod.rs b/uefi/src/proto/media/file/mod.rs index 7875f9627..29509c080 100644 --- a/uefi/src/proto/media/file/mod.rs +++ b/uefi/src/proto/media/file/mod.rs @@ -10,7 +10,7 @@ mod dir; mod info; mod regular; -use crate::{CStr16, Char16, Guid, Result, Status}; +use crate::{CStr16, Char16, Guid, Result, Status, StatusExt}; use bitflags::bitflags; use core::ffi::c_void; use core::fmt::Debug; @@ -76,7 +76,7 @@ pub trait File: Sized { attributes, ) } - .into_with_val(|| unsafe { FileHandle::new(ptr) }) + .to_result_with_val(|| unsafe { FileHandle::new(ptr) }) } /// Close this file handle. Same as dropping this structure. @@ -90,7 +90,7 @@ pub trait File: Sized { /// /// * [`uefi::Status::WARN_DELETE_FAILURE`] fn delete(mut self) -> Result { - let result = (self.imp().delete)(self.imp()).into(); + let result = (self.imp().delete)(self.imp()).to_result(); mem::forget(self); result } @@ -128,7 +128,7 @@ pub trait File: Sized { buffer.as_mut_ptr(), ) } - .into_with( + .to_result_with( || unsafe { Info::from_uefi(buffer.as_mut_ptr().cast::()) }, |s| { if s == Status::BUFFER_TOO_SMALL { @@ -165,7 +165,7 @@ pub trait File: Sized { fn set_info(&mut self, info: &Info) -> Result { let info_ptr = (info as *const Info).cast::(); let info_size = mem::size_of_val(info); - unsafe { (self.imp().set_info)(self.imp(), &Info::GUID, info_size, info_ptr).into() } + unsafe { (self.imp().set_info)(self.imp(), &Info::GUID, info_size, info_ptr).to_result() } } /// Flushes all modified data associated with the file handle to the device @@ -181,7 +181,7 @@ pub trait File: Sized { /// * [`uefi::Status::ACCESS_DENIED`] /// * [`uefi::Status::VOLUME_FULL`] fn flush(&mut self) -> Result { - (self.imp().flush)(self.imp()).into() + (self.imp().flush)(self.imp()).to_result() } /// Read the dynamically allocated info for a file. @@ -307,7 +307,7 @@ impl File for FileHandle { impl Drop for FileHandle { fn drop(&mut self) { - let result: Result = (self.imp().close)(self.imp()).into(); + let result: Result = (self.imp().close)(self.imp()).to_result(); // The spec says this always succeeds. result.expect("Failed to close file"); } diff --git a/uefi/src/proto/media/file/regular.rs b/uefi/src/proto/media/file/regular.rs index 0f5338eee..9a497191e 100644 --- a/uefi/src/proto/media/file/regular.rs +++ b/uefi/src/proto/media/file/regular.rs @@ -1,5 +1,5 @@ use super::{File, FileHandle, FileInternal}; -use crate::{Result, Status}; +use crate::{Result, Status, StatusExt}; /// A `FileHandle` that is also a regular (data) file. /// @@ -44,7 +44,7 @@ impl RegularFile { let status = unsafe { (self.imp().read)(self.imp(), &mut buffer_size, buffer.as_mut_ptr()) }; - status.into_with( + status.to_result_with( || buffer_size, |s| { if s == Status::BUFFER_TOO_SMALL { @@ -81,7 +81,7 @@ impl RegularFile { pub fn write(&mut self, buffer: &[u8]) -> Result<(), usize> { let mut buffer_size = buffer.len(); unsafe { (self.imp().write)(self.imp(), &mut buffer_size, buffer.as_ptr()) } - .into_with_err(|_| buffer_size) + .to_result_with_err(|_| buffer_size) } /// Get the file's current position @@ -93,7 +93,7 @@ impl RegularFile { /// * [`uefi::Status::DEVICE_ERROR`] pub fn get_position(&mut self) -> Result { let mut pos = 0u64; - (self.imp().get_position)(self.imp(), &mut pos).into_with_val(|| pos) + (self.imp().get_position)(self.imp(), &mut pos).to_result_with_val(|| pos) } /// Sets the file's current position @@ -112,7 +112,7 @@ impl RegularFile { /// /// * [`uefi::Status::DEVICE_ERROR`] pub fn set_position(&mut self, position: u64) -> Result { - (self.imp().set_position)(self.imp(), position).into() + (self.imp().set_position)(self.imp(), position).to_result() } } diff --git a/uefi/src/proto/media/fs.rs b/uefi/src/proto/media/fs.rs index 9c9112e77..0a5966fb2 100644 --- a/uefi/src/proto/media/fs.rs +++ b/uefi/src/proto/media/fs.rs @@ -2,7 +2,7 @@ use super::file::{Directory, FileHandle, FileImpl}; use crate::proto::unsafe_protocol; -use crate::{Result, Status}; +use crate::{Result, Status, StatusExt}; use core::ptr; /// Allows access to a FAT-12/16/32 file system. @@ -49,6 +49,6 @@ impl SimpleFileSystem { pub fn open_volume(&mut self) -> Result { let mut ptr = ptr::null_mut(); (self.open_volume)(self, &mut ptr) - .into_with_val(|| unsafe { Directory::new(FileHandle::new(ptr)) }) + .to_result_with_val(|| unsafe { Directory::new(FileHandle::new(ptr)) }) } } diff --git a/uefi/src/proto/network/pxe.rs b/uefi/src/proto/network/pxe.rs index 754acb977..3a732155a 100644 --- a/uefi/src/proto/network/pxe.rs +++ b/uefi/src/proto/network/pxe.rs @@ -12,7 +12,7 @@ use crate::util::ptr_write_unaligned_and_add; use bitflags::bitflags; use ptr_meta::Pointee; -use crate::{CStr8, Char8, Result, Status}; +use crate::{CStr8, Char8, Result, Status, StatusExt}; use super::{IpAddress, MacAddress}; @@ -109,18 +109,18 @@ pub struct BaseCode { impl BaseCode { /// Enables the use of the PXE Base Code Protocol functions. pub fn start(&mut self, use_ipv6: bool) -> Result { - (self.start)(self, use_ipv6).into() + (self.start)(self, use_ipv6).to_result() } /// Disables the use of the PXE Base Code Protocol functions. pub fn stop(&mut self) -> Result { - (self.stop)(self).into() + (self.stop)(self).to_result() } /// Attempts to complete a DHCPv4 D.O.R.A. (discover / offer / request / /// acknowledge) or DHCPv6 S.A.R.R (solicit / advertise / request / reply) sequence. pub fn dhcp(&mut self, sort_offers: bool) -> Result { - (self.dhcp)(self, sort_offers).into() + (self.dhcp)(self, sort_offers).to_result() } /// Attempts to complete the PXE Boot Server and/or boot image discovery @@ -139,7 +139,7 @@ impl BaseCode { }) .unwrap_or(null()); - (self.discover)(self, ty, layer, use_bis, info).into() + (self.discover)(self, ty, layer, use_bis, info).to_result() } /// Returns the size of a file located on a TFTP server. @@ -160,7 +160,7 @@ impl BaseCode { false, ) }; - status.into_with_val(|| buffer_size) + status.to_result_with_val(|| buffer_size) } /// Reads a file located on a TFTP server. @@ -191,7 +191,7 @@ impl BaseCode { dont_use_buffer, ) }; - status.into_with_val(|| buffer_size) + status.to_result_with_val(|| buffer_size) } /// Writes to a file located on a TFTP server. @@ -219,7 +219,7 @@ impl BaseCode { false, ) } - .into() + .to_result() } /// Reads a directory listing of a directory on a TFTP server. @@ -247,7 +247,7 @@ impl BaseCode { false, ) }; - Result::from(status)?; + status.to_result()?; let buffer_size = usize::try_from(buffer_size).expect("buffer length should fit in usize"); let buffer = &buffer[..buffer_size]; @@ -320,7 +320,7 @@ impl BaseCode { false, ) }; - status.into_with_val(|| buffer_size) + status.to_result_with_val(|| buffer_size) } /// Reads a file located on a MTFTP server. @@ -352,7 +352,7 @@ impl BaseCode { dont_use_buffer, ) }; - status.into_with_val(|| buffer_size) + status.to_result_with_val(|| buffer_size) } /// Reads a directory listing of a directory on a MTFTP server. @@ -380,7 +380,7 @@ impl BaseCode { false, ) }; - Result::from(status)?; + status.to_result()?; let buffer_size = usize::try_from(buffer_size).expect("buffer length should fit in usize"); let buffer = &buffer[..buffer_size]; @@ -483,7 +483,7 @@ impl BaseCode { (&buffer[0] as *const u8).cast(), ) } - .into() + .to_result() } /// Reads a UDP packet from the network interface. @@ -522,18 +522,18 @@ impl BaseCode { (&mut buffer[0] as *mut u8).cast(), ) }; - status.into_with_val(|| buffer_size) + status.to_result_with_val(|| buffer_size) } /// Updates the IP receive filters of a network device and enables software /// filtering. pub fn set_ip_filter(&mut self, new_filter: &IpFilter) -> Result { - (self.set_ip_filter)(self, new_filter).into() + (self.set_ip_filter)(self, new_filter).to_result() } /// Uses the ARP protocol to resolve a MAC address. pub fn arp(&mut self, ip_addr: &IpAddress, mac_addr: Option<&mut MacAddress>) -> Result { - (self.arp)(self, ip_addr, mac_addr).into() + (self.arp)(self, ip_addr, mac_addr).to_result() } /// Updates the parameters that affect the operation of the PXE Base Code @@ -554,7 +554,7 @@ impl BaseCode { new_tos.as_ref(), new_make_callback.as_ref(), ) - .into() + .to_result() } /// Updates the station IP address and/or subnet mask values of a network @@ -564,7 +564,7 @@ impl BaseCode { new_station_ip: Option<&IpAddress>, new_subnet_mask: Option<&IpAddress>, ) -> Result { - (self.set_station_ip)(self, new_station_ip, new_subnet_mask).into() + (self.set_station_ip)(self, new_station_ip, new_subnet_mask).to_result() } /// Updates the contents of the cached DHCP and Discover packets. @@ -599,7 +599,7 @@ impl BaseCode { new_pxe_reply, new_pxe_bis_reply, ) - .into() + .to_result() } /// Returns a reference to the `Mode` struct. diff --git a/uefi/src/proto/network/snp.rs b/uefi/src/proto/network/snp.rs index b0adb4269..8e370336d 100644 --- a/uefi/src/proto/network/snp.rs +++ b/uefi/src/proto/network/snp.rs @@ -9,7 +9,7 @@ use super::{IpAddress, MacAddress}; use crate::data_types::Event; -use crate::{Result, Status}; +use crate::{Result, Status, StatusExt}; use bitflags::bitflags; use core::ffi::c_void; use core::ptr; @@ -86,31 +86,31 @@ pub struct SimpleNetwork { impl SimpleNetwork { /// Change the state of a network from "Stopped" to "Started". pub fn start(&self) -> Result { - (self.start)(self).into() + (self.start)(self).to_result() } /// Change the state of a network interface from "Started" to "Stopped". pub fn stop(&self) -> Result { - (self.stop)(self).into() + (self.stop)(self).to_result() } /// Reset a network adapter and allocate the transmit and receive buffers /// required by the network interface; optionally, also request allocation of /// additional transmit and receive buffers. pub fn initialize(&self, extra_rx_buffer_size: usize, extra_tx_buffer_size: usize) -> Result { - (self.initialize)(self, extra_rx_buffer_size, extra_tx_buffer_size).into() + (self.initialize)(self, extra_rx_buffer_size, extra_tx_buffer_size).to_result() } /// Reset a network adapter and reinitialize it with the parameters that were /// provided in the previous call to `initialize`. pub fn reset(&self, extended_verification: bool) -> Result { - (self.reset)(self, extended_verification).into() + (self.reset)(self, extended_verification).to_result() } /// Reset a network adapter, leaving it in a state that is safe /// for another driver to initialize pub fn shutdown(&self) -> Result { - (self.shutdown)(self).into() + (self.shutdown)(self).to_result() } /// Manage the multicast receive filters of a network. @@ -130,21 +130,21 @@ impl SimpleNetwork { mcast_filter.len(), NonNull::new(mcast_filter.as_ptr() as *mut _), ) - .into() + .to_result() } else { (self.receive_filters)(self, enable.bits, disable.bits, reset_mcast_filter, 0, None) - .into() + .to_result() } } /// Modify or reset the current station address, if supported. pub fn station_address(&self, reset: bool, new: Option<&MacAddress>) -> Result { - (self.station_address)(self, reset, new).into() + (self.station_address)(self, reset, new).to_result() } /// Reset statistics on a network interface. pub fn reset_statistics(&self) -> Result { - (self.statistics)(self, true, None, None).into() + (self.statistics)(self, true, None, None).to_result() } /// Collect statistics on a network interface. @@ -152,14 +152,14 @@ impl SimpleNetwork { let mut stats_table: NetworkStats = Default::default(); let mut stats_size = core::mem::size_of::(); let status = (self.statistics)(self, false, Some(&mut stats_size), Some(&mut stats_table)); - status.into_with_val(|| stats_table) + status.to_result_with_val(|| stats_table) } /// Convert a multicast IP address to a multicast HW MAC Address. pub fn mcast_ip_to_mac(&self, ipv6: bool, ip: IpAddress) -> Result { let mut mac_address = MacAddress([0; 32]); let status = (self.mcast_ip_to_mac)(self, ipv6, &ip, &mut mac_address); - status.into_with_val(|| mac_address) + status.to_result_with_val(|| mac_address) } /// Perform read operations on the NVRAM device attached to @@ -172,7 +172,7 @@ impl SimpleNetwork { buffer.len(), buffer.as_ptr() as *mut c_void, ) - .into() + .to_result() } /// Perform write operations on the NVRAM device attached to a network interface. @@ -184,7 +184,7 @@ impl SimpleNetwork { buffer.len(), buffer.as_mut_ptr().cast(), ) - .into() + .to_result() } /// Read the current interrupt status and recycled transmit buffer @@ -192,7 +192,7 @@ impl SimpleNetwork { pub fn get_interrupt_status(&self) -> Result { let mut interrupt_status = InterruptStatus::empty(); let status = (self.get_status)(self, Some(&mut interrupt_status), None); - status.into_with_val(|| interrupt_status) + status.to_result_with_val(|| interrupt_status) } /// Read the current recycled transmit buffer status from a @@ -200,7 +200,7 @@ impl SimpleNetwork { pub fn get_recycled_transmit_buffer_status(&self) -> Result>> { let mut tx_buf: *mut c_void = ptr::null_mut(); let status = (self.get_status)(self, None, Some(&mut tx_buf)); - status.into_with_val(|| NonNull::new(tx_buf.cast())) + status.to_result_with_val(|| NonNull::new(tx_buf.cast())) } /// Place a packet in the transmit queue of a network interface. @@ -221,7 +221,7 @@ impl SimpleNetwork { dest_addr.as_ref(), protocol.as_ref(), ) - .into() + .to_result() } /// Receive a packet from a network interface. @@ -245,7 +245,7 @@ impl SimpleNetwork { dest_addr, protocol, ); - status.into_with_val(|| buffer_size) + status.to_result_with_val(|| buffer_size) } /// Event that fires once a packet is available to be received. diff --git a/uefi/src/proto/pi/mp.rs b/uefi/src/proto/pi/mp.rs index c8944cad3..80e06fc45 100644 --- a/uefi/src/proto/pi/mp.rs +++ b/uefi/src/proto/pi/mp.rs @@ -12,7 +12,7 @@ //! * maintaining MP-related processor status use crate::proto::unsafe_protocol; -use crate::{Result, Status}; +use crate::{Result, Status, StatusExt}; use bitflags::bitflags; use core::ffi::c_void; use core::ptr; @@ -144,13 +144,13 @@ impl MpServices { let mut total: usize = 0; let mut enabled: usize = 0; (self.get_number_of_processors)(self, &mut total, &mut enabled) - .into_with_val(|| ProcessorCount { total, enabled }) + .to_result_with_val(|| ProcessorCount { total, enabled }) } /// Gets detailed information on the requested processor at the instant this call is made. pub fn get_processor_info(&self, processor_number: usize) -> Result { let mut pi: ProcessorInformation = Default::default(); - (self.get_processor_info)(self, processor_number, &mut pi).into_with_val(|| pi) + (self.get_processor_info)(self, processor_number, &mut pi).to_result_with_val(|| pi) } /// Executes provided function on all APs in blocking mode. @@ -175,7 +175,7 @@ impl MpServices { procedure_argument, ptr::null_mut(), ) - .into() + .to_result() } /// Executes provided function on a specific AP in blocking mode. @@ -200,12 +200,12 @@ impl MpServices { procedure_argument, ptr::null_mut(), ) - .into() + .to_result() } /// Switches the requested AP to be the BSP from that point onward. pub fn switch_bsp(&self, processor_number: usize, enable_old_bsp: bool) -> Result { - (self.switch_bsp)(self, processor_number, enable_old_bsp).into() + (self.switch_bsp)(self, processor_number, enable_old_bsp).to_result() } /// Enables or disables an AP from this point onward. @@ -227,12 +227,12 @@ impl MpServices { } None => ptr::null(), }; - (self.enable_disable_ap)(self, processor_number, enable_ap, health_flag_ptr).into() + (self.enable_disable_ap)(self, processor_number, enable_ap, health_flag_ptr).to_result() } /// Gets the handle number of the caller processor. pub fn who_am_i(&self) -> Result { let mut processor_number: usize = 0; - (self.who_am_i)(self, &mut processor_number).into_with_val(|| processor_number) + (self.who_am_i)(self, &mut processor_number).to_result_with_val(|| processor_number) } } diff --git a/uefi/src/proto/rng.rs b/uefi/src/proto/rng.rs index 7d2abce29..2e1d29312 100644 --- a/uefi/src/proto/rng.rs +++ b/uefi/src/proto/rng.rs @@ -2,7 +2,7 @@ use crate::data_types::Guid; use crate::proto::unsafe_protocol; -use crate::{guid, Result, Status}; +use crate::{guid, Result, Status, StatusExt}; use core::{mem, ptr}; newtype_enum! { @@ -61,19 +61,20 @@ impl Rng { let mut algorithm_list_size = algorithm_list.len() * mem::size_of::(); unsafe { - (self.get_info)(self, &mut algorithm_list_size, algorithm_list.as_mut_ptr()).into_with( - || { - let len = algorithm_list_size / mem::size_of::(); - &algorithm_list[..len] - }, - |status| { - if status == Status::BUFFER_TOO_SMALL { - Some(algorithm_list_size) - } else { - None - } - }, - ) + (self.get_info)(self, &mut algorithm_list_size, algorithm_list.as_mut_ptr()) + .to_result_with( + || { + let len = algorithm_list_size / mem::size_of::(); + &algorithm_list[..len] + }, + |status| { + if status == Status::BUFFER_TOO_SMALL { + Some(algorithm_list_size) + } else { + None + } + }, + ) } } @@ -86,6 +87,6 @@ impl Rng { Some(algo) => algo as *const RngAlgorithmType, }; - unsafe { (self.get_rng)(self, algo, buffer_length, buffer.as_mut_ptr()).into() } + unsafe { (self.get_rng)(self, algo, buffer_length, buffer.as_mut_ptr()).to_result() } } } diff --git a/uefi/src/proto/security/memory_protection.rs b/uefi/src/proto/security/memory_protection.rs index 84bfb48dd..00bfb705b 100644 --- a/uefi/src/proto/security/memory_protection.rs +++ b/uefi/src/proto/security/memory_protection.rs @@ -1,7 +1,7 @@ use crate::data_types::PhysicalAddress; use crate::proto::unsafe_protocol; use crate::table::boot::MemoryAttribute; -use crate::{Result, Status}; +use crate::{Result, Status, StatusExt}; use core::ops::Range; /// Protocol for getting and setting memory protection attributes. @@ -56,7 +56,7 @@ impl MemoryProtection { let (base_address, length) = range_to_base_and_len(byte_region); unsafe { (self.get_memory_attributes)(self, base_address, length, &mut attributes) - .into_with_val(|| attributes) + .to_result_with_val(|| attributes) } } @@ -78,7 +78,7 @@ impl MemoryProtection { attributes: MemoryAttribute, ) -> Result { let (base_address, length) = range_to_base_and_len(byte_region); - unsafe { (self.set_memory_attributes)(self, base_address, length, attributes).into() } + unsafe { (self.set_memory_attributes)(self, base_address, length, attributes).to_result() } } /// Clear the attributes of a memory region. @@ -99,7 +99,9 @@ impl MemoryProtection { attributes: MemoryAttribute, ) -> Result { let (base_address, length) = range_to_base_and_len(byte_region); - unsafe { (self.clear_memory_attributes)(self, base_address, length, attributes).into() } + unsafe { + (self.clear_memory_attributes)(self, base_address, length, attributes).to_result() + } } } diff --git a/uefi/src/proto/shim/mod.rs b/uefi/src/proto/shim/mod.rs index 60120df0e..7394a79af 100644 --- a/uefi/src/proto/shim/mod.rs +++ b/uefi/src/proto/shim/mod.rs @@ -9,7 +9,7 @@ use crate::proto::unsafe_protocol; use crate::result::Error; -use crate::{Result, Status}; +use crate::{Result, Status, StatusExt}; use core::ffi::c_void; use core::mem::MaybeUninit; @@ -93,7 +93,7 @@ impl ShimLock { .len() .try_into() .map_err(|_| Error::from(Status::BAD_BUFFER_SIZE))?; - (self.verify)(buffer.as_ptr(), size).into() + (self.verify)(buffer.as_ptr(), size).to_result() } /// Compute the Authenticode Hash of the provided EFI application. /// @@ -108,7 +108,7 @@ impl ShimLock { .map_err(|_| Error::from(Status::BAD_BUFFER_SIZE))?; let mut context = MaybeUninit::::uninit(); - Result::from((self.context)(ptr, size, context.as_mut_ptr()))?; + (self.context)(ptr, size, context.as_mut_ptr()).to_result()?; (self.hash)( ptr, size, @@ -116,6 +116,6 @@ impl ShimLock { &mut hashes.sha256, &mut hashes.sha1, ) - .into() + .to_result() } } diff --git a/uefi/src/proto/tcg/v1.rs b/uefi/src/proto/tcg/v1.rs index e7bffb906..27cd26465 100644 --- a/uefi/src/proto/tcg/v1.rs +++ b/uefi/src/proto/tcg/v1.rs @@ -13,7 +13,7 @@ use crate::data_types::PhysicalAddress; use crate::polyfill::maybe_uninit_slice_as_mut_ptr; use crate::proto::unsafe_protocol; use crate::util::{ptr_write_unaligned_and_add, usize_from_u32}; -use crate::{Error, Result, Status}; +use crate::{Error, Result, Status, StatusExt}; use core::fmt::{self, Debug, Formatter}; use core::marker::PhantomData; use core::mem::{self, MaybeUninit}; @@ -450,7 +450,7 @@ impl Tcg { let event_ptr: *const PcrEvent = event; - unsafe { (self.log_event)(self, event_ptr.cast(), &mut event_number, flags).into() } + unsafe { (self.log_event)(self, event_ptr.cast(), &mut event_number, flags).to_result() } } /// Extend a PCR and add an entry to the event log. @@ -489,7 +489,7 @@ impl Tcg { &mut event_number, &mut event_log_last_entry, ) - .into() + .to_result() } } @@ -520,7 +520,7 @@ impl Tcg { output_parameter_block_len, output_parameter_block.as_mut_ptr(), ) - .into() + .to_result() } } } diff --git a/uefi/src/proto/tcg/v2.rs b/uefi/src/proto/tcg/v2.rs index ac93132c6..ba62dfbd0 100644 --- a/uefi/src/proto/tcg/v2.rs +++ b/uefi/src/proto/tcg/v2.rs @@ -14,7 +14,7 @@ use super::{v1, AlgorithmId, EventType, HashAlgorithm, PcrIndex}; use crate::data_types::{PhysicalAddress, UnalignedSlice}; use crate::proto::unsafe_protocol; use crate::util::{ptr_write_unaligned_and_add, usize_from_u32}; -use crate::{Error, Result, Status}; +use crate::{Error, Result, Status, StatusExt}; use bitflags::bitflags; use core::fmt::{self, Debug, Formatter}; use core::marker::PhantomData; @@ -614,7 +614,7 @@ impl Tcg { /// Get information about the protocol and TPM device. pub fn get_capability(&mut self) -> Result { let mut capability = BootServiceCapability::default(); - unsafe { (self.get_capability)(self, &mut capability).into_with_val(|| capability) } + unsafe { (self.get_capability)(self, &mut capability).to_result_with_val(|| capability) } } /// Get the V1 event log. This provides events in the same format as a V1 @@ -697,7 +697,7 @@ impl Tcg { u64::try_from(data_to_hash.len()).unwrap(), event, ) - .into() + .to_result() } } @@ -728,7 +728,7 @@ impl Tcg { output_parameter_block_len, output_parameter_block.as_mut_ptr(), ) - .into() + .to_result() } } @@ -739,14 +739,14 @@ impl Tcg { let status = unsafe { (self.get_active_pcr_banks)(self, &mut active_pcr_banks) }; - status.into_with_val(|| active_pcr_banks) + status.to_result_with_val(|| active_pcr_banks) } /// Set the active PCR banks. Each bank corresponds to a hash /// algorithm. This change will not take effect until the system is /// rebooted twice. pub fn set_active_pcr_banks(&mut self, active_pcr_banks: HashAlgorithm) -> Result { - unsafe { (self.set_active_pcr_banks)(self, active_pcr_banks) }.into() + unsafe { (self.set_active_pcr_banks)(self, active_pcr_banks) }.to_result() } /// Get the stored result of calling [`Tcg::set_active_pcr_banks`] in a @@ -766,7 +766,7 @@ impl Tcg { (self.get_result_of_set_active_pcr_banks)(self, &mut operation_present, &mut response) }; - status.into_with_val(|| { + status.to_result_with_val(|| { if operation_present == 0 { None } else { diff --git a/uefi/src/result/mod.rs b/uefi/src/result/mod.rs index 907767e18..bf28680ac 100644 --- a/uefi/src/result/mod.rs +++ b/uefi/src/result/mod.rs @@ -7,7 +7,7 @@ pub use self::error::Error; /// Definition of UEFI's standard status codes mod status; -pub use self::status::Status; +pub use self::status::{Status, StatusExt}; /// Return type of most UEFI functions. Both success and error payloads are optional. /// @@ -45,8 +45,9 @@ pub trait ResultExt { /// ``` /// use uefi::{Result, ResultExt, Status}; /// + /// # use uefi::StatusExt; /// # fn x() -> uefi::Result { - /// # let some_result = Result::from(Status::WARN_RESET_REQUIRED); + /// # let some_result = Status::WARN_RESET_REQUIRED.to_result(); /// // Treat a specific warning as success, propagate others as errors. /// some_result.handle_warning(|err| { /// if err.status() == Status::WARN_RESET_REQUIRED { @@ -55,7 +56,7 @@ pub trait ResultExt { /// Err(err) /// } /// })?; - /// # Status::SUCCESS.into() + /// # Status::SUCCESS.to_result() /// # } /// ``` fn handle_warning(self, op: O) -> Result diff --git a/uefi/src/result/status.rs b/uefi/src/result/status.rs index fb8121b6e..e42c767a5 100644 --- a/uefi/src/result/status.rs +++ b/uefi/src/result/status.rs @@ -1,139 +1,54 @@ use super::{Error, Result}; use core::fmt::Debug; -/// Bit indicating that an UEFI status code is an error -const ERROR_BIT: usize = 1 << (core::mem::size_of::() * 8 - 1); +pub use uefi_raw::Status; -newtype_enum! { -/// UEFI uses status codes in order to report successes, errors, and warnings. -/// -/// The spec allows implementation-specific status codes, so the `Status` -/// constants are not a comprehensive list of all possible values. -/// -/// For a convenient integration into the Rust ecosystem, there are several -/// methods to convert a Status into a [`uefi::Result`]: -/// - [`Status::into_with`] -/// - [`Status::into_with_val`] -/// - [`Status::into_with_err`] -#[must_use] -pub enum Status: usize => { - /// The operation completed successfully. - SUCCESS = 0, - - /// The string contained characters that could not be rendered and were skipped. - WARN_UNKNOWN_GLYPH = 1, - /// The handle was closed, but the file was not deleted. - WARN_DELETE_FAILURE = 2, - /// The handle was closed, but the data to the file was not flushed properly. - WARN_WRITE_FAILURE = 3, - /// The resulting buffer was too small, and the data was truncated. - WARN_BUFFER_TOO_SMALL = 4, - /// The data has not been updated within the timeframe set by local policy. - WARN_STALE_DATA = 5, - /// The resulting buffer contains UEFI-compliant file system. - WARN_FILE_SYSTEM = 6, - /// The operation will be processed across a system reset. - WARN_RESET_REQUIRED = 7, +/// Extension trait which provides some convenience methods for [`Status`]. +pub trait StatusExt { + /// Converts this status code into a [`uefi::Result`]. + /// + /// If the status does not indicate success, the status representing the specific error + /// code is embedded into the `Err` variant of type [`uefi::Error`]. + fn to_result(self) -> Result; - /// The image failed to load. - LOAD_ERROR = ERROR_BIT | 1, - /// A parameter was incorrect. - INVALID_PARAMETER = ERROR_BIT | 2, - /// The operation is not supported. - UNSUPPORTED = ERROR_BIT | 3, - /// The buffer was not the proper size for the request. - BAD_BUFFER_SIZE = ERROR_BIT | 4, - /// The buffer is not large enough to hold the requested data. - /// The required buffer size is returned in the appropriate parameter. - BUFFER_TOO_SMALL = ERROR_BIT | 5, - /// There is no data pending upon return. - NOT_READY = ERROR_BIT | 6, - /// The physical device reported an error while attempting the operation. - DEVICE_ERROR = ERROR_BIT | 7, - /// The device cannot be written to. - WRITE_PROTECTED = ERROR_BIT | 8, - /// A resource has run out. - OUT_OF_RESOURCES = ERROR_BIT | 9, - /// An inconstency was detected on the file system. - VOLUME_CORRUPTED = ERROR_BIT | 10, - /// There is no more space on the file system. - VOLUME_FULL = ERROR_BIT | 11, - /// The device does not contain any medium to perform the operation. - NO_MEDIA = ERROR_BIT | 12, - /// The medium in the device has changed since the last access. - MEDIA_CHANGED = ERROR_BIT | 13, - /// The item was not found. - NOT_FOUND = ERROR_BIT | 14, - /// Access was denied. - ACCESS_DENIED = ERROR_BIT | 15, - /// The server was not found or did not respond to the request. - NO_RESPONSE = ERROR_BIT | 16, - /// A mapping to a device does not exist. - NO_MAPPING = ERROR_BIT | 17, - /// The timeout time expired. - TIMEOUT = ERROR_BIT | 18, - /// The protocol has not been started. - NOT_STARTED = ERROR_BIT | 19, - /// The protocol has already been started. - ALREADY_STARTED = ERROR_BIT | 20, - /// The operation was aborted. - ABORTED = ERROR_BIT | 21, - /// An ICMP error occurred during the network operation. - ICMP_ERROR = ERROR_BIT | 22, - /// A TFTP error occurred during the network operation. - TFTP_ERROR = ERROR_BIT | 23, - /// A protocol error occurred during the network operation. - PROTOCOL_ERROR = ERROR_BIT | 24, - /// The function encountered an internal version that was - /// incompatible with a version requested by the caller. - INCOMPATIBLE_VERSION = ERROR_BIT | 25, - /// The function was not performed due to a security violation. - SECURITY_VIOLATION = ERROR_BIT | 26, - /// A CRC error was detected. - CRC_ERROR = ERROR_BIT | 27, - /// Beginning or end of media was reached - END_OF_MEDIA = ERROR_BIT | 28, - /// The end of the file was reached. - END_OF_FILE = ERROR_BIT | 31, - /// The language specified was invalid. - INVALID_LANGUAGE = ERROR_BIT | 32, - /// The security status of the data is unknown or compromised and - /// the data must be updated or replaced to restore a valid security status. - COMPROMISED_DATA = ERROR_BIT | 33, - /// There is an address conflict address allocation - IP_ADDRESS_CONFLICT = ERROR_BIT | 34, - /// A HTTP error occurred during the network operation. - HTTP_ERROR = ERROR_BIT | 35, -}} + /// Converts this status code into a [`uefi::Result`] with a given `Ok` value. + /// + /// If the status does not indicate success, the status representing the specific error + /// code is embedded into the `Err` variant of type [`uefi::Error`]. + fn to_result_with_val(self, val: impl FnOnce() -> T) -> Result; -impl Status { - /// Returns true if status code indicates success. - #[inline] - #[must_use] - pub fn is_success(self) -> bool { - self == Status::SUCCESS - } + /// Converts this status code into a [`uefi::Result`] with a given `Err` payload. + /// + /// If the status does not indicate success, the status representing the specific error + /// code is embedded into the `Err` variant of type [`uefi::Error`]. + fn to_result_with_err( + self, + err: impl FnOnce(Status) -> ErrData, + ) -> Result<(), ErrData>; - /// Returns true if status code indicates a warning. - #[inline] - #[must_use] - pub fn is_warning(self) -> bool { - (self != Status::SUCCESS) && (self.0 & ERROR_BIT == 0) - } + /// Convert this status code into a result with a given `Ok` value and `Err` payload. + /// + /// If the status does not indicate success, the status representing the specific error + /// code is embedded into the `Err` variant of type [`uefi::Error`]. + fn to_result_with( + self, + val: impl FnOnce() -> T, + err: impl FnOnce(Status) -> ErrData, + ) -> Result; +} - /// Returns true if the status code indicates an error. +impl StatusExt for Status { #[inline] - #[must_use] - pub const fn is_error(self) -> bool { - self.0 & ERROR_BIT != 0 + fn to_result(self) -> Result { + if self.is_success() { + Ok(()) + } else { + Err(self.into()) + } } - /// Converts this status code into a [`uefi::Result`] with a given `Ok` value. - /// - /// If the status does not indicate success, the status representing the specific error - /// code is embedded into the `Err` variant of type [`uefi::Error`]. #[inline] - pub fn into_with_val(self, val: impl FnOnce() -> T) -> Result { + fn to_result_with_val(self, val: impl FnOnce() -> T) -> Result { if self.is_success() { Ok(val()) } else { @@ -141,12 +56,8 @@ impl Status { } } - /// Converts this status code into a [`uefi::Result`] with a given `Err` payload. - /// - /// If the status does not indicate success, the status representing the specific error - /// code is embedded into the `Err` variant of type [`uefi::Error`]. #[inline] - pub fn into_with_err( + fn to_result_with_err( self, err: impl FnOnce(Status) -> ErrData, ) -> Result<(), ErrData> { @@ -157,12 +68,8 @@ impl Status { } } - /// Convert this status code into a result with a given `Ok` value and `Err` payload. - /// - /// If the status does not indicate success, the status representing the specific error - /// code is embedded into the `Err` variant of type [`uefi::Error`]. #[inline] - pub fn into_with( + fn to_result_with( self, val: impl FnOnce() -> T, err: impl FnOnce(Status) -> ErrData, @@ -175,61 +82,52 @@ impl Status { } } -// An UEFI status is equivalent to a Result with no data or error payload -impl From for Result<(), ()> { - #[inline] - fn from(status: Status) -> Result<(), ()> { - status.into_with(|| (), |_| ()) - } -} - -impl core::fmt::Display for Status { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - Debug::fmt(self, f) - } -} - #[cfg(test)] mod tests { use super::*; #[test] fn test_status_to_result() { - assert!(Result::from(Status::SUCCESS).is_ok()); - assert!(Result::from(Status::WARN_DELETE_FAILURE).is_err()); - assert!(Result::from(Status::BUFFER_TOO_SMALL).is_err()); + assert!(Status::SUCCESS.to_result().is_ok()); + assert!(Status::WARN_DELETE_FAILURE.to_result().is_err()); + assert!(Status::BUFFER_TOO_SMALL.to_result().is_err()); - assert_eq!(Status::SUCCESS.into_with_val(|| 123).unwrap(), 123); - assert!(Status::WARN_DELETE_FAILURE.into_with_val(|| 123).is_err()); - assert!(Status::BUFFER_TOO_SMALL.into_with_val(|| 123).is_err()); + assert_eq!(Status::SUCCESS.to_result_with_val(|| 123).unwrap(), 123); + assert!(Status::WARN_DELETE_FAILURE + .to_result_with_val(|| 123) + .is_err()); + assert!(Status::BUFFER_TOO_SMALL.to_result_with_val(|| 123).is_err()); - assert!(Status::SUCCESS.into_with_err(|_| 123).is_ok()); + assert!(Status::SUCCESS.to_result_with_err(|_| 123).is_ok()); assert_eq!( *Status::WARN_DELETE_FAILURE - .into_with_err(|_| 123) + .to_result_with_err(|_| 123) .unwrap_err() .data(), 123 ); assert_eq!( *Status::BUFFER_TOO_SMALL - .into_with_err(|_| 123) + .to_result_with_err(|_| 123) .unwrap_err() .data(), 123 ); - assert_eq!(Status::SUCCESS.into_with(|| 123, |_| 456).unwrap(), 123); + assert_eq!( + Status::SUCCESS.to_result_with(|| 123, |_| 456).unwrap(), + 123 + ); assert_eq!( *Status::WARN_DELETE_FAILURE - .into_with(|| 123, |_| 456) + .to_result_with(|| 123, |_| 456) .unwrap_err() .data(), 456 ); assert_eq!( *Status::BUFFER_TOO_SMALL - .into_with(|| 123, |_| 456) + .to_result_with(|| 123, |_| 456) .unwrap_err() .data(), 456 diff --git a/uefi/src/table/boot.rs b/uefi/src/table/boot.rs index af3c18ebf..d8b85364a 100644 --- a/uefi/src/table/boot.rs +++ b/uefi/src/table/boot.rs @@ -4,7 +4,7 @@ use super::{Header, Revision}; use crate::data_types::{Align, PhysicalAddress, VirtualAddress}; use crate::proto::device_path::{DevicePath, FfiDevicePath}; use crate::proto::{Protocol, ProtocolPointer}; -use crate::{Char16, Event, Guid, Handle, Result, Status}; +use crate::{Char16, Event, Guid, Handle, Result, Status, StatusExt}; use bitflags::bitflags; use core::cell::UnsafeCell; use core::ffi::c_void; @@ -363,7 +363,7 @@ impl BootServices { AllocateType::MaxAddress(addr) => (1, addr), AllocateType::Address(addr) => (2, addr), }; - (self.allocate_pages)(ty, mem_ty, count, &mut addr).into_with_val(|| addr) + (self.allocate_pages)(ty, mem_ty, count, &mut addr).to_result_with_val(|| addr) } /// Frees memory pages allocated by UEFI. @@ -375,7 +375,7 @@ impl BootServices { /// * [`uefi::Status::NOT_FOUND`] /// * [`uefi::Status::INVALID_PARAMETER`] pub fn free_pages(&self, addr: PhysicalAddress, count: usize) -> Result { - (self.free_pages)(addr, count).into() + (self.free_pages)(addr, count).to_result() } /// Returns struct which contains the size of a single memory descriptor @@ -450,7 +450,7 @@ impl BootServices { &mut entry_version, ) } - .into_with_val(move || { + .to_result_with_val(move || { let len = map_size / entry_size; MemoryMap { @@ -472,7 +472,7 @@ impl BootServices { /// * [`uefi::Status::INVALID_PARAMETER`] pub fn allocate_pool(&self, mem_ty: MemoryType, size: usize) -> Result<*mut u8> { let mut buffer = ptr::null_mut(); - (self.allocate_pool)(mem_ty, size, &mut buffer).into_with_val(|| buffer) + (self.allocate_pool)(mem_ty, size, &mut buffer).to_result_with_val(|| buffer) } /// Frees memory allocated from a pool. @@ -483,7 +483,7 @@ impl BootServices { /// /// * [`uefi::Status::INVALID_PARAMETER`] pub fn free_pool(&self, addr: *mut u8) -> Result { - (self.free_pool)(addr).into() + (self.free_pool)(addr).to_result() } /// Creates an event @@ -526,7 +526,7 @@ impl BootServices { notify_ctx, event.as_mut_ptr(), ) - .into_with_val(|| event.assume_init()) + .to_result_with_val(|| event.assume_init()) } /// Creates a new `Event` of type `event_type`. The event's notification function, context, @@ -590,7 +590,7 @@ impl BootServices { event_group, event.as_mut_ptr(), ) - .into_with_val(|| event.assume_init()) + .to_result_with_val(|| event.assume_init()) } /// Sets the trigger for `EventType::TIMER` event. @@ -606,7 +606,7 @@ impl BootServices { TimerTrigger::Periodic(hundreds_ns) => (1, hundreds_ns), TimerTrigger::Relative(hundreds_ns) => (2, hundreds_ns), }; - unsafe { (self.set_timer)(event.unsafe_clone(), ty, time) }.into() + unsafe { (self.set_timer)(event.unsafe_clone(), ty, time) }.to_result() } /// Stops execution until an event is signaled. @@ -646,16 +646,17 @@ impl BootServices { pub fn wait_for_event(&self, events: &mut [Event]) -> Result> { let (number_of_events, events) = (events.len(), events.as_mut_ptr()); let mut index = MaybeUninit::::uninit(); - unsafe { (self.wait_for_event)(number_of_events, events, index.as_mut_ptr()) }.into_with( - || unsafe { index.assume_init() }, - |s| { - if s == Status::INVALID_PARAMETER { - unsafe { Some(index.assume_init()) } - } else { - None - } - }, - ) + unsafe { (self.wait_for_event)(number_of_events, events, index.as_mut_ptr()) } + .to_result_with( + || unsafe { index.assume_init() }, + |s| { + if s == Status::INVALID_PARAMETER { + unsafe { Some(index.assume_init()) } + } else { + None + } + }, + ) } /// Place 'event' in the signaled stated. If 'event' is already in the signaled state, @@ -679,7 +680,7 @@ impl BootServices { pub fn signal_event(&self, event: &Event) -> Result { // Safety: cloning this event should be safe, as we're directly passing it to firmware // and not keeping the clone around. - unsafe { (self.signal_event)(event.unsafe_clone()).into() } + unsafe { (self.signal_event)(event.unsafe_clone()).to_result() } } /// Removes `event` from any event group to which it belongs and closes it. If `event` was @@ -696,7 +697,7 @@ impl BootServices { /// /// * [`uefi::Status::INVALID_PARAMETER`] pub fn close_event(&self, event: Event) -> Result { - unsafe { (self.close_event)(event).into() } + unsafe { (self.close_event)(event).to_result() } } /// Checks to see if an event is signaled, without blocking execution to wait for it. @@ -752,7 +753,7 @@ impl BootServices { )) // this `unwrapped_unchecked` is safe, `handle` is guaranteed to be Some() if this call is // successful - .into_with_val(|| handle.unwrap_unchecked()) + .to_result_with_val(|| handle.unwrap_unchecked()) } /// Reinstalls a protocol interface on a device handle. `old_interface` is replaced with `new_interface`. @@ -781,7 +782,8 @@ impl BootServices { old_interface: *mut c_void, new_interface: *mut c_void, ) -> Result<()> { - (self.reinstall_protocol_interface)(handle, protocol, old_interface, new_interface).into() + (self.reinstall_protocol_interface)(handle, protocol, old_interface, new_interface) + .to_result() } /// Removes a protocol interface from a device handle. @@ -809,7 +811,7 @@ impl BootServices { protocol: &Guid, interface: *mut c_void, ) -> Result<()> { - (self.uninstall_protocol_interface)(handle, protocol, interface).into() + (self.uninstall_protocol_interface)(handle, protocol, interface).to_result() } /// Registers `event` to be signalled whenever a protocol interface is registered for @@ -837,7 +839,7 @@ impl BootServices { // Safety: we clone `event` a couple times, but there will be only one left once we return. unsafe { (self.register_protocol_notify)(protocol, event.unsafe_clone(), key.as_mut_ptr()) } // Safety: as long as this call is successful, `key` will be valid. - .into_with_val(|| unsafe { + .to_result_with_val(|| unsafe { ( event.unsafe_clone(), SearchType::ByRegisterNotify(key.assume_init()), @@ -887,7 +889,7 @@ impl BootServices { match (buffer, status) { (NULL_BUFFER, Status::BUFFER_TOO_SMALL) => Ok(buffer_len), - (_, other_status) => other_status.into_with_val(|| buffer_len), + (_, other_status) => other_status.to_result_with_val(|| buffer_len), } } @@ -915,12 +917,11 @@ impl BootServices { let mut handle = MaybeUninit::uninit(); let mut device_path_ptr = device_path.as_ffi_ptr(); unsafe { - (self.locate_device_path)(&P::GUID, &mut device_path_ptr, &mut handle).into_with_val( - || { + (self.locate_device_path)(&P::GUID, &mut device_path_ptr, &mut handle) + .to_result_with_val(|| { *device_path = DevicePath::from_ffi_ptr(device_path_ptr); handle.assume_init() - }, - ) + }) } } @@ -1041,7 +1042,7 @@ impl BootServices { source_size, &mut image_handle, ) - .into_with_val(|| image_handle.assume_init()) + .to_result_with_val(|| image_handle.assume_init()) } } @@ -1059,7 +1060,7 @@ impl BootServices { /// * [`uefi::Status::UNSUPPORTED`] /// * [`uefi::Status::INVALID_PARAMETER`] pub fn unload_image(&self, image_handle: Handle) -> Result { - (self.unload_image)(image_handle).into() + (self.unload_image)(image_handle).to_result() } /// Transfer control to a loaded image's entry point. @@ -1079,7 +1080,7 @@ impl BootServices { // TODO: implement returning exit data to the caller. let mut exit_data_size: usize = 0; let mut exit_data: *mut Char16 = ptr::null_mut(); - (self.start_image)(image_handle, &mut exit_data_size, &mut exit_data).into() + (self.start_image)(image_handle, &mut exit_data_size, &mut exit_data).to_result() } } @@ -1123,7 +1124,7 @@ impl BootServices { image: Handle, mmap_key: MemoryMapKey, ) -> Result { - (self.exit_boot_services)(image, mmap_key).into() + (self.exit_boot_services)(image, mmap_key).to_result() } /// Stalls the processor for an amount of time. @@ -1180,7 +1181,7 @@ impl BootServices { }) .unwrap_or((0, ptr::null_mut())); - unsafe { (self.set_watchdog_timer)(timeout, watchdog_code, data_len, data) }.into() + unsafe { (self.set_watchdog_timer)(timeout, watchdog_code, data_len, data) }.to_result() } /// Connect one or more drivers to a controller. @@ -1213,7 +1214,7 @@ impl BootServices { recursive, ) } - .into_with_err(|_| ()) + .to_result_with_err(|_| ()) } /// Disconnect one or more drivers from a controller. @@ -1234,7 +1235,7 @@ impl BootServices { child: Option, ) -> Result { unsafe { (self.disconnect_controller)(controller, driver_image, child) } - .into_with_err(|_| ()) + .to_result_with_err(|_| ()) } /// Open a protocol interface for a handle. @@ -1293,7 +1294,7 @@ impl BootServices { params.controller, attributes as u32, ) - .into_with_val(|| { + .to_result_with_val(|| { let interface = P::mut_ptr_from_ffi(interface) as *const UnsafeCell

; ScopedProtocol { @@ -1360,7 +1361,7 @@ impl BootServices { params.controller, TEST_PROTOCOL, ) - .into_with_val(|| ()) + .to_result_with_val(|| ()) } /// Get the list of protocol interface [`Guids`][Guid] that are installed @@ -1391,7 +1392,7 @@ impl BootServices { } } - status.into_with_val(|| ProtocolsPerHandle { + status.to_result_with_val(|| ProtocolsPerHandle { boot_services: self, protocols: protocols.cast::<&Guid>(), count, @@ -1420,7 +1421,7 @@ impl BootServices { }; unsafe { (self.locate_handle_buffer)(ty, guid, key, &mut num_handles, &mut buffer) } - .into_with_val(|| HandleBuffer { + .to_result_with_val(|| HandleBuffer { boot_services: self, count: num_handles, buffer, diff --git a/uefi/src/table/runtime.rs b/uefi/src/table/runtime.rs index 73e417afa..f83309567 100644 --- a/uefi/src/table/runtime.rs +++ b/uefi/src/table/runtime.rs @@ -5,7 +5,7 @@ use super::{Header, Revision}; use crate::data_types::FromSliceWithNulError; use crate::result::Error; use crate::table::boot::MemoryDescriptor; -use crate::{guid, CStr16, Char16, Guid, Result, Status}; +use crate::{guid, CStr16, Char16, Guid, Result, Status, StatusExt}; #[cfg(feature = "alloc")] use alloc::{vec, vec::Vec}; use bitflags::bitflags; @@ -88,7 +88,7 @@ impl RuntimeServices { pub fn get_time(&self) -> Result