|
|
|
use std::{fmt::Display, io::ErrorKind, path::{Path, PathBuf}};
|
|
|
|
|
|
|
|
use crate::{
|
|
|
|
common::{Output, Relocatable},
|
|
|
|
error::Error,
|
|
|
|
};
|
|
|
|
|
|
|
|
pub struct Linker<R, O>
|
|
|
|
where
|
|
|
|
R: Relocatable,
|
|
|
|
O: Output<R>,
|
|
|
|
{
|
|
|
|
relocatables: Vec<R>,
|
|
|
|
output: O,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<R, O> Linker<R, O>
|
|
|
|
where
|
|
|
|
R: Relocatable,
|
|
|
|
O: Output<R>,
|
|
|
|
{
|
|
|
|
pub fn new(output: O) -> Self {
|
|
|
|
Self {
|
|
|
|
relocatables: Vec::new(),
|
|
|
|
output,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn add_relocatable(&mut self, path: PathBuf) -> Result<(), Error> {
|
|
|
|
self.relocatables.push(R::try_from(path)?);
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn link(mut self) -> Result<PathBuf, Error> {
|
|
|
|
for r in self.relocatables.iter() {
|
|
|
|
for s in r.sections() {
|
|
|
|
self.output.process_section(s?)?;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
self.output.finalize(&self.relocatables)
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn object_path(origin: &Path) -> Result<PathBuf, Error> {
|
|
|
|
let mut dest = std::fs::canonicalize(origin)?;
|
|
|
|
if !dest.pop() {
|
|
|
|
let err = std::io::Error::new(ErrorKind::Other, "Destination path invalid");
|
|
|
|
Err(Error::IOError(Box::new(err)))
|
|
|
|
} else {
|
|
|
|
dest.push("rld.out");
|
|
|
|
Ok(dest)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<R, O> Display for Linker<R, O>
|
|
|
|
where
|
|
|
|
R: Relocatable,
|
|
|
|
O: Output<R>,
|
|
|
|
{
|
|
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
|
|
writeln!(f, "===Relocatables===")?;
|
|
|
|
|
|
|
|
for r in self.relocatables.iter() {
|
|
|
|
write!(f, "{}", r)?;
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|