diff options
Diffstat (limited to 'view')
| -rw-r--r-- | view/bintxt/Cargo.lock | 7 | ||||
| -rw-r--r-- | view/bintxt/Cargo.toml | 12 | ||||
| -rw-r--r-- | view/bintxt/build.rs | 15 | ||||
| -rw-r--r-- | view/bintxt/src/ihex.rs | 23 | ||||
| -rw-r--r-- | view/bintxt/src/lib.rs | 10 | ||||
| -rw-r--r-- | view/bintxt/src/srec.rs | 6 | ||||
| -rw-r--r-- | view/bintxt/src/titxt.rs | 6 | ||||
| -rw-r--r-- | view/minidump/.gitignore | 2 | ||||
| -rw-r--r-- | view/minidump/Cargo.toml | 13 | ||||
| -rw-r--r-- | view/minidump/README.md | 65 | ||||
| -rw-r--r-- | view/minidump/build.rs | 15 | ||||
| -rw-r--r-- | view/minidump/images/loaded-minidump-screenshot-border.png | bin | 0 -> 266633 bytes | |||
| -rw-r--r-- | view/minidump/images/minidump-binary-view-type-screenshot-border.png | bin | 0 -> 31215 bytes | |||
| -rw-r--r-- | view/minidump/images/minidump-segments-sections-screenshot-border.png | bin | 0 -> 122117 bytes | |||
| -rw-r--r-- | view/minidump/src/command.rs | 41 | ||||
| -rw-r--r-- | view/minidump/src/lib.rs | 40 | ||||
| -rw-r--r-- | view/minidump/src/view.rs | 402 |
17 files changed, 620 insertions, 37 deletions
diff --git a/view/bintxt/Cargo.lock b/view/bintxt/Cargo.lock index faf8fc99..1e862160 100644 --- a/view/bintxt/Cargo.lock +++ b/view/bintxt/Cargo.lock @@ -16,7 +16,6 @@ name = "binaryninja" version = "0.1.0" dependencies = [ "binaryninjacore-sys", - "lazy_static", "log", ] @@ -108,12 +107,6 @@ dependencies = [ ] [[package]] -name = "lazy_static" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" - -[[package]] name = "libc" version = "0.2.155" source = "registry+https://github.com/rust-lang/crates.io-index" diff --git a/view/bintxt/Cargo.toml b/view/bintxt/Cargo.toml index 0ec7a9c1..47740dbd 100644 --- a/view/bintxt/Cargo.toml +++ b/view/bintxt/Cargo.toml @@ -5,15 +5,11 @@ authors = ["Rubens Brandao <git@rubens.io>"] edition = "2021" [dependencies] -binaryninja = { path = "../../rust" } +binaryninja.workspace = true +binaryninjacore-sys.workspace = true ihex = "3.0.0" -log = "*" +log = "0.4" srec = "0.2.0" [lib] -crate-type = ["cdylib"] - -[profile.release] -panic = "abort" -lto = true -debug = 1 +crate-type = ["cdylib"]
\ No newline at end of file diff --git a/view/bintxt/build.rs b/view/bintxt/build.rs new file mode 100644 index 00000000..ed6cec7d --- /dev/null +++ b/view/bintxt/build.rs @@ -0,0 +1,15 @@ +fn main() { + let link_path = std::env::var_os("DEP_BINARYNINJACORE_PATH") + .expect("DEP_BINARYNINJACORE_PATH not specified"); + + println!("cargo::rustc-link-lib=dylib=binaryninjacore"); + println!("cargo::rustc-link-search={}", link_path.to_str().unwrap()); + + #[cfg(not(target_os = "windows"))] + { + println!( + "cargo::rustc-link-arg=-Wl,-rpath,{0},-L{0}", + link_path.to_string_lossy() + ); + } +} diff --git a/view/bintxt/src/ihex.rs b/view/bintxt/src/ihex.rs index bb694941..b1cbfb80 100644 --- a/view/bintxt/src/ihex.rs +++ b/view/bintxt/src/ihex.rs @@ -1,15 +1,15 @@ -use binaryninja::binaryview::*; -use binaryninja::custombinaryview::*; -use binaryninja::rc::Ref; -use binaryninja::segment::SegmentBuilder; -use ihex::Record; -use binaryninja::platform::Platform; -use binaryninja::settings::Settings; use crate::segment_after_address; use crate::segment_from_address; use crate::sort_and_merge_segments; use crate::MergedSegment; use crate::UnmergedSegment; +use binaryninja::binary_view::*; +use binaryninja::custom_binary_view::*; +use binaryninja::platform::Platform; +use binaryninja::rc::Ref; +use binaryninja::segment::SegmentBuilder; +use binaryninja::settings::{QueryOptions, Settings}; +use ihex::Record; fn parse_ihex(string: &str) -> Result<(Vec<u8>, IHexViewData)> { let mut reader = ihex::Reader::new(&string); @@ -101,7 +101,7 @@ impl CustomBinaryViewType for IHexViewConstructor { parent: &BinaryView, builder: CustomViewBuilder<'builder, Self>, ) -> Result<CustomView<'builder>> { - let bytes = parent.len(); + let bytes = parent.len() as usize; let mut buf = vec![0; bytes]; let bytes_read = parent.read(&mut buf, 0); if bytes_read != bytes { @@ -216,15 +216,16 @@ unsafe impl CustomBinaryView for IHexView { .contains_code(true), ); } - + // TODO: Because we detached from the raw view this setting will never be set. + let mut settings_query_opts = QueryOptions::new_with_view(&self.core); let _ = self.core.load_settings(self.type_name()).map(|s| { - let platform_name = s.get_string("loader.platform", Some(&self.core), None); + let platform_name = s.get_string_with_opts("loader.platform", &mut settings_query_opts); if let Some(platform) = Platform::by_name(platform_name) { self.set_default_platform(&platform); } }); - + Ok(()) } } diff --git a/view/bintxt/src/lib.rs b/view/bintxt/src/lib.rs index 392fe4ce..4627c654 100644 --- a/view/bintxt/src/lib.rs +++ b/view/bintxt/src/lib.rs @@ -7,24 +7,24 @@ use ihex::*; use srec::*; use titxt::*; -use std::ops::Range; -use log::LevelFilter; use binaryninja::logger::Logger; +use log::LevelFilter; +use std::ops::Range; #[no_mangle] #[allow(non_snake_case)] pub extern "C" fn CorePluginInit() -> bool { Logger::new("BINTXT").with_level(LevelFilter::Info).init(); - binaryninja::custombinaryview::register_view_type(c"ti-txt", c"TI-TXT", |core| { + binaryninja::custom_binary_view::register_view_type(c"ti-txt", c"TI-TXT", |core| { TiTxtViewConstructor { core } }); - binaryninja::custombinaryview::register_view_type(c"srec", c"Motorola S-record", |core| { + binaryninja::custom_binary_view::register_view_type(c"srec", c"Motorola S-record", |core| { SRecViewConstructor { core } }); - binaryninja::custombinaryview::register_view_type(c"ihex", c"Intel HEX", |core| { + binaryninja::custom_binary_view::register_view_type(c"ihex", c"Intel HEX", |core| { IHexViewConstructor { core } }); diff --git a/view/bintxt/src/srec.rs b/view/bintxt/src/srec.rs index d11e5fd5..beba98b0 100644 --- a/view/bintxt/src/srec.rs +++ b/view/bintxt/src/srec.rs @@ -1,5 +1,5 @@ -use binaryninja::binaryview::{BinaryView, BinaryViewBase, BinaryViewExt}; -use binaryninja::custombinaryview::{ +use binaryninja::binary_view::{BinaryView, BinaryViewBase, BinaryViewExt}; +use binaryninja::custom_binary_view::{ BinaryViewType, BinaryViewTypeBase, CustomBinaryView, CustomBinaryViewType, CustomView, CustomViewBuilder, }; @@ -212,7 +212,7 @@ impl CustomBinaryViewType for SRecViewConstructor { parent: &BinaryView, builder: CustomViewBuilder<'builder, Self>, ) -> Result<CustomView<'builder>, ()> { - let bytes = parent.len(); + let bytes = parent.len() as usize; let mut buf = vec![0; bytes]; let bytes_read = parent.read(&mut buf, 0); if bytes_read != bytes { diff --git a/view/bintxt/src/titxt.rs b/view/bintxt/src/titxt.rs index 6cb006ab..d9b766e4 100644 --- a/view/bintxt/src/titxt.rs +++ b/view/bintxt/src/titxt.rs @@ -1,5 +1,5 @@ -use binaryninja::binaryview::{BinaryView, BinaryViewBase, BinaryViewExt}; -use binaryninja::custombinaryview::{ +use binaryninja::binary_view::{BinaryView, BinaryViewBase, BinaryViewExt}; +use binaryninja::custom_binary_view::{ BinaryViewType, BinaryViewTypeBase, CustomBinaryView, CustomBinaryViewType, CustomView, CustomViewBuilder, }; @@ -172,7 +172,7 @@ impl CustomBinaryViewType for TiTxtViewConstructor { parent: &BinaryView, builder: CustomViewBuilder<'builder, Self>, ) -> Result<CustomView<'builder>, ()> { - let bytes = parent.len(); + let bytes = parent.len() as usize; let mut buf = vec![0; bytes]; let bytes_read = parent.read(&mut buf, 0); if bytes_read != bytes { diff --git a/view/minidump/.gitignore b/view/minidump/.gitignore new file mode 100644 index 00000000..4fffb2f8 --- /dev/null +++ b/view/minidump/.gitignore @@ -0,0 +1,2 @@ +/target +/Cargo.lock diff --git a/view/minidump/Cargo.toml b/view/minidump/Cargo.toml new file mode 100644 index 00000000..276080b4 --- /dev/null +++ b/view/minidump/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "minidump_bn" +version = "0.1.0" +edition = "2021" + +[lib] +crate-type = ["cdylib"] + +[dependencies] +binaryninja.workspace = true +binaryninjacore-sys.workspace = true +log = "0.4" +minidump = "0.23.0"
\ No newline at end of file diff --git a/view/minidump/README.md b/view/minidump/README.md new file mode 100644 index 00000000..3c54ca8e --- /dev/null +++ b/view/minidump/README.md @@ -0,0 +1,65 @@ +# Binary Ninja Minidump Loader + +A Minidump memory dump loader plugin for Binary Ninja. + + + +This plugin adds a new _Minidump_ binary view type. When a binary with the magic number `MDMP` is opened, this plugin will automatically try to load in the binary as a minidump, and create a new _Minidump_ binary view to view the contents. + +The architecture is determined automatically from the platform information embedded in the minidump. + + + +The loaded minidump's memory regions and modules can be navigated via the _Memory Map_ window. In the _Minidump_ binary view, the meanings of "Segments" and "Sections" in the Memory Map window are modified to mean the following: + +- The memory regions in the minidump are loaded as _Segments_. The _Data Offset_ and _Data Length_ fields of each segment are the corresponding addresses in the minidump file where the data for that memory region is located. +- The modules in the minidump are loaded as _Sections_, with the name of each section being the path to the module. + + + +## Supported Minidump Types + +This plugin currently only supports loading minidump files generated by the Windows [`MiniDumpWriteDump` API](https://learn.microsoft.com/en-us/windows/win32/api/minidumpapiset/nf-minidumpapiset-minidumpwritedump). + +This includes dumps generated from: + +- The [`.dump` command](https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/-dump--create-dump-file-) in WinDbg. +- The `.dump` command in Binary Ninja's debugger for Windows targets (which uses the same debugging engine as WinDbg). + +For both of the above, it's recommended to generate a full dump: + +``` +.dump /ma dumpfile.dmp +``` + +- The [`minidump` command](https://help.x64dbg.com/en/latest/commands/memory-operations/minidump.html) in x64dbg. + +``` +minidump dumpfile.dmp +``` + +- Right clicking on a listed process and then clicking "Create dump file" / "Create full dump" from Windows Task Manager, Process Hacker, Sysinternals Process Explorer, etc... + +## Unsupported Features (for now) + +- Loading Minidump files from platforms or APIs other than Windows' `MinidumpWriteDump`, such as those generated by [Google Breakpad](https://chromium.googlesource.com/breakpad/breakpad/). +- Loading and applyng debug information from the minidump file. In Windows minidump files, `MinidumpModuleList` streams contain information about the PDB file which contains the debug information for the module; this isn't currently read or applied, however. +- Integration with Binary Ninja's built-in debugger. Minidump files can contain information about threads, register values, and stack frames, and it would be nice in the future for minidump files to be loadable back into the debugger in order to resume a debugging session. This isn't currently done, however. + +## Building and Installing + +This plugin currently needs to be built from source, then copied into your user plugin folder. + +``` +cargo build --release +cp target/release/libminidump_bn.so ~/.binaryninja/plugins/ +``` + +The code in this plugin targets the `dev` branch of the [Binary Ninja Rust API](https://github.com/Vector35/binaryninja-api/tree/dev/rust). + +To update the Binary Ninja Rust API dependency: + +``` +cargo update -p binaryninja +cargo build --release +```
\ No newline at end of file diff --git a/view/minidump/build.rs b/view/minidump/build.rs new file mode 100644 index 00000000..ed6cec7d --- /dev/null +++ b/view/minidump/build.rs @@ -0,0 +1,15 @@ +fn main() { + let link_path = std::env::var_os("DEP_BINARYNINJACORE_PATH") + .expect("DEP_BINARYNINJACORE_PATH not specified"); + + println!("cargo::rustc-link-lib=dylib=binaryninjacore"); + println!("cargo::rustc-link-search={}", link_path.to_str().unwrap()); + + #[cfg(not(target_os = "windows"))] + { + println!( + "cargo::rustc-link-arg=-Wl,-rpath,{0},-L{0}", + link_path.to_string_lossy() + ); + } +} diff --git a/view/minidump/images/loaded-minidump-screenshot-border.png b/view/minidump/images/loaded-minidump-screenshot-border.png Binary files differnew file mode 100644 index 00000000..51b8282c --- /dev/null +++ b/view/minidump/images/loaded-minidump-screenshot-border.png diff --git a/view/minidump/images/minidump-binary-view-type-screenshot-border.png b/view/minidump/images/minidump-binary-view-type-screenshot-border.png Binary files differnew file mode 100644 index 00000000..9a52dd66 --- /dev/null +++ b/view/minidump/images/minidump-binary-view-type-screenshot-border.png diff --git a/view/minidump/images/minidump-segments-sections-screenshot-border.png b/view/minidump/images/minidump-segments-sections-screenshot-border.png Binary files differnew file mode 100644 index 00000000..0035acca --- /dev/null +++ b/view/minidump/images/minidump-segments-sections-screenshot-border.png diff --git a/view/minidump/src/command.rs b/view/minidump/src/command.rs new file mode 100644 index 00000000..818b1c59 --- /dev/null +++ b/view/minidump/src/command.rs @@ -0,0 +1,41 @@ +use std::str; + +use log::{debug, error, info}; +use minidump::{Minidump, MinidumpMemoryInfoList}; + +use binaryninja::binary_view::{BinaryView, BinaryViewBase, BinaryViewExt}; + +pub fn print_memory_information(bv: &BinaryView) { + debug!("Printing memory information"); + if let Some(minidump_bv) = bv.parent_view() { + if let Ok(read_buffer) = minidump_bv.read_buffer(0, minidump_bv.len() as usize) { + if let Ok(minidump_obj) = Minidump::read(read_buffer.get_data()) { + if let Ok(memory_info_list) = minidump_obj.get_stream::<MinidumpMemoryInfoList>() { + let mut memory_info_list_writer = Vec::new(); + match memory_info_list.print(&mut memory_info_list_writer) { + Ok(_) => { + if let Ok(memory_info_str) = str::from_utf8(&memory_info_list_writer) { + info!("{memory_info_str}"); + } else { + error!("Could not convert the memory information description from minidump into a valid string"); + } + } + Err(_) => { + error!("Could not get memory information from minidump"); + } + } + } else { + error!( + "Could not parse a valid MinidumpMemoryInfoList stream from the minidump" + ); + } + } else { + error!("Could not parse a valid minidump file from the parent binary view's data buffer"); + } + } else { + error!("Could not read data from parent binary view"); + } + } else { + error!("Could not get the parent binary view"); + } +} diff --git a/view/minidump/src/lib.rs b/view/minidump/src/lib.rs new file mode 100644 index 00000000..64aaddd6 --- /dev/null +++ b/view/minidump/src/lib.rs @@ -0,0 +1,40 @@ +use binaryninja::binary_view::BinaryView; +use binaryninja::command::{register_command, Command}; +use binaryninja::custom_binary_view::register_view_type; +use binaryninja::logger::Logger; +use log::{debug, LevelFilter}; + +mod command; +mod view; + +struct PrintMemoryInformationCommand; + +impl Command for PrintMemoryInformationCommand { + fn action(&self, binary_view: &BinaryView) { + command::print_memory_information(binary_view); + } + + fn valid(&self, _binary_view: &BinaryView) -> bool { + true // TODO: Of course, the command will not always be valid! + } +} + +#[no_mangle] +#[allow(non_snake_case)] +pub extern "C" fn CorePluginInit() -> bool { + Logger::new("Minidump") + .with_level(LevelFilter::Trace) + .init(); + + debug!("Registering minidump binary view type"); + register_view_type("Minidump", "Minidump", view::MinidumpBinaryViewType::new); + + debug!("Registering minidump plugin commands"); + register_command( + "Minidump\\[DEBUG] Print Minidump Memory Information", + "Print a human-readable description of the contents of the MinidumpMemoryInfoList stream in the loaded minidump", + PrintMemoryInformationCommand {}, + ); + + true +} diff --git a/view/minidump/src/view.rs b/view/minidump/src/view.rs new file mode 100644 index 00000000..0683030f --- /dev/null +++ b/view/minidump/src/view.rs @@ -0,0 +1,402 @@ +use std::collections::HashMap; +use std::ops::Range; + +use binaryninja::section::Section; +use binaryninja::segment::Segment; +use log::{debug, error, info, warn}; +use minidump::format::MemoryProtection; +use minidump::{ + Minidump, MinidumpMemory64List, MinidumpMemoryInfoList, MinidumpMemoryList, MinidumpModuleList, + MinidumpStream, MinidumpSystemInfo, Module, +}; + +use binaryninja::binary_view::{BinaryView, BinaryViewBase, BinaryViewExt}; +use binaryninja::custom_binary_view::{ + BinaryViewType, BinaryViewTypeBase, CustomBinaryView, CustomBinaryViewType, CustomView, + CustomViewBuilder, +}; +use binaryninja::platform::Platform; +use binaryninja::Endianness; + +type BinaryViewResult<R> = binaryninja::binary_view::Result<R>; + +/// The _Minidump_ binary view type, which the Rust plugin registers with the Binary Ninja core +/// (via `binaryninja::custombinaryview::register_view_type`) as a possible binary view +/// that can be applied to opened binaries. +/// +/// If this view type is valid for an opened binary (determined by `is_valid_for`), +/// the Binary Ninja core then uses this view type to create an actual instance of the _Minidump_ +/// binary view (via `create_custom_view`). +pub struct MinidumpBinaryViewType { + view_type: BinaryViewType, +} + +impl MinidumpBinaryViewType { + pub fn new(view_type: BinaryViewType) -> Self { + MinidumpBinaryViewType { view_type } + } +} + +impl AsRef<BinaryViewType> for MinidumpBinaryViewType { + fn as_ref(&self) -> &BinaryViewType { + &self.view_type + } +} + +impl BinaryViewTypeBase for MinidumpBinaryViewType { + fn is_deprecated(&self) -> bool { + false + } + + fn is_force_loadable(&self) -> bool { + false + } + + fn is_valid_for(&self, data: &BinaryView) -> bool { + let mut magic_number = Vec::<u8>::new(); + data.read_into_vec(&mut magic_number, 0, 4); + + magic_number == b"MDMP" + } +} + +impl CustomBinaryViewType for MinidumpBinaryViewType { + fn create_custom_view<'builder>( + &self, + data: &BinaryView, + builder: CustomViewBuilder<'builder, Self>, + ) -> BinaryViewResult<CustomView<'builder>> { + debug!("Creating MinidumpBinaryView from registered MinidumpBinaryViewType"); + + let binary_view = builder.create::<MinidumpBinaryView>(data, ()); + binary_view + } +} + +#[derive(Debug)] +struct SegmentData { + rva_range: Range<u64>, + mapped_addr_range: Range<u64>, +} + +impl SegmentData { + fn from_addresses_and_size(rva: u64, mapped_addr: u64, size: u64) -> Self { + SegmentData { + rva_range: Range { + start: rva, + end: rva + size, + }, + mapped_addr_range: Range { + start: mapped_addr, + end: mapped_addr + size, + }, + } + } +} + +#[derive(Debug)] +struct SegmentMemoryProtection { + readable: bool, + writable: bool, + executable: bool, +} + +/// An instance of the actual _Minidump_ custom binary view. +/// This contains the main logic to load the memory segments inside a minidump file into the binary view. +pub struct MinidumpBinaryView { + /// The handle to the "real" BinaryView object, in the Binary Ninja core. + inner: binaryninja::rc::Ref<BinaryView>, +} + +impl MinidumpBinaryView { + fn new(view: &BinaryView) -> Self { + MinidumpBinaryView { + inner: view.to_owned(), + } + } + + fn init(&self) -> BinaryViewResult<()> { + let parent_view = self.parent_view().ok_or(())?; + let read_buffer = parent_view.read_buffer(0, parent_view.len() as usize)?; + + if let Ok(minidump_obj) = Minidump::read(read_buffer.get_data()) { + // Architecture, platform information + if let Ok(minidump_system_info) = minidump_obj.get_stream::<MinidumpSystemInfo>() { + if let Some(platform) = MinidumpBinaryView::translate_minidump_platform( + minidump_system_info.cpu, + minidump_obj.endian, + minidump_system_info.os, + ) { + self.set_default_platform(&platform); + } else { + error!( + "Could not parse valid system information from minidump: could not map system information in MinidumpSystemInfo stream (arch {:?}, endian {:?}, os {:?}) to a known architecture", + minidump_system_info.cpu, + minidump_obj.endian, + minidump_system_info.os, + ); + return Err(()); + } + } else { + error!("Could not parse system information from minidump: could not find a valid MinidumpSystemInfo stream"); + return Err(()); + } + + // Memory segments + let mut segment_data = Vec::<SegmentData>::new(); + + // Memory segments in a full memory dump (MinidumpMemory64List) + // Grab the shared base RVA for all entries in the MinidumpMemory64List, + // since the minidump crate doesn't expose this to us + if let Ok(raw_stream) = minidump_obj.get_raw_stream(MinidumpMemory64List::STREAM_TYPE) { + if let Ok(base_rva_array) = raw_stream[8..16].try_into() { + let base_rva = u64::from_le_bytes(base_rva_array); + debug!("Found BaseRVA value {:#x}", base_rva); + + if let Ok(minidump_memory_list) = + minidump_obj.get_stream::<MinidumpMemory64List>() + { + let mut current_rva = base_rva; + for memory_segment in minidump_memory_list.iter() { + debug!( + "Found memory segment at RVA {:#x} with virtual address {:#x} and size {:#x}", + current_rva, + memory_segment.base_address, + memory_segment.size, + ); + segment_data.push(SegmentData::from_addresses_and_size( + current_rva, + memory_segment.base_address, + memory_segment.size, + )); + current_rva += memory_segment.size; + } + } + } else { + error!("Could not parse BaseRVA value shared by all entries in the MinidumpMemory64List stream") + } + } else { + warn!("Could not read memory from minidump: could not find a valid MinidumpMemory64List stream. This minidump may not be a full memory dump. Trying to find partial dump memory from a MinidumpMemoryList now..."); + // Memory segments in a regular memory dump (MinidumpMemoryList), + // i.e. one that does not include the full process memory data. + if let Ok(minidump_memory_list) = minidump_obj.get_stream::<MinidumpMemoryList>() { + for memory_segment in minidump_memory_list.by_addr() { + debug!( + "Found memory segment at RVA {:#x} with virtual address {:#x} and size {:#x}", + memory_segment.desc.memory.rva, + memory_segment.base_address, + memory_segment.size + ); + segment_data.push(SegmentData::from_addresses_and_size( + memory_segment.desc.memory.rva as u64, + memory_segment.base_address, + memory_segment.size, + )); + } + } else { + error!("Could not read any memory from minidump: could not find a valid MinidumpMemory64List stream or a valid MinidumpMemoryList stream."); + } + } + + // Memory protection information + let mut segment_protection_data = HashMap::new(); + + if let Ok(minidump_memory_info_list) = + minidump_obj.get_stream::<MinidumpMemoryInfoList>() + { + for memory_info in minidump_memory_info_list.iter() { + if let Some(memory_range) = memory_info.memory_range() { + debug!( + "Found memory protection info for memory segment ranging from virtual address {:#x} to {:#x}: {:#?}", + memory_range.start, + memory_range.end, + memory_info.protection + ); + segment_protection_data.insert( + // The range returned to us by MinidumpMemoryInfoList is an + // end-inclusive range_map::Range; we need to add 1 to + // the end index to make it into an end-exclusive std::ops::Range. + Range { + start: memory_range.start, + end: memory_range.end + 1, + }, + memory_info.protection, + ); + } + } + } + + for segment in segment_data.iter() { + if let Some(segment_protection) = + segment_protection_data.get(&segment.mapped_addr_range) + { + let segment_memory_protection = + MinidumpBinaryView::translate_memory_protection(*segment_protection); + + info!( + "Adding memory segment at virtual address {:#x} to {:#x}, from data range {:#x} to {:#x}, with protections readable {}, writable {}, executable {}", + segment.mapped_addr_range.start, + segment.mapped_addr_range.end, + segment.rva_range.start, + segment.rva_range.end, + segment_memory_protection.readable, + segment_memory_protection.writable, + segment_memory_protection.executable, + ); + + self.add_segment( + Segment::builder(segment.mapped_addr_range.clone()) + .parent_backing(segment.rva_range.clone()) + .is_auto(true) + .readable(segment_memory_protection.readable) + .writable(segment_memory_protection.writable) + .executable(segment_memory_protection.executable), + ); + } else { + error!( + "Could not find memory protection information for memory segment from {:#x} to {:#x}", segment.mapped_addr_range.start, + segment.mapped_addr_range.end, + ); + } + } + + // Module information + // This stretches the concept a bit, but we can add each module as a + // separate "section" of the binary. + // Sections can be named, and can span multiple segments. + if let Ok(minidump_module_list) = minidump_obj.get_stream::<MinidumpModuleList>() { + for module_info in minidump_module_list.by_addr() { + info!( + "Found module with name {} at virtual address {:#x} with size {:#x}", + module_info.name, + module_info.base_address(), + module_info.size(), + ); + let module_address_range = Range { + start: module_info.base_address(), + end: module_info.base_address() + module_info.size(), + }; + self.add_section( + Section::builder(module_info.name.clone(), module_address_range) + .is_auto(true), + ); + } + } else { + warn!("Could not find valid module information in minidump: could not find a valid MinidumpModuleList stream"); + } + } else { + error!("Could not parse data as minidump"); + return Err(()); + } + Ok(()) + } + + fn translate_minidump_platform( + minidump_cpu_arch: minidump::system_info::Cpu, + minidump_endian: minidump::Endian, + minidump_os: minidump::system_info::Os, + ) -> Option<binaryninja::rc::Ref<Platform>> { + match minidump_os { + minidump::system_info::Os::Windows => match minidump_cpu_arch { + minidump::system_info::Cpu::Arm64 => Platform::by_name("windows-aarch64"), + minidump::system_info::Cpu::Arm => Platform::by_name("windows-armv7"), + minidump::system_info::Cpu::X86 => Platform::by_name("windows-x86"), + minidump::system_info::Cpu::X86_64 => Platform::by_name("windows-x86_64"), + _ => None, + }, + minidump::system_info::Os::MacOs => match minidump_cpu_arch { + minidump::system_info::Cpu::Arm64 => Platform::by_name("mac-aarch64"), + minidump::system_info::Cpu::Arm => Platform::by_name("mac-armv7"), + minidump::system_info::Cpu::X86 => Platform::by_name("mac-x86"), + minidump::system_info::Cpu::X86_64 => Platform::by_name("mac-x86_64"), + _ => None, + }, + minidump::system_info::Os::Linux => match minidump_cpu_arch { + minidump::system_info::Cpu::Arm64 => Platform::by_name("linux-aarch64"), + minidump::system_info::Cpu::Arm => Platform::by_name("linux-armv7"), + minidump::system_info::Cpu::X86 => Platform::by_name("linux-x86"), + minidump::system_info::Cpu::X86_64 => Platform::by_name("linux-x86_64"), + minidump::system_info::Cpu::Ppc => match minidump_endian { + minidump::Endian::Little => Platform::by_name("linux-ppc32_le"), + minidump::Endian::Big => Platform::by_name("linux-ppc32"), + }, + minidump::system_info::Cpu::Ppc64 => match minidump_endian { + minidump::Endian::Little => Platform::by_name("linux-ppc64_le"), + minidump::Endian::Big => Platform::by_name("linux-ppc64"), + }, + _ => None, + }, + minidump::system_info::Os::NaCl => None, + minidump::system_info::Os::Android => None, + minidump::system_info::Os::Ios => None, + minidump::system_info::Os::Ps3 => None, + minidump::system_info::Os::Solaris => None, + _ => None, + } + } + + fn translate_memory_protection( + minidump_memory_protection: MemoryProtection, + ) -> SegmentMemoryProtection { + let (readable, writable, executable) = match minidump_memory_protection { + MemoryProtection::PAGE_NOACCESS => (false, false, false), + MemoryProtection::PAGE_READONLY => (true, false, false), + MemoryProtection::PAGE_READWRITE => (true, true, false), + MemoryProtection::PAGE_WRITECOPY => (true, true, false), + MemoryProtection::PAGE_EXECUTE => (false, false, true), + MemoryProtection::PAGE_EXECUTE_READ => (true, false, true), + MemoryProtection::PAGE_EXECUTE_READWRITE => (true, true, true), + MemoryProtection::PAGE_EXECUTE_WRITECOPY => (true, true, true), + MemoryProtection::ACCESS_MASK => (false, false, false), + MemoryProtection::PAGE_GUARD => (false, false, false), + MemoryProtection::PAGE_NOCACHE => (false, false, false), + MemoryProtection::PAGE_WRITECOMBINE => (false, false, false), + _ => (false, false, false), + }; + SegmentMemoryProtection { + readable, + writable, + executable, + } + } +} + +impl AsRef<BinaryView> for MinidumpBinaryView { + fn as_ref(&self) -> &BinaryView { + &self.inner + } +} + +impl BinaryViewBase for MinidumpBinaryView { + // TODO: This should be filled out with the actual address size + // from the platform information in the minidump. + fn address_size(&self) -> usize { + 0 + } + + fn default_endianness(&self) -> Endianness { + // TODO: This should be filled out with the actual endianness + // from the platform information in the minidump. + Endianness::LittleEndian + } + + fn entry_point(&self) -> u64 { + // TODO: We should fill this out with a real entry point. + // This can be done by getting the main module of the minidump + // with MinidumpModuleList::main_module, + // then parsing the PE metadata of the main module to find its entry point(s). + 0 + } +} + +unsafe impl CustomBinaryView for MinidumpBinaryView { + type Args = (); + + fn new(handle: &BinaryView, _args: &Self::Args) -> BinaryViewResult<Self> { + Ok(MinidumpBinaryView::new(handle)) + } + + fn init(&mut self, _args: Self::Args) -> BinaryViewResult<()> { + MinidumpBinaryView::init(self) + } +} |
