summaryrefslogtreecommitdiff
path: root/rust/examples/dump_type_library.rs
blob: 6dd51ecec495d78464fe479eb184992895278e1e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// Usage: cargo run --example dump_type_library <type_library_path>

use binaryninja::binary_view::BinaryView;
use binaryninja::file_metadata::FileMetadata;
use binaryninja::tracing::TracingLogListener;
use binaryninja::types::library::TypeLibrary;
use binaryninja::types::printer::{CoreTypePrinter, TokenEscapingType};

fn main() {
    tracing_subscriber::fmt::init();
    let _listener = TracingLogListener::new().register();

    let type_lib_str = std::env::args().nth(1).expect("No type library provided");
    let type_lib_path = std::path::Path::new(&type_lib_str);

    // This loads all the core architecture, platform, etc plugins
    let _headless_session =
        binaryninja::headless::Session::new().expect("Failed to initialize session");

    let type_lib = TypeLibrary::load_from_file(type_lib_path).expect("Failed to load type library");
    tracing::info!("Name: `{}`", type_lib.name());
    tracing::info!("GUID: `{}`", type_lib.guid());

    // Print out all the types as a c header.
    let type_lib_header_path = type_lib_path.with_extension("h");

    let all_types: Vec<_> = type_lib
        .named_types()
        .iter()
        .chain(type_lib.named_objects().iter())
        .collect();

    tracing::info!(
        "Dumping {} types to: `{:?}`",
        all_types.len(),
        type_lib_header_path
    );
    let type_printer = CoreTypePrinter::default();
    let empty_bv = BinaryView::from_data(&FileMetadata::new(), &[]);
    let printed_types = type_printer
        .print_all_types(
            all_types,
            &empty_bv,
            4,
            TokenEscapingType::NoTokenEscapingType,
        )
        .expect("Failed to print types");

    // Write the header to disk.
    std::fs::write(type_lib_header_path, printed_types)
        .expect("Failed to write type library header");
}