interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

GitHub aien-dev/aienux#78 (code only)

closed derived 3370036c64585dd6 #78

Imported from GitHub aien-dev/aienux#78 (code only)

GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed).

Base d6d45df6ae9ead7efd3225fa1fdd6bfe83c69f80 · Head 39ba2ac53cffe5e44db513da8b64d98b0b69918c

Fetch it

A git bundle of the pull request's head, 7838 bytes.

curl -fsSL https://interplane.io/drakestapleton/aienux/patches/3370036c64585dd6.bundle -o 3370036c64585dd6.bundle
git fetch 3370036c64585dd6.bundle refs/pull/78/head

Raw bundle · Diff

Provenance

This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record:

github-import 1
aien-dev/aienux
78
39ba2ac53cffe5e44db513da8b64d98b0b69918c
{"kind":"github-import","owner":"aien-dev","repo":"aienux","number":78,"url":"https://github.com/aien-dev/aienux/pull/78","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:43Z","metadata":"unavailable","state_derived":true}

Changes

diff --git a/crates/aienos-kernel/src/acpi.rs b/crates/aienos-kernel/src/acpi.rs
index 89e43761..5ffb0d5d 100644
--- a/crates/aienos-kernel/src/acpi.rs
+++ b/crates/aienos-kernel/src/acpi.rs
@@ -289,7 +289,9 @@ impl EcamWindow {
 /// The ECAM window of a validated MCFG table covering `segment` and `bus`.
 pub fn mcfg_window(mcfg: &[u8], segment: u16, bus: u8) -> Result<Option<EcamWindow>, AcpiError> {
     let mcfg = checked_table(mcfg, b"MCFG")?;
-    let entries = mcfg.get(MCFG_ENTRIES_OFFSET..).ok_or(AcpiError::Truncated)?;
+    let entries = mcfg
+        .get(MCFG_ENTRIES_OFFSET..)
+        .ok_or(AcpiError::Truncated)?;
     Ok(entries
         .as_chunks::<MCFG_ENTRY_LEN>()
         .0
diff --git a/crates/aienos-kernel/src/lib.rs b/crates/aienos-kernel/src/lib.rs
index 06ec2531..9e150ab6 100644
--- a/crates/aienos-kernel/src/lib.rs
+++ b/crates/aienos-kernel/src/lib.rs
@@ -20,12 +20,14 @@ pub mod fatal;
 pub mod gic;
 pub mod mem;
 pub mod nvme;
+pub mod pe;
 pub mod recovery;
 pub mod report;
 pub mod scheduler;
 pub mod store;
 pub mod sync;
 pub mod timer;
+pub mod uefi;
 pub mod usb;
 
 #[cfg(all(target_os = "none", not(feature = "std"), not(test)))]
diff --git a/crates/aienos-kernel/src/mem/map_plan.rs b/crates/aienos-kernel/src/mem/map_plan.rs
index 8765c9dd..9ede3cad 100644
--- a/crates/aienos-kernel/src/mem/map_plan.rs
+++ b/crates/aienos-kernel/src/mem/map_plan.rs
@@ -19,10 +19,9 @@ pub struct EfiMemoryDescriptor {
     pub attribute: u64,
 }
 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub struct PeSection<'a> {
-    pub name: &'a str,
-    pub virtual_address: u32,
-    pub virtual_size: u32,
+pub struct PeSection {
+    pub va: u64,
+    pub size: u64,
     pub characteristics: u32,
 }
 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -77,9 +76,9 @@ fn overlap(a: AddressRange, b: AddressRange) -> Result<bool, PlanError> {
 /// the explicit decision is to finish runtime calls before entering EL1h.
 pub fn build_map_plan(
     memory: &[EfiMemoryDescriptor],
-    image_base: u64,
+    _image_base: u64,
     image_allocation: AddressRange,
-    sections: &[PeSection<'_>],
+    sections: &[PeSection],
     runtime_attributes: Option<&[RuntimeAttributes]>,
     mmio: &[AddressRange],
 ) -> Result<(Vec<PlannedMapping>, Option<RuntimeDecision>), PlanError> {
@@ -96,16 +95,22 @@ pub fn build_map_plan(
         if d.memory_type == EFI_LOADER_CODE {
             let mut covered = 0;
             for section in sections {
-                let size = u64::from(section.virtual_size);
+                let size = section.size;
                 if size == 0 {
                     continue;
                 }
-                let start = image_base
-                    .checked_add(u64::from(section.virtual_address))
-                    .ok_or(PlanError::Overflow)?;
+                let start = section.va;
+                let aligned_start = start & !4095;
+                let aligned_end = start
+                    .checked_add(size)
+                    .and_then(|value| value.checked_add(4095))
+                    .ok_or(PlanError::Overflow)?
+                    & !4095;
                 let r = AddressRange {
-                    start: start & !4095,
-                    length: ((start + size + 4095) & !4095) - (start & !4095),
+                    start: aligned_start,
+                    length: aligned_end
+                        .checked_sub(aligned_start)
+                        .ok_or(PlanError::Overflow)?,
                 };
                 if !overlap(r, image_allocation)? {
                     return Err(PlanError::ImageSectionOutsideAllocation);
@@ -252,15 +257,13 @@ mod tests {
         let mem = [d(EFI_LOADER_CODE, 0x100000, 4, 0)];
         let sec = [
             PeSection {
-                name: ".text",
-                virtual_address: 0,
-                virtual_size: 4096,
+                va: 0x100000,
+                size: 4096,
                 characteristics: RX,
             },
             PeSection {
-                name: ".data",
-                virtual_address: 4096,
-                virtual_size: 4096,
+                va: 0x101000,
+                size: 4096,
                 characteristics: RW,
             },
         ];
diff --git a/crates/aienos-kernel/src/pe.rs b/crates/aienos-kernel/src/pe.rs
new file mode 100644
index 00000000..16348214
--- /dev/null
+++ b/crates/aienos-kernel/src/pe.rs
@@ -0,0 +1,208 @@
+//! Bounds-checked parser for loaded PE32+ AArch64 section tables.
+use crate::mem::map_plan::PeSection;
+use alloc::vec::Vec;
+
+const PAGE: u64 = 4096;
+const IMAGE_FILE_MACHINE_ARM64: u16 = 0xaa64;
+const PE32_PLUS: u16 = 0x20b;
+const EXECUTE: u32 = 0x2000_0000;
+const WRITE: u32 = 0x8000_0000;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum PeError {
+    Truncated,
+    BadDosMagic,
+    BadPeSignature,
+    WrongMachine,
+    WrongOptionalMagic,
+    Overflow,
+    Overlap,
+    WritableExecutable,
+}
+
+fn u16at(b: &[u8], n: usize) -> Result<u16, PeError> {
+    let s = b
+        .get(n..n.checked_add(2).ok_or(PeError::Overflow)?)
+        .ok_or(PeError::Truncated)?;
+    Ok(u16::from_le_bytes([s[0], s[1]]))
+}
+fn u32at(b: &[u8], n: usize) -> Result<u32, PeError> {
+    let s = b
+        .get(n..n.checked_add(4).ok_or(PeError::Overflow)?)
+        .ok_or(PeError::Truncated)?;
+    Ok(u32::from_le_bytes([s[0], s[1], s[2], s[3]]))
+}
+
+/// Parse loaded image sections. Returned virtual addresses are absolute and sizes
+/// cover both virtual and raw contents, rounded to 4 KiB.
+pub fn parse_pe_sections(image: &[u8], image_base: u64) -> Result<Vec<PeSection>, PeError> {
+    if u16at(image, 0)? != 0x5a4d {
+        return Err(PeError::BadDosMagic);
+    }
+    let pe = usize::try_from(u32at(image, 0x3c)?).map_err(|_| PeError::Overflow)?;
+    if image
+        .get(pe..pe.checked_add(4).ok_or(PeError::Overflow)?)
+        .ok_or(PeError::Truncated)?
+        != b"PE\0\0"
+    {
+        return Err(PeError::BadPeSignature);
+    }
+    let coff = pe.checked_add(4).ok_or(PeError::Overflow)?;
+    if u16at(image, coff)? != IMAGE_FILE_MACHINE_ARM64 {
+        return Err(PeError::WrongMachine);
+    }
+    let count = usize::from(u16at(image, coff + 2)?);
+    let optional_size = usize::from(u16at(image, coff + 16)?);
+    let optional = coff.checked_add(20).ok_or(PeError::Overflow)?;
+    let optional_end = optional
+        .checked_add(optional_size)
+        .ok_or(PeError::Overflow)?;
+    if image
+        .get(optional..optional_end)
+        .ok_or(PeError::Truncated)?
+        .len()
+        < 2
+    {
+        return Err(PeError::Truncated);
+    }
+    if u16at(image, optional)? != PE32_PLUS {
+        return Err(PeError::WrongOptionalMagic);
+    }
+    let table = optional_end;
+    let table_len = count.checked_mul(40).ok_or(PeError::Overflow)?;
+    image
+        .get(table..table.checked_add(table_len).ok_or(PeError::Overflow)?)
+        .ok_or(PeError::Truncated)?;
+    let mut sections = Vec::with_capacity(count);
+    for i in 0..count {
+        let h = table + i * 40;
+        let virtual_size = u64::from(u32at(image, h + 8)?);
+        let rva = u64::from(u32at(image, h + 12)?);
+        let raw_size = u64::from(u32at(image, h + 16)?);
+        let bytes = virtual_size.max(raw_size);
+        let start = image_base.checked_add(rva).ok_or(PeError::Overflow)?;
+        let characteristics = u32at(image, h + 36)?;
+        if characteristics & WRITE != 0 && characteristics & EXECUTE != 0 {
+            return Err(PeError::WritableExecutable);
+        }
+        // Page-round both ends: a section starting mid-page still owns that
+        // page, and two sections sharing a page must surface as Overlap
+        // because one page can't carry two different permissions.
+        let va = start & !(PAGE - 1);
+        let end = start
+            .checked_add(bytes)
+            .and_then(|e| e.checked_add(PAGE - 1))
+            .ok_or(PeError::Overflow)?
+            & !(PAGE - 1);
+        let size = end - va;
+        for prior in &sections {
+            let prior: &PeSection = prior;
+            let prior_end = prior.va.checked_add(prior.size).ok_or(PeError::Overflow)?;
+            if size != 0 && prior.size != 0 && va < prior_end && prior.va < end {
+                return Err(PeError::Overlap);
+            }
+        }
+        sections.push(PeSection {
+            va,
+            size,
+            characteristics,
+        });
+    }
+    Ok(sections)
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    fn image(n: usize) -> Vec<u8> {
+        let mut b = vec![0; n.max(0x100 + 24 + 240 + 80)];
+        b[0..2].copy_from_slice(b"MZ");
+        b[0x3c..0x40].copy_from_slice(&0x80u32.to_le_bytes());
+        b[0x80..0x84].copy_from_slice(b"PE\0\0");
+        b[0x84..0x86].copy_from_slice(&IMAGE_FILE_MACHINE_ARM64.to_le_bytes());
+        b[0x86..0x88].copy_from_slice(&2u16.to_le_bytes());
+        b[0x94..0x96].copy_from_slice(&240u16.to_le_bytes());
+        b[0x98..0x9a].copy_from_slice(&PE32_PLUS.to_le_bytes());
+        let t = 0x80 + 24 + 240;
+        for (i, (rva, vs, raw, c)) in [
+            (0x1000u32, 0x1000u32, 0x800u32, 0x6000_0020u32),
+            (0x2000, 0x800, 0x1000, 0xc000_0040),
+        ]
+        .iter()
+        .enumerate()
+        {
+            let h = t + i * 40;
+            b[h + 8..h + 12].copy_from_slice(&vs.to_le_bytes());
+            b[h + 12..h + 16].copy_from_slice(&rva.to_le_bytes());
+            b[h + 16..h + 20].copy_from_slice(&raw.to_le_bytes());
+            b[h + 36..h + 40].copy_from_slice(&c.to_le_bytes());
+        }
+        b
+    }
+    #[test]
+    fn valid_sections_use_base_and_page_rounded_max_size() {
+        let s = parse_pe_sections(&image(0), 0x400000).unwrap();
+        assert_eq!(
+            s[0],
+            PeSection {
+                va: 0x401000,
+                size: 4096,
+                characteristics: 0x6000_0020
+            }
+        );
+        assert_eq!(s[1].size, 4096);
+    }
+    #[test]
+    fn rejects_truncation_and_invalid_headers() {
+        let mut b = image(0);
+        assert_eq!(parse_pe_sections(&b[..10], 0), Err(PeError::Truncated));
+        assert_eq!(parse_pe_sections(&b[..0x90], 0), Err(PeError::Truncated));
+        let table_end = 0x80 + 24 + 240 + 40;
+        assert_eq!(
+            parse_pe_sections(&b[..table_end], 0),
+            Err(PeError::Truncated)
+        );
+        b[0] = 0;
+        assert_eq!(parse_pe_sections(&b, 0), Err(PeError::BadDosMagic));
+        let mut b = image(0);
+        b[0x80] = 0;
+        assert_eq!(parse_pe_sections(&b, 0), Err(PeError::BadPeSignature));
+        let mut b = image(0);
+        b[0x84] = 0;
+        assert_eq!(parse_pe_sections(&b, 0), Err(PeError::WrongMachine));
+        let mut b = image(0);
+        b[0x98] = 0;
+        assert_eq!(parse_pe_sections(&b, 0), Err(PeError::WrongOptionalMagic));
+    }
+    #[test]
+    fn rejects_wx_and_overlapping_ranges() {
+        let mut b = image(0);
+        let t = 0x80 + 24 + 240;
+        b[t + 36..t + 40].copy_from_slice(&0xa000_0000u32.to_le_bytes());
+        assert_eq!(parse_pe_sections(&b, 0), Err(PeError::WritableExecutable));
+        let mut b = image(0);
+        b[t + 40 + 12..t + 40 + 16].copy_from_slice(&0x1800u32.to_le_bytes());
+        assert_eq!(parse_pe_sections(&b, 0), Err(PeError::Overlap));
+    }
+    #[test]
+    fn unaligned_sections_are_page_rounded_and_shared_pages_overlap() {
+        // One section at RVA 0x1001, 1 byte: must cover the whole page 0x1000..0x2000.
+        let mut b = image(0x1000);
+        let t = 0x80 + 24 + 240;
+        b[0x86..0x88].copy_from_slice(&1u16.to_le_bytes());
+        b[t + 8..t + 12].copy_from_slice(&1u32.to_le_bytes());
+        b[t + 12..t + 16].copy_from_slice(&0x1001u32.to_le_bytes());
+        b[t + 16..t + 20].copy_from_slice(&0u32.to_le_bytes());
+        b[t + 36..t + 40].copy_from_slice(&0x4000_0040u32.to_le_bytes());
+        let s = parse_pe_sections(&b, 0x4000_0000).unwrap();
+        assert_eq!((s[0].va, s[0].size), (0x4000_1000, 0x1000));
+        // A second section in the same page (RVA 0x1800) is a shared page: Overlap.
+        b[0x86..0x88].copy_from_slice(&2u16.to_le_bytes());
+        let t2 = t + 40;
+        b[t2 + 8..t2 + 12].copy_from_slice(&0x100u32.to_le_bytes());
+        b[t2 + 12..t2 + 16].copy_from_slice(&0x1800u32.to_le_bytes());
+        b[t2 + 16..t2 + 20].copy_from_slice(&0u32.to_le_bytes());
+        b[t2 + 36..t2 + 40].copy_from_slice(&0x6000_0020u32.to_le_bytes());
+        assert_eq!(parse_pe_sections(&b, 0x4000_0000), Err(PeError::Overlap));
+    }
+}
diff --git a/crates/aienos-kernel/src/uefi.rs b/crates/aienos-kernel/src/uefi.rs
new file mode 100644
index 00000000..7b2e3bb0
--- /dev/null
+++ b/crates/aienos-kernel/src/uefi.rs
@@ -0,0 +1,111 @@
+//! UEFI memory attributes table (MAT) parser.
+use crate::mem::map_plan::{AddressRange, RuntimeAttributes, EFI_MEMORY_RO, EFI_MEMORY_XP};
+use alloc::vec::Vec;
+
+/// EFI_MEMORY_ATTRIBUTES_TABLE configuration table GUID in UEFI byte order.
+pub const EFI_MEMORY_ATTRIBUTES_TABLE_GUID: [u8; 16] = [
+    0x1d, 0x91, 0xfa, 0xdc, 0xeb, 0x26, 0x9f, 0x46, 0xa2, 0x20, 0x38, 0xb7, 0xdc, 0x46, 0x12, 0x20,
+];
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum MatError {
+    Truncated,
+    InvalidDescriptorSize,
+    Overflow,
+}
+fn u32at(b: &[u8], n: usize) -> Result<u32, MatError> {
+    let s = b
+        .get(n..n.checked_add(4).ok_or(MatError::Overflow)?)
+        .ok_or(MatError::Truncated)?;
+    Ok(u32::from_le_bytes([s[0], s[1], s[2], s[3]]))
+}
+fn u64at(b: &[u8], n: usize) -> Result<u64, MatError> {
+    let s = b
+        .get(n..n.checked_add(8).ok_or(MatError::Overflow)?)
+        .ok_or(MatError::Truncated)?;
+    Ok(u64::from_le_bytes([
+        s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7],
+    ]))
+}
+
+/// Parse the MAT table body. Descriptor extensions are skipped according to
+/// DescriptorSize; each result describes one physical descriptor range.
+pub fn parse_memory_attributes_table(table: &[u8]) -> Result<Vec<RuntimeAttributes>, MatError> {
+    if table.len() < 16 {
+        return Err(MatError::Truncated);
+    }
+    let count = usize::try_from(u32at(table, 4)?).map_err(|_| MatError::Overflow)?;
+    let stride = usize::try_from(u32at(table, 8)?).map_err(|_| MatError::Overflow)?;
+    if stride < 40 {
+        return Err(MatError::InvalidDescriptorSize);
+    }
+    let bytes = count.checked_mul(stride).ok_or(MatError::Overflow)?;
+    let end = 16usize.checked_add(bytes).ok_or(MatError::Overflow)?;
+    table.get(16..end).ok_or(MatError::Truncated)?;
+    let mut out = Vec::with_capacity(count);
+    for i in 0..count {
+        let d = 16 + i * stride;
+        let start = u64at(table, d + 8)?;
+        let pages = u64at(table, d + 24)?;
+        let attribute = u64at(table, d + 32)?;
+        let length = pages.checked_mul(4096).ok_or(MatError::Overflow)?;
+        start.checked_add(length).ok_or(MatError::Overflow)?;
+        out.push(RuntimeAttributes {
+            range: AddressRange { start, length },
+            read_only: attribute & EFI_MEMORY_RO != 0,
+            execute_protect: attribute & EFI_MEMORY_XP != 0,
+        });
+    }
+    Ok(out)
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    fn table(stride: usize) -> Vec<u8> {
+        let mut b = vec![0; 16 + stride * 2];
+        b[0..4].copy_from_slice(&1u32.to_le_bytes());
+        b[4..8].copy_from_slice(&2u32.to_le_bytes());
+        b[8..12].copy_from_slice(&(stride as u32).to_le_bytes());
+        for i in 0..2 {
+            let d = 16 + i * stride;
+            b[d + 8..d + 16].copy_from_slice(&(0x8000u64 + i as u64 * 0x2000).to_le_bytes());
+            b[d + 24..d + 32].copy_from_slice(&2u64.to_le_bytes());
+            b[d + 32..d + 40].copy_from_slice(
+                &(if i == 0 { EFI_MEMORY_RO } else { EFI_MEMORY_XP }).to_le_bytes(),
+            );
+        }
+        b
+    }
+    #[test]
+    fn honors_48_and_56_byte_descriptor_strides() {
+        for stride in [48, 56] {
+            let a = parse_memory_attributes_table(&table(stride)).unwrap();
+            assert_eq!(a.len(), 2);
+            assert_eq!(
+                a[0].range,
+                AddressRange {
+                    start: 0x8000,
+                    length: 8192
+                }
+            );
+            assert!(a[0].read_only && !a[0].execute_protect);
+            assert!(!a[1].read_only && a[1].execute_protect);
+        }
+    }
+    #[test]
+    fn rejects_truncated_and_short_descriptors() {
+        assert_eq!(
+            parse_memory_attributes_table(&[0; 15]),
+            Err(MatError::Truncated)
+        );
+        let mut b = table(48);
+        b.truncate(b.len() - 1);
+        assert_eq!(parse_memory_attributes_table(&b), Err(MatError::Truncated));
+        let mut b = table(48);
+        b[8..12].copy_from_slice(&39u32.to_le_bytes());
+        assert_eq!(
+            parse_memory_attributes_table(&b),
+            Err(MatError::InvalidDescriptorSize)
+        );
+    }
+}