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
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
//! `System.IO.Stream`, `MemoryStream`, and `BinaryReader` method hooks.
//!
//! This module provides hook implementations for stream-related classes used by
//! obfuscators for reading embedded data, decompressing payloads, and processing
//! encrypted content. Streams are backed by [`HeapObject::Stream`] for full data
//! tracking and position management.
//!
//! # Overview
//!
//! Stream classes are fundamental to .NET I/O operations. Obfuscators commonly use
//! `MemoryStream` to wrap byte arrays and `BinaryReader` to parse structured data.
//! These hooks provide functional implementations that store and retrieve actual data.
//!
//! # Emulated .NET Methods
//!
//! ## MemoryStream Methods
//!
//! | Method | Description | Implementation |
//! |--------|-------------|----------------|
//! | `MemoryStream..ctor(byte[])` | Create stream from bytes | Stores data in heap Stream object |
//! | `MemoryStream.Read(byte[], int, int)` | Read bytes | Reads from Stream data, advances position |
//! | `MemoryStream.ReadByte()` | Read single byte | Reads byte, advances position |
//! | `MemoryStream.Write(byte[], int, int)` | Write bytes | No-op (read-only streams) |
//! | `MemoryStream.ToArray()` | Get stream contents | Returns full Stream data as byte array |
//! | `MemoryStream.get_Length` | Stream length | Returns actual data length |
//! | `MemoryStream.get_Position` | Current position | Returns current read position |
//! | `MemoryStream.set_Position` | Set position | Updates stream position |
//! | `MemoryStream.Seek(long, SeekOrigin)` | Seek to position | Updates position based on origin |
//!
//! ## Stream Base Class Methods
//!
//! | Method | Description | Implementation |
//! |--------|-------------|----------------|
//! | `Stream.Read(byte[], int, int)` | Read bytes | Reads from Stream data |
//! | `Stream.ReadByte()` | Read single byte | Reads byte from Stream |
//! | `Stream.get_Length` | Stream length | Returns actual length |
//! | `Stream.Close()` | Close stream | No-op |
//! | `Stream.Dispose()` | Dispose stream | No-op |
//!
//! ## BinaryReader Methods
//!
//! | Method | Description | Implementation |
//! |--------|-------------|----------------|
//! | `BinaryReader..ctor(Stream)` | Create reader | Stores stream reference in synthetic field |
//! | `BinaryReader.ReadByte()` | Read byte | Reads from stream, advances position |
//! | `BinaryReader.ReadBytes(int)` | Read byte array | Reads from stream, advances position |
//! | `BinaryReader.ReadInt16()` | Read 16-bit int | Reads little-endian from stream |
//! | `BinaryReader.ReadInt32()` | Read 32-bit int | Reads little-endian from stream |
//! | `BinaryReader.ReadInt64()` | Read 64-bit int | Reads little-endian from stream |
//! | `BinaryReader.ReadString()` | Read length-prefixed string | Reads 7-bit length + UTF-8 bytes |
//! | `BinaryReader.Close()` | Close reader | No-op |
//!
//! # Deobfuscation Use Cases
//!
//! ## Payload Decompression
//!
//! Obfuscators often embed compressed data and decompress at runtime:
//!
//! ```csharp
//! byte[] compressed = GetEmbeddedResource();
//! using (MemoryStream ms = new MemoryStream(compressed))
//! using (DeflateStream ds = new DeflateStream(ms, CompressionMode.Decompress))
//! {
//!     byte[] payload = ReadAll(ds);
//!     Assembly.Load(payload);
//! }
//! ```
//!
//! ## Structured Data Parsing
//!
//! Encrypted string tables are often read with `BinaryReader`:
//!
//! ```csharp
//! using (BinaryReader reader = new BinaryReader(ms))
//! {
//!     int count = reader.ReadInt32();
//!     for (int i = 0; i < count; i++)
//!     {
//!         string s = reader.ReadString();
//!         // Process decrypted string...
//!     }
//! }
//! ```
//!
//! # Implementation Notes
//!
//! Stream data is stored in [`HeapObject::Stream`] which provides:
//!
//! - **Full data tracking**: Stream contents are stored and retrieved correctly
//! - **Position tracking**: Read position advances as data is consumed
//! - **Length tracking**: Actual data length is available
//! - **Read-only**: Write operations are no-ops (sufficient for deobfuscation)
//!
//! [`HeapObject::Stream`]: crate::emulation::memory::HeapObject::Stream

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

/// Returns the synthetic field token used to store the underlying stream reference in BinaryReader.
/// Uses a high value to avoid collision with real field tokens.
fn binary_reader_stream_field() -> Token {
    Token::new(0xFFFF_0001)
}

/// Registers all Stream and BinaryReader method hooks with the given hook manager.
///
/// # Arguments
///
/// * `manager` - The [`HookManager`] to register hooks with
///
/// # Registered Hooks
///
/// ## MemoryStream
/// - `MemoryStream..ctor(byte[])`
/// - `MemoryStream.Read`, `MemoryStream.ReadByte`, `MemoryStream.Write`
/// - `MemoryStream.ToArray`, `MemoryStream.get_Length`
/// - `MemoryStream.get_Position`, `MemoryStream.set_Position`, `MemoryStream.Seek`
///
/// ## Stream
/// - `Stream.Read`, `Stream.ReadByte`, `Stream.get_Length`
/// - `Stream.Close`, `Stream.Dispose`
///
/// ## BinaryReader
/// - `BinaryReader..ctor(Stream)`
/// - `BinaryReader.ReadByte`, `BinaryReader.ReadBytes`
/// - `BinaryReader.ReadInt16`, `BinaryReader.ReadInt32`, `BinaryReader.ReadInt64`
/// - `BinaryReader.ReadString`, `BinaryReader.Close`
pub fn register(manager: &mut HookManager) {
    // MemoryStream methods
    manager.register(
        Hook::new("System.IO.MemoryStream..ctor")
            .match_name("System.IO", "MemoryStream", ".ctor")
            .pre(memory_stream_ctor_pre),
    );

    manager.register(
        Hook::new("System.IO.MemoryStream.Read")
            .match_name("System.IO", "MemoryStream", "Read")
            .pre(stream_read_pre),
    );

    manager.register(
        Hook::new("System.IO.MemoryStream.ReadByte")
            .match_name("System.IO", "MemoryStream", "ReadByte")
            .pre(stream_read_byte_pre),
    );

    manager.register(
        Hook::new("System.IO.MemoryStream.Write")
            .match_name("System.IO", "MemoryStream", "Write")
            .pre(stream_write_pre),
    );

    manager.register(
        Hook::new("System.IO.MemoryStream.ToArray")
            .match_name("System.IO", "MemoryStream", "ToArray")
            .pre(memory_stream_to_array_pre),
    );

    manager.register(
        Hook::new("System.IO.MemoryStream.get_Length")
            .match_name("System.IO", "MemoryStream", "get_Length")
            .pre(stream_get_length_pre),
    );

    manager.register(
        Hook::new("System.IO.MemoryStream.get_Position")
            .match_name("System.IO", "MemoryStream", "get_Position")
            .pre(stream_get_position_pre),
    );

    manager.register(
        Hook::new("System.IO.MemoryStream.set_Position")
            .match_name("System.IO", "MemoryStream", "set_Position")
            .pre(stream_set_position_pre),
    );

    manager.register(
        Hook::new("System.IO.MemoryStream.Seek")
            .match_name("System.IO", "MemoryStream", "Seek")
            .pre(stream_seek_pre),
    );

    // Stream base class methods
    manager.register(
        Hook::new("System.IO.Stream.Read")
            .match_name("System.IO", "Stream", "Read")
            .pre(stream_read_pre),
    );

    manager.register(
        Hook::new("System.IO.Stream.ReadByte")
            .match_name("System.IO", "Stream", "ReadByte")
            .pre(stream_read_byte_pre),
    );

    manager.register(
        Hook::new("System.IO.Stream.get_Length")
            .match_name("System.IO", "Stream", "get_Length")
            .pre(stream_get_length_pre),
    );

    manager.register(
        Hook::new("System.IO.Stream.Close")
            .match_name("System.IO", "Stream", "Close")
            .pre(stream_close_pre),
    );

    manager.register(
        Hook::new("System.IO.Stream.Dispose")
            .match_name("System.IO", "Stream", "Dispose")
            .pre(stream_dispose_pre),
    );

    // BinaryReader methods
    manager.register(
        Hook::new("System.IO.BinaryReader..ctor")
            .match_name("System.IO", "BinaryReader", ".ctor")
            .pre(binary_reader_ctor_pre),
    );

    manager.register(
        Hook::new("System.IO.BinaryReader.ReadByte")
            .match_name("System.IO", "BinaryReader", "ReadByte")
            .pre(binary_reader_read_byte_pre),
    );

    manager.register(
        Hook::new("System.IO.BinaryReader.ReadBytes")
            .match_name("System.IO", "BinaryReader", "ReadBytes")
            .pre(binary_reader_read_bytes_pre),
    );

    manager.register(
        Hook::new("System.IO.BinaryReader.ReadInt16")
            .match_name("System.IO", "BinaryReader", "ReadInt16")
            .pre(binary_reader_read_int16_pre),
    );

    manager.register(
        Hook::new("System.IO.BinaryReader.ReadInt32")
            .match_name("System.IO", "BinaryReader", "ReadInt32")
            .pre(binary_reader_read_int32_pre),
    );

    manager.register(
        Hook::new("System.IO.BinaryReader.ReadInt64")
            .match_name("System.IO", "BinaryReader", "ReadInt64")
            .pre(binary_reader_read_int64_pre),
    );

    manager.register(
        Hook::new("System.IO.BinaryReader.ReadString")
            .match_name("System.IO", "BinaryReader", "ReadString")
            .pre(binary_reader_read_string_pre),
    );

    manager.register(
        Hook::new("System.IO.BinaryReader.Close")
            .match_name("System.IO", "BinaryReader", "Close")
            .pre(stream_close_pre),
    );
}

/// Hook for `System.IO.MemoryStream..ctor` constructor.
///
/// # Handled Overloads
///
/// - `MemoryStream..ctor()` - Creates an empty stream
/// - `MemoryStream..ctor(Byte[])` - Creates a stream from byte array
///
/// # Parameters
///
/// - `buffer`: Optional byte array containing initial stream data
fn memory_stream_ctor_pre(ctx: &HookContext<'_>, thread: &mut EmulationThread) -> PreHookResult {
    // Get the byte array argument (may be None for empty stream)
    let data = if let Some(EmValue::ObjectRef(array_ref)) = ctx.args.first() {
        // Try get_byte_array first (for byte[] arrays with I32 elements)
        // Fall back to get_array_as_bytes which handles multi-byte element types
        // (e.g., uint[] arrays serialized to bytes in little-endian order)
        thread
            .heap()
            .get_byte_array(*array_ref)
            .or_else(|| {
                thread
                    .heap()
                    .get_array_as_bytes(*array_ref, ctx.pointer_size)
            })
            .unwrap_or_default()
    } else {
        Vec::new()
    };

    match ctx.this {
        Some(EmValue::ObjectRef(stream_ref)) => {
            // Instance call: replace the allocated object with a Stream
            thread.heap_mut().replace_with_stream(*stream_ref, data);
            PreHookResult::Bypass(None) // Constructor returns void
        }
        _ => {
            // Factory pattern: allocate a new Stream directly
            match thread.heap_mut().alloc_stream(data) {
                Ok(stream_ref) => PreHookResult::Bypass(Some(EmValue::ObjectRef(stream_ref))),
                Err(_) => PreHookResult::Bypass(Some(EmValue::Null)),
            }
        }
    }
}

/// Hook for `System.IO.Stream.Read` and `System.IO.MemoryStream.Read` methods.
///
/// # Handled Overloads
///
/// - `Stream.Read(Byte[], Int32, Int32) -> Int32`
/// - `MemoryStream.Read(Byte[], Int32, Int32) -> Int32`
///
/// # Parameters
///
/// - `buffer`: Destination byte array to read into
/// - `offset`: Zero-based byte offset in buffer to begin storing data
/// - `count`: Maximum number of bytes to read
///
/// # Returns
///
/// Number of bytes actually read into the buffer
fn stream_read_pre(ctx: &HookContext<'_>, thread: &mut EmulationThread) -> PreHookResult {
    // Get the stream reference
    let stream_ref = match ctx.this {
        Some(EmValue::ObjectRef(r)) => *r,
        _ => return PreHookResult::Bypass(Some(EmValue::I32(0))),
    };

    // Parse arguments: buffer, offset, count
    // Safe: values validated as non-negative
    #[allow(clippy::cast_sign_loss)]
    let (buffer_ref, offset, count) = match (ctx.args.first(), ctx.args.get(1), ctx.args.get(2)) {
        (Some(EmValue::ObjectRef(b)), Some(EmValue::I32(o)), Some(EmValue::I32(c))) => {
            (*b, *o as usize, *c as usize)
        }
        _ => return PreHookResult::Bypass(Some(EmValue::I32(0))),
    };

    // Get stream data and position
    let Some((data, position)) = thread.heap().get_stream_data(stream_ref) else {
        return PreHookResult::Bypass(Some(EmValue::I32(0)));
    };

    // Calculate how many bytes we can read
    let available = data.len().saturating_sub(position);
    let to_read = count.min(available);

    // Read bytes into buffer
    for i in 0..to_read {
        if let Some(&byte) = data.get(position + i) {
            let _ = thread.heap_mut().set_array_element(
                buffer_ref,
                offset + i,
                EmValue::I32(i32::from(byte)),
            );
        }
    }

    // Update stream position
    thread
        .heap_mut()
        .set_stream_position(stream_ref, position + to_read);

    #[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]
    PreHookResult::Bypass(Some(EmValue::I32(to_read as i32)))
}

/// Hook for `System.IO.Stream.ReadByte` and `System.IO.MemoryStream.ReadByte` methods.
///
/// # Handled Overloads
///
/// - `Stream.ReadByte() -> Int32`
/// - `MemoryStream.ReadByte() -> Int32`
///
/// # Returns
///
/// The byte cast to `Int32`, or -1 if at end of stream
fn stream_read_byte_pre(ctx: &HookContext<'_>, thread: &mut EmulationThread) -> PreHookResult {
    // Get the stream reference
    let stream_ref = match ctx.this {
        Some(EmValue::ObjectRef(r)) => *r,
        _ => return PreHookResult::Bypass(Some(EmValue::I32(-1))),
    };

    // Get stream data and position
    let Some((data, position)) = thread.heap().get_stream_data(stream_ref) else {
        return PreHookResult::Bypass(Some(EmValue::I32(-1)));
    };

    // Check if at end of stream
    if position >= data.len() {
        return PreHookResult::Bypass(Some(EmValue::I32(-1))); // EOF
    }

    // Read the byte
    let byte = data[position];

    // Update stream position
    thread
        .heap_mut()
        .set_stream_position(stream_ref, position + 1);

    PreHookResult::Bypass(Some(EmValue::I32(i32::from(byte))))
}

/// Hook for `System.IO.MemoryStream.Write` method.
///
/// # Handled Overloads
///
/// - `MemoryStream.Write(Byte[], Int32, Int32) -> Void`
///
/// # Parameters
///
/// - `buffer`: Source byte array containing data to write
/// - `offset`: Zero-based byte offset in buffer from which to copy bytes
/// - `count`: Number of bytes to write
fn stream_write_pre(ctx: &HookContext<'_>, thread: &mut EmulationThread) -> PreHookResult {
    // Get the stream reference
    let stream_ref = match ctx.this {
        Some(EmValue::ObjectRef(r)) => *r,
        _ => return PreHookResult::Bypass(None),
    };

    // Parse arguments: buffer, offset, count
    // Safe: values validated as non-negative
    #[allow(clippy::cast_sign_loss)]
    let (buffer_ref, offset, count) = match (ctx.args.first(), ctx.args.get(1), ctx.args.get(2)) {
        (Some(EmValue::ObjectRef(b)), Some(EmValue::I32(o)), Some(EmValue::I32(c))) => {
            (*b, *o as usize, *c as usize)
        }
        _ => return PreHookResult::Bypass(None),
    };

    // Get bytes from the buffer array
    let Some(buffer_data) = thread.heap().get_byte_array(buffer_ref) else {
        return PreHookResult::Bypass(None);
    };

    // Extract the slice to write
    let end = (offset + count).min(buffer_data.len());
    let bytes_to_write = if offset < buffer_data.len() {
        &buffer_data[offset..end]
    } else {
        &[]
    };

    // Write to the stream
    thread
        .heap_mut()
        .write_to_stream(stream_ref, bytes_to_write);

    PreHookResult::Bypass(None)
}

/// Hook for `System.IO.MemoryStream.ToArray` method.
///
/// # Handled Overloads
///
/// - `MemoryStream.ToArray() -> Byte[]`
///
/// # Returns
///
/// A new byte array containing the stream contents
fn memory_stream_to_array_pre(
    ctx: &HookContext<'_>,
    thread: &mut EmulationThread,
) -> PreHookResult {
    // Get the stream reference
    let stream_ref = match ctx.this {
        Some(EmValue::ObjectRef(r)) => *r,
        _ => {
            // Return empty byte array if no stream
            match thread.heap_mut().alloc_byte_array(&[]) {
                Ok(array_ref) => return PreHookResult::Bypass(Some(EmValue::ObjectRef(array_ref))),
                Err(_) => return PreHookResult::Bypass(Some(EmValue::Null)),
            }
        }
    };

    // Get stream data (already cloned by get_stream_data)
    let data = match thread.heap().get_stream_data(stream_ref) {
        Some((data, _)) => data,
        None => Vec::new(),
    };

    // Allocate and return byte array
    match thread.heap_mut().alloc_byte_array(&data) {
        Ok(array_ref) => PreHookResult::Bypass(Some(EmValue::ObjectRef(array_ref))),
        Err(_) => PreHookResult::Bypass(Some(EmValue::Null)),
    }
}

/// Hook for `System.IO.Stream.get_Length` and `System.IO.MemoryStream.get_Length` properties.
///
/// # Handled Overloads
///
/// - `Stream.Length { get; } -> Int64`
/// - `MemoryStream.Length { get; } -> Int64`
///
/// # Returns
///
/// The length of the stream in bytes
fn stream_get_length_pre(ctx: &HookContext<'_>, thread: &mut EmulationThread) -> PreHookResult {
    // Get the stream reference
    let stream_ref = match ctx.this {
        Some(EmValue::ObjectRef(r)) => *r,
        _ => return PreHookResult::Bypass(Some(EmValue::I64(0))),
    };

    // Get stream data length
    let length = match thread.heap().get_stream_data(stream_ref) {
        Some((data, _)) => data.len(),
        None => 0,
    };

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

/// Hook for `System.IO.MemoryStream.get_Position` property.
///
/// # Handled Overloads
///
/// - `MemoryStream.Position { get; } -> Int64`
///
/// # Returns
///
/// The current position within the stream
fn stream_get_position_pre(ctx: &HookContext<'_>, thread: &mut EmulationThread) -> PreHookResult {
    // Get the stream reference
    let stream_ref = match ctx.this {
        Some(EmValue::ObjectRef(r)) => *r,
        _ => return PreHookResult::Bypass(Some(EmValue::I64(0))),
    };

    // Get stream position
    let position = match thread.heap().get_stream_data(stream_ref) {
        Some((_, pos)) => pos,
        None => 0,
    };

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

/// Hook for `System.IO.MemoryStream.set_Position` property.
///
/// # Handled Overloads
///
/// - `MemoryStream.Position { set; }`
///
/// # Parameters
///
/// - `value`: The new position within the stream
fn stream_set_position_pre(ctx: &HookContext<'_>, thread: &mut EmulationThread) -> PreHookResult {
    // Get the stream reference
    let stream_ref = match ctx.this {
        Some(EmValue::ObjectRef(r)) => *r,
        _ => return PreHookResult::Bypass(None),
    };

    // Get the new position
    // Safe: values validated as non-negative
    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
    let new_pos = match ctx.args.first() {
        Some(EmValue::I64(v)) => *v as usize,
        Some(EmValue::I32(v)) => *v as usize,
        _ => return PreHookResult::Bypass(None),
    };

    // Update stream position
    thread.heap_mut().set_stream_position(stream_ref, new_pos);
    PreHookResult::Bypass(None)
}

/// Hook for `System.IO.MemoryStream.Seek` method.
///
/// # Handled Overloads
///
/// - `MemoryStream.Seek(Int64, SeekOrigin) -> Int64`
///
/// # Parameters
///
/// - `offset`: Byte offset relative to origin
/// - `origin`: Reference point (Begin=0, Current=1, End=2)
///
/// # Returns
///
/// The new position within the stream
fn stream_seek_pre(ctx: &HookContext<'_>, thread: &mut EmulationThread) -> PreHookResult {
    // Get the stream reference
    let stream_ref = match ctx.this {
        Some(EmValue::ObjectRef(r)) => *r,
        _ => return PreHookResult::Bypass(Some(EmValue::I64(0))),
    };

    // Get offset and origin
    let offset = match ctx.args.first() {
        Some(EmValue::I64(v)) => *v,
        Some(EmValue::I32(v)) => i64::from(*v),
        _ => 0,
    };

    let origin = match ctx.args.get(1) {
        Some(EmValue::I32(v)) => *v,
        _ => 0, // Default to Begin
    };

    // Get current stream data for length and position
    let (length, current_pos) = match thread.heap().get_stream_data(stream_ref) {
        Some((data, pos)) => (data.len(), pos),
        None => return PreHookResult::Bypass(Some(EmValue::I64(0))),
    };

    // Calculate new position based on origin
    // SeekOrigin: 0=Begin, 1=Current, 2=End
    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
    let new_pos = match origin {
        1 => {
            // Current
            // Safe: stream positions fit in i64
            #[allow(clippy::cast_possible_wrap)]
            let pos = current_pos as i64 + offset;
            pos.max(0) as usize
        }
        2 => {
            // End
            // Safe: stream positions fit in i64
            #[allow(clippy::cast_possible_wrap)]
            let pos = length as i64 + offset;
            pos.max(0) as usize
        }
        // Begin (0) and default
        _ => offset.max(0) as usize,
    };

    // Clamp to valid range
    let clamped_pos = new_pos.min(length);

    // Update stream position
    thread
        .heap_mut()
        .set_stream_position(stream_ref, clamped_pos);

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

/// Hook for `System.IO.Stream.Close` and `System.IO.BinaryReader.Close` methods.
///
/// # Handled Overloads
///
/// - `Stream.Close() -> Void`
/// - `BinaryReader.Close() -> Void`
///
/// # Implementation Note
///
/// This is a no-op as emulated streams do not require cleanup.
fn stream_close_pre(_ctx: &HookContext<'_>, _thread: &mut EmulationThread) -> PreHookResult {
    PreHookResult::Bypass(None)
}

/// Hook for `System.IO.Stream.Dispose` method.
///
/// # Handled Overloads
///
/// - `Stream.Dispose() -> Void`
///
/// # Implementation Note
///
/// This is a no-op as emulated streams do not require cleanup.
fn stream_dispose_pre(_ctx: &HookContext<'_>, _thread: &mut EmulationThread) -> PreHookResult {
    PreHookResult::Bypass(None)
}

/// Helper function to get the underlying stream reference from a BinaryReader.
fn get_binary_reader_stream(reader_ref: HeapRef, thread: &EmulationThread) -> Option<HeapRef> {
    let field_value = thread
        .heap()
        .get_field(reader_ref, binary_reader_stream_field())
        .ok()?;
    match field_value {
        EmValue::ObjectRef(stream_ref) => Some(stream_ref),
        _ => None,
    }
}

/// Hook for `System.IO.BinaryReader..ctor` constructor.
///
/// # Handled Overloads
///
/// - `BinaryReader..ctor(Stream)`
///
/// # Parameters
///
/// - `input`: The underlying stream to read from
fn binary_reader_ctor_pre(ctx: &HookContext<'_>, thread: &mut EmulationThread) -> PreHookResult {
    // Get the BinaryReader object reference
    let reader_ref = match ctx.this {
        Some(EmValue::ObjectRef(r)) => *r,
        _ => return PreHookResult::Bypass(None),
    };

    // Get the stream argument
    let stream_ref = match ctx.args.first() {
        Some(EmValue::ObjectRef(r)) => *r,
        _ => return PreHookResult::Bypass(None),
    };

    // Store the stream reference in the BinaryReader's field
    let _ = thread.heap_mut().set_field(
        reader_ref,
        binary_reader_stream_field(),
        EmValue::ObjectRef(stream_ref),
    );

    PreHookResult::Bypass(None)
}

/// Hook for `System.IO.BinaryReader.ReadByte` method.
///
/// # Handled Overloads
///
/// - `BinaryReader.ReadByte() -> Byte`
///
/// # Returns
///
/// The next byte read from the underlying stream
fn binary_reader_read_byte_pre(
    ctx: &HookContext<'_>,
    thread: &mut EmulationThread,
) -> PreHookResult {
    // Get the BinaryReader object reference
    let reader_ref = match ctx.this {
        Some(EmValue::ObjectRef(r)) => *r,
        _ => return PreHookResult::Bypass(Some(EmValue::I32(0))),
    };

    // Get the underlying stream
    let Some(stream_ref) = get_binary_reader_stream(reader_ref, thread) else {
        return PreHookResult::Bypass(Some(EmValue::I32(0)));
    };

    // Get stream data and position
    let Some((data, position)) = thread.heap().get_stream_data(stream_ref) else {
        return PreHookResult::Bypass(Some(EmValue::I32(0)));
    };

    // Check if at end of stream
    if position >= data.len() {
        return PreHookResult::Bypass(Some(EmValue::I32(0)));
    }

    // Read the byte
    let byte = data[position];

    // Update stream position
    thread
        .heap_mut()
        .set_stream_position(stream_ref, position + 1);

    PreHookResult::Bypass(Some(EmValue::I32(i32::from(byte))))
}

/// Hook for `System.IO.BinaryReader.ReadBytes` method.
///
/// # Handled Overloads
///
/// - `BinaryReader.ReadBytes(Int32) -> Byte[]`
///
/// # Parameters
///
/// - `count`: Number of bytes to read
///
/// # Returns
///
/// A byte array containing the requested bytes
fn binary_reader_read_bytes_pre(
    ctx: &HookContext<'_>,
    thread: &mut EmulationThread,
) -> PreHookResult {
    // Safe: value validated as non-negative
    #[allow(clippy::cast_sign_loss)]
    let count = match ctx.args.first() {
        Some(EmValue::I32(v)) => *v as usize,
        _ => 0,
    };

    // Get the BinaryReader object reference
    let reader_ref = match ctx.this {
        Some(EmValue::ObjectRef(r)) => *r,
        _ => match thread.heap_mut().alloc_byte_array(&vec![0u8; count]) {
            Ok(array_ref) => return PreHookResult::Bypass(Some(EmValue::ObjectRef(array_ref))),
            Err(_) => return PreHookResult::Bypass(Some(EmValue::Null)),
        },
    };

    // Get the underlying stream
    let Some(stream_ref) = get_binary_reader_stream(reader_ref, thread) else {
        match thread.heap_mut().alloc_byte_array(&vec![0u8; count]) {
            Ok(array_ref) => return PreHookResult::Bypass(Some(EmValue::ObjectRef(array_ref))),
            Err(_) => return PreHookResult::Bypass(Some(EmValue::Null)),
        }
    };

    // Get stream data and position
    let Some((data, position)) = thread.heap().get_stream_data(stream_ref) else {
        match thread.heap_mut().alloc_byte_array(&vec![0u8; count]) {
            Ok(array_ref) => return PreHookResult::Bypass(Some(EmValue::ObjectRef(array_ref))),
            Err(_) => return PreHookResult::Bypass(Some(EmValue::Null)),
        }
    };

    // Calculate how many bytes we can read
    let available = data.len().saturating_sub(position);
    let to_read = count.min(available);

    // Read the bytes
    let bytes: Vec<u8> = data[position..position + to_read].to_vec();

    // Update stream position
    thread
        .heap_mut()
        .set_stream_position(stream_ref, position + to_read);

    match thread.heap_mut().alloc_byte_array(&bytes) {
        Ok(array_ref) => PreHookResult::Bypass(Some(EmValue::ObjectRef(array_ref))),
        Err(_) => PreHookResult::Bypass(Some(EmValue::Null)),
    }
}

/// Hook for `System.IO.BinaryReader.ReadInt16` method.
///
/// # Handled Overloads
///
/// - `BinaryReader.ReadInt16() -> Int16`
///
/// # Returns
///
/// A 2-byte signed integer read in little-endian format
fn binary_reader_read_int16_pre(
    ctx: &HookContext<'_>,
    thread: &mut EmulationThread,
) -> PreHookResult {
    // Get the BinaryReader object reference
    let reader_ref = match ctx.this {
        Some(EmValue::ObjectRef(r)) => *r,
        _ => return PreHookResult::Bypass(Some(EmValue::I32(0))),
    };

    // Get the underlying stream
    let Some(stream_ref) = get_binary_reader_stream(reader_ref, thread) else {
        return PreHookResult::Bypass(Some(EmValue::I32(0)));
    };

    // Get stream data and position
    let Some((data, position)) = thread.heap().get_stream_data(stream_ref) else {
        return PreHookResult::Bypass(Some(EmValue::I32(0)));
    };

    // Need 2 bytes
    if position + 2 > data.len() {
        return PreHookResult::Bypass(Some(EmValue::I32(0)));
    }

    // Read little-endian i16
    let value = i16::from_le_bytes([data[position], data[position + 1]]);

    // Update stream position
    thread
        .heap_mut()
        .set_stream_position(stream_ref, position + 2);

    PreHookResult::Bypass(Some(EmValue::I32(i32::from(value))))
}

/// Hook for `System.IO.BinaryReader.ReadInt32` method.
///
/// # Handled Overloads
///
/// - `BinaryReader.ReadInt32() -> Int32`
///
/// # Returns
///
/// A 4-byte signed integer read in little-endian format
fn binary_reader_read_int32_pre(
    ctx: &HookContext<'_>,
    thread: &mut EmulationThread,
) -> PreHookResult {
    // Get the BinaryReader object reference
    let reader_ref = match ctx.this {
        Some(EmValue::ObjectRef(r)) => *r,
        _ => return PreHookResult::Bypass(Some(EmValue::I32(0))),
    };

    // Get the underlying stream
    let Some(stream_ref) = get_binary_reader_stream(reader_ref, thread) else {
        return PreHookResult::Bypass(Some(EmValue::I32(0)));
    };

    // Get stream data and position
    let Some((data, position)) = thread.heap().get_stream_data(stream_ref) else {
        return PreHookResult::Bypass(Some(EmValue::I32(0)));
    };

    // Need 4 bytes
    if position + 4 > data.len() {
        return PreHookResult::Bypass(Some(EmValue::I32(0)));
    }

    // Read little-endian i32
    let value = i32::from_le_bytes([
        data[position],
        data[position + 1],
        data[position + 2],
        data[position + 3],
    ]);

    // Update stream position
    thread
        .heap_mut()
        .set_stream_position(stream_ref, position + 4);

    PreHookResult::Bypass(Some(EmValue::I32(value)))
}

/// Hook for `System.IO.BinaryReader.ReadInt64` method.
///
/// # Handled Overloads
///
/// - `BinaryReader.ReadInt64() -> Int64`
///
/// # Returns
///
/// An 8-byte signed integer read in little-endian format
fn binary_reader_read_int64_pre(
    ctx: &HookContext<'_>,
    thread: &mut EmulationThread,
) -> PreHookResult {
    // Get the BinaryReader object reference
    let reader_ref = match ctx.this {
        Some(EmValue::ObjectRef(r)) => *r,
        _ => return PreHookResult::Bypass(Some(EmValue::I64(0))),
    };

    // Get the underlying stream
    let Some(stream_ref) = get_binary_reader_stream(reader_ref, thread) else {
        return PreHookResult::Bypass(Some(EmValue::I64(0)));
    };

    // Get stream data and position
    let Some((data, position)) = thread.heap().get_stream_data(stream_ref) else {
        return PreHookResult::Bypass(Some(EmValue::I64(0)));
    };

    // Need 8 bytes
    if position + 8 > data.len() {
        return PreHookResult::Bypass(Some(EmValue::I64(0)));
    }

    // Read little-endian i64
    let value = i64::from_le_bytes([
        data[position],
        data[position + 1],
        data[position + 2],
        data[position + 3],
        data[position + 4],
        data[position + 5],
        data[position + 6],
        data[position + 7],
    ]);

    // Update stream position
    thread
        .heap_mut()
        .set_stream_position(stream_ref, position + 8);

    PreHookResult::Bypass(Some(EmValue::I64(value)))
}

/// Hook for `System.IO.BinaryReader.ReadString` method.
///
/// # Handled Overloads
///
/// - `BinaryReader.ReadString() -> String`
///
/// # Returns
///
/// A string read using 7-bit encoded length prefix followed by UTF-8 bytes
fn binary_reader_read_string_pre(
    ctx: &HookContext<'_>,
    thread: &mut EmulationThread,
) -> PreHookResult {
    // Get the BinaryReader object reference
    let reader_ref = match ctx.this {
        Some(EmValue::ObjectRef(r)) => *r,
        _ => match thread.heap_mut().alloc_string("") {
            Ok(str_ref) => return PreHookResult::Bypass(Some(EmValue::ObjectRef(str_ref))),
            Err(_) => return PreHookResult::Bypass(Some(EmValue::Null)),
        },
    };

    // Get the underlying stream
    let Some(stream_ref) = get_binary_reader_stream(reader_ref, thread) else {
        match thread.heap_mut().alloc_string("") {
            Ok(str_ref) => return PreHookResult::Bypass(Some(EmValue::ObjectRef(str_ref))),
            Err(_) => return PreHookResult::Bypass(Some(EmValue::Null)),
        }
    };

    // Get stream data and position
    let Some((data, mut position)) = thread.heap().get_stream_data(stream_ref) else {
        match thread.heap_mut().alloc_string("") {
            Ok(str_ref) => return PreHookResult::Bypass(Some(EmValue::ObjectRef(str_ref))),
            Err(_) => return PreHookResult::Bypass(Some(EmValue::Null)),
        }
    };

    // Read 7-bit encoded length (LEB128-style)
    let mut length: usize = 0;
    let mut shift = 0;
    loop {
        if position >= data.len() {
            match thread.heap_mut().alloc_string("") {
                Ok(str_ref) => return PreHookResult::Bypass(Some(EmValue::ObjectRef(str_ref))),
                Err(_) => return PreHookResult::Bypass(Some(EmValue::Null)),
            }
        }
        let byte = data[position];
        position += 1;
        length |= ((byte & 0x7F) as usize) << shift;
        if byte & 0x80 == 0 {
            break;
        }
        shift += 7;
        // Prevent infinite loop on malformed data
        if shift > 35 {
            break;
        }
    }

    // Read the string bytes
    if position + length > data.len() {
        // Not enough data, read what we can
        let available = data.len().saturating_sub(position);
        let str_bytes = &data[position..position + available];
        let s = String::from_utf8_lossy(str_bytes).into_owned();
        position += available;
        thread.heap_mut().set_stream_position(stream_ref, position);
        match thread.heap_mut().alloc_string(&s) {
            Ok(str_ref) => return PreHookResult::Bypass(Some(EmValue::ObjectRef(str_ref))),
            Err(_) => return PreHookResult::Bypass(Some(EmValue::Null)),
        }
    }

    let str_bytes = &data[position..position + length];
    let s = String::from_utf8_lossy(str_bytes).into_owned();
    position += length;

    // Update stream position
    thread.heap_mut().set_stream_position(stream_ref, position);

    match thread.heap_mut().alloc_string(&s) {
        Ok(str_ref) => PreHookResult::Bypass(Some(EmValue::ObjectRef(str_ref))),
        Err(_) => PreHookResult::Bypass(Some(EmValue::Null)),
    }
}

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

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

    #[test]
    fn test_stream_close_hook() {
        let ctx = HookContext::new(
            Token::new(0x0A000001),
            "System.IO",
            "Stream",
            "Close",
            PointerSize::Bit64,
        );

        let mut thread = create_test_thread();
        let result = stream_close_pre(&ctx, &mut thread);

        match result {
            PreHookResult::Bypass(None) => {}
            _ => panic!("Expected Bypass(None)"),
        }
    }

    #[test]
    fn test_stream_read_byte_eof_without_stream() {
        let ctx = HookContext::new(
            Token::new(0x0A000001),
            "System.IO",
            "Stream",
            "ReadByte",
            PointerSize::Bit64,
        );

        let mut thread = create_test_thread();
        let result = stream_read_byte_pre(&ctx, &mut thread);

        match result {
            PreHookResult::Bypass(Some(EmValue::I32(-1))) => {}
            _ => panic!("Expected Bypass with I32(-1) for EOF"),
        }
    }

    #[test]
    fn test_stream_read_byte_with_data() {
        let mut thread = create_test_thread();

        // Create a stream with test data
        let data = vec![1, 2, 3, 4, 5];
        let stream_ref = thread.heap_mut().alloc_stream(data).unwrap();

        let this = EmValue::ObjectRef(stream_ref);
        let ctx = HookContext::new(
            Token::new(0x0A000001),
            "System.IO",
            "Stream",
            "ReadByte",
            PointerSize::Bit64,
        )
        .with_this(Some(&this));

        // Read first byte
        let result = stream_read_byte_pre(&ctx, &mut thread);
        assert!(matches!(
            result,
            PreHookResult::Bypass(Some(EmValue::I32(1)))
        ));

        // Read second byte
        let result = stream_read_byte_pre(&ctx, &mut thread);
        assert!(matches!(
            result,
            PreHookResult::Bypass(Some(EmValue::I32(2)))
        ));

        // Read remaining bytes
        for expected in [3, 4, 5] {
            let result = stream_read_byte_pre(&ctx, &mut thread);
            assert!(
                matches!(result, PreHookResult::Bypass(Some(EmValue::I32(v))) if v == expected)
            );
        }

        // After all bytes, should return EOF
        let result = stream_read_byte_pre(&ctx, &mut thread);
        assert!(matches!(
            result,
            PreHookResult::Bypass(Some(EmValue::I32(-1)))
        ));
    }

    #[test]
    fn test_stream_get_length_hook() {
        let mut thread = create_test_thread();

        let data = vec![1, 2, 3, 4, 5];
        let stream_ref = thread.heap_mut().alloc_stream(data).unwrap();

        let this = EmValue::ObjectRef(stream_ref);
        let ctx = HookContext::new(
            Token::new(0x0A000001),
            "System.IO",
            "Stream",
            "get_Length",
            PointerSize::Bit64,
        )
        .with_this(Some(&this));

        let result = stream_get_length_pre(&ctx, &mut thread);
        assert!(matches!(
            result,
            PreHookResult::Bypass(Some(EmValue::I64(5)))
        ));
    }

    #[test]
    fn test_stream_get_position_hook() {
        let mut thread = create_test_thread();

        let data = vec![1, 2, 3, 4, 5];
        let stream_ref = thread.heap_mut().alloc_stream(data).unwrap();

        let this = EmValue::ObjectRef(stream_ref);
        let get_pos_ctx = HookContext::new(
            Token::new(0x0A000001),
            "System.IO",
            "Stream",
            "get_Position",
            PointerSize::Bit64,
        )
        .with_this(Some(&this));
        let read_byte_ctx = HookContext::new(
            Token::new(0x0A000002),
            "System.IO",
            "Stream",
            "ReadByte",
            PointerSize::Bit64,
        )
        .with_this(Some(&this));

        // Initial position is 0
        let result = stream_get_position_pre(&get_pos_ctx, &mut thread);
        assert!(matches!(
            result,
            PreHookResult::Bypass(Some(EmValue::I64(0)))
        ));

        // Read a byte, position should advance
        stream_read_byte_pre(&read_byte_ctx, &mut thread);

        let result = stream_get_position_pre(&get_pos_ctx, &mut thread);
        assert!(matches!(
            result,
            PreHookResult::Bypass(Some(EmValue::I64(1)))
        ));
    }

    #[test]
    fn test_stream_set_position_hook() {
        let mut thread = create_test_thread();

        let data = vec![1, 2, 3, 4, 5];
        let stream_ref = thread.heap_mut().alloc_stream(data).unwrap();

        let this = EmValue::ObjectRef(stream_ref);
        let args = [EmValue::I64(3)];
        let set_pos_ctx = HookContext::new(
            Token::new(0x0A000001),
            "System.IO",
            "Stream",
            "set_Position",
            PointerSize::Bit64,
        )
        .with_this(Some(&this))
        .with_args(&args);

        // Set position to 3
        stream_set_position_pre(&set_pos_ctx, &mut thread);

        // Verify position
        let get_pos_ctx = HookContext::new(
            Token::new(0x0A000002),
            "System.IO",
            "Stream",
            "get_Position",
            PointerSize::Bit64,
        )
        .with_this(Some(&this));
        let result = stream_get_position_pre(&get_pos_ctx, &mut thread);
        assert!(matches!(
            result,
            PreHookResult::Bypass(Some(EmValue::I64(3)))
        ));

        // Read byte at position 3 (value should be 4)
        let read_byte_ctx = HookContext::new(
            Token::new(0x0A000003),
            "System.IO",
            "Stream",
            "ReadByte",
            PointerSize::Bit64,
        )
        .with_this(Some(&this));
        let result = stream_read_byte_pre(&read_byte_ctx, &mut thread);
        assert!(matches!(
            result,
            PreHookResult::Bypass(Some(EmValue::I32(4)))
        ));
    }

    #[test]
    fn test_memory_stream_to_array_hook() {
        let mut thread = create_test_thread();

        let data = vec![10, 20, 30];
        let stream_ref = thread.heap_mut().alloc_stream(data.clone()).unwrap();

        let this = EmValue::ObjectRef(stream_ref);
        let ctx = HookContext::new(
            Token::new(0x0A000001),
            "System.IO",
            "MemoryStream",
            "ToArray",
            PointerSize::Bit64,
        )
        .with_this(Some(&this));

        let result = memory_stream_to_array_pre(&ctx, &mut thread);

        // Verify we get an array back
        let array_ref = match result {
            PreHookResult::Bypass(Some(EmValue::ObjectRef(r))) => r,
            _ => panic!("Expected Bypass with ObjectRef"),
        };

        // Verify array contents
        let retrieved = thread.heap().get_byte_array(array_ref).unwrap();
        assert_eq!(retrieved.as_slice(), &[10, 20, 30]);
    }

    #[test]
    fn test_memory_stream_ctor_hook() {
        let mut thread = create_test_thread();

        // Create source byte array
        let data = vec![1, 2, 3, 4, 5];
        let array_ref = thread.heap_mut().alloc_byte_array(&data).unwrap();

        // Call constructor (factory pattern)
        let args = [EmValue::ObjectRef(array_ref)];
        let ctx = HookContext::new(
            Token::new(0x0A000001),
            "System.IO",
            "MemoryStream",
            ".ctor",
            PointerSize::Bit64,
        )
        .with_args(&args);

        let result = memory_stream_ctor_pre(&ctx, &mut thread);

        let stream_ref = match result {
            PreHookResult::Bypass(Some(EmValue::ObjectRef(r))) => r,
            _ => panic!("Expected Bypass with ObjectRef"),
        };

        // Verify stream has correct length
        let this = EmValue::ObjectRef(stream_ref);
        let length_ctx = HookContext::new(
            Token::new(0x0A000002),
            "System.IO",
            "MemoryStream",
            "get_Length",
            PointerSize::Bit64,
        )
        .with_this(Some(&this));

        let result = stream_get_length_pre(&length_ctx, &mut thread);
        assert!(matches!(
            result,
            PreHookResult::Bypass(Some(EmValue::I64(5)))
        ));

        // Verify we can read data
        let read_ctx = HookContext::new(
            Token::new(0x0A000003),
            "System.IO",
            "MemoryStream",
            "ReadByte",
            PointerSize::Bit64,
        )
        .with_this(Some(&this));
        let result = stream_read_byte_pre(&read_ctx, &mut thread);
        assert!(matches!(
            result,
            PreHookResult::Bypass(Some(EmValue::I32(1)))
        ));
    }

    #[test]
    fn test_stream_seek_hook() {
        let mut thread = create_test_thread();

        let data = vec![10, 20, 30, 40, 50];
        let stream_ref = thread.heap_mut().alloc_stream(data).unwrap();

        let this = EmValue::ObjectRef(stream_ref);

        // Seek to position 2 from beginning (origin = 0)
        let args = [EmValue::I64(2), EmValue::I32(0)];
        let seek_ctx = HookContext::new(
            Token::new(0x0A000001),
            "System.IO",
            "MemoryStream",
            "Seek",
            PointerSize::Bit64,
        )
        .with_this(Some(&this))
        .with_args(&args);

        let result = stream_seek_pre(&seek_ctx, &mut thread);
        assert!(matches!(
            result,
            PreHookResult::Bypass(Some(EmValue::I64(2)))
        ));

        // Read byte at position 2 (value should be 30)
        let read_ctx = HookContext::new(
            Token::new(0x0A000002),
            "System.IO",
            "MemoryStream",
            "ReadByte",
            PointerSize::Bit64,
        )
        .with_this(Some(&this));
        let result = stream_read_byte_pre(&read_ctx, &mut thread);
        assert!(matches!(
            result,
            PreHookResult::Bypass(Some(EmValue::I32(30)))
        ));

        // Seek to end (origin = 2) with offset -1
        let args = [EmValue::I64(-1), EmValue::I32(2)];
        let seek_ctx = HookContext::new(
            Token::new(0x0A000003),
            "System.IO",
            "MemoryStream",
            "Seek",
            PointerSize::Bit64,
        )
        .with_this(Some(&this))
        .with_args(&args);

        let result = stream_seek_pre(&seek_ctx, &mut thread);
        assert!(matches!(
            result,
            PreHookResult::Bypass(Some(EmValue::I64(4)))
        ));

        // Read last byte (value should be 50)
        let result = stream_read_byte_pre(&read_ctx, &mut thread);
        assert!(matches!(
            result,
            PreHookResult::Bypass(Some(EmValue::I32(50)))
        ));
    }

    /// Helper to create a BinaryReader backed by a stream with the given data.
    fn create_binary_reader(thread: &mut EmulationThread, data: Vec<u8>) -> HeapRef {
        // Create the stream
        let stream_ref = thread.heap_mut().alloc_stream(data).unwrap();

        // Create an empty object for the BinaryReader
        let reader_token = Token::new(0x0200_0001); // Dummy type token
        let reader_ref = thread.heap_mut().alloc_object(reader_token).unwrap();

        // Call constructor to store the stream reference
        let this = EmValue::ObjectRef(reader_ref);
        let args = [EmValue::ObjectRef(stream_ref)];
        let ctx = HookContext::new(
            Token::new(0x0A000001),
            "System.IO",
            "BinaryReader",
            ".ctor",
            PointerSize::Bit64,
        )
        .with_this(Some(&this))
        .with_args(&args);

        binary_reader_ctor_pre(&ctx, thread);

        reader_ref
    }

    #[test]
    fn test_binary_reader_read_byte_from_stream() {
        let mut thread = create_test_thread();
        let reader_ref = create_binary_reader(&mut thread, vec![0x42, 0x55, 0x88]);

        let this = EmValue::ObjectRef(reader_ref);
        let ctx = HookContext::new(
            Token::new(0x0A000001),
            "System.IO",
            "BinaryReader",
            "ReadByte",
            PointerSize::Bit64,
        )
        .with_this(Some(&this));

        // Read first byte
        let result = binary_reader_read_byte_pre(&ctx, &mut thread);
        assert!(matches!(
            result,
            PreHookResult::Bypass(Some(EmValue::I32(0x42)))
        ));

        // Read second byte
        let result = binary_reader_read_byte_pre(&ctx, &mut thread);
        assert!(matches!(
            result,
            PreHookResult::Bypass(Some(EmValue::I32(0x55)))
        ));

        // Read third byte
        let result = binary_reader_read_byte_pre(&ctx, &mut thread);
        assert!(matches!(
            result,
            PreHookResult::Bypass(Some(EmValue::I32(0x88)))
        ));
    }

    #[test]
    fn test_binary_reader_read_bytes_from_stream() {
        let mut thread = create_test_thread();
        let reader_ref = create_binary_reader(&mut thread, vec![1, 2, 3, 4, 5, 6, 7, 8]);

        let this = EmValue::ObjectRef(reader_ref);
        let args = [EmValue::I32(5)];
        let ctx = HookContext::new(
            Token::new(0x0A000001),
            "System.IO",
            "BinaryReader",
            "ReadBytes",
            PointerSize::Bit64,
        )
        .with_this(Some(&this))
        .with_args(&args);

        let result = binary_reader_read_bytes_pre(&ctx, &mut thread);

        let array_ref = match result {
            PreHookResult::Bypass(Some(EmValue::ObjectRef(r))) => r,
            _ => panic!("Expected Bypass with ObjectRef"),
        };

        let bytes = thread.heap().get_byte_array(array_ref).unwrap();
        assert_eq!(bytes.as_slice(), &[1, 2, 3, 4, 5]);
    }

    #[test]
    fn test_binary_reader_read_int16() {
        let mut thread = create_test_thread();
        // Little-endian: 0x1234 = [0x34, 0x12]
        let reader_ref = create_binary_reader(&mut thread, vec![0x34, 0x12]);

        let this = EmValue::ObjectRef(reader_ref);
        let ctx = HookContext::new(
            Token::new(0x0A000001),
            "System.IO",
            "BinaryReader",
            "ReadInt16",
            PointerSize::Bit64,
        )
        .with_this(Some(&this));

        let result = binary_reader_read_int16_pre(&ctx, &mut thread);
        assert!(matches!(
            result,
            PreHookResult::Bypass(Some(EmValue::I32(0x1234)))
        ));
    }

    #[test]
    fn test_binary_reader_read_int32() {
        let mut thread = create_test_thread();
        // Little-endian: 0x12345678 = [0x78, 0x56, 0x34, 0x12]
        let reader_ref = create_binary_reader(&mut thread, vec![0x78, 0x56, 0x34, 0x12]);

        let this = EmValue::ObjectRef(reader_ref);
        let ctx = HookContext::new(
            Token::new(0x0A000001),
            "System.IO",
            "BinaryReader",
            "ReadInt32",
            PointerSize::Bit64,
        )
        .with_this(Some(&this));

        let result = binary_reader_read_int32_pre(&ctx, &mut thread);
        assert!(matches!(
            result,
            PreHookResult::Bypass(Some(EmValue::I32(0x12345678)))
        ));
    }

    #[test]
    fn test_binary_reader_read_int64() {
        let mut thread = create_test_thread();
        // Little-endian: 0x0102030405060708
        let reader_ref = create_binary_reader(
            &mut thread,
            vec![0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01],
        );

        let this = EmValue::ObjectRef(reader_ref);
        let ctx = HookContext::new(
            Token::new(0x0A000001),
            "System.IO",
            "BinaryReader",
            "ReadInt64",
            PointerSize::Bit64,
        )
        .with_this(Some(&this));

        let result = binary_reader_read_int64_pre(&ctx, &mut thread);
        assert!(matches!(
            result,
            PreHookResult::Bypass(Some(EmValue::I64(0x0102030405060708)))
        ));
    }

    #[test]
    fn test_binary_reader_read_string() {
        let mut thread = create_test_thread();
        // Length-prefixed string: length=5, "Hello"
        let reader_ref = create_binary_reader(&mut thread, vec![5, b'H', b'e', b'l', b'l', b'o']);

        let this = EmValue::ObjectRef(reader_ref);
        let ctx = HookContext::new(
            Token::new(0x0A000001),
            "System.IO",
            "BinaryReader",
            "ReadString",
            PointerSize::Bit64,
        )
        .with_this(Some(&this));

        let result = binary_reader_read_string_pre(&ctx, &mut thread);

        let str_ref = match result {
            PreHookResult::Bypass(Some(EmValue::ObjectRef(r))) => r,
            _ => panic!("Expected Bypass with ObjectRef"),
        };

        let s = thread.heap().get_string(str_ref).unwrap();
        assert_eq!(s.as_ref(), "Hello");
    }

    #[test]
    fn test_binary_reader_mixed_reads() {
        let mut thread = create_test_thread();
        // Create data with: byte, int32, string
        // byte: 0xFF
        // int32: 0x12345678 (little-endian: [0x78, 0x56, 0x34, 0x12])
        // string: length=4, "Test"
        let reader_ref = create_binary_reader(
            &mut thread,
            vec![
                0xFF, // byte
                0x78, 0x56, 0x34, 0x12, // int32
                4, b'T', b'e', b's', b't', // string
            ],
        );

        let this = EmValue::ObjectRef(reader_ref);

        // Read byte
        let ctx = HookContext::new(
            Token::new(0x0A000001),
            "System.IO",
            "BinaryReader",
            "ReadByte",
            PointerSize::Bit64,
        )
        .with_this(Some(&this));
        let result = binary_reader_read_byte_pre(&ctx, &mut thread);
        assert!(matches!(
            result,
            PreHookResult::Bypass(Some(EmValue::I32(0xFF)))
        ));

        // Read int32
        let ctx = HookContext::new(
            Token::new(0x0A000002),
            "System.IO",
            "BinaryReader",
            "ReadInt32",
            PointerSize::Bit64,
        )
        .with_this(Some(&this));
        let result = binary_reader_read_int32_pre(&ctx, &mut thread);
        assert!(matches!(
            result,
            PreHookResult::Bypass(Some(EmValue::I32(0x12345678)))
        ));

        // Read string
        let ctx = HookContext::new(
            Token::new(0x0A000003),
            "System.IO",
            "BinaryReader",
            "ReadString",
            PointerSize::Bit64,
        )
        .with_this(Some(&this));
        let result = binary_reader_read_string_pre(&ctx, &mut thread);

        let str_ref = match result {
            PreHookResult::Bypass(Some(EmValue::ObjectRef(r))) => r,
            _ => panic!("Expected Bypass with ObjectRef"),
        };
        let s = thread.heap().get_string(str_ref).unwrap();
        assert_eq!(s.as_ref(), "Test");
    }
}