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 pub fn validate(&self) -> bool {
116 // Check: Is header's min > max
117 let minimal = self.header.min;
118 let maximum = self.header.max;
119 for (&min, &max) in minimal.iter().zip(maximum.iter()) {
120 if min > max {
121 return false;
122 }
123 }
124
125 // Check: Is each section's base and length correct
126 let min_base = HEADER_SIZE + self.header.sections as usize * SECTION_SIZE;
127 for section in self.sections() {
128 if (section.base as usize) < min_base || section.length == 0 {
129 return false;
130 }
131 }
132
133 // All's fine :)
134 true
135 }
136
137 /// Get the header in this buffer.
138 #[inline]
139 pub fn header(&self) -> Header {
140 self.header
141 }
142
143 /// Get each section table.
144 #[allow(private_interfaces)]
145 pub fn sections(&self) -> SectionIter {
146 SectionIter {
147 buf: self.buf,
148 total: self.total_sections,
149 current: 0,
150 }
151 }
152}
153
154/// The error type of parsing header.
155#[repr(C)]
156#[derive(Debug, Clone, Copy, PartialEq, Eq)]
157pub enum Error {
158 /// The executable is not valid
159 ///
160 /// Will appear if magic is not correct.
161 NotValidExecutable,
162
163 /// The executable is corrupted.
164 ///
165 /// Will appear if the buffer size is lower than specified
166 /// length.
167 ExecutableCorrupted,
168
169 /// An unknown character in UTF-8 was found in
170 /// parsing arrays
171 ///
172 /// May appear in converting slice to `&str`.
173 UnknownCharacter,
174}