Skip to main content

proka_exec/
sections.rs

1//! The definitions of section entry.
2use crate::{HEADER_SIZE, SECTION_SIZE};
3
4/// A section entry.
5#[repr(C)]
6#[derive(Debug, Clone, Copy)]
7pub struct Section {
8    /// The section name (16 bytes max).
9    pub name: [u8; 16],
10
11    /// Assign is this section loadable
12    pub is_loadable: bool,
13
14    /// Assign is this section executable
15    pub is_execable: bool,
16
17    /// The offset of the section start.
18    pub base: u32,
19
20    /// The length of the section.
21    pub length: u32,
22}
23
24impl Section {
25    /// Convert this object to array.
26    #[inline]
27    pub const fn to_array(&self) -> [u8; SECTION_SIZE] {
28        // SAFETY: used `#[repr(C)]`
29        unsafe { core::ptr::read(self as *const Self as *const [u8; SECTION_SIZE]) }
30    }
31
32    /// Validate is this section not corrupted.
33    #[inline]
34    pub fn validate(&self) -> bool {
35        // If the section is loadable, its base must 4KiB
36        // aligned.
37        let align_ok = if self.is_loadable {
38            (self.base & 0xfff) == 0
39        } else {
40            true
41        };
42
43        // Cannot executable if unloadable
44        let perm_ok = !(self.is_execable && !self.is_loadable);
45
46        align_ok && perm_ok
47    }
48}
49
50/// The iterator of each sections
51#[derive(Debug, Clone, Copy)]
52pub(crate) struct SectionIter {
53    pub buf: &'static [u8],
54    pub total: u16,
55    pub current: u16,
56}
57
58// Iterator implementations
59impl Iterator for SectionIter {
60    type Item = Section;
61
62    fn next(&mut self) -> Option<Self::Item> {
63        let base = HEADER_SIZE + self.current as usize * SECTION_SIZE;
64        let buf = &self.buf[base..base + SECTION_SIZE];
65
66        // Check: is current over than total
67        if self.current >= self.total {
68            return None;
69        }
70
71        // Now convert it
72        let section = unsafe { *(buf.as_ptr() as *const Section) };
73        Some(section)
74    }
75}