You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
1.8 KiB
Rust

4 years ago
use std::{
fmt::Display,
io::ErrorKind,
path::{Path, PathBuf},
};
4 years ago
use crate::{
common::{DataIndex, Loadable, Output, Relocatable},
error::Error,
};
4 years ago
pub struct Linker<R, O>
4 years ago
where
R: Relocatable,
O: Output<R>,
4 years ago
{
relocatables: Vec<R>,
loadable: Loadable,
4 years ago
output: O,
4 years ago
}
impl<R, O> Linker<R, O>
4 years ago
where
R: Relocatable,
O: Output<R>,
4 years ago
{
pub fn new(output: O) -> Self {
Self {
relocatables: Vec::new(),
loadable: Loadable::default(),
4 years ago
output,
}
4 years ago
}
4 years ago
pub fn add_relocatable(&mut self, origin: PathBuf) -> Result<(), Error> {
self.relocatables.push(R::new(
origin,
DataIndex::for_object(self.relocatables.len()),
)?);
4 years ago
Ok(())
4 years ago
}
4 years ago
pub fn link(mut self) -> Result<PathBuf, Error> {
4 years ago
for r in self.relocatables.iter() {
for s in r.sections() {
self.loadable.process_section(s?)?;
4 years ago
}
}
self.loadable.start_offset = Some(4096); // TODO: get from .start symbol location
self.output.finalize(&self.relocatables, &self.loadable)
4 years ago
}
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)
}
}
4 years ago
}
impl<R, O> Display for Linker<R, O>
4 years ago
where
R: Relocatable,
O: Output<R>,
4 years ago
{
4 years ago
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(f, "===Relocatables===")?;
4 years ago
for r in self.relocatables.iter() {
write!(f, "{}", r)?;
4 years ago
}
Ok(())
}
}