Skip to main content

Crate elf_loader

Crate elf_loader 

Source
Expand description

Relink is a no_std-friendly ELF loader and runtime linker for Rust. It maps ELF images from files or memory, performs relocations at runtime, and exposes typed symbol lookups with Rust lifetimes.

§Start with Loader

Bind a runtime domain with Loader::run before loading an image.

Typed symbols borrow their loaded image. Use RelocatorRun::with_modules or LocalScope to resolve references against other ELF images and synthetic modules.

§Example

use elf_loader::{
    Loader, Relocator, Result,
    AddressSpaceId, Domain,
    image::{SyntheticSymbol, SyntheticModule},
};

extern "C" fn host_double(value: i32) -> i32 {
    value * 2
}

fn main() -> Result<()> {
    let domain = Domain::native(AddressSpaceId::PROCESS);
    let host = SyntheticModule::new(
        &domain,
        "__host",
        [SyntheticSymbol::function(c"host_double", host_double as *const ())],
    );

    let lib = Relocator::new()
        .run(Loader::new().run(domain).load_dylib("path/to/plugin.so")?)
        .with_modules([host])?
        .relocate()?;

    let run = unsafe {
        lib.get::<extern "C" fn(i32) -> i32>("run")?
            .expect("symbol `run` not found")
    };
    assert_eq!(run(21), 42);
    Ok(())
}

§Loading Dependencies With Linker

Use Linker::run and LinkerRun::load when you want a reusable LinkContext and resolver-driven DT_NEEDED dependency loading. The built-in linker::SearchPathResolver covers the common filesystem search-path case; implement linker::KeyResolver when dependencies come from memory, package stores, or another registry.

use elf_loader::{
    LinkContext, Linker, Result,
    input::PathBuf,
    linker::SearchPathResolver,
};

fn main() -> Result<()> {
    let root = PathBuf::from("path/to/plugin.so");
    let mut context = LinkContext::for_process();
    let mut resolver = SearchPathResolver::new();
    resolver.push_rpath();
    resolver.push_runpath();

    let loaded = Linker::new()
        .with_resolver(resolver)
        .run()
        .load(&mut context, root)?;

    let run = unsafe {
        context
            .module(loaded.root())?
            .get::<extern "C" fn() -> i32>("run")?
            .expect("symbol `run` not found")
    };
    let _ = run();
    drop(loaded.release(&mut context)?);

    Ok(())
}

§Observer Hooks

Observers are attached to a single loader or linker run, so reusable Loader and Linker configuration can stay immutable while each run decides which events to inspect or override.

use elf_loader::{
    Loader, Result,
    arch::NativeArch,
    observer::{BeforeLoadEvent, LoadObserver},
    relocation::RelocationArch,
    AddressSpaceId, Domain,
};

struct TraceLoads;

impl LoadObserver for TraceLoads {
    fn on_before_load(
        &mut self,
        event: BeforeLoadEvent<'_, (), <NativeArch as RelocationArch>::Layout>,
    ) -> Result<()> {
        let _path = event.path();
        let _is_dynamic = event.is_dynamic();
        Ok(())
    }
}

fn main() -> Result<()> {
    let _raw = Loader::new()
        .run(Domain::native(AddressSpaceId::PROCESS))
        .with_observer(TraceLoads)
        .load_dylib("path/to/lib.so")?;

    Ok(())
}

§Feature Flags

The default full feature enables std, object, and lazy-binding. Disable default features for no_std builds. use-syscall and std are mutually exclusive.

  • TLS relocation handling is always available. Pass a Domain to Loader::run or LinkContext::new. Domains start with TLS disabled; use Domain::with_tls to enable it.
  • lazy-binding: enables the built-in NativeLazyBinder. Custom lazy::LazyBinder implementations and RelocatorRun::lazy are always available; Relocator::new remains eager until a binder is configured.
  • object: enables LoaderRun::load_object and relocatable object (ET_REL) loading.
  • version: enables version-aware get_version symbol lookups.
  • std: enables standard-library integration and host-library imports on Linux/glibc.
  • log, portable-atomic, and use-syscall: optional integrations for diagnostics and specialized targets.

§Platforms and Examples

  • The examples directory covers loading from memory, LinkerRun::load, scan-first linking, observer hooks, and object loading.
  • The crate currently targets x86_64, x86, aarch64, arm, riscv64, riscv32, and loongarch64.
  • Little-endian Xtensa ELF32 images have basic cross-architecture dynamic relocation support; lazy binding, native runtime hooks, and TLS relocation support are pending.
  • Relocatable object support is currently centered on x86_64 and riscv64.

Re-exports§

pub use error::Error;
pub use image::ElfModule;
pub use image::GlobalScope;
pub use image::LocalScope;
pub use image::Module;
pub use image::ModuleInstanceId;
pub use image::ModuleScope;
pub use image::ModuleSearch;
pub use image::ModuleState;
pub use image::SearchPathPool;
pub use input::ModuleSourceId;
pub use linker::GraphModule;
pub use linker::LinkContext;
pub use linker::Linker;
pub use linker::LinkerRun;
pub use linker::ModuleKey;
pub use loader::Loader;
pub use loader::LoaderRun;
pub use relocation::Relocator;
pub use relocation::RelocatorRun;
pub use runtime::AddressSpaceId;
pub use runtime::Domain;
pub use runtime::DomainId;

Modules§

arch
Architecture-specific definitions and relocation logic.
elf
ELF (Executable and Linkable Format) parsing and data structures.
error
Error types returned by Relink APIs.
hostGNU and Linux and std
Import libraries managed by the Linux/glibc loader into a Relink scope.
image
Raw and relocated ELF images, synthetic modules, and symbol scopes.
input
ELF input traits and built-in data sources.
lazy
Lazy PLT binding support.
linker
Loads ELF dependency graphs into a LinkContext.
loader
Loading entry points and customization hooks.
memory
Virtual memory and mapped image abstractions.
objectobject
Relocatable-object loading, layout, and export helpers.
observer
Observer traits and event payloads for load and relocation hooks.
os
Memory mapping, page protection, and platform backends.
relocation
Relocation, symbol lookup, and binding policy.
runtime
Runtime execution abstractions for mapped images.
tls
TLS registration and per-thread storage.

Traits§

ByteRepr
Types that can be safely viewed from arbitrary bytes.

Type Aliases§

Result
Result returned by loader and linker operations.