Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienux/blob/main/vendor/uefi/src/boot.rs # aienux Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aienux / vendor / uefi / src / boot.rs` 2229 lines ยท 82707 bytes Raw Blame History 1 // SPDX-License-Identifier: MIT OR Apache-2.0 2 3 //! UEFI boot services. 4 //! 5 //! These functions will panic if called after exiting boot services. 6 //! 7 //! # Accessing Protocols 8 //! 9 //! Protocols in this module can be opened through multiple functions. In most 10 //! cases, [`open_protocol_exclusive`] is the recommended choice. It opens the 11 //! protocol with exclusive access, preventing concurrent use until it is 12 //! closed, and returns a [`ScopedProtocol`] that automatically releases the 13 //! protocol when dropped. Note that this approach has certain caveats; refer to 14 //! the documentation of the respective function for details. 15 //! 16 //! Other methods for opening protocols: 17 //! 18 //! * [`open_protocol`] 19 //! * [`get_image_file_system`] 20 //! 21 //! For protocol definitions, see the [`proto`] module. 22 //! 23 //! # Accessing Handles 24 //! 25 //! To access handles supporting a certain protocol, we recommend using 26 //! [`find_handles`], [`locate_handle`], and [`locate_handle_buffer`]. 27 //! 28 //! [`proto`]: crate::proto 29 30 pub use uefi_raw::table::boot::{ 31 EventType, MemoryAttribute, MemoryDescriptor, MemoryType, PAGE_SIZE, Tpl, 32 }; 33 34 use crate::data_types::PhysicalAddress; 35 use crate::mem::memory_map::{MemoryMapBackingMemory, MemoryMapKey, MemoryMapMeta, MemoryMapOwned}; 36 use crate::polyfill::maybe_uninit_slice_assume_init_ref; 37 #[cfg(doc)] 38 use crate::proto::device_path::LoadedImageDevicePath; 39 use crate::proto::device_path::{DevicePath, FfiDevicePath}; 40 use crate::proto::loaded_image::LoadedImage; 41 use crate::proto::media::fs::SimpleFileSystem; 42 use crate::proto::{BootPolicy, Protocol, ProtocolPointer}; 43 use crate::runtime::{self, ResetType}; 44 use crate::table::Revision; 45 use crate::util::opt_nonnull_to_ptr; 46 use crate::{Char16, Error, Event, Guid, Handle, Result, Status, StatusExt, helpers, table}; 47 use core::ffi::c_void; 48 use core::fmt::{self, Display, Formatter}; 49 use core::mem::MaybeUninit; 50 use core::ops::{Deref, DerefMut}; 51 use core::ptr::{self, NonNull}; 52 use core::sync::atomic::{AtomicPtr, Ordering}; 53 use core::time::Duration; 54 use core::{mem, slice}; 55 use uefi_raw::protocol::device_path::DevicePathProtocol; 56 use uefi_raw::table::boot::{ 57 AllocateType as RawAllocateType, BootServices, EventNotifyFn as RawEventNotifyFn, 58 InterfaceType, TimerDelay, 59 }; 60 #[cfg(feature = "alloc")] 61 use {alloc::vec::Vec, uefi::ResultExt}; 62 63 /// Global image handle. This is only set by [`set_image_handle`], and it is 64 /// only read by [`image_handle`]. 65 static IMAGE_HANDLE: AtomicPtr = AtomicPtr::new(ptr::null_mut()); 66 67 /// Get the [`Handle`] of the currently-executing image. 68 #[must_use] 69 pub fn image_handle() -> Handle { 70 let ptr = IMAGE_HANDLE.load(Ordering::Acquire); 71 // Safety: the image handle must be valid. We know it is, because it was set 72 // by `set_image_handle`, which has that same safety requirement. 73 // SAFETY: The memory is valid. 74 unsafe { Handle::from_ptr(ptr) }.expect("set_image_handle has not been called") 75 } 76 77 /// Update the global image [`Handle`]. 78 /// 79 /// This is called automatically in the `main` entry point as part of 80 /// [`uefi::entry`]. It should not be called at any other point in time, unless 81 /// the executable does not use [`uefi::entry`], in which case it should be 82 /// called once before calling other boot services functions. 83 /// 84 /// # Safety 85 /// 86 /// This function should only be called as described above, and the 87 /// `image_handle` must be a valid image [`Handle`]. The safety guarantees of 88 /// [`open_protocol_exclusive`] rely on the global image handle being correct. 89 pub unsafe fn set_image_handle(image_handle: Handle) { 90 IMAGE_HANDLE.store(image_handle.as_ptr(), Ordering::Release); 91 } 92 93 /// Returns `true` if boot services are active and `false` otherwise. 94 pub(crate) fn are_boot_services_active() -> bool { 95 let Some(st) = table::system_table_raw() else { 96 return false; 97 }; 98 99 // SAFETY: valid per requirements of `set_system_table`. 100 let st = unsafe { st.as_ref() }; 101 102 !st.boot_services.is_null() 103 } 104 105 fn boot_services_raw_panicking() -> NonNull { 106 let st = table::system_table_raw_panicking(); 107 // SAFETY: valid per requirements of `set_system_table`. 108 let st = unsafe { st.as_ref() }; 109 NonNull::new(st.boot_services).expect("boot services are not active") 110 } 111 112 /// Raises a task's priority level and returns a [`TplGuard`]. 113 /// 114 /// The effect of calling `raise_tpl` with a `Tpl` that is below the current 115 /// one (which, sadly, cannot be queried) is undefined by the UEFI spec, 116 /// which also warns against remaining at high `Tpl`s for a long time. 117 /// 118 /// This function returns an RAII guard that will automatically restore the 119 /// original `Tpl` when dropped. 120 /// 121 /// # Safety 122 /// 123 /// Raising a task's priority level can affect other running tasks and 124 /// critical processes run by UEFI. The highest priority level is the 125 /// most dangerous, since it disables interrupts. 126 #[must_use] 127 pub unsafe fn raise_tpl(tpl: Tpl) -> TplGuard { 128 let bt = boot_services_raw_panicking(); 129 // SAFETY: The pointer is not null and we assume it to be initialized. 130 let bt = unsafe { bt.as_ref() }; 131 132 TplGuard { 133 // SAFETY: The memory is valid. 134 old_tpl: unsafe { (bt.raise_tpl)(tpl) }, 135 } 136 } 137 138 /// Allocates a consecutive set of memory pages using the UEFI allocator. 139 /// 140 /// The buffer will be [`PAGE_SIZE`] aligned. Callers are responsible for 141 /// freeing the memory using [`free_pages`]. 142 /// 143 /// # Arguments 144 /// - `allocation_type`: The [`AllocateType`] to choose the allocation strategy. 145 /// - `memory_type`: The [`MemoryType`] used to persist the allocation in the 146 /// UEFI memory map. Typically, UEFI OS loaders should allocate memory of 147 /// type [`MemoryType::LOADER_DATA`]. 148 ///- `count`: Number of pages to allocate. 149 /// 150 /// # Safety 151 /// 152 /// Using this function is safe, but it returns a raw pointer to uninitialized 153 /// memory. The memory must be initialized before creating a reference to it 154 /// or reading from it eventually. 155 /// 156 /// # Errors 157 /// 158 /// * [`Status::OUT_OF_RESOURCES`]: allocation failed. 159 /// * [`Status::INVALID_PARAMETER`]: `mem_ty` is [`MemoryType::PERSISTENT_MEMORY`], 160 /// [`MemoryType::UNACCEPTED`], or in the range [MemoryType::MAX]..=0x6fff_ffff. 161 /// * [`Status::NOT_FOUND`]: the requested pages could not be found. 162 pub fn allocate_pages( 163 allocation_type: AllocateType, 164 memory_type: MemoryType, 165 count: usize, 166 ) -> Result> { 167 let bt = boot_services_raw_panicking(); 168 // SAFETY: The pointer is not null and we assume it to be initialized. 169 let bt = unsafe { bt.as_ref() }; 170 171 let (ty, initial_addr) = match allocation_type { 172 AllocateType::AnyPages => (RawAllocateType::ANY_PAGES, 0), 173 AllocateType::MaxAddress(addr) => (RawAllocateType::MAX_ADDRESS, addr), 174 AllocateType::Address(addr) => (RawAllocateType::ADDRESS, addr), 175 }; 176 177 let mut addr1 = initial_addr; 178 // SAFETY: The memory is valid. 179 unsafe { (bt.allocate_pages)(ty, memory_type, count, &mut addr1) }.to_result()?; 180 181 // The UEFI spec allows `allocate_pages` to return a valid allocation at 182 // address zero. Rust does not allow writes through a null pointer (which 183 // Rust defines as address zero), so this is not very useful. Only return 184 // the allocation if the address is non-null. 185 if let Some(ptr) = NonNull::new(addr1 as *mut u8) { 186 return Ok(ptr); 187 } 188 189 // Attempt a second allocation. The first allocation (at address zero) has 190 // not yet been freed, so if this allocation succeeds it should be at a 191 // non-zero address. 192 let mut addr2 = initial_addr; 193 // SAFETY: The memory is valid. 194 let r = unsafe { (bt.allocate_pages)(ty, memory_type, count, &mut addr2) }.to_result(); 195 196 // Free the original allocation (ignoring errors). 197 // SAFETY: This pointer was allocated by the matching UEFI allocator. 198 let _unused = unsafe { (bt.free_pages)(addr1, count) }; 199 200 // Return an error if the second allocation failed, or if it is still at 201 // address zero. Otherwise, return a pointer to the second allocation. 202 r?; 203 if let Some(ptr) = NonNull::new(addr2 as *mut u8) { 204 Ok(ptr) 205 } else { 206 Err(Status::OUT_OF_RESOURCES.into()) 207 } 208 } 209 210 /// Frees memory pages allocated by [`allocate_pages`]. 211 /// 212 /// # Safety 213 /// 214 /// The caller must ensure that no references into the allocation remain, 215 /// and that the memory at the allocation is not used after it is freed. 216 /// 217 /// # Errors 218 /// 219 /// * [`Status::NOT_FOUND`]: `ptr` was not allocated by [`allocate_pages`]. 220 /// * [`Status::INVALID_PARAMETER`]: `ptr` is not page aligned or is otherwise invalid. 221 pub unsafe fn free_pages(ptr: NonNull, count: usize) -> Result { 222 let bt = boot_services_raw_panicking(); 223 // SAFETY: The pointer is not null and we assume it to be initialized. 224 let bt = unsafe { bt.as_ref() }; 225 226 let addr = ptr.as_ptr() as PhysicalAddress; 227 // SAFETY: This pointer was allocated by the matching UEFI allocator. 228 unsafe { (bt.free_pages)(addr, count) }.to_result() 229 } 230 231 /// Allocates a consecutive region of bytes using the UEFI allocator. 232 /// 233 /// The buffer will be 8-byte aligned. Callers are responsible for freeing the 234 /// memory using [`free_pool`]. 235 /// 236 /// # Arguments 237 /// - `memory_type`: The [`MemoryType`] used to persist the allocation in the 238 /// UEFI memory map. Typically, UEFI OS loaders should allocate memory of 239 /// type [`MemoryType::LOADER_DATA`]. 240 ///- `size`: Number of bytes to allocate. 241 /// 242 /// # Safety 243 /// 244 /// Using this function is safe, but it returns a raw pointer to uninitialized 245 /// memory. The memory must be initialized before creating a reference to it 246 /// or reading from it eventually. 247 /// 248 /// # Errors 249 /// 250 /// * [`Status::OUT_OF_RESOURCES`]: allocation failed. 251 /// * [`Status::INVALID_PARAMETER`]: `mem_ty` is [`MemoryType::PERSISTENT_MEMORY`], 252 /// [`MemoryType::UNACCEPTED`], or in the range [MemoryType::MAX]..=0x6fff_ffff. 253 pub fn allocate_pool(memory_type: MemoryType, size: usize) -> Result> { 254 let bt = boot_services_raw_panicking(); 255 // SAFETY: The pointer is not null and we assume it to be initialized. 256 let bt = unsafe { bt.as_ref() }; 257 258 let mut buffer = ptr::null_mut(); 259 // SAFETY: The memory is valid. 260 let ptr = unsafe { (bt.allocate_pool)(memory_type, size, &mut buffer) } 261 .to_result_with_val(|| buffer)?; 262 263 NonNull::new(ptr).ok_or_else(|| Status::OUT_OF_RESOURCES.into()) 264 } 265 266 /// Frees memory allocated by [`allocate_pool`]. 267 /// 268 /// # Safety 269 /// 270 /// The caller must ensure that no references into the allocation remain, 271 /// and that the memory at the allocation is not used after it is freed. 272 /// 273 /// # Errors 274 /// 275 /// * [`Status::INVALID_PARAMETER`]: `ptr` is invalid. 276 pub unsafe fn free_pool(ptr: NonNull) -> Result { 277 let bt = boot_services_raw_panicking(); 278 // SAFETY: The pointer is not null and we assume it to be initialized. 279 let bt = unsafe { bt.as_ref() }; 280 281 // SAFETY: This pointer was allocated by the matching UEFI allocator. 282 unsafe { (bt.free_pool)(ptr.as_ptr()) }.to_result() 283 } 284 285 /// Queries the `get_memory_map` function of UEFI to retrieve the current 286 /// size of the map. Returns a [`MemoryMapMeta`]. 287 /// 288 /// It is recommended to add a few more bytes for a subsequent allocation 289 /// for the memory map, as the memory map itself also needs heap memory, 290 /// and other allocations might occur before that call. 291 #[must_use] 292 pub(crate) fn memory_map_size() -> MemoryMapMeta { 293 let bt = boot_services_raw_panicking(); 294 // SAFETY: The pointer is not null and we assume it to be initialized. 295 let bt = unsafe { bt.as_ref() }; 296 297 let mut map_size = 0; 298 let mut map_key = MemoryMapKey(0); 299 let mut desc_size = 0; 300 let mut desc_version = 0; 301 302 // SAFETY: The memory is valid. 303 let status = unsafe { 304 (bt.get_memory_map)( 305 &mut map_size, 306 ptr::null_mut(), 307 &mut map_key.0, 308 &mut desc_size, 309 &mut desc_version, 310 ) 311 }; 312 assert_eq!(status, Status::BUFFER_TOO_SMALL); 313 314 assert_eq!( 315 map_size % desc_size, 316 0, 317 "Memory map must be a multiple of the reported descriptor size." 318 ); 319 320 let mmm = MemoryMapMeta { 321 desc_size, 322 map_size, 323 map_key, 324 desc_version, 325 }; 326 327 mmm.assert_sanity_checks(); 328 329 mmm 330 } 331 332 /// Stores the current UEFI memory map in a UEFI-heap-allocated buffer 333 /// and returns a [`MemoryMapOwned`]. 334 /// 335 /// The implementation tries to mitigate some UEFI pitfalls, such as getting 336 /// the right allocation size for the memory map to prevent 337 /// [`Status::BUFFER_TOO_SMALL`]. 338 /// 339 /// # Arguments 340 /// 341 /// - `mt`: The memory type for the backing memory on the UEFI heap. 342 /// Usually, this is [`MemoryType::LOADER_DATA`]. You can also use a 343 /// custom type. 344 /// 345 /// # Errors 346 /// 347 /// * [`Status::INVALID_PARAMETER`]: Invalid [`MemoryType`] 348 /// * [`Status::OUT_OF_RESOURCES`]: allocation failed. 349 /// * [`Status::BAD_BUFFER_SIZE`]: the firmware reported a memory map larger 350 /// than the buffer it was given. 351 /// 352 /// # Panics 353 /// 354 /// Panics if the memory map can't be retrieved because of 355 /// [`Status::BUFFER_TOO_SMALL`]. This behaviour was chosen explicitly as 356 /// callers can't do anything about it anyway. 357 pub fn memory_map(mt: MemoryType) -> Result { 358 let mut buffer = MemoryMapBackingMemory::new(mt)?; 359 360 let meta = get_memory_map(buffer.as_mut_slice()); 361 362 if let Err(e) = &meta { 363 // We don't want to confuse users and let them think they should handle 364 // this, as they can't do anything about it anyway. 365 // 366 // This path won't be taken in OOM situations, but only if for unknown 367 // reasons, we failed to properly allocate the memory map. 368 if e.status() == Status::BUFFER_TOO_SMALL { 369 panic!("Failed to get a proper allocation for the memory map"); 370 } 371 } 372 let meta = meta?; 373 374 Ok(MemoryMapOwned::from_initialized_mem(buffer, meta)) 375 } 376 377 /// Calls the underlying `GetMemoryMap` function of UEFI. On success, 378 /// the buffer is mutated and contains the map. The map might be shorter 379 /// than the buffer, which is reflected by the return value. 380 /// 381 /// # Errors 382 /// 383 /// * [`Status::BAD_BUFFER_SIZE`]: the firmware reported success but a map 384 /// size larger than the buffer. 385 pub(crate) fn get_memory_map(buf: &mut [u8]) -> Result { 386 let bt = boot_services_raw_panicking(); 387 // SAFETY: The pointer is not null and we assume it to be initialized. 388 let bt = unsafe { bt.as_ref() }; 389 390 let mut map_size = buf.len(); 391 let map_buffer = buf.as_mut_ptr().cast::(); 392 let mut map_key = MemoryMapKey(0); 393 let mut desc_size = 0; 394 let mut desc_version = 0; 395 396 assert_eq!( 397 (map_buffer as usize) % align_of::(), 398 0, 399 "Memory map buffers must be aligned like a MemoryDescriptor" 400 ); 401 402 // SAFETY: The memory is valid. 403 unsafe { 404 (bt.get_memory_map)( 405 &mut map_size, 406 map_buffer, 407 &mut map_key.0, 408 &mut desc_size, 409 &mut desc_version, 410 ) 411 } 412 .to_result()?; 413 414 // On success, `map_size` is the size of the map written to the buffer. 415 // A value larger than the buffer would make `MemoryMapOwned` read past 416 // the allocation, so treat it as an error. 417 if map_size > buf.len() { 418 return Err(Status::BAD_BUFFER_SIZE.into()); 419 } 420 421 Ok(MemoryMapMeta { 422 map_size, 423 desc_size, 424 map_key, 425 desc_version, 426 }) 427 } 428 429 /// Creates an event. 430 /// 431 /// This function creates a new event of the specified type and returns it. 432 /// 433 /// Events are created in a "waiting" state, and may switch to a "signaled" 434 /// state. If the event type has flag `NotifySignal` set, this will result in 435 /// a callback for the event being immediately enqueued at the `notify_tpl` 436 /// priority level. If the event type has flag `NotifyWait`, the notification 437 /// will be delivered next time `wait_for_event` or `check_event` is called. 438 /// In both cases, a `notify_fn` callback must be specified. 439 /// 440 /// # Safety 441 /// 442 /// This function is unsafe because callbacks must handle exit from boot 443 /// services correctly. 444 /// 445 /// # Errors 446 /// 447 /// * [`Status::INVALID_PARAMETER`]: an invalid combination of parameters was provided. 448 /// * [`Status::OUT_OF_RESOURCES`]: the event could not be allocated. 449 pub unsafe fn create_event( 450 event_ty: EventType, 451 notify_tpl: Tpl, 452 notify_fn: Option, 453 notify_ctx: Option>, 454 ) -> Result { 455 let bt = boot_services_raw_panicking(); 456 // SAFETY: The pointer is not null and we assume it to be initialized. 457 let bt = unsafe { bt.as_ref() }; 458 459 let mut event = ptr::null_mut(); 460 461 // Safety: the argument types of the function pointers are defined 462 // differently, but are compatible and can be safely transmuted. 463 let notify_fn: Option = 464 // SAFETY: The memory is valid. 465 unsafe { mem::transmute(notify_fn) }; 466 467 let notify_ctx = opt_nonnull_to_ptr(notify_ctx); 468 469 // Now we're ready to call UEFI 470 // SAFETY: The memory is valid. 471 unsafe { (bt.create_event)(event_ty, notify_tpl, notify_fn, notify_ctx, &mut event) } 472 .to_result_with_val( 473 // OK to unwrap: event is non-null for Status::SUCCESS. 474 // SAFETY: The memory is valid. 475 || unsafe { Event::from_ptr(event) }.unwrap(), 476 ) 477 } 478 479 /// Creates an event in an event group. 480 /// 481 /// The event's notification function, context, and task priority are specified 482 /// by `notify_fn`, `notify_ctx`, and `notify_tpl`, respectively. The event will 483 /// be added to the group of events identified by `event_group`. 484 /// 485 /// If no group is specified by `event_group`, this function behaves as if the 486 /// same parameters had been passed to `create_event()`. 487 /// 488 /// Event groups are collections of events identified by a shared GUID where, 489 /// when one member event is signaled, all other events are signaled and their 490 /// individual notification actions are taken. All events are guaranteed to be 491 /// signaled before the first notification action is taken. All notification 492 /// functions will be executed in the order specified by their `Tpl`. 493 /// 494 /// An event can only be part of a single event group. An event may be removed 495 /// from an event group by calling [`close_event`]. 496 /// 497 /// The [`EventType`] of an event uses the same values as `create_event()`, except that 498 /// `EventType::SIGNAL_EXIT_BOOT_SERVICES` and `EventType::SIGNAL_VIRTUAL_ADDRESS_CHANGE` 499 /// are not valid. 500 /// 501 /// For events of type `NOTIFY_SIGNAL` or `NOTIFY_WAIT`, `notify_fn` must be 502 /// `Some` and `notify_tpl` must be a valid task priority level. For other event 503 /// types these parameters are ignored. 504 /// 505 /// More than one event of type `EventType::TIMER` may be part of a single event 506 /// group. However, there is no mechanism for determining which of the timers 507 /// was signaled. 508 /// 509 /// This operation is only supported starting with UEFI 2.0; earlier versions 510 /// will fail with [`Status::UNSUPPORTED`]. 511 /// 512 /// # Safety 513 /// 514 /// This function is unsafe because callbacks must handle exit from boot 515 /// services correctly. 516 /// 517 /// # Errors 518 /// 519 /// * [`Status::INVALID_PARAMETER`]: an invalid combination of parameters was provided. 520 /// * [`Status::OUT_OF_RESOURCES`]: the event could not be allocated. 521 pub unsafe fn create_event_ex( 522 event_type: EventType, 523 notify_tpl: Tpl, 524 notify_fn: Option, 525 notify_ctx: Option>, 526 event_group: Option<&Guid>, 527 ) -> Result { 528 let bt = boot_services_raw_panicking(); 529 // SAFETY: The pointer is not null and we assume it to be initialized. 530 let bt = unsafe { bt.as_ref() }; 531 532 if bt.header.revision < Revision::EFI_2_00 { 533 return Err(Status::UNSUPPORTED.into()); 534 } 535 536 let mut event = ptr::null_mut(); 537 538 // Safety: the argument types of the function pointers are defined 539 // differently, but are compatible and can be safely transmuted. 540 let notify_fn: Option = 541 // SAFETY: The memory is valid. 542 unsafe { mem::transmute(notify_fn) }; 543 544 // SAFETY: The memory is valid. 545 unsafe { 546 (bt.create_event_ex)( 547 event_type, 548 notify_tpl, 549 notify_fn, 550 opt_nonnull_to_ptr(notify_ctx), 551 event_group.map_or(ptr::null(), ptr::from_ref), 552 &mut event, 553 ) 554 } 555 .to_result_with_val( 556 // OK to unwrap: event is non-null for Status::SUCCESS. 557 // SAFETY: The memory is valid. 558 || unsafe { Event::from_ptr(event) }.unwrap(), 559 ) 560 } 561 562 /// Checks to see if an event is signaled, without blocking execution to wait for it. 563 /// 564 /// Returns `Ok(true)` if the event is in the signaled state or `Ok(false)` 565 /// if the event is not in the signaled state. 566 /// 567 /// # Errors 568 /// 569 /// Note: Instead of returning [`Status::NOT_READY`] as listed in the UEFI 570 /// Specification, this function will return `Ok(false)`. 571 /// 572 /// * [`Status::INVALID_PARAMETER`]: `event` is of type [`NOTIFY_SIGNAL`]. 573 /// 574 /// [`NOTIFY_SIGNAL`]: EventType::NOTIFY_SIGNAL 575 pub fn check_event(event: &Event) -> Result { 576 let bt = boot_services_raw_panicking(); 577 // SAFETY: The pointer is not null and we assume it to be initialized. 578 let bt = unsafe { bt.as_ref() }; 579 580 // SAFETY: The memory is valid. 581 let status = unsafe { (bt.check_event)(event.as_ptr()) }; 582 match status { 583 Status::SUCCESS => Ok(true), 584 Status::NOT_READY => Ok(false), 585 _ => Err(status.into()), 586 } 587 } 588 589 /// Places the supplied `event` in the signaled state. 590 /// 591 /// If `event` is already in 592 /// the signaled state, the function returns successfully. If `event` is of type 593 /// [`NOTIFY_SIGNAL`], the event's notification function is scheduled to be 594 /// invoked at the event's notification task priority level. 595 /// 596 /// This function may be invoked from any task priority level. 597 /// 598 /// If `event` is part of an event group, then all of the events in the event 599 /// group are also signaled and their notification functions are scheduled. 600 /// 601 /// When signaling an event group, it is possible to create an event in the 602 /// group, signal it and then close the event to remove it from the group. 603 /// 604 /// # Errors 605 /// 606 /// The specification does not list any errors. 607 /// 608 /// [`NOTIFY_SIGNAL`]: EventType::NOTIFY_SIGNAL 609 pub fn signal_event(event: &Event) -> Result { 610 let bt = boot_services_raw_panicking(); 611 // SAFETY: The pointer is not null and we assume it to be initialized. 612 let bt = unsafe { bt.as_ref() }; 613 614 // SAFETY: The memory is valid. 615 unsafe { (bt.signal_event)(event.as_ptr()) }.to_result() 616 } 617 618 /// Removes `event` from any event group to which it belongs and closes it. 619 /// 620 /// If `event` was registered with [`register_protocol_notify`], then the 621 /// corresponding registration will be removed. Calling this function within the 622 /// corresponding notify function is allowed. 623 /// 624 /// # Errors 625 /// 626 /// The specification does not list any errors, however implementations are 627 /// allowed to return an error if needed. 628 pub fn close_event(event: Event) -> Result { 629 let bt = boot_services_raw_panicking(); 630 // SAFETY: The pointer is not null and we assume it to be initialized. 631 let bt = unsafe { bt.as_ref() }; 632 633 // SAFETY: The memory is valid. 634 unsafe { (bt.close_event)(event.as_ptr()) }.to_result() 635 } 636 637 /// Sets the trigger for an event of type [`TIMER`]. 638 /// 639 /// # Errors 640 /// 641 /// * [`Status::INVALID_PARAMETER`]: `event` is not valid. 642 /// 643 /// [`TIMER`]: EventType::TIMER 644 pub fn set_timer(event: &Event, trigger_time: TimerTrigger) -> Result { 645 let bt = boot_services_raw_panicking(); 646 // SAFETY: The pointer is not null and we assume it to be initialized. 647 let bt = unsafe { bt.as_ref() }; 648 649 let time = trigger_time.to_100ns_steps(); 650 let ty = match trigger_time { 651 TimerTrigger::Cancel => TimerDelay::CANCEL, 652 TimerTrigger::Periodic(_) => TimerDelay::PERIODIC, 653 TimerTrigger::Relative(_) => TimerDelay::RELATIVE, 654 }; 655 // SAFETY: The memory is valid. 656 unsafe { (bt.set_timer)(event.as_ptr(), ty, time) }.to_result() 657 } 658 659 /// Stops execution until an event is signaled. 660 /// 661 /// This function must be called at priority level [`Tpl::APPLICATION`]. 662 /// 663 /// The input [`Event`] slice is repeatedly iterated from first to last until 664 /// an event is signaled or an error is detected. The following checks are 665 /// performed on each event: 666 /// 667 /// * If an event is of type [`NOTIFY_SIGNAL`], then a 668 /// [`Status::INVALID_PARAMETER`] error is returned with the index of the 669 /// event that caused the failure. 670 /// * If an event is in the signaled state, the signaled state is cleared 671 /// and the index of the event that was signaled is returned. 672 /// * If an event is not in the signaled state but does have a notification 673 /// function, the notification function is queued at the event's 674 /// notification task priority level. If the execution of the event's 675 /// notification function causes the event to be signaled, then the 676 /// signaled state is cleared and the index of the event that was signaled 677 /// is returned. 678 /// 679 /// To wait for a specified time, a timer event must be included in `events`. 680 /// 681 /// To check if an event is signaled without waiting, an already signaled 682 /// event can be used as the last event in the slice being checked, or the 683 /// [`check_event`] interface may be used. 684 /// 685 /// # Errors 686 /// 687 /// * [`Status::INVALID_PARAMETER`]: `events` is empty, or one of the events of 688 /// of type [`NOTIFY_SIGNAL`]. 689 /// * [`Status::UNSUPPORTED`]: the current TPL is not [`Tpl::APPLICATION`]. 690 /// 691 /// [`NOTIFY_SIGNAL`]: EventType::NOTIFY_SIGNAL 692 pub fn wait_for_event(events: &[Event]) -> Result> { 693 let bt = boot_services_raw_panicking(); 694 // SAFETY: The pointer is not null and we assume it to be initialized. 695 let bt = unsafe { bt.as_ref() }; 696 697 let number_of_events = events.len(); 698 let events: *const uefi_raw::Event = events.as_ptr().cast(); 699 700 let mut index = 0; 701 // SAFETY: The memory is valid. 702 unsafe { (bt.wait_for_event)(number_of_events, events, &mut index) }.to_result_with( 703 || index, 704 |s| { 705 if s == Status::INVALID_PARAMETER { 706 Some(index) 707 } else { 708 None 709 } 710 }, 711 ) 712 } 713 714 /// Connect one or more drivers to a controller. 715 /// 716 /// Usually one disconnects and then reconnects certain drivers 717 /// to make them rescan some state that changed, e.g. reconnecting 718 /// a block handle after your app modified disk partitions. 719 /// 720 /// The `driver_image` argument is usually an empty slice. Otherwise, it 721 /// contains an ordered list of candidates for the driver binding protocols that 722 /// will manage the `controller`. If non-empty, the slice must be terminated 723 /// with `None`. 724 /// 725 /// # Errors 726 /// 727 /// * [`Status::NOT_FOUND`]: there are no driver-binding protocol instances 728 /// present in the system, or no drivers are connected to `controller`. 729 /// * [`Status::SECURITY_VIOLATION`]: the caller does not have permission to 730 /// start drivers associated with `controller`. 731 pub fn connect_controller( 732 controller: Handle, 733 driver_image: &[Option], 734 remaining_device_path: Option<&DevicePath>, 735 recursive: bool, 736 ) -> Result { 737 let bt = boot_services_raw_panicking(); 738 // SAFETY: The pointer is not null and we assume it to be initialized. 739 let bt = unsafe { bt.as_ref() }; 740 741 let driver_image: *const uefi_raw::Handle = if let Some(last) = driver_image.last() { 742 assert!( 743 last.is_none(), 744 "driver_image parameter must be terminated with None" 745 ); 746 driver_image.as_ptr().cast() 747 } else { 748 ptr::null() 749 }; 750 751 // SAFETY: The memory is valid. 752 unsafe { 753 (bt.connect_controller)( 754 controller.as_ptr(), 755 driver_image, 756 remaining_device_path 757 .map(|dp| dp.as_ffi_ptr()) 758 .unwrap_or(ptr::null()) 759 .cast(), 760 recursive.into(), 761 ) 762 } 763 .to_result_with_err(|_| ()) 764 } 765 766 /// Disconnect one or more drivers from a controller. 767 /// 768 /// See also [`connect_controller`]. 769 /// 770 /// # Errors 771 /// 772 /// * [`Status::INVALID_PARAMETER`]: `driver_image` is set but does not manage 773 /// `controller`, or does not support the driver binding protocol, or one of 774 /// the handles is invalid. 775 /// * [`Status::OUT_OF_RESOURCES`]: not enough resources available to disconnect 776 /// drivers. 777 /// * [`Status::DEVICE_ERROR`]: the controller could not be disconnected due to 778 /// a device error. 779 pub fn disconnect_controller( 780 controller: Handle, 781 driver_image: Option, 782 child: Option, 783 ) -> Result { 784 let bt = boot_services_raw_panicking(); 785 // SAFETY: The pointer is not null and we assume it to be initialized. 786 let bt = unsafe { bt.as_ref() }; 787 788 // SAFETY: The memory is valid. 789 unsafe { 790 (bt.disconnect_controller)( 791 controller.as_ptr(), 792 Handle::opt_to_ptr(driver_image), 793 Handle::opt_to_ptr(child), 794 ) 795 } 796 .to_result_with_err(|_| ()) 797 } 798 799 /// Installs a protocol interface on a device handle. 800 /// 801 /// When a protocol interface is installed, firmware will call all functions 802 /// that have registered to wait for that interface to be installed. 803 /// 804 /// If `handle` is `None`, a new handle will be created and returned. 805 /// 806 /// # Safety 807 /// 808 /// The caller is responsible for ensuring that they pass a valid `Guid` for `protocol`. 809 /// 810 /// # Errors 811 /// 812 /// * [`Status::OUT_OF_RESOURCES`]: failed to allocate a new handle. 813 /// * [`Status::INVALID_PARAMETER`]: this protocol is already installed on the handle. 814 pub unsafe fn install_protocol_interface( 815 handle: Option, 816 protocol: &Guid, 817 interface: *const c_void, 818 ) -> Result { 819 let bt = boot_services_raw_panicking(); 820 // SAFETY: The pointer is not null and we assume it to be initialized. 821 let bt = unsafe { bt.as_ref() }; 822 823 let mut handle = Handle::opt_to_ptr(handle); 824 // SAFETY: The memory is valid. 825 unsafe { 826 (bt.install_protocol_interface)( 827 &mut handle, 828 protocol, 829 InterfaceType::NATIVE_INTERFACE, 830 interface, 831 ) 832 } 833 // SAFETY: The memory is valid. 834 .to_result_with_val(|| unsafe { Handle::from_ptr(handle) }.unwrap()) 835 } 836 837 /// Reinstalls a protocol interface on a device handle. `old_interface` is 838 /// replaced with `new_interface`. 839 /// 840 /// These interfaces may be the same, in which case the registered protocol 841 /// notifications occur for the handle without replacing the interface. 842 /// 843 /// As with `install_protocol_interface`, any process that has registered to 844 /// wait for the installation of the interface is notified. 845 /// 846 /// # Safety 847 /// 848 /// The caller is responsible for ensuring that there are no references to the `old_interface` that is being 849 /// removed. 850 /// 851 /// # Errors 852 /// 853 /// * [`Status::NOT_FOUND`]: the old interface was not found on the handle. 854 /// * [`Status::ACCESS_DENIED`]: the old interface is still in use and cannot be uninstalled. 855 pub unsafe fn reinstall_protocol_interface( 856 handle: Handle, 857 protocol: &Guid, 858 old_interface: *const c_void, 859 new_interface: *const c_void, 860 ) -> Result<()> { 861 let bt = boot_services_raw_panicking(); 862 // SAFETY: The pointer is not null and we assume it to be initialized. 863 let bt = unsafe { bt.as_ref() }; 864 865 // SAFETY: The memory is valid. 866 unsafe { 867 (bt.reinstall_protocol_interface)(handle.as_ptr(), protocol, old_interface, new_interface) 868 } 869 .to_result() 870 } 871 872 /// Removes a protocol interface from a device handle. 873 /// 874 /// # Safety 875 /// 876 /// The caller is responsible for ensuring that there are no references to a protocol interface 877 /// that has been removed. Some protocols may not be able to be removed as there is no information 878 /// available regarding the references. This includes Console I/O, Block I/O, Disk I/o, and handles 879 /// to device protocols. 880 /// 881 /// The caller is responsible for ensuring that they pass a valid `Guid` for `protocol`. 882 /// 883 /// # Errors 884 /// 885 /// * [`Status::NOT_FOUND`]: the interface was not found on the handle. 886 /// * [`Status::ACCESS_DENIED`]: the interface is still in use and cannot be uninstalled. 887 pub unsafe fn uninstall_protocol_interface( 888 handle: Handle, 889 protocol: &Guid, 890 interface: *const c_void, 891 ) -> Result<()> { 892 let bt = boot_services_raw_panicking(); 893 // SAFETY: The pointer is not null and we assume it to be initialized. 894 let bt = unsafe { bt.as_ref() }; 895 896 // SAFETY: The memory is valid. 897 unsafe { (bt.uninstall_protocol_interface)(handle.as_ptr(), protocol, interface).to_result() } 898 } 899 900 /// Registers `event` to be signaled whenever a protocol interface is registered for 901 /// `protocol` by [`install_protocol_interface`] or [`reinstall_protocol_interface`]. 902 /// 903 /// If successful, a [`SearchType::ByRegisterNotify`] is returned. This can be 904 /// used with [`locate_handle`] or [`locate_handle_buffer`] to identify the 905 /// newly (re)installed handles that support `protocol`. 906 /// 907 /// Events can be unregistered from protocol interface notification by calling [`close_event`]. 908 /// 909 /// # Errors 910 /// 911 /// * [`Status::OUT_OF_RESOURCES`]: the event could not be allocated. 912 pub fn register_protocol_notify( 913 protocol: &'static Guid, 914 event: &Event, 915 ) -> Result> { 916 let bt = boot_services_raw_panicking(); 917 // SAFETY: The pointer is not null and we assume it to be initialized. 918 let bt = unsafe { bt.as_ref() }; 919 920 let mut key = ptr::null_mut(); 921 // SAFETY: The memory is valid. 922 unsafe { (bt.register_protocol_notify)(protocol, event.as_ptr(), &mut key) }.to_result_with_val( 923 || { 924 // OK to unwrap: key is non-null for Status::SUCCESS. 925 SearchType::ByRegisterNotify(ProtocolSearchKey(NonNull::new(key).unwrap())) 926 }, 927 ) 928 } 929 930 /// Get the list of protocol interface [`Guids`][Guid] that are installed 931 /// on a [`Handle`]. 932 /// 933 /// # Errors 934 /// 935 /// * [`Status::INVALID_PARAMETER`]: `handle` is invalid. 936 /// * [`Status::OUT_OF_RESOURCES`]: out of memory. 937 pub fn protocols_per_handle(handle: Handle) -> Result { 938 let bt = boot_services_raw_panicking(); 939 // SAFETY: The pointer is not null and we assume it to be initialized. 940 let bt = unsafe { bt.as_ref() }; 941 942 let mut protocols = ptr::null_mut(); 943 let mut count = 0; 944 945 // SAFETY: The memory is valid. 946 unsafe { (bt.protocols_per_handle)(handle.as_ptr(), &mut protocols, &mut count) } 947 .to_result()?; 948 // Constructed first so that `Drop` frees the pool buffer if the check 949 // below fails. 950 let guids = ProtocolsPerHandle { 951 count, 952 protocols: NonNull::new(protocols) 953 .expect("protocols_per_handle must not return a null pointer"), 954 }; 955 956 // `Deref` yields references to the GUIDs, so a null entry must be 957 // rejected first. 958 // SAFETY: The firmware initialized `count` entries in the buffer. 959 if unsafe { contains_null(protocols, count) } { 960 return Err(Status::INVALID_PARAMETER.into()); 961 } 962 Ok(guids) 963 } 964 965 /// Locates the handle of a device on the [`DevicePath`] that supports the 966 /// specified [`Protocol`]. 967 /// 968 /// The `device_path` is updated to point at the remaining part that matched the 969 /// protocol. For example, this function can be used with a device path that 970 /// contains a file path to strip off the file system portion of the device 971 /// path, leaving the file path and handle to the file system driver needed to 972 /// access the file. 973 /// 974 /// If the first node of `device_path` matches the protocol, the `device_path` 975 /// is advanced to the device path terminator node. If `device_path` is a 976 /// multi-instance device path, the function will operate on the first instance. 977 /// 978 /// # Errors 979 /// 980 /// * [`Status::NOT_FOUND`]: no matching handles. 981 /// * [`Status::INVALID_PARAMETER`]: the firmware reported success but 982 /// returned a null remaining device path. 983 pub fn locate_device_path( 984 device_path: &mut &DevicePath, 985 ) -> Result { 986 let bt = boot_services_raw_panicking(); 987 // SAFETY: The pointer is not null and we assume it to be initialized. 988 let bt = unsafe { bt.as_ref() }; 989 990 let mut handle = ptr::null_mut(); 991 let mut device_path_ptr: *const DevicePathProtocol = device_path.as_ffi_ptr().cast(); 992 // SAFETY: The memory is valid. 993 unsafe { (bt.locate_device_path)(&P::GUID, &mut device_path_ptr, &mut handle) }.to_result()?; 994 995 // `from_ffi_ptr` reads the node header, so a null pointer must be 996 // rejected before it is dereferenced. 997 if device_path_ptr.is_null() { 998 return Err(Status::INVALID_PARAMETER.into()); 999 } 1000 // SAFETY: The firmware returned a non-null pointer to a device path. 1001 *device_path = unsafe { DevicePath::from_ffi_ptr(device_path_ptr.cast()) }; 1002 // SAFETY: The handle was returned by the firmware. 1003 // OK to unwrap: handle is non-null for Status::SUCCESS. 1004 Ok(unsafe { Handle::from_ptr(handle) }.unwrap()) 1005 } 1006 1007 /// Returns whether any of the `count` pointers starting at `ptr` is null. 1008 /// 1009 /// Used to validate pointer arrays returned by the firmware before they are 1010 /// exposed as [`Handle`]s or references, which must not be null. 1011 /// 1012 /// # Safety 1013 /// 1014 /// `ptr` must be valid for reads of `count` initialized pointers. 1015 unsafe fn contains_null(ptr: *const *const T, count: usize) -> bool { 1016 // SAFETY: Guaranteed by the caller. 1017 let ptrs = unsafe { slice::from_raw_parts(ptr, count) }; 1018 ptrs.iter().any(|p| p.is_null()) 1019 } 1020 1021 /// Enumerates all [`Handle`]s installed on the system which match a certain 1022 /// query. 1023 /// 1024 /// If you use the `alloc` feature, it might be more convenient to use 1025 /// [`find_handles`] instead. Another alternative might be 1026 /// [`locate_handle_buffer`]. 1027 /// 1028 /// # Errors 1029 /// 1030 /// * [`Status::NOT_FOUND`]: no matching handles found. 1031 /// * [`Status::BUFFER_TOO_SMALL`]: the buffer is not large enough. The required 1032 /// size (in number of handles, not bytes) will be returned in the error data. 1033 /// * [`Status::INVALID_PARAMETER`]: the firmware returned a null handle. 1034 pub fn locate_handle<'buf>( 1035 search_ty: SearchType, 1036 buffer: &'buf mut [MaybeUninit], 1037 ) -> Result<&'buf [Handle], Option> { 1038 let bt = boot_services_raw_panicking(); 1039 // SAFETY: The pointer is not null and we assume it to be initialized. 1040 let bt = unsafe { bt.as_ref() }; 1041 1042 // Obtain the needed data from the parameters. 1043 let (ty, guid, key) = match search_ty { 1044 SearchType::AllHandles => (0, ptr::null(), ptr::null()), 1045 SearchType::ByRegisterNotify(registration) => { 1046 (1, ptr::null(), registration.0.as_ptr().cast_const()) 1047 } 1048 SearchType::ByProtocol(guid) => (2, ptr::from_ref(guid), ptr::null()), 1049 }; 1050 1051 let mut buffer_size = buffer.len() * size_of::(); 1052 let status = 1053 // SAFETY: The memory is valid. 1054 unsafe { (bt.locate_handle)(ty, guid, key, &mut buffer_size, buffer.as_mut_ptr().cast()) }; 1055 1056 let num_handles = buffer_size / size_of::(); 1057 1058 match status { 1059 Status::SUCCESS => { 1060 let buffer = &buffer[..num_handles]; 1061 // `Handle` wraps `NonNull`, so a null entry must be rejected 1062 // before the entries are exposed as handles. 1063 // SAFETY: The firmware initialized the entries up to `num_handles`. 1064 if unsafe { contains_null(buffer.as_ptr().cast::<*const c_void>(), num_handles) } { 1065 return Err(Error::new(Status::INVALID_PARAMETER, None)); 1066 } 1067 // SAFETY: The entries up to `num_handles` have been initialized 1068 // and are non-null. 1069 let handles = unsafe { maybe_uninit_slice_assume_init_ref(buffer) }; 1070 Ok(handles) 1071 } 1072 Status::BUFFER_TOO_SMALL => Err(Error::new(status, Some(num_handles))), 1073 _ => Err(Error::new(status, None)), 1074 } 1075 } 1076 1077 /// Returns an array of handles that support the requested protocol in a 1078 /// pool-allocated buffer. 1079 /// 1080 /// See [`SearchType`] for details of the available search operations. 1081 /// 1082 /// Unlike [`find_handles`], this doesn't need the `alloc` feature and operates 1083 /// on the UEFI heap directly. Further, it allows a more fine-grained search 1084 /// via the provided [`SearchType`]. 1085 /// 1086 /// # Errors 1087 /// 1088 /// * [`Status::NOT_FOUND`]: no matching handles. 1089 /// * [`Status::OUT_OF_RESOURCES`]: out of memory. 1090 /// * [`Status::INVALID_PARAMETER`]: the firmware returned a null handle. 1091 pub fn locate_handle_buffer(search_ty: SearchType) -> Result { 1092 let bt = boot_services_raw_panicking(); 1093 // SAFETY: The pointer is not null and we assume it to be initialized. 1094 let bt = unsafe { bt.as_ref() }; 1095 1096 let (ty, guid, key) = match search_ty { 1097 SearchType::AllHandles => (0, ptr::null(), ptr::null()), 1098 SearchType::ByRegisterNotify(registration) => { 1099 (1, ptr::null(), registration.0.as_ptr().cast_const()) 1100 } 1101 SearchType::ByProtocol(guid) => (2, ptr::from_ref(guid), ptr::null()), 1102 }; 1103 1104 let mut num_handles: usize = 0; 1105 let mut buffer: *mut uefi_raw::Handle = ptr::null_mut(); 1106 // SAFETY: The memory is valid. 1107 unsafe { (bt.locate_handle_buffer)(ty, guid, key, &mut num_handles, &mut buffer) } 1108 .to_result()?; 1109 // Constructed first so that `Drop` frees the pool buffer if the check 1110 // below fails. 1111 let handles = HandleBuffer { 1112 count: num_handles, 1113 buffer: NonNull::new(buffer.cast()) 1114 .expect("locate_handle_buffer must not return a null pointer"), 1115 }; 1116 1117 // `Handle` wraps `NonNull`, so a null entry must be rejected before 1118 // `Deref` exposes the entries as handles. 1119 // SAFETY: The firmware initialized `num_handles` entries in the buffer. 1120 if unsafe { contains_null(buffer.cast::<*const c_void>(), num_handles) } { 1121 return Err(Status::INVALID_PARAMETER.into()); 1122 } 1123 Ok(handles) 1124 } 1125 1126 /// Returns all the handles implementing a certain [`Protocol`]. 1127 /// 1128 /// # Errors 1129 /// 1130 /// * [`Status::NOT_FOUND`]: no matching handles. 1131 /// * [`Status::INVALID_PARAMETER`]: the firmware returned a null handle. 1132 #[cfg(feature = "alloc")] 1133 pub fn find_handles() -> Result> { 1134 // Search by protocol. 1135 let search_type = SearchType::from_proto::

(); 1136 1137 // Determine how much we need to allocate. 1138 let num_handles = match locate_handle(search_type, &mut []) { 1139 Err(err) => { 1140 if err.status() == Status::BUFFER_TOO_SMALL { 1141 err.data().expect("error data is missing") 1142 } else { 1143 return Err(err.to_err_without_payload()); 1144 } 1145 } 1146 // This should never happen: if no handles match the search then a 1147 // `NOT_FOUND` error should be returned. 1148 Ok(_) => panic!("locate_handle should not return success with empty buffer"), 1149 }; 1150 1151 // Allocate a large enough buffer without pointless initialization. 1152 let mut handles = Vec::with_capacity(num_handles); 1153 1154 // Perform the search. 1155 let num_handles = locate_handle(search_type, handles.spare_capacity_mut()) 1156 .discard_errdata()? 1157 .len(); 1158 1159 // Mark the returned number of elements as initialized. 1160 // SAFETY: The memory is valid. 1161 unsafe { 1162 handles.set_len(num_handles); 1163 } 1164 1165 // Emit output, with warnings 1166 Ok(handles) 1167 } 1168 1169 /// Find an arbitrary handle that supports a particular [`Protocol`]. Returns 1170 /// [`NOT_FOUND`] if no handles support the protocol. 1171 /// 1172 /// This method is a convenient wrapper around [`locate_handle_buffer`] for 1173 /// getting just one handle. This is useful when you don't care which handle the 1174 /// protocol is opened on. For example, [`DevicePathToText`] isn't tied to a 1175 /// particular device, so only a single handle is expected to exist. 1176 /// 1177 /// [`NOT_FOUND`]: Status::NOT_FOUND 1178 /// [`DevicePathToText`]: uefi::proto::device_path::text::DevicePathToText 1179 /// 1180 /// # Example 1181 /// 1182 /// ``` 1183 /// use uefi::proto::device_path::text::DevicePathToText; 1184 /// use uefi::{boot, Handle}; 1185 /// # use uefi::Result; 1186 /// 1187 /// # fn get_fake_val() -> T { todo!() } 1188 /// # fn test() -> Result { 1189 /// # let image_handle: Handle = get_fake_val(); 1190 /// let handle = boot::get_handle_for_protocol::()?; 1191 /// let device_path_to_text = boot::open_protocol_exclusive::(handle)?; 1192 /// # Ok(()) 1193 /// # } 1194 /// ``` 1195 /// 1196 /// # Errors 1197 /// 1198 /// * [`Status::NOT_FOUND`]: no matching handle. 1199 /// * [`Status::OUT_OF_RESOURCES`]: out of memory. 1200 pub fn get_handle_for_protocol() -> Result { 1201 locate_handle_buffer(SearchType::ByProtocol(&P::GUID))? 1202 .first() 1203 .cloned() 1204 .ok_or_else(|| Status::NOT_FOUND.into()) 1205 } 1206 1207 /// Opens a [`Protocol`] interface for a handle. 1208 /// 1209 /// See also [`open_protocol_exclusive`], which provides a safe subset of this 1210 /// functionality. 1211 /// 1212 /// This function attempts to get the protocol implementation of a handle, based 1213 /// on the [protocol GUID]. 1214 /// 1215 /// See [`OpenProtocolParams`] and [`OpenProtocolAttributes`] for details of the 1216 /// input parameters. 1217 /// 1218 /// If successful, a [`ScopedProtocol`] is returned that will automatically 1219 /// close the protocol interface when dropped. 1220 /// 1221 /// [protocol GUID]: uefi::data_types::Identify::GUID 1222 /// 1223 /// # Safety 1224 /// 1225 /// This function is unsafe because it can be used to open a protocol in ways 1226 /// that don't get tracked by the UEFI implementation. This could allow the 1227 /// protocol to be removed from a handle, or for the handle to be deleted 1228 /// entirely, while a reference to the protocol is still active. The caller is 1229 /// responsible for ensuring that the handle and protocol remain valid until the 1230 /// `ScopedProtocol` is dropped. 1231 /// 1232 /// # Errors 1233 /// 1234 /// * [`Status::INVALID_PARAMETER`]: an invalid combination of `params` and 1235 /// `attributes` was provided. 1236 /// * [`Status::UNSUPPORTED`]: the handle does not support the protocol. 1237 /// * [`Status::ACCESS_DENIED`] or [`Status::ALREADY_STARTED`]: the protocol is 1238 /// already open in a way that is incompatible with the new request. 1239 #[doc(alias = "handle_protocol")] 1240 pub unsafe fn open_protocol( 1241 params: OpenProtocolParams, 1242 attributes: OpenProtocolAttributes, 1243 ) -> Result> { 1244 let bt = boot_services_raw_panicking(); 1245 // SAFETY: The pointer is not null and we assume it to be initialized. 1246 let bt = unsafe { bt.as_ref() }; 1247 1248 let mut interface = ptr::null_mut(); 1249 // SAFETY: The memory is valid. 1250 unsafe { 1251 (bt.open_protocol)( 1252 params.handle.as_ptr(), 1253 &P::GUID, 1254 &mut interface, 1255 params.agent.as_ptr(), 1256 Handle::opt_to_ptr(params.controller), 1257 attributes as u32, 1258 ) 1259 } 1260 .to_result_with_val(|| { 1261 let interface = if interface.is_null() { 1262 None 1263 } else { 1264 // SAFETY: The memory is valid. 1265 NonNull::new(unsafe { P::mut_ptr_from_ffi(interface) }) 1266 }; 1267 ScopedProtocol { 1268 interface, 1269 open_params: params, 1270 } 1271 }) 1272 } 1273 1274 /// Opens a [`Protocol`] interface for a handle in exclusive mode. 1275 /// 1276 /// If successful, a [`ScopedProtocol`] is returned that will automatically 1277 /// close the protocol interface when dropped. 1278 /// 1279 /// Note that if any other drivers currently have the protocol interface opened 1280 /// with the [`OpenProtocolAttributes::ByDriver`] attribute, they will be 1281 /// disconnected via [`disconnect_controller`]. For example, opening the 1282 /// SERIAL_IO_PROTOCOL exclusively will disconnect the console driver from it. 1283 /// 1284 /// # Errors 1285 /// 1286 /// * [`Status::UNSUPPORTED`]: the handle does not support the protocol. 1287 /// * [`Status::ACCESS_DENIED`]: the protocol is already open in a way that is 1288 /// incompatible with the new request. 1289 #[doc(alias = "handle_protocol")] 1290 pub fn open_protocol_exclusive( 1291 handle: Handle, 1292 ) -> Result> { 1293 // Safety: opening in exclusive mode with the correct agent 1294 // handle set ensures that the protocol cannot be modified or 1295 // removed while it is open, so this usage is safe. 1296 // SAFETY: The memory is valid. 1297 unsafe { 1298 open_protocol::

( 1299 OpenProtocolParams { 1300 handle, 1301 agent: image_handle(), 1302 controller: None, 1303 }, 1304 OpenProtocolAttributes::Exclusive, 1305 ) 1306 } 1307 } 1308 1309 /// Tests whether a handle supports a [`Protocol`]. 1310 /// 1311 /// Returns `Ok(true)` if the handle supports the protocol, `Ok(false)` if not. 1312 /// 1313 /// # Errors 1314 /// 1315 /// * [`Status::INVALID_PARAMETER`]: one of the handles in `params` is invalid. 1316 pub fn test_protocol(params: OpenProtocolParams) -> Result { 1317 const TEST_PROTOCOL: u32 = 0x04; 1318 1319 let bt = boot_services_raw_panicking(); 1320 // SAFETY: The pointer is not null and we assume it to be initialized. 1321 let bt = unsafe { bt.as_ref() }; 1322 1323 let mut interface = ptr::null_mut(); 1324 // SAFETY: The memory is valid. 1325 let status = unsafe { 1326 (bt.open_protocol)( 1327 params.handle.as_ptr(), 1328 &P::GUID, 1329 &mut interface, 1330 params.agent.as_ptr(), 1331 Handle::opt_to_ptr(params.controller), 1332 TEST_PROTOCOL, 1333 ) 1334 }; 1335 1336 match status { 1337 Status::SUCCESS => Ok(true), 1338 Status::UNSUPPORTED => Ok(false), 1339 _ => Err(Error::from(status)), 1340 } 1341 } 1342 1343 /// Loads a UEFI image into memory and returns a [`Handle`] to the image. 1344 /// 1345 /// There are two ways to load the image: by copying raw image data 1346 /// from a source buffer, or by loading the image via the 1347 /// [`SimpleFileSystem`] protocol. See [`LoadImageSource`] for more 1348 /// details of the `source` parameter. 1349 /// 1350 /// The `parent_image_handle` is used to initialize the 1351 /// `parent_handle` field of the [`LoadedImage`] protocol for the 1352 /// image. 1353 /// 1354 /// If the image is successfully loaded, a [`Handle`] supporting the 1355 /// [`LoadedImage`] and [`LoadedImageDevicePath`] protocols is returned. The 1356 /// image can be started with [`start_image`] and unloaded with 1357 /// [`unload_image`]. 1358 /// 1359 /// # Errors 1360 /// 1361 /// * [`Status::INVALID_PARAMETER`]: `source` contains an invalid value. 1362 /// * [`Status::UNSUPPORTED`]: the image type is not supported. 1363 /// * [`Status::OUT_OF_RESOURCES`]: insufficient resources to load the image. 1364 /// * [`Status::LOAD_ERROR`]: the image is invalid. 1365 /// * [`Status::DEVICE_ERROR`]: failed to load image due to a read error. 1366 /// * [`Status::ACCESS_DENIED`]: failed to load image due to a security policy. 1367 /// * [`Status::SECURITY_VIOLATION`]: a security policy specifies that the image 1368 /// should not be started. 1369 pub fn load_image(parent_image_handle: Handle, source: LoadImageSource) -> Result { 1370 let bt = boot_services_raw_panicking(); 1371 // SAFETY: The pointer is not null and we assume it to be initialized. 1372 let bt = unsafe { bt.as_ref() }; 1373 1374 let (boot_policy, device_path, source_buffer, source_size) = source.to_ffi_params(); 1375 1376 let mut image_handle = ptr::null_mut(); 1377 // SAFETY: The memory is valid. 1378 unsafe { 1379 (bt.load_image)( 1380 boot_policy.into(), 1381 parent_image_handle.as_ptr(), 1382 device_path.cast(), 1383 source_buffer, 1384 source_size, 1385 &mut image_handle, 1386 ) 1387 .to_result_with_val( 1388 // OK to unwrap: image handle is non-null for Status::SUCCESS. 1389 || Handle::from_ptr(image_handle).unwrap(), 1390 ) 1391 } 1392 } 1393 1394 /// Unloads a UEFI image. 1395 /// 1396 /// # Errors 1397 /// 1398 /// * [`Status::UNSUPPORTED`]: the image has been started, and does not support unload. 1399 /// * [`Status::INVALID_PARAMETER`]: `image_handle` is not valid. 1400 pub fn unload_image(image_handle: Handle) -> Result { 1401 let bt = boot_services_raw_panicking(); 1402 // SAFETY: The pointer is not null and we assume it to be initialized. 1403 let bt = unsafe { bt.as_ref() }; 1404 1405 // SAFETY: The memory is valid. 1406 unsafe { (bt.unload_image)(image_handle.as_ptr()) }.to_result() 1407 } 1408 1409 /// Transfers control to a loaded image's entry point. 1410 /// 1411 /// # Errors 1412 /// 1413 /// * [`Status::INVALID_PARAMETER`]: `image_handle` is not valid, or the image 1414 /// has already been initialized with `start_image`. 1415 /// * [`Status::SECURITY_VIOLATION`]: a security policy specifies that the image 1416 /// should not be started. 1417 pub fn start_image(image_handle: Handle) -> Result { 1418 let bt = boot_services_raw_panicking(); 1419 // SAFETY: The pointer is not null and we assume it to be initialized. 1420 let bt = unsafe { bt.as_ref() }; 1421 1422 // TODO: implement returning exit data to the caller. 1423 let mut exit_data_size: usize = 0; 1424 let mut exit_data: *mut u16 = ptr::null_mut(); 1425 1426 // SAFETY: The memory is valid. 1427 let status = 1428 unsafe { (bt.start_image)(image_handle.as_ptr(), &mut exit_data_size, &mut exit_data) }; 1429 1430 // The image allocates the exit data from the pool and the caller of 1431 // `start_image` must free it. 1432 if let Some(exit_data) = NonNull::new(exit_data) { 1433 // SAFETY: The buffer was allocated by the matching UEFI allocator. 1434 let _ = unsafe { free_pool(exit_data.cast()) }; 1435 } 1436 1437 status.to_result() 1438 } 1439 1440 /// Exits the UEFI application and returns control to the UEFI component 1441 /// that started the UEFI application. 1442 /// 1443 /// # Safety 1444 /// 1445 /// The caller must ensure that resources owned by the application are properly 1446 /// cleaned up. 1447 /// 1448 /// Note that event callbacks installed by the application are not automatically 1449 /// uninstalled. If such a callback is invoked after exiting the application, 1450 /// the function's code may no longer be loaded in memory, leading to a crash or 1451 /// other unexpected behavior. 1452 /// 1453 /// `exit_data`, if present, must be a buffer allocated with 1454 /// [`allocate_pool`]. Ownership of that buffer passes to whoever started this 1455 /// image: the caller of `StartImage()` receives it and must free it. 1456 pub unsafe fn exit( 1457 image_handle: Handle, 1458 exit_status: Status, 1459 exit_data_size: usize, 1460 exit_data: *mut Char16, 1461 ) -> Result { 1462 let bt = boot_services_raw_panicking(); 1463 // SAFETY: The pointer is not null and we assume it to be initialized. 1464 let bt = unsafe { bt.as_ref() }; 1465 1466 // SAFETY: The memory is valid. 1467 let result = unsafe { 1468 (bt.exit)( 1469 image_handle.as_ptr(), 1470 exit_status, 1471 exit_data_size, 1472 exit_data.cast(), 1473 ) 1474 }; 1475 1476 result.to_result() 1477 } 1478 1479 /// Get the current memory map and exit boot services. 1480 unsafe fn get_memory_map_and_exit_boot_services(buf: &mut [u8]) -> Result { 1481 let bt = boot_services_raw_panicking(); 1482 // SAFETY: The pointer is not null and we assume it to be initialized. 1483 let bt = unsafe { bt.as_ref() }; 1484 1485 // Get the memory map. 1486 let memory_map = get_memory_map(buf)?; 1487 1488 // Try to exit boot services using the memory map key. Note that after 1489 // the first call to `exit_boot_services`, there are restrictions on 1490 // what boot services functions can be called. In UEFI 2.8 and earlier, 1491 // only `get_memory_map` and `exit_boot_services` are allowed. Starting 1492 // in UEFI 2.9 other memory allocation functions may also be called. 1493 // SAFETY: The memory is valid. 1494 unsafe { (bt.exit_boot_services)(image_handle().as_ptr(), memory_map.map_key.0) } 1495 .to_result_with_val(|| memory_map) 1496 } 1497 1498 /// Convenient wrapper to exit UEFI boot services along with corresponding 1499 /// essential steps to get the memory map. 1500 /// 1501 /// Exiting UEFI boot services requires a **non-trivial sequence of steps**, 1502 /// including safe retrieval and finalization of the memory map. This wrapper 1503 /// ensures a safe and spec-compliant transition from UEFI boot services to 1504 /// runtime services by retrieving the system memory map and invoking 1505 /// `ExitBootServices()` with the correct memory map key, retrying if necessary. 1506 /// 1507 /// After this function completes, UEFI hands over control of the hardware 1508 /// to the executing OS loader, which implies that the UEFI boot services 1509 /// are shut down and cannot be used anymore. Only UEFI configuration tables 1510 /// and runtime services can be used. 1511 /// 1512 /// Since the boot services function to free memory is no longer available after 1513 /// this function returns, the allocation will not be freed on drop. It will 1514 /// however be reflected by the memory map itself (self-contained). 1515 /// 1516 /// Note that once the boot services are exited, associated loggers and 1517 /// allocators can't use the boot services anymore. For the corresponding 1518 /// abstractions provided by this crate (see the [`helpers`] module), 1519 /// invoking this function will automatically disable them. If the 1520 /// `global_allocator` feature is enabled, attempting to use the allocator 1521 /// after exiting boot services will panic. 1522 /// 1523 /// # Arguments 1524 /// - `custom_memory_type`: The [`MemoryType`] for the UEFI allocation that will 1525 /// store the final memory map. If you pass `None`, this defaults to the 1526 /// recommended default value of [`MemoryType::LOADER_DATA`]. If you want a 1527 /// specific memory region for the memory map, you can pass the desired 1528 /// [`MemoryType`]. 1529 /// 1530 /// # Safety 1531 /// 1532 /// The caller is responsible for ensuring that no references to 1533 /// boot-services data remain. A non-exhaustive list of resources to check: 1534 /// 1535 /// * All protocols will be invalid after exiting boot services. This 1536 /// includes the [`Output`] protocols attached to stdout/stderr. The 1537 /// caller must ensure that no protocol references remain. 1538 /// * The pool allocator is not usable after exiting boot services. Types 1539 /// such as [`PoolString`] which call [`free_pool`] on drop must be 1540 /// dropped before. A later drop skips the call and panics in debug 1541 /// builds. 1542 /// * All data in the memory map marked as 1543 /// [`MemoryType::BOOT_SERVICES_CODE`] and 1544 /// [`MemoryType::BOOT_SERVICES_DATA`] will become free memory. 1545 /// 1546 /// # Errors 1547 /// 1548 /// This function will fail if it is unable to allocate memory for 1549 /// the memory map, if it fails to retrieve the memory map, or if 1550 /// exiting boot services fails (with up to one retry). 1551 /// 1552 /// All errors are treated as unrecoverable because the system is 1553 /// now in an undefined state. Rather than returning control to the 1554 /// caller, the system will be reset. 1555 /// 1556 /// [`helpers`]: crate::helpers 1557 /// [`Output`]: crate::proto::console::text::Output 1558 /// [`PoolString`]: crate::data_types::PoolString 1559 #[must_use] 1560 pub unsafe fn exit_boot_services(custom_memory_type: Option) -> MemoryMapOwned { 1561 // LOADER_DATA is the default and also used by the Linux kernel: 1562 // https://elixir.bootlin.com/linux/v6.13.7/source/drivers/firmware/efi/libstub/mem.c#L24 1563 let memory_type = custom_memory_type.unwrap_or(MemoryType::LOADER_DATA); 1564 helpers::exit(); 1565 1566 let mut buf = MemoryMapBackingMemory::new(memory_type).expect("Failed to allocate memory"); 1567 1568 // Calling `exit_boot_services` can fail if the memory map key is not 1569 // current. Retry a second time if that occurs. This matches the 1570 // behavior of the Linux kernel: 1571 // https://github.com/torvalds/linux/blob/`e544a0743`/drivers/firmware/efi/libstub/efi-stub-helper.c#L375 1572 let mut status = Status::ABORTED; 1573 for _ in 0..2 { 1574 // SAFETY: The memory is valid. 1575 match unsafe { get_memory_map_and_exit_boot_services(buf.as_mut_slice()) } { 1576 Ok(memory_map) => { 1577 return MemoryMapOwned::from_initialized_mem(buf, memory_map); 1578 } 1579 Err(err) => { 1580 log::error!("Error retrieving the memory map for exiting the boot services"); 1581 status = err.status() 1582 } 1583 } 1584 } 1585 1586 // Failed to exit boot services. 1587 log::warn!("Resetting the machine"); 1588 runtime::reset(ResetType::COLD, status, None); 1589 } 1590 1591 /// Adds, updates, or removes a configuration table entry 1592 /// from the EFI System Table. 1593 /// 1594 /// # Safety 1595 /// 1596 /// When installing or updating a configuration table, the data pointed to by 1597 /// `table_ptr` must be a pool allocation of type 1598 /// [`RUNTIME_SERVICES_DATA`]. Once this table has been installed, the caller 1599 /// should not modify or free the data. 1600 /// 1601 /// [`RUNTIME_SERVICES_DATA`]: MemoryType::RUNTIME_SERVICES_DATA 1602 /// 1603 /// # Errors 1604 /// 1605 /// * [`Status::NOT_FOUND`]: tried to delete a nonexistent entry. 1606 /// * [`Status::OUT_OF_RESOURCES`]: out of memory. 1607 pub unsafe fn install_configuration_table( 1608 guid_entry: &'static Guid, 1609 table_ptr: *const c_void, 1610 ) -> Result { 1611 let bt = boot_services_raw_panicking(); 1612 // SAFETY: The pointer is not null and we assume it to be initialized. 1613 let bt = unsafe { bt.as_ref() }; 1614 1615 // SAFETY: The memory is valid. 1616 unsafe { (bt.install_configuration_table)(guid_entry, table_ptr) }.to_result() 1617 } 1618 1619 /// Sets the watchdog timer. 1620 /// 1621 /// UEFI will start a 5-minute countdown after a UEFI image is loaded. The 1622 /// image must either successfully load an OS and exit boot services in that 1623 /// time, or disable the watchdog. 1624 /// 1625 /// Otherwise, the firmware will log the event using the provided numeric 1626 /// code and data, then reset the system. 1627 /// 1628 /// This function allows you to change the watchdog timer's timeout to a 1629 /// certain amount of seconds or to disable the watchdog entirely. It also 1630 /// allows you to change what will be logged when the timer expires. 1631 /// 1632 /// The watchdog codes from 0 to 0xffff (65535) are reserved for internal 1633 /// firmware use. Higher values can be used freely by applications. 1634 /// 1635 /// If provided, the watchdog data must be a null-terminated string optionally 1636 /// followed by other binary data. 1637 /// 1638 /// # Errors 1639 /// 1640 /// * [`Status::INVALID_PARAMETER`]: `watchdog_code` is invalid. 1641 /// * [`Status::UNSUPPORTED`]: the system does not have a watchdog timer. 1642 /// * [`Status::DEVICE_ERROR`]: the watchdog timer could not be set due to a 1643 /// hardware error. 1644 pub fn set_watchdog_timer( 1645 timeout_in_seconds: usize, 1646 watchdog_code: u64, 1647 data: Option<&mut [u16]>, 1648 ) -> Result { 1649 let bt = boot_services_raw_panicking(); 1650 // SAFETY: The pointer is not null and we assume it to be initialized. 1651 let bt = unsafe { bt.as_ref() }; 1652 1653 let (data_size, data) = data 1654 .map(|d| { 1655 assert!( 1656 d.contains(&0), 1657 "Watchdog data must start with a null-terminated string" 1658 ); 1659 // The spec defines the data size in bytes, not in u16 units. 1660 (size_of_val(d), d.as_mut_ptr()) 1661 }) 1662 .unwrap_or((0, ptr::null_mut())); 1663 1664 // SAFETY: The memory is valid. 1665 unsafe { (bt.set_watchdog_timer)(timeout_in_seconds, watchdog_code, data_size, data) } 1666 .to_result() 1667 } 1668 1669 /// Stalls execution for the given duration. 1670 pub fn stall(duration: Duration) { 1671 let bt = boot_services_raw_panicking(); 1672 // SAFETY: The pointer is not null and we assume it to be initialized. 1673 let bt = unsafe { bt.as_ref() }; 1674 1675 let microseconds = duration.as_micros() as usize; 1676 1677 // SAFETY: The memory is valid. 1678 unsafe { 1679 // No error conditions are defined in the spec for this function, so 1680 // ignore the status. 1681 let _ = (bt.stall)(microseconds); 1682 } 1683 } 1684 1685 /// Retrieves a [`SimpleFileSystem`] protocol associated with the device the given 1686 /// image was loaded from. 1687 /// 1688 /// # Errors 1689 /// 1690 /// This function can return errors from [`open_protocol_exclusive`] and 1691 /// [`locate_device_path`]. See those functions for more details. 1692 /// 1693 /// * [`Status::INVALID_PARAMETER`] 1694 /// * [`Status::UNSUPPORTED`] 1695 /// * [`Status::ACCESS_DENIED`] 1696 /// * [`Status::ALREADY_STARTED`] 1697 /// * [`Status::NOT_FOUND`] 1698 pub fn get_image_file_system(image_handle: Handle) -> Result> { 1699 let loaded_image = open_protocol_exclusive::(image_handle)?; 1700 1701 let device_handle = loaded_image 1702 .device() 1703 .ok_or(Error::new(Status::UNSUPPORTED, ()))?; 1704 let device_path = open_protocol_exclusive::(device_handle)?; 1705 1706 let device_handle = locate_device_path::(&mut &*device_path)?; 1707 1708 open_protocol_exclusive(device_handle) 1709 } 1710 1711 /// Calculates the 32-bit CRC32 for the provided slice. 1712 /// 1713 /// # Errors 1714 /// * [`Status::INVALID_PARAMETER`] 1715 pub fn calculate_crc32(data: &[u8]) -> Result { 1716 let bt = boot_services_raw_panicking(); 1717 // SAFETY: The pointer is not null and we assume it to be initialized. 1718 let bt = unsafe { bt.as_ref() }; 1719 let mut crc = 0u32; 1720 1721 // SAFETY: The memory is valid. 1722 unsafe { (bt.calculate_crc32)(data.as_ptr().cast(), data.len(), &mut crc) } 1723 .to_result_with_val(|| crc) 1724 } 1725 1726 /// Protocol interface [`Guids`][Guid] that are installed on a [`Handle`] as 1727 /// returned by [`protocols_per_handle`]. 1728 #[derive(Debug)] 1729 pub struct ProtocolsPerHandle { 1730 protocols: NonNull<*const Guid>, 1731 count: usize, 1732 } 1733 1734 impl Drop for ProtocolsPerHandle { 1735 fn drop(&mut self) { 1736 let active = are_boot_services_active(); 1737 debug_assert!( 1738 active, 1739 "ProtocolsPerHandle dropped after exiting boot services" 1740 ); 1741 if active { 1742 // SAFETY: This pointer was allocated by the matching UEFI allocator. 1743 let _ = unsafe { free_pool(self.protocols.cast::()) }; 1744 } 1745 } 1746 } 1747 1748 impl Deref for ProtocolsPerHandle { 1749 type Target = [&'static Guid]; 1750 1751 fn deref(&self) -> &Self::Target { 1752 let ptr: *const &'static Guid = self.protocols.as_ptr().cast(); 1753 1754 // SAFETY: 1755 // 1756 // * The firmware is assumed to provide a correctly-aligned pointer and 1757 // array length. 1758 // * The GUID pointers were checked to be non-null in 1759 // `protocols_per_handle`. The firmware is assumed to provide valid 1760 // GUIDs behind them. 1761 // * Protocol GUIDs should be constants or statics, so a 'static 1762 // lifetime (of the individual pointers, not the overall slice) can be 1763 // assumed. 1764 // SAFETY: The pointer is valid for the requested slice length. 1765 unsafe { slice::from_raw_parts(ptr, self.count) } 1766 } 1767 } 1768 1769 /// A buffer on the UEFI heap returned by [`locate_handle_buffer`] that contains 1770 /// an array of [`Handle`]s that support the requested [`Protocol`]. 1771 #[derive(Debug, Eq, PartialEq)] 1772 pub struct HandleBuffer { 1773 count: usize, 1774 buffer: NonNull, 1775 } 1776 1777 impl Drop for HandleBuffer { 1778 fn drop(&mut self) { 1779 let active = are_boot_services_active(); 1780 debug_assert!(active, "HandleBuffer dropped after exiting boot services"); 1781 if active { 1782 // SAFETY: This pointer was allocated by the matching UEFI allocator. 1783 let _ = unsafe { free_pool(self.buffer.cast::()) }; 1784 } 1785 } 1786 } 1787 1788 impl Deref for HandleBuffer { 1789 type Target = [Handle]; 1790 1791 fn deref(&self) -> &Self::Target { 1792 // SAFETY: The pointer is valid for the requested slice length and the 1793 // entries were checked to be non-null in `locate_handle_buffer`. 1794 unsafe { slice::from_raw_parts(self.buffer.as_ptr(), self.count) } 1795 } 1796 } 1797 1798 /// An open [`Protocol`] interface. Automatically closes the protocol 1799 /// interface on drop. 1800 /// 1801 /// Most protocols have interface data associated with them. `ScopedProtocol` 1802 /// implements [`Deref`] and [`DerefMut`] to access this data. A few protocols 1803 /// (such as [`DevicePath`] and [`LoadedImageDevicePath`]) may be installed with 1804 /// null interface data, in which case [`Deref`] and [`DerefMut`] will 1805 /// panic. The [`get`] and [`get_mut`] methods may be used to access the 1806 /// optional interface data without panicking. 1807 /// 1808 /// [`DevicePath`]: crate::proto::device_path::DevicePath 1809 /// [`LoadedImageDevicePath`]: crate::proto::device_path::LoadedImageDevicePath 1810 /// [`get`]: ScopedProtocol::get 1811 /// [`get_mut`]: ScopedProtocol::get_mut 1812 #[derive(Debug)] 1813 pub struct ScopedProtocol { 1814 /// The protocol interface. 1815 interface: Option>, 1816 open_params: OpenProtocolParams, 1817 } 1818 1819 impl ScopedProtocol

{ 1820 /// Returns the [`OpenProtocolParams`] used to open the [`ScopedProtocol`]. 1821 #[must_use] 1822 pub const fn open_params(&self) -> OpenProtocolParams { 1823 self.open_params 1824 } 1825 } 1826 1827 // Forward Display impl to inner protocol: 1828 impl Display for ScopedProtocol

{ 1829 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { 1830 match self.get() { 1831 Some(proto) => { 1832 write!(f, "{proto}") 1833 } 1834 None => { 1835 write!(f, "") 1836 } 1837 } 1838 } 1839 } 1840 1841 impl Drop for ScopedProtocol

{ 1842 fn drop(&mut self) { 1843 // The protocol is gone together with the boot services. The value 1844 // should have been dropped before, so flag it in debug builds. 1845 let active = are_boot_services_active(); 1846 debug_assert!(active, "ScopedProtocol dropped after exiting boot services"); 1847 if !active { 1848 return; 1849 } 1850 let bt = boot_services_raw_panicking(); 1851 // SAFETY: The pointer is not null and we assume it to be initialized. 1852 let bt = unsafe { bt.as_ref() }; 1853 1854 // SAFETY: The memory is valid. 1855 let status = unsafe { 1856 (bt.close_protocol)( 1857 self.open_params.handle.as_ptr(), 1858 &P::GUID, 1859 self.open_params.agent.as_ptr(), 1860 Handle::opt_to_ptr(self.open_params.controller), 1861 ) 1862 }; 1863 // All of the error cases for close_protocol boil down to 1864 // calling it with a different set of parameters than what was 1865 // passed to open_protocol. The public API prevents such errors, 1866 // and the error can't be propagated out of drop anyway. A panic 1867 // in drop aborts the program during unwinding, so only check in 1868 // debug builds. 1869 debug_assert_eq!(status, Status::SUCCESS); 1870 } 1871 } 1872 1873 impl Deref for ScopedProtocol

{ 1874 type Target = P; 1875 1876 #[track_caller] 1877 fn deref(&self) -> &Self::Target { 1878 // SAFETY: `interface` is non-null and valid for the lifetime of this 1879 // ScopedProtocol. 1880 unsafe { self.interface.unwrap().as_ref() } 1881 } 1882 } 1883 1884 impl DerefMut for ScopedProtocol

{ 1885 #[track_caller] 1886 fn deref_mut(&mut self) -> &mut Self::Target { 1887 // SAFETY: `interface` is non-null and valid for the lifetime of this 1888 // ScopedProtocol. 1889 unsafe { self.interface.unwrap().as_mut() } 1890 } 1891 } 1892 1893 impl ScopedProtocol

{ 1894 /// Get the protocol interface data, or `None` if the open protocol's 1895 /// interface is null. 1896 #[must_use] 1897 pub fn get(&self) -> Option<&P> { 1898 // SAFETY: `interface` is non-null and valid for the lifetime of this 1899 // ScopedProtocol. 1900 self.interface.map(|p| unsafe { p.as_ref() }) 1901 } 1902 1903 /// Get the protocol interface data, or `None` if the open protocol's 1904 /// interface is null. 1905 #[must_use] 1906 pub fn get_mut(&mut self) -> Option<&mut P> { 1907 // SAFETY: `interface` is non-null and valid for the lifetime of this 1908 // ScopedProtocol. 1909 self.interface.map(|mut p| unsafe { p.as_mut() }) 1910 } 1911 } 1912 1913 /// RAII guard for task priority level changes. 1914 /// 1915 /// Will automatically restore the former task priority level when dropped. 1916 #[derive(Debug)] 1917 pub struct TplGuard { 1918 old_tpl: Tpl, 1919 } 1920 1921 impl TplGuard { 1922 /// Returns the previous [`Tpl`]. 1923 #[must_use] 1924 pub const fn old_tpl(&self) -> Tpl { 1925 self.old_tpl 1926 } 1927 } 1928 1929 impl Drop for TplGuard { 1930 fn drop(&mut self) { 1931 let active = are_boot_services_active(); 1932 debug_assert!(active, "TplGuard dropped after exiting boot services"); 1933 if !active { 1934 return; 1935 } 1936 let bt = boot_services_raw_panicking(); 1937 // SAFETY: The pointer is not null and we assume it to be initialized. 1938 let bt = unsafe { bt.as_ref() }; 1939 1940 // SAFETY: The memory is valid. 1941 unsafe { 1942 (bt.restore_tpl)(self.old_tpl); 1943 } 1944 } 1945 } 1946 1947 // OpenProtocolAttributes is safe to model as a regular enum because it 1948 // is only used as an input. The attributes are bitflags, but all valid 1949 // combinations are listed in the spec and only ByDriver and Exclusive 1950 // can actually be combined. 1951 // 1952 // Some values intentionally excluded: 1953 // 1954 // ByHandleProtocol (0x01) excluded because it is only intended to be 1955 // used in an implementation of `HandleProtocol`. 1956 // 1957 // TestProtocol (0x04) excluded because it doesn't actually open the 1958 // protocol, just tests if it's present on the handle. Since that 1959 // changes the interface significantly, that's exposed as a separate 1960 // method: `test_protocol`. 1961 1962 /// Attributes for [`open_protocol`]. 1963 #[repr(u32)] 1964 #[derive(Debug)] 1965 pub enum OpenProtocolAttributes { 1966 /// Used by applications and drivers to open a protocol interface for a 1967 /// handle. 1968 /// 1969 /// # Safety 1970 /// 1971 /// The interface is opened non-exclusively. The caller must ensure that 1972 /// either the interface is immutable, or that no conflicting concurrent 1973 /// access occurs. 1974 /// 1975 /// The caller must ensure that the interface is not uninstalled or 1976 /// reinstalled while still in use. 1977 GetProtocol = 0x02, 1978 1979 /// Used by bus drivers to show that a protocol is being used by one 1980 /// of the child controllers of the bus. 1981 ByChildController = 0x08, 1982 1983 /// Used by a driver to gain access to a protocol interface. When 1984 /// this mode is used, the driver's `Stop` function will be called 1985 /// if the protocol interface is reinstalled or uninstalled. Once a 1986 /// protocol interface is opened with this attribute, no other 1987 /// drivers will be allowed to open the same protocol interface with 1988 /// the `ByDriver` attribute. 1989 ByDriver = 0x10, 1990 1991 /// Used by applications to gain exclusive access to a protocol 1992 /// interface. If any drivers have the protocol opened with an 1993 /// attribute of `ByDriver`, then an attempt will be made to remove 1994 /// them by calling the driver's `Stop` function. 1995 /// 1996 /// # Warnings 1997 /// 1998 /// Opening an interface in exclusive mode can have surprising side 1999 /// effects. For example: 2000 /// 2001 /// * Opening a serial protocol in exclusive mode may disconnect it from 2002 /// other output protocols, and that connection will not be automatically 2003 /// restored when the exclusive access is ended. ([`connect_controller`] 2004 /// can sometimes be used to manually restore such connections.) 2005 /// 2006 /// * Stopping drivers that have the protocol open may be very slow. On some 2007 /// firmware, opening any of the disk protocols in exclusive mode can take 2008 /// nearly one second to complete. 2009 /// 2010 /// In many cases it is better to use [`GetProtocol`], even though it 2011 /// requires the use of `unsafe`. 2012 /// 2013 /// [`GetProtocol`]: Self::GetProtocol 2014 Exclusive = 0x20, 2015 2016 /// Used by a driver to gain exclusive access to a protocol 2017 /// interface. If any other drivers have the protocol interface 2018 /// opened with an attribute of `ByDriver`, then an attempt will be 2019 /// made to remove them with `DisconnectController`. 2020 /// 2021 /// # Warnings 2022 /// 2023 /// See warning section of [`Exclusive`]. 2024 /// 2025 /// [`Exclusive`]: Self::Exclusive 2026 ByDriverExclusive = 0x30, 2027 } 2028 2029 /// Parameters passed to [`open_protocol`]. 2030 #[derive(Clone, Copy, Debug)] 2031 pub struct OpenProtocolParams { 2032 /// The handle for the protocol to open. 2033 pub handle: Handle, 2034 2035 /// The handle of the calling agent. For drivers, this is the handle 2036 /// containing the `EFI_DRIVER_BINDING_PROTOCOL` instance. For 2037 /// applications, this is the image handle. 2038 pub agent: Handle, 2039 2040 /// For drivers, this is the controller handle that requires the 2041 /// protocol interface. For applications this should be set to 2042 /// `None`. 2043 pub controller: Option, 2044 } 2045 2046 /// Used as a parameter of [`load_image`] to provide the image source. 2047 #[derive(Debug)] 2048 pub enum LoadImageSource<'a> { 2049 /// Load an image from a buffer. The data will be copied from the 2050 /// buffer, so the input reference doesn't need to remain valid 2051 /// after the image is loaded. 2052 FromBuffer { 2053 /// Raw image data. 2054 buffer: &'a [u8], 2055 2056 /// If set, this path will be added as the file path of the 2057 /// loaded image. This is not required to load the image, but 2058 /// may be used by the image itself to load other resources 2059 /// relative to the image's path. 2060 file_path: Option<&'a DevicePath>, 2061 }, 2062 2063 /// Load an image via the [`SimpleFileSystem`] protocol. If there is 2064 /// no instance of that protocol associated with the path then the 2065 /// behavior depends on [`BootPolicy`]. If [`BootPolicy::BootSelection`], 2066 /// attempt to load via the [`LoadFile`] protocol. If 2067 /// [`BootPolicy::ExactMatch`], attempt to load via the [`LoadFile2`] 2068 /// protocol, then fall back to [`LoadFile`]. 2069 /// 2070 /// [`LoadFile`]: crate::proto::media::load_file::LoadFile 2071 /// [`LoadFile2`]: crate::proto::media::load_file::LoadFile2 2072 FromDevicePath { 2073 /// The full device path from which to load the image. 2074 /// 2075 /// The provided path should be a full device path and not just the 2076 /// file path portion of it. So for example, it must be (the binary 2077 /// representation) 2078 /// `PciRoot(0x0)/Pci(0x1F,0x2)/Sata(0x0,0xFFFF,0x0)/HD(1,MBR,0xBE1AFDFA,0x3F,0xFBFC1)/\\EFI\\BOOT\\BOOTX64.EFI` 2079 /// and not just `\\EFI\\BOOT\\BOOTX64.EFI`. 2080 device_path: &'a DevicePath, 2081 2082 /// The [`BootPolicy`] to use. 2083 boot_policy: BootPolicy, 2084 }, 2085 } 2086 2087 impl LoadImageSource<'_> { 2088 /// Returns the raw FFI parameters for `load_image`. 2089 #[must_use] 2090 pub(crate) fn to_ffi_params( 2091 &self, 2092 ) -> ( 2093 BootPolicy, 2094 *const FfiDevicePath, 2095 *const u8, /* buffer */ 2096 usize, /* buffer length */ 2097 ) { 2098 let (boot_policy, device_path, source_buffer, source_size) = match self { 2099 LoadImageSource::FromBuffer { buffer, file_path } => { 2100 // Boot policy is ignored when loading from source buffer. 2101 ( 2102 BootPolicy::default(), 2103 file_path.map(|p| p.as_ffi_ptr()).unwrap_or(ptr::null()), 2104 buffer.as_ptr(), 2105 buffer.len(), 2106 ) 2107 } 2108 LoadImageSource::FromDevicePath { 2109 device_path: d_path, 2110 boot_policy: b_policy, 2111 } => (*b_policy, d_path.as_ffi_ptr(), ptr::null(), 0), 2112 }; 2113 (boot_policy, device_path, source_buffer, source_size) 2114 } 2115 } 2116 2117 /// Type of allocation to perform. 2118 #[derive(Debug, Copy, Clone)] 2119 pub enum AllocateType { 2120 /// Allocate any possible pages. 2121 AnyPages, 2122 /// Allocate pages at any address below the given address. 2123 MaxAddress(PhysicalAddress), 2124 /// Allocate pages at the specified address. 2125 Address(PhysicalAddress), 2126 } 2127 2128 /// The type of handle search to perform. 2129 #[derive(Debug, Copy, Clone)] 2130 pub enum SearchType<'guid> { 2131 /// Return all handles present on the system. 2132 AllHandles, 2133 /// Returns all handles supporting a certain protocol, specified by its GUID. 2134 /// 2135 /// If the protocol implements the `Protocol` interface, 2136 /// you can use the `from_proto` function to construct a new `SearchType`. 2137 ByProtocol(&'guid Guid), 2138 /// Return all handles that implement a protocol when an interface for that protocol 2139 /// is (re)installed. 2140 ByRegisterNotify(ProtocolSearchKey), 2141 } 2142 2143 impl SearchType<'_> { 2144 /// Constructs a new search type for a specified protocol. 2145 #[must_use] 2146 pub const fn from_proto() -> Self { 2147 SearchType::ByProtocol(&P::GUID) 2148 } 2149 } 2150 2151 /// Event notification callback type. 2152 pub type EventNotifyFn = unsafe extern "efiapi" fn(event: Event, context: Option>); 2153 2154 /// Trigger type for events of type [`TIMER`]. 2155 /// 2156 /// See [`set_timer`]. 2157 /// 2158 /// [`TIMER`]: EventType::TIMER 2159 #[derive(Copy, Clone, Debug)] 2160 pub enum TimerTrigger { 2161 /// Remove the event's timer setting. 2162 Cancel, 2163 2164 /// Trigger the event periodically. 2165 Periodic( 2166 /// Duration to wait before the next event is fired. 2167 /// 2168 /// If set to zero, the event will be signaled on every timer tick. 2169 Duration, 2170 ), 2171 2172 /// Trigger the event one time. 2173 Relative( 2174 /// Duration to wait before the next event is fired. 2175 /// 2176 /// If set to zero, the event will be signaled on every timer tick. 2177 Duration, 2178 ), 2179 } 2180 2181 impl TimerTrigger { 2182 /// Transforms the underlying value to 100ns steps, a format widely used 2183 /// in EFI APIs. 2184 #[must_use] 2185 pub fn to_100ns_steps(self) -> u64 { 2186 const NANOS_PER_STEP: u128 = 100; 2187 match self { 2188 Self::Cancel => 0, 2189 Self::Periodic(dur) => { 2190 let ns100_steps = dur.as_nanos().div_ceil(NANOS_PER_STEP); 2191 u64::try_from(ns100_steps).expect("should be representable as u64") 2192 } 2193 Self::Relative(dur) => { 2194 let ns100_steps = dur.as_nanos().div_ceil(NANOS_PER_STEP); 2195 u64::try_from(ns100_steps).expect("should be representable as u64") 2196 } 2197 } 2198 } 2199 } 2200 2201 /// Opaque pointer returned by [`register_protocol_notify`] to be used 2202 /// with [`locate_handle`] via [`SearchType::ByRegisterNotify`]. 2203 #[derive(Debug, Clone, Copy)] 2204 #[repr(transparent)] 2205 pub struct ProtocolSearchKey(pub(crate) NonNull); 2206 2207 #[cfg(test)] 2208 mod tests { 2209 use core::time::Duration; 2210 use uefi::boot::TimerTrigger; 2211 2212 #[test] 2213 fn test_timer_trigger_100ns_steps() { 2214 let trigger = TimerTrigger::Periodic(Duration::from_nanos(0)); 2215 assert_eq!(trigger.to_100ns_steps(), 0); 2216 let trigger = TimerTrigger::Relative(Duration::from_nanos(0)); 2217 assert_eq!(trigger.to_100ns_steps(), 0); 2218 2219 let trigger = TimerTrigger::Periodic(Duration::from_nanos(12_300)); 2220 assert_eq!(trigger.to_100ns_steps(), 123); 2221 let trigger = TimerTrigger::Relative(Duration::from_nanos(12_300)); 2222 assert_eq!(trigger.to_100ns_steps(), 123); 2223 2224 let trigger = TimerTrigger::Periodic(Duration::from_secs(42)); 2225 assert_eq!(trigger.to_100ns_steps(), `420000000`); 2226 let trigger = TimerTrigger::Relative(Duration::from_secs(42)); 2227 assert_eq!(trigger.to_100ns_steps(), `420000000`); 2228 } 2229 }