Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add alignment check to ElfBinary::new #41

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions src/binary.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@ impl<'s> fmt::Debug for ElfBinary<'s> {
impl<'s> ElfBinary<'s> {
/// Create a new ElfBinary.
pub fn new(region: &'s [u8]) -> Result<ElfBinary<'s>, ElfLoaderErr> {
// Verify that the slice is aligned properly
if !crate::is_aligned_to(region.as_ptr() as usize, crate::ALIGNMENT) {
return Err(ElfLoaderErr::UnalignedMemory);
}

let file = ElfFile::new(region)?;

// Parse relevant parts out of the the .dynamic section
Expand Down Expand Up @@ -382,3 +387,42 @@ impl<'s> ElfBinary<'s> {
self.file.program_iter().filter(select_load)
}
}

#[test]
fn test_load_unaligned() {
use core::ops::Deref;

#[repr(C, align(8))]
struct AlignedStackBuffer([u8; 8096]);
impl Deref for AlignedStackBuffer {
type Target = [u8; 8096];
fn deref(&self) -> &Self::Target {
&self.0
}
}

impl AlignedStackBuffer {
fn slice_at_index(&self, index: usize) -> &[u8] {
&self.0[index..]
}

fn buffer_from_file(&mut self, path: &str) {
let data = std::fs::read(path).unwrap();
let max = core::cmp::min(data.len(), self.0.len());
self.0[..max].copy_from_slice(&data[..max]);
}
}

// Read the file into an aligned buffer
let mut aligned = AlignedStackBuffer([0u8; 8096]);
aligned.buffer_from_file("test/test.riscv64");

// Verify aligned version works
let result = ElfBinary::new(aligned.deref());
assert!(result.is_ok());

// Verify unaligned version fails with appropriate error
let unaligned = aligned.slice_at_index(1);
let result = ElfBinary::new(unaligned);
assert_eq!(result.err().unwrap(), ElfLoaderErr::UnalignedMemory);
}
17 changes: 16 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,16 @@ use bitflags::bitflags;
use xmas_elf::dynamic::*;
use xmas_elf::program::ProgramIter;

pub use xmas_elf::header::Machine;
pub use xmas_elf::header::{Header, Machine};
pub use xmas_elf::program::{Flags, ProgramHeader, ProgramHeader64};
pub use xmas_elf::sections::{Rel, Rela};
pub use xmas_elf::symbol_table::{Entry, Entry64};
pub use xmas_elf::{P32, P64};

/// Required alignment for zero-copy reads provided to xmas_elf by the
/// zero crate.
pub(crate) const ALIGNMENT: usize = core::mem::align_of::<Header>();

/// An iterator over [`ProgramHeader`] whose type is `LOAD`.
pub type LoadableHeaders<'a, 'b> = Filter<ProgramIter<'a, 'b>, fn(&ProgramHeader) -> bool>;
pub type PAddr = u64;
Expand All @@ -47,6 +51,7 @@ pub struct RelocationEntry {
pub enum ElfLoaderErr {
ElfParser { source: &'static str },
OutOfMemory,
UnalignedMemory,
SymbolTableNotFound,
UnsupportedElfFormat,
UnsupportedElfVersion,
Expand All @@ -69,6 +74,7 @@ impl fmt::Display for ElfLoaderErr {
match self {
ElfLoaderErr::ElfParser { source } => write!(f, "Error in ELF parser: {}", source),
ElfLoaderErr::OutOfMemory => write!(f, "Out of memory"),
ElfLoaderErr::UnalignedMemory => write!(f, "Data must be aligned to {:?}", ALIGNMENT),
ElfLoaderErr::SymbolTableNotFound => write!(f, "No symbol table in the ELF file"),
ElfLoaderErr::UnsupportedElfFormat => write!(f, "ELF format not supported"),
ElfLoaderErr::UnsupportedElfVersion => write!(f, "ELF version not supported"),
Expand Down Expand Up @@ -166,6 +172,15 @@ pub trait ElfLoader {
}
}

/// Utility function to verify alignment.
///
/// Note: this may be stabilized in the future as:
///
/// [core::ptr::is_aligned_to](https://doc.rust-lang.org/core/primitive.pointer.html#method.is_aligned_to)
pub(crate) fn is_aligned_to(ptr: usize, align: usize) -> bool {
ptr & (align - 1) == 0
}

#[cfg(doctest)]
mod test_readme {
macro_rules! external_doc_test {
Expand Down