elf_loader 0.15.1

A no_std-friendly ELF loader, runtime linker, and JIT linker for Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
use crate::{
    ParsePhdrError, Result,
    elf::{
        ElfDyn, ElfDynamic, ElfPhdr, ElfPhdrs, ElfSymbol, Lifecycle, PreCompute, SymbolInfo,
        SymbolTable,
    },
    image::{DynamicInfo, Module},
    input::{Path, PathBuf},
    loader::DynLifecycleHandler,
    relocation::{EmuContext, Emulator, RelocAddr, RelocationArch},
    segment::ElfSegments,
    sync::{Arc, AtomicBool, Ordering, Weak},
    tls::{CoreTlsState, TlsDescArgs, TlsModuleId, TlsTpOffset},
};
use alloc::boxed::Box;
use alloc::vec::Vec;
use core::{any::Any, fmt::Debug, ptr::NonNull};

/// Inner structure for ElfCore
#[repr(C)]
pub(crate) struct CoreInner<D = (), Arch: RelocationArch = crate::arch::NativeArch> {
    /// Indicates whether the component has been initialized
    pub(crate) is_init: AtomicBool,

    /// Loader source path or caller-provided source identifier.
    pub(crate) path: PathBuf,

    /// ELF symbols table
    pub(crate) symtab: SymbolTable<Arch::Layout>,

    /// Finalization functions.
    pub(crate) fini: Lifecycle<'static>,

    /// Finalization handler
    pub(crate) fini_handler: CoreFiniHandler<Arch>,

    /// Dynamic information
    pub(crate) dynamic_info: Option<Arc<DynamicInfo<Arch>>>,

    /// TLS runtime state for the loaded object.
    pub(crate) tls: CoreTlsState,

    /// Memory segments
    pub(crate) segments: ElfSegments,

    /// User-defined data
    pub(crate) user_data: D,
}

impl<D, Arch: RelocationArch> Drop for CoreInner<D, Arch> {
    /// Executes finalization functions when the component is dropped
    fn drop(&mut self) {
        if self.is_init.load(Ordering::Relaxed) {
            match &self.fini_handler {
                CoreFiniHandler::Native(handler) => {
                    handler.call(&self.fini);
                }
                CoreFiniHandler::Emu(emu) => {
                    let ctx = EmuContext::from_parts(
                        self.path.as_str(),
                        self.segments.base(),
                        &self.segments,
                    );
                    emu.call_fini(&ctx, &self.fini);
                }
            }
        }
        self.tls.cleanup();
    }
}

pub(crate) enum CoreFiniHandler<Arch: RelocationArch> {
    Native(DynLifecycleHandler),
    Emu(Arc<dyn Emulator<Arch>>),
}

/// A non-owning reference to an [`ElfCore`].
///
/// `ElfCoreRef` holds a weak reference to the shared core allocation. It is useful
/// when you want to avoid extending the lifetime of a loaded image unnecessarily
/// or need to detect when the image has been dropped.
#[derive(Clone)]
pub struct ElfCoreRef<D = (), Arch: RelocationArch = crate::arch::NativeArch> {
    /// Weak reference to the shared core allocation.
    inner: Weak<CoreInner<D, Arch>>,
}

impl<D, Arch: RelocationArch> ElfCoreRef<D, Arch> {
    /// Attempts to upgrade the weak pointer to an [`ElfCore`].
    ///
    /// # Returns
    /// * `Some(ElfCore)` - If the component is still alive and the upgrade is successful.
    /// * `None` - If the [`ElfCore`] has been dropped.
    pub fn upgrade(&self) -> Option<ElfCore<D, Arch>> {
        self.inner.upgrade().map(|inner| ElfCore { inner })
    }
}

/// Shared core state for a loaded ELF image.
///
/// `ElfCore` stores metadata, symbol tables, segments, TLS state, and lifecycle
/// handlers behind an [`Arc`]. Higher-level image wrappers delegate most common
/// operations to this type.
pub struct ElfCore<D = (), Arch: RelocationArch = crate::arch::NativeArch> {
    /// Shared reference to the inner component data.
    pub(crate) inner: Arc<CoreInner<D, Arch>>,
}

impl<D, Arch: RelocationArch> Clone for ElfCore<D, Arch> {
    /// Clones the [`ElfCore`], incrementing the internal reference count.
    fn clone(&self) -> Self {
        ElfCore {
            inner: Arc::clone(&self.inner),
        }
    }
}

// Safety: ModuleInner can be shared between threads
unsafe impl<D, Arch: RelocationArch> Sync for CoreInner<D, Arch> {}
// Safety: ModuleInner can be sent between threads
unsafe impl<D, Arch: RelocationArch> Send for CoreInner<D, Arch> {}

impl<D, Arch: RelocationArch> ElfCore<D, Arch> {
    /// Returns whether the ELF object has been initialized.
    #[inline]
    pub fn is_init(&self) -> bool {
        self.inner.is_init.load(Ordering::Relaxed)
    }

    /// Marks the component as initialized
    #[inline]
    pub(crate) fn set_init(&self) {
        self.inner.is_init.store(true, Ordering::Relaxed);
    }

    /// Creates a weak reference to this ELF core.
    #[inline]
    pub fn downgrade(&self) -> ElfCoreRef<D, Arch> {
        ElfCoreRef {
            inner: Arc::downgrade(&self.inner),
        }
    }

    /// Gets user data from the ELF object
    #[inline]
    pub fn user_data(&self) -> &D {
        &self.inner.user_data
    }

    /// Returns the program headers of the ELF object.
    pub fn phdrs(&self) -> Option<&[ElfPhdr<Arch::Layout>]> {
        self.inner
            .dynamic_info
            .as_ref()
            .map(|info| info.phdrs.as_slice())
    }

    /// Returns a mutable reference to the user-defined data.
    #[inline]
    pub fn user_data_mut(&mut self) -> Option<&mut D> {
        Arc::get_mut(&mut self.inner).map(|inner| &mut inner.user_data)
    }

    /// Gets the number of strong references to the ELF object
    #[inline]
    pub fn strong_count(&self) -> usize {
        Arc::strong_count(&self.inner)
    }

    /// Gets the number of weak references to the ELF object
    #[inline]
    pub fn weak_count(&self) -> usize {
        Arc::weak_count(&self.inner)
    }

    /// Returns the loader source path or caller-provided source identifier.
    #[inline]
    pub fn path(&self) -> &Path {
        &self.inner.path
    }

    /// Returns the ELF module identity used for diagnostics.
    ///
    /// Dynamic images prefer `DT_SONAME`; other images fall back to the basename
    /// of the loader source path.
    #[inline]
    pub fn name(&self) -> &str {
        self.soname().unwrap_or_else(|| self.path().file_name())
    }

    /// Returns the DT_SONAME value when this core has dynamic metadata.
    #[inline]
    pub(crate) fn soname(&self) -> Option<&str> {
        self.inner
            .dynamic_info
            .as_ref()
            .and_then(|info| info.soname)
    }

    /// Gets the base address of the ELF object
    #[inline]
    pub fn base(&self) -> usize {
        self.inner.segments.base()
    }

    #[inline]
    pub(crate) fn base_addr(&self) -> RelocAddr {
        self.inner.segments.base_addr()
    }

    /// Gets the length of the bounding runtime span covered by mapped memory.
    #[inline]
    pub fn mapped_len(&self) -> usize {
        self.inner.segments.mapped_len()
    }

    /// Returns the lowest runtime address covered by this image's mapped slices.
    #[inline]
    pub(crate) fn mapped_base(&self) -> usize {
        self.inner.segments.mapped_base()
    }

    /// Returns whether `addr` is inside one of this image's mapped slices.
    #[inline]
    pub fn contains_addr(&self, addr: usize) -> bool {
        self.inner.segments.contains_addr(addr)
    }

    /// Returns whether the backing memory is one contiguous span with no gaps.
    #[inline]
    pub fn is_contiguous_mapping(&self) -> bool {
        self.inner.segments.is_contiguous_mapping()
    }

    /// Gets the symbol table
    #[inline]
    pub fn symtab(&self) -> &SymbolTable<Arch::Layout> {
        &self.inner.symtab
    }

    /// Gets a pointer to the dynamic section
    #[inline]
    pub fn dynamic_ptr(&self) -> Option<NonNull<ElfDyn<Arch::Layout>>> {
        self.inner
            .dynamic_info
            .as_ref()
            .map(|info| info.dynamic_ptr)
    }

    /// Gets the EH frame header pointer
    #[inline]
    pub fn eh_frame_hdr(&self) -> Option<NonNull<u8>> {
        self.inner
            .dynamic_info
            .as_ref()
            .and_then(|info| info.eh_frame_hdr)
    }

    /// Gets the segments
    #[inline]
    pub(crate) fn segments(&self) -> &ElfSegments {
        &self.inner.segments
    }

    #[inline]
    pub(crate) fn segment_slice(&self, offset: usize, len: usize) -> &[u8] {
        self.segments().get_slice(offset, len)
    }

    /// Gets the TLS module ID of the ELF object
    #[inline]
    pub fn tls_mod_id(&self) -> Option<TlsModuleId> {
        self.inner.tls.mod_id()
    }

    /// Gets the TLS thread pointer offset of the ELF object
    #[inline]
    pub fn tls_tp_offset(&self) -> Option<TlsTpOffset> {
        self.inner.tls.tp_offset()
    }

    #[inline]
    pub(crate) fn tls_get_addr(&self) -> RelocAddr {
        self.inner.tls.tls_get_addr()
    }

    /// Set the TLS descriptor arguments (used for dynamic relocation)
    /// # Safety
    /// This should only be called during the relocation process
    pub(crate) unsafe fn set_tls_desc_args(&self, args: TlsDescArgs) {
        let inner = Arc::as_ptr(&self.inner) as *mut CoreInner<D, Arch>;
        unsafe {
            (*inner).tls.set_desc_args(args);
        }
    }

    /// Set the finalization handler used after emulated initialization.
    ///
    /// # Safety
    /// This should only be called during relocation before the loaded image is
    /// published to callers.
    pub(crate) unsafe fn set_emu_fini(&self, emu: Arc<dyn Emulator<Arch>>) {
        let inner = Arc::as_ptr(&self.inner) as *mut CoreInner<D, Arch>;
        unsafe {
            (*inner).fini_handler = CoreFiniHandler::Emu(emu);
        }
    }

    /// Creates an ElfCore from raw components
    pub(super) unsafe fn from_raw(
        path: PathBuf,
        base: usize,
        dynamic_ptr: *const ElfDyn<Arch::Layout>,
        phdrs: Vec<ElfPhdr<Arch::Layout>>,
        eh_frame_hdr: Option<NonNull<u8>>,
        mut segments: ElfSegments,
        tls_mod_id: Option<TlsModuleId>,
        tls_tp_offset: Option<TlsTpOffset>,
        tls_get_addr: RelocAddr,
        tls_unregister: fn(TlsModuleId),
        user_data: D,
    ) -> Result<Self> {
        if dynamic_ptr.is_null() {
            return Err(ParsePhdrError::MissingDynamicSection.into());
        }

        segments.set_base(base);
        let dynamic = ElfDynamic::<Arch>::new(dynamic_ptr, &segments)?;
        let symtab = SymbolTable::from_dynamic(&dynamic);
        let soname = dynamic
            .soname_off
            .map(|soname_off| symtab.strtab().get_str(soname_off.get()));
        Ok(Self {
            inner: Arc::new(CoreInner {
                path,
                is_init: AtomicBool::new(true),
                symtab,
                dynamic_info: Some(Arc::new(DynamicInfo {
                    eh_frame_hdr,
                    dynamic_ptr: unsafe { NonNull::new_unchecked(dynamic_ptr.cast_mut()) },
                    phdrs: ElfPhdrs::Vec(phdrs),
                    soname,
                    #[cfg(feature = "lazy-binding")]
                    lazy: crate::image::LazyBindingInfo::new(dynamic.pltrel),
                })),
                tls: CoreTlsState::new(tls_mod_id, tls_tp_offset, tls_get_addr, tls_unregister),
                segments,
                fini: Lifecycle::empty(),
                fini_handler: CoreFiniHandler::Native(Arc::new(Box::new(|_: &Lifecycle<'_>| {}))),
                user_data,
            }),
        })
    }
}

impl<D, Arch: RelocationArch> Debug for ElfCore<D, Arch> {
    /// Formats the ElfCore for debugging purposes.
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("ElfCore")
            .field("path", &self.inner.path)
            .field("base", &format_args!("0x{:x}", self.base()))
            .field("mapped_len", &self.mapped_len())
            .field("tls_mod_id", &self.tls_mod_id())
            .finish()
    }
}

impl<D, Arch> Module<Arch> for ElfCore<D, Arch>
where
    D: 'static,
    Arch: RelocationArch,
{
    #[inline]
    fn as_any(&self) -> &dyn Any {
        self
    }

    #[inline]
    fn name(&self) -> &str {
        ElfCore::name(self)
    }

    #[inline]
    fn soname(&self) -> Option<&str> {
        ElfCore::soname(self)
    }

    #[inline]
    fn lookup_symbol<'source>(
        &'source self,
        symbol: &SymbolInfo<'_>,
        precompute: &mut PreCompute,
    ) -> Option<&'source ElfSymbol<Arch::Layout>> {
        self.symtab().lookup_filter(symbol, precompute)
    }

    #[inline]
    fn base_addr(&self) -> usize {
        self.base()
    }

    #[inline]
    fn segment_slice(&self, offset: usize, len: usize) -> Option<&[u8]> {
        Some(ElfCore::segment_slice(self, offset, len))
    }

    #[inline]
    fn tls_mod_id(&self) -> Option<TlsModuleId> {
        ElfCore::tls_mod_id(self)
    }

    #[inline]
    fn tls_tp_offset(&self) -> Option<TlsTpOffset> {
        ElfCore::tls_tp_offset(self)
    }
}