use pewter::elf::{
ElfClass, ElfFile, ElfImageDef, ElfMachine, SectionFlags, SectionType, SegmentFlags,
};
use xur_runtime::XurStr;
use xur_runtime::registry::ModuleBuilder;
use crate::error_text;
use crate::re::flags::register_flags;
use crate::re::native::{open_bytes, open_path};
pub(super) fn register(elf: &mut ModuleBuilder<'_>) {
elf.ty::<ElfFile<'static>>("ElfFile")
.raw_function_returns::<ElfFile<'static>>("parse", |cx, args| {
open_bytes(cx, args, ElfFile::parse)
})
.raw_function_returns::<ElfFile<'static>>("open", |cx, args| {
open_path(cx, args, ElfFile::parse)
})
.method("is_64", |f: &ElfFile<'static>| f.is_64())
.method("section_names", |f: &ElfFile<'static>| {
f.sections
.iter()
.map(|s| s.name.to_owned())
.collect::<Vec<_>>()
})
.method("section", |f: &ElfFile<'static>, name: XurStr| {
f.section_by_name(&name).cloned()
})
.method("symbols", |f: &ElfFile<'static>| {
f.symbols().map_err(error_text)
})
.method("find_symbol", |f: &ElfFile<'static>, name: XurStr| {
f.find_symbol(&name).map_err(error_text)
})
.method("relocations", |f: &ElfFile<'static>| {
f.relocations().map_err(error_text)
})
.method("vaddr_to_offset", |f: &ElfFile<'static>, vaddr: u64| {
f.vaddr_to_offset(vaddr)
})
.method("offset_to_vaddr", |f: &ElfFile<'static>, offset: usize| {
f.offset_to_vaddr(offset)
})
.method("read", |f: &ElfFile<'static>, vaddr: u64, len: usize| {
f.data_at_vaddr(vaddr)
.and_then(|data| data.get(..len))
.map(<[u8]>::to_vec)
})
.method(
"relocated_pointers",
|f: &ElfFile<'static>| -> Result<Vec<(u64, u64)>, String> {
f.relocated_pointers().map(|rp| rp.0).map_err(error_text)
},
);
register_image_def(elf);
register_flags!(elf, "section_flags", SectionFlags, u64);
register_flags!(elf, "segment_flags", SegmentFlags, u32);
}
fn register_image_def(elf: &mut ModuleBuilder<'_>) {
elf.ty::<ElfImageDef>("ImageDef")
.function("new_shared", |class: ElfClass, machine: ElfMachine| {
ElfImageDef::new_shared(class, machine)
})
.method("section_index", |def: &ElfImageDef, name: XurStr| {
def.section_index(&name)
})
.method_mut(
"add_section",
|def: &mut ElfImageDef,
name: String,
section_type: SectionType,
flags: u64,
data: Vec<u8>|
-> usize {
def.add_section(
&name,
section_type,
SectionFlags::from_bits_retain(flags),
data,
)
},
)
.method_mut("write", |def: &mut ElfImageDef| {
def.write_file().map_err(error_text)
});
elf.function(
"dynamic_proxy",
|class: ElfClass, machine: ElfMachine, soname: String, needed: Vec<String>| {
let needed: Vec<&str> = needed.iter().map(String::as_str).collect();
ElfImageDef::dynamic_proxy(class, machine, &soname, &needed).map_err(error_text)
},
);
}