document by hand much more of the sprout code

This commit is contained in:
2025-10-19 23:03:28 -07:00
parent 8997e417b3
commit 106064d3e7
9 changed files with 153 additions and 8 deletions

View File

@@ -19,20 +19,26 @@ pub struct DriverDeclaration {
pub path: String, pub path: String,
} }
/// Loads the driver specified by the [driver] declaration.
fn load_driver(context: Rc<SproutContext>, driver: &DriverDeclaration) -> Result<()> { fn load_driver(context: Rc<SproutContext>, driver: &DriverDeclaration) -> Result<()> {
// Acquire the handle and device path of the loaded image.
let sprout_image = uefi::boot::image_handle(); let sprout_image = uefi::boot::image_handle();
let image_device_path_protocol = let image_device_path_protocol =
uefi::boot::open_protocol_exclusive::<LoadedImageDevicePath>(sprout_image) uefi::boot::open_protocol_exclusive::<LoadedImageDevicePath>(sprout_image)
.context("unable to open loaded image device path protocol")?; .context("unable to open loaded image device path protocol")?;
// Get the device path root of the sprout image.
let mut full_path = utils::device_path_root(&image_device_path_protocol)?; let mut full_path = utils::device_path_root(&image_device_path_protocol)?;
// Push the path of the driver from the root.
full_path.push_str(&context.stamp(&driver.path)); full_path.push_str(&context.stamp(&driver.path));
info!("driver path: {}", full_path); info!("driver path: {}", full_path);
// Convert the path to a device path.
let device_path = utils::text_to_device_path(&full_path)?; let device_path = utils::text_to_device_path(&full_path)?;
// Load the driver image.
let image = uefi::boot::load_image( let image = uefi::boot::load_image(
sprout_image, sprout_image,
uefi::boot::LoadImageSource::FromDevicePath { uefi::boot::LoadImageSource::FromDevicePath {
@@ -42,37 +48,55 @@ fn load_driver(context: Rc<SproutContext>, driver: &DriverDeclaration) -> Result
) )
.context("unable to load image")?; .context("unable to load image")?;
// Start the driver image, this is expected to return control to sprout.
// There is no guarantee that the driver will actually return control as it is
// just a standard EFI image.
uefi::boot::start_image(image).context("unable to start driver image")?; uefi::boot::start_image(image).context("unable to start driver image")?;
Ok(()) Ok(())
} }
/// Reconnects all handles to their controllers.
/// This is effectively a UEFI stack reload in a sense.
/// After we load all the drivers, we need to reconnect all of their handles
/// so that filesystems are recognized again.
fn reconnect() -> Result<()> { fn reconnect() -> Result<()> {
// Locate all of the handles in the UEFI stack.
let handles = uefi::boot::locate_handle_buffer(SearchType::AllHandles) let handles = uefi::boot::locate_handle_buffer(SearchType::AllHandles)
.context("unable to locate handles buffer")?; .context("unable to locate handles buffer")?;
for handle in handles.iter() { for handle in handles.iter() {
// ignore result as there is nothing we can do if it doesn't work. // Ignore the result as there is nothing we can do if reconnecting a controller fails.
// This is also likely to fail in some cases but should fail safely.
let _ = uefi::boot::connect_controller(*handle, None, None, true); let _ = uefi::boot::connect_controller(*handle, None, None, true);
} }
Ok(()) Ok(())
} }
/// Load all the drivers specified in `drivers`.
/// There is no driver order currently. This will reconnect all the controllers
/// to all handles if at least one driver was loaded.
pub fn load( pub fn load(
context: Rc<SproutContext>, context: Rc<SproutContext>,
drivers: &BTreeMap<String, DriverDeclaration>, drivers: &BTreeMap<String, DriverDeclaration>,
) -> Result<()> { ) -> Result<()> {
// If there are no drivers, we don't need to do anything.
if drivers.is_empty() { if drivers.is_empty() {
return Ok(()); return Ok(());
} }
info!("loading drivers"); info!("loading drivers");
// Load all the drivers in no particular order.
for (name, driver) in drivers { for (name, driver) in drivers {
load_driver(context.clone(), driver).context(format!("unable to load driver: {}", name))?; load_driver(context.clone(), driver).context(format!("unable to load driver: {}", name))?;
} }
// Reconnect all the controllers to all handles.
reconnect().context("unable to reconnect drivers")?; reconnect().context("unable to reconnect drivers")?;
info!("loaded drivers"); info!("loaded drivers");
// We've now loaded all the drivers, so we can return.
Ok(()) Ok(())
} }

View File

@@ -4,14 +4,25 @@ use anyhow::{Result, bail};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::rc::Rc; use std::rc::Rc;
/// The filesystem device match extractor.
pub mod filesystem_device_match; pub mod filesystem_device_match;
/// Declares an extractor configuration.
/// Extractors allow calculating values at runtime
/// using built-in sprout modules.
#[derive(Serialize, Deserialize, Default, Clone)] #[derive(Serialize, Deserialize, Default, Clone)]
pub struct ExtractorDeclaration { pub struct ExtractorDeclaration {
/// The filesystem device match extractor.
/// This extractor finds a filesystem using some search criteria and returns
/// the device root path that can concatenated with subpaths to access files
/// on a particular filesystem.
#[serde(default, rename = "filesystem-device-match")] #[serde(default, rename = "filesystem-device-match")]
pub filesystem_device_match: Option<FilesystemDeviceMatchExtractor>, pub filesystem_device_match: Option<FilesystemDeviceMatchExtractor>,
} }
/// Extracts the value using the specified `extractor` under the provided `context`.
/// The extractor must return a value, and if a value cannot be determined, an error
/// should be returned.
pub fn extract(context: Rc<SproutContext>, extractor: &ExtractorDeclaration) -> Result<String> { pub fn extract(context: Rc<SproutContext>, extractor: &ExtractorDeclaration) -> Result<String> {
if let Some(filesystem) = &extractor.filesystem_device_match { if let Some(filesystem) = &extractor.filesystem_device_match {
filesystem_device_match::extract(context, filesystem) filesystem_device_match::extract(context, filesystem)

View File

@@ -13,34 +13,57 @@ use uefi::proto::media::partition::PartitionInfo;
use uefi::{CString16, Guid}; use uefi::{CString16, Guid};
use uefi_raw::Status; use uefi_raw::Status;
/// The filesystem device match extractor.
/// This extractor finds a filesystem using some search criteria and returns
/// the device root path that can concatenated with subpaths to access files
/// on a particular filesystem.
///
/// This function only requires one of the criteria to match.
/// The fallback value can be used to provide a value if none is found.
#[derive(Serialize, Deserialize, Default, Clone)] #[derive(Serialize, Deserialize, Default, Clone)]
pub struct FilesystemDeviceMatchExtractor { pub struct FilesystemDeviceMatchExtractor {
/// Matches a filesystem that has the specified label.
#[serde(default, rename = "has-label")] #[serde(default, rename = "has-label")]
pub has_label: Option<String>, pub has_label: Option<String>,
/// Matches a filesystem that has the specified item.
/// An item is either a directory or file.
#[serde(default, rename = "has-item")] #[serde(default, rename = "has-item")]
pub has_item: Option<String>, pub has_item: Option<String>,
/// Matches a filesystem that has the specified partition UUID.
#[serde(default, rename = "has-partition-uuid")] #[serde(default, rename = "has-partition-uuid")]
pub has_partition_uuid: Option<String>, pub has_partition_uuid: Option<String>,
/// Matches a filesystem that has the specified partition type UUID.
#[serde(default, rename = "has-partition-type-uuid")] #[serde(default, rename = "has-partition-type-uuid")]
pub has_partition_type_uuid: Option<String>, pub has_partition_type_uuid: Option<String>,
/// The fallback value to use if no filesystem matches the criteria.
#[serde(default)] #[serde(default)]
pub fallback: Option<String>, pub fallback: Option<String>,
} }
/// Extract a filesystem device path using the specified `context` and `extractor` configuration.
pub fn extract( pub fn extract(
context: Rc<SproutContext>, context: Rc<SproutContext>,
extractor: &FilesystemDeviceMatchExtractor, extractor: &FilesystemDeviceMatchExtractor,
) -> Result<String> { ) -> Result<String> {
// Find all the filesystems inside the UEFI stack.
let handles = uefi::boot::find_handles::<SimpleFileSystem>() let handles = uefi::boot::find_handles::<SimpleFileSystem>()
.context("unable to find filesystem handles")?; .context("unable to find filesystem handles")?;
// Iterate over all the filesystems and check if they match the criteria.
for handle in handles { for handle in handles {
// This defines whether a match has been found.
let mut has_match = false; let mut has_match = false;
// Extract the partition info for this filesystem.
// There is no guarantee that the filesystem has a partition.
let partition_info = { let partition_info = {
// Open the partition info protocol for this handle.
let partition_info = uefi::boot::open_protocol_exclusive::<PartitionInfo>(handle); let partition_info = uefi::boot::open_protocol_exclusive::<PartitionInfo>(handle);
match partition_info { match partition_info {
Ok(partition_info) => { Ok(partition_info) => {
// GPT partitions have a unique partition GUID.
// MBR does not.
if let Some(gpt) = partition_info.gpt_partition_entry() { if let Some(gpt) = partition_info.gpt_partition_entry() {
let uuid = gpt.unique_partition_guid; let uuid = gpt.unique_partition_guid;
let type_uuid = gpt.partition_type_guid; let type_uuid = gpt.partition_type_guid;
@@ -51,10 +74,12 @@ pub fn extract(
} }
Err(error) => { Err(error) => {
// If the filesystem does not have a partition, that is okay.
if error.status() == Status::NOT_FOUND || error.status() == Status::UNSUPPORTED if error.status() == Status::NOT_FOUND || error.status() == Status::UNSUPPORTED
{ {
None None
} else { } else {
// We should still handle other errors gracefully.
Err(error).context("unable to open filesystem partition info")?; Err(error).context("unable to open filesystem partition info")?;
None None
} }
@@ -62,6 +87,7 @@ pub fn extract(
} }
}; };
// Check if the partition info matches partition uuid criteria.
if let Some((partition_uuid, _partition_type_guid)) = partition_info if let Some((partition_uuid, _partition_type_guid)) = partition_info
&& let Some(ref has_partition_uuid) = extractor.has_partition_uuid && let Some(ref has_partition_uuid) = extractor.has_partition_uuid
{ {
@@ -73,6 +99,7 @@ pub fn extract(
has_match = true; has_match = true;
} }
// Check if the partition info matches partition type uuid criteria.
if let Some((_partition_uuid, partition_type_guid)) = partition_info if let Some((_partition_uuid, partition_type_guid)) = partition_info
&& let Some(ref has_partition_type_uuid) = extractor.has_partition_type_uuid && let Some(ref has_partition_type_uuid) = extractor.has_partition_type_uuid
{ {
@@ -84,9 +111,11 @@ pub fn extract(
has_match = true; has_match = true;
} }
// Open the filesystem protocol for this handle.
let mut filesystem = uefi::boot::open_protocol_exclusive::<SimpleFileSystem>(handle) let mut filesystem = uefi::boot::open_protocol_exclusive::<SimpleFileSystem>(handle)
.context("unable to open filesystem protocol")?; .context("unable to open filesystem protocol")?;
// Check if the filesystem matches label criteria.
if let Some(ref label) = extractor.has_label { if let Some(ref label) = extractor.has_label {
let want_label = CString16::try_from(context.stamp(label).as_str()) let want_label = CString16::try_from(context.stamp(label).as_str())
.context("unable to convert label to CString16")?; .context("unable to convert label to CString16")?;
@@ -103,35 +132,46 @@ pub fn extract(
has_match = true; has_match = true;
} }
// Check if the filesystem matches item criteria.
if let Some(ref item) = extractor.has_item { if let Some(ref item) = extractor.has_item {
let want_item = CString16::try_from(context.stamp(item).as_str()) let want_item = CString16::try_from(context.stamp(item).as_str())
.context("unable to convert item to CString16")?; .context("unable to convert item to CString16")?;
let mut filesystem = FileSystem::new(filesystem); let mut filesystem = FileSystem::new(filesystem);
// Check the metadata of the item.
let metadata = filesystem.metadata(Path::new(&want_item)); let metadata = filesystem.metadata(Path::new(&want_item));
// Ignore filesystem errors as we can't do anything useful with the error.
if metadata.is_err() { if metadata.is_err() {
continue; continue;
} }
let metadata = metadata?; let metadata = metadata?;
// Only check directories and files.
if !(metadata.is_directory() || metadata.is_regular_file()) { if !(metadata.is_directory() || metadata.is_regular_file()) {
continue; continue;
} }
has_match = true; has_match = true;
} }
// If there is no match, continue to the next filesystem.
if !has_match { if !has_match {
continue; continue;
} }
// If we have a match, return the device root path.
let path = uefi::boot::open_protocol_exclusive::<DevicePath>(handle) let path = uefi::boot::open_protocol_exclusive::<DevicePath>(handle)
.context("unable to open filesystem device path")?; .context("unable to open filesystem device path")?;
let path = path.deref(); let path = path.deref();
// Acquire the device path root as a string.
return utils::device_path_root(path).context("unable to get device path root"); return utils::device_path_root(path).context("unable to get device path root");
} }
// If there is a fallback value, use it at this point.
if let Some(fallback) = &extractor.fallback { if let Some(fallback) = &extractor.fallback {
return Ok(fallback.clone()); return Ok(fallback.clone());
} }
// Without a fallback, we can't continue, so bail.
bail!("unable to find matching filesystem") bail!("unable to find matching filesystem")
} }

View File

@@ -20,6 +20,9 @@ pub struct PhasesConfiguration {
pub late: Vec<PhaseConfiguration>, pub late: Vec<PhaseConfiguration>,
} }
/// Configures a single phase of the boot process.
/// There can be multiple phase configurations that are
/// executed sequentially.
#[derive(Serialize, Deserialize, Default, Clone)] #[derive(Serialize, Deserialize, Default, Clone)]
pub struct PhaseConfiguration { pub struct PhaseConfiguration {
/// The actions to run when the phase is executed. /// The actions to run when the phase is executed.

View File

@@ -6,19 +6,22 @@ use std::os::uefi as uefi_std;
/// This fetches the system table and current image handle from uefi_std and injects /// This fetches the system table and current image handle from uefi_std and injects
/// them into the uefi crate. /// them into the uefi crate.
pub fn init() -> Result<()> { pub fn init() -> Result<()> {
// Acquire the system table and image handle from the uefi_std environment.
let system_table = uefi_std::env::system_table(); let system_table = uefi_std::env::system_table();
let image_handle = uefi_std::env::image_handle(); let image_handle = uefi_std::env::image_handle();
// SAFETY: The uefi variables above come from the Rust std. // SAFETY: The UEFI variables above come from the Rust std.
// These variables are nonnull and calling the uefi crates with these values is validated // These variables are not-null and calling the uefi crates with these values is validated
// to be corrected by hand. // to be corrected by hand.
unsafe { unsafe {
// Set the system table and image handle.
uefi::table::set_system_table(system_table.as_ptr().cast()); uefi::table::set_system_table(system_table.as_ptr().cast());
let handle = uefi::Handle::from_ptr(image_handle.as_ptr().cast()) let handle = uefi::Handle::from_ptr(image_handle.as_ptr().cast())
.context("unable to resolve image handle")?; .context("unable to resolve image handle")?;
uefi::boot::set_image_handle(handle); uefi::boot::set_image_handle(handle);
} }
// Initialize the uefi logger mechanism and other helpers.
uefi::helpers::init().context("unable to initialize uefi")?; uefi::helpers::init().context("unable to initialize uefi")?;
Ok(()) Ok(())
} }

View File

@@ -6,7 +6,10 @@ use uefi::proto::device_path::{DevicePath, PoolDevicePath};
use uefi::proto::media::fs::SimpleFileSystem; use uefi::proto::media::fs::SimpleFileSystem;
use uefi::{CString16, Handle}; use uefi::{CString16, Handle};
/// Support code for the EFI framebuffer.
pub mod framebuffer; pub mod framebuffer;
/// Support code for the media loader protocol.
pub mod media_loader; pub mod media_loader;
/// Parses the input [path] as a [DevicePath]. /// Parses the input [path] as a [DevicePath].

View File

@@ -1,13 +1,18 @@
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use uefi::proto::console::gop::{BltOp, BltPixel, BltRegion, GraphicsOutput}; use uefi::proto::console::gop::{BltOp, BltPixel, BltRegion, GraphicsOutput};
/// Represents the EFI framebuffer.
pub struct Framebuffer { pub struct Framebuffer {
/// The width of the framebuffer in pixels.
width: usize, width: usize,
/// The height of the framebuffer in pixels.
height: usize, height: usize,
/// The pixels of the framebuffer.
pixels: Vec<BltPixel>, pixels: Vec<BltPixel>,
} }
impl Framebuffer { impl Framebuffer {
/// Creates a new framebuffer of the specified `width` and `height`.
pub fn new(width: usize, height: usize) -> Self { pub fn new(width: usize, height: usize) -> Self {
Framebuffer { Framebuffer {
width, width,
@@ -16,10 +21,12 @@ impl Framebuffer {
} }
} }
/// Mutably acquires a pixel of the framebuffer at the specified `x` and `y` coordinate.
pub fn pixel(&mut self, x: usize, y: usize) -> Option<&mut BltPixel> { pub fn pixel(&mut self, x: usize, y: usize) -> Option<&mut BltPixel> {
self.pixels.get_mut(y * self.width + x) self.pixels.get_mut(y * self.width + x)
} }
/// Blit the framebuffer to the specified `gop` [GraphicsOutput].
pub fn blit(&self, gop: &mut GraphicsOutput) -> Result<()> { pub fn blit(&self, gop: &mut GraphicsOutput) -> Result<()> {
gop.blt(BltOp::BufferToVideo { gop.blt(BltOp::BufferToVideo {
buffer: &self.pixels, buffer: &self.pixels,

View File

@@ -11,9 +11,11 @@ use uefi_raw::{Boolean, Status};
pub mod constants; pub mod constants;
/// The media loader protocol.
#[derive(Debug)] #[derive(Debug)]
#[repr(C)] #[repr(C)]
struct MediaLoaderProtocol { struct MediaLoaderProtocol {
/// This is the standard EFI LoadFile2 protocol.
pub load_file: unsafe extern "efiapi" fn( pub load_file: unsafe extern "efiapi" fn(
this: *mut MediaLoaderProtocol, this: *mut MediaLoaderProtocol,
file_path: *const DevicePathProtocol, file_path: *const DevicePathProtocol,
@@ -21,7 +23,9 @@ struct MediaLoaderProtocol {
buffer_size: *mut usize, buffer_size: *mut usize,
buffer: *mut c_void, buffer: *mut c_void,
) -> Status, ) -> Status,
/// A pointer to a Box<[u8]> containing the data to load.
pub address: *mut c_void, pub address: *mut c_void,
/// The length of the data to load.
pub length: usize, pub length: usize,
} }
@@ -29,9 +33,13 @@ struct MediaLoaderProtocol {
/// You MUST call [MediaLoaderHandle::unregister] when ready to unregister. /// You MUST call [MediaLoaderHandle::unregister] when ready to unregister.
/// [Drop] is not implemented for this type. /// [Drop] is not implemented for this type.
pub struct MediaLoaderHandle { pub struct MediaLoaderHandle {
/// The vendor GUID of the media loader.
guid: Guid, guid: Guid,
/// The handle of the media loader in the UEFI stack.
handle: Handle, handle: Handle,
/// The protocol interface pointer.
protocol: *mut MediaLoaderProtocol, protocol: *mut MediaLoaderProtocol,
/// The device path pointer.
path: *mut DevicePath, path: *mut DevicePath,
} }
@@ -50,11 +58,12 @@ impl MediaLoaderHandle {
buffer_size: *mut usize, buffer_size: *mut usize,
buffer: *mut c_void, buffer: *mut c_void,
) -> Status { ) -> Status {
// Check if the pointers are non-null first.
if this.is_null() || buffer_size.is_null() || file_path.is_null() { if this.is_null() || buffer_size.is_null() || file_path.is_null() {
return Status::INVALID_PARAMETER; return Status::INVALID_PARAMETER;
} }
// Boot policy must not be true, as that's special behavior that is irrelevant // Boot policy must not be true, and if it is, that is special behavior that is irrelevant
// for the media loader concept. // for the media loader concept.
if boot_policy == Boolean::TRUE { if boot_policy == Boolean::TRUE {
return Status::UNSUPPORTED; return Status::UNSUPPORTED;
@@ -63,48 +72,68 @@ impl MediaLoaderHandle {
// SAFETY: Validated as safe because this is checked to be non-null. It is the caller's // SAFETY: Validated as safe because this is checked to be non-null. It is the caller's
// responsibility to ensure that the right pointer is passed for [this]. // responsibility to ensure that the right pointer is passed for [this].
unsafe { unsafe {
// Check if the length and address are valid.
if (*this).length == 0 || (*this).address.is_null() { if (*this).length == 0 || (*this).address.is_null() {
return Status::NOT_FOUND; return Status::NOT_FOUND;
} }
// Check if the buffer is large enough.
// If it is not, we need to set the buffer size to the length of the data.
// This is the way that Linux calls this function, to check the size to allocate
// for the buffer that holds the data.
if buffer.is_null() || *buffer_size < (*this).length { if buffer.is_null() || *buffer_size < (*this).length {
*buffer_size = (*this).length; *buffer_size = (*this).length;
return Status::BUFFER_TOO_SMALL; return Status::BUFFER_TOO_SMALL;
} }
// Copy the data into the buffer.
buffer.copy_from((*this).address, (*this).length); buffer.copy_from((*this).address, (*this).length);
// Set the buffer size to the length of the data.
*buffer_size = (*this).length; *buffer_size = (*this).length;
} }
// We've successfully loaded the data.
Status::SUCCESS Status::SUCCESS
} }
/// Creates a new device path for the media loader based on a vendor `guid`.
fn device_path(guid: Guid) -> Box<DevicePath> { fn device_path(guid: Guid) -> Box<DevicePath> {
// The buffer for the device path.
let mut path = Vec::new(); let mut path = Vec::new();
// Build a device path for the media loader with a vendor-specific guid.
let path = DevicePathBuilder::with_vec(&mut path) let path = DevicePathBuilder::with_vec(&mut path)
.push(&Vendor { .push(&Vendor {
vendor_guid: guid, vendor_guid: guid,
vendor_defined_data: &[], vendor_defined_data: &[],
}) })
.unwrap() .unwrap() // We know that the device path is valid, so we can unwrap.
.finalize() .finalize()
.unwrap(); .unwrap(); // We know that the device path is valid, so we can unwrap.
// Convert the device path to a boxed device path.
// This is safer than dealing with a pooled device path.
path.to_boxed() path.to_boxed()
} }
/// Checks if the media loader is already registered with the UEFI stack.
fn already_registered(guid: Guid) -> Result<bool> { fn already_registered(guid: Guid) -> Result<bool> {
// Acquire the device path for the media loader.
let path = Self::device_path(guid); let path = Self::device_path(guid);
let mut existing_path = path.as_ref(); let mut existing_path = path.as_ref();
// Locate the LoadFile2 protocol for the media loader based on the device path.
let result = uefi::boot::locate_device_path::<LoadFile2>(&mut existing_path); let result = uefi::boot::locate_device_path::<LoadFile2>(&mut existing_path);
// If the result is okay, the media loader is already registered.
if result.is_ok() { if result.is_ok() {
return Ok(true); return Ok(true);
} else if let Err(error) = result } else if let Err(error) = result
&& error.status() != Status::NOT_FOUND && error.status() != Status::NOT_FOUND
// If the error is not found, that means it's not registered.
{ {
bail!("unable to locate media loader device path: {}", error); bail!("unable to locate media loader device path: {}", error);
} }
// The media loader is not registered.
Ok(false) Ok(false)
} }
@@ -112,13 +141,20 @@ impl MediaLoaderHandle {
/// This uses a special device path that other EFI programs will look at /// This uses a special device path that other EFI programs will look at
/// to load the data from. /// to load the data from.
pub fn register(guid: Guid, data: Box<[u8]>) -> Result<MediaLoaderHandle> { pub fn register(guid: Guid, data: Box<[u8]>) -> Result<MediaLoaderHandle> {
// Acquire the vendor device path for the media loader.
let path = Self::device_path(guid); let path = Self::device_path(guid);
let path = Box::leak(path);
// Check if the media loader is already registered.
// If it is, we can't register it again safely.
if Self::already_registered(guid)? { if Self::already_registered(guid)? {
bail!("media loader already registered"); bail!("media loader already registered");
} }
// Leak the device path to pass it to the UEFI stack.
let path = Box::leak(path);
// Install a protocol interface for the device path.
// This ensures it can be located by other EFI programs.
let mut handle = unsafe { let mut handle = unsafe {
uefi::boot::install_protocol_interface( uefi::boot::install_protocol_interface(
None, None,
@@ -128,16 +164,20 @@ impl MediaLoaderHandle {
} }
.context("unable to install media loader device path handle")?; .context("unable to install media loader device path handle")?;
// Leak the data we need to pass to the UEFI stack.
let data = Box::leak(data); let data = Box::leak(data);
// Allocate a new box for the protocol interface.
let protocol = Box::new(MediaLoaderProtocol { let protocol = Box::new(MediaLoaderProtocol {
load_file: Self::load_file, load_file: Self::load_file,
address: data.as_ptr() as *mut _, address: data.as_ptr() as *mut _,
length: data.len(), length: data.len(),
}); });
// Leak the protocol interface to pass it to the UEFI stack.
let protocol = Box::leak(protocol); let protocol = Box::leak(protocol);
// Install a protocol interface for the load file protocol for the media loader protocol.
handle = unsafe { handle = unsafe {
uefi::boot::install_protocol_interface( uefi::boot::install_protocol_interface(
Some(handle), Some(handle),
@@ -147,10 +187,13 @@ impl MediaLoaderHandle {
} }
.context("unable to install media loader load file handle")?; .context("unable to install media loader load file handle")?;
// Check if the media loader is registered.
// If it is not, we can't continue safely because something went wrong.
if !Self::already_registered(guid)? { if !Self::already_registered(guid)? {
bail!("media loader not registered when expected to be registered"); bail!("media loader not registered when expected to be registered");
} }
// Return a handle to the media loader.
Ok(Self { Ok(Self {
guid, guid,
handle, handle,
@@ -162,11 +205,16 @@ impl MediaLoaderHandle {
/// Unregisters a media loader from the UEFI stack. /// Unregisters a media loader from the UEFI stack.
/// This will free the memory allocated by the passed data. /// This will free the memory allocated by the passed data.
pub fn unregister(self) -> Result<()> { 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)? { if !Self::already_registered(self.guid)? {
return Ok(()); return Ok(());
} }
// SAFETY: We know that the media loader is registered, so we can safely uninstall it.
// We should have allocated the pointers involved, so we can safely free them.
unsafe { unsafe {
// Uninstall the protocol interface for the device path protocol.
uefi::boot::uninstall_protocol_interface( uefi::boot::uninstall_protocol_interface(
self.handle, self.handle,
&DevicePathProtocol::GUID, &DevicePathProtocol::GUID,
@@ -174,6 +222,7 @@ impl MediaLoaderHandle {
) )
.context("unable to uninstall media loader device path handle")?; .context("unable to uninstall media loader device path handle")?;
// Uninstall the protocol interface for the load file protocol.
uefi::boot::uninstall_protocol_interface( uefi::boot::uninstall_protocol_interface(
self.handle, self.handle,
&LoadFile2Protocol::GUID, &LoadFile2Protocol::GUID,
@@ -181,12 +230,16 @@ impl MediaLoaderHandle {
) )
.context("unable to uninstall media loader load file handle")?; .context("unable to uninstall media loader load file handle")?;
// Retrieve a box for the device path and protocols.
let path = Box::from_raw(self.path); let path = Box::from_raw(self.path);
let protocol = Box::from_raw(self.protocol); let protocol = Box::from_raw(self.protocol);
// Retrieve a box for the data we passed in.
let slice = let slice =
std::ptr::slice_from_raw_parts_mut(protocol.address as *mut u8, protocol.length); std::ptr::slice_from_raw_parts_mut(protocol.address as *mut u8, protocol.length);
let data = Box::from_raw(slice); let data = Box::from_raw(slice);
// Drop all the allocations explicitly, as we don't want to leak them.
drop(path); drop(path);
drop(protocol); drop(protocol);
drop(data); drop(data);

View File

@@ -13,7 +13,8 @@ pub mod xen {
/// The device path GUID for the Xen EFI config. /// The device path GUID for the Xen EFI config.
pub const XEN_EFI_CONFIG_MEDIA_GUID: Guid = guid!("bf61f458-a28e-46cd-93d7-07dac5e8cd66"); pub const XEN_EFI_CONFIG_MEDIA_GUID: Guid = guid!("bf61f458-a28e-46cd-93d7-07dac5e8cd66");
/// The device path GUID for the Xen EFI config. /// The device path GUID for the Xen EFI kernel.
pub const XEN_EFI_KERNEL_MEDIA_GUID: Guid = guid!("4010c8bf-6ced-40f5-a53f-e820aee8f34b"); pub const XEN_EFI_KERNEL_MEDIA_GUID: Guid = guid!("4010c8bf-6ced-40f5-a53f-e820aee8f34b");
/// The device path GUID for the Xen EFI ramdisk.
pub const XEN_EFI_RAMDISK_MEDIA_GUID: Guid = guid!("5db1fd01-c3cb-4812-b2ba-8791e52d4a89"); pub const XEN_EFI_RAMDISK_MEDIA_GUID: Guid = guid!("5db1fd01-c3cb-4812-b2ba-8791e52d4a89");
} }