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
434
435
436
437
438
439
440
441
442
443
444
445
446
//! Reflection-based method invocation testing
//!
//! This module generates and executes C# test programs that use .NET reflection
//! to invoke methods in dotscope-modified assemblies. This validates that methods
//! added or modified by dotscope are correctly callable at runtime.

use crate::prelude::*;
use crate::test::mono::capabilities::{Architecture, TestCapabilities};
use crate::test::mono::compilation::{compile, CompilationResult};
use crate::test::mono::execution::{execute, ExecutionResult};
use std::path::Path;

/// Result of a reflection test
#[derive(Debug)]
pub struct ReflectionTestResult {
    /// Whether the test passed
    pub success: bool,
    /// Compilation result for the test harness
    pub compilation: Option<CompilationResult>,
    /// Execution result
    pub execution: Option<ExecutionResult>,
    /// Error message if failed
    pub error: Option<String>,
}

impl ReflectionTestResult {
    /// Create a successful result
    pub fn success(compilation: CompilationResult, execution: ExecutionResult) -> Self {
        Self {
            success: true,
            compilation: Some(compilation),
            execution: Some(execution),
            error: None,
        }
    }

    /// Create a failed result
    pub fn failure(error: String) -> Self {
        Self {
            success: false,
            compilation: None,
            execution: None,
            error: Some(error),
        }
    }

    /// Check if test was successful
    pub fn is_success(&self) -> bool {
        self.success
    }

    /// Get error summary
    pub fn error_summary(&self) -> String {
        if let Some(ref err) = self.error {
            err.clone()
        } else if let Some(ref exec) = self.execution {
            if !exec.is_success() {
                exec.error_summary()
            } else {
                "Success".to_string()
            }
        } else {
            "Unknown error".to_string()
        }
    }
}

/// A single test case for method invocation
#[derive(Debug, Clone)]
pub struct MethodTest {
    /// Method name to invoke
    pub method_name: String,
    /// Type name containing the method
    pub type_name: Option<String>,
    /// Arguments to pass (as C# literal strings)
    pub arguments: Vec<String>,
    /// Expected return value (as C# literal)
    pub expected_result: Option<String>,
    /// Description of this test
    pub description: Option<String>,
}

impl MethodTest {
    /// Create a new method test
    pub fn new(method_name: &str) -> Self {
        Self {
            method_name: method_name.to_string(),
            type_name: None,
            arguments: Vec::new(),
            expected_result: None,
            description: None,
        }
    }

    /// Set the type containing the method
    pub fn in_type(mut self, type_name: &str) -> Self {
        self.type_name = Some(type_name.to_string());
        self
    }

    /// Add an integer argument
    pub fn arg_int(mut self, value: i32) -> Self {
        self.arguments.push(value.to_string());
        self
    }

    /// Add a string argument
    pub fn arg_string(mut self, value: &str) -> Self {
        self.arguments.push(format!("\"{}\"", value));
        self
    }

    /// Add a boolean argument
    pub fn arg_bool(mut self, value: bool) -> Self {
        self.arguments
            .push(if value { "true" } else { "false" }.to_string());
        self
    }

    /// Expect an integer result
    pub fn expect_int(mut self, value: i32) -> Self {
        self.expected_result = Some(value.to_string());
        self
    }

    /// Expect a string result
    pub fn expect_string(mut self, value: &str) -> Self {
        self.expected_result = Some(format!("\"{}\"", value));
        self
    }

    /// Expect a boolean result
    pub fn expect_bool(mut self, value: bool) -> Self {
        self.expected_result = Some(if value { "true" } else { "false" }.to_string());
        self
    }

    /// Set a description
    pub fn describe(mut self, description: &str) -> Self {
        self.description = Some(description.to_string());
        self
    }
}

/// Generate a reflection test program
pub fn generate_test_program(assembly_path: &Path, tests: &[MethodTest]) -> String {
    let assembly_path_str = assembly_path.to_string_lossy().replace('\\', "\\\\");

    let mut test_code = String::new();

    for (i, test) in tests.iter().enumerate() {
        let type_search = if let Some(ref type_name) = test.type_name {
            format!(
                r#"
            Type type{i} = null;
            foreach (Type t in assembly.GetTypes())
            {{
                if (t.Name == "{type_name}" || t.FullName == "{type_name}")
                {{
                    type{i} = t;
                    break;
                }}
            }}
            if (type{i} == null)
            {{
                Console.WriteLine("ERROR: Type '{type_name}' not found");
                Environment.Exit(1);
            }}"#
            )
        } else {
            format!(
                r#"
            Type type{i} = assembly.GetTypes()[0];"#
            )
        };

        let method_name = &test.method_name;
        let args_array = if test.arguments.is_empty() {
            "new object[0]".to_string()
        } else {
            format!("new object[] {{ {} }}", test.arguments.join(", "))
        };

        let result_check = if let Some(ref expected) = test.expected_result {
            format!(
                r#"
            if (!result{i}.Equals({expected}))
            {{
                Console.WriteLine("ERROR: Expected {expected}, got " + result{i});
                Environment.Exit(1);
            }}
            Console.WriteLine("PASS: {method_name} returned " + result{i});"#
            )
        } else {
            format!(
                r#"
            Console.WriteLine("PASS: {method_name} executed successfully");"#
            )
        };

        let description = test.description.as_deref().unwrap_or(method_name);

        test_code.push_str(&format!(r#"
            // Test {i}: {description}
            {type_search}
            MethodInfo method{i} = type{i}.GetMethod("{method_name}", BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance);
            if (method{i} == null)
            {{
                Console.WriteLine("ERROR: Method '{method_name}' not found");
                Environment.Exit(1);
            }}
            object result{i} = method{i}.Invoke(null, {args_array});
            {result_check}
"#));
    }

    format!(
        r#"using System;
using System.Reflection;

class Program
{{
    static void Main()
    {{
        try
        {{
            Assembly assembly = Assembly.LoadFile(@"{assembly_path_str}");
            {test_code}
            Console.WriteLine("All tests passed!");
        }}
        catch (Exception ex)
        {{
            Console.WriteLine("ERROR: " + ex.Message);
            if (ex.InnerException != null)
            {{
                Console.WriteLine("Inner: " + ex.InnerException.Message);
            }}
            Environment.Exit(1);
        }}
    }}
}}
"#
    )
}

/// Run a reflection test
pub fn run_reflection_test(
    capabilities: &TestCapabilities,
    assembly_path: &Path,
    tests: &[MethodTest],
    output_dir: &Path,
    arch: &Architecture,
) -> Result<ReflectionTestResult> {
    // Generate test program
    let test_source = generate_test_program(assembly_path, tests);

    // Compile test harness
    let compile_result = compile(
        capabilities,
        &test_source,
        output_dir,
        "reflection_test",
        arch,
    )?;

    if !compile_result.is_success() {
        return Ok(ReflectionTestResult {
            success: false,
            compilation: Some(compile_result),
            execution: None,
            error: Some("Failed to compile reflection test harness".to_string()),
        });
    }

    // Execute test harness
    let exec_result = execute(capabilities, compile_result.assembly_path())?;

    if exec_result.is_success() {
        Ok(ReflectionTestResult::success(compile_result, exec_result))
    } else {
        Ok(ReflectionTestResult {
            success: false,
            compilation: Some(compile_result),
            execution: Some(exec_result.clone()),
            error: Some(exec_result.error_summary()),
        })
    }
}

/// Simple reflection test that just tries to load an assembly and list its types
pub fn verify_assembly_loadable(
    capabilities: &TestCapabilities,
    assembly_path: &Path,
    output_dir: &Path,
    arch: &Architecture,
) -> Result<ReflectionTestResult> {
    let assembly_path_str = assembly_path.to_string_lossy().replace('\\', "\\\\");

    let test_source = format!(
        r#"using System;
using System.Reflection;

class Program
{{
    static void Main()
    {{
        try
        {{
            Assembly assembly = Assembly.LoadFile(@"{assembly_path_str}");
            Console.WriteLine("Assembly loaded: " + assembly.FullName);
            foreach (Type t in assembly.GetTypes())
            {{
                Console.WriteLine("  Type: " + t.FullName);
                foreach (MethodInfo m in t.GetMethods(BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly))
                {{
                    Console.WriteLine("    Method: " + m.Name);
                }}
            }}
            Console.WriteLine("SUCCESS: Assembly is valid and loadable");
        }}
        catch (Exception ex)
        {{
            Console.WriteLine("ERROR: " + ex.Message);
            if (ex.InnerException != null)
            {{
                Console.WriteLine("Inner: " + ex.InnerException.Message);
            }}
            Environment.Exit(1);
        }}
    }}
}}
"#
    );

    // Compile test harness
    let compile_result = compile(capabilities, &test_source, output_dir, "verify_test", arch)?;

    if !compile_result.is_success() {
        return Ok(ReflectionTestResult {
            success: false,
            compilation: Some(compile_result),
            execution: None,
            error: Some("Failed to compile verification test".to_string()),
        });
    }

    // Execute test harness
    let exec_result = execute(capabilities, compile_result.assembly_path())?;

    if exec_result.is_success() {
        Ok(ReflectionTestResult::success(compile_result, exec_result))
    } else {
        Ok(ReflectionTestResult {
            success: false,
            compilation: Some(compile_result),
            execution: Some(exec_result.clone()),
            error: Some(exec_result.error_summary()),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test::mono::compilation::templates;
    use tempfile::TempDir;

    #[test]
    fn test_method_test_builder() {
        let test = MethodTest::new("Add")
            .in_type("TestClass")
            .arg_int(5)
            .arg_int(7)
            .expect_int(12)
            .describe("Test addition");

        assert_eq!(test.method_name, "Add");
        assert_eq!(test.type_name, Some("TestClass".to_string()));
        assert_eq!(test.arguments, vec!["5", "7"]);
        assert_eq!(test.expected_result, Some("12".to_string()));
    }

    #[test]
    fn test_generate_test_program() {
        let tests = vec![MethodTest::new("Add")
            .in_type("TestClass")
            .arg_int(1)
            .arg_int(2)
            .expect_int(3)];

        let source = generate_test_program(Path::new("/test/assembly.dll"), &tests);
        assert!(source.contains("Assembly.LoadFile"));
        assert!(source.contains("GetMethod"));
        assert!(source.contains("Add"));
    }

    #[test]
    fn test_reflection_on_simple_class() -> Result<()> {
        let caps = TestCapabilities::detect();
        if !caps.can_test() {
            println!("Skipping: no compiler/runtime available");
            return Ok(());
        }

        let temp_dir = TempDir::new()?;
        let arch = caps.supported_architectures.first().unwrap();

        // Compile the test assembly
        let assembly_result = compile(
            &caps,
            templates::SIMPLE_CLASS,
            temp_dir.path(),
            "testasm",
            arch,
        )?;
        assert!(
            assembly_result.is_success(),
            "Failed to compile test assembly"
        );

        // Create reflection tests
        let tests = vec![MethodTest::new("Add")
            .in_type("TestClass")
            .arg_int(5)
            .arg_int(7)
            .expect_int(12)
            .describe("5 + 7 = 12")];

        // Run reflection test
        let result = run_reflection_test(
            &caps,
            assembly_result.assembly_path(),
            &tests,
            temp_dir.path(),
            arch,
        )?;

        assert!(
            result.is_success(),
            "Reflection test failed: {}",
            result.error_summary()
        );

        Ok(())
    }
}