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

btfdump: Allow to dump from /sys/kernel/btf/vmlinux #16

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
35 changes: 27 additions & 8 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::convert::TryFrom;
use std::error::Error;
use std::io::Write;
use std::io::{Read, Seek, SeekFrom, Write};

use bitflags::bitflags;
use clap::builder::TypedValueParser as _;
Expand Down Expand Up @@ -193,10 +194,28 @@ fn main() -> Result<(), Box<dyn Error>> {
verbose,
union_as_struct,
} => {
let file = std::fs::File::open(&file)?;
let file = unsafe { memmap::Mmap::map(&file) }?;
let file = object::File::parse(&*file)?;
let btf = Btf::load(&file)?;
let mut file = std::fs::File::open(&file)?;

// Read the magic number first.
let mut buffer = [0u8; 2];
file.read_exact(&mut buffer)?;
let magic_number: u16 = u16::from_le_bytes(buffer);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this should take into account host endianness, no?


// And then the full file content.
let mut contents = Vec::with_capacity(usize::try_from(file.metadata()?.len())?);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you add BTF::load_file() API which would detect raw vs ELF internally and just return BTF? And then use that at least for Stat command below as well. Both dump and state are frequently used (by me, at least), so would be good to keep them both in sync in terms of what they support.

file.seek(SeekFrom::Start(0))?;
file.read_to_end(&mut contents)?;

let btf = if magic_number == BTF_MAGIC {
// If the file starts with BTF magic number, parse BTF from the
// full file content.
Btf::load_raw(contents.as_slice())?
} else {
// Otherwise, assume it's an object file and parse BTF from
// the `.BTF` section.
let file = object::File::parse(contents.as_slice())?;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you please keep mmap way for ELF case? ELF file can potentially be very big, there is no need to allocate so much memory for the buffer

Btf::load_from_elf(&file)?
};
let filter = create_query_filter(query)?;

match format {
Expand Down Expand Up @@ -259,7 +278,7 @@ fn main() -> Result<(), Box<dyn Error>> {
let local_file = std::fs::File::open(&local_file)?;
let local_mmap = unsafe { memmap::Mmap::map(&local_file) }?;
let local_elf = object::File::parse(&*local_mmap)?;
let local_btf = Btf::load(&local_elf)?;
let local_btf = Btf::load_from_elf(&local_elf)?;
if !local_btf.has_ext() {
return btf_error(format!(
"No {} section found for local ELF file, can't perform relocations.",
Expand All @@ -269,7 +288,7 @@ fn main() -> Result<(), Box<dyn Error>> {
let targ_file = std::fs::File::open(&targ_file)?;
let targ_mmap = unsafe { memmap::Mmap::map(&targ_file) }?;
let targ_elf = object::File::parse(&*targ_mmap)?;
let targ_btf = Btf::load(&targ_elf)?;
let targ_btf = Btf::load_from_elf(&targ_elf)?;
let cfg = RelocatorCfg { verbose: verbose };
let mut relocator = Relocator::new(&targ_btf, &local_btf, cfg);
let relocs = relocator.relocate()?;
Expand Down Expand Up @@ -363,7 +382,7 @@ fn stat_btf(elf: &object::File) -> BtfResult<()> {
} else {
println!("{} not found.", BTF_EXT_ELF_SEC);
}
match Btf::load(elf) {
match Btf::load_from_elf(elf) {
Err(e) => println!("Failed to parse BTF data: {}", e),
Ok(btf) => {
let mut type_stats: HashMap<BtfKind, (usize, usize)> = HashMap::new();
Expand Down
68 changes: 51 additions & 17 deletions src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use std::fmt;
use std::mem::size_of;

use object::{Object, ObjectSection};
use scroll::Pread;
use scroll::{Endian, Pread};
use scroll_derive::{IOread, IOwrite, Pread as DerivePread, Pwrite, SizeWith};

use crate::{btf_error, BtfError, BtfResult};
Expand Down Expand Up @@ -1084,30 +1084,24 @@ impl<'a> Btf<'a> {
}
}

pub fn load(elf: &object::File<'a>) -> BtfResult<Btf<'a>> {
let endian = if elf.is_little_endian() {
scroll::LE
} else {
scroll::BE
};
/// Helper method which keeps the common BTF loading logic and returns
/// both `Btf` and a subslice with the string section.
fn load_from_bytes(
endian: Endian,
ptr_sz: u32,
data: &'a [u8],
) -> BtfResult<(Btf<'a>, &'a [u8])> {
let mut btf = Btf::<'a> {
endian: endian,
ptr_sz: if elf.is_64() { 8 } else { 4 },
endian,
ptr_sz,
types: vec![BtfType::Void],
has_ext: false,
func_secs: Vec::new(),
line_secs: Vec::new(),
core_reloc_secs: Vec::new(),
};

let btf_section = elf
.section_by_name(BTF_ELF_SEC)
.ok_or_else(|| Box::new(BtfError::new("No .BTF section found!")))?;
let data = match btf_section.data() {
Ok(d) => d,
_ => panic!("expected borrowed data"),
};
let hdr = data.pread_with::<btf_header>(0, endian)?;
let hdr = data.pread_with::<btf_header>(0, scroll::LE)?;
if hdr.magic != BTF_MAGIC {
return btf_error(format!("Invalid BTF magic: {}", hdr.magic));
}
Expand All @@ -1130,6 +1124,29 @@ impl<'a> Btf<'a> {
btf.types.push(t);
}

Ok((btf, str_data))
}

/// Loads BTF information from the given ELF object file.
pub fn load_from_elf(elf: &object::File<'a>) -> BtfResult<Btf<'a>> {
let endian = if elf.is_little_endian() {
scroll::LE
} else {
scroll::BE
};

let ptr_sz = if elf.is_64() { 8 } else { 4 };

let btf_section = elf
.section_by_name(BTF_ELF_SEC)
.ok_or_else(|| Box::new(BtfError::new("No .BTF section found!")))?;
let data = match btf_section.data() {
Ok(d) => d,
_ => panic!("expected borrowed data"),
};

let (mut btf, str_data) = Self::load_from_bytes(endian, ptr_sz, data)?;

if let Some(ext_section) = elf.section_by_name(BTF_EXT_ELF_SEC) {
btf.has_ext = true;
let ext_data = match ext_section.data() {
Expand Down Expand Up @@ -1173,6 +1190,23 @@ impl<'a> Btf<'a> {
Ok(btf)
}

/// Loads BTF information from the given slice of bytes.
pub fn load_raw(data: &'a [u8]) -> BtfResult<Btf<'a>> {
#[cfg(target_endian = "little")]
let endian = scroll::LE;
#[cfg(target_endian = "big")]
let endian = scroll::BE;

#[cfg(target_pointer_width = "64")]
let ptr_sz = 8_u32;
#[cfg(target_pointer_width = "32")]
let ptr_sz = 4_u32;

let (btf, _) = Self::load_from_bytes(endian, ptr_sz, data)?;

Ok(btf)
}

pub fn type_size(t: &BtfType) -> usize {
let common = size_of::<btf_type>();
match t {
Expand Down