Skip to content

Commit a3a3738

Browse files
authored
Unrolled build for rust-lang#135475
Rollup merge of rust-lang#135475 - Ayush1325:uefi-absolute-path, r=jhpratt uefi: Implement path This PR is split off from rust-lang#135368 to reduce noise. UEFI paths can be of 4 types: 1. Absolute Shell Path: Uses shell mappings 2. Absolute Device Path: this is what we want 3. Relative root: path relative to the current root. 4. Relative Absolute shell path can be identified with `:` and Absolute Device path can be identified with `/`. Relative root path will start with `\`. The algorithm is mostly taken from edk2 UEFI shell implementation and is somewhat simple. Check for the path type in order. For Absolute Shell path, use `EFI_SHELL->GetDevicePathFromMap` to get a BorrowedDevicePath for the volume. For Relative paths, we use the current working directory to construct the new path. BorrowedDevicePath abstraction is needed to interact with `EFI_SHELL->GetDevicePathFromMap` which returns a Device Path Protocol with the lifetime of UEFI shell. Absolute Shell paths cannot exist if UEFI shell is missing. cc `@nicholasbishop`
2 parents a730edc + c1790b1 commit a3a3738

File tree

3 files changed

+158
-5
lines changed

3 files changed

+158
-5
lines changed

library/std/src/sys/pal/uefi/helpers.rs

+49-1
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,12 @@ use r_efi::protocols::{device_path, device_path_to_text, shell};
1414

1515
use crate::ffi::{OsStr, OsString};
1616
use crate::io::{self, const_error};
17+
use crate::marker::PhantomData;
1718
use crate::mem::{MaybeUninit, size_of};
1819
use crate::os::uefi::env::boot_services;
1920
use crate::os::uefi::ffi::{OsStrExt, OsStringExt};
2021
use crate::os::uefi::{self};
22+
use crate::path::Path;
2123
use crate::ptr::NonNull;
2224
use crate::slice;
2325
use crate::sync::atomic::{AtomicPtr, Ordering};
@@ -278,6 +280,10 @@ impl OwnedDevicePath {
278280
pub(crate) const fn as_ptr(&self) -> *mut r_efi::protocols::device_path::Protocol {
279281
self.0.as_ptr()
280282
}
283+
284+
pub(crate) const fn borrow<'a>(&'a self) -> BorrowedDevicePath<'a> {
285+
BorrowedDevicePath::new(self.0)
286+
}
281287
}
282288

283289
impl Drop for OwnedDevicePath {
@@ -293,13 +299,37 @@ impl Drop for OwnedDevicePath {
293299

294300
impl crate::fmt::Debug for OwnedDevicePath {
295301
fn fmt(&self, f: &mut crate::fmt::Formatter<'_>) -> crate::fmt::Result {
296-
match device_path_to_text(self.0) {
302+
match self.borrow().to_text() {
297303
Ok(p) => p.fmt(f),
298304
Err(_) => f.debug_struct("OwnedDevicePath").finish_non_exhaustive(),
299305
}
300306
}
301307
}
302308

309+
pub(crate) struct BorrowedDevicePath<'a> {
310+
protocol: NonNull<r_efi::protocols::device_path::Protocol>,
311+
phantom: PhantomData<&'a r_efi::protocols::device_path::Protocol>,
312+
}
313+
314+
impl<'a> BorrowedDevicePath<'a> {
315+
pub(crate) const fn new(protocol: NonNull<r_efi::protocols::device_path::Protocol>) -> Self {
316+
Self { protocol, phantom: PhantomData }
317+
}
318+
319+
pub(crate) fn to_text(&self) -> io::Result<OsString> {
320+
device_path_to_text(self.protocol)
321+
}
322+
}
323+
324+
impl<'a> crate::fmt::Debug for BorrowedDevicePath<'a> {
325+
fn fmt(&self, f: &mut crate::fmt::Formatter<'_>) -> crate::fmt::Result {
326+
match self.to_text() {
327+
Ok(p) => p.fmt(f),
328+
Err(_) => f.debug_struct("BorrowedDevicePath").finish_non_exhaustive(),
329+
}
330+
}
331+
}
332+
303333
pub(crate) struct OwnedProtocol<T> {
304334
guid: r_efi::efi::Guid,
305335
handle: NonNull<crate::ffi::c_void>,
@@ -452,3 +482,21 @@ pub(crate) fn open_shell() -> Option<NonNull<shell::Protocol>> {
452482

453483
None
454484
}
485+
486+
/// Get device path protocol associated with shell mapping.
487+
///
488+
/// returns None in case no such mapping is exists
489+
pub(crate) fn get_device_path_from_map(map: &Path) -> io::Result<BorrowedDevicePath<'static>> {
490+
let shell =
491+
open_shell().ok_or(io::const_error!(io::ErrorKind::NotFound, "UEFI Shell not found"))?;
492+
let mut path = os_string_to_raw(map.as_os_str())
493+
.ok_or(io::const_error!(io::ErrorKind::InvalidFilename, "Invalid UEFI shell mapping"))?;
494+
495+
// The Device Path Protocol pointer returned by UEFI shell is owned by the shell and is not
496+
// freed throughout it's lifetime. So it has a 'static lifetime.
497+
let protocol = unsafe { ((*shell.as_ptr()).get_device_path_from_map)(path.as_mut_ptr()) };
498+
let protocol = NonNull::new(protocol)
499+
.ok_or(io::const_error!(io::ErrorKind::NotFound, "UEFI Shell mapping not found"))?;
500+
501+
Ok(BorrowedDevicePath::new(protocol))
502+
}

library/std/src/sys/path/mod.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,12 @@ cfg_if::cfg_if! {
55
} else if #[cfg(all(target_vendor = "fortanix", target_env = "sgx"))] {
66
mod sgx;
77
pub use sgx::*;
8-
} else if #[cfg(any(
9-
target_os = "uefi",
10-
target_os = "solid_asp3",
11-
))] {
8+
} else if #[cfg(target_os = "solid_asp3")] {
129
mod unsupported_backslash;
1310
pub use unsupported_backslash::*;
11+
} else if #[cfg(target_os = "uefi")] {
12+
mod uefi;
13+
pub use uefi::*;
1414
} else {
1515
mod unix;
1616
pub use unix::*;

library/std/src/sys/path/uefi.rs

+105
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
#![forbid(unsafe_op_in_unsafe_fn)]
2+
use crate::ffi::OsStr;
3+
use crate::io;
4+
use crate::path::{Path, PathBuf, Prefix};
5+
use crate::sys::{helpers, unsupported_err};
6+
7+
const FORWARD_SLASH: u8 = b'/';
8+
const COLON: u8 = b':';
9+
10+
#[inline]
11+
pub fn is_sep_byte(b: u8) -> bool {
12+
b == b'\\'
13+
}
14+
15+
#[inline]
16+
pub fn is_verbatim_sep(b: u8) -> bool {
17+
b == b'\\'
18+
}
19+
20+
pub fn parse_prefix(_: &OsStr) -> Option<Prefix<'_>> {
21+
None
22+
}
23+
24+
pub const MAIN_SEP_STR: &str = "\\";
25+
pub const MAIN_SEP: char = '\\';
26+
27+
/// UEFI paths can be of 4 types:
28+
///
29+
/// 1. Absolute Shell Path: Uses shell mappings (eg: `FS0:`). Does not exist if UEFI shell not present.
30+
/// It can be identified with `:`.
31+
/// Eg: FS0:\abc\run.efi
32+
///
33+
/// 2. Absolute Device Path: this is what we want
34+
/// It can be identified with `/`.
35+
/// Eg: PciRoot(0x0)/Pci(0x1,0x1)/Ata(Secondary,Slave,0x0)/\abc\run.efi
36+
///
37+
/// 3: Relative root: path relative to the current volume.
38+
/// It will start with `\`.
39+
/// Eg: \abc\run.efi
40+
///
41+
/// 4: Relative
42+
/// Eg: run.efi
43+
///
44+
/// The algorithm is mostly taken from edk2 UEFI shell implementation and is
45+
/// somewhat simple. Check for the path type in order.
46+
///
47+
/// The volume mapping in Absolute Shell Path (not the rest of the path) can be converted to Device
48+
/// Path Protocol using `EFI_SHELL->GetDevicePathFromMap`. The rest of the path (Relative root
49+
/// path), can just be appended to the remaining path.
50+
///
51+
/// For Relative root, we get the current volume (either in Shell Mapping, or Device Path Protocol
52+
/// form) and join it with the relative root path. We then recurse the function to resolve the Shell
53+
/// Mapping if present.
54+
///
55+
/// For Relative paths, we use the current working directory to construct
56+
/// the new path and recurse the function to resolve the Shell mapping if present.
57+
///
58+
/// Finally, at the end, we get the 2nd form, i.e. Absolute Device Path, which can be used in the
59+
/// normal UEFI APIs such as file, process, etc.
60+
/// Eg: PciRoot(0x0)/Pci(0x1,0x1)/Ata(Secondary,Slave,0x0)/\abc\run.efi
61+
pub(crate) fn absolute(path: &Path) -> io::Result<PathBuf> {
62+
// Absolute Shell Path
63+
if path.as_os_str().as_encoded_bytes().contains(&COLON) {
64+
let mut path_components = path.components();
65+
// Since path is not empty, it has at least one Component
66+
let prefix = path_components.next().unwrap();
67+
68+
let dev_path = helpers::get_device_path_from_map(prefix.as_ref())?;
69+
let mut dev_path_text = dev_path.to_text().map_err(|_| unsupported_err())?;
70+
71+
// UEFI Shell does not seem to end device path with `/`
72+
if *dev_path_text.as_encoded_bytes().last().unwrap() != FORWARD_SLASH {
73+
dev_path_text.push("/");
74+
}
75+
76+
let mut ans = PathBuf::from(dev_path_text);
77+
ans.push(path_components);
78+
79+
return Ok(ans);
80+
}
81+
82+
// Absolute Device Path
83+
if path.as_os_str().as_encoded_bytes().contains(&FORWARD_SLASH) {
84+
return Ok(path.to_path_buf());
85+
}
86+
87+
// cur_dir() always returns something
88+
let cur_dir = crate::env::current_dir().unwrap();
89+
let mut path_components = path.components();
90+
91+
// Relative Root
92+
if path_components.next().unwrap() == crate::path::Component::RootDir {
93+
let mut ans = PathBuf::new();
94+
ans.push(cur_dir.components().next().unwrap());
95+
ans.push(path_components);
96+
return absolute(&ans);
97+
}
98+
99+
absolute(&cur_dir.join(path))
100+
}
101+
102+
pub(crate) fn is_absolute(path: &Path) -> bool {
103+
let temp = path.as_os_str().as_encoded_bytes();
104+
temp.contains(&COLON) || temp.contains(&FORWARD_SLASH)
105+
}

0 commit comments

Comments
 (0)