Skip to content

Commit 4262963

Browse files
committed
Handle ExitBootServices
- Make BootServices unavailable if ExitBootServices event is signaled. - Use thread locals for SystemTable and ImageHandle Signed-off-by: Ayush Singh <[email protected]>
1 parent ca85e91 commit 4262963

File tree

4 files changed

+116
-26
lines changed

4 files changed

+116
-26
lines changed

library/std/src/os/uefi/env.rs

+33-10
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,17 @@
22
33
#![unstable(feature = "uefi_std", issue = "100499")]
44

5-
use crate::ffi::c_void;
6-
use crate::ptr::NonNull;
7-
use crate::sync::atomic::{AtomicPtr, Ordering};
8-
use crate::sync::OnceLock;
5+
use crate::{cell::Cell, ffi::c_void, ptr::NonNull};
96

10-
// Position 0 = SystemTable
11-
// Position 1 = ImageHandle
12-
static GLOBALS: OnceLock<(AtomicPtr<c_void>, AtomicPtr<c_void>)> = OnceLock::new();
7+
// Since UEFI is single-threaded, making the global variables thread local should be safe.
8+
thread_local! {
9+
// Flag to check if BootServices are still valid.
10+
// Start with assuming that they are not available
11+
static BOOT_SERVICES_FLAG: Cell<bool> = Cell::new(false);
12+
// Position 0 = SystemTable
13+
// Position 1 = ImageHandle
14+
static GLOBALS: Cell<Option<(NonNull<c_void>, NonNull<c_void>)>> = Cell::new(None);
15+
}
1316

1417
/// Initializes the global System Table and Image Handle pointers.
1518
///
@@ -25,7 +28,7 @@ static GLOBALS: OnceLock<(AtomicPtr<c_void>, AtomicPtr<c_void>)> = OnceLock::new
2528
///
2629
/// This function must not be called more than once.
2730
pub unsafe fn init_globals(handle: NonNull<c_void>, system_table: NonNull<c_void>) {
28-
GLOBALS.set((AtomicPtr::new(system_table.as_ptr()), AtomicPtr::new(handle.as_ptr()))).unwrap()
31+
GLOBALS.set(Some((system_table, handle)));
2932
}
3033

3134
/// Get the SystemTable Pointer.
@@ -43,11 +46,31 @@ pub fn image_handle() -> NonNull<c_void> {
4346
/// Get the SystemTable Pointer.
4447
/// This function is mostly intended for places where panic is not an option
4548
pub(crate) fn try_system_table() -> Option<NonNull<crate::ffi::c_void>> {
46-
NonNull::new(GLOBALS.get()?.0.load(Ordering::Acquire))
49+
GLOBALS.get().map(|x| x.0)
4750
}
4851

4952
/// Get the SystemHandle Pointer.
5053
/// This function is mostly intended for places where panic is not an option
5154
pub(crate) fn try_image_handle() -> Option<NonNull<crate::ffi::c_void>> {
52-
NonNull::new(GLOBALS.get()?.1.load(Ordering::Acquire))
55+
GLOBALS.get().map(|x| x.1)
56+
}
57+
58+
/// Get the BootServices Pointer.
59+
/// This function also checks if `ExitBootServices` has already been called.
60+
pub(crate) fn boot_services() -> Option<NonNull<r_efi::efi::BootServices>> {
61+
if BOOT_SERVICES_FLAG.get() {
62+
let system_table: NonNull<r_efi::efi::SystemTable> = try_system_table()?.cast();
63+
let boot_services = unsafe { (*system_table.as_ptr()).boot_services };
64+
NonNull::new(boot_services)
65+
} else {
66+
None
67+
}
68+
}
69+
70+
pub(crate) fn enable_boot_services() {
71+
BOOT_SERVICES_FLAG.set(true);
72+
}
73+
74+
pub(crate) fn disable_boot_services() {
75+
BOOT_SERVICES_FLAG.set(false);
5376
}

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

+10
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,11 @@ const MEMORY_TYPE: u32 = r_efi::efi::LOADER_DATA;
88
#[stable(feature = "alloc_system_type", since = "1.28.0")]
99
unsafe impl GlobalAlloc for System {
1010
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
11+
// Return null pointer if boot services are not available
12+
if crate::os::uefi::env::boot_services().is_none() {
13+
return crate::ptr::null_mut();
14+
}
15+
1116
let system_table = match crate::os::uefi::env::try_system_table() {
1217
None => return crate::ptr::null_mut(),
1318
Some(x) => x.as_ptr() as *mut _,
@@ -18,6 +23,11 @@ unsafe impl GlobalAlloc for System {
1823
}
1924

2025
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
26+
// Do nothing if boot services are not available
27+
if crate::os::uefi::env::boot_services().is_none() {
28+
return;
29+
}
30+
2131
let system_table = match crate::os::uefi::env::try_system_table() {
2232
None => handle_alloc_error(layout),
2333
Some(x) => x.as_ptr() as *mut _,

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

+37-13
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,18 @@
99
//! - Protocols are produced and consumed.
1010
//! - More information about protocols can be found [here](https://edk2-docs.gitbook.io/edk-ii-uefi-driver-writer-s-guide/3_foundation/36_protocols_and_handles)
1111
12-
use r_efi::efi::Guid;
12+
use r_efi::efi::{self, Guid};
1313

14-
use crate::io::{self, const_io_error};
1514
use crate::mem::{size_of, MaybeUninit};
1615
use crate::os::uefi;
1716
use crate::ptr::NonNull;
17+
use crate::{
18+
io::{self, const_io_error},
19+
os::uefi::env::boot_services,
20+
};
21+
22+
const BOOT_SERVICES_UNAVAILABLE: io::Error =
23+
const_io_error!(io::ErrorKind::Other, "Boot Services are no longer available");
1824

1925
/// Locate Handles with a particular Protocol GUID
2026
/// Implemented using `EFI_BOOT_SERVICES.LocateHandles()`
@@ -40,7 +46,7 @@ pub(crate) fn locate_handles(mut guid: Guid) -> io::Result<Vec<NonNull<crate::ff
4046
if r.is_error() { Err(status_to_io_error(r)) } else { Ok(()) }
4147
}
4248

43-
let boot_services = boot_services();
49+
let boot_services = boot_services().ok_or(BOOT_SERVICES_UNAVAILABLE)?;
4450
let mut buf_len = 0usize;
4551

4652
// This should always fail since the size of buffer is 0. This call should update the buf_len
@@ -76,7 +82,7 @@ pub(crate) fn open_protocol<T>(
7682
handle: NonNull<crate::ffi::c_void>,
7783
mut protocol_guid: Guid,
7884
) -> io::Result<NonNull<T>> {
79-
let boot_services = boot_services();
85+
let boot_services = boot_services().ok_or(BOOT_SERVICES_UNAVAILABLE)?;
8086
let system_handle = uefi::env::image_handle();
8187
let mut protocol: MaybeUninit<*mut T> = MaybeUninit::uninit();
8288

@@ -267,14 +273,32 @@ pub(crate) fn status_to_io_error(s: r_efi::efi::Status) -> io::Error {
267273
}
268274
}
269275

270-
/// Get the BootServices Pointer.
271-
pub(crate) fn boot_services() -> NonNull<r_efi::efi::BootServices> {
272-
try_boot_services().unwrap()
276+
pub(crate) fn create_event(
277+
signal: u32,
278+
tpl: efi::Tpl,
279+
handler: Option<efi::EventNotify>,
280+
context: *mut crate::ffi::c_void,
281+
) -> io::Result<NonNull<crate::ffi::c_void>> {
282+
let boot_services = boot_services().ok_or(BOOT_SERVICES_UNAVAILABLE)?;
283+
let mut exit_boot_service_event: r_efi::efi::Event = crate::ptr::null_mut();
284+
let r = unsafe {
285+
let create_event = (*boot_services.as_ptr()).create_event;
286+
(create_event)(signal, tpl, handler, context, &mut exit_boot_service_event)
287+
};
288+
if r.is_error() {
289+
Err(status_to_io_error(r))
290+
} else {
291+
NonNull::new(exit_boot_service_event)
292+
.ok_or(const_io_error!(io::ErrorKind::Other, "null protocol"))
293+
}
273294
}
274-
/// Get the BootServices Pointer.
275-
/// This function is mostly intended for places where panic is not an option
276-
pub(crate) fn try_boot_services() -> Option<NonNull<r_efi::efi::BootServices>> {
277-
let system_table: NonNull<r_efi::efi::SystemTable> = uefi::env::try_system_table()?.cast();
278-
let boot_services = unsafe { (*system_table.as_ptr()).boot_services };
279-
NonNull::new(boot_services)
295+
296+
pub(crate) fn close_event(evt: NonNull<crate::ffi::c_void>) -> io::Result<()> {
297+
let boot_services = boot_services().ok_or(BOOT_SERVICES_UNAVAILABLE)?;
298+
let r = unsafe {
299+
let close_event = (*boot_services.as_ptr()).close_event;
300+
(close_event)(evt.as_ptr())
301+
};
302+
303+
if r.is_error() { Err(status_to_io_error(r)) } else { Ok(()) }
280304
}

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

+36-3
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ pub(crate) mod helpers;
5252
#[cfg(test)]
5353
mod tests;
5454

55+
use crate::cell::Cell;
5556
use crate::io as std_io;
5657
use crate::os::uefi;
5758
use crate::ptr::NonNull;
@@ -60,6 +61,10 @@ pub mod memchr {
6061
pub use core::slice::memchr::{memchr, memrchr};
6162
}
6263

64+
thread_local! {
65+
static EXIT_BOOT_SERVICE_EVENT: Cell<Option<NonNull<crate::ffi::c_void>>> = Cell::new(None);
66+
}
67+
6368
/// # SAFETY
6469
/// - must be called only once during runtime initialization.
6570
/// - argc must be 2.
@@ -68,13 +73,32 @@ pub(crate) unsafe fn init(argc: isize, argv: *const *const u8, _sigpipe: u8) {
6873
assert_eq!(argc, 2);
6974
let image_handle = unsafe { NonNull::new(*argv as *mut crate::ffi::c_void).unwrap() };
7075
let system_table = unsafe { NonNull::new(*argv.add(1) as *mut crate::ffi::c_void).unwrap() };
71-
unsafe { crate::os::uefi::env::init_globals(image_handle, system_table) };
76+
unsafe { uefi::env::init_globals(image_handle, system_table) };
77+
// Enable boot services once GLOBALS are initialized
78+
uefi::env::enable_boot_services();
79+
80+
// Register exit boot services handler
81+
match helpers::create_event(
82+
r_efi::efi::EVT_SIGNAL_EXIT_BOOT_SERVICES,
83+
r_efi::efi::TPL_NOTIFY,
84+
Some(exit_boot_service_handler),
85+
crate::ptr::null_mut(),
86+
) {
87+
Ok(x) => {
88+
EXIT_BOOT_SERVICE_EVENT.set(Some(x));
89+
}
90+
Err(_) => abort_internal(),
91+
}
7292
}
7393

7494
/// # SAFETY
7595
/// this is not guaranteed to run, for example when the program aborts.
7696
/// - must be called only once during runtime cleanup.
77-
pub unsafe fn cleanup() {}
97+
pub unsafe fn cleanup() {
98+
if let Some(exit_boot_service_event) = EXIT_BOOT_SERVICE_EVENT.take() {
99+
let _ = helpers::close_event(exit_boot_service_event);
100+
}
101+
}
78102

79103
#[inline]
80104
pub const fn unsupported<T>() -> std_io::Result<T> {
@@ -98,8 +122,12 @@ pub fn decode_error_kind(code: i32) -> crate::io::ErrorKind {
98122
}
99123

100124
pub fn abort_internal() -> ! {
125+
if let Some(exit_boot_service_event) = EXIT_BOOT_SERVICE_EVENT.take() {
126+
let _ = helpers::close_event(exit_boot_service_event);
127+
}
128+
101129
if let (Some(boot_services), Some(handle)) =
102-
(helpers::try_boot_services(), uefi::env::try_image_handle())
130+
(uefi::env::boot_services(), uefi::env::try_image_handle())
103131
{
104132
let _ = unsafe {
105133
((*boot_services.as_ptr()).exit)(
@@ -155,3 +183,8 @@ fn get_random() -> Option<(u64, u64)> {
155183
}
156184
None
157185
}
186+
187+
/// Disable access to BootServices if `EVT_SIGNAL_EXIT_BOOT_SERVICES` is signaled
188+
extern "efiapi" fn exit_boot_service_handler(_e: r_efi::efi::Event, _ctx: *mut crate::ffi::c_void) {
189+
uefi::env::disable_boot_services();
190+
}

0 commit comments

Comments
 (0)