dotscope 0.6.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
430
431
432
433
//! Analysis test runner.
//!
//! This module provides the main test runner that compiles C# source,
//! loads the resulting assembly, and verifies analysis results.

use std::path::PathBuf;
use std::sync::Arc;

use crate::{
    analysis::CallGraph,
    metadata::token::Token,
    project::ProjectLoader,
    test::{
        analysis::{
            templates::{AnalysisTestCase, ANALYSIS_TEST_CASES, ANALYSIS_TEST_SOURCE},
            verification::{
                build_analysis, verify_callgraph, verify_cfg, verify_dataflow, verify_ssa,
                VerificationError,
            },
        },
        mono::{compilation::compile_debug, Architecture, TestCapabilities},
    },
    CilObject, Result,
};

/// Path to Mono 4.8 framework assemblies for dependency resolution.
fn mono_framework_path() -> std::path::PathBuf {
    std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/samples/mono_4.8")
}

/// Result of running a single analysis test.
#[derive(Debug)]
pub struct AnalysisTestResult {
    /// Name of the test.
    pub test_name: String,
    /// Whether the test passed.
    pub passed: bool,
    /// Verification errors (empty if passed).
    pub errors: Vec<VerificationError>,
    /// Error message if the test failed to run.
    pub run_error: Option<String>,
}

impl AnalysisTestResult {
    /// Creates a successful test result.
    #[must_use]
    pub fn success(name: impl Into<String>) -> Self {
        Self {
            test_name: name.into(),
            passed: true,
            errors: Vec::new(),
            run_error: None,
        }
    }

    /// Creates a failed test result with verification errors.
    #[must_use]
    pub fn verification_failed(name: impl Into<String>, errors: Vec<VerificationError>) -> Self {
        Self {
            test_name: name.into(),
            passed: false,
            errors,
            run_error: None,
        }
    }

    /// Creates a failed test result with a run error.
    #[must_use]
    pub fn run_failed(name: impl Into<String>, error: impl Into<String>) -> Self {
        Self {
            test_name: name.into(),
            passed: false,
            errors: Vec::new(),
            run_error: Some(error.into()),
        }
    }

    /// Gets a combined error message.
    #[must_use]
    pub fn error_message(&self) -> String {
        if let Some(ref run_error) = self.run_error {
            return run_error.clone();
        }

        if self.errors.is_empty() {
            return String::new();
        }

        self.errors
            .iter()
            .map(|e| e.to_string())
            .collect::<Vec<_>>()
            .join("; ")
    }
}

/// Runner for analysis verification tests.
pub struct AnalysisTestRunner {
    /// Platform capabilities.
    capabilities: TestCapabilities,
    /// Temporary directory for compiled assemblies.
    temp_dir: tempfile::TempDir,
    /// Path to compiled test assembly.
    assembly_path: Option<PathBuf>,
    /// Loaded assembly.
    assembly: Option<Arc<CilObject>>,
    /// Call graph (built once for all tests).
    callgraph: Option<CallGraph>,
}

impl AnalysisTestRunner {
    /// Creates a new analysis test runner.
    ///
    /// # Returns
    ///
    /// A new runner instance, or an error if initialization fails.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - No C# compiler is available
    /// - Failed to create temporary directory
    pub fn new() -> Result<Self> {
        let capabilities = TestCapabilities::detect();

        if !capabilities.can_test() {
            return Err(crate::Error::Other(
                "No C# compiler available for analysis tests".to_string(),
            ));
        }

        let temp_dir = tempfile::TempDir::new()
            .map_err(|e| crate::Error::Other(format!("Failed to create temp dir: {}", e)))?;

        Ok(Self {
            capabilities,
            temp_dir,
            assembly_path: None,
            assembly: None,
            callgraph: None,
        })
    }

    /// Compiles the test source code.
    ///
    /// # Returns
    ///
    /// The path to the compiled assembly.
    ///
    /// # Errors
    ///
    /// Returns an error if compilation fails.
    pub fn compile(&mut self) -> Result<PathBuf> {
        if let Some(ref path) = self.assembly_path {
            return Ok(path.clone());
        }

        // Use the first available architecture
        let arch = self
            .capabilities
            .supported_architectures
            .first()
            .cloned()
            .unwrap_or(Architecture::ANYCPU);

        let result = compile_debug(
            &self.capabilities,
            ANALYSIS_TEST_SOURCE,
            self.temp_dir.path(),
            "AnalysisTests",
            &arch,
        )?;

        if !result.is_success() {
            return Err(crate::Error::Other(format!(
                "Compilation failed: {}",
                result.error.unwrap_or_else(|| "Unknown error".to_string())
            )));
        }

        let path = result.assembly_path().to_path_buf();
        self.assembly_path = Some(path.clone());
        Ok(path)
    }

    /// Loads the compiled assembly using CilProject for dependency resolution.
    ///
    /// Uses the Mono 4.8 framework assemblies as a search path to resolve
    /// dependencies like mscorlib that are needed for debug-compiled assemblies.
    ///
    /// # Returns
    ///
    /// A reference to the loaded assembly.
    ///
    /// # Errors
    ///
    /// Returns an error if loading fails.
    pub fn load(&mut self) -> Result<Arc<CilObject>> {
        if let Some(ref assembly) = self.assembly {
            return Ok(assembly.clone());
        }

        let path = self.compile()?;

        // Use ProjectLoader with Mono framework path for dependency resolution
        let project_result = ProjectLoader::new()
            .primary_file(&path)?
            .with_search_path(mono_framework_path())?
            .auto_discover(true)
            .build()?;

        let assembly = project_result
            .project
            .get_primary()
            .ok_or_else(|| crate::Error::Other("Failed to get primary assembly".to_string()))?;

        self.assembly = Some(assembly.clone());
        Ok(assembly)
    }

    /// Builds the call graph for the loaded assembly.
    ///
    /// # Returns
    ///
    /// A reference to the call graph.
    ///
    /// # Errors
    ///
    /// Returns an error if call graph construction fails.
    pub fn build_callgraph(&mut self) -> Result<&CallGraph> {
        if let Some(ref cg) = self.callgraph {
            return Ok(cg);
        }

        let assembly = self.load()?;
        let callgraph = CallGraph::build(&assembly)?;
        self.callgraph = Some(callgraph);
        Ok(self.callgraph.as_ref().expect("just inserted"))
    }

    /// Finds a method by class and method name.
    ///
    /// # Arguments
    ///
    /// * `class_name` - The class containing the method
    /// * `method_name` - The method name
    ///
    /// # Returns
    ///
    /// The method token if found.
    pub fn find_method(&self, class_name: &str, method_name: &str) -> Option<Token> {
        let assembly = self.assembly.as_ref()?;

        // Search through types to find the class
        for type_info in assembly.types().all_types() {
            if type_info.name == class_name {
                // Search methods
                for (_, method_ref) in type_info.methods.iter() {
                    if let Some(method) = method_ref.upgrade() {
                        if method.name == method_name {
                            return Some(method.token);
                        }
                    }
                }
            }
        }

        None
    }

    /// Runs a single test case.
    ///
    /// # Arguments
    ///
    /// * `test_case` - The test case to run
    ///
    /// # Returns
    ///
    /// The test result.
    pub fn run_test(&mut self, test_case: &AnalysisTestCase) -> AnalysisTestResult {
        // Ensure assembly is loaded
        let assembly = match self.load() {
            Ok(a) => a,
            Err(e) => {
                return AnalysisTestResult::run_failed(
                    test_case.name,
                    format!("Failed to load assembly: {}", e),
                )
            }
        };

        // Find the method
        let token = match self.find_method(test_case.class_name, test_case.method_name) {
            Some(t) => t,
            None => {
                return AnalysisTestResult::run_failed(
                    test_case.name,
                    format!(
                        "Method not found: {}::{}",
                        test_case.class_name, test_case.method_name
                    ),
                )
            }
        };

        // Get the method
        let method = match assembly.method(&token) {
            Some(method) => method,
            None => {
                return AnalysisTestResult::run_failed(
                    test_case.name,
                    format!("Method with token {:?} not in method table", token),
                )
            }
        };

        // Build CFG and SSA
        let (cfg, ssa) = match build_analysis(&method, Some(&assembly)) {
            Ok(result) => result,
            Err(e) => return AnalysisTestResult::run_failed(test_case.name, e),
        };

        let mut all_errors = Vec::new();

        // Verify CFG
        let cfg_errors = verify_cfg(&cfg, &test_case.cfg);
        all_errors.extend(cfg_errors);

        // Verify SSA
        let ssa_errors = verify_ssa(&ssa, &cfg, &test_case.ssa);
        all_errors.extend(ssa_errors);

        // Verify call graph if expectation is provided
        if let Some(ref cg_expectation) = test_case.callgraph {
            // Ensure call graph is built
            match self.build_callgraph() {
                Ok(callgraph) => {
                    let cg_errors = verify_callgraph(callgraph, &method, cg_expectation);
                    all_errors.extend(cg_errors);
                }
                Err(e) => {
                    all_errors.push(VerificationError::new(
                        "CallGraph",
                        "build",
                        "success",
                        format!("error: {}", e),
                    ));
                }
            }
        }

        // Verify data flow if expectation is provided
        if let Some(ref df_expectation) = test_case.dataflow {
            let df_errors = verify_dataflow(&ssa, &cfg, df_expectation);
            all_errors.extend(df_errors);
        }

        if all_errors.is_empty() {
            AnalysisTestResult::success(test_case.name)
        } else {
            AnalysisTestResult::verification_failed(test_case.name, all_errors)
        }
    }

    /// Runs all defined test cases.
    ///
    /// # Returns
    ///
    /// Results for all test cases.
    ///
    /// # Errors
    ///
    /// Returns an error if test setup fails (individual test failures are reported in results).
    pub fn run_all_tests(&mut self) -> Result<Vec<AnalysisTestResult>> {
        // Compile and load first
        self.load()?;

        let mut results = Vec::with_capacity(ANALYSIS_TEST_CASES.len());

        for test_case in ANALYSIS_TEST_CASES {
            let result = self.run_test(test_case);
            results.push(result);
        }

        Ok(results)
    }

    /// Runs a subset of tests matching the given prefix.
    ///
    /// # Arguments
    ///
    /// * `prefix` - Test name prefix to match (e.g., "cfg_", "ssa_", "callgraph_")
    ///
    /// # Returns
    ///
    /// Results for matching test cases.
    ///
    /// # Errors
    ///
    /// Returns an error if test setup fails.
    pub fn run_tests_matching(&mut self, prefix: &str) -> Result<Vec<AnalysisTestResult>> {
        self.load()?;

        let mut results = Vec::new();

        for test_case in ANALYSIS_TEST_CASES {
            if test_case.name.starts_with(prefix) {
                let result = self.run_test(test_case);
                results.push(result);
            }
        }

        Ok(results)
    }

    /// Returns the test capabilities.
    #[must_use]
    pub fn capabilities(&self) -> &TestCapabilities {
        &self.capabilities
    }

    /// Returns the number of defined test cases.
    #[must_use]
    pub fn test_count() -> usize {
        ANALYSIS_TEST_CASES.len()
    }

    /// Returns the test case definitions.
    #[must_use]
    pub fn test_cases() -> &'static [AnalysisTestCase] {
        ANALYSIS_TEST_CASES
    }
}