patina_dxe_core 21.1.0

A pure rust implementation of the UEFI DXE Core.
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
//! DXE Core CPU Architectural Protocol
//!
//! ## License
//!
//! Copyright (c) Microsoft Corporation.
//!
//! SPDX-License-Identifier: Apache-2.0
//!
#![allow(unused)]
/// Architecture independent public C EFI CPU Architectural Protocol definition.
use crate::{dxe_services, protocols::PROTOCOL_DB};
use alloc::boxed::Box;
use core::ffi::c_void;
use patina::{
    boot_services::{BootServices, StandardBootServices},
    component::{
        Storage, component,
        service::{IntoService, Service},
    },
    error::{EfiError, Result},
    uefi_protocol::ProtocolInterface,
};
use patina_internal_cpu::{
    cpu::{Cpu, EfiCpu},
    interrupts::{self, ExceptionType, HandlerType, InterruptManager, Interrupts},
};
use r_efi::efi;

use patina::pi::protocols::cpu_arch::{CpuFlushType, CpuInitType, InterruptHandler, PROTOCOL_GUID, Protocol};

#[derive(IntoService)]
#[service(dyn Cpu)]
pub(crate) struct DxeCpu(pub(crate) EfiCpu);

impl Cpu for DxeCpu {
    fn flush_data_cache(&self, start: efi::PhysicalAddress, length: u64, flush_type: CpuFlushType) -> Result<()> {
        self.0.flush_data_cache(start, length, flush_type)
    }

    fn init(&self, init_type: CpuInitType) -> Result<()> {
        self.0.init(init_type)
    }

    fn get_timer_value(&self, timer_index: u32) -> Result<(u64, u64)> {
        self.0.get_timer_value(timer_index)
    }

    fn cache_writeback_granule(&self) -> u32 {
        self.0.cache_writeback_granule()
    }
}

#[derive(IntoService)]
#[service(dyn InterruptManager)]
pub(crate) struct DxeInterruptManager(pub(crate) Interrupts);

impl InterruptManager for DxeInterruptManager {
    fn register_exception_handler(&self, exception_type: ExceptionType, handler: HandlerType) -> Result<()> {
        self.0.register_exception_handler(exception_type, handler)
    }

    fn unregister_exception_handler(&self, exception_type: ExceptionType) -> Result<()> {
        self.0.unregister_exception_handler(exception_type)
    }
}

#[repr(C)]
struct EfiCpuArchProtocolImpl {
    protocol: Protocol,

    // Crate accessible fields
    pub(crate) cpu: Service<dyn Cpu>,
    pub(crate) interrupt_manager: Service<dyn InterruptManager>,
}

// SAFETY: EfiCpuArchProtocolImpl provides a valid protocol structure with stable GUID.
unsafe impl ProtocolInterface for EfiCpuArchProtocolImpl {
    const PROTOCOL_GUID: patina::BinaryGuid = PROTOCOL_GUID;
}

// Helper to convert a raw protocol pointer to a reference. Returns `None` when the caller passes a
// null pointer so the caller can determine the appropriate action to take.
fn get_impl_ref<'a>(this: *const Protocol) -> Option<&'a EfiCpuArchProtocolImpl> {
    if this.is_null() {
        return None;
    }

    // SAFETY: `this` is non-null and points to an EfiCpuArchProtocolImpl instance installed by
    //         Patina via `Box::leak`, so it is properly aligned and valid for the protocol's
    //         lifetime.
    Some(unsafe { &*(this as *const EfiCpuArchProtocolImpl) })
}

fn get_impl_ref_mut<'a>(this: *mut Protocol) -> Option<&'a mut EfiCpuArchProtocolImpl> {
    if this.is_null() {
        return None;
    }

    // SAFETY: `this` is non-null and points to an EfiCpuArchProtocolImpl instance installed by
    //         Patina via `Box::leak`, so it is properly aligned and valid for the protocol's
    //         lifetime.
    Some(unsafe { &mut *(this as *mut EfiCpuArchProtocolImpl) })
}

// EfiCpuArchProtocolImpl function pointers implementations.

extern "efiapi" fn flush_data_cache(
    this: *const Protocol,
    start: efi::PhysicalAddress,
    length: u64,
    flush_type: CpuFlushType,
) -> efi::Status {
    let Some(impl_ref) = get_impl_ref(this) else {
        return efi::Status::INVALID_PARAMETER;
    };

    let result = impl_ref.cpu.flush_data_cache(start, length, flush_type);

    result.map(|_| efi::Status::SUCCESS).unwrap_or_else(|err| err.into())
}

extern "efiapi" fn enable_interrupt(this: *const Protocol) -> efi::Status {
    interrupts::enable_interrupts();

    efi::Status::SUCCESS
}

extern "efiapi" fn disable_interrupt(this: *const Protocol) -> efi::Status {
    interrupts::disable_interrupts();

    efi::Status::SUCCESS
}

extern "efiapi" fn get_interrupt_state(this: *const Protocol, state: *mut bool) -> efi::Status {
    if state.is_null() {
        return efi::Status::INVALID_PARAMETER;
    }
    interrupts::get_interrupt_state()
        .map(|interrupt_state| {
            // SAFETY: caller must ensure that state is a valid pointer. It is null-checked above.
            unsafe {
                state.write_unaligned(interrupt_state);
            }
            efi::Status::SUCCESS
        })
        .unwrap_or_else(|err| err.into())
}

extern "efiapi" fn init(this: *const Protocol, init_type: CpuInitType) -> efi::Status {
    let Some(impl_ref) = get_impl_ref(this) else {
        return efi::Status::INVALID_PARAMETER;
    };

    let result = impl_ref.cpu.init(init_type);

    result.map(|_| efi::Status::SUCCESS).unwrap_or_else(|err| err.into())
}

extern "efiapi" fn register_interrupt_handler(
    this: *const Protocol,
    interrupt_type: isize,
    interrupt_handler: InterruptHandler,
) -> efi::Status {
    let Some(impl_ref) = get_impl_ref(this) else {
        return efi::Status::INVALID_PARAMETER;
    };
    let interrupt_manager = &impl_ref.interrupt_manager;

    let const_fn_ptr = interrupt_handler as *const ();
    let result = if const_fn_ptr.is_null() {
        interrupt_manager.unregister_exception_handler(interrupt_type as ExceptionType)
    } else {
        interrupt_manager
            .register_exception_handler(interrupt_type as ExceptionType, HandlerType::UefiRoutine(interrupt_handler))
    };

    match result {
        Ok(()) => efi::Status::SUCCESS,
        Err(err) => err.into(),
    }
}

extern "efiapi" fn get_timer_value(
    this: *const Protocol,
    timer_index: u32,
    timer_value: *mut u64,
    timer_period: *mut u64,
) -> efi::Status {
    if timer_value.is_null() || timer_period.is_null() {
        return efi::Status::INVALID_PARAMETER;
    }
    let Some(impl_ref) = get_impl_ref(this) else {
        return efi::Status::INVALID_PARAMETER;
    };

    let result = impl_ref.cpu.get_timer_value(timer_index);

    match result {
        Ok((value, period)) => {
            // SAFETY: caller must ensure that timer_value and timer_period are valid pointers. They are null-checked above.
            unsafe {
                timer_value.write_unaligned(value);
                timer_period.write_unaligned(period);
            }
            efi::Status::SUCCESS
        }
        Err(err) => err.into(),
    }
}

extern "efiapi" fn set_memory_attributes(
    _this: *const Protocol,
    base_address: efi::PhysicalAddress,
    length: u64,
    attributes: u64,
) -> efi::Status {
    match dxe_services::core_set_memory_space_attributes(base_address, length, attributes) {
        Ok(_) => efi::Status::SUCCESS,
        Err(status) => status.into(),
    }
}

impl EfiCpuArchProtocolImpl {
    fn new(cpu: Service<dyn Cpu>, interrupt_manager: Service<dyn InterruptManager>) -> Self {
        Self {
            protocol: Protocol {
                flush_data_cache,
                enable_interrupt,
                disable_interrupt,
                get_interrupt_state,
                init,
                register_interrupt_handler,
                get_timer_value,
                set_memory_attributes,
                number_of_timers: 0,
                dma_buffer_alignment: cpu.cache_writeback_granule(),
            },

            // private data
            cpu,
            interrupt_manager,
        }
    }
}

/// This component installs the cpu arch protocol
#[derive(Default)]
pub(crate) struct CpuArchProtocolInstaller;

#[component]
impl CpuArchProtocolInstaller {
    fn entry_point(
        self,
        cpu: Service<dyn Cpu>,
        interrupt_manager: Service<dyn InterruptManager>,
        bs: StandardBootServices,
    ) -> Result<()> {
        let protocol = EfiCpuArchProtocolImpl::new(cpu, interrupt_manager);

        // Convert the protocol to a raw pointer and store it in to protocol DB
        let interface = Box::leak(Box::new(protocol));

        bs.install_protocol_interface(None, interface)
            .inspect_err(|_| log::error!("Failed to install EFI_CPU_ARCH_PROTOCOL"))?;
        log::info!("installed EFI_CPU_ARCH_PROTOCOL_GUID");

        Ok(())
    }
}

#[cfg(test)]
#[coverage(off)]
mod tests {
    use crate::test_support;

    use super::*;

    use mockall::{mock, predicate::*};
    use patina::pi::protocols::cpu_arch::{EfiExceptionType, EfiSystemContext};

    mock! {
        EfiCpuInit {}
        impl Cpu for EfiCpuInit {
            fn flush_data_cache(
                &self,
                start: efi::PhysicalAddress,
                length: u64,
                flush_type: CpuFlushType,
            ) -> Result<()>;
            fn init(&self, init_type: CpuInitType) -> Result<()>;
            fn get_timer_value(&self, timer_index: u32) -> Result<(u64, u64)>;
            fn cache_writeback_granule(&self) -> u32;
        }
    }

    mock! {
        InterruptManager {}
        impl InterruptManager for InterruptManager {
            fn register_exception_handler(
                &self,
                interrupt_type: ExceptionType,
                handler: HandlerType,
            ) -> Result<()>;
            fn unregister_exception_handler(&self, interrupt_type: ExceptionType) -> Result<()>;
        }
    }

    fn with_locked_state<F: Fn() + std::panic::RefUnwindSafe>(f: F) {
        crate::test_support::with_global_lock(|| {
            test_support::init_test_logger();
            f();
        })
        .unwrap();
    }

    #[test]
    fn test_flush_data_cache() {
        with_locked_state(|| {
            let mut cpu_init = MockEfiCpuInit::new();
            cpu_init.expect_cache_writeback_granule().return_const(64_u32);
            cpu_init.expect_flush_data_cache().with(eq(0), eq(0), always()).returning(|_, _, _| Ok(()));
            let cpu: Service<dyn Cpu> = Service::mock(Box::new(cpu_init));

            let im: Service<dyn InterruptManager> = Service::mock(Box::new(MockInterruptManager::new()));

            let protocol = EfiCpuArchProtocolImpl::new(cpu, im);

            let status = flush_data_cache(&protocol.protocol, 0, 0, CpuFlushType::EfiCpuFlushTypeWriteBackInvalidate);
            assert_eq!(status, efi::Status::SUCCESS);

            // Verify the case when `this` is null.
            let status = flush_data_cache(core::ptr::null(), 0, 0, CpuFlushType::EfiCpuFlushTypeWriteBackInvalidate);
            assert_eq!(status, efi::Status::INVALID_PARAMETER);
        });
    }

    #[test]
    fn test_enable_interrupt() {
        with_locked_state(|| {
            let mut cpu_init = MockEfiCpuInit::new();
            cpu_init.expect_cache_writeback_granule().return_const(64_u32);
            let cpu: Service<dyn Cpu> = Service::mock(Box::new(cpu_init));
            let im: Service<dyn InterruptManager> = Service::mock(Box::new(MockInterruptManager::new()));
            let protocol = EfiCpuArchProtocolImpl::new(cpu, im);

            let status = enable_interrupt(&protocol.protocol);
            assert_eq!(status, efi::Status::SUCCESS);
        });
    }

    #[test]
    fn test_disable_interrupt() {
        with_locked_state(|| {
            let mut cpu_init = MockEfiCpuInit::new();
            cpu_init.expect_cache_writeback_granule().return_const(64_u32);
            let cpu: Service<dyn Cpu> = Service::mock(Box::new(cpu_init));
            let im: Service<dyn InterruptManager> = Service::mock(Box::new(MockInterruptManager::new()));
            let protocol = EfiCpuArchProtocolImpl::new(cpu, im);

            let status = disable_interrupt(&protocol.protocol);
            assert_eq!(status, efi::Status::SUCCESS);
        });
    }

    #[test]
    fn test_get_interrupt_state() {
        with_locked_state(|| {
            let mut cpu_init = MockEfiCpuInit::new();
            cpu_init.expect_cache_writeback_granule().return_const(64_u32);
            let cpu: Service<dyn Cpu> = Service::mock(Box::new(cpu_init));
            let im: Service<dyn InterruptManager> = Service::mock(Box::new(MockInterruptManager::new()));
            let protocol = EfiCpuArchProtocolImpl::new(cpu, im);

            let mut state = false;
            let status = get_interrupt_state(&protocol.protocol, &mut state as *mut bool);
            assert_eq!(status, efi::Status::SUCCESS);
        });
    }

    #[test]
    fn test_init() {
        with_locked_state(|| {
            let mut cpu_init = MockEfiCpuInit::new();
            cpu_init.expect_init().with(always()).returning(|_| Ok(()));
            cpu_init.expect_cache_writeback_granule().return_const(64_u32);
            let cpu: Service<dyn Cpu> = Service::mock(Box::new(cpu_init));

            let mut im: Service<dyn InterruptManager> = Service::mock(Box::new(MockInterruptManager::new()));

            let protocol = EfiCpuArchProtocolImpl::new(cpu, im);

            let status = init(&protocol.protocol, CpuInitType::EfiCpuInit);
            assert_eq!(status, efi::Status::SUCCESS);

            // Verify the case when `this` is null.
            let status = init(core::ptr::null(), CpuInitType::EfiCpuInit);
            assert_eq!(status, efi::Status::INVALID_PARAMETER);
        });
    }

    extern "efiapi" fn mock_interrupt_handler(_type: EfiExceptionType, _context: EfiSystemContext) {}

    #[test]
    fn test_register_interrupt_handler() {
        with_locked_state(|| {
            let mut cpu_init = MockEfiCpuInit::new();
            cpu_init.expect_cache_writeback_granule().return_const(64_u32);
            let cpu: Service<dyn Cpu> = Service::mock(Box::new(cpu_init));

            let mut interrupt_manager = MockInterruptManager::new();
            interrupt_manager
                .expect_register_exception_handler()
                .with(eq(ExceptionType::from(0_usize)), always())
                .returning(|_, _| Ok(()));
            let im: Service<dyn InterruptManager> = Service::mock(Box::new(interrupt_manager));

            let protocol = EfiCpuArchProtocolImpl::new(cpu, im);

            let status = register_interrupt_handler(&protocol.protocol, 0, mock_interrupt_handler);
            assert_eq!(status, efi::Status::SUCCESS);

            // Verify the case when `this` is null.
            let status = register_interrupt_handler(core::ptr::null(), 0, mock_interrupt_handler);
            assert_eq!(status, efi::Status::INVALID_PARAMETER);
        });
    }

    #[test]
    fn test_get_timer_value() {
        with_locked_state(|| {
            let mut cpu_init = MockEfiCpuInit::new();
            cpu_init.expect_cache_writeback_granule().return_const(64_u32);
            cpu_init.expect_get_timer_value().with(eq(0)).returning(|_| Ok((0, 0)));
            let cpu: Service<dyn Cpu> = Service::mock(Box::new(cpu_init));

            let im: Service<dyn InterruptManager> = Service::mock(Box::new(MockInterruptManager::new()));

            let protocol = EfiCpuArchProtocolImpl::new(cpu, im);

            let mut timer_value: u64 = 0;
            let mut timer_period: u64 = 0;
            let status =
                get_timer_value(&protocol.protocol, 0, &mut timer_value as *mut _, &mut timer_period as *mut _);
            assert_eq!(status, efi::Status::SUCCESS);

            // Verify the case when `this` is null.
            let status = get_timer_value(core::ptr::null(), 0, &mut timer_value as *mut _, &mut timer_period as *mut _);
            assert_eq!(status, efi::Status::INVALID_PARAMETER);

            // Null out-parameters should also be rejected.
            let status = get_timer_value(&protocol.protocol, 0, core::ptr::null_mut(), &mut timer_period as *mut _);
            assert_eq!(status, efi::Status::INVALID_PARAMETER);
            let status = get_timer_value(&protocol.protocol, 0, &mut timer_value as *mut _, core::ptr::null_mut());
            assert_eq!(status, efi::Status::INVALID_PARAMETER);
        });
    }

    // Tests for DxeCpu delegation
    #[test]
    fn test_dxe_cpu_flush_data_cache_delegates() {
        with_locked_state(|| {
            let dxe_cpu = DxeCpu(EfiCpu::default());
            let result = dxe_cpu.flush_data_cache(0x1000, 0x100, CpuFlushType::EfiCpuFlushTypeWriteBackInvalidate);
            assert!(result.is_ok());
        });
    }

    #[test]
    fn test_dxe_cpu_init_delegates() {
        with_locked_state(|| {
            let dxe_cpu = DxeCpu(EfiCpu::default());
            let result = dxe_cpu.init(CpuInitType::EfiCpuInit);
            assert!(result.is_ok());
        });
    }

    #[test]
    fn test_dxe_cpu_get_timer_value_delegates() {
        with_locked_state(|| {
            let dxe_cpu = DxeCpu(EfiCpu::default());
            let result = dxe_cpu.get_timer_value(0);
            assert_eq!(result.unwrap(), (0, 0));
        });
    }

    #[test]
    fn test_dxe_cpu_cache_writeback_granule_delegates() {
        with_locked_state(|| {
            let dxe_cpu = DxeCpu(EfiCpu::default());
            let granule = dxe_cpu.cache_writeback_granule();
            assert!(granule == 64u32);
        });
    }

    // Tests for DxeInterruptManager delegation
    #[test]
    fn test_dxe_interrupt_manager_register_then_unregister_delegates() {
        with_locked_state(|| {
            let dxe_interrupt_manager = DxeInterruptManager(Interrupts::default());

            // Register first
            let result = dxe_interrupt_manager.register_exception_handler(
                ExceptionType::from(0_usize),
                HandlerType::UefiRoutine(mock_interrupt_handler),
            );
            assert!(result.is_ok());

            // Then unregister
            let result = dxe_interrupt_manager.unregister_exception_handler(ExceptionType::from(0_usize));
            assert!(result.is_ok());
        });
    }

    #[test]
    fn test_dxe_interrupt_manager_unregister_then_register_delegates() {
        with_locked_state(|| {
            let dxe_interrupt_manager = DxeInterruptManager(Interrupts::default());
            let result = dxe_interrupt_manager.unregister_exception_handler(ExceptionType::from(0_usize));
            // Expecting an error because there is no handler registered yet, but the method should still be callable.
            assert!(result.is_err());

            let result = dxe_interrupt_manager.register_exception_handler(
                ExceptionType::from(0_usize),
                HandlerType::UefiRoutine(mock_interrupt_handler),
            );
            assert!(result.is_ok());

            // Now the unregister should succeed
            let result = dxe_interrupt_manager.unregister_exception_handler(ExceptionType::from(0_usize));
            assert!(result.is_ok());
        });
    }

    #[test]
    fn test_get_impl_ref_null_returns_none() {
        assert!(get_impl_ref(core::ptr::null()).is_none());
    }

    #[test]
    fn test_get_impl_ref_returns_some_for_valid_pointer() {
        with_locked_state(|| {
            let mut cpu_init = MockEfiCpuInit::new();
            cpu_init.expect_cache_writeback_granule().return_const(64_u32);
            let cpu: Service<dyn Cpu> = Service::mock(Box::new(cpu_init));
            let im: Service<dyn InterruptManager> = Service::mock(Box::new(MockInterruptManager::new()));
            let protocol = EfiCpuArchProtocolImpl::new(cpu, im);

            let this = &raw const protocol.protocol;
            let impl_ref = get_impl_ref(this).expect("non-null pointer should yield Some");
            assert_eq!(&raw const impl_ref.protocol, this);
        });
    }

    #[test]
    fn test_get_impl_ref_mut_null_returns_none() {
        assert!(get_impl_ref_mut(core::ptr::null_mut()).is_none());
    }

    #[test]
    fn test_get_impl_ref_mut_returns_some_for_valid_pointer() {
        with_locked_state(|| {
            let mut cpu_init = MockEfiCpuInit::new();
            cpu_init.expect_cache_writeback_granule().return_const(64_u32);
            let cpu: Service<dyn Cpu> = Service::mock(Box::new(cpu_init));
            let im: Service<dyn InterruptManager> = Service::mock(Box::new(MockInterruptManager::new()));
            let mut protocol = EfiCpuArchProtocolImpl::new(cpu, im);

            let this = &raw mut protocol.protocol;
            let impl_ref = get_impl_ref_mut(this).expect("non-null pointer should yield Some");
            assert_eq!(&raw const impl_ref.protocol, this.cast_const());
        });
    }
}