Skip to main content

native_loader/
lib.rs

1//! Load trusted, statically linked position-independent native applications.
2#![no_std]
3
4mod elf;
5
6use core::{alloc::Layout, ptr::NonNull};
7use elf::{Elf, Native};
8pub use xila_version::Version;
9
10pub const ELF_MAGIC: &[u8; 4] = b"\x7fELF";
11
12#[derive(Clone, Copy, Debug, Eq, PartialEq)]
13pub enum Error {
14    InvalidHeader,
15    Truncated,
16    WrongClass,
17    WrongEndian,
18    WrongMachine,
19    NotPositionIndependent,
20    Interpreter,
21    ThreadLocalStorage,
22    InvalidAlignment,
23    /// `e_flags` the target cannot run: Arm EABI version or float ABI, RISC-V float ABI or RVC.
24    IncompatibleFlags(u32),
25    InvalidSegment,
26    OverlappingSegments,
27    InvalidEntry,
28    InvalidAbiNote,
29    MissingAbiNote,
30    /// The image was built for a Xila version that the running one does not run
31    /// (see [`xila_version::compatible`]).
32    IncompatibleXilaVersion {
33        declared: Version,
34        running: Version,
35    },
36    InvalidDynamic,
37    /// DT_INIT, DT_FINI or an init, fini or preinit array: the loader runs no
38    /// constructors or destructors.
39    Constructors,
40    DynamicDependency,
41    UnsupportedDynamicTag(usize),
42    InvalidRelocationTable,
43    InvalidRelocationTarget,
44    InvalidRelocationAddend,
45    UnsupportedRelocation(u32),
46    UnsupportedSplitAddressSpace,
47    SymbolRelocation,
48    ImageTooLarge,
49    AllocationFailed,
50    FinalizationFailed,
51}
52
53/// A loadable region, relative to the beginning of the allocated image.
54#[derive(Clone, Copy, Debug)]
55pub struct Region {
56    pub offset: usize,
57    pub size: usize,
58    pub executable: bool,
59    pub writable: bool,
60}
61
62/// Platform-specific executable RAM or PSRAM.
63///
64/// # Safety
65/// Successful allocations supply an exclusive writable allocation of the given
66/// layout. On unified-address platforms, the same virtual addresses are used
67/// for data access and execution ([`Self::execution_base`] returns
68/// `allocation`). On split-bus (Harvard) platforms where instruction fetch
69/// uses a separate address alias of the same physical memory,
70/// [`Self::execution_base`] returns that alias with at least the same
71/// alignment and size as `allocation`, valid until [`Self::free`].
72/// Finalization must make written instructions visible to instruction fetch,
73/// apply permissions supported by the platform and preserve region contents.
74/// Memory must remain mapped until freed, including on finalization failure.
75pub unsafe trait ExecutableMemory: Sync {
76    fn allocate(&self, layout: Layout) -> Result<NonNull<u8>, Error>;
77
78    /// Instruction-fetch base address aliasing `allocation`.
79    ///
80    /// Unified-address platforms inherit the default, which returns
81    /// `allocation`. Split-bus platforms (such as ESP32-S2/S3 internal D/IRAM)
82    /// override this to return the instruction-bus alias of the same physical
83    /// bytes.
84    fn execution_base(&self, allocation: NonNull<u8>) -> NonNull<u8> {
85        allocation
86    }
87
88    /// Synchronize caches and apply final executable/data permissions.
89    /// Return an error if the region layout cannot be supported.
90    ///
91    /// # Safety
92    /// The allocation must have come from `allocate` with this layout. All
93    /// writes by the loader are complete and no references to the bytes remain.
94    unsafe fn finish_writes(
95        &self,
96        allocation: NonNull<u8>,
97        layout: Layout,
98        regions: &mut dyn Iterator<Item = Region>,
99    ) -> Result<(), Error>;
100
101    /// Release the allocation, regardless of whether finalization succeeded.
102    ///
103    /// # Safety
104    /// The allocation must have come from `allocate` with this layout. No code
105    /// may still be executing from or referencing it.
106    unsafe fn free(&self, allocation: NonNull<u8>, layout: Layout);
107}
108
109/// An installed image. The input ELF bytes may be discarded after loading.
110pub struct LoadedImage {
111    memory: &'static dyn ExecutableMemory,
112    allocation: NonNull<u8>,
113    execution_base: NonNull<u8>,
114    layout: Layout,
115    entry_offset: usize,
116}
117
118impl LoadedImage {
119    /// Validate, copy and relocate the ELF. Reject images whose full virtual
120    /// span (including gaps and BSS) exceeds the caller's memory budget.
121    pub fn load(
122        bytes: &[u8],
123        memory: &'static dyn ExecutableMemory,
124        max_image_size: usize,
125    ) -> Result<Self, Error> {
126        let elf = Elf::<Native>::parse(bytes)?;
127        elf.check_abi()?;
128        if elf.layout.size() > max_image_size {
129            return Err(Error::ImageTooLarge);
130        }
131        let allocation = memory.allocate(elf.layout)?;
132        let execution_base = memory.execution_base(allocation);
133        let loaded = Self {
134            memory,
135            allocation,
136            execution_base,
137            layout: elf.layout,
138            entry_offset: elf.entry_offset,
139        };
140        let data_addr = allocation.as_ptr().addr();
141        let exec_addr = execution_base.as_ptr().addr();
142        if exec_addr != data_addr
143            && (!exec_addr.is_multiple_of(elf.layout.align())
144                || exec_addr.checked_add(elf.layout.size()).is_none())
145        {
146            return Err(Error::AllocationFailed);
147        }
148        let data_bias = data_addr.wrapping_sub(elf.start);
149        let execution_bias = exec_addr.wrapping_sub(elf.start);
150        // Initialize raw memory before constructing a byte slice.
151        unsafe { allocation.as_ptr().write_bytes(0, elf.layout.size()) };
152        let image =
153            unsafe { core::slice::from_raw_parts_mut(allocation.as_ptr(), elf.layout.size()) };
154        elf.copy_to(image);
155        elf.relocate(image, data_bias, execution_bias)?;
156        unsafe { memory.finish_writes(allocation, elf.layout, &mut elf.regions()) }?;
157        Ok(loaded)
158    }
159
160    pub fn base(&self) -> NonNull<u8> {
161        self.allocation
162    }
163
164    pub fn execution_base(&self) -> NonNull<u8> {
165        self.execution_base
166    }
167
168    pub fn entry_address(&self) -> NonNull<u8> {
169        // SAFETY: the ELF parser proved the entry lies in the allocation, and
170        // `execution_base` aliases the same layout on the instruction bus.
171        unsafe { self.execution_base.add(self.entry_offset) }
172    }
173
174    pub fn image_size(&self) -> usize {
175        self.layout.size()
176    }
177}
178
179impl Drop for LoadedImage {
180    fn drop(&mut self) {
181        unsafe { self.memory.free(self.allocation, self.layout) };
182    }
183}
184
185#[cfg(any(
186    all(
187        any(target_arch = "x86_64", target_arch = "aarch64"),
188        target_os = "linux"
189    ),
190    all(
191        any(
192            target_arch = "x86_64",
193            target_arch = "aarch64",
194            target_arch = "arm",
195            target_arch = "riscv32",
196            target_arch = "xtensa"
197        ),
198        target_os = "none"
199    )
200))]
201mod run;
202#[cfg(any(
203    all(
204        any(target_arch = "x86_64", target_arch = "aarch64"),
205        target_os = "linux"
206    ),
207    all(
208        any(
209            target_arch = "x86_64",
210            target_arch = "aarch64",
211            target_arch = "arm",
212            target_arch = "riscv32",
213            target_arch = "xtensa"
214        ),
215        target_os = "none"
216    )
217))]
218pub use run::Startup;
219
220#[cfg(all(test, target_arch = "x86_64", target_endian = "little"))]
221mod tests;