dldota 0.1.3

Load shared libraries from statically linked programs by bootstrapping the system's own dynamic loader
Documentation
//! The synthesized in-memory "main program" handed to `ld.so` via `AT_PHDR`.
//!
//! It carries `PT_PHDR`/`PT_INTERP`/`PT_LOAD`/`PT_DYNAMIC`, a `.dynamic` with
//! `DT_NEEDED libc.so.6`, and `GLOB_DAT` relocations that make `ld.so` fill a
//! GOT with `dlopen`, `dlsym`, `dlclose`, `dlerror`, ... for us. `AT_ENTRY`
//! points at the arch entry thunk that returns control to `bootstrap()`.
//!
//! It will also *define* the symbols we interpose (first in every lookup scope):
//! the `malloc` family (backed by [`crate::heap`]), `pthread_create`, and
//! `__cxa_atexit`/`__cxa_finalize`/`atexit`.
//!
//! Every address inside is relative to the block's start, which is the
//! object's load bias (`PT_PHDR` has vaddr 0).

use std::ffi::CStr;

use super::elf::{
    IS_64, PF_R, PF_W, PHDR_SIZE, PT_DYNAMIC, PT_GNU_STACK, PT_INTERP, PT_LOAD, PT_PHDR,
};
use crate::arch;
use crate::error::Result;
use crate::sys;

const DT_NULL: usize = 0;
const DT_NEEDED: usize = 1;
const DT_HASH: usize = 4;
const DT_STRTAB: usize = 5;
const DT_SYMTAB: usize = 6;
const DT_RELA: usize = 7;
const DT_RELASZ: usize = 8;
const DT_RELAENT: usize = 9;
const DT_STRSZ: usize = 10;
const DT_SYMENT: usize = 11;
const DT_REL: usize = 17;
const DT_RELSZ: usize = 18;
const DT_RELENT: usize = 19;
const DT_DEBUG: usize = 21;
/// STB_GLOBAL << 4 | STT_FUNC
const GLOBAL_FUNC: u8 = 0x12;
/// A machine word (`ElfN_Addr`, `ElfN_Xword`...).
const WORD: usize = size_of::<usize>();
/// `Elf64_Sym` / `Elf32_Sym`.
const SYM_SIZE: usize = if IS_64 { 24 } else { 16 };
/// i386 and 32-bit ARM loaders only understand `REL` relocations (the addend
/// lives in the relocated word); the 64-bit ones use `RELA`.
const RELA: bool = IS_64;
const REL_SIZE: usize = if RELA { 3 * WORD } else { 2 * WORD };

pub(crate) struct Stub {
    /// The block: `(start, len)`. Also the object's load bias.
    pub region: (usize, usize),
    /// Runtime address of the program headers (`AT_PHDR`).
    pub phdr: usize,
    pub phnum: usize,
    /// Runtime address of the GOT: one slot per import, in order.
    pub got: usize,
    /// Runtime address of the `DT_DEBUG` value, where ld.so stores `&r_debug`.
    pub debug_slot: usize,
}

/// Byte buffer with word-aligned appends.
#[derive(Default)]
struct Buf(Vec<u8>);

impl Buf {
    fn align(&mut self) -> usize {
        self.0.resize(self.0.len().next_multiple_of(8), 0);
        self.0.len()
    }
    fn put(&mut self, bytes: &[u8]) -> usize {
        let at = self.0.len();
        self.0.extend_from_slice(bytes);
        at
    }
    fn u16(&mut self, v: u16) {
        self.put(&v.to_le_bytes());
    }
    fn u32(&mut self, v: u32) {
        self.put(&v.to_le_bytes());
    }
    /// A word of the host's ELF class.
    fn word(&mut self, v: usize) -> usize {
        self.put(&v.to_le_bytes())
    }
    fn phdr(&mut self, p_type: u32, flags: u32, off: usize, size: usize, align: usize) {
        self.u32(p_type);
        if IS_64 {
            self.u32(flags);
        }
        self.word(off); // p_offset
        self.word(off); // p_vaddr
        self.word(off); // p_paddr
        self.word(size); // p_filesz
        self.word(size); // p_memsz
        if !IS_64 {
            self.u32(flags);
        }
        self.word(align);
    }
    /// A symbol; returns the offset of its `st_value`.
    fn sym(&mut self, name: u32, info: u8, shndx: u16) -> usize {
        self.u32(name);
        if IS_64 {
            self.put(&[info, 0]);
            self.u16(shndx);
            let value = self.word(0);
            self.word(0); // st_size
            value
        } else {
            let value = self.word(0);
            self.word(0); // st_size
            self.put(&[info, 0]);
            self.u16(shndx);
            value
        }
    }
}

/// Build the main program: depends on `needed`, imports `imports` into a GOT,
/// and defines `defs` (name, absolute address), which then take precedence
/// over every library's definition.
pub(crate) fn build(
    page: usize,
    interp: &CStr,
    needed: &[&CStr],
    imports: &[&CStr],
    defs: &[(&CStr, usize)],
) -> Result<Stub> {
    const PHNUM: usize = 5;
    let nsyms = imports.len() + defs.len() + 1;

    // Lay out everything after the program headers first; the headers need
    // the final offsets, so they are written last into the reserved space.
    let mut b = Buf::default();
    b.put(&[0; PHNUM * PHDR_SIZE]);

    let interp_off = b.put(interp.to_bytes_with_nul());

    let strtab_off = b.put(&[0]);
    let needed_names: Vec<usize> = needed
        .iter()
        .map(|n| b.put(n.to_bytes_with_nul()) - strtab_off)
        .collect();
    let import_names: Vec<usize> = imports
        .iter()
        .map(|n| b.put(n.to_bytes_with_nul()) - strtab_off)
        .collect();
    let def_names: Vec<usize> = defs
        .iter()
        .map(|(n, _)| b.put(n.to_bytes_with_nul()) - strtab_off)
        .collect();
    let strsz = b.0.len() - strtab_off;

    let symtab_off = b.align();
    b.put(&[0; SYM_SIZE]); // index 0: the null symbol
    for &name in &import_names {
        b.sym(name as u32, GLOBAL_FUNC, 0); // SHN_UNDEF
    }
    // Defined symbols: any section index but SHN_UNDEF/SHN_ABS, so every
    // loader adds the load bias to st_value; patched once the block is mapped.
    let def_values: Vec<usize> = def_names
        .iter()
        .map(|&name| b.sym(name as u32, GLOBAL_FUNC, 1))
        .collect();

    // SysV hash with a single bucket chaining every symbol: lookups into this
    // object stay correct whatever the hash function says.
    let hash_off = b.align();
    b.u32(1); // nbucket
    b.u32(nsyms as u32); // nchain
    b.u32((nsyms - 1) as u32); // bucket[0]
    for i in 0..nsyms {
        b.u32(i.saturating_sub(1) as u32); // chain[i] -> i-1, chain[0] = 0
    }

    let got_off = b.align();
    b.put(&vec![0; imports.len() * WORD]);

    // GLOB_DAT relocations: the GOT slot gets the symbol's address. With
    // REL, the implicit addend is the slot's current value, 0.
    let rel_off = b.align();
    for i in 0..imports.len() {
        b.word(got_off + i * WORD); // r_offset
        let sym = i + 1;
        if RELA {
            b.word((((sym as u64) << 32) | arch::R_GLOB_DAT as u64) as usize); // r_info
            b.word(0); // r_addend
        } else {
            b.word((sym << 8) | arch::R_GLOB_DAT as usize); // r_info
        }
    }
    let relsz = b.0.len() - rel_off;

    let dynamic_off = b.align();
    let mut dynamic = vec![];
    dynamic.extend(needed_names.iter().map(|&n| (DT_NEEDED, n)));
    let (dt_rel, dt_relsz, dt_relent) = if RELA {
        (DT_RELA, DT_RELASZ, DT_RELAENT)
    } else {
        (DT_REL, DT_RELSZ, DT_RELENT)
    };
    dynamic.extend([
        (DT_HASH, hash_off),
        (DT_STRTAB, strtab_off),
        (DT_STRSZ, strsz),
        (DT_SYMTAB, symtab_off),
        (DT_SYMENT, SYM_SIZE),
        (dt_rel, rel_off),
        (dt_relsz, relsz),
        (dt_relent, REL_SIZE),
        (DT_DEBUG, 0),
        (DT_NULL, 0),
    ]);
    let debug_slot = dynamic_off
        + dynamic
            .iter()
            .position(|&(tag, _)| tag == DT_DEBUG)
            .unwrap()
            * 2
            * WORD
        + WORD;
    for &(tag, val) in &dynamic {
        b.word(tag);
        b.word(val);
    }
    let dynamic_size = b.0.len() - dynamic_off;
    let total = b.0.len();

    let mut headers = Buf::default();
    headers.phdr(PT_PHDR, PF_R, 0, PHNUM * PHDR_SIZE, WORD);
    headers.phdr(
        PT_INTERP,
        PF_R,
        interp_off,
        interp.to_bytes_with_nul().len(),
        1,
    );
    headers.phdr(PT_LOAD, PF_R | PF_W, 0, total, page);
    headers.phdr(PT_DYNAMIC, PF_R | PF_W, dynamic_off, dynamic_size, WORD);
    headers.phdr(PT_GNU_STACK, PF_R | PF_W, 0, 0, 16);
    b.0[..headers.0.len()].copy_from_slice(&headers.0);

    // Writable: ld.so fills the GOT and DT_DEBUG.
    let len = total.next_multiple_of(page);
    // SAFETY: a fresh private mapping.
    let start = unsafe {
        sys::mmap(
            0,
            len,
            sys::PROT_READ | sys::PROT_WRITE,
            sys::MAP_PRIVATE | sys::MAP_ANONYMOUS,
            -1,
            0,
        )
    }?;
    for (&at, &(_, addr)) in def_values.iter().zip(defs) {
        b.0[at..at + WORD].copy_from_slice(&addr.wrapping_sub(start).to_le_bytes());
    }
    // SAFETY: `total <= len`, freshly mapped.
    unsafe { std::ptr::copy_nonoverlapping(b.0.as_ptr(), start as *mut u8, total) };
    Ok(Stub {
        region: (start, len),
        phdr: start,
        phnum: PHNUM,
        got: start + got_off,
        debug_slot: start + debug_slot,
    })
}