From e71423a72222bc712c2f1e696dcf37d39c84955f Mon Sep 17 00:00:00 2001 From: yoloyyh <1764163852@qq.com> Date: Wed, 16 Oct 2024 16:14:45 +0800 Subject: [PATCH] feat parse elf memory usage --- rasp/librasp/src/golang.rs | 8 +++----- rasp/librasp/src/parse_elf.rs | 24 ++++++++++++++++-------- 2 files changed, 19 insertions(+), 13 deletions(-) diff --git a/rasp/librasp/src/golang.rs b/rasp/librasp/src/golang.rs index f8a2240f9..95001efb8 100644 --- a/rasp/librasp/src/golang.rs +++ b/rasp/librasp/src/golang.rs @@ -1,7 +1,6 @@ use log::*; use std::fs::File; use std::{fs, path::PathBuf, process::Command}; -use std::io::Read; use regex::Regex; use anyhow::{anyhow, Result}; use goblin::elf::Elf; @@ -167,9 +166,8 @@ pub fn parse_version(version: &String) -> Result { } pub fn golang_version(bin_file: &PathBuf) -> Result { - let mut file = File::open(bin_file)?; - let mut buffer = Vec::new(); - file.read_to_end(&mut buffer)?; + let file = File::open(bin_file)?; + let buffer = unsafe { MmapOptions::new().map(&file)? }; // parse elf let elf = match Elf::parse(&buffer) { @@ -183,7 +181,7 @@ pub fn golang_version(bin_file: &PathBuf) -> Result { } }; - if let Ok(version) = find_by_section(&elf, &buffer, &file) { + if let Ok(version) = find_by_section(&elf, &file) { return parse_version(&version); } else { if let Ok(version) = find_by_symbol(&elf, &file) { diff --git a/rasp/librasp/src/parse_elf.rs b/rasp/librasp/src/parse_elf.rs index db5a0d844..2645009a7 100644 --- a/rasp/librasp/src/parse_elf.rs +++ b/rasp/librasp/src/parse_elf.rs @@ -5,7 +5,7 @@ use byteorder::{ByteOrder, LittleEndian, BigEndian}; use anyhow::{anyhow, Result}; use std::io::{Read, Seek, SeekFrom}; use log::*; - +use memmap::Mmap; const MAGIC: &[u8] = b"\xff Go buildinf:"; const RUNTIME_VERSION_MAGIC: &str = "runtime.buildVersion"; const EXPECTED_MAGIC_LEN: usize = 14; @@ -143,7 +143,7 @@ pub fn find_by_symbol(elf: &Elf, file: &File) -> Result { } } -pub fn find_by_section(elf: &Elf, buffer:&Vec, file: &File) -> Result { +pub fn find_by_section(elf: &Elf, file: &File) -> Result { let mut version: String = String::new(); // find .go.buildinfo @@ -154,13 +154,21 @@ pub fn find_by_section(elf: &Elf, buffer:&Vec, file: &File) -> Result m, + Err(e) => {return Err(anyhow!(e));}// Return empty string if mmap fails + }; + if mmap.len() < end { + return Err(anyhow!("mmap length invaild")); // Return empty string if the section is out of bounds } - - let buildinfo_data = &buffer[go_buildinfo_section.sh_offset as usize - ..(go_buildinfo_section.sh_offset + go_buildinfo_section.sh_size) as usize]; + + // Extract the data of the section + let buildinfo_data = &mmap[start..end]; // check Magic let magic_header = &buildinfo_data[0..EXPECTED_MAGIC_LEN];