dotscope 0.6.0

A high-performance, cross-platform framework for analyzing and reverse engineering .NET PE executables
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
//! Native PE export table support for .NET assemblies.
//!
//! This module provides comprehensive functionality for parsing, analyzing, and generating
//! native PE export tables. It enables dotscope to handle mixed-mode assemblies that export
//! native functions alongside managed (.NET) types, supporting COM interop, native libraries,
//! and other scenarios requiring PE export table functionality.
//!
//! # Architecture
//!
//! The native export system implements the PE/COFF export table format with support for:
//!
//! - **Export Directory**: Main export table with metadata and function table references
//! - **Export Address Table (EAT)**: Function addresses indexed by ordinal number
//! - **Export Name Table**: Function names for name-based exports
//! - **Export Ordinal Table**: Ordinal mappings for name-to-ordinal resolution
//! - **Export Forwarders**: Function forwarding to other DLLs
//!
//! # Key Components
//!
//! - [`NativeExports`] - Main container for PE export table data
//! - [`ExportFunction`] - Individual function export with address/ordinal information
//! - [`ExportForwarder`] - Export forwarding to external DLL functions
//! - [`ExportDirectory`] - PE export directory structure metadata
//!
//! # Export Table Structure
//!
//! The PE export table follows this layout:
//! ```text
//! Export Directory Table
//! ├── DLL Name RVA
//! ├── Base Ordinal
//! ├── Number of Functions
//! ├── Number of Names
//! ├── Export Address Table RVA
//! ├── Export Name Table RVA
//! └── Export Ordinal Table RVA
//!
//! Export Address Table (EAT)
//! ├── Function 1 Address/Forwarder RVA
//! ├── Function 2 Address/Forwarder RVA
//! └── ...
//!
//! Export Name Table
//! ├── Function Name 1 RVA
//! ├── Function Name 2 RVA
//! └── ...
//!
//! Export Ordinal Table
//! ├── Function 1 Ordinal
//! ├── Function 2 Ordinal
//! └── ...
//!
//! Name Strings
//! ├── DLL Name + Null
//! ├── Function Name 1 + Null
//! ├── Function Name 2 + Null
//! └── Forwarder Strings + Null
//! ```
//!
//! # Usage Examples
//!
//! ## Parse Existing Export Table
//!
//! ```rust,ignore
//! use dotscope::metadata::exports::native::NativeExports;
//!
//! let pe_data = std::fs::read("library.dll")?;
//! let native_exports = NativeExports::parse_from_pe(&pe_data)?;
//!
//! // Analyze exported functions
//! for function in native_exports.functions() {
//!     match &function.name {
//!         Some(name) => println!("Export: {} @ ordinal {}", name, function.ordinal),
//!         None => println!("Export: ordinal {} only", function.ordinal),
//!     }
//!
//!     if function.is_forwarder() {
//!         println!("  Forwarded to: {}", function.get_forwarder_target().unwrap());
//!     } else {
//!         println!("  Address: 0x{:X}", function.address);
//!     }
//! }
//! ```
//!
//! ## Create Export Table
//!
//! ```rust,no_run
//! use dotscope::metadata::exports::NativeExports;
//!
//! let mut exports = NativeExports::new("MyLibrary.dll");
//!
//! // Add a regular function export
//! exports.add_function("MyFunction", 1, 0x1000)?;
//!
//! // Add an ordinal-only export
//! exports.add_function_by_ordinal(2, 0x2000)?;
//!
//! // Add a forwarded export
//! exports.add_forwarder("ForwardedFunc", 3, "Other.dll.TargetFunc")?;
//!
//! // Generate export table data
//! let export_data = exports.get_export_table_data()?;
//! # Ok::<(), dotscope::Error>(())
//! ```
//!
//! # Thread Safety
//!
//! All operations on [`NativeExports`] are thread-safe when accessed through shared references.
//! Mutable operations require exclusive access but can be performed concurrently with
//! immutable operations on different instances.
//!
//! # Integration
//!
//! This module integrates with:
//! - [`crate::metadata::exports::UnifiedExportContainer`] - Unified export container combining CIL and native
//! - [`crate::cilassembly::CilAssembly`] - PE writing pipeline for export table generation
//! - [`goblin`] - PE parsing library for export directory analysis

use std::collections::HashMap;

use crate::{
    file::pe::Export,
    utils::{to_u32, write_le_at, write_string_at},
    Result,
};

/// Container for native PE export table data.
///
/// Manages export directory metadata, function exports, and forwarder entries for
/// native DLL exports. Provides functionality for parsing existing export tables
/// from PE files and generating new export table data.
///
/// # Storage Strategy
/// - **Export Directory**: Core metadata including DLL name and table parameters
/// - **Function Exports**: Indexed by ordinal with optional name mapping
/// - **Forwarder Entries**: Export forwarding to external DLL functions
/// - **Name Mapping**: Efficient name-to-ordinal lookup
///
/// # Examples
///
/// ```rust,no_run
/// use dotscope::metadata::exports::NativeExports;
///
/// let mut exports = NativeExports::new("MyLibrary.dll");
///
/// // Add a function export
/// exports.add_function("MyFunction", 1, 0x1000)?;
///
/// // Generate export table
/// let table_data = exports.get_export_table_data()?;
/// println!("Export table size: {} bytes", table_data.len());
/// # Ok::<(), dotscope::Error>(())
/// ```
#[derive(Debug, Clone)]
pub struct NativeExports {
    /// Export directory metadata
    directory: ExportDirectory,

    /// Function exports indexed by ordinal
    functions: HashMap<u16, ExportFunction>,

    /// Export forwarders indexed by ordinal
    forwarders: HashMap<u16, ExportForwarder>,

    /// Name-to-ordinal mapping for efficient lookups
    name_to_ordinal: HashMap<String, u16>,

    /// Next available ordinal for automatic assignment
    next_ordinal: u16,

    /// Base RVA where the export table will be placed
    export_table_base_rva: u32,
}

/// PE export directory structure.
///
/// Contains the core metadata for the export table, including DLL identification,
/// table sizes, and RVA references to the various export tables.
///
/// # PE Format Mapping
/// This structure corresponds to the PE IMAGE_EXPORT_DIRECTORY:
/// - `dll_name`: Name of the DLL containing the exports
/// - `base_ordinal`: Starting ordinal number (usually 1)
/// - `function_count`: Number of entries in Export Address Table
/// - `name_count`: Number of entries in Export Name Table
#[derive(Debug, Clone)]
pub struct ExportDirectory {
    /// Name of the DLL (e.g., "MyLibrary.dll")
    pub dll_name: String,

    /// Base ordinal number (typically 1)
    pub base_ordinal: u16,

    /// Number of functions in Export Address Table
    pub function_count: u32,

    /// Number of names in Export Name Table
    pub name_count: u32,

    /// Timestamp for the export table (usually 0)
    pub timestamp: u32,

    /// Major version number
    pub major_version: u16,

    /// Minor version number
    pub minor_version: u16,
}

/// Individual function export within the export table.
///
/// Represents a single exported function with its ordinal, optional name,
/// and either a function address or forwarder target. Functions can be
/// exported by ordinal only or by both name and ordinal.
///
/// # Export Methods
/// - **By Name**: Uses function name for symbolic resolution
/// - **By Ordinal**: Uses ordinal number for direct address lookup
/// - **Forwarded**: Redirects to function in another DLL
#[derive(Debug, Clone)]
pub struct ExportFunction {
    /// Ordinal number for this export
    pub ordinal: u16,

    /// Function name if exported by name
    pub name: Option<String>,

    /// Function address (RVA) if not forwarded
    pub address: u32,

    /// Whether this export is a forwarder
    pub is_forwarder: bool,
}

/// Export forwarder to another DLL.
///
/// Represents an export that forwards calls to a function in another DLL.
/// The Windows loader resolves forwarders at runtime by loading the target
/// DLL and finding the specified function.
#[derive(Debug, Clone)]
pub struct ExportForwarder {
    /// Ordinal number for this forwarder
    pub ordinal: u16,

    /// Function name if exported by name
    pub name: Option<String>,

    /// Target specification: "DllName.FunctionName" or "DllName.#Ordinal"
    pub target: String,
}

impl NativeExports {
    /// Create a new native exports container.
    ///
    /// Initializes an empty container with the specified DLL name and default
    /// export directory settings. The container starts with base ordinal 1.
    ///
    /// # Arguments
    /// * `dll_name` - Name of the DLL (e.g., "MyLibrary.dll")
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::metadata::exports::NativeExports;
    ///
    /// let exports = NativeExports::new("MyLibrary.dll");
    /// assert!(exports.is_empty());
    /// assert_eq!(exports.dll_name(), "MyLibrary.dll");
    /// assert_eq!(exports.function_count(), 0);
    /// ```
    #[must_use]
    pub fn new(dll_name: &str) -> Self {
        Self {
            directory: ExportDirectory {
                dll_name: dll_name.to_owned(),
                base_ordinal: 1,
                function_count: 0,
                name_count: 0,
                timestamp: 0,
                major_version: 0,
                minor_version: 0,
            },
            functions: HashMap::new(),
            forwarders: HashMap::new(),
            name_to_ordinal: HashMap::new(),
            next_ordinal: 1,
            export_table_base_rva: 0,
        }
    }

    /// Creates native exports from PE export data
    ///
    /// # Arguments
    /// * `pe_exports` - Slice of PE export entries to process
    ///
    /// # Returns
    /// Returns a configured NativeExports instance with all export functions,
    /// forwarders, and internal structures properly initialized.
    ///
    /// # Errors
    /// Returns error if:
    /// - Memory allocation fails during structure creation
    /// - Export data contains invalid or inconsistent information
    /// - Adding functions or forwarders to the directory fails
    ///
    /// # Examples
    /// ```rust,ignore
    /// use dotscope::metadata::exports::NativeExports;
    /// use dotscope::file::pe::Export;
    ///
    /// let pe_exports = vec![
    ///     Export {
    ///         name: Some("MyFunction".to_string()),
    ///         rva: 0x1000,
    ///         offset: Some(1),
    ///     },
    /// ];
    ///
    /// let native_exports = NativeExports::from_pe_exports(&pe_exports).unwrap();
    /// assert!(!native_exports.is_empty());
    /// ```
    pub fn from_pe_exports(pe_exports: &[Export]) -> Result<Self> {
        let mut exports = Self::new(""); // DLL name will be set from first export

        for export in pe_exports {
            let ordinal = u16::try_from(export.offset.unwrap_or(0))
                .map_err(|_| malformed_error!("Export ordinal exceeds u16 range"))?;

            if export.rva == 0 {
                continue; // Skip invalid exports
            }

            // Set DLL name from first export if available
            if exports.directory.dll_name.is_empty() {
                if let Some(ref name) = export.name {
                    exports.directory.dll_name.clone_from(name);
                }
            }

            if let Some(ref name) = export.name {
                // Named export
                exports.add_function(name, ordinal, export.rva)?;
            } else {
                // Ordinal-only export
                exports.add_function_by_ordinal(ordinal, export.rva)?;
            }
        }

        Ok(exports)
    }

    /// Add a function export with name and ordinal.
    ///
    /// Adds a named function export to the export table with the specified
    /// ordinal and function address. The function will be accessible by both
    /// name and ordinal.
    ///
    /// # Arguments
    /// * `name` - Name of the exported function
    /// * `ordinal` - Ordinal number for the export
    /// * `address` - Function address (RVA)
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::metadata::exports::NativeExports;
    ///
    /// let mut exports = NativeExports::new("MyLibrary.dll");
    /// exports.add_function("MyFunction", 1, 0x1000)?;
    /// exports.add_function("AnotherFunc", 2, 0x2000)?;
    ///
    /// assert_eq!(exports.function_count(), 2);
    /// assert!(exports.has_function("MyFunction"));
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The function name is empty
    /// - The ordinal is already in use
    /// - The function name is already exported
    /// - The ordinal is 0 (invalid)
    pub fn add_function(&mut self, name: &str, ordinal: u16, address: u32) -> Result<()> {
        if name.is_empty() {
            return Err(malformed_error!("Function name cannot be empty"));
        }

        if ordinal == 0 {
            return Err(malformed_error!("Ordinal cannot be 0"));
        }

        // Check for conflicts
        if self.functions.contains_key(&ordinal) || self.forwarders.contains_key(&ordinal) {
            return Err(malformed_error!("Ordinal {ordinal} is already in use"));
        }

        if self.name_to_ordinal.contains_key(name) {
            return Err(malformed_error!(
                "Function name '{name}' is already exported"
            ));
        }

        // Create function export
        let function = ExportFunction {
            ordinal,
            name: Some(name.to_owned()),
            address,
            is_forwarder: false,
        };

        // Update mappings
        self.functions.insert(ordinal, function);
        self.name_to_ordinal.insert(name.to_owned(), ordinal);

        // Update directory metadata
        self.directory.function_count = to_u32(self.functions.len())?;
        self.directory.name_count = to_u32(self.name_to_ordinal.len())?;

        // Update next ordinal
        if ordinal >= self.next_ordinal {
            self.next_ordinal = ordinal + 1;
        }

        Ok(())
    }

    /// Add a function export by ordinal only.
    ///
    /// Adds a function export that is accessible by ordinal number only,
    /// without a symbolic name. This can be more efficient but is less
    /// portable across DLL versions.
    ///
    /// # Arguments
    /// * `ordinal` - Ordinal number for the export
    /// * `address` - Function address (RVA)
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::metadata::exports::NativeExports;
    ///
    /// let mut exports = NativeExports::new("MyLibrary.dll");
    /// exports.add_function_by_ordinal(1, 0x1000)?;
    /// exports.add_function_by_ordinal(2, 0x2000)?;
    ///
    /// assert_eq!(exports.function_count(), 2);
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The ordinal is already in use
    /// - The ordinal is 0 (invalid)
    pub fn add_function_by_ordinal(&mut self, ordinal: u16, address: u32) -> Result<()> {
        if ordinal == 0 {
            return Err(malformed_error!("Ordinal cannot be 0"));
        }

        // Check for conflicts
        if self.functions.contains_key(&ordinal) || self.forwarders.contains_key(&ordinal) {
            return Err(malformed_error!("Ordinal {ordinal} is already in use"));
        }

        // Create function export
        let function = ExportFunction {
            ordinal,
            name: None,
            address,
            is_forwarder: false,
        };

        // Update mappings
        self.functions.insert(ordinal, function);

        // Update directory metadata
        self.directory.function_count = to_u32(self.functions.len())?;

        // Update next ordinal
        if ordinal >= self.next_ordinal {
            self.next_ordinal = ordinal + 1;
        }

        Ok(())
    }

    /// Add an export forwarder.
    ///
    /// Adds a function export that forwards calls to a function in another DLL.
    /// The target specification can be either "DllName.FunctionName" or
    /// "DllName.#Ordinal" for ordinal-based forwarding.
    ///
    /// # Arguments
    /// * `name` - Name of the exported function (can be empty for ordinal-only)
    /// * `ordinal` - Ordinal number for the export
    /// * `target` - Target specification: "DllName.FunctionName" or "DllName.#Ordinal"
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::metadata::exports::NativeExports;
    ///
    /// let mut exports = NativeExports::new("MyLibrary.dll");
    ///
    /// // Forward by name
    /// exports.add_forwarder("ForwardedFunc", 1, "kernel32.dll.GetCurrentProcessId")?;
    ///
    /// // Forward by ordinal
    /// exports.add_forwarder("AnotherForward", 2, "user32.dll.#120")?;
    ///
    /// assert_eq!(exports.forwarder_count(), 2);
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The ordinal is already in use
    /// - The function name is already exported (if name is provided)
    /// - The target specification is empty
    /// - The ordinal is 0 (invalid)
    pub fn add_forwarder(&mut self, name: &str, ordinal: u16, target: &str) -> Result<()> {
        if ordinal == 0 {
            return Err(malformed_error!("Ordinal cannot be 0"));
        }

        if target.is_empty() {
            return Err(malformed_error!("Forwarder target cannot be empty"));
        }

        if !target.contains('.') {
            return Err(malformed_error!(
                "Forwarder target '{}' must be in format 'DllName.FunctionName' or 'DllName.#Ordinal'",
                target
            ));
        }

        if target.contains('\0') {
            return Err(malformed_error!(
                "Forwarder target cannot contain null bytes"
            ));
        }

        if self.functions.contains_key(&ordinal) || self.forwarders.contains_key(&ordinal) {
            return Err(malformed_error!("Ordinal {ordinal} is already in use"));
        }

        if !name.is_empty() && self.name_to_ordinal.contains_key(name) {
            return Err(malformed_error!(
                "Function name '{name}' is already exported"
            ));
        }

        let forwarder = ExportForwarder {
            ordinal,
            name: if name.is_empty() {
                None
            } else {
                Some(name.to_owned())
            },
            target: target.to_owned(),
        };

        self.forwarders.insert(ordinal, forwarder);

        if !name.is_empty() {
            self.name_to_ordinal.insert(name.to_owned(), ordinal);
        }

        self.directory.function_count = to_u32(self.functions.len() + self.forwarders.len())?;
        self.directory.name_count = to_u32(self.name_to_ordinal.len())?;

        if ordinal >= self.next_ordinal {
            self.next_ordinal = ordinal + 1;
        }

        Ok(())
    }

    /// Get the DLL name.
    ///
    /// Returns the name of the DLL that contains these exports.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::metadata::exports::NativeExports;
    ///
    /// let exports = NativeExports::new("MyLibrary.dll");
    /// assert_eq!(exports.dll_name(), "MyLibrary.dll");
    /// ```
    #[must_use]
    pub fn dll_name(&self) -> &str {
        &self.directory.dll_name
    }

    /// Get the number of function exports.
    ///
    /// Returns the total count of function exports, including both regular
    /// functions and forwarders.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::metadata::exports::NativeExports;
    ///
    /// let exports = NativeExports::new("MyLibrary.dll");
    /// assert_eq!(exports.function_count(), 0);
    /// ```
    #[must_use]
    pub fn function_count(&self) -> usize {
        self.functions.len() + self.forwarders.len()
    }

    /// Get the number of forwarder exports.
    ///
    /// Returns the count of export forwarders to other DLLs.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::metadata::exports::NativeExports;
    ///
    /// let exports = NativeExports::new("MyLibrary.dll");
    /// assert_eq!(exports.forwarder_count(), 0);
    /// ```
    #[must_use]
    pub fn forwarder_count(&self) -> usize {
        self.forwarders.len()
    }

    /// Check if the export table is empty.
    ///
    /// Returns `true` if no functions or forwarders have been added.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::metadata::exports::NativeExports;
    ///
    /// let exports = NativeExports::new("MyLibrary.dll");
    /// assert!(exports.is_empty());
    /// ```
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.functions.is_empty() && self.forwarders.is_empty()
    }

    /// Check if a function is exported.
    ///
    /// Returns `true` if the specified function name is exported.
    ///
    /// # Arguments
    /// * `name` - Name of the function to check
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::metadata::exports::NativeExports;
    ///
    /// let mut exports = NativeExports::new("MyLibrary.dll");
    /// exports.add_function("MyFunction", 1, 0x1000)?;
    ///
    /// assert!(exports.has_function("MyFunction"));
    /// assert!(!exports.has_function("MissingFunction"));
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    #[must_use]
    pub fn has_function(&self, name: &str) -> bool {
        self.name_to_ordinal.contains_key(name)
    }

    /// Get a function export by ordinal.
    ///
    /// Returns a reference to the function export with the specified ordinal,
    /// or `None` if no function exists with that ordinal.
    ///
    /// # Arguments
    /// * `ordinal` - Ordinal number to find
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::metadata::exports::NativeExports;
    ///
    /// let mut exports = NativeExports::new("MyLibrary.dll");
    /// exports.add_function("MyFunction", 1, 0x1000)?;
    ///
    /// let function = exports.get_function_by_ordinal(1);
    /// assert!(function.is_some());
    /// assert_eq!(function.unwrap().ordinal, 1);
    ///
    /// let missing = exports.get_function_by_ordinal(99);
    /// assert!(missing.is_none());
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    #[must_use]
    pub fn get_function_by_ordinal(&self, ordinal: u16) -> Option<&ExportFunction> {
        self.functions.get(&ordinal)
    }

    /// Get a forwarder export by ordinal.
    ///
    /// Returns a reference to the forwarder export with the specified ordinal,
    /// or `None` if no forwarder exists with that ordinal.
    ///
    /// # Arguments
    /// * `ordinal` - Ordinal number to find
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::metadata::exports::NativeExports;
    ///
    /// let mut exports = NativeExports::new("MyLibrary.dll");
    /// exports.add_forwarder("ForwardedFunc", 1, "kernel32.dll.GetCurrentProcessId")?;
    ///
    /// let forwarder = exports.get_forwarder_by_ordinal(1);
    /// assert!(forwarder.is_some());
    /// assert_eq!(forwarder.unwrap().target, "kernel32.dll.GetCurrentProcessId");
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    #[must_use]
    pub fn get_forwarder_by_ordinal(&self, ordinal: u16) -> Option<&ExportForwarder> {
        self.forwarders.get(&ordinal)
    }

    /// Get an ordinal by function name.
    ///
    /// Returns the ordinal number for the specified function name,
    /// or `None` if the function is not exported.
    ///
    /// # Arguments
    /// * `name` - Name of the function to find
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::metadata::exports::NativeExports;
    ///
    /// let mut exports = NativeExports::new("MyLibrary.dll");
    /// exports.add_function("MyFunction", 5, 0x1000)?;
    ///
    /// let ordinal = exports.get_ordinal_by_name("MyFunction");
    /// assert_eq!(ordinal, Some(5));
    ///
    /// let missing = exports.get_ordinal_by_name("MissingFunction");
    /// assert_eq!(missing, None);
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    #[must_use]
    pub fn get_ordinal_by_name(&self, name: &str) -> Option<u16> {
        self.name_to_ordinal.get(name).copied()
    }

    /// Get all function exports.
    ///
    /// Returns an iterator over all function exports in the table.
    /// The order is not guaranteed to be consistent.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::metadata::exports::{NativeExports, ExportFunction};
    ///
    /// let mut exports = NativeExports::new("MyLibrary.dll");
    /// exports.add_function("Function1", 1, 0x1000)?;
    /// exports.add_function("Function2", 2, 0x2000)?;
    ///
    /// let functions: Vec<&ExportFunction> = exports.functions().collect();
    /// assert_eq!(functions.len(), 2);
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn functions(&self) -> impl Iterator<Item = &ExportFunction> {
        self.functions.values()
    }

    /// Get all forwarder exports.
    ///
    /// Returns an iterator over all forwarder exports in the table.
    /// The order is not guaranteed to be consistent.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use dotscope::metadata::exports::NativeExports;
    /// use dotscope::metadata::exports::native::ExportForwarder;
    ///
    /// let mut exports = NativeExports::new("MyLibrary.dll");
    /// exports.add_forwarder("Forwarder1", 1, "kernel32.dll.Function1")?;
    /// exports.add_forwarder("Forwarder2", 2, "user32.dll.Function2")?;
    ///
    /// let forwarders: Vec<&ExportForwarder> = exports.forwarders().collect();
    /// assert_eq!(forwarders.len(), 2);
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn forwarders(&self) -> impl Iterator<Item = &ExportForwarder> {
        self.forwarders.values()
    }

    /// Get all exported function names.
    ///
    /// Returns a vector of all function names that are exported.
    /// The order is not guaranteed to be consistent.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::metadata::exports::NativeExports;
    ///
    /// let mut exports = NativeExports::new("MyLibrary.dll");
    /// exports.add_function("Function1", 1, 0x1000)?;
    /// exports.add_function("Function2", 2, 0x2000)?;
    ///
    /// let names = exports.get_exported_function_names();
    /// assert_eq!(names.len(), 2);
    /// assert!(names.contains(&"Function1".to_string()));
    /// assert!(names.contains(&"Function2".to_string()));
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    #[must_use]
    pub fn get_exported_function_names(&self) -> Vec<String> {
        self.name_to_ordinal.keys().cloned().collect()
    }

    /// Generate export table data for PE writing.
    ///
    /// Creates the complete export table structure including export directory,
    /// Export Address Table (EAT), Export Name Table, Export Ordinal Table,
    /// and name strings. The returned data can be written directly to a PE
    /// file's export section.
    ///
    /// # Returns
    ///
    /// A vector containing the complete export table data in PE format, or an
    /// empty vector if no exports are present.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::metadata::exports::NativeExports;
    ///
    /// let mut exports = NativeExports::new("MyLibrary.dll");
    /// exports.add_function("MyFunction", 1, 0x1000)?;
    ///
    /// let table_data = exports.get_export_table_data()?;
    /// assert!(!table_data.is_empty());
    /// println!("Export table size: {} bytes", table_data.len());
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    ///
    /// # Table Layout
    ///
    /// The generated data follows this structure:
    /// 1. Export Directory (40 bytes)
    /// 2. Export Address Table (4 bytes per function)
    /// 3. Export Name Table (4 bytes per named export)
    /// 4. Export Ordinal Table (2 bytes per named export)
    /// 5. DLL name string
    /// 6. Function name strings
    /// 7. Forwarder target strings
    ///
    /// # Errors
    ///
    /// Returns an error if the export table base RVA has not been set or if
    /// data encoding fails during table generation.
    pub fn get_export_table_data(&self) -> Result<Vec<u8>> {
        if self.is_empty() {
            return Ok(Vec::new());
        }

        let base_rva = self.export_table_base_rva;
        if base_rva == 0 {
            return Err(malformed_error!("Export table base RVA not set"));
        }
        self.get_export_table_data_with_base_rva(base_rva)
    }

    /// Generate export table data for PE writing with a specified base RVA.
    ///
    /// This is the same as [`get_export_table_data`](Self::get_export_table_data)
    /// but allows specifying the base RVA for all internal RVA calculations.
    /// This is useful when the export table location is calculated dynamically
    /// during PE file layout.
    ///
    /// # Arguments
    /// * `base_rva` - The RVA where the export table will be placed in the final PE file
    ///
    /// # Returns
    ///
    /// A vector containing the complete export table data in PE format, or an
    /// empty vector if no exports are present.
    ///
    /// # Errors
    ///
    /// Returns an error if the export table data cannot be serialized due to
    /// invalid ordinal ranges or buffer allocation failures.
    pub fn get_export_table_data_with_base_rva(&self, base_rva: u32) -> Result<Vec<u8>> {
        if self.is_empty() {
            return Ok(Vec::new());
        }

        // Calculate table sizes and offsets
        let export_dir_size = 40u32; // sizeof(IMAGE_EXPORT_DIRECTORY)

        // Calculate the ordinal range we need to cover
        let mut min_ordinal = u16::MAX;
        let mut max_ordinal = 0u16;
        for &ordinal in self.functions.keys().chain(self.forwarders.keys()) {
            if ordinal < min_ordinal {
                min_ordinal = ordinal;
            }
            if ordinal > max_ordinal {
                max_ordinal = ordinal;
            }
        }

        // EAT must cover from base_ordinal to highest ordinal
        let eat_entry_count = if max_ordinal >= self.directory.base_ordinal {
            u32::from(max_ordinal - self.directory.base_ordinal + 1)
        } else {
            0
        };

        let eat_size = eat_entry_count * 4; // 4 bytes per address
        let name_table_size = self.directory.name_count * 4; // 4 bytes per name RVA
        let ordinal_table_size = self.directory.name_count * 2; // 2 bytes per ordinal

        let eat_rva = base_rva + export_dir_size;
        let name_table_rva = eat_rva + eat_size;
        let ordinal_table_rva = name_table_rva + name_table_size;
        let strings_rva = ordinal_table_rva + ordinal_table_size;

        // Calculate total size needed for strings
        let mut total_strings_size = self.directory.dll_name.len() + 1; // DLL name + null
        for name in self.name_to_ordinal.keys() {
            total_strings_size += name.len() + 1; // name + null
        }
        for forwarder in self.forwarders.values() {
            total_strings_size += forwarder.target.len() + 1; // target + null
        }

        let total_size = export_dir_size
            + eat_size
            + name_table_size
            + ordinal_table_size
            + to_u32(total_strings_size)?;
        let mut data = vec![0u8; total_size as usize];
        let mut offset = 0;

        // Write Export Directory (IMAGE_EXPORT_DIRECTORY structure)
        write_le_at(&mut data, &mut offset, 0u32)?; // Characteristics (reserved)
        write_le_at(&mut data, &mut offset, self.directory.timestamp)?; // TimeDateStamp
        write_le_at(&mut data, &mut offset, self.directory.major_version)?; // MajorVersion
        write_le_at(&mut data, &mut offset, self.directory.minor_version)?; // MinorVersion
        write_le_at(&mut data, &mut offset, strings_rva)?; // Name RVA (DLL name)
        write_le_at(
            &mut data,
            &mut offset,
            u32::from(self.directory.base_ordinal),
        )?; // Base ordinal
        write_le_at(&mut data, &mut offset, eat_entry_count)?; // NumberOfFunctions
        write_le_at(&mut data, &mut offset, self.directory.name_count)?; // NumberOfNames
        write_le_at(&mut data, &mut offset, eat_rva)?; // AddressOfFunctions (EAT RVA)
        write_le_at(&mut data, &mut offset, name_table_rva)?; // AddressOfNames (Export Name Table RVA)
        write_le_at(&mut data, &mut offset, ordinal_table_rva)?; // AddressOfNameOrdinals (Export Ordinal Table RVA)

        // Build sorted lists for consistent output
        let mut named_exports: Vec<(&String, u16)> = self
            .name_to_ordinal
            .iter()
            .map(|(name, &ordinal)| (name, ordinal))
            .collect();
        named_exports.sort_by_key(|(name, _)| name.as_str());

        // Calculate string offsets for forwarders
        let mut forwarder_string_offsets = HashMap::new();
        let mut current_forwarder_offset = self.directory.dll_name.len() + 1; // After DLL name
        for (name, _) in &named_exports {
            current_forwarder_offset += name.len() + 1; // +1 for null terminator
        }
        for forwarder in self.forwarders.values() {
            forwarder_string_offsets.insert(forwarder.ordinal, current_forwarder_offset);
            current_forwarder_offset += forwarder.target.len() + 1;
        }

        // Write Export Address Table (EAT)
        // Fill with zeros first, then populate known entries
        let eat_start_offset = offset;
        for _ in 0..eat_entry_count {
            write_le_at(&mut data, &mut offset, 0u32)?;
        }

        // Go back and populate known entries
        let mut temp_offset = eat_start_offset;
        for ordinal_index in 0..eat_entry_count {
            #[allow(clippy::cast_possible_truncation)]
            let ordinal = self.directory.base_ordinal + (ordinal_index as u16);

            if let Some(function) = self.functions.get(&ordinal) {
                // Regular function - write address
                data[temp_offset..temp_offset + 4].copy_from_slice(&function.address.to_le_bytes());
            } else if let Some(_forwarder) = self.forwarders.get(&ordinal) {
                // Forwarder - write RVA to forwarder string
                if let Some(&string_offset) = forwarder_string_offsets.get(&ordinal) {
                    let forwarder_rva = strings_rva + to_u32(string_offset)?;
                    data[temp_offset..temp_offset + 4]
                        .copy_from_slice(&forwarder_rva.to_le_bytes());
                }
            }
            // Otherwise leave as 0 (no function at this ordinal)

            temp_offset += 4;
        }

        // Write Export Name Table
        let mut name_string_offset = self.directory.dll_name.len() + 1; // After DLL name
        for (name, _) in &named_exports {
            let name_rva = strings_rva + to_u32(name_string_offset)?;
            write_le_at(&mut data, &mut offset, name_rva)?;
            name_string_offset += name.len() + 1; // +1 for null terminator
        }

        // Write Export Ordinal Table
        for (_, ordinal) in &named_exports {
            let adjusted_ordinal = ordinal - self.directory.base_ordinal;
            write_le_at(&mut data, &mut offset, adjusted_ordinal)?;
        }

        // Write strings
        // DLL name
        write_string_at(&mut data, &mut offset, &self.directory.dll_name)?;

        // Function names (in alphabetical order)
        for (name, _ordinal) in &named_exports {
            write_string_at(&mut data, &mut offset, name)?;
        }

        // Forwarder strings
        for forwarder in self.forwarders.values() {
            write_string_at(&mut data, &mut offset, &forwarder.target)?;
        }

        Ok(data)
    }

    /// Set the base RVA for the export table.
    ///
    /// Sets the RVA where the export table will be placed in the final PE file.
    /// This is used to calculate proper RVAs for all export table components.
    ///
    /// # Arguments
    /// * `base_rva` - The RVA where the export table will be placed in the final PE file
    pub fn set_export_table_base_rva(&mut self, base_rva: u32) {
        self.export_table_base_rva = base_rva;
    }

    /// Set the DLL name for the export directory.
    ///
    /// Updates the DLL name used in the PE export directory. This is the name
    /// that will appear in the export table when the PE file is written.
    ///
    /// # Arguments
    /// * `dll_name` - New DLL name to use (e.g., "MyLibrary.dll")
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::metadata::exports::NativeExports;
    ///
    /// let mut exports = NativeExports::new("OldName.dll");
    /// assert_eq!(exports.dll_name(), "OldName.dll");
    ///
    /// exports.set_dll_name("NewName.dll").unwrap();
    /// assert_eq!(exports.dll_name(), "NewName.dll");
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if the DLL name is empty or contains invalid characters.
    pub fn set_dll_name(&mut self, dll_name: &str) -> Result<()> {
        if dll_name.is_empty() {
            return Err(malformed_error!("DLL name cannot be empty"));
        }

        if dll_name.contains('\0') {
            return Err(malformed_error!("DLL name cannot contain null bytes"));
        }

        dll_name.clone_into(&mut self.directory.dll_name);
        Ok(())
    }

    /// Get the export directory.
    ///
    /// Returns a reference to the export directory metadata.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::metadata::exports::NativeExports;
    ///
    /// let exports = NativeExports::new("MyLibrary.dll");
    /// let directory = exports.directory();
    /// assert_eq!(directory.dll_name, "MyLibrary.dll");
    /// assert_eq!(directory.base_ordinal, 1);
    /// ```
    #[must_use]
    pub fn directory(&self) -> &ExportDirectory {
        &self.directory
    }
}

impl ExportFunction {
    /// Check if this export is a forwarder.
    ///
    /// Returns `true` if this function export forwards calls to another DLL.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::metadata::exports::ExportFunction;
    ///
    /// let function = ExportFunction {
    ///     ordinal: 1,
    ///     name: Some("MyFunction".to_string()),
    ///     address: 0x1000,
    ///     is_forwarder: false,
    /// };
    ///
    /// assert!(!function.is_forwarder());
    /// ```
    #[must_use]
    pub fn is_forwarder(&self) -> bool {
        self.is_forwarder
    }
}

impl Default for NativeExports {
    fn default() -> Self {
        Self::new("Unknown.dll")
    }
}

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

    #[test]
    fn new_native_exports_is_empty() {
        let exports = NativeExports::new("Test.dll");
        assert!(exports.is_empty());
        assert_eq!(exports.function_count(), 0);
        assert_eq!(exports.forwarder_count(), 0);
        assert_eq!(exports.dll_name(), "Test.dll");
    }

    #[test]
    fn add_function_works() {
        let mut exports = NativeExports::new("Test.dll");

        exports.add_function("MyFunction", 1, 0x1000).unwrap();
        assert!(!exports.is_empty());
        assert_eq!(exports.function_count(), 1);
        assert!(exports.has_function("MyFunction"));

        let function = exports.get_function_by_ordinal(1).unwrap();
        assert_eq!(function.name, Some("MyFunction".to_string()));
        assert_eq!(function.address, 0x1000);
        assert!(!function.is_forwarder());
    }

    #[test]
    fn add_function_with_empty_name_fails() {
        let mut exports = NativeExports::new("Test.dll");

        let result = exports.add_function("", 1, 0x1000);
        assert!(result.is_err());
    }

    #[test]
    fn add_function_with_zero_ordinal_fails() {
        let mut exports = NativeExports::new("Test.dll");

        let result = exports.add_function("MyFunction", 0, 0x1000);
        assert!(result.is_err());
    }

    #[test]
    fn add_duplicate_function_name_fails() {
        let mut exports = NativeExports::new("Test.dll");

        exports.add_function("MyFunction", 1, 0x1000).unwrap();
        let result = exports.add_function("MyFunction", 2, 0x2000);
        assert!(result.is_err());
    }

    #[test]
    fn add_duplicate_ordinal_fails() {
        let mut exports = NativeExports::new("Test.dll");

        exports.add_function("Function1", 1, 0x1000).unwrap();
        let result = exports.add_function("Function2", 1, 0x2000);
        assert!(result.is_err());
    }

    #[test]
    fn add_function_by_ordinal_works() {
        let mut exports = NativeExports::new("Test.dll");

        exports.add_function_by_ordinal(1, 0x1000).unwrap();
        assert_eq!(exports.function_count(), 1);

        let function = exports.get_function_by_ordinal(1).unwrap();
        assert_eq!(function.name, None);
        assert_eq!(function.address, 0x1000);
    }

    #[test]
    fn add_forwarder_works() {
        let mut exports = NativeExports::new("Test.dll");

        exports
            .add_forwarder("ForwardedFunc", 1, "kernel32.dll.GetCurrentProcessId")
            .unwrap();
        assert_eq!(exports.function_count(), 1);
        assert_eq!(exports.forwarder_count(), 1);
        assert!(exports.has_function("ForwardedFunc"));

        let forwarder = exports.get_forwarder_by_ordinal(1).unwrap();
        assert_eq!(forwarder.name, Some("ForwardedFunc".to_string()));
        assert_eq!(forwarder.target, "kernel32.dll.GetCurrentProcessId");
    }

    #[test]
    fn add_forwarder_with_empty_target_fails() {
        let mut exports = NativeExports::new("Test.dll");

        let result = exports.add_forwarder("ForwardedFunc", 1, "");
        assert!(result.is_err());
    }

    #[test]
    fn get_ordinal_by_name_works() {
        let mut exports = NativeExports::new("Test.dll");

        exports.add_function("Function1", 5, 0x1000).unwrap();
        exports
            .add_forwarder("Function2", 10, "kernel32.dll.SomeFunc")
            .unwrap();

        assert_eq!(exports.get_ordinal_by_name("Function1"), Some(5));
        assert_eq!(exports.get_ordinal_by_name("Function2"), Some(10));
        assert_eq!(exports.get_ordinal_by_name("MissingFunction"), None);
    }

    #[test]
    fn get_exported_function_names_works() {
        let mut exports = NativeExports::new("Test.dll");

        exports.add_function("Function1", 1, 0x1000).unwrap();
        exports.add_function("Function2", 2, 0x2000).unwrap();
        exports.add_function_by_ordinal(3, 0x3000).unwrap(); // No name

        let names = exports.get_exported_function_names();
        assert_eq!(names.len(), 2);
        assert!(names.contains(&"Function1".to_string()));
        assert!(names.contains(&"Function2".to_string()));
    }

    #[test]
    fn get_export_table_data_empty_returns_empty() {
        let exports = NativeExports::new("Test.dll");
        let data = exports.get_export_table_data().unwrap();
        assert!(data.is_empty());
    }

    #[test]
    fn get_export_table_data_without_base_rva_fails() {
        let mut exports = NativeExports::new("Test.dll");
        exports.add_function("MyFunction", 1, 0x1000).unwrap();

        let result = exports.get_export_table_data();
        assert!(result.is_err());
    }

    #[test]
    fn get_export_table_data_with_exports_returns_data() {
        let mut exports = NativeExports::new("Test.dll");
        exports.set_export_table_base_rva(0x3000);

        exports.add_function("MyFunction", 1, 0x1000).unwrap();

        let data = exports.get_export_table_data().unwrap();
        assert!(!data.is_empty());
        assert!(data.len() >= 40); // At least export directory size
    }

    #[test]
    fn function_iteration_works() {
        let mut exports = NativeExports::new("Test.dll");

        exports.add_function("Function1", 1, 0x1000).unwrap();
        exports.add_function("Function2", 2, 0x2000).unwrap();

        let functions: Vec<&ExportFunction> = exports.functions().collect();
        assert_eq!(functions.len(), 2);
    }

    #[test]
    fn forwarder_iteration_works() {
        let mut exports = NativeExports::new("Test.dll");

        exports
            .add_forwarder("Forwarder1", 1, "kernel32.dll.Func1")
            .unwrap();
        exports
            .add_forwarder("Forwarder2", 2, "user32.dll.Func2")
            .unwrap();

        let forwarders: Vec<&ExportForwarder> = exports.forwarders().collect();
        assert_eq!(forwarders.len(), 2);
    }

    #[test]
    fn mixed_functions_and_forwarders() {
        let mut exports = NativeExports::new("Test.dll");

        exports.add_function("RegularFunc", 1, 0x1000).unwrap();
        exports
            .add_forwarder("ForwardedFunc", 2, "kernel32.dll.GetTick")
            .unwrap();
        exports.add_function_by_ordinal(3, 0x3000).unwrap();

        assert_eq!(exports.function_count(), 3); // Total including forwarders
        assert_eq!(exports.forwarders().count(), 1); // Just forwarders
        assert_eq!(exports.functions().count(), 2); // Just regular functions

        let names = exports.get_exported_function_names();
        assert_eq!(names.len(), 2); // Only named exports
    }

    #[test]
    fn set_dll_name_works() {
        let mut exports = NativeExports::new("OldName.dll");
        assert_eq!(exports.dll_name(), "OldName.dll");

        exports.set_dll_name("NewName.dll").unwrap();
        assert_eq!(exports.dll_name(), "NewName.dll");

        // Check that directory is also updated
        assert_eq!(exports.directory().dll_name, "NewName.dll");
    }

    #[test]
    fn set_dll_name_empty_fails() {
        let mut exports = NativeExports::new("Original.dll");
        let result = exports.set_dll_name("");
        assert!(result.is_err());

        // Original name should be unchanged
        assert_eq!(exports.dll_name(), "Original.dll");
    }

    #[test]
    fn set_dll_name_with_null_byte_fails() {
        let mut exports = NativeExports::new("Original.dll");
        let result = exports.set_dll_name("Invalid\0Name.dll");
        assert!(result.is_err());

        // Original name should be unchanged
        assert_eq!(exports.dll_name(), "Original.dll");
    }

    #[test]
    fn add_forwarder_invalid_format_fails() {
        let mut exports = NativeExports::new("Test.dll");

        // Missing dot separator
        let result = exports.add_forwarder("BadForward", 1, "kernel32GetTick");
        assert!(result.is_err());

        // Should have no forwarders
        assert_eq!(exports.forwarder_count(), 0);
    }

    #[test]
    fn add_forwarder_with_null_byte_fails() {
        let mut exports = NativeExports::new("Test.dll");

        let result = exports.add_forwarder("BadForward", 1, "kernel32\0.dll.GetTick");
        assert!(result.is_err());

        // Should have no forwarders
        assert_eq!(exports.forwarder_count(), 0);
    }

    #[test]
    fn add_forwarder_valid_formats() {
        let mut exports = NativeExports::new("Test.dll");

        // Valid format: DllName.FunctionName
        exports
            .add_forwarder("Forward1", 1, "kernel32.dll.GetCurrentProcessId")
            .unwrap();

        // Valid format: DllName.#Ordinal
        exports
            .add_forwarder("Forward2", 2, "user32.dll.#120")
            .unwrap();

        // Valid format: Simple name.function
        exports.add_forwarder("Forward3", 3, "api.Func").unwrap();

        assert_eq!(exports.forwarder_count(), 3);
    }
}