Skip to content

Commit 37716c7

Browse files
committed
uef-raw: add MemoryDescriptor::uefi_desc_size()
This helps to create unit tests for the memory map which are closer to a real world scenario.
1 parent c7725c2 commit 37716c7

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

uefi-raw/CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
# uefi-raw - [Unreleased]
22

3+
## Added
4+
- `MemoryDescriptor::uefi_desc_size`
5+
36
## Changed
47
- `maximum_capsule_size` of `query_capsule_capabilities` now takes a *mut u64 instead of a *mut usize.
58
- `ResetType` now derives the `Default` trait.

uefi-raw/src/table/boot.rs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ use crate::table::Header;
55
use crate::{Char16, Event, Guid, Handle, PhysicalAddress, Status, VirtualAddress};
66
use bitflags::bitflags;
77
use core::ffi::c_void;
8+
use core::mem;
89

910
/// Table of pointers to all the boot services.
1011
#[derive(Debug)]
@@ -363,6 +364,25 @@ pub struct MemoryDescriptor {
363364
impl MemoryDescriptor {
364365
/// Memory descriptor version number.
365366
pub const VERSION: u32 = 1;
367+
368+
/// Returns a best-effort **guess** of the `desc_size` that UEFI will
369+
/// report for a [`MemoryDescriptor`]. You may use this in unit testing. In
370+
/// integration tests and real world scenarios, refrain from using this, and
371+
/// use the actual reported `desc_size` reported from `UEFI#GetMemoryMap()`
372+
/// instead.
373+
///
374+
/// # Safety
375+
/// Unsafe because you should always use the `desc_size` that is associated
376+
/// with the memory map.
377+
#[must_use]
378+
pub const unsafe fn uefi_desc_size() -> usize {
379+
let size_base = mem::size_of::<Self>();
380+
// Taken from https://github.com/tianocore/edk2/blob/7142e648416ff5d3eac6c6d607874805f5de0ca8/MdeModulePkg/Core/PiSmmCore/Page.c#L1059
381+
let desc_size_diff = mem::size_of::<u64>() - size_base % mem::size_of::<u64>();
382+
let desc_size = size_base + desc_size_diff;
383+
assert!(desc_size > size_base);
384+
desc_size
385+
}
366386
}
367387

368388
impl Default for MemoryDescriptor {
@@ -466,3 +486,17 @@ pub enum Tpl: usize => {
466486
/// Even processor interrupts are disable at this level.
467487
HIGH_LEVEL = 31,
468488
}}
489+
490+
#[cfg(test)]
491+
mod tests {
492+
use super::*;
493+
494+
/// This refers to the ABI of the MemoryDescriptor version 1 a
495+
#[test]
496+
fn test_abi_v1() {
497+
assert_eq!(MemoryDescriptor::VERSION, 1);
498+
assert_eq!(mem::size_of::<MemoryDescriptor>(), 40);
499+
// This is what GetMemoryMap from UEFI usually returns.
500+
assert_eq!(unsafe { MemoryDescriptor::uefi_desc_size() }, 48);
501+
}
502+
}

0 commit comments

Comments
 (0)