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
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
//! Discovery: find the code of an image that has no symbol table, or an incomplete or wrong one.
//!
//! The result separates what is certain from what is guessed:
//!
//! * **certain**: code reached by following control flow from entry points that the hardware or
//! the user defines (the Cortex-M vector table, symbols given by the user), the literal pools
//! and jump tables that this code reads;
//! * **referenced**: bytes whose address certain code loads (data, with the loading instruction
//! as evidence);
//! * **speculative**: everything else. Unreached bytes get a heuristic "looks like Thumb code"
//! score; nothing is ever called code because of the score alone.
//!
//! With sources, anonymous functions are then named by *proof*: a discovered function gets the
//! name of a source function only if the equivalence proof of the two succeeds (see
//! [`matcher`]).
use crate::image::{Image, Segment, SymKind, Symbol};
use crate::inputs;
use crate::thumb::decode::{Addr, DpOp, Insn, Offset, Op, Operand, Shift, decode};
use crate::thumb::strict::unpredictable;
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::fmt::Write as _;
mod anchor;
pub mod matcher;
/// How a function (or a symbol) came to be in the recovered table.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Provenance {
/// In the symbol table given by the user, and consistent with the code.
Given,
/// In the symbol table given by the user, with its address or size changed.
Corrected,
/// Found by following control flow from a certain entry point.
Discovered,
/// A guess: unreached bytes that decode as a well-formed function.
Speculative,
}
impl Provenance {
pub fn label(self) -> &'static str {
match self {
Provenance::Given => "given",
Provenance::Corrected => "corrected",
Provenance::Discovered => "discovered",
Provenance::Speculative => "speculative",
}
}
}
/// An entry point and why it is one.
#[derive(Clone, Debug)]
pub struct Root {
pub addr: u32,
pub why: String,
pub certain: bool,
}
/// A function of the image.
#[derive(Clone, Debug)]
pub struct Func {
pub addr: u32,
/// From the entry to the end of the last block or literal pool that belongs to it.
pub size: u32,
pub name: String,
pub provenance: Provenance,
/// Why this is a function entry.
pub why: String,
/// Instruction ranges and data-in-code ranges (literal pools, jump tables).
pub code: Vec<(u32, u32)>,
pub pools: Vec<(u32, u32)>,
/// Targets of its direct calls and tail calls, in address order of the call sites.
pub calls: Vec<u32>,
/// No path through it returns to the caller.
pub noreturn: bool,
/// Something about it that could not be analysed.
pub notes: Vec<String>,
/// Constants it forms that may be addresses (literal-pool words, movw/movt pairs,
/// pc-relative addresses, and those plus the constant offset of an access).
pub consts: Vec<u32>,
}
/// A name discovery made up for a function nothing names: `fn_<address>` (certain) or
/// `sub_<address>` (a guess).
pub fn is_anonymous(name: &str) -> bool {
["fn_", "sub_"].iter().any(|p| {
name.strip_prefix(p)
.is_some_and(|h| h.len() == 8 && h.bytes().all(|c| c.is_ascii_hexdigit()))
})
}
/// A function of the compiler's run-time library, which verification models by name.
pub fn is_helper_name(name: &str) -> bool {
name.starts_with("__aeabi_")
|| name.starts_with("__gnu_thumb1_case_")
|| (name.starts_with("__") && name.ends_with("i3"))
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kind {
/// Instructions reached from an entry point.
Code,
/// Literal pool or jump table read by reached code.
Pool,
/// The vector table.
Vectors,
/// Bytes whose address reached code loads.
DataRef,
/// Words that are all addresses inside the image or RAM.
PointerTable,
/// Fill between functions or sections.
Padding,
/// Printable text ending in NUL.
String,
/// Nothing is known.
Unknown,
}
impl Kind {
pub fn label(self) -> &'static str {
match self {
Kind::Code => "code",
Kind::Pool => "literal-pool",
Kind::Vectors => "vector-table",
Kind::DataRef => "data-referenced",
Kind::PointerTable => "pointer-table",
Kind::Padding => "padding",
Kind::String => "likely-string",
Kind::Unknown => "unknown",
}
}
}
/// A classified address range.
#[derive(Clone, Debug)]
pub struct Range {
pub start: u32,
pub end: u32,
pub kind: Kind,
/// True when the classification follows from reached code, false when it is a guess from
/// the contents alone.
pub certain: bool,
pub evidence: String,
/// Heuristic 0..1 "looks like Thumb code", for ranges no code was found in.
pub score: Option<f32>,
}
/// Something wrong (or missing) in the symbol table that was given.
#[derive(Clone, Debug)]
pub struct Finding {
pub addr: u32,
pub name: String,
/// `missing`, `wrong-size`, `wrong-address`, `mid-instruction`, `data-covers-code`,
/// `overlap`, `not-code`, `proof-fails`, `swapped`.
pub kind: &'static str,
pub text: String,
}
/// A discovered function identified as a source function.
#[derive(Clone, Debug)]
pub struct Match {
pub source: String,
pub addr: u32,
/// `proved`, `bounded` (no difference on the paths explored), `recognised` (a run-time
/// helper identified by test vectors, not proved) or `given` (the name comes from the
/// user's table and was not contradicted).
pub how: &'static str,
/// Other functions the proof succeeds for as well (identical code).
pub also: Vec<u32>,
pub detail: String,
}
#[derive(Clone, Debug, Default)]
pub struct Discovery {
pub roots: Vec<Root>,
pub funcs: Vec<Func>,
pub ranges: Vec<Range>,
pub findings: Vec<Finding>,
pub matches: Vec<Match>,
/// Source functions with a body for which no code was found.
pub not_found: Vec<String>,
/// What the attempts to match each of them ended in (same order).
pub not_found_why: Vec<String>,
/// Functions of the image that no source function was matched to.
pub binary_only: Vec<u32>,
/// Address and number of entries of the vector table, if one was recognised.
pub vectors: Option<(u32, usize)>,
pub notes: Vec<String>,
/// Objects located for the source (name, address): a guess confirmed by the proofs that use them.
pub objects: Vec<(String, u32, u32)>,
}
#[derive(Clone, Debug, Default)]
pub struct Options {
/// Address of the vector table (default: the lowest address of the image).
pub vectors: Option<u32>,
/// Do not look for a vector table.
pub no_vectors: bool,
/// Sizes as the user's table states them, where the loader has since filled in missing
/// ones: (name, address, size).
pub given_sizes: Vec<(String, u32, u32)>,
}
/// Load an image for discovery: an ELF file as it is, anything else as flat memory in which
/// nothing is known to be code or data. `symtabs` may be empty.
pub fn open(
binary: &[u8],
base: u32,
extra: &[(Vec<u8>, u32)],
symtabs: &[String],
opts: &mut Options,
) -> Result<Image, String> {
if inputs::sniff(binary) == inputs::Format::Elf {
return inputs::load(binary, base, extra, symtabs, None);
}
let mut info = inputs::SymInfo::default();
for t in symtabs {
info.merge(inputs::parse_symbols(t)?);
}
opts.given_sizes = info
.symbols
.iter()
.filter(|s| s.kind == SymKind::Func)
.map(|s| (s.name.clone(), s.addr, s.size))
.collect();
let mut regions = inputs::regions_of(binary, base)?;
for (bytes, addr) in extra {
regions.extend(inputs::regions_of(bytes, *addr)?);
}
regions.sort_by_key(|r| r.0);
for w in regions.windows(2) {
if w[0].0 + w[0].1.len() as u32 > w[1].0 {
return Err(format!("memory images overlap at {:#x}", w[1].0));
}
}
let mut img = inputs::build_image(regions, &info)?;
flatten(&mut img);
Ok(img)
}
/// Merge the read-only pieces of a raw image back into whole regions that may all hold code.
fn flatten(img: &mut Image) {
let mut out: Vec<Segment> = Vec::new();
img.segments.sort_by_key(|s| (s.writable, s.addr));
for s in std::mem::take(&mut img.segments) {
match out.last_mut() {
Some(p) if !p.writable && !s.writable && p.addr + p.data.len() as u32 == s.addr => {
p.data.extend_from_slice(&s.data);
}
_ => out.push(Segment {
exec: !s.writable,
name: if s.writable { s.name.clone() } else { "raw".into() },
..s
}),
}
}
out.sort_by_key(|s| s.addr);
img.segments = out;
img.soft_bounds = true;
}
fn word(img: &Image, a: u32) -> Option<u32> {
let b = img.read_const(a, 4)?;
Some(u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
}
/// Is `a` inside memory that may hold code?
fn in_code_space(img: &Image, a: u32) -> bool {
img.segment_at(a).is_some_and(|s| s.exec && !s.writable)
}
fn is_ram(img: &Image, a: u32) -> bool {
(0x1000_0000..0x4000_0000).contains(&a) || img.segment_at(a).is_some_and(|s| s.writable)
}
// ----- recursive descent ----------------------------------------------------------------
/// A switch helper of libgcc (`__gnu_thumb1_case_*`): the table follows the call.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct CaseHelper {
size: u8,
signed: bool,
}
/// What exploring one function from its entry finds.
#[derive(Clone, Debug, Default)]
struct Body {
insns: BTreeMap<u32, u8>,
/// Data in code: (address, length, what reads it).
pools: Vec<(u32, u32, String)>,
/// (site, target) of direct calls; of jumps that leave the function.
calls: Vec<(u32, u32)>,
tails: Vec<(u32, u32)>,
/// Constant values that may be addresses: (value, address of the instruction that forms it).
consts: Vec<(u32, u32)>,
/// Some path returns (or leaves through a jump whose target is unknown).
returns: bool,
/// The first thing that is not valid code, if any.
bad: Option<(u32, String)>,
/// Computed jumps whose targets are not known.
unresolved: Vec<u32>,
notes: Vec<String>,
/// Calls to switch helpers: the table that follows was decoded.
indirect_calls: usize,
pushes_lr: bool,
}
struct Scan<'a> {
img: &'a Image,
/// Function entries (even addresses) and why.
entries: BTreeMap<u32, (String, bool)>,
noreturn: BTreeSet<u32>,
helpers: BTreeMap<u32, CaseHelper>,
/// Extra block starts found by symbolic execution: (function entry, address).
extra: BTreeSet<(u32, u32)>,
/// Table bytes found by symbolic execution: function entry -> (address, length).
extra_data: BTreeMap<u32, Vec<(u32, u32)>>,
}
fn written(op: &Op) -> u16 {
let r = |x: u8| 1u16 << x;
let base = |a: &Addr| match a {
Addr::Base { rn, wback: true, .. } => r(*rn),
_ => 0,
};
match op {
Op::Dp { rd, .. } => rd.map_or(0, r),
Op::ShiftReg { rd, .. }
| Op::Movt { rd, .. }
| Op::Adr { rd, .. }
| Op::Mul { rd, .. }
| Op::Mla { rd, .. }
| Op::MulHalves { rd, .. }
| Op::Mls { rd, .. }
| Op::Div { rd, .. }
| Op::Bfi { rd, .. }
| Op::Bfc { rd, .. }
| Op::Bfx { rd, .. }
| Op::Extend { rd, .. }
| Op::Clz { rd, .. }
| Op::Rbit { rd, .. }
| Op::Rev { rd, .. }
| Op::Rev16 { rd, .. }
| Op::Revsh { rd, .. }
| Op::Sat { rd, .. } => r(*rd),
Op::MulLong { rdlo, rdhi, .. } => r(*rdlo) | r(*rdhi),
Op::Load { rt, addr, .. } => r(*rt) | base(addr),
Op::LoadDual { rt, rt2, addr } => r(*rt) | r(*rt2) | base(addr),
Op::Store { addr, .. } | Op::StoreDual { addr, .. } => base(addr),
Op::LoadMulti { rn, regs, .. } => *regs | r(*rn),
Op::StoreMulti { rn, .. } => r(*rn),
Op::Bl { .. } | Op::Blx { .. } => 0x500f,
Op::Unsupported(_) => 0xffff,
_ => 0,
}
}
/// ITSTATE after one instruction.
fn it_advance(it: u8) -> u8 {
if it & 7 == 0 {
0
} else {
(it & 0xe0) | ((it << 1) & 0x1f)
}
}
impl<'a> Scan<'a> {
fn new(img: &'a Image) -> Scan<'a> {
Scan {
img,
entries: BTreeMap::new(),
noreturn: BTreeSet::new(),
helpers: BTreeMap::new(),
extra: BTreeSet::new(),
extra_data: BTreeMap::new(),
}
}
/// The end of the address range a function entered at `entry` may extend over: the next
/// entry, or the end of its segment.
fn limit(&self, entry: u32) -> u32 {
let seg_end = self
.img
.segment_at(entry)
.map_or(entry, |s| s.addr + s.data.len() as u32);
self.entries
.range(entry + 1..)
.next()
.map_or(seg_end, |(a, _)| (*a).min(seg_end))
}
/// Follow control flow from `entry`. `strict`: stop at the first thing a compiler would
/// not emit (used to validate guesses).
fn explore(&self, entry: u32, strict: bool) -> Body {
let img = self.img;
let limit = self.limit(entry);
let mut b = Body::default();
let mut work: Vec<u32> = vec![entry];
work.extend(self.extra.range((entry, 0)..=(entry, u32::MAX)).map(|x| x.1));
if let Some(d) = self.extra_data.get(&entry) {
for &(a, n) in d {
b.pools
.push((a, n, "table read on a path found by symbolic execution".into()));
}
}
let inside = |t: u32| t >= entry && t < limit;
while let Some(start) = work.pop() {
let mut pc = start;
let mut it: u8 = 0;
let mut regs: [Option<u32>; 16] = [None; 16];
// The last few instructions of the block, for the patterns around computed jumps.
let mut recent: Vec<(u32, Op)> = Vec::new();
loop {
if b.insns.contains_key(&pc) {
break;
}
if pc != entry && self.entries.contains_key(&pc) {
// Falls through into another function.
b.tails.push((pc, pc));
break;
}
if b.pools.iter().any(|p| pc >= p.0 && pc < p.0 + p.1) {
b.bad.get_or_insert((pc, "execution runs into a literal pool".into()));
break;
}
let bytes = img.read_const(pc, 4).or_else(|| img.read_const(pc, 2));
let Some(insn) = bytes
.filter(|_| in_code_space(img, pc))
.and_then(|x| decode(x, pc, it & 0xf != 0))
else {
b.bad.get_or_insert((pc, "execution leaves the image".into()));
break;
};
let Insn { len, op } = insn;
let raw = bytes.unwrap();
let hw1 = u16::from_le_bytes([raw[0], raw[1]]) as u32;
let hw2 = if len == 4 {
u16::from_le_bytes([raw[2], raw[3]]) as u32
} else {
0
};
if unpredictable(hw1, hw2, it) {
b.bad.get_or_insert((pc, "UNPREDICTABLE encoding".into()));
break;
}
if matches!(op, Op::Unsupported(_)) && strict {
b.bad.get_or_insert((pc, "not an instruction this tool knows".into()));
break;
}
// A range another instruction already covers from a different alignment?
if len == 4 && b.insns.contains_key(&(pc + 2)) {
b.bad
.get_or_insert((pc, "overlaps an instruction decoded from another path".into()));
break;
}
b.insns.insert(pc, len);
let cond = it & 0xf != 0;
let next = pc + len as u32;
let val = |regs: &[Option<u32>; 16], r: u8| if r == 15 { Some(pc + 4) } else { regs[r as usize] };
let mut set: Option<(u8, u32, bool)> = None; // (register, value, may be an address)
let mut stop = false;
match op {
Op::It { cond: c, mask } => {
it = ((c as u8) << 4) | (mask & 0xf);
recent.push((pc, op));
pc = next;
continue;
}
Op::Dp {
op: DpOp::Mov,
rd: Some(15),
src: Operand::Reg { rm, .. },
..
} => {
if rm == 14 {
b.returns = true;
} else if !self.absolute_table(&mut b, pc, rm, &recent, ®s, entry, limit, &mut work) {
b.unresolved.push(pc);
b.returns = true;
}
stop = true;
}
Op::Dp {
op: DpOp::Add,
rd: Some(15),
src: Operand::Reg { rm, .. },
..
} => {
// add pc, rX: an inline table of offsets follows (clang, ARMv6-M).
let size = recent
.iter()
.rev()
.take(4)
.find_map(|(_, o)| match o {
Op::Load { rt, size, signed, .. } if *rt == rm => Some((*size, *signed)),
_ => None,
})
.unwrap_or((1, false));
if size.0 > 2
|| !self.offset_table(&mut b, pc, next, pc + 4, size, None, entry, limit, &mut work)
{
b.unresolved.push(pc);
b.returns = true;
}
stop = true;
}
Op::Dp {
op: dp,
rd: Some(d),
rn,
src,
..
} if d != 15 => {
let s = match src {
Operand::Imm { value, .. } => Some(value),
Operand::Reg {
rm,
shift: Shift::Lsl,
amount,
} => val(®s, rm).map(|v| v << amount),
Operand::Reg {
rm,
shift: Shift::Lsr,
amount,
} if amount > 0 && amount < 32 => val(®s, rm).map(|v| v >> amount),
_ => None,
};
let pcrel = matches!(src, Operand::Reg { rm: 15, .. }) || rn == Some(15);
let v = match (dp, rn, s) {
(DpOp::Mov, _, Some(s)) => Some(s),
(DpOp::Add, Some(n), Some(s)) => val(®s, n).map(|x| x.wrapping_add(s)),
(DpOp::Sub, Some(n), Some(s)) => val(®s, n).map(|x| x.wrapping_sub(s)),
(DpOp::Orr, Some(n), Some(s)) => val(®s, n).map(|x| x | s),
_ => None,
};
if let Some(v) = v {
set = Some((d, v, pcrel));
}
}
Op::Movt { rd, imm } => {
if let Some(lo) = regs[rd as usize] {
set = Some((rd, (lo & 0xffff) | ((imm as u32) << 16), true));
}
}
Op::Adr { rd, target } => set = Some((rd, target, true)),
Op::Load { rt, size, addr, .. } | Op::Store { rt, size, addr } => {
let is_load = matches!(op, Op::Load { .. });
let at = match addr {
Addr::Lit(a) => Some((a, true)),
Addr::Base {
rn,
offset: Offset::Imm(o),
index: true,
..
} => val(®s, rn).map(|x| (x.wrapping_add(o as u32), false)),
_ => None,
};
if let Some((a, lit)) = at {
if lit && is_load {
if !in_code_space(img, a) || img.read_const(a, size as u32).is_none() {
b.bad.get_or_insert((pc, "literal load from outside the image".into()));
break;
}
b.pools.push((a, size as u32, format!("literal loaded at {pc:#x}")));
} else {
b.consts.push((a, pc));
}
if is_load
&& size == 4
&& rt != 15
&& let Some(w) = word(img, a)
{
set = Some((rt, w, true));
}
}
if is_load && rt == 15 {
// ldr pc, ...: a return (pop), or a jump through a table.
let pop = matches!(addr, Addr::Base { rn: 13, .. });
// `adr rn, table; ldr pc, [rn, rm, lsl #2]`: a jump through a
// table of addresses.
let table = match addr {
Addr::Base {
rn,
offset: Offset::Reg { .. },
..
} if rn != 13 && rn != 15 => regs[rn as usize],
_ => None,
};
let resolved = table.is_some_and(|t| self.table_at(&mut b, pc, t, entry, limit, &mut work));
if !pop && !resolved {
b.unresolved.push(pc);
}
b.returns = true;
stop = true;
}
}
Op::LoadDual { addr: Addr::Lit(a), .. } => {
b.pools.push((a, 8, format!("literal loaded at {pc:#x}")))
}
Op::LoadMulti { rn, regs: mask, .. } if mask & 0x8000 != 0 => {
if rn != 13 {
b.unresolved.push(pc);
}
b.returns = true;
stop = true;
}
Op::StoreMulti { rn: 13, regs: mask, .. } if mask & 0x4000 != 0 => b.pushes_lr = true,
Op::B { cond: c, target } => {
let always = matches!(c, crate::thumb::decode::Cond::Al) && !cond;
if !in_code_space(img, target) {
b.bad
.get_or_insert((pc, format!("branch to {target:#x}, outside the image")));
break;
}
if inside(target) && !(target != entry && self.entries.contains_key(&target)) {
work.push(target);
} else {
b.tails.push((pc, target));
}
stop = always;
}
Op::Cbz { target, .. } => {
if inside(target) {
work.push(target);
} else {
b.bad
.get_or_insert((pc, format!("cbz to {target:#x}, outside the function")));
break;
}
}
Op::Bl { target } => {
if !in_code_space(img, target) {
if strict {
b.bad
.get_or_insert((pc, format!("call to {target:#x}, outside the image")));
break;
}
b.notes
.push(format!("call at {pc:#x} to {target:#x}, outside the image"));
} else {
b.calls.push((pc, target));
if let Some(h) = self.helpers.get(&target) {
let base = next;
if !self.offset_table(
&mut b,
pc,
base,
base,
(h.size, h.signed),
None,
entry,
limit,
&mut work,
) {
b.unresolved.push(pc);
}
stop = true;
} else if self.noreturn.contains(&target) && !cond {
stop = true;
}
}
}
Op::Bx { rm } => {
// (Leaving through another register after the frame is gone is a tail
// call through a pointer, not a jump inside the function.)
let frame_gone = recent.iter().rev().take(3).any(|(_, o)| match o {
Op::LoadMulti { rn: 13, regs: mask, .. } => mask & 0x4000 != 0,
_ => false,
});
if frame_gone {
b.indirect_calls += 1;
} else if rm != 14 && !recent.iter().rev().take(3).any(|(_, o)| written(o) & (1 << rm) != 0) {
// A jump through a register this block did not just load: unknown target.
b.unresolved.push(pc);
}
b.returns = true;
stop = true;
}
Op::Blx { .. } => b.indirect_calls += 1,
Op::TableBranch { rn, rm, half } => {
let bound = recent.iter().rev().take(6).find_map(|(_, o)| match o {
Op::Dp {
op: DpOp::Sub,
rd: None,
rn: Some(r),
src: Operand::Imm { value, .. },
..
} if *r == rm => Some(*value as usize + 1),
_ => None,
});
let size = (if half { 2 } else { 1 }, false);
if rn != 15 || !self.offset_table(&mut b, pc, next, next, size, bound, entry, limit, &mut work)
{
b.unresolved.push(pc);
b.returns = true;
}
stop = true;
}
Op::Udf | Op::Bkpt(_) => stop = true,
_ => {}
}
let w = written(&op);
for (r, slot) in regs.iter_mut().enumerate() {
if w & (1 << r) != 0 {
*slot = None;
}
}
if let Some((r, v, addr)) = set
&& !cond
{
regs[r as usize] = Some(v);
if addr {
b.consts.push((v, pc));
}
}
recent.push((pc, op));
if recent.len() > 8 {
recent.remove(0);
}
it = it_advance(it);
if stop && !cond {
break;
}
if next >= limit && !self.entries.contains_key(&next) {
if in_code_space(img, next) {
b.tails.push((pc, next));
} else {
b.bad
.get_or_insert((pc, "execution runs off the end of the image".into()));
}
break;
}
pc = next;
}
}
b
}
/// An inline table of scaled offsets at `table`: entry `e` jumps to `base + 2 * e`.
#[allow(clippy::too_many_arguments)]
fn offset_table(
&self,
b: &mut Body,
site: u32,
table: u32,
base: u32,
(size, signed): (u8, bool),
bound: Option<usize>,
entry: u32,
limit: u32,
work: &mut Vec<u32>,
) -> bool {
let size = size as u32;
let mut targets = Vec::new();
let mut min_target = limit;
let mut i = 0u32;
loop {
let at = table + i * size;
if at + size > min_target || bound.is_some_and(|n| i as usize >= n) || i >= 1024 {
break;
}
let Some(raw) = self.img.read_const(at, size) else {
break;
};
let mut e = if size == 1 {
raw[0] as i64
} else {
u16::from_le_bytes([raw[0], raw[1]]) as i64
};
if signed {
e = if size == 1 {
e as u8 as i8 as i64
} else {
e as u16 as i16 as i64
};
}
let t = base as i64 + 2 * e;
if t < entry as i64 || t >= limit as i64 || (signed && t < table as i64 && t >= site as i64) {
break;
}
let t = t as u32;
if t >= table && t < at + size {
break; // points into the table itself: padding after the last entry
}
if t > table {
min_target = min_target.min(t);
}
targets.push(t);
i += 1;
}
if targets.is_empty() {
return false;
}
let len = (i * size).next_multiple_of(2);
b.pools
.push((table, len, format!("jump table of the computed jump at {site:#x}")));
work.extend(targets);
true
}
/// `mov pc, rX` after `ldr rX, [table, index]`: a table of absolute addresses.
#[allow(clippy::too_many_arguments)]
fn absolute_table(
&self,
b: &mut Body,
site: u32,
rm: u8,
recent: &[(u32, Op)],
regs: &[Option<u32>; 16],
entry: u32,
limit: u32,
work: &mut Vec<u32>,
) -> bool {
let table = recent.iter().rev().take(4).find_map(|(_, o)| match o {
Op::Load {
rt,
size: 4,
addr:
Addr::Base {
rn,
offset: Offset::Reg { rm: idx, .. },
..
},
..
} if *rt == rm => regs[*rn as usize].or(regs[*idx as usize]),
_ => None,
});
let Some(table) = table else { return false };
self.table_at(b, site, table, entry, limit, work)
}
/// The targets of a computed jump through the table of code addresses at `table`.
fn table_at(&self, b: &mut Body, site: u32, table: u32, entry: u32, limit: u32, work: &mut Vec<u32>) -> bool {
let mut n = 0u32;
let mut targets = Vec::new();
while n < 1024 {
let Some(w) = word(self.img, table + 4 * n) else { break };
let t = w & !1;
if w & 1 == 0 || t < entry || t >= limit {
break;
}
if table >= entry
&& table < limit
&& table + 4 * n >= targets.iter().copied().filter(|x| *x > table).min().unwrap_or(limit)
{
break;
}
targets.push(t);
n += 1;
}
if targets.is_empty() {
return false;
}
b.pools.push((
table,
4 * n,
format!("table of addresses of the computed jump at {site:#x}"),
));
work.extend(targets);
true
}
/// Is the function at `entry` one of libgcc's switch helpers?
fn case_helper(&self, entry: u32) -> Option<CaseHelper> {
let mut pc = entry;
let (mut from_lr, mut to_lr, mut load) = (false, false, None);
for _ in 0..12 {
let insn = decode(self.img.read_const(pc, 2)?, pc, false)?;
match insn.op {
Op::Dp {
op: DpOp::Mov,
rd: Some(1),
src: Operand::Reg { rm: 14, .. },
..
} => from_lr = true,
Op::Dp {
op: DpOp::Add,
rd: Some(14),
src: Operand::Reg { rm: 1, .. },
..
} => to_lr = true,
Op::Load {
rt: 1,
size,
signed,
addr:
Addr::Base {
rn: 1,
offset: Offset::Reg { rm: 0, .. },
..
},
} if size <= 2 => load = Some(CaseHelper { size, signed }),
Op::Bx { rm: 14 } => return if from_lr && to_lr { load } else { None },
Op::Bl { .. } | Op::B { .. } | Op::Blx { .. } | Op::Unsupported(_) => return None,
_ => {}
}
pc += insn.len as u32;
}
None
}
/// Does `t` (not a known function) hold up as the start of one: well-formed code that
/// returns, or ends in a jump to a known function, and calls nothing unknown?
fn plausible(&mut self, t: u32, known: &BTreeSet<u32>) -> bool {
if t & 1 != 0 || !in_code_space(self.img, t) {
return false;
}
let had = self.entries.contains_key(&t);
if !had {
self.entries.insert(t, (String::new(), false));
}
let b = self.explore(t, true);
if !had {
self.entries.remove(&t);
}
b.bad.is_none()
&& b.unresolved.is_empty()
&& !b.insns.is_empty()
&& (b.returns || !b.tails.is_empty())
&& b.calls.iter().all(|(_, x)| known.contains(x))
// (Library routines jump into the middle of one another.)
&& b.tails.iter().all(|(_, x)| known.range(..=*x).next_back().is_some_and(|k| x - k < 0x400))
}
fn add_entry(&mut self, addr: u32, why: String, certain: bool) -> bool {
let addr = addr & !1;
if !in_code_space(self.img, addr) {
return false;
}
match self.entries.get_mut(&addr) {
Some(e) => {
if certain && !e.1 {
*e = (why, true);
}
false
}
None => {
self.entries.insert(addr, (why, certain));
true
}
}
}
/// Explore every entry until no new entry, switch helper or non-returning function appears.
fn fixpoint(&mut self) -> BTreeMap<u32, Body> {
let mut bodies: BTreeMap<u32, Body> = BTreeMap::new();
for _round in 0..64 {
let mut changed = false;
bodies.clear();
let entries: Vec<u32> = self.entries.keys().copied().collect();
for &e in &entries {
if !self.helpers.contains_key(&e)
&& let Some(h) = self.case_helper(e)
{
self.helpers.insert(e, h);
changed = true;
}
}
for &e in &entries {
let certain = self.entries[&e].1;
let body = self.explore(e, !certain);
for &(site, t) in body.calls.iter().chain(&body.tails) {
if t != e {
let how = if body.calls.contains(&(site, t)) {
"called"
} else {
"jumped to"
};
changed |= self.add_entry(t, format!("{how} from {site:#x}"), certain);
}
}
bodies.insert(e, body);
}
// Functions that cannot return: no path reaches a return, and every way out is a
// call or jump to a function that does not return either.
let mut noreturn: BTreeSet<u32> = bodies
.iter()
.filter(|(_, b)| !b.returns && b.bad.is_none() && b.unresolved.is_empty())
.map(|(e, _)| *e)
.collect();
loop {
let drop: Vec<u32> = noreturn
.iter()
.copied()
.filter(|e| bodies[e].tails.iter().any(|(_, t)| !noreturn.contains(t)))
.collect();
if drop.is_empty() {
break;
}
for e in drop {
noreturn.remove(&e);
}
}
if !noreturn.is_subset(&self.noreturn) {
self.noreturn.extend(noreturn);
changed = true;
}
if !changed {
break;
}
}
bodies
}
}
// ----- the vector table -----------------------------------------------------------------
/// A Cortex-M vector table at `at`: the number of entries, if the first two words are
/// plausible (an initial stack pointer in RAM, a reset handler inside the image).
fn vector_table(img: &Image, at: u32) -> Option<usize> {
let sp = word(img, at)?;
let reset = word(img, at + 4)?;
let handler = |w: u32| w & 1 == 1 && in_code_space(img, w & !1);
let sp_ok = sp.is_multiple_of(4) && sp != 0 && (is_ram(img, sp) || is_ram(img, sp.wrapping_sub(4)));
if !sp_ok || !handler(reset) {
return None;
}
let mut lowest = reset & !1;
let mut n = 2usize;
while n < 16 + 480 {
let a = at + 4 * n as u32;
if a >= lowest && lowest > at {
break; // the table cannot run into the code of its own handlers
}
let Some(w) = word(img, a) else { break };
if handler(w) {
lowest = lowest.min(w & !1);
} else if w != 0 && w != 0xffff_ffff {
// Reserved entries are 0 (some tools write a checksum into one of them).
if !(n < 16 && !in_code_space(img, w)) {
break;
}
}
n += 1;
}
// Trailing reserved words are not evidence of anything.
while n > 2 && !word(img, at + 4 * (n as u32 - 1)).is_some_and(handler) {
n -= 1;
}
Some(n)
}
// ----- classification of what the descent did not reach -----------------------------------
/// How much a byte range looks like Thumb code (0..1), and why.
///
/// Thumb is a dense encoding: most random halfwords decode as some instruction, so validity
/// alone says little. The score rests on structure instead: the share of the range covered
/// by sequences that run from a plausible start to a return without anything a compiler would
/// not emit, with branches that stay in the range, plus calls that hit known functions.
pub fn code_score(img: &Image, start: u32, end: u32, known: &BTreeSet<u32>) -> (f32, String) {
let len = end.saturating_sub(start);
if len < 2 {
return (0.0, "too short".into());
}
let mut scan = Scan::new(img);
for &k in known {
scan.entries.insert(k, (String::new(), true));
}
let mut clean = 0u32;
let mut funcs = 0usize;
let mut calls_known = 0usize;
let mut returns = 0usize;
let mut pc = start.next_multiple_of(2);
let mut seen: BTreeSet<u32> = BTreeSet::new();
while pc + 2 <= end {
if seen.contains(&pc) {
pc += 2;
continue;
}
scan.entries.insert(pc, (String::new(), false));
let b = scan.explore(pc, true);
scan.entries.remove(&pc);
let within = b.insns.iter().all(|(a, n)| *a >= start && a + *n as u32 <= end);
let ok = b.bad.is_none()
&& within
&& b.returns
&& b.unresolved.is_empty()
&& b.insns.len() >= 2
&& b.tails
.iter()
.all(|(_, t)| known.contains(t) || (*t >= start && *t < end))
&& b.pools.iter().all(|p| p.0 >= start && p.0 + p.1 <= end)
&& b.calls
.iter()
.all(|(_, t)| known.contains(t) || (*t >= start && *t < end) || scan.plausible(*t, known));
if ok {
funcs += 1;
returns += 1;
calls_known += b.calls.iter().filter(|(_, t)| known.contains(t)).count();
for (a, n) in &b.insns {
for x in *a..*a + *n as u32 {
if seen.insert(x) {
clean += 1;
}
}
}
for p in &b.pools {
for x in p.0..p.0 + p.1 {
if seen.insert(x) {
clean += 1;
}
}
}
pc = b
.insns
.keys()
.next_back()
.map_or(pc + 2, |a| a + b.insns[a] as u32)
.max(pc + 2);
} else {
pc += 2;
}
}
let frac = clean as f32 / len as f32;
// Diversity: fill patterns and tables repeat one halfword; code does not.
let mut distinct: BTreeSet<u16> = BTreeSet::new();
let mut total = 0usize;
let mut a = start.next_multiple_of(2);
while a + 2 <= end {
if let Some(x) = img.read_const(a, 2) {
distinct.insert(u16::from_le_bytes([x[0], x[1]]));
total += 1;
}
a += 2;
}
let diversity = if total == 0 {
0.0
} else {
(distinct.len() as f32 / total as f32).min(1.0)
};
let mut score =
0.7 * frac + 0.15 * (returns.min(1) as f32) * frac.min(1.0) + 0.15 * (calls_known.min(2) as f32 / 2.0);
if diversity < 0.25 {
score *= diversity / 0.25;
}
let why = format!(
"{:.0}% of the bytes form {funcs} well-formed sequence(s) ending in a return, {calls_known} call(s) to known functions",
100.0 * frac
);
(score.clamp(0.0, 1.0), why)
}
fn printable(b: u8) -> bool {
(0x20..0x7f).contains(&b) || matches!(b, b'\n' | b'\r' | b'\t')
}
/// Printable strings, each ending in NUL, possibly padded with NULs?
fn looks_like_strings(d: &[u8]) -> bool {
if d.len() < 4 || *d.last().unwrap() != 0 {
return false;
}
let mut run = 0usize;
let mut longest = 0usize;
for &b in d {
if b == 0 {
run = 0;
} else if printable(b) {
run += 1;
longest = longest.max(run);
} else {
return false;
}
}
longest >= 3
}
// ----- the driver -----------------------------------------------------------------------
/// What discovery works out about an image, before any source is consulted.
pub struct Analysis {
pub discovery: Discovery,
/// The image with the recovered symbol table (see [`rebuild`]).
pub image: Image,
}
/// Run discovery on `img` (as loaded by [`open`]); the symbols of `img` are the table given by
/// the user, possibly empty.
pub fn discover(img: &Image, opts: &Options) -> Analysis {
let mut d = Discovery::default();
let mut scan = Scan::new(img);
// 1. Certain entry points.
if !opts.no_vectors {
let at = opts
.vectors
.or_else(|| img.segments.iter().filter(|s| !s.writable).map(|s| s.addr).min());
match at.and_then(|at| Some((at, vector_table(img, at)?))) {
Some((at, n)) => {
d.vectors = Some((at, n));
for i in 1..n as u32 {
let w = word(img, at + 4 * i).unwrap_or(0);
if w & 1 == 1 && in_code_space(img, w & !1) {
let why = if i == 1 {
"reset vector".to_string()
} else {
format!("vector {i} of the vector table at {at:#x}")
};
d.roots.push(Root {
addr: w & !1,
why: why.clone(),
certain: true,
});
scan.add_entry(w & !1, why, true);
}
}
}
None => d.notes.push(match at {
Some(at) => format!(
"no Cortex-M vector table at {at:#x} (the first word is not a stack pointer in RAM, or the second not a code address): give its address with --vectors, or entry points with --symbols"
),
None => "the image has no read-only memory".into(),
}),
}
}
// Pass 1: what the hardware-defined entries reach, without trusting any symbol.
let reached_first: BTreeMap<u32, u8> = {
let bodies = scan.fixpoint();
bodies
.values()
.flat_map(|b| b.insns.iter().map(|(a, n)| (*a, *n)))
.collect()
};
let first_entries: BTreeSet<u32> = scan.entries.keys().copied().collect();
// 2. Symbols given by the user: audited against pass 1, then used as entry points.
let given: Vec<&Symbol> = img.symbols.iter().filter(|s| s.kind == SymKind::Func).collect();
let mut renamed: HashMap<u32, (String, Provenance)> = HashMap::new();
// Of several names for one address the one to go by: a sized symbol before a bare label,
// an ordinary name before an assembler-local one.
let mut given: Vec<&Symbol> = given;
let stated = |s: &Symbol| {
opts.given_sizes
.iter()
.find(|g| g.0 == s.name && g.1 == s.addr)
.map_or(s.size, |g| g.2)
};
given.sort_by_key(|s| (s.addr, s.name.starts_with('.'), stated(s) == 0, s.name.clone()));
for s in &given {
if !in_code_space(img, s.addr) {
continue;
}
if first_entries.contains(&s.addr) {
renamed.entry(s.addr).or_insert((s.name.clone(), Provenance::Given));
continue;
}
// Inside code that is already known: on an instruction boundary?
let near = first_entries
.iter()
.copied()
.filter(|e| e.abs_diff(s.addr) <= 8 && !given.iter().any(|g| g.addr == *e))
.min_by_key(|e| e.abs_diff(s.addr));
let inside_known = reached_first
.range(s.addr.saturating_sub(3)..=s.addr)
.any(|(a, n)| s.addr < a + *n as u32);
if inside_known {
let boundary = reached_first.contains_key(&s.addr);
if let Some(e) = near {
d.findings.push(Finding {
addr: s.addr,
name: s.name.clone(),
kind: "wrong-address",
text: format!(
"symbol {} is given at {:#x}, {} the function that is called at {e:#x}: corrected to {e:#x}",
s.name,
s.addr,
if boundary {
"inside"
} else {
"in the middle of an instruction of"
}
),
});
renamed.insert(e, (s.name.clone(), Provenance::Corrected));
continue;
}
if !boundary {
d.findings.push(Finding {
addr: s.addr,
name: s.name.clone(),
kind: "mid-instruction",
text: format!(
"symbol {} is given at {:#x}, which is not an instruction boundary of the code around it: ignored",
s.name, s.addr
),
});
continue;
}
}
d.roots.push(Root {
addr: s.addr,
why: format!("symbol {} given by the user", s.name),
certain: true,
});
scan.add_entry(s.addr, format!("symbol {} given by the user", s.name), true);
renamed.entry(s.addr).or_insert((s.name.clone(), Provenance::Given));
}
let mut bodies = scan.fixpoint();
// 3. Addresses taken: odd words in the literal pools of reached code, and odd words in
// pointer tables this code refers to, that hold up as function entries.
// (A table that a function with an unresolved computed jump refers to is in all
// likelihood its jump table: step 4 resolves the jump first, then this step runs again.)
for _outer in 0..4 {
for _ in 0..16 {
let mut cands: Vec<(u32, String)> = Vec::new();
// Words of data that hold an address inside the image: certainly not code.
let mut pointers: BTreeSet<u32> = BTreeSet::new();
let text_at = |v: u32| {
img.read_const(v, 6).is_some_and(|x| {
x[..4].iter().all(|c| printable(*c)) && x[4..].iter().all(|c| *c == 0 || printable(*c))
})
};
for (e, b) in &bodies {
if !scan.entries[e].1 || !b.unresolved.is_empty() {
continue;
}
for &(v, at) in &b.consts {
let t = v & !1;
// (An odd address may just as well be that of a string.)
let text = img.read_const(v, 6).is_some_and(|x| {
x[..4].iter().all(|c| printable(*c)) && x[4..].iter().all(|c| *c == 0 || printable(*c))
});
if v & 1 == 1 && in_code_space(img, t) && !scan.entries.contains_key(&t) && !text {
cands.push((t, format!("address taken at {at:#x}")));
}
// A table of code addresses that reached code refers to.
if v & 3 == 0 && in_code_space(img, v) && !covered(&bodies, v) {
let mut a = v;
let mut found = Vec::new();
while let Some(w) = word(img, a) {
if covered(&bodies, a)
|| (a != v && bodies.values().any(|b| b.consts.iter().any(|c| c.0 == a)))
{
break;
}
if w & 1 == 1 && in_code_space(img, w & !1) {
found.push((w & !1, a));
} else if w != 0 {
break;
}
a += 4;
}
if found.len() >= 2 {
for (t, a) in found {
if !scan.entries.contains_key(&t) {
cands.push((
t,
format!("entry at {a:#x} of the table of addresses loaded at {at:#x}"),
));
}
}
}
}
}
}
// Data that reached code refers to, and the data that data points to in turn: the
// objects of a program built around tables of function pointers. An odd word there
// that is an address inside the image is a candidate entry, held to the same test as
// the others (it has to be well-formed code on its own, outside known code).
{
let code: BTreeSet<u32> = bodies
.values()
.flat_map(|b| {
let pools = b.pools.iter().flat_map(|(a, n, _)| *a..*a + *n);
b.insns.iter().flat_map(|(a, n)| *a..*a + *n as u32).chain(pools)
})
.collect();
let vectors = d.vectors.map_or(0..0, |(at, n)| at..at + 4 * n as u32);
let mut seen: BTreeSet<u32> = BTreeSet::new();
let mut queue: Vec<(u32, u32)> = bodies
.iter()
.filter(|(e, b)| scan.entries[*e].1 && b.unresolved.is_empty())
.flat_map(|(_, b)| b.consts.iter().map(|c| (c.0 & !3, c.1)))
.collect();
while let Some((from, loaded_at)) = queue.pop() {
let mut a = from;
while in_code_space(img, a) && !code.contains(&a) && !vectors.contains(&a) && seen.insert(a) {
let Some(w) = word(img, a) else { break };
let t = w & !1;
if in_code_space(img, t) {
pointers.insert(a);
}
if w & 1 == 1 && in_code_space(img, t) && !scan.entries.contains_key(&t) && !text_at(w) {
cands.push((
t,
format!("pointer at {a:#x}, in data reached from the address loaded at {loaded_at:#x}"),
));
} else if w & 3 == 0 && in_code_space(img, w) && !code.contains(&w) && !seen.contains(&w) {
queue.push((w, loaded_at));
}
a += 4;
}
}
}
let mut added = false;
cands.sort();
cands.dedup_by_key(|c| c.0);
for (t, why) in cands {
if scan.entries.contains_key(&t) {
continue;
}
// Not inside known code, and well-formed on its own.
if covered(&bodies, t) {
d.notes.push(format!(
"{why}: {t:#x} lies inside known code and is not taken as a function entry"
));
continue;
}
scan.entries.insert(t, (why.clone(), false));
let b = scan.explore(t, true);
scan.entries.remove(&t);
let in_data = b
.insns
.iter()
.any(|(a, n)| pointers.range(a.saturating_sub(3)..a + *n as u32).next().is_some());
if in_data {
d.notes.push(format!(
"{why}: not taken as a function entry (the code there would run into words that hold addresses)"
));
} else if b.bad.is_none() && !b.insns.is_empty() {
d.roots.push(Root {
addr: t,
why: why.clone(),
certain: true,
});
added |= scan.add_entry(t, why, true);
} else if let Some((a, what)) = b.bad {
d.notes
.push(format!("{why}: not taken as a function entry ({what} at {a:#x})"));
}
}
if !added {
break;
}
bodies = scan.fixpoint();
}
// 4. Computed jumps the patterns did not resolve: ask the symbolic executor.
let unresolved: Vec<u32> = bodies
.iter()
.filter(|(_, b)| !b.unresolved.is_empty())
.map(|(e, _)| *e)
.collect();
let mut any = false;
if !unresolved.is_empty() {
let view = exec_view(img, &scan, &bodies);
for e in unresolved {
let limit = scan.limit(e);
let (insns, data, complete) = matcher::trace(&view, e, limit);
let known = &bodies[&e];
for (a, _) in &insns {
if *a >= e && *a < limit && !known.insns.contains_key(a) {
any |= scan.extra.insert((e, *a));
}
}
let tables: Vec<(u32, u32)> = data
.iter()
.filter(|(a, _)| *a >= e && *a < limit)
.map(|(a, n)| (*a, *n as u32))
.collect();
if !tables.is_empty() {
scan.extra_data.insert(e, tables);
}
if !complete {
d.notes.push(format!(
"computed jump in the function at {e:#x}: symbolic execution did not explore every path, some targets may be missing"
));
}
}
if any {
bodies = scan.fixpoint();
}
}
if !any {
break;
}
}
// 5. Functions, with their extents.
let mut byte: BTreeMap<u32, (Kind, u32)> = BTreeMap::new(); // address -> (kind, owning entry)
for (e, b) in &bodies {
for (a, n) in &b.insns {
for x in *a..*a + *n as u32 {
byte.insert(x, (Kind::Code, *e));
}
}
}
for (e, b) in &bodies {
for (a, n, _) in &b.pools {
for x in *a..*a + *n {
byte.entry(x).or_insert((Kind::Pool, *e));
}
}
}
let known: BTreeSet<u32> = scan.entries.keys().copied().collect();
for (e, b) in &bodies {
let limit = scan.limit(*e);
let end = byte
.range(*e..limit)
.filter(|(_, v)| v.1 == *e || v.0 == Kind::Pool)
.map(|(a, _)| *a + 1)
.max()
.unwrap_or(*e);
let (name, provenance) = renamed
.get(e)
.cloned()
.unwrap_or_else(|| (format!("fn_{e:08x}"), Provenance::Discovered));
let mut notes = b.notes.clone();
if let Some((a, what)) = &b.bad {
notes.push(format!("{what} at {a:#x}"));
}
for u in &b.unresolved {
notes.push(format!("computed jump at {u:#x}: targets unknown"));
}
let mut calls: Vec<(u32, u32)> = b.calls.clone();
calls.extend(b.tails.iter().filter(|(_, t)| *t != *e));
calls.sort();
d.funcs.push(Func {
addr: *e,
size: end - *e,
name,
provenance,
why: scan.entries[e].0.clone(),
code: runs(b.insns.iter().map(|(a, n)| (*a, *a + *n as u32))),
pools: runs(b.pools.iter().map(|p| (p.0, p.0 + p.1))),
calls: calls.into_iter().map(|c| c.1).collect(),
noreturn: scan.noreturn.contains(e),
notes,
consts: b
.consts
.iter()
.map(|c| c.0)
.collect::<BTreeSet<u32>>()
.into_iter()
.collect(),
});
}
// 6. Everything else.
let mut refs: BTreeMap<u32, u32> = BTreeMap::new(); // referenced address -> instruction
for b in bodies.values() {
for &(v, at) in &b.consts {
if img.segment_at(v).is_some_and(|s| !s.writable) && !byte.contains_key(&v) {
refs.entry(v).or_insert(at);
}
}
}
let vec_range = d.vectors.map(|(at, n)| (at, at + 4 * n as u32));
for seg in img.segments.iter().filter(|s| !s.writable) {
let seg_end = seg.addr + seg.data.len() as u32;
let mut a = seg.addr;
while a < seg_end {
if let Some(&(kind, owner)) = byte.get(&a) {
let mut e = a;
while e < seg_end && byte.get(&e) == Some(&(kind, owner)) {
e += 1;
}
let evidence = match kind {
Kind::Code => format!("reached from the function at {owner:#x}"),
_ => bodies[&owner]
.pools
.iter()
.find(|p| a >= p.0 && a < p.0 + p.1)
.map(|p| p.2.clone())
.unwrap_or_default(),
};
d.ranges.push(Range {
start: a,
end: e,
kind,
certain: true,
evidence,
score: None,
});
a = e;
continue;
}
if let Some((v0, v1)) = vec_range
&& a >= v0
&& a < v1
{
let e = (a..v1.min(seg_end))
.find(|x| byte.contains_key(x))
.unwrap_or(v1.min(seg_end));
d.ranges.push(Range {
start: a,
end: e,
kind: Kind::Vectors,
certain: true,
evidence: format!("vector table: initial stack pointer and {} vectors", (v1 - v0) / 4 - 1),
score: None,
});
a = e;
continue;
}
// A gap: up to the next classified byte, the vector table or the next referenced address.
let mut e = byte.range(a..seg_end).next().map_or(seg_end, |(x, _)| *x);
if let Some((v0, _)) = vec_range
&& v0 > a
{
e = e.min(v0);
}
if let Some((r, _)) = refs.range(a + 1..e).next() {
e = *r;
}
let data = &seg.data[(a - seg.addr) as usize..(e - seg.addr) as usize];
d.ranges
.extend(classify_gap(img, a, data, refs.get(&a).copied(), &known));
a = e;
}
}
// Unreached bytes inside the extent of a function are most likely its own.
for r in d.ranges.iter_mut().filter(|r| r.kind == Kind::Unknown) {
if let Some(f) = d.funcs.iter().find(|f| f.addr < r.start && r.end <= f.addr + f.size) {
r.evidence = format!(
"inside {} but not reached: dead code (after a call that does not return, say) or data; {}",
f.name, r.evidence
);
}
}
// 7. Speculative functions: unknown ranges that look like code become candidates.
let mut spec_scan = Scan::new(img);
spec_scan.entries = scan.entries.clone();
spec_scan.helpers = scan.helpers.clone();
spec_scan.noreturn = scan.noreturn.clone();
let unknown: Vec<(u32, u32, f32)> = d
.ranges
.iter()
.filter(|r| matches!(r.kind, Kind::Unknown | Kind::DataRef))
.map(|r| (r.start, r.end, r.score.unwrap_or(0.0)))
.collect();
// A long range may hold code and data side by side: its parts are judged one by one.
const WINDOW: u32 = 128;
let mut windows: HashMap<u32, f32> = HashMap::new();
// Functions that only a guessed function calls: guesses as well.
let mut pending: Vec<u32> = Vec::new();
for (start, end, whole) in unknown {
let mut pc = start.next_multiple_of(2);
while pc + 2 <= end {
let local = if whole >= 0.5 {
whole
} else if end - start <= WINDOW {
0.0
} else {
let w = (pc - start) / WINDOW * WINDOW + start;
*windows
.entry(w)
.or_insert_with(|| code_score(img, w, (w + WINDOW).min(end), &known).0)
};
if local < 0.35 {
pc += 2;
continue;
}
let strict = local < 0.5;
// Alignment padding is not the start of a function.
if img
.read_const(pc, 2)
.is_some_and(|x| matches!(u16::from_le_bytes([x[0], x[1]]), 0 | 0xbf00 | 0x46c0))
{
pc += 2;
continue;
}
spec_scan
.entries
.insert(pc, ("unreached bytes that decode as a function".into(), false));
let b = spec_scan.explore(pc, true);
let last = b.insns.iter().map(|(a, n)| a + *n as u32).max().unwrap_or(pc);
let ok = b.bad.is_none()
&& b.returns
&& b.unresolved.is_empty()
&& b.insns.len() >= if strict { 4 } else { 2 }
&& last <= end
&& b.calls
.iter()
.chain(&b.tails)
.all(|(_, t)| known.contains(t) || (*t >= start && *t < end) || spec_scan.plausible(*t, &known));
if !ok {
spec_scan.entries.remove(&pc);
pc += 2;
continue;
}
pending.extend(
b.calls
.iter()
.map(|c| c.1)
.filter(|t| !known.contains(t) && !(*t >= start && *t < end)),
);
let pool_end = b
.pools
.iter()
.map(|p| p.0 + p.1)
.filter(|x| *x <= end)
.max()
.unwrap_or(last);
let fend = last.max(pool_end);
d.funcs.push(Func {
addr: pc,
size: fend - pc,
name: format!("sub_{pc:08x}"),
provenance: Provenance::Speculative,
why: "unreached bytes that decode as a function ending in a return (a guess)".into(),
code: runs(b.insns.iter().map(|(a, n)| (*a, *a + *n as u32))),
pools: runs(b.pools.iter().map(|p| (p.0, p.0 + p.1))),
calls: b.calls.iter().map(|c| c.1).collect(),
noreturn: false,
notes: Vec::new(),
consts: b
.consts
.iter()
.map(|c| c.0)
.collect::<BTreeSet<u32>>()
.into_iter()
.collect(),
});
pc = fend.next_multiple_of(2).max(pc + 2);
}
}
pending.sort_unstable();
pending.dedup();
for t in pending {
if d.funcs.iter().any(|f| f.addr <= t && t < f.addr + f.size.max(2)) {
continue;
}
spec_scan.entries.insert(
t,
("called from unreached bytes that decode as a function".into(), false),
);
let b = spec_scan.explore(t, true);
let last = b.insns.iter().map(|(a, n)| a + *n as u32).max().unwrap_or(t);
if b.bad.is_some() || b.insns.is_empty() {
spec_scan.entries.remove(&t);
continue;
}
d.funcs.push(Func {
addr: t,
size: last - t,
name: format!("sub_{t:08x}"),
provenance: Provenance::Speculative,
why: "called from unreached bytes that decode as a function (a guess)".into(),
code: runs(b.insns.iter().map(|(a, n)| (*a, *a + *n as u32))),
pools: Vec::new(),
calls: b.calls.iter().map(|c| c.1).collect(),
noreturn: false,
notes: Vec::new(),
consts: Vec::new(),
});
}
d.funcs.sort_by_key(|f| f.addr);
// 8. Audit of the given table against what was found.
audit(img, opts, &mut d, &byte);
let image = rebuild(img, &d);
Analysis { discovery: d, image }
}
fn covered(bodies: &BTreeMap<u32, Body>, a: u32) -> bool {
bodies.values().any(|b| {
b.insns.range(a.saturating_sub(3)..=a).any(|(s, n)| a < s + *n as u32)
|| b.pools.iter().any(|p| a >= p.0 && a < p.0 + p.1)
})
}
/// Merge ranges into maximal runs.
fn runs(it: impl Iterator<Item = (u32, u32)>) -> Vec<(u32, u32)> {
let mut v: Vec<(u32, u32)> = it.collect();
v.sort();
let mut out: Vec<(u32, u32)> = Vec::new();
for (a, b) in v {
match out.last_mut() {
Some(l) if a <= l.1 => l.1 = l.1.max(b),
_ => out.push((a, b)),
}
}
out
}
/// Classify bytes no code was found in. `referenced`: the instruction that loads the address
/// of the first byte, if any.
fn classify_gap(img: &Image, start: u32, data: &[u8], referenced: Option<u32>, known: &BTreeSet<u32>) -> Vec<Range> {
let end = start + data.len() as u32;
let mut out = Vec::new();
let mk = |start: u32, end: u32, kind: Kind, certain: bool, evidence: String, score: Option<f32>| Range {
start,
end,
kind,
certain,
evidence,
score,
};
let fill = |d: &[u8]| {
d.iter().all(|&x| x == 0)
|| d.iter().all(|&x| x == 0xff)
|| (d.len().is_multiple_of(2)
&& start.is_multiple_of(2)
&& d.chunks(2)
.all(|c| matches!(u16::from_le_bytes([c[0], c[1]]), 0xbf00 | 0x46c0 | 0)))
};
let refd = referenced.map(|at| format!("its address is loaded at {at:#x}"));
if fill(data) && referenced.is_none() {
out.push(mk(start, end, Kind::Padding, false, "fill bytes".into(), None));
return out;
}
// Trailing fill is padding, not part of the object.
let mut body = data.len();
if referenced.is_none() || data.len() > 16 {
while body > 0 && matches!(data[body - 1], 0 | 0xff) && body > data.len().saturating_sub(64) {
body -= 1;
}
// Keep the NUL that ends a string.
if body < data.len() && data[body] == 0 && body > 0 && printable(data[body - 1]) {
body += 1;
}
if data.len() - body < 2 {
body = data.len();
}
}
let (d0, mid) = (&data[..body], start + body as u32);
let words: Vec<u32> = if start.is_multiple_of(4) && d0.len().is_multiple_of(4) && d0.len() >= 8 {
d0.chunks(4)
.map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]]))
.collect()
} else {
Vec::new()
};
let pointers = words
.iter()
.filter(|&&w| w != 0 && (img.segment_at(w & !1).is_some() || (0x2000_0000..0x2010_0000).contains(&w)))
.count();
let code_ptrs = words
.iter()
.filter(|&&w| w & 1 == 1 && known.contains(&(w & !1)))
.count();
let (score, why) = code_score(img, start, mid, known);
let kind;
let mut evidence;
if !words.is_empty() && pointers == words.iter().filter(|&&w| w != 0).count() && pointers >= 2 {
kind = Kind::PointerTable;
evidence = format!(
"{} words, all addresses inside the image or RAM ({code_ptrs} are entries of known functions)",
words.len()
);
} else if looks_like_strings(d0) {
kind = Kind::String;
let text: String = d0
.iter()
.take(24)
.map(|&b| if (0x20..0x7f).contains(&b) { b as char } else { '.' })
.collect();
evidence = format!("printable text ending in NUL: \"{text}\"");
} else if referenced.is_some() {
kind = Kind::DataRef;
evidence = String::new();
} else {
kind = Kind::Unknown;
evidence = if score >= 0.7 {
format!("unreferenced, looks like code (score {score:.2}): possible dead or hidden function; {why}")
} else if score >= 0.4 {
format!("unreferenced, may be code (score {score:.2}); {why}")
} else {
format!("unreferenced, no evidence of code (score {score:.2})")
};
}
match &refd {
Some(r) if evidence.is_empty() => evidence = r.clone(),
Some(r) => evidence = format!("{r}; {evidence}"),
None => {}
}
if referenced.is_some() && score >= 0.7 && kind != Kind::Unknown {
evidence.push_str(&format!("; but it looks like code (score {score:.2}): {why}"));
}
out.push(mk(start, mid, kind, referenced.is_some(), evidence, Some(score)));
if mid < end {
out.push(mk(mid, end, Kind::Padding, false, "fill bytes".into(), None));
}
out
}
/// Compare the symbol table that was given with what discovery found.
fn audit(img: &Image, opts: &Options, d: &mut Discovery, byte: &BTreeMap<u32, (Kind, u32)>) {
let any_given = img.symbols.iter().any(|s| s.kind != SymKind::Other);
let func_at = |d: &Discovery, a: u32| d.funcs.iter().position(|f| f.addr == a);
for s in img.symbols.iter().filter(|s| s.kind == SymKind::Func) {
let Some(i) = func_at(d, s.addr) else { continue };
let f = &d.funcs[i];
if f.name != s.name {
continue; // an alias, or a symbol that was corrected away
}
let bad = f
.notes
.iter()
.find(|n| n.contains("UNPREDICTABLE") || n.contains("leaves the image"));
if let Some(n) = bad {
d.findings.push(Finding {
addr: s.addr,
name: s.name.clone(),
kind: "not-code",
text: format!("symbol {} at {:#x} does not hold up as code: {n}", s.name, s.addr),
});
}
// Sizes: the linker's size covers the code and its literal pools, as the extent does;
// alignment padding belongs to neither.
let stated = opts
.given_sizes
.iter()
.find(|g| g.0 == s.name && g.1 == s.addr)
.map_or(s.size, |g| g.2);
// A larger size that takes in fragments other code jumps into (shared tails of
// hand-written routines) is the table's to decide: the fragments join the function.
if stated != u32::MAX && stated > f.size + 2 {
let end = s.addr + stated;
let inside: Vec<usize> = (0..d.funcs.len())
.filter(|&j| d.funcs[j].addr > s.addr && d.funcs[j].addr < end)
.collect();
let fragments = inside.iter().all(|&j| {
let x = &d.funcs[j];
x.addr + x.size <= end && x.why.starts_with("jumped to") && is_anonymous(&x.name)
});
let filled = inside.iter().map(|&j| d.funcs[j].addr + d.funcs[j].size).max();
if fragments && filled.is_some_and(|e| e + 2 >= end) {
let mut code = Vec::new();
let mut pools = Vec::new();
for &j in inside.iter().rev() {
let x = d.funcs.remove(j);
code.extend(x.code);
pools.extend(x.pools);
}
let f = &mut d.funcs[i];
f.code = runs(f.code.iter().copied().chain(code));
f.pools = runs(f.pools.iter().copied().chain(pools));
f.size = stated;
continue;
}
}
let f = &d.funcs[i];
if stated != u32::MAX && (stated == 0 || stated.abs_diff(f.size) > 2) {
let text = match stated {
0 => format!("symbol {} has no size: the code extends over {} bytes", s.name, f.size),
n => format!(
"symbol {} is given {n} bytes, the code reached from it extends over {} bytes",
s.name, f.size
),
};
// A size that is merely inferred from the next symbol is not a finding when it
// agrees with the extent up to padding.
d.findings.push(Finding {
addr: s.addr,
name: s.name.clone(),
kind: "wrong-size",
text,
});
d.funcs[i].provenance = d.funcs[i].provenance.max(Provenance::Corrected);
}
}
if any_given {
for f in d.funcs.iter().filter(|f| f.provenance == Provenance::Discovered) {
d.findings.push(Finding {
addr: f.addr,
name: f.name.clone(),
kind: "missing",
text: format!(
"no symbol for the function at {:#x} ({} bytes; {})",
f.addr, f.size, f.why
),
});
}
}
for s in img.symbols.iter().filter(|s| s.kind == SymKind::Object && s.size > 0) {
let code: Vec<u32> = byte
.range(s.addr..s.addr + s.size)
.filter(|(_, v)| v.0 == Kind::Code)
.map(|(a, _)| *a)
.collect();
if let (Some(first), Some(last)) = (code.first(), code.last()) {
d.findings.push(Finding {
addr: s.addr,
name: s.name.clone(),
kind: "data-covers-code",
text: format!(
"data symbol {} ({:#x}, {} bytes) covers code that is reached from an entry point: {first:#x}-{:#x}",
s.name,
s.addr,
s.size,
last + 1
),
});
}
}
let sized: Vec<&Symbol> = img
.symbols
.iter()
.filter(|s| s.kind != SymKind::Other && s.size > 0 && img.segment_at(s.addr).is_some_and(|g| !g.writable))
.collect();
for (i, a) in sized.iter().enumerate() {
for b in &sized[i + 1..] {
if b.addr >= a.addr + a.size {
break;
}
if b.addr != a.addr && a.kind == b.kind {
d.findings.push(Finding {
addr: b.addr,
name: b.name.clone(),
kind: "overlap",
text: format!(
"symbols {} ({:#x}, {} bytes) and {} ({:#x}) overlap",
a.name, a.addr, a.size, b.name, b.addr
),
});
}
}
}
}
/// An image the executor can run during discovery: every read-only byte may be executed.
fn exec_view(img: &Image, scan: &Scan, bodies: &BTreeMap<u32, Body>) -> Image {
let mut v = Image {
segments: img.segments.clone(),
static_base: img.static_base,
soft_bounds: img.soft_bounds,
..Default::default()
};
for e in scan.entries.keys() {
if scan.helpers.contains_key(e) || !bodies.contains_key(e) {
continue;
}
v.symbols.push(Symbol {
name: format!("fn_{e:08x}"),
addr: *e,
size: scan.limit(*e) - *e,
kind: SymKind::Func,
global: true,
file: None,
});
}
v
}
/// The image with the recovered symbol table: functions as found (given names kept, new ones
/// named `fn_<address>`, guesses `sub_<address>`), literal pools marked as data in code. In a
/// raw image the memory is cut into code (what the functions cover) and the rest; the rest is
/// counted by verification unless something accounts for it, and ranges that reached code
/// refers to as data are set aside with that evidence.
pub fn rebuild(img: &Image, d: &Discovery) -> Image {
let mut out = Image {
segments: Vec::new(),
symbols: Vec::new(),
data_ranges: Vec::new(),
..img.clone()
};
// Functions: speculative ones are listed but do not become symbols unless they were named.
let mut names: BTreeSet<(u32, String)> = BTreeSet::new();
for f in &d.funcs {
if f.provenance == Provenance::Speculative && f.name.starts_with("sub_") {
continue;
}
if names.insert((f.addr, f.name.clone())) {
out.symbols.push(Symbol {
name: f.name.clone(),
addr: f.addr,
size: f.size.max(2),
kind: SymKind::Func,
global: true,
file: None,
});
}
out.data_ranges.extend(f.pools.iter().copied());
}
// Other names for the same code (aliases, identical functions folded by the linker).
for m in &d.matches {
if let Some(f) = d.funcs.iter().find(|f| f.addr == m.addr)
&& names.insert((m.addr, m.source.clone()))
{
out.symbols.push(Symbol {
name: m.source.clone(),
addr: m.addr,
size: f.size.max(2),
kind: SymKind::Func,
global: true,
file: None,
});
}
}
for s in &img.symbols {
match s.kind {
SymKind::Func => {
// Aliases of a function that was kept under another given name.
if d.funcs
.iter()
.any(|f| f.addr == s.addr && f.provenance != Provenance::Speculative)
&& names.insert((s.addr, s.name.clone()))
&& !d
.findings
.iter()
.any(|x| x.name == s.name && matches!(x.kind, "wrong-address" | "mid-instruction" | "swapped"))
{
let size = d.funcs.iter().find(|f| f.addr == s.addr).map_or(s.size, |f| f.size);
out.symbols.push(Symbol {
size: size.max(2),
..s.clone()
});
}
}
_ => out.symbols.push(s.clone()),
}
}
for (name, addr, size) in &d.objects {
if !out
.symbols
.iter()
.any(|s| s.kind == SymKind::Object && s.name == *name && s.addr == *addr)
{
out.symbols.push(Symbol {
name: name.clone(),
addr: *addr,
size: *size,
kind: SymKind::Object,
global: true,
file: None,
});
}
}
if !img.soft_bounds {
out.segments = img.segments.clone();
out.data_ranges.extend(img.data_ranges.iter().copied());
out.finish();
return out;
}
// Cut the flat memory: executable where a function (not a guess) has code or pools.
let mut code: Vec<(u32, u32)> = Vec::new();
for f in d
.funcs
.iter()
.filter(|f| out.symbols.iter().any(|s| s.kind == SymKind::Func && s.addr == f.addr))
{
code.extend(f.code.iter().copied());
code.extend(f.pools.iter().copied());
}
let mut code = runs(code.into_iter());
// Padding between two pieces of code stays with the code.
let mut merged: Vec<(u32, u32)> = Vec::new();
for (a, b) in code.drain(..) {
match merged.last_mut() {
Some(l)
if a - l.1 <= 16
&& img.read_const(l.1, a - l.1).is_some_and(|g| {
g.len().is_multiple_of(2)
&& g.chunks(2)
.all(|c| matches!(u16::from_le_bytes([c[0], c[1]]), 0 | 0xbf00 | 0x46c0))
}) =>
{
l.1 = b
}
_ => merged.push((a, b)),
}
}
for seg in &img.segments {
if seg.writable {
out.segments.push(seg.clone());
continue;
}
let end = seg.addr + seg.data.len() as u32;
let mut at = seg.addr;
let piece = |a: u32, b: u32, exec: bool, out: &mut Image| {
if a < b {
out.segments.push(Segment {
name: if exec { "code".into() } else { "raw".into() },
addr: a,
data: seg.data[(a - seg.addr) as usize..(b - seg.addr) as usize].to_vec(),
writable: false,
exec,
load_addr: None,
});
}
};
for &(a, b) in merged.iter().filter(|r| r.0 >= seg.addr && r.1 <= end) {
piece(at, a, false, &mut out);
piece(a, b, true, &mut out);
at = b;
}
piece(at, end, false, &mut out);
}
for r in &d.ranges {
let aside = match r.kind {
Kind::Vectors => true,
Kind::DataRef | Kind::PointerTable | Kind::String => r.certain && r.score.is_none_or(|s| s < 0.7),
_ => false,
};
if aside {
out.set_aside.push((
r.start,
r.end,
format!("classified by discovery as {}: {}", r.kind.label(), r.evidence),
));
}
}
out.finish();
out
}
/// Discovery, then naming by proof against the source `prog`: the analysis with the names
/// applied, and how verification has to place the source's functions and objects.
pub fn discover_with_source(
given: &Image,
prog: &crate::c::ast::Program,
opts: &Options,
vopts: &crate::verify::Options,
) -> (Analysis, crate::verify::Preset) {
let first_analysis = discover(given, opts);
let first = matcher::run(prog, given, &first_analysis, vopts, &HashMap::new(), &HashMap::new());
let has = |img: &Image, name: &str, addr: u32| {
img.symbols
.iter()
.any(|s| s.kind == SymKind::Func && s.name == name && s.addr == addr)
};
// What the proofs establish becomes part of the table: functions that nothing reaches are
// entry points once they are proved to be a source function, and what they call is then
// reached too.
let added: Vec<(u32, String)> = first
.matches
.iter()
.filter(|m| matches!(m.how, "proved" | "conditional" | "bounded") && !has(given, &m.source, m.addr))
// (Naming a function that discovery already has changes nothing about what is reached.)
.filter(|m| {
let known = first_analysis.discovery.funcs.iter().find(|f| f.addr == m.addr);
!given.symbols.iter().all(|s| s.kind != SymKind::Func)
|| known.is_none_or(|f| f.provenance == Provenance::Speculative)
})
.map(|m| (m.addr, m.source.clone()))
.collect();
let (mut a, out, table) = if added.is_empty() && first.dropped.is_empty() {
(first_analysis, first, given.clone())
} else {
let mut g2 = given.clone();
g2.symbols
.retain(|s| !(s.kind == SymKind::Func && first.dropped.iter().any(|d| d.0 == s.name && d.1 == s.addr)));
let mut o2 = opts.clone();
o2.given_sizes
.retain(|g| !first.dropped.iter().any(|d| d.0 == g.0 && d.1 == g.1));
for (addr, name) in &added {
g2.symbols.push(Symbol {
name: name.clone(),
addr: *addr,
size: 0,
kind: SymKind::Func,
global: true,
file: None,
});
o2.given_sizes.push((name.clone(), *addr, u32::MAX));
}
g2.symbols
.sort_by_key(|s| (s.addr, s.kind != SymKind::Func, s.name.clone()));
let mut a2 = discover(&g2, &o2);
let mut second = matcher::run(prog, &g2, &a2, vopts, &first.tried, &first.last);
second.findings.extend(first.findings.iter().cloned());
second.dropped = first.dropped.clone();
for f in a2.discovery.funcs.iter_mut() {
let Some((_, name)) = added.iter().find(|e| e.0 == f.addr && e.1 == f.name) else {
continue;
};
if first.dropped.iter().any(|d| d.0 == *name) {
f.provenance = Provenance::Corrected;
} else {
f.provenance = Provenance::Discovered;
let before = first_analysis.discovery.funcs.iter().find(|x| x.addr == f.addr);
f.why = match before {
Some(x) if x.provenance != Provenance::Speculative => x.why.clone(),
_ => {
let how = first
.matches
.iter()
.find(|m| m.addr == f.addr && m.source == *name)
.map(|m| m.how);
match how {
Some("proved") | None => {
format!(
"not reached from any entry point; proved equivalent to the source function {name}"
)
}
Some(how) => format!(
"not reached from any entry point; taken to be the source function {name} ({how} match, not proved outright)"
),
}
}
};
}
}
a2.discovery.roots.retain(|r| {
!added
.iter()
.any(|e| r.why == format!("symbol {} given by the user", e.1))
});
(a2, second, g2)
};
matcher::apply(&mut a.discovery, &out);
// What the given table lacks is judged against the table as it was given.
a.discovery.findings.retain(|f| f.kind != "missing");
if given.symbols.iter().any(|s| s.kind == SymKind::Func) {
let missing: Vec<Finding> = a
.discovery
.funcs
.iter()
.filter(|f| {
f.provenance != Provenance::Speculative
&& !given
.symbols
.iter()
.any(|s| s.kind == SymKind::Func && s.addr == f.addr)
})
.map(|f| Finding {
addr: f.addr,
name: f.name.clone(),
kind: "missing",
text: format!(
"no symbol for the function at {:#x} ({} bytes; {}){}",
f.addr,
f.size,
f.why,
if is_anonymous(&f.name) {
String::new()
} else {
format!(": it is {}", f.name)
}
),
})
.collect();
a.discovery.findings.extend(missing);
}
a.discovery.findings.sort_by_key(|f| (f.addr, f.kind));
a.discovery
.findings
.dedup_by(|x, y| x.addr == y.addr && x.kind == y.kind && x.name == y.name);
a.image = rebuild(&table, &a.discovery);
(a, out.preset)
}
// ----- output ---------------------------------------------------------------------------
impl Discovery {
/// The recovered symbol table in `nm` format, one line per symbol, with the provenance
/// after the name (cverif reads the file back with `--symbols`; other tools read the
/// first four columns).
pub fn symbols_text(&self, image: &Image) -> String {
let mut o = String::new();
let _ = writeln!(o, "# symbol table recovered by cverif --discover");
let _ = writeln!(o, "# address size type name # provenance: reason");
for f in &self.funcs {
if f.provenance == Provenance::Speculative && is_anonymous(&f.name) {
let _ = writeln!(
o,
"# {:08x} {:08x} t {} # speculative: {}",
f.addr, f.size, f.name, f.why
);
continue;
}
let mut names: Vec<(String, String)> = vec![(f.name.clone(), f.provenance.label().to_string())];
for m in self.matches.iter().filter(|m| m.addr == f.addr) {
match names.iter_mut().find(|n| n.0 == m.source) {
Some(n) => n.1 = format!("{}, {}", n.1, m.how),
None => names.push((m.source.clone(), format!("{}, {}", f.provenance.label(), m.how))),
}
}
// Other names the given table has for the same address.
for s in image
.symbols
.iter()
.filter(|s| s.kind == SymKind::Func && s.addr == f.addr)
{
if !names.iter().any(|n| n.0 == s.name) {
names.push((s.name.clone(), "given".to_string()));
}
}
for (name, prov) in names {
let _ = writeln!(o, "{:08x} {:08x} T {} # {}: {}", f.addr, f.size, name, prov, f.why);
}
}
for s in image.symbols.iter().filter(|s| s.kind != SymKind::Func) {
let class = match (s.kind, image.segment_at(s.addr).is_some_and(|g| g.writable)) {
(SymKind::Other, _) => 'A',
(_, true) => 'D',
(_, false) => 'R',
};
let prov = if self.objects.iter().any(|o| o.0 == s.name) {
"located by the proofs that use it"
} else {
"given"
};
if s.size > 0 {
let _ = writeln!(o, "{:08x} {:08x} {class} {} # {prov}", s.addr, s.size, s.name);
} else {
let _ = writeln!(o, "{:08x} {class} {} # {prov}", s.addr, s.name);
}
}
o
}
/// A map-like listing of every classified range in address order.
pub fn map_text(&self) -> String {
let mut o = String::new();
let _ = writeln!(o, "memory map (address range, size, classification, evidence):");
for r in &self.ranges {
let name = match r.kind {
Kind::Code | Kind::Pool => self
.funcs
.iter()
.rev()
.find(|f| f.addr <= r.start && r.start < f.addr + f.size.max(1))
.map(|f| format!(" <{}>", f.name))
.unwrap_or_default(),
_ => String::new(),
};
let _ = writeln!(
o,
" {:08x}-{:08x} {:>6} {:<15} {}{}{}",
r.start,
r.end,
r.end - r.start,
r.kind.label(),
if r.certain { "" } else { "(guess) " },
r.evidence,
name
);
}
o
}
/// The report printed by `cverif --discover`.
pub fn render(&self, verbose: bool) -> String {
let mut o = String::new();
let _ = writeln!(o, "discovery:");
match self.vectors {
Some((at, n)) => {
let _ = writeln!(o, " vector table at {at:#x}: {n} words");
}
None => {
let _ = writeln!(o, " no vector table");
}
}
let count = |p: Provenance| self.funcs.iter().filter(|f| f.provenance == p).count();
let _ = writeln!(
o,
" functions: {} given, {} corrected, {} discovered (reached from an entry point, or proved against the source), {} speculative (guesses)",
count(Provenance::Given),
count(Provenance::Corrected),
count(Provenance::Discovered),
count(Provenance::Speculative)
);
let mut by: BTreeMap<&str, (u32, u32, usize)> = BTreeMap::new();
for r in &self.ranges {
let e = by.entry(r.kind.label()).or_default();
e.0 += r.end - r.start;
if !r.certain {
e.1 += r.end - r.start;
}
e.2 += 1;
}
let _ = writeln!(o, " bytes by classification:");
for (k, (n, guess, ranges)) in &by {
let g = if *guess > 0 && guess != n {
format!(" ({guess} by guess)")
} else if *guess > 0 {
" (by guess from the contents)".into()
} else {
String::new()
};
let _ = writeln!(o, " {k:<15} {n:>7} bytes in {ranges} range(s){g}");
}
for r in self
.ranges
.iter()
.filter(|r| r.kind == Kind::Unknown || r.score.is_some_and(|s| s >= 0.7))
{
let _ = writeln!(
o,
" {:#x}-{:#x} ({} bytes): {}",
r.start,
r.end,
r.end - r.start,
r.evidence
);
}
for f in self.funcs.iter().filter(|f| !f.notes.is_empty()) {
for n in &f.notes {
let _ = writeln!(o, " {} at {:#x}: {n}", f.name, f.addr);
}
}
for n in &self.notes {
let _ = writeln!(o, " note: {n}");
}
if !self.findings.is_empty() {
let _ = writeln!(o, "symbol table audit: {} finding(s)", self.findings.len());
for f in &self.findings {
let _ = writeln!(o, " [{}] {}", f.kind, f.text);
}
}
if !self.matches.is_empty() || !self.not_found.is_empty() {
let n = |how: &str| self.matches.iter().filter(|m| m.how == how).count();
let _ = writeln!(
o,
"source matching: {} proved, {} proved given the names of their callees (conditional), {} bounded match(es), {} named by the source's data (not proved), {} named by the calls of their callers (not proved), {} recognised by test vectors (not proved), {} kept as given; {} source function(s) not found, {} function(s) of the binary without source",
n("proved"),
n("conditional"),
n("bounded"),
n("by-data"),
n("by-calls"),
n("recognised"),
n("given"),
self.not_found.len(),
self.binary_only.len()
);
for m in &self.matches {
if m.how == "given" && !verbose {
continue;
}
let also = if m.also.is_empty() {
String::new()
} else {
format!(
" (the proof also succeeds at {})",
m.also.iter().map(|a| format!("{a:#x}")).collect::<Vec<_>>().join(", ")
)
};
let _ = writeln!(
o,
" {:<10} {:#x} = {}{also}{}",
m.how,
m.addr,
m.source,
if m.detail.is_empty() {
String::new()
} else {
format!(" [{}]", m.detail)
}
);
}
for (name, addr, _) in &self.objects {
let _ = writeln!(o, " object {addr:#x} = {name} (located by the proofs that use it)");
}
for (i, s) in self.not_found.iter().enumerate() {
match self.not_found_why.get(i).filter(|_| verbose) {
Some(why) => {
let _ = writeln!(o, " not found: {s} ({why})");
}
None => {
let _ = writeln!(o, " not found: {s}");
}
}
}
for a in &self.binary_only {
let f = self.funcs.iter().find(|f| f.addr == *a);
let _ = writeln!(
o,
" binary only: {} at {a:#x} ({} bytes)",
f.map_or("?", |f| f.name.as_str()),
f.map_or(0, |f| f.size)
);
}
}
if verbose {
let _ = writeln!(o, "functions:");
for f in &self.funcs {
let _ = writeln!(
o,
" {:08x} {:>5} {:<12} {}{} ({})",
f.addr,
f.size,
f.provenance.label(),
f.name,
if f.noreturn { " [does not return]" } else { "" },
f.why
);
}
o.push_str(&self.map_text());
}
o
}
/// The `"discovery"` object of the JSON report.
pub fn json(&self) -> String {
let s = json_str;
let mut o = String::from("{\n");
match self.vectors {
Some((at, n)) => {
let _ = writeln!(o, " \"vector_table\": {{\"address\":{at},\"words\":{n}}},");
}
None => o.push_str(" \"vector_table\": null,\n"),
}
let list = |items: Vec<String>| items.join(",\n ");
let _ = writeln!(
o,
" \"roots\": [\n {}\n ],",
list(
self.roots
.iter()
.map(|r| format!(
"{{\"address\":{},\"why\":{},\"certain\":{}}}",
r.addr,
s(&r.why),
r.certain
))
.collect()
)
);
let _ = writeln!(
o,
" \"functions\": [\n {}\n ],",
list(
self.funcs
.iter()
.map(|f| format!(
"{{\"address\":{},\"size\":{},\"name\":{},\"provenance\":\"{}\",\"why\":{},\"noreturn\":{},\"notes\":[{}]}}",
f.addr,
f.size,
s(&f.name),
f.provenance.label(),
s(&f.why),
f.noreturn,
f.notes.iter().map(|n| s(n)).collect::<Vec<_>>().join(",")
))
.collect()
)
);
let _ = writeln!(
o,
" \"ranges\": [\n {}\n ],",
list(
self.ranges
.iter()
.map(|r| format!(
"{{\"start\":{},\"end\":{},\"kind\":\"{}\",\"certain\":{},\"evidence\":{},\"code_score\":{}}}",
r.start,
r.end,
r.kind.label(),
r.certain,
s(&r.evidence),
r.score.map_or("null".to_string(), |x| format!("{x:.2}"))
))
.collect()
)
);
let _ = writeln!(
o,
" \"audit\": [\n {}\n ],",
list(
self.findings
.iter()
.map(|f| format!(
"{{\"kind\":\"{}\",\"address\":{},\"name\":{},\"text\":{}}}",
f.kind,
f.addr,
s(&f.name),
s(&f.text)
))
.collect()
)
);
let _ = writeln!(
o,
" \"matches\": [\n {}\n ],",
list(
self.matches
.iter()
.map(|m| format!(
"{{\"source\":{},\"address\":{},\"how\":\"{}\",\"also\":[{}],\"detail\":{}}}",
s(&m.source),
m.addr,
m.how,
m.also.iter().map(|a| a.to_string()).collect::<Vec<_>>().join(","),
s(&m.detail)
))
.collect()
)
);
let _ = writeln!(
o,
" \"objects\": [{}],",
self.objects
.iter()
.map(|(n, a, size)| format!("{{\"name\":{},\"address\":{a},\"size\":{size}}}", s(n)))
.collect::<Vec<_>>()
.join(",")
);
let _ = writeln!(
o,
" \"source_functions_not_found\": [{}],",
self.not_found.iter().map(|n| s(n)).collect::<Vec<_>>().join(",")
);
let _ = writeln!(
o,
" \"binary_only\": [{}],",
self.binary_only
.iter()
.map(|a| a.to_string())
.collect::<Vec<_>>()
.join(",")
);
let _ = writeln!(
o,
" \"notes\": [{}]",
self.notes.iter().map(|n| s(n)).collect::<Vec<_>>().join(",")
);
o.push_str(" }");
o
}
}
fn json_str(s: &str) -> String {
let mut o = String::with_capacity(s.len() + 2);
o.push('"');
for c in s.chars() {
match c {
'"' => o.push_str("\\\""),
'\\' => o.push_str("\\\\"),
'\n' => o.push_str("\\n"),
c if (c as u32) < 0x20 => {
let _ = write!(o, "\\u{:04x}", c as u32);
}
c => o.push(c),
}
}
o.push('"');
o
}