Skip to main content

proka_exec/
lib.rs

1//! The proka executable header definitions.
2#![no_std]
3
4pub mod header;
5pub mod sections;
6
7use header::Header;
8use sections::{SectionIter, Section};
9
10/// The header size.
11pub const HEADER_SIZE: usize = core::mem::size_of::<Header>();
12
13/// The section entry size
14pub const SECTION_SIZE: usize = core::mem::size_of::<Section>();
15
16/// The parser of the proka executable.
17///
18/// # Usage
19/// To use this parser, you must put an slice into the initializations.
20///
21/// If the content of the proka executable is in memory, the best way
22/// is to use `core::slice::from_raw_parts`.
23#[derive(Debug, Clone, Copy)]
24pub struct Parser {
25    buf: &'static [u8],
26    header: Header,
27    total_sections: u16,
28}
29
30impl Parser {
31    /// Initialize the parser by passing an slice.
32    ///
33    /// # Safety
34    /// You must ensure these before invoking this function:
35    ///
36    ///  - The slice's content is a valid executable;
37    ///  - The slice's pointer is accessable and mapped;
38    ///  - The slice's length is larger than 128 bytes.
39    ///
40    /// If this crate has used by kernel, you need to do mapping 
41    /// first, and invoke this.
42    pub unsafe fn init(buf: &'static [u8]) -> Result<Self, Error> {
43        let header_raw = &buf[0..HEADER_SIZE];    // Header length
44        let header = unsafe { *(header_raw.as_ptr() as *const Header) };
45
46        // Check: Validate is this correct executable
47        if !header.validate() {
48            return Err(Error::NotValidExecutable);
49        }
50        
51        Ok(Self {
52            buf, header,
53            total_sections: header.sections,
54        })
55    }
56
57    /// Get the header.
58    #[inline]
59    pub fn header(&self) -> Header {
60        self.header
61    }
62
63    /// Get each section table.
64    #[allow(private_interfaces)]
65    pub fn sections(&self) -> SectionIter {
66        SectionIter {
67            buf: self.buf,
68            total: self.total_sections,
69            current: 0,
70        }
71    }
72}
73
74/// The error type of parsing header.
75#[repr(C)]
76#[derive(Debug, Clone, Copy, PartialEq, Eq)]
77pub enum Error {
78    /// The executable is not valid.
79    NotValidExecutable,
80}