elf_loader/
lib.rs

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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
//! # elf_loader
//! A `lightweight`, `extensible`, and `high-performance` library for loading ELF files.
//! ## Usage
//! It implements the general steps for loading ELF files and leaves extension interfaces,
//! allowing users to implement their own customized loaders.
//! ## Example
//! This repository provides an example of a [mini-loader](https://github.com/weizhiao/elf_loader/tree/main/mini-loader) implemented using `elf_loader`.
//! The miniloader can load PIE files and currently only supports `x86_64`.
#![cfg_attr(not(feature = "std"), no_std)]
extern crate alloc;

#[cfg(not(any(
    target_arch = "x86_64",
    target_arch = "aarch64",
    target_arch = "riscv64",
)))]
compile_error!("unsupport arch");

pub mod arch;
pub mod dynamic;
mod loader;
pub mod mmap;
pub mod object;
pub mod relocation;
pub mod segment;
mod symbol;
#[cfg(feature = "version")]
mod version;

use alloc::{
    boxed::Box,
    ffi::CString,
    string::{String, ToString},
    sync::{Arc, Weak},
    vec::Vec,
};
use arch::{Dyn, ElfRela, Phdr};
use core::{
    any::Any,
    ffi::{c_void, CStr},
    fmt::{Debug, Display},
    marker::PhantomData,
    ops,
};
use dynamic::ElfDynamic;

use object::*;
use relocation::{ElfRelocation, GLOBAL_SCOPE};
use segment::{ELFRelro, ElfSegments};
use symbol::{SymbolInfo, SymbolTable};

pub use elf::abi;
pub use loader::Loader;

impl Debug for ElfDylib {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("ElfLibrary")
            .field("name", &self.core.inner.name)
            .field("needed_libs", &self.core.inner.needed_libs)
            .finish()
    }
}

struct DataItem {
    key: u8,
    value: Option<Box<dyn Any>>,
}

/// User-defined data associated with the loaded ELF file
pub struct UserData {
    data: Vec<DataItem>,
}

impl UserData {
    #[inline]
    pub const fn empty() -> Self {
        Self { data: Vec::new() }
    }

    #[inline]
    pub fn insert(&mut self, key: u8, value: Box<dyn Any>) -> Option<Box<dyn Any>> {
        for item in self.data.iter_mut() {
            if item.key == key {
                let old = core::mem::take(&mut item.value);
                item.value = Some(value);
                return old;
            }
        }
        self.data.push(DataItem {
            key,
            value: Some(value),
        });
        None
    }

    #[inline]
    pub fn get(&self, key: u8) -> Option<&Box<dyn Any>> {
        self.data.iter().find_map(|item| {
            if item.key == key {
                return item.value.as_ref();
            }
            None
        })
    }
}

/// An unrelocated dynamic library
pub struct ElfDylib {
    /// entry
    entry: usize,
    /// .got.plt
    got: Option<*mut usize>,
    /// rela.dyn and rela.plt
    relocation: ElfRelocation,
    /// GNU_RELRO segment
    relro: Option<ELFRelro>,
    /// .init
    init_fn: Option<extern "C" fn()>,
    /// .init_array
    init_array_fn: Option<&'static [extern "C" fn()]>,
    /// lazy binding
    lazy: bool,
    /// DT_RPATH
    rpath: Option<&'static str>,
    /// DT_RUNPATH
    runpath: Option<&'static str>,
    /// core component
    core: CoreComponent,
}

impl ElfDylib {
    /// Gets the entry point of the elf object.
    #[inline]
    pub fn entry(&self) -> usize {
        self.entry + self.base()
    }

    /// Gets phdrs of the elf object.
    #[inline]
    pub fn phdrs(&self) -> &[Phdr] {
        &self.core.inner.phdrs
    }

    /// Gets the C-style name of the elf object.
    #[inline]
    pub fn cname(&self) -> &CStr {
        self.core.cname()
    }

    /// Gets the name of the elf object.
    #[inline]
    pub fn name(&self) -> &str {
        self.core.name()
    }

    /// Gets the address of the dynamic section.
    #[inline]
    pub fn dynamic(&self) -> *const Dyn {
        self.core.dynamic()
    }

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

    /// Gets the memory length of the elf object map.
    #[inline]
    pub fn map_len(&self) -> usize {
        self.core.map_len()
    }

    /// Gets the symbol table.
    #[inline]
    pub fn symtab(&self) -> &SymbolTable {
        &self.core.inner.symbols
    }

    /// Gets rela.dyn section content
    #[inline]
    pub fn dyn_relocation(&self) -> Option<&[ElfRela]> {
        self.relocation.dynrel()
    }

    /// Gets rela.plt section content
    #[inline]
    pub fn plt_relocation(&self) -> Option<&[ElfRela]> {
        self.relocation.pltrel()
    }

    /// Gets the core component reference of the elf object
    /// # Safety
    /// The current elf object has not yet been relocated, so it is dangerous to use this
    /// function to get `CoreComponent` in the elf object.
    #[inline]
    pub unsafe fn core_component_ref(&self) -> &CoreComponent {
        &self.core
    }

    /// Gets the core component of the elf object
    /// # Safety
    /// The current elf object has not yet been relocated, so it is dangerous to use this
    /// function to get `CoreComponent` in the elf object.
    #[inline]
    pub unsafe fn core_component(&self) -> CoreComponent {
        self.core.clone()
    }

    /// Gets the name of the elf object
    #[inline]
    pub fn needed_libs(&self) -> &[&'static str] {
        self.core.needed_libs()
    }

    /// Gets user data from the elf object.
    #[inline]
    pub fn user_data(&self) -> &UserData {
        self.core.user_data()
    }

    /// Whether lazy binding is enabled for the current dynamic library.
    #[inline]
    pub fn is_lazy(&self) -> bool {
        self.lazy
    }

    /// Gets the DT_RPATH value.
    #[inline]
    pub fn rpath(&self) -> Option<&str> {
        self.rpath
    }

    /// Gets the DT_RUNPATH value.
    #[inline]
    pub fn runpath(&self) -> Option<&str> {
        self.runpath
    }
}

struct CoreComponentInner {
    /// file name
    name: CString,
    /// elf symbols
    symbols: SymbolTable,
    /// dynamic
    dynamic: *const Dyn,
    /// rela.plt
    pltrel: *const ElfRela,
    /// phdrs
    phdrs: &'static [Phdr],
    /// .fini
    fini_fn: Option<extern "C" fn()>,
    /// .fini_array
    fini_array_fn: Option<&'static [extern "C" fn()]>,
    /// needed libs' name
    needed_libs: Box<[&'static str]>,
    /// user data
    user_data: UserData,
    /// lazy binding scope
    lazy_scope: Option<Box<dyn Fn(&str) -> Option<*const ()> + 'static>>,
    /// semgents
    segments: ElfSegments,
}

impl CoreComponentInner {
    #[inline]
    unsafe fn call_fini(&self) {
        if let Some(f) = self.fini_fn {
            f();
        }

        if let Some(array) = self.fini_array_fn {
            for f in array {
                f();
            }
        }
    }

    #[inline]
    unsafe fn get<'lib, T>(&'lib self, name: &str) -> Option<Symbol<'lib, T>> {
        self.symbols
            .lookup_filter(&SymbolInfo::new(name))
            .map(|sym| Symbol {
                ptr: (self.segments.base() + sym.st_value as usize) as _,
                pd: PhantomData,
            })
    }
}

/// `CoreComponentRef` is a version of `CoreComponent` that holds a non-owning reference to the managed allocation.
pub struct CoreComponentRef {
    inner: Weak<CoreComponentInner>,
}

impl CoreComponentRef {
    /// Attempts to upgrade the Weak pointer to an Arc
    pub fn upgrade(&self) -> Option<CoreComponent> {
        self.inner.upgrade().map(|inner| CoreComponent { inner })
    }
}

/// The core part of an elf object
#[derive(Clone)]
pub struct CoreComponent {
    inner: Arc<CoreComponentInner>,
}

unsafe impl Sync for CoreComponent {}
unsafe impl Send for CoreComponent {}

impl CoreComponent {
    /// Creates a new Weak pointer to this allocation.
    pub fn downgrade(&self) -> CoreComponentRef {
        CoreComponentRef {
            inner: Arc::downgrade(&self.inner),
        }
    }

    /// Gets user data from the elf object.
    #[inline]
    pub fn user_data(&self) -> &UserData {
        &self.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)
    }

    /// Gets the name of the elf object.
    #[inline]
    pub fn name(&self) -> &str {
        self.inner.name.to_str().unwrap()
    }

    /// Gets the C-style name of the elf object.
    #[inline]
    pub fn cname(&self) -> &CStr {
        &self.inner.name
    }

    /// Gets the short name of the elf object.
    #[inline]
    pub fn shortname(&self) -> &str {
        self.name().split('/').last().unwrap()
    }

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

    /// Gets the memory length of the elf object map.
    #[inline]
    pub fn map_len(&self) -> usize {
        self.inner.segments.len()
    }

    /// Gets the program headers of the elf object.
    #[inline]
    pub fn phdrs(&self) -> &[Phdr] {
        &self.inner.phdrs
    }

    /// Gets the address of the dynamic section.
    #[inline]
    pub fn dynamic(&self) -> *const Dyn {
        self.inner.dynamic
    }

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

    /// Gets the needed libs' name of the elf object.
    #[inline]
    pub fn needed_libs(&self) -> &[&'static str] {
        &self.inner.needed_libs
    }

    /// Call the fini function, usually when the elf object is destroyed.
    #[inline]
    pub unsafe fn call_fini(&self) {
        self.inner.call_fini();
    }

    unsafe fn from_raw(
        name: CString,
        base: usize,
        dynamic: ElfDynamic,
        phdrs: &'static [Phdr],
        mut segments: ElfSegments,
        user_data: UserData,
    ) -> Self {
        segments.offset = (segments.memory.as_ptr() as usize).wrapping_sub(base);
        Self {
            inner: Arc::new(CoreComponentInner {
                name,
                symbols: SymbolTable::new(&dynamic),
                pltrel: core::ptr::null(),
                dynamic: dynamic.dyn_ptr,
                phdrs,
                segments,
                fini_fn: None,
                fini_array_fn: None,
                needed_libs: Box::new([]),
                user_data,
                lazy_scope: None,
            }),
        }
    }

    pub unsafe fn get<'lib, T>(&'lib self, name: &str) -> Option<Symbol<'lib, T>> {
        self.inner.get(name)
    }

    #[cfg(feature = "version")]
    pub unsafe fn get_version<'lib, T>(
        &'lib self,
        name: &str,
        version: &str,
    ) -> Option<Symbol<'lib, T>> {
        self.inner
            .symbols
            .lookup_filter(&SymbolInfo::new_with_version(name, version))
            .map(|sym| Symbol {
                ptr: (self.base() + sym.st_value as usize) as _,
                pd: PhantomData,
            })
    }
}

impl Debug for CoreComponent {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("Dylib")
            .field("name", &self.inner.name)
            .finish()
    }
}

/// A symbol from elf object
#[derive(Debug, Clone)]
pub struct Symbol<'lib, T: 'lib> {
    ptr: *mut (),
    pd: PhantomData<&'lib T>,
}

impl<'lib, T> ops::Deref for Symbol<'lib, T> {
    type Target = T;
    fn deref(&self) -> &T {
        unsafe { &*(&self.ptr as *const *mut _ as *const T) }
    }
}

impl<'lib, T> Symbol<'lib, T> {
    pub fn into_raw(self) -> *const () {
        self.ptr
    }
}

/// A dynamic library that has been relocated
#[derive(Clone)]
pub struct RelocatedDylib<'scope> {
    core: CoreComponent,
    _marker: PhantomData<&'scope ()>,
}

impl<'scope> Debug for RelocatedDylib<'scope> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        self.core.fmt(f)
    }
}

impl<'scope> RelocatedDylib<'scope> {
    /// Gets the name of the elf object.
    #[inline]
    pub fn needed_libs(&self) -> &[&'static str] {
        self.core.needed_libs()
    }

    /// Gets the name of the elf object.
    #[inline]
    pub fn name(&self) -> &str {
        self.core.name()
    }

    /// Call the fini function, usually when the elf object is destroyed.
    #[inline]
    pub unsafe fn call_fini(&self) {
        self.core.call_fini();
    }

    /// Gets the C-style name of the elf object.
    #[inline]
    pub fn cname(&self) -> &CStr {
        &self.core.cname()
    }

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

    /// Gets the user data of the elf object.
    #[inline]
    pub fn user_data(&self) -> &UserData {
        &self.core.inner.user_data
    }

    /// Gets the program headers of the elf object.
    #[inline]
    pub fn phdrs(&self) -> &[Phdr] {
        &self.core.phdrs()
    }

    #[inline]
    pub fn into_ptr(self) -> *const c_void {
        Arc::into_raw(self.core.inner) as _
    }

    #[inline]
    pub fn as_ptr(&self) -> *const c_void {
        Arc::as_ptr(&self.core.inner).cast()
    }

    /// Gets the short name of the elf object.
    #[inline]
    pub fn shortname(&self) -> &str {
        self.core.shortname()
    }

    /// Gets the core component of the elf object.
    #[inline]
    pub fn into_core_component(self) -> CoreComponent {
        self.core
    }

    /// Gets the core component of the elf object.
    #[inline]
    pub fn core_component(&self) -> &CoreComponent {
        &self.core
    }

    #[inline]
    pub unsafe fn from_ptr(raw: *const c_void) -> Self {
        Self {
            core: CoreComponent {
                inner: Arc::from_raw(raw as *const CoreComponentInner),
            },
            _marker: PhantomData,
        }
    }

    #[inline]
    pub unsafe fn new_uncheck(
        name: CString,
        base: usize,
        dynamic: ElfDynamic,
        phdrs: &'static [Phdr],
        segments: ElfSegments,
        user_data: UserData,
    ) -> Self {
        Self {
            core: CoreComponent::from_raw(name, base, dynamic, phdrs, segments, user_data),
            _marker: PhantomData,
        }
    }

    /// Gets a pointer to a function or static variable by symbol name.
    ///
    /// The symbol is interpreted as-is; no mangling is done. This means that symbols like `x::y` are
    /// most likely invalid.
    ///
    /// # Safety
    /// Users of this API must specify the correct type of the function or variable loaded.
    ///
    /// # Examples
    /// ```no_run
    /// unsafe {
    ///     let awesome_function: Symbol<unsafe extern fn(f64) -> f64> =
    ///         lib.get("awesome_function").unwrap();
    ///     awesome_function(0.42);
    /// }
    /// ```
    /// A static variable may also be loaded and inspected:
    /// ```no_run
    /// unsafe {
    ///     let awesome_variable: Symbol<*mut f64> = lib.get("awesome_variable").unwrap();
    ///     **awesome_variable = 42.0;
    /// };
    /// ```
    #[inline]
    pub unsafe fn get<'lib, T>(&'lib self, name: &str) -> Option<Symbol<'lib, T>> {
        self.core.get(name)
    }

    /// Load a versioned symbol from the elf object.
    ///
    /// # Examples
    /// ```
    /// let symbol = unsafe { lib.get_version::<fn()>>("function_name", "1.0").unwrap() };
    /// ```
    #[cfg(feature = "version")]
    #[inline]
    pub unsafe fn get_version<'lib, T>(
        &'lib self,
        name: &str,
        version: &str,
    ) -> Option<Symbol<'lib, T>> {
        self.core.get_version(name, version)
    }
}

/// elf_loader error types
#[derive(Debug)]
pub enum Error {
    /// An error occurred while opening or reading or writing elf files.
    #[cfg(feature = "std")]
    IOError { err: std::io::Error },
    /// An error occurred while memory mapping.
    MmapError { msg: String },
    /// An error occurred during dynamic library relocation.
    RelocateError { msg: String },
    /// An error occurred while parsing dynamic section.
    ParseDynamicError { msg: &'static str },
    /// An error occurred while parsing elf header.
    ParseEhdrError { msg: String },
    /// An error occurred while parsing program header.
    ParsePhdrError { msg: String },
}

impl Display for Error {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            #[cfg(feature = "std")]
            Error::IOError { err } => write!(f, "{err}"),
            Error::MmapError { msg } => write!(f, "{msg}"),
            Error::RelocateError { msg } => write!(f, "{msg}"),
            Error::ParseDynamicError { msg } => write!(f, "{msg}"),
            Error::ParseEhdrError { msg } => write!(f, "{msg}"),
            Error::ParsePhdrError { msg } => write!(f, "{msg}"),
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Error::IOError { err } => Some(err),
            _ => None,
        }
    }
}

#[cfg(feature = "std")]
impl From<std::io::Error> for Error {
    #[cold]
    fn from(value: std::io::Error) -> Self {
        Error::IOError { err: value }
    }
}

#[cold]
#[inline(never)]
fn relocate_error(msg: impl ToString) -> Error {
    Error::RelocateError {
        msg: msg.to_string(),
    }
}

#[cold]
#[inline(never)]
fn parse_dynamic_error(msg: &'static str) -> Error {
    Error::ParseDynamicError { msg }
}

#[cold]
#[inline(never)]
fn parse_ehdr_error(msg: impl ToString) -> Error {
    Error::ParseEhdrError {
        msg: msg.to_string(),
    }
}

#[cold]
#[inline(never)]
pub fn parse_phdr_error(msg: impl ToString) -> Error {
    Error::ParsePhdrError {
        msg: msg.to_string(),
    }
}

/// Set the global scope, lazy binding will look for the symbol in the global scope.
///
/// # Safety
/// This function is marked as unsafe because it directly interacts with raw pointers,
/// and it also requires the user to ensure thread safety.  
/// It is the caller's responsibility to ensure that the provided function `f` behaves correctly.
///
/// # Parameters
/// - `f`: A function that takes a symbol name as a parameter and returns an optional raw pointer.
///        If the symbol is found in the global scope, the function should return `Some(raw_pointer)`,
///        otherwise, it should return `None`.
///
/// # Return
/// This function does not return a value. It sets the global scope for lazy binding.
pub unsafe fn set_global_scope(f: fn(&str) -> Option<*const ()>) {
    GLOBAL_SCOPE.store(f as usize, core::sync::atomic::Ordering::Release);
}

pub type Result<T> = core::result::Result<T, Error>;