elf_loader 0.15.0

A no_std-friendly ELF loader, runtime linker, and JIT linker for Rust.
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
//! 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, RawDynamic},
    input::{Path, PathBuf},
    loader::{ImageBuilder, LoadHook},
    os::Mmap,
    relocation::{
        RelocAddr, Relocatable, RelocateArgs, RelocationArch, RelocationHandler, Relocator,
    },
    segment::ElfSegments,
    tls::{TlsModuleId, TlsResolver, TlsTpOffset},
};
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.
#[derive(Clone)]
pub struct StaticExec<D, Arch: RelocationArch = NativeArch> {
    inner: Arc<StaticExecInner<D, Arch>>,
}

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

impl<D, Arch: RelocationArch> StaticExec<D, Arch> {
    /// 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().into_inner()
    }

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

    /// Returns the TLS module id assigned to this image, when registered.
    pub fn tls_mod_id(&self) -> Option<TlsModuleId> {
        self.inner.tls_mod_id
    }

    /// Returns the static TLS thread-pointer offset, when assigned.
    pub fn tls_tp_offset(&self) -> Option<TlsTpOffset> {
        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) -> usize {
        self.inner.segments.base()
    }

    pub(crate) fn mapped_base(&self) -> usize {
        self.inner.segments.mapped_base()
    }

    /// Returns the mapped memory length in bytes.
    pub fn mapped_len(&self) -> usize {
        self.inner.segments.mapped_len()
    }

    /// Returns whether `addr` lies inside this executable mapping.
    pub fn contains_addr(&self, addr: usize) -> bool {
        self.inner.segments.contains_addr(addr)
    }
}

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

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

    /// User-defined data
    user_data: D,

    /// Memory segments
    segments: ElfSegments,

    /// 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>,
}

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

    fn relocate<PreH, PostH>(
        self,
        args: RelocateArgs<'_, D, Arch, PreH, PostH>,
    ) -> Result<Self::Output>
    where
        PreH: RelocationHandler<Arch> + ?Sized,
        PostH: RelocationHandler<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.
pub enum RawExec<D, Arch = crate::arch::NativeArch>
where
    D: 'static,
    Arch: RelocationArch,
{
    /// A dynamically linked executable with `PT_DYNAMIC`.
    Dynamic(RawDynamic<D, Arch>),

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

impl<D, Arch: RelocationArch> Debug for RawExec<D, Arch> {
    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> RawExec<D, Arch> {
    /// Creates a relocation builder for this executable image.
    pub fn relocator(self) -> Relocator<Self, (), (), D, Arch> {
        Relocator::new().with_object(self)
    }

    /// 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 the TLS module id assigned to this executable, when registered.
    pub fn tls_mod_id(&self) -> Option<TlsModuleId> {
        match self {
            RawExec::Dynamic(image) => image.tls_mod_id(),
            RawExec::Static(image) => image.tls_mod_id(),
        }
    }

    /// Returns the static TLS thread-pointer offset, when assigned.
    pub fn tls_tp_offset(&self) -> Option<TlsTpOffset> {
        match self {
            RawExec::Dynamic(image) => image.tls_tp_offset(),
            RawExec::Static(image) => image.tls_tp_offset(),
        }
    }

    /// 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 the length of the bounding runtime span covered by mapped slices.
    pub fn mapped_len(&self) -> usize {
        match self {
            RawExec::Dynamic(image) => image.mapped_len(),
            RawExec::Static(image) => image.mapped_len(),
        }
    }

    /// Returns the lowest runtime address covered by this executable's mapped slices.
    pub(crate) fn mapped_base(&self) -> usize {
        match self {
            RawExec::Dynamic(image) => image.mapped_base(),
            RawExec::Static(image) => image.mapped_base(),
        }
    }

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

    /// Returns the runtime base address.
    pub fn base(&self) -> usize {
        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(Clone, Debug)]
pub struct LoadedExec<D: 'static, Arch: RelocationArch = NativeArch> {
    /// Entry point of the executable.
    entry: RelocAddr,
    /// The relocated ELF object.
    inner: LoadedExecInner<D, Arch>,
}

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

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

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

    /// Returns the length of the bounding runtime span covered by mapped slices.
    pub fn mapped_len(&self) -> usize {
        match &self.inner {
            LoadedExecInner::Dynamic(module) => unsafe { module.core_ref().mapped_len() },
            LoadedExecInner::Static(static_image) => static_image.mapped_len(),
        }
    }

    /// Returns whether `addr` is inside one of this executable's mapped slices.
    pub fn contains_addr(&self, addr: usize) -> bool {
        match &self.inner {
            LoadedExecInner::Dynamic(module) => module.contains_addr(addr),
            LoadedExecInner::Static(static_image) => static_image.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) => unsafe { &module.core_ref().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>> {
        match &self.inner {
            LoadedExecInner::Dynamic(module) => Some(module),
            LoadedExecInner::Static(_) => None,
        }
    }

    /// Returns the TLS module id assigned to this executable, when registered.
    pub fn tls_mod_id(&self) -> Option<TlsModuleId> {
        match &self.inner {
            LoadedExecInner::Dynamic(module) => module.core.tls_mod_id(),
            LoadedExecInner::Static(static_image) => static_image.tls_mod_id(),
        }
    }

    /// Returns the static TLS thread-pointer offset, when assigned.
    pub fn tls_tp_offset(&self) -> Option<TlsTpOffset> {
        match &self.inner {
            LoadedExecInner::Dynamic(module) => module.core.tls_tp_offset(),
            LoadedExecInner::Static(static_image) => static_image.tls_tp_offset(),
        }
    }
}

impl<D, Arch: RelocationArch> StaticExec<D, Arch> {
    pub(crate) fn from_builder<'hook, H, M, Tls>(
        mut builder: ImageBuilder<'hook, H, M, Tls, D, Arch::Layout>,
        phdrs: &[ElfPhdr<Arch::Layout>],
    ) -> Result<Self>
    where
        M: Mmap,
        H: LoadHook<Arch::Layout>,
        Tls: TlsResolver,
    {
        // Parse all program headers
        builder.parse_phdrs(phdrs)?;

        let entry = RelocAddr::new(builder.ehdr.e_entry());
        let (tls_mod_id, tls_tp_offset) = if let Some(info) = &builder.tls_info {
            // 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 static_inner = StaticExecInner {
            entry,
            path: builder.path,
            user_data: builder.user_data,
            segments: builder.segments,
            phdrs: if phdrs.is_empty() {
                None
            } else {
                Some(phdrs.to_vec())
            },
            tls_mod_id,
            tls_tp_offset,
        };
        Ok(StaticExec {
            inner: Arc::new(static_inner),
        })
    }
}

impl<D: 'static, Arch: RelocationArch> RawExec<D, Arch> {
    pub(crate) fn from_builder<'hook, H, M, Tls>(
        builder: ImageBuilder<'hook, H, M, Tls, D, Arch::Layout>,
        phdrs: &[ElfPhdr<Arch::Layout>],
        has_dynamic: bool,
    ) -> Result<Self>
    where
        M: Mmap,
        H: LoadHook<Arch::Layout>,
        Tls: TlsResolver,
    {
        if has_dynamic {
            Ok(Self::Dynamic(RawDynamic::from_builder(builder, phdrs)?))
        } else {
            Ok(Self::Static(StaticExec::from_builder(builder, phdrs)?))
        }
    }
}