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 / build.rs

626 lines · 20352 bytes Raw Blame History
1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3//! Utilities for creating new [`DevicePaths`].
4//!
5//! This module contains [`DevicePathBuilder`], as well as submodules
6//! containing types for building each type of device path node.
7//!
8//! [`DevicePaths`]: DevicePath
9
10pub use crate::proto::device_path::device_path_gen::build::*;
11
12use crate::polyfill::{maybe_uninit_slice_as_mut_ptr, maybe_uninit_slice_assume_init_ref};
13use crate::proto::device_path::{DevicePath, DevicePathNode};
14use core::error;
15use core::fmt::{self, Display, Formatter};
16use core::mem::MaybeUninit;
17
18#[cfg(feature = "alloc")]
19use alloc::vec::Vec;
20
21/// A builder for [`DevicePaths`].
22///
23/// The builder can be constructed with either a fixed-length buffer or
24/// (if the `alloc` feature is enabled) a `Vec`.
25///
26/// Nodes are added via the [`push`] method. To construct a node, use one
27/// of the structs in these submodules:
28/// * [`acpi`]
29/// * [`bios_boot_spec`]
30/// * [`end`]
31/// * [`hardware`]
32/// * [`media`]
33/// * [`messaging`]
34///
35/// A node can also be constructed by copying a node from an existing
36/// device path.
37///
38/// To complete a path, call the [`finalize`] method. This adds an
39/// [`END_ENTIRE`] node and returns a [`DevicePath`] reference tied to
40/// the lifetime of the buffer the builder was constructed with.
41///
42/// [`DevicePaths`]: DevicePath
43/// [`END_ENTIRE`]: uefi::proto::device_path::DeviceSubType::END_ENTIRE
44/// [`finalize`]: DevicePathBuilder::finalize
45/// [`push`]: DevicePathBuilder::push
46///
47/// # Examples
48///
49/// ```
50/// use core::mem::MaybeUninit;
51/// use uefi::guid;
52/// use uefi::proto::device_path::DevicePath;
53/// use uefi::proto::device_path::build;
54///
55/// # fn main() -> Result<(), build::BuildError> {
56/// let mut buf = [MaybeUninit::uninit(); 256];
57/// let path: &DevicePath = build::DevicePathBuilder::with_buf(&mut buf)
58/// .push(&build::acpi::Acpi {
59/// hid: 0x41d0_0a03,
60/// uid: 0x0000_0000,
61/// })?
62/// .push(&build::hardware::Pci {
63/// function: 0x00,
64/// device: 0x1f,
65/// })?
66/// .push(&build::hardware::Vendor {
67/// vendor_guid: guid!("15e39a00-1dd2-1000-8d7f-00a0c92408fc"),
68/// vendor_defined_data: &[1, 2, 3, 4, 5, 6],
69/// })?
70/// .finalize()?;
71///
72/// assert_eq!(path.node_iter().count(), 3);
73/// # Ok(())
74/// # }
75/// ```
76#[derive(Debug)]
77pub struct DevicePathBuilder<'a> {
78 storage: BuilderStorage<'a>,
79}
80
81impl<'a> DevicePathBuilder<'a> {
82 /// Create a builder backed by a statically-sized buffer.
83 pub const fn with_buf(buf: &'a mut [MaybeUninit<u8>]) -> Self {
84 Self {
85 storage: BuilderStorage::Buf { buf, offset: 0 },
86 }
87 }
88
89 /// Create a builder backed by a `Vec`.
90 ///
91 /// The `Vec` is cleared before use.
92 #[cfg(feature = "alloc")]
93 pub fn with_vec(v: &'a mut Vec<u8>) -> Self {
94 v.clear();
95 Self {
96 storage: BuilderStorage::Vec(v),
97 }
98 }
99
100 /// Add a node to the device path.
101 ///
102 /// An error will be returned if an [`END_ENTIRE`] node is passed to
103 /// this function, as that node will be added when [`Self::finalize`] is
104 /// called.
105 ///
106 /// [`END_ENTIRE`]: uefi::proto::device_path::DeviceSubType::END_ENTIRE
107 pub fn push(mut self, node: &dyn BuildNode) -> Result<Self, BuildError> {
108 let node_size = usize::from(node.size_in_bytes()?);
109
110 match &mut self.storage {
111 BuilderStorage::Buf { buf, offset } => {
112 node.write_data(
113 buf.get_mut(*offset..*offset + node_size)
114 .ok_or(BuildError::BufferTooSmall)?,
115 );
116 *offset += node_size;
117 }
118 #[cfg(feature = "alloc")]
119 BuilderStorage::Vec(vec) => {
120 let old_size = vec.len();
121 vec.reserve(node_size);
122 let buf = &mut vec.spare_capacity_mut()[..node_size];
123 node.write_data(buf);
124 // SAFETY: The memory is valid.
125 unsafe {
126 vec.set_len(old_size + node_size);
127 }
128 }
129 }
130
131 Ok(self)
132 }
133
134 /// Add an [`END_ENTIRE`] node and return the resulting [`DevicePath`].
135 ///
136 /// This method consumes the builder.
137 ///
138 /// [`END_ENTIRE`]: uefi::proto::device_path::DeviceSubType::END_ENTIRE
139 pub fn finalize(self) -> Result<&'a DevicePath, BuildError> {
140 let this = self.push(&end::Entire)?;
141
142 let data: &[u8] = match &this.storage {
143 // SAFETY: The memory is valid.
144 BuilderStorage::Buf { buf, offset } => unsafe {
145 maybe_uninit_slice_assume_init_ref(&buf[..*offset])
146 },
147 #[cfg(feature = "alloc")]
148 BuilderStorage::Vec(vec) => vec,
149 };
150
151 let ptr: *const () = data.as_ptr().cast();
152 // SAFETY: The memory is valid.
153 Ok(unsafe { &*ptr_meta::from_raw_parts(ptr, data.len()) })
154 }
155}
156
157/// Reference to the backup storage for [`DevicePathBuilder`]
158#[derive(Debug)]
159enum BuilderStorage<'a> {
160 Buf {
161 buf: &'a mut [MaybeUninit<u8>],
162 offset: usize,
163 },
164
165 #[cfg(feature = "alloc")]
166 Vec(&'a mut Vec<u8>),
167}
168
169/// Error type used by [`DevicePathBuilder`].
170#[derive(Clone, Copy, Debug)]
171pub enum BuildError {
172 /// A node was too big to fit in the remaining buffer space.
173 BufferTooSmall,
174
175 /// An individual node's length is too big to fit in a [`u16`].
176 NodeTooBig,
177
178 /// An [`END_ENTIRE`] node was passed to the builder. Use
179 /// [`DevicePathBuilder::finalize`] instead.
180 ///
181 /// [`END_ENTIRE`]: uefi::proto::device_path::DeviceSubType::END_ENTIRE
182 UnexpectedEndEntire,
183}
184
185impl Display for BuildError {
186 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
187 write!(
188 f,
189 "{}",
190 match self {
191 Self::BufferTooSmall => "a node was too big to fit in remaining buffer space",
192 Self::NodeTooBig => "a node was too big",
193 Self::UnexpectedEndEntire => "unexpected END_ENTIRE",
194 }
195 )
196 }
197}
198
199impl error::Error for BuildError {}
200
201/// Trait for types that can be used to build a node via
202/// [`DevicePathBuilder::push`].
203///
204/// This trait is implemented for all the node types in
205/// [`uefi::proto::device_path::build`]. It is also implemented for
206/// [`&DevicePathNode`], which allows an existing node to be copied by
207/// the builder.
208///
209/// # Safety
210///
211/// The methods of this trait are safe to call, but the trait itself is
212/// `unsafe` because an incorrect implementation could cause
213/// unsafety. In particular, the `write_data` is required to
214/// completely initialize all bytes in the output slice.
215///
216/// [`&DevicePathNode`]: DevicePathNode
217pub unsafe trait BuildNode {
218 /// Size of the node in bytes, including the standard node
219 /// header. Returns [`BuildError::NodeTooBig`] if the node's size
220 /// does not fit in a [`u16`].
221 fn size_in_bytes(&self) -> Result<u16, BuildError>;
222
223 /// Write out the node data.
224 ///
225 /// The length of `out` must be equal to the node's `size_in_bytes`.
226 ///
227 /// The `out` slice will be fully initialized after the call.
228 fn write_data(&self, out: &mut [MaybeUninit<u8>]);
229}
230
231// SAFETY: The type satisfies the contract required by this unsafe impl.
232unsafe impl BuildNode for &DevicePathNode {
233 fn size_in_bytes(&self) -> Result<u16, BuildError> {
234 Ok(self.header.length())
235 }
236
237 fn write_data(&self, out: &mut [MaybeUninit<u8>]) {
238 let src: *const u8 = self.as_ffi_ptr().cast();
239
240 let dst: *mut u8 = maybe_uninit_slice_as_mut_ptr(out);
241 // SAFETY: The memory is valid.
242 unsafe {
243 dst.copy_from_nonoverlapping(src, out.len());
244 }
245 }
246}
247
248#[cfg(test)]
249mod tests {
250 use super::*;
251 use crate::guid;
252 use crate::proto::device_path::media::{PartitionFormat, PartitionSignature};
253 use crate::proto::device_path::messaging::{
254 Ipv4AddressOrigin, IscsiLoginOptions, IscsiProtocol, RestServiceAccessMode, RestServiceType,
255 };
256
257 /// Test building an ACPI ADR node.
258 #[test]
259 fn test_acpi_adr() -> Result<(), BuildError> {
260 assert!(acpi::AdrSlice::new(&[]).is_none());
261
262 let mut v = Vec::new();
263 let path = DevicePathBuilder::with_vec(&mut v)
264 .push(&acpi::Adr {
265 adr: acpi::AdrSlice::new(&[1, 2]).unwrap(),
266 })?
267 .finalize()?;
268
269 let node: &crate::proto::device_path::acpi::Adr =
270 path.node_iter().next().unwrap().try_into().unwrap();
271 assert_eq!(node.adr().iter().collect::<Vec<_>>(), [1, 2]);
272 #[rustfmt::skip]
273 assert_eq!(path.as_bytes(), [
274 // ACPI ADR node
275 0x02, 0x03, 0x0c, 0x00,
276 // Values
277 0x01, 0x00, 0x00, 0x00,
278 0x02, 0x00, 0x00, 0x00,
279
280 // End-entire node
281 0x7f, 0xff, 0x04, 0x00,
282 ]);
283
284 Ok(())
285 }
286
287 /// Test building an ACPI Expanded node.
288 #[test]
289 fn test_acpi_expanded() -> Result<(), BuildError> {
290 let mut v = Vec::new();
291 let path = DevicePathBuilder::with_vec(&mut v)
292 .push(&acpi::Expanded {
293 hid: 1,
294 uid: 2,
295 cid: 3,
296 hid_str: b"a\0",
297 uid_str: b"bc\0",
298 cid_str: b"def\0",
299 })?
300 .finalize()?;
301
302 let node: &crate::proto::device_path::acpi::Expanded =
303 path.node_iter().next().unwrap().try_into().unwrap();
304 assert_eq!(node.hid(), 1);
305 assert_eq!(node.uid(), 2);
306 assert_eq!(node.cid(), 3);
307 assert_eq!(node.hid_str(), b"a\0");
308 assert_eq!(node.uid_str(), b"bc\0");
309 assert_eq!(node.cid_str(), b"def\0");
310
311 #[rustfmt::skip]
312 assert_eq!(path.as_bytes(), [
313 // ACPI Expanded node
314 0x02, 0x02, 0x19, 0x00,
315 // HID
316 0x01, 0x00, 0x00, 0x00,
317 // UID
318 0x02, 0x00, 0x00, 0x00,
319 // CID
320 0x03, 0x00, 0x00, 0x00,
321
322 // HID str
323 0x61, 0x00,
324
325 // UID str
326 0x62, 0x63, 0x00,
327
328 // CID str
329 0x64, 0x65, 0x66, 0x00,
330
331 // End-entire node
332 0x7f, 0xff, 0x04, 0x00,
333 ]);
334
335 Ok(())
336 }
337
338 /// Test building a messaging REST Service node.
339 #[test]
340 fn test_messaging_rest_service() -> Result<(), BuildError> {
341 let mut v = Vec::new();
342 let vendor_guid = guid!("a1005a90-6591-4596-9bab-1c4249a6d4ff");
343 let path = DevicePathBuilder::with_vec(&mut v)
344 .push(&messaging::RestService {
345 service_type: RestServiceType::REDFISH,
346 access_mode: RestServiceAccessMode::IN_BAND,
347 vendor_guid_and_data: None,
348 })?
349 .push(&messaging::RestService {
350 service_type: RestServiceType::VENDOR,
351 access_mode: RestServiceAccessMode::OUT_OF_BAND,
352 vendor_guid_and_data: Some(messaging::RestServiceVendorData {
353 vendor_guid,
354 vendor_defined_data: &[1, 2, 3, 4, 5],
355 }),
356 })?
357 .finalize()?;
358
359 let mut iter = path.node_iter();
360 let mut node: &crate::proto::device_path::messaging::RestService =
361 iter.next().unwrap().try_into().unwrap();
362 assert!(node.vendor_guid_and_data().is_none());
363 node = iter.next().unwrap().try_into().unwrap();
364 assert_eq!(node.vendor_guid_and_data().unwrap().0, vendor_guid);
365 assert_eq!(node.vendor_guid_and_data().unwrap().1, &[1, 2, 3, 4, 5]);
366
367 #[rustfmt::skip]
368 assert_eq!(path.as_bytes(), [
369 // Messaging REST Service node.
370 0x03, 0x21, 0x06, 0x00,
371 // Type and access mode
372 0x01, 0x01,
373
374 // Messaging REST Service node. The spec incorrectly says
375 // the length is 21+n bytes, it's actually 22+n bytes.
376 0x03, 0x21, 0x1b, 0x00,
377 // Type and access mode
378 0xff, 0x02,
379 // Vendor guid
380 0x90, 0x5a, 0x00, 0xa1,
381 0x91, 0x65, 0x96, 0x45,
382 0x9b, 0xab, 0x1c, 0x42,
383 0x49, 0xa6, 0xd4, 0xff,
384 // Vendor data
385 0x01, 0x02, 0x03, 0x04, 0x05,
386
387 // End-entire node
388 0x7f, 0xff, 0x04, 0x00,
389 ]);
390
391 Ok(())
392 }
393
394 /// Test that packed nodes can be passed into the builder.
395 #[test]
396 fn test_build_with_packed_node() -> Result<(), BuildError> {
397 // Build a path with both a statically-sized and DST nodes.
398 let mut v = Vec::new();
399 let path1 = DevicePathBuilder::with_vec(&mut v)
400 .push(&acpi::Acpi {
401 hid: 0x41d0_0a03,
402 uid: 0x0000_0000,
403 })?
404 .push(&hardware::Vendor {
405 vendor_guid: guid!("15e39a00-1dd2-1000-8d7f-00a0c92408fc"),
406 vendor_defined_data: &[1, 2, 3, 4, 5, 6],
407 })?
408 .finalize()?;
409
410 // Create a second path by copying in the packed nodes from the
411 // first path.
412 let mut v = Vec::new();
413 let mut builder = DevicePathBuilder::with_vec(&mut v);
414 for node in path1.node_iter() {
415 builder = builder.push(&node)?;
416 }
417 let path2 = builder.finalize()?;
418
419 // Verify the copied path is identical.
420 assert_eq!(path1, path2);
421
422 Ok(())
423 }
424
425 /// This test is based on the "Fibre Channel Ex Device Path Example"
426 /// from the UEFI Specification.
427 #[test]
428 fn test_fibre_channel_ex_device_path_example() -> Result<(), BuildError> {
429 let nodes: &[&dyn BuildNode] = &[
430 &acpi::Acpi {
431 hid: 0x41d0_0a03,
432 uid: 0x0000_0000,
433 },
434 &hardware::Pci {
435 function: 0x00,
436 device: 0x1f,
437 },
438 &messaging::FibreChannelEx {
439 world_wide_name: [0, 1, 2, 3, 4, 5, 6, 7],
440 logical_unit_number: [0, 1, 2, 3, 4, 5, 6, 7],
441 },
442 ];
443
444 // Arbitrarily choose this test to use a statically-sized
445 // buffer, just to make sure that code path is tested.
446 let mut buf = [MaybeUninit::uninit(); 256];
447 let path1 = DevicePathBuilder::with_buf(&mut buf)
448 .push(nodes[0])?
449 .push(nodes[1])?
450 .push(nodes[2])?
451 .finalize()?;
452
453 #[rustfmt::skip]
454 const EXPECTED: [u8; 46] = [
455 // ACPI node
456 0x02, 0x01, 0x0c, 0x00,
457 // HID
458 0x03, 0x0a, 0xd0, 0x41,
459 // UID
460 0x00, 0x00, 0x00, 0x00,
461
462 // PCI node
463 0x01, 0x01, 0x06, 0x00,
464 // Function
465 0x00,
466 // Device
467 0x1f,
468
469 // Fibre Channel Ex node
470 0x03, 0x15,
471 // The example in the spec is wrong here; it says 0x14 for
472 // the length and leaves out the four-byte reserved field.
473 0x18, 0x00,
474 // Reserved
475 0x00, 0x00, 0x00, 0x00,
476 // World wide name
477 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
478 // Logical unit number
479 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
480
481 // End-entire node
482 0x7f, 0xff, 0x04, 0x00,
483 ];
484
485 assert_eq!(path1.as_bytes(), EXPECTED);
486
487 Ok(())
488 }
489
490 /// This test is based on the "IPv4 configuration" example from the
491 /// UEFI Specification.
492 #[test]
493 fn test_ipv4_configuration_example() -> Result<(), BuildError> {
494 let mut v = Vec::new();
495 let path = DevicePathBuilder::with_vec(&mut v)
496 .push(&acpi::Acpi {
497 hid: 0x41d0_0a03,
498 uid: 0x0000_0000,
499 })?
500 .push(&hardware::Pci {
501 function: 0x00,
502 device: 0x19,
503 })?
504 .push(&messaging::MacAddress {
505 mac_address: [
506 0x00, 0x13, 0x20, 0xf5, 0xfa, 0x77, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
507 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
508 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
509 ],
510 interface_type: 0x01,
511 })?
512 .push(&messaging::Ipv4 {
513 local_ip_address: [192, 168, 0, 1],
514 remote_ip_address: [192, 168, 0, 100],
515 local_port: 0,
516 remote_port: 3260,
517 protocol: 6,
518 ip_address_origin: Ipv4AddressOrigin::STATIC,
519 gateway_ip_address: [0, 0, 0, 0],
520 subnet_mask: [0, 0, 0, 0],
521 })?
522 .push(&messaging::Iscsi {
523 protocol: IscsiProtocol::TCP,
524 options: IscsiLoginOptions::AUTH_METHOD_NONE,
525 logical_unit_number: 0u64.to_le_bytes(),
526 target_portal_group_tag: 1,
527 iscsi_target_name: b"iqn.1991-05.com.microsoft:iscsitarget-iscsidisk-target\0",
528 })?
529 .push(&media::HardDrive {
530 partition_number: 1,
531 partition_start: 0x22,
532 partition_size: 0x2710000,
533 partition_format: PartitionFormat::GPT,
534 partition_signature: PartitionSignature::Guid(guid!(
535 "15e39a00-1dd2-1000-8d7f-00a0c92408fc"
536 )),
537 })?
538 .finalize()?;
539
540 #[rustfmt::skip]
541 assert_eq!(path.as_bytes(), [
542 // ACPI node
543 0x02, 0x01, 0x0c, 0x00,
544 // HID
545 0x03, 0x0a, 0xd0, 0x41,
546 // UID
547 0x00, 0x00, 0x00, 0x00,
548
549 // PCI node
550 0x01, 0x01, 0x06, 0x00,
551 // Function
552 0x00,
553 // Device
554 0x19,
555
556 // MAC address node
557 0x03, 0x0b, 0x25, 0x00,
558 // MAC address
559 0x00, 0x13, 0x20, 0xf5, 0xfa, 0x77, 0x00, 0x00,
560 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
561 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
562 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
563 // Network interface type
564 0x01,
565
566 // IPv4 node
567 0x03, 0x0c, 0x1b, 0x00,
568 // Local address
569 0xc0, 0xa8, 0x00, 0x01,
570 // Remote address
571 0xc0, 0xa8, 0x00, 0x64,
572 // Local port
573 0x00, 0x00,
574 // Remote port
575 0xbc, 0x0c,
576 // Protocol
577 0x06, 0x00,
578 // Static IP
579 0x01,
580 // Gateway IP
581 0x00, 0x00, 0x00, 0x00,
582 // Subnet mask
583 0x00, 0x00, 0x00, 0x00,
584
585 // iSCSI node
586 0x03, 0x13, 0x49, 0x00,
587 // Protocol
588 0x00, 0x00,
589 // Login options
590 0x00, 0x08,
591 // LUN
592 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
593 // Target portal group tag
594 0x01, 0x00,
595 // Node name
596 0x69, 0x71, 0x6e, 0x2e, 0x31, 0x39, 0x39, 0x31,
597 0x2d, 0x30, 0x35, 0x2e, 0x63, 0x6f, 0x6d, 0x2e,
598 0x6d, 0x69, 0x63, 0x72, 0x6f, 0x73, 0x6f, 0x66,
599 0x74, 0x3a, 0x69, 0x73, 0x63, 0x73, 0x69, 0x74,
600 0x61, 0x72, 0x67, 0x65, 0x74, 0x2d, 0x69, 0x73,
601 0x63, 0x73, 0x69, 0x64, 0x69, 0x73, 0x6b, 0x2d,
602 0x74, 0x61, 0x72, 0x67, 0x65, 0x74, 0x00,
603
604 // Hard drive node
605 0x04, 0x01, 0x2a, 0x00,
606 // Partition number
607 0x01, 0x00, 0x00, 0x00,
608 // Partition start
609 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
610 // Partition size
611 0x00, 0x00, 0x71, 0x02, 0x00, 0x00, 0x00, 0x00,
612 // Partition signature
613 0x00, 0x9a, 0xe3, 0x15, 0xd2, 0x1d, 0x00, 0x10,
614 0x8d, 0x7f, 0x00, 0xa0, 0xc9, 0x24, 0x08, 0xfc,
615 // Partition format
616 0x02,
617 // Signature type
618 0x02,
619
620 // End-entire node
621 0x7f, 0xff, 0x04, 0x00,
622 ]);
623
624 Ok(())
625 }
626}