2022-11-28 07:38:01 -05:00
|
|
|
// Clippy doesn't like the lifetimes, but rustc wants them. 🤷
|
|
|
|
#![allow(clippy::needless_lifetimes)]
|
|
|
|
// Clippy doesn't understand that we exit with ? from the closure in
|
|
|
|
// and_then below and this can't be expressed with map.
|
|
|
|
#![allow(clippy::bind_instead_of_map)]
|
|
|
|
|
2022-11-23 09:40:52 -05:00
|
|
|
use alloc::{borrow::ToOwned, string::String};
|
|
|
|
|
|
|
|
/// Extracts the data of a section of a PE file.
|
2022-11-22 10:18:12 -05:00
|
|
|
pub fn pe_section<'a>(file_data: &'a [u8], section_name: &str) -> Option<&'a [u8]> {
|
|
|
|
let pe_binary = goblin::pe::PE::parse(file_data).ok()?;
|
|
|
|
|
|
|
|
pe_binary
|
|
|
|
.sections
|
|
|
|
.iter()
|
|
|
|
.find(|s| s.name().unwrap() == section_name)
|
|
|
|
.and_then(|s| {
|
|
|
|
let section_start: usize = s.pointer_to_raw_data.try_into().ok()?;
|
2022-11-23 11:57:23 -05:00
|
|
|
|
|
|
|
assert!(s.virtual_size <= s.size_of_raw_data);
|
|
|
|
let section_end: usize = section_start + usize::try_from(s.virtual_size).ok()?;
|
2022-11-22 10:18:12 -05:00
|
|
|
|
|
|
|
Some(&file_data[section_start..section_end])
|
|
|
|
})
|
|
|
|
}
|
2022-11-23 09:40:52 -05:00
|
|
|
|
|
|
|
/// Extracts the data of a section of a PE file and returns it as a string.
|
|
|
|
pub fn pe_section_as_string<'a>(file_data: &'a [u8], section_name: &str) -> Option<String> {
|
2022-11-28 07:38:01 -05:00
|
|
|
pe_section(file_data, section_name).map(|data| core::str::from_utf8(data).unwrap().to_owned())
|
2022-11-23 09:40:52 -05:00
|
|
|
}
|