mod assemble;
mod deps;
use std::path::{Path, PathBuf};
use rayon::prelude::*;
use rustc_hash::FxHashSet;
use self::assemble::{
assemble_full, check_dep_machines, derive_target as derive_target_inner,
needed_sonames,
};
pub use self::deps::{
DepAddr, DepExports, DepUndefs, DepVersion, DepVersions, DynExport,
};
use crate::{
archive::Archive,
buildid::BuildId,
comdat::GroupDedup,
debug::DebugSections,
dynamic::{DynConfig, HashStyle, LinkMode, Strip, ZOptions},
ehframe::EhFramePlan,
elf::{
Group, ObjectFile, Shdr64,
constants::{
ET_DYN, SHF_ALLOC, SHF_COMPRESSED, SHF_EXCLUDE, SHF_EXECINSTR,
SHF_MERGE, SHF_TLS, SHF_WRITE, SHN_UNDEF, SHT_NOBITS, SHT_NOTE,
SHT_NULL, SHT_PROGBITS, STB_GLOBAL, STT_NOTYPE, STV_DEFAULT,
},
},
error::{Error, Result},
icf::{FoldMap, IcfMode},
input::{Input, InputBytes, InputFile, InputSymbol},
merge::MergePlan,
output::{
Member, NO_PRIORITY, Named, OutKind, OutputSections, init_priority,
},
pool,
startstop::StartStop,
symbol::{
DefSource, Definition, Symbol, SymbolId, SymbolKind, SymbolTable,
},
util::{open_all, show},
versionscript::{VersionScript, Visibility as VersionVisibility},
};
pub struct Context<'data> {
pub files: Vec<InputFile<'data>>,
extracted: Vec<Option<Vec<InputSymbol<'data>>>>,
group_lists: Vec<Vec<Group<'data>>>,
bins: Vec<Vec<(u32, u32)>>,
pub symbols: SymbolTable<'data>,
pub sym_id: Vec<Vec<Option<SymbolId>>>,
pub outputs: OutputSections,
pub defsyms: Vec<(SymbolId, crate::defsym::DefSym)>,
pub dep_exports: DepExports<'data>,
pub dep_order: Vec<u32>,
pub dep_versions: DepVersions<'data>,
pub dep_undefs: DepUndefs<'data>,
pub gc: bool,
pub export_dynamic: bool,
pub icf: IcfMode,
pub folding: FoldMap,
pub groups: GroupDedup,
pub eh: EhFramePlan,
has_mergeable: bool,
pub merge: MergePlan,
pub debug: DebugSections,
pub start_stop: StartStop,
}
impl Default for Context<'_> {
fn default() -> Self {
Self {
files: Vec::new(),
extracted: Vec::new(),
group_lists: Vec::new(),
bins: Vec::new(),
symbols: SymbolTable::new(),
sym_id: Vec::new(),
outputs: OutputSections::new(),
defsyms: Vec::new(),
dep_exports: DepExports::default(),
dep_order: Vec::new(),
dep_versions: DepVersions::default(),
dep_undefs: DepUndefs::default(),
gc: false,
export_dynamic: false,
icf: IcfMode::None,
folding: FoldMap::default(),
groups: GroupDedup::default(),
eh: EhFramePlan::default(),
has_mergeable: false,
merge: MergePlan::default(),
debug: DebugSections::new(),
start_stop: StartStop::default(),
}
}
}
impl<'data> Context<'data> {
pub fn new() -> Self {
Self::default()
}
pub fn add_file(&mut self, path: &Path, bytes: &'data [u8]) -> Result<()> {
self.files.push(InputFile::open(path, bytes)?);
self.extracted.push(None);
self.group_lists.push(Vec::new());
self.bins.push(Vec::new());
self.sym_id.push(Vec::new());
Ok(())
}
pub fn global_id(&self, file: usize, sym_idx: u32) -> Option<SymbolId> {
*self.sym_id.get(file)?.get(sym_idx as usize)?
}
pub fn resolve_symbols(&mut self) -> Result<()> {
let Self {
files,
extracted,
group_lists,
bins,
symbols: table,
groups,
sym_id,
..
} = self;
let parsed = std::mem::take(group_lists);
groups.scan_batch(&parsed)?;
drop(parsed);
let symbols: Vec<Result<Vec<InputSymbol<'_>>>> = extracted
.par_iter_mut()
.zip(bins.par_iter_mut())
.enumerate()
.map(|(file, (slot, bin))| {
let mut syms = if let Some(syms) = slot.take() {
syms
} else {
let mut syms = files
.get(file)
.map(InputFile::global_symbols_direct)
.transpose()?
.unwrap_or_default();
*bin = crate::symbol::partition_file(&mut syms);
syms
};
for sym in &mut syms {
if groups.is_discarded(file, sym.shndx) {
sym.shndx = SHN_UNDEF;
}
}
Ok(syms)
})
.collect::<Vec<Result<_>>>();
let symbols = in_input_order(symbols)?;
let taken_bins = std::mem::take(bins);
*sym_id = table.intern_all(&symbols, &taken_bins).map_err(|err| {
name_duplicate_files(err, files)
})?;
Ok(())
}
fn resolve_file(&mut self, file: usize) -> Result<()> {
self.scan_groups(file)?;
let symbols = match self.extracted.get_mut(file).and_then(Option::take)
{
Some(syms) => syms,
None => self
.files
.get(file)
.map(InputFile::global_symbols)
.transpose()?
.unwrap_or_default(),
};
let len = symbols
.iter()
.map(|s| s.sym_idx as usize)
.max()
.map_or(0, |m| m.saturating_add(1));
let mut row = vec![None; len];
for sym in symbols {
let sym = if self.groups.is_discarded(file, sym.shndx) {
InputSymbol {
shndx: SHN_UNDEF,
..sym
}
} else {
sym
};
let id = self.symbols.intern(&sym, file)?;
if let Some(slot) = row.get_mut(sym.sym_idx as usize) {
*slot = Some(id);
}
}
if let Some(target) = self.sym_id.get_mut(file) {
*target = row;
}
Ok(())
}
fn scan_groups(&mut self, file: usize) -> Result<()> {
let Self { files, groups, .. } = self;
let Some(input) = files.get(file) else {
return Ok(());
};
let mut parsed = Vec::new();
input.object()?.groups(&mut parsed)?;
groups.scan(file, &parsed)
}
pub fn pull_archives(&mut self, archives: &[Archive<'data>]) -> Result<()> {
if archives.is_empty() {
return Ok(());
}
let mut pulled: FxHashSet<(usize, u64)> = FxHashSet::default();
loop {
let undefined: Vec<Vec<u8>> = self
.symbols
.entries()
.filter(|(_, s)| strong_undefined(&s.kind))
.map(|(n, _)| n.to_vec())
.collect();
let mut progressed = false;
for name in &undefined {
for (index, archive) in archives.iter().enumerate() {
if !self.still_extractable(name, archive.pos()) {
continue;
}
let Some(offset) = archive.lookup(name) else {
continue;
};
if !pulled.insert((index, offset)) {
continue;
}
let member = archive.member(offset)?;
let label = archive
.member_name(offset)
.unwrap_or_else(|_| format!("0x{offset:x}"));
let path = PathBuf::from(format!("({label})"));
let file = self.files.len();
self.files
.push(InputFile::from_member(&path, &member[..])?);
self.extracted.push(None);
self.group_lists.push(Vec::new());
self.bins.push(Vec::new());
self.sym_id.push(Vec::new());
self.resolve_file(file)?;
progressed = true;
break;
}
}
if !progressed {
break;
}
}
Ok(())
}
fn extracts_member(
&self,
name: &[u8],
sym: &Symbol,
archive_pos: u32,
) -> bool {
strong_undefined(&sym.kind)
&& !(sym.visibility == STV_DEFAULT
&& self.dep_preempts(name, archive_pos))
}
fn dep_preempts(&self, name: &[u8], archive_pos: u32) -> bool {
let Some(exp) = self.dep_exports.get(name) else {
return false;
};
self.dep_order
.get(exp.at.dep as usize)
.is_some_and(|&dep_pos| dep_pos < archive_pos)
}
fn still_extractable(&self, name: &[u8], archive_pos: u32) -> bool {
self.symbols.find(name).is_some_and(|id| {
self.symbols
.symbol(id)
.is_some_and(|s| self.extracts_member(name, s, archive_pos))
})
}
pub fn assign_sections(&mut self) -> Result<()> {
let groups = &self.groups;
let start_stop = &self.start_stop;
let classified: Vec<Result<Vec<Assigned<'_>>>> = self
.files
.par_iter()
.enumerate()
.map(|(file, input)| {
classify_sections(file, input, groups, start_stop)
})
.collect::<Vec<Result<_>>>();
for row in in_input_order(classified)? {
for item in row {
self.has_mergeable |= item.mergeable;
if let Some(run) = item.run {
self.start_stop.record(item.file, item.section, run);
}
match item.kind {
Some(kind) => self.outputs.add(
kind,
Member {
file: item.file,
section: item.section,
size: item.size,
align: item.align,
priority: item.priority,
},
),
None => self.debug.add(
item.file,
item.section,
item.shdr,
item.name,
),
}
}
}
self.outputs.sort_init_fini();
Ok(())
}
pub fn gc_sections(
&mut self,
entry: &[u8],
undefined: &[&[u8]],
mode: LinkMode,
) -> Result<()> {
if self.gc {
crate::gc::run(self, entry, undefined, mode)?;
}
Ok(())
}
pub fn icf_sections(&mut self, mode: LinkMode) -> Result<()> {
if self.icf.is_active() {
crate::icf::run(self, self.icf, mode)?;
}
Ok(())
}
pub fn split_eh_frame(&mut self) -> Result<()> {
let plan = crate::ehframe::build_plan(self)?;
self.commit_eh(plan);
Ok(())
}
fn commit_eh(&mut self, plan: EhFramePlan) {
self.outputs
.set_member_sizes(OutKind::EhFrame, plan.sizes());
self.eh = plan;
}
pub fn merge_sections(&mut self) -> Result<()> {
if !self.has_mergeable {
return Ok(());
}
let plan = crate::merge::build_plan(self)?;
self.commit_merge(plan);
Ok(())
}
fn commit_merge(&mut self, plan: MergePlan) {
if plan.is_empty() {
return;
}
let folded: FxHashSet<(usize, u16)> =
plan.folded().iter().map(|&(at, _)| at).collect();
for (at, carrier) in plan.folded() {
self.folding.alias(at, carrier);
}
self.outputs.drop_members(&folded);
for (file, section, size) in plan.carrier_sizes() {
self.outputs.set_member_size(file, section, size);
}
self.debug
.relayout(|file, section| plan.member_size(file, section));
self.merge = plan;
}
pub fn group_start_stop(&mut self) {
if self.start_stop.is_empty() {
return;
}
let Self {
outputs,
start_stop,
..
} = self;
outputs.group_runs(|file, section| {
start_stop.run_of_section(file, section)
});
}
pub fn report(&self) {
println!("xold: {} input file(s)", self.files.len());
let mut rows: Vec<(&[u8], &Symbol)> = self.symbols.entries().collect();
rows.sort_by(|a, b| a.0.cmp(b.0));
let mut defined = 0usize;
let mut common = 0usize;
let mut undefined = 0usize;
println!("global symbols:");
for (name, sym) in &rows {
match &sym.kind {
SymbolKind::Defined(def) => {
defined = defined.saturating_add(1);
println!(
" {:<20} defined {}",
show(name),
self.describe_definition(def)
);
}
SymbolKind::Common { size, .. } => {
common = common.saturating_add(1);
println!(" {:<20} common size={size}", show(name));
}
SymbolKind::Undefined { .. } => {
undefined = undefined.saturating_add(1);
println!(" {:<20} undefined", show(name));
}
}
}
println!(
" -> {defined} defined, {common} common, {undefined} undefined"
);
println!("output sections:");
for section in self.outputs.iter() {
if section.members.is_empty() {
continue;
}
println!(
" {:<10} size={:<6} align={:<3} members={}",
section.kind.name(),
section.size,
section.align,
section.members.len(),
);
}
}
fn describe_definition(&self, def: &Definition) -> String {
let file = self.files.get(def.file).map_or("?", InputFile::basename);
match &def.source {
DefSource::Section { index, .. } => {
format!("{} {}", file, self.section_name(def.file, *index))
}
DefSource::Absolute { value } => {
format!("{file} (absolute 0x{value:x})")
}
}
}
fn section_name(&self, file: usize, section: u16) -> String {
let Some(input) = self.files.get(file) else {
return String::new();
};
let Ok(obj) = input.object() else {
return String::new();
};
obj.sections().get(usize::from(section)).map_or_else(
|| format!("#{section}"),
|shdr| show(obj.section_name(shdr)),
)
}
}
const fn strong_undefined(kind: &SymbolKind) -> bool {
matches!(kind, SymbolKind::Undefined { weak: false })
}
pub fn link(inputs: &[Input<'_>]) -> Result<()> {
let opened = open_all(inputs)?;
let bytes: Vec<&[u8]> = opened.iter().map(InputBytes::bytes).collect();
pool::run(&bytes, || {
let (mut ctx, archives, _deps) = assemble_full(inputs, &bytes)?;
ctx.resolve_symbols()?;
ctx.pull_archives(&archives)?;
crate::defsym::define(&mut ctx)?;
ctx.assign_sections()?;
ctx.report();
Ok(())
})
}
#[derive(Clone, Copy)]
#[allow(clippy::struct_excessive_bools)]
pub struct Link<'a> {
pub inputs: &'a [Input<'a>],
pub output: &'a Path,
pub mode: LinkMode,
pub entry: &'a [u8],
pub soname: Option<&'a [u8]>,
pub interpreter: Option<&'a [u8]>,
pub gc: bool,
pub export_dynamic: bool,
pub icf: IcfMode,
pub strip: Strip,
pub hash_style: HashStyle,
pub rpath: &'a [u8],
pub build_id: Option<&'a BuildId>,
pub undefined: &'a [&'a [u8]],
pub version_script: Option<&'a VersionScript>,
pub undefined_version: bool,
pub pie: Option<bool>,
pub no_undefined: bool,
pub z: ZOptions,
pub relax: bool,
}
const DEFAULT_ENTRY: &[u8] = b"_start";
impl<'a> Link<'a> {
pub const fn exec(inputs: &'a [Input<'a>], output: &'a Path) -> Self {
Self {
inputs,
output,
mode: LinkMode::Static,
entry: DEFAULT_ENTRY,
soname: None,
interpreter: None,
gc: false,
export_dynamic: false,
icf: IcfMode::None,
relax: true,
no_undefined: false,
z: ZOptions::new(),
pie: None,
strip: Strip::None,
hash_style: HashStyle::Both,
rpath: b"",
build_id: None,
undefined: &[],
version_script: None,
undefined_version: true,
}
}
pub const fn shared(inputs: &'a [Input<'a>], output: &'a Path) -> Self {
Self {
mode: LinkMode::Shared,
entry: b"",
..Self::exec(inputs, output)
}
}
pub const fn dyn_exec(
inputs: &'a [Input<'a>],
output: &'a Path,
interpreter: &'a [u8],
) -> Self {
Self {
mode: LinkMode::DynExec,
interpreter: Some(interpreter),
..Self::exec(inputs, output)
}
}
}
pub fn link_image(job: &Link<'_>) -> Result<()> {
let opened = open_all(job.inputs)?;
let bytes: Vec<&[u8]> = opened.iter().map(InputBytes::bytes).collect();
pool::run(&bytes, || link_opened(job, &bytes))
}
fn link_opened<'a>(job: &Link<'_>, bytes: &'a [&'a [u8]]) -> Result<()> {
let Link {
inputs,
output,
mode,
entry,
soname,
interpreter,
gc,
export_dynamic,
icf,
relax,
no_undefined,
z,
pie,
strip,
hash_style,
rpath,
build_id,
undefined,
version_script,
undefined_version,
} = *job;
let (mut ctx, archives, deps) = assemble_full(inputs, bytes)?;
ctx.gc = gc;
ctx.export_dynamic = export_dynamic;
ctx.icf = icf;
ctx.resolve_symbols()?;
force_undefined(&mut ctx, undefined)?;
ctx.pull_archives(&archives)?;
crate::defsym::define(&mut ctx)?;
if no_undefined {
check_no_undefined(&ctx)?;
}
if let Some(script) = version_script {
apply_version_script(&mut ctx, script, undefined_version)?;
}
ctx.assign_sections()?;
ctx.gc_sections(entry, undefined, mode)?;
ctx.merge_sections()?;
ctx.icf_sections(mode)?;
ctx.split_eh_frame()?;
ctx.group_start_stop();
let target = derive_target(&ctx)?;
check_dep_machines(&deps, target)?;
let mut needed: Vec<&[u8]> = Vec::new();
needed_sonames(&ctx, &deps, mode, &mut needed);
let config = DynConfig {
relax,
z,
pie,
strip,
hash_style,
rpath,
build_id,
soname,
interpreter,
needed: &needed,
};
let mut layout = crate::layout::build(&ctx, target, mode, entry, &config)?;
crate::writer::write(&ctx, target, &mut layout, mode, &config, output)
}
fn force_undefined(ctx: &mut Context<'_>, names: &[&[u8]]) -> Result<()> {
for &name in names {
if ctx.symbols.find(name).is_some() {
continue;
}
let inc = InputSymbol {
name,
binding: STB_GLOBAL,
type_: STT_NOTYPE,
visibility: STV_DEFAULT,
shndx: SHN_UNDEF,
value: 0,
size: 0,
sym_idx: 0,
name_hash: crate::symbol::name_hash(name),
};
ctx.symbols.intern(&inc, 0)?;
}
Ok(())
}
fn apply_version_script(
ctx: &mut Context<'_>,
script: &VersionScript,
undefined_version: bool,
) -> Result<()> {
if !undefined_version {
for name in script.exact_names() {
let defined = ctx
.symbols
.find(name)
.and_then(|id| ctx.symbols.symbol(id))
.is_some_and(|sym| {
!matches!(sym.kind, SymbolKind::Undefined { .. })
});
if !defined {
return Err(Error::CommandLine(format!(
"the version script names `{}`, which this link does not \
define; --no-undefined-version is in force",
String::from_utf8_lossy(name)
)));
}
}
}
if !script.hides_anything() {
return Ok(());
}
let hide: Vec<SymbolId> = ctx
.symbols
.entries()
.filter(|(_, sym)| !matches!(sym.kind, SymbolKind::Undefined { .. }))
.filter(|(name, _)| script.visibility(name) == VersionVisibility::Local)
.filter_map(|(name, _)| ctx.symbols.find(name))
.collect();
for id in hide {
ctx.symbols.hide(id);
}
Ok(())
}
fn check_no_undefined(ctx: &Context<'_>) -> Result<()> {
let mut missing: Vec<&[u8]> = Vec::new();
for (name, sym) in ctx.symbols.entries() {
if !matches!(sym.kind, SymbolKind::Undefined { weak: false }) {
continue;
}
if ctx.dep_exports.contains(name) {
continue;
}
missing.push(name);
}
let Some(&first) = missing.first() else {
return Ok(());
};
let name = String::from_utf8_lossy(first);
let report = match missing.len() {
1 => name.into_owned(),
n => format!("{name} (and {} more)", n - 1),
};
Err(Error::UndefinedReference(report))
}
pub fn link_to(
paths: &[PathBuf],
output: &Path,
entry: &[u8],
gc: bool,
icf: IcfMode,
relax: bool,
) -> Result<()> {
let inputs = Input::from_paths(paths);
link_image(&Link {
entry,
gc,
icf,
relax,
..Link::exec(&inputs, output)
})
}
pub fn link_shared(
paths: &[PathBuf],
output: &Path,
soname: Option<&[u8]>,
gc: bool,
icf: IcfMode,
relax: bool,
) -> Result<()> {
let inputs = Input::from_paths(paths);
link_image(&Link {
soname,
gc,
icf,
relax,
..Link::shared(&inputs, output)
})
}
pub fn link_dyn_exec(
paths: &[PathBuf],
output: &Path,
entry: &[u8],
interpreter: &[u8],
gc: bool,
icf: IcfMode,
relax: bool,
) -> Result<()> {
let inputs = Input::from_paths(paths);
link_image(&Link {
entry,
gc,
icf,
relax,
..Link::dyn_exec(&inputs, output, interpreter)
})
}
struct Assigned<'a> {
file: usize,
section: u16,
size: u64,
align: u64,
kind: Option<OutKind>,
run: Option<usize>,
mergeable: bool,
priority: i32,
shdr: &'a Shdr64,
name: &'a [u8],
}
const EH_FRAME: &[u8] = b".eh_frame";
const INIT: &[u8] = b".init";
const FINI: &[u8] = b".fini";
const DATA_REL_RO: &[u8] = b".data.rel.ro";
fn named_section(obj: ObjectFile<'_>, shdr: &Shdr64) -> Named {
if obj.section_name_is(shdr, EH_FRAME) {
return Named::EhFrame;
}
let flags = shdr.sh_flags.get();
if flags & SHF_EXECINSTR != 0 {
if obj.section_name_is(shdr, INIT) {
return Named::Init;
}
if obj.section_name_is(shdr, FINI) {
return Named::Fini;
}
}
if flags & (SHF_WRITE | SHF_TLS) == SHF_WRITE
&& shdr.sh_type.get() == SHT_PROGBITS
&& obj.section_name_starts_with(shdr, DATA_REL_RO)
{
return Named::DataRelRo;
}
Named::Other
}
fn array_priority(
kind: Option<OutKind>,
obj: ObjectFile<'_>,
shdr: &Shdr64,
) -> i32 {
match kind {
Some(
OutKind::PreinitArray | OutKind::InitArray | OutKind::FiniArray,
) => init_priority(obj.section_name(shdr)),
_ => NO_PRIORITY,
}
}
fn classify_sections<'a>(
file: usize,
input: &'a InputFile<'_>,
groups: &GroupDedup,
start_stop: &StartStop,
) -> Result<Vec<Assigned<'a>>> {
let obj = input.object()?;
let sections = obj.sections();
let mut out = Vec::with_capacity(sections.len() / 2);
let (mut lto, mut content) = (false, false);
for (index, shdr) in sections.iter().enumerate() {
if shdr.sh_type.get() == SHT_NULL {
continue;
}
let section = u16::try_from(index)
.map_err(|_| Error::OutOfRange("section index"))?;
if groups.is_discarded(file, section) {
continue;
}
if obj.section_name_starts_with(shdr, LTO_PREFIX) {
lto = true;
}
if alloc_content(shdr) {
content = true;
}
if shdr.sh_flags.get() & SHF_EXCLUDE != 0 {
continue;
}
if shdr.sh_flags.get() & SHF_COMPRESSED != 0 {
return Err(Error::Format(
"compressed section (SHF_COMPRESSED): decompression is not \
implemented",
));
}
crate::util::check_align(
shdr.sh_addralign.get(),
"section alignment is not a usable power of two",
)?;
if shdr.sh_type.get() != SHT_NOBITS {
obj.section_data(shdr)?;
}
let alloc = shdr.sh_flags.get() & SHF_ALLOC != 0;
if !alloc {
if obj.section_name_starts_with(shdr, crate::debug::ZDEBUG_PREFIX) {
return Err(Error::Format(
"legacy zlib-compressed debug section (.zdebug_*): \
decompression is not implemented",
));
}
if !keeps_non_alloc(&obj, shdr) {
continue;
}
}
let kind =
alloc.then(|| OutKind::from_shdr(shdr, named_section(obj, shdr)));
out.push(Assigned {
file,
section,
size: shdr.sh_size.get(),
align: shdr.sh_addralign.get().max(1),
kind,
run: alloc.then(|| start_stop.run_of(obj, shdr)).flatten(),
mergeable: shdr.sh_flags.get() & SHF_MERGE != 0,
priority: array_priority(kind, obj, shdr),
shdr,
name: if alloc { &[] } else { obj.section_name(shdr) },
});
}
refuse_thin_lto(lto, content)?;
Ok(out)
}
fn alloc_content(shdr: &Shdr64) -> bool {
shdr.sh_flags.get() & SHF_ALLOC != 0
&& shdr.sh_size.get() != 0
&& shdr.sh_type.get() != SHT_NOTE
}
fn refuse_thin_lto(lto: bool, content: bool) -> Result<()> {
if lto && !content {
return Err(Error::Format(
"input holds GCC LTO bytecode and nothing else: link-time \
optimisation is not implemented, so build with -fno-lto or \
-ffat-lto-objects",
));
}
Ok(())
}
fn keeps_non_alloc(obj: &ObjectFile<'_>, shdr: &Shdr64) -> bool {
shdr.sh_type.get() == SHT_PROGBITS
&& shdr.sh_size.get() != 0
&& obj.section_name(shdr) != GNU_STACK_NOTE
}
const GNU_STACK_NOTE: &[u8] = b".note.GNU-stack";
const LTO_PREFIX: &[u8] = b".gnu.lto_";
pub(super) fn is_shared_object(bytes: &[u8]) -> bool {
ObjectFile::parse(bytes)
.is_ok_and(|obj| obj.header().e_type.get() == ET_DYN)
}
fn name_duplicate_files(err: Error, files: &[InputFile<'_>]) -> Error {
let Error::DuplicateSymbol(d) = err else {
return err;
};
let path = |raw: &str| {
raw.parse::<usize>()
.ok()
.and_then(|i| files.get(i))
.map_or_else(|| raw.to_string(), |f| f.path().display().to_string())
};
Error::duplicate_symbol(d.name, path(&d.first), path(&d.second))
}
pub(crate) fn in_input_order<T>(results: Vec<Result<T>>) -> Result<Vec<T>> {
results.into_iter().collect()
}
pub(crate) fn derive_target(ctx: &Context<'_>) -> Result<crate::reloc::Target> {
derive_target_inner(ctx)
}
pub(crate) fn derive_eflags(
ctx: &Context<'_>,
target: crate::reloc::Target,
) -> Result<u32> {
let mut flags: Option<u32> = None;
for input in &ctx.files {
let incoming = input.object()?.header().e_flags.get();
let merged = target.merge_eflags(flags, incoming).map_err(|what| {
Error::incompatible_input(input.path().display().to_string(), what)
})?;
flags = Some(merged);
}
Ok(flags.unwrap_or(0))
}