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
use super::Header;
use crate::proto::{device_path::DevicePath, loaded_image::LoadedImage, Protocol};
use crate::{data_types::Align, proto::media::fs::SimpleFileSystem};
use crate::{Event, Guid, Handle, Result, Status};
#[cfg(feature = "exts")]
use alloc_api::vec::Vec;
use bitflags::bitflags;
use core::cell::UnsafeCell;
use core::ffi::c_void;
use core::mem::{self, MaybeUninit};
use core::ptr;
#[repr(C)]
pub struct BootServices {
header: Header,
raise_tpl: unsafe extern "efiapi" fn(new_tpl: Tpl) -> Tpl,
restore_tpl: unsafe extern "efiapi" fn(old_tpl: Tpl),
allocate_pages: extern "efiapi" fn(
alloc_ty: u32,
mem_ty: MemoryType,
count: usize,
addr: &mut u64,
) -> Status,
free_pages: extern "efiapi" fn(addr: u64, 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,
create_event: unsafe extern "efiapi" fn(
ty: EventType,
notify_tpl: Tpl,
notify_func: Option<EventNotifyFn>,
notify_ctx: *mut c_void,
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: usize,
close_event: usize,
check_event: usize,
install_protocol_interface: usize,
reinstall_protocol_interface: usize,
uninstall_protocol_interface: usize,
handle_protocol:
extern "efiapi" fn(handle: Handle, proto: &Guid, out_proto: &mut *mut c_void) -> Status,
_reserved: usize,
register_protocol_notify: usize,
locate_handle: unsafe extern "efiapi" fn(
search_ty: i32,
proto: *const Guid,
key: *mut c_void,
buf_sz: &mut usize,
buf: *mut Handle,
) -> Status,
locate_device_path: unsafe extern "efiapi" fn(
proto: &Guid,
device_path: &mut *mut DevicePath,
out_handle: *mut Handle,
) -> Status,
install_configuration_table: usize,
load_image: usize,
start_image: usize,
exit: usize,
unload_image: usize,
exit_boot_services:
unsafe extern "efiapi" fn(image_handle: Handle, map_key: MemoryMapKey) -> Status,
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,
connect_controller: usize,
disconnect_controller: usize,
open_protocol: usize,
close_protocol: usize,
open_protocol_information: usize,
protocols_per_handle: usize,
locate_handle_buffer: usize,
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,
calculate_crc32: usize,
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),
create_event_ex: usize,
}
impl BootServices {
pub unsafe fn raise_tpl(&self, tpl: Tpl) -> TplGuard<'_> {
TplGuard {
boot_services: self,
old_tpl: (self.raise_tpl)(tpl),
}
}
pub fn allocate_pages(
&self,
ty: AllocateType,
mem_ty: MemoryType,
count: usize,
) -> Result<u64> {
let (ty, mut addr) = match ty {
AllocateType::AnyPages => (0, 0),
AllocateType::MaxAddress(addr) => (1, addr as u64),
AllocateType::Address(addr) => (2, addr as u64),
};
(self.allocate_pages)(ty, mem_ty, count, &mut addr).into_with_val(|| addr)
}
pub fn free_pages(&self, addr: u64, count: usize) -> Result {
(self.free_pages)(addr, count).into()
}
pub fn memory_map_size(&self) -> usize {
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);
map_size
}
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);
#[allow(clippy::cast_ptr_alignment)]
let map_buffer = buffer.as_ptr() as *mut 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)
})
}
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)
}
pub fn free_pool(&self, addr: *mut u8) -> Result {
(self.free_pool)(addr).into()
}
pub unsafe fn create_event(
&self,
event_ty: EventType,
notify_tpl: Tpl,
notify_fn: Option<fn(Event)>,
) -> Result<Event> {
let mut event = MaybeUninit::<Event>::uninit();
unsafe extern "efiapi" fn notify_trampoline(e: Event, ctx: *mut c_void) {
let notify_fn: fn(Event) = mem::transmute(ctx);
notify_fn(e);
}
let (notify_func, notify_ctx) = notify_fn
.map(|notify_fn| {
(
Some(notify_trampoline as EventNotifyFn),
notify_fn as fn(Event) as *mut c_void,
)
})
.unwrap_or((None, ptr::null_mut()));
(self.create_event)(
event_ty,
notify_tpl,
notify_func,
notify_ctx,
event.as_mut_ptr(),
)
.into_with_val(|| event.assume_init())
}
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
}
},
)
}
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, ty, time) }.into()
}
pub fn handle_protocol<P: Protocol>(&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 = ptr as *mut P as *mut UnsafeCell<P>;
unsafe { &*ptr }
})
}
pub fn locate_handle(
&self,
search_ty: SearchType,
output: Option<&mut [Handle]>,
) -> Result<usize> {
let handle_size = mem::size_of::<Handle>();
const NULL_BUFFER: *mut 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),
};
let (ty, guid, key) = match search_ty {
SearchType::AllHandles => (0, ptr::null(), ptr::null_mut()),
SearchType::ByProtocol(guid) => (2, guid as *const _, ptr::null_mut()),
};
let status = unsafe { (self.locate_handle)(ty, guid, key, &mut buffer_size, buffer) };
let buffer_len = buffer_size / handle_size;
match (buffer, status) {
(NULL_BUFFER, Status::BUFFER_TOO_SMALL) => Ok(buffer_len.into()),
(_, other_status) => other_status.into_with_val(|| buffer_len),
}
}
pub fn locate_device_path<P: Protocol>(&self, device_path: &mut DevicePath) -> Result<Handle> {
unsafe {
let mut handle = Handle::uninitialized();
let mut device_path_ptr = device_path as *mut DevicePath;
(self.locate_device_path)(&P::GUID, &mut device_path_ptr, &mut handle)
.into_with_val(|| handle)
}
}
pub(super) unsafe fn exit_boot_services(
&self,
image: Handle,
mmap_key: MemoryMapKey,
) -> Result {
(self.exit_boot_services)(image, mmap_key).into()
}
pub fn stall(&self, time: usize) {
assert_eq!((self.stall)(time), Status::SUCCESS);
}
pub fn set_watchdog_timer(
&self,
timeout: usize,
watchdog_code: u64,
data: Option<&mut [u16]>,
) -> Result {
assert!(
watchdog_code > 0xffff,
"Invalid use of a reserved firmware watchdog code"
);
let (data_len, data) = data
.map(|d| {
assert!(
d.contains(&0),
"Watchdog data must start with a null-terminated string"
);
(d.len(), d.as_mut_ptr())
})
.unwrap_or((0, ptr::null_mut()));
unsafe { (self.set_watchdog_timer)(timeout, watchdog_code, data_len, data) }.into()
}
pub fn locate_protocol<P: Protocol>(&self) -> Result<&UnsafeCell<P>> {
let mut ptr = ptr::null_mut();
(self.locate_protocol)(&P::GUID, ptr::null_mut(), &mut ptr).into_with_val(|| {
let ptr = ptr as *mut P as *mut UnsafeCell<P>;
unsafe { &*ptr }
})
}
pub unsafe fn memmove(&self, dest: *mut u8, src: *const u8, size: usize) {
(self.copy_mem)(dest, src, size);
}
pub unsafe fn memset(&self, buffer: *mut u8, size: usize, value: u8) {
(self.set_mem)(buffer, size, value);
}
}
#[cfg(feature = "exts")]
impl BootServices {
pub fn find_handles<P: Protocol>(&self) -> Result<Vec<Handle>> {
let search_type = SearchType::from_proto::<P>();
let (status1, buffer_size) = self.locate_handle(search_type, None)?.split();
let mut buffer = Vec::with_capacity(buffer_size);
unsafe {
buffer.set_len(buffer_size);
}
let (status2, buffer_size) = self.locate_handle(search_type, Some(&mut buffer))?.split();
unsafe {
buffer.set_len(buffer_size);
}
status1
.into_with_val(|| buffer)
.map(|completion| completion.with_status(status2))
}
pub fn get_image_file_system(
&self,
image_handle: Handle,
) -> Result<&UnsafeCell<SimpleFileSystem>> {
let loaded_image = self
.handle_protocol::<LoadedImage>(image_handle)?
.expect("Failed to retrieve `LoadedImage` protocol from handle");
let loaded_image = unsafe { &*loaded_image.get() };
let device_handle = loaded_image.device();
let device_path = self
.handle_protocol::<DevicePath>(device_handle)?
.expect("Failed to retrieve `DevicePath` protocol from image's device handle");
let device_path = unsafe { &mut *device_path.get() };
let device_handle = self
.locate_device_path::<SimpleFileSystem>(device_path)?
.expect("Failed to locate `SimpleFileSystem` protocol on device path");
self.handle_protocol::<SimpleFileSystem>(device_handle)
}
}
impl super::Table for BootServices {
const SIGNATURE: u64 = 0x5652_4553_544f_4f42;
}
newtype_enum! {
pub enum Tpl: usize => {
APPLICATION = 4,
CALLBACK = 8,
NOTIFY = 16,
HIGH_LEVEL = 31,
}}
pub struct TplGuard<'boot> {
boot_services: &'boot BootServices,
old_tpl: Tpl,
}
impl Drop for TplGuard<'_> {
fn drop(&mut self) {
unsafe {
(self.boot_services.restore_tpl)(self.old_tpl);
}
}
}
#[derive(Debug, Copy, Clone)]
pub enum AllocateType {
AnyPages,
MaxAddress(usize),
Address(usize),
}
newtype_enum! {
pub enum MemoryType: u32 => {
RESERVED = 0,
LOADER_CODE = 1,
LOADER_DATA = 2,
BOOT_SERVICES_CODE = 3,
BOOT_SERVICES_DATA = 4,
RUNTIME_SERVICES_CODE = 5,
RUNTIME_SERVICES_DATA = 6,
CONVENTIONAL = 7,
UNUSABLE = 8,
ACPI_RECLAIM = 9,
ACPI_NON_VOLATILE = 10,
MMIO = 11,
MMIO_PORT_SPACE = 12,
PAL_CODE = 13,
PERSISTENT_MEMORY = 14,
}}
impl MemoryType {
pub const fn custom(value: u32) -> MemoryType {
assert!(value >= 0x80000000);
MemoryType(value)
}
}
pub const MEMORY_DESCRIPTOR_VERSION: u32 = 1;
#[derive(Debug, Copy, Clone)]
#[repr(C)]
pub struct MemoryDescriptor {
pub ty: MemoryType,
padding: u32,
pub phys_start: u64,
pub virt_start: u64,
pub page_count: u64,
pub att: MemoryAttribute,
}
impl Default for MemoryDescriptor {
fn default() -> MemoryDescriptor {
MemoryDescriptor {
ty: MemoryType::RESERVED,
padding: 0,
phys_start: 0,
virt_start: 0,
page_count: 0,
att: MemoryAttribute::empty(),
}
}
}
impl Align for MemoryDescriptor {
fn alignment() -> usize {
mem::align_of::<Self>()
}
}
bitflags! {
pub struct MemoryAttribute: u64 {
const UNCACHEABLE = 0x1;
const WRITE_COMBINE = 0x2;
const WRITE_THROUGH = 0x4;
const WRITE_BACK = 0x8;
const UNCACHABLE_EXPORTED = 0x10;
const WRITE_PROTECT = 0x1000;
const READ_PROTECT = 0x2000;
const EXECUTE_PROTECT = 0x4000;
const NON_VOLATILE = 0x8000;
const MORE_RELIABLE = 0x10000;
const READ_ONLY = 0x20000;
const RUNTIME = 0x8000_0000_0000_0000;
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
#[repr(C)]
pub struct MemoryMapKey(usize);
#[derive(Debug, Clone)]
struct MemoryMapIter<'buf> {
buffer: &'buf [u8],
entry_size: usize,
index: usize,
len: usize,
}
impl<'buf> Iterator for MemoryMapIter<'buf> {
type Item = &'buf MemoryDescriptor;
fn size_hint(&self) -> (usize, Option<usize>) {
let sz = self.len - self.index;
(sz, Some(sz))
}
fn next(&mut self) -> Option<Self::Item> {
if self.index < self.len {
let ptr = self.buffer.as_ptr() as usize + self.entry_size * self.index;
self.index += 1;
let descriptor = unsafe { &*(ptr as *const MemoryDescriptor) };
Some(descriptor)
} else {
None
}
}
}
impl ExactSizeIterator for MemoryMapIter<'_> {}
#[derive(Debug, Copy, Clone)]
pub enum SearchType<'guid> {
AllHandles,
ByProtocol(&'guid Guid),
}
impl<'guid> SearchType<'guid> {
pub fn from_proto<P: Protocol>() -> Self {
SearchType::ByProtocol(&P::GUID)
}
}
bitflags! {
pub struct EventType: u32 {
const TIMER = 0x8000_0000;
const RUNTIME = 0x4000_0000;
const NOTIFY_WAIT = 0x0000_0100;
const NOTIFY_SIGNAL = 0x0000_0200;
const SIGNAL_EXIT_BOOT_SERVICES = 0x0000_0201;
const SIGNAL_VIRTUAL_ADDRESS_CHANGE = 0x6000_0202;
}
}
type EventNotifyFn = unsafe extern "efiapi" fn(event: Event, context: *mut c_void);
pub enum TimerTrigger {
Cancel,
Periodic(u64),
Relative(u64),
}