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
//! Process builder for configuring emulation processes.
//!
//! This module provides [`ProcessBuilder`] for fluent configuration of
//! emulation processes. The builder pattern allows for flexible setup of
//! all aspects of .NET emulation including:
//!
//! - Assembly loading and PE image mapping
//! - Memory configuration and data mapping
//! - Execution limits and resource constraints
//! - Stub registration for BCL method emulation
//! - Capture configuration for extracting runtime data
//!
//! # Overview
//!
//! The [`ProcessBuilder`] is the primary entry point for creating [`EmulationProcess`]
//! instances. It provides a fluent API that supports both simple and complex
//! configuration scenarios through method chaining.
//!
//! # Usage Patterns
//!
//! ## Simple Configuration
//!
//! For basic emulation, load an assembly and use preset configurations:
//!
//! ```rust,no_run
//! use dotscope::emulation::ProcessBuilder;
//! use dotscope::CilObject;
//!
//! # fn main() -> Result<(), dotscope::Error> {
//! let assembly = CilObject::from_path("sample.exe")?;
//! let process = ProcessBuilder::new()
//!     .assembly(assembly)
//!     .for_extraction()
//!     .build()?;
//! # Ok(())
//! # }
//! ```
//!
//! ## Advanced Configuration
//!
//! For detailed control, configure individual components:
//!
//! ```rust,no_run
//! use dotscope::emulation::{ProcessBuilder, EmulationConfig, CaptureConfig};
//! use dotscope::CilObject;
//!
//! # fn main() -> Result<(), dotscope::Error> {
//! # let assembly = CilObject::from_path("sample.exe")?;
//! # let pe_bytes = std::fs::read("sample.exe").unwrap();
//! # let encrypted_data = vec![0u8; 16];
//! let process = ProcessBuilder::new()
//!     .assembly(assembly)
//!     .config(EmulationConfig::extraction())
//!     .with_max_instructions(100_000_000)
//!     .with_max_heap_bytes(512 * 1024 * 1024)
//!     .map_pe_image(&pe_bytes, "main.exe")
//!     .map_data(0x400000, encrypted_data, "encrypted_section")
//!     .capture_assemblies()
//!     .capture_strings()
//!     .build()?;
//! # Ok(())
//! # }
//! ```
//!
//! ## Custom Stubs
//!
//! Register custom method stubs for BCL methods:
//!
//! ```rust,ignore
//! # use dotscope::emulation::ProcessBuilder;
//! let process = ProcessBuilder::new()
//!     .assembly(assembly)
//!     .stub(signature, my_custom_stub)
//!     .no_default_stubs() // Optionally disable built-in stubs
//!     .build()?;
//! ```

use std::path::Path;
use std::sync::Arc;

use log::debug;

use crate::{
    emulation::{
        capture::CaptureContext,
        engine::TraceWriter,
        fakeobjects::SharedFakeObjects,
        loader::{DataLoader, PeLoader, PeLoaderConfig},
        memory::{AddressSpace, MemoryProtection, SharedHeap},
        process::{CaptureConfig, EmulationConfig, EmulationProcess, TracingConfig},
        runtime::{Hook, RuntimeState},
        EmValue,
    },
    metadata::{tables::FieldRvaRaw, token::Token, typesystem::PointerSize},
    CilObject, Result,
};

/// Pre-populates static fields with data from the FieldRVA table.
///
/// This function reads the FieldRVA metadata table and initializes static fields
/// that have embedded data in the PE file. This is essential for deobfuscation
/// where static initializers may reference this data.
///
/// # What Gets Initialized
///
/// - Primitive value types (I1, I2, I4, I8, U1, U2, U4, U8, R4, R8, Boolean, Char)
/// - Value types with known sizes from the ClassLayout table
///
/// # What Is NOT Initialized
///
/// - Arrays (handled by `RuntimeHelpers.InitializeArray` during execution)
/// - Reference types
/// - Complex value types without explicit size information
///
/// # Arguments
///
/// * `assembly` - The assembly to read FieldRVA data from
/// * `address_space` - The address space containing static field storage
fn populate_fieldrva_statics(assembly: &CilObject, address_space: &AddressSpace) {
    let Some(tables) = assembly.tables() else {
        return;
    };

    let Some(fieldrva_table) = tables.table::<FieldRvaRaw>() else {
        return;
    };

    let types = assembly.types();
    let file = assembly.file();
    let pe_data = file.data();
    let ptr_size = PointerSize::from_pe(file.pe().is_64bit);

    for row in fieldrva_table {
        if row.rva == 0 {
            continue;
        }

        // Convert field index to full token (table 0x04 = Field)
        let field_token = Token::new(row.field | 0x0400_0000);

        // Look up the field to get its byte size from TypeRegistry
        let Some(field_type_size) = types.get_field_byte_size(&field_token, ptr_size) else {
            continue;
        };

        // Convert RVA to file offset
        let Ok(file_offset) = file.rva_to_offset(row.rva as usize) else {
            continue;
        };

        if file_offset + field_type_size > pe_data.len() {
            continue;
        }

        // Read the bytes from the PE file
        let data = &pe_data[file_offset..file_offset + field_type_size];

        // Convert to EmValue based on size
        let value = match field_type_size {
            1 => EmValue::I32(i32::from(data[0].cast_signed())),
            2 => {
                let bytes = [data[0], data[1]];
                EmValue::I32(i32::from(i16::from_le_bytes(bytes)))
            }
            4 => {
                let bytes = [data[0], data[1], data[2], data[3]];
                EmValue::I32(i32::from_le_bytes(bytes))
            }
            8 => {
                let bytes = [
                    data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7],
                ];
                EmValue::I64(i64::from_le_bytes(bytes))
            }
            _ => continue,
        };

        // Store in static field storage
        address_space.statics().set(field_token, value);
    }
}

/// Deferred mapping operation for [`ProcessBuilder`].
///
/// Represents a memory mapping operation that will be executed when
/// [`ProcessBuilder::build`] is called. Operations are stored in order
/// and executed sequentially during process construction.
///
/// This enum is internal to the builder and not exposed publicly.
#[derive(Clone)]
enum MappingOperation {
    /// Map a PE image from raw bytes into the address space.
    ///
    /// The PE loader will parse headers, map sections, and apply relocations.
    PeImage {
        /// Raw PE file bytes.
        data: Vec<u8>,
        /// Display name for the loaded image.
        name: String,
        /// Configuration for the PE loader.
        config: PeLoaderConfig,
    },

    /// Map a PE image from a file path.
    ///
    /// The file will be read and loaded using the PE loader.
    PeFile {
        /// Path to the PE file.
        path: std::path::PathBuf,
        /// Configuration for the PE loader.
        config: PeLoaderConfig,
    },

    /// Map raw data at a specific virtual address.
    ///
    /// Used for mapping decrypted sections, unpacked data, or other
    /// raw memory regions at known addresses.
    DataAt {
        /// Target virtual address for the mapping.
        address: u64,
        /// Raw data bytes to map.
        data: Vec<u8>,
        /// Descriptive label for the region.
        label: String,
        /// Memory protection flags.
        protection: MemoryProtection,
    },

    /// Map raw data at the next available address.
    ///
    /// The address space allocator will choose an appropriate location.
    Data {
        /// Raw data bytes to map.
        data: Vec<u8>,
        /// Descriptive label for the region.
        label: String,
        /// Memory protection flags.
        protection: MemoryProtection,
    },

    /// Map file contents at a specific address.
    ///
    /// Reads a file and maps its contents into the address space.
    File {
        /// Path to the file to map.
        path: std::path::PathBuf,
        /// Target virtual address for the mapping.
        address: u64,
        /// Memory protection flags.
        protection: MemoryProtection,
    },

    /// Map zeroed memory at a specific address.
    ///
    /// Allocates a region of zero-initialized memory, useful for
    /// creating stack space, heap regions, or uninitialized data sections.
    Zeroed {
        /// Target virtual address for the mapping.
        address: u64,
        /// Size of the region in bytes.
        size: usize,
        /// Descriptive label for the region.
        label: String,
        /// Memory protection flags.
        protection: MemoryProtection,
    },
}

/// Builder for creating and configuring emulation processes.
///
/// `ProcessBuilder` provides a fluent API for setting up .NET emulation with
/// assemblies, PE images, mapped data, and custom stubs. It is the recommended
/// way to create [`EmulationProcess`] instances.
///
/// # Builder Pattern
///
/// The builder follows a fluent interface pattern where all configuration methods
/// return `self`, allowing method chaining. Configuration is accumulated and
/// applied when [`build()`](ProcessBuilder::build) is called.
///
/// # Configuration Categories
///
/// The builder supports several categories of configuration:
///
/// - **Assembly**: Set the primary .NET assembly to emulate
/// - **Memory Mapping**: Map PE images, raw data, or files into the address space
/// - **Limits**: Configure instruction counts, call depth, and memory limits
/// - **Stubs**: Register custom method implementations for BCL methods
/// - **Capture**: Configure what data to capture during emulation
/// - **Presets**: Use predefined configurations for common use cases
///
/// # Example
///
/// ```rust,no_run
/// use dotscope::emulation::{ProcessBuilder, EmulationConfig};
/// use dotscope::CilObject;
///
/// # fn main() -> Result<(), dotscope::Error> {
/// let assembly = CilObject::from_path("sample.exe")?;
/// # let pe_bytes = std::fs::read("sample.exe").unwrap();
///
/// let process = ProcessBuilder::new()
///     .assembly(assembly)
///     .config(EmulationConfig::extraction())
///     .map_pe_image(&pe_bytes, "main.exe")
///     .capture_assemblies()
///     .build()?;
/// # Ok(())
/// # }
/// ```
///
/// # Thread Safety
///
/// The builder itself is not thread-safe, but the resulting [`EmulationProcess`]
/// can be safely shared across threads via `Arc`.
pub struct ProcessBuilder {
    /// Primary .NET assembly to emulate.
    ///
    /// When set, the assembly's PE image is automatically mapped as the
    /// primary image during build.
    assembly: Option<Arc<CilObject>>,

    /// Emulation configuration controlling execution behavior.
    ///
    /// Includes limits, stub settings, threading options, and more.
    config: EmulationConfig,

    /// Configuration for capturing runtime data.
    ///
    /// Controls what information (assemblies, strings, buffers) is
    /// captured during emulation.
    capture_config: CaptureConfig,

    /// Hooks for method interception.
    ///
    /// These are registered with the runtime's hook manager before execution.
    hooks: Vec<Hook>,

    /// Deferred memory mapping operations.
    ///
    /// These are executed in order during build to set up the address space.
    mappings: Vec<MappingOperation>,

    /// Whether to register default BCL stubs.
    ///
    /// When true (default), standard library stubs for String, Array,
    /// Math, etc. are automatically registered.
    register_defaults: bool,

    /// Optional process name for identification.
    ///
    /// If not set, defaults to the assembly name or "emulation".
    name: Option<String>,
}

impl ProcessBuilder {
    /// Creates a new process builder with default settings.
    ///
    /// The builder is initialized with:
    /// - No assembly loaded
    /// - Default emulation configuration
    /// - Default capture configuration (nothing captured)
    /// - No custom hooks
    /// - Default BCL hooks enabled
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use dotscope::emulation::ProcessBuilder;
    ///
    /// let builder = ProcessBuilder::new();
    /// ```
    #[must_use]
    pub fn new() -> Self {
        Self {
            assembly: None,
            config: EmulationConfig::default(),
            capture_config: CaptureConfig::default(),
            hooks: Vec::new(),
            mappings: Vec::new(),
            register_defaults: true,
            name: None,
        }
    }

    /// Sets the primary .NET assembly for emulation.
    ///
    /// The assembly provides metadata for type resolution, method lookup,
    /// and instruction decoding. Its PE image is automatically mapped
    /// into the address space during build.
    ///
    /// # Arguments
    ///
    /// * `assembly` - The loaded [`CilObject`] to use as the primary assembly
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use dotscope::emulation::ProcessBuilder;
    /// use dotscope::CilObject;
    ///
    /// # fn main() -> Result<(), dotscope::Error> {
    /// let assembly = CilObject::from_path("sample.exe")?;
    /// let builder = ProcessBuilder::new().assembly(assembly);
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn assembly(mut self, assembly: CilObject) -> Self {
        self.assembly = Some(Arc::new(assembly));
        self
    }

    /// Sets the primary assembly using an existing `Arc<CilObject>`.
    ///
    /// This variant is useful when the assembly is already wrapped in an
    /// `Arc`, avoiding an extra allocation.
    ///
    /// # Arguments
    ///
    /// * `assembly` - Arc-wrapped [`CilObject`] to use as the primary assembly
    #[must_use]
    pub fn assembly_arc(mut self, assembly: Arc<CilObject>) -> Self {
        self.assembly = Some(assembly);
        self
    }

    /// Sets the emulation configuration.
    ///
    /// The configuration controls execution limits, stub behavior,
    /// threading options, and tracing settings.
    ///
    /// # Arguments
    ///
    /// * `config` - The [`EmulationConfig`] to use
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use dotscope::emulation::{ProcessBuilder, EmulationConfig};
    ///
    /// let builder = ProcessBuilder::new()
    ///     .config(EmulationConfig::extraction());
    /// ```
    ///
    /// # See Also
    ///
    /// - [`for_extraction`](Self::for_extraction) - Preset for assembly extraction
    /// - [`for_analysis`](Self::for_analysis) - Preset for static analysis
    /// - [`for_full_emulation`](Self::for_full_emulation) - Preset for complete emulation
    #[must_use]
    pub fn config(mut self, config: EmulationConfig) -> Self {
        self.config = config;
        self
    }

    /// Overrides the target pointer size for native int/uint types.
    ///
    /// By default, pointer size is auto-detected from the PE header during
    /// [`build()`](Self::build). Use this method to override it manually.
    ///
    /// # Arguments
    ///
    /// * `ptr_size` - The [`PointerSize`] to use
    #[must_use]
    pub fn pointer_size(mut self, ptr_size: PointerSize) -> Self {
        self.config.pointer_size = ptr_size;
        self
    }

    /// Sets the capture configuration.
    ///
    /// The capture configuration determines what runtime data is collected
    /// during emulation, such as loaded assemblies, decrypted strings,
    /// and memory buffers.
    ///
    /// # Arguments
    ///
    /// * `config` - The [`CaptureConfig`] to use
    ///
    /// # See Also
    ///
    /// For individual capture settings, see:
    /// - [`capture_assemblies`](Self::capture_assemblies)
    /// - [`capture_strings`](Self::capture_strings)
    /// - [`capture_memory_region`](Self::capture_memory_region)
    #[must_use]
    pub fn capture(mut self, config: CaptureConfig) -> Self {
        self.capture_config = config;
        self
    }

    /// Sets the process name for identification.
    ///
    /// The name is used for logging and debugging. If not set, defaults
    /// to the assembly name or "emulation".
    ///
    /// # Arguments
    ///
    /// * `name` - Display name for the process
    #[must_use]
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Applies the extraction preset configuration.
    ///
    /// This preset is optimized for extracting packed or encrypted assemblies:
    /// - High instruction limit (50 million)
    /// - Unknown methods return default values
    /// - Assembly capture enabled automatically
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use dotscope::emulation::ProcessBuilder;
    /// use dotscope::CilObject;
    ///
    /// # fn main() -> Result<(), dotscope::Error> {
    /// # let assembly = CilObject::from_path("sample.exe")?;
    /// let process = ProcessBuilder::new()
    ///     .assembly(assembly)
    ///     .for_extraction()
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn for_extraction(mut self) -> Self {
        self.config = EmulationConfig::extraction();
        self.capture_config.assemblies = true;
        self
    }

    /// Applies the analysis preset configuration.
    ///
    /// This preset is optimized for static analysis and constant propagation:
    /// - Moderate instruction limit (1 million)
    /// - Symbolic tracking enabled
    /// - Threading disabled for determinism
    /// - Unknown methods return symbolic values
    #[must_use]
    pub fn for_analysis(mut self) -> Self {
        self.config = EmulationConfig::analysis();
        self
    }

    /// Applies the full emulation preset configuration.
    ///
    /// This preset enables all emulation features:
    /// - Very high instruction limit (100 million)
    /// - 5 minute timeout
    /// - Strict mode (fail on missing stubs)
    /// - Full threading and exception handling
    #[must_use]
    pub fn for_full_emulation(mut self) -> Self {
        self.config = EmulationConfig::full();
        self
    }

    /// Applies the minimal preset configuration.
    ///
    /// This preset is optimized for simple constant folding:
    /// - Low instruction limit (10,000)
    /// - Shallow call depth (10)
    /// - Only BCL stubs enabled
    /// - Threading and exceptions disabled
    #[must_use]
    pub fn for_minimal(mut self) -> Self {
        self.config = EmulationConfig::minimal();
        self
    }

    /// Sets the maximum number of instructions to execute.
    ///
    /// When this limit is reached, emulation stops with a
    /// [`LimitReached`](crate::emulation::engine::EmulationOutcome::LimitReached) outcome.
    ///
    /// # Arguments
    ///
    /// * `max` - Maximum instruction count (0 for unlimited)
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use dotscope::emulation::ProcessBuilder;
    ///
    /// # fn main() -> Result<(), dotscope::Error> {
    /// let process = ProcessBuilder::new()
    ///     .with_max_instructions(1_000_000)
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn with_max_instructions(mut self, max: u64) -> Self {
        self.config.limits.max_instructions = max;
        self
    }

    /// Sets the maximum call stack depth.
    ///
    /// Prevents runaway recursion by limiting nested method calls.
    ///
    /// # Arguments
    ///
    /// * `max` - Maximum call depth
    #[must_use]
    pub fn with_max_call_depth(mut self, max: usize) -> Self {
        self.config.limits.max_call_depth = max;
        self
    }

    /// Sets the maximum heap memory in bytes.
    ///
    /// Limits total memory that can be allocated on the managed heap.
    ///
    /// # Arguments
    ///
    /// * `max` - Maximum heap size in bytes
    #[must_use]
    pub fn with_max_heap_bytes(mut self, max: usize) -> Self {
        self.config.limits.max_heap_bytes = max;
        self
    }

    /// Sets the execution timeout in milliseconds.
    ///
    /// When exceeded, emulation stops with a timeout error.
    ///
    /// # Arguments
    ///
    /// * `ms` - Timeout in milliseconds (0 for no timeout)
    #[must_use]
    pub fn with_timeout_ms(mut self, ms: u64) -> Self {
        self.config.limits.timeout_ms = ms;
        self
    }

    /// Sets the tracing configuration.
    ///
    /// Controls what events are logged during emulation. Use the preset
    /// methods on [`TracingConfig`] for common scenarios.
    ///
    /// # Arguments
    ///
    /// * `tracing` - The [`TracingConfig`] to use
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use dotscope::emulation::{ProcessBuilder, TracingConfig};
    ///
    /// # fn main() -> Result<(), dotscope::Error> {
    /// let process = ProcessBuilder::new()
    ///     .with_tracing(TracingConfig::full_trace("trace.log"))
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn with_tracing(mut self, tracing: TracingConfig) -> Self {
        self.config.tracing = tracing;
        self
    }

    /// Maps a PE image from raw bytes into the address space.
    ///
    /// The PE loader will:
    /// - Parse PE headers
    /// - Map sections at their virtual addresses
    /// - Apply base relocations if needed
    /// - Set appropriate memory protections
    ///
    /// # Arguments
    ///
    /// * `pe_bytes` - Raw PE file bytes
    /// * `name` - Display name for the loaded image
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use dotscope::emulation::ProcessBuilder;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let pe_data = std::fs::read("sample.exe")?;
    /// let process = ProcessBuilder::new()
    ///     .map_pe_image(&pe_data, "sample.exe")
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn map_pe_image(mut self, pe_bytes: &[u8], name: impl Into<String>) -> Self {
        self.mappings.push(MappingOperation::PeImage {
            data: pe_bytes.to_vec(),
            name: name.into(),
            config: PeLoaderConfig::default(),
        });
        self
    }

    /// Maps a PE image from bytes with custom loader configuration.
    ///
    /// Allows fine-grained control over how the PE is loaded, such as
    /// forcing a specific base address or skipping relocations.
    ///
    /// # Arguments
    ///
    /// * `pe_bytes` - Raw PE file bytes
    /// * `name` - Display name for the loaded image
    /// * `config` - Custom [`PeLoaderConfig`] settings
    #[must_use]
    pub fn map_pe_image_with_config(
        mut self,
        pe_bytes: &[u8],
        name: impl Into<String>,
        config: PeLoaderConfig,
    ) -> Self {
        self.mappings.push(MappingOperation::PeImage {
            data: pe_bytes.to_vec(),
            name: name.into(),
            config,
        });
        self
    }

    /// Maps a PE image from a file path.
    ///
    /// Reads the file and loads it as a PE image during build.
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the PE file
    #[must_use]
    pub fn map_pe_file(mut self, path: impl AsRef<Path>) -> Self {
        self.mappings.push(MappingOperation::PeFile {
            path: path.as_ref().to_path_buf(),
            config: PeLoaderConfig::default(),
        });
        self
    }

    /// Maps raw data at a specific virtual address.
    ///
    /// The data is mapped with read/write protection by default. This is
    /// useful for mapping decrypted sections, unpacked code, or test data.
    ///
    /// # Arguments
    ///
    /// * `address` - Target virtual address
    /// * `data` - Raw bytes to map
    /// * `label` - Descriptive label for the region
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use dotscope::emulation::ProcessBuilder;
    ///
    /// # fn main() -> Result<(), dotscope::Error> {
    /// let decrypted = vec![0x90; 0x1000];
    /// let process = ProcessBuilder::new()
    ///     .map_data(0x00400000, decrypted, "decrypted_code")
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn map_data(mut self, address: u64, data: Vec<u8>, label: impl Into<String>) -> Self {
        self.mappings.push(MappingOperation::DataAt {
            address,
            data,
            label: label.into(),
            protection: MemoryProtection::READ | MemoryProtection::WRITE,
        });
        self
    }

    /// Maps raw data at a specific address with custom protection.
    ///
    /// # Arguments
    ///
    /// * `address` - Target virtual address
    /// * `data` - Raw bytes to map
    /// * `label` - Descriptive label for the region
    /// * `protection` - Memory protection flags
    #[must_use]
    pub fn map_data_with_protection(
        mut self,
        address: u64,
        data: Vec<u8>,
        label: impl Into<String>,
        protection: MemoryProtection,
    ) -> Self {
        self.mappings.push(MappingOperation::DataAt {
            address,
            data,
            label: label.into(),
            protection,
        });
        self
    }

    /// Maps a file's contents at a specific address.
    ///
    /// The file is read during build and mapped with read-only protection.
    ///
    /// # Arguments
    ///
    /// * `address` - Target virtual address
    /// * `path` - Path to the file to map
    #[must_use]
    pub fn map_file(mut self, address: u64, path: impl AsRef<Path>) -> Self {
        self.mappings.push(MappingOperation::File {
            path: path.as_ref().to_path_buf(),
            address,
            protection: MemoryProtection::READ,
        });
        self
    }

    /// Maps zeroed memory at a specific address.
    ///
    /// Creates a region of zero-initialized memory with read/write protection.
    /// Useful for allocating stack space, heap regions, or BSS sections.
    ///
    /// # Arguments
    ///
    /// * `address` - Target virtual address
    /// * `size` - Size of the region in bytes
    /// * `label` - Descriptive label for the region
    #[must_use]
    pub fn map_zeroed(mut self, address: u64, size: usize, label: impl Into<String>) -> Self {
        self.mappings.push(MappingOperation::Zeroed {
            address,
            size,
            label: label.into(),
            protection: MemoryProtection::READ | MemoryProtection::WRITE,
        });
        self
    }

    /// Enables capture of dynamically loaded assemblies.
    ///
    /// When enabled, assemblies loaded via `Assembly.Load` during emulation
    /// are captured and can be retrieved after execution.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use dotscope::emulation::ProcessBuilder;
    /// use dotscope::CilObject;
    /// use dotscope::metadata::token::Token;
    ///
    /// # fn main() -> Result<(), dotscope::Error> {
    /// # let packed_assembly = CilObject::from_path("sample.exe")?;
    /// # let entry_point = Token::new(0x06000001);
    /// let process = ProcessBuilder::new()
    ///     .assembly(packed_assembly)
    ///     .capture_assemblies()
    ///     .build()?;
    ///
    /// process.execute_method(entry_point, vec![])?;
    ///
    /// for asm in process.captured_assemblies() {
    ///     println!("Captured: {} bytes", asm.data.len());
    /// }
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn capture_assemblies(mut self) -> Self {
        self.capture_config.assemblies = true;
        self
    }

    /// Enables capture of decrypted/constructed strings.
    ///
    /// Captures strings that are created or decrypted during emulation,
    /// useful for extracting obfuscated string literals.
    #[must_use]
    pub fn capture_strings(mut self) -> Self {
        self.capture_config.strings = true;
        self
    }

    /// Enables capture of file system operations.
    ///
    /// Records file reads, writes, and other I/O operations performed
    /// during emulation.
    #[must_use]
    pub fn capture_file_operations(mut self) -> Self {
        self.capture_config.file_operations = true;
        self
    }

    /// Enables capture of network operations.
    ///
    /// Records network connections, sends, and receives performed
    /// during emulation.
    #[must_use]
    pub fn capture_network_operations(mut self) -> Self {
        self.capture_config.network_operations = true;
        self
    }

    /// Adds a memory region to capture.
    ///
    /// Monitors writes to the specified address range and captures
    /// the data. Useful for extracting decrypted code or data.
    ///
    /// # Arguments
    ///
    /// * `start` - Start address of the region (inclusive)
    /// * `end` - End address of the region (exclusive)
    #[must_use]
    pub fn capture_memory_region(mut self, start: u64, end: u64) -> Self {
        self.capture_config.memory_regions.push(start..end);
        self
    }

    /// Registers a method hook for interception.
    ///
    /// Hooks provide flexible method interception with support for:
    /// - Multiple matching criteria (name, signature types, runtime data)
    /// - Pre/post execution handlers
    /// - Bypassing the original method execution
    ///
    /// Hooks can intercept any method call that matches their matchers.
    ///
    /// # Arguments
    ///
    /// * `hook` - The hook to register
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use dotscope::emulation::{ProcessBuilder, Hook, PreHookResult};
    ///
    /// # fn main() -> Result<(), dotscope::Error> {
    /// let process = ProcessBuilder::new()
    ///     .hook(Hook::new("log-calls")
    ///         .match_method_name("Decrypt")
    ///         .pre(|ctx, thread| {
    ///             println!("Decrypt called!");
    ///             PreHookResult::Continue
    ///         }))
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn hook(mut self, hook: Hook) -> Self {
        self.hooks.push(hook);
        self
    }

    /// Disables registration of default BCL stubs.
    ///
    /// By default, the builder registers stubs for common BCL methods
    /// (String, Array, Math, etc.). Call this to start with no stubs
    /// and only use explicitly registered ones.
    ///
    /// # Warning
    ///
    /// Disabling default stubs may cause emulation to fail if the
    /// target code calls any BCL methods.
    #[must_use]
    pub fn no_default_stubs(mut self) -> Self {
        self.register_defaults = false;
        self
    }

    /// Builds the emulation process from the configured settings.
    ///
    /// This method consumes the builder and creates an [`EmulationProcess`]
    /// ready for method execution. The build process:
    ///
    /// 1. Creates the address space with configured heap size
    /// 2. Initializes the runtime state with stubs
    /// 3. Sets up the capture context
    /// 4. Maps the primary assembly's PE image (if set)
    /// 5. Executes all deferred mapping operations in order
    /// 6. Determines the process name
    ///
    /// # Returns
    ///
    /// Returns `Ok(EmulationProcess)` on success, or an error if:
    /// - A PE image fails to load or parse
    /// - A mapping operation fails (invalid address, file not found, etc.)
    /// - Memory allocation fails
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error`] if any mapping operation fails. The error
    /// type depends on the specific failure (I/O error, PE parse error, etc.).
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use dotscope::emulation::ProcessBuilder;
    /// use dotscope::CilObject;
    /// use dotscope::metadata::token::Token;
    ///
    /// # fn main() -> Result<(), dotscope::Error> {
    /// # let assembly = CilObject::from_path("sample.exe")?;
    /// # let entry_point = Token::new(0x06000001);
    /// let process = ProcessBuilder::new()
    ///     .assembly(assembly)
    ///     .for_extraction()
    ///     .build()?;
    ///
    /// // Process is now ready for execution
    /// let outcome = process.execute_method(entry_point, vec![])?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn build(self) -> Result<EmulationProcess> {
        debug!(
            "Creating emulation process: instruction_limit={}, call_depth={}",
            self.config.limits.max_instructions, self.config.limits.max_call_depth
        );
        let heap_size = self.config.memory.max_heap_size;
        let heap = SharedHeap::new(heap_size);

        // Initialize fake BCL objects before anything else uses the heap
        let fake_objects = SharedFakeObjects::new(heap.heap());

        let address_space = Arc::new(AddressSpace::with_heap(heap));

        let mut config = self.config.clone();
        if !self.register_defaults {
            config.stubs.bcl_stubs = false;
            config.stubs.pinvoke_stubs = false;
        }

        // Auto-detect pointer size from PE header
        if let Some(ref assembly) = self.assembly {
            config.pointer_size = if assembly.file().pe().is_64bit {
                PointerSize::Bit64
            } else {
                PointerSize::Bit32
            };
        }

        let config_arc = Arc::new(config);
        let mut runtime = RuntimeState::with_config(config_arc.clone());

        for hook in self.hooks {
            runtime.register_hook(hook);
        }

        let capture = Arc::new(CaptureContext::with_config(self.capture_config));
        let mut loaded_images = Vec::new();
        let mut mapped_regions = Vec::new();

        if let Some(ref assembly) = self.assembly {
            let loader = PeLoader::default();
            let pe_bytes = assembly.file().data();
            let name = assembly
                .assembly()
                .map_or_else(|| "primary".to_string(), |a| a.name.clone());
            if let Ok(image) = loader.load(pe_bytes, &address_space, name) {
                loaded_images.push(image);
            }

            populate_fieldrva_statics(assembly, &address_space);
        }

        for mapping in self.mappings {
            match mapping {
                MappingOperation::PeImage { data, name, config } => {
                    let loader = PeLoader::with_config(config);
                    let image = loader.load(&data, &address_space, name)?;
                    loaded_images.push(image);
                }
                MappingOperation::PeFile { path, config } => {
                    let loader = PeLoader::with_config(config);
                    let image = loader.load_file(&path, &address_space)?;
                    loaded_images.push(image);
                }
                MappingOperation::DataAt {
                    address,
                    data,
                    label,
                    protection,
                } => {
                    let info =
                        DataLoader::map_at(&address_space, address, &data, label, protection)?;
                    mapped_regions.push(info);
                }
                MappingOperation::Data {
                    data,
                    label,
                    protection,
                } => {
                    let info = DataLoader::map(&address_space, &data, label, protection)?;
                    mapped_regions.push(info);
                }
                MappingOperation::File {
                    path,
                    address,
                    protection,
                } => {
                    let info = DataLoader::map_file(&address_space, &path, address, protection)?;
                    mapped_regions.push(info);
                }
                MappingOperation::Zeroed {
                    address,
                    size,
                    label,
                    protection,
                } => {
                    let info =
                        DataLoader::map_zeroed(&address_space, address, size, label, protection)?;
                    mapped_regions.push(info);
                }
            }
        }

        let name = self.name.unwrap_or_else(|| {
            self.assembly
                .as_ref()
                .and_then(|a| a.assembly())
                .map_or_else(|| "emulation".to_string(), |asm| asm.name.clone())
        });

        // Create trace writer if tracing is enabled
        let trace_writer = if config_arc.tracing.is_enabled() {
            let context = config_arc.tracing.context_prefix.clone();
            if let Some(ref path) = config_arc.tracing.output_path {
                // File-based tracing - propagate errors to caller
                let writer = TraceWriter::new_file(path, context).map_err(|e| {
                    crate::Error::TracingError(format!(
                        "Failed to create trace file {}: {e}",
                        path.display()
                    ))
                })?;
                Some(Arc::new(writer))
            } else {
                // Memory-based tracing
                Some(Arc::new(TraceWriter::new_memory(
                    config_arc.tracing.max_trace_entries,
                    context,
                )))
            }
        } else {
            None
        };

        let hook_count = runtime.hooks().len();
        let process = EmulationProcess {
            name,
            assembly: self.assembly,
            config: config_arc,
            address_space,
            runtime: Arc::new(std::sync::RwLock::new(runtime)),
            capture,
            loaded_images,
            mapped_regions,
            instruction_count: std::sync::atomic::AtomicU64::new(0),
            fake_objects,
            trace_writer,
        };
        debug!("Emulation process ready: {} hooks registered", hook_count);
        Ok(process)
    }
}

impl Default for ProcessBuilder {
    /// Creates a default process builder.
    ///
    /// Equivalent to calling [`ProcessBuilder::new()`].
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_builder_defaults() {
        let builder = ProcessBuilder::new();
        let process = builder.build().unwrap();

        assert!(!process.has_assembly());
        assert_eq!(process.loaded_image_count(), 0);
    }

    #[test]
    fn test_builder_config_presets() {
        let process = ProcessBuilder::new().for_extraction().build().unwrap();

        assert!(process.capture().config().assemblies);
    }

    #[test]
    fn test_builder_capture_config() {
        let process = ProcessBuilder::new()
            .capture_assemblies()
            .capture_strings()
            .capture_memory_region(0x400000, 0x410000)
            .build()
            .unwrap();

        let config = process.capture().config();
        assert!(config.assemblies);
        assert!(config.strings);
        assert_eq!(config.memory_regions.len(), 1);
    }

    #[test]
    fn test_builder_map_data() {
        let process = ProcessBuilder::new()
            .map_data(0x10000, vec![0x01, 0x02, 0x03, 0x04], "test_data")
            .build()
            .unwrap();

        assert_eq!(process.mapped_region_count(), 1);

        let data = process.address_space().read(0x10000, 4).unwrap();
        assert_eq!(data, vec![0x01, 0x02, 0x03, 0x04]);
    }

    #[test]
    fn test_builder_name() {
        let process = ProcessBuilder::new().name("test_process").build().unwrap();

        assert_eq!(process.name(), "test_process");
    }

    #[test]
    fn test_builder_no_default_hooks() {
        // With default hooks enabled (default behavior)
        let process_with_hooks = ProcessBuilder::new().build().unwrap();
        let runtime_with = process_with_hooks.runtime.read().unwrap();
        let count_with = runtime_with.hooks().len();

        // With default hooks disabled
        let process_no_hooks = ProcessBuilder::new().no_default_stubs().build().unwrap();
        let runtime_no = process_no_hooks.runtime.read().unwrap();
        let count_no = runtime_no.hooks().len();

        // Default hooks should have many registered (BCL + native)
        assert!(count_with > 0, "Expected default hooks to be registered");

        // No default hooks should have zero registered
        assert_eq!(
            count_no, 0,
            "Expected no hooks when no_default_stubs() is called"
        );
    }
}