dotscope 0.7.0

A high-performance, cross-platform framework for analyzing and reverse engineering .NET PE executables
Documentation
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
//! # Disassembler and IL Analysis
//!
//! **What this example teaches:**
//! - CIL instruction decoding and analysis
//! - Method body examination and local variables
//! - Exception handler analysis
//! - Control flow and stack effect analysis
//! - Basic block construction from IL code
//!
//! **When to use this pattern:**
//! - Building disassemblers and decompilers
//! - Security analysis requiring instruction-level detail
//! - Performance analysis of IL code
//! - Understanding control flow patterns
//!
//! **Prerequisites:**
//! - Completed basic.rs and comprehensive.rs examples
//! - Understanding of CIL instruction set
//! - Familiarity with control flow concepts

use dotscope::prelude::*;
use std::{env, path::Path};

fn main() -> Result<()> {
    let args: Vec<String> = env::args().collect();
    if args.len() < 2 {
        eprintln!("Usage: {} <path-to-dotnet-assembly>", args[0]);
        eprintln!();
        eprintln!("This example demonstrates IL disassembly and method analysis:");
        eprintln!("  • CIL instruction decoding with full operand support");
        eprintln!("  • Method body structure analysis");
        eprintln!("  • Exception handler examination");
        eprintln!("  • Stack and local variable analysis");
        return Ok(());
    }

    let path = Path::new(&args[1]);
    println!("⚙️  IL Disassembly analysis of: {}", path.display());

    let assembly = CilObject::from_path(path)?;

    // === Method Body Analysis ===
    print_method_body_analysis(&assembly);

    // === IL Instruction Analysis ===
    print_instruction_analysis(&assembly);

    // === Exception Handler Analysis ===
    print_exception_analysis(&assembly);

    // === Stack and Local Variable Analysis ===
    print_stack_analysis(&assembly);

    println!("\n✅ IL disassembly analysis completed!");

    Ok(())
}

fn print_method_body_analysis(assembly: &CilObject) {
    println!("\n🔧 Method Body Analysis:");

    let methods = assembly.methods();
    let mut stats = MethodBodyStats::default();

    println!("  Analyzing method bodies...");

    for entry in methods.iter().take(20) {
        let method = entry.value();
        stats.total_methods += 1;

        if let Some(body) = method.body.get() {
            stats.methods_with_body += 1;
            stats.total_il_bytes += body.size_code;

            if body.max_stack > stats.max_stack_size {
                stats.max_stack_size = body.max_stack;
            }

            if body.local_var_sig_token != 0 {
                stats.methods_with_locals += 1;
            }

            if !body.exception_handlers.is_empty() {
                stats.methods_with_exceptions += 1;
                stats.total_exception_handlers += body.exception_handlers.len();
            }

            // Analyze method characteristics
            if body.is_init_local {
                stats.init_locals += 1;
            }

            if body.size_code < 64 {
                stats.tiny_methods += 1;
            } else {
                stats.fat_methods += 1;
            }
        } else {
            stats.abstract_or_extern += 1;
        }
    }

    print_method_stats(&stats);
}

fn print_method_stats(stats: &MethodBodyStats) {
    println!("  Method body statistics:");
    println!("    Total methods analyzed: {}", stats.total_methods);
    println!("    Methods with IL body: {}", stats.methods_with_body);
    println!("    Abstract/extern methods: {}", stats.abstract_or_extern);
    println!("    Total IL bytes: {}", stats.total_il_bytes);
    println!(
        "    Average IL size: {:.1} bytes",
        stats.total_il_bytes as f64 / stats.methods_with_body.max(1) as f64
    );
    println!("    Max stack size encountered: {}", stats.max_stack_size);
    println!(
        "    Methods with local variables: {}",
        stats.methods_with_locals
    );
    println!(
        "    Methods with exception handlers: {}",
        stats.methods_with_exceptions
    );
    println!(
        "    Total exception handlers: {}",
        stats.total_exception_handlers
    );
    println!("    Tiny format methods: {}", stats.tiny_methods);
    println!("    Fat format methods: {}", stats.fat_methods);
    println!("    Methods with init_locals flag: {}", stats.init_locals);
}

fn print_instruction_analysis(assembly: &CilObject) {
    println!("\n📋 IL Instruction Analysis:");

    let methods = assembly.methods();
    let mut instruction_stats = InstructionStats::default();

    // Find methods with IL to disassemble
    for entry in methods.iter().take(5) {
        let method = entry.value();

        if let Some(body) = method.body.get() {
            println!("    Analyzing method: {}", method.name);

            if body.size_code > 0 {
                println!("      Method body details:");
                println!("        IL size: {} bytes", body.size_code);
                println!("        Max stack: {}", body.max_stack);
                println!(
                    "        Local variables token: 0x{:08X}",
                    body.local_var_sig_token
                );

                // Display actual disassembled instructions from blocks
                let mut total_instructions = 0;
                let mut block_count = 0;

                // Access blocks - blocks are automatically populated when method is loaded
                for (block_id, block) in method.blocks() {
                    block_count += 1;
                    if block_count <= 3 && !block.instructions.is_empty() {
                        println!(
                            "        Block {} (RVA: 0x{:X}, {} instructions):",
                            block_id,
                            block.rva,
                            block.instructions.len()
                        );

                        for (inst_idx, instruction) in block.instructions.iter().enumerate() {
                            if inst_idx < 5 {
                                // Show first 5 instructions per block
                                println!(
                                    "          [0x{:04X}] {} {:?}",
                                    instruction.rva, instruction.mnemonic, instruction.operand
                                );

                                // Update instruction statistics
                                instruction_stats.total_instructions += 1;
                                match instruction.flow_type {
                                    dotscope::assembly::FlowType::ConditionalBranch
                                    | dotscope::assembly::FlowType::UnconditionalBranch => {
                                        instruction_stats.branch_instructions += 1;
                                    }
                                    dotscope::assembly::FlowType::Call => {
                                        instruction_stats.call_instructions += 1;
                                    }
                                    _ => {}
                                }

                                if instruction.mnemonic.starts_with("ld")
                                    || instruction.mnemonic.starts_with("st")
                                {
                                    instruction_stats.load_store_instructions += 1;
                                }
                            }
                        }
                        if block.instructions.len() > 5 {
                            println!(
                                "          ... ({} more instructions)",
                                block.instructions.len() - 5
                            );
                        }
                    }
                    total_instructions += block.instructions.len();
                }

                println!("        Basic blocks: {block_count}");
                if block_count > 3 {
                    println!("        ... ({} more blocks)", block_count - 3);
                }

                println!("        Total instructions: {total_instructions}");

                instruction_stats.methods_analyzed += 1;
            }

            if instruction_stats.methods_analyzed >= 3 {
                break;
            }
        }
    }

    println!("  Instruction analysis summary:");
    println!(
        "    Methods with IL analyzed: {}",
        instruction_stats.methods_analyzed
    );
    println!(
        "    Total instructions decoded: {}",
        instruction_stats.total_instructions
    );
    println!(
        "    Branch instructions: {}",
        instruction_stats.branch_instructions
    );
    println!(
        "    Call instructions: {}",
        instruction_stats.call_instructions
    );
    println!(
        "    Load/Store instructions: {}",
        instruction_stats.load_store_instructions
    );
}

fn print_exception_analysis(assembly: &CilObject) {
    println!("\n🛡️  Exception Handler Analysis:");

    let methods = assembly.methods();
    let mut exception_stats = ExceptionStats::default();

    for entry in methods.iter().take(50) {
        let method = entry.value();

        if let Some(body) = method.body.get() {
            if !body.exception_handlers.is_empty() {
                exception_stats.methods_with_handlers += 1;

                for handler in &body.exception_handlers {
                    exception_stats.total_handlers += 1;

                    // Analyze handler types based on flags
                    match handler.flags {
                        ExceptionHandlerFlags::EXCEPTION => exception_stats.catch_handlers += 1,
                        ExceptionHandlerFlags::FILTER => exception_stats.filter_handlers += 1,
                        ExceptionHandlerFlags::FINALLY => exception_stats.finally_handlers += 1,
                        ExceptionHandlerFlags::FAULT => exception_stats.fault_handlers += 1,
                        _ => exception_stats.unknown_handlers += 1,
                    }

                    // Track protected region sizes
                    let protected_size = handler.try_length;
                    if protected_size > exception_stats.largest_protected_region {
                        exception_stats.largest_protected_region = protected_size;
                    }
                }

                if exception_stats.methods_with_handlers <= 3 {
                    println!("    Method '{}' exception handlers:", method.name);
                    for (i, handler) in body.exception_handlers.iter().enumerate() {
                        let handler_type = match handler.flags {
                            ExceptionHandlerFlags::EXCEPTION => "Catch",
                            ExceptionHandlerFlags::FILTER => "Filter",
                            ExceptionHandlerFlags::FINALLY => "Finally",
                            ExceptionHandlerFlags::FAULT => "Fault",
                            _ => "Unknown",
                        };
                        println!(
                            "      [{}] {} handler: IL_{:04X}-IL_{:04X} -> IL_{:04X}",
                            i,
                            handler_type,
                            handler.try_offset,
                            handler.try_offset + handler.try_length,
                            handler.handler_offset
                        );
                    }
                }
            }
        }
    }

    println!("  Exception handler statistics:");
    println!(
        "    Methods with exception handlers: {}",
        exception_stats.methods_with_handlers
    );
    println!(
        "    Total exception handlers: {}",
        exception_stats.total_handlers
    );
    println!("    Catch handlers: {}", exception_stats.catch_handlers);
    println!("    Finally handlers: {}", exception_stats.finally_handlers);
    println!("    Filter handlers: {}", exception_stats.filter_handlers);
    println!("    Fault handlers: {}", exception_stats.fault_handlers);
    println!(
        "    Largest protected region: {} IL bytes",
        exception_stats.largest_protected_region
    );
}

fn print_stack_analysis(assembly: &CilObject) {
    println!("\n📚 Stack and Local Variable Analysis:");

    let methods = assembly.methods();
    let mut local_stats = LocalVariableStats::default();

    for entry in methods.iter().take(30) {
        let method = entry.value();

        if let Some(body) = method.body.get() {
            local_stats.methods_analyzed += 1;

            if body.local_var_sig_token != 0 {
                local_stats.methods_with_locals += 1;

                // In a real implementation, you would parse the local variable signature
                // to determine the exact types and count of local variables
                // For now, we'll show the structure

                if local_stats.methods_with_locals <= 3 {
                    println!(
                        "    Method '{}' has local variables (token: 0x{:08X})",
                        method.name, body.local_var_sig_token
                    );
                }
            }

            // Track stack information
            if body.max_stack > local_stats.max_stack_encountered {
                local_stats.max_stack_encountered = body.max_stack;
                local_stats.method_with_max_stack = method.name.clone();
            }

            // Check init_locals flag
            if body.is_init_local {
                local_stats.methods_with_init_locals += 1;
            }
        }
    }

    println!("  Local variable statistics:");
    println!("    Methods analyzed: {}", local_stats.methods_analyzed);
    println!(
        "    Methods with local variables: {}",
        local_stats.methods_with_locals
    );
    println!(
        "    Methods with init_locals flag: {}",
        local_stats.methods_with_init_locals
    );
    println!(
        "    Maximum stack size: {} (in method '{}')",
        local_stats.max_stack_encountered, local_stats.method_with_max_stack
    );

    println!("  Stack analysis capabilities:");
    println!("    • Local variable signature parsing");
    println!("    • Stack effect simulation");
    println!("    • Type flow analysis");
    println!("    • Stack underflow/overflow detection");
}

#[derive(Default)]
struct MethodBodyStats {
    total_methods: usize,
    methods_with_body: usize,
    abstract_or_extern: usize,
    total_il_bytes: usize,
    max_stack_size: usize,
    methods_with_locals: usize,
    methods_with_exceptions: usize,
    total_exception_handlers: usize,
    tiny_methods: usize,
    fat_methods: usize,
    init_locals: usize,
}

#[derive(Default)]
#[allow(dead_code)] // These fields demonstrate the structure for instruction analysis
struct InstructionStats {
    methods_analyzed: usize,
    total_instructions: usize,
    branch_instructions: usize,
    call_instructions: usize,
    load_store_instructions: usize,
}

#[derive(Default)]
struct ExceptionStats {
    methods_with_handlers: usize,
    total_handlers: usize,
    catch_handlers: usize,
    finally_handlers: usize,
    filter_handlers: usize,
    fault_handlers: usize,
    unknown_handlers: usize,
    largest_protected_region: u32,
}

#[derive(Default)]
struct LocalVariableStats {
    methods_analyzed: usize,
    methods_with_locals: usize,
    methods_with_init_locals: usize,
    max_stack_encountered: usize,
    method_with_max_stack: String,
}