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
//! `DevicePathToText` and `DevicePathFromText` Protocol

// Note on return types: the specification of the conversion functions
// is a little unusual in that they return a pointer rather than
// `EFI_STATUS`. A NULL pointer is used to indicate an error, and the
// spec says that will only happen if the input pointer is null (which
// can't happen here since we use references as input, not pointers), or
// if there is insufficient memory. So we treat any NULL output as an
// `OUT_OF_RESOURCES` error.

use crate::proto::device_path::{DevicePath, DevicePathNode};
use crate::proto::unsafe_protocol;
use crate::table::boot::BootServices;
use crate::{CStr16, Char16, Result, Status};
use core::ops::Deref;
use uefi_raw::protocol::device_path::{DevicePathFromTextProtocol, DevicePathToTextProtocol};

/// This struct is a wrapper of `display_only` parameter
/// used by Device Path to Text protocol.
///
/// The `display_only` parameter controls whether the longer
/// (parseable)  or shorter (display-only) form of the conversion
/// is used. If `display_only` is TRUE, then the shorter text
/// representation of the display node is used, where applicable.
/// If `display_only` is FALSE, then the longer text representation
/// of the display node is used.
#[derive(Clone, Copy, Debug)]
pub struct DisplayOnly(pub bool);

/// This struct is a wrapper of `allow_shortcuts` parameter
/// used by Device Path to Text protocol.
///
/// The `allow_shortcuts` is FALSE, then the shortcut forms of
/// text representation for a device node cannot be used. A
/// shortcut form is one which uses information other than the
/// type or subtype. If `allow_shortcuts is TRUE, then the
/// shortcut forms of text representation for a device node
/// can be used, where applicable.
#[derive(Clone, Copy, Debug)]
pub struct AllowShortcuts(pub bool);

/// Wrapper for a string internally allocated from
/// UEFI boot services memory.
#[derive(Debug)]
pub struct PoolString<'a> {
    boot_services: &'a BootServices,
    text: *const Char16,
}

impl<'a> PoolString<'a> {
    fn new(boot_services: &'a BootServices, text: *const Char16) -> Result<Self> {
        if text.is_null() {
            Err(Status::OUT_OF_RESOURCES.into())
        } else {
            Ok(Self {
                boot_services,
                text,
            })
        }
    }
}

impl<'a> Deref for PoolString<'a> {
    type Target = CStr16;

    fn deref(&self) -> &Self::Target {
        unsafe { CStr16::from_ptr(self.text) }
    }
}

impl Drop for PoolString<'_> {
    fn drop(&mut self) {
        let addr = self.text as *mut u8;
        unsafe { self.boot_services.free_pool(addr) }.expect("Failed to free pool [{addr:#?}]");
    }
}

/// Device Path to Text protocol.
///
/// This protocol provides common utility functions for converting device
/// nodes and device paths to a text representation.
#[derive(Debug)]
#[repr(transparent)]
#[unsafe_protocol(DevicePathToTextProtocol::GUID)]
pub struct DevicePathToText(DevicePathToTextProtocol);

impl DevicePathToText {
    /// Convert a device node to its text representation.
    ///
    /// Returns an [`OUT_OF_RESOURCES`] error if there is insufficient
    /// memory for the conversion.
    ///
    /// [`OUT_OF_RESOURCES`]: Status::OUT_OF_RESOURCES
    pub fn convert_device_node_to_text<'boot>(
        &self,
        boot_services: &'boot BootServices,
        device_node: &DevicePathNode,
        display_only: DisplayOnly,
        allow_shortcuts: AllowShortcuts,
    ) -> Result<PoolString<'boot>> {
        let text_device_node = unsafe {
            (self.0.convert_device_node_to_text)(
                device_node.as_ffi_ptr().cast(),
                display_only.0,
                allow_shortcuts.0,
            )
        };
        PoolString::new(boot_services, text_device_node.cast())
    }

    /// Convert a device path to its text representation.
    ///
    /// Returns an [`OUT_OF_RESOURCES`] error if there is insufficient
    /// memory for the conversion.
    ///
    /// [`OUT_OF_RESOURCES`]: Status::OUT_OF_RESOURCES
    pub fn convert_device_path_to_text<'boot>(
        &self,
        boot_services: &'boot BootServices,
        device_path: &DevicePath,
        display_only: DisplayOnly,
        allow_shortcuts: AllowShortcuts,
    ) -> Result<PoolString<'boot>> {
        let text_device_path = unsafe {
            (self.0.convert_device_path_to_text)(
                device_path.as_ffi_ptr().cast(),
                display_only.0,
                allow_shortcuts.0,
            )
        };
        PoolString::new(boot_services, text_device_path.cast())
    }
}

/// Device Path from Text protocol.
///
/// This protocol provides common utilities for converting text to
/// device paths and device nodes.
#[derive(Debug)]
#[repr(transparent)]
#[unsafe_protocol("05c99a21-c70f-4ad2-8a5f-35df3343f51e")]
pub struct DevicePathFromText(DevicePathFromTextProtocol);

impl DevicePathFromText {
    /// Convert text to the binary representation of a device node.
    ///
    /// `text_device_node` is the text representation of a device node.
    /// Conversion starts with the first character and continues until
    /// the first non-device node character.
    ///
    /// Returns an [`OUT_OF_RESOURCES`] error if there is insufficient
    /// memory for the conversion.
    ///
    /// [`OUT_OF_RESOURCES`]: Status::OUT_OF_RESOURCES
    pub fn convert_text_to_device_node(
        &self,
        text_device_node: &CStr16,
    ) -> Result<&DevicePathNode> {
        unsafe {
            let ptr = (self.0.convert_text_to_device_node)(text_device_node.as_ptr().cast());
            if ptr.is_null() {
                Err(Status::OUT_OF_RESOURCES.into())
            } else {
                Ok(DevicePathNode::from_ffi_ptr(ptr.cast()))
            }
        }
    }

    /// Convert a text to its binary device path representation.
    ///
    /// `text_device_path` is the text representation of a device path.
    /// Conversion starts with the first character and continues until
    /// the first non-device path character.
    ///
    /// Returns an [`OUT_OF_RESOURCES`] error if there is insufficient
    /// memory for the conversion.
    ///
    /// [`OUT_OF_RESOURCES`]: Status::OUT_OF_RESOURCES
    pub fn convert_text_to_device_path(&self, text_device_path: &CStr16) -> Result<&DevicePath> {
        unsafe {
            let ptr = (self.0.convert_text_to_device_path)(text_device_path.as_ptr().cast());
            if ptr.is_null() {
                Err(Status::OUT_OF_RESOURCES.into())
            } else {
                Ok(DevicePath::from_ffi_ptr(ptr.cast()))
            }
        }
    }
}