use super::mystd::borrow::ToOwned;
use super::mystd::env;
use super::mystd::ffi::{CStr, OsStr};
use super::mystd::os::unix::prelude::*;
use super::{Library, LibrarySegment, OsString, Vec};
use core::slice;
pub(super) fn native_libraries() -> Vec<Library> {
let mut ret = Vec::new();
unsafe {
libc::dl_iterate_phdr(Some(callback), core::ptr::addr_of_mut!(ret).cast());
}
return ret;
}
fn infer_current_exe(base_addr: usize) -> OsString {
cfg_if::cfg_if! {
if #[cfg(not(target_os = "hurd"))] {
if let Ok(entries) = super::parse_running_mmaps::parse_maps() {
let opt_path = entries
.iter()
.find(|e| e.ip_matches(base_addr) && e.pathname().len() > 0)
.map(|e| e.pathname())
.cloned();
if let Some(path) = opt_path {
return path;
}
}
}
}
env::current_exe().map(|e| e.into()).unwrap_or_default()
}
#[forbid(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn callback(
info: *mut libc::dl_phdr_info,
_size: libc::size_t,
vec: *mut libc::c_void,
) -> libc::c_int {
let dlpi_addr = unsafe { (*info).dlpi_addr };
let dlpi_name = unsafe { (*info).dlpi_name };
let dlpi_phdr = unsafe { (*info).dlpi_phdr };
let dlpi_phnum = unsafe { (*info).dlpi_phnum };
let libs = unsafe { &mut *vec.cast::<Vec<Library>>() };
let is_main = libs.is_empty();
let is_static = dlpi_addr == 0;
let no_given_name = dlpi_name.is_null()
|| unsafe { *dlpi_name == 0 };
let name = if is_static {
env::current_exe().unwrap_or_default().into_os_string()
} else if is_main && no_given_name {
infer_current_exe(dlpi_addr as usize)
} else {
if dlpi_name.is_null() {
OsString::new()
} else {
OsStr::from_bytes(unsafe { CStr::from_ptr(dlpi_name) }.to_bytes()).to_owned()
}
};
let headers = if dlpi_phdr.is_null() || dlpi_phnum == 0 {
&[]
} else {
unsafe { slice::from_raw_parts(dlpi_phdr, dlpi_phnum as usize) }
};
libs.push(Library {
name,
segments: headers
.iter()
.map(|header| LibrarySegment {
len: (*header).p_memsz as usize,
stated_virtual_memory_address: (*header).p_vaddr as usize,
})
.collect(),
bias: dlpi_addr as usize,
});
0
}