proka_exec/lib.rs
1//! # `proka-exec`
2//!
3//! [](https://www.rust-lang.org/)
4//! [](https://opensource.org/license/gpl-3.0)
5//! [](https://github.com/RainSTR-Studio/proka-exec/stargazers)
6//! [](https://github.com/RainSTR-Studio/proka-exec/issues)
7//! [](https://github.com/RainSTR-Studio/proka-exec/pulls)
8//! [](https://prokadoc.pages.dev/)
9//!
10//! Copyright (C) 2026 RainSTR Studio. All rights reserved.
11//!
12//! ---
13//!
14//! ## Introduction
15//! This crate provides the definitions of headers, section
16//! entrys, and some utils to help you parse the executable
17//! easily.
18//!
19//! ## Steps to use this crate
20//! Before you parse it, you should do these steps:
21//!
22//! - Read the executable file content;
23//! - Make this file's content to a slice (`&'static [u8]`)
24//! - Use [`Parser`] to parse the executable.
25//!
26//! After this, you can do further operations through this parser by
27//! calling its functions.
28//!
29//! ### Note
30//! If you want to do minimal reading, you can just read the header and
31//! section table, other content can be read later;
32//!
33//! Make sure you have read the header and each sections, and they are **NOT** optional!!!
34//!
35//! # LICENSE
36//! This crate is under license [GPL-v3](https://github.com/RainSTR-Studio/proka-exec/blob/main/LICENSE),
37//! and you must follow its rules.
38//!
39//! See [LICENSE](https://github.com/RainSTR-Studio/proka-exec/blob/main/LICENSE) file for more details.
40//!
41//! ## MSRV
42//! This crate's MSRV is `1.85.0` stable.
43#![no_std]
44
45pub mod header;
46pub mod sections;
47pub mod utils;
48
49use header::Header;
50use sections::{Section, SectionIter};
51pub use utils::*;
52
53/// The header size.
54pub const HEADER_SIZE: usize = core::mem::size_of::<Header>();
55
56/// The section entry size
57pub const SECTION_SIZE: usize = core::mem::size_of::<Section>();
58
59/// The parser of the proka executable.
60///
61/// # Usage
62/// To use this parser, you must put an slice into the initializations.
63///
64/// If the content of the proka executable is in memory, the best way
65/// is to use `core::slice::from_raw_parts`.
66#[derive(Debug, Clone, Copy)]
67pub struct Parser {
68 buf: &'static [u8],
69 header: Header,
70 total_sections: u16,
71}
72
73impl Parser {
74 /// Initialize the parser by passing a slice.
75 ///
76 /// # Safety
77 /// You must ensure these before invoking this function:
78 ///
79 /// - The slice's pointer is accessible and properly mapped;
80 /// - The slice's content is a valid executable (internally checked);
81 /// - The slice must contain the header and all section tables (internally checked).
82 ///
83 /// If this crate is used on the kernel-side, you must first map the memory
84 /// that the slice points to before invoking this function.
85 pub unsafe fn init(buf: &'static [u8]) -> Result<Self, Error> {
86 let header_raw = &buf[0..HEADER_SIZE]; // Header length
87 let header = unsafe { *(header_raw.as_ptr() as *const Header) };
88
89 // Check: Validate is this correct executable
90 if !header.validate() {
91 return Err(Error::NotValidExecutable);
92 }
93
94 // Check: Is the buffer contains all sections
95 let len = HEADER_SIZE + header.sections as usize * SECTION_SIZE;
96 if buf.len() < len {
97 return Err(Error::ExecutableCorrupted);
98 }
99
100 Ok(Self {
101 buf,
102 header,
103 total_sections: header.sections,
104 })
105 }
106
107 /// Do more validation after initialization.
108 ///
109 /// # Content
110 /// This will validates:
111 ///
112 /// - Is the header min >= max;
113 /// - Is each section's base correct;
114 /// - Is the section's length not zeroed.
115 /// - Is section base out of length.
116 pub fn validate(&self) -> bool {
117 // Check: Is header's min > max
118 let minimal = self.header.min;
119 let maximum = self.header.max;
120 for (&min, &max) in minimal.iter().zip(maximum.iter()) {
121 if min > max {
122 return false;
123 }
124 }
125
126 // Check: Is each section's base and length correct
127 let min_base = HEADER_SIZE + self.header.sections as usize * SECTION_SIZE;
128 for section in self.sections() {
129 let base_off = section.base as usize;
130 let len = section.length as usize;
131
132 if base_off < min_base
133 || base_off + len > self.buf.len()
134 || len == 0
135 || !section.validate()
136 {
137 return false;
138 }
139 }
140
141 // All's fine :)
142 true
143 }
144
145 /// Get the header in this buffer.
146 #[inline]
147 pub fn header(&self) -> Header {
148 self.header
149 }
150
151 /// Get each section table.
152 #[allow(private_interfaces)]
153 pub fn sections(&self) -> SectionIter {
154 SectionIter {
155 buf: self.buf,
156 total: self.total_sections,
157 current: 0,
158 }
159 }
160}
161
162/// The error type of parsing header.
163#[repr(C)]
164#[derive(Debug, Clone, Copy, PartialEq, Eq)]
165pub enum Error {
166 /// The executable is not valid
167 ///
168 /// Will appear if magic is not correct.
169 NotValidExecutable,
170
171 /// The executable is corrupted.
172 ///
173 /// Will appear if the buffer size is lower than specified
174 /// length.
175 ExecutableCorrupted,
176
177 /// An unknown character in UTF-8 was found in
178 /// parsing arrays
179 ///
180 /// May appear in converting slice to `&str`.
181 UnknownCharacter,
182}