pub mod aarch64;
pub mod coff_i386;
pub mod coff_x86_64;
pub mod macho_arm64;
pub mod macho_x86_64;
pub mod riscv;
pub mod x86_64;
use std::ops::Range;
use crate::{
elf::{
Rela64,
constants::{EM_AARCH64, EM_RISCV, EM_X86_64},
},
error::{Error, Result},
symbol::SymbolId,
};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum RelExpr {
None,
Abs,
Pc,
Got,
GotOffset,
GotPc,
TlsGotPc,
TlsIndexPc,
DtpOff,
GotOff,
GotBase,
Plt,
PltPc,
Size,
Escape,
}
impl RelExpr {
pub fn compute<R: Resolver>(
self,
sym: Option<SymbolId>,
addend: i64,
place: u64,
resolver: &R,
) -> Result<u64> {
let a = addend.cast_unsigned();
let sym_addr = || sym.map_or(0, |id| resolver.symbol_addr(id));
let got_addr = || sym.map_or(0, |id| resolver.got_addr(id));
let plt_addr = || sym.map_or(0, |id| resolver.plt_addr(id));
let value = match self {
Self::Abs => sym_addr().wrapping_add(a),
Self::Pc => sym_addr().wrapping_add(a).wrapping_sub(place),
Self::Got => got_addr().wrapping_add(a),
Self::GotOffset => {
got_addr().wrapping_sub(resolver.got_base()).wrapping_add(a)
}
Self::GotPc => got_addr().wrapping_add(a).wrapping_sub(place),
Self::TlsGotPc => sym
.map_or(0, |id| resolver.tls_got_addr(id))
.wrapping_add(a)
.wrapping_sub(place),
Self::TlsIndexPc => match resolver.tls_index_addr() {
0 => return Err(Error::UnsupportedReloc(0)),
index => index.wrapping_add(a).wrapping_sub(place),
},
Self::DtpOff => {
sym.map_or(0, |id| resolver.tls_dtp_off(id)).wrapping_add(a)
}
Self::GotOff => {
sym_addr().wrapping_add(a).wrapping_sub(resolver.got_base())
}
Self::GotBase => {
resolver.got_base().wrapping_add(a).wrapping_sub(place)
}
Self::Plt => plt_addr().wrapping_add(a),
Self::PltPc => plt_addr().wrapping_add(a).wrapping_sub(place),
Self::Size => {
sym.map_or(0, |id| resolver.sym_size(id)).wrapping_add(a)
}
Self::None => 0,
Self::Escape => return Err(Error::UnsupportedReloc(0)),
};
Ok(value)
}
pub const fn needs(self) -> Needs {
match self {
Self::Got | Self::GotOffset | Self::GotPc => Needs {
got: true,
..Needs::NONE
},
Self::TlsGotPc => Needs {
tls_got: true,
..Needs::NONE
},
Self::Plt | Self::PltPc => Needs {
plt: true,
..Needs::NONE
},
Self::Size => Needs {
size: true,
..Needs::NONE
},
_ => Needs::NONE,
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Write {
Bytes(WriteKind),
Field(Field),
}
impl Write {
pub fn width(self) -> usize {
match self {
Self::Bytes(k) => k.width(),
Self::Field(f) => usize::from(f.cell_bytes),
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum WriteKind {
W8,
W16,
W16SU,
W32,
W32S,
W32SU,
W64,
}
impl WriteKind {
pub const fn width(self) -> usize {
match self {
Self::W8 => 1,
Self::W16 | Self::W16SU => 2,
Self::W32 | Self::W32S | Self::W32SU => 4,
Self::W64 => 8,
}
}
const fn fits(self, value: u64) -> bool {
match self {
Self::W64 => true,
Self::W32 => value <= u32::MAX as u64,
Self::W16 => value <= u16::MAX as u64,
Self::W8 => value <= u8::MAX as u64,
Self::W32S => fits_signed(value, 32),
Self::W32SU => value <= u32::MAX as u64 || fits_signed(value, 32),
Self::W16SU => value <= u16::MAX as u64 || fits_signed(value, 16),
}
}
fn store(self, value: u64, out: &mut [u8]) {
match self {
#[allow(clippy::cast_possible_truncation)]
Self::W8 => out[0] = value as u8,
#[allow(clippy::cast_possible_truncation)]
Self::W16 | Self::W16SU => {
out.copy_from_slice(&(value as u16).to_le_bytes());
}
#[allow(clippy::cast_possible_truncation)]
Self::W32 | Self::W32SU => {
out.copy_from_slice(&(value as u32).to_le_bytes());
}
#[allow(clippy::cast_possible_truncation)]
Self::W32S => out.copy_from_slice(&(value as i32).to_le_bytes()),
Self::W64 => out.copy_from_slice(&value.to_le_bytes()),
}
}
}
const fn fits_signed(value: u64, bits: u32) -> bool {
let bound = 1i64 << (bits - 1);
let signed = value.cast_signed();
signed >= -bound && signed < bound
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Check {
None,
Unsigned,
Signed,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Field {
pub cell_bytes: u8,
pub right_shift: u8,
pub left_shift: u8,
pub width: u8,
pub check: Check,
pub align_bits: u8,
}
impl Field {
pub const fn new(
cell_bytes: u8,
right_shift: u8,
left_shift: u8,
width: u8,
check: Check,
) -> Self {
Self {
cell_bytes,
right_shift,
left_shift,
width,
check,
align_bits: 0,
}
}
pub const fn scaled(
cell_bytes: u8,
scale: u8,
left_shift: u8,
width: u8,
check: Check,
) -> Self {
Self {
cell_bytes,
right_shift: scale,
left_shift,
width,
check,
align_bits: scale,
}
}
pub fn aligned(self, value: u64) -> bool {
if self.align_bits == 0 {
return true;
}
value & ((1u64 << self.align_bits) - 1) == 0
}
pub fn fits(self, value: u64) -> bool {
let total =
u32::from(self.width).saturating_add(u32::from(self.right_shift));
match self.check {
Check::None => true,
Check::Unsigned => {
if total >= 64 {
return true;
}
value >> total == 0
}
Check::Signed => total >= 64 || fits_signed(value, total),
}
}
pub fn store(self, value: u64, out: &mut [u8]) {
let n = usize::from(self.cell_bytes);
let cell = read_le(out, n);
let scaled: u64 = match self.check {
Check::Signed => {
(value.cast_signed() >> self.right_shift).cast_unsigned()
}
Check::None | Check::Unsigned => value >> self.right_shift,
};
let width_mask: u64 = (1u64 << self.width) - 1;
let mask = width_mask << self.left_shift;
let field = (scaled & width_mask) << self.left_shift;
let patched = (cell & !mask) | field;
write_le(out, n, patched);
}
}
fn read_le(buf: &[u8], n: usize) -> u64 {
let mut wide = [0u8; 8];
wide[..n].copy_from_slice(&buf[..n]);
u64::from_le_bytes(wide)
}
fn write_le(buf: &mut [u8], n: usize, value: u64) {
buf[..n].copy_from_slice(&value.to_le_bytes()[..n]);
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Spec {
pub expr: RelExpr,
pub write: Write,
}
const fn of(expr: RelExpr, write: Write) -> Spec {
Spec { expr, write }
}
const fn bytes_of(expr: RelExpr, write: WriteKind) -> Spec {
of(expr, Write::Bytes(write))
}
const fn insn_cell(cell_bytes: u8) -> Field {
Field::new(cell_bytes, 0, 0, 0, Check::None)
}
const fn branch26() -> Field {
Field::scaled(4, 2, 0, 26, Check::Signed)
}
const fn page(addr: u64) -> u64 {
addr & !0xFFF
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[allow(clippy::struct_excessive_bools)]
pub struct Needs {
pub got: bool,
pub plt: bool,
pub tls_got: bool,
pub size: bool,
}
impl Needs {
pub const NONE: Self = Self {
got: false,
plt: false,
tls_got: false,
size: false,
};
}
pub trait Resolver {
fn symbol_addr(&self, sym: SymbolId) -> u64;
fn got_addr(&self, sym: SymbolId) -> u64;
fn got_base(&self) -> u64;
fn plt_addr(&self, sym: SymbolId) -> u64;
fn tls_index_addr(&self) -> u64 {
0
}
fn tls_dtp_off(&self, sym: SymbolId) -> u64 {
let _ = sym;
0
}
fn sym_size(&self, sym: SymbolId) -> u64 {
let _ = sym;
0
}
fn tls_got_addr(&self, sym: SymbolId) -> u64 {
let _ = sym;
0
}
fn is_exec(&self) -> bool {
false
}
fn is_preemptible(&self, sym: SymbolId) -> bool {
let _ = sym;
true
}
fn is_absolute(&self, sym: SymbolId) -> bool {
let _ = sym;
true
}
fn has_got_slot(&self, sym: SymbolId) -> bool {
let _ = sym;
true
}
fn is_undef_weak(&self, sym: SymbolId) -> bool {
let _ = sym;
false
}
}
#[derive(Clone, Copy)]
pub struct RelaxSite<'a> {
pub r_type: u32,
pub sym: Option<SymbolId>,
pub addend: i64,
pub place: u64,
pub data: &'a [u8],
pub slot: u64,
}
pub trait Arch {
fn spec(r_type: u32) -> Result<Spec>;
fn scan_needs(r_type: u32) -> Result<Needs> {
Ok(Self::spec(r_type)?.expr.needs())
}
fn escape<R: Resolver>(
r_type: u32,
_sym: Option<SymbolId>,
_addend: i64,
_place: u64,
_resolver: &R,
_out: &mut [u8],
) -> Result<()> {
Err(Error::UnsupportedReloc(r_type))
}
fn undef_weak_pc(r_type: u32, addend: i64, place: u64) -> u64 {
let _ = r_type;
addend.cast_unsigned().wrapping_sub(place)
}
fn relax_lead(r_type: u32) -> usize {
let _ = r_type;
0
}
fn relax_covers(r_type: u32) -> bool {
Self::relax_lead(r_type) != 0
}
fn relax_drops_got(_r_type: u32, _addend: i64, _lead: &[u8]) -> bool {
false
}
fn relax_required<R: Resolver>(
r_type: u32,
sym: Option<SymbolId>,
resolver: &R,
) -> bool {
let _ = (r_type, sym, resolver);
false
}
fn relax_trail(r_type: u32, slot: &[u8], after: &[u8]) -> usize {
let _ = (r_type, slot, after);
0
}
fn relax_span<R: Resolver>(
site: RelaxSite<'_>,
resolver: &R,
) -> Option<Range<u64>> {
let _ = (site, resolver);
None
}
fn spans_type(r_type: u32) -> bool {
let _ = r_type;
false
}
fn relax<R: Resolver>(
r_type: u32,
_sym: Option<SymbolId>,
_addend: i64,
_place: u64,
_resolver: &R,
_window: &mut [u8],
) -> Result<bool> {
let _ = r_type;
Ok(false)
}
}
#[derive(Clone, Copy, Debug)]
pub struct Reloc {
pub r_type: u32,
pub sym: u32,
pub addend: i64,
pub offset: u64,
}
impl Reloc {
pub const fn from_rela(r: &Rela64) -> Self {
Self {
r_type: r.r_type(),
sym: r.sym(),
addend: r.r_addend.get(),
offset: r.r_offset.get(),
}
}
}
pub fn apply<A: Arch, R: Resolver>(
r_type: u32,
sym: Option<SymbolId>,
addend: i64,
place: u64,
resolver: &R,
out: &mut [u8],
) -> Result<()> {
let spec = A::spec(r_type)?;
if spec.expr == RelExpr::Escape {
return A::escape(r_type, sym, addend, place, resolver, out);
}
if spec.expr == RelExpr::None {
return Ok(());
}
let write = spec.write;
if out.len() != write.width() {
return Err(Error::OutOfRange("relocation output slot"));
}
let value = match spec.expr {
RelExpr::Pc => pc_value::<A, R>(r_type, sym, addend, place, resolver)?,
RelExpr::PltPc => {
plt_pc_value::<A, R>(r_type, sym, addend, place, resolver)?
}
_ => spec.expr.compute(sym, addend, place, resolver)?,
};
match write {
Write::Bytes(k) => {
if !k.fits(value) {
return Err(Error::RelocOverflow(r_type));
}
k.store(value, out);
}
Write::Field(f) => {
if !f.aligned(value) {
return Err(Error::RelocMisaligned(r_type));
}
if !f.fits(value) {
return Err(Error::RelocOverflow(r_type));
}
f.store(value, out);
}
}
Ok(())
}
pub fn scan<A: Arch>(r_type: u32) -> Result<Needs> {
A::scan_needs(r_type)
}
pub(crate) fn pc_value<A: Arch, R: Resolver>(
r_type: u32,
sym: Option<SymbolId>,
addend: i64,
place: u64,
resolver: &R,
) -> Result<u64> {
if sym.is_some_and(|id| resolver.is_undef_weak(id)) {
return Ok(A::undef_weak_pc(r_type, addend, place));
}
RelExpr::Pc.compute(sym, addend, place, resolver)
}
pub(crate) fn plt_pc_value<A: Arch, R: Resolver>(
r_type: u32,
sym: Option<SymbolId>,
addend: i64,
place: u64,
resolver: &R,
) -> Result<u64> {
let entry = sym.map_or(0, |id| resolver.plt_addr(id));
if entry == 0 && sym.is_some_and(|id| resolver.is_undef_weak(id)) {
return Ok(A::undef_weak_pc(r_type, addend, place));
}
RelExpr::PltPc.compute(sym, addend, place, resolver)
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Target {
X86_64,
AArch64,
Riscv64,
}
impl Target {
pub fn from_machine(e_machine: u16) -> Result<Self> {
match e_machine {
EM_X86_64 => Ok(Self::X86_64),
EM_AARCH64 => Ok(Self::AArch64),
EM_RISCV => Ok(Self::Riscv64),
_ => Err(Error::Format("unsupported e_machine")),
}
}
pub const fn machine(self) -> u16 {
match self {
Self::X86_64 => EM_X86_64,
Self::AArch64 => EM_AARCH64,
Self::Riscv64 => EM_RISCV,
}
}
pub const fn dyn_relocs(self) -> DynRelocs {
match self {
Self::X86_64 => DynRelocs {
relative: x86_64::R_X86_64_RELATIVE,
glob_dat: x86_64::R_X86_64_GLOB_DAT,
jump_slot: x86_64::R_X86_64_JUMP_SLOT,
copy: x86_64::R_X86_64_COPY,
irelative: x86_64::R_X86_64_IRELATIVE,
dtpmod: x86_64::R_X86_64_DTPMOD64,
dtpoff: x86_64::R_X86_64_DTPOFF64,
tpoff: x86_64::R_X86_64_TPOFF64,
abs64: x86_64::R_X86_64_64,
},
Self::AArch64 => DynRelocs {
relative: aarch64::R_AARCH64_RELATIVE,
glob_dat: aarch64::R_AARCH64_GLOB_DAT,
jump_slot: aarch64::R_AARCH64_JUMP_SLOT,
copy: aarch64::R_AARCH64_COPY,
irelative: aarch64::R_AARCH64_IRELATIVE,
dtpmod: aarch64::R_AARCH64_TLS_DTPMOD64,
dtpoff: aarch64::R_AARCH64_TLS_DTPREL64,
tpoff: aarch64::R_AARCH64_TLS_TPREL64,
abs64: aarch64::R_AARCH64_ABS64,
},
Self::Riscv64 => DynRelocs {
relative: riscv::R_RISCV_RELATIVE,
glob_dat: riscv::R_RISCV_64,
jump_slot: riscv::R_RISCV_JUMP_SLOT,
copy: riscv::R_RISCV_COPY,
irelative: riscv::R_RISCV_IRELATIVE,
dtpmod: riscv::R_RISCV_TLS_DTPMOD64,
dtpoff: riscv::R_RISCV_TLS_DTPREL64,
tpoff: riscv::R_RISCV_TLS_TPREL64,
abs64: riscv::R_RISCV_64,
},
}
}
pub fn merge_eflags(
self,
so_far: Option<u32>,
incoming: u32,
) -> core::result::Result<u32, &'static str> {
match self {
Self::X86_64 | Self::AArch64 => Ok(0),
Self::Riscv64 => riscv::merge_eflags(so_far, incoming),
}
}
pub const fn plt_spec(self) -> PltSpec {
match self {
Self::X86_64 => PltSpec {
header_size: 16,
entry_size: 16,
got_plt_reserved: 3,
},
Self::AArch64 => PltSpec {
header_size: 32,
entry_size: 16,
got_plt_reserved: 3,
},
Self::Riscv64 => PltSpec {
header_size: 32,
entry_size: 16,
got_plt_reserved: 2,
},
}
}
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct DynRelocs {
pub relative: u32,
pub glob_dat: u32,
pub jump_slot: u32,
pub copy: u32,
pub irelative: u32,
pub abs64: u32,
pub tpoff: u32,
pub dtpmod: u32,
pub dtpoff: u32,
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct PltSpec {
pub header_size: u64,
pub entry_size: u64,
pub got_plt_reserved: u64,
}
pub fn scan_target(target: Target, r_type: u32) -> Result<Needs> {
match target {
Target::X86_64 => scan::<x86_64::X86_64>(r_type),
Target::AArch64 => scan::<aarch64::AArch64>(r_type),
Target::Riscv64 => scan::<riscv::Riscv64>(r_type),
}
}
pub fn spec_target(target: Target, r_type: u32) -> Result<Spec> {
match target {
Target::X86_64 => x86_64::X86_64::spec(r_type),
Target::AArch64 => aarch64::AArch64::spec(r_type),
Target::Riscv64 => riscv::Riscv64::spec(r_type),
}
}
pub fn apply_target<R: Resolver>(
target: Target,
r_type: u32,
sym: Option<SymbolId>,
addend: i64,
place: u64,
resolver: &R,
out: &mut [u8],
) -> Result<()> {
match target {
Target::X86_64 => apply::<x86_64::X86_64, R>(
r_type, sym, addend, place, resolver, out,
),
Target::AArch64 => apply::<aarch64::AArch64, R>(
r_type, sym, addend, place, resolver, out,
),
Target::Riscv64 => apply::<riscv::Riscv64, R>(
r_type, sym, addend, place, resolver, out,
),
}
}
pub fn relax_lead_target(target: Target, r_type: u32) -> usize {
match target {
Target::X86_64 => x86_64::X86_64::relax_lead(r_type),
Target::AArch64 => aarch64::AArch64::relax_lead(r_type),
Target::Riscv64 => riscv::Riscv64::relax_lead(r_type),
}
}
pub fn relax_drops_got_target(
target: Target,
r_type: u32,
addend: i64,
lead: &[u8],
) -> bool {
match target {
Target::X86_64 => x86_64::X86_64::relax_drops_got(r_type, addend, lead),
Target::AArch64 => {
aarch64::AArch64::relax_drops_got(r_type, addend, lead)
}
Target::Riscv64 => {
riscv::Riscv64::relax_drops_got(r_type, addend, lead)
}
}
}
pub fn relax_covers_target(target: Target, r_type: u32) -> bool {
match target {
Target::X86_64 => x86_64::X86_64::relax_covers(r_type),
Target::AArch64 => aarch64::AArch64::relax_covers(r_type),
Target::Riscv64 => riscv::Riscv64::relax_covers(r_type),
}
}
pub fn relax_required_target<R: Resolver>(
target: Target,
r_type: u32,
sym: Option<SymbolId>,
resolver: &R,
) -> bool {
match target {
Target::X86_64 => x86_64::X86_64::relax_required(r_type, sym, resolver),
Target::AArch64 => {
aarch64::AArch64::relax_required(r_type, sym, resolver)
}
Target::Riscv64 => {
riscv::Riscv64::relax_required(r_type, sym, resolver)
}
}
}
pub fn relax_trail_target(
target: Target,
r_type: u32,
slot: &[u8],
after: &[u8],
) -> usize {
match target {
Target::X86_64 => x86_64::X86_64::relax_trail(r_type, slot, after),
Target::AArch64 => aarch64::AArch64::relax_trail(r_type, slot, after),
Target::Riscv64 => riscv::Riscv64::relax_trail(r_type, slot, after),
}
}
pub fn relax_span_target<R: Resolver>(
target: Target,
site: RelaxSite<'_>,
resolver: &R,
) -> Option<Range<u64>> {
match target {
Target::X86_64 => x86_64::X86_64::relax_span(site, resolver),
Target::AArch64 => aarch64::AArch64::relax_span(site, resolver),
Target::Riscv64 => riscv::Riscv64::relax_span(site, resolver),
}
}
pub fn relax_spans_type(target: Target, r_type: u32) -> bool {
match target {
Target::X86_64 => x86_64::X86_64::spans_type(r_type),
Target::AArch64 => aarch64::AArch64::spans_type(r_type),
Target::Riscv64 => riscv::Riscv64::spans_type(r_type),
}
}
pub fn relax_target<R: Resolver>(
target: Target,
r_type: u32,
sym: Option<SymbolId>,
addend: i64,
place: u64,
resolver: &R,
window: &mut [u8],
) -> Result<bool> {
match target {
Target::X86_64 => {
x86_64::X86_64::relax(r_type, sym, addend, place, resolver, window)
}
Target::AArch64 => aarch64::AArch64::relax(
r_type, sym, addend, place, resolver, window,
),
Target::Riscv64 => {
riscv::Riscv64::relax(r_type, sym, addend, place, resolver, window)
}
}
}