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