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.

88 lines
2.0 KiB
Rust

4 years ago
use std::{fmt::Display, path::PathBuf};
4 years ago
use crate::{
4 years ago
common::{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> {
4 years ago
let r = R::new(origin, self.relocatables.len())?;
4 years ago
// TODO: parallelize?
for section in r.sections() {
self.loadable.process_section(section?)?;
4 years ago
}
self.relocatables.push(r);
4 years ago
Ok(())
4 years ago
}
4 years ago
pub fn link(mut self) -> Result<PathBuf, Error> {
self.process_symbols()?;
4 years ago
self.loadable.set_start_offset(4096); // TODO: get from .start symbol location
self.output.finalize(&self.relocatables, &self.loadable)
4 years ago
}
fn process_symbols(&mut self) -> Result<(), Error> {
for r in &self.relocatables {
4 years ago
for (name, symbol) in r.symbols() {
self.loadable.process_symbol(name, symbol)?;
}
}
Ok(())
}
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(())
}
}