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        // Base address must 4KiB aligned.
36        let is_aligned = (self.base & 0xfff) == 0;
37
38        // If is_loadable = false, is_executable = true, it is illegal
39        let is_correct_group = if self.is_execable && !self.is_loadable {
40            false
41        } else {
42            true
43        };
44
45        is_aligned || is_correct_group
46    }
47}
48
49/// The iterator of each sections
50#[derive(Debug, Clone, Copy)]
51pub(crate) struct SectionIter {
52    pub buf: &'static [u8],
53    pub total: u16,
54    pub current: u16,
55}
56
57// Iterator implementations
58impl Iterator for SectionIter {
59    type Item = Section;
60
61    fn next(&mut self) -> Option<Self::Item> {
62        let base = HEADER_SIZE + self.current as usize * SECTION_SIZE;
63        let buf = &self.buf[base..base + SECTION_SIZE];
64
65        // Check: is current over than total
66        if self.current >= self.total {
67            return None;
68        }
69
70        // Now convert it
71        let section = unsafe { *(buf.as_ptr() as *const Section) };
72        Some(section)
73    }
74}