dotscope 0.7.0

A high-performance, cross-platform framework for analyzing and reverse engineering .NET PE executables
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
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
//! Unified address space management for CIL emulation.
//!
//! This module provides the [`AddressSpace`] type, which offers a unified view of all memory
//! in an emulated .NET process. It combines multiple memory subsystems:
//!
//! - **Managed heap** ([`SharedHeap`]) - Objects, arrays, and strings allocated via `newobj`, `newarr`, etc.
//! - **Memory regions** ([`MemoryRegion`](super::MemoryRegion)) - PE images, mapped data, and unmanaged allocations
//! - **Static fields** ([`StaticFieldStorage`](super::StaticFieldStorage)) - Static field values shared across threads
//!
//! # Shared Heap Semantics
//!
//! The managed heap is wrapped in [`SharedHeap`], which uses `Arc<ManagedHeap>` internally.
//! This enables cheap cloning and sharing across threads while maintaining reference semantics
//! for heap objects.
//!
//! # Example
//!
//! ```rust
//! use dotscope::emulation::AddressSpace;
//!
//! // Create a new address space with default settings (64MB heap, 4GB address space)
//! let space = AddressSpace::new();
//!
//! // Allocate a string on the managed heap
//! let string_ref = space.alloc_string("Hello, World!").unwrap();
//!
//! // Map raw data at a specific address
//! space.map_data(0x1000, &[0xDE, 0xAD, 0xBE, 0xEF], "test_data").unwrap();
//!
//! // Read back the data
//! let data = space.read(0x1000, 4).unwrap();
//! assert_eq!(data, vec![0xDE, 0xAD, 0xBE, 0xEF]);
//! ```

use std::sync::{
    atomic::{AtomicU64, Ordering},
    Arc, RwLock,
};

use imbl::HashMap as ImHashMap;

use crate::{
    emulation::{
        memory::{
            region::{MemoryProtection, MemoryRegion, SectionInfo},
            statics::StaticFieldStorage,
        },
        EmValue, EmulationError, HeapRef, ManagedHeap,
    },
    metadata::token::Token,
    Error, Result,
};

/// Shared managed heap wrapper for thread-safe heap access.
///
/// `SharedHeap` wraps a [`ManagedHeap`] in an `Arc`, enabling cheap cloning and
/// sharing across threads and method calls. Multiple [`AddressSpace`] instances
/// can share the same heap, allowing objects allocated in one context to be
/// visible in another.
///
/// # Thread Safety
///
/// The underlying [`ManagedHeap`] uses interior mutability via `RwLock`, so
/// `SharedHeap` can be safely shared across threads with just `Clone`.
///
/// # Example
///
/// ```rust
/// use dotscope::emulation::SharedHeap;
///
/// let heap = SharedHeap::new(64 * 1024 * 1024); // 64MB
/// let heap2 = heap.clone(); // Cheap clone, shares same underlying heap
///
/// // Allocate in one clone
/// let str_ref = heap.alloc_string("shared").unwrap();
///
/// // Visible in the other
/// let s = heap2.get_string(str_ref).unwrap();
/// assert_eq!(&*s, "shared");
/// ```
#[derive(Clone, Debug)]
pub struct SharedHeap {
    inner: Arc<ManagedHeap>,
}

impl SharedHeap {
    /// Creates a new shared heap with the given size limit.
    ///
    /// # Arguments
    ///
    /// * `max_size` - Maximum heap size in bytes
    ///
    /// # Example
    ///
    /// ```rust
    /// use dotscope::emulation::SharedHeap;
    ///
    /// let heap = SharedHeap::new(1024 * 1024); // 1MB heap
    /// ```
    #[must_use]
    pub fn new(max_size: usize) -> Self {
        Self {
            inner: Arc::new(ManagedHeap::new(max_size)),
        }
    }

    /// Creates a shared heap from an existing [`ManagedHeap`].
    ///
    /// This wraps the given heap in an `Arc` for shared access.
    ///
    /// # Arguments
    ///
    /// * `heap` - The managed heap to wrap
    pub fn from_heap(heap: ManagedHeap) -> Self {
        Self {
            inner: Arc::new(heap),
        }
    }

    /// Returns a reference to the underlying [`ManagedHeap`].
    ///
    /// This provides direct access to the heap for operations not exposed
    /// through the `Deref` implementation.
    #[must_use]
    pub fn heap(&self) -> &ManagedHeap {
        &self.inner
    }

    /// Returns the number of strong references to this heap.
    ///
    /// Useful for debugging and understanding sharing patterns.
    #[must_use]
    pub fn ref_count(&self) -> usize {
        Arc::strong_count(&self.inner)
    }

    /// Returns `true` if this is the only reference to the heap.
    ///
    /// When unique, the heap can be safely modified without affecting
    /// other users.
    #[must_use]
    pub fn is_unique(&self) -> bool {
        Arc::strong_count(&self.inner) == 1
    }

    /// Forks this heap, creating an independent copy with CoW semantics.
    ///
    /// The forked heap shares its data structure with the original via
    /// structural sharing (using `imbl`). Both heaps can be modified
    /// independently - only the modified entries are copied.
    ///
    /// # Performance
    ///
    /// This is an O(1) operation due to `imbl`'s structural sharing.
    ///
    /// # Note
    ///
    /// Unlike `clone()` which shares the same heap via `Arc`, `fork()`
    /// creates a truly independent heap that starts with the same data
    /// but diverges on modification.
    pub fn fork(&self) -> Result<Self> {
        Ok(Self {
            inner: Arc::new(self.inner.fork()?),
        })
    }
}

impl Default for SharedHeap {
    fn default() -> Self {
        Self::new(64 * 1024 * 1024) // 64 MB default
    }
}

impl std::ops::Deref for SharedHeap {
    type Target = ManagedHeap;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

/// Metadata for a pinned managed array whose native address aliases
/// the managed heap data. Reads and writes through the native address
/// are transparently delegated to the managed heap's `Vec<EmValue>`.
#[derive(Clone, Debug)]
struct PinnedArrayEntry {
    /// The managed array on the heap.
    array_ref: HeapRef,
    /// Base native address for the pinned region.
    base_addr: u64,
    /// Total byte length of the pinned region.
    byte_length: usize,
    /// Size of each element in bytes (1 for U1, 4 for I4, 8 for I8, etc.).
    element_size: usize,
}

/// Unified address space for an emulated .NET process.
///
/// `AddressSpace` provides a complete view of all memory accessible to an emulated
/// .NET process, integrating:
///
/// - **Managed heap** - Objects, arrays, and strings (via [`SharedHeap`])
/// - **Memory regions** - PE images, mapped data, and unmanaged allocations
/// - **Static fields** - Type-level static field storage
/// - **Pinned arrays** - Native pointer aliases for managed arrays
///
/// # Memory Layout
///
/// The address space has a configurable size (default 4GB). Automatic allocations
/// start at address `0x1000_0000` (256MB) and grow upward. PE images should be
/// mapped at their preferred base addresses using [`map_pe_image`](Self::map_pe_image).
///
/// # Pinned Arrays
///
/// When CIL code pins a managed array (via `ldelema` + `conv.u`), the resulting
/// native pointer is registered with the address space. Subsequent reads and writes
/// through native pointers (`ldind.*`/`stind.*`) that target the pinned address
/// range are transparently delegated to the managed heap, ensuring a single source
/// of truth with no synchronization overhead.
///
/// # Thread Safety
///
/// The address space uses interior mutability for thread-safe access:
/// - Heap operations use `RwLock` internally
/// - Region operations are protected by a `RwLock`
/// - Static fields use `RwLock` for concurrent access
///
/// # Cloning Semantics
///
/// When cloned, the heap is shared (via `Arc`), but regions are copied.
/// This means heap objects are visible across clones, but region mappings
/// are independent.
///
/// # Example
///
/// ```rust
/// use dotscope::emulation::{AddressSpace, EmValue};
/// use dotscope::metadata::token::Token;
///
/// let space = AddressSpace::new();
///
/// // Allocate managed objects
/// let str_ref = space.alloc_string("Hello").unwrap();
///
/// // Map raw memory
/// space.map_data(0x1000, &[1, 2, 3, 4], "data").unwrap();
///
/// // Access static fields
/// let field_token = Token::new(0x04000001);
/// space.set_static(field_token, EmValue::I32(42)).unwrap();
/// ```
#[derive(Debug)]
pub struct AddressSpace {
    /// Managed .NET heap (shared across threads).
    heap: SharedHeap,

    /// Memory regions (PE images, mapped data, etc.).
    regions: RwLock<Vec<MemoryRegion>>,

    /// Static field storage.
    statics: StaticFieldStorage,

    /// Next available address for automatic mapping.
    next_address: AtomicU64,

    /// Address space size limit.
    size: u64,

    /// Protection overrides for VirtualProtect emulation.
    ///
    /// Maps page-aligned addresses to their current protection flags.
    /// This allows VirtualProtect to change protection dynamically,
    /// overriding the default protection derived from PE sections.
    ///
    /// Uses `imbl::HashMap` for O(1) fork via structural sharing.
    protection_overrides: RwLock<ImHashMap<u64, MemoryProtection>>,

    /// Monitor lock state: maps heap object ID → re-entrant lock count.
    ///
    /// Tracks `System.Threading.Monitor.Enter`/`Exit` calls per object.
    /// In single-threaded emulation there is no contention, but we still
    /// track counts so that `Exit` can detect mismatched release attempts
    /// and `TryEnter` can verify the lock is actually held.
    ///
    /// Uses `imbl::HashMap` for O(1) fork via structural sharing.
    monitor_locks: RwLock<ImHashMap<u64, u32>>,

    /// Pinned array mappings: native base address → pinned array metadata.
    ///
    /// When a managed array is pinned (via `ldelema` + `conv.u`), its native
    /// address is registered here. Reads and writes through the native address
    /// are transparently delegated to the managed heap's `Vec<EmValue>`,
    /// ensuring a single source of truth with no data duplication.
    ///
    /// Uses `imbl::HashMap` for O(1) fork via structural sharing.
    pinned_arrays: RwLock<ImHashMap<u64, PinnedArrayEntry>>,
}

impl AddressSpace {
    /// Page size for protection tracking (4KB), derived from [`page::PAGE_SIZE`].
    const PAGE_SIZE: u64 = super::page::PAGE_SIZE as u64;

    /// Creates a new address space with default settings.
    ///
    /// Default configuration:
    /// - 64 MB managed heap
    /// - 4 GB address space
    /// - Automatic allocations start at 256 MB
    #[must_use]
    pub fn new() -> Self {
        Self::with_config(64 * 1024 * 1024, 0x1_0000_0000) // 64MB heap, 4GB address space
    }

    /// Creates a new address space with custom configuration.
    ///
    /// # Arguments
    ///
    /// * `heap_size` - Maximum size of the managed heap in bytes
    /// * `address_space_size` - Total address space size in bytes
    #[must_use]
    pub fn with_config(heap_size: usize, address_space_size: u64) -> Self {
        Self {
            heap: SharedHeap::new(heap_size),
            regions: RwLock::new(Vec::new()),
            statics: StaticFieldStorage::new(),
            next_address: AtomicU64::new(0x1000_0000), // Start at 256MB
            size: address_space_size,
            protection_overrides: RwLock::new(ImHashMap::new()),
            monitor_locks: RwLock::new(ImHashMap::new()),
            pinned_arrays: RwLock::new(ImHashMap::new()),
        }
    }

    /// Creates an address space with an existing shared heap.
    ///
    /// This allows multiple address spaces to share the same managed heap,
    /// useful for emulating multi-threaded scenarios where all threads
    /// share the same GC heap.
    ///
    /// # Arguments
    ///
    /// * `heap` - The shared heap to use
    #[must_use]
    pub fn with_heap(heap: SharedHeap) -> Self {
        Self {
            heap,
            regions: RwLock::new(Vec::new()),
            statics: StaticFieldStorage::new(),
            next_address: AtomicU64::new(0x1000_0000),
            size: 0x1_0000_0000,
            protection_overrides: RwLock::new(ImHashMap::new()),
            monitor_locks: RwLock::new(ImHashMap::new()),
            pinned_arrays: RwLock::new(ImHashMap::new()),
        }
    }

    /// Returns a reference to the shared heap.
    #[must_use]
    pub fn heap(&self) -> &SharedHeap {
        &self.heap
    }

    /// Returns a reference to the underlying [`ManagedHeap`].
    #[must_use]
    pub fn managed_heap(&self) -> &ManagedHeap {
        self.heap.heap()
    }

    /// Returns a reference to the static field storage.
    #[must_use]
    pub fn statics(&self) -> &StaticFieldStorage {
        &self.statics
    }

    /// Acquires a monitor lock on the given heap object.
    ///
    /// Increments the re-entrant lock count for the object. In single-threaded
    /// emulation this always succeeds (no contention), but the count is tracked
    /// so that `monitor_exit` can detect mismatched releases.
    ///
    /// Returns the new lock count (1 for first acquisition).
    pub fn monitor_enter(&self, object_id: u64) -> u32 {
        let mut locks = self.monitor_locks.write().unwrap();
        let count = locks.get(&object_id).copied().unwrap_or(0) + 1;
        *locks = locks.update(object_id, count);
        count
    }

    /// Releases a monitor lock on the given heap object.
    ///
    /// Decrements the re-entrant lock count. Returns `true` if the lock was
    /// held and successfully released, `false` if Exit was called without a
    /// matching Enter (would throw `SynchronizationLockException` in .NET).
    pub fn monitor_exit(&self, object_id: u64) -> bool {
        let mut locks = self.monitor_locks.write().unwrap();
        match locks.get(&object_id).copied() {
            Some(count) if count > 1 => {
                *locks = locks.update(object_id, count - 1);
                true
            }
            Some(1) => {
                *locks = locks.without(&object_id);
                true
            }
            _ => false, // Not locked — mismatched Exit
        }
    }

    /// Checks whether a monitor lock is currently held on the given heap object.
    #[must_use]
    pub fn monitor_is_locked(&self, object_id: u64) -> bool {
        self.monitor_locks
            .read()
            .map(|l| l.get(&object_id).copied().unwrap_or(0) > 0)
            .unwrap_or(false)
    }

    /// Maps a region into the address space at a specific address.
    ///
    /// # Arguments
    ///
    /// * `address` - The base address to map the region at
    /// * `region` - The memory region to map
    ///
    /// # Errors
    ///
    /// Returns an error if the region overlaps with an existing mapping or
    /// if the region lock is poisoned.
    pub fn map_at(&self, address: u64, region: MemoryRegion) -> Result<()> {
        let mut regions = self.regions.write().map_err(|_| {
            Error::from(EmulationError::InternalError {
                description: "region lock poisoned".to_string(),
            })
        })?;

        // Check for overlaps
        for existing in regions.iter() {
            if Self::regions_overlap(existing, &region) {
                return Err(EmulationError::InvalidAddress {
                    address,
                    reason: "region overlaps with existing mapping".to_string(),
                }
                .into());
            }
        }

        regions.push(region);
        Ok(())
    }

    /// Maps a region at an automatically chosen address.
    ///
    /// The address is selected from the available address space and aligned
    /// to a page boundary (4KB). The region's base address is updated to
    /// reflect the chosen location.
    ///
    /// # Arguments
    ///
    /// * `region` - The memory region to map (base address will be updated)
    ///
    /// # Returns
    ///
    /// The base address where the region was mapped.
    ///
    /// # Errors
    ///
    /// Returns an error if the mapping fails.
    pub fn map(&self, region: MemoryRegion) -> Result<u64> {
        let size = region.size();
        let aligned_size = (size + 0xFFF) & !0xFFF; // Page align

        // Find next available address
        let base = self
            .next_address
            .fetch_add(aligned_size as u64, Ordering::SeqCst);

        // PE images should use map_at with explicit base
        if region.is_pe_image() {
            return Err(EmulationError::InternalError {
                description: "PE images must use map_at with explicit base address".to_string(),
            }
            .into());
        }

        // Update region base
        let region = region.with_base(base);

        self.map_at(base, region)?;
        Ok(base)
    }

    /// Unmaps a region by its base address.
    ///
    /// # Arguments
    ///
    /// * `base` - The base address of the region to unmap
    ///
    /// # Errors
    ///
    /// Returns an error if no region exists at the given address.
    pub fn unmap(&self, base: u64) -> Result<()> {
        let mut regions = self.regions.write().map_err(|_| {
            Error::from(EmulationError::InternalError {
                description: "region lock poisoned".to_string(),
            })
        })?;

        if let Some(pos) = regions.iter().position(|r| r.base() == base) {
            regions.remove(pos);
            Ok(())
        } else {
            Err(EmulationError::InvalidAddress {
                address: base,
                reason: "no region at this address".to_string(),
            }
            .into())
        }
    }

    /// Reads bytes from any mapped region.
    ///
    /// # Arguments
    ///
    /// * `address` - The address to read from
    /// * `len` - The number of bytes to read
    ///
    /// # Errors
    ///
    /// Returns an error if the address is not mapped or the read fails.
    pub fn read(&self, address: u64, len: usize) -> Result<Vec<u8>> {
        // Check pinned arrays first (transparent shared backing)
        if let Some(result) = self.read_pinned(address, len) {
            return result;
        }

        let regions = self.regions.read().map_err(|_| {
            Error::from(EmulationError::InternalError {
                description: "region lock poisoned".to_string(),
            })
        })?;

        for region in regions.iter() {
            if region.contains_range(address, len) {
                return region.read(address, len).ok_or_else(|| {
                    EmulationError::InvalidAddress {
                        address,
                        reason: "read failed".to_string(),
                    }
                    .into()
                });
            }
        }

        Err(EmulationError::InvalidAddress {
            address,
            reason: "address not mapped".to_string(),
        }
        .into())
    }

    /// Writes bytes to any mapped region.
    ///
    /// # Arguments
    ///
    /// * `address` - The address to write to
    /// * `data` - The bytes to write
    ///
    /// # Errors
    ///
    /// Returns an error if the address is not mapped, the region is read-only,
    /// or the write otherwise fails.
    pub fn write(&self, address: u64, data: &[u8]) -> Result<()> {
        // Check pinned arrays first (transparent shared backing)
        if let Some(result) = self.write_pinned(address, data) {
            return result;
        }

        let regions = self.regions.read().map_err(|_| {
            Error::from(EmulationError::InternalError {
                description: "region lock poisoned".to_string(),
            })
        })?;

        for region in regions.iter() {
            if region.contains_range(address, data.len()) {
                if region.write(address, data) {
                    return Ok(());
                }
                return Err(EmulationError::InvalidAddress {
                    address,
                    reason: "write failed (possibly read-only)".to_string(),
                }
                .into());
            }
        }

        Err(EmulationError::InvalidAddress {
            address,
            reason: "address not mapped".to_string(),
        }
        .into())
    }

    /// Returns `true` if the address is within a mapped region.
    ///
    /// # Arguments
    ///
    /// * `address` - The address to check
    #[must_use]
    pub fn is_valid(&self, address: u64) -> bool {
        // Check pinned arrays first
        if let Ok(pins) = self.pinned_arrays.read() {
            for entry in pins.values() {
                let end = entry.base_addr + entry.byte_length as u64;
                if address >= entry.base_addr && address < end {
                    return true;
                }
            }
        }

        let Ok(regions) = self.regions.read() else {
            return false;
        };
        regions.iter().any(|r| r.contains(address))
    }

    /// Returns the region containing the given address, if any.
    ///
    /// # Arguments
    ///
    /// * `address` - The address to look up
    #[must_use]
    pub fn get_region(&self, address: u64) -> Option<MemoryRegion> {
        let regions = self.regions.read().ok()?;
        regions.iter().find(|r| r.contains(address)).cloned()
    }

    /// Returns the memory protection flags for an address.
    ///
    /// This method first checks for any runtime protection overrides (set by
    /// `VirtualProtect` emulation), then falls back to the region's default
    /// protection. For PE images, the default considers the section containing
    /// the address.
    ///
    /// # Arguments
    ///
    /// * `address` - The address to check
    #[must_use]
    pub fn get_protection(&self, address: u64) -> Option<MemoryProtection> {
        // Check for override first (page-aligned)
        let page_addr = address & !(Self::PAGE_SIZE - 1);
        if let Ok(overrides) = self.protection_overrides.read() {
            if let Some(&prot) = overrides.get(&page_addr) {
                return Some(prot);
            }
        }

        // Fall back to region's inherent protection
        let regions = self.regions.read().ok()?;
        regions
            .iter()
            .find(|r| r.contains(address))
            .and_then(|r| r.protection_at(address).ok())
    }

    /// Sets the memory protection for a range of addresses.
    ///
    /// This emulates `VirtualProtect` by storing protection overrides at
    /// page granularity. The original protection for the first page is returned.
    ///
    /// # Arguments
    ///
    /// * `address` - The starting address (will be page-aligned)
    /// * `size` - The size of the region to protect
    /// * `new_protection` - The new protection flags
    ///
    /// # Returns
    ///
    /// The previous protection of the first affected page, or `None` if the
    /// address is not mapped.
    pub fn set_protection(
        &self,
        address: u64,
        size: usize,
        new_protection: MemoryProtection,
    ) -> Option<MemoryProtection> {
        // Calculate page-aligned range
        let start_page = address & !(Self::PAGE_SIZE - 1);

        // Anti-emulation countermeasure:
        //
        // Some obfuscators (notably ConfuserEx) mark their encrypted sections as RWX
        // in the PE headers, then check VirtualProtect's returned old protection:
        //
        //   uint w = 0x40;  // PAGE_EXECUTE_READWRITE
        //   VirtualProtect(addr, size, w, out w);
        //   if (w == 0x40) return;  // Skip decryption if already RWX
        //
        // A naive emulator that accurately maps PE section characteristics would
        // return 0x40, causing decryption to be skipped. Real Windows apparently
        // behaves differently (possibly due to copy-on-write, DEP, or CLR-specific
        // loading behavior), returning a different value on first access.
        //
        // We handle this by returning READ_EXECUTE (0x20) for the FIRST VirtualProtect
        // call on executable sections, regardless of PE characteristics. Subsequent
        // calls return the actual stored protection, preserving re-entry guards.
        let old_protection = if let Ok(overrides) = self.protection_overrides.read() {
            if overrides.contains_key(&start_page) {
                // Has override - use it
                drop(overrides);
                self.get_protection(address)?
            } else {
                // No override yet - this is the first call.
                // Return READ_EXECUTE for executable sections to simulate
                // fresh process state (before any VirtualProtect calls).
                drop(overrides);
                let region_prot = self.get_protection(address)?;
                if region_prot.contains(MemoryProtection::EXECUTE) {
                    MemoryProtection::READ_EXECUTE
                } else {
                    region_prot
                }
            }
        } else {
            self.get_protection(address)?
        };

        // Calculate end page
        let end_addr = address.saturating_add(size as u64);
        let end_page = (end_addr + Self::PAGE_SIZE - 1) & !(Self::PAGE_SIZE - 1);

        // Update protection for all affected pages
        if let Ok(mut overrides) = self.protection_overrides.write() {
            let mut page = start_page;
            while page < end_page {
                overrides.insert(page, new_protection);
                page += Self::PAGE_SIZE;
            }
        }

        Some(old_protection)
    }

    /// Gets a static field value.
    ///
    /// # Arguments
    ///
    /// * `field_token` - The metadata token of the static field
    ///
    /// # Errors
    ///
    /// Returns [`EmulationError::LockPoisoned`] if the static field storage lock is poisoned.
    pub fn get_static(&self, field_token: Token) -> Result<Option<EmValue>> {
        self.statics.get(field_token)
    }

    /// Sets a static field value.
    ///
    /// # Arguments
    ///
    /// * `field_token` - The metadata token of the static field
    /// * `value` - The value to store
    ///
    /// # Errors
    ///
    /// Returns [`EmulationError::LockPoisoned`] if the static field storage lock is poisoned.
    pub fn set_static(&self, field_token: Token, value: EmValue) -> Result<()> {
        self.statics.set(field_token, value)
    }

    /// Allocates unmanaged memory (for `Marshal.AllocHGlobal`, etc.).
    ///
    /// The memory is zeroed and mapped at an automatically chosen address.
    ///
    /// # Arguments
    ///
    /// * `size` - The size of the allocation in bytes
    ///
    /// # Returns
    ///
    /// The base address of the allocated region.
    ///
    /// # Errors
    ///
    /// Returns an error if the mapping fails.
    pub fn alloc_unmanaged(&self, size: usize) -> Result<u64> {
        let region = MemoryRegion::unmanaged_alloc(0, size);
        self.map(region)
    }

    /// Frees unmanaged memory previously allocated with [`alloc_unmanaged`](Self::alloc_unmanaged).
    ///
    /// # Arguments
    ///
    /// * `address` - The base address of the allocation to free
    ///
    /// # Errors
    ///
    /// Returns an error if the address does not correspond to an unmanaged allocation.
    pub fn free_unmanaged(&self, address: u64) -> Result<()> {
        // Verify it's an unmanaged allocation
        let regions = self.regions.read().map_err(|_| {
            Error::from(EmulationError::InternalError {
                description: "region lock poisoned".to_string(),
            })
        })?;

        let is_unmanaged = regions
            .iter()
            .any(|r| r.base() == address && r.is_unmanaged_alloc());

        drop(regions);

        if is_unmanaged {
            self.unmap(address)
        } else {
            Err(EmulationError::InvalidAddress {
                address,
                reason: "not an unmanaged allocation".to_string(),
            }
            .into())
        }
    }

    /// Reserves an address range without creating a backing memory region.
    ///
    /// Used for pinned arrays where the backing store is the managed heap.
    /// The returned address is guaranteed not to conflict with other allocations.
    pub fn reserve_address_range(&self, size: usize) -> u64 {
        let aligned_size = (size + 0xFFF) & !0xFFF; // Align to 4KB
        self.next_address
            .fetch_add(aligned_size as u64, Ordering::SeqCst)
    }

    /// Registers a pinned managed array so that native pointer access
    /// transparently delegates to the managed heap.
    ///
    /// After registration, `read()` and `write()` calls targeting the
    /// pinned address range will be handled by reading from or writing
    /// to the managed array's elements rather than a separate memory region.
    ///
    /// # Arguments
    ///
    /// * `base_addr` - Native base address of the pinned region
    /// * `array_ref` - The managed array on the heap
    /// * `element_size` - Size of each element in bytes
    /// * `element_count` - Number of elements in the array
    pub fn register_pinned_array(
        &self,
        base_addr: u64,
        array_ref: HeapRef,
        element_size: usize,
        element_count: usize,
    ) -> Result<()> {
        let entry = PinnedArrayEntry {
            array_ref,
            base_addr,
            byte_length: element_size * element_count,
            element_size,
        };
        let mut pins = self.pinned_arrays.write().map_err(|_| {
            Error::from(EmulationError::LockPoisoned {
                description: "pinned arrays",
            })
        })?;
        pins.insert(base_addr, entry);
        Ok(())
    }

    /// Attempts to read from a pinned array region.
    ///
    /// Returns `None` if the address is not within a pinned array range.
    /// Returns `Some(Ok(bytes))` if the read succeeded, `Some(Err(...))` on failure.
    fn read_pinned(&self, addr: u64, len: usize) -> Option<Result<Vec<u8>>> {
        if len == 0 {
            return None;
        }
        let pins = self.pinned_arrays.read().ok()?;
        if pins.is_empty() {
            return None;
        }

        for entry in pins.values() {
            let end = entry.base_addr + entry.byte_length as u64;
            if addr >= entry.base_addr && addr + len as u64 <= end {
                return Some(self.read_pinned_bytes(entry, addr, len));
            }
        }
        None
    }

    /// Reads bytes from a pinned array by delegating to the managed heap.
    fn read_pinned_bytes(
        &self,
        entry: &PinnedArrayEntry,
        addr: u64,
        len: usize,
    ) -> Result<Vec<u8>> {
        let byte_offset = (addr - entry.base_addr) as usize;
        let heap = self.managed_heap();
        let mut result = vec![0u8; len];

        if entry.element_size == 1 {
            // Byte array fast path: each element is one byte
            for (i, slot) in result.iter_mut().enumerate().take(len) {
                let elem_idx = byte_offset + i;
                match heap.get_array_element(entry.array_ref, elem_idx) {
                    Ok(EmValue::I32(v)) => {
                        #[allow(clippy::cast_sign_loss)]
                        {
                            *slot = (v & 0xFF) as u8;
                        }
                    }
                    Ok(_) | Err(_) => *slot = 0,
                }
            }
        } else {
            // Multi-byte element path: deserialize elements to bytes
            let start_elem = byte_offset / entry.element_size;
            let end_elem = (byte_offset + len).div_ceil(entry.element_size);
            let mut elem_buf = vec![0u8; entry.element_size];

            for elem_idx in start_elem..end_elem {
                Self::emvalue_to_bytes(
                    &heap
                        .get_array_element(entry.array_ref, elem_idx)
                        .unwrap_or(EmValue::I32(0)),
                    &mut elem_buf,
                );
                let elem_byte_start = elem_idx * entry.element_size;
                for (j, &b) in elem_buf.iter().enumerate() {
                    let abs_byte = elem_byte_start + j;
                    if abs_byte >= byte_offset && abs_byte < byte_offset + len {
                        result[abs_byte - byte_offset] = b;
                    }
                }
            }
        }
        Ok(result)
    }

    /// Attempts to write to a pinned array region.
    ///
    /// Returns `None` if the address is not within a pinned array range.
    /// Returns `Some(Ok(()))` if the write succeeded, `Some(Err(...))` on failure.
    fn write_pinned(&self, addr: u64, data: &[u8]) -> Option<Result<()>> {
        if data.is_empty() {
            return None;
        }
        let pins = self.pinned_arrays.read().ok()?;
        if pins.is_empty() {
            return None;
        }

        for entry in pins.values() {
            let end = entry.base_addr + entry.byte_length as u64;
            if addr >= entry.base_addr && addr + data.len() as u64 <= end {
                return Some(self.write_pinned_bytes(entry, addr, data));
            }
        }
        None
    }

    /// Writes bytes to a pinned array by delegating to the managed heap.
    fn write_pinned_bytes(&self, entry: &PinnedArrayEntry, addr: u64, data: &[u8]) -> Result<()> {
        let byte_offset = (addr - entry.base_addr) as usize;
        let heap = self.managed_heap();

        if entry.element_size == 1 {
            // Byte array fast path: each byte is one element
            for (i, &byte) in data.iter().enumerate() {
                let elem_idx = byte_offset + i;
                heap.set_array_element(entry.array_ref, elem_idx, EmValue::I32(i32::from(byte)))?;
            }
        } else {
            // Multi-byte element path: read-modify-write for partial elements
            let start_elem = byte_offset / entry.element_size;
            let end_elem = (byte_offset + data.len()).div_ceil(entry.element_size);

            for elem_idx in start_elem..end_elem {
                let elem_byte_start = elem_idx * entry.element_size;
                let mut elem_buf = vec![0u8; entry.element_size];

                // Read existing element value
                Self::emvalue_to_bytes(
                    &heap
                        .get_array_element(entry.array_ref, elem_idx)
                        .unwrap_or(EmValue::I32(0)),
                    &mut elem_buf,
                );

                // Overwrite the affected bytes
                for (j, byte) in elem_buf.iter_mut().enumerate() {
                    let abs_byte = elem_byte_start + j;
                    if abs_byte >= byte_offset && abs_byte < byte_offset + data.len() {
                        *byte = data[abs_byte - byte_offset];
                    }
                }

                // Write back
                let value = Self::bytes_to_emvalue(&elem_buf);
                heap.set_array_element(entry.array_ref, elem_idx, value)?;
            }
        }
        Ok(())
    }

    /// Serializes an `EmValue` to little-endian bytes.
    fn emvalue_to_bytes(value: &EmValue, buf: &mut [u8]) {
        match value {
            EmValue::I32(v) => {
                let bytes = v.to_le_bytes();
                let copy_len = buf.len().min(4);
                buf[..copy_len].copy_from_slice(&bytes[..copy_len]);
            }
            EmValue::I64(v) | EmValue::NativeInt(v) => {
                let bytes = v.to_le_bytes();
                let copy_len = buf.len().min(8);
                buf[..copy_len].copy_from_slice(&bytes[..copy_len]);
            }
            EmValue::F32(v) => {
                let bytes = v.to_le_bytes();
                let copy_len = buf.len().min(4);
                buf[..copy_len].copy_from_slice(&bytes[..copy_len]);
            }
            EmValue::F64(v) => {
                let bytes = v.to_le_bytes();
                let copy_len = buf.len().min(8);
                buf[..copy_len].copy_from_slice(&bytes[..copy_len]);
            }
            _ => buf.fill(0),
        }
    }

    /// Deserializes little-endian bytes to an `EmValue`.
    fn bytes_to_emvalue(bytes: &[u8]) -> EmValue {
        match bytes.len() {
            1 => EmValue::I32(i32::from(bytes[0])),
            2 => EmValue::I32(i32::from(i16::from_le_bytes([bytes[0], bytes[1]]))),
            4 => EmValue::I32(i32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])),
            8 => EmValue::I64(i64::from_le_bytes([
                bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
            ])),
            _ => EmValue::I32(0),
        }
    }

    /// Copies a block of memory from source to destination.
    ///
    /// Implements the CIL `cpblk` instruction semantics. Handles overlapping
    /// regions by reading the source data first.
    ///
    /// # Arguments
    ///
    /// * `dest` - Destination address
    /// * `src` - Source address
    /// * `size` - Number of bytes to copy
    ///
    /// # Errors
    ///
    /// Returns an error if either address is unmapped or the copy fails.
    pub fn copy_block(&self, dest: u64, src: u64, size: usize) -> Result<()> {
        if size == 0 {
            return Ok(());
        }

        // Read source data
        let src_data = self.read(src, size)?;

        // Write to destination
        self.write(dest, &src_data)
    }

    /// Initializes a block of memory with a byte value.
    ///
    /// Implements the CIL `initblk` instruction semantics.
    ///
    /// # Arguments
    ///
    /// * `address` - The starting address to initialize
    /// * `value` - The byte value to fill with
    /// * `size` - Number of bytes to initialize
    ///
    /// # Errors
    ///
    /// Returns an error if the address is unmapped.
    pub fn init_block(&self, address: u64, value: u8, size: usize) -> Result<()> {
        if size == 0 {
            return Ok(());
        }

        let data = vec![value; size];
        self.write(address, &data)
    }

    /// Maps a PE image at its preferred base address.
    ///
    /// # Arguments
    ///
    /// * `data` - The PE image bytes (should be mapped according to section alignment)
    /// * `preferred_base` - The preferred base address (usually from the PE header)
    /// * `sections` - Section information for protection lookup
    /// * `name` - A label for the image (for debugging)
    ///
    /// # Returns
    ///
    /// The base address where the image was mapped (same as `preferred_base`).
    ///
    /// # Errors
    ///
    /// Returns an error if the mapping fails.
    pub fn map_pe_image(
        &self,
        data: &[u8],
        preferred_base: u64,
        sections: Vec<SectionInfo>,
        name: impl Into<String>,
    ) -> Result<u64> {
        let region = MemoryRegion::pe_image(preferred_base, data, sections, name);
        self.map_at(preferred_base, region)?;
        Ok(preferred_base)
    }

    /// Maps raw data at a specific address with read-write protection.
    ///
    /// # Arguments
    ///
    /// * `address` - The address to map the data at
    /// * `data` - The data bytes
    /// * `label` - A label for the region (for debugging)
    ///
    /// # Errors
    ///
    /// Returns an error if the mapping fails.
    pub fn map_data(&self, address: u64, data: &[u8], label: impl Into<String>) -> Result<()> {
        let region = MemoryRegion::mapped_data(address, data, label, MemoryProtection::READ_WRITE);
        self.map_at(address, region)
    }

    /// Returns information about all mapped regions.
    ///
    /// Each tuple contains `(base_address, size, label)`.
    #[must_use]
    pub fn regions(&self) -> Vec<(u64, usize, String)> {
        match self.regions.read() {
            Ok(regions) => regions
                .iter()
                .map(|r| (r.base(), r.size(), r.label().to_string()))
                .collect(),
            Err(_) => Vec::new(),
        }
    }

    /// Returns the total size of all mapped regions in bytes.
    #[must_use]
    pub fn mapped_size(&self) -> usize {
        match self.regions.read() {
            Ok(regions) => regions.iter().map(MemoryRegion::size).sum(),
            Err(_) => 0,
        }
    }

    /// Checks if two regions overlap in the address space.
    ///
    /// Uses the standard interval overlap test: two intervals [a_start, a_end)
    /// and [b_start, b_end) overlap iff a_start < b_end && b_start < a_end.
    fn regions_overlap(a: &MemoryRegion, b: &MemoryRegion) -> bool {
        let a_start = a.base();
        let a_end = a.end();
        let b_start = b.base();
        let b_end = b.end();

        a_start < b_end && b_start < a_end
    }

    /// Allocates a string on the managed heap.
    ///
    /// # Arguments
    ///
    /// * `value` - The string value to allocate
    ///
    /// # Errors
    ///
    /// Returns an error if the heap is out of memory.
    pub fn alloc_string(&self, value: &str) -> Result<HeapRef> {
        self.heap.alloc_string(value)
    }

    /// Gets a string from the managed heap.
    ///
    /// # Arguments
    ///
    /// * `heap_ref` - Reference to the string object
    ///
    /// # Returns
    ///
    /// An `Arc<str>` for efficient, borrow-free access.
    ///
    /// # Errors
    ///
    /// Returns an error if the reference is invalid or not a string.
    pub fn get_string(&self, heap_ref: HeapRef) -> Result<std::sync::Arc<str>> {
        self.heap.get_string(heap_ref)
    }

    /// Allocates an empty object on the managed heap.
    ///
    /// # Arguments
    ///
    /// * `type_token` - The type token for the object
    ///
    /// # Errors
    ///
    /// Returns an error if the heap is out of memory.
    pub fn alloc_object(&self, type_token: Token) -> Result<HeapRef> {
        self.heap.alloc_object(type_token)
    }

    /// Gets a field value from a heap object.
    ///
    /// # Arguments
    ///
    /// * `heap_ref` - Reference to the object
    /// * `field_token` - Token of the field to read
    ///
    /// # Errors
    ///
    /// Returns an error if the reference is invalid, not an object,
    /// or the field does not exist.
    pub fn get_field(&self, heap_ref: HeapRef, field_token: Token) -> Result<EmValue> {
        self.heap.get_field(heap_ref, field_token)
    }

    /// Sets a field value on a heap object.
    ///
    /// # Arguments
    ///
    /// * `heap_ref` - Reference to the object
    /// * `field_token` - Token of the field to set
    /// * `value` - The value to store
    ///
    /// # Errors
    ///
    /// Returns an error if the reference is invalid or not an object.
    pub fn set_field(&self, heap_ref: HeapRef, field_token: Token, value: EmValue) -> Result<()> {
        self.heap.set_field(heap_ref, field_token, value)
    }
}

impl Default for AddressSpace {
    fn default() -> Self {
        Self::new()
    }
}

impl AddressSpace {
    /// Creates a fresh address space that shares memory regions but has independent mutable state.
    ///
    /// This is optimized for spawning lightweight emulation instances from a template:
    /// - **Shared (cheap)**: Memory regions (PE images, mapped data) - data uses `Arc` internally
    /// - **Fresh**: Heap, static fields, protection overrides, allocation pointer
    ///
    /// This pattern is ideal for deobfuscation where you need to run the same decryptor
    /// method many times with different arguments. The expensive PE loading and mapping
    /// is done once in the template, while each spawn gets fresh mutable state.
    ///
    /// # Example
    ///
    /// ```rust
    /// use dotscope::emulation::AddressSpace;
    ///
    /// // Create template with mapped data
    /// let template = AddressSpace::new();
    /// template.map_data(0x10000, &[1, 2, 3, 4], "data").unwrap();
    ///
    /// // Spawn a fresh instance - shares regions, fresh heap/statics
    /// let fresh = template.spawn_fresh();
    ///
    /// // Modifications to fresh don't affect template's heap/statics
    /// fresh.set_static(dotscope::metadata::token::Token::new(0x04000001),
    ///                  dotscope::emulation::EmValue::I32(42)).unwrap();
    /// assert!(template.get_static(dotscope::metadata::token::Token::new(0x04000001)).unwrap().is_none());
    /// ```
    #[must_use]
    pub fn spawn_fresh(&self) -> Self {
        // Clone regions - this is cheap because pages use CoW internally
        let regions = match self.regions.read() {
            Ok(r) => r.clone(),
            Err(_) => Vec::new(),
        };

        Self {
            // Fresh heap - each spawn gets independent heap allocations
            heap: SharedHeap::default(),
            // Shared regions - cheap clone due to CoW pages
            regions: RwLock::new(regions),
            // Fresh statics - each spawn starts with empty static field storage
            statics: StaticFieldStorage::new(),
            // Fresh allocation pointer
            next_address: AtomicU64::new(self.next_address.load(Ordering::SeqCst)),
            // Same size limit
            size: self.size,
            // Fresh protection overrides (VirtualProtect state)
            protection_overrides: RwLock::new(ImHashMap::new()),
            // Fresh monitor locks
            monitor_locks: RwLock::new(ImHashMap::new()),
            // Fresh pinned array mappings
            pinned_arrays: RwLock::new(ImHashMap::new()),
        }
    }

    /// Forks this address space with full Copy-on-Write semantics.
    ///
    /// Creates an independent copy that shares data with the original via
    /// structural sharing. Both the original and fork can be modified independently -
    /// only the modified data is actually copied (true copy-on-write).
    ///
    /// # What Gets Forked
    ///
    /// - **Memory regions**: Forked with per-page CoW (4KB granularity)
    /// - **Managed heap**: Forked via `imbl` structural sharing (O(1))
    /// - **Static fields**: Forked via `imbl` structural sharing (O(1))
    /// - **Protection overrides**: Forked via `imbl` structural sharing (O(1))
    ///
    /// # Performance
    ///
    /// This is an O(1) operation for heap, statics, and protection overrides.
    /// Regions are O(n) where n is the number of regions (not pages), since
    /// each region's pages use CoW internally.
    ///
    /// # Use Case
    ///
    /// Ideal for running many parallel decryption operations from a single
    /// setup. The expensive emulator initialization (PE loading, type resolution,
    /// static initializers) happens once, then `fork()` creates lightweight
    /// copies for each decryptor call.
    ///
    /// # Example
    ///
    /// ```rust
    /// use dotscope::emulation::{AddressSpace, EmValue};
    /// use dotscope::metadata::token::Token;
    ///
    /// // Set up template with data
    /// let template = AddressSpace::new();
    /// template.map_data(0x1000, &[1, 2, 3, 4], "data").unwrap();
    /// template.set_static(Token::new(0x04000001), EmValue::I32(42)).unwrap();
    ///
    /// // Fork creates independent copy with shared backing
    /// let forked = template.fork().unwrap();
    ///
    /// // Modifications are independent
    /// forked.set_static(Token::new(0x04000001), EmValue::I32(100)).unwrap();
    /// forked.write(0x1000, &[0xFF]).unwrap();
    ///
    /// // Original unchanged
    /// assert_eq!(template.get_static(Token::new(0x04000001)).unwrap(), Some(EmValue::I32(42)));
    /// assert_eq!(template.read(0x1000, 1).unwrap(), vec![1]);
    /// ```
    pub fn fork(&self) -> Result<Self> {
        // Fork all regions (each region forks its pages)
        let regions = self
            .regions
            .read()
            .map_err(|_| EmulationError::LockPoisoned {
                description: "address space regions",
            })?
            .iter()
            .map(|region| region.fork())
            .collect::<std::result::Result<Vec<_>, _>>()?;

        // Fork protection overrides (O(1) due to imbl)
        let protection_overrides = self
            .protection_overrides
            .read()
            .map_err(|_| EmulationError::LockPoisoned {
                description: "address space protection overrides",
            })?
            .clone();

        // Fork monitor locks (O(1) due to imbl)
        let monitor_locks = self
            .monitor_locks
            .read()
            .map_err(|_| EmulationError::LockPoisoned {
                description: "address space monitor locks",
            })?
            .clone();

        // Fork pinned array mappings (O(1) due to imbl)
        let pinned_arrays = self
            .pinned_arrays
            .read()
            .map_err(|_| EmulationError::LockPoisoned {
                description: "address space pinned arrays",
            })?
            .clone();

        Ok(Self {
            // Fork heap - O(1) due to imbl structural sharing
            heap: self.heap.fork()?,
            // Forked regions - each region's pages use CoW
            regions: RwLock::new(regions),
            // Fork statics - O(1) due to imbl structural sharing
            statics: self.statics.fork()?,
            // Copy allocation pointer
            next_address: AtomicU64::new(self.next_address.load(Ordering::SeqCst)),
            // Same size limit
            size: self.size,
            // Fork protection overrides - O(1) due to imbl
            protection_overrides: RwLock::new(protection_overrides),
            // Fork monitor locks - O(1) due to imbl
            monitor_locks: RwLock::new(monitor_locks),
            // Fork pinned array mappings - O(1) due to imbl
            pinned_arrays: RwLock::new(pinned_arrays),
        })
    }
}

#[cfg(test)]
mod tests {
    use crate::{
        emulation::{
            memory::{
                addressspace::{AddressSpace, SharedHeap},
                region::MemoryProtection,
            },
            EmValue,
        },
        metadata::token::Token,
    };

    #[test]
    fn test_address_space_creation() {
        let space = AddressSpace::new();
        assert!(space.regions().is_empty());
    }

    #[test]
    fn test_map_and_read_data() {
        let space = AddressSpace::new();
        let data = vec![0xDE, 0xAD, 0xBE, 0xEF];

        space.map_data(0x1000, &data, "test").unwrap();

        let read = space.read(0x1000, 4).unwrap();
        assert_eq!(read, data);
    }

    #[test]
    fn test_write_data() {
        let space = AddressSpace::new();
        space.map_data(0x1000, &[0u8; 16], "test").unwrap();

        space.write(0x1000, &[0xCA, 0xFE]).unwrap();

        let read = space.read(0x1000, 2).unwrap();
        assert_eq!(read, vec![0xCA, 0xFE]);
    }

    #[test]
    fn test_static_fields() {
        let space = AddressSpace::new();
        let field = Token::new(0x04000001);

        assert!(space.get_static(field).unwrap().is_none());

        space.set_static(field, EmValue::I32(42)).unwrap();
        assert_eq!(space.get_static(field).unwrap(), Some(EmValue::I32(42)));
    }

    #[test]
    fn test_shared_heap() {
        let space1 = AddressSpace::new();
        let str_ref = space1.alloc_string("Hello").unwrap();

        // Create a second address space sharing the same heap
        let space2 = AddressSpace::with_heap(space1.heap().clone());

        // Both can see the string
        let s1 = space1.get_string(str_ref).unwrap();
        let s2 = space2.get_string(str_ref).unwrap();
        assert_eq!(&*s1, "Hello");
        assert_eq!(&*s2, "Hello");

        // Allocating in one is visible in the other
        let str_ref2 = space2.alloc_string("World").unwrap();
        let s3 = space1.get_string(str_ref2).unwrap();
        assert_eq!(&*s3, "World");
    }

    #[test]
    fn test_unmanaged_alloc() {
        let space = AddressSpace::new();

        let addr = space.alloc_unmanaged(256).unwrap();
        assert!(space.is_valid(addr));

        // Write and read
        space.write(addr, &[1, 2, 3, 4]).unwrap();
        let data = space.read(addr, 4).unwrap();
        assert_eq!(data, vec![1, 2, 3, 4]);

        // Free
        space.free_unmanaged(addr).unwrap();
        assert!(!space.is_valid(addr));
    }

    #[test]
    fn test_heap_delegation() {
        let space = AddressSpace::new();

        // Test string allocation through AddressSpace
        let str_ref = space.alloc_string("Test").unwrap();
        let s = space.get_string(str_ref).unwrap();
        assert_eq!(&*s, "Test");

        // Test object allocation through AddressSpace
        let type_token = Token::new(0x02000001);
        let field_token = Token::new(0x04000001);
        let obj_ref = space.alloc_object(type_token).unwrap();

        space
            .set_field(obj_ref, field_token, EmValue::I32(100))
            .unwrap();
        let value = space.get_field(obj_ref, field_token).unwrap();
        assert_eq!(value, EmValue::I32(100));
    }

    #[test]
    fn test_fork_memory_isolation() {
        let space = AddressSpace::new();
        space.map_data(0x1000, &[1, 2, 3, 4], "test").unwrap();

        // Fork
        let forked = space.fork().unwrap();

        // Both see the same initial data
        assert_eq!(space.read(0x1000, 4).unwrap(), vec![1, 2, 3, 4]);
        assert_eq!(forked.read(0x1000, 4).unwrap(), vec![1, 2, 3, 4]);

        // Modify forked
        forked.write(0x1000, &[0xFF, 0xFE]).unwrap();

        // Original unchanged, fork modified
        assert_eq!(space.read(0x1000, 4).unwrap(), vec![1, 2, 3, 4]);
        assert_eq!(forked.read(0x1000, 4).unwrap(), vec![0xFF, 0xFE, 3, 4]);
    }

    #[test]
    fn test_fork_heap_isolation() {
        let space = AddressSpace::new();
        let str_ref = space.alloc_string("Original").unwrap();

        // Fork
        let forked = space.fork().unwrap();

        // Both see the same string
        assert_eq!(&*space.get_string(str_ref).unwrap(), "Original");
        assert_eq!(&*forked.get_string(str_ref).unwrap(), "Original");

        // Allocate new string in fork
        let new_ref = forked.alloc_string("Forked").unwrap();
        assert_eq!(&*forked.get_string(new_ref).unwrap(), "Forked");

        // Original doesn't see the new string
        assert!(space.get_string(new_ref).is_err());
    }

    #[test]
    fn test_fork_statics_isolation() {
        let space = AddressSpace::new();
        let field = Token::new(0x04000001);
        space.set_static(field, EmValue::I32(42)).unwrap();

        // Fork
        let forked = space.fork().unwrap();

        // Both see the same static
        assert_eq!(space.get_static(field).unwrap(), Some(EmValue::I32(42)));
        assert_eq!(forked.get_static(field).unwrap(), Some(EmValue::I32(42)));

        // Modify in fork
        forked.set_static(field, EmValue::I32(100)).unwrap();

        // Original unchanged
        assert_eq!(space.get_static(field).unwrap(), Some(EmValue::I32(42)));
        assert_eq!(forked.get_static(field).unwrap(), Some(EmValue::I32(100)));
    }

    #[test]
    fn test_fork_protection_isolation() {
        let space = AddressSpace::new();
        space.map_data(0x1000, &vec![0u8; 0x2000], "test").unwrap();

        // Set protection
        space.set_protection(0x1000, 0x1000, MemoryProtection::READ_EXECUTE);

        // Fork
        let forked = space.fork().unwrap();

        // Both see the same protection
        assert_eq!(
            space.get_protection(0x1000),
            Some(MemoryProtection::READ_EXECUTE)
        );
        assert_eq!(
            forked.get_protection(0x1000),
            Some(MemoryProtection::READ_EXECUTE)
        );

        // Modify in fork
        forked.set_protection(0x1000, 0x1000, MemoryProtection::READ_WRITE);

        // Original unchanged
        assert_eq!(
            space.get_protection(0x1000),
            Some(MemoryProtection::READ_EXECUTE)
        );
        assert_eq!(
            forked.get_protection(0x1000),
            Some(MemoryProtection::READ_WRITE)
        );
    }

    #[test]
    fn test_multiple_forks_isolation() {
        let space = AddressSpace::new();
        let field = Token::new(0x04000001);
        space.set_static(field, EmValue::I32(1)).unwrap();

        // Create multiple forks
        let fork1 = space.fork().unwrap();
        let fork2 = space.fork().unwrap();

        // Modify each independently
        fork1.set_static(field, EmValue::I32(10)).unwrap();
        fork2.set_static(field, EmValue::I32(20)).unwrap();

        // Each has its own value
        assert_eq!(space.get_static(field).unwrap(), Some(EmValue::I32(1)));
        assert_eq!(fork1.get_static(field).unwrap(), Some(EmValue::I32(10)));
        assert_eq!(fork2.get_static(field).unwrap(), Some(EmValue::I32(20)));
    }

    #[test]
    fn test_shared_heap_fork() {
        let heap = SharedHeap::new(1024 * 1024);
        let str_ref = heap.alloc_string("Hello").unwrap();

        // Fork the heap
        let forked = heap.fork().unwrap();

        // Both see the string
        assert_eq!(&*heap.get_string(str_ref).unwrap(), "Hello");
        assert_eq!(&*forked.get_string(str_ref).unwrap(), "Hello");

        // Allocate in forked
        let new_ref = forked.alloc_string("World").unwrap();
        assert_eq!(&*forked.get_string(new_ref).unwrap(), "World");

        // Original doesn't see it
        assert!(heap.get_string(new_ref).is_err());
    }
}