Skip to content

Commit

Permalink
General cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
Lichtso committed Dec 6, 2023
1 parent b503a18 commit 1709f6e
Show file tree
Hide file tree
Showing 8 changed files with 23 additions and 51 deletions.
3 changes: 1 addition & 2 deletions src/aligned_memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ pub struct AlignedMemory<const ALIGN: usize> {
impl<const ALIGN: usize> AlignedMemory<ALIGN> {
fn get_mem(max_len: usize) -> (Vec<u8>, usize) {
let mut mem: Vec<u8> = Vec::with_capacity(max_len.saturating_add(ALIGN));
mem.push(0);
let align_offset = mem.as_ptr().align_offset(ALIGN);
mem.resize(align_offset, 0);
(mem, align_offset)
Expand Down Expand Up @@ -122,7 +121,7 @@ impl<const ALIGN: usize> AlignedMemory<ALIGN> {
_ => {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"aligned memory resize failed",
"aligned memory fill_write failed",
))
}
};
Expand Down
25 changes: 13 additions & 12 deletions src/assembler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,17 @@ fn insn(opc: u8, dst: i64, src: i64, off: i64, imm: i64) -> Result<Insn, String>
})
}

fn resolve_label(
insn_ptr: usize,
labels: &HashMap<&str, usize>,
label: &str,
) -> Result<i64, String> {
labels
.get(label)
.map(|target_pc| *target_pc as i64 - insn_ptr as i64 - 1)
.ok_or_else(|| format!("Label not found {label}"))
}

/// Parse assembly source and translate to binary.
///
/// # Examples
Expand Down Expand Up @@ -299,16 +310,6 @@ pub fn assemble<C: ContextObject>(
} else {
SBPFVersion::V1
};
fn resolve_label(
insn_ptr: usize,
labels: &HashMap<&str, usize>,
label: &str,
) -> Result<i64, String> {
labels
.get(label)
.map(|target_pc| *target_pc as i64 - insn_ptr as i64 - 1)
.ok_or_else(|| format!("Label not found {label}"))
}

let statements = parse(src)?;
let instruction_map = make_instruction_map();
Expand All @@ -321,7 +322,7 @@ pub fn assemble<C: ContextObject>(
Statement::Label { name } => {
if name.starts_with("function_") || name == "entrypoint" {
function_registry
.register_function(insn_ptr as u32, name.as_bytes().to_vec(), insn_ptr)
.register_function(insn_ptr as u32, name.as_bytes(), insn_ptr)
.map_err(|_| format!("Label hash collision {name}"))?;
}
labels.insert(name.as_str(), insn_ptr);
Expand Down Expand Up @@ -372,7 +373,7 @@ pub fn assemble<C: ContextObject>(
function_registry
.register_function(
target_pc as u32,
label.as_bytes().to_vec(),
label.as_bytes(),
target_pc as usize,
)
.map_err(|_| format!("Label hash collision {name}"))?;
Expand Down
2 changes: 1 addition & 1 deletion src/elf_parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ impl<'a> Elf64<'a> {
let section_header_table =
slice_from_bytes::<Elf64Shdr>(elf_bytes, section_header_table_range.clone())?;
section_header_table
.get(0)
.first()
.filter(|section_header| section_header.sh_type == SHT_NULL)
.ok_or(ElfParserError::InvalidSectionHeader)?;

Expand Down
13 changes: 1 addition & 12 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,7 @@
// the MIT license <http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.

//! This module contains all the definitions related to eBPF, and some functions permitting to
//! manipulate eBPF instructions.
//!
//! The number of bytes in an instruction, the maximum number of instructions in a program, and
//! also all operation codes are defined here as constants.
//!
//! The structure for an instruction used by this crate, as well as the function to extract it from
//! a program, is also defined in the module.
//!
//! To learn more about these instructions, see the Linux kernel documentation:
//! <https://www.kernel.org/doc/Documentation/networking/filter.txt>, or for a shorter version of
//! the list of the operation codes: <https://github.com/iovisor/bpf-docs/blob/master/eBPF.md>
//! This module contains error and result types
use {
crate::{elf::ElfError, memory_region::AccessType, verifier::VerifierError},
Expand Down
14 changes: 2 additions & 12 deletions src/memory_region.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,12 +104,7 @@ impl MemoryRegion {

/// Creates a new writable MemoryRegion from a mutable slice
pub fn new_writable(slice: &mut [u8], vm_addr: u64) -> Self {
Self::new(
unsafe { std::mem::transmute::<&mut [u8], &[u8]>(slice) },
vm_addr,
0,
MemoryState::Writable,
)
Self::new(&*slice, vm_addr, 0, MemoryState::Writable)
}

/// Creates a new copy on write MemoryRegion.
Expand All @@ -121,12 +116,7 @@ impl MemoryRegion {

/// Creates a new writable gapped MemoryRegion from a mutable slice
pub fn new_writable_gapped(slice: &mut [u8], vm_addr: u64, vm_gap_size: u64) -> Self {
Self::new(
unsafe { std::mem::transmute::<&mut [u8], &[u8]>(slice) },
vm_addr,
vm_gap_size,
MemoryState::Writable,
)
Self::new(&*slice, vm_addr, vm_gap_size, MemoryState::Writable)
}

/// Convert a virtual machine address into a host address
Expand Down
2 changes: 1 addition & 1 deletion src/program.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ impl<T: Copy + PartialEq> FunctionRegistry<T> {

/// Iterate over all keys
pub fn keys(&self) -> impl Iterator<Item = u32> + '_ {
self.map.keys().cloned()
self.map.keys().copied()
}

/// Iterate over all entries
Expand Down
3 changes: 1 addition & 2 deletions src/static_analysis.rs
Original file line number Diff line number Diff line change
Expand Up @@ -553,8 +553,7 @@ impl<'a> Analysis<'a> {
format!("<tr><td align=\"left\">{}</td></tr>", html_escape(&desc))
}
})
.collect::<Vec<String>>()
.join("")
.collect::<String>()
)?;
if let Some(dynamic_analysis) = dynamic_analysis {
if let Some(recorded_edges) = dynamic_analysis.edges.get(&cfg_node_start) {
Expand Down
12 changes: 3 additions & 9 deletions src/syscalls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,16 +158,10 @@ declare_builtin_function!(
let host_addr: Result<u64, EbpfError> =
memory_mapping.map(AccessType::Load, vm_addr, len).into();
let host_addr = host_addr?;
let c_buf: *const i8 = host_addr as *const i8;
unsafe {
for i in 0..len {
let c = std::ptr::read(c_buf.offset(i as isize));
if c == 0 {
break;
}
}
let message = from_utf8(from_raw_parts(host_addr as *const u8, len as usize))
.unwrap_or("Invalid UTF-8 String");
let c_buf = from_raw_parts(host_addr as *const u8, len as usize);
let len = c_buf.iter().position(|c| *c == 0).unwrap_or(len as usize);
let message = from_utf8(&c_buf[0..len]).unwrap_or("Invalid UTF-8 String");
println!("log: {message}");
}
Ok(0)
Expand Down

0 comments on commit 1709f6e

Please sign in to comment.