elf_loader 0.16.0

A no_std-friendly ELF loader and runtime 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
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
//! Executable image types.
//!
//! Use [`RawExec`] for an executable that has been mapped but not yet relocated,
//! and [`LoadedExec`] for the final executable form produced by relocation.

use crate::sync::Arc;
use crate::{
    Result,
    arch::NativeArch,
    elf::ElfPhdr,
    image::{LoadedCore, ModuleTls, RawDynamic},
    input::{Path, PathBuf},
    lazy::{LazyBinder, SupportLazy},
    loader::ImageBuilder,
    memory::{HostRegion, RegionAccess, VmAddr, VmOffset},
    observer::RelocationObserver,
    relocation::{Relocatable, RelocateArgs, RelocationArch},
    segment::ElfSegments,
    tls::{
        TlsImageProvider, TlsImageSource, TlsModuleId, TlsResolver, TlsTemplate, TlsTpOffset,
        tls_image_provider_handle,
    },
};
use alloc::vec::Vec;
use core::fmt::Debug;

/// A mapped static executable.
///
/// Static executables do not have `PT_DYNAMIC`, so they are ready to run after
/// mapping and any static TLS setup performed by the loader.
pub struct StaticExec<D, Arch: RelocationArch = NativeArch, R: RegionAccess = HostRegion> {
    inner: Arc<StaticExecInner<D, Arch, R>>,
}

// Keep this impl manual so cloning a static executable handle does not require D, Arch, or R to be Clone.
impl<D, Arch: RelocationArch, R: RegionAccess> Clone for StaticExec<D, Arch, R> {
    #[inline]
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
        }
    }
}

impl<D, Arch: RelocationArch, R: RegionAccess> Debug for StaticExec<D, Arch, R> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("StaticExec")
            .field("path", &self.inner.path)
            .finish()
    }
}

impl<D: 'static, Arch: RelocationArch, R: RegionAccess> StaticExec<D, Arch, R> {
    /// Returns the source path or caller-provided path identifier.
    pub fn path(&self) -> &Path {
        self.inner.path.as_path()
    }

    /// Returns the final path component.
    pub fn name(&self) -> &str {
        self.path().file_name()
    }

    /// Returns the executable entry point address.
    pub fn entry(&self) -> usize {
        self.entry_addr().get()
    }

    pub(crate) fn entry_addr(&self) -> VmAddr {
        self.inner.entry
    }

    /// Returns TLS metadata associated with this image.
    pub fn tls(&self) -> ModuleTls {
        ModuleTls::new(self.inner.tls_mod_id, self.inner.tls_tp_offset)
    }

    /// Returns user data associated with the image.
    pub fn user_data(&self) -> &D {
        &self.inner.user_data
    }

    /// Returns program headers when they were retained by the loader.
    pub fn phdrs(&self) -> Option<&[ElfPhdr<Arch::Layout>]> {
        self.inner.phdrs.as_deref()
    }

    /// Returns the runtime base address.
    pub fn base(&self) -> VmAddr {
        self.inner.segments.base()
    }

    /// Returns the mapped segments owned by this executable.
    pub fn segments(&self) -> &ElfSegments<R> {
        &self.inner.segments
    }
}

struct StaticExecInner<D, Arch: RelocationArch = NativeArch, R: RegionAccess = HostRegion> {
    /// Loader source path or caller-provided source identifier.
    path: PathBuf,

    /// Entry point of the executable
    entry: VmAddr,

    /// User-defined data
    user_data: D,

    /// Memory segments
    segments: ElfSegments<R>,

    /// Program headers
    phdrs: Option<Vec<ElfPhdr<Arch::Layout>>>,

    /// TLS module ID
    tls_mod_id: Option<TlsModuleId>,

    /// TLS thread pointer offset
    tls_tp_offset: Option<TlsTpOffset>,

    /// Keeps the static TLS image source alive while the executable is alive.
    _tls_image: Option<Arc<StaticTlsImage>>,
}

struct StaticTlsImage {
    template: TlsTemplate<'static>,
}

impl TlsImageProvider for StaticTlsImage {
    fn with_tls_template(&self, f: &mut dyn FnMut(TlsTemplate<'_>) -> Result<()>) -> Result<()> {
        f(self.template)
    }
}

impl<D: 'static, Arch: RelocationArch, R: RegionAccess, Tls: TlsResolver<Arch>> Relocatable<D>
    for RawExec<D, Arch, R, Tls>
{
    type Output = LoadedExec<D, Arch, R, Tls>;
    type Arch = Arch;
    type Tls = Tls;

    fn relocate<Obs, Binder>(
        self,
        args: RelocateArgs<'_, Arch, Tls, Obs, Binder>,
    ) -> Result<Self::Output>
    where
        Obs: RelocationObserver<Arch> + ?Sized,
        Binder: LazyBinder<Arch> + ?Sized,
    {
        match self {
            RawExec::Dynamic(image) => {
                let entry = image.entry_addr();
                let inner = Relocatable::relocate(image, args)?;
                Ok(LoadedExec {
                    entry,
                    inner: LoadedExecInner::Dynamic(inner),
                })
            }
            RawExec::Static(image) => Ok(LoadedExec {
                entry: image.entry_addr(),
                inner: LoadedExecInner::Static(image),
            }),
        }
    }
}

/// A mapped but unrelocated executable image.
///
/// Values of this type are returned by [`crate::Loader::load_exec`]. They may
/// represent either a dynamic executable that still needs relocation or a
/// static executable that is already ready to run.
///
/// The optional `Arch` type parameter is forwarded to the underlying
/// [`RawDynamic`] for dynamic executables. Static executables ignore it but
/// still carry it so that downstream APIs can treat both variants uniformly.
///
/// The dynamic variant intentionally stays inline to avoid changing the public
/// enum shape or adding an allocation to executable loading.
#[allow(clippy::large_enum_variant)]
pub enum RawExec<
    D,
    Arch = crate::arch::NativeArch,
    R: RegionAccess = HostRegion,
    Tls: TlsResolver<Arch> = (),
> where
    D: 'static,
    Arch: RelocationArch,
{
    /// A dynamically linked executable with `PT_DYNAMIC`.
    Dynamic(RawDynamic<D, Arch, R, Tls>),

    /// A statically linked executable without `PT_DYNAMIC`.
    Static(StaticExec<D, Arch, R>),
}

impl<D, Arch: RelocationArch, R: RegionAccess, Tls: TlsResolver<Arch>> Debug
    for RawExec<D, Arch, R, Tls>
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("RawExec")
            .field("name", &self.name())
            .finish()
    }
}

impl<D: 'static, Arch: RelocationArch, R: RegionAccess, Tls: TlsResolver<Arch>> SupportLazy
    for RawExec<D, Arch, R, Tls>
{
}

impl<D: 'static, Arch: RelocationArch, R: RegionAccess, Tls: TlsResolver<Arch>>
    RawExec<D, Arch, R, Tls>
{
    /// Returns the loader source path or caller-provided source identifier.
    pub fn path(&self) -> &Path {
        match self {
            RawExec::Dynamic(image) => image.path(),
            RawExec::Static(image) => image.path(),
        }
    }

    /// Returns the executable identity used for diagnostics.
    pub fn name(&self) -> &str {
        match self {
            RawExec::Dynamic(image) => image.name(),
            RawExec::Static(image) => image.name(),
        }
    }

    /// Returns the entry point of the executable.
    pub fn entry(&self) -> usize {
        match self {
            RawExec::Dynamic(image) => image.entry(),
            RawExec::Static(image) => image.entry(),
        }
    }

    /// Returns TLS metadata associated with this executable.
    pub fn tls(&self) -> ModuleTls {
        match self {
            RawExec::Dynamic(image) => image.tls(),
            RawExec::Static(image) => image.tls(),
        }
    }

    /// Returns the PT_INTERP value.
    pub fn interp(&self) -> Option<&str> {
        match self {
            RawExec::Dynamic(image) => image.interp(),
            RawExec::Static(_) => None,
        }
    }

    /// Returns the list of needed library names from the dynamic section.
    pub fn needed_libs(&self) -> &[&str] {
        match self {
            RawExec::Dynamic(image) => image.needed_libs(),
            RawExec::Static(_) => &[],
        }
    }

    /// Returns the program headers of the executable.
    pub fn phdrs(&self) -> Option<&[ElfPhdr<Arch::Layout>]> {
        match self {
            RawExec::Dynamic(image) => Some(image.phdrs()),
            RawExec::Static(image) => image.phdrs(),
        }
    }

    /// Returns whether `addr` is inside one of this executable's mapped slices.
    pub fn contains_addr(&self, addr: VmAddr) -> bool {
        match self {
            RawExec::Dynamic(image) => image.segments().contains_addr(addr),
            RawExec::Static(image) => image.segments().contains_addr(addr),
        }
    }

    /// Returns the runtime base address.
    pub fn base(&self) -> VmAddr {
        match self {
            RawExec::Dynamic(image) => image.base(),
            RawExec::Static(image) => image.base(),
        }
    }
}

/// A relocated executable image.
///
/// Dynamic executables retain access to their underlying [`LoadedCore`], while
/// static executables expose a smaller set of metadata directly on this wrapper.
#[derive(Debug)]
pub struct LoadedExec<
    D: 'static,
    Arch: RelocationArch = NativeArch,
    R: RegionAccess = HostRegion,
    Tls: TlsResolver<Arch> = (),
> {
    /// Entry point of the executable.
    entry: VmAddr,
    /// The relocated ELF object.
    inner: LoadedExecInner<D, Arch, R, Tls>,
}

#[derive(Debug)]
enum LoadedExecInner<
    D: 'static,
    Arch: RelocationArch = NativeArch,
    R: RegionAccess = HostRegion,
    Tls: TlsResolver<Arch> = (),
> {
    Dynamic(LoadedCore<D, Arch, R, Tls>),
    Static(StaticExec<D, Arch, R>),
}

// Keep this impl manual so cloning a loaded executable does not require D, Arch, or R to be Clone.
impl<D: 'static, Arch: RelocationArch, R: RegionAccess, Tls: TlsResolver<Arch>> Clone
    for LoadedExec<D, Arch, R, Tls>
{
    #[inline]
    fn clone(&self) -> Self {
        Self {
            entry: self.entry,
            inner: self.inner.clone(),
        }
    }
}

impl<D: 'static, Arch: RelocationArch, R: RegionAccess, Tls: TlsResolver<Arch>> Clone
    for LoadedExecInner<D, Arch, R, Tls>
{
    #[inline]
    fn clone(&self) -> Self {
        match self {
            Self::Dynamic(module) => Self::Dynamic(module.clone()),
            Self::Static(module) => Self::Static(module.clone()),
        }
    }
}

impl<D: 'static, Arch: RelocationArch, R: RegionAccess, Tls: TlsResolver<Arch>>
    LoadedExec<D, Arch, R, Tls>
{
    /// Returns the entry point of the executable.
    #[inline]
    pub fn entry(&self) -> usize {
        self.entry.get()
    }

    /// Returns the loader source path or caller-provided source identifier.
    #[inline]
    pub fn path(&self) -> &Path {
        match &self.inner {
            LoadedExecInner::Dynamic(module) => module.path(),
            LoadedExecInner::Static(static_image) => static_image.path(),
        }
    }

    /// Returns the executable identity used for diagnostics.
    #[inline]
    pub fn name(&self) -> &str {
        match &self.inner {
            LoadedExecInner::Dynamic(module) => module.name(),
            LoadedExecInner::Static(static_image) => static_image.name(),
        }
    }

    /// Returns whether `addr` is inside one of this executable's mapped slices.
    pub fn contains_addr(&self, addr: VmAddr) -> bool {
        match &self.inner {
            LoadedExecInner::Dynamic(module) => module.segments().contains_addr(addr),
            LoadedExecInner::Static(static_image) => static_image.segments().contains_addr(addr),
        }
    }

    /// Returns a reference to the user-defined data associated with this executable.
    pub fn user_data(&self) -> &D {
        match &self.inner {
            LoadedExecInner::Dynamic(module) => module.user_data(),
            LoadedExecInner::Static(static_image) => &static_image.inner.user_data,
        }
    }

    /// Returns whether this executable was loaded as a static binary.
    pub fn is_static(&self) -> bool {
        match &self.inner {
            LoadedExecInner::Dynamic(_) => false,
            LoadedExecInner::Static(_) => true,
        }
    }

    /// Returns a reference to the core ELF object if this is a dynamic executable.
    /// Returns the loaded dynamic core, or `None` for static executables.
    pub fn core_ref(&self) -> Option<&LoadedCore<D, Arch, R, Tls>> {
        match &self.inner {
            LoadedExecInner::Dynamic(module) => Some(module),
            LoadedExecInner::Static(_) => None,
        }
    }

    /// Returns TLS metadata associated with this executable.
    pub fn tls(&self) -> ModuleTls {
        match &self.inner {
            LoadedExecInner::Dynamic(module) => module.tls(),
            LoadedExecInner::Static(static_image) => static_image.tls(),
        }
    }
}

impl<Tls, D: 'static, Arch: RelocationArch, R: RegionAccess> ImageBuilder<Tls, D, Arch, R>
where
    Tls: TlsResolver<Arch>,
{
    pub(crate) fn build_static_exec(
        mut self,
        phdrs: &[ElfPhdr<Arch::Layout>],
    ) -> Result<StaticExec<D, Arch, R>> {
        self.parse_phdrs(phdrs)?;

        let entry = self.entry;
        let mut tls_image = None;
        let (tls_mod_id, tls_tp_offset) = if let Some(info) = &self.tls_info {
            let template = self
                .segments
                .read_view::<u8>(VmOffset::new(info.vaddr), info.filesz)
                .ok_or_else(|| crate::ParsePhdrError::malformed("PT_TLS image is malformed"))?;
            tls_image = Some(Arc::new(StaticTlsImage {
                template: (*info).template(template.as_slice()),
            }));
            // Static executables always use static TLS if PT_TLS is present.
            let (mod_id, offset) = Tls::register_static(info)?;
            (Some(mod_id), Some(offset))
        } else {
            (None, None)
        };

        let inner = Arc::new(StaticExecInner {
            entry,
            path: self.path,
            user_data: self.user_data,
            segments: self.segments,
            phdrs: if phdrs.is_empty() {
                None
            } else {
                Some(phdrs.to_vec())
            },
            tls_mod_id,
            tls_tp_offset,
            _tls_image: tls_image.clone(),
        });

        if let (Some(mod_id), Some(offset), Some(image)) =
            (tls_mod_id, tls_tp_offset, tls_image.as_ref())
        {
            let provider = tls_image_provider_handle(image.clone());
            Tls::init_tls(
                TlsImageSource::new(image.template.info, Arc::downgrade(&provider)),
                mod_id,
                Some(offset),
            )?;
        }

        Ok(StaticExec { inner })
    }

    pub(crate) fn build_exec(
        self,
        phdrs: &[ElfPhdr<Arch::Layout>],
        has_dynamic: bool,
    ) -> Result<RawExec<D, Arch, R, Tls>> {
        if has_dynamic {
            Ok(RawExec::Dynamic(self.build_dynamic(phdrs)?))
        } else {
            Ok(RawExec::Static(self.build_static_exec(phdrs)?))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    struct NonCloneData;

    #[test]
    fn exec_handles_clone_without_user_data_clone() {
        fn assert_clone<T: Clone>() {}

        assert_clone::<StaticExec<NonCloneData>>();
        assert_clone::<LoadedExec<NonCloneData>>();
    }
}