interplane.Get Omega
Read in your language

aienux

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

Brought by drakestapleton

branch main Branches Tags History

aienux / vendor / uefi / src / proto / device_path / mod.rs

1267 lines · 44008 bytes Raw Blame History
1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3//! The UEFI device path [`Protocol`], i.e., UEFI device paths.
4//!
5//! This module provides high-level wrappers to work with UEFI device paths.
6//! Please find additional low-level information in the
7//! [device path section of `uefi-raw`].
8//!
9//! # Terminology: Device Paths, Device Path Instances, and Device Path Nodes
10//! An open UEFI device path [`Protocol`], also called _device path_, is a
11//! flexible and structured sequence of binary nodes that describes a route from
12//! the UEFI root to a particular device, controller, or file.
13//!
14//! An entire device path can be made up of multiple device path instances,
15//! and each instance is made up of multiple device path nodes. A device path
16//! _may_ contain multiple device-path instances, but typical paths contain only
17//! a single instance.
18//!
19//! Each node represents a step in the path: PCI device, partition, filesystem,
20//! file path, etc. Each node represents a step in the path: PCI device,
21//! partition, filesystem, file path, etc.
22//!
23//! Example of what a device path containing two instances (each comprised of
24//! three nodes) might look like:
25//!
26//! ```text
27//! ┌──────┬──────┬──────────────╥───────┬──────────┬────────────┐
28//! │ ACPI │ PCI │ END_INSTANCE ║ CDROM │ FILEPATH │ END_ENTIRE │
29//! └──────┴──────┴──────────────╨───────┴──────────┴────────────┘
30//! ↑ ↑ ↑ ↑ ↑ ↑ ↑
31//! ├─Node─╨─Node─╨─────Node─────╨─Node──╨───Node───╨────Node────┤
32//! ↑ ↑ ↑
33//! ├─── DevicePathInstance ─────╨────── DevicePathInstance ─────┤
34//! │ │
35//! └──────────────────── Entire DevicePath ─────────────────────┘
36//! ```
37//!
38//! # Types
39//!
40//! This module defines several types used to represent device paths.
41//! For constructing device paths, see the [`build`] module.
42//!
43//! * [`DevicePath`] is the root type that represents a full device
44//! path, containing one or more device path instance. It ends with an
45//! [`END_ENTIRE`] node. It implements [`Protocol`] (corresponding to
46//! `EFI_DEVICE_PATH_PROTOCOL`).
47//!
48//! * [`DevicePathInstance`] represents a single path instance within a
49//! device path. It ends with either an [`END_INSTANCE`] or [`END_ENTIRE`]
50//! node.
51//!
52//! * [`DevicePathNode`] represents a single node within a path. The
53//! node's [`device_type`] and [`sub_type`] must be examined to
54//! determine what type of data it contains.
55//!
56//! Specific node types have their own structures in these submodules:
57//! * [`acpi`]
58//! * [`bios_boot_spec`]
59//! * [`end`]
60//! * [`hardware`]
61//! * [`media`]
62//! * [`messaging`]
63//!
64//! * [`DevicePathNodeEnum`] contains variants for references to each
65//! type of node. Call [`DevicePathNode::as_enum`] to convert from a
66//! [`DevicePathNode`] reference to a `DevicePathNodeEnum`.
67//!
68//! * [`DevicePathHeader`] is a header present at the start of every
69//! node. It describes the type of node as well as the node's size.
70//!
71//! * [`FfiDevicePath`] is an opaque type used whenever a device path
72//! pointer is passed to or from external UEFI interfaces (i.e. where
73//! the UEFI spec uses `const* EFI_DEVICE_PATH_PROTOCOL`, `*const
74//! FfiDevicePath` should be used in the Rust definition). Many of the
75//! other types in this module are DSTs, so pointers to the type are
76//! "fat" and not suitable for FFI.
77//!
78//! * [`PoolDevicePath`] is an owned device path on the UEFI heap.
79//!
80//! All of these types use a packed layout and may appear on any byte
81//! boundary.
82//!
83//! Note: the API provided by this module is currently mostly limited to
84//! reading existing device paths rather than constructing new ones.
85//!
86//! # Submodules
87//!
88//! - utilities to construct device paths: [`build`]
89//! - utilities to transform device paths to a textual representation: [`text`]
90//! - DevicePathUtilities protocol:: [`util`]
91//!
92//!
93//! [`END_ENTIRE`]: DeviceSubType::END_ENTIRE
94//! [`END_INSTANCE`]: DeviceSubType::END_INSTANCE
95//! [`Protocol`]: crate::proto::Protocol
96//! [`device_type`]: DevicePathNode::device_type
97//! [`sub_type`]: DevicePathNode::sub_type
98//! [device path section of `uefi-raw`]: uefi_raw::protocol::device_path
99
100pub mod build;
101pub mod text;
102pub mod util;
103
104mod device_path_gen;
105
106pub use device_path_gen::{
107 DevicePathNodeEnum, acpi, bios_boot_spec, end, hardware, media, messaging,
108};
109pub use uefi_raw::protocol::device_path::{DeviceSubType, DeviceType};
110
111use crate::mem::PoolAllocation;
112use crate::proto::{ProtocolPointer, unsafe_protocol};
113use core::ffi::c_void;
114use core::fmt::{self, Debug, Display, Formatter};
115use core::ops::Deref;
116use core::{error, ptr};
117use ptr_meta::Pointee;
118use uefi_raw::protocol::device_path::DevicePathProtocol;
119#[cfg(feature = "alloc")]
120use {
121 crate::boot::{self, OpenProtocolAttributes, OpenProtocolParams, ScopedProtocol, SearchType},
122 crate::proto::device_path::text::{AllowShortcuts, DevicePathToText, DisplayOnly},
123 crate::proto::device_path::util::DevicePathUtilities,
124 crate::{CString16, Identify},
125 alloc::borrow::ToOwned,
126 alloc::boxed::Box,
127 core::mem,
128};
129
130opaque_type! {
131 /// Opaque type that should be used to represent a pointer to a
132 /// [`DevicePath`] or [`DevicePathNode`] in foreign function interfaces. This
133 /// type produces a thin pointer, unlike [`DevicePath`] and
134 /// [`DevicePathNode`].
135 pub struct FfiDevicePath;
136}
137
138/// Device path allocated from UEFI pool memory.
139///
140/// Please note that this differs from `Box<[DevicePath]>`. Although both
141/// represent owned values, a `Box<[DevicePath]>` is on the Rust heap which may
142/// or may not be backed by the UEFI heap.
143#[derive(Debug)]
144pub struct PoolDevicePath(pub(crate) PoolAllocation);
145
146impl Deref for PoolDevicePath {
147 type Target = DevicePath;
148
149 fn deref(&self) -> &Self::Target {
150 // SAFETY: The memory is valid.
151 unsafe { DevicePath::from_ffi_ptr(self.0.as_ptr().as_ptr().cast()) }
152 }
153}
154
155/// Device path node allocated from UEFI pool memory.
156#[derive(Debug)]
157pub struct PoolDevicePathNode(pub(crate) PoolAllocation);
158
159impl Deref for PoolDevicePathNode {
160 type Target = DevicePathNode;
161
162 fn deref(&self) -> &Self::Target {
163 // SAFETY: The memory is valid.
164 unsafe { DevicePathNode::from_ffi_ptr(self.0.as_ptr().as_ptr().cast()) }
165 }
166}
167
168/// Fixed header that appears at the start of every [`DevicePathNode`].
169///
170/// This type is ABI-compatible with `EFI_DEVICE_PATH_PROTOCOL`.
171#[derive(Clone, Copy, Debug, Eq, PartialEq)]
172#[repr(transparent)]
173pub struct DevicePathHeader(DevicePathProtocol);
174
175impl DevicePathHeader {
176 /// Constructs a new [`DevicePathHeader`].
177 #[must_use]
178 pub const fn new(major_type: DeviceType, sub_type: DeviceSubType, length: u16) -> Self {
179 Self(DevicePathProtocol {
180 major_type,
181 sub_type,
182 length: length.to_le_bytes(),
183 })
184 }
185
186 /// Returns the [`DeviceType`].
187 #[must_use]
188 pub const fn device_type(&self) -> DeviceType {
189 self.0.major_type
190 }
191
192 /// Returns the [`DeviceSubType`].
193 #[must_use]
194 pub const fn sub_type(&self) -> DeviceSubType {
195 self.0.sub_type
196 }
197
198 /// Returns the total length of the device path node.
199 #[must_use]
200 pub const fn length(&self) -> u16 {
201 self.0.length()
202 }
203}
204
205impl<'a> TryFrom<&'a [u8]> for &'a DevicePathHeader {
206 type Error = ByteConversionError;
207
208 fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
209 if size_of::<DevicePathHeader>() <= bytes.len() {
210 // SAFETY: The memory is valid.
211 unsafe { Ok(&*bytes.as_ptr().cast::<DevicePathHeader>()) }
212 } else {
213 Err(ByteConversionError::InvalidLength)
214 }
215 }
216}
217
218/// A single node within a [`DevicePath`].
219///
220/// Each node starts with a [`DevicePathHeader`]. The rest of the data
221/// in the node depends on the type of node. You can "cast" a node to a specific
222/// one like this:
223/// ```no_run
224/// use uefi::proto::device_path::DevicePath;
225/// use uefi::proto::device_path::media::FilePath;
226///
227/// let image_device_path: &DevicePath = unsafe { DevicePath::from_ffi_ptr(0x1337 as *const _) };
228/// let file_path = image_device_path
229/// .node_iter()
230/// .find_map(|node| {
231/// let node: &FilePath = node.try_into().ok()?;
232/// let path = node.path_name().to_cstring16().ok()?;
233/// Some(path.to_string().to_uppercase())
234/// });
235/// ```
236/// More types are available in [`uefi::proto::device_path`]. Builder types
237/// can be found in [`uefi::proto::device_path::build`]
238///
239/// See the [module-level documentation] for more details.
240///
241/// [module-level documentation]: crate::proto::device_path
242#[derive(Eq, Pointee)]
243#[repr(C, packed)]
244pub struct DevicePathNode {
245 header: DevicePathHeader,
246 data: [u8],
247}
248
249impl DevicePathNode {
250 /// Creates a [`DevicePathNode`] reference from an opaque pointer.
251 ///
252 /// # Safety
253 ///
254 /// The input pointer must point to valid data. That data must
255 /// remain valid for the lifetime `'a`, and cannot be mutated during
256 /// that lifetime. The length of the node is taken from its header, so
257 /// the memory must be readable for at least that many bytes.
258 ///
259 /// # Panics
260 ///
261 /// Panics if the node's length is smaller than the size of
262 /// [`DevicePathHeader`], which violates the UEFI specification.
263 #[must_use]
264 pub unsafe fn from_ffi_ptr<'a>(ptr: *const FfiDevicePath) -> &'a Self {
265 // SAFETY: The memory is valid.
266 let header = unsafe { *ptr.cast::<DevicePathHeader>() };
267
268 let data_len = usize::from(header.length())
269 .checked_sub(size_of::<DevicePathHeader>())
270 .expect("device path node length should cover the node header");
271 // SAFETY: The memory is valid.
272 unsafe { &*ptr_meta::from_raw_parts(ptr.cast(), data_len) }
273 }
274
275 /// Casts this node to a [`FfiDevicePath`] pointer.
276 #[must_use]
277 pub const fn as_ffi_ptr(&self) -> *const FfiDevicePath {
278 let ptr: *const Self = self;
279 ptr.cast::<FfiDevicePath>()
280 }
281
282 /// Returns the device type.
283 #[must_use]
284 pub const fn device_type(&self) -> DeviceType {
285 self.header.device_type()
286 }
287
288 /// Returns the device subtype.
289 #[must_use]
290 pub const fn sub_type(&self) -> DeviceSubType {
291 self.header.sub_type()
292 }
293
294 /// Tuple of the node's type and subtype.
295 #[must_use]
296 pub const fn full_type(&self) -> (DeviceType, DeviceSubType) {
297 (self.device_type(), self.sub_type())
298 }
299
300 /// Returns the size in bytes of the full [`DevicePathNode`], including the
301 /// header.
302 #[must_use]
303 pub const fn length(&self) -> u16 {
304 self.header.length()
305 }
306
307 /// Returns whether this node ends an entire [`DevicePath`].
308 #[must_use]
309 pub fn is_end_entire(&self) -> bool {
310 self.full_type() == (DeviceType::END, DeviceSubType::END_ENTIRE)
311 }
312
313 /// Returns the payload data of this node.
314 #[must_use]
315 pub const fn data(&self) -> &[u8] {
316 &self.data
317 }
318
319 /// Converts a generic [`DevicePathNode`] reference to an enum
320 /// of more specific node types.
321 pub fn as_enum(&self) -> Result<DevicePathNodeEnum<'_>, NodeConversionError> {
322 DevicePathNodeEnum::try_from(self)
323 }
324
325 /// Transforms the device path node to an owned UEFI string ([`CString16`])
326 /// using the [`DevicePathToText`] protocol.
327 #[cfg(feature = "alloc")]
328 pub fn to_string16(
329 &self,
330 display_only: DisplayOnly,
331 allow_shortcuts: AllowShortcuts,
332 ) -> Result<CString16, DevicePathToTextError> {
333 let to_text_protocol = open_text_protocol()?;
334
335 to_text_protocol
336 .convert_device_node_to_text(self, display_only, allow_shortcuts)
337 .map(|pool_string| {
338 let cstr16 = &*pool_string;
339 // Another allocation; pool string is dropped. This overhead
340 // is negligible. CString16 is more convenient to use.
341 CString16::from(cstr16)
342 })
343 .map_err(|_| DevicePathToTextError::OutOfMemory)
344 }
345}
346
347#[cfg(feature = "alloc")]
348impl Display for DevicePathNode {
349 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
350 // The conversion needs boot services, the device path to text
351 // protocol and pool memory, none of which is guaranteed.
352 let text = boot::are_boot_services_active()
353 .then(|| {
354 self.to_string16(DisplayOnly(true), AllowShortcuts(true))
355 .ok()
356 })
357 .flatten();
358 match text {
359 Some(text) => write!(f, "{text}"),
360 None => write!(f, "<device path node: {} bytes>", self.data.len()),
361 }
362 }
363}
364
365impl Debug for DevicePathNode {
366 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
367 f.debug_struct("DevicePathNode")
368 .field("header", &self.header)
369 .field("data", &&self.data)
370 .finish()
371 }
372}
373
374impl PartialEq for DevicePathNode {
375 fn eq(&self, other: &Self) -> bool {
376 self.header == other.header && self.data == other.data
377 }
378}
379
380impl<'a> TryFrom<&'a [u8]> for &'a DevicePathNode {
381 type Error = ByteConversionError;
382
383 fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
384 let dp = <&DevicePathHeader>::try_from(bytes)?;
385 let length = usize::from(dp.length());
386 if length >= size_of::<DevicePathHeader>() && length <= bytes.len() {
387 // SAFETY: The memory is valid.
388 unsafe { Ok(DevicePathNode::from_ffi_ptr(bytes.as_ptr().cast())) }
389 } else {
390 Err(ByteConversionError::InvalidLength)
391 }
392 }
393}
394
395/// A single device path instance within a fully-qualified [`DevicePath`], which
396/// ends with either an [`END_INSTANCE`] or [`END_ENTIRE`] node.
397///
398/// An instance is one of possibly multiple complete route to the target, e.g.,
399/// a file can be located via network device one or two.
400///
401/// Use [`DevicePath::instance_iter`] to get the path instances in a
402/// [`DevicePath`].
403///
404/// See the [module-level documentation] for more details.
405///
406/// [`END_ENTIRE`]: DeviceSubType::END_ENTIRE
407/// [`END_INSTANCE`]: DeviceSubType::END_INSTANCE
408/// [module-level documentation]: crate::proto::device_path
409#[repr(C, packed)]
410#[derive(Eq, Pointee)]
411pub struct DevicePathInstance {
412 data: [u8],
413}
414
415impl DevicePathInstance {
416 /// Returns an iterator over the [`DevicePathNodes`] in this
417 /// instance. Iteration ends when any [`DeviceType::END`] node is
418 /// reached.
419 ///
420 /// [`DevicePathNodes`]: DevicePathNode
421 #[must_use]
422 pub const fn node_iter(&self) -> DevicePathNodeIterator<'_> {
423 DevicePathNodeIterator {
424 nodes: &self.data,
425 stop_condition: StopCondition::AnyEndNode,
426 }
427 }
428
429 /// Returns a slice of the underlying bytes.
430 #[must_use]
431 pub const fn as_bytes(&self) -> &[u8] {
432 &self.data
433 }
434
435 /// Returns a boxed copy of that value.
436 ///
437 /// The semantics slightly differs from a [`PoolDevicePath`] but is
438 /// generally more idiomatic to use.
439 #[cfg(feature = "alloc")]
440 #[must_use]
441 pub fn to_boxed(&self) -> Box<Self> {
442 let data = self.data.to_owned();
443 let data = data.into_boxed_slice();
444 // SAFETY: This is safe as a DevicePath has the same layout.
445 unsafe { mem::transmute(data) }
446 }
447}
448
449impl Debug for DevicePathInstance {
450 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
451 f.debug_struct("DevicePathInstance")
452 .field("data", &&self.data)
453 .finish()
454 }
455}
456
457impl PartialEq for DevicePathInstance {
458 fn eq(&self, other: &Self) -> bool {
459 self.data == other.data
460 }
461}
462
463#[cfg(feature = "alloc")]
464impl ToOwned for DevicePathInstance {
465 type Owned = Box<Self>;
466
467 fn to_owned(&self) -> Self::Owned {
468 self.to_boxed()
469 }
470}
471
472/// High-level representation of the UEFI [device path protocol], often simply
473/// referred to as "device path".
474///
475/// This type represents an entire device path, possibly consisting of multiple
476/// [`DevicePathInstance`]s and [`DevicePathNode`]s.
477///
478/// Further, this Rust type is a DST and therefore typically exists as reference
479/// to parse underlying data correspondingly. To get an owned device path, you
480/// can use [`DevicePath::to_owned`].
481///
482/// See the [module-level documentation] for more details.
483///
484/// # Usage
485/// This type implements [`Protocol`] and therefore can be used on any
486/// device handle to obtain generic path/location information concerning the
487/// physical device or logical device. If the handle does not logically map to a
488/// physical device, the handle may not necessarily support the device path
489/// protocol. The device path describes the location of the device the handle is
490/// for. The size of the Device Path can be determined from the structures that
491/// make up the Device Path.
492///
493/// # Example
494/// ```rust,no_run
495/// use uefi::Handle;
496/// use uefi::boot::{open_protocol_exclusive, ScopedProtocol};
497/// use uefi::proto::device_path::DevicePath;
498/// use uefi::proto::device_path::text::{AllowShortcuts, DisplayOnly};
499/// use uefi::proto::loaded_image::LoadedImage;
500///
501/// fn open_device_path(image_handle: Handle) {
502/// let loaded_image = open_protocol_exclusive::<LoadedImage>(image_handle).unwrap();
503/// let device_handle = loaded_image.device().unwrap();
504/// let device_path: ScopedProtocol<DevicePath>
505/// = open_protocol_exclusive::<DevicePath>(device_handle).unwrap();
506/// log::debug!(
507/// "Device path: {device_path}",
508/// );
509/// }
510/// ```
511///
512/// [module-level documentation]: crate::proto::device_path
513/// [`END_ENTIRE`]: DeviceSubType::END_ENTIRE
514/// [`DevicePathProtocol`]: uefi_raw::protocol::device_path::DevicePathProtocol
515/// [`Protocol`]: uefi::proto::Protocol
516/// [device path protocol]: uefi_raw::protocol::device_path
517#[repr(C, packed)]
518#[unsafe_protocol(DevicePathProtocol::GUID)]
519#[derive(Eq, Pointee)]
520pub struct DevicePath {
521 data: [u8],
522}
523
524// References to the DST are transmuted from/to slice references; ensure
525// both have the same fat-pointer layout.
526const _: () = assert!(size_of::<&DevicePath>() == size_of::<&[u8]>());
527
528impl ProtocolPointer for DevicePath {
529 unsafe fn ptr_from_ffi(ptr: *const c_void) -> *const Self {
530 // SAFETY: The memory is valid.
531 ptr_meta::from_raw_parts(ptr.cast(), unsafe { Self::size_in_bytes_from_ptr(ptr) })
532 }
533
534 unsafe fn mut_ptr_from_ffi(ptr: *mut c_void) -> *mut Self {
535 // SAFETY: The memory is valid.
536 ptr_meta::from_raw_parts_mut(ptr.cast(), unsafe { Self::size_in_bytes_from_ptr(ptr) })
537 }
538}
539
540impl DevicePath {
541 /// Calculate the size in bytes of the entire `DevicePath` starting
542 /// at `ptr`. This adds up each node's length, including the
543 /// end-entire node.
544 unsafe fn size_in_bytes_from_ptr(ptr: *const c_void) -> usize {
545 let mut ptr = ptr.cast::<u8>();
546 let mut total_size_in_bytes: usize = 0;
547 loop {
548 // SAFETY: The memory is valid.
549 let node = unsafe { DevicePathNode::from_ffi_ptr(ptr.cast::<FfiDevicePath>()) };
550 let node_size_in_bytes = usize::from(node.length());
551 total_size_in_bytes += node_size_in_bytes;
552 if node.is_end_entire() {
553 break;
554 }
555 // SAFETY: The memory is valid.
556 ptr = unsafe { ptr.add(node_size_in_bytes) };
557 }
558
559 total_size_in_bytes
560 }
561
562 /// Calculate the size in bytes of the entire `DevicePath` starting
563 /// at `bytes`. This adds up each node's length, including the
564 /// end-entire node.
565 ///
566 /// # Errors
567 ///
568 /// The [`ByteConversionError::InvalidLength`] error will be returned
569 /// when the length of the given bytes slice cannot contain the full
570 /// [`DevicePath`] represented by the slice.
571 fn size_in_bytes_from_slice(mut bytes: &[u8]) -> Result<usize, ByteConversionError> {
572 let max_size_in_bytes = bytes.len();
573 let mut total_size_in_bytes: usize = 0;
574 loop {
575 let node = <&DevicePathNode>::try_from(bytes)?;
576 let node_size_in_bytes = usize::from(node.length());
577 total_size_in_bytes += node_size_in_bytes;
578 // Length of last processed node extends past the bytes slice.
579 if total_size_in_bytes > max_size_in_bytes {
580 return Err(ByteConversionError::InvalidLength);
581 }
582 if node.is_end_entire() {
583 break;
584 }
585 bytes = &bytes[node_size_in_bytes..];
586 }
587
588 Ok(total_size_in_bytes)
589 }
590
591 /// Creates a [`DevicePath`] reference from an opaque pointer.
592 ///
593 /// # Safety
594 ///
595 /// The input pointer must point to valid data. That data must
596 /// remain valid for the lifetime `'a`, and cannot be mutated during
597 /// that lifetime. The length of the path is determined by walking its
598 /// nodes up to the end-entire node, so the data must contain one. A
599 /// path without it makes this function read past its end, which is
600 /// undefined behavior.
601 ///
602 /// # Panics
603 ///
604 /// Panics if any node's length is smaller than the size of
605 /// [`DevicePathHeader`], see [`DevicePathNode::from_ffi_ptr`].
606 #[must_use]
607 pub unsafe fn from_ffi_ptr<'a>(ptr: *const FfiDevicePath) -> &'a Self {
608 // SAFETY: The memory is valid.
609 unsafe { &*Self::ptr_from_ffi(ptr.cast::<c_void>()) }
610 }
611
612 /// Casts this path to a [`FfiDevicePath`] pointer.
613 #[must_use]
614 pub const fn as_ffi_ptr(&self) -> *const FfiDevicePath {
615 ptr::from_ref(self).cast()
616 }
617
618 /// Returns an iterator over the [`DevicePathInstance`]s in this path.
619 #[must_use]
620 pub const fn instance_iter(&self) -> DevicePathInstanceIterator<'_> {
621 DevicePathInstanceIterator {
622 remaining_path: Some(self),
623 }
624 }
625
626 /// Returns an iterator over the [`DevicePathNode`]s starting at
627 /// `self`. Iteration ends when a path is reached where
628 /// [`is_end_entire`][DevicePathNode::is_end_entire] is true. That ending
629 /// path is not returned by the iterator.
630 #[must_use]
631 pub const fn node_iter(&self) -> DevicePathNodeIterator<'_> {
632 DevicePathNodeIterator {
633 nodes: &self.data,
634 stop_condition: StopCondition::EndEntireNode,
635 }
636 }
637
638 /// Returns a slice of the underlying bytes.
639 #[must_use]
640 pub const fn as_bytes(&self) -> &[u8] {
641 &self.data
642 }
643
644 /// Returns a boxed copy of that value on the Rust heap.
645 ///
646 /// The semantics slightly differs from a [`PoolDevicePath`] but is
647 /// generally more idiomatic to use.
648 #[cfg(feature = "alloc")]
649 #[must_use]
650 pub fn to_boxed(&self) -> Box<Self> {
651 let data = self.data.to_owned();
652 let data = data.into_boxed_slice();
653 // SAFETY: This is safe as a DevicePath has the same layout.
654 unsafe { mem::transmute(data) }
655 }
656
657 /// Returns an owned pool copy of this path.
658 #[cfg(feature = "alloc")]
659 pub fn to_pool(&self) -> Result<PoolDevicePath, DevicePathUtilitiesError> {
660 open_utility_protocol()?
661 .duplicate_path(self)
662 .map_err(|_| DevicePathUtilitiesError::OutOfMemory)
663 }
664
665 /// Transforms the device path to an owned UEFI string ([`CString16`])
666 /// using the [`DevicePathToText`] protocol.
667 #[cfg(feature = "alloc")]
668 // to_string() comes from Display and produces a Rust string.
669 pub fn to_string16(
670 &self,
671 display_only: DisplayOnly,
672 allow_shortcuts: AllowShortcuts,
673 ) -> Result<CString16, DevicePathToTextError> {
674 let to_text_protocol = open_text_protocol()?;
675
676 to_text_protocol
677 .convert_device_path_to_text(self, display_only, allow_shortcuts)
678 .map(|pool_string| {
679 let cstr16 = &*pool_string;
680 // Another allocation; pool string is dropped. This overhead
681 // is negligible. CString16 is more convenient to use.
682 CString16::from(cstr16)
683 })
684 .map_err(|_| DevicePathToTextError::OutOfMemory)
685 }
686
687 /// Allocates and returns a new [`DevicePath`] by copying this one and appending the given `right` path.
688 #[cfg(feature = "alloc")]
689 pub fn append_path(&self, right: &Self) -> Result<PoolDevicePath, DevicePathUtilitiesError> {
690 open_utility_protocol()?
691 .append_path(self, right)
692 .map_err(|_| DevicePathUtilitiesError::OutOfMemory)
693 }
694
695 /// Allocates and returns a new [`DevicePath`] by copying this one and appending the given `right` node.
696 #[cfg(feature = "alloc")]
697 pub fn append_node(
698 &self,
699 right: &DevicePathNode,
700 ) -> Result<PoolDevicePath, DevicePathUtilitiesError> {
701 open_utility_protocol()?
702 .append_node(self, right)
703 .map_err(|_| DevicePathUtilitiesError::OutOfMemory)
704 }
705}
706
707#[cfg(feature = "alloc")]
708impl Display for DevicePath {
709 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
710 // The conversion needs boot services, the device path to text
711 // protocol and pool memory, none of which is guaranteed.
712 let text = boot::are_boot_services_active()
713 .then(|| {
714 self.to_string16(DisplayOnly(true), AllowShortcuts(true))
715 .ok()
716 })
717 .flatten();
718 match text {
719 Some(text) => write!(f, "{text}"),
720 None => write!(f, "<device path: {} bytes>", self.data.len()),
721 }
722 }
723}
724
725impl Debug for DevicePath {
726 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
727 f.debug_struct("DevicePath")
728 .field("data", &&self.data)
729 .finish()
730 }
731}
732
733impl PartialEq for DevicePath {
734 fn eq(&self, other: &Self) -> bool {
735 self.data == other.data
736 }
737}
738
739impl<'a> TryFrom<&'a [u8]> for &'a DevicePath {
740 type Error = ByteConversionError;
741
742 fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
743 let len = DevicePath::size_in_bytes_from_slice(bytes)?;
744 // SAFETY: The memory is valid.
745 unsafe { Ok(&*ptr_meta::from_raw_parts(bytes.as_ptr().cast(), len)) }
746 }
747}
748
749#[cfg(feature = "alloc")]
750impl ToOwned for DevicePath {
751 type Owned = Box<Self>;
752
753 fn to_owned(&self) -> Self::Owned {
754 self.to_boxed()
755 }
756}
757
758/// Iterator over the [`DevicePathInstance`]s in a [`DevicePath`].
759///
760/// This struct is returned by [`DevicePath::instance_iter`].
761#[derive(Debug)]
762pub struct DevicePathInstanceIterator<'a> {
763 remaining_path: Option<&'a DevicePath>,
764}
765
766impl<'a> Iterator for DevicePathInstanceIterator<'a> {
767 type Item = &'a DevicePathInstance;
768
769 fn next(&mut self) -> Option<Self::Item> {
770 let remaining_path = self.remaining_path?;
771
772 let mut instance_size: usize = 0;
773
774 // Find the end of the instance, which can be either kind of end
775 // node (end-instance or end-entire). Count the number of bytes
776 // up to and including that end node.
777 let node_iter = DevicePathNodeIterator {
778 nodes: &remaining_path.data,
779 stop_condition: StopCondition::NoMoreNodes,
780 };
781 for node in node_iter {
782 instance_size += usize::from(node.length());
783 if node.device_type() == DeviceType::END {
784 break;
785 }
786 }
787
788 let (head, rest) = remaining_path.data.split_at(instance_size);
789
790 if rest.is_empty() {
791 self.remaining_path = None;
792 } else {
793 // SAFETY: The memory is valid.
794 self.remaining_path = unsafe {
795 Some(&*ptr_meta::from_raw_parts(
796 rest.as_ptr().cast::<()>(),
797 rest.len(),
798 ))
799 };
800 }
801
802 // SAFETY: The memory is valid.
803 unsafe {
804 Some(&*ptr_meta::from_raw_parts(
805 head.as_ptr().cast::<()>(),
806 head.len(),
807 ))
808 }
809 }
810}
811
812#[derive(Debug)]
813enum StopCondition {
814 AnyEndNode,
815 EndEntireNode,
816 NoMoreNodes,
817}
818
819/// Iterator over [`DevicePathNode`]s.
820///
821/// This struct is returned by [`DevicePath::node_iter`] and
822/// [`DevicePathInstance::node_iter`].
823#[derive(Debug)]
824pub struct DevicePathNodeIterator<'a> {
825 nodes: &'a [u8],
826 stop_condition: StopCondition,
827}
828
829impl<'a> Iterator for DevicePathNodeIterator<'a> {
830 type Item = &'a DevicePathNode;
831
832 fn next(&mut self) -> Option<Self::Item> {
833 if self.nodes.is_empty() {
834 return None;
835 }
836
837 let node =
838 // SAFETY: The memory is valid.
839 unsafe { DevicePathNode::from_ffi_ptr(self.nodes.as_ptr().cast::<FfiDevicePath>()) };
840
841 // Check if an early stop condition has been reached.
842 let stop = match self.stop_condition {
843 StopCondition::AnyEndNode => node.device_type() == DeviceType::END,
844 StopCondition::EndEntireNode => node.is_end_entire(),
845 StopCondition::NoMoreNodes => false,
846 };
847
848 if stop {
849 // Clear the remaining node data so that future calls to
850 // next() immediately return `None`.
851 self.nodes = &[];
852 None
853 } else {
854 // Advance to next node.
855 let node_size = usize::from(node.length());
856 self.nodes = &self.nodes[node_size..];
857 Some(node)
858 }
859 }
860}
861
862/// Error returned when attempting to convert from a `&[u8]` to a
863/// [`DevicePath`] type.
864#[derive(Clone, Copy, Debug, Eq, PartialEq)]
865pub enum ByteConversionError {
866 /// The length of the given slice is not valid for its [`DevicePath`] type.
867 InvalidLength,
868}
869
870/// Error returned when converting from a [`DevicePathNode`] to a more
871/// specific node type.
872#[derive(Clone, Copy, Debug, Eq, PartialEq)]
873pub enum NodeConversionError {
874 /// The requested node type does not match the actual node type.
875 DifferentType,
876
877 /// The length of the node data is not valid for its type.
878 InvalidLength,
879
880 /// The node type is not currently supported.
881 UnsupportedType,
882}
883
884/// Loaded Image Device Path [`Protocol`].
885///
886/// Protocol for accessing the device path that was passed in to [`load_image`]
887/// when loading a PE/COFF image.
888///
889/// The layout of this type is the same as a [`DevicePath`].
890///
891/// [`load_image`]: crate::boot::load_image
892/// [`Protocol`]: uefi::proto::Protocol
893#[repr(transparent)]
894#[unsafe_protocol("bc62157e-3e33-4fec-9920-2d3b36d750df")]
895#[derive(Debug, Pointee)]
896pub struct LoadedImageDevicePath(DevicePath);
897
898impl ProtocolPointer for LoadedImageDevicePath {
899 unsafe fn ptr_from_ffi(ptr: *const c_void) -> *const Self {
900 // SAFETY: The memory is valid.
901 ptr_meta::from_raw_parts(ptr.cast(), unsafe {
902 DevicePath::size_in_bytes_from_ptr(ptr)
903 })
904 }
905
906 unsafe fn mut_ptr_from_ffi(ptr: *mut c_void) -> *mut Self {
907 // SAFETY: The memory is valid.
908 ptr_meta::from_raw_parts_mut(ptr.cast(), unsafe {
909 DevicePath::size_in_bytes_from_ptr(ptr)
910 })
911 }
912}
913
914impl Deref for LoadedImageDevicePath {
915 type Target = DevicePath;
916
917 fn deref(&self) -> &DevicePath {
918 &self.0
919 }
920}
921
922/// Errors that may happen when a device path is transformed to a string
923/// using:
924/// - [`DevicePath::to_string16`]
925/// - [`DevicePathNode::to_string16`]
926#[derive(Debug)]
927pub enum DevicePathToTextError {
928 /// Can't locate a handle buffer with handles associated with the
929 /// [`DevicePathToText`] protocol.
930 CantLocateHandleBuffer(crate::Error),
931 /// There is no handle supporting the [`DevicePathToText`] protocol.
932 NoHandle,
933 /// The handle supporting the [`DevicePathToText`] protocol exists but it
934 /// could not be opened.
935 CantOpenProtocol(crate::Error),
936 /// Failed to allocate pool memory.
937 OutOfMemory,
938}
939
940impl Display for DevicePathToTextError {
941 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
942 write!(f, "{self:?}")
943 }
944}
945
946impl error::Error for DevicePathToTextError {
947 fn source(&self) -> Option<&(dyn error::Error + 'static)> {
948 match self {
949 Self::CantLocateHandleBuffer(e) => Some(e),
950 Self::CantOpenProtocol(e) => Some(e),
951 _ => None,
952 }
953 }
954}
955
956/// Helper function to open the [`DevicePathToText`] protocol using the boot
957/// services.
958#[cfg(feature = "alloc")]
959fn open_text_protocol() -> Result<ScopedProtocol<DevicePathToText>, DevicePathToTextError> {
960 let &handle = boot::locate_handle_buffer(SearchType::ByProtocol(&DevicePathToText::GUID))
961 .map_err(DevicePathToTextError::CantLocateHandleBuffer)?
962 .first()
963 .ok_or(DevicePathToTextError::NoHandle)?;
964
965 // SAFETY: The memory is valid.
966 unsafe {
967 boot::open_protocol::<DevicePathToText>(
968 OpenProtocolParams {
969 handle,
970 agent: boot::image_handle(),
971 controller: None,
972 },
973 OpenProtocolAttributes::GetProtocol,
974 )
975 }
976 .map_err(DevicePathToTextError::CantOpenProtocol)
977}
978
979/// Errors that may occur when working with the [`DevicePathUtilities`] protocol.
980///
981/// These errors are typically encountered during operations involving device
982/// paths, such as appending or manipulating path segments.
983#[derive(Debug)]
984pub enum DevicePathUtilitiesError {
985 /// Can't locate a handle buffer with handles associated with the
986 /// [`DevicePathUtilities`] protocol.
987 CantLocateHandleBuffer(crate::Error),
988 /// No handle supporting the [`DevicePathUtilities`] protocol was found.
989 NoHandle,
990 /// The handle supporting the [`DevicePathUtilities`] protocol exists but
991 /// it could not be opened.
992 CantOpenProtocol(crate::Error),
993 /// Memory allocation failed during device path operations.
994 OutOfMemory,
995}
996
997impl Display for DevicePathUtilitiesError {
998 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
999 write!(f, "{self:?}")
1000 }
1001}
1002
1003impl error::Error for DevicePathUtilitiesError {
1004 fn source(&self) -> Option<&(dyn error::Error + 'static)> {
1005 match self {
1006 Self::CantLocateHandleBuffer(e) => Some(e),
1007 Self::CantOpenProtocol(e) => Some(e),
1008 _ => None,
1009 }
1010 }
1011}
1012
1013/// Helper function to open the [`DevicePathUtilities`] protocol using the boot
1014/// services.
1015#[cfg(feature = "alloc")]
1016fn open_utility_protocol() -> Result<ScopedProtocol<DevicePathUtilities>, DevicePathUtilitiesError>
1017{
1018 let &handle = boot::locate_handle_buffer(SearchType::ByProtocol(&DevicePathUtilities::GUID))
1019 .map_err(DevicePathUtilitiesError::CantLocateHandleBuffer)?
1020 .first()
1021 .ok_or(DevicePathUtilitiesError::NoHandle)?;
1022
1023 // SAFETY: The memory is valid.
1024 unsafe {
1025 boot::open_protocol::<DevicePathUtilities>(
1026 OpenProtocolParams {
1027 handle,
1028 agent: boot::image_handle(),
1029 controller: None,
1030 },
1031 OpenProtocolAttributes::GetProtocol,
1032 )
1033 }
1034 .map_err(DevicePathUtilitiesError::CantOpenProtocol)
1035}
1036
1037#[cfg(test)]
1038mod tests {
1039 use super::*;
1040 use alloc::vec::Vec;
1041
1042 /// Adds a node to `path` from raw data.
1043 fn add_node(path: &mut Vec<u8>, device_type: u8, sub_type: u8, node_data: &[u8]) {
1044 path.push(device_type);
1045 path.push(sub_type);
1046 path.extend(
1047 u16::try_from(size_of::<DevicePathHeader>() + node_data.len())
1048 .unwrap()
1049 .to_le_bytes(),
1050 );
1051 path.extend(node_data);
1052 }
1053
1054 /// Creates a test device path list as raw bytes.
1055 fn create_raw_device_path() -> Vec<u8> {
1056 let mut raw_data = Vec::new();
1057
1058 // First path instance.
1059 add_node(&mut raw_data, 0xa0, 0xb0, &[10, 11]);
1060 add_node(&mut raw_data, 0xa1, 0xb1, &[20, 21, 22, 23]);
1061 add_node(
1062 &mut raw_data,
1063 DeviceType::END.0,
1064 DeviceSubType::END_INSTANCE.0,
1065 &[],
1066 );
1067 // Second path instance.
1068 add_node(&mut raw_data, 0xa2, 0xb2, &[30, 31]);
1069 add_node(&mut raw_data, 0xa3, 0xb3, &[40, 41, 42, 43]);
1070 add_node(
1071 &mut raw_data,
1072 DeviceType::END.0,
1073 DeviceSubType::END_ENTIRE.0,
1074 &[],
1075 );
1076
1077 raw_data
1078 }
1079
1080 /// Checks that `node` has the expected content.
1081 fn check_node(node: &DevicePathNode, device_type: u8, sub_type: u8, node_data: &[u8]) {
1082 assert_eq!(node.device_type().0, device_type);
1083 assert_eq!(node.sub_type().0, sub_type);
1084 assert_eq!(
1085 node.length(),
1086 u16::try_from(size_of::<DevicePathHeader>() + node_data.len()).unwrap()
1087 );
1088 assert_eq!(&node.data, node_data);
1089 }
1090
1091 #[test]
1092 fn test_device_path_nodes() {
1093 let raw_data = create_raw_device_path();
1094 // SAFETY: The memory is valid.
1095 let dp = unsafe { DevicePath::from_ffi_ptr(raw_data.as_ptr().cast()) };
1096
1097 // Check that the size is the sum of the nodes' lengths.
1098 assert_eq!(size_of_val(dp), 6 + 8 + 4 + 6 + 8 + 4);
1099
1100 // Check the list's node iter.
1101 let nodes: Vec<_> = dp.node_iter().collect();
1102 check_node(nodes[0], 0xa0, 0xb0, &[10, 11]);
1103 check_node(nodes[1], 0xa1, 0xb1, &[20, 21, 22, 23]);
1104 check_node(
1105 nodes[2],
1106 DeviceType::END.0,
1107 DeviceSubType::END_INSTANCE.0,
1108 &[],
1109 );
1110 check_node(nodes[3], 0xa2, 0xb2, &[30, 31]);
1111 check_node(nodes[4], 0xa3, 0xb3, &[40, 41, 42, 43]);
1112 // The end-entire node is not returned by the iterator.
1113 assert_eq!(nodes.len(), 5);
1114 }
1115
1116 #[test]
1117 fn test_device_path_instances() {
1118 let raw_data = create_raw_device_path();
1119 // SAFETY: The memory is valid.
1120 let dp = unsafe { DevicePath::from_ffi_ptr(raw_data.as_ptr().cast()) };
1121
1122 // Check the list's instance iter.
1123 let mut iter = dp.instance_iter();
1124 let mut instance = iter.next().unwrap();
1125 assert_eq!(size_of_val(instance), 6 + 8 + 4);
1126
1127 // Check the first instance's node iter.
1128 let nodes: Vec<_> = instance.node_iter().collect();
1129 check_node(nodes[0], 0xa0, 0xb0, &[10, 11]);
1130 check_node(nodes[1], 0xa1, 0xb1, &[20, 21, 22, 23]);
1131 // The end node is not returned by the iterator.
1132 assert_eq!(nodes.len(), 2);
1133
1134 // Check second instance.
1135 instance = iter.next().unwrap();
1136 assert_eq!(size_of_val(instance), 6 + 8 + 4);
1137
1138 let nodes: Vec<_> = instance.node_iter().collect();
1139 check_node(nodes[0], 0xa2, 0xb2, &[30, 31]);
1140 check_node(nodes[1], 0xa3, 0xb3, &[40, 41, 42, 43]);
1141 // The end node is not returned by the iterator.
1142 assert_eq!(nodes.len(), 2);
1143
1144 // Only two instances.
1145 assert!(iter.next().is_none());
1146 }
1147
1148 #[test]
1149 fn test_to_owned() {
1150 let raw_data = create_raw_device_path();
1151 // SAFETY: The memory is valid.
1152 let dp = unsafe { DevicePath::from_ffi_ptr(raw_data.as_ptr().cast()) };
1153
1154 // Relevant assertion to verify the transmute is fine.
1155 assert_eq!(size_of_val(dp), size_of_val(&dp.data));
1156
1157 let owned_dp = dp.to_owned();
1158 let owned_dp_ref = &*owned_dp;
1159 assert_eq!(owned_dp_ref, dp)
1160 }
1161
1162 #[test]
1163 fn test_device_path_node_from_bytes() {
1164 let mut raw_data = Vec::new();
1165 let node = [0xa0, 0xb0];
1166 let node_data = &[10, 11];
1167
1168 // Raw data is less than size of a [`DevicePathNode`].
1169 raw_data.push(node[0]);
1170 assert!(<&DevicePathNode>::try_from(raw_data.as_slice()).is_err());
1171
1172 // Raw data is long enough to hold a [`DevicePathNode`].
1173 raw_data.push(node[1]);
1174 raw_data.extend(
1175 u16::try_from(size_of::<DevicePathHeader>() + node_data.len())
1176 .unwrap()
1177 .to_le_bytes(),
1178 );
1179 raw_data.extend(node_data);
1180 let dp = <&DevicePathNode>::try_from(raw_data.as_slice()).unwrap();
1181
1182 // Relevant assertions to verify the conversion is fine.
1183 assert_eq!(size_of_val(dp), 6);
1184 check_node(dp, 0xa0, 0xb0, &[10, 11]);
1185
1186 // [`DevicePathNode`] data length exceeds the raw_data slice.
1187 raw_data[2] += 1;
1188 assert!(<&DevicePathNode>::try_from(raw_data.as_slice()).is_err());
1189
1190 // [`DevicePathNode`] data length is shorter than the fixed header.
1191 raw_data[2..4].copy_from_slice(&3_u16.to_le_bytes());
1192 assert!(<&DevicePathNode>::try_from(raw_data.as_slice()).is_err());
1193 }
1194
1195 #[test]
1196 fn test_device_path_nodes_from_bytes() {
1197 let raw_data = create_raw_device_path();
1198 let dp = <&DevicePath>::try_from(raw_data.as_slice()).unwrap();
1199
1200 // Check that the size is the sum of the nodes' lengths.
1201 assert_eq!(size_of_val(dp), 6 + 8 + 4 + 6 + 8 + 4);
1202
1203 // Check the list's node iter.
1204 let nodes: Vec<_> = dp.node_iter().collect();
1205 check_node(nodes[0], 0xa0, 0xb0, &[10, 11]);
1206 check_node(nodes[1], 0xa1, 0xb1, &[20, 21, 22, 23]);
1207 check_node(
1208 nodes[2],
1209 DeviceType::END.0,
1210 DeviceSubType::END_INSTANCE.0,
1211 &[],
1212 );
1213 check_node(nodes[3], 0xa2, 0xb2, &[30, 31]);
1214 check_node(nodes[4], 0xa3, 0xb3, &[40, 41, 42, 43]);
1215 // The end-entire node is not returned by the iterator.
1216 assert_eq!(nodes.len(), 5);
1217 }
1218
1219 #[test]
1220 fn test_device_path_from_bytes_rejects_short_node_length() {
1221 #[rustfmt::skip]
1222 let raw_data = [
1223 0xa0, 0xb0,
1224 // Length shorter than the fixed header.
1225 0x03, 0x00,
1226 ];
1227
1228 assert!(<&DevicePath>::try_from(raw_data.as_slice()).is_err());
1229 }
1230
1231 /// A node length below the header size violates the spec. The raw
1232 /// pointer path must panic instead of underflowing the data length.
1233 #[test]
1234 #[should_panic(expected = "device path node length should cover the node header")]
1235 fn test_device_path_from_ffi_ptr_rejects_zero_node_length() {
1236 let raw_data = [0xa0, 0xb0, 0x00, 0x00];
1237 // SAFETY: The memory is valid.
1238 let _ = unsafe { DevicePath::from_ffi_ptr(raw_data.as_ptr().cast()) };
1239 }
1240
1241 #[test]
1242 #[should_panic(expected = "device path node length should cover the node header")]
1243 fn test_device_path_from_ffi_ptr_rejects_short_node_length() {
1244 let raw_data = [0xa0, 0xb0, 0x03, 0x00];
1245 // SAFETY: The memory is valid.
1246 let _ = unsafe { DevicePath::from_ffi_ptr(raw_data.as_ptr().cast()) };
1247 }
1248
1249 /// Test converting from `&DevicePathNode` to a specific node type.
1250 #[test]
1251 fn test_specific_node_from_device_path_node() {
1252 let mut raw_data = Vec::new();
1253 add_node(
1254 &mut raw_data,
1255 DeviceType::END.0,
1256 DeviceSubType::END_INSTANCE.0,
1257 &[],
1258 );
1259 let node = <&DevicePathNode>::try_from(raw_data.as_slice()).unwrap();
1260
1261 assert!(<&end::Instance>::try_from(node).is_ok());
1262 assert_eq!(
1263 <&end::Entire>::try_from(node).unwrap_err(),
1264 NodeConversionError::DifferentType
1265 );
1266 }
1267}