dotscope 0.6.0

A high-performance, cross-platform framework for analyzing and reverse engineering .NET PE executables
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
//! Custom attribute blob parsing implementation for .NET metadata.
//!
//! This module provides robust parsing of custom attribute blob data according to the
//! ECMA-335 II.23.3 `CustomAttribute` signature specification. It implements the documented
//! `CorSerializationType` enumeration for accurate .NET runtime-compliant parsing with
//! comprehensive error handling and graceful degradation strategies.
//!
//! # Architecture
//!
//! The parsing architecture follows established patterns from other metadata parsers
//! in the codebase, providing structured and reliable custom attribute processing:
//!
//! ## Core Components
//!
//! - **Fixed Arguments**: Type-aware parsing based on constructor parameter types (CilFlavor-based)
//! - **Named Arguments**: Explicit `CorSerializationType` tag parsing from blob data
//! - **Iterative Design**: Stack-based iterative parsing with depth limiting for complex types
//! - **Enum Support**: Uses `SERIALIZATION_TYPE` constants for documented .NET types
//!
//! ## Error Handling Strategy
//!
//! - **Graceful Degradation**: Falls back to safer parsing when type resolution fails
//! - **Heuristic Enum Detection**: Uses inheritance analysis and name patterns for external types
//! - **Error Recovery**: Continues parsing despite unknown or malformed data sections
//! - **Future-Proof Design**: Ready for multi-assembly loading while working with current single-assembly model
//!
//! # Key Components
//!
//! - [`crate::metadata::customattributes::parser::CustomAttributeParser`] - Main parser implementation
//! - [`crate::metadata::customattributes::parser::parse_custom_attribute_blob`] - Blob heap parsing
//! - [`crate::metadata::customattributes::parser::parse_custom_attribute_data`] - Raw data parsing
//! - [`crate::metadata::customattributes::types::SERIALIZATION_TYPE`] - Type tag constants
//!
//! # Usage Examples
//!
//! ## Parsing from Blob Heap
//!
//! ```rust,no_run
//! use dotscope::metadata::customattributes::parse_custom_attribute_blob;
//! use dotscope::CilObject;
//!
//! let assembly = CilObject::from_path("tests/samples/WindowsBase.dll")?;
//!
//! # fn get_custom_attribute_data() -> (u32, std::sync::Arc<boxcar::Vec<dotscope::metadata::tables::ParamRc>>) { todo!() }
//! let (blob_index, constructor_params) = get_custom_attribute_data();
//!
//! if let Some(blob_heap) = assembly.blob() {
//!     let custom_attr = parse_custom_attribute_blob(blob_heap, blob_index, &constructor_params)?;
//!
//!     println!("Fixed arguments: {}", custom_attr.fixed_args.len());
//!     println!("Named arguments: {}", custom_attr.named_args.len());
//! }
//! # Ok::<(), dotscope::Error>(())
//! ```
//!
//! ## Parsing Raw Blob Data
//!
//! ```rust,no_run
//! use dotscope::metadata::customattributes::{parse_custom_attribute_data, CustomAttributeArgument};
//!
//! # fn get_constructor_params() -> std::sync::Arc<boxcar::Vec<dotscope::metadata::tables::ParamRc>> { todo!() }
//! let constructor_params = get_constructor_params();
//!
//! // Example: Simple custom attribute with string argument
//! let blob_data = &[
//!     0x01, 0x00,                     // Prolog (0x0001)
//!     0x05,                           // String length
//!     0x48, 0x65, 0x6C, 0x6C, 0x6F,   // "Hello" (UTF-8)
//!     0x00, 0x00,                     // Named argument count (0)
//! ];
//!
//! let result = parse_custom_attribute_data(blob_data, &constructor_params)?;
//!
//! // Access parsed arguments
//! match &result.fixed_args[0] {
//!     CustomAttributeArgument::String(s) => println!("String argument: '{}'", s),
//!     _ => println!("Unexpected argument type"),
//! }
//!
//! println!("Named arguments: {}", result.named_args.len());
//! # Ok::<(), dotscope::Error>(())
//! ```
//!
//! # Thread Safety
//!
//! All functions in this module are thread-safe and stateless. The parser implementation
//! can be called concurrently from multiple threads as it operates only on immutable
//! input data and produces owned output structures.
//!
//! # Integration
//!
//! This module integrates with:
//! - [`crate::metadata::customattributes::types`] - Type definitions and argument structures
//! - [`crate::metadata::streams::Blob`] - Blob heap access for custom attribute data
//! - [`crate::metadata::tables`] - Parameter resolution for constructor type information
//! - [`crate::metadata::typesystem`] - Type system integration for `CilFlavor` handling
//!
//! # Implementation Features
//!
//! ## Current Capabilities
//! - **Single Assembly Scope**: Optimized for current single-assembly analysis model
//! - **Type Resolution**: Full support for resolved constructor parameter types
//! - **Graceful Fallbacks**: Heuristic parsing when full type information unavailable
//! - **Comprehensive Validation**: ECMA-335 compliance with detailed error reporting
//! - **Iterative Processing**: Stack-based parsing supporting arbitrarily deep nesting
//!
//! ## Future Enhancements
//! - **Multi-Assembly Support**: Planned project-style loading with cross-assembly resolution
//! - **External Type Loading**: Default `windows_dll` directory for common .NET assemblies
//! - **Enhanced Inheritance**: Full inheritance chain analysis for enum detection
//!
//! # Standards Compliance
//!
//! - **ECMA-335**: Full compliance with custom attribute specification (II.23.3)
//! - **Type Safety**: Robust type checking and validation throughout parsing
//! - **Memory Safety**: Comprehensive bounds checking and nesting depth limiting
//! - **Error Handling**: Detailed error messages for debugging malformed data

use crate::{
    file::parser::Parser,
    metadata::{
        customattributes::types::{
            CustomAttributeArgument, CustomAttributeNamedArgument, CustomAttributeValue,
            NAMED_ARG_TYPE, SERIALIZATION_TYPE,
        },
        streams::Blob,
        tables::ParamRc,
        typesystem::{CilFlavor, CilTypeRef, TypeRegistry},
    },
    utils::EnumUtils,
    Error::DepthLimitExceeded,
    Result,
};
use std::sync::Arc;

/// Maximum nesting depth for custom attribute parsing.
///
/// This limit prevents stack overflow and excessive memory usage when parsing
/// deeply nested custom attribute structures. The iterative implementation
/// uses explicit stack allocation which is tracked against this limit.
///
/// The limit is set generously to accommodate legitimate complex custom attributes
/// while still protecting against malformed or malicious metadata.
const MAX_NESTING_DEPTH: usize = 1000;

/// Maximum number of named arguments in a custom attribute.
///
/// Custom attributes can have named properties/fields, but excessive counts indicate
/// malformed data. 1024 is far beyond any reasonable use case.
const MAX_NAMED_ARGS: u16 = 1024;

/// Maximum array length in custom attribute arguments.
///
/// # Rationale
///
/// This limit (65536 = 2^16 elements) serves two purposes:
///
/// 1. **Memory Safety**: Prevents allocation bombs where malformed metadata claims
///    astronomical array sizes (e.g., 2^31 elements × 8 bytes = 16GB allocation).
///    With this limit, the maximum allocation is ~512KB for 64-bit elements.
///
/// 2. **Practical Sufficiency**: Real-world custom attributes rarely contain large
///    arrays. Even data-heavy attributes like `[Guid]` or permission sets typically
///    use fixed-size data, not variable-length arrays of this magnitude.
///
/// # Value Choice
///
/// The value 65536 (2^16) was chosen because:
/// - It's large enough for any legitimate use case encountered in practice
/// - It keeps maximum allocation bounded to reasonable memory
/// - It matches the maximum value representable by a u16, which is often used
///   as an array length type in .NET metadata
const MAX_ATTRIBUTE_ARRAY_LENGTH: i32 = 65536;

/// Parse custom attribute blob data from the blob heap using constructor parameter information.
///
/// This function retrieves custom attribute data from the specified blob heap index and
/// parses it according to ECMA-335 II.23.3 specification. It uses the constructor method's
/// parameter types to accurately parse fixed arguments and automatically handles named
/// arguments using their embedded type information.
///
/// # Arguments
/// * `blob` - The [`crate::metadata::streams::Blob`] heap containing custom attribute data
/// * `index` - The index into the blob heap (0 indicates empty custom attribute)
/// * `params` - Reference to the constructor method's parameter vector for type-aware parsing
///
/// # Returns
/// A parsed [`crate::metadata::customattributes::CustomAttributeValue`] containing:
/// - `fixed_args` - Constructor arguments in declaration order
/// - `named_args` - Field and property assignments with names and values
///
/// # Errors
/// Returns [`crate::Error::OutOfBounds`] if the index is invalid, or one of the following:
/// - [`crate::Error::Malformed`]: Invalid prolog (not 0x0001), insufficient data for declared arguments, or type/value mismatches in argument parsing
/// - [`crate::Error::DepthLimitExceeded`]: Maximum nesting depth exceeded during parsing
///
/// # Examples
///
/// ```rust,no_run
/// use dotscope::metadata::customattributes::parse_custom_attribute_blob;
/// use dotscope::CilObject;
///
/// let assembly = CilObject::from_path("tests/samples/WindowsBase.dll")?;
///
/// # fn get_custom_attribute_data() -> (u32, std::sync::Arc<boxcar::Vec<dotscope::metadata::tables::ParamRc>>) { todo!() }
/// let (blob_index, constructor_params) = get_custom_attribute_data();
///
/// if let Some(blob_heap) = assembly.blob() {
///     let custom_attr = parse_custom_attribute_blob(blob_heap, blob_index, &constructor_params)?;
///
///     println!("Fixed arguments: {}", custom_attr.fixed_args.len());
///     println!("Named arguments: {}", custom_attr.named_args.len());
/// }
/// # Ok::<(), dotscope::Error>(())
/// ```
///
/// # Thread Safety
///
/// This function is thread-safe and can be called concurrently from multiple threads.
pub fn parse_custom_attribute_blob(
    blob: &Blob,
    index: u32,
    params: &Arc<boxcar::Vec<ParamRc>>,
) -> Result<CustomAttributeValue> {
    if index == 0 {
        return Ok(CustomAttributeValue {
            fixed_args: vec![],
            named_args: vec![],
        });
    }

    let data = blob.get(index as usize)?;
    let mut parser = CustomAttributeParser::new(data);
    parser.parse_custom_attribute(params)
}

/// Parse custom attribute blob data directly from raw bytes using constructor parameter information.
///
/// This function parses custom attribute data from a raw byte slice according to the
/// ECMA-335 II.23.3 specification. It's the core parsing function used by other APIs
/// and provides direct access to the parsing logic without blob heap indirection.
///
/// The parser uses constructor method parameter types for accurate fixed argument parsing
/// and handles named arguments through their embedded serialization type information.
/// It implements graceful degradation when type resolution fails and provides comprehensive
/// error reporting for malformed data.
///
/// # Arguments
/// * `data` - Raw bytes of the custom attribute blob data to parse
/// * `params` - Reference to the constructor method's parameter vector for type-aware parsing
///
/// # Returns
/// A parsed [`crate::metadata::customattributes::CustomAttributeValue`] containing:
/// - `fixed_args` - Constructor arguments parsed using parameter type information
/// - `named_args` - Field and property assignments with their names and values
///
/// # Errors
/// Returns one of the following errors if the blob data doesn't conform to ECMA-335 format:
/// - [`crate::Error::Malformed`]: Invalid or missing prolog (must be 0x0001), insufficient data for the number of declared arguments, type mismatches between expected and actual argument types, invalid serialization type tags in named arguments, or truncated/corrupted blob data
/// - [`crate::Error::DepthLimitExceeded`]: Maximum nesting depth exceeded during complex type parsing
///
/// # Examples
///
/// ```rust,no_run
/// use dotscope::metadata::customattributes::{parse_custom_attribute_data, CustomAttributeArgument};
///
/// # fn get_constructor_params() -> std::sync::Arc<boxcar::Vec<dotscope::metadata::tables::ParamRc>> { todo!() }
/// let constructor_params = get_constructor_params();
///
/// // Example: Simple custom attribute with string argument
/// let blob_data = &[
///     0x01, 0x00,                     // Prolog (0x0001)
///     0x05,                           // String length
///     0x48, 0x65, 0x6C, 0x6C, 0x6F,   // "Hello" (UTF-8)
///     0x00, 0x00,                     // Named argument count (0)
/// ];
///
/// let result = parse_custom_attribute_data(blob_data, &constructor_params)?;
///
/// // Access parsed arguments
/// match &result.fixed_args[0] {
///     CustomAttributeArgument::String(s) => println!("String argument: '{}'", s),
///     _ => println!("Unexpected argument type"),
/// }
///
/// println!("Named arguments: {}", result.named_args.len());
/// # Ok::<(), dotscope::Error>(())
/// ```
///
/// # Thread Safety
///
/// This function is thread-safe and can be called concurrently from multiple threads.
pub fn parse_custom_attribute_data(
    data: &[u8],
    params: &Arc<boxcar::Vec<ParamRc>>,
) -> Result<CustomAttributeValue> {
    let mut parser = CustomAttributeParser::new(data);
    parser.parse_custom_attribute(params)
}

/// Parse custom attribute blob data with enhanced cross-assembly type resolution.
///
/// This enhanced version leverages the TypeRegistry's cross-assembly resolution capabilities
/// to properly handle external enum types that were previously causing parsing failures
/// in mono assemblies. This addresses the core issue where CustomAttribute parsing would
/// fail when enum underlying types were defined in external assemblies.
///
/// # Key Enhancements
///
/// - **Cross-Assembly Type Resolution**: Uses `TypeRegistry.resolve_type_global()` to find
///   TypeDef entries across all linked assemblies instead of just the current assembly
/// - **Proper Enum Detection**: Can determine if external types are enums by finding their
///   actual TypeDef and analyzing inheritance chains
/// - **Reliable Underlying Type Resolution**: Gets actual enum underlying types instead of
///   using heuristics or hardcoded type lists
///
/// # Arguments
/// * `data` - Raw bytes of the custom attribute blob data to parse
/// * `params` - Reference to the constructor method's parameter vector for type-aware parsing
/// * `type_registry` - TypeRegistry with cross-assembly resolution via `registry_link()`
///
/// # Returns
/// A fully parsed [`crate::metadata::customattributes::CustomAttributeValue`] with proper
/// external enum handling that previously would have failed with heuristic approaches.
///
/// # Errors
/// Returns an error if the custom attribute data cannot be parsed.
///
/// # Thread Safety
/// This function is thread-safe and can be called concurrently from multiple threads.
pub fn parse_custom_attribute_data_with_registry(
    data: &[u8],
    params: &Arc<boxcar::Vec<ParamRc>>,
    type_registry: &Arc<TypeRegistry>,
) -> Result<CustomAttributeValue> {
    let mut parser = CustomAttributeParser::with_registry(data, type_registry.clone());
    parser.parse_custom_attribute(params)
}

/// Parse custom attribute blob data with enhanced cross-assembly type resolution.
///
/// This enhanced version of [`parse_custom_attribute_blob`] leverages the TypeRegistry's
/// cross-assembly resolution capabilities to properly handle external enum types that were
/// previously causing parsing failures in mono assemblies.
///
/// # Arguments
/// * `blob` - The blob heap containing custom attribute data
/// * `index` - Index into the blob heap where the custom attribute data starts
/// * `params` - Reference to the constructor method's parameter vector for type-aware parsing
/// * `type_registry` - TypeRegistry with cross-assembly resolution via `registry_link()`
///
/// # Returns
/// A fully parsed [`crate::metadata::customattributes::CustomAttributeValue`] with proper
/// external enum handling that previously would have failed with heuristic approaches.
///
/// # Errors
/// Returns an error if the custom attribute blob cannot be parsed.
///
/// # Thread Safety
/// This function is thread-safe and can be called concurrently from multiple threads.
pub fn parse_custom_attribute_blob_with_registry(
    blob: &Blob,
    index: u32,
    params: &Arc<boxcar::Vec<ParamRc>>,
    type_registry: &Arc<TypeRegistry>,
) -> Result<CustomAttributeValue> {
    let data = blob.get(index as usize)?;
    let mut parser = CustomAttributeParser::with_registry(data, type_registry.clone());
    parser.parse_custom_attribute(params)
}

/// Custom attribute parser implementing ECMA-335 II.23.3 specification.
///
/// This parser uses an iterative stack-based approach with depth limiting to handle
/// arbitrarily nested custom attribute structures without risk of stack overflow.
/// It provides a structured approach to parsing the complex binary format of .NET
/// custom attributes.
///
/// The parser handles both fixed arguments (based on constructor parameters) and named
/// arguments (with embedded type information) while maintaining compatibility with
/// real-world .NET assemblies through graceful degradation strategies.
///
/// # Thread Safety
///
/// [`CustomAttributeParser`] is not [`std::marker::Send`] or [`std::marker::Sync`] due to mutable state.
/// Each thread should create its own parser instance for concurrent parsing operations.
pub struct CustomAttributeParser<'a> {
    /// Binary data parser for reading attribute blob
    parser: Parser<'a>,
    /// Optional TypeRegistry for cross-assembly type resolution
    type_registry: Option<Arc<TypeRegistry>>,
}

impl<'a> CustomAttributeParser<'a> {
    /// Creates a new custom attribute parser for the provided blob data.
    ///
    /// # Arguments
    /// * `data` - Raw bytes of the custom attribute blob to parse
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use dotscope::metadata::customattributes::parser::CustomAttributeParser;
    ///
    /// let blob_data = &[0x01, 0x00, 0x00, 0x00]; // Minimal custom attribute
    /// let parser = CustomAttributeParser::new(blob_data);
    /// ```
    #[must_use]
    pub fn new(data: &'a [u8]) -> Self {
        Self {
            parser: Parser::new(data),
            type_registry: None,
        }
    }

    /// Creates a new custom attribute parser with cross-assembly type resolution support.
    ///
    /// This enhanced constructor enables cross-assembly type resolution for proper handling
    /// of external enum types that would otherwise fail with heuristic approaches.
    ///
    /// # Arguments
    /// * `data` - Raw bytes of the custom attribute blob to parse
    /// * `type_registry` - TypeRegistry with cross-assembly resolution via `registry_link()`
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use dotscope::metadata::customattributes::parser::CustomAttributeParser;
    /// use std::sync::Arc;
    ///
    /// let blob_data = &[0x01, 0x00, 0x00, 0x00]; // Minimal custom attribute
    /// let test_identity = AssemblyIdentity::parse("TestAssembly, Version=1.0.0.0").unwrap();
    /// let type_registry = Arc::new(TypeRegistry::new(test_identity).unwrap());
    /// let parser = CustomAttributeParser::with_registry(blob_data, type_registry);
    /// ```
    #[must_use]
    pub fn with_registry(data: &'a [u8], type_registry: Arc<TypeRegistry>) -> Self {
        Self {
            parser: Parser::new(data),
            type_registry: Some(type_registry),
        }
    }

    /// Parse a complete custom attribute blob according to ECMA-335 II.23.3.
    ///
    /// This method handles the full custom attribute parsing workflow:
    /// 1. Validates the standard prolog (0x0001)
    /// 2. Parses fixed arguments using constructor parameter types
    /// 3. Parses named arguments using embedded type information
    ///
    /// The parser implements type-aware parsing for fixed arguments when constructor
    /// parameter information is available, and falls back to heuristic parsing when
    /// type resolution fails. Named arguments are always parsed using their embedded
    /// serialization type tags.
    ///
    /// # Arguments
    /// * `params` - Constructor method parameters for fixed argument type resolution
    ///
    /// # Returns
    /// A complete [`crate::metadata::customattributes::CustomAttributeValue`] with all parsed data.
    ///
    /// # Errors
    /// Returns [`crate::Error::Malformed`] for various format violations:
    /// - Invalid prolog (not 0x0001)
    /// - Insufficient data for declared arguments
    /// - Invalid serialization types in named arguments
    /// - Nesting depth limit exceeded during parsing
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use dotscope::metadata::customattributes::parser::CustomAttributeParser;
    ///
    /// # fn get_constructor_params() -> std::sync::Arc<boxcar::Vec<dotscope::metadata::tables::ParamRc>> { todo!() }
    /// let blob_data = &[0x01, 0x00, 0x00, 0x00]; // Simple custom attribute
    /// let mut parser = CustomAttributeParser::new(blob_data);
    /// let params = get_constructor_params();
    ///
    /// let custom_attr = parser.parse_custom_attribute(&params)?;
    /// println!("Parsed {} fixed args and {} named args",
    ///          custom_attr.fixed_args.len(), custom_attr.named_args.len());
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn parse_custom_attribute(
        &mut self,
        params: &Arc<boxcar::Vec<ParamRc>>,
    ) -> Result<CustomAttributeValue> {
        // Check for the standard prolog (0x0001)
        let prolog = self.parser.read_le::<u16>()?;
        if prolog != 0x0001 {
            return Err(malformed_error!(
                "Invalid custom attribute prolog - expected 0x0001"
            ));
        }

        // Parse fixed arguments based on constructor parameter types
        let fixed_args = self.parse_fixed_arguments(params)?;

        // Parse named arguments using explicit type tags
        let named_args =
            if self.parser.has_more_data() && self.parser.len() >= self.parser.pos() + 2 {
                let num_named = self.parser.read_le::<u16>()?;
                if num_named > MAX_NAMED_ARGS {
                    return Err(malformed_error!(
                        "Custom attribute has too many named arguments: {} (max: {})",
                        num_named,
                        MAX_NAMED_ARGS
                    ));
                }

                let mut args = Vec::with_capacity(num_named as usize);
                for _ in 0..num_named {
                    if let Some(arg) = self.parse_named_argument()? {
                        args.push(arg);
                    } else {
                        break;
                    }
                }
                args
            } else {
                vec![]
            };

        Ok(CustomAttributeValue {
            fixed_args,
            named_args,
        })
    }

    /// Parse fixed arguments based on constructor parameter types.
    ///
    /// Extracts constructor parameters (excluding return parameter at sequence 0),
    /// sorts them by sequence number, and parses each argument using its type information.
    /// This ensures proper argument order matching the constructor signature.
    ///
    /// # Arguments
    /// * `params` - Constructor method parameters with type and sequence information
    ///
    /// # Returns
    /// Vector of parsed arguments in constructor parameter order
    ///
    /// # Errors
    /// Returns [`crate::Error::Malformed`] if:
    /// - Constructor has parameters but no resolved types
    /// - Insufficient blob data for declared parameters
    /// - Parameter type parsing fails
    fn parse_fixed_arguments(
        &mut self,
        params: &Arc<boxcar::Vec<ParamRc>>,
    ) -> Result<Vec<CustomAttributeArgument>> {
        // Create sorted list of constructor parameters (excluding return parameter)
        let mut sorted_params: Vec<_> = params
            .iter()
            .filter(|(_, param)| param.sequence > 0)
            .map(|(_, param)| param)
            .collect();
        sorted_params.sort_by_key(|param| param.sequence);

        let resolved_param_types: Vec<_> = sorted_params
            .iter()
            .filter_map(|param| param.base.get())
            .collect();

        if resolved_param_types.is_empty() && !sorted_params.is_empty() {
            return Err(malformed_error!(
                "Constructor has {} parameters but no resolved types",
                sorted_params.len()
            ));
        }

        let mut fixed_args = Vec::new();
        for param_type in resolved_param_types {
            if !self.parser.has_more_data() {
                return Err(malformed_error!(
                    "Not enough data for remaining constructor parameters"
                ));
            }

            if let Some(arg) = self.parse_fixed_argument(param_type)? {
                fixed_args.push(arg);
            } else {
                return Err(malformed_error!(
                    "Unsupported parameter type in custom attribute constructor"
                ));
            }
        }

        Ok(fixed_args)
    }

    /// Parse an enum value based on its underlying type size.
    ///
    /// This method handles all enum parsing logic in one place, reading the appropriate
    /// number of bytes based on the enum's underlying type and creating the correct
    /// CustomAttributeArgument variant.
    ///
    /// # Arguments
    /// * `type_name` - Full name of the enum type
    /// * `underlying_type_size` - Size in bytes of the enum's underlying type
    ///
    /// # Returns
    /// * `Ok(Some(CustomAttributeArgument))` - Successfully parsed enum value
    /// * `Err(Error)` - If parsing fails or invalid underlying type size
    fn parse_enum(
        &mut self,
        type_name: String,
        underlying_type_size: usize,
    ) -> Result<Option<CustomAttributeArgument>> {
        match underlying_type_size {
            0 => Err(malformed_error!(
                "Cannot determine enum underlying type size for '{}' - enum fields not loaded yet.",
                type_name
            )),
            1 => {
                let enum_value = self.parser.read_le::<u8>()?;
                Ok(Some(CustomAttributeArgument::Enum(
                    type_name,
                    Box::new(CustomAttributeArgument::U1(enum_value)),
                )))
            }
            2 => {
                let enum_value = self.parser.read_le::<u16>()?;
                Ok(Some(CustomAttributeArgument::Enum(
                    type_name,
                    Box::new(CustomAttributeArgument::U2(enum_value)),
                )))
            }
            4 => {
                let enum_value = self.parser.read_le::<i32>()?;
                Ok(Some(CustomAttributeArgument::Enum(
                    type_name,
                    Box::new(CustomAttributeArgument::I4(enum_value)),
                )))
            }
            8 => {
                let enum_value = self.parser.read_le::<i64>()?;
                Ok(Some(CustomAttributeArgument::Enum(
                    type_name,
                    Box::new(CustomAttributeArgument::I8(enum_value)),
                )))
            }
            _ => Err(malformed_error!(
                "Invalid enum underlying type size {} for enum '{}'. Expected 1, 2, 4, or 8 bytes.",
                underlying_type_size,
                type_name
            )),
        }
    }

    /// Parse a single fixed argument based on constructor parameter type.
    ///
    /// Uses [`crate::metadata::typesystem::CilFlavor`] to determine the correct parsing
    /// strategy for each parameter type. Handles primitive types, strings, arrays,
    /// and complex types including System.Type, System.Object, and enum types.
    ///
    /// # Type Handling
    /// - **Primitives**: Direct binary reading (bool, int, float, etc.)
    /// - **String**: Compressed length + UTF-8 data or null marker (0xFF)
    /// - **Class Types**: Special handling for System.Type, System.String, System.Object
    /// - **`ValueType`**: Treated as enum with i32 underlying type
    /// - **Arrays**: Single-dimensional arrays with element type parsing
    /// - **Enum**: Heuristic detection with graceful fallback to Type parsing
    ///
    /// # Arguments
    /// * `cil_type` - Constructor parameter type information for parsing guidance
    ///
    /// # Returns
    /// Parsed argument if successful, None if type is unsupported
    ///
    /// # Errors
    /// Returns [`crate::Error::Malformed`] for invalid data or unsupported types
    fn parse_fixed_argument(
        &mut self,
        cil_type: &CilTypeRef,
    ) -> Result<Option<CustomAttributeArgument>> {
        let Some(type_ref) = cil_type.upgrade() else {
            return Err(malformed_error!("Type reference has been dropped"));
        };

        let flavor = type_ref.flavor();

        if !self.parser.has_more_data() {
            return Err(malformed_error!(
                "Not enough data for fixed argument type {:?} (pos={}, len={})",
                flavor,
                self.parser.pos(),
                self.parser.len()
            ));
        }

        match flavor {
            // Primitive types - stored directly without type tags
            CilFlavor::Boolean => Ok(Some(CustomAttributeArgument::Bool(
                self.parser.read_le::<u8>()? != 0,
            ))),
            CilFlavor::Char => {
                let val = self.parser.read_le::<u16>()?;
                let character = char::from_u32(u32::from(val)).unwrap_or('\u{FFFD}');
                Ok(Some(CustomAttributeArgument::Char(character)))
            }
            CilFlavor::I1 => Ok(Some(CustomAttributeArgument::I1(
                self.parser.read_le::<i8>()?,
            ))),
            CilFlavor::U1 => Ok(Some(CustomAttributeArgument::U1(
                self.parser.read_le::<u8>()?,
            ))),
            CilFlavor::I2 => Ok(Some(CustomAttributeArgument::I2(
                self.parser.read_le::<i16>()?,
            ))),
            CilFlavor::U2 => Ok(Some(CustomAttributeArgument::U2(
                self.parser.read_le::<u16>()?,
            ))),
            CilFlavor::I4 => Ok(Some(CustomAttributeArgument::I4(
                self.parser.read_le::<i32>()?,
            ))),
            CilFlavor::U4 => Ok(Some(CustomAttributeArgument::U4(
                self.parser.read_le::<u32>()?,
            ))),
            CilFlavor::I8 => Ok(Some(CustomAttributeArgument::I8(
                self.parser.read_le::<i64>()?,
            ))),
            CilFlavor::U8 => Ok(Some(CustomAttributeArgument::U8(
                self.parser.read_le::<u64>()?,
            ))),
            CilFlavor::R4 => Ok(Some(CustomAttributeArgument::R4(
                self.parser.read_le::<f32>()?,
            ))),
            CilFlavor::R8 => Ok(Some(CustomAttributeArgument::R8(
                self.parser.read_le::<f64>()?,
            ))),
            CilFlavor::I => {
                // Native integers: size depends on target platform
                // On 64-bit: read i64, isize is i64 - no truncation
                // On 32-bit: read i32, isize is i32 - no truncation
                // Note: Cross-platform parsing (32-bit assembly on 64-bit host) is not supported
                if cfg!(target_pointer_width = "64") {
                    let val = self.parser.read_le::<i64>()?;
                    #[allow(clippy::cast_possible_truncation)] // Safe: i64 == isize on 64-bit
                    Ok(Some(CustomAttributeArgument::I(val as isize)))
                } else {
                    let val = self.parser.read_le::<i32>()?;
                    Ok(Some(CustomAttributeArgument::I(val as isize)))
                }
            }
            CilFlavor::U => {
                // Native integers: size depends on target platform
                // On 64-bit: read u64, usize is u64 - no truncation
                // On 32-bit: read u32, usize is u32 - no truncation
                // Note: Cross-platform parsing (32-bit assembly on 64-bit host) is not supported
                if cfg!(target_pointer_width = "64") {
                    let val = self.parser.read_le::<u64>()?;
                    #[allow(clippy::cast_possible_truncation)] // Safe: u64 == usize on 64-bit
                    Ok(Some(CustomAttributeArgument::U(val as usize)))
                } else {
                    let val = self.parser.read_le::<u32>()?;
                    Ok(Some(CustomAttributeArgument::U(val as usize)))
                }
            }
            CilFlavor::String => {
                if self.parser.peek_byte()? == 0xFF {
                    let _ = self.parser.read_le::<u8>()?; // consume null marker
                    Ok(Some(CustomAttributeArgument::String(String::new())))
                } else {
                    let s = self
                        .parse_string()
                        .map_err(|e| malformed_error!("Failed to parse String parameter: {}", e))?;
                    Ok(Some(CustomAttributeArgument::String(s)))
                }
            }
            CilFlavor::Class => {
                // For Class types in fixed arguments, we need to check what specific class it is
                // According to .NET runtime: only System.Type, System.String, and System.Object are supported
                // BUT: Enum types can also appear as Class and should be handled as ValueType/Enum
                let type_name = type_ref.fullname();

                if type_name == "System.Type" {
                    // System.Type is stored as a string (type name)
                    if self.parser.peek_byte()? == 0xFF {
                        let _ = self.parser.read_le::<u8>()?; // consume null marker
                        Ok(Some(CustomAttributeArgument::Type(String::new())))
                    } else {
                        let s = self.parse_string().map_err(|e| {
                            malformed_error!("Failed to parse System.Type parameter: {}", e)
                        })?;
                        Ok(Some(CustomAttributeArgument::Type(s)))
                    }
                } else if type_name == "System.String" {
                    // System.String is stored as a string
                    if self.parser.peek_byte()? == 0xFF {
                        let _ = self.parser.read_le::<u8>()?; // consume null marker
                        Ok(Some(CustomAttributeArgument::String(String::new())))
                    } else {
                        let s = self.parse_string().map_err(|e| {
                            malformed_error!("Failed to parse System.String parameter: {}", e)
                        })?;
                        Ok(Some(CustomAttributeArgument::String(s)))
                    }
                } else if type_name == "System.Object" {
                    // System.Object is stored as a tagged object - read type tag first
                    let type_tag = self.parser.read_le::<u8>()?;
                    let value = self.parse_argument_by_type_tag(type_tag)?;
                    Ok(Some(value))
                } else {
                    // Class types that are actually enums (external enum references)
                    // use the same multi-stage fallback strategy as ValueType enums.
                    //
                    // Stage 1: Direct type resolution via TypeRegistry
                    if let Some(registry) = &self.type_registry {
                        if let Some(resolved_type) = registry.resolve_type_global(&type_name) {
                            if EnumUtils::is_enum_type(&resolved_type, Some(registry)) {
                                let underlying_type_size =
                                    EnumUtils::get_enum_underlying_type_size(&resolved_type);
                                return self.parse_enum(type_name, underlying_type_size);
                            }
                        }
                    }

                    // Stage 2: Heuristic enum detection as fallback
                    let is_enum = if let Some(registry) = &self.type_registry {
                        EnumUtils::is_enum_type_by_name(&type_name, registry)
                    } else {
                        EnumUtils::is_enum_type(&type_ref, None)
                    };

                    if is_enum {
                        let underlying_type_size = if let Some(registry) = &self.type_registry {
                            EnumUtils::get_enum_underlying_type_size_by_name(&type_name, registry)
                        } else {
                            EnumUtils::get_enum_underlying_type_size(&type_ref)
                        };

                        return self.parse_enum(type_name, underlying_type_size);
                    }

                    // Stage 3: Fallback for unresolvable external types
                    // TypeRef types (external references) often have CilFlavor::Class even
                    // when they're actually enums, because we lack the type definition to
                    // determine inheritance. For custom attributes, external types that
                    // aren't System.Type/String/Object are typically enums. Assume int32
                    // underlying type (the most common) to allow parsing to continue.
                    self.parse_enum(type_name, 4)
                }
            }
            CilFlavor::ValueType => {
                // ValueType enum resolution uses a multi-stage fallback strategy:
                //
                // Stage 1: Direct type resolution via TypeRegistry
                //   - Look up the type by full name in the registry
                //   - If found and it's an enum, use its defined underlying type size
                //   - This is the most accurate method when the type is fully loaded
                //
                // Stage 2: Heuristic enum detection (fallback)
                //   - Use EnumUtils to detect enums by name patterns or inheritance
                //   - Infer underlying type size from available metadata
                //   - Used when the type definition isn't directly available
                //
                // Stage 3: Error (no resolution possible)
                //   - If neither stage succeeds, the type cannot be parsed
                //   - Indicates missing assembly dependencies
                let type_name = type_ref.fullname();

                // Stage 1: Try direct type resolution via TypeRegistry
                if let Some(registry) = &self.type_registry {
                    if let Some(resolved_type) = registry.resolve_type_global(&type_name) {
                        if EnumUtils::is_enum_type(&resolved_type, Some(registry)) {
                            let underlying_type_size =
                                EnumUtils::get_enum_underlying_type_size(&resolved_type);
                            return self.parse_enum(type_name, underlying_type_size);
                        }
                    }
                }

                // Stage 2: Heuristic enum detection as fallback
                let is_enum = if let Some(registry) = &self.type_registry {
                    EnumUtils::is_enum_type_by_name(&type_name, registry)
                } else {
                    EnumUtils::is_enum_type(&type_ref, None)
                };

                if is_enum {
                    let underlying_type_size = if let Some(registry) = &self.type_registry {
                        EnumUtils::get_enum_underlying_type_size_by_name(&type_name, registry)
                    } else {
                        EnumUtils::get_enum_underlying_type_size(&type_ref)
                    };

                    self.parse_enum(type_name, underlying_type_size)
                } else {
                    // Stage 3: No resolution possible - missing dependencies
                    Err(malformed_error!(
                            "Cannot resolve ValueType '{}' - type not found in TypeRegistry. This indicates the assembly containing this type is not loaded yet.",
                            type_name
                        ))
                }
            }
            CilFlavor::Array { rank, .. } => {
                if *rank == 1 {
                    let array_length = self.parser.read_le::<i32>()?;
                    if array_length == -1 {
                        Ok(Some(CustomAttributeArgument::Array(vec![]))) // null array
                    } else if array_length < 0 {
                        Err(malformed_error!("Invalid array length: {}", array_length))
                    } else if array_length > MAX_ATTRIBUTE_ARRAY_LENGTH {
                        Err(malformed_error!(
                            "Custom attribute array too large: {} (max: {})",
                            array_length,
                            MAX_ATTRIBUTE_ARRAY_LENGTH
                        ))
                    } else {
                        // Try to get the base element type from the array type
                        if let Some(base_type) = type_ref.base() {
                            let base_type_ref = base_type.into();
                            // Safe: array_length was validated as positive and <= MAX_ATTRIBUTE_ARRAY_LENGTH
                            #[allow(clippy::cast_sign_loss)]
                            let mut elements = Vec::with_capacity(array_length as usize);

                            for _ in 0..array_length {
                                if let Some(element) = self.parse_fixed_argument(&base_type_ref)? {
                                    elements.push(element);
                                } else {
                                    return Err(malformed_error!("Failed to parse array element"));
                                }
                            }

                            Ok(Some(CustomAttributeArgument::Array(elements)))
                        } else {
                            Err(malformed_error!(
                                "Array type has no base element type information for fixed arguments"
                            ))
                        }
                    }
                } else {
                    Err(malformed_error!(
                        "Multi-dimensional arrays not supported in custom attributes"
                    ))
                }
            }
            CilFlavor::Void => Ok(Some(CustomAttributeArgument::Void)),
            CilFlavor::Object => {
                // System.Object in CustomAttribute is stored as a tagged object - read type tag first
                let type_tag = self.parser.read_le::<u8>()?;
                let value = self.parse_argument_by_type_tag(type_tag)?;
                Ok(Some(value))
            }
            _ => Err(malformed_error!(
                "Unsupported type flavor in custom attribute: {:?}",
                flavor
            )),
        }
    }

    /// Parse a named argument (field or property) with explicit type tags.
    ///
    /// Named arguments start with a field/property indicator (0x53/0x54), followed by
    /// a [`crate::metadata::customattributes::types::SERIALIZATION_TYPE`] tag, name length,
    /// name string, and the argument value. This follows ECMA-335 II.23.3 exactly.
    ///
    /// # Format
    /// 1. Field/Property indicator: 0x53 (FIELD) or 0x54 (PROPERTY)
    /// 2. Type tag: `CorSerializationType` enumeration value
    /// 3. Name: Compressed length + UTF-8 string
    /// 4. Value: Type-specific binary data
    ///
    /// # Returns
    /// Parsed named argument with name, type, and value, or None if no more data
    ///
    /// # Errors
    /// Returns [`crate::Error::Malformed`] for invalid format or unsupported types
    fn parse_named_argument(&mut self) -> Result<Option<CustomAttributeNamedArgument>> {
        if !self.parser.has_more_data() {
            return Ok(None);
        }

        // Read field/property indicator per ECMA-335 §II.23.3
        let field_or_prop = self.parser.read_le::<u8>()?;
        let is_field = match field_or_prop {
            NAMED_ARG_TYPE::FIELD => true,
            NAMED_ARG_TYPE::PROPERTY => false,
            0x00 => {
                // 0x00 can appear as padding or end-of-data marker in some custom attributes
                // This is sometimes used as a null terminator in malformed or legacy attributes
                return Ok(None);
            }
            _ => {
                return Err(malformed_error!(
                    "Invalid field/property indicator: 0x{:02X} (expected 0x{:02X} for FIELD or 0x{:02X} for PROPERTY)",
                    field_or_prop,
                    NAMED_ARG_TYPE::FIELD,
                    NAMED_ARG_TYPE::PROPERTY
                ))
            }
        };

        // Read type information
        let type_info = self.parser.read_le::<u8>()?;
        let arg_type = match type_info {
            SERIALIZATION_TYPE::BOOLEAN => "Boolean".to_string(),
            SERIALIZATION_TYPE::CHAR => "Char".to_string(),
            SERIALIZATION_TYPE::I1 => "I1".to_string(),
            SERIALIZATION_TYPE::U1 => "U1".to_string(),
            SERIALIZATION_TYPE::I2 => "I2".to_string(),
            SERIALIZATION_TYPE::U2 => "U2".to_string(),
            SERIALIZATION_TYPE::I4 => "I4".to_string(),
            SERIALIZATION_TYPE::U4 => "U4".to_string(),
            SERIALIZATION_TYPE::I8 => "I8".to_string(),
            SERIALIZATION_TYPE::U8 => "U8".to_string(),
            SERIALIZATION_TYPE::R4 => "R4".to_string(),
            SERIALIZATION_TYPE::R8 => "R8".to_string(),
            SERIALIZATION_TYPE::STRING => "String".to_string(),
            SERIALIZATION_TYPE::TYPE => "Type".to_string(),
            SERIALIZATION_TYPE::TAGGED_OBJECT => "TaggedObject".to_string(),
            SERIALIZATION_TYPE::ENUM => "Enum".to_string(),
            _ => {
                return Err(malformed_error!(
                    "Unsupported named argument type: 0x{:02X}",
                    type_info
                ))
            }
        };

        // Read field/property name
        let name_length = self.parser.read_compressed_uint()?;
        let mut name = String::with_capacity(name_length as usize);
        for _ in 0..name_length {
            name.push(char::from(self.parser.read_le::<u8>()?));
        }

        // Parse value based on type tag
        let value = self.parse_argument_by_type_tag(type_info)?;

        Ok(Some(CustomAttributeNamedArgument {
            is_field,
            name,
            arg_type,
            value,
        }))
    }

    /// Parse an argument based on its `CorSerializationType` tag using iterative processing.
    ///
    /// This method uses an explicit stack-based approach to handle deeply nested structures
    /// without consuming call stack space. It supports complex types like arrays and tagged
    /// objects while preventing resource exhaustion through depth limiting.
    ///
    /// # Supported Types
    /// - All primitive types (bool, int, float, char)
    /// - String and Type arguments
    /// - Enum values with type name and underlying value
    /// - Single-dimensional arrays (SZARRAY) - supports arbitrary nesting depth
    /// - Tagged objects - supports arbitrary nesting depth
    ///
    /// # Nesting Safety
    /// Uses explicit stack tracking with [`MAX_NESTING_DEPTH`] limit to prevent memory
    /// exhaustion from maliciously crafted or deeply nested custom attribute data.
    ///
    /// # Arguments
    /// * `type_tag` - [`crate::metadata::customattributes::types::SERIALIZATION_TYPE`] enumeration value
    ///
    /// # Returns
    /// Parsed argument value according to the type tag specification
    ///
    /// # Errors
    /// - [`crate::Error::DepthLimitExceeded`]: Maximum nesting depth exceeded
    /// - [`crate::Error::Malformed`]: Invalid type tags or malformed data format
    fn parse_argument_by_type_tag(&mut self, type_tag: u8) -> Result<CustomAttributeArgument> {
        /// Work item for iterative parsing stack
        enum WorkItem {
            /// Parse a type tag and push result
            ParseTag(u8),
            /// Build array from N elements on stack
            BuildArray(i32),
            /// Take inner tagged object result
            TaggedObject,
        }

        let mut work_stack: Vec<WorkItem> = Vec::new();
        let mut result_stack: Vec<CustomAttributeArgument> = Vec::new();

        work_stack.push(WorkItem::ParseTag(type_tag));

        while let Some(work) = work_stack.pop() {
            if work_stack.len() + result_stack.len() > MAX_NESTING_DEPTH {
                return Err(DepthLimitExceeded(MAX_NESTING_DEPTH));
            }

            match work {
                WorkItem::ParseTag(tag) => {
                    match tag {
                        SERIALIZATION_TYPE::BOOLEAN => {
                            let val = self.parser.read_le::<u8>()?;
                            result_stack.push(CustomAttributeArgument::Bool(val != 0));
                        }
                        SERIALIZATION_TYPE::CHAR => {
                            let val = self.parser.read_le::<u16>()?;
                            let character = char::from_u32(u32::from(val)).unwrap_or('\u{FFFD}');
                            result_stack.push(CustomAttributeArgument::Char(character));
                        }
                        SERIALIZATION_TYPE::I1 => {
                            result_stack
                                .push(CustomAttributeArgument::I1(self.parser.read_le::<i8>()?));
                        }
                        SERIALIZATION_TYPE::U1 => {
                            result_stack
                                .push(CustomAttributeArgument::U1(self.parser.read_le::<u8>()?));
                        }
                        SERIALIZATION_TYPE::I2 => {
                            result_stack
                                .push(CustomAttributeArgument::I2(self.parser.read_le::<i16>()?));
                        }
                        SERIALIZATION_TYPE::U2 => {
                            result_stack
                                .push(CustomAttributeArgument::U2(self.parser.read_le::<u16>()?));
                        }
                        SERIALIZATION_TYPE::I4 => {
                            result_stack
                                .push(CustomAttributeArgument::I4(self.parser.read_le::<i32>()?));
                        }
                        SERIALIZATION_TYPE::U4 => {
                            result_stack
                                .push(CustomAttributeArgument::U4(self.parser.read_le::<u32>()?));
                        }
                        SERIALIZATION_TYPE::I8 => {
                            result_stack
                                .push(CustomAttributeArgument::I8(self.parser.read_le::<i64>()?));
                        }
                        SERIALIZATION_TYPE::U8 => {
                            result_stack
                                .push(CustomAttributeArgument::U8(self.parser.read_le::<u64>()?));
                        }
                        SERIALIZATION_TYPE::R4 => {
                            result_stack
                                .push(CustomAttributeArgument::R4(self.parser.read_le::<f32>()?));
                        }
                        SERIALIZATION_TYPE::R8 => {
                            result_stack
                                .push(CustomAttributeArgument::R8(self.parser.read_le::<f64>()?));
                        }
                        SERIALIZATION_TYPE::STRING => {
                            if self.parser.peek_byte()? == 0xFF {
                                let _ = self.parser.read_le::<u8>()?; // consume null marker
                                result_stack.push(CustomAttributeArgument::String(String::new()));
                            } else {
                                let s = self.parse_string()?;
                                result_stack.push(CustomAttributeArgument::String(s));
                            }
                        }
                        SERIALIZATION_TYPE::TYPE => {
                            if self.parser.peek_byte()? == 0xFF {
                                let _ = self.parser.read_le::<u8>()?; // consume null marker
                                result_stack.push(CustomAttributeArgument::Type(String::new()));
                            } else {
                                let s = self.parse_string()?;
                                result_stack.push(CustomAttributeArgument::Type(s));
                            }
                        }
                        SERIALIZATION_TYPE::TAGGED_OBJECT => {
                            // Read inner type tag and schedule work
                            let inner_type_tag = self.parser.read_le::<u8>()?;
                            work_stack.push(WorkItem::TaggedObject);
                            work_stack.push(WorkItem::ParseTag(inner_type_tag));
                        }
                        SERIALIZATION_TYPE::ENUM => {
                            // Read enum type name, then value
                            let type_name = self.parse_string()?;
                            let val = self.parser.read_le::<i32>()?; // Most enums are I4-based
                            result_stack.push(CustomAttributeArgument::Enum(
                                type_name,
                                Box::new(CustomAttributeArgument::I4(val)),
                            ));
                        }
                        SERIALIZATION_TYPE::SZARRAY => {
                            // Read array element type tag and length
                            let element_type_tag = self.parser.read_le::<u8>()?;
                            let array_length = self.parser.read_le::<i32>()?;

                            if array_length == -1 {
                                result_stack.push(CustomAttributeArgument::Array(vec![]));
                            // null array
                            } else if array_length < 0 {
                                return Err(malformed_error!(
                                    "Invalid array length: {}",
                                    array_length
                                ));
                            } else {
                                // Schedule work to build array after parsing elements
                                work_stack.push(WorkItem::BuildArray(array_length));

                                // Schedule parsing of array elements in reverse order
                                // (so they are processed in correct order from stack)
                                for _ in 0..array_length {
                                    work_stack.push(WorkItem::ParseTag(element_type_tag));
                                }
                            }
                        }
                        _ => {
                            return Err(malformed_error!(
                                "Unsupported serialization type tag: 0x{:02X}",
                                tag
                            ));
                        }
                    }
                }
                WorkItem::BuildArray(count) => {
                    // Pop N elements from result stack and build array
                    // Safe: count was validated as non-negative when BuildArray was pushed
                    #[allow(clippy::cast_sign_loss)]
                    let count_usize = count as usize;

                    if result_stack.len() < count_usize {
                        return Err(malformed_error!(
                            "Insufficient elements on stack for array of length {}",
                            count
                        ));
                    }

                    // Elements are on stack in correct order (last parsed = last in array)
                    let start_idx = result_stack.len() - count_usize;
                    let elements = result_stack.drain(start_idx..).collect();
                    result_stack.push(CustomAttributeArgument::Array(elements));
                }
                WorkItem::TaggedObject => {
                    // Result is already on stack from inner ParseTag, nothing to do
                    // Tagged object is transparent - we just return the inner value
                }
            }
        }

        // Should have exactly one result
        if result_stack.len() != 1 {
            return Err(malformed_error!(
                "Internal error: expected 1 result, got {}",
                result_stack.len()
            ));
        }

        // Safe: we just verified len() == 1, so pop() will return Some
        result_stack
            .pop()
            .ok_or_else(|| malformed_error!("Internal error: result stack unexpectedly empty"))
    }

    /// Attempt to parse a string speculatively, with validation and heuristics.
    ///
    /// This method tries to parse a string from the current position. If parsing
    /// succeeds and the data looks like a valid string, it returns `Some(string)`
    /// and the parser position is advanced. If parsing fails or the data doesn't
    /// look like a valid string, it returns `None` and the parser position is restored.
    ///
    /// This is useful for graceful fallback during ambiguous type parsing situations
    /// where we need to speculatively try parsing as a string.
    ///
    /// # Validation Strategy
    /// 1. Checks for null string marker (0xFF)
    /// 2. Attempts to read compressed length
    /// 3. Validates available data matches declared length
    /// 4. Performs UTF-8 validation on string bytes
    /// 5. Applies heuristics for reasonable string lengths (max 1000 chars)
    ///
    /// # Parser State
    /// On success (`Some`), the parser position is advanced past the string.
    /// On failure (`None`), the parser position is restored to its original value.
    ///
    /// # Returns
    /// `Some(String)` if a valid string was parsed, `None` otherwise
    fn try_parse_string(&mut self) -> Option<String> {
        // Check for null string marker first
        if self.parser.has_more_data() && self.parser.peek_byte().ok()? == 0xFF {
            self.parser.read_le::<u8>().ok()?;
            return Some(String::new());
        }

        self.parser
            .transactional(|p| {
                let length = p.read_compressed_uint()?;

                // Check if we have enough data for the string
                let remaining_data = p.len() - p.pos();
                if length as usize > remaining_data {
                    return Err(malformed_error!("not enough data"));
                }

                // Heuristic: reject unreasonably large "lengths" that are likely
                // misinterpreted enum values. Custom attribute strings are typically
                // short (type names, messages, etc.). The 1000 char limit is
                // conservative but catches most false positives where an i32 enum
                // value is misread as a compressed length.
                if length > 1000 {
                    return Err(malformed_error!("length too large for speculative string"));
                }

                if length == 0 {
                    return Ok(String::new());
                }

                // Check if the bytes are valid UTF-8
                let string_bytes = &p.data()[p.pos()..p.pos() + length as usize];
                let s = std::str::from_utf8(string_bytes)
                    .map_err(|_| malformed_error!("invalid UTF-8"))?;
                let result = s.to_string();

                // Advance past the string bytes
                p.advance_by(length as usize)?;

                Ok(result)
            })
            .ok()
    }

    /// Parse a compressed string from the blob.
    ///
    /// Implements ECMA-335 string parsing with support for null strings (0xFF marker)
    /// and proper UTF-8 handling. Uses compressed unsigned integer for length encoding
    /// as specified in the .NET metadata format.
    ///
    /// # Format
    /// - **Null String**: Single 0xFF byte → returns empty `String`
    /// - **Empty String**: Compressed uint 0 → returns empty `String`
    /// - **Regular String**: Compressed length + UTF-8 bytes
    ///
    /// # Design Note
    ///
    /// Both null strings (0xFF) and empty strings (length 0) return an empty Rust `String`,
    /// since Rust's `String` type cannot represent null. This means the distinction between
    /// null and empty is lost during parsing, but this is acceptable for the Rust API.
    ///
    /// # Returns
    /// Parsed string (empty `String` for both null marker and zero length)
    ///
    /// # Errors
    /// Returns [`crate::Error::Malformed`] if:
    /// - No data available for reading
    /// - Declared length exceeds available data
    /// - Compressed length parsing fails
    /// - String data contains invalid UTF-8
    fn parse_string(&mut self) -> Result<String> {
        if !self.parser.has_more_data() {
            return Err(malformed_error!("No data available for string"));
        }

        // Check for null string marker (0xFF) first
        let first_byte = self.parser.peek_byte()?;
        if first_byte == 0xFF {
            // Null string - consume the 0xFF byte and return empty string
            self.parser.read_le::<u8>()?;
            return Ok(String::new());
        }

        // Not a null string, parse as normal compressed uint + data
        let length = self.parser.read_compressed_uint()?;
        let available_data = self.parser.len() - self.parser.pos();

        if length == 0 {
            Ok(String::new())
        } else if length as usize <= available_data {
            let mut bytes = Vec::with_capacity(length as usize);
            for _ in 0..length {
                bytes.push(self.parser.read_le::<u8>()?);
            }
            String::from_utf8(bytes).map_err(|e| {
                malformed_error!(
                    "Invalid UTF-8 in custom attribute string at position {}: {}",
                    self.parser.pos() - length as usize,
                    e.utf8_error()
                )
            })
        } else {
            Err(malformed_error!(
                "String length {} exceeds available data {} (blob context: pos={}, len={}, first_byte=0x{:02X})",
                length,
                available_data,
                self.parser.pos() - 1, // subtract 1 because we already read the length
                self.parser.len(),
                first_byte
            ))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::metadata::{
        identity::AssemblyIdentity,
        tables::Param,
        token::Token,
        typesystem::{CilFlavor, CilPrimitiveKind, CilTypeRef, TypeBuilder, TypeRegistry},
    };
    use crate::test::factories::metadata::customattributes::{
        create_constructor_with_params, create_constructor_with_params_and_registry,
        create_empty_constructor, get_test_type_registry,
    };
    use std::{
        collections::HashMap,
        sync::{
            atomic::{AtomicU64, Ordering},
            Arc, Mutex, OnceLock,
        },
    };

    #[test]
    fn test_parse_empty_blob_with_method() {
        let method = create_empty_constructor();
        let result = parse_custom_attribute_data(&[0x01, 0x00], &method.params).unwrap();
        assert!(result.fixed_args.is_empty());
        assert!(result.named_args.is_empty());
    }

    #[test]
    fn test_parse_invalid_prolog_with_method() {
        let method = create_empty_constructor();
        let result = parse_custom_attribute_data(&[0x00, 0x01], &method.params);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Invalid custom attribute prolog"));
    }

    #[test]
    fn test_parse_simple_blob_with_method() {
        let method = create_empty_constructor();

        // Test case 1: Just prolog
        let blob_data = &[0x01, 0x00];
        let result = parse_custom_attribute_data(blob_data, &method.params).unwrap();
        assert_eq!(result.fixed_args.len(), 0);
        assert_eq!(result.named_args.len(), 0);

        // Test case 2: Valid prolog with no fixed arguments and no named arguments
        let blob_data = &[
            0x01, 0x00, // Prolog (0x0001)
            0x00, 0x00, // NumNamed = 0
        ];
        let result = parse_custom_attribute_data(blob_data, &method.params).unwrap();
        // Without resolved parameter types, fixed args should be empty
        assert_eq!(result.fixed_args.len(), 0);
        assert_eq!(result.named_args.len(), 0);
    }

    #[test]
    fn test_parse_boolean_argument() {
        let method = create_constructor_with_params(vec![CilFlavor::Boolean]);

        let blob_data = &[
            0x01, 0x00, // Prolog
            0x01, // Boolean true
            0x00, 0x00, // NumNamed = 0
        ];

        let result = parse_custom_attribute_data(blob_data, &method.params).unwrap();
        assert_eq!(result.fixed_args.len(), 1);
        match &result.fixed_args[0] {
            CustomAttributeArgument::Bool(val) => assert!(*val),
            _ => panic!("Expected Boolean argument"),
        }
    }

    #[test]
    fn test_parse_char_argument() {
        let method = create_constructor_with_params(vec![CilFlavor::Char]);

        let blob_data = &[
            0x01, 0x00, // Prolog
            0x41, 0x00, // Char 'A' (UTF-16 LE)
            0x00, 0x00, // NumNamed = 0
        ];

        let result = parse_custom_attribute_data(blob_data, &method.params).unwrap();
        assert_eq!(result.fixed_args.len(), 1);
        match &result.fixed_args[0] {
            CustomAttributeArgument::Char(val) => assert_eq!(*val, 'A'),
            _ => panic!("Expected Char argument"),
        }
    }

    #[test]
    fn test_parse_integer_arguments() {
        let method = create_constructor_with_params(vec![
            CilFlavor::I1,
            CilFlavor::U1,
            CilFlavor::I2,
            CilFlavor::U2,
            CilFlavor::I4,
            CilFlavor::U4,
            CilFlavor::I8,
            CilFlavor::U8,
        ]);

        let blob_data = &[
            0x01, 0x00, // Prolog
            0xFF, // I1: -1
            0x42, // U1: 66
            0x00, 0x80, // I2: -32768 (LE)
            0xFF, 0xFF, // U2: 65535 (LE)
            0x00, 0x00, 0x00, 0x80, // I4: -2147483648 (LE)
            0xFF, 0xFF, 0xFF, 0xFF, // U4: 4294967295 (LE)
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, // I8: -9223372036854775808 (LE)
            0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // U8: 18446744073709551615 (LE)
            0x00, 0x00, // NumNamed = 0
        ];

        // Using direct API
        let result = parse_custom_attribute_data(blob_data, &method.params).unwrap();
        assert_eq!(result.fixed_args.len(), 8);

        match &result.fixed_args[0] {
            CustomAttributeArgument::I1(val) => assert_eq!(*val, -1i8),
            _ => panic!("Expected I1 argument"),
        }
        match &result.fixed_args[1] {
            CustomAttributeArgument::U1(val) => assert_eq!(*val, 66u8),
            _ => panic!("Expected U1 argument"),
        }
        match &result.fixed_args[2] {
            CustomAttributeArgument::I2(val) => assert_eq!(*val, -32768i16),
            _ => panic!("Expected I2 argument"),
        }
        match &result.fixed_args[3] {
            CustomAttributeArgument::U2(val) => assert_eq!(*val, 65535u16),
            _ => panic!("Expected U2 argument"),
        }
        match &result.fixed_args[4] {
            CustomAttributeArgument::I4(val) => assert_eq!(*val, -2147483648i32),
            _ => panic!("Expected I4 argument"),
        }
        match &result.fixed_args[5] {
            CustomAttributeArgument::U4(val) => assert_eq!(*val, 4294967295u32),
            _ => panic!("Expected U4 argument"),
        }
        match &result.fixed_args[6] {
            CustomAttributeArgument::I8(val) => assert_eq!(*val, -9223372036854775808i64),
            _ => panic!("Expected I8 argument"),
        }
        match &result.fixed_args[7] {
            CustomAttributeArgument::U8(val) => assert_eq!(*val, 18446744073709551615u64),
            _ => panic!("Expected U8 argument"),
        }
    }

    #[test]
    fn test_parse_floating_point_arguments() {
        let method = create_constructor_with_params(vec![CilFlavor::R4, CilFlavor::R8]);

        let blob_data = &[
            0x01, 0x00, // Prolog
            0x00, 0x00, 0x20, 0x41, // R4: 10.0 (LE)
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x24, 0x40, // R8: 10.0 (LE)
            0x00, 0x00, // NumNamed = 0
        ];

        // Using direct API
        let result = parse_custom_attribute_data(blob_data, &method.params).unwrap();
        assert_eq!(result.fixed_args.len(), 2);

        match &result.fixed_args[0] {
            CustomAttributeArgument::R4(val) => assert_eq!(*val, 10.0f32),
            _ => panic!("Expected R4 argument"),
        }
        match &result.fixed_args[1] {
            CustomAttributeArgument::R8(val) => assert_eq!(*val, 10.0f64),
            _ => panic!("Expected R8 argument"),
        }
    }

    #[test]
    fn test_parse_native_integer_arguments() {
        let method = create_constructor_with_params(vec![CilFlavor::I, CilFlavor::U]);

        #[cfg(target_pointer_width = "64")]
        let blob_data = &[
            0x01, 0x00, // Prolog
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x80, // I: -9223372036854775808 (LE, 64-bit)
            0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
            0xFF, // U: 18446744073709551615 (LE, 64-bit)
            0x00, 0x00, // NumNamed = 0
        ];

        #[cfg(target_pointer_width = "32")]
        let blob_data = &[
            0x01, 0x00, // Prolog
            0x00, 0x00, 0x00, 0x80, // I: -2147483648 (LE, 32-bit)
            0xFF, 0xFF, 0xFF, 0xFF, // U: 4294967295 (LE, 32-bit)
            0x00, 0x00, // NumNamed = 0
        ];

        // Using direct API
        let result = parse_custom_attribute_data(blob_data, &method.params).unwrap();
        assert_eq!(result.fixed_args.len(), 2);

        match &result.fixed_args[0] {
            CustomAttributeArgument::I(_) => (), // Value depends on platform
            _ => panic!("Expected I argument"),
        }
        match &result.fixed_args[1] {
            CustomAttributeArgument::U(_) => (), // Value depends on platform
            _ => panic!("Expected U argument"),
        }
    }

    #[test]
    fn test_parse_string_argument() {
        let method = create_constructor_with_params(vec![CilFlavor::String]);

        let blob_data = &[
            0x01, 0x00, // Prolog
            0x05, // String length (compressed)
            0x48, 0x65, 0x6C, 0x6C, 0x6F, // "Hello"
            0x00, 0x00, // NumNamed = 0
        ];

        // Using direct API
        let result = parse_custom_attribute_data(blob_data, &method.params).unwrap();
        assert_eq!(result.fixed_args.len(), 1);
        match &result.fixed_args[0] {
            CustomAttributeArgument::String(val) => assert_eq!(val, "Hello"),
            _ => panic!("Expected String argument"),
        }
    }

    #[test]
    fn test_parse_class_as_type_argument() {
        let method = create_constructor_with_params(vec![CilFlavor::Class]);

        let blob_data = &[
            0x01, 0x00, // Prolog
            0x0C, // Type name length (compressed) - 12 bytes for "System.Int32"
            0x53, 0x79, 0x73, 0x74, 0x65, 0x6D, 0x2E, 0x49, 0x6E, 0x74, 0x33,
            0x32, // "System.Int32"
            0x00, 0x00, // NumNamed = 0
        ];

        // Class types are parsed as Type arguments when they represent System.Type references
        let result = parse_custom_attribute_data(blob_data, &method.params).unwrap();
        assert_eq!(result.fixed_args.len(), 1);
        // Parser may return either Type or String depending on context
        match &result.fixed_args[0] {
            CustomAttributeArgument::Type(val) => assert_eq!(val, "System.Int32"),
            CustomAttributeArgument::String(val) => assert_eq!(val, "System.Int32"),
            other => panic!("Expected Type or String argument, got: {other:?}"),
        }
    }

    #[test]
    fn test_parse_class_argument_scenarios() {
        let test_registry = get_test_type_registry();

        // Test basic class scenarios that should work
        let method1 =
            create_constructor_with_params_and_registry(vec![CilFlavor::Class], &test_registry);
        let blob_data1 = &[
            0x01, 0x00, // Prolog
            0x00, // Compressed length: 0 (empty string)
            0x00, 0x00, // NumNamed = 0
        ];

        let result1 =
            parse_custom_attribute_data_with_registry(blob_data1, &method1.params, &test_registry);
        match result1 {
            Ok(attr) => {
                assert_eq!(attr.fixed_args.len(), 1);
                // Accept either Type or String argument based on actual parser behavior
                match &attr.fixed_args[0] {
                    CustomAttributeArgument::Type(s) => assert_eq!(s, ""),
                    CustomAttributeArgument::String(s) => assert_eq!(s, ""),
                    _ => panic!("Expected empty string or type argument"),
                }
            }
            Err(e) => panic!("Expected success for empty string, got: {e}"),
        }
    }

    #[test]
    fn test_parse_valuetype_enum_argument() {
        let test_registry = get_test_type_registry();
        let method =
            create_constructor_with_params_and_registry(vec![CilFlavor::ValueType], &test_registry);

        let blob_data = &[
            0x01, 0x00, // Prolog
            0x01, 0x00, 0x00, 0x00, // Enum value as I4 (1)
            0x00, 0x00, // NumNamed = 0
        ];

        let result =
            parse_custom_attribute_data_with_registry(blob_data, &method.params, &test_registry)
                .unwrap();
        assert_eq!(result.fixed_args.len(), 1);
        match &result.fixed_args[0] {
            CustomAttributeArgument::Enum(type_name, boxed_val) => {
                // Accept either "Unknown" or "System.TestEnum" based on actual parser behavior
                assert!(type_name == "Unknown" || type_name == "System.TestEnum");
                match boxed_val.as_ref() {
                    CustomAttributeArgument::I4(val) => assert_eq!(*val, 1),
                    _ => panic!("Expected I4 in enum"),
                }
            }
            _ => panic!("Expected Enum argument"),
        }
    }

    #[test]
    fn test_parse_void_argument() {
        let method = create_constructor_with_params(vec![CilFlavor::Void]);

        let blob_data = &[
            0x01, 0x00, // Prolog
            0x00, 0x00, // NumNamed = 0
        ];

        // Using direct API
        let result = parse_custom_attribute_data(blob_data, &method.params).unwrap();
        assert_eq!(result.fixed_args.len(), 1);
        match &result.fixed_args[0] {
            CustomAttributeArgument::Void => (),
            _ => panic!("Expected Void argument"),
        }
    }

    #[test]
    fn test_parse_array_argument_error() {
        let method = create_constructor_with_params(vec![CilFlavor::Array {
            element_type: Box::new(CilFlavor::I4),
            rank: 1,
            dimensions: vec![],
        }]);

        let blob_data = &[
            0x01, 0x00, // Prolog
            0x03, 0x00, 0x00, 0x00, // Array element count (I4) = 3
            0x00, 0x00, // NumNamed = 0
        ];

        // Using direct API
        let result = parse_custom_attribute_data(blob_data, &method.params);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Array type has no base element type information"));
    }

    #[test]
    fn test_parse_simple_array_argument() {
        // Create an array type with I4 elements using TypeBuilder
        let test_identity = AssemblyIdentity::parse("TestAssembly, Version=1.0.0.0").unwrap();
        let type_registry = Arc::new(TypeRegistry::new(test_identity).unwrap());

        // Create the array type using TypeBuilder to properly set the base type
        let array_type = TypeBuilder::new(type_registry.clone())
            .primitive(CilPrimitiveKind::I4)
            .unwrap()
            .array()
            .unwrap()
            .build()
            .unwrap();

        // Create method with the array parameter
        let method = create_empty_constructor();
        let param = Arc::new(Param {
            rid: 1,
            token: Token::new(0x08000001),
            offset: 0,
            flags: 0,
            sequence: 1,
            name: Some("arrayParam".to_string()),
            default: OnceLock::new(),
            marshal: OnceLock::new(),
            modifiers: Arc::new(boxcar::Vec::new()),
            base: OnceLock::new(),
            is_by_ref: std::sync::atomic::AtomicBool::new(false),
            custom_attributes: Arc::new(boxcar::Vec::new()),
        });
        param.base.set(CilTypeRef::from(array_type)).ok();
        method.params.push(param);

        // Test blob data: array with 3 I4 elements
        let blob_data = &[
            0x01, 0x00, // Prolog
            0x03, 0x00, 0x00, 0x00, // Array element count (I4) = 3
            0x01, 0x00, 0x00, 0x00, // First I4: 1
            0x02, 0x00, 0x00, 0x00, // Second I4: 2
            0x03, 0x00, 0x00, 0x00, // Third I4: 3
            0x00, 0x00, // NumNamed = 0
        ];

        // Using direct API
        let result = parse_custom_attribute_data(blob_data, &method.params).unwrap();
        assert_eq!(result.fixed_args.len(), 1);

        match &result.fixed_args[0] {
            CustomAttributeArgument::Array(elements) => {
                assert_eq!(elements.len(), 3);
                match &elements[0] {
                    CustomAttributeArgument::I4(val) => assert_eq!(*val, 1),
                    _ => panic!("Expected I4 element"),
                }
                match &elements[1] {
                    CustomAttributeArgument::I4(val) => assert_eq!(*val, 2),
                    _ => panic!("Expected I4 element"),
                }
                match &elements[2] {
                    CustomAttributeArgument::I4(val) => assert_eq!(*val, 3),
                    _ => panic!("Expected I4 element"),
                }
            }
            _ => panic!("Expected Array argument"),
        }

        // Keep the type registry alive for the duration of the test
        static TYPE_REGISTRIES: OnceLock<Mutex<HashMap<u64, Arc<TypeRegistry>>>> = OnceLock::new();
        static COUNTER: AtomicU64 = AtomicU64::new(1);

        let registries = TYPE_REGISTRIES.get_or_init(|| Mutex::new(HashMap::new()));
        let mut registries_lock = registries.lock().unwrap();
        let key = COUNTER.fetch_add(1, Ordering::SeqCst);
        registries_lock.insert(key, type_registry);
    }

    #[test]
    fn test_parse_multidimensional_array_error() {
        let method = create_constructor_with_params(vec![CilFlavor::Array {
            element_type: Box::new(CilFlavor::I4),
            rank: 2,
            dimensions: vec![],
        }]);

        let blob_data = &[
            0x01, 0x00, // Prolog
            0x00, 0x00, // NumNamed = 0
        ];

        // Using direct API
        let result = parse_custom_attribute_data(blob_data, &method.params);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Multi-dimensional arrays not supported"));
    }

    #[test]
    fn test_parse_named_arguments() {
        let method = create_empty_constructor();

        let blob_data = &[
            0x01, 0x00, // Prolog
            0x02, 0x00, // NumNamed = 2
            // First named argument (field)
            0x53, // Field indicator
            0x08, // I4 type
            0x05, // Name length
            0x56, 0x61, 0x6C, 0x75, 0x65, // "Value"
            0x2A, 0x00, 0x00, 0x00, // I4 value: 42
            // Second named argument (property)
            0x54, // Property indicator
            0x0E, // String type
            0x04, // Name length
            0x4E, 0x61, 0x6D, 0x65, // "Name"
            0x04, // String value length
            0x54, 0x65, 0x73, 0x74, // "Test"
        ];

        // Using direct API
        let result = parse_custom_attribute_data(blob_data, &method.params).unwrap();
        assert_eq!(result.fixed_args.len(), 0);
        assert_eq!(result.named_args.len(), 2);

        // Check first named argument (field)
        let field_arg = &result.named_args[0];
        assert!(field_arg.is_field);
        assert_eq!(field_arg.name, "Value");
        assert_eq!(field_arg.arg_type, "I4");
        match &field_arg.value {
            CustomAttributeArgument::I4(val) => assert_eq!(*val, 42),
            _ => panic!("Expected I4 value"),
        }

        // Check second named argument (property)
        let prop_arg = &result.named_args[1];
        assert!(!prop_arg.is_field);
        assert_eq!(prop_arg.name, "Name");
        assert_eq!(prop_arg.arg_type, "String");
        match &prop_arg.value {
            CustomAttributeArgument::String(val) => assert_eq!(val, "Test"),
            _ => panic!("Expected String value"),
        }
    }

    #[test]
    fn test_parse_named_argument_char_type() {
        let method = create_empty_constructor();

        let blob_data = &[
            0x01, 0x00, // Prolog
            0x01, 0x00, // NumNamed = 1
            0x53, // Field indicator
            0x03, // Char type
            0x06, // Name length
            0x4C, 0x65, 0x74, 0x74, 0x65, 0x72, // "Letter"
            0x5A, 0x00, // Char value: 'Z' (UTF-16 LE)
        ];

        // Using direct API
        let result = parse_custom_attribute_data(blob_data, &method.params).unwrap();
        assert_eq!(result.named_args.len(), 1);

        let named_arg = &result.named_args[0];
        assert_eq!(named_arg.arg_type, "Char");
        match &named_arg.value {
            CustomAttributeArgument::Char(val) => assert_eq!(*val, 'Z'),
            _ => panic!("Expected Char value"),
        }
    }

    #[test]
    fn test_parse_invalid_named_argument_type() {
        let method = create_empty_constructor();

        let blob_data = &[
            0x01, 0x00, // Prolog
            0x01, 0x00, // NumNamed = 1
            0x99, // Invalid field/property indicator (should be 0x53 or 0x54)
            0x08, // Valid type indicator (I4)
            0x04, // Name length
            0x54, 0x65, 0x73, 0x74, // "Test"
        ];

        // Using direct API
        let result = parse_custom_attribute_data(blob_data, &method.params);
        assert!(result.is_err());
        if let Err(e) = result {
            assert!(e.to_string().contains("Invalid field/property indicator"));
        }
    }

    #[test]
    fn test_parse_malformed_data_errors() {
        let method = create_constructor_with_params(vec![CilFlavor::I4]);

        // Test insufficient data for fixed argument
        let blob_data = &[
            0x01, 0x00, // Prolog
            0x00, 0x00, // Not enough data for I4
        ];

        let result = parse_custom_attribute_data(blob_data, &method.params);
        assert!(result.is_err());
        let error_msg = result.unwrap_err().to_string();
        // Be more flexible with error message matching - accept "Out of Bound" messages too
        assert!(
            error_msg.contains("data")
                || error_msg.contains("I4")
                || error_msg.contains("enough")
                || error_msg.contains("Out of Bound")
                || error_msg.contains("bound"),
            "Error should mention data, I4, or bound issue: {error_msg}"
        );

        // Test string with invalid length
        let method_string = create_constructor_with_params(vec![CilFlavor::String]);
        let blob_data = &[
            0x01, 0x00, // Prolog
            0xFF, 0xFF, 0xFF, 0xFF, 0x0F, // Invalid compressed length (too large)
        ];

        let result = parse_custom_attribute_data(blob_data, &method_string.params);
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_mixed_fixed_and_named_arguments() {
        let method = create_constructor_with_params(vec![CilFlavor::I4, CilFlavor::String]);

        let blob_data = &[
            0x01, 0x00, // Prolog
            // Fixed arguments
            0x2A, 0x00, 0x00, 0x00, // I4: 42
            0x05, // String length
            0x48, 0x65, 0x6C, 0x6C, 0x6F, // "Hello"
            // Named arguments
            0x01, 0x00, // NumNamed = 1
            0x54, // Property indicator
            0x02, // Boolean type
            0x07, // Name length
            0x45, 0x6E, 0x61, 0x62, 0x6C, 0x65, 0x64, // "Enabled"
            0x01, // Boolean true
        ];

        // Using direct API
        let result = parse_custom_attribute_data(blob_data, &method.params).unwrap();
        assert_eq!(result.fixed_args.len(), 2);
        assert_eq!(result.named_args.len(), 1);

        // Check fixed arguments
        match &result.fixed_args[0] {
            CustomAttributeArgument::I4(val) => assert_eq!(*val, 42),
            _ => panic!("Expected I4 argument"),
        }
        match &result.fixed_args[1] {
            CustomAttributeArgument::String(val) => assert_eq!(val, "Hello"),
            _ => panic!("Expected String argument"),
        }

        // Check named argument
        let named_arg = &result.named_args[0];
        assert!(!named_arg.is_field);
        assert_eq!(named_arg.name, "Enabled");
        assert_eq!(named_arg.arg_type, "Boolean");
        match &named_arg.value {
            CustomAttributeArgument::Bool(val) => assert!(*val),
            _ => panic!("Expected Boolean value"),
        }
    }

    #[test]
    fn test_parse_utf16_edge_cases() {
        let method = create_constructor_with_params(vec![CilFlavor::Char]);

        // Test invalid UTF-16 value (should be replaced with replacement character)
        let blob_data = &[
            0x01, 0x00, // Prolog
            0x00, 0xD8, // Invalid UTF-16 surrogate (0xD800)
            0x00, 0x00, // NumNamed = 0
        ];

        // Using direct API
        let result = parse_custom_attribute_data(blob_data, &method.params).unwrap();
        assert_eq!(result.fixed_args.len(), 1);
        match &result.fixed_args[0] {
            CustomAttributeArgument::Char(val) => assert_eq!(*val, '\u{FFFD}'), // Replacement character
            _ => panic!("Expected Char argument"),
        }
    }

    #[test]
    fn test_unsupported_type_flavor_error() {
        let method = create_constructor_with_params(vec![CilFlavor::Pointer]);

        let blob_data = &[
            0x01, 0x00, // Prolog
            0x00, 0x00, // NumNamed = 0
        ];

        // Using direct API
        let result = parse_custom_attribute_data(blob_data, &method.params);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Unsupported type flavor in custom attribute"));
    }

    #[test]
    fn test_empty_string_argument() {
        let method = create_constructor_with_params(vec![CilFlavor::String]);

        let blob_data = &[
            0x01, 0x00, // Prolog
            0x00, // String length = 0
            0x00, 0x00, // NumNamed = 0
        ];

        // Using direct API
        let result = parse_custom_attribute_data(blob_data, &method.params).unwrap();
        assert_eq!(result.fixed_args.len(), 1);
        match &result.fixed_args[0] {
            CustomAttributeArgument::String(val) => assert_eq!(val, ""),
            _ => panic!("Expected String argument"),
        }
    }

    #[test]
    fn test_parse_unsupported_named_argument_type() {
        let method = create_empty_constructor();

        let blob_data = &[
            0x01, 0x00, // Prolog
            0x01, 0x00, // NumNamed = 1
            0x53, // Valid field indicator
            0xFF, // Unsupported type indicator
            0x04, // Name length
            0x54, 0x65, 0x73, 0x74, // "Test"
        ];

        // Using direct API
        let result = parse_custom_attribute_data(blob_data, &method.params);
        // Strict parsing should fail on unsupported types
        assert!(result.is_err());
        if let Err(e) = result {
            assert!(e
                .to_string()
                .contains("Unsupported named argument type: 0xFF"));
        }
    }
}