Skip to main content

plthook/
module_elf.rs

1//! [`Module`](crate::Module).
2//!
3//! A [`Module`] is a validated identity for one object currently mapped into the
4//! process: its load bias (`dl_iterate_phdr`'s `dlpi_addr`), its loadable
5//! segments, the address of its dynamic table, and its path. Acquisition walks the
6//! program headers and validates the ELF header up front, so an address that names
7//! no loaded object — or a non-ELF64 one — is rejected here rather than deep inside
8//! enumeration.
9//!
10//! The heavy lifting (relocation / symbol / version decoding) lives in the
11//! host-independent [`crate::elf`] parser; this module only supplies the *live*
12//! [`ElfView`](crate::elf::ElfView): dynamic pointers are absolute addresses (the
13//! glibc dynamic linker relocates the dynamic section in place on x86-64/`AArch64`),
14//! and a slot address is `load_bias + r_offset`.
15
16use crate::dlpi::{self, Object};
17use crate::elf::{self, ElfView, Segment};
18use crate::error::{Error, Result};
19use crate::slot::ImportSlot;
20use core::ffi::{c_char, c_void};
21
22/// The head of glibc's `struct link_map`. Only the first field — the load bias
23/// `l_addr` (`ElfW(Addr)`) — is read; `dlinfo(RTLD_DI_LINKMAP)` writes a pointer to
24/// the real, longer `link_map`, whose tail is intentionally opaque here. The
25/// `libc` crate does not expose `link_map`, so the minimal ABI head is declared.
26#[repr(C)]
27struct LinkMapHead {
28    l_addr: usize,
29}
30
31/// A validated, currently-loaded ELF object.
32#[derive(Debug, Clone)]
33pub struct Module {
34    /// Load bias (`dlpi_addr`) — added to a link-time vaddr to get its address.
35    base: usize,
36    /// Loadable segments, for bounds-checking live reads and slot targets.
37    loads: Vec<Segment>,
38    /// The image's `e_machine` (picks the relocation constants).
39    machine: u16,
40    /// Absolute address of the dynamic (`PT_DYNAMIC`) table.
41    dynamic_addr: u64,
42    /// Lowest / highest mapped byte (`[lo, hi)`), for size + liveness checks.
43    span: (usize, usize),
44    /// The object's path (`dlpi_name`), possibly empty for the main executable.
45    path: String,
46}
47
48/// Read `buf.len()` bytes from live process memory at absolute address `cursor`,
49/// bounds-checked to lie inside a mapped `PT_LOAD` segment of the object with load
50/// bias `base`.
51fn read_live(base: usize, loads: &[Segment], cursor: u64, buf: &mut [u8]) -> Result<()> {
52    let len = buf.len() as u64;
53    // `cursor` is an absolute address; recover the link-time vaddr to bound-check.
54    let vaddr = cursor
55        .checked_sub(base as u64)
56        .ok_or(Error::Malformed("address below load base"))?;
57    if !vaddr_in_load(loads, vaddr, len) {
58        return Err(Error::Malformed("read outside loadable segments"));
59    }
60    let addr = usize::try_from(cursor).map_err(|_| Error::Malformed("address overflow"))?;
61    // SAFETY: `[cursor, cursor+len)` was validated to lie within a committed,
62    // readable `PT_LOAD` mapping of this live object; `buf` cannot overlap it.
63    unsafe {
64        core::ptr::copy_nonoverlapping(addr as *const u8, buf.as_mut_ptr(), buf.len());
65    }
66    Ok(())
67}
68
69/// Whether `[vaddr, vaddr+len)` lies inside some loadable segment's in-memory
70/// range (`p_memsz` covers `.bss`, which is mapped and readable).
71fn vaddr_in_load(loads: &[Segment], vaddr: u64, len: u64) -> bool {
72    loads.iter().any(|seg| {
73        let end = seg.vaddr.saturating_add(seg.memsz);
74        vaddr >= seg.vaddr && vaddr.checked_add(len).is_some_and(|hi| hi <= end)
75    })
76}
77
78impl ElfView for Module {
79    fn machine(&self) -> u16 {
80        self.machine
81    }
82    fn dynamic_cursor(&self) -> u64 {
83        self.dynamic_addr
84    }
85    fn dynptr_cursor(&self, d_ptr: u64) -> Result<u64> {
86        // The dynamic linker has relocated the *address* dynamic pointers
87        // (DT_SYMTAB/DT_STRTAB/DT_JMPREL/DT_RELA/DT_VERSYM) to absolute addresses
88        // in place, so `d_ptr` is already the address to read (no bias added). It
89        // must fall within a loadable range, or the image is malformed.
90        let vaddr = d_ptr
91            .checked_sub(self.base as u64)
92            .ok_or(Error::Malformed("dynamic pointer below load base"))?;
93        if !vaddr_in_load(&self.loads, vaddr, 1) {
94            return Err(Error::Malformed(
95                "dynamic pointer outside loadable segments",
96            ));
97        }
98        Ok(d_ptr)
99    }
100    fn vaddr_cursor(&self, vaddr: u64) -> Result<u64> {
101        // DT_VERNEED / DT_VERDEF are NOT relocated in place by glibc's
102        // ADJUST_DYN_INFO (unlike the pointers `dynptr_cursor` handles), so their
103        // d_ptr is a link-time vaddr the loader biases by the load base only at
104        // use. Bias it here and bounds-check the result within a loadable range.
105        if !vaddr_in_load(&self.loads, vaddr, 1) {
106            return Err(Error::Malformed(
107                "version-table vaddr outside loadable segments",
108            ));
109        }
110        (self.base as u64)
111            .checked_add(vaddr)
112            .ok_or(Error::Malformed("version-table address overflow"))
113    }
114    fn read(&self, cursor: u64, buf: &mut [u8]) -> Result<()> {
115        read_live(self.base, &self.loads, cursor, buf)
116    }
117    fn slot_address(&self, r_offset: u64) -> Result<u64> {
118        let addr = (self.base as u64)
119            .checked_add(r_offset)
120            .ok_or(Error::Malformed("slot address overflow"))?;
121        // The GOT slot must lie within a loadable segment and be pointer-aligned:
122        // the install/restore path reinterprets it as an `&AtomicUsize`, so a
123        // misaligned cell would be instant UB.
124        if !vaddr_in_load(&self.loads, r_offset, crate::arch::PTR_SIZE as u64) {
125            return Err(Error::Malformed(
126                "relocation offset outside loadable segments",
127            ));
128        }
129        if !addr.is_multiple_of(core::mem::align_of::<usize>() as u64) {
130            return Err(Error::Malformed("relocation slot is not pointer-aligned"));
131        }
132        Ok(addr)
133    }
134}
135
136impl Module {
137    /// Acquire a module from a `dlopen` handle. On glibc, `dlinfo`
138    /// (`RTLD_DI_LINKMAP`) yields the object's load bias, which selects its
139    /// `dl_iterate_phdr` entry.
140    ///
141    /// # Safety
142    /// `handle` must be a live handle returned by `dlopen`/`dlmopen` for a
143    /// currently-loaded object.
144    pub unsafe fn from_handle(handle: *mut c_void) -> Result<Self> {
145        if handle.is_null() {
146            return Err(Error::ModuleNotFound {
147                reason: "null handle",
148                os_error: 0,
149            });
150        }
151        let mut lmap: *mut LinkMapHead = core::ptr::null_mut();
152        // SAFETY: `handle` is a live dlopen handle; `lmap` is a valid out-pointer.
153        let rc = unsafe {
154            libc::dlinfo(
155                handle,
156                libc::RTLD_DI_LINKMAP,
157                (&raw mut lmap).cast::<c_void>(),
158            )
159        };
160        if rc != 0 || lmap.is_null() {
161            return Err(Error::ModuleNotFound {
162                reason: "dlinfo handle",
163                os_error: 0,
164            });
165        }
166        // SAFETY: `lmap` points at a live `link_map`; its first field is `l_addr`.
167        let base = unsafe { (*lmap).l_addr };
168        Self::from_base(base)
169    }
170
171    /// Acquire the module containing `address` — e.g. the address of an exported
172    ///
173    /// # Safety
174    /// `address` must point into a loadable segment of a currently-mapped object.
175    pub unsafe fn from_address(address: *const c_void) -> Result<Self> {
176        let target = address as usize;
177        let found = dlpi::for_each(|obj| obj.contains_address(target).then(|| obj.clone()));
178        match found {
179            Some(obj) => Self::from_raw(&obj),
180            None => Err(Error::ModuleNotFound {
181                reason: "address",
182                os_error: 0,
183            }),
184        }
185    }
186
187    /// Acquire an already-loaded module by SONAME / path (`dlopen` with
188    /// `RTLD_NOLOAD`, so a not-yet-loaded object is reported rather than loaded).
189    pub fn from_name(name: &str) -> Result<Self> {
190        let mut c_name: Vec<u8> = name.as_bytes().to_vec();
191        c_name.push(0);
192        // SAFETY: `c_name` is a valid NUL-terminated C string.
193        let handle = unsafe {
194            libc::dlopen(
195                c_name.as_ptr().cast::<c_char>(),
196                libc::RTLD_LAZY | libc::RTLD_NOLOAD,
197            )
198        };
199        if handle.is_null() {
200            return Err(Error::ModuleNotFound {
201                reason: "name",
202                os_error: 0,
203            });
204        }
205        // SAFETY: `handle` is a live dlopen handle we own.
206        let module = unsafe { Self::from_handle(handle) };
207        // SAFETY: closing the handle we just opened; the object stays mapped
208        // because `RTLD_NOLOAD` did not add a fresh reference to an already-loaded
209        // object beyond the one this call holds.
210        unsafe { libc::dlclose(handle) };
211        module
212    }
213
214    /// Enumerate every object loaded in the process (`Scope::AllModules`). Objects
215    /// that fail validation (no `PT_DYNAMIC`, unsupported machine) are skipped.
216    pub fn enumerate() -> Result<Vec<Self>> {
217        let mut out = Vec::new();
218        dlpi::for_each(|obj| -> Option<()> {
219            if let Ok(module) = Self::from_raw(obj) {
220                out.push(module);
221            }
222            None
223        });
224        Ok(out)
225    }
226
227    /// Build and validate a module from an object's load bias.
228    fn from_base(base: usize) -> Result<Self> {
229        let obj = dlpi::find_base(base).ok_or(Error::ModuleNotFound {
230            reason: "base",
231            os_error: 0,
232        })?;
233        Self::from_raw(&obj)
234    }
235
236    /// Validate and capture identity from a raw `dl_iterate_phdr` object.
237    fn from_raw(obj: &Object) -> Result<Self> {
238        let ph = elf::parse_program_headers(&obj.phdrs, obj.phnum)?;
239        let dyn_vaddr = ph
240            .dynamic_vaddr
241            .ok_or(Error::Malformed("object has no PT_DYNAMIC"))?;
242        let bias = obj.base as u64;
243
244        // Validate the ELF header, read from the object's mapped image.
245        let ehdr_addr = bias
246            .checked_add(ph.ehdr_vaddr)
247            .ok_or(Error::Malformed("ELF header address overflow"))?;
248        let mut ehdr = [0u8; 64];
249        read_live(obj.base, &ph.loads, ehdr_addr, &mut ehdr)?;
250        let machine = elf::validate_ehdr(&ehdr)?;
251
252        let dynamic_addr = bias
253            .checked_add(dyn_vaddr)
254            .ok_or(Error::Malformed("dynamic table address overflow"))?;
255
256        let (lo, hi) = span_of(obj.base, &ph.loads);
257        Ok(Self {
258            base: obj.base,
259            loads: ph.loads,
260            machine,
261            dynamic_addr,
262            span: (lo, hi),
263            path: obj.name.clone(),
264        })
265    }
266
267    /// File name of the module (final path component).
268    #[must_use]
269    pub fn name(&self) -> &str {
270        match self.path.rfind('/') {
271            Some(pos) => self.path.get(pos + 1..).unwrap_or(&self.path),
272            None => &self.path,
273        }
274    }
275
276    /// Full path of the module (`dlpi_name`; empty for the main executable).
277    #[must_use]
278    pub fn path(&self) -> &str {
279        &self.path
280    }
281
282    /// Load bias (`dlpi_addr`) of the mapped image.
283    #[must_use]
284    pub fn base(&self) -> *const c_void {
285        self.base as *const c_void
286    }
287
288    /// Size of the mapped image span (`hi - lo` over its loadable segments).
289    #[must_use]
290    pub fn size(&self) -> usize {
291        self.span.1.saturating_sub(self.span.0)
292    }
293
294    pub(crate) fn base_addr(&self) -> usize {
295        self.base
296    }
297
298    /// Enumerate the module's import slots (`JUMP_SLOT` + `GLOB_DAT`).
299    ///
300    /// Every returned slot's address was validated to lie inside a loadable
301    /// segment and to be pointer-aligned, so it is safe to pass to
302    /// [`crate::install`].
303    pub fn imports(&self) -> Result<Vec<ImportSlot>> {
304        Ok(elf::parse_imports(self)?
305            .into_iter()
306            .map(|raw| ImportSlot::from_raw(self.base, raw))
307            .collect())
308    }
309}
310
311/// Lowest / highest mapped absolute address over the loadable segments.
312fn span_of(base: usize, loads: &[Segment]) -> (usize, usize) {
313    let mut lo = usize::MAX;
314    let mut hi = 0usize;
315    for seg in loads {
316        // ELF64 addresses on the 64-bit-only targets fit `usize`; a value that did
317        // not would simply saturate this informational span.
318        let vaddr = usize::try_from(seg.vaddr).unwrap_or(usize::MAX);
319        let memsz = usize::try_from(seg.memsz).unwrap_or(0);
320        let start = base.wrapping_add(vaddr);
321        let end = start.wrapping_add(memsz);
322        lo = lo.min(start);
323        hi = hi.max(end);
324    }
325    if lo == usize::MAX {
326        (base, base)
327    } else {
328        (lo, hi)
329    }
330}