-
Notifications
You must be signed in to change notification settings - Fork 163
/
Copy pathboot.rs
1983 lines (1829 loc) · 74 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
//! UEFI services available during boot.
use super::{Header, Revision};
use crate::data_types::{Align, PhysicalAddress, VirtualAddress};
use crate::proto::device_path::{DevicePath, FfiDevicePath};
#[cfg(feature = "alloc")]
use crate::proto::{loaded_image::LoadedImage, media::fs::SimpleFileSystem};
use crate::proto::{Protocol, ProtocolPointer};
use crate::{Char16, Event, Guid, Handle, Result, Status};
#[cfg(feature = "alloc")]
use ::alloc::vec::Vec;
use bitflags::bitflags;
use core::cell::UnsafeCell;
use core::ffi::c_void;
use core::fmt::{Debug, Formatter};
use core::mem::{self, MaybeUninit};
use core::ops::{Deref, DerefMut};
use core::ptr::NonNull;
use core::{ptr, slice};
// TODO: this similar to `SyncUnsafeCell`. Once that is stabilized we
// can use it instead.
struct GlobalImageHandle {
handle: UnsafeCell<Option<Handle>>,
}
// Safety: reads and writes are managed via `set_image_handle` and
// `BootServices::image_handle`.
unsafe impl Sync for GlobalImageHandle {}
static IMAGE_HANDLE: GlobalImageHandle = GlobalImageHandle {
handle: UnsafeCell::new(None),
};
/// Contains pointers to all of the boot services.
///
/// # Accessing `BootServices`
///
/// A reference to `BootServices` can only be accessed by calling [`SystemTable::boot_services`].
///
/// [`SystemTable::boot_services`]: crate::table::SystemTable::boot_services
///
/// # Accessing protocols
///
/// Protocols can be opened using several methods of `BootServices`. 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`]
/// * [`handle_protocol`]
/// * [`locate_protocol`]
///
/// For protocol definitions, see the [`proto`] module.
///
/// [`proto`]: crate::proto
/// [`open_protocol_exclusive`]: BootServices::open_protocol_exclusive
/// [`open_protocol`]: BootServices::open_protocol
/// [`get_image_file_system`]: BootServices::get_image_file_system
/// [`locate_protocol`]: BootServices::locate_protocol
/// [`handle_protocol`]: BootServices::handle_protocol
///
/// ## Use of [`UnsafeCell`] for protocol references
///
/// Some protocols require mutable access to themselves. For example,
/// most of the methods of the [`Output`] protocol take `&mut self`,
/// because the internal function pointers specified by UEFI for that
/// protocol take a mutable `*This` pointer. We don't want to directly
/// return a mutable reference to a protocol though because the lifetime
/// of the protocol is tied to `BootServices`. (That lifetime improves
/// safety by ensuring protocols aren't accessed after exiting boot
/// services.) If methods like [`open_protocol`] protocol took a mutable
/// reference to `BootServices` and returned a mutable reference to a
/// protocol it would prevent all other access to `BootServices` until
/// the protocol reference was dropped. To work around this, the
/// protocol reference is wrapped in an [`UnsafeCell`]. Callers can then
/// get a mutable reference to the protocol if needed.
///
/// [`Output`]: crate::proto::console::text::Output
/// [`open_protocol`]: BootServices::open_protocol
#[repr(C)]
pub struct BootServices {
header: Header,
// Task Priority services
raise_tpl: unsafe extern "efiapi" fn(new_tpl: Tpl) -> Tpl,
restore_tpl: unsafe extern "efiapi" fn(old_tpl: Tpl),
// Memory allocation functions
allocate_pages: extern "efiapi" fn(
alloc_ty: u32,
mem_ty: MemoryType,
count: usize,
addr: &mut PhysicalAddress,
) -> Status,
free_pages: extern "efiapi" fn(addr: PhysicalAddress, pages: usize) -> Status,
get_memory_map: unsafe extern "efiapi" fn(
size: &mut usize,
map: *mut MemoryDescriptor,
key: &mut MemoryMapKey,
desc_size: &mut usize,
desc_version: &mut u32,
) -> Status,
allocate_pool:
extern "efiapi" fn(pool_type: MemoryType, size: usize, buffer: &mut *mut u8) -> Status,
free_pool: extern "efiapi" fn(buffer: *mut u8) -> Status,
// Event & timer functions
create_event: unsafe extern "efiapi" fn(
ty: EventType,
notify_tpl: Tpl,
notify_func: Option<EventNotifyFn>,
notify_ctx: Option<NonNull<c_void>>,
out_event: *mut Event,
) -> Status,
set_timer: unsafe extern "efiapi" fn(event: Event, ty: u32, trigger_time: u64) -> Status,
wait_for_event: unsafe extern "efiapi" fn(
number_of_events: usize,
events: *mut Event,
out_index: *mut usize,
) -> Status,
signal_event: extern "efiapi" fn(event: Event) -> Status,
close_event: unsafe extern "efiapi" fn(event: Event) -> Status,
check_event: unsafe extern "efiapi" fn(event: Event) -> Status,
// Protocol handlers
install_protocol_interface: unsafe extern "efiapi" fn(
handle: &mut Option<Handle>,
guid: &Guid,
interface_type: InterfaceType,
interface: *mut c_void,
) -> Status,
reinstall_protocol_interface: unsafe extern "efiapi" fn(
handle: Handle,
protocol: &Guid,
old_interface: *mut c_void,
new_interface: *mut c_void,
) -> Status,
uninstall_protocol_interface: unsafe extern "efiapi" fn(
handle: Handle,
protocol: &Guid,
interface: *mut c_void,
) -> Status,
handle_protocol:
extern "efiapi" fn(handle: Handle, proto: &Guid, out_proto: &mut *mut c_void) -> Status,
_reserved: usize,
register_protocol_notify: extern "efiapi" fn(
protocol: &Guid,
event: Event,
registration: *mut ProtocolSearchKey,
) -> Status,
locate_handle: unsafe extern "efiapi" fn(
search_ty: i32,
proto: Option<&Guid>,
key: Option<ProtocolSearchKey>,
buf_sz: &mut usize,
buf: *mut MaybeUninit<Handle>,
) -> Status,
locate_device_path: unsafe extern "efiapi" fn(
proto: &Guid,
device_path: &mut *const FfiDevicePath,
out_handle: &mut MaybeUninit<Handle>,
) -> Status,
install_configuration_table: usize,
// Image services
load_image: unsafe extern "efiapi" fn(
boot_policy: u8,
parent_image_handle: Handle,
device_path: *const FfiDevicePath,
source_buffer: *const u8,
source_size: usize,
image_handle: &mut MaybeUninit<Handle>,
) -> Status,
start_image: unsafe extern "efiapi" fn(
image_handle: Handle,
exit_data_size: *mut usize,
exit_data: &mut *mut Char16,
) -> Status,
exit: extern "efiapi" fn(
image_handle: Handle,
exit_status: Status,
exit_data_size: usize,
exit_data: *mut Char16,
) -> !,
unload_image: extern "efiapi" fn(image_handle: Handle) -> Status,
exit_boot_services:
unsafe extern "efiapi" fn(image_handle: Handle, map_key: MemoryMapKey) -> Status,
// Misc services
get_next_monotonic_count: usize,
stall: extern "efiapi" fn(microseconds: usize) -> Status,
set_watchdog_timer: unsafe extern "efiapi" fn(
timeout: usize,
watchdog_code: u64,
data_size: usize,
watchdog_data: *const u16,
) -> Status,
// Driver support services
connect_controller: unsafe extern "efiapi" fn(
controller: Handle,
driver_image: Option<Handle>,
remaining_device_path: *const FfiDevicePath,
recursive: bool,
) -> Status,
disconnect_controller: unsafe extern "efiapi" fn(
controller: Handle,
driver_image: Option<Handle>,
child: Option<Handle>,
) -> Status,
// Protocol open / close services
open_protocol: extern "efiapi" fn(
handle: Handle,
protocol: &Guid,
interface: &mut *mut c_void,
agent_handle: Handle,
controller_handle: Option<Handle>,
attributes: u32,
) -> Status,
close_protocol: extern "efiapi" fn(
handle: Handle,
protocol: &Guid,
agent_handle: Handle,
controller_handle: Option<Handle>,
) -> Status,
open_protocol_information: usize,
// Library services
protocols_per_handle: unsafe extern "efiapi" fn(
handle: Handle,
protocol_buffer: *mut *mut *const Guid,
protocol_buffer_count: *mut usize,
) -> Status,
locate_handle_buffer: unsafe extern "efiapi" fn(
search_ty: i32,
proto: Option<&Guid>,
key: Option<ProtocolSearchKey>,
no_handles: &mut usize,
buf: &mut *mut Handle,
) -> Status,
locate_protocol: extern "efiapi" fn(
proto: &Guid,
registration: *mut c_void,
out_proto: &mut *mut c_void,
) -> Status,
install_multiple_protocol_interfaces: usize,
uninstall_multiple_protocol_interfaces: usize,
// CRC services
calculate_crc32: usize,
// Misc services
copy_mem: unsafe extern "efiapi" fn(dest: *mut u8, src: *const u8, len: usize),
set_mem: unsafe extern "efiapi" fn(buffer: *mut u8, len: usize, value: u8),
// New event functions (UEFI 2.0 or newer)
create_event_ex: unsafe extern "efiapi" fn(
ty: EventType,
notify_tpl: Tpl,
notify_fn: Option<EventNotifyFn>,
notify_ctx: Option<NonNull<c_void>>,
event_group: Option<NonNull<Guid>>,
out_event: *mut Event,
) -> Status,
}
impl BootServices {
/// Get the [`Handle`] of the currently-executing image.
pub fn image_handle(&self) -> Handle {
// Safety:
//
// `IMAGE_HANDLE` is only set by `set_image_handle`, see that
// documentation for more details.
//
// Additionally, `image_handle` takes a `&self` which ensures it
// can only be called while boot services are active. (After
// exiting boot services, the image handle should not be
// considered valid.)
unsafe {
IMAGE_HANDLE
.handle
.get()
.read()
.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_macros::entry`]. It should not be called at any other
/// point in time, unless the executable does not use
/// [`uefi_macros::entry`], in which case it should be called once
/// before calling other `BootServices` functions.
///
/// # Safety
///
/// This function should only be called as described above. The
/// safety guarantees of [`BootServices::open_protocol_exclusive`]
/// rely on the global image handle being correct.
pub unsafe fn set_image_handle(&self, image_handle: Handle) {
// As with `image_handle`, `&self` isn't actually used, but it
// enforces that this function is only called while boot
// services are active.
IMAGE_HANDLE.handle.get().write(Some(image_handle));
}
/// Raises a task's priority level and returns its previous level.
///
/// 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 outputs 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(&self, tpl: Tpl) -> TplGuard<'_> {
TplGuard {
boot_services: self,
old_tpl: (self.raise_tpl)(tpl),
}
}
/// Allocates memory pages from the system.
///
/// UEFI OS loaders should allocate memory of the type `LoaderData`. An `u64`
/// is returned even on 32-bit platforms because some hardware configurations
/// like Intel PAE enable 64-bit physical addressing on a 32-bit processor.
pub fn allocate_pages(
&self,
ty: AllocateType,
mem_ty: MemoryType,
count: usize,
) -> Result<PhysicalAddress> {
let (ty, mut addr) = match ty {
AllocateType::AnyPages => (0, 0),
AllocateType::MaxAddress(addr) => (1, addr),
AllocateType::Address(addr) => (2, addr),
};
(self.allocate_pages)(ty, mem_ty, count, &mut addr).into_with_val(|| addr)
}
/// Frees memory pages allocated by UEFI.
pub fn free_pages(&self, addr: PhysicalAddress, count: usize) -> Result {
(self.free_pages)(addr, count).into()
}
/// Returns struct which contains the size of a single memory descriptor
/// as well as the size of the current memory map.
///
/// Note that the size of the memory map can increase any time an allocation happens,
/// so when creating a buffer to put the memory map into, it's recommended to allocate a few extra
/// elements worth of space above the size of the current memory map.
#[must_use]
pub fn memory_map_size(&self) -> MemoryMapSize {
let mut map_size = 0;
let mut map_key = MemoryMapKey(0);
let mut entry_size = 0;
let mut entry_version = 0;
let status = unsafe {
(self.get_memory_map)(
&mut map_size,
ptr::null_mut(),
&mut map_key,
&mut entry_size,
&mut entry_version,
)
};
assert_eq!(status, Status::BUFFER_TOO_SMALL);
MemoryMapSize {
entry_size,
map_size,
}
}
/// Retrieves the current memory map.
///
/// The allocated buffer should be big enough to contain the memory map,
/// and a way of estimating how big it should be is by calling `memory_map_size`.
///
/// The buffer must be aligned like a `MemoryDescriptor`.
///
/// The returned key is a unique identifier of the current configuration of memory.
/// Any allocations or such will change the memory map's key.
///
/// If you want to store the resulting memory map without having to keep
/// the buffer around, you can use `.copied().collect()` on the iterator.
pub fn memory_map<'buf>(
&self,
buffer: &'buf mut [u8],
) -> Result<(
MemoryMapKey,
impl ExactSizeIterator<Item = &'buf MemoryDescriptor> + Clone,
)> {
let mut map_size = buffer.len();
MemoryDescriptor::assert_aligned(buffer);
let map_buffer = buffer.as_mut_ptr().cast::<MemoryDescriptor>();
let mut map_key = MemoryMapKey(0);
let mut entry_size = 0;
let mut entry_version = 0;
assert_eq!(
(map_buffer as usize) % mem::align_of::<MemoryDescriptor>(),
0,
"Memory map buffers must be aligned like a MemoryDescriptor"
);
unsafe {
(self.get_memory_map)(
&mut map_size,
map_buffer,
&mut map_key,
&mut entry_size,
&mut entry_version,
)
}
.into_with_val(move || {
let len = map_size / entry_size;
let iter = MemoryMapIter {
buffer,
entry_size,
index: 0,
len,
};
(map_key, iter)
})
}
/// Allocates from a memory pool. The pointer will be 8-byte aligned.
pub fn allocate_pool(&self, mem_ty: MemoryType, size: usize) -> Result<*mut u8> {
let mut buffer = ptr::null_mut();
(self.allocate_pool)(mem_ty, size, &mut buffer).into_with_val(|| buffer)
}
/// Frees memory allocated from a pool.
pub fn free_pool(&self, addr: *mut u8) -> Result {
(self.free_pool)(addr).into()
}
/// 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.
pub unsafe fn create_event(
&self,
event_ty: EventType,
notify_tpl: Tpl,
notify_fn: Option<EventNotifyFn>,
notify_ctx: Option<NonNull<c_void>>,
) -> Result<Event> {
// Prepare storage for the output Event
let mut event = MaybeUninit::<Event>::uninit();
// Now we're ready to call UEFI
(self.create_event)(
event_ty,
notify_tpl,
notify_fn,
notify_ctx,
event.as_mut_ptr(),
)
.into_with_val(|| event.assume_init())
}
/// Creates a new `Event` of type `event_type`. 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 `Event`s 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`.
///
/// A single event can only be part of a single event group. An event may be removed from an
/// event group by using `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.
///
/// If `event_type` has `EventType::NOTIFY_SIGNAL` or `EventType::NOTIFY_WAIT`, then `notify_fn`
/// mus be `Some` and `notify_tpl` must be a valid task priority level, otherwise 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.
pub unsafe fn create_event_ex(
&self,
event_type: EventType,
notify_tpl: Tpl,
notify_fn: Option<EventNotifyFn>,
notify_ctx: Option<NonNull<c_void>>,
event_group: Option<NonNull<Guid>>,
) -> Result<Event> {
if self.header.revision < Revision::EFI_2_00 {
return Err(Status::UNSUPPORTED.into());
}
let mut event = MaybeUninit::<Event>::uninit();
(self.create_event_ex)(
event_type,
notify_tpl,
notify_fn,
notify_ctx,
event_group,
event.as_mut_ptr(),
)
.into_with_val(|| event.assume_init())
}
/// Sets the trigger for `EventType::TIMER` event.
pub fn set_timer(&self, event: &Event, trigger_time: TimerTrigger) -> Result {
let (ty, time) = match trigger_time {
TimerTrigger::Cancel => (0, 0),
TimerTrigger::Periodic(hundreds_ns) => (1, hundreds_ns),
TimerTrigger::Relative(hundreds_ns) => (2, hundreds_ns),
};
unsafe { (self.set_timer)(event.unsafe_clone(), ty, time) }.into()
}
/// Stops execution until an event is signaled.
///
/// This function must be called at priority level `Tpl::APPLICATION`. If an
/// attempt is made to call it at any other priority level, an `Unsupported`
/// error is returned.
///
/// 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 `NotifySignal`, then an `InvalidParameter`
/// error is returned with the index of the eve,t 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 the
/// Event slice.
///
/// 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.
pub fn wait_for_event(&self, events: &mut [Event]) -> Result<usize, Option<usize>> {
let (number_of_events, events) = (events.len(), events.as_mut_ptr());
let mut index = MaybeUninit::<usize>::uninit();
unsafe { (self.wait_for_event)(number_of_events, events, index.as_mut_ptr()) }.into_with(
|| unsafe { index.assume_init() },
|s| {
if s == Status::INVALID_PARAMETER {
unsafe { Some(index.assume_init()) }
} else {
None
}
},
)
}
/// Place 'event' in the signaled stated. If 'event' is already in the signaled state,
/// then nothing further occurs and `Status::SUCCESS` is returned. If `event` is of type
/// `EventType::NOTIFY_SIGNAL`, then 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.
pub fn signal_event(&self, event: &Event) -> Result {
// Safety: cloning this event should be safe, as we're directly passing it to firmware
// and not keeping the clone around.
unsafe { (self.signal_event)(event.unsafe_clone()).into() }
}
/// 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. It is safe to call this function within the corresponding notify function.
///
///
/// Note: The UEFI Specification v2.9 states that this may only return `EFI_SUCCESS`, but,
/// at least for application based on EDK2 (such as OVMF), it may also return `EFI_INVALID_PARAMETER`.
pub fn close_event(&self, event: Event) -> Result {
unsafe { (self.close_event)(event).into() }
}
/// Checks to see if an event is signaled, without blocking execution to wait for it.
///
/// The returned value will be `true` if the event is in the signaled state,
/// otherwise `false` is returned.
pub fn check_event(&self, event: Event) -> Result<bool> {
let status = unsafe { (self.check_event)(event) };
match status {
Status::SUCCESS => Ok(true),
Status::NOT_READY => Ok(false),
_ => Err(status.into()),
}
}
/// Installs a protocol interface on a device handle. If the inner `Option` in `handle` is `None`,
/// one will be created and added to the list of handles in the system and then returned.
///
/// When a protocol interface is installed, firmware will call all functions that have registered
/// to wait for that interface to be installed.
///
/// # Safety
///
/// The caller is responsible for ensuring that they pass a valid `Guid` for `protocol`.
pub unsafe fn install_protocol_interface(
&self,
mut handle: Option<Handle>,
protocol: &Guid,
interface: *mut c_void,
) -> Result<Handle> {
((self.install_protocol_interface)(
&mut handle,
protocol,
InterfaceType::NATIVE_INTERFACE,
interface,
))
// this `unwrapped_unchecked` is safe, `handle` is guaranteed to be Some() if this call is
// successful
.into_with_val(|| handle.unwrap_unchecked())
}
/// 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 notifies 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.
pub unsafe fn reinstall_protocol_interface(
&self,
handle: Handle,
protocol: &Guid,
old_interface: *mut c_void,
new_interface: *mut c_void,
) -> Result<()> {
(self.reinstall_protocol_interface)(handle, protocol, old_interface, new_interface).into()
}
/// 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`.
pub unsafe fn uninstall_protocol_interface(
&self,
handle: Handle,
protocol: &Guid,
interface: *mut c_void,
) -> Result<()> {
(self.uninstall_protocol_interface)(handle, protocol, interface).into()
}
/// Query a handle for a certain protocol.
///
/// This function attempts to get the protocol implementation of a handle,
/// based on the protocol GUID.
///
/// It is recommended that all new drivers and applications use
/// [`open_protocol_exclusive`] or [`open_protocol`] instead of `handle_protocol`.
///
/// UEFI protocols are neither thread-safe nor reentrant, but the firmware
/// provides no mechanism to protect against concurrent usage. Such
/// protections must be implemented by user-level code, for example via a
/// global `HashSet`.
///
/// # Safety
///
/// This method is unsafe because the handle database is not
/// notified that the handle and protocol are in use; there is no
/// guarantee that they will remain valid for the duration of their
/// use. Use [`open_protocol_exclusive`] if possible, otherwise use
/// [`open_protocol`].
///
/// [`open_protocol`]: BootServices::open_protocol
/// [`open_protocol_exclusive`]: BootServices::open_protocol_exclusive
#[deprecated(
note = "it is recommended to use `open_protocol_exclusive` or `open_protocol` instead"
)]
pub unsafe fn handle_protocol<P: ProtocolPointer + ?Sized>(
&self,
handle: Handle,
) -> Result<&UnsafeCell<P>> {
let mut ptr = ptr::null_mut();
(self.handle_protocol)(handle, &P::GUID, &mut ptr).into_with_val(|| {
let ptr = P::mut_ptr_from_ffi(ptr) as *const UnsafeCell<P>;
&*ptr
})
}
/// Registers `event` to be signalled whenever a protocol interface is registered for
/// `protocol` by `install_protocol_interface()` or `reinstall_protocol_interface()`.
///
/// Once `event` has been signalled, `BootServices::locate_handle()` can be used to identify
/// the newly (re)installed handles that support `protocol`. The returned `SearchKey` on success
/// corresponds to the `search_key` parameter in `locate_handle()`.
///
/// Events can be unregistered from protocol interface notification by calling `close_event()`.
pub fn register_protocol_notify(
&self,
protocol: &Guid,
event: Event,
) -> Result<(Event, SearchType)> {
let mut key: MaybeUninit<ProtocolSearchKey> = MaybeUninit::uninit();
// Safety: we clone `event` a couple times, but there will be only one left once we return.
unsafe { (self.register_protocol_notify)(protocol, event.unsafe_clone(), key.as_mut_ptr()) }
// Safety: as long as this call is successful, `key` will be valid.
.into_with_val(|| unsafe {
(
event.unsafe_clone(),
SearchType::ByRegisterNotify(key.assume_init()),
)
})
}
/// Enumerates all handles installed on the system which match a certain query.
///
/// You should first call this function with `None` for the output buffer,
/// in order to retrieve the length of the buffer you need to allocate.
///
/// The next call will fill the buffer with the requested data.
pub fn locate_handle(
&self,
search_ty: SearchType,
output: Option<&mut [MaybeUninit<Handle>]>,
) -> Result<usize> {
let handle_size = mem::size_of::<Handle>();
const NULL_BUFFER: *mut MaybeUninit<Handle> = ptr::null_mut();
let (mut buffer_size, buffer) = match output {
Some(buffer) => (buffer.len() * handle_size, buffer.as_mut_ptr()),
None => (0, NULL_BUFFER),
};
// Obtain the needed data from the parameters.
let (ty, guid, key) = match search_ty {
SearchType::AllHandles => (0, None, None),
SearchType::ByRegisterNotify(registration) => (1, None, Some(registration)),
SearchType::ByProtocol(guid) => (2, Some(guid), None),
};
let status = unsafe { (self.locate_handle)(ty, guid, key, &mut buffer_size, buffer) };
// Must convert the returned size (in bytes) to length (number of elements).
let buffer_len = buffer_size / handle_size;
match (buffer, status) {
(NULL_BUFFER, Status::BUFFER_TOO_SMALL) => Ok(buffer_len),
(_, other_status) => other_status.into_with_val(|| buffer_len),
}
}
/// Locates the handle to 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.
pub fn locate_device_path<P: Protocol>(&self, device_path: &mut &DevicePath) -> Result<Handle> {
let mut handle = MaybeUninit::uninit();
let mut device_path_ptr = device_path.as_ffi_ptr();
unsafe {
(self.locate_device_path)(&P::GUID, &mut device_path_ptr, &mut handle).into_with_val(
|| {
*device_path = DevicePath::from_ffi_ptr(device_path_ptr);
handle.assume_init()
},
)
}
}
/// 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
/// [`BootServices::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::table::boot::{BootServices, OpenProtocolAttributes, OpenProtocolParams};
/// use uefi::Handle;
/// # use uefi::Result;
///
/// # fn get_fake_val<T>() -> T { todo!() }
/// # fn test() -> Result {
/// # let boot_services: &BootServices = get_fake_val();
/// # let image_handle: Handle = get_fake_val();
/// let handle = boot_services.get_handle_for_protocol::<DevicePathToText>()?;
/// let device_path_to_text = boot_services.open_protocol_exclusive::<DevicePathToText>(handle)?;
/// # Ok(())
/// # }
/// ```
pub fn get_handle_for_protocol<P: Protocol>(&self) -> Result<Handle> {
// Delegate to a non-generic function to potentially reduce code size.
self.get_handle_for_protocol_impl(&P::GUID)
}
fn get_handle_for_protocol_impl(&self, guid: &Guid) -> Result<Handle> {
self.locate_handle_buffer(SearchType::ByProtocol(guid))?
.handles()
.first()
.cloned()
.ok_or_else(|| Status::NOT_FOUND.into())
}
/// Load an EFI image into memory and return a [`Handle`] to the image.
///
/// There are two ways to load the image: by copying raw image data
/// from a source buffer, or by loading the image via the
/// [`SimpleFileSystem`] protocol. See [`LoadImageSource`] for more
/// details of the `source` parameter.
///
/// The `parent_image_handle` is used to initialize the
/// `parent_handle` field of the [`LoadedImage`] protocol for the
/// image.
///
/// If the image is successfully loaded, a [`Handle`] supporting the
/// [`LoadedImage`] and `LoadedImageDevicePath` protocols is
/// returned. The image can be started with [`start_image`] or
/// unloaded with [`unload_image`].
///
/// [`start_image`]: BootServices::start_image
/// [`unload_image`]: BootServices::unload_image
pub fn load_image(
&self,
parent_image_handle: Handle,
source: LoadImageSource,
) -> uefi::Result<Handle> {
let boot_policy;
let device_path;
let source_buffer;
let source_size;
match source {
LoadImageSource::FromBuffer { buffer, file_path } => {
// Boot policy is ignored when loading from source buffer.
boot_policy = 0;
device_path = file_path.map(|p| p.as_ffi_ptr()).unwrap_or(ptr::null());
source_buffer = buffer.as_ptr();
source_size = buffer.len();
}
LoadImageSource::FromFilePath {
file_path,
from_boot_manager,
} => {
boot_policy = u8::from(from_boot_manager);
device_path = file_path.as_ffi_ptr();
source_buffer = ptr::null();
source_size = 0;
}
};
let mut image_handle = MaybeUninit::uninit();
unsafe {
(self.load_image)(
boot_policy,
parent_image_handle,
device_path,
source_buffer,
source_size,
&mut image_handle,
)
.into_with_val(|| image_handle.assume_init())
}
}
/// Unload an EFI image.
pub fn unload_image(&self, image_handle: Handle) -> Result {
(self.unload_image)(image_handle).into()
}
/// Transfer control to a loaded image's entry point.
pub fn start_image(&self, image_handle: Handle) -> Result {
unsafe {
// TODO: implement returning exit data to the caller.
let mut exit_data_size: usize = 0;
let mut exit_data: *mut Char16 = ptr::null_mut();
(self.start_image)(image_handle, &mut exit_data_size, &mut exit_data).into()
}
}
/// Exits the UEFI application and returns control to the UEFI component
/// that started the UEFI application.
///
/// # Safety
///
/// This function is unsafe because it is up to the caller to ensure that
/// all resources allocated by the application is freed before invoking
/// exit and returning control to the UEFI component that started the UEFI
/// application.
pub unsafe fn exit(
&self,
image_handle: Handle,
exit_status: Status,
exit_data_size: usize,
exit_data: *mut Char16,
) -> ! {
(self.exit)(image_handle, exit_status, exit_data_size, exit_data)
}
/// Exits the UEFI boot services
///
/// This unsafe method is meant to be an implementation detail of the safe
/// `SystemTable<Boot>::exit_boot_services()` method, which is why it is not
/// public.
///
/// Everything that is explained in the documentation of the high-level
/// `SystemTable<Boot>` method is also true here, except that this function
/// is one-shot (no automatic retry) and does not prevent you from shooting
/// yourself in the foot by calling invalid boot services after a failure.
pub(super) unsafe fn exit_boot_services(
&self,
image: Handle,
mmap_key: MemoryMapKey,
) -> Result {
(self.exit_boot_services)(image, mmap_key).into()
}
/// Stalls the processor for an amount of time.
///
/// The time is in microseconds.
pub fn stall(&self, time: usize) {
assert_eq!((self.stall)(time), Status::SUCCESS);
}
/// Set the watchdog timer.
///
/// UEFI will start a 5-minute countdown after an UEFI image is loaded.
/// The image must either successfully load an OS and call `ExitBootServices`
/// in that time, or disable the watchdog.
///
/// Otherwise, the firmware will log the event using the provided numeric