mod elf;
mod stack;
mod stub;
use std::ffi::{CStr, CString};
use std::fs::File;
use std::os::unix::ffi::OsStrExt;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::sync::atomic::AtomicPtr;
use crate::arch;
use crate::error::{Error, Result};
use crate::sys;
const IMPORTS: &[&CStr] = &[
c"__libc_start_main",
c"dlopen",
c"dlsym",
c"dlclose",
c"dlerror",
c"__errno_location",
];
const NEEDED: &[&CStr] = &[c"libc.so.6", c"libdl.so.2"];
#[repr(C)]
#[derive(Default)]
pub(crate) struct BootState {
host_sp: usize,
host_tp: usize,
start_main_slot: usize,
foreign_tp: usize,
rtld_fini: usize,
}
pub(crate) static BOOT_STATE: AtomicPtr<BootState> = AtomicPtr::new(std::ptr::null_mut());
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Flavor {
Glibc,
Musl,
}
pub(crate) struct Booted {
pub flavor: Flavor,
pub foreign_tp: usize,
pub rtld_fini: usize,
pub dlopen: usize,
pub dlsym: usize,
pub dlclose: usize,
pub dlerror: usize,
pub errno_location: usize,
pub regions: Vec<(usize, usize)>,
pub ld_base: usize,
pub stub_base: usize,
pub debug_slot: usize,
pub boot_anon: Vec<(usize, usize)>,
pub signals: Vec<Option<sys::KSigaction>>,
}
pub(crate) fn page_size() -> usize {
static PAGE: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
*PAGE.get_or_init(|| {
stack::host_auxv()
.iter()
.find(|&&(k, _)| k == stack::AT_PAGESZ)
.map_or(4096, |&(_, v)| v)
})
}
fn tune_env(env: &mut Vec<CString>) {
const RSEQ_OFF: &str = "glibc.pthread.rseq=0:glibc.pthread.stack_cache_size=0";
match env
.iter_mut()
.find(|e| e.as_bytes().starts_with(b"GLIBC_TUNABLES="))
{
Some(e) => {
let mut v = e.as_bytes().to_vec();
if v.len() > b"GLIBC_TUNABLES=".len() {
v.push(b':');
}
v.extend_from_slice(RSEQ_OFF.as_bytes());
*e = CString::new(v).expect("no NUL in tunables");
}
None => env.push(CString::new(format!("GLIBC_TUNABLES={RSEQ_OFF}")).unwrap()),
}
}
fn block_brk(page: usize) -> Option<usize> {
let at = sys::current_brk().next_multiple_of(page);
let guard = unsafe {
sys::mmap(
at,
page,
sys::PROT_NONE,
sys::MAP_PRIVATE | sys::MAP_ANONYMOUS | sys::MAP_FIXED_NOREPLACE,
-1,
0,
)
}
.ok()?;
if guard != at {
let _ = unsafe { sys::munmap(guard, page) };
return None;
}
Some(guard)
}
pub(crate) fn boot(
interpreter: &Path,
mut env: Vec<CString>,
defs: &[(&CStr, usize)],
) -> Result<Booted> {
if !arch::BOOT_SUPPORTED {
return Err(Error::Unimplemented("booting on this architecture"));
}
static BOOT_LOCK: Mutex<()> = Mutex::new(());
let _boot = BOOT_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let host_aux = stack::host_auxv();
let page = page_size();
let hwcap2 = host_aux
.iter()
.find(|&&(k, _)| k == stack::AT_HWCAP2)
.map_or(0, |&(_, v)| v);
arch::init(hwcap2);
let flavor = match interpreter.file_name().map(|n| n.as_bytes()) {
Some(n) if n.windows(4).any(|w| w == b"musl") => Flavor::Musl,
_ => Flavor::Glibc,
};
if flavor == Flavor::Glibc {
tune_env(&mut env);
}
debug!(
"booting {} ({flavor:?}), page size {page}",
interpreter.display()
);
let file = File::open(interpreter)?;
let image = std::fs::read(interpreter)?;
let ld = elf::map_image(&file, &image, page)?;
drop(file);
debug!("ld.so mapped at {:#x}, entry {:#x}", ld.region.0, ld.entry);
let interp =
CString::new(interpreter.as_os_str().as_bytes()).map_err(|_| Error::InterpreterNotFound)?;
let stub = stub::build(page, &interp, NEEDED, IMPORTS, defs)?;
debug!("stub at {:#x}, GOT at {:#x}", stub.region.0, stub.got);
let argv0 = std::env::args_os()
.next()
.and_then(|a| CString::new(a.as_bytes()).ok())
.unwrap_or_else(|| c"dldota".to_owned());
let mut aux: Vec<(usize, usize)> = host_aux
.iter()
.copied()
.filter(|(k, _)| stack::PASSTHROUGH.contains(k))
.collect();
aux.extend([
(stack::AT_PHDR, stub.phdr),
(stack::AT_PHENT, elf::PHDR_SIZE),
(stack::AT_PHNUM, stub.phnum),
(stack::AT_BASE, ld.region.0),
(stack::AT_FLAGS, 0),
(stack::AT_ENTRY, arch::entry_address()),
]);
let boot_stack = stack::build(page, &argv0, &env, &aux)?;
let tid_address = sys::get_tid_address();
let robust_list = sys::get_robust_list();
let dispositions = (0..=64)
.map(|sig| {
if sig == 0 {
None
} else {
sys::sigaction_get(sig)
}
})
.collect();
let brk_guard = (flavor == Flavor::Musl).then(|| block_brk(page)).flatten();
let signals = sys::sigprocmask_set(!0)?;
arch::before_boot();
let mut state = BootState {
host_tp: arch::thread_pointer(),
start_main_slot: stub.got,
..BootState::default()
};
BOOT_STATE.store(&mut state, std::sync::atomic::Ordering::SeqCst);
debug!("entering ld.so");
let maps_before = crate::debug_enabled().then(anon_mappings);
unsafe { arch::boot(&mut state, ld.entry, boot_stack.sp) };
let boot_anon: Vec<(usize, usize)> = match maps_before {
Some(before) => anon_mappings()
.into_iter()
.filter(|m| !before.contains(m))
.collect(),
None => vec![],
};
for &(start, end) in &boot_anon {
debug!(
"ld.so mapped anonymous {start:#x}-{end:#x} ({} KiB) during boot",
(end - start) / 1024
);
}
BOOT_STATE.store(std::ptr::null_mut(), std::sync::atomic::Ordering::SeqCst);
unsafe {
if let Some(addr) = tid_address {
sys::set_tid_address(addr);
}
if let Some((head, len)) = robust_list {
sys::set_robust_list(head, len);
}
}
sys::sigprocmask_set(signals)?;
if let Some(guard) = brk_guard {
let _ = unsafe { sys::munmap(guard, page) };
}
arch::after_boot().map_err(Error::Unimplemented)?;
debug!(
"back from ld.so: foreign TP {:#x}, rtld_fini {:#x}",
state.foreign_tp, state.rtld_fini
);
let got = |i: usize| unsafe { (stub.got as *const usize).add(i).read() };
let names = IMPORTS.iter().map(|n| n.to_string_lossy());
if let Some((name, _)) = names.zip(0..).find(|&(_, i)| got(i) == 0) {
return Err(Error::Dl(format!(
"{name} not resolved by the system loader"
)));
}
Ok(Booted {
flavor,
foreign_tp: state.foreign_tp,
rtld_fini: state.rtld_fini,
dlopen: got(1),
dlsym: got(2),
dlclose: got(3),
dlerror: got(4),
errno_location: got(5),
regions: vec![ld.region, stub.region, boot_stack.region],
ld_base: ld.region.0,
stub_base: stub.region.0,
debug_slot: stub.debug_slot,
signals: dispositions,
boot_anon,
})
}
const PROBE_BINARIES: &[&str] = &["/bin/sh", "/usr/bin/env", "/bin/ls"];
#[cfg(target_arch = "x86_64")]
const WELL_KNOWN: &[&str] = &[
"/lib64/ld-linux-x86-64.so.2",
"/lib/ld-linux-x86-64.so.2",
"/lib/ld-musl-x86_64.so.1",
];
#[cfg(target_arch = "aarch64")]
const WELL_KNOWN: &[&str] = &["/lib/ld-linux-aarch64.so.1", "/lib/ld-musl-aarch64.so.1"];
#[cfg(target_arch = "x86")]
const WELL_KNOWN: &[&str] = &[
"/lib/ld-linux.so.2",
"/lib32/ld-linux.so.2",
"/lib/ld-musl-i386.so.1",
];
#[cfg(target_arch = "arm")]
const WELL_KNOWN: &[&str] = &[
"/lib/ld-linux-armhf.so.3",
"/lib/arm-linux-gnueabihf/ld-linux-armhf.so.3",
"/lib/ld-musl-armhf.so.1",
];
pub(crate) fn find_interpreter() -> Result<PathBuf> {
for probe in PROBE_BINARIES {
let Ok(image) = std::fs::read(probe) else {
continue;
};
if let Ok(Some(interp)) = elf::interp(&image) {
let path = PathBuf::from(interp);
if path.exists() {
return Ok(path);
}
}
}
WELL_KNOWN
.iter()
.map(PathBuf::from)
.find(|p| p.exists())
.ok_or(Error::InterpreterNotFound)
}
pub(crate) fn anon_mappings() -> Vec<(usize, usize)> {
let Ok(maps) = std::fs::read_to_string("/proc/self/maps") else {
return vec![];
};
maps.lines()
.filter(|l| {
l.split_whitespace()
.nth(5)
.is_none_or(|p| !p.starts_with('/'))
})
.filter_map(|l| {
let (start, end) = l.split_whitespace().next()?.split_once('-')?;
Some((
usize::from_str_radix(start, 16).ok()?,
usize::from_str_radix(end, 16).ok()?,
))
})
.collect()
}
pub(crate) struct LoadedObject {
pub base: usize,
pub dynamic: usize,
pub span: Option<(usize, usize)>,
}
pub(crate) unsafe fn loaded_objects(booted: &Booted) -> Vec<LoadedObject> {
let vdso = stack::host_auxv()
.iter()
.find(|&&(k, _)| k == 33) .map_or(0, |&(_, v)| v);
let mut out = vec![];
unsafe {
let r_debug = *(booted.debug_slot as *const usize);
if r_debug == 0 {
debug!("no r_debug: cannot enumerate loaded objects");
return out;
}
let mut map = *((r_debug + size_of::<usize>()) as *const usize);
while map != 0 {
let words = map as *const usize;
let (base, name, dynamic, next) = (*words, *words.add(1), *words.add(2), *words.add(3));
let is_vdso = (vdso != 0 && base == vdso)
|| (name != 0
&& CStr::from_ptr(name as *const _)
.to_bytes()
.windows(4)
.any(|w| w == b"vdso"));
let unnamed = name == 0 || *(name as *const u8) == 0;
if base != booted.ld_base
&& base != booted.stub_base
&& !is_vdso
&& !unnamed
&& base != 0
{
out.push(LoadedObject {
base,
dynamic,
span: mapped_span(base),
});
}
map = next;
}
}
out
}
unsafe fn mapped_span(base: usize) -> Option<(usize, usize)> {
let header = unsafe { std::slice::from_raw_parts(base as *const u8, elf::EHDR_SIZE) };
let len = elf::headers_len(header)?;
let image = unsafe { std::slice::from_raw_parts(base as *const u8, len) };
let page = page_size();
let loads = elf::phdrs(image)
.ok()?
.into_iter()
.filter(|p| p.p_type == elf::PT_LOAD);
let (mut lo, mut hi) = (usize::MAX, 0);
for p in loads {
lo = lo.min(p.p_vaddr as usize & !(page - 1));
hi = hi.max((p.p_vaddr + p.p_memsz) as usize);
}
(lo < hi).then(|| (base + lo, hi.next_multiple_of(page) - lo))
}
#[cfg(test)]
mod tests {
#[test]
fn finds_system_interpreter() {
let path = super::find_interpreter().expect("no interpreter on this system");
assert!(path.is_absolute());
}
}