Provide BinaryLoader::load

Only provide the function


use eframe::{egui, Frame};
use memmap::Mmap;
use std::fs;
use iced_x86::{Decoder as IcedDecoder, DecoderOptions, Formatter, Instruction as IcedInstruction};
use goblin::{Object, pe, elf};
use std::sync::{Arc, Mutex};
use std::collections::{HashSet, HashMap};
use std::str;
use log::info;
use env_logger;
use rfd::FileDialog;
use std::thread;
use std::fs::File;
use std::io::Read;
use std::path::Path;

fn main() {
    // Initialize logging
    env_logger::init();

    let app = ReaverApp::default();
    let native_options = eframe::NativeOptions::default();
    eframe::run_native(
        "Reaver", // Replace with your app name
        native_options,
        Box::new(|cc| Ok(Box::new(app))),
    );
}

// Application State
struct ReaverApp {
    analysis: Option<Arc<Mutex<BinaryAnalysis>>>,
    selected_function: Option<usize>,
    selected_string: Option<usize>,
    selected_exception: Option<usize>,
}

impl Default for ReaverApp {
    fn default() -> Self {
        Self {
            analysis: None,
            selected_function: None,
            selected_string: None,
            selected_exception: None,
        }
    }
}

impl eframe::App for ReaverApp {


    fn update(&mut self, ctx: &egui::Context, frame: &mut Frame) {
        self.draw_menu_bar(ctx);
        self.draw_side_panel(ctx);
        self.draw_main_panel(ctx);
        self.draw_status_bar(ctx);
    }
}

impl ReaverApp {
    fn draw_menu_bar(&mut self, ctx: &egui::Context) {
        egui::TopBottomPanel::top("menu_bar").show(ctx, |ui| {
            ui.horizontal(|ui| {
                if ui.button("Open").clicked() {
                    self.open_file();
                }
                if ui.button("Exit").clicked() {
                    std::process::exit(0);
                }
            });
        });
    }

    fn draw_side_panel(&mut self, ctx: &egui::Context) {
        egui::SidePanel::left("navigation_panel").show(ctx, |ui| {
            if let Some(analysis) = &self.analysis {
                let analysis = analysis.lock().unwrap();
                ui.heading("Functions");
                egui::ScrollArea::vertical().show(ui, |ui| {
                    for (index, function) in analysis.functions.iter().enumerate() {
                        if ui
                            .selectable_label(
                                self.selected_function == Some(index),
                                format!("{:#X} {}", function.address, function.name),
                            )
                            .clicked()
                        {
                            self.selected_function = Some(index);
                            self.selected_string = None;
                            self.selected_exception = None;
                        }
                    }
                });
                ui.separator();
                ui.heading("Strings");
                egui::ScrollArea::vertical().show(ui, |ui| {
                    for (index, string_entry) in analysis.strings.iter().enumerate() {
                        if ui
                            .selectable_label(
                                self.selected_string == Some(index),
                                format!("{:#X} {}", string_entry.address, string_entry.value),
                            )
                            .clicked()
                        {
                            self.selected_string = Some(index);
                            self.selected_function = None;
                            self.selected_exception = None;
                        }
                    }
                });
                ui.separator();
                ui.heading("Exception Handlers");
                egui::ScrollArea::vertical().show(ui, |ui| {
                    for (index, exception) in analysis.exception_handlers.iter().enumerate() {
                        if ui
                            .selectable_label(
                                self.selected_exception == Some(index),
                                format!("{:#X} Handler at {:#X}", exception.address, exception.handler_address),
                            )
                            .clicked()
                        {
                            self.selected_exception = Some(index);
                            self.selected_function = None;
                            self.selected_string = None;
                        }
                    }
                });
            } else {
                ui.label("No binary loaded.");
            }
        });
    }

    fn draw_main_panel(&mut self, ctx: &egui::Context) {
        egui::CentralPanel::default().show(ctx, |ui| {
            if let Some(analysis) = &self.analysis {
                let analysis = analysis.lock().unwrap();
                if let Some(index) = self.selected_function {
                    let function = &analysis.functions[index];
                    ui.heading(format!("Function {:#X} {}", function.address, function.name));
                    egui::ScrollArea::vertical().show(ui, |ui| {
                        for instruction in &function.instructions {
                            ui.horizontal(|ui| {
                                ui.label(format!("{:#016X}:", instruction.address));
                                ui.monospace(&instruction.text);
                            });
                        }
                    });
                } else if let Some(index) = self.selected_string {
                    let string_entry = &analysis.strings[index];
                    ui.heading(format!("String at {:#X}", string_entry.address));
                    ui.monospace(&string_entry.value);
                } else if let Some(index) = self.selected_exception {
                    let exception = &analysis.exception_handlers[index];
                    ui.heading(format!("Exception Handler at {:#X}", exception.address));
                    ui.label(format!("End Address: {:#X}", exception.end_address));
                    ui.label(format!("Handler Address: {:#X}", exception.handler_address));
                } else {
                    ui.label("Select an item from the navigation panel.");
                }
            } else {
                ui.label("No binary loaded.");
            }
        });
    }

    fn draw_status_bar(&mut self, ctx: &egui::Context) {
        egui::TopBottomPanel::bottom("status_bar").show(ctx, |ui| {
            ui.horizontal(|ui| {
                ui.label("Status: Ready");
            });
        });
    }

    fn open_file(&mut self) {
        if let Some(file_path) = FileDialog::new()
            .add_filter("Executable", &["exe", "dll", "bin", "elf"])
            .pick_file()
        {
            let file_path_str = file_path.to_string_lossy().to_string();
            info!("Selected file: {}", file_path_str);

            let analysis = Arc::new(Mutex::new(BinaryAnalysis::new()));
            let analysis_clone = analysis.clone();
            thread::spawn(move || {
                let mut analysis = analysis_clone.lock().unwrap();
                if let Err(e) = analysis.load_binary(&file_path_str) {
                    eprintln!("Failed to load binary: {}", e);
                }
            });
            self.analysis = Some(analysis);
            self.selected_function = None;
            self.selected_string = None;
            self.selected_exception = None;
        }
    }
}

// Core Analysis Structures and Functions

struct BinaryAnalysis {
    functions: Vec<Function>,
    strings: Vec<StringEntry>,
    exception_handlers: Vec<ExceptionHandler>,
}

impl BinaryAnalysis {
    pub fn new() -> Self {
        Self {
            functions: Vec::new(),
            strings: Vec::new(),
            exception_handlers: Vec::new(),
        }
    }

    pub fn load_binary(&mut self, path: &str) -> Result<(), Box<dyn std::error::Error>> {
        info!("Loading binary from '{}'", path);
        let loader = BinaryLoader::load(path)?;
        self.process_binary(loader);
        Ok(())
    }

    fn process_binary(&mut self, loader: BinaryLoader) {
        for section in &loader.sections {
            if section.is_executable {
                info!("Disassembling section '{}'", section.name);
                let disassembler = Disassembler::new(&section.data, section.addr, loader.bitness);
                let instructions = disassembler.disassemble();
                info!(
                    "Disassembled {} instructions in section '{}'",
                    instructions.len(),
                    section.name
                );
                self.detect_functions(&instructions);
            }
        }
        self.extract_strings(&loader);
        self.analyze_exception_handlers(&loader);
    }

    fn detect_functions(&mut self, instructions: &[Instruction]) {
        let mut function_starts = HashSet::new();
        let mut addr_to_instr = HashMap::new();

        // Identify potential function entry points
        for instr in instructions {
            let mnemonic = instr.instr.mnemonic();
            // Simple heuristic: Looking for 'push rbp' or 'sub rsp, imm' as function prologue
            if mnemonic == iced_x86::Mnemonic::Push && instr.instr.op0_register() == iced_x86::Register::RBP {
                function_starts.insert(instr.address);
            } else if mnemonic == iced_x86::Mnemonic::Sub && instr.instr.op0_register() == iced_x86::Register::RSP {
                function_starts.insert(instr.address);
            }
            addr_to_instr.insert(instr.address, instr.clone());
        }

        // Build functions by following the control flow
        for &start_addr in &function_starts {
            if !self.functions.iter().any(|f| f.address == start_addr) {
                let function = self.build_function(start_addr, &addr_to_instr);
                self.functions.push(function);
            }
        }
    }

    fn build_function(&self, start_addr: u64, addr_to_instr: &HashMap<u64, Instruction>) -> Function {
        let mut visited = HashSet::new();
        let mut to_visit = vec![start_addr];
        let mut instructions = Vec::new();

        while let Some(addr) = to_visit.pop() {
            if visited.contains(&addr) {
                continue;
            }
            if let Some(instr) = addr_to_instr.get(&addr) {
                instructions.push(instr.clone());
                visited.insert(addr);

                let mnemonic = instr.instr.mnemonic();
                let instr_len = instr.instr.len() as u64;

                // Determine next addresses to visit based on the instruction type
                if mnemonic == iced_x86::Mnemonic::Jmp {
                    if let target_addr = instr.instr.near_branch_target() {
                        to_visit.push(target_addr);
                    }
                } else if mnemonic == iced_x86::Mnemonic::Call {
                    // Continue with next instruction
                    to_visit.push(addr + instr_len);
                } else if mnemonic == iced_x86::Mnemonic::Ret {
                    // End of function
                    continue;
                } else {
                    // Default case: proceed to next instruction
                    to_visit.push(addr + instr_len);
                }
            }
        }

        Function {
            address: start_addr,
            name: format!("sub{:X}", start_addr),
            instructions,
        }
    }

    fn extract_strings(&mut self, loader: &BinaryLoader) {
        info!("Extracting strings from binary");
        let min_length = 4;
        for section in &loader.sections {
            if !section.is_executable {
                let data = &section.data;
                let mut offset = 0;
                while offset < data.len() {
                    let byte = data[offset];
                    if byte.is_ascii() && !byte.is_ascii_control() {
                        let start = offset;
                        while offset < data.len() && data[offset].is_ascii_graphic() {
                            offset += 1;
                        }
                        if offset - start >= min_length {
                            if let Ok(string) = str::from_utf8(&data[start..offset]) {
                                self.strings.push(StringEntry {
                                    address: section.addr + start as u64,
                                    value: string.to_string(),
                                });
                            }
                        }
                    } else {
                        offset += 1;
                    }
                }
            }
        }
        info!("Extracted {} strings", self.strings.len());
    }

    fn analyze_exception_handlers(&mut self, loader: &BinaryLoader) {
        info!("Analyzing exception handlers");
            info!("Exception handler analysis is currently implemented only for PE files");
        }
}

// Data Structures

struct Function {
    address: u64,
    name: String,
    instructions: Vec<Instruction>,
}

#[derive(Clone)]
struct Instruction {
    address: u64,
    text: String,
    instr: IcedInstruction,
}

struct StringEntry {
    address: u64,
    value: String,
}

struct ExceptionHandler {
    address: u64,
    end_address: u64,
    handler_address: u64,
}

// Binary Loader

struct BinaryLoader {
    entry_point: u64,
    sections: Vec<BinarySection>,
    bitness: u32,
    pe: Option<pe::PE<'static>>,
    elf: Option<elf::Elf<'static>>,
    mmap: memmap::Mmap,
}

struct BinarySection {
    name: String,
    addr: u64,
    size: u64,
    data: Vec<u8>,
    is_executable: bool,
}
impl BinaryLoader {
}
// Disassembler

struct Disassembler<'a> {
    bitness: u32,
    code: &'a [u8],
    address: u64,
}

impl<'a> Disassembler<'a> {
    pub fn new(code: &'a [u8], address: u64, bitness: u32) -> Self {
        Self { bitness, code, address }
    }

    pub fn disassemble(&self) -> Vec<Instruction> {
        let mut decoder = IcedDecoder::with_ip(self.bitness, self.code, self.address, DecoderOptions::NONE);
        let mut formatter = iced_x86::IntelFormatter::new();
        let mut output = String::new();
        let mut instructions = Vec::new();

        while decoder.can_decode() {
            let instr = decoder.decode();
            output.clear();
            formatter.format(&instr, &mut output);
            let instruction = Instruction {
                address: instr.ip(),
                text: output.clone(),
                instr,
            };
            instructions.push(instruction);
        }
        instructions
    }
}