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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
//! `System.Runtime.InteropServices.Marshal` and pointer method hooks.
//!
//! This module provides hook implementations for interop-related methods used in
//! obfuscated .NET assemblies for accessing unmanaged memory, P/Invoke operations,
//! and pointer arithmetic. These are critical for anti-tamper and native code interaction.
//!
//! # Overview
//!
//! The `Marshal` class and pointer types (`IntPtr`, `UIntPtr`) are heavily used by
//! obfuscators to access raw memory, read PE headers, and implement anti-tamper checks.
//!
//! # Emulated .NET Methods
//!
//! ## Marshal Methods
//!
//! | Method | Description |
//! |--------|-------------|
//! | `Marshal.GetHINSTANCE(Module)` | Returns PE image base address |
//! | `Marshal.Copy(IntPtr, byte[], int, int)` | Copies from unmanaged to managed |
//! | `Marshal.ReadByte(IntPtr)` | Reads a byte from unmanaged memory |
//! | `Marshal.ReadInt32(IntPtr)` | Reads a 32-bit integer |
//! | `Marshal.WriteByte(IntPtr, byte)` | Writes a byte to unmanaged memory |
//! | `Marshal.WriteInt32(IntPtr, int)` | Writes a 32-bit integer |
//!
//! ## IntPtr Methods
//!
//! | Method | Description |
//! |--------|-------------|
//! | `IntPtr.op_Explicit` | Type conversion operators |
//! | `IntPtr.Add(IntPtr, int)` | Pointer arithmetic |
//! | `IntPtr.ToInt32()` | Convert to 32-bit integer |
//! | `IntPtr.ToInt64()` | Convert to 64-bit integer |
//!
//! ## UIntPtr Methods
//!
//! | Method | Description |
//! |--------|-------------|
//! | `UIntPtr.op_Explicit` | Type conversion operators |
//!
//! # Deobfuscation Use Cases
//!
//! ## Anti-Tamper Checks
//!
//! Many obfuscators read the PE image to verify checksums or locate encrypted code:
//!
//! ```csharp
//! Module mod = typeof(MyClass).Module;
//! IntPtr imageBase = Marshal.GetHINSTANCE(mod);  // <-- Returns PE image base
//! byte[] header = new byte[4096];
//! Marshal.Copy(imageBase, header, 0, 4096);  // <-- Reads PE header
//! ```
//!
//! ## ConfuserEx Anti-Tamper
//!
//! ConfuserEx uses `GetHINSTANCE` to locate the PE sections containing encrypted
//! method bodies. The hook returns the actual image base from the PE file.
//!
//! # Address Space
//!
//! These hooks interact with the [`AddressSpace`] to simulate unmanaged memory.
//! The PE image is mapped into the address space, allowing reads of actual PE data.
//!
//! [`AddressSpace`]: crate::emulation::memory::AddressSpace

use crate::emulation::{
    runtime::hook::{Hook, HookContext, HookManager, PreHookResult},
    thread::EmulationThread,
    EmValue,
};

/// Registers all interop method hooks with the given hook manager.
///
/// # Arguments
///
/// * `manager` - The [`HookManager`] to register hooks with
///
/// # Registered Hooks
///
/// - `Marshal.GetHINSTANCE`, `Marshal.Copy`, `Marshal.ReadByte/Int32`, `Marshal.WriteByte/Int32`
/// - `IntPtr.op_Explicit`, `IntPtr.Add`, `IntPtr.ToInt32/64`
/// - `UIntPtr.op_Explicit`
pub fn register(manager: &mut HookManager) {
    // Marshal methods
    manager.register(
        Hook::new("System.Runtime.InteropServices.Marshal.GetHINSTANCE")
            .match_name("System.Runtime.InteropServices", "Marshal", "GetHINSTANCE")
            .pre(marshal_get_hinstance_pre),
    );

    manager.register(
        Hook::new("System.Runtime.InteropServices.Marshal.Copy")
            .match_name("System.Runtime.InteropServices", "Marshal", "Copy")
            .pre(marshal_copy_pre),
    );

    manager.register(
        Hook::new("System.Runtime.InteropServices.Marshal.ReadByte")
            .match_name("System.Runtime.InteropServices", "Marshal", "ReadByte")
            .pre(marshal_read_byte_pre),
    );

    manager.register(
        Hook::new("System.Runtime.InteropServices.Marshal.ReadInt32")
            .match_name("System.Runtime.InteropServices", "Marshal", "ReadInt32")
            .pre(marshal_read_int32_pre),
    );

    manager.register(
        Hook::new("System.Runtime.InteropServices.Marshal.WriteByte")
            .match_name("System.Runtime.InteropServices", "Marshal", "WriteByte")
            .pre(marshal_write_byte_pre),
    );

    manager.register(
        Hook::new("System.Runtime.InteropServices.Marshal.WriteInt32")
            .match_name("System.Runtime.InteropServices", "Marshal", "WriteInt32")
            .pre(marshal_write_int32_pre),
    );

    // IntPtr methods
    manager.register(
        Hook::new("System.IntPtr.op_Explicit")
            .match_name("System", "IntPtr", "op_Explicit")
            .pre(intptr_op_explicit_pre),
    );

    manager.register(
        Hook::new("System.IntPtr.Add")
            .match_name("System", "IntPtr", "Add")
            .pre(intptr_add_pre),
    );

    manager.register(
        Hook::new("System.IntPtr.ToInt32")
            .match_name("System", "IntPtr", "ToInt32")
            .pre(intptr_to_int32_pre),
    );

    manager.register(
        Hook::new("System.IntPtr.ToInt64")
            .match_name("System", "IntPtr", "ToInt64")
            .pre(intptr_to_int64_pre),
    );

    // UIntPtr methods
    manager.register(
        Hook::new("System.UIntPtr.op_Explicit")
            .match_name("System", "UIntPtr", "op_Explicit")
            .pre(uintptr_op_explicit_pre),
    );
}

/// Hook for `System.Runtime.InteropServices.Marshal.GetHINSTANCE` method.
///
/// Returns the PE base address for the module's assembly image.
///
/// # Handled Overloads
///
/// - `Marshal.GetHINSTANCE(Module) -> IntPtr`
///
/// # Parameters
///
/// - `m`: The module whose HINSTANCE is requested
fn marshal_get_hinstance_pre(
    _ctx: &HookContext<'_>,
    thread: &mut EmulationThread,
) -> PreHookResult {
    // Try to get actual image base from the assembly
    let image_base = thread
        .assembly()
        .map_or(0x0040_0000, |asm| asm.file().imagebase()); // Default Windows image base

    #[allow(clippy::cast_possible_wrap)]
    PreHookResult::Bypass(Some(EmValue::NativeInt(image_base as i64)))
}

/// Hook for `System.Runtime.InteropServices.Marshal.Copy` method.
///
/// Copies data between managed byte arrays and unmanaged memory.
///
/// # Handled Overloads
///
/// - `Marshal.Copy(IntPtr, Byte[], Int32, Int32) -> void` (unmanaged to managed)
/// - `Marshal.Copy(Byte[], Int32, IntPtr, Int32) -> void` (managed to unmanaged)
/// - `Marshal.Copy(IntPtr, Char[], Int32, Int32) -> void`
/// - `Marshal.Copy(IntPtr, Int16[], Int32, Int32) -> void`
/// - `Marshal.Copy(IntPtr, Int32[], Int32, Int32) -> void`
/// - `Marshal.Copy(IntPtr, Int64[], Int32, Int32) -> void`
/// - `Marshal.Copy(IntPtr, Single[], Int32, Int32) -> void`
/// - `Marshal.Copy(IntPtr, Double[], Int32, Int32) -> void`
/// - `Marshal.Copy(IntPtr, IntPtr[], Int32, Int32) -> void`
///
/// # Parameters
///
/// - `source`: Source pointer or array
/// - `destination`: Destination array or pointer
/// - `startIndex`: Starting index in the array
/// - `length`: Number of elements to copy
fn marshal_copy_pre(ctx: &HookContext<'_>, thread: &mut EmulationThread) -> PreHookResult {
    if ctx.args.len() < 4 {
        return PreHookResult::Bypass(None);
    }

    // Check first arg type to determine which overload
    let src_addr = match &ctx.args[0] {
        EmValue::UnmanagedPtr(a) => Some(*a),
        EmValue::NativeInt(a) => Some((*a).cast_unsigned()),
        _ => None,
    };

    if let Some(src_addr) = src_addr {
        // Overload: Copy(IntPtr source, byte[] dest, int startIndex, int length)
        let dst_ref = match &ctx.args[1] {
            EmValue::ObjectRef(r) => *r,
            _ => return PreHookResult::Bypass(None),
        };
        let start_idx = match &ctx.args[2] {
            EmValue::I32(v) => (*v).cast_unsigned() as usize,
            _ => return PreHookResult::Bypass(None),
        };
        let length = match &ctx.args[3] {
            EmValue::I32(v) => (*v).cast_unsigned() as usize,
            _ => return PreHookResult::Bypass(None),
        };

        if let Ok(bytes) = thread.address_space().read(src_addr, length) {
            for (i, &byte) in bytes.iter().enumerate() {
                let _ = thread.heap_mut().set_array_element(
                    dst_ref,
                    start_idx + i,
                    EmValue::I32(i32::from(byte)),
                );
            }
        }
        return PreHookResult::Bypass(None);
    }

    // Overload: Copy(byte[] source, int startIndex, IntPtr dest, int length)
    let EmValue::ObjectRef(src_ref) = &ctx.args[0] else {
        return PreHookResult::Bypass(None);
    };
    let start_idx = match &ctx.args[1] {
        EmValue::I32(v) => (*v).cast_unsigned() as usize,
        _ => return PreHookResult::Bypass(None),
    };
    let dest_addr = match &ctx.args[2] {
        EmValue::UnmanagedPtr(a) => *a,
        EmValue::NativeInt(a) => (*a).cast_unsigned(),
        _ => return PreHookResult::Bypass(None),
    };
    let length = match &ctx.args[3] {
        EmValue::I32(v) => (*v).cast_unsigned() as usize,
        _ => return PreHookResult::Bypass(None),
    };

    let mut bytes = Vec::with_capacity(length);
    for i in 0..length {
        #[allow(clippy::cast_possible_truncation)]
        let byte_val = thread
            .heap()
            .get_array_element(*src_ref, start_idx + i)
            .map(|elem| match elem {
                EmValue::I32(v) => v.cast_unsigned() as u8,
                _ => 0,
            })
            .unwrap_or(0);
        bytes.push(byte_val);
    }

    let _ = thread.address_space().write(dest_addr, &bytes);
    PreHookResult::Bypass(None)
}

/// Hook for `System.Runtime.InteropServices.Marshal.ReadByte` method.
///
/// Reads a single byte from unmanaged memory.
///
/// # Handled Overloads
///
/// - `Marshal.ReadByte(IntPtr) -> Byte`
/// - `Marshal.ReadByte(IntPtr, Int32) -> Byte`
/// - `Marshal.ReadByte(Object, Int32) -> Byte`
///
/// # Parameters
///
/// - `ptr`: Pointer to read from
/// - `ofs`: Byte offset to add to ptr (optional)
/// - `o`: Object in unmanaged memory to read from (overload 3)
fn marshal_read_byte_pre(ctx: &HookContext<'_>, thread: &mut EmulationThread) -> PreHookResult {
    let addr = match ctx.args.first() {
        Some(EmValue::UnmanagedPtr(a)) => *a,
        Some(EmValue::NativeInt(a)) => (*a).cast_unsigned(),
        _ => return PreHookResult::Bypass(Some(EmValue::I32(0))),
    };

    if let Ok(bytes) = thread.address_space().read(addr, 1) {
        PreHookResult::Bypass(Some(EmValue::I32(i32::from(bytes[0]))))
    } else {
        PreHookResult::Bypass(Some(EmValue::I32(0)))
    }
}

/// Hook for `System.Runtime.InteropServices.Marshal.ReadInt32` method.
///
/// Reads a 32-bit signed integer from unmanaged memory.
///
/// # Handled Overloads
///
/// - `Marshal.ReadInt32(IntPtr) -> Int32`
/// - `Marshal.ReadInt32(IntPtr, Int32) -> Int32`
/// - `Marshal.ReadInt32(Object, Int32) -> Int32`
///
/// # Parameters
///
/// - `ptr`: Pointer to read from
/// - `ofs`: Byte offset to add to ptr (optional)
/// - `o`: Object in unmanaged memory to read from (overload 3)
fn marshal_read_int32_pre(ctx: &HookContext<'_>, thread: &mut EmulationThread) -> PreHookResult {
    let addr = match ctx.args.first() {
        Some(EmValue::UnmanagedPtr(a)) => *a,
        Some(EmValue::NativeInt(a)) => (*a).cast_unsigned(),
        _ => return PreHookResult::Bypass(Some(EmValue::I32(0))),
    };

    if let Ok(bytes) = thread.address_space().read(addr, 4) {
        let value = i32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
        PreHookResult::Bypass(Some(EmValue::I32(value)))
    } else {
        PreHookResult::Bypass(Some(EmValue::I32(0)))
    }
}

/// Hook for `System.Runtime.InteropServices.Marshal.WriteByte` method.
///
/// Writes a single byte to unmanaged memory.
///
/// # Handled Overloads
///
/// - `Marshal.WriteByte(IntPtr, Byte) -> void`
/// - `Marshal.WriteByte(IntPtr, Int32, Byte) -> void`
/// - `Marshal.WriteByte(Object, Int32, Byte) -> void`
///
/// # Parameters
///
/// - `ptr`: Pointer to write to
/// - `ofs`: Byte offset to add to ptr (overloads 2-3)
/// - `val`: Byte value to write
/// - `o`: Object in unmanaged memory to write to (overload 3)
fn marshal_write_byte_pre(ctx: &HookContext<'_>, thread: &mut EmulationThread) -> PreHookResult {
    if ctx.args.len() < 2 {
        return PreHookResult::Bypass(None);
    }

    let addr = match &ctx.args[0] {
        EmValue::UnmanagedPtr(a) => *a,
        EmValue::NativeInt(a) => (*a).cast_unsigned(),
        _ => return PreHookResult::Bypass(None),
    };

    #[allow(clippy::cast_possible_truncation)]
    let value = match &ctx.args[1] {
        EmValue::I32(v) => (*v).cast_unsigned() as u8,
        _ => return PreHookResult::Bypass(None),
    };

    let _ = thread.address_space().write(addr, &[value]);
    PreHookResult::Bypass(None)
}

/// Hook for `System.Runtime.InteropServices.Marshal.WriteInt32` method.
///
/// Writes a 32-bit signed integer to unmanaged memory.
///
/// # Handled Overloads
///
/// - `Marshal.WriteInt32(IntPtr, Int32) -> void`
/// - `Marshal.WriteInt32(IntPtr, Int32, Int32) -> void`
/// - `Marshal.WriteInt32(Object, Int32, Int32) -> void`
///
/// # Parameters
///
/// - `ptr`: Pointer to write to
/// - `ofs`: Byte offset to add to ptr (overloads 2-3)
/// - `val`: 32-bit value to write
/// - `o`: Object in unmanaged memory to write to (overload 3)
fn marshal_write_int32_pre(ctx: &HookContext<'_>, thread: &mut EmulationThread) -> PreHookResult {
    if ctx.args.len() < 2 {
        return PreHookResult::Bypass(None);
    }

    let addr = match &ctx.args[0] {
        EmValue::UnmanagedPtr(a) => *a,
        EmValue::NativeInt(a) => (*a).cast_unsigned(),
        _ => return PreHookResult::Bypass(None),
    };

    let value = match &ctx.args[1] {
        EmValue::I32(v) => *v,
        _ => return PreHookResult::Bypass(None),
    };

    let _ = thread.address_space().write(addr, &value.to_le_bytes());
    PreHookResult::Bypass(None)
}

/// Hook for `System.IntPtr.op_Explicit` operator method.
///
/// Converts between IntPtr and various integer/pointer types.
///
/// # Handled Overloads
///
/// - `IntPtr.op_Explicit(IntPtr) -> Int32`
/// - `IntPtr.op_Explicit(IntPtr) -> Int64`
/// - `IntPtr.op_Explicit(IntPtr) -> void*`
/// - `IntPtr.op_Explicit(Int32) -> IntPtr`
/// - `IntPtr.op_Explicit(Int64) -> IntPtr`
/// - `IntPtr.op_Explicit(void*) -> IntPtr`
///
/// # Parameters
///
/// - `value`: The value to convert
fn intptr_op_explicit_pre(ctx: &HookContext<'_>, _thread: &mut EmulationThread) -> PreHookResult {
    let result = if let Some(arg) = ctx.args.first() {
        match arg {
            EmValue::NativeInt(v) | EmValue::I64(v) => EmValue::NativeInt(*v),
            EmValue::NativeUInt(v) | EmValue::UnmanagedPtr(v) => {
                EmValue::NativeInt((*v).cast_signed())
            }
            EmValue::I32(v) => EmValue::NativeInt(i64::from(*v)),
            _ => arg.clone(),
        }
    } else {
        EmValue::NativeInt(0)
    };
    PreHookResult::Bypass(Some(result))
}

/// Hook for `System.IntPtr.Add` method.
///
/// Adds an offset to a pointer value.
///
/// # Handled Overloads
///
/// - `IntPtr.Add(IntPtr, Int32) -> IntPtr`
///
/// # Parameters
///
/// - `pointer`: The pointer to add to
/// - `offset`: The offset to add
fn intptr_add_pre(ctx: &HookContext<'_>, _thread: &mut EmulationThread) -> PreHookResult {
    if ctx.args.len() < 2 {
        return PreHookResult::Bypass(Some(EmValue::NativeInt(0)));
    }

    let ptr = match &ctx.args[0] {
        EmValue::NativeInt(v) => *v,
        EmValue::UnmanagedPtr(v) => (*v).cast_signed(),
        _ => return PreHookResult::Bypass(Some(EmValue::NativeInt(0))),
    };

    let offset = match &ctx.args[1] {
        EmValue::I32(v) => i64::from(*v),
        EmValue::I64(v) => *v,
        _ => return PreHookResult::Bypass(Some(EmValue::NativeInt(ptr))),
    };

    PreHookResult::Bypass(Some(EmValue::NativeInt(ptr.wrapping_add(offset))))
}

/// Hook for `System.IntPtr.ToInt32` method.
///
/// Converts the pointer value to a 32-bit signed integer.
///
/// # Handled Overloads
///
/// - `IntPtr.ToInt32() -> Int32`
fn intptr_to_int32_pre(ctx: &HookContext<'_>, _thread: &mut EmulationThread) -> PreHookResult {
    #[allow(clippy::cast_possible_truncation)]
    let value = match ctx.this {
        Some(EmValue::NativeInt(v)) => *v as i32,
        Some(EmValue::UnmanagedPtr(v)) => *v as i32,
        _ => 0,
    };
    PreHookResult::Bypass(Some(EmValue::I32(value)))
}

/// Hook for `System.IntPtr.ToInt64` method.
///
/// Converts the pointer value to a 64-bit signed integer.
///
/// # Handled Overloads
///
/// - `IntPtr.ToInt64() -> Int64`
fn intptr_to_int64_pre(ctx: &HookContext<'_>, _thread: &mut EmulationThread) -> PreHookResult {
    let value = match ctx.this {
        Some(EmValue::NativeInt(v)) => *v,
        Some(EmValue::UnmanagedPtr(v)) => (*v).cast_signed(),
        _ => 0,
    };
    PreHookResult::Bypass(Some(EmValue::I64(value)))
}

/// Hook for `System.UIntPtr.op_Explicit` operator method.
///
/// Converts between UIntPtr and various integer/pointer types.
///
/// # Handled Overloads
///
/// - `UIntPtr.op_Explicit(UIntPtr) -> UInt32`
/// - `UIntPtr.op_Explicit(UIntPtr) -> UInt64`
/// - `UIntPtr.op_Explicit(UIntPtr) -> void*`
/// - `UIntPtr.op_Explicit(UInt32) -> UIntPtr`
/// - `UIntPtr.op_Explicit(UInt64) -> UIntPtr`
/// - `UIntPtr.op_Explicit(void*) -> UIntPtr`
///
/// # Parameters
///
/// - `value`: The value to convert
fn uintptr_op_explicit_pre(ctx: &HookContext<'_>, _thread: &mut EmulationThread) -> PreHookResult {
    let result = if let Some(arg) = ctx.args.first() {
        match arg {
            EmValue::NativeUInt(v) | EmValue::UnmanagedPtr(v) => EmValue::NativeUInt(*v),
            EmValue::NativeInt(v) | EmValue::I64(v) => EmValue::NativeUInt((*v).cast_unsigned()),
            EmValue::I32(v) => EmValue::NativeUInt((*v).cast_unsigned().into()),
            _ => arg.clone(),
        }
    } else {
        EmValue::NativeUInt(0)
    };
    PreHookResult::Bypass(Some(result))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        emulation::runtime::hook::HookManager,
        metadata::{token::Token, typesystem::PointerSize},
        test::emulation::create_test_thread,
    };

    #[test]
    fn test_register_hooks() {
        let mut manager = HookManager::new();
        register(&mut manager);
        assert_eq!(manager.len(), 11);
    }

    #[test]
    fn test_gethinstance_hook() {
        let ctx = HookContext::new(
            Token::new(0x0A000001),
            "System.Runtime.InteropServices",
            "Marshal",
            "GetHINSTANCE",
            PointerSize::Bit64,
        );

        let mut thread = create_test_thread();

        // Without an assembly, returns default Windows image base
        let result = marshal_get_hinstance_pre(&ctx, &mut thread);
        match result {
            PreHookResult::Bypass(Some(EmValue::NativeInt(v))) => {
                assert_eq!(v, 0x0040_0000);
            }
            _ => panic!("Expected Bypass with NativeInt"),
        }
    }

    #[test]
    fn test_intptr_op_explicit_hook() {
        let args = [EmValue::I32(42)];
        let ctx = HookContext::new(
            Token::new(0x0A000001),
            "System",
            "IntPtr",
            "op_Explicit",
            PointerSize::Bit64,
        )
        .with_args(&args);

        let mut thread = create_test_thread();

        let result = intptr_op_explicit_pre(&ctx, &mut thread);
        match result {
            PreHookResult::Bypass(Some(EmValue::NativeInt(v))) => assert_eq!(v, 42),
            _ => panic!("Expected Bypass with NativeInt(42)"),
        }
    }

    #[test]
    fn test_intptr_add_hook() {
        let args = [EmValue::NativeInt(0x1000), EmValue::I32(0x100)];
        let ctx = HookContext::new(
            Token::new(0x0A000001),
            "System",
            "IntPtr",
            "Add",
            PointerSize::Bit64,
        )
        .with_args(&args);

        let mut thread = create_test_thread();

        let result = intptr_add_pre(&ctx, &mut thread);
        match result {
            PreHookResult::Bypass(Some(EmValue::NativeInt(v))) => assert_eq!(v, 0x1100),
            _ => panic!("Expected Bypass with NativeInt(0x1100)"),
        }
    }

    #[test]
    fn test_intptr_to_int32_hook() {
        let ctx = HookContext::new(
            Token::new(0x0A000001),
            "System",
            "IntPtr",
            "ToInt32",
            PointerSize::Bit64,
        )
        .with_this(Some(&EmValue::NativeInt(42)));

        let mut thread = create_test_thread();

        let result = intptr_to_int32_pre(&ctx, &mut thread);
        match result {
            PreHookResult::Bypass(Some(EmValue::I32(v))) => assert_eq!(v, 42),
            _ => panic!("Expected Bypass with I32(42)"),
        }
    }
}