patina 21.1.1

Common types and functionality used in UEFI development.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
//! A Device Path is used to define the programmatic path to a device.
//!
//! The primary purpose of a Device Path is to allow an application, such as an OS loader, to determine the physical device that the interfaces are abstracting.
//!
//! ## License
//!
//! Copyright (c) Microsoft Corporation.
//!
//! SPDX-License-Identifier: Apache-2.0
//!

use alloc::{borrow::ToOwned, boxed::Box, vec::Vec};
use core::{
    borrow::Borrow,
    clone::Clone,
    convert::{AsRef, From},
    debug_assert, debug_assert_eq,
    fmt::{Debug, Display, Write},
    format_args,
    iter::Iterator,
    mem,
    ops::{Deref, DerefMut},
};

use scroll::Pread;

use crate::device_path::{
    node_defs::{self, DevicePathType, EndEntire, EndInstance},
    parse_node::{DevicePathNode, UnknownDevicePathNode},
};

/// DevicePathBuf is an owned version of device path. This is used to create device paths or when performing mutable operations on them.
#[derive(Debug, Clone)]
pub struct DevicePathBuf {
    buffer: Vec<u8>,
}

impl DevicePathBuf {
    /// Create a DevicePathBuf with an empty buffer.
    fn new_empty() -> Self {
        Self { buffer: Vec::new() }
    }

    /// Append a node to the device path.
    /// This function does not ensure that the device path is valid, the EndEntire node must be manually added to the device path.
    pub fn append<T>(&mut self, node: T)
    where
        T: DevicePathNode + Sized,
    {
        let writing_start_offset = self.buffer.len();
        let header = node.header();

        let nb_additional_byte = (writing_start_offset + header.length).saturating_sub(self.buffer.capacity());

        if let Err(e) = self.buffer.try_reserve_exact(nb_additional_byte) {
            debug_assert!(false, "Device Path: Cannot allocate enough memory to append a device path node. {e:?}");
            return;
        }

        // No allocation will be done here, handled by the `try_reserve`.
        self.buffer.resize(writing_start_offset + header.length, 0);

        let writing_buffer = &mut self.buffer.as_mut_slice()[writing_start_offset..];
        match node.write_into(writing_buffer) {
            Ok(nb_byte_written) => debug_assert_eq!(header.length, nb_byte_written),
            Err(_) => debug_assert!(false, "Unexpected error, buffer should be large enough at that point."),
        }
    }

    /// Append a device path to this device path, the EndEntire node of self will be removed when appending the other path.
    pub fn append_device_path(&mut self, device_path: &DevicePath) {
        self.buffer.truncate(self.buffer.len() - EndEntire.header().length);
        self.buffer.extend_from_slice(&device_path.buffer[..]);
    }

    /// Append a device path to this device path, the EndEntire node of self will be replaced with an end instance.
    pub fn append_device_path_instances(&mut self, device_path: &DevicePath) {
        self.buffer.truncate(self.buffer.len() - EndEntire.header().length);
        self.append(EndInstance);
        self.buffer.extend_from_slice(&device_path.buffer[..]);
    }

    /// Create a device path from an iterator of device path nodes.
    /// If the iterator does not end with an `EndEntire` node, it will be added to the device path.
    pub fn from_device_path_node_iter<I, T>(iter: I) -> DevicePathBuf
    where
        I: Iterator<Item = T>,
        T: DevicePathNode,
    {
        let mut device_path = DevicePathBuf::new_empty();
        let mut last_node_header = None;
        for n in iter {
            last_node_header.replace(n.header());
            device_path.append(n);
        }
        match last_node_header {
            Some(h) if EndEntire::is_type(h.r#type, h.sub_type) => (),
            _ => device_path.append(EndEntire),
        }
        device_path
    }

    /// Convert the device path to a boxed [`DevicePath`].
    pub fn into_box_device_path(self) -> Box<DevicePath> {
        // SAFETY: DevicePath has the same memory layout as [u8].
        unsafe { mem::transmute(self.buffer.into_boxed_slice()) }
    }
}

impl Deref for DevicePathBuf {
    type Target = DevicePath;

    fn deref(&self) -> &Self::Target {
        DevicePath::from(self)
    }
}

impl DerefMut for DevicePathBuf {
    fn deref_mut(&mut self) -> &mut Self::Target {
        // SAFETY: DevicePath has the same memory layout as `[u8]`.
        unsafe { &mut *(self.buffer.as_mut_slice() as *mut [u8] as *mut DevicePath) }
    }
}

impl AsRef<DevicePath> for DevicePathBuf {
    fn as_ref(&self) -> &DevicePath {
        self
    }
}

impl AsMut<DevicePath> for DevicePathBuf {
    fn as_mut(&mut self) -> &mut DevicePath {
        self
    }
}

impl From<&DevicePath> for DevicePathBuf {
    fn from(value: &DevicePath) -> Self {
        DevicePathBuf { buffer: Vec::from(&value.buffer) }
    }
}

impl Display for DevicePathBuf {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_fmt(format_args!("{}", self.as_ref()))
    }
}

impl PartialEq for DevicePathBuf {
    fn eq(&self, other: &DevicePathBuf) -> bool {
        DevicePath::from(self) == DevicePath::from(other)
    }
}

impl Eq for DevicePathBuf {}

/// DevicePath is the borrowed version of a [`DevicePathBuf`].
/// Only immutable operations are possible on this type.
#[derive(Debug)]
#[repr(transparent)]
pub struct DevicePath {
    buffer: [u8],
}

impl DevicePath {
    /// Create a &DevicePath for a DevicePathBuf.
    pub fn from(device_path_buff: &DevicePathBuf) -> &Self {
        // SAFETY: This is safe because DevicePath have the same memory layout as `[u8]`.
        unsafe { &*(device_path_buff.buffer.as_slice() as *const [u8] as *const Self) }
    }

    /// Create a &DevicePath from a pointer to a byte buffer.
    /// This is used to interface with device paths from C code.
    ///
    /// # Safety
    ///
    /// The buffer pointer must point to valid device path data that remains valid
    /// for the lifetime 'a. The device path must be properly terminated with an
    /// EndEntire node.
    pub unsafe fn try_from_ptr<'a>(buffer: *const u8) -> Result<&'a DevicePath, &'static str> {
        if buffer.is_null() {
            return Err("Null pointer provided");
        }

        // SAFETY: The caller contract requires that the buffer pointer is valid and points to at least
        // Header::size_of_header() bytes.
        let mut buffer =
            unsafe { core::slice::from_raw_parts(buffer, crate::device_path::parse_node::Header::size_of_header()) };
        let mut offset = 0;
        loop {
            let header = buffer
                .pread_with::<crate::device_path::parse_node::Header>(offset, scroll::LE)
                .map_err(|_| "Error while trying to read header.")?;
            if EndEntire::is_type(header.r#type, header.sub_type) {
                break;
            }

            let new_length = buffer.len() + header.length;
            offset += header.length;
            // SAFETY: The buffer slice is extended based on the length field from the device path header.
            // The caller guarantees that the buffer points to valid device path data for the entire lifetime.
            buffer = unsafe { core::slice::from_raw_parts(buffer.as_ptr(), new_length) };
        }

        // SAFETY: The device path structure was validated by iterating through all nodes and finding an end node.
        // The buffer is properly sized and contains a valid device path. The cast is considered safe due to
        // DevicePath's repr(transparent).
        let device_path = unsafe { &*(buffer as *const [u8] as *const DevicePath) };
        Ok(device_path)
    }

    /// Return the size in bytes of the device path.
    pub fn size(&self) -> usize {
        self.buffer.len()
    }

    /// Return the number of nodes in the device path.
    pub fn node_count(&self) -> usize {
        self.iter().count()
    }

    /// Return true if the device path contains more than one instance, otherwise false.
    pub fn is_multi_instance(&self) -> bool {
        self.iter().any(|n| EndInstance::is_type(n.header.r#type, n.header.sub_type))
    }

    /// Return a &DevicePath for the n last nodes of the device path.
    /// This operation does not copy memory since the trailing end of a device path is a valid device path.
    pub fn slice_end(&self, n: usize) -> &DevicePath {
        let count = self.node_count();

        debug_assert!(n >= 1, "Device path needs to have at least the end node.");
        debug_assert!(n <= count, "Cannot return a device path bigger than self.");

        let nb_skip = count - n;
        let mut idx = 0;
        for _ in 0..nb_skip {
            let header = self.buffer.pread_with::<crate::device_path::parse_node::Header>(idx, scroll::LE).unwrap();
            idx += header.length;
        }
        let end_buffer = &self.buffer[idx..];
        // SAFETY: The slice `end_buffer` is a valid trailing portion of the device path that contains
        // the last n nodes including the end node. DevicePath is repr(transparent) over [u8], so this cast is
        // considered valid.
        unsafe { &*(end_buffer as *const [u8] as *const DevicePath) }
    }

    /// Return true if the device path starts with the other device path.
    pub fn starts_with(&self, other: &DevicePath) -> bool {
        let self_iter = self.iter();
        let other_iter = other.iter();
        for (self_node, other_node) in self_iter.zip(other_iter) {
            if other_node.header.r#type == DevicePathType::End as u8 {
                return true;
            }
            if self_node != other_node {
                return false;
            }
        }
        false
    }

    /// Iterate through every node of a device path.
    pub fn iter(&self) -> Iter<'_> {
        Iter::new(self)
    }

    /// Iterate through every instance of a device path.
    pub fn iter_instances(&self) -> IterInstance<'_> {
        IterInstance { node_iterator: self.iter() }
    }
}

impl PartialEq for &DevicePath {
    fn eq(&self, other: &&DevicePath) -> bool {
        self.buffer == other.buffer
    }
}

impl Eq for &DevicePath {}

impl ToOwned for DevicePath {
    type Owned = DevicePathBuf;

    fn to_owned(&self) -> Self::Owned {
        self.into()
    }
}

impl Borrow<DevicePath> for DevicePathBuf {
    fn borrow(&self) -> &DevicePath {
        self.as_ref()
    }
}

impl Clone for Box<DevicePath> {
    fn clone(&self) -> Self {
        DevicePathBuf::from(self.as_ref()).into_box_device_path()
    }
}

/// Device path instance iterator.
pub struct IterInstance<'a> {
    node_iterator: Iter<'a>,
}

impl Iterator for IterInstance<'_> {
    type Item = DevicePathBuf;

    fn next(&mut self) -> Option<Self::Item> {
        let mut item = None;
        for node in self.node_iterator.by_ref() {
            if node.header().r#type == DevicePathType::End as u8 {
                item.get_or_insert(DevicePathBuf::new_empty()).append(EndEntire);
                break;
            } else {
                item.get_or_insert(DevicePathBuf::new_empty()).append(node);
            }
        }
        item
    }
}

/// Device path node iterator.
pub struct Iter<'a> {
    device_path: &'a DevicePath,
    offset: usize,
}

impl<'a> Iter<'a> {
    fn new(device_path: &'a DevicePath) -> Iter<'a> {
        Self { device_path, offset: 0 }
    }
}

impl<'a> Iterator for Iter<'a> {
    type Item = UnknownDevicePathNode<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        // No more byte to read in the device path.
        if self.offset == self.device_path.buffer.len() {
            return None;
        }

        let Ok(unknown_device_path) =
            self.device_path.buffer.gread_with::<UnknownDevicePathNode>(&mut self.offset, scroll::LE)
        else {
            debug_assert!(false, "The buffer is corrupted, could not read the device path node.");
            return None;
        };

        Some(unknown_device_path)
    }
}

impl Display for DevicePath {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let mut nodes = self.iter().map(node_defs::cast_to_dyn_device_path_node).peekable();

        while let Some(node) = nodes.next() {
            f.write_fmt(format_args!("{}", &node))?;

            if let Some(next) = nodes.peek()
                && node.header().r#type != DevicePathType::End as u8
                && next.header().r#type != DevicePathType::End as u8
            {
                f.write_char('/')?;
            };
        }

        Ok(())
    }
}

#[cfg(test)]
#[coverage(off)]
mod tests {
    use super::*;
    use core::assert_eq;

    use crate::device_path::{
        node_defs::{Acpi, AcpiSubType, EndSubType, Pci},
        paths::DevicePathBuf,
    };

    #[test]
    fn test_new_empty_device_path_buf() {
        let device_path = DevicePathBuf::new_empty();
        assert!(device_path.buffer.is_empty());
    }

    #[test]
    fn test_append_node() {
        let mut device_path = DevicePathBuf::new_empty();
        device_path.append(Acpi::new_pci_root(0));
        device_path.append(EndEntire);

        let expected_data = [
            DevicePathType::Acpi as u8,
            AcpiSubType::Acpi as u8,
            12, // length lower byte
            0,  // length upper byte
            (Acpi::PCI_ROOT_HID & 0xFF) as u8,
            ((Acpi::PCI_ROOT_HID >> 8) & 0xFF) as u8,
            ((Acpi::PCI_ROOT_HID >> 16) & 0xFF) as u8,
            ((Acpi::PCI_ROOT_HID >> 24) & 0xFF) as u8,
            0, // uid byte 0
            0, // uid byte 1
            0, // uid byte 2
            0, // uid byte 3
            DevicePathType::End as u8,
            EndSubType::Entire as u8,
            4, // length lower byte
            0, // length upper byte
        ];

        assert_eq!(expected_data, device_path.buffer.as_slice());
    }

    #[test]
    fn test_append_device_path() {
        let mut device_path = DevicePathBuf::new_empty();
        device_path.append(Acpi::new_pci_root(0));
        device_path.append(EndEntire);

        let mut device_path_to_add = DevicePathBuf::new_empty();
        device_path_to_add.append(Pci { function: 1, device: 2 });
        device_path_to_add.append(EndEntire);

        let mut expected_device_path = DevicePathBuf::new_empty();
        expected_device_path.append(Acpi::new_pci_root(0));
        expected_device_path.append(Pci { function: 1, device: 2 });
        expected_device_path.append(EndEntire);

        device_path.append_device_path(&device_path_to_add);

        assert_eq!(expected_device_path, device_path);
    }

    #[test]
    fn test_append_device_path_instance() {
        let mut device_path = DevicePathBuf::new_empty();
        device_path.append(Acpi::new_pci_root(0));
        device_path.append(EndEntire);

        let mut device_path_to_add = DevicePathBuf::new_empty();
        device_path_to_add.append(Pci { function: 1, device: 2 });
        device_path_to_add.append(EndEntire);

        let mut expected_device_path = DevicePathBuf::new_empty();
        expected_device_path.append(Acpi::new_pci_root(0));
        expected_device_path.append(EndInstance);
        expected_device_path.append(Pci { function: 1, device: 2 });
        expected_device_path.append(EndEntire);

        device_path.append_device_path_instances(&device_path_to_add);

        assert_eq!(expected_device_path, device_path);
    }

    #[test]
    fn test_device_path_buff_from_node_iter() {
        let mut expected_device_path = DevicePathBuf::new_empty();
        expected_device_path.append(Acpi::new_pci_root(0));
        expected_device_path.append(Pci { function: 1, device: 2 });
        expected_device_path.append(EndEntire);

        let device_path = DevicePathBuf::from_device_path_node_iter(expected_device_path.iter());

        assert_eq!(expected_device_path, device_path);
    }

    #[test]
    fn test_device_path_buff_to_boxed_device_path() {
        let mut device_path_buf = DevicePathBuf::new_empty();
        device_path_buf.append(Acpi::new_pci_root(0));
        device_path_buf.append(Pci { function: 1, device: 2 });
        device_path_buf.append(EndEntire);

        let device_path = DevicePathBuf::clone(&device_path_buf).into_box_device_path();

        assert_eq!(device_path_buf.as_ref(), device_path.as_ref());
    }

    #[test]
    fn test_device_path_from_ptr() {
        let mut device_path_buf = DevicePathBuf::new_empty();
        device_path_buf.append(Acpi::new_pci_root(0));
        device_path_buf.append(Pci { function: 1, device: 2 });
        device_path_buf.append(EndEntire);
        let buffer_ptr = device_path_buf.buffer.as_slice().as_ptr();

        // SAFETY: Test code - creating DevicePath from a valid buffer pointer for testing.
        let device_path = unsafe { DevicePath::try_from_ptr(buffer_ptr) }.unwrap();

        assert_eq!(device_path_buf.as_ref(), device_path);
    }

    #[test]
    fn test_device_path_size() {
        let mut device_path_buf = DevicePathBuf::new_empty();
        assert_eq!(0, device_path_buf.size());
        device_path_buf.append(Acpi::new_pci_root(0));
        assert_eq!(12, device_path_buf.size());
        device_path_buf.append(Pci { function: 1, device: 2 });
        assert_eq!(18, device_path_buf.size());
        device_path_buf.append(EndEntire);
        assert_eq!(22, device_path_buf.size());
    }

    #[test]
    fn test_device_path_node_count() {
        let mut device_path_buf = DevicePathBuf::new_empty();
        assert_eq!(0, device_path_buf.node_count());
        device_path_buf.append(Acpi::new_pci_root(0));
        assert_eq!(1, device_path_buf.node_count());
        device_path_buf.append(Pci { function: 1, device: 2 });
        assert_eq!(2, device_path_buf.node_count());
        device_path_buf.append(EndEntire);
        assert_eq!(3, device_path_buf.node_count());
    }

    #[test]
    fn test_device_path_is_multi_instances() {
        let mut device_path_buf = DevicePathBuf::new_empty();
        device_path_buf.append(Acpi::new_pci_root(0));
        device_path_buf.append(Pci { function: 1, device: 2 });
        device_path_buf.append(EndEntire);

        let mut device_path_buf_2 = DevicePathBuf::new_empty();
        device_path_buf_2.append(Acpi::new_pci_root(0));
        device_path_buf_2.append(Pci { function: 1, device: 2 });
        device_path_buf_2.append(EndEntire);

        assert!(!device_path_buf.is_multi_instance());

        device_path_buf.append_device_path_instances(&device_path_buf_2);

        assert!(device_path_buf.is_multi_instance());
    }

    #[test]
    fn test_device_path_slice_end() {
        let mut device_path_buf = DevicePathBuf::new_empty();
        device_path_buf.append(Acpi::new_pci_root(0));
        device_path_buf.append(Pci { function: 1, device: 2 });
        device_path_buf.append(EndEntire);

        let mut expected_device_path = DevicePathBuf::new_empty();
        expected_device_path.append(Pci { function: 1, device: 2 });
        expected_device_path.append(EndEntire);

        assert_eq!(expected_device_path.as_ref(), device_path_buf.slice_end(2));
    }

    #[test]
    fn test_device_path_start_with() {
        let mut device_path_buf = DevicePathBuf::new_empty();
        device_path_buf.append(Acpi::new_pci_root(0));
        device_path_buf.append(Pci { function: 1, device: 2 });
        device_path_buf.append(EndEntire);

        let mut start = DevicePathBuf::new_empty();
        start.append(Acpi::new_pci_root(0));
        start.append(EndEntire);

        assert!(device_path_buf.starts_with(&start));

        let mut start = DevicePathBuf::new_empty();
        start.append(Acpi::new_pci_root(1));
        start.append(EndEntire);

        assert!(!device_path_buf.starts_with(&start));
    }
}