Skip to main content

dump/
dump.rs

1//! Dumps an image: header facts, table row counts, and one method disassembly.
2//!
3//! ```text
4//! cargo run --example dump -- <image.dll> [MethodName]
5//! ```
6
7use cildec::tables::{MethodDefRow, TypeDefRow};
8use cildec::{MethodBody, Names, PeImage, Rid, TableId};
9
10fn main() -> Result<(), Box<dyn std::error::Error>> {
11    let mut args = std::env::args().skip(1);
12    let path = args.next().ok_or("usage: dump <image.dll> [MethodName]")?;
13    let wanted = args.next();
14
15    let bytes = std::fs::read(&path)?;
16    let image = PeImage::parse(&bytes)?;
17    let header = image.cli_header()?;
18    println!("{path}");
19    println!(
20        "  {} machine={:#06x} runtime={}.{} il_only={} 32bit_required={} 32bit_preferred={}",
21        if image.is_pe32_plus() { "PE32+" } else { "PE32" },
22        image.machine(),
23        header.major_runtime_version,
24        header.minor_runtime_version,
25        header.flags.il_only(),
26        header.flags.requires_32bit(),
27        header.flags.prefers_32bit(),
28    );
29
30    let metadata = image.metadata()?;
31    println!("  metadata version {}", metadata.version_string());
32    print!("  streams:");
33    for stream in metadata.streams() {
34        print!(" {}({})", stream.name_lossy(), stream.size);
35    }
36    println!();
37
38    let tables = metadata.tables();
39    let mut populated: Vec<(TableId, u32)> = TableId::ALL
40        .iter()
41        .map(|&id| (id, tables.row_count(id)))
42        .filter(|&(_, count)| count > 0)
43        .collect();
44    populated.sort_by_key(|&(id, _)| id.to_u8());
45    println!("  tables:");
46    for (id, count) in &populated {
47        println!("    {:<24} {count:>8}", id.name());
48    }
49
50    for diagnostic in image.diagnostics().iter().chain(metadata.diagnostics()) {
51        println!("  diagnostic: {diagnostic}");
52    }
53
54    let names = Names::new(&metadata);
55    let Some(wanted) = wanted else { return Ok(()) };
56    let wanted_rid: Option<u32> = wanted.strip_prefix('#').and_then(|r| r.parse().ok());
57    for (rid, row) in tables.iter::<MethodDefRow>() {
58        let row = row?;
59        let matched = match wanted_rid {
60            Some(target) => rid == target,
61            None => metadata.strings().str_opt(row.name) == Some(wanted.as_str()),
62        };
63        if !matched {
64            continue;
65        }
66        println!("\n{}", names.method_def_full(Rid::new(rid))?);
67        let Some(body) = MethodBody::from_image(&image, &row)? else {
68            println!("  (no body)");
69            continue;
70        };
71        println!(
72            "  .maxstack {}  code {} bytes  handlers {}",
73            body.max_stack,
74            body.code_size(),
75            body.exception_handlers.len()
76        );
77        if let Some(token) = body.local_var_sig {
78            let sig_row = tables.stand_alone_sig(token.rid())?;
79            let blob = metadata.blobs().get(sig_row.signature)?;
80            let locals = cildec::LocalVarSig::parse(blob)?;
81            for (slot, local) in locals.locals.iter().enumerate() {
82                println!("  .local [{slot}] {}", names.type_(&local.type_));
83            }
84        }
85        for folded in body.folded_instructions() {
86            let folded = folded?;
87            let instruction = &folded.instruction;
88            let mut line = format!("  IL_{:04x}: ", instruction.offset);
89            if folded.prefixes.volatile {
90                line.push_str("volatile. ");
91            }
92            if folded.prefixes.tail {
93                line.push_str("tail. ");
94            }
95            if let Some(token) = folded.prefixes.constrained {
96                line.push_str(&format!("constrained. {} ", names.token(token)));
97            }
98            line.push_str(instruction.opcode.name());
99            match &instruction.operand {
100                _ if instruction.info().operand == cildec::OperandKind::InlineNone => {}
101                cildec::Operand::None => {}
102                cildec::Operand::Var(index) => line.push_str(&format!(" {index}")),
103                cildec::Operand::I8(value) => line.push_str(&format!(" {value}")),
104                cildec::Operand::I32(value) => line.push_str(&format!(" {value}")),
105                cildec::Operand::I64(value) => line.push_str(&format!(" {value}")),
106                cildec::Operand::R32(value) => line.push_str(&format!(" {value}")),
107                cildec::Operand::R64(value) => line.push_str(&format!(" {value}")),
108                cildec::Operand::BranchTarget(target) => {
109                    line.push_str(&format!(" IL_{target:04x}"));
110                }
111                cildec::Operand::Switch(targets) => {
112                    let list: Vec<String> = targets.iter().map(|t| format!("IL_{t:04x}")).collect();
113                    line.push_str(&format!(" ({})", list.join(", ")));
114                }
115                cildec::Operand::String(token) => {
116                    let text = metadata.user_strings().get(*token)?;
117                    line.push_str(&format!(" {:?}", text.to_string_lossy()));
118                }
119                operand => {
120                    if let Some(token) = operand.token() {
121                        line.push_str(&format!(" {}", names.token(token)));
122                    }
123                }
124            }
125            println!("{line}");
126        }
127        for handler in &body.exception_handlers {
128            println!(
129                "  .try IL_{:04x}..IL_{:04x} {:?} handler IL_{:04x}..IL_{:04x}",
130                handler.try_offset,
131                handler.try_end(),
132                handler.kind,
133                handler.handler_offset,
134                handler.handler_end()
135            );
136        }
137        if let Err(e) = body.validate_handlers() {
138            println!("  invalid exception table: {e}");
139        }
140    }
141
142    let type_count = tables.row_count(TableId::TypeDef);
143    if type_count > 0 {
144        let first: TypeDefRow = tables.type_def(1)?;
145        let _ = first;
146    }
147    Ok(())
148}