llvm-native-core 0.1.13

LLVM-native core semantic engine — IR, CodeGen, X86 MC, Clang frontend pipeline
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
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
//! clang_embedded — Embedded systems support for Clang.
//!
//! Provides target triple support, bare-metal startup, linker scripts,
//! interrupt vector tables, libc integration, semihosting, ITM/SWO trace,
//! MPU configuration, stack overflow protection, and heap configuration
//! for embedded targets.
//!
//! Targets: ARM Cortex-M, RISC-V, AVR, MSP430, Xtensa ESP32.
//!
//! Clean-room reconstruction from ARM documentation, RISC-V specs,
//! and published embedded toolchain design.

use std::fmt;

// ============================================================================
// Target Triple Support for Embedded
// ============================================================================

/// Embedded target architecture.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum EmbeddedArch {
    ArmCortexM0,
    ArmCortexM0Plus,
    ArmCortexM3,
    ArmCortexM4,
    ArmCortexM7,
    ArmCortexM23,
    ArmCortexM33,
    ArmCortexM35P,
    ArmCortexM55,
    ArmCortexM85,
    Riscv32Imac,
    Riscv32ImacZicsr,
    Riscv32Imc,
    Riscv64Imac,
    Avr,
    AvrXmega,
    Msp430,
    Msp430x,
    XtensaLx6,
    XtensaLx7,
}

impl EmbeddedArch {
    /// Returns the canonical target triple for this architecture.
    pub fn target_triple(&self) -> &'static str {
        match self {
            Self::ArmCortexM0 => "thumbv6m-none-eabi",
            Self::ArmCortexM0Plus => "thumbv6m-none-eabi",
            Self::ArmCortexM3 => "thumbv7m-none-eabi",
            Self::ArmCortexM4 => "thumbv7em-none-eabihf",
            Self::ArmCortexM7 => "thumbv7em-none-eabihf",
            Self::ArmCortexM23 => "thumbv8m.base-none-eabi",
            Self::ArmCortexM33 => "thumbv8m.main-none-eabihf",
            Self::ArmCortexM35P => "thumbv8m.main-none-eabihf",
            Self::ArmCortexM55 => "thumbv8.1m.main-none-eabihf",
            Self::ArmCortexM85 => "thumbv8.1m.main-none-eabihf",
            Self::Riscv32Imac => "riscv32-unknown-elf",
            Self::Riscv32ImacZicsr => "riscv32-unknown-elf",
            Self::Riscv32Imc => "riscv32-unknown-elf",
            Self::Riscv64Imac => "riscv64-unknown-elf",
            Self::Avr => "avr-unknown-unknown",
            Self::AvrXmega => "avr-unknown-unknown",
            Self::Msp430 => "msp430-none-elf",
            Self::Msp430x => "msp430-none-elf",
            Self::XtensaLx6 => "xtensa-esp32-none-elf",
            Self::XtensaLx7 => "xtensa-esp32s2-none-elf",
        }
    }

    /// Returns the CPU flag for Clang.
    pub fn cpu_flag(&self) -> &'static str {
        match self {
            Self::ArmCortexM0 => "cortex-m0",
            Self::ArmCortexM0Plus => "cortex-m0plus",
            Self::ArmCortexM3 => "cortex-m3",
            Self::ArmCortexM4 => "cortex-m4",
            Self::ArmCortexM7 => "cortex-m7",
            Self::ArmCortexM23 => "cortex-m23",
            Self::ArmCortexM33 => "cortex-m33",
            Self::ArmCortexM35P => "cortex-m35p",
            Self::ArmCortexM55 => "cortex-m55",
            Self::ArmCortexM85 => "cortex-m85",
            Self::Riscv32Imac => "generic-rv32",
            Self::Riscv32ImacZicsr => "generic-rv32",
            Self::Riscv32Imc => "generic-rv32",
            Self::Riscv64Imac => "generic-rv64",
            Self::Avr => "atmega328p",
            Self::AvrXmega => "atxmega128a1",
            Self::Msp430 => "msp430",
            Self::Msp430x => "msp430x",
            Self::XtensaLx6 => "esp32",
            Self::XtensaLx7 => "esp32s2",
        }
    }

    /// Returns the pointer width in bits.
    pub fn pointer_width(&self) -> u32 {
        match self {
            Self::ArmCortexM0
            | Self::ArmCortexM0Plus
            | Self::ArmCortexM3
            | Self::ArmCortexM4
            | Self::ArmCortexM7
            | Self::ArmCortexM23
            | Self::ArmCortexM33
            | Self::ArmCortexM35P
            | Self::ArmCortexM55
            | Self::ArmCortexM85 => 32,
            Self::Riscv32Imac | Self::Riscv32ImacZicsr | Self::Riscv32Imc => 32,
            Self::Riscv64Imac => 64,
            Self::Avr | Self::AvrXmega => 16,
            Self::Msp430 | Self::Msp430x => 16,
            Self::XtensaLx6 | Self::XtensaLx7 => 32,
        }
    }

    /// Returns the architecture family.
    pub fn family(&self) -> EmbeddedArchFamily {
        match self {
            Self::ArmCortexM0
            | Self::ArmCortexM0Plus
            | Self::ArmCortexM3
            | Self::ArmCortexM4
            | Self::ArmCortexM7
            | Self::ArmCortexM23
            | Self::ArmCortexM33
            | Self::ArmCortexM35P
            | Self::ArmCortexM55
            | Self::ArmCortexM85 => EmbeddedArchFamily::Arm,
            Self::Riscv32Imac
            | Self::Riscv32ImacZicsr
            | Self::Riscv32Imc
            | Self::Riscv64Imac => EmbeddedArchFamily::RiscV,
            Self::Avr | Self::AvrXmega => EmbeddedArchFamily::Avr,
            Self::Msp430 | Self::Msp430x => EmbeddedArchFamily::Msp430,
            Self::XtensaLx6 | Self::XtensaLx7 => EmbeddedArchFamily::Xtensa,
        }
    }

    /// Returns whether this is a Thumb-only ARM variant.
    pub fn is_thumb_only(&self) -> bool {
        matches!(self.family(), EmbeddedArchFamily::Arm)
    }
}

/// Architecture family for embedded targets.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EmbeddedArchFamily {
    Arm,
    RiscV,
    Avr,
    Msp430,
    Xtensa,
}

/// Embedded target triple parser.
pub struct EmbeddedTriple {
    pub arch: String,
    pub vendor: String,
    pub os: String,
    pub abi: String,
}

impl EmbeddedTriple {
    pub fn parse(triple: &str) -> Option<Self> {
        let parts: Vec<&str> = triple.split('-').collect();
        if parts.len() < 3 {
            return None;
        }
        let arch = parts[0].to_string();
        let vendor = parts[1].to_string();
        let os = parts[2].to_string();
        let abi = if parts.len() > 3 {
            parts[3..].join("-")
        } else {
            String::new()
        };
        Some(Self {
            arch,
            vendor,
            os,
            abi,
        })
    }

    /// Identify the embedded architecture from the triple.
    pub fn identify_arch(&self) -> Option<EmbeddedArch> {
        match self.arch.as_str() {
            "thumbv6m" => Some(EmbeddedArch::ArmCortexM0),
            "thumbv7m" => Some(EmbeddedArch::ArmCortexM3),
            "thumbv7em" => Some(EmbeddedArch::ArmCortexM4),
            "thumbv8m.base" => Some(EmbeddedArch::ArmCortexM23),
            "thumbv8m.main" => Some(EmbeddedArch::ArmCortexM33),
            "thumbv8.1m.main" => Some(EmbeddedArch::ArmCortexM55),
            "riscv32" => Some(EmbeddedArch::Riscv32Imac),
            "riscv64" => Some(EmbeddedArch::Riscv64Imac),
            "avr" => Some(EmbeddedArch::Avr),
            "msp430" => Some(EmbeddedArch::Msp430),
            "xtensa" => Some(EmbeddedArch::XtensaLx6),
            _ => None,
        }
    }

    /// Check if this is an embedded (bare-metal) target.
    pub fn is_bare_metal(&self) -> bool {
        matches!(self.os.as_str(), "none" | "unknown" | "elf")
    }
}

impl fmt::Display for EmbeddedTriple {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if self.abi.is_empty() {
            write!(f, "{}-{}-{}", self.arch, self.vendor, self.os)
        } else {
            write!(f, "{}-{}-{}-{}", self.arch, self.vendor, self.os, self.abi)
        }
    }
}

// ============================================================================
// Bare-Metal Startup (crt0 equivalent)
// ============================================================================

/// Startup file generator for bare-metal programs.
pub struct BareMetalStartup {
    pub arch: EmbeddedArch,
    pub stack_top: u64,
    pub heap_start: u64,
    pub heap_size: u64,
    pub bss_start: u64,
    pub bss_size: u64,
    pub data_load_addr: u64,
    pub data_start: u64,
    pub data_size: u64,
}

impl BareMetalStartup {
    pub fn new(arch: EmbeddedArch) -> Self {
        Self {
            arch,
            stack_top: 0x20010000,
            heap_start: 0x20001000,
            heap_size: 0x1000,
            bss_start: 0x20000000,
            bss_size: 0x1000,
            data_load_addr: 0x08000100,
            data_start: 0x20000000,
            data_size: 0x100,
        }
    }

    /// Generate the startup assembly for ARM Cortex-M.
    pub fn generate_cortex_m_startup(&self) -> String {
        let mut asm = String::new();
        asm.push_str("// ARM Cortex-M startup code\n");
        asm.push_str("    .syntax unified\n");
        asm.push_str("    .cpu cortex-m4\n");
        asm.push_str("    .thumb\n\n");

        asm.push_str("    .section .vector_table, \"a\"\n");
        asm.push_str("    .global __vector_table\n");
        asm.push_str("__vector_table:\n");
        asm.push_str(&format!(
            "    .word {:#010x}    // initial stack pointer\n",
            self.stack_top
        ));
        asm.push_str("    .word _start          // reset handler\n");
        // Fill other vector entries with default handler
        for i in 1..16 {
            asm.push_str(&format!(
                "    .word default_handler  // exception {}\n",
                i
            ));
        }
        // Additional interrupt vectors
        for i in 16..48 {
            asm.push_str(&format!(
                "    .word default_handler  // IRQ {}\n",
                i - 16
            ));
        }
        asm.push('\n');

        asm.push_str("    .section .text._start, \"ax\"\n");
        asm.push_str("    .global _start\n");
        asm.push_str("    .type _start, %function\n");
        asm.push_str("_start:\n");
        asm.push_str("    // Initialize .data section\n");
        asm.push_str("    ldr r0, =__data_load_addr\n");
        asm.push_str("    ldr r1, =__data_start\n");
        asm.push_str("    ldr r2, =__data_end\n");
        asm.push_str("    cmp r1, r2\n");
        asm.push_str("    beq 1f\n");
        asm.push_str("0:  ldr r3, [r0], #4\n");
        asm.push_str("    str r3, [r1], #4\n");
        asm.push_str("    cmp r1, r2\n");
        asm.push_str("    bne 0b\n");
        asm.push_str("1:\n");
        asm.push_str("    // Zero .bss section\n");
        asm.push_str("    ldr r1, =__bss_start\n");
        asm.push_str("    ldr r2, =__bss_end\n");
        asm.push_str("    movs r0, #0\n");
        asm.push_str("    cmp r1, r2\n");
        asm.push_str("    beq 3f\n");
        asm.push_str("2:  str r0, [r1], #4\n");
        asm.push_str("    cmp r1, r2\n");
        asm.push_str("    bne 2b\n");
        asm.push_str("3:\n");
        asm.push_str("    // Call main\n");
        asm.push_str("    bl main\n");
        asm.push_str("    // Infinite loop if main returns\n");
        asm.push_str("    b .\n\n");

        asm.push_str("    .global default_handler\n");
        asm.push_str("    .type default_handler, %function\n");
        asm.push_str("default_handler:\n");
        asm.push_str("    b .\n");

        asm
    }

    /// Generate startup for RISC-V.
    pub fn generate_riscv_startup(&self) -> String {
        let mut asm = String::new();
        asm.push_str("// RISC-V bare-metal startup\n");
        asm.push_str("    .section .text.init, \"ax\"\n");
        asm.push_str("    .global _start\n");
        asm.push_str("    .align 4\n");
        asm.push_str("_start:\n");
        asm.push_str(&format!(
            "    la sp, {:#010x}       // initialize stack pointer\n",
            self.stack_top
        ));
        asm.push_str("    // Initialize .data section\n");
        asm.push_str("    la t0, __data_load_addr\n");
        asm.push_str("    la t1, __data_start\n");
        asm.push_str("    la t2, __data_end\n");
        asm.push_str("    beq t1, t2, 2f\n");
        asm.push_str("1:  lw t3, 0(t0)\n");
        asm.push_str("    sw t3, 0(t1)\n");
        asm.push_str("    addi t0, t0, 4\n");
        asm.push_str("    addi t1, t1, 4\n");
        asm.push_str("    bne t1, t2, 1b\n");
        asm.push_str("2:\n");
        asm.push_str("    // Zero .bss section\n");
        asm.push_str("    la t1, __bss_start\n");
        asm.push_str("    la t2, __bss_end\n");
        asm.push_str("    beq t1, t2, 4f\n");
        asm.push_str("3:  sw zero, 0(t1)\n");
        asm.push_str("    addi t1, t1, 4\n");
        asm.push_str("    bne t1, t2, 3b\n");
        asm.push_str("4:\n");
        asm.push_str("    // Jump to main\n");
        asm.push_str("    call main\n");
        asm.push_str("    // Spin if main returns\n");
        asm.push_str("    j .\n\n");

        asm.push_str("    .section .vector_table, \"a\"\n");
        asm.push_str("    .align 6\n");
        asm.push_str("__vector_table:\n");
        asm.push_str("    j _start          // reset\n");
        for i in 1..16 {
            asm.push_str(&format!("    j default_handler  // exception {}\n", i));
        }
        asm.push_str("default_handler:\n");
        asm.push_str("    j .\n");

        asm
    }

    /// Generate startup for AVR.
    pub fn generate_avr_startup(&self) -> String {
        let mut asm = String::new();
        asm.push_str("// AVR startup code\n");
        asm.push_str("    .section .vectors, \"ax\"\n");
        asm.push_str("    .global __vectors\n");
        asm.push_str("__vectors:\n");
        asm.push_str(&format!(
            "    rjmp _start       // reset vector\n"
        ));
        for i in 1..26 {
            asm.push_str(&format!("    rjmp __bad_interrupt  // vector {}\n", i));
        }
        asm.push('\n');
        asm.push_str("    .section .text._start, \"ax\"\n");
        asm.push_str("    .global _start\n");
        asm.push_str("_start:\n");
        asm.push_str("    // Set stack pointer\n");
        asm.push_str("    ldi r16, lo8(RAMEND)\n");
        asm.push_str("    out 0x3d, r16\n");
        asm.push_str("    ldi r16, hi8(RAMEND)\n");
        asm.push_str("    out 0x3e, r16\n");
        asm.push_str("    // Clear .bss\n");
        asm.push_str("    ldi r30, lo8(__bss_start)\n");
        asm.push_str("    ldi r31, hi8(__bss_start)\n");
        asm.push_str("    ldi r26, lo8(__bss_end)\n");
        asm.push_str("    ldi r27, hi8(__bss_end)\n");
        asm.push_str("    rjmp 2f\n");
        asm.push_str("1:  st Z+, r1\n");
        asm.push_str("2:  cp r30, r26\n");
        asm.push_str("    cpc r31, r27\n");
        asm.push_str("    brlo 1b\n");
        asm.push_str("    // Copy .data\n");
        asm.push_str("    ldi r30, lo8(__data_load_addr)\n");
        asm.push_str("    ldi r31, hi8(__data_load_addr)\n");
        asm.push_str("    ldi r26, lo8(__data_start)\n");
        asm.push_str("    ldi r27, hi8(__data_start)\n");
        asm.push_str("    rjmp 4f\n");
        asm.push_str("3:  ld r0, Z+\n");
        asm.push_str("    st X+, r0\n");
        asm.push_str("4:  ...\n"); // simplified
        asm.push_str("    // Call main\n");
        asm.push_str("    rcall main\n");
        asm.push_str("    rjmp .\n\n");
        asm.push_str("__bad_interrupt:\n");
        asm.push_str("    rjmp .\n");

        asm
    }

    /// Generate linker script symbols as a string for use in inline assembly.
    pub fn linker_symbols_asm(&self) -> String {
        format!(
            "// Linker symbols\n\
             .global __data_load_addr\n\
             .set __data_load_addr, {data_load}\n\
             .global __data_start\n\
             .set __data_start, {data_start}\n\
             .global __data_end\n\
             .set __data_end, {data_end}\n\
             .global __bss_start\n\
             .set __bss_start, {bss_start}\n\
             .global __bss_end\n\
             .set __bss_end, {bss_end}\n",
            data_load = self.data_load_addr,
            data_start = self.data_start,
            data_end = self.data_start + self.data_size,
            bss_start = self.bss_start,
            bss_end = self.bss_start + self.bss_size,
        )
    }
}

impl Default for BareMetalStartup {
    fn default() -> Self {
        Self::new(EmbeddedArch::ArmCortexM4)
    }
}

// ============================================================================
// Linker Script Generation
// ============================================================================

/// Memory region descriptor for linker scripts.
#[derive(Debug, Clone)]
pub struct MemoryRegion {
    pub name: String,
    pub origin: u64,
    pub length: u64,
    pub attributes: Vec<String>,
}

impl MemoryRegion {
    pub fn new(name: &str, origin: u64, length: u64) -> Self {
        Self {
            name: name.to_string(),
            origin,
            length,
            attributes: Vec::new(),
        }
    }

    pub fn with_attribute(mut self, attr: &str) -> Self {
        self.attributes.push(attr.to_string());
        self
    }
}

/// Section placement descriptor.
#[derive(Debug, Clone)]
pub struct SectionPlacement {
    pub name: String,
    pub region: String,
    pub load_address: Option<u64>,
    pub alignment: u32,
    pub keep: bool,
}

impl SectionPlacement {
    pub fn new(name: &str, region: &str) -> Self {
        Self {
            name: name.to_string(),
            region: region.to_string(),
            load_address: None,
            alignment: 4,
            keep: false,
        }
    }

    pub fn with_alignment(mut self, align: u32) -> Self {
        self.alignment = align;
        self
    }

    pub fn with_load_address(mut self, addr: u64) -> Self {
        self.load_address = Some(addr);
        self
    }

    pub fn with_keep(mut self) -> Self {
        self.keep = true;
        self
    }
}

/// Linker script generator for embedded targets.
pub struct LinkerScript {
    pub arch: EmbeddedArch,
    pub memory_regions: Vec<MemoryRegion>,
    pub sections: Vec<SectionPlacement>,
    pub entry_point: String,
    pub stack_size: u64,
    pub heap_size: u64,
}

impl LinkerScript {
    pub fn new(arch: EmbeddedArch) -> Self {
        let (memory_regions, sections) = default_memory_layout(arch);
        Self {
            arch,
            memory_regions,
            sections,
            entry_point: "_start".to_string(),
            stack_size: 0x2000,
            heap_size: 0x8000,
        }
    }

    /// Generate the linker script content.
    pub fn generate(&self) -> String {
        let mut script = String::new();
        script.push_str("/* Auto-generated linker script */\n");
        script.push_str(&format!("OUTPUT_FORMAT(\"{}\")\n", self.output_format()));
        script.push_str(&format!("ENTRY({})\n\n", self.entry_point));

        // MEMORY block
        script.push_str("MEMORY\n{\n");
        for region in &self.memory_regions {
            let attrs = if region.attributes.is_empty() {
                String::new()
            } else {
                format!(" ({})", region.attributes.join(" "))
            };
            script.push_str(&format!(
                "    {} (rwx){} : ORIGIN = {:#010x}, LENGTH = {:#x}\n",
                region.name, attrs, region.origin, region.length
            ));
        }
        script.push_str("}\n\n");

        // SECTIONS block
        script.push_str("SECTIONS\n{\n");
        for section in &self.sections {
            if section.keep {
                script.push_str(&format!("    KEEP(*({}))\n", section.name));
            } else {
                script.push_str(&format!(
                    "    .{} : ALIGN({})\n    {{\n        *(.{} .{}.*)\n    }} >{}\n",
                    section.name.replace('.', '_'),
                    section.alignment,
                    section.name,
                    section.name,
                    section.region
                ));
            }
        }
        script.push_str("    PROVIDE(__stack_top = ORIGIN(RAM) + LENGTH(RAM));\n");
        script.push_str("    PROVIDE(__heap_start = __stack_top - ");
        script.push_str(&format!("{});\n", self.heap_size));
        script.push_str("}\n");

        script
    }

    fn output_format(&self) -> &'static str {
        match self.arch.family() {
            EmbeddedArchFamily::Arm => "elf32-littlearm",
            EmbeddedArchFamily::RiscV => "elf32-littleriscv",
            EmbeddedArchFamily::Avr => "elf32-avr",
            EmbeddedArchFamily::Msp430 => "elf32-msp430",
            EmbeddedArchFamily::Xtensa => "elf32-xtensa-le",
        }
    }

    /// Add a memory region.
    pub fn add_memory_region(&mut self, region: MemoryRegion) {
        self.memory_regions.push(region);
    }

    /// Add a section placement.
    pub fn add_section(&mut self, section: SectionPlacement) {
        self.sections.push(section);
    }

    /// Set stack size.
    pub fn with_stack_size(mut self, size: u64) -> Self {
        self.stack_size = size;
        self
    }

    /// Set heap size.
    pub fn with_heap_size(mut self, size: u64) -> Self {
        self.heap_size = size;
        self
    }

    /// Get memory regions by name.
    pub fn get_region(&self, name: &str) -> Option<&MemoryRegion> {
        self.memory_regions.iter().find(|r| r.name == name)
    }
}

fn default_memory_layout(arch: EmbeddedArch) -> (Vec<MemoryRegion>, Vec<SectionPlacement>) {
    match arch.family() {
        EmbeddedArchFamily::Arm => (
            vec![
                MemoryRegion::new("FLASH", 0x08000000, 0x00100000),
                MemoryRegion::new("RAM", 0x20000000, 0x00040000),
                MemoryRegion::new("CCMRAM", 0x10000000, 0x00010000)
                    .with_attribute("w"),
            ],
            vec![
                SectionPlacement::new(".vector_table", "FLASH")
                    .with_alignment(512),
                SectionPlacement::new(".text", "FLASH"),
                SectionPlacement::new(".rodata", "FLASH"),
                SectionPlacement::new(".data", "RAM")
                    .with_load_address(0x08000000 + 0x1000),
                SectionPlacement::new(".bss", "RAM"),
                SectionPlacement::new(".heap", "RAM"),
                SectionPlacement::new(".stack", "RAM"),
            ],
        ),
        EmbeddedArchFamily::RiscV => (
            vec![
                MemoryRegion::new("FLASH", 0x20000000, 0x00100000),
                MemoryRegion::new("RAM", 0x80000000, 0x00010000),
            ],
            vec![
                SectionPlacement::new(".text", "FLASH"),
                SectionPlacement::new(".rodata", "FLASH"),
                SectionPlacement::new(".data", "RAM"),
                SectionPlacement::new(".bss", "RAM"),
            ],
        ),
        EmbeddedArchFamily::Avr => (
            vec![
                MemoryRegion::new("FLASH", 0x0000, 0x8000),
                MemoryRegion::new("RAM", 0x0100, 0x0800),
                MemoryRegion::new("EEPROM", 0x0000, 0x0400),
            ],
            vec![
                SectionPlacement::new(".vectors", "FLASH").with_alignment(256),
                SectionPlacement::new(".text", "FLASH"),
                SectionPlacement::new(".data", "RAM"),
                SectionPlacement::new(".bss", "RAM"),
            ],
        ),
        EmbeddedArchFamily::Msp430 => (
            vec![
                MemoryRegion::new("FRAM", 0xC000, 0x4000),
                MemoryRegion::new("RAM", 0x1C00, 0x0800),
            ],
            vec![
                SectionPlacement::new(".vectors", "FRAM").with_alignment(512),
                SectionPlacement::new(".text", "FRAM"),
                SectionPlacement::new(".data", "RAM"),
                SectionPlacement::new(".bss", "RAM"),
            ],
        ),
        EmbeddedArchFamily::Xtensa => (
            vec![
                MemoryRegion::new("IROM", 0x400D0000, 0x00300000),
                MemoryRegion::new("DROM", 0x3F400000, 0x00400000),
                MemoryRegion::new("IRAM", 0x40080000, 0x00020000),
                MemoryRegion::new("DRAM", 0x3FFB0000, 0x00050000),
            ],
            vec![
                SectionPlacement::new(".text", "IROM"),
                SectionPlacement::new(".rodata", "DROM"),
                SectionPlacement::new(".data", "DRAM"),
                SectionPlacement::new(".bss", "DRAM"),
            ],
        ),
    }
}

// ============================================================================
// Interrupt Vector Table
// ============================================================================

/// Interrupt vector entry.
#[derive(Debug, Clone)]
pub struct InterruptVector {
    pub number: u32,
    pub name: String,
    pub handler: String,
    pub priority: u32,
    pub enabled: bool,
}

impl InterruptVector {
    pub fn new(number: u32, name: &str, handler: &str) -> Self {
        Self {
            number,
            name: name.to_string(),
            handler: handler.to_string(),
            priority: 0,
            enabled: true,
        }
    }

    pub fn with_priority(mut self, prio: u32) -> Self {
        self.priority = prio;
        self
    }
}

/// ARM Cortex-M NVIC (Nested Vectored Interrupt Controller).
pub struct CmNvic {
    pub vectors: Vec<InterruptVector>,
    pub priority_grouping: u32,
    pub systick_enabled: bool,
}

impl CmNvic {
    pub fn new() -> Self {
        Self {
            vectors: Vec::new(),
            priority_grouping: 0,
            systick_enabled: true,
        }
    }

    /// Standard Cortex-M system exceptions.
    pub fn system_exceptions() -> Vec<InterruptVector> {
        vec![
            InterruptVector::new(0, "Reset", "_start"),
            InterruptVector::new(1, "NMI", "nmi_handler").with_priority(0),
            InterruptVector::new(2, "HardFault", "hard_fault_handler"),
            InterruptVector::new(3, "MemManage", "mem_manage_handler"),
            InterruptVector::new(4, "BusFault", "bus_fault_handler"),
            InterruptVector::new(5, "UsageFault", "usage_fault_handler"),
            InterruptVector::new(7, "SVCall", "svcall_handler"),
            InterruptVector::new(8, "DebugMon", "debug_mon_handler"),
            InterruptVector::new(10, "PendSV", "pend_sv_handler"),
            InterruptVector::new(11, "SysTick", "sys_tick_handler"),
        ]
    }

    /// Register a peripheral interrupt.
    pub fn register_irq(&mut self, irq_num: u32, name: &str, handler: &str) {
        self.vectors.push(InterruptVector::new(
            16 + irq_num,
            name,
            handler,
        ));
    }

    /// Generate the vector table as assembly.
    pub fn generate_vector_table_asm(&self, stack_top: u64) -> String {
        let mut asm = String::new();
        asm.push_str("    .section .vector_table, \"a\"\n");
        asm.push_str("    .global __vector_table\n");
        asm.push_str("__vector_table:\n");
        asm.push_str(&format!("    .word {:#010x}\n", stack_top));
        for v in &self.vectors {
            asm.push_str(&format!(
                "    .word {}  // {}\n",
                v.handler, v.name
            ));
        }
        // Fill remaining
        let total = 16 + 240; // Cortex-M maximum
        for _ in self.vectors.len()..total {
            asm.push_str("    .word default_handler\n");
        }
        asm
    }

    /// Enable an interrupt in the NVIC.
    pub fn enable_irq(&mut self, irq_num: u32) {
        if let Some(v) = self.vectors
            .iter_mut()
            .find(|v| v.number == 16 + irq_num)
        {
            v.enabled = true;
        }
    }

    /// Disable an interrupt.
    pub fn disable_irq(&mut self, irq_num: u32) {
        if let Some(v) = self.vectors
            .iter_mut()
            .find(|v| v.number == 16 + irq_num)
        {
            v.enabled = false;
        }
    }

    /// Set interrupt priority.
    pub fn set_priority(&mut self, irq_num: u32, priority: u32) {
        let clamped = priority.min(255);
        if let Some(v) = self.vectors
            .iter_mut()
            .find(|v| v.number == 16 + irq_num)
        {
            v.priority = clamped;
        }
    }
}

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

/// RISC-V interrupt controller (PLIC/CLIC).
#[derive(Debug, Clone)]
pub enum RiscVInterruptMode {
    Direct,
    Vectored,
    Clinted,
}

#[derive(Debug, Clone)]
pub struct RiscVInterruptController {
    pub mode: RiscVInterruptMode,
    pub num_interrupts: u32,
    pub mtime_addr: u64,
    pub mtimecmp_addr: u64,
    pub mtime_freq: u64,
}

impl RiscVInterruptController {
    pub fn new_plic(num_interrupts: u32) -> Self {
        Self {
            mode: RiscVInterruptMode::Direct,
            num_interrupts,
            mtime_addr: 0x200BFF8,
            mtimecmp_addr: 0x2004000,
            mtime_freq: 10_000_000,
        }
    }

    pub fn new_clic(num_interrupts: u32) -> Self {
        Self {
            mode: RiscVInterruptMode::Vectored,
            num_interrupts,
            mtime_addr: 0x200BFF8,
            mtimecmp_addr: 0x2004000,
            mtime_freq: 10_000_000,
        }
    }

    /// Generate RISC-V exception handler.
    pub fn generate_trap_handler_asm(&self) -> String {
        let mut asm = String::new();
        asm.push_str("    .section .text.trap, \"ax\"\n");
        asm.push_str("    .align 4\n");
        asm.push_str("    .global trap_entry\n");
        asm.push_str("trap_entry:\n");
        asm.push_str("    // Save context\n");
        asm.push_str("    addi sp, sp, -128\n");
        asm.push_str("    sw ra, 0(sp)\n");
        asm.push_str("    sw t0, 4(sp)\n");
        asm.push_str("    sw t1, 8(sp)\n");
        asm.push_str("    sw a0, 12(sp)\n");
        asm.push_str("    sw a1, 16(sp)\n");
        asm.push_str("    // Read mcause\n");
        asm.push_str("    csrr a0, mcause\n");
        asm.push_str("    csrr a1, mepc\n");
        asm.push_str("    // Call C handler\n");
        asm.push_str("    call trap_handler\n");
        asm.push_str("    // Restore context\n");
        asm.push_str("    lw ra, 0(sp)\n");
        asm.push_str("    lw t0, 4(sp)\n");
        asm.push_str("    lw t1, 8(sp)\n");
        asm.push_str("    lw a0, 12(sp)\n");
        asm.push_str("    lw a1, 16(sp)\n");
        asm.push_str("    addi sp, sp, 128\n");
        asm.push_str("    mret\n");
        asm
    }
}

impl Default for RiscVInterruptController {
    fn default() -> Self {
        Self::new_plic(32)
    }
}

/// AVR interrupt vector definitions.
pub struct AvrInterrupts {
    pub vectors: Vec<InterruptVector>,
}

impl AvrInterrupts {
    pub fn new() -> Self {
        Self {
            vectors: Vec::new(),
        }
    }

    /// Standard ATmega328P interrupts.
    pub fn atmega328p_vectors() -> Vec<InterruptVector> {
        vec![
            InterruptVector::new(0, "RESET", "__vectors"),
            InterruptVector::new(1, "INT0", "int0_handler"),
            InterruptVector::new(2, "INT1", "int1_handler"),
            InterruptVector::new(3, "PCINT0", "pcint0_handler"),
            InterruptVector::new(4, "PCINT1", "pcint1_handler"),
            InterruptVector::new(5, "PCINT2", "pcint2_handler"),
            InterruptVector::new(6, "WDT", "wdt_handler"),
            InterruptVector::new(7, "TIMER2_COMPA", "timer2_compa_handler"),
            InterruptVector::new(8, "TIMER2_COMPB", "timer2_compb_handler"),
            InterruptVector::new(9, "TIMER2_OVF", "timer2_ovf_handler"),
            InterruptVector::new(10, "TIMER1_CAPT", "timer1_capt_handler"),
            InterruptVector::new(11, "TIMER1_COMPA", "timer1_compa_handler"),
            InterruptVector::new(12, "TIMER1_COMPB", "timer1_compb_handler"),
            InterruptVector::new(13, "TIMER1_OVF", "timer1_ovf_handler"),
            InterruptVector::new(14, "TIMER0_COMPA", "timer0_compa_handler"),
            InterruptVector::new(15, "TIMER0_COMPB", "timer0_compb_handler"),
            InterruptVector::new(16, "TIMER0_OVF", "timer0_ovf_handler"),
            InterruptVector::new(17, "SPI_STC", "spi_stc_handler"),
            InterruptVector::new(18, "USART_RX", "usart_rx_handler"),
            InterruptVector::new(19, "USART_UDRE", "usart_udre_handler"),
            InterruptVector::new(20, "USART_TX", "usart_tx_handler"),
            InterruptVector::new(21, "ADC", "adc_handler"),
            InterruptVector::new(22, "EE_READY", "ee_ready_handler"),
            InterruptVector::new(23, "ANALOG_COMP", "analog_comp_handler"),
            InterruptVector::new(24, "TWI", "twi_handler"),
            InterruptVector::new(25, "SPM_READY", "spm_ready_handler"),
        ]
    }
}

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

// ============================================================================
// Newlib/Nano Libc Integration
// ============================================================================

/// Minimal libc for embedded systems (Newlib/nano integration).
#[derive(Debug, Clone)]
pub struct MinimalLibc {
    pub use_newlib_nano: bool,
    pub syscalls_implemented: Vec<String>,
    pub heap_impl: Option<String>,
    pub stdout_device: Option<String>,
    pub stderr_device: Option<String>,
    pub stdin_device: Option<String>,
}

impl MinimalLibc {
    pub fn new() -> Self {
        Self {
            use_newlib_nano: true,
            syscalls_implemented: Vec::new(),
            heap_impl: None,
            stdout_device: Some("usart1".to_string()),
            stderr_device: Some("usart1".to_string()),
            stdin_device: Some("usart1".to_string()),
        }
    }

    /// Essential Newlib syscalls.
    pub fn required_syscalls() -> Vec<&'static str> {
        vec![
            "_sbrk", "_write", "_read", "_close", "_fstat", "_isatty",
            "_lseek", "_exit", "_kill", "_getpid", "_open",
        ]
    }

    /// Generate _write syscall implementation.
    pub fn generate_write_syscall(&self) -> String {
        let mut c = String::new();
        c.push_str("// Minimal _write syscall for semihosting/UART\n");
        c.push_str("#include <sys/stat.h>\n");
        c.push_str("#include <unistd.h>\n\n");
        c.push_str("int _write(int fd, const char *buf, int len) {\n");
        c.push_str("    if (fd == STDOUT_FILENO || fd == STDERR_FILENO) {\n");
        c.push_str("        for (int i = 0; i < len; i++) {\n");
        c.push_str("            // Write to semihosting or UART\n");
        c.push_str("            __asm__ volatile (\n");
        c.push_str("                \"mov r0, #0x03\\n\"  // SYS_WRITEC\n");
        c.push_str("                \"mov r1, %[c]\\n\"\n");
        c.push_str("                \"bkpt #0xAB\\n\"\n");
        c.push_str("                : : [c] \"r\" (buf[i]) : \"r0\", \"r1\"\n");
        c.push_str("            );\n");
        c.push_str("        }\n");
        c.push_str("        return len;\n");
        c.push_str("    }\n");
        c.push_str("    return -1;\n");
        c.push_str("}\n");
        c
    }

    /// Generate _sbrk syscall implementation.
    pub fn generate_sbrk_syscall(&self, heap_start: u64, heap_size: u64) -> String {
        format!(
            "// _sbrk implementation for embedded heap\n\
             #include <unistd.h>\n\n\
             static char *heap_end = (char *){heap_start:#x};\n\
             static char *heap_limit = (char *)({heap_start:#x} + {heap_size:#x});\n\n\
             void *_sbrk(int incr) {{\n\
                 char *prev_heap_end = heap_end;\n\
                 if (heap_end + incr > heap_limit) {{\n\
                     return (void *)-1;  // ENOMEM\n\
                 }}\n\
                 heap_end += incr;\n\
                 return prev_heap_end;\n\
             }}\n",
            heap_start = heap_start,
            heap_size = heap_size,
        )
    }

    /// Generate _exit syscall.
    pub fn generate_exit_syscall(&self) -> &'static str {
        "void _exit(int status) {\n    while (1) { __asm__ volatile (\"wfi\"); }\n}\n"
    }

    /// Generate minimal startup with Newlib integration.
    pub fn generate_newlib_startup(&self, arch: EmbeddedArch) -> String {
        let startup = BareMetalStartup::new(arch);
        match arch.family() {
            EmbeddedArchFamily::Arm => startup.generate_cortex_m_startup(),
            EmbeddedArchFamily::RiscV => startup.generate_riscv_startup(),
            EmbeddedArchFamily::Avr => startup.generate_avr_startup(),
            _ => String::from("// Unsupported arch for newlib startup\n"),
        }
    }

    /// Check if a syscall is implemented.
    pub fn has_syscall(&self, name: &str) -> bool {
        self.syscalls_implemented.iter().any(|s| s == name)
    }

    /// Mark a syscall as implemented.
    pub fn implement_syscall(&mut self, name: &str) {
        if !self.has_syscall(name) {
            self.syscalls_implemented.push(name.to_string());
        }
    }
}

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

// ============================================================================
// Semihosting Support
// ============================================================================

/// Semihosting operation numbers.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SemihostingOp {
    /// SYS_OPEN (0x01) — Open a file on the host.
    SysOpen = 0x01,
    /// SYS_CLOSE (0x02) — Close a file.
    SysClose = 0x02,
    /// SYS_WRITEC (0x03) — Write character to debug console.
    SysWritec = 0x03,
    /// SYS_WRITE0 (0x04) — Write null-terminated string.
    SysWrite0 = 0x04,
    /// SYS_WRITE (0x05) — Write to file.
    SysWrite = 0x05,
    /// SYS_READ (0x06) — Read from file.
    SysRead = 0x06,
    /// SYS_READC (0x07) — Read character.
    SysReadc = 0x07,
    /// SYS_ISERROR (0x08) — Check if return code is error.
    SysIsError = 0x08,
    /// SYS_ISTTY (0x09) — Check if file descriptor is a TTY.
    SysIsTty = 0x09,
    /// SYS_SEEK (0x0A) — Seek to position.
    SysSeek = 0x0A,
    /// SYS_FLEN (0x0C) — Get file length.
    SysFlen = 0x0C,
    /// SYS_TMPNAM (0x0D) — Get temporary file name.
    SysTmpNam = 0x0D,
    /// SYS_REMOVE (0x0E) — Remove file.
    SysRemove = 0x0E,
    /// SYS_RENAME (0x0F) — Rename file.
    SysRename = 0x0F,
    /// SYS_CLOCK (0x10) — Get elapsed time.
    SysClock = 0x10,
    /// SYS_TIME (0x11) — Get current time.
    SysTime = 0x11,
    /// SYS_SYSTEM (0x12) — Execute host command.
    SysSystem = 0x12,
    /// SYS_ERRNO (0x13) — Get errno.
    SysErrno = 0x13,
    /// SYS_GET_CMDLINE (0x15) — Get command line.
    SysGetCmdLine = 0x15,
    /// SYS_HEAPINFO (0x16) — Get heap info.
    SysHeapInfo = 0x16,
    /// SYS_EXIT (0x18) — Exit with status.
    SysExit = 0x18,
    /// SYS_EXIT_EXTENDED (0x20) — Exit with extended status.
    SysExitExtended = 0x20,
    /// SYS_ELAPSED (0x30) — Get elapsed time (microseconds).
    SysElapsed = 0x30,
    /// SYS_TICKFREQ (0x31) — Get tick frequency.
    SysTickFreq = 0x31,
}

impl SemihostingOp {
    pub fn as_u32(self) -> u32 {
        self as u32
    }
}

/// Semihosting call interface.
pub struct Semihosting {
    pub enabled: bool,
    pub target: SemihostingTarget,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SemihostingTarget {
    /// ARM semihosting via BKPT 0xAB.
    ArmBkpt,
    /// RISC-V semihosting via EBREAK.
    RiscVEbreak,
    /// QEMU semihosting (exit with code).
    Qemu,
    /// Custom semihosting trap.
    Custom(u32),
}

impl Semihosting {
    pub fn new(target: SemihostingTarget) -> Self {
        Self {
            enabled: true,
            target,
        }
    }

    /// Generate ARM semihosting call assembly.
    pub fn arm_semihosting_asm(&self, op: SemihostingOp, param: u32) -> String {
        format!(
            "    mov r0, #{op}\n\
                 mov r1, #{param}\n\
                 bkpt #0xAB\n",
            op = op.as_u32(),
            param = param,
        )
    }

    /// Generate RISC-V semihosting call assembly.
    pub fn riscv_semihosting_asm(&self, op: SemihostingOp, param: u32) -> String {
        format!(
            "    li a0, {op}\n\
                 li a1, {param}\n\
                 ebreak\n",
            op = op.as_u32(),
            param = param,
        )
    }

    /// Semihosting write string (SYS_WRITE0).
    pub fn write_string_asm(&self, msg_addr: u64) -> String {
        match self.target {
            SemihostingTarget::ArmBkpt => {
                format!(
                    "    mov r0, #0x04\n\
                         ldr r1, ={msg:#x}\n\
                         bkpt #0xAB\n",
                    msg = msg_addr,
                )
            }
            SemihostingTarget::RiscVEbreak => {
                format!(
                    "    li a0, 4\n\
                         li a1, {msg}\n\
                         ebreak\n",
                    msg = msg_addr,
                )
            }
            _ => String::new(),
        }
    }

    /// Semihosting exit (SYS_EXIT).
    pub fn exit_asm(&self, status: u32) -> String {
        match self.target {
            SemihostingTarget::ArmBkpt => {
                format!(
                    "    mov r0, #0x18\n\
                         mov r1, #{status}\n\
                         bkpt #0xAB\n",
                    status = status,
                )
            }
            SemihostingTarget::RiscVEbreak => {
                format!(
                    "    li a0, 0x18\n\
                         li a1, {status}\n\
                         ebreak\n",
                    status = status,
                )
            }
            SemihostingTarget::Qemu => {
                format!(
                    "    // QEMU semihosting exit\n\
                         .insn 0x00100073  // ebreak with custom encoding\n",
                )
            }
            _ => String::new(),
        }
    }

    /// Test PASS message via semihosting.
    pub fn test_pass_asm(&self) -> String {
        let msg = "PASS\\n\\0";
        match self.target {
            SemihostingTarget::ArmBkpt => {
                format!(
                    "    ldr r0, =msg\n\
                         mov r1, #0x04\n\
                         bkpt #0xAB\n\
                         msg:\n\
                         .asciz \"PASS\\n\"\n",
                )
            }
            SemihostingTarget::RiscVEbreak => {
                format!(
                    "    la a0, msg\n\
                         ebreak\n\
                         msg:\n\
                         .asciz \"PASS\\n\"\n",
                )
            }
            _ => String::from("    // semihosting test PASS\n"),
        }
    }
}

impl Default for Semihosting {
    fn default() -> Self {
        Self::new(SemihostingTarget::ArmBkpt)
    }
}

// ============================================================================
// ITM/SWO Trace Support (ARM Instrumentation Trace Macrocell)
// ============================================================================

/// ARM ITM stimulus port.
#[derive(Debug, Clone)]
pub struct ItmStimulusPort {
    pub port_number: u32,
    pub enabled: bool,
    pub privilege: ItmPrivilege,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ItmPrivilege {
    Any,
    Privileged,
}

/// ITM trace configuration.
pub struct ItmTrace {
    pub enabled: bool,
    pub stimulus_ports: Vec<ItmStimulusPort>,
    pub trace_bus_id: u32,
    pub global_timestamp_enabled: bool,
    pub local_timestamp_enabled: bool,
    pub sync_packets_enabled: bool,
    pub swo_baud_rate: u32,
}

impl ItmTrace {
    pub fn new() -> Self {
        let mut ports = Vec::new();
        for i in 0..32 {
            ports.push(ItmStimulusPort {
                port_number: i,
                enabled: i < 8, // First 8 ports enabled by default
                privilege: ItmPrivilege::Any,
            });
        }
        Self {
            enabled: true,
            stimulus_ports: ports,
            trace_bus_id: 0,
            global_timestamp_enabled: true,
            local_timestamp_enabled: false,
            sync_packets_enabled: true,
            swo_baud_rate: 2_000_000,
        }
    }

    /// Enable a stimulus port.
    pub fn enable_port(&mut self, port: u32) {
        if let Some(p) = self.stimulus_ports.iter_mut().find(|p| p.port_number == port) {
            p.enabled = true;
        }
    }

    /// Disable a stimulus port.
    pub fn disable_port(&mut self, port: u32) {
        if let Some(p) = self.stimulus_ports.iter_mut().find(|p| p.port_number == port) {
            p.enabled = false;
        }
    }

    /// Write a byte to an ITM stimulus port.
    pub fn write_byte(&self, port: u32, byte: u8) -> bool {
        if let Some(p) = self.stimulus_ports.iter().find(|p| p.port_number == port) {
            p.enabled
        } else {
            false
        }
    }

    /// Generate initialization code for ITM.
    pub fn generate_init_code(&self) -> String {
        let mut c = String::new();
        c.push_str("// ITM trace initialization\n");
        c.push_str("void itm_init(void) {\n");
        c.push_str("    // Enable trace in Debug Exception and Monitor Control Register\n");
        c.push_str("    *((volatile uint32_t *)0xE000EDFC) |= (1 << 24);  // TRCENA\n\n");
        c.push_str("    // Unlock ITM registers\n");
        c.push_str("    *((volatile uint32_t *)0xE0000FB0) = 0xC5ACCE55;\n\n");
        c.push_str("    // Configure trace control\n");
        c.push_str(&format!(
            "    *((volatile uint32_t *)0xE0000E80) = 0x{:08X};  // ITM TCR\n",
            self.trace_control_register()
        ));
        c.push('\n');
        // Configure stimulus ports
        for port in &self.stimulus_ports {
            if port.enabled {
                c.push_str(&format!(
                    "    *((volatile uint32_t *)0xE0000E00) |= (1 << {});  // Enable port {}\n",
                    port.port_number, port.port_number
                ));
            }
        }
        c.push_str("}\n");
        c.push('\n');
        c.push_str("void itm_send_char(char c) {\n");
        c.push_str("    // Wait for stimulus port 0 to be ready\n");
        c.push_str("    while (!(*((volatile uint32_t *)0xE0000000) & 1));\n");
        c.push_str("    *((volatile uint32_t *)0xE0000000) = c;\n");
        c.push_str("}\n");
        c
    }

    fn trace_control_register(&self) -> u32 {
        let mut tcr = 0u32;
        if self.enabled {
            tcr |= 1 << 0; // ITMENA
        }
        if self.global_timestamp_enabled {
            tcr |= 1 << 1; // TSENA
        }
        if self.sync_packets_enabled {
            tcr |= 1 << 2; // SYNCENA
        }
        if self.local_timestamp_enabled {
            tcr |= 1 << 3; // TXENA
        }
        tcr |= (self.trace_bus_id & 0x7F) << 16; // TraceBusID
        tcr
    }

    /// Set SWO baud rate.
    pub fn set_swo_baud_rate(&mut self, baud: u32) {
        self.swo_baud_rate = baud;
    }
}

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

// ============================================================================
// MPU Configuration (ARM Cortex-M Memory Protection Unit)
// ============================================================================

/// MPU region attributes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MpuRegionAttributes {
    pub read_enable: bool,
    pub write_enable: bool,
    pub execute_enable: bool,
    pub cacheable: bool,
    pub bufferable: bool,
    pub shareable: bool,
    pub tex: u8,
}

impl Default for MpuRegionAttributes {
    fn default() -> Self {
        Self {
            read_enable: true,
            write_enable: true,
            execute_enable: false,
            cacheable: false,
            bufferable: false,
            shareable: false,
            tex: 0,
        }
    }
}

impl MpuRegionAttributes {
    pub fn ram() -> Self {
        Self {
            read_enable: true,
            write_enable: true,
            execute_enable: false,
            cacheable: true,
            bufferable: true,
            shareable: false,
            tex: 1,
        }
    }

    pub fn flash() -> Self {
        Self {
            read_enable: true,
            write_enable: false,
            execute_enable: true,
            cacheable: true,
            bufferable: false,
            shareable: false,
            tex: 0,
        }
    }

    pub fn device() -> Self {
        Self {
            read_enable: true,
            write_enable: true,
            execute_enable: false,
            cacheable: false,
            bufferable: false,
            shareable: true,
            tex: 2,
        }
    }

    /// Encode attributes into MPU_RASR format.
    pub fn encode(&self, size_log2: u8, subregion_disable: u8) -> u32 {
        let mut rasr = 0u32;
        rasr |= 1; // Enable
        rasr |= (size_log2 as u32 & 0x1F) << 1; // SIZE
        rasr |= (subregion_disable as u32 & 0xFF) << 8; // SRD
        // Access permissions
        let mut ap = 0u32;
        if self.read_enable && self.write_enable {
            ap = 3; // Full access
        } else if self.read_enable {
            ap = 2; // Read-only
        }
        rasr |= ap << 24; // AP
        // TEX, C, B, S
        rasr |= (self.tex as u32 & 0x07) << 19; // TEX
        if self.cacheable {
            rasr |= 1 << 17;
        } // C
        if self.bufferable {
            rasr |= 1 << 16;
        } // B
        if self.shareable {
            rasr |= 1 << 18;
        } // S
        rasr
    }
}

/// MPU region descriptor.
#[derive(Debug, Clone)]
pub struct MpuRegion {
    pub region_number: u32,
    pub base_address: u64,
    pub size: u64,
    pub subregion_disable: u8,
    pub attributes: MpuRegionAttributes,
}

impl MpuRegion {
    pub fn new(region_number: u32, base: u64, size: u64) -> Self {
        Self {
            region_number,
            base_address: base,
            size,
            subregion_disable: 0,
            attributes: MpuRegionAttributes::default(),
        }
    }

    pub fn with_attributes(mut self, attrs: MpuRegionAttributes) -> Self {
        self.attributes = attrs;
        self
    }

    /// Compute the SIZE field (log2 of region size, minimum 32 bytes).
    pub fn size_log2(&self) -> u8 {
        let size = self.size.max(32);
        (63 - size.leading_zeros()) as u8
    }
}

/// ARM Cortex-M MPU configuration.
pub struct MpuConfig {
    pub enabled: bool,
    pub hfnmiena: bool,
    pub privdefena: bool,
    pub regions: Vec<MpuRegion>,
    pub max_regions: u32,
}

impl MpuConfig {
    pub fn new(max_regions: u32) -> Self {
        Self {
            enabled: false,
            hfnmiena: false,
            privdefena: true,
            regions: Vec::new(),
            max_regions,
        }
    }

    /// Cortex-M4 standard MPU config (8 regions).
    pub fn cortex_m4_default() -> Self {
        let mut mpu = Self::new(8);
        mpu.add_region(MpuRegion::new(0, 0x08000000, 0x00100000)
            .with_attributes(MpuRegionAttributes::flash()));
        mpu.add_region(MpuRegion::new(1, 0x20000000, 0x00040000)
            .with_attributes(MpuRegionAttributes::ram()));
        mpu.add_region(MpuRegion::new(2, 0x40000000, 0x20000000)
            .with_attributes(MpuRegionAttributes::device()));
        mpu
    }

    /// Add a memory region.
    pub fn add_region(&mut self, region: MpuRegion) {
        if (self.regions.len() as u32) < self.max_regions {
            self.regions.push(region);
        }
    }

    /// Remove a region.
    pub fn remove_region(&mut self, region_number: u32) {
        self.regions.retain(|r| r.region_number != region_number);
    }

    /// Generate MPU initialization code.
    pub fn generate_init_code(&self) -> String {
        let mut c = String::new();
        c.push_str("void mpu_init(void) {\n");
        c.push_str("    // Disable MPU during configuration\n");
        c.push_str("    *((volatile uint32_t *)0xE000ED94) &= ~1;\n\n");
        for region in &self.regions {
            c.push_str(&format!(
                "    // Region {}: base={:#010x}, size={:#x}\n",
                region.region_number, region.base_address, region.size
            ));
            c.push_str(&format!(
                "    *((volatile uint32_t *)0xE000ED9C) = {};\n",
                region.region_number
            ));
            c.push_str(&format!(
                "    *((volatile uint32_t *)0xE000EDA0) = {:#010x} | (1 << 4);\n",
                region.base_address
            ));
            c.push_str(&format!(
                "    *((volatile uint32_t *)0xE000EDA4) = {:#010x};\n",
                region.attributes.encode(region.size_log2(), region.subregion_disable)
            ));
            c.push('\n');
        }
        c.push_str("    // Enable MPU\n");
        if self.privdefena {
            c.push_str("    *((volatile uint32_t *)0xE000ED94) |= (1 << 0) | (1 << 2);\n");
        } else {
            c.push_str("    *((volatile uint32_t *)0xE000ED94) |= (1 << 0);\n");
        }
        c.push_str("    __asm__ volatile (\"dsb\\nisb\\n\");\n");
        c.push_str("}\n");
        c
    }
}

impl Default for MpuConfig {
    fn default() -> Self {
        Self::cortex_m4_default()
    }
}

// ============================================================================
// Stack Overflow Protection
// ============================================================================

/// Stack canary value for overflow detection.
pub const STACK_CANARY_VALUE: u32 = 0xDEADBEEF;

/// Stack overflow protection configuration.
#[derive(Debug, Clone)]
pub enum StackProtection {
    /// No stack protection.
    None,
    /// Stack canary at stack top.
    Canary { value: u32 },
    /// MPU guard region at stack bottom.
    MpuGuard { region_size: u64 },
    /// Split stacks (LLVM split-stack support).
    SplitStack { segment_size: u64 },
    /// Combined canary + MPU guard.
    Combined { canary_value: u32, guard_size: u64 },
}

impl StackProtection {
    /// Default stack protection with canary.
    pub fn canary() -> Self {
        StackProtection::Canary {
            value: STACK_CANARY_VALUE,
        }
    }

    /// MPU guard-based protection.
    pub fn mpu_guard(size: u64) -> Self {
        StackProtection::MpuGuard { region_size: size }
    }

    /// Split stack.
    pub fn split_stack(segment_size: u64) -> Self {
        StackProtection::SplitStack { segment_size }
    }

    /// Combined protection.
    pub fn combined(canary: u32, guard_size: u64) -> Self {
        StackProtection::Combined {
            canary_value: canary,
            guard_size,
        }
    }

    /// Check if any protection is enabled.
    pub fn is_enabled(&self) -> bool {
        !matches!(self, StackProtection::None)
    }

    /// Generate stack canary initialization code.
    pub fn generate_canary_init(&self) -> String {
        match self {
            StackProtection::Canary { value } | StackProtection::Combined { canary_value: value, .. } => {
                format!(
                    "// Stack canary initialization\n\
                     extern uint32_t __stack_top;\n\
                     *((volatile uint32_t *)&__stack_top) = {:#010x};\n",
                    value
                )
            }
            _ => String::new(),
        }
    }

    /// Generate stack canary check code.
    pub fn generate_canary_check(&self) -> String {
        match self {
            StackProtection::Canary { value } | StackProtection::Combined { canary_value: value, .. } => {
                format!(
                    "// Stack canary check\n\
                     extern uint32_t __stack_top;\n\
                     if (*((volatile uint32_t *)&__stack_top) != {:#010x}) {{\n\
                         // Stack overflow detected!\n\
                         stack_overflow_handler();\n\
                     }}\n",
                    value
                )
            }
            _ => String::new(),
        }
    }

    /// Generate MPU guard region setup.
    pub fn generate_mpu_guard_init(&self) -> String {
        match self {
            StackProtection::MpuGuard { region_size }
            | StackProtection::Combined {
                guard_size: region_size,
                ..
            } => {
                format!(
                    "// MPU guard region for stack overflow detection\n\
                     // Configure region at stack bottom as no-access\n\
                     *((volatile uint32_t *)0xE000ED9C) = 7;  // Select region 7\n\
                     *((volatile uint32_t *)0xE000EDA0) = END_OF_STACK - {size:#x};\n\
                     *((volatile uint32_t *)0xE000EDA4) = 0x00000001 | (({size_log2}) << 1);\n",
                    size = region_size,
                    size_log2 = (63 - region_size.leading_zeros()),
                )
            }
            _ => String::new(),
        }
    }

    /// Generate LLVM split-stack attribute.
    pub fn split_stack_attribute(&self) -> Option<String> {
        match self {
            StackProtection::SplitStack { .. } => Some("split-stack".to_string()),
            _ => None,
        }
    }
}

impl Default for StackProtection {
    fn default() -> Self {
        StackProtection::canary()
    }
}

// ============================================================================
// Heap Configuration
// ============================================================================

/// Heap configuration for embedded systems.
#[derive(Debug, Clone)]
pub struct HeapConfig {
    pub heap_start: u64,
    pub heap_size: u64,
    pub min_align: u32,
    pub use_dlmalloc: bool,
    pub use_tlsf: bool,
    pub custom_impl: Option<String>,
}

impl HeapConfig {
    pub fn new(start: u64, size: u64) -> Self {
        Self {
            heap_start: start,
            heap_size: size,
            min_align: 8,
            use_dlmalloc: false,
            use_tlsf: true,
            custom_impl: None,
        }
    }

    /// Default heap for Cortex-M4 with 64KB heap.
    pub fn cortex_m4_default() -> Self {
        Self::new(0x20001000, 0x10000)
    }

    /// Default heap for RISC-V with 128KB heap.
    pub fn riscv_default() -> Self {
        Self::new(0x80001000, 0x20000)
    }

    /// Default heap for AVR with 1KB heap.
    pub fn avr_default() -> Self {
        Self::new(0x0200, 0x0400)
    }

    /// Generate sbrk implementation for newlib.
    pub fn generate_sbrk(&self) -> String {
        format!(
            "// sbrk() implementation for embedded system\n\
             #include <sys/types.h>\n\
             #include <errno.h>\n\n\
             static uint8_t *__heap_ptr = (uint8_t *){start:#x};\n\
             static uint8_t *__heap_limit = (uint8_t *)({start:#x} + {size:#x});\n\n\
             void *_sbrk(int incr) {{\n\
                 uint8_t *prev_heap_ptr = __heap_ptr;\n\
                 if (__heap_ptr + incr > __heap_limit) {{\n\
                     errno = ENOMEM;\n\
                     return (void *)-1;\n\
                 }}\n\
                 __heap_ptr += incr;\n\
                 return (void *)prev_heap_ptr;\n\
             }}\n",
            start = self.heap_start,
            size = self.heap_size,
        )
    }

    /// Generate malloc/free wrappers for dlmalloc.
    pub fn generate_dlmalloc_config(&self) -> String {
        format!(
            "// dlmalloc configuration\n\
             #define HAVE_MORECORE 0\n\
             #define HAVE_MMAP 0\n\
             #define MSPACES 1\n\
             #define ONLY_MSPACES 1\n\
             #define DEFAULT_GRANULARITY {align}\n\n\
             static mspace __embedded_mspace;\n\n\
             void embedded_malloc_init(void) {{\n\
                 __embedded_mspace = create_mspace_with_base(\n\
                     (void *){start:#x}, {size:#x}, 0);\n\
             }}\n\n\
             void *malloc(size_t sz) {{\n\
                 return mspace_malloc(__embedded_mspace, sz);\n\
             }}\n\
             void free(void *ptr) {{\n\
                 mspace_free(__embedded_mspace, ptr);\n\
             }}\n",
            start = self.heap_start,
            size = self.heap_size,
            align = self.min_align,
        )
    }

    /// Generate TLSF-based heap allocator.
    pub fn generate_tlsf_config(&self) -> String {
        format!(
            "// TLSF allocator configuration\n\
             static unsigned char tlsf_pool[{size:#x}] __attribute__((aligned({align})));\n\
             static tlsf_t tlsf_instance;\n\n\
             void tlsf_heap_init(void) {{\n\
                 tlsf_instance = tlsf_create_with_pool(tlsf_pool, {size:#x});\n\
             }}\n\n\
             void *malloc(size_t size) {{\n\
                 return tlsf_malloc(tlsf_instance, size);\n\
             }}\n\
             void free(void *ptr) {{\n\
                 tlsf_free(tlsf_instance, ptr);\n\
             }}\n",
            size = self.heap_size,
            align = self.min_align,
        )
    }

    /// Set custom heap implementation.
    pub fn with_custom_impl(mut self, impl_code: &str) -> Self {
        self.custom_impl = Some(impl_code.to_string());
        self
    }

    /// Generate linker script heap symbols.
    pub fn linker_heap_symbols(&self) -> String {
        format!(
            "    PROVIDE(__heap_start = {start:#010x});\n\
                 PROVIDE(__heap_end = {end:#010x});\n",
            start = self.heap_start,
            end = self.heap_start + self.heap_size,
        )
    }
}

impl Default for HeapConfig {
    fn default() -> Self {
        Self::cortex_m4_default()
    }
}

// ============================================================================
// Embedded Project Configuration
// ============================================================================

/// Complete embedded project configuration.
#[derive(Debug, Clone)]
pub struct EmbeddedProjectConfig {
    pub name: String,
    pub arch: EmbeddedArch,
    pub startup: BareMetalStartup,
    pub linker: LinkerScript,
    pub nvic: Option<CmNvic>,
    pub riscv_intc: Option<RiscVInterruptController>,
    pub semihosting: Option<Semihosting>,
    pub itm: Option<ItmTrace>,
    pub mpu: Option<MpuConfig>,
    pub stack_protection: StackProtection,
    pub heap: HeapConfig,
    pub libc: MinimalLibc,
    pub compiler_flags: Vec<String>,
    pub linker_flags: Vec<String>,
}

impl EmbeddedProjectConfig {
    pub fn new(name: &str, arch: EmbeddedArch) -> Self {
        let mut flags = Vec::new();
        flags.push("-ffreestanding".to_string());
        flags.push("-nostdlib".to_string());
        flags.push("-fno-exceptions".to_string());
        flags.push("-fno-rtti".to_string());
        flags.push(format!("-mcpu={}", arch.cpu_flag()));
        flags.push(format!("--target={}", arch.target_triple()));

        Self {
            name: name.to_string(),
            arch,
            startup: BareMetalStartup::new(arch),
            linker: LinkerScript::new(arch),
            nvic: None,
            riscv_intc: None,
            semihosting: None,
            itm: None,
            mpu: None,
            stack_protection: StackProtection::canary(),
            heap: HeapConfig::default(),
            libc: MinimalLibc::new(),
            compiler_flags: flags.clone(),
            linker_flags: vec![
                "-nostartfiles".to_string(),
                "-Wl,-T,linker.ld".to_string(),
                format!("-Wl,-Map={}.map", name),
            ],
        }
    }

    /// Enable semihosting.
    pub fn with_semihosting(mut self, target: SemihostingTarget) -> Self {
        self.semihosting = Some(Semihosting::new(target));
        self
    }

    /// Enable ITM trace.
    pub fn with_itm(mut self) -> Self {
        self.itm = Some(ItmTrace::new());
        self
    }

    /// Enable MPU.
    pub fn with_mpu(mut self, mpu: MpuConfig) -> Self {
        self.mpu = Some(mpu);
        self
    }

    /// Enable stack protection.
    pub fn with_stack_protection(mut self, sp: StackProtection) -> Self {
        self.stack_protection = sp;
        self
    }

    /// Set heap configuration.
    pub fn with_heap(mut self, heap: HeapConfig) -> Self {
        self.heap = heap;
        self
    }

    /// Add a compiler flag.
    pub fn add_flag(&mut self, flag: &str) {
        self.compiler_flags.push(flag.to_string());
    }

    /// Generate all configuration files.
    pub fn generate_all(&self) -> EmbeddedProjectFiles {
        let startup_asm = match self.arch.family() {
            EmbeddedArchFamily::Arm => self.startup.generate_cortex_m_startup(),
            EmbeddedArchFamily::RiscV => self.startup.generate_riscv_startup(),
            EmbeddedArchFamily::Avr => self.startup.generate_avr_startup(),
            _ => String::from("// unsupported arch for startup\n"),
        };

        let linker_ld = self.linker.generate();

        let heap_c = self.heap.generate_sbrk();

        let mpu_c = self.mpu.as_ref()
            .map(|m| m.generate_init_code())
            .unwrap_or_default();

        let itm_c = self.itm.as_ref()
            .map(|i| i.generate_init_code())
            .unwrap_or_default();

        EmbeddedProjectFiles {
            startup_asm,
            linker_script: linker_ld,
            heap_sbrk: heap_c,
            mpu_init: mpu_c,
            itm_init: itm_c,
            compiler_flags: self.compiler_flags.clone(),
        }
    }
}

impl Default for EmbeddedProjectConfig {
    fn default() -> Self {
        Self::new("default", EmbeddedArch::ArmCortexM4)
    }
}

/// Generated embedded project files.
#[derive(Debug, Clone)]
pub struct EmbeddedProjectFiles {
    pub startup_asm: String,
    pub linker_script: String,
    pub heap_sbrk: String,
    pub mpu_init: String,
    pub itm_init: String,
    pub compiler_flags: Vec<String>,
}

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn test_embedded_arch_triples() {
        assert_eq!(EmbeddedArch::ArmCortexM4.target_triple(), "thumbv7em-none-eabihf");
        assert_eq!(EmbeddedArch::Riscv32Imac.target_triple(), "riscv32-unknown-elf");
        assert_eq!(EmbeddedArch::Avr.target_triple(), "avr-unknown-unknown");
        assert_eq!(EmbeddedArch::Msp430.target_triple(), "msp430-none-elf");
    }

    #[test]
    fn test_embedded_arch_cpu_flags() {
        assert_eq!(EmbeddedArch::ArmCortexM4.cpu_flag(), "cortex-m4");
        assert_eq!(EmbeddedArch::ArmCortexM0.cpu_flag(), "cortex-m0");
        assert_eq!(EmbeddedArch::ArmCortexM33.cpu_flag(), "cortex-m33");
    }

    #[test]
    fn test_embedded_arch_pointer_width() {
        assert_eq!(EmbeddedArch::ArmCortexM4.pointer_width(), 32);
        assert_eq!(EmbeddedArch::Riscv64Imac.pointer_width(), 64);
        assert_eq!(EmbeddedArch::Avr.pointer_width(), 16);
    }

    #[test]
    fn test_embedded_arch_family() {
        assert_eq!(EmbeddedArch::ArmCortexM4.family(), EmbeddedArchFamily::Arm);
        assert_eq!(EmbeddedArch::Riscv32Imac.family(), EmbeddedArchFamily::RiscV);
        assert_eq!(EmbeddedArch::Avr.family(), EmbeddedArchFamily::Avr);
        assert_eq!(EmbeddedArch::XtensaLx6.family(), EmbeddedArchFamily::Xtensa);
    }

    #[test]
    fn test_embedded_triple_parse() {
        let t = EmbeddedTriple::parse("thumbv7em-none-eabihf").unwrap();
        assert_eq!(t.arch, "thumbv7em");
        assert_eq!(t.vendor, "none");
        assert_eq!(t.os, "eabihf");
        assert!(t.is_bare_metal());
    }

    #[test]
    fn test_embedded_triple_identify_arch() {
        let t = EmbeddedTriple::parse("thumbv7em-none-eabi").unwrap();
        let arch = t.identify_arch().unwrap();
        assert_eq!(arch, EmbeddedArch::ArmCortexM4);
    }

    #[test]
    fn test_bare_metal_startup_cortex_m() {
        let startup = BareMetalStartup::new(EmbeddedArch::ArmCortexM4);
        let asm = startup.generate_cortex_m_startup();
        assert!(asm.contains("_start"));
        assert!(asm.contains("vector_table"));
        assert!(asm.contains("bkpt"));
    }

    #[test]
    fn test_bare_metal_startup_riscv() {
        let startup = BareMetalStartup::new(EmbeddedArch::Riscv32Imac);
        let asm = startup.generate_riscv_startup();
        assert!(asm.contains("_start"));
        assert!(asm.contains("vector_table"));
        assert!(asm.contains("call main"));
    }

    #[test]
    fn test_bare_metal_startup_avr() {
        let startup = BareMetalStartup::new(EmbeddedArch::Avr);
        let asm = startup.generate_avr_startup();
        assert!(asm.contains("_start"));
        assert!(asm.contains("__vectors"));
        assert!(asm.contains("rcall main"));
    }

    #[test]
    fn test_linker_script_arm() {
        let ls = LinkerScript::new(EmbeddedArch::ArmCortexM4);
        let script = ls.generate();
        assert!(script.contains("MEMORY"));
        assert!(script.contains("FLASH"));
        assert!(script.contains("RAM"));
        assert!(script.contains("SECTIONS"));
    }

    #[test]
    fn test_linker_script_riscv() {
        let ls = LinkerScript::new(EmbeddedArch::Riscv32Imac);
        let script = ls.generate();
        assert!(script.contains("MEMORY"));
        assert!(script.contains("SECTIONS"));
    }

    #[test]
    fn test_memory_region() {
        let region = MemoryRegion::new("FLASH", 0x08000000, 0x100000)
            .with_attribute("rx");
        assert_eq!(region.name, "FLASH");
        assert_eq!(region.origin, 0x08000000);
        assert_eq!(region.attributes.len(), 1);
    }

    #[test]
    fn test_section_placement() {
        let section = SectionPlacement::new(".text", "FLASH")
            .with_alignment(8)
            .with_load_address(0x08001000);
        assert_eq!(section.region, "FLASH");
        assert_eq!(section.alignment, 8);
        assert!(section.load_address.is_some());
    }

    #[test]
    fn test_cm_nvic_system_exceptions() {
        let exceptions = CmNvic::system_exceptions();
        assert_eq!(exceptions.len(), 10);
        assert_eq!(exceptions[0].name, "Reset");
        assert_eq!(exceptions[2].name, "HardFault");
    }

    #[test]
    fn test_cm_nvic_vector_table() {
        let mut nvic = CmNvic::new();
        nvic.register_irq(0, "USART1", "usart1_handler");
        let asm = nvic.generate_vector_table_asm(0x20010000);
        assert!(asm.contains("vector_table"));
        assert!(asm.contains("0x20010000"));
        assert!(asm.contains("usart1_handler"));
    }

    #[test]
    fn test_cm_nvic_enable_disable() {
        let mut nvic = CmNvic::new();
        nvic.register_irq(5, "TIM2", "tim2_handler");
        nvic.disable_irq(5);
        if let Some(v) = nvic.vectors.iter().find(|v| v.number == 21) {
            assert!(!v.enabled);
        }
        nvic.enable_irq(5);
        if let Some(v) = nvic.vectors.iter().find(|v| v.number == 21) {
            assert!(v.enabled);
        }
    }

    #[test]
    fn test_riscv_interrupt_controller() {
        let ic = RiscVInterruptController::new_plic(64);
        assert_eq!(ic.num_interrupts, 64);
        let asm = ic.generate_trap_handler_asm();
        assert!(asm.contains("trap_entry"));
        assert!(asm.contains("mcause"));
    }

    #[test]
    fn test_avr_interrupts() {
        let vectors = AvrInterrupts::atmega328p_vectors();
        assert_eq!(vectors.len(), 26);
        assert_eq!(vectors[0].name, "RESET");
        assert_eq!(vectors[19].name, "USART_TX");
    }

    #[test]
    fn test_minimal_libc_required_syscalls() {
        let syscalls = MinimalLibc::required_syscalls();
        assert!(syscalls.contains(&"_sbrk"));
        assert!(syscalls.contains(&"_write"));
        assert!(syscalls.contains(&"_exit"));
    }

    #[test]
    fn test_minimal_libc_generate_write() {
        let libc = MinimalLibc::new();
        let code = libc.generate_write_syscall();
        assert!(code.contains("_write"));
        assert!(code.contains("SYS_WRITEC"));
        assert!(code.contains("bkpt #0xAB"));
    }

    #[test]
    fn test_minimal_libc_generate_sbrk() {
        let libc = MinimalLibc::new();
        let code = libc.generate_sbrk_syscall(0x20001000, 0x10000);
        assert!(code.contains("_sbrk"));
        assert!(code.contains("0x20001000"));
    }

    #[test]
    fn test_semihosting_arm_ops() {
        let sh = Semihosting::new(SemihostingTarget::ArmBkpt);
        let asm = sh.arm_semihosting_asm(SemihostingOp::SysWritec, b'A' as u32);
        assert!(asm.contains("bkpt #0xAB"));
        assert!(asm.contains("mov r0, #0x03"));
    }

    #[test]
    fn test_semihosting_riscv_ops() {
        let sh = Semihosting::new(SemihostingTarget::RiscVEbreak);
        let asm = sh.riscv_semihosting_asm(SemihostingOp::SysExit, 0);
        assert!(asm.contains("ebreak"));
        assert!(asm.contains("li a0, 0x18"));
    }

    #[test]
    fn test_semihosting_exit() {
        let sh = Semihosting::new(SemihostingTarget::ArmBkpt);
        let asm = sh.exit_asm(0);
        assert!(asm.contains("SYS_EXIT"));
    }

    #[test]
    fn test_itm_init_code() {
        let itm = ItmTrace::new();
        let code = itm.generate_init_code();
        assert!(code.contains("itm_init"));
        assert!(code.contains("itm_send_char"));
        assert!(code.contains("TRCENA"));
    }

    #[test]
    fn test_mpu_region_attributes_encode() {
        let attrs = MpuRegionAttributes::ram();
        let rasr = attrs.encode(10, 0);
        assert!(rasr & 1 != 0); // enable bit set
    }

    #[test]
    fn test_mpu_config_init() {
        let mpu = MpuConfig::cortex_m4_default();
        assert_eq!(mpu.regions.len(), 3);
        let code = mpu.generate_init_code();
        assert!(code.contains("mpu_init"));
        assert!(code.contains("dsb"));
    }

    #[test]
    fn test_stack_canary_init() {
        let sp = StackProtection::canary();
        let code = sp.generate_canary_init();
        assert!(code.contains("0xDEADBEEF"));
    }

    #[test]
    fn test_stack_canary_check() {
        let sp = StackProtection::canary();
        let code = sp.generate_canary_check();
        assert!(code.contains("stack_overflow_handler"));
    }

    #[test]
    fn test_heap_config_sbrk() {
        let heap = HeapConfig::new(0x20000000, 0x10000);
        let code = heap.generate_sbrk();
        assert!(code.contains("_sbrk"));
        assert!(code.contains("ENOMEM"));
    }

    #[test]
    fn test_embedded_project_config_new() {
        let config = EmbeddedProjectConfig::new("test", EmbeddedArch::ArmCortexM4);
        assert_eq!(config.name, "test");
        assert!(config.compiler_flags.iter().any(|f| f.contains("freestanding")));
    }

    #[test]
    fn test_embedded_project_generate_all() {
        let config = EmbeddedProjectConfig::new("proj", EmbeddedArch::ArmCortexM4)
            .with_semihosting(SemihostingTarget::ArmBkpt)
            .with_itm()
            .with_mpu(MpuConfig::cortex_m4_default());
        let files = config.generate_all();
        assert!(!files.startup_asm.is_empty());
        assert!(!files.linker_script.is_empty());
        assert!(!files.heap_sbrk.is_empty());
    }

    #[test]
    fn test_stack_protection_split_stack() {
        let sp = StackProtection::split_stack(4096);
        assert!(sp.split_stack_attribute().is_some());
    }

    #[test]
    fn test_heap_config_tlsf() {
        let heap = HeapConfig::new(0x80000000, 0x20000);
        let code = heap.generate_tlsf_config();
        assert!(code.contains("tlsf_create_with_pool"));
    }

    #[test]
    fn test_mpu_region_attributes_device() {
        let attrs = MpuRegionAttributes::device();
        assert!(attrs.read_enable);
        assert!(attrs.write_enable);
        assert!(!attrs.execute_enable);
        assert!(attrs.shareable);
    }

    #[test]
    fn test_embedded_arch_is_thumb_only() {
        assert!(EmbeddedArch::ArmCortexM4.is_thumb_only());
        assert!(!EmbeddedArch::Riscv32Imac.is_thumb_only());
        assert!(!EmbeddedArch::Avr.is_thumb_only());
    }

    #[test]
    fn test_linker_script_with_sizes() {
        let ls = LinkerScript::new(EmbeddedArch::ArmCortexM4)
            .with_stack_size(8192)
            .with_heap_size(32768);
        assert_eq!(ls.stack_size, 8192);
        assert_eq!(ls.heap_size, 32768);
    }
}