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
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
|
//
// Created by kat on 5/19/23.
//
#include "binaryninjaapi.h"
/* ---
* This is the primary image loader logic for Shared Caches
*
* It is standalone code that operates on a DSCView.
*
* This has to recreate _all_ of the Mach-O View logic, but slightly differently, as everything is spicy and weird and
* different enough that it's not worth trying to make a shared base class.
*
* The SharedCache api object is a 'Controller' that serializes its own state in view metadata.
*
* It is multithreading capable (multiple SharedCache objects can exist and do things on different threads, it will manage)
*
* View state is saved to BinaryView any time it changes, however due to json deser speed we must also cache it on heap.
* This cache is 'load bearing' and controllers on other threads may serialize it back to view after making changes, so it
* must be kept up to date.
*
*
*
* */
#include "SharedCache.h"
#include "ObjC.h"
#include <filesystem>
#include <mutex>
#include <unordered_map>
#include <utility>
#include <fcntl.h>
#include <memory>
#include <chrono>
#include <thread>
using namespace BinaryNinja;
using namespace SharedCacheCore;
#ifdef _MSC_VER
int count_trailing_zeros(uint64_t value) {
unsigned long index; // 32-bit long on Windows
if (_BitScanForward64(&index, value)) {
return index;
} else {
return 64; // If the value is 0, return 64.
}
}
#else
int count_trailing_zeros(uint64_t value) {
return value == 0 ? 64 : __builtin_ctzll(value);
}
#endif
struct SharedCache::State
{
std::unordered_map<uint64_t, std::vector<std::pair<uint64_t, std::pair<BNSymbolType, std::string>>>>
exportInfos;
std::unordered_map<uint64_t, std::vector<std::pair<uint64_t, std::pair<BNSymbolType, std::string>>>>
symbolInfos;
std::unordered_map<std::string, uint64_t> imageStarts;
std::unordered_map<uint64_t, SharedCacheMachOHeader> headers;
std::vector<CacheImage> images;
std::vector<MemoryRegion> regionsMappedIntoMemory;
std::vector<BackingCache> backingCaches;
std::vector<MemoryRegion> stubIslandRegions; // TODO honestly both of these should be refactored into nonImageRegions. :p
std::vector<MemoryRegion> dyldDataRegions;
std::vector<MemoryRegion> nonImageRegions;
std::string baseFilePath;
SharedCacheFormat cacheFormat;
DSCViewState viewState = DSCViewStateUnloaded;
};
struct SharedCache::ViewSpecificState {
std::mutex typeLibraryMutex;
std::unordered_map<std::string, Ref<TypeLibrary>> typeLibraries;
std::mutex viewOperationsThatInfluenceMetadataMutex;
std::atomic<BNDSCViewLoadProgress> progress;
std::mutex stateMutex;
std::shared_ptr<struct SharedCache::State> cachedState;
};
std::shared_ptr<SharedCache::ViewSpecificState> ViewSpecificStateForId(uint64_t viewIdentifier, bool insertIfNeeded = true) {
static std::mutex viewSpecificStateMutex;
static std::unordered_map<uint64_t, std::weak_ptr<SharedCache::ViewSpecificState>> viewSpecificState;
std::lock_guard lock(viewSpecificStateMutex);
if (auto it = viewSpecificState.find(viewIdentifier); it != viewSpecificState.end()) {
if (auto statePtr = it->second.lock()) {
return statePtr;
}
}
if (!insertIfNeeded) {
return nullptr;
}
auto statePtr = std::make_shared<SharedCache::ViewSpecificState>();
viewSpecificState[viewIdentifier] = statePtr;
// Prune entries for any views that are no longer in use.
for (auto it = viewSpecificState.begin(); it != viewSpecificState.end(); ) {
if (it->second.expired()) {
it = viewSpecificState.erase(it);
} else {
++it;
}
}
return statePtr;
}
std::shared_ptr<SharedCache::ViewSpecificState> ViewSpecificStateForView(Ref<BinaryNinja::BinaryView> view) {
return ViewSpecificStateForId(view->GetFile()->GetSessionId());
}
std::string base_name(std::string const& path)
{
return path.substr(path.find_last_of("/\\") + 1);
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-function"
static int64_t readSLEB128(DataBuffer& buffer, size_t length, size_t& offset)
{
uint8_t cur;
int64_t value = 0;
size_t shift = 0;
while (offset < length)
{
cur = buffer[offset++];
value |= (cur & 0x7f) << shift;
shift += 7;
if ((cur & 0x80) == 0)
break;
}
value = (value << (64 - shift)) >> (64 - shift);
return value;
}
#pragma clang diagnostic pop
static uint64_t readLEB128(DataBuffer& p, size_t end, size_t& offset)
{
uint64_t result = 0;
int bit = 0;
do
{
if (offset >= end)
return -1;
uint64_t slice = p[offset] & 0x7f;
if (bit > 63)
return -1;
else
{
result |= (slice << bit);
bit += 7;
}
} while (p[offset++] & 0x80);
return result;
}
uint64_t readValidULEB128(DataBuffer& buffer, size_t& cursor)
{
uint64_t value = readLEB128(buffer, buffer.GetLength(), cursor);
if ((int64_t)value == -1)
throw ReadException();
return value;
}
uint64_t SharedCache::FastGetBackingCacheCount(BinaryNinja::Ref<BinaryNinja::BinaryView> dscView)
{
std::shared_ptr<MMappedFileAccessor> baseFile;
try {
baseFile = MMappedFileAccessor::Open(dscView, dscView->GetFile()->GetSessionId(), dscView->GetFile()->GetOriginalFilename())->lock();
}
catch (...){
LogError("Shared Cache preload: Failed to open file %s", dscView->GetFile()->GetOriginalFilename().c_str());
return 0;
}
dyld_cache_header header {};
size_t header_size = baseFile->ReadUInt32(16);
baseFile->Read(&header, 0, std::min(header_size, sizeof(dyld_cache_header)));
SharedCacheFormat cacheFormat;
if (header.imagesCountOld != 0)
cacheFormat = RegularCacheFormat;
size_t subCacheOff = offsetof(struct dyld_cache_header, subCacheArrayOffset);
size_t headerEnd = header.mappingOffset;
if (headerEnd > subCacheOff)
{
if (header.cacheType != 2)
{
if (std::filesystem::exists(ResolveFilePath(dscView, baseFile->Path() + ".01")))
cacheFormat = LargeCacheFormat;
else
cacheFormat = SplitCacheFormat;
}
else
cacheFormat = iOS16CacheFormat;
}
switch (cacheFormat)
{
case RegularCacheFormat:
{
return 1;
}
case LargeCacheFormat:
{
auto mainFileName = baseFile->Path();
auto subCacheCount = header.subCacheArrayCount;
return subCacheCount + 1;
}
case SplitCacheFormat:
{
auto mainFileName = baseFile->Path();
auto subCacheCount = header.subCacheArrayCount;
return subCacheCount + 2;
}
case iOS16CacheFormat:
{
auto mainFileName = baseFile->Path();
auto subCacheCount = header.subCacheArrayCount;
return subCacheCount + 2;
}
}
}
void SharedCache::PerformInitialLoad()
{
m_logger->LogInfo("Performing initial load of Shared Cache");
auto path = m_dscView->GetFile()->GetOriginalFilename();
auto baseFile = MMappedFileAccessor::Open(m_dscView, m_dscView->GetFile()->GetSessionId(), path)->lock();
m_viewSpecificState->progress = LoadProgressLoadingCaches;
WillMutateState();
MutableState().baseFilePath = path;
DataBuffer sig = baseFile->ReadBuffer(0, 4);
if (sig.GetLength() != 4)
abort();
const char* magic = (char*)sig.GetData();
if (strncmp(magic, "dyld", 4) != 0)
abort();
MutableState().cacheFormat = RegularCacheFormat;
dyld_cache_header primaryCacheHeader {};
size_t header_size = baseFile->ReadUInt32(16);
baseFile->Read(&primaryCacheHeader, 0, std::min(header_size, sizeof(dyld_cache_header)));
if (primaryCacheHeader.imagesCountOld != 0)
MutableState().cacheFormat = RegularCacheFormat;
size_t subCacheOff = offsetof(struct dyld_cache_header, subCacheArrayOffset);
size_t headerEnd = primaryCacheHeader.mappingOffset;
if (headerEnd > subCacheOff)
{
if (primaryCacheHeader.cacheType != 2)
{
if (std::filesystem::exists(ResolveFilePath(m_dscView, baseFile->Path() + ".01")))
MutableState().cacheFormat = LargeCacheFormat;
else
MutableState().cacheFormat = SplitCacheFormat;
}
else
MutableState().cacheFormat = iOS16CacheFormat;
}
switch (State().cacheFormat)
{
case RegularCacheFormat:
{
dyld_cache_mapping_info mapping {};
BackingCache cache;
cache.isPrimary = true;
cache.path = path;
for (size_t i = 0; i < primaryCacheHeader.mappingCount; i++)
{
baseFile->Read(&mapping, primaryCacheHeader.mappingOffset + (i * sizeof(mapping)), sizeof(mapping));
std::pair<uint64_t, std::pair<uint64_t, uint64_t>> mapRawToAddrAndSize;
mapRawToAddrAndSize.first = mapping.fileOffset;
mapRawToAddrAndSize.second.first = mapping.address;
mapRawToAddrAndSize.second.second = mapping.size;
cache.mappings.push_back(mapRawToAddrAndSize);
}
MutableState().backingCaches.push_back(std::move(cache));
dyld_cache_image_info img {};
for (size_t i = 0; i < primaryCacheHeader.imagesCountOld; i++)
{
baseFile->Read(&img, primaryCacheHeader.imagesOffsetOld + (i * sizeof(img)), sizeof(img));
auto iname = baseFile->ReadNullTermString(img.pathFileOffset);
MutableState().imageStarts[iname] = img.address;
}
m_logger->LogInfo("Found %d images in the shared cache", primaryCacheHeader.imagesCountOld);
if (primaryCacheHeader.branchPoolsCount)
{
std::vector<uint64_t> addresses;
for (size_t i = 0; i < primaryCacheHeader.branchPoolsCount; i++)
{
addresses.push_back(baseFile->ReadULong(primaryCacheHeader.branchPoolsOffset + (i * m_dscView->GetAddressSize())));
}
baseFile.reset(); // No longer needed, we're about to remap this file into VM space so we can load these.
uint64_t i = 0;
for (auto address : addresses)
{
i++;
auto vm = GetVMMap(true);
auto machoHeader = SharedCache::LoadHeaderForAddress(vm, address, "dyld_shared_cache_branch_islands_" + std::to_string(i));
if (machoHeader)
{
for (const auto& segment : machoHeader->segments)
{
MemoryRegion stubIslandRegion;
stubIslandRegion.start = segment.vmaddr;
stubIslandRegion.size = segment.filesize;
char segName[17];
memcpy(segName, segment.segname, 16);
segName[16] = 0;
std::string segNameStr = std::string(segName);
stubIslandRegion.prettyName = "dyld_shared_cache_branch_islands_" + std::to_string(i) + "::" + segNameStr;
stubIslandRegion.flags = (BNSegmentFlag)(BNSegmentFlag::SegmentReadable | BNSegmentFlag::SegmentExecutable);
MutableState().stubIslandRegions.push_back(std::move(stubIslandRegion));
}
}
}
}
m_logger->LogInfo("Found %d branch pools in the shared cache", primaryCacheHeader.branchPoolsCount);
break;
}
case LargeCacheFormat:
{
dyld_cache_mapping_info mapping {}; // We're going to reuse this for all of the mappings. We only need it
// briefly.
BackingCache cache;
cache.isPrimary = true;
cache.path = path;
for (size_t i = 0; i < primaryCacheHeader.mappingCount; i++)
{
baseFile->Read(&mapping, primaryCacheHeader.mappingOffset + (i * sizeof(mapping)), sizeof(mapping));
std::pair<uint64_t, std::pair<uint64_t, uint64_t>> mapRawToAddrAndSize;
mapRawToAddrAndSize.first = mapping.fileOffset;
mapRawToAddrAndSize.second.first = mapping.address;
mapRawToAddrAndSize.second.second = mapping.size;
cache.mappings.push_back(std::move(mapRawToAddrAndSize));
}
MutableState().backingCaches.push_back(std::move(cache));
dyld_cache_image_info img {};
for (size_t i = 0; i < primaryCacheHeader.imagesCount; i++)
{
baseFile->Read(&img, primaryCacheHeader.imagesOffset + (i * sizeof(img)), sizeof(img));
auto iname = baseFile->ReadNullTermString(img.pathFileOffset);
MutableState().imageStarts[iname] = img.address;
}
if (primaryCacheHeader.branchPoolsCount)
{
std::vector<uint64_t> pool {};
for (size_t i = 0; i < primaryCacheHeader.branchPoolsCount; i++)
{
MutableState().imageStarts["dyld_shared_cache_branch_islands_" + std::to_string(i)] =
baseFile->ReadULong(primaryCacheHeader.branchPoolsOffset + (i * m_dscView->GetAddressSize()));
}
}
std::string mainFileName = base_name(path);
if (auto projectFile = m_dscView->GetFile()->GetProjectFile())
mainFileName = projectFile->GetName();
auto subCacheCount = primaryCacheHeader.subCacheArrayCount;
dyld_subcache_entry2 _entry {};
std::vector<dyld_subcache_entry2> subCacheEntries;
for (size_t i = 0; i < subCacheCount; i++)
{
baseFile->Read(&_entry, primaryCacheHeader.subCacheArrayOffset + (i * sizeof(dyld_subcache_entry2)),
sizeof(dyld_subcache_entry2));
subCacheEntries.push_back(_entry);
}
baseFile.reset();
for (const auto& entry : subCacheEntries)
{
std::string subCachePath;
std::string subCacheFilename;
if (std::string(entry.fileExtension).find('.') != std::string::npos)
{
subCachePath = path + entry.fileExtension;
subCacheFilename = mainFileName + entry.fileExtension;
}
else
{
subCachePath = path + "." + entry.fileExtension;
subCacheFilename = mainFileName + "." + entry.fileExtension;
}
auto subCacheFile = MMappedFileAccessor::Open(m_dscView, m_dscView->GetFile()->GetSessionId(), subCachePath)->lock();
dyld_cache_header subCacheHeader {};
uint64_t headerSize = subCacheFile->ReadUInt32(16);
if (headerSize > sizeof(dyld_cache_header))
{
m_logger->LogDebug("Header size is larger than expected (0x%llx), using default size (0x%llx)", headerSize,
sizeof(dyld_cache_header));
headerSize = sizeof(dyld_cache_header);
}
subCacheFile->Read(&subCacheHeader, 0, headerSize);
dyld_cache_mapping_info subCacheMapping {};
BackingCache subCache;
subCache.isPrimary = false;
subCache.path = subCachePath;
for (size_t j = 0; j < subCacheHeader.mappingCount; j++)
{
subCacheFile->Read(&subCacheMapping, subCacheHeader.mappingOffset + (j * sizeof(subCacheMapping)),
sizeof(subCacheMapping));
std::pair<uint64_t, std::pair<uint64_t, uint64_t>> mapRawToAddrAndSize;
mapRawToAddrAndSize.first = subCacheMapping.fileOffset;
mapRawToAddrAndSize.second.first = subCacheMapping.address;
mapRawToAddrAndSize.second.second = subCacheMapping.size;
subCache.mappings.push_back(std::move(mapRawToAddrAndSize));
}
if (subCacheHeader.mappingCount == 1 && subCacheHeader.imagesCountOld == 0 && subCacheHeader.imagesCount == 0
&& subCacheHeader.imagesTextOffset == 0)
{
auto pathBasename = subCachePath.substr(subCachePath.find_last_of("/\\") + 1);
uint64_t address = subCacheMapping.address;
uint64_t size = subCacheMapping.size;
MemoryRegion stubIslandRegion;
stubIslandRegion.start = address;
stubIslandRegion.size = size;
stubIslandRegion.prettyName = subCacheFilename + "::_stubs";
stubIslandRegion.flags = (BNSegmentFlag)(BNSegmentFlag::SegmentReadable | BNSegmentFlag::SegmentExecutable);
MutableState().stubIslandRegions.push_back(std::move(stubIslandRegion));
}
MutableState().backingCaches.push_back(std::move(subCache));
}
break;
}
case SplitCacheFormat:
{
dyld_cache_mapping_info mapping {}; // We're going to reuse this for all of the mappings. We only need it
// briefly.
BackingCache cache;
cache.isPrimary = true;
cache.path = path;
for (size_t i = 0; i < primaryCacheHeader.mappingCount; i++)
{
baseFile->Read(&mapping, primaryCacheHeader.mappingOffset + (i * sizeof(mapping)), sizeof(mapping));
std::pair<uint64_t, std::pair<uint64_t, uint64_t>> mapRawToAddrAndSize;
mapRawToAddrAndSize.first = mapping.fileOffset;
mapRawToAddrAndSize.second.first = mapping.address;
mapRawToAddrAndSize.second.second = mapping.size;
cache.mappings.push_back(std::move(mapRawToAddrAndSize));
}
MutableState().backingCaches.push_back(std::move(cache));
dyld_cache_image_info img {};
for (size_t i = 0; i < primaryCacheHeader.imagesCount; i++)
{
baseFile->Read(&img, primaryCacheHeader.imagesOffset + (i * sizeof(img)), sizeof(img));
auto iname = baseFile->ReadNullTermString(img.pathFileOffset);
MutableState().imageStarts[iname] = img.address;
}
if (primaryCacheHeader.branchPoolsCount)
{
std::vector<uint64_t> pool {};
for (size_t i = 0; i < primaryCacheHeader.branchPoolsCount; i++)
{
MutableState().imageStarts["dyld_shared_cache_branch_islands_" + std::to_string(i)] =
baseFile->ReadULong(primaryCacheHeader.branchPoolsOffset + (i * m_dscView->GetAddressSize()));
}
}
std::string mainFileName = base_name(path);
if (auto projectFile = m_dscView->GetFile()->GetProjectFile())
mainFileName = projectFile->GetName();
auto subCacheCount = primaryCacheHeader.subCacheArrayCount;
baseFile.reset();
for (size_t i = 1; i <= subCacheCount; i++)
{
auto subCachePath = path + "." + std::to_string(i);
auto subCacheFilename = mainFileName + "." + std::to_string(i);
auto subCacheFile = MMappedFileAccessor::Open(m_dscView, m_dscView->GetFile()->GetSessionId(), subCachePath)->lock();
dyld_cache_header subCacheHeader {};
uint64_t headerSize = subCacheFile->ReadUInt32(16);
if (headerSize > sizeof(dyld_cache_header))
{
m_logger->LogDebug("Header size is larger than expected (0x%llx), using default size (0x%llx)", headerSize,
sizeof(dyld_cache_header));
headerSize = sizeof(dyld_cache_header);
}
subCacheFile->Read(&subCacheHeader, 0, headerSize);
BackingCache subCache;
subCache.isPrimary = false;
subCache.path = subCachePath;
dyld_cache_mapping_info subCacheMapping {};
for (size_t j = 0; j < subCacheHeader.mappingCount; j++)
{
subCacheFile->Read(&subCacheMapping, subCacheHeader.mappingOffset + (j * sizeof(subCacheMapping)),
sizeof(subCacheMapping));
std::pair<uint64_t, std::pair<uint64_t, uint64_t>> mapRawToAddrAndSize;
mapRawToAddrAndSize.first = subCacheMapping.fileOffset;
mapRawToAddrAndSize.second.first = subCacheMapping.address;
mapRawToAddrAndSize.second.second = subCacheMapping.size;
subCache.mappings.push_back(std::move(mapRawToAddrAndSize));
}
MutableState().backingCaches.push_back(std::move(subCache));
if (subCacheHeader.mappingCount == 1 && subCacheHeader.imagesCountOld == 0 && subCacheHeader.imagesCount == 0
&& subCacheHeader.imagesTextOffset == 0)
{
auto pathBasename = subCachePath.substr(subCachePath.find_last_of("/\\") + 1);
uint64_t address = subCacheMapping.address;
uint64_t size = subCacheMapping.size;
MemoryRegion stubIslandRegion;
stubIslandRegion.start = address;
stubIslandRegion.size = size;
stubIslandRegion.prettyName = subCacheFilename + "::_stubs";
stubIslandRegion.flags = (BNSegmentFlag)(BNSegmentFlag::SegmentReadable | BNSegmentFlag::SegmentExecutable);
MutableState().stubIslandRegions.push_back(std::move(stubIslandRegion));
}
}
// Load .symbols subcache
auto subCachePath = path + ".symbols";
auto subCacheFile = MMappedFileAccessor::Open(m_dscView, m_dscView->GetFile()->GetSessionId(), subCachePath)->lock();
dyld_cache_header subCacheHeader {};
uint64_t headerSize = subCacheFile->ReadUInt32(16);
if (headerSize > sizeof(dyld_cache_header))
{
m_logger->LogDebug("Header size is larger than expected (0x%llx), using default size (0x%llx)", headerSize,
sizeof(dyld_cache_header));
headerSize = sizeof(dyld_cache_header);
}
subCacheFile->Read(&subCacheHeader, 0, headerSize);
dyld_cache_mapping_info subCacheMapping {};
BackingCache subCache;
for (size_t j = 0; j < subCacheHeader.mappingCount; j++)
{
subCacheFile->Read(&subCacheMapping, subCacheHeader.mappingOffset + (j * sizeof(subCacheMapping)),
sizeof(subCacheMapping));
std::pair<uint64_t, std::pair<uint64_t, uint64_t>> mapRawToAddrAndSize;
mapRawToAddrAndSize.first = subCacheMapping.fileOffset;
mapRawToAddrAndSize.second.first = subCacheMapping.address;
mapRawToAddrAndSize.second.second = subCacheMapping.size;
subCache.mappings.push_back(std::move(mapRawToAddrAndSize));
}
MutableState().backingCaches.push_back(std::move(subCache));
break;
}
case iOS16CacheFormat:
{
dyld_cache_mapping_info mapping {};
BackingCache cache;
cache.isPrimary = true;
cache.path = path;
for (size_t i = 0; i < primaryCacheHeader.mappingCount; i++)
{
baseFile->Read(&mapping, primaryCacheHeader.mappingOffset + (i * sizeof(mapping)), sizeof(mapping));
std::pair<uint64_t, std::pair<uint64_t, uint64_t>> mapRawToAddrAndSize;
mapRawToAddrAndSize.first = mapping.fileOffset;
mapRawToAddrAndSize.second.first = mapping.address;
mapRawToAddrAndSize.second.second = mapping.size;
cache.mappings.push_back(std::move(mapRawToAddrAndSize));
}
MutableState().backingCaches.push_back(std::move(cache));
dyld_cache_image_info img {};
for (size_t i = 0; i < primaryCacheHeader.imagesCount; i++)
{
baseFile->Read(&img, primaryCacheHeader.imagesOffset + (i * sizeof(img)), sizeof(img));
auto iname = baseFile->ReadNullTermString(img.pathFileOffset);
MutableState().imageStarts[iname] = img.address;
}
if (primaryCacheHeader.branchPoolsCount)
{
std::vector<uint64_t> pool {};
for (size_t i = 0; i < primaryCacheHeader.branchPoolsCount; i++)
{
MutableState().imageStarts["dyld_shared_cache_branch_islands_" + std::to_string(i)] =
baseFile->ReadULong(primaryCacheHeader.branchPoolsOffset + (i * m_dscView->GetAddressSize()));
}
}
std::string mainFileName = base_name(path);
if (auto projectFile = m_dscView->GetFile()->GetProjectFile())
mainFileName = projectFile->GetName();
auto subCacheCount = primaryCacheHeader.subCacheArrayCount;
dyld_subcache_entry2 _entry {};
std::vector<dyld_subcache_entry2> subCacheEntries;
for (size_t i = 0; i < subCacheCount; i++)
{
baseFile->Read(&_entry, primaryCacheHeader.subCacheArrayOffset + (i * sizeof(dyld_subcache_entry2)),
sizeof(dyld_subcache_entry2));
subCacheEntries.push_back(_entry);
}
baseFile.reset();
for (const auto& entry : subCacheEntries)
{
std::string subCachePath;
std::string subCacheFilename;
if (std::string(entry.fileExtension).find('.') != std::string::npos)
{
subCachePath = path + entry.fileExtension;
subCacheFilename = mainFileName + entry.fileExtension;
}
else
{
subCachePath = path + "." + entry.fileExtension;
subCacheFilename = mainFileName + "." + entry.fileExtension;
}
auto subCacheFile = MMappedFileAccessor::Open(m_dscView, m_dscView->GetFile()->GetSessionId(), subCachePath)->lock();
dyld_cache_header subCacheHeader {};
uint64_t headerSize = subCacheFile->ReadUInt32(16);
if (headerSize > sizeof(dyld_cache_header))
{
m_logger->LogDebug("Header size is larger than expected (0x%llx), using default size (0x%llx)", headerSize,
sizeof(dyld_cache_header));
headerSize = sizeof(dyld_cache_header);
}
subCacheFile->Read(&subCacheHeader, 0, headerSize);
dyld_cache_mapping_info subCacheMapping {};
BackingCache subCache;
subCache.isPrimary = false;
subCache.path = subCachePath;
for (size_t j = 0; j < subCacheHeader.mappingCount; j++)
{
subCacheFile->Read(&subCacheMapping, subCacheHeader.mappingOffset + (j * sizeof(subCacheMapping)),
sizeof(subCacheMapping));
std::pair<uint64_t, std::pair<uint64_t, uint64_t>> mapRawToAddrAndSize;
mapRawToAddrAndSize.first = subCacheMapping.fileOffset;
mapRawToAddrAndSize.second.first = subCacheMapping.address;
mapRawToAddrAndSize.second.second = subCacheMapping.size;
subCache.mappings.push_back(std::move(mapRawToAddrAndSize));
if (subCachePath.find(".dylddata") != std::string::npos)
{
auto pathBasename = subCachePath.substr(subCachePath.find_last_of("/\\") + 1);
uint64_t address = subCacheMapping.address;
uint64_t size = subCacheMapping.size;
MemoryRegion dyldDataRegion;
dyldDataRegion.start = address;
dyldDataRegion.size = size;
dyldDataRegion.prettyName = subCacheFilename + "::_data" + std::to_string(j);
dyldDataRegion.flags = (BNSegmentFlag)(BNSegmentFlag::SegmentReadable);
MutableState().dyldDataRegions.push_back(std::move(dyldDataRegion));
}
}
MutableState().backingCaches.push_back(std::move(subCache));
if (subCacheHeader.mappingCount == 1 && subCacheHeader.imagesCountOld == 0 && subCacheHeader.imagesCount == 0
&& subCacheHeader.imagesTextOffset == 0)
{
auto pathBasename = subCachePath.substr(subCachePath.find_last_of("/\\") + 1);
uint64_t address = subCacheMapping.address;
uint64_t size = subCacheMapping.size;
MemoryRegion stubIslandRegion;
stubIslandRegion.start = address;
stubIslandRegion.size = size;
stubIslandRegion.prettyName = subCacheFilename + "::_stubs";
stubIslandRegion.flags = (BNSegmentFlag)(BNSegmentFlag::SegmentReadable | BNSegmentFlag::SegmentExecutable);
MutableState().stubIslandRegions.push_back(std::move(stubIslandRegion));
}
}
// Load .symbols subcache
try
{
auto subCachePath = path + ".symbols";
auto subCacheFile = MMappedFileAccessor::Open(m_dscView, m_dscView->GetFile()->GetSessionId(), subCachePath)->lock();
dyld_cache_header subCacheHeader {};
uint64_t headerSize = subCacheFile->ReadUInt32(16);
if (subCacheFile->ReadUInt32(16) > sizeof(dyld_cache_header))
{
m_logger->LogDebug("Header size is larger than expected, using default size");
headerSize = sizeof(dyld_cache_header);
}
subCacheFile->Read(&subCacheHeader, 0, headerSize);
BackingCache subCache;
subCache.isPrimary = false;
subCache.path = subCachePath;
dyld_cache_mapping_info subCacheMapping {};
for (size_t j = 0; j < subCacheHeader.mappingCount; j++)
{
subCacheFile->Read(&subCacheMapping, subCacheHeader.mappingOffset + (j * sizeof(subCacheMapping)),
sizeof(subCacheMapping));
std::pair<uint64_t, std::pair<uint64_t, uint64_t>> mapRawToAddrAndSize;
mapRawToAddrAndSize.first = subCacheMapping.fileOffset;
mapRawToAddrAndSize.second.first = subCacheMapping.address;
mapRawToAddrAndSize.second.second = subCacheMapping.size;
subCache.mappings.push_back(std::move(mapRawToAddrAndSize));
}
MutableState().backingCaches.push_back(std::move(subCache));
}
catch (...)
{}
break;
}
}
baseFile.reset();
m_viewSpecificState->progress = LoadProgressLoadingImages;
// We have set up enough metadata to map VM now.
auto vm = GetVMMap(true);
if (!vm)
{
m_logger->LogError("Failed to map VM pages for Shared Cache on initial load, this is fatal.");
return;
}
for (const auto& start : State().imageStarts)
{
try {
auto imageHeader = SharedCache::LoadHeaderForAddress(vm, start.second, start.first);
if (imageHeader)
{
if (imageHeader->linkeditPresent && vm->AddressIsMapped(imageHeader->linkeditSegment.vmaddr))
{
auto mapping = vm->MappingAtAddress(imageHeader->linkeditSegment.vmaddr);
imageHeader->exportTriePath = mapping.first.filePath;
}
MutableState().headers[start.second] = imageHeader.value();
CacheImage image;
image.installName = start.first;
image.headerLocation = start.second;
for (const auto& segment : imageHeader->segments)
{
char segName[17];
memcpy(segName, segment.segname, 16);
segName[16] = 0;
MemoryRegion sectionRegion;
sectionRegion.prettyName = imageHeader.value().identifierPrefix + "::" + std::string(segName);
sectionRegion.start = segment.vmaddr;
sectionRegion.size = segment.vmsize;
uint32_t flags = 0;
if (segment.initprot & MACHO_VM_PROT_READ)
flags |= SegmentReadable;
if (segment.initprot & MACHO_VM_PROT_WRITE)
flags |= SegmentWritable;
if (segment.initprot & MACHO_VM_PROT_EXECUTE)
flags |= SegmentExecutable;
if (((segment.initprot & MACHO_VM_PROT_WRITE) == 0) &&
((segment.maxprot & MACHO_VM_PROT_WRITE) == 0))
flags |= SegmentDenyWrite;
if (((segment.initprot & MACHO_VM_PROT_EXECUTE) == 0) &&
((segment.maxprot & MACHO_VM_PROT_EXECUTE) == 0))
flags |= SegmentDenyExecute;
// if we're positive we have an entry point for some reason, force the segment
// executable. this helps with kernel images.
for (auto &entryPoint : imageHeader->m_entryPoints)
if (segment.vmaddr <= entryPoint && (entryPoint < (segment.vmaddr + segment.filesize)))
flags |= SegmentExecutable;
sectionRegion.flags = (BNSegmentFlag)flags;
image.regions.push_back(sectionRegion);
}
MutableState().images.push_back(image);
}
else
{
m_logger->LogError("Failed to load Mach-O header for %s", start.first.c_str());
}
}
catch (std::exception& ex)
{
m_logger->LogError("Failed to load Mach-O header for %s: %s", start.first.c_str(), ex.what());
}
}
m_logger->LogInfo("Loaded %d Mach-O headers", State().headers.size());
for (const auto& cache : State().backingCaches)
{
size_t i = 0;
for (const auto& mapping : cache.mappings)
{
MemoryRegion region;
region.start = mapping.second.first;
region.size = mapping.second.second;
region.prettyName = base_name(cache.path) + "::" + std::to_string(i);
// FIXME flags!!! BackingCache.mapping needs refactored to store this information!
region.flags = (BNSegmentFlag)(BNSegmentFlag::SegmentReadable | BNSegmentFlag::SegmentExecutable);
MutableState().nonImageRegions.push_back(std::move(region));
i++;
}
}
// Iterate through each Mach-O header
if (!State().dyldDataRegions.empty())
{
for (const auto& [headerKey, header] : State().headers)
{
// Iterate through each segment of the header
for (const auto& segment : header.segments)
{
uint64_t segmentStart = segment.vmaddr;
uint64_t segmentEnd = segmentStart + segment.vmsize;
// Iterate through each region in m_dyldDataRegions
for (auto it = State().dyldDataRegions.begin(); it != State().dyldDataRegions.end();)
{
uint64_t regionStart = it->start;
uint64_t regionSize = it->size;
uint64_t regionEnd = regionStart + regionSize;
// Check if the region overlaps with the segment
if (segmentStart < regionEnd && segmentEnd > regionStart)
{
// Split the region into two, removing the overlapped portion
std::vector<MemoryRegion> newRegions;
// Part before the overlap
if (regionStart < segmentStart)
{
MemoryRegion newRegion(*it);
newRegion.start = regionStart;
newRegion.size = segmentStart - regionStart;
newRegions.push_back(std::move(newRegion));
}
// Part after the overlap
if (regionEnd > segmentEnd)
{
MemoryRegion newRegion(*it);
newRegion.start = segmentEnd;
newRegion.size = regionEnd - segmentEnd;
newRegions.push_back(std::move(newRegion));
}
// Erase the original region
it = MutableState().dyldDataRegions.erase(it);
// Insert the new regions (if any)
for (const auto& newRegion : newRegions)
{
it = MutableState().dyldDataRegions.insert(it, newRegion);
++it; // Move iterator to the next position
}
}
else
{
++it; // No overlap, move to the next region
}
}
}
}
}
// Iterate through each Mach-O header
if (!State().nonImageRegions.empty())
{
for (const auto& [headerKey, header] : State().headers)
{
// Iterate through each segment of the header
for (const auto& segment : header.segments)
{
uint64_t segmentStart = segment.vmaddr;
uint64_t segmentEnd = segmentStart + segment.vmsize;
// Iterate through each region in m_dyldDataRegions
for (auto it = State().nonImageRegions.begin(); it != State().nonImageRegions.end();)
{
uint64_t regionStart = it->start;
uint64_t regionSize = it->size;
uint64_t regionEnd = regionStart + regionSize;
// Check if the region overlaps with the segment
if (segmentStart < regionEnd && segmentEnd > regionStart)
{
// Split the region into two, removing the overlapped portion
std::vector<MemoryRegion> newRegions;
// Part before the overlap
if (regionStart < segmentStart)
{
MemoryRegion newRegion(*it);
newRegion.start = regionStart;
newRegion.size = segmentStart - regionStart;
newRegions.push_back(std::move(newRegion));
}
// Part after the overlap
if (regionEnd > segmentEnd)
{
MemoryRegion newRegion(*it);
newRegion.start = segmentEnd;
newRegion.size = regionEnd - segmentEnd;
newRegions.push_back(std::move(newRegion));
}
// Erase the original region
it = MutableState().nonImageRegions.erase(it);
// Insert the new regions (if any)
for (const auto& newRegion : newRegions)
{
it = MutableState().nonImageRegions.insert(it, newRegion);
++it; // Move iterator to the next position
}
}
else
{
++it; // No overlap, move to the next region
}
}
}
}
}
SaveToDSCView();
m_logger->LogDebug("Finished initial load of Shared Cache");
m_viewSpecificState->progress = LoadProgressFinished;
}
std::shared_ptr<VM> SharedCache::GetVMMap(bool mapPages)
{
std::shared_ptr<VM> vm = std::make_shared<VM>(0x1000);
if (mapPages)
{
for (const auto& cache : State().backingCaches)
{
for (const auto& mapping : cache.mappings)
{
vm->MapPages(m_dscView, m_dscView->GetFile()->GetSessionId(), mapping.second.first, mapping.first, mapping.second.second, cache.path,
[this, vm=vm](std::shared_ptr<MMappedFileAccessor> mmap){
ParseAndApplySlideInfoForFile(mmap);
});
}
}
}
return vm;
}
void SharedCache::DeserializeFromRawView()
{
if (m_dscView->QueryMetadata(SharedCacheMetadataTag))
{
std::lock_guard lock(m_viewSpecificState->stateMutex);
if (m_viewSpecificState->cachedState)
{
m_state = m_viewSpecificState->cachedState;
m_stateIsShared = true;
m_metadataValid = true;
}
else
{
LoadFromString(m_dscView->GetStringMetadata(SharedCacheMetadataTag));
}
if (!m_metadataValid)
{
m_logger->LogError("Failed to deserialize Shared Cache metadata");
WillMutateState();
MutableState().viewState = DSCViewStateUnloaded;
}
}
else
{
m_metadataValid = true;
WillMutateState();
MutableState().viewState = DSCViewStateUnloaded;
MutableState().images.clear(); // fixme ??
}
}
std::string to_hex_string(uint64_t value)
{
std::stringstream ss;
ss << std::hex << value;
return ss.str();
}
void SharedCache::ParseAndApplySlideInfoForFile(std::shared_ptr<MMappedFileAccessor> file)
{
if (file->SlideInfoWasApplied())
return;
WillMutateState();
std::vector<std::pair<uint64_t, uint64_t>> rewrites;
dyld_cache_header baseHeader;
file->Read(&baseHeader, 0, sizeof(dyld_cache_header));
uint64_t base = UINT64_MAX;
for (const auto& backingCache : State().backingCaches)
{
for (const auto& mapping : backingCache.mappings)
{
if (mapping.second.first < base)
{
base = mapping.second.first;
break;
}
}
}
std::vector<std::pair<uint64_t, MappingInfo>> mappings;
if (baseHeader.slideInfoOffsetUnused)
{
// Legacy
auto slideInfoOff = baseHeader.slideInfoOffsetUnused;
auto slideInfoVersion = file->ReadUInt32(slideInfoOff);
if (slideInfoVersion != 2 && slideInfoVersion != 3)
{
abort();
}
MappingInfo map;
file->Read(&map.mappingInfo, baseHeader.mappingOffset + sizeof(dyld_cache_mapping_info), sizeof(dyld_cache_mapping_info));
map.file = file;
map.slideInfoVersion = slideInfoVersion;
if (map.slideInfoVersion == 2)
file->Read(&map.slideInfoV2, slideInfoOff, sizeof(dyld_cache_slide_info_v2));
else if (map.slideInfoVersion == 3)
file->Read(&map.slideInfoV3, slideInfoOff, sizeof(dyld_cache_slide_info_v3));
mappings.emplace_back(slideInfoOff, map);
}
else
{
dyld_cache_header targetHeader;
file->Read(&targetHeader, 0, sizeof(dyld_cache_header));
if (targetHeader.mappingWithSlideCount == 0)
{
m_logger->LogDebug("No mappings with slide info found");
}
for (auto i = 0; i < targetHeader.mappingWithSlideCount; i++)
{
dyld_cache_mapping_and_slide_info mappingAndSlideInfo;
file->Read(&mappingAndSlideInfo, targetHeader.mappingWithSlideOffset + (i * sizeof(dyld_cache_mapping_and_slide_info)), sizeof(dyld_cache_mapping_and_slide_info));
if (mappingAndSlideInfo.slideInfoFileOffset)
{
MappingInfo map;
map.file = file;
if (mappingAndSlideInfo.size == 0)
continue;
map.slideInfoVersion = file->ReadUInt32(mappingAndSlideInfo.slideInfoFileOffset);
m_logger->LogDebug("Slide Info Version: %d", map.slideInfoVersion);
map.mappingInfo.address = mappingAndSlideInfo.address;
map.mappingInfo.size = mappingAndSlideInfo.size;
map.mappingInfo.fileOffset = mappingAndSlideInfo.fileOffset;
if (map.slideInfoVersion == 2)
{
file->Read(
&map.slideInfoV2, mappingAndSlideInfo.slideInfoFileOffset, sizeof(dyld_cache_slide_info_v2));
}
else if (map.slideInfoVersion == 3)
{
file->Read(
&map.slideInfoV3, mappingAndSlideInfo.slideInfoFileOffset, sizeof(dyld_cache_slide_info_v3));
map.slideInfoV3.auth_value_add = base;
}
else if (map.slideInfoVersion == 5)
{
file->Read(
&map.slideInfoV5, mappingAndSlideInfo.slideInfoFileOffset, sizeof(dyld_cache_slide_info5));
map.slideInfoV5.value_add = base;
}
else
{
m_logger->LogError("Unknown slide info version: %d", map.slideInfoVersion);
continue;
}
uint64_t slideInfoOffset = mappingAndSlideInfo.slideInfoFileOffset;
mappings.emplace_back(slideInfoOffset, map);
m_logger->LogDebug("Filename: %s", file->Path().c_str());
m_logger->LogDebug("Slide Info Offset: 0x%llx", slideInfoOffset);
m_logger->LogDebug("Mapping Address: 0x%llx", map.mappingInfo.address);
m_logger->LogDebug("Slide Info v", map.slideInfoVersion);
}
}
}
if (mappings.empty())
{
m_logger->LogDebug("No slide info found");
file->SetSlideInfoWasApplied(true);
return;
}
for (const auto& [off, mapping] : mappings)
{
m_logger->LogDebug("Slide Info Version: %d", mapping.slideInfoVersion);
uint64_t extrasOffset = off;
uint64_t pageStartsOffset = off;
uint64_t pageStartCount;
uint64_t pageSize;
if (mapping.slideInfoVersion == 2)
{
pageStartsOffset += mapping.slideInfoV2.page_starts_offset;
pageStartCount = mapping.slideInfoV2.page_starts_count;
pageSize = mapping.slideInfoV2.page_size;
extrasOffset += mapping.slideInfoV2.page_extras_offset;
auto cursor = pageStartsOffset;
for (size_t i = 0; i < pageStartCount; i++)
{
try
{
uint16_t start = mapping.file->ReadUShort(cursor);
cursor += sizeof(uint16_t);
if (start == DYLD_CACHE_SLIDE_PAGE_ATTR_NO_REBASE)
continue;
auto rebaseChain = [&](const dyld_cache_slide_info_v2& slideInfo, uint64_t pageContent, uint16_t startOffset)
{
uintptr_t slideAmount = 0;
auto deltaMask = slideInfo.delta_mask;
auto valueMask = ~deltaMask;
auto valueAdd = slideInfo.value_add;
auto deltaShift = count_trailing_zeros(deltaMask) - 2;
uint32_t pageOffset = startOffset;
uint32_t delta = 1;
while ( delta != 0 )
{
uint64_t loc = pageContent + pageOffset;
try
{
uintptr_t rawValue = file->ReadULong(loc);
delta = (uint32_t)((rawValue & deltaMask) >> deltaShift);
uintptr_t value = (rawValue & valueMask);
if (value != 0)
{
value += valueAdd;
value += slideAmount;
}
pageOffset += delta;
rewrites.emplace_back(loc, value);
}
catch (MappingReadException& ex)
{
m_logger->LogError("Failed to read v2 slide pointer at 0x%llx\n", loc);
break;
}
}
};
if (start & DYLD_CACHE_SLIDE_PAGE_ATTR_EXTRA)
{
int j=(start & 0x3FFF);
bool done = false;
do
{
uint64_t extraCursor = extrasOffset + (j * sizeof(uint16_t));
try
{
auto extra = mapping.file->ReadUShort(extraCursor);
uint16_t aStart = extra;
uint64_t page = mapping.mappingInfo.fileOffset + (pageSize * i);
uint16_t pageStartOffset = (aStart & 0x3FFF)*4;
rebaseChain(mapping.slideInfoV2, page, pageStartOffset);
done = (extra & DYLD_CACHE_SLIDE_PAGE_ATTR_END);
++j;
}
catch (MappingReadException& ex)
{
m_logger->LogError("Failed to read v2 slide extra at 0x%llx\n", cursor);
break;
}
} while (!done);
}
else
{
uint64_t page = mapping.mappingInfo.fileOffset + (pageSize * i);
uint16_t pageStartOffset = start*4;
rebaseChain(mapping.slideInfoV2, page, pageStartOffset);
}
}
catch (MappingReadException& ex)
{
m_logger->LogError("Failed to read v2 slide info at 0x%llx\n", cursor);
}
}
}
else if (mapping.slideInfoVersion == 3) {
// Slide Info Version 3 Logic
pageStartsOffset += sizeof(dyld_cache_slide_info_v3);
pageStartCount = mapping.slideInfoV3.page_starts_count;
pageSize = mapping.slideInfoV3.page_size;
auto cursor = pageStartsOffset;
for (size_t i = 0; i < pageStartCount; i++)
{
try
{
uint16_t delta = mapping.file->ReadUShort(cursor);
cursor += sizeof(uint16_t);
if (delta == DYLD_CACHE_SLIDE_V3_PAGE_ATTR_NO_REBASE)
continue;
delta = delta/sizeof(uint64_t); // initial offset is byte based
uint64_t loc = mapping.mappingInfo.fileOffset + (pageSize * i);
do
{
loc += delta * sizeof(dyld_cache_slide_pointer3);
try
{
dyld_cache_slide_pointer3 slideInfo;
file->Read(&slideInfo, loc, sizeof(slideInfo));
delta = slideInfo.plain.offsetToNextPointer;
if (slideInfo.auth.authenticated)
{
uint64_t value = slideInfo.auth.offsetFromSharedCacheBase;
value += mapping.slideInfoV3.auth_value_add;
rewrites.emplace_back(loc, value);
}
else
{
uint64_t value51 = slideInfo.plain.pointerValue;
uint64_t top8Bits = value51 & 0x0007F80000000000;
uint64_t bottom43Bits = value51 & 0x000007FFFFFFFFFF;
uint64_t value = (uint64_t)top8Bits << 13 | bottom43Bits;
rewrites.emplace_back(loc, value);
}
}
catch (MappingReadException& ex)
{
m_logger->LogError("Failed to read v3 slide pointer at 0x%llx\n", loc);
break;
}
} while (delta != 0);
}
catch (MappingReadException& ex)
{
m_logger->LogError("Failed to read v3 slide info at 0x%llx\n", cursor);
}
}
}
else if (mapping.slideInfoVersion == 5)
{
pageStartsOffset += sizeof(dyld_cache_slide_info5);
pageStartCount = mapping.slideInfoV5.page_starts_count;
pageSize = mapping.slideInfoV5.page_size;
auto cursor = pageStartsOffset;
for (size_t i = 0; i < pageStartCount; i++)
{
try
{
uint16_t delta = mapping.file->ReadUShort(cursor);
cursor += sizeof(uint16_t);
if (delta == DYLD_CACHE_SLIDE_V5_PAGE_ATTR_NO_REBASE)
continue;
delta = delta/sizeof(uint64_t); // initial offset is byte based
uint64_t loc = mapping.mappingInfo.fileOffset + (pageSize * i);
do
{
loc += delta * sizeof(dyld_cache_slide_pointer5);
try
{
dyld_cache_slide_pointer5 slideInfo;
file->Read(&slideInfo, loc, sizeof(slideInfo));
delta = slideInfo.regular.next;
if (slideInfo.auth.auth)
{
uint64_t value = mapping.slideInfoV5.value_add + slideInfo.auth.runtimeOffset;
rewrites.emplace_back(loc, value);
}
else
{
uint64_t value = mapping.slideInfoV5.value_add + slideInfo.regular.runtimeOffset;
rewrites.emplace_back(loc, value);
}
}
catch (MappingReadException& ex)
{
m_logger->LogError("Failed to read v5 slide pointer at 0x%llx\n", loc);
break;
}
} while (delta != 0);
}
catch (MappingReadException& ex)
{
m_logger->LogError("Failed to read v5 slide info at 0x%llx\n", cursor);
}
}
}
}
for (const auto& [loc, value] : rewrites)
{
file->WritePointer(loc, value);
#ifdef SLIDEINFO_DEBUG_TAGS
uint64_t vmAddr = 0;
{
for (uint64_t off = baseHeader.mappingOffset; off < baseHeader.mappingOffset + baseHeader.mappingCount * sizeof(dyld_cache_mapping_info); off += sizeof(dyld_cache_mapping_info))
{
dyld_cache_mapping_info mapping;
file->Read(&mapping, off, sizeof(dyld_cache_mapping_info));
if (mapping.fileOffset <= loc && loc < mapping.fileOffset + mapping.size)
{
vmAddr = mapping.address + (loc - mapping.fileOffset);
break;
}
}
}
Ref<TagType> type = m_dscView->GetTagType("slideinfo");
if (!type)
{
m_dscView->AddTagType(new TagType(m_dscView, "slideinfo", "\xF0\x9F\x9A\x9E"));
type = m_dscView->GetTagType("slideinfo");
}
m_dscView->AddAutoDataTag(vmAddr, new Tag(type, "0x" + to_hex_string(file->ReadULong(loc)) + " => 0x" + to_hex_string(value)));
#endif
}
m_logger->LogDebug("Applied slide info for %s (0x%llx rewrites)", file->Path().c_str(), rewrites.size());
file->SetSlideInfoWasApplied(true);
}
SharedCache::SharedCache(BinaryNinja::Ref<BinaryNinja::BinaryView> dscView) : m_dscView(dscView), m_viewSpecificState(ViewSpecificStateForView(dscView))
{
if (dscView->GetTypeName() != VIEW_NAME)
{
// Unreachable?
m_logger->LogError("Attempted to create SharedCache object from non-Shared Cache view");
return;
}
sharedCacheReferences++;
INIT_SHAREDCACHE_API_OBJECT()
m_logger = LogRegistry::GetLogger("SharedCache", dscView->GetFile()->GetSessionId());
DeserializeFromRawView();
if (!m_metadataValid)
return;
if (State().viewState != DSCViewStateUnloaded) {
m_viewSpecificState->progress = LoadProgressFinished;
return;
}
std::unique_lock lock(m_viewSpecificState->viewOperationsThatInfluenceMetadataMutex);
try {
PerformInitialLoad();
}
catch (...)
{
m_logger->LogError("Failed to perform initial load of Shared Cache");
}
auto settings = m_dscView->GetLoadSettings(VIEW_NAME);
bool autoLoadLibsystem = true;
if (settings && settings->Contains("loader.dsc.autoLoadLibSystem"))
{
autoLoadLibsystem = settings->Get<bool>("loader.dsc.autoLoadLibSystem", m_dscView);
}
if (autoLoadLibsystem)
{
for (const auto& [_, header] : State().headers)
{
if (header.installName.find("libsystem_c.dylib") != std::string::npos)
{
lock.unlock();
m_logger->LogInfo("Loading core libsystem_c.dylib library");
LoadImageWithInstallName(header.installName, false);
break;
}
}
}
MutableState().viewState = DSCViewStateLoaded;
SaveToDSCView();
}
SharedCache::~SharedCache() {
sharedCacheReferences--;
}
SharedCache* SharedCache::GetFromDSCView(BinaryNinja::Ref<BinaryNinja::BinaryView> dscView)
{
if (dscView->GetTypeName() != VIEW_NAME)
return nullptr;
try {
return new SharedCache(dscView);
}
catch (...)
{
return nullptr;
}
}
std::optional<uint64_t> SharedCache::GetImageStart(std::string installName)
{
for (const auto& [name, start] : State().imageStarts)
{
if (name == installName)
{
return start;
}
}
return {};
}
std::optional<SharedCacheMachOHeader> SharedCache::HeaderForAddress(uint64_t address)
{
// We _could_ mark each page with the image start? :grimacing emoji:
// But that'd require mapping pages :grimacing emoji: :grimacing emoji:
// There's not really any other hacks that could make this faster, that I can think of...
for (const auto& [start, header] : State().headers)
{
for (const auto& segment : header.segments)
{
if (segment.vmaddr <= address && segment.vmaddr + segment.vmsize > address)
{
return header;
}
}
}
return {};
}
std::string SharedCache::NameForAddress(uint64_t address)
{
for (const auto& stubIsland : State().stubIslandRegions)
{
if (stubIsland.start <= address && stubIsland.start + stubIsland.size > address)
{
return stubIsland.prettyName;
}
}
for (const auto& dyldData : State().dyldDataRegions)
{
if (dyldData.start <= address && dyldData.start + dyldData.size > address)
{
return dyldData.prettyName;
}
}
for (const auto& nonImageRegion : State().nonImageRegions)
{
if (nonImageRegion.start <= address && nonImageRegion.start + nonImageRegion.size > address)
{
return nonImageRegion.prettyName;
}
}
if (auto header = HeaderForAddress(address))
{
for (const auto& section : header->sections)
{
if (section.addr <= address && section.addr + section.size > address)
{
char sectionName[17];
strncpy(sectionName, section.sectname, 16);
sectionName[16] = '\0';
return header->identifierPrefix + "::" + sectionName;
}
}
}
return "";
}
std::string SharedCache::ImageNameForAddress(uint64_t address)
{
if (auto header = HeaderForAddress(address))
{
return header->identifierPrefix;
}
return "";
}
bool SharedCache::LoadImageContainingAddress(uint64_t address, bool skipObjC)
{
for (const auto& [start, header] : State().headers)
{
for (const auto& segment : header.segments)
{
if (segment.vmaddr <= address && segment.vmaddr + segment.vmsize > address)
{
return LoadImageWithInstallName(header.installName, skipObjC);
}
}
}
return false;
}
bool SharedCache::LoadSectionAtAddress(uint64_t address)
{
std::unique_lock lock(m_viewSpecificState->viewOperationsThatInfluenceMetadataMutex);
DeserializeFromRawView();
WillMutateState();
auto vm = GetVMMap();
if (!vm)
{
m_logger->LogError("Failed to map VM pages for Shared Cache.");
return false;
}
SharedCacheMachOHeader targetHeader;
CacheImage* targetImage = nullptr;
MemoryRegion* targetSegment = nullptr;
for (auto& image : MutableState().images)
{
for (auto& region : image.regions)
{
if (region.start <= address && region.start + region.size > address)
{
targetHeader = MutableState().headers[image.headerLocation];
targetImage = ℑ
targetSegment = ®ion;
break;
}
}
if (targetSegment)
break;
}
if (!targetSegment)
{
for (auto& stubIsland : MutableState().stubIslandRegions)
{
if (stubIsland.start <= address && stubIsland.start + stubIsland.size > address)
{
if (stubIsland.loaded)
{
return true;
}
m_logger->LogInfo("Loading stub island %s @ 0x%llx", stubIsland.prettyName.c_str(), stubIsland.start);
auto targetFile = vm->MappingAtAddress(stubIsland.start).first.fileAccessor->lock();
ParseAndApplySlideInfoForFile(targetFile);
auto reader = VMReader(vm);
auto buff = reader.ReadBuffer(stubIsland.start, stubIsland.size);
auto rawViewEnd = m_dscView->GetParentView()->GetEnd();
auto name = stubIsland.prettyName;
m_dscView->GetParentView()->GetParentView()->WriteBuffer(
m_dscView->GetParentView()->GetParentView()->GetEnd(), buff);
m_dscView->GetParentView()->AddAutoSegment(rawViewEnd, stubIsland.size, rawViewEnd, stubIsland.size,
SegmentReadable | SegmentExecutable);
m_dscView->AddUserSegment(stubIsland.start, stubIsland.size, rawViewEnd, stubIsland.size,
SegmentReadable | SegmentExecutable);
m_dscView->AddUserSection(name, stubIsland.start, stubIsland.size, ReadOnlyCodeSectionSemantics);
m_dscView->WriteBuffer(stubIsland.start, buff);
stubIsland.loaded = true;
stubIsland.rawViewOffsetIfLoaded = rawViewEnd;
MutableState().regionsMappedIntoMemory.push_back(stubIsland);
SaveToDSCView();
m_dscView->AddAnalysisOption("linearsweep");
m_dscView->UpdateAnalysis();
return true;
}
}
for (auto& dyldData : MutableState().dyldDataRegions)
{
if (dyldData.start <= address && dyldData.start + dyldData.size > address)
{
if (dyldData.loaded)
{
return true;
}
m_logger->LogInfo("Loading dyld data %s", dyldData.prettyName.c_str());
auto targetFile = vm->MappingAtAddress(dyldData.start).first.fileAccessor->lock();
ParseAndApplySlideInfoForFile(targetFile);
auto reader = VMReader(vm);
auto buff = reader.ReadBuffer(dyldData.start, dyldData.size);
auto rawViewEnd = m_dscView->GetParentView()->GetEnd();
auto name = dyldData.prettyName;
m_dscView->GetParentView()->GetParentView()->WriteBuffer(
m_dscView->GetParentView()->GetParentView()->GetEnd(), buff);
m_dscView->GetParentView()->WriteBuffer(rawViewEnd, buff);
m_dscView->GetParentView()->AddAutoSegment(rawViewEnd, dyldData.size, rawViewEnd, dyldData.size,
SegmentReadable);
m_dscView->AddUserSegment(dyldData.start, dyldData.size, rawViewEnd, dyldData.size, SegmentReadable);
m_dscView->AddUserSection(name, dyldData.start, dyldData.size, ReadOnlyDataSectionSemantics);
m_dscView->WriteBuffer(dyldData.start, buff);
dyldData.loaded = true;
dyldData.rawViewOffsetIfLoaded = rawViewEnd;
MutableState().regionsMappedIntoMemory.push_back(dyldData);
SaveToDSCView();
m_dscView->AddAnalysisOption("linearsweep");
m_dscView->UpdateAnalysis();
return true;
}
}
for (auto& region : MutableState().nonImageRegions)
{
if (region.start <= address && region.start + region.size > address)
{
if (region.loaded)
{
return true;
}
m_logger->LogInfo("Loading non-image region %s", region.prettyName.c_str());
auto targetFile = vm->MappingAtAddress(region.start).first.fileAccessor->lock();
ParseAndApplySlideInfoForFile(targetFile);
auto reader = VMReader(vm);
auto buff = reader.ReadBuffer(region.start, region.size);
auto rawViewEnd = m_dscView->GetParentView()->GetEnd();
auto name = region.prettyName;
m_dscView->GetParentView()->GetParentView()->WriteBuffer(
m_dscView->GetParentView()->GetParentView()->GetEnd(), buff);
m_dscView->GetParentView()->WriteBuffer(rawViewEnd, buff);
m_dscView->GetParentView()->AddAutoSegment(rawViewEnd, region.size, rawViewEnd, region.size, region.flags);
m_dscView->AddUserSegment(region.start, region.size, rawViewEnd, region.size, region.flags);
m_dscView->AddUserSection(name, region.start, region.size, ReadOnlyCodeSectionSemantics);
m_dscView->WriteBuffer(region.start, buff);
region.loaded = true;
region.rawViewOffsetIfLoaded = rawViewEnd;
MutableState().regionsMappedIntoMemory.push_back(region);
SaveToDSCView();
m_dscView->AddAnalysisOption("linearsweep");
m_dscView->UpdateAnalysis();
return true;
}
}
m_logger->LogError("Failed to find a segment containing address 0x%llx", address);
return false;
}
auto id = m_dscView->BeginUndoActions();
auto rawViewEnd = m_dscView->GetParentView()->GetEnd();
auto reader = VMReader(vm);
m_logger->LogDebug("Partial loading image %s", targetHeader.installName.c_str());
auto targetFile = vm->MappingAtAddress(targetSegment->start).first.fileAccessor->lock();
ParseAndApplySlideInfoForFile(targetFile);
auto buff = reader.ReadBuffer(targetSegment->start, targetSegment->size);
m_dscView->GetParentView()->GetParentView()->WriteBuffer(
m_dscView->GetParentView()->GetParentView()->GetEnd(), buff);
m_dscView->GetParentView()->WriteBuffer(rawViewEnd, buff);
m_dscView->GetParentView()->AddAutoSegment(
rawViewEnd, targetSegment->size, rawViewEnd, targetSegment->size, SegmentReadable);
m_dscView->AddUserSegment(
targetSegment->start, targetSegment->size, rawViewEnd, targetSegment->size, targetSegment->flags);
m_dscView->WriteBuffer(targetSegment->start, buff);
targetSegment->loaded = true;
targetSegment->rawViewOffsetIfLoaded = rawViewEnd;
MutableState().regionsMappedIntoMemory.push_back(*targetSegment);
SaveToDSCView();
if (!targetSegment->headerInitialized)
{
SharedCache::InitializeHeader(m_dscView, vm.get(), targetHeader, {targetSegment});
}
m_dscView->AddAnalysisOption("linearsweep");
m_dscView->UpdateAnalysis();
m_dscView->CommitUndoActions(id);
return true;
}
static void GetObjCSettings(Ref<BinaryView> view, bool* processObjCMetadata, bool* processCFStrings)
{
auto settings = view->GetLoadSettings(VIEW_NAME);
*processCFStrings = true;
*processObjCMetadata = true;
if (settings && settings->Contains("loader.dsc.processCFStrings"))
*processCFStrings = settings->Get<bool>("loader.dsc.processCFStrings", view);
if (settings && settings->Contains("loader.dsc.processObjC"))
*processObjCMetadata = settings->Get<bool>("loader.dsc.processObjC", view);
}
static void ProcessObjCSectionsForImageWithName(std::string baseName, std::shared_ptr<VM> vm, std::shared_ptr<DSCObjC::DSCObjCProcessor> objc, bool processCFStrings, bool processObjCMetadata, Ref<Logger> logger)
{
try
{
if (processObjCMetadata)
objc->ProcessObjCData(vm, baseName);
if (processCFStrings)
objc->ProcessCFStrings(vm, baseName);
}
catch (const std::exception& ex)
{
logger->LogWarn("Error processing ObjC data for image %s: %s", baseName.c_str(), ex.what());
}
catch (...)
{
logger->LogWarn("Error processing ObjC data for image %s", baseName.c_str());
}
}
void SharedCache::ProcessObjCSectionsForImageWithInstallName(std::string installName)
{
bool processCFStrings;
bool processObjCMetadata;
GetObjCSettings(m_dscView, &processCFStrings, &processObjCMetadata);
if (!processObjCMetadata && !processCFStrings)
return;
auto objc = std::make_shared<DSCObjC::DSCObjCProcessor>(m_dscView, this, false);
auto vm = GetVMMap();
ProcessObjCSectionsForImageWithName(base_name(installName), vm, objc, processCFStrings, processObjCMetadata, m_logger);
}
void SharedCache::ProcessAllObjCSections()
{
bool processCFStrings;
bool processObjCMetadata;
GetObjCSettings(m_dscView, &processCFStrings, &processObjCMetadata);
if (!processObjCMetadata && !processCFStrings)
return;
auto objc = std::make_shared<DSCObjC::DSCObjCProcessor>(m_dscView, this, false);
auto vm = GetVMMap();
std::set<uint64_t> processedImageHeaders;
for (auto region : GetMappedRegions())
{
if (!region.loaded)
continue;
// Don't repeat the same images multiple times
auto header = HeaderForAddress(region.start);
if (!header)
continue;
if (processedImageHeaders.find(header->textBase) != processedImageHeaders.end())
continue;
processedImageHeaders.insert(header->textBase);
ProcessObjCSectionsForImageWithName(header->identifierPrefix, vm, objc, processCFStrings, processObjCMetadata, m_logger);
}
}
bool SharedCache::LoadImageWithInstallName(std::string installName, bool skipObjC)
{
auto settings = m_dscView->GetLoadSettings(VIEW_NAME);
std::unique_lock lock(m_viewSpecificState->viewOperationsThatInfluenceMetadataMutex);
DeserializeFromRawView();
WillMutateState();
m_logger->LogInfo("Loading image %s", installName.c_str());
auto vm = GetVMMap();
CacheImage* targetImage = nullptr;
for (auto& cacheImage : MutableState().images)
{
if (cacheImage.installName == installName)
{
targetImage = &cacheImage;
break;
}
}
auto it = State().headers.find(targetImage->headerLocation);
if (it == State().headers.end())
{
return false;
}
const auto& header = it->second;
auto id = m_dscView->BeginUndoActions();
MutableState().viewState = DSCViewStateLoadedWithImages;
auto reader = VMReader(vm);
reader.Seek(targetImage->headerLocation);
std::vector<MemoryRegion*> regionsToLoad;
for (auto& region : targetImage->regions)
{
bool allowLoadingLinkedit = false;
if (settings && settings->Contains("loader.dsc.allowLoadingLinkeditSegments"))
allowLoadingLinkedit = settings->Get<bool>("loader.dsc.allowLoadingLinkeditSegments", m_dscView);
if ((region.prettyName.find("__LINKEDIT") != std::string::npos) && !allowLoadingLinkedit)
continue;
if (region.loaded)
{
m_logger->LogDebug("Skipping region %s as it is already loaded.", region.prettyName.c_str());
continue;
}
auto targetFile = vm->MappingAtAddress(region.start).first.fileAccessor->lock();
ParseAndApplySlideInfoForFile(targetFile);
auto rawViewEnd = m_dscView->GetParentView()->GetEnd();
auto buff = reader.ReadBuffer(region.start, region.size);
m_dscView->GetParentView()->GetParentView()->WriteBuffer(rawViewEnd, buff);
m_dscView->GetParentView()->WriteBuffer(rawViewEnd, buff);
region.loaded = true;
region.rawViewOffsetIfLoaded = rawViewEnd;
MutableState().regionsMappedIntoMemory.push_back(region);
m_dscView->GetParentView()->AddAutoSegment(rawViewEnd, region.size, rawViewEnd, region.size, region.flags);
m_dscView->AddUserSegment(region.start, region.size, rawViewEnd, region.size, region.flags);
m_dscView->WriteBuffer(region.start, buff);
regionsToLoad.push_back(®ion);
}
if (regionsToLoad.empty())
{
m_logger->LogWarn("No regions to load for image %s", installName.c_str());
return false;
}
auto typeLib = TypeLibraryForImage(header.installName);
SaveToDSCView();
auto h = SharedCache::LoadHeaderForAddress(vm, targetImage->headerLocation, installName);
if (!h.has_value())
{
return false;
}
std::vector<MemoryRegion*> regions;
for (auto& region : regionsToLoad)
{
regions.push_back(region);
}
SharedCache::InitializeHeader(m_dscView, vm.get(), *h, regions);
if (!skipObjC)
{
bool processCFStrings;
bool processObjCMetadata;
GetObjCSettings(m_dscView, &processCFStrings, &processObjCMetadata);
ProcessObjCSectionsForImageWithName(h->identifierPrefix, vm, std::make_shared<DSCObjC::DSCObjCProcessor>(m_dscView, this, false), processCFStrings, processObjCMetadata, m_logger);
}
m_dscView->AddAnalysisOption("linearsweep");
m_dscView->UpdateAnalysis();
m_dscView->CommitUndoActions(id);
return true;
}
std::optional<SharedCacheMachOHeader> SharedCache::LoadHeaderForAddress(std::shared_ptr<VM> vm, uint64_t address, std::string installName)
{
SharedCacheMachOHeader header;
header.textBase = address;
header.installName = installName;
header.identifierPrefix = base_name(installName);
std::string errorMsg;
// address is a Raw file offset
VMReader reader(vm);
reader.Seek(address);
header.ident.magic = reader.Read32();
BNEndianness endianness;
if (header.ident.magic == MH_MAGIC || header.ident.magic == MH_MAGIC_64)
endianness = LittleEndian;
else if (header.ident.magic == MH_CIGAM || header.ident.magic == MH_CIGAM_64)
endianness = BigEndian;
else
{
return {};
}
reader.SetEndianness(endianness);
header.ident.cputype = reader.Read32();
header.ident.cpusubtype = reader.Read32();
header.ident.filetype = reader.Read32();
header.ident.ncmds = reader.Read32();
header.ident.sizeofcmds = reader.Read32();
header.ident.flags = reader.Read32();
if ((header.ident.cputype & MachOABIMask) == MachOABI64) // address size == 8
{
header.ident.reserved = reader.Read32();
}
header.loadCommandOffset = reader.GetOffset();
bool first = true;
// Parse segment commands
try
{
for (size_t i = 0; i < header.ident.ncmds; i++)
{
// BNLogInfo("of 0x%llx", reader.GetOffset());
load_command load;
segment_command_64 segment64;
section_64 sect;
memset(§, 0, sizeof(sect));
size_t curOffset = reader.GetOffset();
load.cmd = reader.Read32();
load.cmdsize = reader.Read32();
size_t nextOffset = curOffset + load.cmdsize;
if (load.cmdsize < sizeof(load_command))
return {};
switch (load.cmd)
{
case LC_MAIN:
{
uint64_t entryPoint = reader.Read64();
header.entryPoints.push_back({entryPoint, true});
(void)reader.Read64(); // Stack start
break;
}
case LC_SEGMENT: // map the 32bit version to 64 bits
segment64.cmd = LC_SEGMENT_64;
reader.Read(&segment64.segname, 16);
segment64.vmaddr = reader.Read32();
segment64.vmsize = reader.Read32();
segment64.fileoff = reader.Read32();
segment64.filesize = reader.Read32();
segment64.maxprot = reader.Read32();
segment64.initprot = reader.Read32();
segment64.nsects = reader.Read32();
segment64.flags = reader.Read32();
if (first)
{
if (!((header.ident.flags & MH_SPLIT_SEGS) || header.ident.cputype == MACHO_CPU_TYPE_X86_64)
|| (segment64.flags & MACHO_VM_PROT_WRITE))
{
header.relocationBase = segment64.vmaddr;
first = false;
}
}
for (size_t j = 0; j < segment64.nsects; j++)
{
reader.Read(§.sectname, 16);
reader.Read(§.segname, 16);
sect.addr = reader.Read32();
sect.size = reader.Read32();
sect.offset = reader.Read32();
sect.align = reader.Read32();
sect.reloff = reader.Read32();
sect.nreloc = reader.Read32();
sect.flags = reader.Read32();
sect.reserved1 = reader.Read32();
sect.reserved2 = reader.Read32();
// if the segment isn't mapped into virtual memory don't add the corresponding sections.
if (segment64.vmsize > 0)
{
header.sections.push_back(sect);
}
if (!strncmp(sect.sectname, "__mod_init_func", 15))
header.moduleInitSections.push_back(sect);
if ((sect.flags & (S_ATTR_SELF_MODIFYING_CODE | S_SYMBOL_STUBS))
== (S_ATTR_SELF_MODIFYING_CODE | S_SYMBOL_STUBS))
header.symbolStubSections.push_back(sect);
if ((sect.flags & S_NON_LAZY_SYMBOL_POINTERS) == S_NON_LAZY_SYMBOL_POINTERS)
header.symbolPointerSections.push_back(sect);
if ((sect.flags & S_LAZY_SYMBOL_POINTERS) == S_LAZY_SYMBOL_POINTERS)
header.symbolPointerSections.push_back(sect);
}
header.segments.push_back(segment64);
break;
case LC_SEGMENT_64:
segment64.cmd = LC_SEGMENT_64;
reader.Read(&segment64.segname, 16);
segment64.vmaddr = reader.Read64();
segment64.vmsize = reader.Read64();
segment64.fileoff = reader.Read64();
segment64.filesize = reader.Read64();
segment64.maxprot = reader.Read32();
segment64.initprot = reader.Read32();
segment64.nsects = reader.Read32();
segment64.flags = reader.Read32();
if (strncmp(segment64.segname, "__LINKEDIT", 10) == 0)
{
header.linkeditSegment = segment64;
header.linkeditPresent = true;
}
if (first)
{
if (!((header.ident.flags & MH_SPLIT_SEGS) || header.ident.cputype == MACHO_CPU_TYPE_X86_64)
|| (segment64.flags & MACHO_VM_PROT_WRITE))
{
header.relocationBase = segment64.vmaddr;
first = false;
}
}
for (size_t j = 0; j < segment64.nsects; j++)
{
reader.Read(§.sectname, 16);
reader.Read(§.segname, 16);
sect.addr = reader.Read64();
sect.size = reader.Read64();
sect.offset = reader.Read32();
sect.align = reader.Read32();
sect.reloff = reader.Read32();
sect.nreloc = reader.Read32();
sect.flags = reader.Read32();
sect.reserved1 = reader.Read32();
sect.reserved2 = reader.Read32();
sect.reserved3 = reader.Read32();
// if the segment isn't mapped into virtual memory don't add the corresponding sections.
if (segment64.vmsize > 0)
{
header.sections.push_back(sect);
}
if (!strncmp(sect.sectname, "__mod_init_func", 15))
header.moduleInitSections.push_back(sect);
if ((sect.flags & (S_ATTR_SELF_MODIFYING_CODE | S_SYMBOL_STUBS))
== (S_ATTR_SELF_MODIFYING_CODE | S_SYMBOL_STUBS))
header.symbolStubSections.push_back(sect);
if ((sect.flags & S_NON_LAZY_SYMBOL_POINTERS) == S_NON_LAZY_SYMBOL_POINTERS)
header.symbolPointerSections.push_back(sect);
if ((sect.flags & S_LAZY_SYMBOL_POINTERS) == S_LAZY_SYMBOL_POINTERS)
header.symbolPointerSections.push_back(sect);
}
header.segments.push_back(segment64);
break;
case LC_ROUTINES: // map the 32bit version to 64bits
header.routines64.cmd = LC_ROUTINES_64;
header.routines64.init_address = reader.Read32();
header.routines64.init_module = reader.Read32();
header.routines64.reserved1 = reader.Read32();
header.routines64.reserved2 = reader.Read32();
header.routines64.reserved3 = reader.Read32();
header.routines64.reserved4 = reader.Read32();
header.routines64.reserved5 = reader.Read32();
header.routines64.reserved6 = reader.Read32();
header.routinesPresent = true;
break;
case LC_ROUTINES_64:
header.routines64.cmd = LC_ROUTINES_64;
header.routines64.init_address = reader.Read64();
header.routines64.init_module = reader.Read64();
header.routines64.reserved1 = reader.Read64();
header.routines64.reserved2 = reader.Read64();
header.routines64.reserved3 = reader.Read64();
header.routines64.reserved4 = reader.Read64();
header.routines64.reserved5 = reader.Read64();
header.routines64.reserved6 = reader.Read64();
header.routinesPresent = true;
break;
case LC_FUNCTION_STARTS:
header.functionStarts.funcoff = reader.Read32();
header.functionStarts.funcsize = reader.Read32();
header.functionStartsPresent = true;
break;
case LC_SYMTAB:
header.symtab.symoff = reader.Read32();
header.symtab.nsyms = reader.Read32();
header.symtab.stroff = reader.Read32();
header.symtab.strsize = reader.Read32();
break;
case LC_DYSYMTAB:
header.dysymtab.ilocalsym = reader.Read32();
header.dysymtab.nlocalsym = reader.Read32();
header.dysymtab.iextdefsym = reader.Read32();
header.dysymtab.nextdefsym = reader.Read32();
header.dysymtab.iundefsym = reader.Read32();
header.dysymtab.nundefsym = reader.Read32();
header.dysymtab.tocoff = reader.Read32();
header.dysymtab.ntoc = reader.Read32();
header.dysymtab.modtaboff = reader.Read32();
header.dysymtab.nmodtab = reader.Read32();
header.dysymtab.extrefsymoff = reader.Read32();
header.dysymtab.nextrefsyms = reader.Read32();
header.dysymtab.indirectsymoff = reader.Read32();
header.dysymtab.nindirectsyms = reader.Read32();
header.dysymtab.extreloff = reader.Read32();
header.dysymtab.nextrel = reader.Read32();
header.dysymtab.locreloff = reader.Read32();
header.dysymtab.nlocrel = reader.Read32();
header.dysymPresent = true;
break;
case LC_DYLD_CHAINED_FIXUPS:
header.chainedFixups.dataoff = reader.Read32();
header.chainedFixups.datasize = reader.Read32();
header.chainedFixupsPresent = true;
break;
case LC_DYLD_INFO:
case LC_DYLD_INFO_ONLY:
header.dyldInfo.rebase_off = reader.Read32();
header.dyldInfo.rebase_size = reader.Read32();
header.dyldInfo.bind_off = reader.Read32();
header.dyldInfo.bind_size = reader.Read32();
header.dyldInfo.weak_bind_off = reader.Read32();
header.dyldInfo.weak_bind_size = reader.Read32();
header.dyldInfo.lazy_bind_off = reader.Read32();
header.dyldInfo.lazy_bind_size = reader.Read32();
header.dyldInfo.export_off = reader.Read32();
header.dyldInfo.export_size = reader.Read32();
header.exportTrie.dataoff = header.dyldInfo.export_off;
header.exportTrie.datasize = header.dyldInfo.export_size;
header.exportTriePresent = true;
header.dyldInfoPresent = true;
break;
case LC_DYLD_EXPORTS_TRIE:
header.exportTrie.dataoff = reader.Read32();
header.exportTrie.datasize = reader.Read32();
header.exportTriePresent = true;
break;
case LC_THREAD:
case LC_UNIXTHREAD:
/*while (reader.GetOffset() < nextOffset)
{
thread_command thread;
thread.flavor = reader.Read32();
thread.count = reader.Read32();
switch (m_archId)
{
case MachOx64:
m_logger->LogDebug("x86_64 Thread state\n");
if (thread.flavor != X86_THREAD_STATE64)
{
reader.SeekRelative(thread.count * sizeof(uint32_t));
break;
}
//This wont be big endian so we can just read the whole thing
reader.Read(&thread.statex64, sizeof(thread.statex64));
header.entryPoints.push_back({thread.statex64.rip, false});
break;
case MachOx86:
m_logger->LogDebug("x86 Thread state\n");
if (thread.flavor != X86_THREAD_STATE32)
{
reader.SeekRelative(thread.count * sizeof(uint32_t));
break;
}
//This wont be big endian so we can just read the whole thing
reader.Read(&thread.statex86, sizeof(thread.statex86));
header.entryPoints.push_back({thread.statex86.eip, false});
break;
case MachOArm:
m_logger->LogDebug("Arm Thread state\n");
if (thread.flavor != _ARM_THREAD_STATE)
{
reader.SeekRelative(thread.count * sizeof(uint32_t));
break;
}
//This wont be big endian so we can just read the whole thing
reader.Read(&thread.statearmv7, sizeof(thread.statearmv7));
header.entryPoints.push_back({thread.statearmv7.r15, false});
break;
case MachOAarch64:
case MachOAarch6432:
m_logger->LogDebug("Aarch64 Thread state\n");
if (thread.flavor != _ARM_THREAD_STATE64)
{
reader.SeekRelative(thread.count * sizeof(uint32_t));
break;
}
reader.Read(&thread.stateaarch64, sizeof(thread.stateaarch64));
header.entryPoints.push_back({thread.stateaarch64.pc, false});
break;
case MachOPPC:
m_logger->LogDebug("PPC Thread state\n");
if (thread.flavor != PPC_THREAD_STATE)
{
reader.SeekRelative(thread.count * sizeof(uint32_t));
break;
}
//Read individual entries for endian reasons
header.entryPoints.push_back({reader.Read32(), false});
(void)reader.Read32();
(void)reader.Read32();
//Read the rest of the structure
(void)reader.Read(&thread.stateppc.r1, sizeof(thread.stateppc) - (3 * 4));
break;
case MachOPPC64:
m_logger->LogDebug("PPC64 Thread state\n");
if (thread.flavor != PPC_THREAD_STATE64)
{
reader.SeekRelative(thread.count * sizeof(uint32_t));
break;
}
header.entryPoints.push_back({reader.Read64(), false});
(void)reader.Read64();
(void)reader.Read64(); // Stack start
(void)reader.Read(&thread.stateppc64.r1, sizeof(thread.stateppc64) - (3 * 8));
break;
default:
m_logger->LogError("Unknown archid: %x", m_archId);
}
}*/
break;
case LC_LOAD_DYLIB:
{
uint32_t offset = reader.Read32();
if (offset < nextOffset)
{
reader.Seek(curOffset + offset);
std::string libname = reader.ReadCString(reader.GetOffset());
header.dylibs.push_back(libname);
}
}
break;
case LC_BUILD_VERSION:
{
// m_logger->LogDebug("LC_BUILD_VERSION:");
header.buildVersion.platform = reader.Read32();
header.buildVersion.minos = reader.Read32();
header.buildVersion.sdk = reader.Read32();
header.buildVersion.ntools = reader.Read32();
// m_logger->LogDebug("Platform: %s", BuildPlatformToString(header.buildVersion.platform).c_str());
// m_logger->LogDebug("MinOS: %s", BuildToolVersionToString(header.buildVersion.minos).c_str());
// m_logger->LogDebug("SDK: %s", BuildToolVersionToString(header.buildVersion.sdk).c_str());
for (uint32_t j = 0; (i < header.buildVersion.ntools) && (j < 10); j++)
{
uint32_t tool = reader.Read32();
uint32_t version = reader.Read32();
header.buildToolVersions.push_back({tool, version});
// m_logger->LogDebug("Build Tool: %s: %s", BuildToolToString(tool).c_str(),
// BuildToolVersionToString(version).c_str());
}
break;
}
case LC_FILESET_ENTRY:
{
throw ReadException();
}
default:
// m_logger->LogDebug("Unhandled command: %s : %" PRIu32 "\n", CommandToString(load.cmd).c_str(),
// load.cmdsize);
break;
}
if (reader.GetOffset() != nextOffset)
{
// m_logger->LogDebug("Didn't parse load command: %s fully %" PRIx64 ":%" PRIxPTR,
// CommandToString(load.cmd).c_str(), reader.GetOffset(), nextOffset);
}
reader.Seek(nextOffset);
}
for (auto& section : header.sections)
{
char sectionName[17];
memcpy(sectionName, section.sectname, sizeof(section.sectname));
sectionName[16] = 0;
if (header.identifierPrefix.empty())
header.sectionNames.push_back(sectionName);
else
header.sectionNames.push_back(header.identifierPrefix + "::" + sectionName);
}
}
catch (ReadException&)
{
return {};
}
return header;
}
void SharedCache::InitializeHeader(
Ref<BinaryView> view, VM* vm, SharedCacheMachOHeader header, std::vector<MemoryRegion*> regionsToLoad)
{
WillMutateState();
Ref<Settings> settings = view->GetLoadSettings(VIEW_NAME);
bool applyFunctionStarts = true;
if (settings && settings->Contains("loader.dsc.processFunctionStarts"))
applyFunctionStarts = settings->Get<bool>("loader.dsc.processFunctionStarts", view);
for (size_t i = 0; i < header.sections.size(); i++)
{
bool skip = false;
for (const auto& region : regionsToLoad)
{
if (header.sections[i].addr >= region->start && header.sections[i].addr < region->start + region->size)
{
if (region->headerInitialized)
{
skip = true;
}
break;
}
}
if (!header.sections[i].size || skip)
continue;
std::string type;
BNSectionSemantics semantics = DefaultSectionSemantics;
switch (header.sections[i].flags & 0xff)
{
case S_REGULAR:
if (header.sections[i].flags & S_ATTR_PURE_INSTRUCTIONS)
{
type = "PURE_CODE";
semantics = ReadOnlyCodeSectionSemantics;
}
else if (header.sections[i].flags & S_ATTR_SOME_INSTRUCTIONS)
{
type = "CODE";
semantics = ReadOnlyCodeSectionSemantics;
}
else
{
type = "REGULAR";
}
break;
case S_ZEROFILL:
type = "ZEROFILL";
semantics = ReadWriteDataSectionSemantics;
break;
case S_CSTRING_LITERALS:
type = "CSTRING_LITERALS";
semantics = ReadOnlyDataSectionSemantics;
break;
case S_4BYTE_LITERALS:
type = "4BYTE_LITERALS";
break;
case S_8BYTE_LITERALS:
type = "8BYTE_LITERALS";
break;
case S_LITERAL_POINTERS:
type = "LITERAL_POINTERS";
semantics = ReadOnlyDataSectionSemantics;
break;
case S_NON_LAZY_SYMBOL_POINTERS:
type = "NON_LAZY_SYMBOL_POINTERS";
semantics = ReadOnlyDataSectionSemantics;
break;
case S_LAZY_SYMBOL_POINTERS:
type = "LAZY_SYMBOL_POINTERS";
semantics = ReadOnlyDataSectionSemantics;
break;
case S_SYMBOL_STUBS:
type = "SYMBOL_STUBS";
semantics = ReadOnlyCodeSectionSemantics;
break;
case S_MOD_INIT_FUNC_POINTERS:
type = "MOD_INIT_FUNC_POINTERS";
semantics = ReadOnlyDataSectionSemantics;
break;
case S_MOD_TERM_FUNC_POINTERS:
type = "MOD_TERM_FUNC_POINTERS";
semantics = ReadOnlyDataSectionSemantics;
break;
case S_COALESCED:
type = "COALESCED";
break;
case S_GB_ZEROFILL:
type = "GB_ZEROFILL";
semantics = ReadWriteDataSectionSemantics;
break;
case S_INTERPOSING:
type = "INTERPOSING";
break;
case S_16BYTE_LITERALS:
type = "16BYTE_LITERALS";
break;
case S_DTRACE_DOF:
type = "DTRACE_DOF";
break;
case S_LAZY_DYLIB_SYMBOL_POINTERS:
type = "LAZY_DYLIB_SYMBOL_POINTERS";
semantics = ReadOnlyDataSectionSemantics;
break;
case S_THREAD_LOCAL_REGULAR:
type = "THREAD_LOCAL_REGULAR";
break;
case S_THREAD_LOCAL_ZEROFILL:
type = "THREAD_LOCAL_ZEROFILL";
break;
case S_THREAD_LOCAL_VARIABLES:
type = "THREAD_LOCAL_VARIABLES";
break;
case S_THREAD_LOCAL_VARIABLE_POINTERS:
type = "THREAD_LOCAL_VARIABLE_POINTERS";
break;
case S_THREAD_LOCAL_INIT_FUNCTION_POINTERS:
type = "THREAD_LOCAL_INIT_FUNCTION_POINTERS";
break;
default:
type = "UNKNOWN";
break;
}
if (i >= header.sectionNames.size())
break;
if (strncmp(header.sections[i].sectname, "__text", sizeof(header.sections[i].sectname)) == 0)
semantics = ReadOnlyCodeSectionSemantics;
if (strncmp(header.sections[i].sectname, "__const", sizeof(header.sections[i].sectname)) == 0)
semantics = ReadOnlyDataSectionSemantics;
if (strncmp(header.sections[i].sectname, "__data", sizeof(header.sections[i].sectname)) == 0)
semantics = ReadWriteDataSectionSemantics;
if (strncmp(header.sections[i].segname, "__DATA_CONST", sizeof(header.sections[i].segname)) == 0)
semantics = ReadOnlyDataSectionSemantics;
view->AddUserSection(header.sectionNames[i], header.sections[i].addr, header.sections[i].size, semantics,
type, header.sections[i].align);
}
auto typeLib = view->GetTypeLibrary(header.installName);
BinaryReader virtualReader(view);
bool applyHeaderTypes = false;
for (const auto& region : regionsToLoad)
{
if (header.textBase >= region->start && header.textBase < region->start + region->size)
{
if (!region->headerInitialized)
applyHeaderTypes = true;
break;
}
}
if (applyHeaderTypes)
{
view->DefineDataVariable(header.textBase, Type::NamedType(view, QualifiedName("mach_header_64")));
view->DefineAutoSymbol(
new Symbol(DataSymbol, "__macho_header::" + header.identifierPrefix, header.textBase, LocalBinding));
try
{
virtualReader.Seek(header.textBase + sizeof(mach_header_64));
size_t sectionNum = 0;
for (size_t i = 0; i < header.ident.ncmds; i++)
{
load_command load;
uint64_t curOffset = virtualReader.GetOffset();
load.cmd = virtualReader.Read32();
load.cmdsize = virtualReader.Read32();
uint64_t nextOffset = curOffset + load.cmdsize;
switch (load.cmd)
{
case LC_SEGMENT:
{
view->DefineDataVariable(curOffset, Type::NamedType(view, QualifiedName("segment_command")));
virtualReader.SeekRelative(5 * 8);
size_t numSections = virtualReader.Read32();
virtualReader.SeekRelative(4);
for (size_t j = 0; j < numSections; j++)
{
view->DefineDataVariable(
virtualReader.GetOffset(), Type::NamedType(view, QualifiedName("section")));
view->DefineUserSymbol(new Symbol(DataSymbol,
"__macho_section::" + header.identifierPrefix + "_[" + std::to_string(sectionNum++) + "]",
virtualReader.GetOffset(), LocalBinding));
virtualReader.SeekRelative((8 * 8) + 4);
}
break;
}
case LC_SEGMENT_64:
{
view->DefineDataVariable(curOffset, Type::NamedType(view, QualifiedName("segment_command_64")));
virtualReader.SeekRelative(7 * 8);
size_t numSections = virtualReader.Read32();
virtualReader.SeekRelative(4);
for (size_t j = 0; j < numSections; j++)
{
view->DefineDataVariable(
virtualReader.GetOffset(), Type::NamedType(view, QualifiedName("section_64")));
view->DefineUserSymbol(new Symbol(DataSymbol,
"__macho_section_64::" + header.identifierPrefix + "_[" + std::to_string(sectionNum++) + "]",
virtualReader.GetOffset(), LocalBinding));
virtualReader.SeekRelative(10 * 8);
}
break;
}
case LC_SYMTAB:
view->DefineDataVariable(curOffset, Type::NamedType(view, QualifiedName("symtab")));
break;
case LC_DYSYMTAB:
view->DefineDataVariable(curOffset, Type::NamedType(view, QualifiedName("dysymtab")));
break;
case LC_UUID:
view->DefineDataVariable(curOffset, Type::NamedType(view, QualifiedName("uuid")));
break;
case LC_ID_DYLIB:
case LC_LOAD_DYLIB:
case LC_REEXPORT_DYLIB:
case LC_LOAD_WEAK_DYLIB:
case LC_LOAD_UPWARD_DYLIB:
view->DefineDataVariable(curOffset, Type::NamedType(view, QualifiedName("dylib_command")));
if (load.cmdsize - 24 <= 150)
view->DefineDataVariable(
curOffset + 24, Type::ArrayType(Type::IntegerType(1, true), load.cmdsize - 24));
break;
case LC_CODE_SIGNATURE:
case LC_SEGMENT_SPLIT_INFO:
case LC_FUNCTION_STARTS:
case LC_DATA_IN_CODE:
case LC_DYLIB_CODE_SIGN_DRS:
case LC_DYLD_EXPORTS_TRIE:
case LC_DYLD_CHAINED_FIXUPS:
view->DefineDataVariable(curOffset, Type::NamedType(view, QualifiedName("linkedit_data")));
break;
case LC_ENCRYPTION_INFO:
view->DefineDataVariable(curOffset, Type::NamedType(view, QualifiedName("encryption_info")));
break;
case LC_VERSION_MIN_MACOSX:
case LC_VERSION_MIN_IPHONEOS:
view->DefineDataVariable(curOffset, Type::NamedType(view, QualifiedName("version_min")));
break;
case LC_DYLD_INFO:
case LC_DYLD_INFO_ONLY:
view->DefineDataVariable(curOffset, Type::NamedType(view, QualifiedName("dyld_info")));
break;
default:
view->DefineDataVariable(curOffset, Type::NamedType(view, QualifiedName("load_command")));
break;
}
view->DefineAutoSymbol(new Symbol(DataSymbol,
"__macho_load_command::" + header.identifierPrefix + "_[" + std::to_string(i) + "]", curOffset,
LocalBinding));
virtualReader.Seek(nextOffset);
}
}
catch (ReadException&)
{
LogError("Error when applying Mach-O header types at %" PRIx64, header.textBase);
}
}
if (applyFunctionStarts && header.functionStartsPresent && header.linkeditPresent && vm->AddressIsMapped(header.linkeditSegment.vmaddr))
{
auto funcStarts =
vm->MappingAtAddress(header.linkeditSegment.vmaddr)
.first.fileAccessor->lock()
->ReadBuffer(header.functionStarts.funcoff, header.functionStarts.funcsize);
size_t i = 0;
uint64_t curfunc = header.textBase;
uint64_t curOffset;
while (i < header.functionStarts.funcsize)
{
curOffset = readLEB128(funcStarts, header.functionStarts.funcsize, i);
bool addFunction = false;
for (const auto& region : regionsToLoad)
{
if (curfunc >= region->start && curfunc < region->start + region->size)
{
if (!region->headerInitialized)
addFunction = true;
}
}
// LogError("0x%llx, 0x%llx", header.textBase, curOffset);
if (curOffset == 0 || !addFunction)
continue;
curfunc += curOffset;
uint64_t target = curfunc;
Ref<Platform> targetPlatform = view->GetDefaultPlatform();
view->AddFunctionForAnalysis(targetPlatform, target);
}
}
view->BeginBulkModifySymbols();
if (header.symtab.symoff != 0 && header.linkeditPresent && vm->AddressIsMapped(header.linkeditSegment.vmaddr))
{
// Mach-O View symtab processing with
// a ton of stuff cut out so it can work
auto reader = vm->MappingAtAddress(header.linkeditSegment.vmaddr).first.fileAccessor->lock();
// auto symtab = reader->ReadBuffer(header.symtab.symoff, header.symtab.nsyms * sizeof(nlist_64));
auto strtab = reader->ReadBuffer(header.symtab.stroff, header.symtab.strsize);
nlist_64 sym;
memset(&sym, 0, sizeof(sym));
auto N_TYPE = 0xE; // idk
std::vector<std::pair<uint64_t, std::pair<BNSymbolType, std::string>>> symbolInfos;
for (size_t i = 0; i < header.symtab.nsyms; i++)
{
reader->Read(&sym, header.symtab.symoff + i * sizeof(nlist_64), sizeof(nlist_64));
if (sym.n_strx >= header.symtab.strsize || ((sym.n_type & N_TYPE) == N_INDR))
continue;
std::string symbol((char*)strtab.GetDataAt(sym.n_strx));
// BNLogError("%s: 0x%llx", symbol.c_str(), sym.n_value);
if (symbol == "<redacted>")
continue;
BNSymbolType type = DataSymbol;
uint32_t flags;
if ((sym.n_type & N_TYPE) == N_SECT && sym.n_sect > 0 && (size_t)(sym.n_sect - 1) < header.sections.size())
{}
else if ((sym.n_type & N_TYPE) == N_ABS)
{}
else if ((sym.n_type & 0x1))
{
type = ExternalSymbol;
}
else
continue;
for (auto s : header.sections)
{
if (s.addr < sym.n_value)
{
if (s.addr + s.size > sym.n_value)
{
flags = s.flags;
}
}
}
if (type != ExternalSymbol)
{
if ((flags & S_ATTR_PURE_INSTRUCTIONS) == S_ATTR_PURE_INSTRUCTIONS
|| (flags & S_ATTR_SOME_INSTRUCTIONS) == S_ATTR_SOME_INSTRUCTIONS)
type = FunctionSymbol;
else
type = DataSymbol;
}
if ((sym.n_desc & N_ARM_THUMB_DEF) == N_ARM_THUMB_DEF)
sym.n_value++;
auto symbolObj = new Symbol(type, symbol, sym.n_value, GlobalBinding);
if (type == FunctionSymbol)
{
Ref<Platform> targetPlatform = view->GetDefaultPlatform();
view->AddFunctionForAnalysis(targetPlatform, sym.n_value);
}
if (typeLib)
{
auto _type = m_dscView->ImportTypeLibraryObject(typeLib, {symbolObj->GetFullName()});
if (_type)
{
view->DefineAutoSymbolAndVariableOrFunction(view->GetDefaultPlatform(), symbolObj, _type);
}
else
view->DefineAutoSymbol(symbolObj);
}
else
view->DefineAutoSymbol(symbolObj);
symbolInfos.push_back({sym.n_value, {type, symbol}});
}
MutableState().symbolInfos[header.textBase] = symbolInfos;
}
if (header.exportTriePresent && header.linkeditPresent && vm->AddressIsMapped(header.linkeditSegment.vmaddr))
{
auto symbols = SharedCache::ParseExportTrie(vm->MappingAtAddress(header.linkeditSegment.vmaddr).first.fileAccessor->lock(), header);
std::vector<std::pair<uint64_t, std::pair<BNSymbolType, std::string>>> exportMapping;
for (const auto& symbol : symbols)
{
exportMapping.push_back({symbol->GetAddress(), {symbol->GetType(), symbol->GetRawName()}});
if (typeLib)
{
auto type = m_dscView->ImportTypeLibraryObject(typeLib, {symbol->GetFullName()});
if (type)
{
view->DefineAutoSymbolAndVariableOrFunction(view->GetDefaultPlatform(), symbol, type);
}
else
view->DefineAutoSymbol(symbol);
if (view->GetAnalysisFunction(view->GetDefaultPlatform(), symbol->GetAddress()))
{
auto func = view->GetAnalysisFunction(view->GetDefaultPlatform(), symbol->GetAddress());
if (symbol->GetFullName() == "_objc_msgSend")
{
func->SetHasVariableArguments(false);
}
else if (symbol->GetFullName().find("_objc_retain_x") != std::string::npos || symbol->GetFullName().find("_objc_release_x") != std::string::npos)
{
auto x = symbol->GetFullName().rfind("x");
auto num = symbol->GetFullName().substr(x + 1);
std::vector<BinaryNinja::FunctionParameter> callTypeParams;
auto cc = m_dscView->GetDefaultArchitecture()->GetCallingConventionByName("apple-arm64-objc-fast-arc-" + num);
callTypeParams.push_back({"obj", m_dscView->GetTypeByName({ "id" }), true, BinaryNinja::Variable()});
auto funcType = BinaryNinja::Type::FunctionType(m_dscView->GetTypeByName({ "id" }), cc, callTypeParams);
func->SetUserType(funcType);
}
}
}
else
view->DefineAutoSymbol(symbol);
}
MutableState().exportInfos[header.textBase] = std::move(exportMapping);
}
view->EndBulkModifySymbols();
for (auto region : regionsToLoad)
{
region->headerInitialized = true;
}
}
struct ExportNode
{
std::string text;
uint64_t offset;
uint64_t flags;
};
void SharedCache::ReadExportNode(std::vector<Ref<Symbol>>& symbolList, SharedCacheMachOHeader& header, DataBuffer& buffer, uint64_t textBase,
const std::string& currentText, size_t cursor, uint32_t endGuard)
{
if (cursor > endGuard)
throw ReadException();
uint64_t terminalSize = readValidULEB128(buffer, cursor);
uint64_t childOffset = cursor + terminalSize;
if (terminalSize != 0) {
uint64_t imageOffset = 0;
uint64_t flags = readValidULEB128(buffer, cursor);
if (!(flags & EXPORT_SYMBOL_FLAGS_REEXPORT))
{
imageOffset = readValidULEB128(buffer, cursor);
auto symbolType = m_dscView->GetAnalysisFunctionsForAddress(textBase + imageOffset).size() ? FunctionSymbol : DataSymbol;
{
if (!currentText.empty() && textBase + imageOffset)
{
uint32_t flags;
BNSymbolType type;
for (auto s : header.sections)
{
if (s.addr < textBase + imageOffset)
{
if (s.addr + s.size > textBase + imageOffset)
{
flags = s.flags;
}
}
}
if ((flags & S_ATTR_PURE_INSTRUCTIONS) == S_ATTR_PURE_INSTRUCTIONS
|| (flags & S_ATTR_SOME_INSTRUCTIONS) == S_ATTR_SOME_INSTRUCTIONS)
type = FunctionSymbol;
else
type = DataSymbol;
#if EXPORT_TRIE_DEBUG
// BNLogInfo("export: %s -> 0x%llx", n.text.c_str(), image.baseAddress + n.offset);
#endif
auto sym = new Symbol(type, currentText, textBase + imageOffset);
symbolList.push_back(sym);
}
}
}
}
cursor = childOffset;
uint8_t childCount = buffer[cursor];
cursor++;
if (cursor > endGuard)
throw ReadException();
for (uint8_t i = 0; i < childCount; ++i)
{
std::string childText;
while (buffer[cursor] != 0 & cursor <= endGuard)
childText.push_back(buffer[cursor++]);
cursor++;
if (cursor > endGuard)
throw ReadException();
auto next = readValidULEB128(buffer, cursor);
if (next == 0)
throw ReadException();
ReadExportNode(symbolList, header, buffer, textBase, currentText + childText, next, endGuard);
}
}
std::vector<Ref<Symbol>> SharedCache::ParseExportTrie(std::shared_ptr<MMappedFileAccessor> linkeditFile, SharedCacheMachOHeader header)
{
std::vector<Ref<Symbol>> symbols;
try
{
auto reader = linkeditFile;
std::vector<ExportNode> nodes;
DataBuffer buffer = reader->ReadBuffer(header.exportTrie.dataoff, header.exportTrie.datasize);
ReadExportNode(symbols, header, buffer, header.textBase, "", 0, header.exportTrie.datasize);
}
catch (std::exception& e)
{
BNLogError("Failed to load Export Trie");
}
return symbols;
}
std::vector<std::string> SharedCache::GetAvailableImages()
{
std::vector<std::string> installNames;
for (const auto& header : State().headers)
{
installNames.push_back(header.second.installName);
}
return installNames;
}
std::vector<std::pair<std::string, Ref<Symbol>>> SharedCache::LoadAllSymbolsAndWait()
{
WillMutateState();
std::lock_guard initialLoadBlock(m_viewSpecificState->viewOperationsThatInfluenceMetadataMutex);
std::vector<std::pair<std::string, Ref<Symbol>>> symbols;
for (const auto& img : State().images)
{
auto header = HeaderForAddress(img.headerLocation);
std::shared_ptr<MMappedFileAccessor> mapping;
try {
mapping = MMappedFileAccessor::Open(m_dscView, m_dscView->GetFile()->GetSessionId(), header->exportTriePath)->lock();
}
catch (...)
{
m_logger->LogWarn("Serious Error: Failed to open export trie %s for %s", header->exportTriePath.c_str(), header->installName.c_str());
continue;
}
auto exportList = SharedCache::ParseExportTrie(mapping, *header);
std::vector<std::pair<uint64_t, std::pair<BNSymbolType, std::string>>> exportMapping;
for (const auto& sym : exportList)
{
exportMapping.push_back({sym->GetAddress(), {sym->GetType(), sym->GetRawName()}});
symbols.push_back({img.installName, sym});
}
MutableState().exportInfos[header->textBase] = std::move(exportMapping);
}
SaveToDSCView();
return symbols;
}
std::string SharedCache::SerializedImageHeaderForAddress(uint64_t address)
{
auto header = HeaderForAddress(address);
if (header)
{
return header->AsString();
}
return "";
}
std::string SharedCache::SerializedImageHeaderForName(std::string name)
{
if (auto it = State().imageStarts.find(name); it != State().imageStarts.end())
{
if (auto header = HeaderForAddress(it->second))
{
return header->AsString();
}
}
return "";
}
Ref<TypeLibrary> SharedCache::TypeLibraryForImage(const std::string& installName) {
std::lock_guard lock(m_viewSpecificState->typeLibraryMutex);
if (auto it = m_viewSpecificState->typeLibraries.find(installName); it != m_viewSpecificState->typeLibraries.end()) {
return it->second;
}
auto typeLib = m_dscView->GetTypeLibrary(installName);
if (!typeLib) {
auto typeLibs = m_dscView->GetDefaultPlatform()->GetTypeLibrariesByName(installName);
if (!typeLibs.empty()) {
typeLib = typeLibs[0];
m_dscView->AddTypeLibrary(typeLib);
}
}
m_viewSpecificState->typeLibraries[installName] = typeLib;
return typeLib;
}
void SharedCache::FindSymbolAtAddrAndApplyToAddr(
uint64_t symbolLocation, uint64_t targetLocation, bool triggerReanalysis)
{
WillMutateState();
std::string prefix = "";
if (symbolLocation != targetLocation)
prefix = "j_";
if (auto preexistingSymbol = m_dscView->GetSymbolByAddress(targetLocation))
{
if (preexistingSymbol->GetFullName().find("j_") != std::string::npos)
return;
}
auto id = m_dscView->BeginUndoActions();
if (auto loadedSymbol = m_dscView->GetSymbolByAddress(symbolLocation))
{
if (m_dscView->GetAnalysisFunction(m_dscView->GetDefaultPlatform(), targetLocation))
m_dscView->DefineUserSymbol(new Symbol(FunctionSymbol, prefix + loadedSymbol->GetFullName(), targetLocation));
else
m_dscView->DefineUserSymbol(new Symbol(loadedSymbol->GetType(), prefix + loadedSymbol->GetFullName(), targetLocation));
}
else if (auto sym = m_dscView->GetSymbolByAddress(symbolLocation))
{
if (m_dscView->GetAnalysisFunction(m_dscView->GetDefaultPlatform(), targetLocation))
m_dscView->DefineUserSymbol(new Symbol(FunctionSymbol, prefix + sym->GetFullName(), targetLocation));
else
m_dscView->DefineUserSymbol(new Symbol(sym->GetType(), prefix + sym->GetFullName(), targetLocation));
}
m_dscView->ForgetUndoActions(id);
auto header = HeaderForAddress(symbolLocation);
if (header)
{
std::shared_ptr<MMappedFileAccessor> mapping;
try {
mapping = MMappedFileAccessor::Open(m_dscView, m_dscView->GetFile()->GetSessionId(), header->exportTriePath)->lock();
}
catch (...)
{
m_logger->LogWarn("Serious Error: Failed to open export trie for %s", header->installName.c_str());
return;
}
auto exportList = SharedCache::ParseExportTrie(mapping, *header);
std::vector<std::pair<uint64_t, std::pair<BNSymbolType, std::string>>> exportMapping;
auto typeLib = TypeLibraryForImage(header->installName);
id = m_dscView->BeginUndoActions();
m_dscView->BeginBulkModifySymbols();
for (const auto& sym : exportList)
{
exportMapping.push_back({sym->GetAddress(), {sym->GetType(), sym->GetRawName()}});
if (sym->GetAddress() == symbolLocation)
{
if (auto func = m_dscView->GetAnalysisFunction(m_dscView->GetDefaultPlatform(), targetLocation))
{
m_dscView->DefineUserSymbol(
new Symbol(FunctionSymbol, prefix + sym->GetFullName(), targetLocation));
if (typeLib)
if (auto type = m_dscView->ImportTypeLibraryObject(typeLib, {sym->GetFullName()}))
func->SetUserType(type);
}
else
{
m_dscView->DefineUserSymbol(
new Symbol(sym->GetType(), prefix + sym->GetFullName(), targetLocation));
if (typeLib)
if (auto type = m_dscView->ImportTypeLibraryObject(typeLib, {sym->GetFullName()}))
m_dscView->DefineUserDataVariable(targetLocation, type);
}
if (triggerReanalysis)
{
auto func = m_dscView->GetAnalysisFunction(m_dscView->GetDefaultPlatform(), targetLocation);
if (func)
func->Reanalyze();
}
break;
}
}
{
std::lock_guard lock(m_viewSpecificState->viewOperationsThatInfluenceMetadataMutex);
MutableState().exportInfos[header->textBase] = std::move(exportMapping);
}
m_dscView->EndBulkModifySymbols();
m_dscView->ForgetUndoActions(id);
}
}
bool SharedCache::SaveToDSCView()
{
if (m_dscView)
{
auto data = AsMetadata();
m_dscView->StoreMetadata(SharedCacheMetadataTag, data);
m_dscView->GetParentView()->GetParentView()->StoreMetadata(SharedCacheMetadataTag, data);
// By moving our state the to cache we can avoid creating a copy in the case
// that no further mutations are made to `this`. If we're not done being mutated,
// the data will be copied on the first mutation.
auto cachedState = std::make_shared<struct State>(std::move(*m_state));
m_state = cachedState;
m_stateIsShared = true;
std::lock_guard lock(m_viewSpecificState->stateMutex);
m_viewSpecificState->cachedState = std::move(cachedState);
m_metadataValid = true;
return true;
}
return false;
}
std::vector<MemoryRegion> SharedCache::GetMappedRegions() const
{
std::lock_guard lock(m_viewSpecificState->viewOperationsThatInfluenceMetadataMutex);
return State().regionsMappedIntoMemory;
}
bool SharedCache::IsMemoryMapped(uint64_t address)
{
return m_dscView->IsValidOffset(address);
}
extern "C"
{
BNSharedCache* BNGetSharedCache(BNBinaryView* data)
{
if (!data)
return nullptr;
Ref<BinaryView> view = new BinaryView(BNNewViewReference(data));
if (auto cache = SharedCache::GetFromDSCView(view))
{
cache->AddAPIRef();
return cache->GetAPIObject();
}
return nullptr;
}
BNSharedCache* BNNewSharedCacheReference(BNSharedCache* cache)
{
if (!cache->object)
return nullptr;
cache->object->AddAPIRef();
return cache;
}
void BNFreeSharedCacheReference(BNSharedCache* cache)
{
if (!cache->object)
return;
cache->object->ReleaseAPIRef();
}
bool BNDSCViewLoadImageWithInstallName(BNSharedCache* cache, char* name, bool skipObjC)
{
std::string imageName = std::string(name);
// FIXME !!!!!!!! BNFreeString(name);
if (cache->object)
return cache->object->LoadImageWithInstallName(imageName, skipObjC);
return false;
}
bool BNDSCViewLoadSectionAtAddress(BNSharedCache* cache, uint64_t addr)
{
if (cache->object)
{
return cache->object->LoadSectionAtAddress(addr);
}
return false;
}
bool BNDSCViewLoadImageContainingAddress(BNSharedCache* cache, uint64_t address, bool skipObjC)
{
if (cache->object)
{
return cache->object->LoadImageContainingAddress(address, skipObjC);
}
return false;
}
void BNDSCViewProcessObjCSectionsForImageWithInstallName(BNSharedCache* cache, char* name, bool deallocName)
{
std::string imageName = std::string(name);
if (deallocName)
BNFreeString(name);
if (cache->object)
cache->object->ProcessObjCSectionsForImageWithInstallName(imageName);
}
void BNDSCViewProcessAllObjCSections(BNSharedCache* cache)
{
if (cache->object)
cache->object->ProcessAllObjCSections();
}
char** BNDSCViewGetInstallNames(BNSharedCache* cache, size_t* count)
{
if (cache->object)
{
auto value = cache->object->GetAvailableImages();
*count = value.size();
std::vector<const char*> cstrings;
for (size_t i = 0; i < value.size(); i++)
{
cstrings.push_back(value[i].c_str());
}
return BNAllocStringList(cstrings.data(), cstrings.size());
}
*count = 0;
return nullptr;
}
BNDSCSymbolRep* BNDSCViewLoadAllSymbolsAndWait(BNSharedCache* cache, size_t* count)
{
if (cache->object)
{
auto value = cache->object->LoadAllSymbolsAndWait();
*count = value.size();
BNDSCSymbolRep* symbols = (BNDSCSymbolRep*)malloc(sizeof(BNDSCSymbolRep) * value.size());
for (size_t i = 0; i < value.size(); i++)
{
symbols[i].address = value[i].second->GetAddress();
symbols[i].name = BNAllocString(value[i].second->GetRawName().c_str());
symbols[i].image = BNAllocString(value[i].first.c_str());
}
return symbols;
}
*count = 0;
return nullptr;
}
void BNDSCViewFreeSymbols(BNDSCSymbolRep* symbols, size_t count)
{
for (size_t i = 0; i < count; i++)
{
BNFreeString(symbols[i].name);
BNFreeString(symbols[i].image);
}
delete symbols;
}
char* BNDSCViewGetNameForAddress(BNSharedCache* cache, uint64_t address)
{
if (cache->object)
{
return BNAllocString(cache->object->NameForAddress(address).c_str());
}
return nullptr;
}
char* BNDSCViewGetImageNameForAddress(BNSharedCache* cache, uint64_t address)
{
if (cache->object)
{
return BNAllocString(cache->object->ImageNameForAddress(address).c_str());
}
return nullptr;
}
uint64_t BNDSCViewLoadedImageCount(BNSharedCache* cache)
{
// FIXME?
return 0;
}
BNDSCViewState BNDSCViewGetState(BNSharedCache* cache)
{
if (cache->object)
{
return (BNDSCViewState)cache->object->ViewState();
}
return BNDSCViewState::Unloaded;
}
BNDSCMappedMemoryRegion* BNDSCViewGetLoadedRegions(BNSharedCache* cache, size_t* count)
{
if (cache->object)
{
auto regions = cache->object->GetMappedRegions();
*count = regions.size();
BNDSCMappedMemoryRegion* mappedRegions = (BNDSCMappedMemoryRegion*)malloc(sizeof(BNDSCMappedMemoryRegion) * regions.size());
for (size_t i = 0; i < regions.size(); i++)
{
mappedRegions[i].vmAddress = regions[i].start;
mappedRegions[i].size = regions[i].size;
mappedRegions[i].name = BNAllocString(regions[i].prettyName.c_str());
}
return mappedRegions;
}
*count = 0;
return nullptr;
}
void BNDSCViewFreeLoadedRegions(BNDSCMappedMemoryRegion* images, size_t count)
{
for (size_t i = 0; i < count; i++)
{
BNFreeString(images[i].name);
}
delete images;
}
BNDSCBackingCache* BNDSCViewGetBackingCaches(BNSharedCache* cache, size_t* count)
{
BNDSCBackingCache* caches = nullptr;
if (cache->object)
{
auto viewCaches = cache->object->BackingCaches();
*count = viewCaches.size();
caches = (BNDSCBackingCache*)malloc(sizeof(BNDSCBackingCache) * viewCaches.size());
for (size_t i = 0; i < viewCaches.size(); i++)
{
caches[i].path = BNAllocString(viewCaches[i].path.c_str());
caches[i].isPrimary = viewCaches[i].isPrimary;
BNDSCBackingCacheMapping* mappings;
mappings = (BNDSCBackingCacheMapping*)malloc(sizeof(BNDSCBackingCacheMapping) * viewCaches[i].mappings.size());
size_t j = 0;
for (const auto& [fileOffset, mapping] : viewCaches[i].mappings)
{
mappings[j].vmAddress = mapping.first;
mappings[j].size = mapping.second;
mappings[j].fileOffset = fileOffset;
j++;
}
caches[i].mappings = mappings;
caches[i].mappingCount = viewCaches[i].mappings.size();
}
}
return caches;
}
void BNDSCViewFreeBackingCaches(BNDSCBackingCache* caches, size_t count)
{
for (size_t i = 0; i < count; i++)
{
delete[] caches[i].mappings;
BNFreeString(caches[i].path);
}
delete[] caches;
}
void BNDSCFindSymbolAtAddressAndApplyToAddress(BNSharedCache* cache, uint64_t symbolLocation, uint64_t targetLocation, bool triggerReanalysis)
{
if (cache->object)
{
cache->object->FindSymbolAtAddrAndApplyToAddr(symbolLocation, targetLocation, triggerReanalysis);
}
}
BNDSCImage* BNDSCViewGetAllImages(BNSharedCache* cache, size_t* count)
{
if (cache->object)
{
auto vm = cache->object->GetVMMap(true);
auto viewImageHeaders = cache->object->AllImageHeaders();
*count = viewImageHeaders.size();
BNDSCImage* images = (BNDSCImage*)malloc(sizeof(BNDSCImage) * viewImageHeaders.size());
size_t i = 0;
for (const auto& [baseAddress, header] : viewImageHeaders)
{
images[i].name = BNAllocString(header.installName.c_str());
images[i].headerAddress = baseAddress;
images[i].mappingCount = header.sections.size();
images[i].mappings = (BNDSCImageMemoryMapping*)malloc(sizeof(BNDSCImageMemoryMapping) * header.sections.size());
for (size_t j = 0; j < header.sections.size(); j++)
{
const auto sectionStart = header.sections[j].addr;
images[i].mappings[j].rawViewOffset = header.sections[j].offset;
images[i].mappings[j].vmAddress = sectionStart;
images[i].mappings[j].size = header.sections[j].size;
images[i].mappings[j].name = BNAllocString(header.sectionNames[j].c_str());
images[i].mappings[j].filePath = BNAllocString(vm->MappingAtAddress(sectionStart).first.filePath.c_str());
images[i].mappings[j].loaded = cache->object->IsMemoryMapped(sectionStart);
}
i++;
}
return images;
}
*count = 0;
return nullptr;
}
void BNDSCViewFreeAllImages(BNDSCImage* images, size_t count)
{
for (size_t i = 0; i < count; i++)
{
for (size_t j = 0; j < images[i].mappingCount; j++)
{
BNFreeString(images[i].mappings[j].name);
BNFreeString(images[i].mappings[j].filePath);
}
delete[] images[i].mappings;
BNFreeString(images[i].name);
}
delete[] images;
}
char* BNDSCViewGetImageHeaderForAddress(BNSharedCache* cache, uint64_t address)
{
if (cache->object)
{
auto header = cache->object->SerializedImageHeaderForAddress(address);
return BNAllocString(header.c_str());
}
return nullptr;
}
char* BNDSCViewGetImageHeaderForName(BNSharedCache* cache, char* name)
{
std::string imageName = std::string(name);
BNFreeString(name);
if (cache->object)
{
auto header = cache->object->SerializedImageHeaderForName(imageName);
return BNAllocString(header.c_str());
}
return nullptr;
}
BNDSCMemoryUsageInfo BNDSCViewGetMemoryUsageInfo()
{
BNDSCMemoryUsageInfo info;
info.mmapRefs = mmapCount.load();
info.sharedCacheRefs = sharedCacheReferences.load();
return info;
}
BNDSCViewLoadProgress BNDSCViewGetLoadProgress(uint64_t sessionID)
{
if (auto viewSpecificState = ViewSpecificStateForId(sessionID, false)) {
return viewSpecificState->progress;
}
return LoadProgressNotStarted;
}
uint64_t BNDSCViewFastGetBackingCacheCount(BNBinaryView* data)
{
Ref<BinaryView> view = new BinaryView(BNNewViewReference(data));
return SharedCache::FastGetBackingCacheCount(view);
}
}
[[maybe_unused]] DSCViewType* g_dscViewType;
[[maybe_unused]] DSCRawViewType* g_dscRawViewType;
void InitDSCViewType()
{
MMappedFileAccessor::InitialVMSetup();
std::atexit(VMShutdown);
static DSCRawViewType rawType;
BinaryViewType::Register(&rawType);
static DSCViewType type;
BinaryViewType::Register(&type);
g_dscViewType = &type;
g_dscRawViewType = &rawType;
}
namespace SharedCacheCore {
void SharedCache::Store(SerializationContext& context) const
{
Serialize(context, "metadataVersion", METADATA_VERSION);
Serialize(context, "m_viewState", State().viewState);
Serialize(context, "m_cacheFormat", State().cacheFormat);
Serialize(context, "m_imageStarts", State().imageStarts);
Serialize(context, "m_baseFilePath", State().baseFilePath);
Serialize(context, "headers");
context.writer.StartArray();
for (auto& [k, v] : State().headers)
{
context.writer.StartObject();
v.Store(context);
context.writer.EndObject();
}
context.writer.EndArray();
Serialize(context, "exportInfos");
context.writer.StartArray();
for (const auto& pair1 : State().exportInfos)
{
context.writer.StartObject();
Serialize(context, "key", pair1.first);
Serialize(context, "value");
context.writer.StartArray();
for (const auto& pair2 : pair1.second)
{
context.writer.StartObject();
Serialize(context, "key", pair2.first);
Serialize(context, "val1", pair2.second.first);
Serialize(context, "val2", pair2.second.second);
context.writer.EndObject();
}
context.writer.EndArray();
context.writer.EndObject();
}
context.writer.EndArray();
Serialize(context, "symbolInfos");
context.writer.StartArray();
for (const auto& pair1 : State().symbolInfos)
{
context.writer.StartObject();
Serialize(context, "key", pair1.first);
Serialize(context, "value");
context.writer.StartArray();
for (const auto& pair2 : pair1.second)
{
context.writer.StartObject();
Serialize(context, "key", pair2.first);
Serialize(context, "val1", pair2.second.first);
Serialize(context, "val2", pair2.second.second);
context.writer.EndObject();
}
context.writer.EndArray();
context.writer.EndObject();
}
context.writer.EndArray();
Serialize(context, "backingCaches", State().backingCaches);
Serialize(context, "stubIslands", State().stubIslandRegions);
Serialize(context, "images", State().images);
Serialize(context, "regionsMappedIntoMemory", State().regionsMappedIntoMemory);
Serialize(context, "dyldDataSections", State().dyldDataRegions);
Serialize(context, "nonImageRegions", State().nonImageRegions);
}
void SharedCache::Load(DeserializationContext& context)
{
if (context.doc.HasMember("metadataVersion"))
{
if (context.doc["metadataVersion"].GetUint() != METADATA_VERSION)
{
m_logger->LogError("Shared Cache metadata version mismatch");
return;
}
}
else
{
m_logger->LogError("Shared Cache metadata version missing");
return;
}
m_stateIsShared = false;
m_state = std::make_shared<struct SharedCache::State>();
MutableState().viewState = static_cast<DSCViewState>(context.load<uint8_t>("m_viewState"));
MutableState().cacheFormat = static_cast<SharedCacheFormat>(context.load<uint8_t>("m_cacheFormat"));
for (auto& startAndHeader : context.doc["headers"].GetArray())
{
SharedCacheMachOHeader header;
header.LoadFromValue(startAndHeader);
MutableState().headers[header.textBase] = std::move(header);
}
Deserialize(context, "m_imageStarts", MutableState().imageStarts);
Deserialize(context, "m_baseFilePath", MutableState().baseFilePath);
for (const auto& obj1 : context.doc["exportInfos"].GetArray())
{
std::vector<std::pair<uint64_t, std::pair<BNSymbolType, std::string>>> innerVec;
for (const auto& obj2 : obj1["value"].GetArray())
{
std::pair<BNSymbolType, std::string> innerPair = {
(BNSymbolType)obj2["val1"].GetUint64(), obj2["val2"].GetString()};
innerVec.push_back({obj2["key"].GetUint64(), innerPair});
}
MutableState().exportInfos[obj1["key"].GetUint64()] = std::move(innerVec);
}
for (auto& symbolInfo : context.doc["symbolInfos"].GetArray())
{
std::vector<std::pair<uint64_t, std::pair<BNSymbolType, std::string>>>
symbolInfos;
for (auto& si : symbolInfo["value"].GetArray())
{
symbolInfos.push_back({si["key"].GetUint64(),
{static_cast<BNSymbolType>(si["val1"].GetUint64()), si["val2"].GetString()}});
}
MutableState().symbolInfos[symbolInfo["key"].GetUint64()] = std::move(symbolInfos);
}
for (auto& bcV : context.doc["backingCaches"].GetArray())
{
BackingCache bc;
bc.LoadFromValue(bcV);
MutableState().backingCaches.push_back(std::move(bc));
}
for (auto& imgV : context.doc["images"].GetArray())
{
CacheImage img;
img.LoadFromValue(imgV);
MutableState().images.push_back(std::move(img));
}
for (auto& rV : context.doc["regionsMappedIntoMemory"].GetArray())
{
MemoryRegion r;
r.LoadFromValue(rV);
MutableState().regionsMappedIntoMemory.push_back(std::move(r));
}
for (auto& siV : context.doc["stubIslands"].GetArray())
{
MemoryRegion si;
si.LoadFromValue(siV);
MutableState().stubIslandRegions.push_back(std::move(si));
}
for (auto& siV : context.doc["dyldDataSections"].GetArray())
{
MemoryRegion si;
si.LoadFromValue(siV);
MutableState().dyldDataRegions.push_back(std::move(si));
}
for (auto& siV : context.doc["nonImageRegions"].GetArray())
{
MemoryRegion si;
si.LoadFromValue(siV);
MutableState().nonImageRegions.push_back(std::move(si));
}
m_metadataValid = true;
}
#if defined(__GNUC__) || defined(__clang__)
__attribute__((always_inline)) void SharedCache::AssertMutable() const
#elif defined(_MSC_VER)
__forceinline void SharedCache::AssertMutable() const
#else
#error "Unsupported compiler"
#endif
{
if (m_stateIsShared)
{
abort();
}
}
void SharedCache::WillMutateState()
{
if (!m_state)
{
m_state = std::make_shared<struct State>();
}
else if (m_stateIsShared)
{
m_state = std::make_shared<struct State>(*m_state);
}
m_stateIsShared = false;
}
const std::vector<BackingCache>& SharedCache::BackingCaches() const
{
return State().backingCaches;
}
DSCViewState SharedCache::ViewState() const
{
return State().viewState;
}
const std::unordered_map<std::string, uint64_t>& SharedCache::AllImageStarts() const
{
return State().imageStarts;
}
const std::unordered_map<uint64_t, SharedCacheMachOHeader>& SharedCache::AllImageHeaders() const
{
return State().headers;
}
} // namespace SharedCacheCore
|