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