From a998832f6b475d87746fd00e1ef4c8da9e23506d Mon Sep 17 00:00:00 2001 From: Alex Zenla Date: Sat, 1 Nov 2025 18:49:10 -0400 Subject: [PATCH] fix(utils): improve safety of media loader and utf-16 handling --- src/utils.rs | 15 +++++++++------ src/utils/media_loader.rs | 12 ++---------- 2 files changed, 11 insertions(+), 16 deletions(-) diff --git a/src/utils.rs b/src/utils.rs index ab9bde4..24352d9 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -280,11 +280,14 @@ pub fn utf16_bytes_to_cstring16(bytes: &[u8]) -> Result { bail!("utf16 bytes must be a multiple of 2"); } - // SAFETY: reinterpret &[u8] as &[u16]. - // We just validated it has the right length. - let ptr = bytes.as_ptr() as *const u16; - let len = bytes.len() / 2; - let utf16 = unsafe { std::slice::from_raw_parts(ptr, len) }; + // Convert the bytes to UTF-16 data. + let data = bytes + // Chunk everything into two bytes. + .chunks_exact(2) + // Reinterpret the bytes as u16 little-endian. + .map(|chunk| u16::from_le_bytes([chunk[0], chunk[1]])) + // Collect the result into a vector. + .collect::>(); - CString16::try_from(utf16.to_vec()).context("unable to convert utf16 bytes to CString16") + CString16::try_from(data).context("unable to convert utf16 bytes to CString16") } diff --git a/src/utils/media_loader.rs b/src/utils/media_loader.rs index 13615c8..0b49f2e 100644 --- a/src/utils/media_loader.rs +++ b/src/utils/media_loader.rs @@ -33,8 +33,6 @@ struct MediaLoaderProtocol { /// You MUST call [MediaLoaderHandle::unregister] when ready to unregister. /// [Drop] is not implemented for this type. pub struct MediaLoaderHandle { - /// The vendor GUID of the media loader. - guid: Guid, /// The handle of the media loader in the UEFI stack. handle: Handle, /// The protocol interface pointer. @@ -229,7 +227,6 @@ impl MediaLoaderHandle { // Return a handle to the media loader. Ok(Self { - guid, handle: primary_handle, protocol, path, @@ -239,13 +236,8 @@ impl MediaLoaderHandle { /// Unregisters a media loader from the UEFI stack. /// This will free the memory allocated by the passed data. pub fn unregister(self) -> Result<()> { - // Check if the media loader is registered. - // If it is not, we don't need to do anything. - if !Self::already_registered(self.guid)? { - return Ok(()); - } - - // SAFETY: We know that the media loader is registered, so we can safely uninstall it. + // SAFETY: We know that the media loader is registered if the handle is valid, + // so we can safely uninstall it. // We should have allocated the pointers involved, so we can safely free them. unsafe { // Uninstall the protocol interface for the device path protocol.